Cotton code
327 lines · 10.5 KB · RustRaw
//! Every case of `packages/core/__tests__/handles.test.ts`, the//! `RELAY_NAME_PATTERN` byte-equality case of//! `packages/core/__tests__/device/pairing.test.ts`, and vectors computed by//! running the TypeScript in Node.use super::*;// ── handle shape ─────────────────────────────────────────────────────────────#[test]fn accepts_the_shapes_a_person_would_actually_pick() {    for handle in ["asha", "abc", "a-b-c", "cotton2026", &"a".repeat(30)] {        assert!(is_valid_handle(handle), "{handle}");    }}#[test]fn refuses_everything_outside_the_class() {    for handle in [        "ab",        &"a".repeat(31),        "Milo Example",        "as_ha",        "asha.dev",        "muk esh",        "",        "café",    ] {        assert_eq!(            reject_handle(handle),            Some(HandleRejection::Shape),            "{handle}"        );    }}#[test]fn is_never_digits_alone() {    // The sharing spec's phone-vs-handle rule, in the relay's words: core, the    // site and the relay must never disagree on what a name is.    for digits in ["123", "12345678", &"0".repeat(30)] {        assert_eq!(            reject_handle(digits),            Some(HandleRejection::Shape),            "{digits}"        );        assert!(!is_valid_handle(digits), "{digits}");    }    assert!(is_valid_handle("1234-5678"));    assert!(is_valid_handle("2fast"));    assert!(is_valid_handle("asha-2"));}#[test]fn folds_case_before_judging_and_deliberately_does_not_trim() {    assert_eq!(normalize_handle("  AsHa  "), "asha");    // Uppercase is a shape violation only until it is folded — which is the    // point: two people must not own `Asha` and `asha`.    assert!(is_valid_handle("ASHA"));    // Whitespace is NOT the same kind of thing. `is_relay_name` trims nothing,    // so a padded string that passed here was a handle claimable in the app    // and unregistrable at the relay — an address reaching nobody.    assert!(!is_valid_handle("  ASHA "));    assert!(is_valid_handle(&normalize_handle("  ASHA ")));}/// `normalizeHandle` vectors, read out of Node.////// The `İstanbul` row is the one that proves the fold is Unicode's default/// case conversion on both sides: it lowercases to `i` plus a COMBINING DOT/// ABOVE, two code points from one, in Node and in Rust alike. The padded rows/// prove the trim is ECMAScript's — U+00A0 and U+FEFF both go.#[test]fn normalize_handle_matches_node_vectors() {    for (raw, expected) in [        ("  AsHa  ", "asha"),        ("ASHA", "asha"),        ("asha", "asha"),        ("", ""),        ("   ", ""),        ("\tBright-Oak\n", "bright-oak"),        ("STRASSE", "strasse"),        ("İstanbul", "i\u{307}stanbul"),        ("\u{a0}Pad\u{a0}", "pad"),        ("\u{feff}Bom\u{feff}", "bom"),        (&"A".repeat(31), &"a".repeat(31)),        ("Asha-2026", "asha-2026"),    ] {        assert_eq!(normalize_handle(raw), expected, "normalize {raw:?}");    }}#[test]fn refuses_every_reserved_word_case_insensitively() {    for reserved in RESERVED_HANDLES {        assert!(!is_valid_handle(reserved), "{reserved}");        assert!(!is_valid_handle(&reserved.to_uppercase()), "{reserved}");        assert_eq!(            reject_handle(reserved),            Some(HandleRejection::Reserved),            "{reserved}"        );    }}#[test]fn keeps_the_deny_list_itself_shape_valid_so_every_entry_earns_its_place() {    // A word the SHAPE rule already refuses cannot be reserved —    // `reject_handle` reports `Shape` and the entry protects nothing while    // looking like it does. `m` was added here for a day on the theory that    // the `/m/` namespace needed defending; it is one character, so no handle    // could ever be `m` anyway.    for reserved in RESERVED_HANDLES {        assert!(            reserved.len() >= 3                && reserved.len() <= 30                && reserved                    .bytes()                    .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-'),            "{reserved} is not shape-valid"        );    }}// ── the bounds the app renders against ───────────────────────────────────────#[test]fn states_the_bounds_as_numbers_not_just_inside_the_pattern() {    assert_eq!(HANDLE_MIN, 3);    assert_eq!(HANDLE_MAX, 30);    assert!(is_valid_handle(&"a".repeat(HANDLE_MAX)));    assert!(!is_valid_handle(&"a".repeat(HANDLE_MAX + 1)));    assert!(is_valid_handle(&"a".repeat(HANDLE_MIN)));    assert!(!is_valid_handle(&"a".repeat(HANDLE_MIN - 1)));}#[test]fn holds_the_sites_own_path_segments() {    for word in ["inbox", "api", "admin", "app", "settings"] {        assert!(RESERVED_HANDLES.contains(&word), "{word}");    }}// ── handle_from_path ─────────────────────────────────────────────────────────#[test]fn reads_the_handle_out_of_a_message_page_path() {    assert_eq!(handle_from_path("/m/asha").as_deref(), Some("asha"));    assert_eq!(handle_from_path("/m/asha/").as_deref(), Some("asha"));    assert_eq!(handle_from_path("/m/ASHA").as_deref(), Some("asha"));}#[test]fn is_none_for_anything_that_is_not_one_servable_message_page() {    for path in [        "/",        "/inbox",        "/m/",        "/m/ab",        "/m/admin",        "/m/a/b",        "/mm/asha",    ] {        assert_eq!(handle_from_path(path), None, "{path}");    }}/// `handleFromPath` vectors, read out of Node.#[test]fn handle_from_path_matches_node_vectors() {    for (path, expected) in [        ("/m/asha", Some("asha")),        ("/m/asha/", Some("asha")),        ("/m/ASHA", Some("asha")),        ("/", None),        ("/inbox", None),        ("/m/", None),        ("/m/ab", None),        ("/m/admin", None),        ("/m/a/b", None),        ("/mm/asha", None),        ("/m/asha?x=1", None),        ("/m/asha#a", None),        ("/m/br%69ght-oak", Some("bright-oak")),        ("/m/%20asha", Some("asha")),        ("/m/ASHA/", Some("asha")),        ("/m/1234-5678", Some("1234-5678")),        ("/m/12345678", None),        ("/m/bright-oak//", None),    ] {        assert_eq!(handle_from_path(path).as_deref(), expected, "path {path:?}");    }}/// The one deliberate divergence: TypeScript throws a `URIError` here.#[test]fn answers_none_where_decode_uri_component_would_throw() {    assert_eq!(handle_from_path("/m/%zz"), None);    assert_eq!(handle_from_path("/m/%"), None);    assert_eq!(handle_from_path("/m/%ff%fe"), None);}// ── a handle a person may CLAIM is a name the relay could REGISTER ───────────/// The enumerated corpus of `handles.test.ts` — every string of length 1 to 4/// over `a z 0 9 -`, plus the boundary cases.fn corpus() -> Vec<String> {    let alphabet = ['a', 'z', '0', '9', '-'];    let mut out: Vec<String> = Vec::new();    let mut level: Vec<String> = vec![String::new()];    for _ in 1..=4 {        level = level            .iter()            .flat_map(|prefix| {                alphabet.iter().map(move |c| {                    let mut next = prefix.clone();                    next.push(*c);                    next                })            })            .collect();        out.extend(level.iter().cloned());    }    out.extend([        "a".repeat(30),        "a".repeat(31),        "alice-t".to_string(),        "bright-oak".to_string(),        "1234-5678".to_string(),    ]);    out}#[test]fn admits_nothing_the_relay_would_refuse() {    // The invariant, and the reason this module's rule is not the relay's.    // `@name` resolves to `https://<name>.relay.cottondb.com`, so a handle    // that cannot be registered as a relay name is a handle whose owner hands    // out an address that reaches nobody. Narrower is safe. WIDER IS THE BUG.    let wider: Vec<String> = corpus()        .into_iter()        .filter(|value| is_valid_handle(value) && !is_relay_name(value))        .collect();    assert!(        wider.is_empty(),        "these are claimable here and unregistrable at the relay — a handle whose address reaches nobody: {wider:?}"    );}#[test]fn refuses_a_leading_hyphen_which_the_relays_first_character_forbids() {    for handle in ["-abc", "-a-b", "--ab"] {        assert_eq!(            reject_handle(handle),            Some(HandleRejection::Shape),            "{handle}"        );    }}#[test]fn reserves_the_relays_own_labels_not_only_the_sites_paths() {    for label in [        "directory",        "tunnel",        "relay",        "api",        "www",        "admin",        "status",    ] {        assert_eq!(            reject_handle(label),            Some(HandleRejection::Reserved),            "{label}"        );    }}/// `isRelayName` vectors, read out of Node — the predicate the invariant above/// is stated against.#[test]fn is_relay_name_matches_node_vectors() {    for (value, expected) in [        ("asha", true),        ("abc", true),        ("a-b-c", true),        ("cotton2026", true),        ("ab", true),        ("a", false),        (&"a".repeat(30), true),        (&"a".repeat(31), true),        (&"a".repeat(32), false),        ("Milo Example", false),        ("as_ha", false),        ("asha.dev", false),        ("", false),        ("café", false),        ("123", false),        ("12345678", false),        (&"0".repeat(30), false),        ("1234-5678", true),        ("2fast", true),        ("ASHA", false),        ("  ASHA ", false),        ("-abc", false),        ("a--b", true),        ("abc-", true),        ("directory", true),    ] {        assert_eq!(is_relay_name(value), expected, "is_relay_name {value:?}");    }}// ── the copy that may not drift ──────────────────────────────────────────────/// And the copy is the rule this crate actually runs: the shape half of/// [`is_relay_name`] admits exactly what that pattern does.#[test]fn the_relay_pattern_copy_describes_the_predicate_that_runs() {    assert_eq!(RELAY_NAME_PATTERN_SOURCE, "/^[a-z0-9][a-z0-9-]{1,30}$/");    // The pattern's own bounds: 1 leading character plus 1..30 more.    assert!(is_relay_name("ab"));    assert!(!is_relay_name("a"));    assert!(is_relay_name(&"a".repeat(31)));    assert!(!is_relay_name(&"a".repeat(32)));}