//! The handle contract — the rule for CLAIMING one. The port of//! `packages/core/src/handles.ts`.//!//! A handle IS a relay name: `@name` resolves to//! `https://<name>.relay.cottondb.com`, and the relay's names directory is the//! handle directory. So this rule and the relay's are not independent — but//! they are not equal either, and the difference is deliberate://!//! - the relay (`packages/relay/src/protocol/names.ts`) is the REGISTRATION//! rule — 2 to 31 characters, never all digits, its own labels reserved;//! - this module is the CLAIM rule — what a person may take through the app or//! the server's handle route — and is a strict SUBSET of it.//!//! Subset in the safe direction, and only that direction: everything claimable//! here must be registrable there, or a person walks away with an address that//! reaches nobody. Narrower is fine. Wider is the bug, and the tests assert it//! cannot happen by running both predicates over an enumerated corpus, exactly//! as `packages/core/__tests__/handles.test.ts` does.//!//! **No regex crate.** Every pattern here is a character-class run that reads//! more honestly spelled out than compiled, and the two that matter//! ([`RELAY_NAME_PATTERN_SOURCE`] and the handle shape) are held to their//! TypeScript declarations by tests rather than by a shared engine./// The shortest handle a person may claim.pubconst HANDLE_MIN: usize = 3;/// The longest handle a person may claim — the length the app's field has/// always offered.pubconst HANDLE_MAX: usize = 30;/// Words a handle may never be.////// Two reasons, and only the first is obvious. (1) `/api` and friends would/// read as site infrastructure to anyone looking at the URL, and a handle that/// impersonates the site is a phishing primitive we would have shipped/// ourselves. (2) These are the paths the site is likely to grow — a claimed/// handle is a promise we cannot take back.////// The relay's own labels are here too (`RESERVED_NAMES` in/// `packages/relay/src/protocol/names.ts`): a name the relay keeps for itself/// can never be registered, so a handle that passed the shape rule and/// happened to be one of these would be claimable and dead on arrival.////// Enforced on BOTH sides on purpose: at the claim (so it cannot be taken) and/// at the read (so a row seeded by a migration or a human still cannot be/// served).pubconst RESERVED_HANDLES: &[&str] = &["about","admin","api","app","assets","directory","download","inbox","privacy","relay","settings","status","terms","tunnel","www",];/// Why this handle cannot be used.////// A REASON rather than a boolean because a caller answers both cases with the/// same 404 or the same 400 — but a log line that says which is the difference/// between "someone typo'd" and "someone is walking the reserved list".#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubenumHandleRejection {/// Outside `[a-z0-9][a-z0-9-]{2,29}`, or digits alone.Shape,/// On [`RESERVED_HANDLES`].Reserved,}implHandleRejection {/// The wire spelling — the TypeScript union's own strings.pubconstfn as_str(self) -> &'static str {matchself {HandleRejection::Shape => "shape",HandleRejection::Reserved => "reserved", } }}impl std::fmt::DisplayforHandleRejection {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.as_str()) }}/// The shape a handle is stored and compared in — `raw.trim().toLowerCase()`.////// `trim` is JavaScript's, which is not Rust's: the ECMAScript whitespace/// class includes U+FEFF and excludes U+0085. `to_lowercase` is the Unicode/// default case conversion on both sides, conditional mappings included, so/// `İstanbul` folds to `i̇stanbul` in Rust exactly as it does in Node (pinned/// in the tests).pubfn normalize_handle(raw: &str) -> String { js_trim(raw).to_lowercase()}/// `[a-z0-9][a-z0-9-]{2,29}` — three to thirty characters, opening with a/// letter or a digit.////// The leading-character rule is the relay's, carried here because a handle/// starting with a hyphen was claimable and could never have been registered./// The length bounds are this module's own and narrower than the relay's 2 to/// 31 on purpose.fn matches_handle_shape(handle: &str) -> bool {// `.length` is UTF-16 code units in JavaScript, but every character the// class admits is ASCII, so a non-ASCII character fails the class before// the length is ever consulted — bytes and units agree on what is left.let bytes = handle.as_bytes();if bytes.len() < HANDLE_MIN || bytes.len() > HANDLE_MAX {returnfalse; }letSome((first, rest)) = bytes.split_first() else {returnfalse; };if !first.is_ascii_lowercase() && !first.is_ascii_digit() {returnfalse; } rest.iter() .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'-')}/// A handle is never digits alone.////// The sharing spec tells a phone number from a handle by "8–15 digits is a/// phone, otherwise the handle grammar with at least one non-digit", and the/// relay's name grammar states the same rule (`NAME_NOT_ALL_DIGITS`) — so this/// one does too, or `12345678` would be both. One letter or hyphen anywhere/// satisfies it; `asha-2` and `1234-5678` are handles.fn has_a_non_digit(handle: &str) -> bool { handle.bytes().any(|b| b.is_ascii_lowercase() || b == b'-')}/// Why this handle cannot be used, or `None` when it can.////// Case is folded; WHITESPACE is not trimmed away, and the difference is the/// stated invariant. "Everything claimable here is registrable at the relay"/// is a claim about the STRING the caller handed over, and [`is_relay_name`]/// trims nothing — so a version of this that quietly trimmed admitted/// `" bright-oak "` while the relay refused it, which is a person walking/// away with an address that reaches nobody. Case-folding is a real/// normalisation of what somebody typed; a leading space is not part of any/// handle. Every caller in the tree normalises before it stores.pubfn reject_handle(raw: &str) -> Option<HandleRejection> {let handle = raw.to_lowercase();if !matches_handle_shape(&handle) || !has_a_non_digit(&handle) {returnSome(HandleRejection::Shape); }if RESERVED_HANDLES.contains(&handle.as_str()) {returnSome(HandleRejection::Reserved); }None}/// Whether a handle may be claimed, stored, or looked up at all.pubfn is_valid_handle(raw: &str) -> bool { reject_handle(raw).is_none()}/// The handle a `/m/...` path names, or `None` when the path is not a message/// page (or names something unusable).////// The message page itself is retired and a `/m/...` link now answers the/// site's 404 with the name on it; this is what reads the name out for that/// page.////// **Divergence, deliberate.** TypeScript's `decodeURIComponent` THROWS a/// `URIError` on a malformed escape (`/m/%zz`); this answers `None` instead./// A pure function in a server library may not panic on input a stranger/// controls, and "not a message page" is the same outcome every caller wants.pubfn handle_from_path(pathname: &str) -> Option<String> {// `/^\/m\/([^/?#]+)\/?$/`let rest = pathname.strip_prefix("/m/")?;let rest = rest.strip_suffix('/').unwrap_or(rest);if rest.is_empty() || rest.contains(['/', '?', '#']) {returnNone; }let handle = normalize_handle(&percent_decode(rest)?);if is_valid_handle(&handle) {Some(handle) } else {None }}// ─────────────────────────────────────────────────────────────────────────────// The relay's own rule, and the copy that may not drift from it.// ─────────────────────────────────────────────────────────────────────────────/// The relay's `NAME_PATTERN`, as its SOURCE TEXT.////// The Rust store carries no port of `packages/store/src/protocol/relay.ts`/// yet, so the shape lives here — and a copy is allowed to exist only while it/// cannot drift. `relay_name_pattern_is_byte_equal_to_the_relays` reads/// `packages/relay/src/protocol/names.ts` BY PATH and compares this string to/// the line it declares, failing loudly (naming the path) if the read comes/// back empty. That is what makes a MOVE of the relay's file red here rather/// than silently green — the failure mode `#332` shipped.pubconst RELAY_NAME_PATTERN_SOURCE: &str = "/^[a-z0-9][a-z0-9-]{1,30}$/";pubuse cotton_rules::ids::is_relay_name;// ─────────────────────────────────────────────────────────────────────────────// JavaScript string semantics.// ─────────────────────────────────────────────────────────────────────────────/// `String.prototype.trim()` — the ECMAScript whitespace class.fn js_trim(input: &str) -> &str { input.trim_matches(cotton_store::protocol::js::is_js_whitespace)}/// `decodeURIComponent`, answering `None` where it would throw.fn percent_decode(input: &str) -> Option<String> {let bytes = input.as_bytes();letmut out: Vec<u8> = Vec::with_capacity(bytes.len());letmut index = 0usize;while index < bytes.len() {if bytes[index] == b'%' {let hex = bytes.get(index + 1..index + 3)?;let hex = std::str::from_utf8(hex).ok()?; out.push(u8::from_str_radix(hex, 16).ok()?); index += 3; } else { out.push(bytes[index]); index += 1; } }// `decodeURIComponent` throws on a byte run that is not valid UTF-8, too.String::from_utf8(out).ok()}#[cfg(test)]#[path = "handles_tests.rs"]mod tests;