use std::sync::atomic::{AtomicBool, Ordering}; use crate::types::{CapturedRequest, Endpoint, ParsedEmail, SearchHit, UsageInfo}; use crate::util::format::{format_bytes, format_timestamp}; use crate::util::parsed::{Tone, parsed_lines}; static NO_COLOR: AtomicBool = AtomicBool::new(false); /// Strip ANSI control characters from untrusted text to prevent terminal injection. /// Preserves normal whitespace (space, tab, newline, carriage return). pub fn sanitize(s: &str) -> String { s.chars() .filter(|c| !c.is_control() || *c == '\n' || *c == '\r' || *c == '\t' || *c == ' ') .collect() } /// Like `sanitize`, but for text that must stay on one line, such as an /// email's subject or sender, which the sender controls: line breaks and tabs /// become spaces, so they cannot fake extra rows in a listing. pub fn sanitize_line(s: &str) -> String { s.chars() .filter_map(|c| match c { '\n' | '\r' | '\t' => Some(' '), c if c.is_control() => None, c => Some(c), }) .collect() } pub fn set_no_color(val: bool) { NO_COLOR.store(val, Ordering::Relaxed); } fn no_color() -> bool { NO_COLOR.load(Ordering::Relaxed) } pub fn bold(s: &str) -> String { if no_color() { s.to_string() } else { format!("\x1b[1m{s}\x1b[0m") } } pub fn dim(s: &str) -> String { if no_color() { s.to_string() } else { format!("\x1b[2m{s}\x1b[0m") } } pub fn green(s: &str) -> String { if no_color() { s.to_string() } else { format!("\x1b[32m{s}\x1b[0m") } } pub fn red(s: &str) -> String { if no_color() { s.to_string() } else { format!("\x1b[31m{s}\x1b[0m") } } pub fn method_color(method: &str) -> String { if no_color() { return method.to_string(); } match method.to_uppercase().as_str() { "GET" => format!("\x1b[32m{method}\x1b[0m"), "POST" => format!("\x1b[34m{method}\x1b[0m"), "PUT" => format!("\x1b[33m{method}\x1b[0m"), "DELETE" => format!("\x1b[31m{method}\x1b[0m"), "PATCH" => format!("\x1b[36m{method}\x1b[0m"), "EMAIL" => format!("\x1b[35m{method}\x1b[0m"), _ => method.to_string(), } } /// How a table cell is drawn: its colour, and which side it is padded on. #[derive(Debug, Clone, Copy, PartialEq)] pub enum Cell { Plain, Bold, Dim, /// Right-aligned (numbers), plain. Right, /// Right-aligned and dim: the header over a [`Cell::Right`] column. DimRight, } /// The width a terminal gives text: wide characters count two columns. pub fn display_width(s: &str) -> usize { unicode_width::UnicodeWidthStr::width(s) } /// Text cut to `max` columns, ending in "..." when it was longer. pub fn fit(s: &str, max: usize) -> String { if display_width(s) <= max { return s.to_string(); } let mut out = String::new(); let mut width = 0; for c in s.chars() { let w = unicode_width::UnicodeWidthChar::width(c).unwrap_or(0); if width + w + 3 > max { break; } width += w; out.push(c); } out.push_str("..."); out } /// Rows as aligned lines: each column as wide as its widest cell, padded by /// display width before any colour is added, so escape codes and wide /// characters never shift a column. The last column is not padded. The /// first row is usually the header, drawn dim. pub fn table_lines(indent: &str, rows: &[Vec<(String, Cell)>]) -> Vec { let columns = rows.iter().map(Vec::len).max().unwrap_or(0); let mut widths = vec![0; columns]; for row in rows { for (i, (text, _)) in row.iter().enumerate() { widths[i] = widths[i].max(display_width(text)); } } rows.iter() .map(|row| { let cells: Vec = row .iter() .enumerate() .map(|(i, (text, cell))| { let gap = " ".repeat(widths[i].saturating_sub(display_width(text))); let last = i + 1 == row.len(); let padded = match cell { Cell::Right | Cell::DimRight => format!("{gap}{text}"), _ if last => text.clone(), _ => format!("{text}{gap}"), }; match cell { Cell::Bold => bold(&padded), Cell::Dim | Cell::DimRight => dim(&padded), Cell::Plain | Cell::Right => padded, } }) .collect(); format!("{indent}{}", cells.join(" ")) }) .collect() } /// A dim header row for [`table_lines`], right-aligned where `right` says. pub fn header_row(names: &[&str], right: &[usize]) -> Vec<(String, Cell)> { names .iter() .enumerate() .map(|(i, name)| { let cell = if right.contains(&i) { Cell::DimRight } else { Cell::Dim }; (name.to_string(), cell) }) .collect() } /// Announce a stream reconnect (emitted by `ApiClient::stream_requests`). pub fn print_reconnecting(json: bool, attempt: u32, delay_ms: u64, reason: &str) { if json { crate::outln!( "{}", serde_json::json!({ "event": "reconnecting", "attempt": attempt, "delay_ms": delay_ms, "reason": reason, }) ); } else { let secs = (delay_ms + 500) / 1000; let line = format!( "Reconnecting in {secs}s (attempt {attempt}): {}", sanitize(reason) ); crate::outln!(" {} {}", dim("●"), dim(&line)); } } /// Announce that a stream reconnect succeeded. pub fn print_reconnected(json: bool) { if json { crate::outln!("{}", serde_json::json!({ "event": "reconnected" })); } else { crate::outln!(" {} {}", green("●"), dim("Reconnected")); } } pub fn print_endpoint_table(endpoints: &[Endpoint], webhook_url: &str) { if endpoints.is_empty() { crate::outln!(" No endpoints found."); return; } for line in endpoint_table_lines(endpoints, webhook_url) { crate::outln!("{line}"); } } /// The widest an endpoint's name or team column grows in `whk list`; longer /// ones are cut, so one long name cannot push every URL off the screen. const LIST_COLUMN_MAX: usize = 32; /// What `whk list` prints, line by line: a header, then one row per /// endpoint, a favourite marked with a star in the first column. fn endpoint_table_lines(endpoints: &[Endpoint], webhook_url: &str) -> Vec { let mut rows = vec![header_row(&["", "SLUG", "NAME", "TEAM", "URL"], &[])]; for ep in endpoints { let name = sanitize_line(ep.name.as_deref().unwrap_or("-")); let slug = sanitize_line(&ep.slug); let url = format!("{}/w/{}", webhook_url, slug); let team = if let Some(ref from) = ep.from_team { format!("[-> {}]", sanitize_line(&from.team_name)) } else if !ep.shared_with.is_empty() { format!( "[{}]", ep.shared_with .iter() .map(|t| sanitize_line(&t.team_name)) .collect::>() .join(", ") ) } else { String::new() }; let star = if ep.is_favorite() { "\u{2605}" } else { " " }; rows.push(vec![ (star.to_string(), Cell::Plain), (slug, Cell::Bold), (fit(&name, LIST_COLUMN_MAX), Cell::Dim), (fit(&team, LIST_COLUMN_MAX), Cell::Dim), (url, Cell::Dim), ]); } table_lines(" ", &rows) } /// One search row: like `print_request_line`, plus the endpoint slug because /// a search spans endpoints, including ones shared through teams. pub fn print_search_hit(hit: &SearchHit) { let time = format_timestamp(hit.received_at); let method = method_color(&hit.method); let size = format_bytes(hit.size); crate::outln!( " {} {} {} {} {}", dim(&time), method, bold(&sanitize(&hit.slug)), sanitize(&hit.path), dim(&size) ); } pub fn print_request_line(req: &CapturedRequest) { let time = format_timestamp(req.received_at); let method = method_color(&req.method); let size = format_bytes(req.size); match req.email.as_ref().filter(|_| req.is_email()) { Some(email) => crate::outln!( " {} {} {} {} {}", dim(&time), method, sanitize_line(&req.path), bold(&sanitize_line( email.subject.as_deref().unwrap_or("(no subject)") )), dim(&size) ), None => crate::outln!( " {} {} {} {}", dim(&time), method, sanitize(&req.path), dim(&size) ), } } /// Longest text part shown by `print_request_detail`; the rest is cut. const EMAIL_TEXT_PREVIEW: usize = 4000; fn print_email_detail(req: &CapturedRequest, email: &crate::types::EmailSummary) { for line in email_detail_lines(req, email) { crate::outln!("{line}"); } } /// What `whk requests get` prints for an email, line by line. fn email_detail_lines(req: &CapturedRequest, email: &crate::types::EmailSummary) -> Vec { let mut out = vec![bold("Email Details")]; out.push(format!(" {} {}", dim("ID:"), sanitize(&req.id))); out.push(format!(" {} {}", dim("To:"), sanitize_line(&req.path))); if let Some(from) = email.from.first() { out.push(format!( " {} {}", dim("From:"), sanitize_line(&from.to_string()) )); } out.push(format!( " {} {}", dim("Subject:"), sanitize_line(email.subject.as_deref().unwrap_or("(no subject)")) )); if let Some(ref tag) = email.tag { out.push(format!(" {} {}", dim("Tag:"), sanitize_line(tag))); } out.push(format!(" {} {}", dim("Size:"), format_bytes(req.size))); out.push(format!( " {} {}", dim("Time:"), format_timestamp(req.received_at) )); if !email.attachments.is_empty() { out.push(String::new()); out.push(bold("Attachments")); for attachment in &email.attachments { out.push(format!( " {} {} {}", sanitize_line(attachment.filename.as_deref().unwrap_or("(unnamed)")), dim(&sanitize_line( attachment.content_type.as_deref().unwrap_or("") )), dim(&format_bytes(attachment.size as usize)) )); } } out.extend(parsed_section(req.parsed.as_deref())); if let Some(ref text) = email.text { out.push(String::new()); out.push(bold("Text")); let preview: String = text.chars().take(EMAIL_TEXT_PREVIEW).collect(); out.push(sanitize(&preview)); if text.chars().count() > EMAIL_TEXT_PREVIEW { out.push(dim("... (cut; the dashboard shows the whole email)")); } } out.push(String::new()); out.push(dim( "Headers and the raw message: --json. HTML and sender checks: the dashboard.", )); out } /// The "Parsed" section of an email's details: what the endpoint's layouts /// found (see `util::parsed`). Empty when the email has no parsed result, /// because its endpoint has no layouts or its parse has not finished. pub fn parsed_section(parsed: Option<&ParsedEmail>) -> Vec { let Some(parsed) = parsed else { return Vec::new(); }; let mut out = vec![String::new(), bold("Parsed")]; // The terminal's width, less a line's indent; 100 columns when it is not // known (piped, or a pty that reports no size, which reads as 0). let columns = crossterm::terminal::size() .ok() .map(|(columns, _)| columns as usize) .filter(|columns| *columns > 0) .unwrap_or(100); for line in parsed_lines(parsed, columns.saturating_sub(4)) { let mut text = " ".repeat(line.depth + 1); for (tone, piece) in &line.spans { text.push_str(&match tone { Tone::Plain => piece.clone(), Tone::Strong => bold(piece), Tone::Muted => dim(piece), Tone::Danger => red(piece), }); } out.push(text); } out } pub fn print_request_detail(req: &CapturedRequest) { if let Some(email) = req.email.as_ref().filter(|_| req.is_email()) { print_email_detail(req, email); return; } crate::outln!("{}", bold("Request Details")); crate::outln!(" {} {}", dim("ID:"), sanitize(&req.id)); crate::outln!( " {} {} {}", dim("Method:"), method_color(&req.method), sanitize(&req.path) ); crate::outln!(" {} {}", dim("IP:"), sanitize(&req.ip)); crate::outln!(" {} {}", dim("Size:"), format_bytes(req.size)); crate::outln!(" {} {}", dim("Time:"), format_timestamp(req.received_at)); if let Some(ref ct) = req.content_type { crate::outln!(" {} {}", dim("Content-Type:"), sanitize(ct)); } if !req.query_params.is_empty() { crate::outln!("\n{}", bold("Query Parameters")); for (k, v) in &req.query_params { crate::outln!(" {} = {}", bold(&sanitize(k)), sanitize(v)); } } if !req.headers.is_empty() { crate::outln!("\n{}", bold("Headers")); let mut headers: Vec<_> = req.headers.iter().collect(); headers.sort_by_key(|(k, _)| k.to_lowercase()); for (k, v) in headers { crate::outln!(" {}: {}", bold(&sanitize(k)), sanitize(v)); } } if let Some(ref body) = req.body { crate::outln!("\n{}", bold("Body")); let sanitized_body = sanitize(body); if let Ok(val) = serde_json::from_str::(&sanitized_body) { crate::outln!( "{}", serde_json::to_string_pretty(&val).unwrap_or(sanitized_body) ); } else { crate::outln!("{sanitized_body}"); } } if let Some(ref live) = req.live_response { crate::outln!("\n{}", bold("Live Response")); for line in crate::util::live::live_response_lines(live) { crate::outln!(" {line}"); } } } pub fn print_usage(usage: &UsageInfo) { crate::outln!("{}", bold("Usage")); crate::outln!(" {} {}", dim("Plan:"), usage.plan); crate::outln!( " {} {}/{} ({} remaining)", dim("Requests:"), usage.used, usage.limit, usage.remaining ); if let Some(pe) = usage.period_end { crate::outln!(" {} {}", dim("Period ends:"), format_timestamp(pe)); } for (label, text) in allowance_lines(usage) { crate::outln!(" {} {}", dim(label), text); } } /// The plan's other allowances, one line each, with when each frees up: /// parsed pages (the page window), preview data (the UTC month) and AI /// assists (a rolling 30 days). Ones the server did not report are left out. pub fn allowance_lines(usage: &UsageInfo) -> Vec<(&'static str, String)> { let mut lines = Vec::new(); if let Some(pages) = &usage.parsed_pages { let mut text = format!("{}/{}", pages.used, pages.limit); let mut extras = Vec::new(); if pages.credit_pages > 0 { extras.push(format!("+{} one-time", pages.credit_pages)); } if let Some(overage) = pages.overage.as_ref().filter(|o| o.active && o.used > 0) { extras.push(format!("+{} in overage", overage.used)); } if !extras.is_empty() { text.push_str(&format!(" ({})", extras.join(", "))); } if let Some(resets) = &pages.resets_at { text.push_str(&format!(", resets {}", resets.display())); } lines.push(("Parsed pages:", text)); } if let Some(preview) = &usage.preview_data { let mut text = format!( "{} of {}", crate::cli::share::data(preview.bytes), crate::cli::share::data(preview.limit_bytes) ); let resets = preview.resets_at.as_ref().map(|t| t.display()); match (preview.over, resets) { (true, Some(at)) => text.push_str(&format!(", previews paused until {at}")), (true, None) => text.push_str(", previews paused"), (false, Some(at)) => text.push_str(&format!(", resets {at}")), (false, None) => {} } lines.push(("Preview data:", text)); } if let Some(assists) = &usage.ai_assists { let mut text = format!("{}/{}", assists.used, assists.allowed); match (&assists.next_at, assists.used >= assists.allowed) { (Some(next), true) => text.push_str(&format!(", next one back {}", next.display())), _ => text.push_str(" over the last 30 days"), } lines.push(("AI assists:", text)); } lines } #[cfg(test)] mod tests { use super::*; #[test] fn allowance_lines_say_when_each_frees_up() { let usage: UsageInfo = serde_json::from_str( r#"{"used":0,"limit":50,"remaining":50,"plan":"pro", "parsedPages":{"used":87,"limit":100,"creditPages":1000, "overage":{"active":true,"used":40,"max":2000},"resetsAt":null}, "previewData":{"bytes":3650722202,"limitBytes":26843545600,"over":true, "resetsAt":"not a time"}, "aiAssists":{"used":20,"allowed":20,"nextAt":"later"}}"#, ) .unwrap(); assert_eq!( allowance_lines(&usage), vec![ ( "Parsed pages:", "87/100 (+1000 one-time, +40 in overage)".to_string() ), ( "Preview data:", "3.40 GB of 25.00 GB, previews paused until not a time".to_string() ), ("AI assists:", "20/20, next one back later".to_string()), ] ); let none: UsageInfo = serde_json::from_str(r#"{"used":0,"limit":50,"remaining":50,"plan":"free"}"#).unwrap(); assert!(allowance_lines(&none).is_empty()); } #[test] fn sanitize_line_keeps_sender_text_on_one_line() { assert_eq!( sanitize_line("Hi\n 12:00:00 POST /fake\r\n\tx\x1b[31m"), "Hi 12:00:00 POST /fake x[31m" ); assert_eq!(sanitize_line("Confirm your email"), "Confirm your email"); } /// The text of colored output: ANSI color sequences removed, so the test /// holds whether or not color is on. fn strip_ansi(s: &str) -> String { let mut out = String::new(); let mut chars = s.chars(); while let Some(c) = chars.next() { if c == '\x1b' { for c in chars.by_ref() { if c == 'm' { break; } } } else { out.push(c); } } out } #[test] fn endpoint_table_stars_favourites() { let endpoints: Vec = serde_json::from_str( r#"[ {"id":"1","slug":"acme-orders","name":"Orders","favorite":true}, {"id":"2","slug":"acme-refunds","favorite":false}, {"id":"3","slug":"acme-new"} ]"#, ) .unwrap(); let lines: Vec = endpoint_table_lines(&endpoints, "https://go.example.test") .iter() .map(|line| strip_ansi(line)) .collect(); assert_eq!(lines.len(), 4); assert!(lines[0].starts_with(" SLUG"), "{lines:#?}"); // Every URL starts in the same column. let column = |line: &str, text: &str| line.find(text).map(|i| display_width(&line[..i])); let url_at = column(&lines[1], "http"); assert!(url_at.is_some(), "{lines:#?}"); for line in &lines[2..] { assert_eq!(column(line, "http"), url_at, "{lines:#?}"); } assert_eq!(column(&lines[0], "URL"), url_at, "{lines:#?}"); assert!(lines[1].starts_with(" \u{2605} acme-orders"), "{lines:#?}"); assert!(lines[2].starts_with(" acme-refunds"), "{lines:#?}"); assert!(lines[3].starts_with(" acme-new"), "{lines:#?}"); assert!(lines[1].ends_with("https://go.example.test/w/acme-orders")); } #[test] fn tables_line_up_whatever_the_colour_and_the_width_of_the_text() { let rows = vec![ header_row(&["NAME", "COUNT", "ID"], &[1]), vec![ ("a very long endpoint name".into(), Cell::Bold), ("7".into(), Cell::Right), ("x1".into(), Cell::Dim), ], vec![ ("\u{65e5}\u{672c}".into(), Cell::Bold), ("1200".into(), Cell::Right), ("x2".into(), Cell::Dim), ], ]; // Whether colour is on or not (the escape codes are taken out). let lines: Vec = table_lines(" ", &rows) .iter() .map(|line| strip_ansi(line)) .collect(); assert_eq!( lines, vec![ " NAME COUNT ID", " a very long endpoint name 7 x1", " \u{65e5}\u{672c} 1200 x2", ] ); assert_eq!(fit("abcdefghij", 8), "abcde..."); assert_eq!(fit("abc", 8), "abc"); } #[test] fn email_details_show_the_parsed_result() { let request = crate::util::parsed::tests::acme_order(); // What `whk requests get` prints carries the section too. if let Some(email) = request.email.as_ref() { let printed: Vec = email_detail_lines(&request, email) .iter() .map(|line| strip_ansi(line)) .collect(); assert!(printed.contains(&"Parsed".to_string()), "{printed:#?}"); assert!(printed.contains(&" order: 1001".to_string())); } else { panic!("the fixture is an email"); } let section: Vec = parsed_section(request.parsed.as_deref()) .iter() .map(|line| strip_ansi(line)) .collect(); assert_eq!( section.join("\n"), " Parsed Layout: Acme orders Pages: 3 Fields order: 1001 po: not found Line items (2) sku qty price A-1 2 9.50 B-7 1 24.00 Attachments order-1001.csv csv, 1 page, 1 sheet, 3 rows terms.pdf pdf, 2 pages, 18 B of text scan.pdf pdf, is encrypted" ); } #[test] fn email_details_add_nothing_without_a_parsed_result() { // An email on an endpoint without layouts, or whose parse is pending. let mut request = crate::util::parsed::tests::acme_order(); request.parsed = None; assert!(parsed_section(request.parsed.as_deref()).is_empty()); let pending: CapturedRequest = serde_json::from_str( r#"{"id":"e1","endpointId":"ep","method":"EMAIL","path":"orders@mailhooks.cc","queryParams":{},"ip":"192.0.2.1","size":1,"receivedAt":1,"kind":"email","email":{"subject":"Hi"},"parsed":null}"#, ) .unwrap(); assert!(pending.parsed.is_none()); assert!(parsed_section(pending.parsed.as_deref()).is_empty()); } }