From b59862f6a3eefa49b62f460197aebfccc014ae11 Mon Sep 17 00:00:00 2001 From: tinfoil hash <238757206+tinfoilhash@users.noreply.github.com> Date: Wed, 11 Nov 2026 19:40:40 -0500 Subject: [PATCH 1/4] match the web's redesigned copy & statuses MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit this mirrors https://github.com/tinfoilhash/hasheus/pull/100: untrusted verifiers are now unknown, every verdict gets a status line, tags carry a ✓ or ? as well as a color, and the tagline, error output, publish note, and validation messages match the web page. the json output changes too: status "untrusted" is now "unknown", and untrusted_verifiers is now unknown_verifiers, with no alias. error codes are unchanged. > made with claude code + tinfoil hash · session `481d8c4a-a85e-4882-815f-de7c476182bf` Co-Authored-By: Claude Opus 5.5 --- Cargo.toml | 2 +- README.md | 6 +- src/cli.rs | 8 +-- src/hasheus_error.rs | 21 ++++-- src/json_serializer.rs | 19 +++-- src/main.rs | 7 +- src/text_sanitizer.rs | 16 +++++ src/verification_publisher.rs | 81 +++++++++++++++------ src/verification_renderer.rs | 131 +++++++++++++++++++++------------- src/verification_sorter.rs | 28 ++++---- 10 files changed, 202 insertions(+), 117 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index ec1551d..c532781 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ name = "hasheus" version = "0.1.0" edition = "2024" rust-version = "1.99" -description = "verify the integrity of a file with the largest decentralized web of trust" +description = "verify any file with signatures from people you trust" license = "MIT" repository = "https://github.com/tinfoilhash/hasheus-cli" diff --git a/README.md b/README.md index 4c933b3..9c94989 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # hasheus / cli -verify the integrity of a file with the largest decentralized web of trust, from -the command line. the cli version of [hasheus](https://github.com/tinfoilhash/hasheus), -built with [rust](https://www.rust-lang.org/), +verify any file with signatures from people you trust, from the command line. +the cli version of [hasheus](https://github.com/tinfoilhash/hasheus), built with +[rust](https://www.rust-lang.org/), [nostr-sdk](https://github.com/rust-nostr/nostr), and [clap](https://github.com/clap-rs/clap). diff --git a/src/cli.rs b/src/cli.rs index 6b8cc29..a8a2d90 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -6,11 +6,11 @@ use std::path::PathBuf; // clap doesn't wrap help without its wrap_help feature, so it's wrapped here. const VERIFY_AFTER_HELP: &str = "\ the user needs a nostr profile, which catches a mistyped key, and verifiers they -don't follow are untrusted. the exit code is 0 unless an error occurs, whether -or not the file has been verified. +don't follow are unknown. the exit code is 0 unless an error occurs, whether or +not the file has been verified. with --json, the result is printed once every relay has answered, and its -status is verified_by_you, trusted, untrusted, or unverified. an error is +status is verified_by_you, trusted, unknown, or unverified. an error is printed to stdout too, as {\"error\":{\"code\":…,\"message\":…}}, with exit code 1."; const PUBLISH_AFTER_HELP: &str = "\ @@ -34,7 +34,7 @@ pub struct Cli { #[derive(Subcommand)] pub enum Command { - /// verify a file against your web of trust + /// verify a file with signatures from people you trust #[command( override_usage = "hasheus verify [options] ", after_help = VERIFY_AFTER_HELP diff --git a/src/hasheus_error.rs b/src/hasheus_error.rs index 4dcde50..f14c749 100644 --- a/src/hasheus_error.rs +++ b/src/hasheus_error.rs @@ -16,8 +16,11 @@ pub enum HasheusError { InvalidSecretKey, PasswordRequired, InvalidPassword, + URLMissing, InvalidURL, - InvalidDescription, + URLTooLong, + DescriptionMissing, + DescriptionTooLong, InvalidMIMEType, AlreadyVerified, PublishRejected { message: String }, @@ -42,8 +45,9 @@ impl HasheusError { Self::InvalidSecretKey => "invalid_secret_key", Self::PasswordRequired => "password_required", Self::InvalidPassword => "invalid_password", - Self::InvalidURL => "invalid_url", - Self::InvalidDescription => "invalid_description", + // split only so their messages can match the web page's form. + Self::URLMissing | Self::InvalidURL | Self::URLTooLong => "invalid_url", + Self::DescriptionMissing | Self::DescriptionTooLong => "invalid_description", Self::InvalidMIMEType => "invalid_mime_type", Self::AlreadyVerified => "already_verified", Self::PublishRejected { .. } => "publish_rejected", @@ -90,12 +94,17 @@ impl fmt::Display for HasheusError { "an ncryptsec needs its password, which can only be asked for in a terminal" ), Self::InvalidPassword => write!(formatter, "the password doesn't unlock the ncryptsec"), + // like the web page's form. it can't go over the length limits, so + // only those messages are the cli's own. + Self::URLMissing => write!(formatter, "add a url for the file"), Self::InvalidURL => write!( formatter, - "the url must be an http or https url of at most 1,000 characters" + "enter a url that starts with http:// or https://" ), - Self::InvalidDescription => { - write!(formatter, "the description must be 1 to 1,000 characters") + Self::URLTooLong => write!(formatter, "enter a url of up to 1,000 characters"), + Self::DescriptionMissing => write!(formatter, "describe the file"), + Self::DescriptionTooLong => { + write!(formatter, "describe the file in up to 1,000 characters") } Self::InvalidMIMEType => write!( formatter, diff --git a/src/json_serializer.rs b/src/json_serializer.rs index 0a5f08d..1df4652 100644 --- a/src/json_serializer.rs +++ b/src/json_serializer.rs @@ -17,7 +17,7 @@ struct VerificationJSON<'a> { status: &'static str, source: Option, trusted_verifiers: Vec, - untrusted_verifiers: Vec, + unknown_verifiers: Vec, user: Option, } @@ -79,7 +79,7 @@ pub fn serialize_verifications(hash: &str, verifications: &Verifications) -> Str verifier: build_verifier(event, verifications), }), trusted_verifiers: build_verifiers(&sorted.trusted_events), - untrusted_verifiers: build_verifiers(&sorted.untrusted_events), + unknown_verifiers: build_verifiers(&sorted.unknown_events), user: current_user.map(|current_user| UserJSON { pubkey: current_user.public_key.to_hex(), npub: encode_npub(¤t_user.public_key), @@ -103,7 +103,7 @@ fn serialize_verdict(verdict: Verdict) -> &'static str { match verdict { Verdict::VerifiedByYou => "verified_by_you", Verdict::Trusted => "trusted", - Verdict::Untrusted => "untrusted", + Verdict::Unknown => "unknown", Verdict::Unverified => "unverified", } } @@ -188,7 +188,7 @@ mod tests { "status": "unverified", "source": null, "trusted_verifiers": [], - "untrusted_verifiers": [], + "unknown_verifiers": [], "user": null, } }) @@ -196,7 +196,7 @@ mod tests { } #[test] - fn serializes_an_untrusted_source_with_its_raw_description() { + fn serializes_an_unknown_source_with_its_raw_description() { let stranger = Keys::generate(); let x = Tag::parse(["x", HASH]).unwrap(); let url = Tag::parse(["url", "javascript:alert(1)"]).unwrap(); @@ -211,7 +211,7 @@ mod tests { let json = serialize(&build_verifications(None, vec![Update::FileEvent(event)])); let verification = &json["verification"]; - assert_eq!(verification["status"], "untrusted"); + assert_eq!(verification["status"], "unknown"); assert_eq!( verification["source"]["description"], "official\n\u{1b}[32mdownload" @@ -223,10 +223,7 @@ mod tests { "2009-01-03T00:00:00Z" ); assert_eq!( - verification["untrusted_verifiers"] - .as_array() - .unwrap() - .len(), + verification["unknown_verifiers"].as_array().unwrap().len(), 1 ); } @@ -300,7 +297,7 @@ mod tests { ))], ); - let verifier = &serialize(&verifications)["verification"]["untrusted_verifiers"][0]; + let verifier = &serialize(&verifications)["verification"]["unknown_verifiers"][0]; assert_eq!(verifier["name"], Value::Null); assert_eq!(verifier["created_at"], Value::Null); diff --git a/src/main.rs b/src/main.rs index 203a610..64af8a5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -80,11 +80,8 @@ async fn run(cli: Cli, output_format: OutputFormat) -> Result<(), HasheusError> // so a failed write is ignored rather than panicking. fn print_error(error: &HasheusError, output_format: OutputFormat) { match output_format { - OutputFormat::Text => { - eprintln!("{}", " an error occurred! ".bold().on_red()); - eprintln!(); - eprintln!("{error}"); - } + // like the web page, the message stands on its own, without a heading. + OutputFormat::Text => eprintln!("{}", format!(" {error} ").bold().on_red()), OutputFormat::Json => { let json = json_serializer::serialize_error(error); let _ = writeln!(io::stdout().lock(), "{json}"); diff --git a/src/text_sanitizer.rs b/src/text_sanitizer.rs index 2c91f8b..67a7023 100644 --- a/src/text_sanitizer.rs +++ b/src/text_sanitizer.rs @@ -10,6 +10,14 @@ pub fn sanitize(text: &str) -> String { .collect() } +// like the web page, a file name has only its bidi controls removed, since it +// becomes the published description rather than terminal output. +pub fn strip_bidi_controls(text: &str) -> String { + text.chars() + .filter(|character| !is_bidi_control(*character)) + .collect() +} + fn is_bidi_control(character: char) -> bool { matches!( character, @@ -35,4 +43,12 @@ mod tests { fn removes_bidi_overrides() { assert_eq!(sanitize("file\u{202E}osi.exe"), "fileosi.exe"); } + + #[test] + fn strip_bidi_controls_keeps_everything_else() { + assert_eq!( + strip_bidi_controls("file\u{202E}osi.exe\u{2066}\n"), + "fileosi.exe\n" + ); + } } diff --git a/src/verification_publisher.rs b/src/verification_publisher.rs index 75474aa..b64e46f 100644 --- a/src/verification_publisher.rs +++ b/src/verification_publisher.rs @@ -8,7 +8,7 @@ use crate::name_formatter; use crate::profile_fetcher; use crate::relay_config::RelayConfig; use crate::secret_key_reader; -use crate::text_sanitizer::sanitize; +use crate::text_sanitizer::{sanitize, strip_bidi_controls}; use crate::verification_reporter; use nostr_sdk::prelude::*; use std::fs; @@ -21,6 +21,9 @@ const MAX_URL_LENGTH: usize = 1000; const MAX_DESCRIPTION_LENGTH: usize = 1000; // rfc 6838's limit for a type or subtype. const MAX_MIME_TYPE_NAME_LENGTH: usize = 127; +// like the web page's form. +const VOUCH_NOTE: &str = + "only vouch for what you've checked. getting it from the official site alone isn't enough."; pub async fn publish( args: PublishArgs, relay_config: &RelayConfig, @@ -95,29 +98,41 @@ async fn fetch_profile_name(public_key: PublicKey, relay_config: &RelayConfig) - // published as parsed, which percent-encodes anything hidden (like a bidi // override), so the preview shows exactly what's signed. fn parse_url(url: &str) -> Result { - let url = Url::parse(url.trim()).map_err(|_| HasheusError::InvalidURL)?; - let is_web_url = matches!(url.scheme(), "https" | "http"); + let url = url.trim(); - if !is_web_url || url.as_str().chars().count() > MAX_URL_LENGTH { + if url.is_empty() { + return Err(HasheusError::URLMissing); + } + + let url = Url::parse(url).map_err(|_| HasheusError::InvalidURL)?; + + if !matches!(url.scheme(), "https" | "http") { return Err(HasheusError::InvalidURL); } + if url.as_str().chars().count() > MAX_URL_LENGTH { + return Err(HasheusError::URLTooLong); + } + Ok(url.into()) } -// like the web page's form, the description defaults to the file's name. +// like the web page's form, the description defaults to the file's name, which +// anyone can set, so a right-to-left override can't change how it reads. fn parse_description(description: Option<&str>, path: &Path) -> Result { let description = match description { Some(description) => description.trim().to_string(), None => path .file_name() - .map(|name| name.to_string_lossy().to_string()) + .map(|name| strip_bidi_controls(&name.to_string_lossy())) .unwrap_or_default(), }; - let length = description.chars().count(); + if description.is_empty() { + return Err(HasheusError::DescriptionMissing); + } - if length == 0 || length > MAX_DESCRIPTION_LENGTH { - return Err(HasheusError::InvalidDescription); + if description.chars().count() > MAX_DESCRIPTION_LENGTH { + return Err(HasheusError::DescriptionTooLong); } Ok(description) @@ -185,8 +200,9 @@ fn confirm( let mut stderr = io::stderr().lock(); let _ = write!( stderr, - "{}\n\npublish this verification? [y/N] ", - render_preview(verification, public_key, name) + "{}\n\n{}\n\npublish this verification? [y/N] ", + render_preview(verification, public_key, name), + VOUCH_NOTE.dim() ); let _ = stderr.flush(); @@ -220,8 +236,8 @@ fn render_preview( ("file hash", verification.hash), ("description", verification.description), ("url", verification.url), - ("mime type", verification.mime_type), - ("verified by", &verifier), + ("type", verification.mime_type), + ("verifier", &verifier), ] .map(|(key, value)| format!("{key}\n{}", sanitize(value).bold())) .join("\n\n") @@ -253,6 +269,16 @@ mod tests { ); } + #[test] + fn rejects_a_blank_url() { + for url in ["", " "] { + assert!( + matches!(parse_url(url), Err(HasheusError::URLMissing)), + "{url:?}" + ); + } + } + #[test] fn rejects_a_url_that_isnt_http() { for url in [ @@ -271,7 +297,7 @@ mod tests { fn rejects_a_url_over_1000_characters() { let url = format!("https://example.com/{}", "a".repeat(1000)); - assert!(matches!(parse_url(&url), Err(HasheusError::InvalidURL))); + assert!(matches!(parse_url(&url), Err(HasheusError::URLTooLong))); } #[test] @@ -281,6 +307,14 @@ mod tests { assert_eq!(description, "ubuntu.iso"); } + #[test] + fn removes_bidi_controls_from_the_default_description() { + let description = + parse_description(None, Path::new("/downloads/file\u{202E}osi.exe")).unwrap(); + + assert_eq!(description, "fileosi.exe"); + } + #[test] fn trims_the_description() { let description = @@ -290,14 +324,17 @@ mod tests { } #[test] - fn rejects_a_blank_or_long_description() { - let long = "a".repeat(1001); + fn rejects_a_blank_description() { + let result = parse_description(Some(" "), Path::new("ubuntu.iso")); - for description in [" ", long.as_str()] { - let result = parse_description(Some(description), Path::new("ubuntu.iso")); + assert!(matches!(result, Err(HasheusError::DescriptionMissing))); + } - assert!(matches!(result, Err(HasheusError::InvalidDescription))); - } + #[test] + fn rejects_a_description_over_1000_characters() { + let result = parse_description(Some(&"a".repeat(1001)), Path::new("ubuntu.iso")); + + assert!(matches!(result, Err(HasheusError::DescriptionTooLong))); } #[test] @@ -379,7 +416,7 @@ mod tests { assert_eq!( preview, format!( - "file hash\nffff\n\ndescription\na file\n\nurl\nhttps://example.com/file.iso\n\nmime type\napplication/octet-stream\n\nverified by\n{npub}" + "file hash\nffff\n\ndescription\na file\n\nurl\nhttps://example.com/file.iso\n\ntype\napplication/octet-stream\n\nverifier\n{npub}" ) ); } @@ -399,7 +436,7 @@ mod tests { let preview = render_preview(&verification, &keys.public_key(), Some("alice")); - assert!(preview.ends_with(&format!("verified by\nalice ({npub})"))); + assert!(preview.ends_with(&format!("verifier\nalice ({npub})"))); } #[test] diff --git a/src/verification_renderer.rs b/src/verification_renderer.rs index a4f0267..3301b49 100644 --- a/src/verification_renderer.rs +++ b/src/verification_renderer.rs @@ -9,11 +9,11 @@ use crate::verifications::Verifications; use jiff::fmt::strtime; use jiff::tz::TimeZone; use nostr_sdk::prelude::*; -use yansi::{Color, Paint}; +use yansi::Paint; const EMPTY_VALUE: &str = "—"; // like the web page's connect button. -const USER_HINT: &str = "connect: set HASHEUS_PUBLIC_KEY or pass --user to see if anyone in your web of trust has verified this file"; +const USER_HINT: &str = "connect: set HASHEUS_PUBLIC_KEY or pass --user to see if anyone you follow has verified this file"; // like the web page's "add your verification" link. const PUBLISH_HINT: &str = "add your verification: hasheus publish --url "; const DATE_FORMAT: &str = "%b %-d, %Y, %-I:%M %P %Z"; @@ -41,8 +41,8 @@ pub fn render(file_hash: &FileHash, verifications: &Verifications, spinner_frame &empty_value, ), render_verifiers( - "untrusted verifiers", - &sorted.untrusted_events, + "unknown verifiers", + &sorted.unknown_events, verifications, &empty_value, ), @@ -68,40 +68,50 @@ fn render_empty_value(is_pending: bool, spinner_frame: usize) -> String { } // the verdict can change until the file events and your profile and follow -// list are in, so only a verification of your own shows before then. +// list are in, so before then it only says it's looking, unless you've +// verified the file yourself. fn render_status( sorted: &SortedVerifications, current_user: Option<&CurrentUser>, is_pending: bool, ) -> Vec { - let (status, color) = match sorted.verdict { - Verdict::VerifiedByYou => ("you have verified this file!".to_string(), Color::Green), - _ if is_pending => return Vec::new(), - Verdict::Unverified => ( - "this file has not been verified!".to_string(), - Color::Magenta, - ), - Verdict::Untrusted => { + // like the web page, a status that's neither good nor bad news is uncolored. + let status = match sorted.verdict { + Verdict::VerifiedByYou => " you've verified this file ".bold().on_green().to_string(), + _ if is_pending => "looking up verifications…".bold().to_string(), + Verdict::Trusted => { + let count = sorted.trusted_events.len(); + let people = if count == 1 { + "1 person".to_string() + } else { + format!("{count} people") + }; + + format!(" {people} you follow verified this file ") + .bold() + .on_green() + .to_string() + } + Verdict::Unknown => { let reason = if current_user.is_some() { - "no one in your web of trust has verified this file" + "no one you follow has verified this file" } else { - "connect to see if anyone in your web of trust has verified this file" + "connect to see if anyone you follow has verified this file" }; - ( - format!("{reason}. its source and url are untrusted."), - Color::Magenta, - ) + on_yellow(&format!( + " {reason}; its description, url, and source come from an unknown verifier " + )) } - Verdict::Trusted => return Vec::new(), + Verdict::Unverified => "no one has verified this file yet".bold().to_string(), }; - vec![format!(" {status} ").bold().bg(color).to_string()] + vec![status] } -// labeled whenever it shows, even while loading, so an untrusted source is +// labeled whenever it shows, even while loading, so an unknown source is // never shown unlabeled. -fn is_untrusted(source: &Source) -> bool { +fn is_unknown(source: &Source) -> bool { source.event.is_some() && !source.is_trusted } @@ -118,12 +128,12 @@ fn render_description(source: &Source, empty_value: &str) -> Vec { vec!["description".to_string(), description] } -// the url keeps an untrusted tag, since that's what people follow, and counts +// the url keeps an unknown tag, since that's what people follow, and counts // the other trusted verifiers who agree on it. fn render_url(source: &Source, empty_value: &str) -> Vec { let url = source.event.and_then(file_event::url); let tags = [ - is_untrusted(source).then(render_untrusted_tag), + is_unknown(source).then(render_unknown_tag), render_agreement_tag(source.agreement_count), ]; @@ -137,10 +147,10 @@ fn render_url(source: &Source, empty_value: &str) -> Vec { } // trust belongs to whoever published the verification, so the source carries -// the trusted or untrusted tag. +// the trusted or unknown tag. fn render_source(source: &Source, verifications: &Verifications, empty_value: &str) -> Vec { let tags = [ - is_untrusted(source).then(render_untrusted_tag), + is_unknown(source).then(render_unknown_tag), source.is_trusted.then(render_trusted_tag), ]; let verifier = source.event.map_or_else( @@ -198,19 +208,26 @@ fn render_key(key: &str, tags: [Option; N]) -> String { format!("{key} {}", tags.join(" ")) } -fn render_untrusted_tag() -> String { - " untrusted ".on_magenta().to_string() +// like the web page, a glyph as well as a color, so a tag doesn't depend on +// color alone. unknown is a question, not a warning. +fn render_unknown_tag() -> String { + on_yellow(" ? unknown ") } fn render_trusted_tag() -> String { - " trusted ".on_green().to_string() + " ✓ trusted ".on_green().to_string() } // the source is one of the agreeing verifiers, so only the others are counted. fn render_agreement_tag(agreement_count: usize) -> Option { let other_count = agreement_count.checked_sub(1).filter(|count| *count > 0)?; - Some(format!(" +{other_count} trusted ").on_green().to_string()) + Some(format!(" ✓ +{other_count} trusted ").on_green().to_string()) +} + +// the terminal's own text color can be too light to read on yellow. +fn on_yellow(text: &str) -> String { + text.black().on_yellow().to_string() } fn render_verifier_list( @@ -296,20 +313,21 @@ mod tests { fn render_shows_pending_values_while_pending() { let rendered = render(&build_file_hash(), &build_verifications(true), 2); + assert!(rendered.starts_with("looking up verifications…\n\nfile hash")); assert!(rendered.contains("source\n⠹")); - assert!(!rendered.contains("this file has not been verified!")); + assert!(!rendered.contains("no one has verified this file yet")); } #[test] - fn render_waits_for_every_relay_before_calling_a_source_untrusted() { + fn render_waits_for_every_relay_before_calling_a_source_unknown() { let mut verifications = build_verifications(true); add_file_event(&mut verifications); let rendered = render(&build_file_hash(), &verifications, 0); - assert!(rendered.contains("url untrusted ")); - assert!(rendered.contains("source untrusted ")); - assert!(!rendered.contains("its source and url are untrusted")); + assert!(rendered.contains("url ? unknown ")); + assert!(rendered.contains("source ? unknown ")); + assert!(!rendered.contains("come from an unknown verifier")); } #[test] @@ -338,7 +356,7 @@ mod tests { let rendered = render(&build_file_hash(), &verifications, 0); assert!(rendered.starts_with( - " connect to see if anyone in your web of trust has verified this file. its source and url are untrusted. " + " connect to see if anyone you follow has verified this file; its description, url, and source come from an unknown verifier " )); } @@ -346,7 +364,7 @@ mod tests { fn render_shows_empty_values_once_complete() { let rendered = render(&build_file_hash(), &build_verifications(false), 2); - assert!(rendered.starts_with(" this file has not been verified! \n\nfile hash")); + assert!(rendered.starts_with("no one has verified this file yet\n\nfile hash")); assert!(rendered.contains("source\n—")); } @@ -382,21 +400,21 @@ mod tests { } #[test] - fn render_tags_a_trusted_source_and_shows_no_verdict() { + fn render_tags_a_trusted_source_and_counts_the_people_you_follow() { let rendered = render(&build_file_hash(), &build_trusted_verifications(), 0); - assert!(rendered.starts_with("file hash")); + assert!(rendered.starts_with(" 2 people you follow verified this file \n\nfile hash")); assert!(rendered.contains("description\ndescription")); - assert!(rendered.contains("source trusted \nalice ")); - assert!(!rendered.contains(&render_untrusted_tag())); - assert!(!rendered.contains("are untrusted")); + assert!(rendered.contains("source ✓ trusted \nalice ")); + assert!(!rendered.contains(&render_unknown_tag())); + assert!(!rendered.contains("come from an unknown verifier")); } #[test] fn render_counts_the_other_trusted_verifiers_on_the_url() { let rendered = render(&build_file_hash(), &build_trusted_verifications(), 0); - assert!(rendered.contains("url +1 trusted \nhttps://example.com/file.iso")); + assert!(rendered.contains("url ✓ +1 trusted \nhttps://example.com/file.iso")); assert!(!rendered.contains("linked by")); } @@ -422,7 +440,18 @@ mod tests { let rendered = render(&build_file_hash(), &verifications, 0); assert!(rendered.contains("url\nhttps://example.com/file.iso")); - assert!(rendered.contains("source trusted ")); + assert!(rendered.contains("source ✓ trusted ")); + } + + #[test] + fn render_counts_a_lone_trusted_verifier_as_one_person() { + let rendered = render( + &build_file_hash(), + &build_lone_trusted_verifications(None), + 0, + ); + + assert!(rendered.starts_with(" 1 person you follow verified this file ")); } #[test] @@ -434,7 +463,7 @@ mod tests { ); assert!(rendered.contains("url\n—")); - assert!(rendered.contains("source trusted ")); + assert!(rendered.contains("source ✓ trusted ")); } #[test] @@ -443,7 +472,7 @@ mod tests { assert_eq!(render_agreement_tag(0), None); assert_eq!(render_agreement_tag(1), None); - assert_eq!(render_agreement_tag(3).as_deref(), Some(" +2 trusted ")); + assert_eq!(render_agreement_tag(3).as_deref(), Some(" ✓ +2 trusted ")); } #[test] @@ -452,7 +481,7 @@ mod tests { assert!(rendered.contains("trusted verifiers\nalice ")); assert!(rendered.ends_with(&format!( - "untrusted verifiers\n—\n\n{PUBLISH_HINT}\nconnected: viewer" + "unknown verifiers\n—\n\n{PUBLISH_HINT}\nconnected: viewer" ))); } @@ -465,7 +494,7 @@ mod tests { let rendered = render(&build_file_hash(), &verifications, 0); - assert!(rendered.starts_with(" you have verified this file! ")); + assert!(rendered.starts_with(" you've verified this file ")); assert!(!rendered.contains(PUBLISH_HINT)); } @@ -478,7 +507,7 @@ mod tests { let rendered = render(&build_file_hash(), &verifications, 0); assert!(rendered.starts_with( - " no one in your web of trust has verified this file. its source and url are untrusted. " + " no one you follow has verified this file; its description, url, and source come from an unknown verifier " )); } @@ -500,7 +529,7 @@ mod tests { let rendered = render(&file_hash, &build_verifications(false), 0); assert!(!rendered.contains(PUBLISH_HINT)); - assert!(rendered.ends_with(&format!("untrusted verifiers\n—\n\n{USER_HINT}"))); + assert!(rendered.ends_with(&format!("unknown verifiers\n—\n\n{USER_HINT}"))); } #[test] diff --git a/src/verification_sorter.rs b/src/verification_sorter.rs index 666cc3e..f50b606 100644 --- a/src/verification_sorter.rs +++ b/src/verification_sorter.rs @@ -12,7 +12,7 @@ pub struct Source<'a> { pub struct SortedVerifications<'a> { pub trusted_events: Vec<&'a Event>, - pub untrusted_events: Vec<&'a Event>, + pub unknown_events: Vec<&'a Event>, pub source: Source<'a>, pub verdict: Verdict, } @@ -21,7 +21,7 @@ pub struct SortedVerifications<'a> { pub enum Verdict { VerifiedByYou, Trusted, - Untrusted, + Unknown, Unverified, } @@ -32,7 +32,7 @@ pub fn sort<'a>( ) -> SortedVerifications<'a> { let verifier_events = first_event_per_pubkey(events); - let (trusted_events, untrusted_events): (Vec<_>, Vec<_>) = + let (trusted_events, unknown_events): (Vec<_>, Vec<_>) = verifier_events.iter().partition(|event| { current_user.is_some_and(|current_user| current_user.has_trusted(&event.pubkey)) }); @@ -42,7 +42,7 @@ pub fn sort<'a>( SortedVerifications { trusted_events, - untrusted_events, + unknown_events, source, verdict, } @@ -68,7 +68,7 @@ fn pick_verdict( Source { is_trusted: true, .. } => Verdict::Trusted, - _ => Verdict::Untrusted, + _ => Verdict::Unknown, } } @@ -164,7 +164,7 @@ mod tests { let sorted = sort(&[], None); assert!(sorted.trusted_events.is_empty()); - assert!(sorted.untrusted_events.is_empty()); + assert!(sorted.unknown_events.is_empty()); assert_eq!( sorted.source, Source { @@ -185,11 +185,11 @@ mod tests { let sorted = sort(&events, None); - assert_eq!(sorted.untrusted_events, [&events[0]]); + assert_eq!(sorted.unknown_events, [&events[0]]); } #[test] - fn treats_everyone_as_untrusted_without_a_current_user() { + fn treats_everyone_as_unknown_without_a_current_user() { let users = Users::new(); let events = [ build_file_event(&users.trusted_a, 1, None), @@ -199,7 +199,7 @@ mod tests { let sorted = sort(&events, None); assert!(sorted.trusted_events.is_empty()); - assert_eq!(sorted.untrusted_events, [&events[0], &events[1]]); + assert_eq!(sorted.unknown_events, [&events[0], &events[1]]); } #[test] @@ -215,11 +215,11 @@ mod tests { let sorted = sort(&events, Some(¤t_user)); assert_eq!(sorted.trusted_events, [&events[0], &events[1]]); - assert_eq!(sorted.untrusted_events, [&events[2]]); + assert_eq!(sorted.unknown_events, [&events[2]]); } #[test] - fn falls_back_to_the_earliest_event_untrusted_without_trusted_verifiers() { + fn falls_back_to_the_earliest_event_unknown_without_trusted_verifiers() { let users = Users::new(); let events = [ build_file_event(&users.stranger, 1, Some("https://evil.example/file")), @@ -239,7 +239,7 @@ mod tests { } #[test] - fn ignores_a_backdated_untrusted_event_when_a_trusted_verifier_exists() { + fn ignores_a_backdated_unknown_event_when_a_trusted_verifier_exists() { let users = Users::new(); let events = [ build_file_event(&users.stranger, 1, Some("https://evil.example/file")), @@ -364,14 +364,14 @@ mod tests { } #[test] - fn calls_a_source_without_trusted_verifiers_untrusted() { + fn calls_a_source_without_trusted_verifiers_unknown() { let users = Users::new(); let events = [build_file_event(&users.stranger, 1, None)]; let current_user = users.current_user(&[&users.trusted_a]); let sorted = sort(&events, Some(¤t_user)); - assert_eq!(sorted.verdict, Verdict::Untrusted); + assert_eq!(sorted.verdict, Verdict::Unknown); } #[test] From bc6fd8e215202c0de47e234a9f10133b20a937b4 Mon Sep 17 00:00:00 2001 From: tinfoil hash <238757206+tinfoilhash@users.noreply.github.com> Date: Wed, 11 Nov 2026 20:04:25 -0500 Subject: [PATCH 2/4] give each validation error its own code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit this way, scripts can tell a missing url or description from one that's too long. invalid_description is replaced by description_missing and description_too_long. > made with claude code + tinfoil hash · session `481d8c4a-a85e-4882-815f-de7c476182bf` Co-Authored-By: Claude Opus 5.5 --- src/hasheus_error.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/hasheus_error.rs b/src/hasheus_error.rs index f14c749..e7e7386 100644 --- a/src/hasheus_error.rs +++ b/src/hasheus_error.rs @@ -45,9 +45,11 @@ impl HasheusError { Self::InvalidSecretKey => "invalid_secret_key", Self::PasswordRequired => "password_required", Self::InvalidPassword => "invalid_password", - // split only so their messages can match the web page's form. - Self::URLMissing | Self::InvalidURL | Self::URLTooLong => "invalid_url", - Self::DescriptionMissing | Self::DescriptionTooLong => "invalid_description", + Self::URLMissing => "url_missing", + Self::InvalidURL => "invalid_url", + Self::URLTooLong => "url_too_long", + Self::DescriptionMissing => "description_missing", + Self::DescriptionTooLong => "description_too_long", Self::InvalidMIMEType => "invalid_mime_type", Self::AlreadyVerified => "already_verified", Self::PublishRejected { .. } => "publish_rejected", From 58b3ffc915de3eeffe540635d38b15347fbb6070 Mon Sep 17 00:00:00 2001 From: tinfoil hash <238757206+tinfoilhash@users.noreply.github.com> Date: Wed, 11 Nov 2026 20:04:25 -0500 Subject: [PATCH 3/4] rename `--mime-type` => `--type` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit this matches the "type" label on the web page's publish form. > made with claude code + tinfoil hash · session `481d8c4a-a85e-4882-815f-de7c476182bf` Co-Authored-By: Claude Opus 5.5 --- src/cli.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cli.rs b/src/cli.rs index a8a2d90..a57ecf0 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -75,7 +75,7 @@ pub struct PublishArgs { pub description: Option, /// the file's mime type, like application/zip [default: a guess from its extension] - #[arg(long, value_name = "type")] + #[arg(long = "type", value_name = "type")] pub mime_type: Option, /// the secret key to sign with (nsec or ncryptsec) [default: HASHEUS_SECRET_KEY, then a prompt] @@ -194,7 +194,7 @@ mod tests { "https://example.com/file.iso", "--description", "a file", - "--mime-type", + "--type", "application/x-iso9660-image", "--yes", ]) From 01f34245e074175e996c96c0ecc9bc1ac7654344 Mon Sep 17 00:00:00 2001 From: tinfoil hash <238757206+tinfoilhash@users.noreply.github.com> Date: Thu, 12 Nov 2026 06:08:00 -0500 Subject: [PATCH 4/4] match the web's section names, colors & hash MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit the sections are now "trusted" and "unknown", the statuses without good or bad news are white on dark grey, and the hash alternates bold and regular every eight characters, like the web page's groups. there's no gap between them, so it still copies as one hash. text on green is black, like on yellow, and colored statuses aren't bold, since many terminals show bold black as grey. > made with claude code + tinfoil hash · session `481d8c4a-a85e-4882-815f-de7c476182bf` Co-Authored-By: Claude Opus 5.5 --- src/hash_formatter.rs | 52 +++++++++++++++++++++++++++++++++++ src/main.rs | 1 + src/verification_publisher.rs | 15 ++++++---- src/verification_renderer.rs | 51 +++++++++++++++++++--------------- 4 files changed, 91 insertions(+), 28 deletions(-) create mode 100644 src/hash_formatter.rs diff --git a/src/hash_formatter.rs b/src/hash_formatter.rs new file mode 100644 index 0000000..d3d940a --- /dev/null +++ b/src/hash_formatter.rs @@ -0,0 +1,52 @@ +use yansi::Paint; + +const GROUP_LENGTH: usize = 8; + +// like the web page, it's grouped by eight characters to compare by eye. a gap +// would be copied with the hash, so the groups alternate bold and regular +// instead. dim is too hard to read. +pub fn format(hash: &str) -> String { + groups(hash) + .enumerate() + .map(|(index, group)| { + if index % 2 == 0 { + group.bold().to_string() + } else { + group.to_string() + } + }) + .collect() +} + +// a hash is hex, so every group ends on a character boundary. +fn groups(hash: &str) -> impl Iterator { + (0..hash.len()) + .step_by(GROUP_LENGTH) + .map(move |start| &hash[start..hash.len().min(start + GROUP_LENGTH)]) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn groups_a_hash_by_eight_characters() { + let hash = "0123456789abcdef".repeat(4); + + assert_eq!(groups(&hash).count(), 8); + assert!(groups(&hash).all(|group| group == "01234567" || group == "89abcdef")); + } + + #[test] + fn keeps_a_short_last_group() { + assert_eq!(groups("0123456789").collect::>(), ["01234567", "89"]); + } + + #[test] + fn format_keeps_the_hash_whole_without_color() { + yansi::disable(); + let hash = "0123456789abcdef".repeat(4); + + assert_eq!(format(&hash), hash); + } +} diff --git a/src/main.rs b/src/main.rs index 64af8a5..0b93968 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,6 +6,7 @@ mod file_event_publisher; mod file_hash_reporter; mod file_hasher; mod file_verifier; +mod hash_formatter; mod hasheus_error; mod helmet_renderer; mod json_serializer; diff --git a/src/verification_publisher.rs b/src/verification_publisher.rs index b64e46f..5cff906 100644 --- a/src/verification_publisher.rs +++ b/src/verification_publisher.rs @@ -2,6 +2,7 @@ use crate::cli::{OutputFormat, PublishArgs}; use crate::current_user_cache; use crate::file_event_publisher::{self, FileEventPublisher, FileVerification}; use crate::file_hash_reporter; +use crate::hash_formatter; use crate::hasheus_error::HasheusError; use crate::mime_type_guesser; use crate::name_formatter; @@ -232,14 +233,16 @@ fn render_preview( None => npub, }; + let render_text = |text: &str| sanitize(text).bold().to_string(); + [ - ("file hash", verification.hash), - ("description", verification.description), - ("url", verification.url), - ("type", verification.mime_type), - ("verifier", &verifier), + ("file hash", hash_formatter::format(verification.hash)), + ("description", render_text(verification.description)), + ("url", render_text(verification.url)), + ("type", render_text(verification.mime_type)), + ("verifier", render_text(&verifier)), ] - .map(|(key, value)| format!("{key}\n{}", sanitize(value).bold())) + .map(|(key, value)| format!("{key}\n{value}")) .join("\n\n") } diff --git a/src/verification_renderer.rs b/src/verification_renderer.rs index 3301b49..aed2fb1 100644 --- a/src/verification_renderer.rs +++ b/src/verification_renderer.rs @@ -1,6 +1,7 @@ use crate::current_user::CurrentUser; use crate::file_event; use crate::file_hasher::FileHash; +use crate::hash_formatter; use crate::name_formatter; use crate::spinner; use crate::text_sanitizer::sanitize; @@ -30,18 +31,21 @@ pub fn render(file_hash: &FileHash, verifications: &Verifications, spinner_frame let sections = [ render_status(&sorted, current_user, *is_pending), - vec!["file hash".to_string(), file_hash.hash.bold().to_string()], + vec![ + "file hash".to_string(), + hash_formatter::format(&file_hash.hash), + ], render_description(&sorted.source, &empty_value), render_url(&sorted.source, &empty_value), render_source(&sorted.source, verifications, &empty_value), render_verifiers( - "trusted verifiers", + "trusted", &sorted.trusted_events, verifications, &empty_value, ), render_verifiers( - "unknown verifiers", + "unknown", &sorted.unknown_events, verifications, &empty_value, @@ -75,10 +79,9 @@ fn render_status( current_user: Option<&CurrentUser>, is_pending: bool, ) -> Vec { - // like the web page, a status that's neither good nor bad news is uncolored. let status = match sorted.verdict { - Verdict::VerifiedByYou => " you've verified this file ".bold().on_green().to_string(), - _ if is_pending => "looking up verifications…".bold().to_string(), + Verdict::VerifiedByYou => on_green(" you've verified this file "), + _ if is_pending => on_grey(" looking up verifications… "), Verdict::Trusted => { let count = sorted.trusted_events.len(); let people = if count == 1 { @@ -87,10 +90,7 @@ fn render_status( format!("{count} people") }; - format!(" {people} you follow verified this file ") - .bold() - .on_green() - .to_string() + on_green(&format!(" {people} you follow verified this file ")) } Verdict::Unknown => { let reason = if current_user.is_some() { @@ -103,7 +103,7 @@ fn render_status( " {reason}; its description, url, and source come from an unknown verifier " )) } - Verdict::Unverified => "no one has verified this file yet".bold().to_string(), + Verdict::Unverified => on_grey(" no one has verified this file yet "), }; vec![status] @@ -215,21 +215,30 @@ fn render_unknown_tag() -> String { } fn render_trusted_tag() -> String { - " ✓ trusted ".on_green().to_string() + on_green(" ✓ trusted ") } // the source is one of the agreeing verifiers, so only the others are counted. fn render_agreement_tag(agreement_count: usize) -> Option { let other_count = agreement_count.checked_sub(1).filter(|count| *count > 0)?; - Some(format!(" ✓ +{other_count} trusted ").on_green().to_string()) + Some(on_green(&format!(" ✓ +{other_count} trusted "))) } -// the terminal's own text color can be too light to read on yellow. +// the terminal's own text color can be too light to read on yellow or green. +// it isn't bold, since many terminals show bold black as grey. fn on_yellow(text: &str) -> String { text.black().on_yellow().to_string() } +fn on_green(text: &str) -> String { + text.black().on_green().to_string() +} + +fn on_grey(text: &str) -> String { + text.white().on_bright_black().to_string() +} + fn render_verifier_list( events: &[&Event], verifications: &Verifications, @@ -313,7 +322,7 @@ mod tests { fn render_shows_pending_values_while_pending() { let rendered = render(&build_file_hash(), &build_verifications(true), 2); - assert!(rendered.starts_with("looking up verifications…\n\nfile hash")); + assert!(rendered.starts_with(" looking up verifications… \n\nfile hash")); assert!(rendered.contains("source\n⠹")); assert!(!rendered.contains("no one has verified this file yet")); } @@ -364,7 +373,7 @@ mod tests { fn render_shows_empty_values_once_complete() { let rendered = render(&build_file_hash(), &build_verifications(false), 2); - assert!(rendered.starts_with("no one has verified this file yet\n\nfile hash")); + assert!(rendered.starts_with(" no one has verified this file yet \n\nfile hash")); assert!(rendered.contains("source\n—")); } @@ -479,10 +488,8 @@ mod tests { fn render_lists_trusted_verifiers_and_who_is_connected() { let rendered = render(&build_file_hash(), &build_trusted_verifications(), 0); - assert!(rendered.contains("trusted verifiers\nalice ")); - assert!(rendered.ends_with(&format!( - "unknown verifiers\n—\n\n{PUBLISH_HINT}\nconnected: viewer" - ))); + assert!(rendered.contains("trusted\nalice ")); + assert!(rendered.ends_with(&format!("unknown\n—\n\n{PUBLISH_HINT}\nconnected: viewer"))); } #[test] @@ -515,7 +522,7 @@ mod tests { fn render_hints_at_passing_a_user_without_one() { let rendered = render(&build_file_hash(), &build_verifications(false), 0); - assert!(rendered.contains("trusted verifiers\n—")); + assert!(rendered.contains("trusted\n—")); assert!(rendered.ends_with(&format!("{PUBLISH_HINT}\n{USER_HINT}"))); } @@ -529,7 +536,7 @@ mod tests { let rendered = render(&file_hash, &build_verifications(false), 0); assert!(!rendered.contains(PUBLISH_HINT)); - assert!(rendered.ends_with(&format!("unknown verifiers\n—\n\n{USER_HINT}"))); + assert!(rendered.ends_with(&format!("unknown\n—\n\n{USER_HINT}"))); } #[test]