// Check a GuardHelm receipt WITHOUT TRUSTING GUARDHELM. This file is the verification recipe in // executable form; docs/verifying-a-receipt.md is the same procedure in prose. // // pnpm verify:receipt -- --bundle ./receipt.json --jwks ./jwks.json # fully offline // pnpm verify:receipt -- --self-test // pnpm verify:receipt -- --release ./release.json --jwks ./jwks.json # a client release, offline // pnpm verify:receipt -- --share "https://console.example.com/shared-receipt?token=..." // // `--bundle` comes first because `--share` puts the link, a bearer that opens the receipt for 45 // days, into your shell history. Save the receipt file from its page and check that instead. // // Outside this repository, with no pnpm and no install: `node --experimental-strip-types // verify-receipt.ts --self-test` on Node 22.6+ (where --experimental-strip-types arrived). No npm packages. // The optional independent timestamp check uses OpenSSL's `ts` command and separately trusted CAs. // // THIS FILE IMPORTS NOTHING FROM THIS REPOSITORY, and that is the single most important thing about // it. A verifier that called GuardHelm's own evidence package would prove only that GuardHelm // agrees with itself: change the canonicalization and both sides move together, and the check stays // green through the defect. The receipt signature recipe is re-implemented from the specifications // (RFC 8785, RFC 7515/7517/7518) using Node built-ins, so this file and // `packages/evidence/src/canonical.ts` are two independent statements of one protocol that must // agree. `test/verify-receipt.test.ts` asserts they do, and pins both against a FROZEN VECTOR whose // bytes and signature are hard-coded below — the reference neither implementation can move. // // A third party can therefore copy this one file out of the repository, run it against a share link // they were sent, and satisfy themselves. Nothing here needs an account, a credential, or us. // // EXIT CODES, and they are not interchangeable: // 0 the signature verified and the signed bytes are in canonical form // 1 the signature did not verify, or supplied timestamp evidence does not verify // 2 could not complete (e.g. a missing key, local TSA trust file or OpenSSL executable) // 3 the signature verified but the signed bytes are NOT canonical — a defect in GuardHelm's // serialization, not in the receipt. Authenticity holds; independent reconstruction does not // // Codes 1 and 2 are separated because "this receipt is forged" and "I could not reach the key // endpoint" are different sentences and only one of them is ever true. A verifier that conflates // them accuses a company of fabricating evidence because of a proxy timeout. // DO NOT WRITE THE EVIDENCE PACKAGE'S IMPORT SPECIFIER ANYWHERE IN THIS FILE, not even in a comment. // `test/reachability.test.ts` builds its "is this export reached?" corpus from files whose TEXT // contains that specifier, so a mention here — with no import behind it — silently enrols this file // as a caller. It exports its own `receiptSigningBytes`, which is on that gate's UNREACHED list, so // one word of prose turned a real allowlist entry into a false "now reached" failure. Say // "packages/evidence/src/canonical.ts" instead; it is more precise anyway. import { spawnSync } from "node:child_process"; import { createHash, createHmac, X509Certificate } from "node:crypto"; import { mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; /** The domain tag that prefixes the signed bytes. Part of the signature, not decoration: a * signature over a receipt can never be replayed as a signature over an event envelope. */ export const RECEIPT_DOMAIN = "guardhelm.receipt.v1"; /** Where GuardHelm publishes its public keys. Under `/v1/` because that is the only path prefix the * Worker is routed; `/.well-known/jwks.json` is served as an alias to the identical document. */ export const DEFAULT_JWKS_PATH = "/v1/verification-keys/jwks.json"; /** The API leg a share token resolves against. A share link a supervisor sends points at the * console path `/shared-receipt`, which fetches this one same-origin. */ export const SHARED_RECEIPT_PATH = "/v1/shared-receipts"; /** GuardHelm's published key set, for `--jwks` beside a saved receipt. */ export const PUBLISHED_JWKS = "https://api.guardhelm.com/v1/verification-keys/jwks.json"; /* ------------------------------------------------------------------ RFC 8785 canonical JSON */ /** * Canonical JSON, re-implemented from RFC 8785 (JCS) with the SAME TWO NARROWINGS GuardHelm applies. * Both are deliberate and both refuse inputs rather than accepting more: * * • Only finite SAFE INTEGERS are accepted. JCS's float rules are an ES6 double-formatting * contract and a cross-runtime footgun; a receipt carries no fractional number, and every * bigint-domain value (`ingest_ordinal`) travels as a decimal STRING. A number outside the safe * range is rejected rather than rounded, because 9007199254740992 and 9007199254740993 are the * same double and would canonicalize identically — one signature over two different facts. * • `undefined` is REJECTED, never skipped. Skipping would make `{b:1}` and `{a:undefined,b:1}` * produce identical bytes: two inputs, one signature, which is a collision. * * Key ordering is UTF-16 code unit, which is what JCS specifies and what a bare `Array#sort()` on * strings does. Serialization is manual because `JSON.stringify` re-enumerates integer-like keys in * numeric order and would silently discard that ordering. */ export function canonicalJson(value: unknown): string { if (value === null) return "null"; if (typeof value === "boolean") return value ? "true" : "false"; if (typeof value === "string") return quoteJson(value); if (typeof value === "number") { if (!Number.isSafeInteger(value)) { throw new TypeError( `canonicalJson: only safe integers are allowed (got ${value}); bigint-domain values must ` + "travel as decimal strings", ); } return String(value); } if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`; if (typeof value === "object") { const proto = Object.getPrototypeOf(value) as unknown; if (proto !== Object.prototype && proto !== null) { throw new TypeError("canonicalJson: only plain objects are allowed"); } const entries = Object.keys(value as Record).sort(); const o = value as Record; return `{${entries.map((k) => `${quoteJson(k)}:${canonicalJson(o[k])}`).join(",")}}`; } if (value === undefined) { throw new TypeError("canonicalJson: undefined is not representable (it would collide with an absent key)"); } throw new TypeError(`canonicalJson: unsupported type ${typeof value}`); } /** * JSON string escaping with unpaired surrogates REFUSED. * * JCS requires valid Unicode. `JSON.stringify` since ES2019 emits an escaped lone surrogate rather * than failing, so a malformed string would canonicalize to something that looks fine and hashes * differently on a runtime that normalises. Checking first turns that into an error. */ function quoteJson(s: string): string { for (let i = 0; i < s.length; i++) { const c = s.charCodeAt(i); if (c >= 0xd800 && c <= 0xdbff) { const next = s.charCodeAt(i + 1); if (!(next >= 0xdc00 && next <= 0xdfff)) throw new TypeError("canonicalJson: unpaired high surrogate"); i++; } else if (c >= 0xdc00 && c <= 0xdfff) { throw new TypeError("canonicalJson: unpaired low surrogate"); } } return JSON.stringify(s); } /* ------------------------------------------------------------------------------- byte helpers */ /** * Standard base64, WITH INTERNAL WHITESPACE STRIPPED. * * Being lenient in a verifier is usually wrong, and this is the exception: MIME and PEM both wrap * base64 at 76 columns, and so does `psql`'s `encode(…, 'base64')`, so a signature that reached the * reader through an email, a PDF or a database export arrives with line breaks in it. Removing them * cannot change the decoded bytes and cannot admit a signature that would otherwise fail — it only * stops a correct receipt being reported as malformed input because of how it was transported. * Anything that is not base64 after that is still refused. */ export function fromBase64(text: string): Uint8Array { const clean = text.replace(/\s+/g, ""); if (!/^[A-Za-z0-9+/]*={0,2}$/.test(clean)) throw new TypeError("not base64"); return Uint8Array.from(Buffer.from(clean, "base64")); } /** RFC 7515 §2 base64url: no padding, `-`/`_` for `+`/`/`. JWK members `x` and `y` use it. */ export function fromBase64Url(text: string): Uint8Array { const clean = text.trim(); if (!/^[A-Za-z0-9_-]+$/.test(clean)) throw new TypeError("not base64url"); return Uint8Array.from(Buffer.from(clean.replace(/-/g, "+").replace(/_/g, "/"), "base64")); } const equalBytes = (a: Uint8Array, b: Uint8Array): boolean => a.length === b.length && a.every((v, i) => v === b[i]); /* ------------------------------------------------------------------------------- the recipe */ /** * STEP 2 OF THE RECIPE, and the whole reason a domain tag exists. * * The signed bytes are the UTF-8 encoding of the tag, ONE LINE FEED (0x0A, not CRLF), then the * canonical JSON exactly as it was stored — no re-indentation, no key re-ordering, no trailing * newline. One byte different is a different signature. */ export function receiptSigningBytes(canonical: string): Uint8Array { return new TextEncoder().encode(`${RECEIPT_DOMAIN}\n${canonical}`); } /** One published key, as `keys[]` / `revoked_keys[]` carry it. */ export interface PublishedJwk { kty?: unknown; crv?: unknown; x?: unknown; y?: unknown; kid?: unknown; alg?: unknown; guardhelm?: { purpose?: unknown; state?: unknown; retired_at?: unknown } | undefined; } /** * STEP 4: import the JWK and check the signature. * * The signature is 64-byte RAW r||s (RFC 7518 §3.4), which is what WebCrypto's ECDSA takes and what * `crypto.subtle.sign` produced. It is NOT ASN.1 DER — most command-line tooling (`openssl dgst * -verify`) expects DER, so a verifier who reaches for openssl gets a false negative unless they * re-encode first. The length check below turns that mistake into a sentence instead of a verdict. */ export async function verifyEs256( jwk: PublishedJwk, signature: Uint8Array, bytes: Uint8Array, ): Promise { if (signature.length !== 64) { throw new TypeError( `signature is ${signature.length} bytes; ES256 here is 64-byte raw r||s, not ASN.1 DER. ` + "If you decoded it from a DER blob, convert it first.", ); } if (jwk.kty !== "EC" || jwk.crv !== "P-256" || typeof jwk.x !== "string" || typeof jwk.y !== "string") { throw new TypeError("published key is not an EC P-256 public key"); } const key = await crypto.subtle.importKey( "jwk", { kty: "EC", crv: "P-256", x: jwk.x, y: jwk.y, ext: true }, { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"], ); return crypto.subtle.verify( { name: "ECDSA", hash: "SHA-256" }, key, signature as unknown as BufferSource, bytes as unknown as BufferSource, ); } /* -------------------------------------------------------------------------------- key lookup */ export interface KeySet { keys?: unknown; revoked_keys?: unknown; } export type KeyLookup = | { found: true; jwk: PublishedJwk } | { found: false; why: "empty" | "revoked" | "absent" | "wrong_purpose"; detail: string }; /** * STEP 3: find the key the receipt names. * * FOUR DIFFERENT FAILURES, four different sentences, because a verifier who collapses them reaches * the wrong conclusion in three of the four cases: * * empty GuardHelm publishes no keys at all. The fault is ours; the receipt is not * implicated and must not be reported as unverified. * revoked the key exists and is published, in `revoked_keys`. GuardHelm has withdrawn its * trust in that key's private half, so a signature under it proves nothing about * who made it — but the receipt is not a fabrication either, and saying "unknown * key" about a key that is right there in the document would be false. * absent no such kid. Either the receipt names a key that never existed, or your copy of * the key set predates the key. REFETCH PAST YOUR CACHE before concluding anything: * the document is served with `max-age=300`, and rotation publishes a new key the * instant it starts signing. * wrong_purpose the kid resolves to a key whose purpose is not `receipt`. Purpose separation is * the reason an event-signing key cannot mint a receipt; accepting one here would * hand back the property the schema exists to enforce. */ export function findReceiptKey(set: KeySet, kid: string): KeyLookup { return findKey(set, kid, "receipt"); } /** The same lookup for either purpose: a client release's envelope is checked against an * `event`-purpose key, the receipts inside it against `receipt`-purpose keys. */ export function findKey(set: KeySet, kid: string, wanted: "receipt" | "event"): KeyLookup { const live = Array.isArray(set.keys) ? (set.keys as PublishedJwk[]) : []; const revoked = Array.isArray(set.revoked_keys) ? (set.revoked_keys as PublishedJwk[]) : []; if (live.length === 0 && revoked.length === 0) { return { found: false, why: "empty", detail: "GuardHelm's published key set is empty, so no receipt can be checked against it. " + "That is a fault on GuardHelm's side and says nothing about this receipt.", }; } const hit = live.find((k) => k.kid === kid); if (hit !== undefined) { const purpose = hit.guardhelm?.purpose; if (purpose !== wanted) { return { found: false, why: "wrong_purpose", detail: `key ${kid} is published with purpose ${String(purpose)}, not "${wanted}". This ` + `signature must be checked against a ${wanted}-purpose key; anything else defeats the ` + "separation that stops one key signing two kinds of thing.", }; } return { found: true, jwk: hit }; } const dead = revoked.find((k) => k.kid === kid); if (dead !== undefined) { return { found: false, why: "revoked", detail: `key ${kid} is published as REVOKED (retired ${String(dead.guardhelm?.retired_at)}). ` + "GuardHelm no longer vouches for its private half, so a signature under it does not " + "establish who produced this signature. The record itself is not implicated.", }; } return { found: false, why: "absent", detail: `no key with kid ${kid} is published. If you are reading a cached copy of the key set, ` + "refetch it past your cache before concluding anything — a key that started signing in the " + "last few minutes may not be in an older copy.", }; } /* ------------------------------------------------------------------------------ input parsing */ export interface ServerReceipt { /** The exact canonical bytes GuardHelm signed, as a string. */ canonical: string; /** Standard base64 (padded) of the 64-byte raw r||s signature. */ signature: string; timestamp_anchor?: unknown; } /** * Pull `{canonical, signature}` out of whatever the user actually has. * * THREE ACCEPTED SHAPES, listed rather than sniffed, because a verifier tool that guesses at * structure is a verifier tool that one day verifies the wrong field: * 1. the whole `/v1/shared-receipts` response → `.receipt.server_receipt` * 2. a single receipt → `.server_receipt` * 3. the pair on its own → `{canonical, signature}` */ export function extractServerReceipt(doc: unknown): ServerReceipt { const nested = isObject(doc) ? doc.receipt : undefined; for (const [receipt, signed] of [ [nested, isObject(nested) ? nested.server_receipt : undefined], [doc, isObject(doc) ? doc.server_receipt : undefined], [doc, doc], ]) { if (isObject(receipt) && isObject(signed) && typeof signed.canonical === "string" && typeof signed.signature === "string") { return { canonical: signed.canonical, signature: signed.signature, ...(receipt.timestamp_anchor == null ? {} : { timestamp_anchor: receipt.timestamp_anchor }), }; } } throw new TypeError( "could not find a server receipt in that input. Expected one of: the whole " + "/v1/shared-receipts response, an object with a server_receipt member, or " + '{"canonical": "...", "signature": "..."} on its own.', ); } /** The `server_key_id` inside the signed bytes — the only place a verifier may read the kid from. */ export function receiptKeyId(canonical: string): string { let parsed: unknown; try { parsed = JSON.parse(canonical); } catch { throw new TypeError("the canonical receipt is not JSON"); } const kid = (parsed as Record | null)?.["server_key_id"]; if (typeof kid !== "string" || kid === "") throw new TypeError("the receipt names no server_key_id"); return kid; } /* ------------------------------------------------------------------------------ frozen vector */ /** * A RECEIPT, A KEY AND A SIGNATURE THAT MUST ALWAYS VERIFY. Generated once, pasted here, never * regenerated. * * This is the fixed point the rest of the check hangs from. Every other assertion in this lane * compares one piece of GuardHelm to another piece of GuardHelm, and this project has already paid * for what that is worth: a margin test that compared a value against the constant it was built * from stayed green while the constant was zeroed. These bytes cannot move. If a future edit to * `canonicalJson`, to the domain tag, to the signature encoding, or to the JWK import changes ANY * of them, `--self-test` fails — including the case where this file and * `packages/evidence/src/canonical.ts` are changed together and still agree with each other. * * The private half was never written down. It existed inside one `node` process, signed these * bytes, and was discarded; there is nothing here to keep secret and nothing to rotate. * * A third party should run `--self-test` FIRST. It proves the verifier on their machine works * before they point it at a receipt whose result they care about — so a red result later means the * receipt, not the tool. */ export const FROZEN_VECTOR = { canonical: '{"accepted_at":"2026-03-14T09:26:53.589Z","event_hash":"5d41402abc4b2a76b9719d911017c592a1b2' + 'c3d4e5f60718293a4b5c6d7e8f90","event_id":"01936f2a-7c58-7a1b-9e44-2d8c0f5b3a97","ingest_ord' + 'inal":"41","schema_version":1,"server_key_id":"9f2c1e6a-4b70-4d18-9a3e-1c5f80b2d743","tenan' + 't_id":"3a7d5c92-8e41-4b6f-90ad-6f2b1c4e8d05"}', signature: "gOKlzY8pNJiABhYqdN9nLUdPCV4bm++ZdtPFvv8wJyheCvNHXmsbvSDKZNE1Q7rsuDrYOO+Uhy9fgE/gTFF5nw==", jwks: { keys: [{ kty: "EC", crv: "P-256", x: "AlFo0yCTqgyCfVldRTAc6FGZFGhPkYX4wS_ylDRP3-o", y: "kTp63Ue6qt0anK-C9uECPyBFeU1t5imscM7CF4Lm77I", kid: "9f2c1e6a-4b70-4d18-9a3e-1c5f80b2d743", use: "sig", alg: "ES256", guardhelm: { purpose: "receipt", state: "active", created_at: "2026-03-14T09:00:00.000Z", retired_at: null, }, }], revoked_keys: [], }, } as const; /* --------------------------------------------------------------------------------- the check */ export interface Outcome { /** Did the signature check out against the published key? */ signatureValid: boolean; /** Were the signed bytes in canonical form, so anyone can reconstruct them from the fields? */ canonicalFormValid: boolean; /** False when the check could not be run at all. Never confuse this with `signatureValid:false`. */ complete: boolean; lines: string[]; exitCode: 0 | 1 | 2 | 3; } const failed = (lines: string[], why: string): Outcome => ({ signatureValid: false, canonicalFormValid: false, complete: false, lines: [...lines, `COULD NOT COMPLETE ${why}`, "This says nothing about the receipt. It means the check did not run."], exitCode: 2, }); // Independent, authority-specific pins, not a system CA bundle chosen by the response. const TSA_PINS: Readonly> = { FreeTSA: { ca: "a6379e7cecc05faa3cbf076013d745e327bbbaa38c0b9af22469d4701d18aabc", signer: "32e841a95cc1164101ffde41298ef2fc75c1c4372ef095e88a6bbd47dfb191fc", }, Sigstore: { ca: "2aca8fea5d3ce48b01cc77076293c280e6c23ffe44034757ee7833ca9f45d633", signer: "85f927bc07ab62cac3b44356c10efc81b2c6883fda7ab9e6d870d9d13acd05b7", }, }; const TSA_COUNT = Object.keys(TSA_PINS).length; const fingerprint = (cert: X509Certificate): string => cert.fingerprint256.replaceAll(":", "").toLowerCase(); class InvalidTimestamp extends Error {} function openssl(args: string[]): string { const run = spawnSync("openssl", args, { encoding: "utf8", timeout: 10_000, maxBuffer: 128 * 1024 }); if (run.error || run.signal || (run.status !== 0 && /invalid command|unknown option|unrecognized flag/i.test(run.stderr))) { throw new Error("OpenSSL could not run. Put openssl with ts and cms support on PATH."); } if (run.status !== 0) throw new InvalidTimestamp("OpenSSL did not verify the timestamp response."); return run.stdout; } function timestampEvidence(canonical: string, signature: Uint8Array, proof: unknown, trustDir?: string): string[] { const hex = /^[0-9a-f]{64}$/; if (!isObject(proof) || typeof proof.root !== "string" || !hex.test(proof.root) || !Array.isArray(proof.path) || proof.path.length > 12 // At most 4,096 receipts per tree. || !Array.isArray(proof.tokens) || proof.tokens.length > TSA_COUNT) { throw new InvalidTimestamp("Malformed timestamp proof."); } let node = createHash("sha256").update(Buffer.from([0])).update(receiptSigningBytes(canonical)).update(signature).digest(); for (const step of proof.path) { if (!isObject(step) || (step.side !== "left" && step.side !== "right") || typeof step.hash !== "string" || !hex.test(step.hash)) throw new InvalidTimestamp("Malformed inclusion path."); const sibling = Buffer.from(step.hash, "hex"); const parent = createHash("sha256").update(Buffer.from([1])); node = (step.side === "left" ? parent.update(sibling).update(node) : parent.update(node).update(sibling)).digest(); } const root = Buffer.from(node.buffer, node.byteOffset, node.byteLength).toString("hex"); if (root !== proof.root) throw new InvalidTimestamp("The receipt does not lead to the supplied batch root."); const lines = [`5 inclusion MATCHES ${root}`]; if (!proof.tokens.length) return [...lines, "No authority response supplied. No independent witness is established."]; const seen = new Set(); const dir = mkdtempSync(join(tmpdir(), "receipt-timestamp-")); try { for (const token of proof.tokens) { if (!isObject(token) || typeof token.authority !== "string" || !Object.hasOwn(TSA_PINS, token.authority) || seen.has(token.authority) || typeof token.time !== "string" || typeof token.response_base64 !== "string" || token.response_base64.length > 4 * Math.ceil(32 * 1024 / 3)) throw new InvalidTimestamp("Malformed or duplicate authority response."); seen.add(token.authority); const response = Buffer.from(token.response_base64, "base64"); if (response.length > 32 * 1024 || response.toString("base64") !== token.response_base64 || !isOneDerSequence(response)) throw new InvalidTimestamp("Not a single DER timestamp response in standard base64."); if (!trustDir) throw new Error(`Supply --tsa-trust with an independently trusted ${token.authority} CA.`); const cert = new X509Certificate(readFileSync(join(trustDir, `${token.authority.toLowerCase()}.pem`))); const pins = TSA_PINS[token.authority]!; if (fingerprint(cert) !== pins.ca) { throw new InvalidTimestamp(`The local CA does not match ${token.authority}'s timestamp CA.`); } // Write only the pinned CA, never a second certificate appended to the same PEM file. const ca = join(dir, "ca.pem"), tsr = join(dir, "response.tsr"); writeFileSync(ca, cert.toString()); writeFileSync(tsr, response); // -token_out -text renders TSTInfo only, excluding the unsigned PKIStatusInfo free text. const info = openssl(["ts", "-reply", "-token_out", "-text", "-in", tsr]); const utc = /^Time stamp: (.+ GMT)\r?$/m.exec(info)?.[1]; const epoch = utc ? Date.parse(utc) : NaN; if (/^Hash Algorithm: ([^\r\n]+)\r?$/m.exec(info)?.[1] !== "sha256" || !Number.isFinite(epoch) || new Date(epoch).toISOString() !== token.time) throw new InvalidTimestamp("The imprint algorithm or timestamp does not match."); openssl(["ts", "-verify", "-digest", root, "-in", tsr, "-CAfile", ca, "-attime", String(Math.floor(epoch / 1000))]); // ts checked the chain and purpose. Identify the actual CMS signer (not an arbitrary extra // certificate attached to the response) before attributing a time to today's pinned service. const cms = join(dir, "token.der"), signer = join(dir, "signer.pem"); openssl(["ts", "-reply", "-in", tsr, "-token_out", "-out", cms]); openssl(["cms", "-verify", "-noverify", "-binary", "-inform", "DER", "-in", cms, "-signer", signer]); if (fingerprint(new X509Certificate(readFileSync(signer))) !== pins.signer) { throw new InvalidTimestamp(`The signer does not match ${token.authority}'s timestamp certificate.`); } lines.push(`${token.authority}: signed receipt existed by ${new Date(epoch).toISOString()} (authority's stated UTC time)`); } return [...lines, `${seen.size} of ${TSA_COUNT} configured timestamp authorities verified.`]; } finally { rmSync(dir, { recursive: true, force: true }); } } /** OpenSSL consumes the first DER object from a file. Reject a truncated or padded response. */ function isOneDerSequence(bytes: Buffer): boolean { if (bytes.length < 2 || bytes[0] !== 0x30) return false; const tag = bytes[1]!; if (tag < 128) return tag === bytes.length - 2; const octets = tag - 128; if (octets < 1 || octets > 2 || bytes.length < 2 + octets || bytes[2] === 0) return false; const length = octets === 1 ? bytes[2]! : bytes[2]! * 256 + bytes[3]!; return length >= 128 && length === bytes.length - 2 - octets; } /** * Run the four steps against one receipt and one key set, printing each as it goes. * * Takes the documents themselves rather than URLs, so the whole procedure is testable and runnable * with no network at all — which is what a court's expert working from an archive needs. */ export async function verifyReceiptDocument( receipt: ServerReceipt, keySet: KeySet, trustDir?: string, ): Promise { const lines: string[] = []; // 1. The bytes, as served. lines.push(`1 canonical receipt ${receipt.canonical.length} bytes`); // 2. Re-canonicalize and compare. A mismatch does NOT invalidate the signature — the signature is // over the bytes as served — but it does break the claim that anyone can rebuild those bytes // from the receipt's fields, which is what makes the receipt independently checkable at all. let canonicalFormValid = false; let kid: string; try { const reserialized = canonicalJson(JSON.parse(receipt.canonical)); canonicalFormValid = reserialized === receipt.canonical; kid = receiptKeyId(receipt.canonical); lines.push(canonicalFormValid ? "2 canonical form OK — re-serializing the parsed receipt reproduces these exact bytes" : "2 canonical form MISMATCH — re-serializing the parsed receipt produces DIFFERENT " + "bytes. The signature below is still over the bytes as served, but they are not in " + "canonical form, so a verifier who rebuilds them from the fields will disagree."); } catch (e) { return failed(lines, `the canonical receipt could not be read: ${(e as Error).message}`); } // 3. Resolve the key the receipt names — never a key chosen any other way. const lookup = findReceiptKey(keySet, kid); if (!lookup.found) { if (lookup.why === "revoked") { return { signatureValid: false, canonicalFormValid, complete: true, lines: [...lines, `3 signing key ${kid}`, ` ${lookup.detail}`, "NOT VERIFIED the signature cannot establish authorship under a revoked key."], exitCode: 1, }; } return failed(lines, lookup.detail); } lines.push(`3 signing key ${kid} (purpose receipt, state ${String(lookup.jwk.guardhelm?.state)})`); // 4. Verify. let signatureValid: boolean; let signature: Uint8Array; try { signature = fromBase64(receipt.signature); signatureValid = await verifyEs256( lookup.jwk, signature, receiptSigningBytes(receipt.canonical), ); } catch (e) { return failed(lines, (e as Error).message); } lines.push(signatureValid ? `4 ES256 signature VALID over "${RECEIPT_DOMAIN}\\n" + the canonical bytes` : "4 ES256 signature INVALID — these bytes were not signed by that key"); if (!signatureValid) { lines.push("NOT VERIFIED GuardHelm's receipt-purpose key did not sign these bytes."); return { signatureValid, canonicalFormValid, complete: true, lines, exitCode: 1 }; } if (receipt.timestamp_anchor != null) { try { lines.push(...timestampEvidence(receipt.canonical, signature, receipt.timestamp_anchor, trustDir)); } catch (err) { const unavailable = !(err instanceof InvalidTimestamp); lines.push(`${unavailable ? "TIMESTAMP CHECK INCOMPLETE" : "TIMESTAMP NOT VERIFIED"} ${(err as Error).message}`, "The GuardHelm signature holds. No independent witness is established by this check."); return { signatureValid, canonicalFormValid, lines, complete: !unavailable, exitCode: unavailable ? 2 : 1 }; } } if (!canonicalFormValid) { lines.push( "VERIFIED WITH ONE DEFECT the signature is genuine, and the bytes it covers are not in", "canonical form. Authenticity holds. Independent reconstruction from the fields does not,", "and that is GuardHelm's defect to fix, not a problem with this record."); return { signatureValid, canonicalFormValid, complete: true, lines, exitCode: 3 }; } lines.push("VERIFIED GuardHelm's receipt-purpose key signed exactly these bytes."); return { signatureValid, canonicalFormValid, complete: true, lines, exitCode: 0 }; } /** The frozen vector, checked end to end with no network. Run this before you trust a red result. */ export async function selfTest(): Promise { return verifyReceiptDocument( { canonical: FROZEN_VECTOR.canonical, signature: FROZEN_VECTOR.signature }, FROZEN_VECTOR.jwks as unknown as KeySet, ); } /* ----------------------------------------------------------------------------- client releases */ /** The domain tag over an event envelope, the twin of `RECEIPT_DOMAIN`. */ export const EVENT_DOMAIN = "guardhelm.event.v1"; export const RELEASE_BUNDLE_FORMAT = "guardhelm.client_release_bundle.v1"; /** Known only once a release is signed, so the preview's content digest leaves them out. */ const RELEASE_ONLY_FIELDS = new Set(["reference", "released_at", "released_by_label"]); const isObject = (v: unknown): v is Record => v !== null && typeof v === "object" && !Array.isArray(v); const sha256Hex = (text: string): string => createHash("sha256").update(text, "utf8").digest("hex"); /** The human reference a release carries, from its own id. Restated from the issuing side. */ export const releaseReferenceOf = (releaseId: string): string => `CR-${releaseId.replace(/-/g, "").slice(0, 12).toUpperCase()}`; /** * Check one client release bundle against one key set, with no network and nothing from GuardHelm. * * FIVE CLAIMS, each checked rather than assumed: * 1. an `event`-purpose key signed the envelope (`EVENT_DOMAIN` + LF + the envelope bytes); * 2. the envelope is this release: kind `client_release`, server-signed, its own event id; * 3. the body is what was signed: HMAC-SHA256 under the bundled record key over the body's * canonical JSON equals the envelope's `body_commit`. This is the step that holds the prose, * which the database stores encrypted and this bundle carries restored; * 4. the document is the content its digest names, and carries its own reference and instant; * 5. every included receipt verifies under a `receipt`-purpose key, belongs to this tenant and to * the released records, and the document cites exactly those receipts. * * Exit codes as for a receipt: 1 when any claim is false, 2 when a key or the record key is missing * so the check could not run, 3 when the envelope verifies but is not in canonical form. */ export async function verifyReleaseBundle(bundle: unknown, keySet: KeySet): Promise { const lines: string[] = []; const no = (why: string): Outcome => ({ signatureValid: false, canonicalFormValid: false, complete: true, lines: [...lines, `NOT VERIFIED ${why}`], exitCode: 1, }); const b = isObject(bundle) ? bundle : {}; const { envelope, signature, signer_key_id: kid, release_id: releaseId, body_key: bodyKey } = b; const body = b.body; if (b.format !== RELEASE_BUNDLE_FORMAT || typeof envelope !== "string" || typeof signature !== "string" || typeof kid !== "string" || typeof releaseId !== "string" || !isObject(body) || !Array.isArray(b.receipts)) { return failed(lines, `that file is not a ${RELEASE_BUNDLE_FORMAT} bundle.`); } lines.push(`1 release ${releaseId}`); let meta: Record; let canonicalFormValid: boolean; try { const parsed: unknown = JSON.parse(envelope); if (!isObject(parsed)) throw new TypeError("the envelope is not a JSON object"); meta = parsed; canonicalFormValid = canonicalJson(meta) === envelope; } catch (e) { return failed(lines, `the envelope could not be read: ${(e as Error).message}`); } const key = findKey(keySet, kid, "event"); if (!key.found) { if (key.why === "revoked") return no(key.detail); return failed(lines, key.detail); } let valid: boolean; try { valid = await verifyEs256(key.jwk, fromBase64(signature), new TextEncoder().encode(`${EVENT_DOMAIN}\n${envelope}`)); } catch (e) { return failed(lines, (e as Error).message); } if (!valid) return no("GuardHelm's event-purpose key did not sign this envelope."); lines.push(`2 envelope signature VALID under event key ${kid}`); if (meta.kind !== "client_release" || meta.signer_kind !== "server" || meta.event_id !== releaseId) { return no("the signed envelope is not a server-signed client_release with this release's id."); } let recordKey: Uint8Array; try { recordKey = typeof bodyKey === "string" ? fromBase64(bodyKey) : new Uint8Array(0); } catch { recordKey = new Uint8Array(0); } if (recordKey.length !== 32) { return failed(lines, "the bundle carries no 32-byte record key, so the body commitment cannot be recomputed."); } const commit = createHmac("sha256", recordKey).update(canonicalJson(body), "utf8").digest("hex"); if (commit !== meta.body_commit) { return no("the body is not the one that was signed: its HMAC under the record key differs from the envelope's body_commit."); } lines.push("3 body commitment MATCHES the envelope (prose included)"); const document = body.document; if (!isObject(document)) return no("the signed body carries no document."); const content = Object.fromEntries(Object.entries(document).filter(([k]) => !RELEASE_ONLY_FIELDS.has(k))); if (sha256Hex(canonicalJson(content)) !== body.content_digest) { return no("the document is not the content its content_digest names."); } if (document.reference !== releaseReferenceOf(releaseId) || document.released_at !== meta.captured_at) { return no("the document's reference or release instant is not this release's own."); } lines.push(`4 document ${String(document.reference)}, content digest matches`); const included = new Set(Array.isArray(body.included_event_ids) ? body.included_event_ids : []); const hashes = new Set(); for (const r of b.receipts as unknown[]) { if (!isObject(r) || typeof r.canonical !== "string" || typeof r.signature !== "string") { return no("an included receipt is malformed."); } let rkid: string; let parsed: Record; try { rkid = receiptKeyId(r.canonical); parsed = JSON.parse(r.canonical) as Record; } catch (e) { return no(`an included receipt could not be read: ${(e as Error).message}`); } const rkey = findReceiptKey(keySet, rkid); if (!rkey.found) { if (rkey.why === "revoked") return no(rkey.detail); return failed(lines, rkey.detail); } let ok: boolean; try { ok = await verifyEs256(rkey.jwk, fromBase64(r.signature), receiptSigningBytes(r.canonical)); } catch (e) { return failed(lines, (e as Error).message); } if (!ok) return no(`the receipt for event ${String(parsed.event_id)} does not verify.`); if (parsed.tenant_id !== meta.tenant_id || !included.has(parsed.event_id)) { return no(`the receipt for event ${String(parsed.event_id)} is not one of this release's records.`); } hashes.add(String(parsed.event_hash)); } const cited = Array.isArray(document.receipts) ? document.receipts.map((x) => (isObject(x) ? String(x.fingerprint) : "")) : []; if (cited.length !== hashes.size || !cited.every((h) => hashes.has(h))) { return no("the document's receipts are not exactly the receipts in this bundle."); } lines.push(`5 included receipts ${hashes.size} VALID, and exactly the ones the document cites`); if (!canonicalFormValid) { lines.push("VERIFIED WITH ONE DEFECT every signature holds, and the envelope bytes are not in canonical form."); return { signatureValid: true, canonicalFormValid, complete: true, lines, exitCode: 3 }; } lines.push( "VERIFIED GuardHelm signed this release, its document is the body that was signed, and every", "record it cites carries a valid receipt. This release check does not verify independent timestamps."); return { signatureValid: true, canonicalFormValid, complete: true, lines, exitCode: 0 }; } /* ------------------------------------------------------------------------------------ fetching */ /** * A share link, as a supervisor sends it, reduced to the two URLs this script needs. * * Accepts BOTH the console address (`/shared-receipt?token=…`, which renders a page) and the API * address (`/v1/shared-receipts?token=…`, which returns the JSON). A person pasting whichever one * they happen to have should not have to know the difference. */ export function resolveShareUrls(shareUrl: string, jwksOverride?: string): { receiptUrl: string; jwksUrl: string; } { const url = new URL(shareUrl); const token = url.searchParams.get("token"); if (token === null || token === "") { throw new TypeError("that share link carries no ?token= — copy the whole link, including the query string"); } const receipt = new URL(SHARED_RECEIPT_PATH, url.origin); receipt.searchParams.set("token", token); return { receiptUrl: receipt.toString(), jwksUrl: jwksOverride ?? new URL(DEFAULT_JWKS_PATH, url.origin).toString(), }; } /** `--jwks` may be a URL or a path on disk, so an air-gapped verifier is a first-class case. */ async function loadJson(where: string): Promise { if (/^https?:\/\//i.test(where)) { // `cache: "no-store"` because a stale key set is the one cache miss that produces a WRONG // conclusion rather than a slow one: the document is served with max-age=300 and a key that // began signing a minute ago will not be in an older copy. const res = await fetch(where, { cache: "no-store", headers: { accept: "application/jwk-set+json, application/json" } }); if (!res.ok) throw new TypeError(`${where} answered HTTP ${res.status}`); const text = await res.text(); try { return JSON.parse(text); } catch { // The exact failure the `.well-known` wrangler note exists to prevent, named where somebody // will actually hit it. throw new TypeError( `${where} did not return JSON (content-type ${res.headers.get("content-type") ?? "none"}). ` + "If it returned HTML with status 200, you reached a web app's catch-all page rather than " + "the API.", ); } } return JSON.parse(readFileSync(where, "utf8")); } /* ---------------------------------------------------------------------------------------- CLI */ const USAGE = `Check a GuardHelm receipt against GuardHelm's published public keys. --bundle --jwks a saved receipt: the receipt page's file, the /v1/shared-receipts response, or {canonical,signature}. Keys: ${PUBLISHED_JWKS} --self-test verify the frozen vector built into this file. No network. --release a client release bundle: its signature, its body, and every receipt it cites --share a share link (console or API form). Fetches the receipt and the keys. The link opens the receipt for 45 days and stays in your shell history; prefer --bundle. --jwks where the public keys come from (with --share, default: the link's origin) --tsa-trust independently trusted TSA certificates for a receipt with timestamps Exit: 0 verified · 1 signature or supplied timestamp NOT verified · 2 could not complete · 3 verified, bytes not canonical `; export async function main(argv: readonly string[]): Promise { const arg = (name: string): string | undefined => { const i = argv.indexOf(name); return i === -1 ? undefined : argv[i + 1]; }; if (argv.includes("--self-test")) return selfTest(); const share = arg("--share"); const bundle = arg("--bundle"); const release = arg("--release"); const jwksArg = arg("--jwks"); if (release !== undefined) { if (jwksArg === undefined) { return failed([], "--release needs --jwks: a saved release carries no address to fetch keys from."); } try { const doc: unknown = JSON.parse(readFileSync(release, "utf8")); // AWAITED, so a key set that throws (a JSON null) is caught here and exits 2, never 1. return await verifyReleaseBundle(doc, await loadJson(jwksArg) as KeySet); } catch (e) { return failed([], (e as Error).message); } } if (share === undefined && bundle === undefined) { return failed([USAGE], "no receipt was named. Pass --bundle, --self-test, --release, or --share."); } try { let receiptDoc: unknown; let jwksWhere: string; if (share !== undefined) { const urls = resolveShareUrls(share, jwksArg); receiptDoc = await loadJson(urls.receiptUrl); jwksWhere = urls.jwksUrl; } else { receiptDoc = JSON.parse(readFileSync(bundle!, "utf8")); if (jwksArg === undefined) { return failed([], "--bundle needs --jwks: a saved receipt carries no address to fetch keys from."); } jwksWhere = jwksArg; } const receipt = extractServerReceipt(receiptDoc); const keySet = await loadJson(jwksWhere) as KeySet; return await verifyReceiptDocument(receipt, keySet, arg("--tsa-trust")); } catch (e) { return failed([], (e as Error).message); } } // Runs only when invoked directly, so `test/verify-receipt.test.ts` can import the functions above // without executing the CLI. // // BOTH SIDES ARE PUT THROUGH `realpathSync` FIRST, and the sibling scripts that skip that step are // wrong in a way that costs them nothing and would cost this file everything. `import.meta.url` is // what the ESM loader resolved, which means SYMLINKS ARE ALREADY FOLLOWED; `process.argv[1]` is the // string the user typed, which means they are not. On macOS `/tmp` is a symlink to `/private/tmp`, // so the invocation this file exists for — // // node --experimental-strip-types /tmp/verify-receipt.ts --self-test // // — made the two disagree, the CLI never ran, and the process exited 0 with NO OUTPUT AT ALL. // Exit 0 is this script's contract for VERIFIED. A third party checking the exit code (`verify… && // echo ok`, or any CI step) was therefore told a receipt verified when nothing had been read, let // alone checked. That is the worst answer a verification tool can give, and it was one keystroke // away: the same file run as `cd /tmp && node … verify-receipt.ts` works, because Node resolves a // relative argv[1] against an already-real `process.cwd()`. // // The `try` is not decoration either: `realpathSync` throws on a path that no longer exists, and a // throw here escapes before `main` and produces the same silent-ish failure by another route. const invokedDirectly = (): boolean => { const entry = process.argv[1]; if (entry === undefined) return false; try { return import.meta.url === pathToFileURL(realpathSync(entry)).href; } catch { return false; } }; if (invokedDirectly()) { const outcome = await main(process.argv.slice(2)); process.stdout.write(`${outcome.lines.join("\n")}\n`); process.exit(outcome.exitCode); }