/** * RULE: no relay host is a compiled constant — Cotton's own relay is spelled * once, as the DEFAULT of a value that is passed, because a household may run * its own relay and every address has to follow the one it was handed. * * A household is reached at `https://.` and its Macs dial * `wss:///tunnel/v1`. Until 11 Oct 2026 four crates each declared the * domain (the server's hostname parser, core's pairing origin, the Mac shell's * public URL, the tunnel's default) and this guard — then * `no-peer-host-literal.test.ts` — held them to "one declaration per crate". * That was the right rule for a relay that could only be ours. The relay is * replaceable now (`packages/relay/README.md`), so the rule is one declaration * in the tree: `cotton_core::relay_address`, where `RelayAddress::cotton()` is * what a household that never chose gets. Everything else builds an address by * calling a method on a `RelayAddress`. * * Two offences, as before: * - DECLARING: the literal host, under any quoting, outside that module; * - BUILDING: putting the default constant next to something else, or * renaming it — the fifth caller that re-derives an address works on the * live network and fails only for the household on another relay, as a * connection that does not come up with nothing naming the cause. * Reading the constant, passing it on, and naming the address in a comment or * a test are none of those. * * It reads the Rust tree BY PATH (nothing in Rust sweeps its own sources), so * a read that comes back empty fails loudly first. Swift is held by * `RelayNameSweepTests`: no Swift source names the domain at all. */ import { execFileSync } from "node:child_process"; import { existsSync, readdirSync, readFileSync } from "node:fs"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { describe, expect, it } from "vitest"; const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); /** The one declaration. */ const DECLARATION = "crates/cotton-core/src/relay_address.rs"; /** Either host of Cotton's own relay, under any quoting or none. */ const LITERAL = String.raw`(relay|tunnel)\.cottondb\.com`; /** * BUILDING with the default: the constant interpolated (`{IDENT}` inside a * `format!`/`write!` string), concatenated (`+`), or bound to another name * (`const`/`let`/`static`). The names retired on 11 Oct 2026 stay in the * pattern so a revived per-crate constant is caught as what it is. */ const DEFAULTS = String.raw`DEFAULT_RELAY_DOMAIN|DEFAULT_TUNNEL_HOST|RELAY_(HOST_)?SUFFIX|RELAY_DOMAIN`; const CONSTRUCTIONS = [ String.raw`"[^"]*\{[^}]*\b(` + DEFAULTS + String.raw`)\b[^}]*\}`, // format!("…{DEFAULT_RELAY_DOMAIN}") String.raw`\+\s*&?(` + DEFAULTS + String.raw`)\b`, // … + DEFAULT_RELAY_DOMAIN String.raw`\b(` + DEFAULTS + String.raw`)\s*\+`, // DEFAULT_RELAY_DOMAIN + … String.raw`(const|let|static)\s+\w+(\s*:[^=]*)?=\s*(` + DEFAULTS + String.raw`)\b`, // an alias ]; /** Every crate's sources — a crate added tomorrow is swept without being listed. */ const ROOTS = readdirSync(join(REPO_ROOT, "crates"), { withFileTypes: true }) .filter((entry) => entry.isDirectory() && existsSync(join(REPO_ROOT, "crates", entry.name, "src"))) .map((entry) => `crates/${entry.name}/src`); /** * The files besides the declaration that hold the literal, each with the * reason it is not a second declaration of a household's address. */ const ALSO_NAMED_IN = new Map([]); /** * A Rust unit test lives INSIDE `src/`, in two shapes: `*_tests.rs` (and * `tests.rs`) are whole files, dropped by name; an inline `#[cfg(test)]` module * is the TAIL of a production file by this workspace's convention, so * everything from the first `#[cfg(test)]` on is test code. Dropping the tail * can only hide a spelling placed BELOW a test module. */ function isTestFile(path: string): boolean { return /(^|\/)[^/]*_tests\.rs$/.test(path) || /(^|\/)tests\.rs$/.test(path); } function testTailStart(path: string): number { const full = join(REPO_ROOT, path); if (!existsSync(full)) return Number.POSITIVE_INFINITY; const lines = readFileSync(full, "utf8").split("\n"); const index = lines.findIndex((line) => line.trim().startsWith("#[cfg(test)]")); return index === -1 ? Number.POSITIVE_INFINITY : index + 1; } /** One sweep per pattern, however many tests ask: the tree is large. */ const swept = new Map(); function grep(pattern: string): string[] { const known = swept.get(pattern); if (known) return known; const found = sweep(pattern); swept.set(pattern, found); return found; } function sweep(pattern: string): string[] { try { const out = execFileSync("grep", ["-rEn", "--include=*.rs", pattern, ...ROOTS], { cwd: REPO_ROOT, encoding: "utf8", maxBuffer: 64 * 1024 * 1024, }); return out .split("\n") .filter((line) => line.trim() !== "") // `file:line:text` — a match inside a COMMENT is prose, not a dial. .filter((line) => !/^\s*(\/\/|\*|\/\*)/.test(line.split(":").slice(2).join(":"))) .filter((line) => !isTestFile(line.split(":")[0] ?? "")) .filter((line) => { const [file, lineNo] = line.split(":"); return Number(lineNo) < testTailStart(file ?? ""); }); } catch (error) { // grep exits 1 with no output when nothing matched, which is the pass. if ((error as { status?: number }).status === 1) return []; throw error; } } const fileOf = (line: string) => line.split(":")[0] ?? ""; describe("no relay host is a compiled constant", () => { it("the Rust tree this guard reads by path is actually there", () => { expect(ROOTS, "no crate sources found — did the crates move?").toContain("crates/cotton-core/src"); expect(ROOTS.length).toBeGreaterThan(5); for (const file of [DECLARATION, ...ALSO_NAMED_IN.keys()]) { expect(existsSync(join(REPO_ROOT, file)), `${file} is named by this guard but not on disk`).toBe(true); } }); it("Cotton's own relay is spelled in one module", () => { const offenders = grep(LITERAL).filter((line) => fileOf(line) !== DECLARATION && !ALSO_NAMED_IN.has(fileOf(line))); expect( offenders, "a relay host is written out — take a `cotton_core::relay_address::RelayAddress` and ask it for the address", ).toEqual([]); }); it("and nothing builds an address out of the default by hand", () => { // One pass for all four shapes. const offenders = grep(CONSTRUCTIONS.map((shape) => `(${shape})`).join("|")); expect( offenders, "an address is assembled from the default constant — `RelayAddress::origin`, `host` and `directory_origin` are where one is made, so a household on its own relay gets its own", ).toEqual([]); }); it("the declaration is still where the guard looks", () => { // A guard that matches nothing passes for ever: a moved or renamed // declaration fails here rather than going quiet. expect(new Set(grep(LITERAL).map(fileOf))).toContain(DECLARATION); const declared = readFileSync(join(REPO_ROOT, DECLARATION), "utf8"); expect(declared).toMatch(/pub const DEFAULT_RELAY_DOMAIN: &str = "/); expect(declared).toMatch(/pub const DEFAULT_TUNNEL_HOST: &str = "/); expect(declared).toMatch(/pub fn cotton\(\) -> RelayAddress/); }); it("each exception says why it is not a household's address", () => { for (const [path, reason] of ALSO_NAMED_IN) { expect(reason.length, `${path}'s reason is too short to be one`).toBeGreaterThan(60); } }); it("sees the Rust spellings of both offences, and reading is not building", () => { const literal = new RegExp(LITERAL); const constructions = CONSTRUCTIONS.map((p) => new RegExp(p)); const caught = (line: string) => literal.test(line) || constructions.some((r) => r.test(line)); expect(caught(' let o = format!("https://{handle}.relay.cottondb.com");')).toBe(true); expect(caught(' host: "tunnel.cottondb.com".to_string(),')).toBe(true); expect(caught(' format!("https://{name}.{DEFAULT_RELAY_DOMAIN}")')).toBe(true); expect(caught(' format!("https://directory.{RELAY_DOMAIN}/v1/names/{name}/available")')).toBe(true); expect(caught(" let host = name.to_string() + DEFAULT_RELAY_DOMAIN;")).toBe(true); expect(caught(" const SUFFIX: &str = DEFAULT_RELAY_DOMAIN;")).toBe(true); expect(caught(' pub const RELAY_HOST_SUFFIX: &str = ".relay.cottondb.com";')).toBe(true); // Reading the default, passing it on and importing it are not building. expect(caught(" relay_domain: DEFAULT_RELAY_DOMAIN.to_string(),")).toBe(false); expect(caught("pub use cotton_core::relay_address::DEFAULT_TUNNEL_HOST;")).toBe(false); expect(caught("use crate::tunnel::{TunnelState, DEFAULT_RELAY_DOMAIN, DEFAULT_TUNNEL_HOST};")).toBe(false); expect(caught(" public_url_for(name, DEFAULT_RELAY_DOMAIN),")).toBe(false); // And neither fires on prose that merely mentions a relay. expect(caught("// the relay is an SNI passthrough holding no certificate")).toBe(false); }); });