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..a57ecf0 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 @@ -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", ]) 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/hasheus_error.rs b/src/hasheus_error.rs index 4dcde50..e7e7386 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,11 @@ impl HasheusError { Self::InvalidSecretKey => "invalid_secret_key", Self::PasswordRequired => "password_required", Self::InvalidPassword => "invalid_password", + Self::URLMissing => "url_missing", Self::InvalidURL => "invalid_url", - Self::InvalidDescription => "invalid_description", + 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", @@ -90,12 +96,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..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; @@ -80,11 +81,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..5cff906 100644 --- a/src/verification_publisher.rs +++ b/src/verification_publisher.rs @@ -2,13 +2,14 @@ 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; 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 +22,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 +99,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 +201,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(); @@ -216,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), - ("mime type", verification.mime_type), - ("verified by", &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") } @@ -253,6 +272,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 +300,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 +310,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 +327,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 +419,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 +439,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..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; @@ -9,11 +10,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"; @@ -30,19 +31,22 @@ 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( - "untrusted verifiers", - &sorted.untrusted_events, + "unknown", + &sorted.unknown_events, verifications, &empty_value, ), @@ -68,40 +72,46 @@ 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 => { + let status = match sorted.verdict { + 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 { + "1 person".to_string() + } else { + format!("{count} people") + }; + + on_green(&format!(" {people} you follow verified this file ")) + } + 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 => on_grey(" no one has verified this file yet "), }; - 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,35 @@ 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() + 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 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( @@ -296,20 +322,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 +365,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 +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(" 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 +409,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 +449,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 +472,7 @@ mod tests { ); assert!(rendered.contains("url\n—")); - assert!(rendered.contains("source trusted ")); + assert!(rendered.contains("source ✓ trusted ")); } #[test] @@ -443,17 +481,15 @@ 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] 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!( - "untrusted 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] @@ -465,7 +501,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 +514,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 " )); } @@ -486,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}"))); } @@ -500,7 +536,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\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]