From 1590145a81d68b8b940e0da2bb0d2962b1506cec Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 16 Sep 2026 16:27:06 +0200 Subject: [PATCH] Pin the TypeScript-signed direction of the authority parity check `contracts/cultmesh/authority-route-vectors.json` proves C# bytes verify in TypeScript. Nothing in the repo proved the reverse; Soul's probe did it once in a scratch directory. It is now a committed check in the same shape, mirrored: - `scripts/sign-cultmesh-authority-vectors.mjs` builds the route and session transcripts with the shared module, signs them with fixed TypeScript-owned test keys over awkward inputs (a quic scheme with a query, three unsorted protocol ids, non-ASCII generation text, priority 13), self-verifies, and writes `contracts/cultmesh/authority-route-vectors.ts-signed.json`. - `CultMeshAuthorityProofTests.AuthorityRouteVectorsSignedByTypeScriptVerifyHere` reads that file with keys taken from the file, asserts the protocol ids are unsorted, that `Validate` and `VerifySessionProof` accept, and that a priority-tampered route and a replayed nonce are refused. - The TypeScript vector test runs over both files, so a transcript change on the TypeScript side fails here before C# could trust a stale file. Checked negatively: one base64 character changed in the committed signature fails the C# test. Co-Authored-By: Claude Fable 5.1 --- .../authority-route-vectors.ts-signed.json | 45 ++++++++ .../test/cultmesh-authority.test.ts | 12 +- scripts/sign-cultmesh-authority-vectors.mjs | 109 ++++++++++++++++++ .../CultMeshAuthorityProofTests.cs | 78 +++++++++++++ 4 files changed, 241 insertions(+), 3 deletions(-) create mode 100644 contracts/cultmesh/authority-route-vectors.ts-signed.json create mode 100644 scripts/sign-cultmesh-authority-vectors.mjs diff --git a/contracts/cultmesh/authority-route-vectors.ts-signed.json b/contracts/cultmesh/authority-route-vectors.ts-signed.json new file mode 100644 index 00000000..726731ce --- /dev/null +++ b/contracts/cultmesh/authority-route-vectors.ts-signed.json @@ -0,0 +1,45 @@ +{ + "nowUnixMilliseconds": 1800000000000, + "odinRoot": { + "keyId": "odin-ts-vector", + "x": "lqw9TE0EyuDU5Ghe8SafIbBBYkhHMUF7HXJQUc0nXsw=", + "y": "nUj+Xhakih97JiJcTUNMHM9JIo7MVQaauuAkCXph+tw=" + }, + "route": { + "verseId": "aetheria", + "authorityRuntimeId": "aetheria-daemon", + "endpoint": "cultmesh-state+quic://provider.example:4433/?cert-sha256=ABCDEF", + "protocolIds": [ + "cultmesh.documents.v1", + "cultmesh.content.v1", + "cultmesh.realtime.v1" + ], + "priority": 13, + "generation": "ts-generation-ünïcode-∞-1", + "certificate": { + "providerKey": { + "keyId": "provider-ts-vector", + "x": "JKyjtWnoE5fhSWbeqr188SbReQWCjssf5mSMEa5pV+E=", + "y": "vtduzojDpbT49sbxBSsBQ+f3PG3rm+CUk/MTy2MM/ws=" + }, + "odinKeyId": "odin-ts-vector", + "issuedAtUnixMilliseconds": 1799999940000, + "expiresAtUnixMilliseconds": 1800003600000, + "signature": "NS5a7X8fNqTi1CdpPAcJaMmEsozwFRoygTW4z+JlhHFq7uaZcb4G7NwoEpPqo/Fv+UA7pNl5N+qUMuSD/oAq1Q==" + } + }, + "sessionProof": { + "request": { + "schemaVersion": "cultmesh.session_open.v2", + "messageId": "ts-vector-message-1", + "sourceRuntimeId": "ts-vector-consumer", + "verseId": "aetheria", + "authorityRuntimeId": "aetheria-daemon", + "protocolId": "cultmesh.documents.v1", + "routeGeneration": "ts-generation-ünïcode-∞-1", + "clientNonce": "HICtAmV++1MarssY04Tkyn1j9qVEcOMp/P5Ce1M0Yec=" + }, + "providerKeyId": "provider-ts-vector", + "providerSignature": "OgJHkmw3fhPRS5TXxZm94yZvkWAV5TPDuvG+/zIVlnU7OFENZ0Nn0Pdx0IT/vDfEWXD+8/+sCZVFIFwa4tUjsg==" + } +} diff --git a/packages/cultnet-ts/test/cultmesh-authority.test.ts b/packages/cultnet-ts/test/cultmesh-authority.test.ts index 03a9b9f0..5cd47245 100644 --- a/packages/cultnet-ts/test/cultmesh-authority.test.ts +++ b/packages/cultnet-ts/test/cultmesh-authority.test.ts @@ -30,7 +30,13 @@ import { } from "../src/cultmesh-authority"; const NOW = 1_800_000_000_000; -const VECTORS_PATH = join(__dirname, "..", "..", "..", "..", "contracts", "cultmesh", "authority-route-vectors.json"); +const CONTRACTS = join(__dirname, "..", "..", "..", "..", "contracts", "cultmesh"); +// Written by the C# reference (`CultMeshAuthorityProofTests.AuthorityRouteVectorsAreSharedWithTypeScript`). +const VECTORS_PATH = join(CONTRACTS, "authority-route-vectors.json"); +// Written by `scripts/sign-cultmesh-authority-vectors.mjs` and verified by the +// C# reference; checked here too so a transcript change on this side cannot +// leave a stale TypeScript-signed file behind for C# to trust. +const TS_SIGNED_VECTORS_PATH = join(CONTRACTS, "authority-route-vectors.ts-signed.json"); interface Vectors { nowUnixMilliseconds: number; @@ -305,8 +311,8 @@ test("base64 helpers round-trip across the 32 KiB chunk boundary", () => { assert.deepEqual(base64ToBytes(bytesToBase64(bytes)), bytes); }); -test("the C# reference vectors verify through the shared module", async () => { - const vectors = JSON.parse(readFileSync(VECTORS_PATH, "utf8")) as Vectors; +for (const [label, path] of [["C# reference", VECTORS_PATH], ["TypeScript-signed", TS_SIGNED_VECTORS_PATH]] as const) test(`the ${label} vectors verify through the shared module`, async () => { + const vectors = JSON.parse(readFileSync(path, "utf8")) as Vectors; const trust = { mode: "authenticated-remote" as const, odinRoots: [vectors.odinRoot], now: () => vectors.nowUnixMilliseconds }; await verifyAuthorityRoute(vectors.route, trust); await assert.rejects(verifyAuthorityRoute({ ...vectors.route, priority: 8 }, trust), /signature is invalid/); diff --git a/scripts/sign-cultmesh-authority-vectors.mjs b/scripts/sign-cultmesh-authority-vectors.mjs new file mode 100644 index 00000000..dd68e2b2 --- /dev/null +++ b/scripts/sign-cultmesh-authority-vectors.mjs @@ -0,0 +1,109 @@ +// The TypeScript -> C# direction of the CultMesh authority parity check. +// +// `contracts/cultmesh/authority-route-vectors.json` is written by the C# +// reference and verified by TypeScript. This script writes the mirror file, +// `contracts/cultmesh/authority-route-vectors.ts-signed.json`: TypeScript +// builds the route and session transcripts with the shared module +// (`packages/cultnet-ts/src/cultmesh-authority.ts`), signs them with fixed +// TypeScript-owned test keys, and the C# test +// `CultMeshAuthorityProofTests.AuthorityRouteVectorsSignedByTypeScriptVerifyHere` +// verifies the committed file with the reference implementation only. +// +// The inputs are deliberately awkward: a quic scheme with a query, three +// unsorted protocol ids, non-ASCII generation text, a non-default priority. +// +// npm run build --workspace packages/cultnet-ts +// node scripts/sign-cultmesh-authority-vectors.mjs +// +// Rewrite the file only when the transcript rules change; ECDSA signatures are +// randomised, so every run produces a different byte-for-byte file. The keys +// sign only this vector and prove nothing else. + +import { createHash, createPrivateKey, sign } from "node:crypto"; +import { existsSync, writeFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const modulePath = join(repoRoot, "packages", "cultnet-ts", "dist", "cultmesh-authority.js"); +const outputPath = join(repoRoot, "contracts", "cultmesh", "authority-route-vectors.ts-signed.json"); +if (!existsSync(modulePath)) { + throw new Error(`${modulePath} is missing; run 'npm run build --workspace packages/cultnet-ts' first.`); +} +const { canonicalRoute, canonicalSession, verifyAuthorityRoute, verifyProviderSessionProof } = + createRequire(import.meta.url)(modulePath); + +const NOW = 1_800_000_000_000; +const odin = testKey("odin-ts-vector", { + kty: "EC", crv: "P-256", + x: "lqw9TE0EyuDU5Ghe8SafIbBBYkhHMUF7HXJQUc0nXsw", + y: "nUj-Xhakih97JiJcTUNMHM9JIo7MVQaauuAkCXph-tw", + d: "8X45DCbNJ7IR2iPoz5JUC_zB8fHh3zoUJUaAA7mnOnQ", +}); +const provider = testKey("provider-ts-vector", { + kty: "EC", crv: "P-256", + x: "JKyjtWnoE5fhSWbeqr188SbReQWCjssf5mSMEa5pV-E", + y: "vtduzojDpbT49sbxBSsBQ-f3PG3rm-CUk_MTy2MM_ws", + d: "ZSdIb9sLpAfb-nTAUR1Y1re4OsVM4ABJ1Gpq5pStSyQ", +}); + +function testKey(keyId, jwk) { + return { + privateKey: createPrivateKey({ key: jwk, format: "jwk" }), + publicKey: { + keyId, + x: Buffer.from(jwk.x, "base64url").toString("base64"), + y: Buffer.from(jwk.y, "base64url").toString("base64"), + }, + }; +} + +function signP1363(privateKey, payload) { + return sign("sha256", payload, { key: privateKey, dsaEncoding: "ieee-p1363" }).toString("base64"); +} + +const unsigned = { + verseId: "aetheria", + authorityRuntimeId: "aetheria-daemon", + endpoint: "cultmesh-state+quic://provider.example:4433/?cert-sha256=ABCDEF", + protocolIds: ["cultmesh.documents.v1", "cultmesh.content.v1", "cultmesh.realtime.v1"], + priority: 13, + generation: "ts-generation-ünïcode-∞-1", + certificate: { + providerKey: provider.publicKey, + odinKeyId: odin.publicKey.keyId, + issuedAtUnixMilliseconds: NOW - 60_000, + expiresAtUnixMilliseconds: NOW + 3_600_000, + signature: "", + }, +}; +const route = { + ...unsigned, + certificate: { ...unsigned.certificate, signature: signP1363(odin.privateKey, canonicalRoute(unsigned)) }, +}; +const request = { + schemaVersion: "cultmesh.session_open.v2", + messageId: "ts-vector-message-1", + sourceRuntimeId: "ts-vector-consumer", + verseId: "aetheria", + authorityRuntimeId: "aetheria-daemon", + protocolId: "cultmesh.documents.v1", + routeGeneration: route.generation, + clientNonce: createHash("sha256").update("ts-vector-nonce").digest("base64"), +}; +const providerSignature = signP1363(provider.privateKey, canonicalSession(request, route.endpoint)); + +// A file TypeScript cannot verify itself would make a C# refusal meaningless. +await verifyAuthorityRoute(route, { mode: "authenticated-remote", odinRoots: [odin.publicKey], now: () => NOW }); +if (!await verifyProviderSessionProof(request, route.endpoint, provider.publicKey, providerSignature)) { + throw new Error("The TypeScript module refused its own session proof."); +} + +writeFileSync(outputPath, JSON.stringify({ + nowUnixMilliseconds: NOW, + odinRoot: odin.publicKey, + route, + sessionProof: { request, providerKeyId: provider.publicKey.keyId, providerSignature }, +}, null, 2) + "\n"); +console.log(`wrote ${outputPath}`); diff --git a/tests/GameCult.Mesh.Tests/CultMeshAuthorityProofTests.cs b/tests/GameCult.Mesh.Tests/CultMeshAuthorityProofTests.cs index 44c078cc..f89cb40c 100644 --- a/tests/GameCult.Mesh.Tests/CultMeshAuthorityProofTests.cs +++ b/tests/GameCult.Mesh.Tests/CultMeshAuthorityProofTests.cs @@ -332,6 +332,84 @@ public sealed class CultMeshAuthorityProofTests CultMeshAuthorityProof.VerifySessionProof(request, accepted, verseId, route, trust, now).Should().BeTrue(); } + // The other direction. `scripts/sign-cultmesh-authority-vectors.mjs` builds + // the transcripts with the TypeScript module and signs them with + // TypeScript-owned keys over awkward inputs (a quic scheme, unsorted + // protocol ids, non-ASCII generation text, a non-default priority). Only + // the reference implementation judges the file here; the keys come from + // the file, never from this side. + [Test] + public void AuthorityRouteVectorsSignedByTypeScriptVerifyHere() + { + var path = Path.Combine(RepoRoot(), "contracts", "cultmesh", "authority-route-vectors.ts-signed.json"); + using var vectors = JsonDocument.Parse(File.ReadAllText(path)); + var rootElement = vectors.RootElement; + var routeElement = rootElement.GetProperty("route"); + var certificateElement = routeElement.GetProperty("certificate"); + var odinRoot = PublicKey(rootElement.GetProperty("odinRoot")); + var providerKey = PublicKey(certificateElement.GetProperty("providerKey")); + var certificate = new CultMeshRouteCertificate( + providerKey, + certificateElement.GetProperty("odinKeyId").GetString()!, + certificateElement.GetProperty("issuedAtUnixMilliseconds").GetInt64(), + certificateElement.GetProperty("expiresAtUnixMilliseconds").GetInt64(), + certificateElement.GetProperty("signature").GetString()!); + var protocolIds = routeElement.GetProperty("protocolIds").EnumerateArray().Select(value => value.GetString()!).ToArray(); + var priority = routeElement.GetProperty("priority").GetInt32(); + CultMeshAuthorityRoute Route(int routePriority) => new( + routeElement.GetProperty("authorityRuntimeId").GetString()!, + routeElement.GetProperty("endpoint").GetString()!, + protocolIds, + routePriority, + routeElement.GetProperty("generation").GetString(), + certificate); + var route = Route(priority); + var trust = new CultMeshAuthorityTrustPolicy(CultMeshAuthorityTrustMode.AuthenticatedRemote, new[] { odinRoot }); + var now = DateTimeOffset.FromUnixTimeMilliseconds(rootElement.GetProperty("nowUnixMilliseconds").GetInt64()); + var verseId = routeElement.GetProperty("verseId").GetString()!; + + protocolIds.Should().NotBeInAscendingOrder(StringComparer.Ordinal, "the vector must exercise the sort"); + trust.Validate(verseId, route, now); + Action tampered = () => trust.Validate(verseId, Route(priority + 1), now); + tampered.Should().Throw() + .Which.Failure.Message.Should().Be("The Odin route certificate signature is invalid."); + + var proofElement = rootElement.GetProperty("sessionProof"); + var requestElement = proofElement.GetProperty("request"); + var request = new GameCult.Networking.CultMeshSessionOpenMessage + { + MessageId = requestElement.GetProperty("messageId").GetString(), + SourceRuntimeId = requestElement.GetProperty("sourceRuntimeId").GetString(), + VerseId = requestElement.GetProperty("verseId").GetString(), + AuthorityRuntimeId = requestElement.GetProperty("authorityRuntimeId").GetString(), + ProtocolId = requestElement.GetProperty("protocolId").GetString(), + RouteGeneration = requestElement.GetProperty("routeGeneration").GetString(), + ClientNonce = requestElement.GetProperty("clientNonce").GetString() + }; + var accepted = Accepted(request, proofElement.GetProperty("providerSignature").GetString()!); + accepted.ProviderKeyId = proofElement.GetProperty("providerKeyId").GetString()!; + CultMeshAuthorityProof.VerifySessionProof(request, accepted, verseId, route, trust, now).Should().BeTrue(); + + var replayed = new GameCult.Networking.CultMeshSessionOpenMessage + { + MessageId = request.MessageId, + SourceRuntimeId = request.SourceRuntimeId, + VerseId = request.VerseId, + AuthorityRuntimeId = request.AuthorityRuntimeId, + ProtocolId = request.ProtocolId, + RouteGeneration = request.RouteGeneration, + ClientNonce = "replayed" + }; + var replayedAccepted = Accepted(replayed, accepted.ProviderSignature!); + replayedAccepted.ProviderKeyId = accepted.ProviderKeyId; + CultMeshAuthorityProof.VerifySessionProof(replayed, replayedAccepted, verseId, route, trust, now).Should().BeFalse(); + } + + private static CultMeshEcdsaP256PublicKey PublicKey(JsonElement element) => new( + element.GetProperty("keyId").GetString()!, + element.GetProperty("x").GetString()!, + element.GetProperty("y").GetString()!); + private static string RepoRoot() { var directory = new DirectoryInfo(TestContext.CurrentContext.TestDirectory);