diff --git a/packages/cultmesh-browser/test/cultmesh-browser.test.ts b/packages/cultmesh-browser/test/cultmesh-browser.test.ts index 77237bb9..59f9fac1 100644 --- a/packages/cultmesh-browser/test/cultmesh-browser.test.ts +++ b/packages/cultmesh-browser/test/cultmesh-browser.test.ts @@ -245,26 +245,43 @@ test("browser client opens an unsigned-certificate loopback session under local- trust, socketFactory: () => handshakeOnlySocket(route), }); - const blank = (route: CultMeshBrowserRoute) => ({ ...route, certificate: { ...route.certificate!, signature: "" } }); + const blank = (route: CultMeshBrowserRoute, signature: string) => + ({ ...route, certificate: { ...route.certificate!, signature } }); const loopback = await createSignedRoute("ws://127.0.0.1:4501/mesh"); const localTrust = { mode: "local-development" as const, odinRoots: [loopback.odinPublic] }; - const client = await connect(blank(loopback.route), localTrust); - assert.equal(client.state, "connected"); - await client.dispose(); + const remote = await createSignedRoute("wss://provider.example/mesh"); + + // Empty is the easy case. The whitespace signatures are the ones that catch a + // local re-reading of "unsigned" here: an inline `signature === ""` passes + // every other test in this file and fails these, and U+0085 also separates + // `String.prototype.trim` from the C# `char.IsWhiteSpace` the shared + // `isUnsignedCertificate` uses. Both sides of the session check have to read + // "unsigned" the same way, or the route verifier accepts a session the + // acceptance check then demands a provider proof for. + for (const signature of ["", " ", "\u0085", "\u00a0\t\n"]) { + const label = JSON.stringify(signature); + const client = await connect(blank(loopback.route, signature), localTrust); + assert.equal(client.state, "connected", label); + await client.dispose(); + await assert.rejects( + connect(blank(remote.route, signature), { mode: "local-development", odinRoots: [remote.odinPublic] }), + /Odin-signed authority certificate/, + label, + ); + await assert.rejects( + connect(blank(remote.route, signature), { mode: "authenticated-remote", odinRoots: [remote.odinPublic] }), + /Odin-signed authority certificate/, + label, + ); + } + // U+FEFF is whitespace to JavaScript and not to C#, so it is a signature, not + // an unsigned route, and the loopback route is refused for its bytes. + await assert.rejects(connect(blank(loopback.route, "\ufeff"), localTrust), /not base64|not IEEE P1363/); + // A signed loopback certificate is an authenticated route even under // local-development; the provider must still prove its key. await assert.rejects(connect(loopback.route, localTrust), /did not prove possession/); - - const remote = await createSignedRoute("wss://provider.example/mesh"); - await assert.rejects( - connect(blank(remote.route), { mode: "local-development", odinRoots: [remote.odinPublic] }), - /Odin-signed authority certificate/, - ); - await assert.rejects( - connect(blank(remote.route), { mode: "authenticated-remote", odinRoots: [remote.odinPublic] }), - /Odin-signed authority certificate/, - ); }); test("browser client rejects a mutated or expired signed route before opening a provider socket", async () => { diff --git a/packages/cultnet-ts/src/cultmesh-authority.ts b/packages/cultnet-ts/src/cultmesh-authority.ts index c5fd2c5b..b9681c71 100644 --- a/packages/cultnet-ts/src/cultmesh-authority.ts +++ b/packages/cultnet-ts/src/cultmesh-authority.ts @@ -316,7 +316,7 @@ function ownedBytes(view: Uint8Array): ArrayBuffer { * accepts them: " ws://127.0.0.1/mesh" is loopback to both. */ function refusedByCSharpUriShape(value: string): boolean { - const raw = value.replace(/^[- ]+|[- ]+$/g, ""); + const raw = value.replace(/^[\u0000-\u0020]+|[\u0000-\u0020]+$/g, ""); if (raw.includes("\\")) return true; const shape = /^[A-Za-z][A-Za-z0-9+\-.]*:\/\/([^/?#]+)/.exec(raw); if (!shape) return true; @@ -327,7 +327,7 @@ function refusedByCSharpUriShape(value: string): boolean { : afterUserInfo.split(":")[0]!; if (host.length === 0) return true; // eslint-disable-next-line no-control-regex - return /[^!-~]/.test(host) || host.endsWith("."); + return /[^\u0021-\u007e]/.test(host) || host.endsWith("."); } /** diff --git a/scripts/mutate-cultmesh-authority.mjs b/scripts/mutate-cultmesh-authority.mjs index 25c289ab..92e4bf53 100644 --- a/scripts/mutate-cultmesh-authority.mjs +++ b/scripts/mutate-cultmesh-authority.mjs @@ -1,15 +1,23 @@ -// Mutation check for the shared CultMesh route verifier. +// Mutation check for the CultMesh route verification rules. // -// Each rule the cut map names for `packages/cultnet-ts/src/cultmesh-authority.ts` -// gets one mutation. A mutation is killed when `npm run test --workspace -// packages/cultnet-ts` fails with it applied; a survivor means no test pins that -// rule. The file is rewritten as UTF-8 bytes and restored from the original -// bytes with a digest check, never from git. A no-op control runs first through -// the same write path so a false kill from the write itself cannot hide. +// Two files own those rules and each is one target here. `shared` is +// `packages/cultnet-ts/src/cultmesh-authority.ts`, the one verifier, killed by +// `npm run test --workspace packages/cultnet-ts`. `browser` is +// `packages/cultmesh-browser/src/index.ts`, which must *call* the shared rules +// rather than re-read them locally, killed by `npm run test --workspace +// packages/cultmesh-browser`. A browser mutation cannot be killed by the +// cultnet-ts tests and a shared one is not the browser's to pin, so the killer +// is the target's own workspace. // -// The original bytes also live in `.mutation-original` from the first +// Each rule the cut map names gets one mutation. A survivor means no test pins +// that rule. Each file is rewritten as UTF-8 bytes and restored from the +// original bytes with a digest check, never from git. A no-op control runs +// first per target through the same write path so a false kill from the write +// itself cannot hide. +// +// The original bytes also live in `.mutation-original` from the first // write until a verified restore; a run killed mid-mutation is repaired from -// that sidecar by the next run, not by git. After the final restore the +// that sidecar by the next run, not by git. After the final restore each // package is rebuilt so `dist/` never carries the last mutant. // // node scripts/mutate-cultmesh-authority.mjs @@ -21,15 +29,27 @@ import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); -const target = join(repoRoot, "packages", "cultnet-ts", "src", "cultmesh-authority.ts"); -const sidecar = `${target}.mutation-original`; -const dist = join(repoRoot, "packages", "cultnet-ts", "dist", "cultmesh-authority.js"); const npmCli = process.env.npm_execpath ?? join(dirname(process.execPath), "node_modules", "npm", "bin", "npm-cli.js"); -// Present in the restored source and compiled verbatim into dist/; the last -// mutation in the list removes it, which is what makes the post-rebuild check -// distinguish a rebuilt dist/ from one still carrying that mutant. -const sentinel = 'scheme === "https"'; + +// Each target's `sentinel` is present in its restored source and compiled +// verbatim into its dist/; that target's last mutation removes it, which is +// what makes the post-rebuild check distinguish a rebuilt dist/ from one still +// carrying that mutant. +const targets = { + shared: { + workspace: "packages/cultnet-ts", + file: join(repoRoot, "packages", "cultnet-ts", "src", "cultmesh-authority.ts"), + dist: join(repoRoot, "packages", "cultnet-ts", "dist", "cultmesh-authority.js"), + sentinel: 'scheme === "https"', + }, + browser: { + workspace: "packages/cultmesh-browser", + file: join(repoRoot, "packages", "cultmesh-browser", "src", "index.ts"), + dist: join(repoRoot, "packages", "cultmesh-browser", "dist", "index.js"), + sentinel: "isUnsignedCertificate(route.certificate)", + }, +}; const mutations = [ { @@ -218,51 +238,38 @@ const mutations = [ old: 'scheme === "https" || ', new: "", }, + // The browser target. Its session-acceptance short-circuit must ask the + // shared module what "unsigned" means; a local re-reading here and the route + // verifier's reading there can drift apart, and a browser route that the + // verifier let through unsigned would then be asked for a provider proof. + { + target: "browser", + rule: "the session short-circuit calls the shared isUnsignedCertificate, not a local reading", + old: "isUnsignedCertificate(route.certificate)", + new: '(route.certificate?.signature ?? "") === ""', + }, ]; -if (existsSync(sidecar)) { - writeFileSync(target, readFileSync(sidecar)); - unlinkSync(sidecar); - console.log(`repaired ${target} from ${sidecar}: a previous run stopped before restoring it`); -} - -const original = readFileSync(target); -const originalText = original.toString("utf8"); -const originalDigest = digest(original); - -// Anchors are written with "\n"; the checkout may be CRLF (autocrlf). Match -// the file's own line ending so a multi-line anchor cannot silently miss. -const eol = originalText.includes("\r\n") ? "\r\n" : "\n"; -const withEol = text => text.replace(/\r?\n/g, eol); - function digest(bytes) { return createHash("sha256").update(bytes).digest("hex"); } -function npm(...args) { - execFileSync(process.execPath, [npmCli, ...args, "--workspace", "packages/cultnet-ts"], { +function npm(workspace, ...args) { + execFileSync(process.execPath, [npmCli, ...args, "--workspace", workspace], { cwd: repoRoot, stdio: ["ignore", "pipe", "pipe"], }); } -function testsPass() { +function testsPass(workspace) { try { - npm("run", "test"); + npm(workspace, "run", "test"); return true; } catch { return false; } } -function restore() { - writeFileSync(target, original); - const restored = digest(readFileSync(target)); - if (restored !== originalDigest) { - throw new Error(`restore failed: ${target} digest ${restored} != ${originalDigest}`); - } -} - function occurrences(text, needle) { return text.split(needle).length - 1; } @@ -270,43 +277,81 @@ function occurrences(text, needle) { const results = []; let failed = false; -const last = mutations[mutations.length - 1]; -if (!originalText.includes(sentinel) || originalText.replace(withEol(last.old), withEol(last.new)).includes(sentinel)) { - throw new Error(`the sentinel '${sentinel}' must be in the source and removed by the last mutation ('${last.rule}')`); -} - -writeFileSync(sidecar, original); -try { - writeFileSync(target, Buffer.from(originalText, "utf8")); - const controlPass = testsPass(); - results.push({ rule: "control (no-op rewrite)", outcome: controlPass ? "green" : "RED" }); - if (!controlPass) failed = true; - else { - for (const mutation of mutations) { - const [old, replacement] = [withEol(mutation.old), withEol(mutation.new)]; - const count = occurrences(originalText, old); - if (count !== 1) { - throw new Error(`anchor for '${mutation.rule}' matched ${count} times, expected exactly 1`); - } - writeFileSync(target, Buffer.from(originalText.replace(old, replacement), "utf8")); - const pass = testsPass(); - restore(); - results.push({ rule: mutation.rule, outcome: pass ? "SURVIVED" : "killed" }); - if (pass) failed = true; - } +for (const [name, target] of Object.entries(targets)) { + const own = mutations.filter(mutation => (mutation.target ?? "shared") === name); + if (own.length === 0) throw new Error(`target '${name}' has no mutations`); + const sidecar = `${target.file}.mutation-original`; + if (existsSync(sidecar)) { + writeFileSync(target.file, readFileSync(sidecar)); + unlinkSync(sidecar); + console.log(`repaired ${target.file} from ${sidecar}: a previous run stopped before restoring it`); } -} finally { - restore(); -} -unlinkSync(sidecar); -// Every test run above rebuilt dist/ from a mutant; put the restored source back in it. -npm("run", "build"); -if (!readFileSync(dist, "utf8").includes(sentinel)) { - throw new Error(`${dist} does not contain '${sentinel}' after the rebuild; it still carries a mutant`); + const original = readFileSync(target.file); + const originalText = original.toString("utf8"); + const originalDigest = digest(original); + + // Anchors are written with "\n"; the checkout may be CRLF (autocrlf). Match + // the file's own line ending so a multi-line anchor cannot silently miss. + const eol = originalText.includes("\r\n") ? "\r\n" : "\n"; + const withEol = text => text.replace(/\r?\n/g, eol); + + const restore = () => { + writeFileSync(target.file, original); + const restored = digest(readFileSync(target.file)); + if (restored !== originalDigest) { + throw new Error(`restore failed: ${target.file} digest ${restored} != ${originalDigest}`); + } + }; + + const last = own[own.length - 1]; + if (!originalText.includes(target.sentinel) || + originalText.replace(withEol(last.old), withEol(last.new)).includes(target.sentinel)) { + throw new Error( + `the sentinel '${target.sentinel}' must be in ${target.file} and removed by its last mutation ('${last.rule}')`, + ); + } + + writeFileSync(sidecar, original); + try { + writeFileSync(target.file, Buffer.from(originalText, "utf8")); + const controlPass = testsPass(target.workspace); + results.push({ target: name, outcome: controlPass ? "green" : "RED", rule: "control (no-op rewrite)" }); + if (!controlPass) failed = true; + else { + for (const mutation of own) { + const [old, replacement] = [withEol(mutation.old), withEol(mutation.new)]; + const count = occurrences(originalText, old); + if (count !== 1) { + throw new Error(`anchor for '${mutation.rule}' matched ${count} times in ${target.file}, expected exactly 1`); + } + writeFileSync(target.file, Buffer.from(originalText.replace(old, replacement), "utf8")); + const pass = testsPass(target.workspace); + restore(); + results.push({ target: name, outcome: pass ? "SURVIVED" : "killed", rule: mutation.rule }); + if (pass) failed = true; + } + } + } finally { + // A verified restore is what the sidecar exists to guarantee, so it goes + // here and not after the try: a throw mid-run used to leave the sidecar + // behind, and the next run "repaired" the file from bytes that were already + // stale, silently undoing whatever had been fixed in between. + restore(); + unlinkSync(sidecar); + } + + // Every test run above rebuilt dist/ from a mutant; put the restored source back in it. + npm(target.workspace, "run", "build"); + if (!readFileSync(target.dist, "utf8").includes(target.sentinel)) { + throw new Error(`${target.dist} does not contain '${target.sentinel}' after the rebuild; it still carries a mutant`); + } + results.push({ + target: name, + outcome: "restored", + rule: `${target.file} sha256=${originalDigest}, rebuilt ${target.dist}`, + }); } -for (const result of results) console.log(`${result.outcome.padEnd(9)} ${result.rule}`); -console.log(`restored ${target} sha256=${originalDigest}`); -console.log(`rebuilt ${dist}`); +for (const result of results) console.log(`${result.outcome.padEnd(9)} [${result.target}] ${result.rule}`); process.exit(failed ? 1 : 0);