//! Which addresses this client will talk to, and which routes are exempt from//! a standing refusal.//!//! The port of `apps/cotton/src/replica/serverAddress.ts`'s pure half. What is//! NOT here is the remembering: a Mac and a phone both keep the address in//! `client/connection.json` ([`crate::connection`]), which is the ONE seam for//! "which server this device talks to". This module only decides whether a//! string is an address at all./// Trailing slashes off. An origin is a signed field, and one slash is a/// signature over a string the server did not build.pubfn trim_slashes(value: &str) -> String { value.trim_end_matches('/').to_string()}/// The origin a string names, or `None`.////// `https:` anywhere. `http:` on THIS MACHINE or THIS HOUSE, and nowhere else:////// * LOOPBACK — `localhost`, `127.0.0.1`, `[::1]`, the three spellings the URL/// parser produces. A development build against a server on this desk is why/// plain http was admitted here at all;/// * a PRIVATE IPv4 — `10/8`, `172.16/12`, `192.168/16`, the predicate/// [`cotton_core::net::is_private_ipv4`], which the Mac uses to choose which/// of its interfaces to offer. The two must agree or a Mac recommends an/// address the phone then refuses, which is why there is one predicate and/// it lives in core;/// * a SINGLE-LABEL `*.local` name — `studio.local`, which is what Bonjour/// resolves a Mac to. One label before `.local` and no more: `a.b.local` is/// not a name mDNS mints, and admitting it would admit a public host that/// happened to end in `.local`.////// **A home network is the one place a signature may travel in the clear, and/// it is a deliberate trade.** The device signature is the credential and it/// rides in a header; over the internet that header needs TLS, and there is no/// certificate a Mac on `192.168.1.10` can hold for its own address. The/// alternative was no LAN join at all — a phone standing next to its Mac/// forced out to the relay and back. The blast radius is somebody already on/// the same Wi-Fi, and the signature is still over the origin, the method, the/// path, the body and the clock, so replaying one elsewhere buys nothing.////// Refused as well: credentials, a query, a fragment, and any path but `/`./// A "server address" carrying a path is somebody pasting a link to a page.pubfn normalize_server_url(value: &str) -> Option<String> {let trimmed = value.trim();if trimmed.is_empty() {returnNone; }let url = url::Url::parse(trimmed).ok()?;match url.scheme() {"https" => {}"http"if is_home_host(url.host_str()?) => {} _ => returnNone, }if !url.username().is_empty() || url.password().is_some() {returnNone; }if url.query().is_some() || url.fragment().is_some() {returnNone; }if url.path() != "/" && !url.path().is_empty() {returnNone; }Some(trim_slashes(url.origin().ascii_serialization().as_str()))}/// Is this a host plain http may reach — this machine, or this house?fn is_home_host(host: &str) -> bool { is_loopback_host(host) || cotton_core::net::is_private_ipv4(host) || is_bonjour_host(host)}/// `studio.local` — ONE label, then `.local`, and nothing else.////// What Bonjour resolves a Mac to on the home network. The single-label rule is/// the whole of the check: `a.b.local` is not a name mDNS mints, and a rule/// that only looked at the suffix would admit `anything.you.like.local` from a/// DNS server somebody else controls. Case-insensitive, because a person types/// `Studio.local` and mDNS answers `Studio.local.` — a trailing dot is stripped/// before this is asked, since a URL parser keeps it and it would make two/// spellings of one origin, and an origin is a SIGNED string.fn is_bonjour_host(host: &str) -> bool {let lower = host.to_ascii_lowercase();letSome(label) = lower.strip_suffix(".local") else {returnfalse; }; !label.is_empty() && !label.contains('.')}fn is_loopback_host(host: &str) -> bool {// The bracketed form is what `URL.hostname` answers in JavaScript and what// `Url::host_str` answers here is the BARE `::1`, so both spellings are// named. Nothing else: not `0.0.0.0`, not `::ffff:127.0.0.1`, not another// address in `127.0.0.0/8` — the TypeScript admits exactly three and a// wider rule here would be a second opinion.//// ON A PHONE, PREFER `127.0.0.1` OVER `localhost`. The origin is what gets// SIGNED, and the two are different strings: a server bound to// `127.0.0.1:8790` builds and verifies its side against that, so a request// signed over `http://localhost:8790` is a signature over an origin the// server never offers and comes back a 401 that names nothing useful.// `localhost` also resolves to `::1` first on some stacks, which is a// second way to reach a server that is not listening there. matches!(host, "localhost" | "127.0.0.1" | "::1" | "[::1]")}/// The `wss://…/v1/live` address for a base, or `None` for no base.pubfn live_socket_url(base: &str) -> Option<String> {let base = trim_slashes(base);if base.is_empty() {returnNone; }// `https` first, or `http`'s prefix would swallow it and mint a `wss`// address spelled `ws`.let swapped = match base.strip_prefix("https") {Some(rest) => format!("wss{rest}"),None => format!("ws{}", base.strip_prefix("http")?), };Some(format!("{swapped}/v1/live"))}/// The `wss://…/v1/sessions/attach?session=<id>` address for one session's/// terminal.////// **The session id is checked, not escaped.** What a device SIGNS is/// `URL.pathname + URL.search` as the server reads it back/// (`cotton_core::device::signature::signed_path`), so a character this side/// percent-encoded and the server did not would be a signature over a path/// nobody asked for. Every id that reaches here is a uuid the executor minted/// or one an agent did; anything outside that alphabet is a refusal rather/// than an encoding guess.pubfn attach_socket_url(base: &str, session_id: &str) -> Option<String> {if session_id.is_empty() || !session_id .chars() .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')) {returnNone; }let live = live_socket_url(base)?;let root = live.strip_suffix("/v1/live")?;Some(format!("{root}/v1/sessions/attach?session={session_id}"))}/// The `http(s)://host[:port]` a `ws(s)://…` URL dials.////// A socket needs a host, a port and whether to wrap it in TLS — `wss` is a URL/// scheme and carries none of that on its own. The path is dropped here on/// purpose: it belongs to the upgrade REQUEST, not to the connection.pubfn http_origin_of(socket_url: &str) -> Result<String, String> {let parsed = url::Url::parse(socket_url).map_err(|_| format!("{socket_url} is not an address"))?;let scheme = match parsed.scheme() {"wss" => "https","ws" => "http", other => returnErr(format!("{other}:// is not a socket address")), };let host = parsed .host_str() .ok_or_else(|| format!("{socket_url} names no host"))?;Ok(match parsed.port() {Some(port) => format!("{scheme}://{host}:{port}"),None => format!("{scheme}://{host}"), })}/// Is this one of the pairing routes?////// THE EXEMPTION THIS ANSWERS, in two places: a pairing request goes out even/// while a terminal refusal stands (that is the way back in), and a `401/// device_bad_signature` on one records nothing (Join's own sentence carries/// it, and a standing note would paint over the way out).////// `/v1/devices/pair` and anything under it — the POST that presents the key/// and the long-poll that waits for an answer, `?wait=25` and all. Nothing/// else: every other `/v1/devices/*` route is an APPROVED device's, and a/// standing refusal stops those.pubfn is_pairing_route(path: &str) -> bool {ifletSome(rest) = path.strip_prefix("/v1/devices/pair") {return rest.is_empty() || rest.starts_with('/') || rest.starts_with('?'); }// AN INVITE'S CLAIM IS PAIRING TOO. `POST /v1/invites/{id}/claim` is how// a device gets into a shared database at another person's Mac — the// server verifies the key it presents and asks for no row — and a device// that Mac once refused (removed from one database there, 4 Oct 2026)// must still be able to claim an invite to another.letSome(rest) = path.strip_prefix("/v1/invites/") else {returnfalse; };let (id, after) = rest.split_once("/claim").unwrap_or((rest, "")); !id.is_empty() && !id.contains('/') && rest.contains("/claim") && (after.is_empty() || after.starts_with('?'))}#[cfg(test)]#[path = "address_tests.rs"]mod tests;