Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -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).

Expand Down
12 changes: 6 additions & 6 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 = "\
Expand All @@ -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] <file>",
after_help = VERIFY_AFTER_HELP
Expand Down Expand Up @@ -75,7 +75,7 @@ pub struct PublishArgs {
pub description: Option<String>,

/// 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<String>,

/// the secret key to sign with (nsec or ncryptsec) [default: HASHEUS_SECRET_KEY, then a prompt]
Expand Down Expand Up @@ -194,7 +194,7 @@ mod tests {
"https://example.com/file.iso",
"--description",
"a file",
"--mime-type",
"--type",
"application/x-iso9660-image",
"--yes",
])
Expand Down
52 changes: 52 additions & 0 deletions src/hash_formatter.rs
Original file line number Diff line number Diff line change
@@ -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<Item = &str> {
(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::<Vec<_>>(), ["01234567", "89"]);
}

#[test]
fn format_keeps_the_hash_whole_without_color() {
yansi::disable();
let hash = "0123456789abcdef".repeat(4);

assert_eq!(format(&hash), hash);
}
}
21 changes: 16 additions & 5 deletions src/hasheus_error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,11 @@ pub enum HasheusError {
InvalidSecretKey,
PasswordRequired,
InvalidPassword,
URLMissing,
InvalidURL,
InvalidDescription,
URLTooLong,
DescriptionMissing,
DescriptionTooLong,
InvalidMIMEType,
AlreadyVerified,
PublishRejected { message: String },
Expand All @@ -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",
Expand Down Expand Up @@ -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,
Expand Down
19 changes: 8 additions & 11 deletions src/json_serializer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ struct VerificationJSON<'a> {
status: &'static str,
source: Option<SourceJSON>,
trusted_verifiers: Vec<VerifierJSON>,
untrusted_verifiers: Vec<VerifierJSON>,
unknown_verifiers: Vec<VerifierJSON>,
user: Option<UserJSON>,
}

Expand Down Expand Up @@ -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(&current_user.public_key),
Expand All @@ -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",
}
}
Expand Down Expand Up @@ -188,15 +188,15 @@ mod tests {
"status": "unverified",
"source": null,
"trusted_verifiers": [],
"untrusted_verifiers": [],
"unknown_verifiers": [],
"user": null,
}
})
);
}

#[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();
Expand All @@ -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"
Expand All @@ -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
);
}
Expand Down Expand Up @@ -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);
Expand Down
8 changes: 3 additions & 5 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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}");
Expand Down
16 changes: 16 additions & 0 deletions src/text_sanitizer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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"
);
}
}
Loading
Loading