/** * THE CONFIGURED PORT IS NOT AN ADDRESS. The BOUND port is. * * `PORT=0` is a legal value — it asks the OS for a free port, and `startServer` * reads the one it got off the listener and reports it as `RunningServer.port`, * with `deps.boundPort` carrying it into the origins a device signs. Which * means the configured value and the real one differ exactly when it matters, * and anything that reads the configured value BEFORE the bind and puts it * somewhere durable is minting an address for port 0. * * THE PORT IS FINISHED, AND WHAT IS LEFT HERE IS THE RULE. Step 5i deleted * `packages/server`, whose `start.ts` and `deps.ts` were the last TypeScript * readers of the configured value, so the allow-list below is EMPTY and the * sweep is what keeps it that way: the surviving TypeScript — the site, the * relay and `scripts/` — has no reason to read a port and now has to argue for * it if it ever does. The refusals themselves are Rust, and are asserted by * path at the bottom of this file. * * Two places once did. `buildObjectStore` fell back to `http://localhost:${env.PORT}` * for a `COTTON_MEDIA_DIR` server with no `COTTON_PUBLIC_URL`, and the Mac's * `mediaOrigin` fell back to `http://${lanIp}:${port}` with no relay name. Both * are answered while the port is still 0, so every presigned media URL would * have been signed against `:0` — links that resolve for nobody, handed out by * a server that otherwise looks healthy, failing one file at a time. * * ONE OF THEM IS NOW ANSWERED RATHER THAN REFUSED. Refusing was right about the * `:0` and wrong about the port: a data directory that asks the OS for its port * — which is what this whole guard asks everything else to do — could not start * at all without a relay name, and a seed-walk directory is exactly that. So * the media store holds the BOUND-PORT CELL (`ServerDeps::bound_port_handle`) * and the Mac's `media_origin` answers a HOST rather than a URL; the number is * read when a URL is minted, which is always after the bind. The refusal that * survives is the one that is still true: a caller that composes a store and * binds NOTHING (the test harness, through `build_object_store`) has no port to * name, and `PORT=0` there is refused as it always was. * * This guard is the reason a THIRD one has to argue for itself. The allow-list * is not a list of paths, it is a list of REASONS: every entry says what that * read does with the value and why a 0 cannot survive it. A new read is not * forbidden — it is required to write its sentence here. * * The Mac's own reads were included too, because its `serverController.ts` and * `import-hosted.ts` reached the same value through `parseEnvFile(...).PORT` * rather than through `env.PORT`, and a guard that only knew the server's * spelling would have missed half the hole this closed. Both went with the * Electron app in #395. THE RULE DID NOT — it is Rust now, and this sweep * cannot see Rust: the file filter below is `.ts/.tsx/.js/.mjs`, and the Rust * spellings (`vars.get("PORT")`, `file.get("PORT")`) are held by their own * modules' tests instead — `cotton_server::local_port` (a configured 0 is * reported as a sentence, never as an address; the running server's port is * read from `run/port`, which exists only after a bind) and * `cotton_ffi::shell::env_file` (`configured_port` KEEPS a 0, because it is * the value handed to the bind rather than an address). */ import { execFileSync } from "node:child_process"; import { 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)), "../.."); /** * Reading the CONFIGURED port, in every spelling that reaches one. * * `env.PORT` is the server's; `fromFile.PORT` / `parseEnvFile(…).PORT` is the * Mac's; `process.env.PORT` is nobody's today and is here so it stays that way. * `COTTON_TUNNEL_PORT` is a different key and is not swept: it is already 0 * everywhere and has no URL to appear in. */ const READ = String.raw`\benv\.PORT\b|process\.env\.PORT\b|\bfromFile\.PORT\b|\)\.PORT\b`; /** Shipped source. Tests read the port freely — that is what tests are for. */ const ROOTS = ["apps", "infra", "scripts"]; /** * Every read of the configured port that exists, and why a 0 cannot escape it. * * A path here is exact, never a prefix, so a new file cannot slip in behind * one. Adding an entry means writing the sentence — if the sentence is hard to * write, that is the finding. */ const ALLOWED = new Map([ // EMPTY, and that is the finished state rather than a gap. Both entries were // `packages/server`'s and went with it in 5i; their rules are Rust now and // are asserted by path below. A new TypeScript reader is not forbidden — it // is required to write its sentence here first. ]); /** * Read and match in JS, not with `git grep -E`. * * git's ERE has no `\b`, so the first version's pattern matched nothing and the * sweep came back clean on a tree with four readers in it — a guard that is * green because it is blind. `git ls-files` is used for what it is good at * (knowing what is tracked, so build output and `node_modules` are out by * construction) and the regex runs here, in the same dialect the pinned * examples below are checked in. */ function sourceFiles(): string[] { return execFileSync("git", ["ls-files", "--cached", "--others", "--exclude-standard", "--", ...ROOTS], { cwd: REPO_ROOT, encoding: "utf8", maxBuffer: 32 * 1024 * 1024, }) .split("\n") .filter((path) => /\.(ts|tsx|js|mjs)$/.test(path) && !path.includes("__tests__/")); } /** * Code, with the prose taken out. * * A comment that NAMES `env.PORT` while explaining why nothing should read it * is not a read, and a guard that cannot tell the difference turns every future * sentence about this rule into an allow-list entry — at which point the list * stops meaning anything. (`env.ts`'s docstring quoting the Mac's * `fromFile.PORT?.trim()` is exactly that, and was the first thing this caught.) * * WHOLE LINES ONLY, and a block only when its `/*` opens a line. Deliberately * not a general comment stripper, in both directions: * * - `"http://localhost:${env.PORT}"` has a `//` inside a string, so cutting * at the first `//` anywhere would halve the one line this guard exists * for. A trailing `// …` after code therefore survives — the conservative * direction, since a read hiding behind one still gets listed. * - `start.ts` has a LINE comment that quotes a block-comment opener while * explaining an OAuth failure. A whole-file regex for a block comment * opened one there and swallowed eighty lines, the bind among them, so the * sweep came back three-of-four — caught by the stale-entry test, not by * the sweep, which is the argument for having both. Blocks are recognised * only where they open a line. * * TWO SHAPES IT GETS WRONG, both named so a future reader does not have to * rediscover them, and neither worth more machinery than a real parser: * * - A multi-line template literal whose continuation line begins with `//` * is STRING CONTENT, and this removes it. Harmless today (nothing embeds a * port read in one) and it can only hide a read, never invent one — a * false negative, which the stale-entry test below would catch for any * path already on the list. * - A block comment opened AFTER code on the same line is not a comment to * this at all: the line is kept whole, so a read inside one would be * listed. That is the wrong direction to be wrong in, which is why it is * the one chosen. */ function codeOnly(text: string): string { const out: string[] = []; let inBlock = false; for (const line of text.split("\n")) { const start = line.trimStart(); if (inBlock) { if (line.includes("*/")) inBlock = false; continue; } if (start.startsWith("/*")) { if (!line.includes("*/")) inBlock = true; continue; } if (start.startsWith("//") || start.startsWith("*")) continue; out.push(line); } return out.join("\n"); } function readers(): string[] { const read = new RegExp(READ); return sourceFiles().filter((path) => read.test(codeOnly(readFileSync(join(REPO_ROOT, path), "utf8")))); } describe("nothing reads the configured port without saying why", () => { // RULE: An address is the port a server actually bound, never the port it was configured with. it("every reader of the configured port is on the list, with its reason", () => { const unlisted = readers().filter((path) => !ALLOWED.has(path)); expect( unlisted, "these read the CONFIGURED port, which is 0 until the bind. Read `deps.boundPort` / " + "`RunningServer.port` instead, or add an entry to ALLOWED saying why a 0 cannot escape:\n " + unlisted.join("\n "), ).toEqual([]); }); it("no entry on the list is stale — a path that stopped reading it is a comment nobody deleted", () => { const live = new Set(readers()); for (const path of ALLOWED.keys()) { expect(live, `${path} is on the allow-list but no longer reads the configured port`).toContain(path); } }); it("each reason is a sentence, not a shrug", () => { for (const [path, reason] of ALLOWED) { expect(reason.length, `${path}'s reason is too short to be one`).toBeGreaterThan(80); } }); it("the sweep is not vacuous — the pattern still matches what it is for", () => { // NONE today, which is why the pattern itself is exercised rather than a // count: an empty sweep over a tree with no readers and an empty sweep from // a regex that stopped matching look identical from here, and only one of // them is the pass. expect(readers()).toEqual([]); expect(new RegExp(READ).test("const p = env.PORT;")).toBe(true); expect(new RegExp(READ).test("const p = parseEnvFile(text).PORT;")).toBe(true); expect(new RegExp(READ).test("const written = fromFile.PORT?.trim();")).toBe(true); expect(new RegExp(READ).test("const p = process.env.PORT;")).toBe(true); // And leaves the bound one alone, which is the whole point. expect(new RegExp(READ).test("deps.boundPort = boundPort;")).toBe(false); expect(new RegExp(READ).test("port = running.port;")).toBe(false); }); it("a comment that NAMES the read is not a read — but a URL with `//` in it still is", () => { const read = new RegExp(READ); // Prose, in both comment shapes. expect(read.test(codeOnly("// the Mac reads fromFile.PORT here"))).toBe(false); expect(read.test(codeOnly(" * `env.PORT` is the configured one, not the bound one"))).toBe(false); expect(read.test(codeOnly("/**\n * env.PORT\n */"))).toBe(false); // And the line this guard exists for, which contains a `//` of its own and // must survive the strip whole. expect(read.test(codeOnly(" publicUrl: env.COTTON_PUBLIC_URL ?? `http://localhost:${env.PORT}`,"))).toBe(true); // A trailing comment on a line of code is left alone — conservative, and a // read hiding behind one would still be listed. expect(read.test(codeOnly("const p = env.PORT; // the configured one"))).toBe(true); }); });