diff --git a/packages/cultnet-ts/src/cultmesh-authority.ts b/packages/cultnet-ts/src/cultmesh-authority.ts index f3a9121d..9e28bad7 100644 --- a/packages/cultnet-ts/src/cultmesh-authority.ts +++ b/packages/cultnet-ts/src/cultmesh-authority.ts @@ -103,8 +103,9 @@ export async function verifyAuthorityRoute( if (!isProtectedEndpoint(route.endpoint) && !(trust.mode === "local-development" && isLoopbackEndpoint(route.endpoint))) { throw new Error("Authenticated remote CultMesh routes require TLS or QUIC channel protection."); } - const root = roots.get(certificate.odinKeyId); - if (!root) throw new Error(`Odin key '${certificate.odinKeyId}' is not trusted by this consumer.`); + const odinKeyId = certificateOdinKeyId(certificate); + const root = roots.get(odinKeyId); + if (!root) throw new Error(`Odin key '${odinKeyId}' is not trusted by this consumer.`); const now = trust.now?.() ?? Date.now(); if (now < certificate.issuedAtUnixMilliseconds || now >= certificate.expiresAtUnixMilliseconds) { throw new Error("The Odin route certificate is not currently valid."); @@ -132,11 +133,15 @@ export async function verifyAuthorityRoute( // The C# policy is a dictionary keyed by Odin key id and its constructor // throws on a duplicate. A TypeScript policy is a plain object, so the same // refusal happens at the first use of the policy, before any route is judged. +// The key is `CultMeshEcdsaP256PublicKey.KeyId`, which `Require` already +// trimmed, so two roots whose ids differ only in padding are one duplicate here +// too, and a padded certificate id still finds its root. function trustedOdinRoots(trust: CultMeshAuthorityTrustPolicy): Map { const roots = new Map(); for (const root of trust.odinRoots ?? []) { - if (roots.has(root.keyId)) throw new Error(`Odin root key id '${root.keyId}' is listed more than once in the trust policy.`); - roots.set(root.keyId, root); + const keyId = requireNonEmptyCSharp(root.keyId, "keyId"); + if (roots.has(keyId)) throw new Error(`Odin root key id '${keyId}' is listed more than once in the trust policy.`); + roots.set(keyId, root); } return roots; } @@ -151,36 +156,87 @@ export function verifyProviderSessionProof( return verifyP256(providerKey, canonicalSession(request, endpoint), signatureBase64); } +/** + * `CultMeshAuthorityRoute.Clean`: trim each protocol id, drop the blank ones, + * keep one of each ordinally, and sort ordinally. JavaScript's default sort is + * UTF-16 code-unit order, which is what `StringComparer.Ordinal` compares. + * + * A route that lists no protocol ids at all is `Array.Empty()` in C# + * and transcribes as the empty string, so there is no substitute id here: the + * TypeScript route view carries a separate `protocolId` for the handshake, and + * reading it as a one-element list would transcribe bytes the reference never + * writes. + */ +function cleanProtocolIds(values: readonly string[] | undefined): string[] { + return [...new Set((values ?? []).filter(value => !isNullOrWhiteSpaceCSharp(value)).map(trimCSharp))].sort(); +} + +/** `RequireNonEmpty` and `Require` in the C# reference: one refusal, one trimmed value. */ +function requireNonEmptyCSharp(value: string | undefined, parameterName: string): string { + if (isNullOrWhiteSpaceCSharp(value)) throw new Error(`Value must be non-empty. (Parameter '${parameterName}')`); + return trimCSharp(value!); +} + +/** `CultMeshRouteCertificate`: the Odin key identity is required, and trimmed. */ +function certificateOdinKeyId(certificate: CultMeshAuthorityRouteCertificate): string { + if (isNullOrWhiteSpaceCSharp(certificate.odinKeyId)) { + throw new Error("Odin key identity is required. (Parameter 'odinKeyId')"); + } + return trimCSharp(certificate.odinKeyId); +} + +/** + * The transcript the C# reference signs is over a *constructed* route, and the + * C# constructors clean every field on the way in. Cleaning at the transcript + * is where TypeScript gets the same bytes: a duplicated protocol id, a padded + * protocol id, a padded generation and a padded Odin key id all verify against + * a C#-written signature, because C# never saw the padding either. + * + * `verseId` is the exception. It is not a route field: `CanonicalRoute` passes + * the caller's string straight into `Canonical`, untrimmed, so padding it + * changes the bytes on both sides. + */ export function canonicalRoute(route: CultMeshAuthorityRouteView): Uint8Array { const certificate = route.certificate!; + const authorityRuntimeId = requireNonEmptyCSharp(route.authorityRuntimeId, "authorityRuntimeId"); + const endpoint = requireNonEmptyCSharp(route.endpoint, "endpoint"); return canonicalFields( "gamecult.cultmesh.route-certificate.v1", route.verseId, - route.authorityRuntimeId, - route.endpoint, - [...(route.protocolIds ?? [route.protocolId ?? "cultmesh.documents.v1"])].sort().join(""), + authorityRuntimeId, + endpoint, + cleanProtocolIds(route.protocolIds).join(""), String(route.priority ?? 0), - route.generation, - certificate.providerKey.keyId, - certificate.providerKey.x, - certificate.providerKey.y, - certificate.odinKeyId, + // A blank generation is not blank in C#: the route constructor substitutes + // the runtime id and endpoint, already cleaned, joined by "@". + isNullOrWhiteSpaceCSharp(route.generation) ? `${authorityRuntimeId}@${endpoint}` : trimCSharp(route.generation), + requireNonEmptyCSharp(certificate.providerKey.keyId, "keyId"), + requireNonEmptyCSharp(certificate.providerKey.x, "x"), + requireNonEmptyCSharp(certificate.providerKey.y, "y"), + certificateOdinKeyId(certificate), String(certificate.issuedAtUnixMilliseconds), String(certificate.expiresAtUnixMilliseconds), ); } +/** + * `CanonicalSession` cleans nothing on the request: it substitutes the empty + * string for a null field and trims none of them, because the handshake message + * is what the wire carried, not a constructed route. The endpoint is the only + * cleaned field, because the one C# passes is `Route.Endpoint`, which the route + * constructor already required non-empty and trimmed. + */ export function canonicalSession(request: CultMeshSessionOpenMessage, endpoint: string): Uint8Array { return canonicalFields( "gamecult.cultmesh.session-proof.v1", - request.clientNonce, - request.messageId, - request.sourceRuntimeId, - request.verseId, - request.authorityRuntimeId, - request.protocolId, - endpoint, - request.routeGeneration, + request.clientNonce ?? "", + request.messageId ?? "", + request.sourceRuntimeId ?? "", + request.verseId ?? "", + request.authorityRuntimeId ?? "", + request.protocolId ?? "", + requireNonEmptyCSharp(endpoint, "endpoint"), + request.routeGeneration ?? "", ); } diff --git a/packages/cultnet-ts/test/cultmesh-authority.test.ts b/packages/cultnet-ts/test/cultmesh-authority.test.ts index b8fc2509..a0820628 100644 --- a/packages/cultnet-ts/test/cultmesh-authority.test.ts +++ b/packages/cultnet-ts/test/cultmesh-authority.test.ts @@ -383,7 +383,9 @@ for (const [label, path] of [["C# reference", VECTORS_PATH], ["TypeScript-signed await verifyAuthorityRoute(vectors.route, trust); await assert.rejects(verifyAuthorityRoute({ ...vectors.route, priority: 8 }, trust), /signature is invalid/); await assert.rejects( - verifyAuthorityRoute({ ...vectors.route, protocolIds: [...vectors.route.protocolIds!, "cultmesh.realtime.v1"] }, trust), + // An id the vector does not already list: one it does list would be a + // duplicate, and the C# `Clean` drops duplicates before the transcript. + verifyAuthorityRoute({ ...vectors.route, protocolIds: [...vectors.route.protocolIds!, "cultmesh.telemetry.v1"] }, trust), /signature is invalid/, ); @@ -399,6 +401,55 @@ for (const [label, path] of [["C# reference", VECTORS_PATH], ["TypeScript-signed ); }); +// Soul ran each of these against the C# reference on 2026-09-16 by tampering +// with the committed vector and rerunning the C# test: C# accepted every one, +// because its constructors clean the field before `CanonicalRoute` sees it. +// TypeScript refused every one until it cleaned at the transcript too. The +// signature here is the C#-written one; nothing is re-signed. +test("padding and duplication the C# constructors clean still verify against the C#-written vector", async () => { + const vectors = JSON.parse(readFileSync(VECTORS_PATH, "utf8")) as Vectors; + const trust = { mode: "authenticated-remote" as const, odinRoots: [vectors.odinRoot], now: () => vectors.nowUnixMilliseconds }; + const route = vectors.route; + const certificate = route.certificate!; + const protocolIds = route.protocolIds!; + const accepted: readonly (readonly [string, CultMeshAuthorityRouteView])[] = [ + ["a duplicated protocol id", { ...route, protocolIds: [...protocolIds, protocolIds[0]!] }], + ["a padded protocol id", { ...route, protocolIds: [` ${protocolIds[0]!}…`, ...protocolIds.slice(1)] }], + ["a blank protocol id", { ...route, protocolIds: [...protocolIds, " "] }], + ["the protocol ids reversed", { ...route, protocolIds: [...protocolIds].reverse() }], + ["a padded generation", { ...route, generation: ` ${route.generation} ` }], + ["a padded endpoint", { ...route, endpoint: ` ${route.endpoint} ` }], + ["a padded Odin key id", { ...route, certificate: { ...certificate, odinKeyId: ` ${certificate.odinKeyId} ` } }], + ["a padded provider key id", { + ...route, + certificate: { ...certificate, providerKey: { ...certificate.providerKey, keyId: ` ${certificate.providerKey.keyId} ` } }, + }], + ]; + for (const [label, candidate] of accepted) { + await verifyAuthorityRoute(candidate, trust).catch((error: Error) => { + assert.fail(`${label} should verify as it does in C#, but: ${error.message}`); + }); + } + // A padded Odin key id also has to find its root, as it does in the C# + // dictionary, whose keys `Require` already trimmed. + await verifyAuthorityRoute( + { ...route, certificate: { ...certificate, odinKeyId: ` ${certificate.odinKeyId} ` } }, + { ...trust, odinRoots: [{ ...vectors.odinRoot, keyId: `\t${vectors.odinRoot.keyId}\t` }] }, + ); + + // `verseId` is not a route field and C# does not clean it, so padding it + // changes the bytes on both sides. + await assert.rejects(verifyAuthorityRoute({ ...route, verseId: ` ${route.verseId} ` }, trust), /signature is invalid/); + // A route with no protocol ids transcribes the empty string, as C#'s + // `Array.Empty()` does; there is no substituted default id. + await assert.rejects(verifyAuthorityRoute({ ...route, protocolIds: undefined }, trust), /signature is invalid/); + await assert.rejects(verifyAuthorityRoute({ ...route, protocolIds: [] }, trust), /signature is invalid/); + assert.deepEqual( + canonicalRoute({ ...route, protocolIds: undefined }), + canonicalRoute({ ...route, protocolIds: ["", " "] }), + ); +}); + test("the shared module keeps the browser-safe surface: no node: import", () => { const source = readFileSync(join(__dirname, "..", "..", "src", "cultmesh-authority.ts"), "utf8"); assert.doesNotMatch(source, /from "node:|require\("node:/); diff --git a/scripts/mutate-cultmesh-authority.mjs b/scripts/mutate-cultmesh-authority.mjs index 176c7f7f..1e86133a 100644 --- a/scripts/mutate-cultmesh-authority.mjs +++ b/scripts/mutate-cultmesh-authority.mjs @@ -54,7 +54,7 @@ const mutations = [ }, { rule: "Odin root lookup by key id", - old: "const root = roots.get(certificate.odinKeyId);", + old: "const root = roots.get(odinKeyId);", new: "const root = [...roots.values()][0];", }, { @@ -90,8 +90,9 @@ const mutations = [ }, { rule: "root lookup precedes the validity window", - old: " const root = roots.get(certificate.odinKeyId);\n" + - " if (!root) throw new Error(`Odin key '${certificate.odinKeyId}' is not trusted by this consumer.`);\n" + + old: " const odinKeyId = certificateOdinKeyId(certificate);\n" + + " const root = roots.get(odinKeyId);\n" + + " if (!root) throw new Error(`Odin key '${odinKeyId}' is not trusted by this consumer.`);\n" + " const now = trust.now?.() ?? Date.now();\n" + " if (now < certificate.issuedAtUnixMilliseconds || now >= certificate.expiresAtUnixMilliseconds) {\n" + ' throw new Error("The Odin route certificate is not currently valid.");\n' + @@ -100,18 +101,19 @@ const mutations = [ " if (now < certificate.issuedAtUnixMilliseconds || now >= certificate.expiresAtUnixMilliseconds) {\n" + ' throw new Error("The Odin route certificate is not currently valid.");\n' + " }\n" + - " const root = roots.get(certificate.odinKeyId);\n" + - " if (!root) throw new Error(`Odin key '${certificate.odinKeyId}' is not trusted by this consumer.`);\n", + " const odinKeyId = certificateOdinKeyId(certificate);\n" + + " const root = roots.get(odinKeyId);\n" + + " if (!root) throw new Error(`Odin key '${odinKeyId}' is not trusted by this consumer.`);\n", }, { rule: "duplicate Odin root key ids refuse the policy", - old: " if (roots.has(root.keyId)) throw new Error(`Odin root key id '${root.keyId}' is listed more than once in the trust policy.`);\n", + old: " if (roots.has(keyId)) throw new Error(`Odin root key id '${keyId}' is listed more than once in the trust policy.`);\n", new: "", }, { rule: "protocol ids are sorted into the transcript", - old: "].sort().join(", - new: "].join(", + old: ")].sort();", + new: ")];", }, { rule: "verifyP256 copies the viewed payload bytes, not the pool behind a Buffer", @@ -120,14 +122,39 @@ const mutations = [ }, { rule: "route transcript field order", - old: " route.verseId,\n route.authorityRuntimeId,\n", - new: " route.authorityRuntimeId,\n route.verseId,\n", + old: " route.verseId,\n authorityRuntimeId,\n", + new: " authorityRuntimeId,\n route.verseId,\n", }, { rule: "session transcript binds the nonce", - old: " request.clientNonce,\n", + old: ' request.clientNonce ?? "",\n', new: "", }, + { + rule: "protocol ids are deduplicated into the transcript", + old: " return [...new Set(", + new: " return [...(", + }, + { + rule: "the generation is trimmed into the transcript", + old: ": trimCSharp(route.generation),", + new: ": route.generation,", + }, + { + rule: "the provider key id is trimmed into the transcript", + old: ' requireNonEmptyCSharp(certificate.providerKey.keyId, "keyId"),', + new: " certificate.providerKey.keyId,", + }, + { + rule: "the Odin key id is trimmed before the root lookup", + old: " const odinKeyId = certificateOdinKeyId(certificate);", + new: " const odinKeyId = certificate.odinKeyId;", + }, + { + rule: "blank protocol ids are dropped from the transcript", + old: "(values ?? []).filter(value => !isNullOrWhiteSpaceCSharp(value)).map(trimCSharp)", + new: "(values ?? []).map(trimCSharp)", + }, { rule: "length-prefix framing is big-endian", old: "view.setUint32(offset, value.byteLength, false);",