@coreguard/agent-commerce 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/spend.mjs ADDED
@@ -0,0 +1,291 @@
1
+ /**
2
+ * CoreGuard Spend Ledger (CG-SPEND/1) — single-use, across processes and across
3
+ * parties that never share a database.
4
+ *
5
+ * "Single use" is not a boolean a verifier can read out of a receipt. A receipt
6
+ * that says `used: false` is a receipt from before it was used. The only way to
7
+ * know an approval has already been spent is to keep a record of the spending,
8
+ * and the only way that record survives a restart, a second worker, or a second
9
+ * system is for it to be append-only, signed, and readable by both sides.
10
+ *
11
+ * So the unit here is a spend ATTESTATION: "this approval, under this nonce, was
12
+ * spent for this order at this time, by this key". It is appended to a log and
13
+ * signed with the issuer's Ed25519 key, which gives three properties that a
14
+ * process-local Set cannot:
15
+ *
16
+ * - a second worker in the same machine sees it (file lock + append),
17
+ * - a second machine sees it once the log is exchanged or mirrored, and
18
+ * - two logs that DISAGREE are detectable: the same approval spent under two
19
+ * different nonces is a `conflict`, not a duplicate to be settled quietly.
20
+ *
21
+ * BOUNDARY (standing, load-bearing), stated here because it is the difference
22
+ * between a ledger and a fake:
23
+ * - The ledger is only as global as the logs the verifier can see. There is no
24
+ * world-wide register and this module does not pretend to be one: it
25
+ * guarantees single-use WITHIN every log supplied to `checkSpent`, and it
26
+ * makes disagreement between logs visible. A deployment that needs stronger
27
+ * freshness publishes the log head (the anchor module already produces a
28
+ * Merkle root) and refuses approvals whose head is older than its policy.
29
+ * - A verified spend entry proves an approval was recorded as spent. It proves
30
+ * nothing about delivery, amount or who the buyer was.
31
+ * - The file lock is an OS guarantee on one host; the signature is what
32
+ * carries across hosts. Neither replaces the other.
33
+ */
34
+
35
+ import { createHash } from "node:crypto";
36
+ import { closeSync, fsyncSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
37
+ import { createPrivateKey, createPublicKey, sign, verify } from "node:crypto";
38
+ import { keyIdFor } from "./anchor.mjs";
39
+
40
+ export const SPEND_VERSION = "CG-SPEND/1";
41
+ export const SPEND_SCHEMA = "coreguard.spend/1";
42
+ export const SPEND_STATES = Object.freeze(["unspent", "spent", "conflict", "busy", "unreadable"]);
43
+
44
+ function canonicalJson(value) {
45
+ if (value === null || typeof value !== "object") return JSON.stringify(value ?? null);
46
+ if (Array.isArray(value)) return "[" + value.map((v) => canonicalJson(v)).join(",") + "]";
47
+ const keys = Object.keys(value).sort();
48
+ return "{" + keys.map((k) => JSON.stringify(k) + ":" + canonicalJson(value[k])).join(",") + "}";
49
+ }
50
+
51
+ const sha256 = (s) => createHash("sha256").update(Buffer.from(s, "utf8")).digest("hex");
52
+ const isDigest = (v) => typeof v === "string" && /^sha256:[0-9a-f]{64}$/.test(v);
53
+
54
+ /**
55
+ * The spend key: one approval, one nonce, one identity. Committed inside the
56
+ * approval, so replaying the approval under a different nonce is not a second
57
+ * legitimate spend — it is a different key, and its presence in a log alongside
58
+ * the first is exactly the conflict this ledger reports.
59
+ */
60
+ export function spendKeyFor({ receiptDigest, approvalNonce } = {}) {
61
+ if (!isDigest(receiptDigest)) throw new TypeError("receiptDigest must be sha256:<64 hex>");
62
+ if (typeof approvalNonce !== "string" || approvalNonce.length === 0) throw new TypeError("approvalNonce must be a non-empty string");
63
+ return "sha256:" + sha256(canonicalJson({ receiptDigest, approvalNonce }));
64
+ }
65
+
66
+ export function createSpendLog({ path = null } = {}) {
67
+ return Object.freeze({ spendVersion: SPEND_VERSION, schema: SPEND_SCHEMA, path, entries: Object.freeze([]) });
68
+ }
69
+
70
+ function spendBody({ receiptDigest, approvalNonce, at, orderRef }) {
71
+ return {
72
+ spendVersion: SPEND_VERSION,
73
+ schema: SPEND_SCHEMA,
74
+ type: "spend",
75
+ receiptDigest,
76
+ approvalNonce,
77
+ spendKey: spendKeyFor({ receiptDigest, approvalNonce }),
78
+ at,
79
+ orderRef: typeof orderRef === "string" ? orderRef : null,
80
+ };
81
+ }
82
+
83
+ /** Pure: sign one spend attestation and return it. Nothing is written here. */
84
+ export function makeSpendEntry({ receiptDigest, approvalNonce, at, orderRef = null, privateKeyPem } = {}) {
85
+ if (!isDigest(receiptDigest)) throw new TypeError("receiptDigest must be sha256:<64 hex>");
86
+ if (typeof approvalNonce !== "string" || approvalNonce.length === 0) throw new TypeError("approvalNonce must be a non-empty string");
87
+ if (typeof at !== "string" || Number.isNaN(Date.parse(at))) throw new TypeError("at must be an ISO-8601 timestamp");
88
+ if (typeof privateKeyPem !== "string" || !privateKeyPem.includes("PRIVATE KEY")) throw new TypeError("privateKeyPem must be a PKCS#8 PEM string");
89
+ const publicKeyPem = createPublicKey(createPrivateKey(privateKeyPem)).export({ type: "spki", format: "pem" }).toString();
90
+ const body = { ...spendBody({ receiptDigest, approvalNonce, at, orderRef }), issuer: { keyId: keyIdFor(publicKeyPem), publicKeyPem } };
91
+ const signature = sign(null, Buffer.from(canonicalJson(body), "utf8"), privateKeyPem).toString("base64");
92
+ return Object.freeze({ ...body, signature });
93
+ }
94
+
95
+ /** One entry's own integrity: schema, keyId binding, Ed25519 signature. */
96
+ export function verifySpendEntry(entry) {
97
+ const checks = [];
98
+ if (!entry || typeof entry !== "object") return Object.freeze({ ok: false, checks: Object.freeze([{ name: "entry is an object", ok: false }]) });
99
+ checks.push({ name: "spend version is CG-SPEND/1", ok: entry.spendVersion === SPEND_VERSION });
100
+ checks.push({ name: "spend key recomputes", ok: entry.spendKey === (() => { try { return spendKeyFor(entry); } catch { return null; } })() });
101
+ const keyOk = entry?.issuer && typeof entry.issuer.publicKeyPem === "string";
102
+ checks.push({ name: "issuer carries a public key", ok: !!keyOk });
103
+ if (keyOk) checks.push({ name: "keyId matches the public key", ok: entry.issuer.keyId === keyIdFor(entry.issuer.publicKeyPem) });
104
+ const { signature, ...body } = entry;
105
+ let sigOk = false;
106
+ if (keyOk && typeof signature === "string") {
107
+ try {
108
+ sigOk = verify(null, Buffer.from(canonicalJson(body), "utf8"), entry.issuer.publicKeyPem, Buffer.from(signature, "base64"));
109
+ } catch {
110
+ sigOk = false;
111
+ }
112
+ }
113
+ checks.push({ name: "Ed25519 signature verifies over canonical JSON", ok: sigOk });
114
+ return Object.freeze({ ok: checks.every((c) => c.ok), checks: Object.freeze(checks) });
115
+ }
116
+
117
+ const entriesOf = (item) => {
118
+ if (!item || typeof item !== "object") return [];
119
+ if (Array.isArray(item)) return item.flatMap(entriesOf);
120
+ if (Array.isArray(item.entries)) return item.entries.flatMap(entriesOf);
121
+ return typeof item.spendKey === "string" ? [item] : [];
122
+ };
123
+
124
+ /**
125
+ * checkSpent(logs, { receiptDigest, approvalNonce })
126
+ *
127
+ * logs one log, an array of logs, or an array of entry arrays — the caller
128
+ * decides whose copies count as evidence.
129
+ *
130
+ * Returns `spent` when the same approval+nonce is recorded, `conflict` when the
131
+ * same approval is recorded under a DIFFERENT nonce (two systems both believe
132
+ * they were the first), `unspent` when no log mentions it, and `unreadable`
133
+ * when a supplied entry fails its own signature.
134
+ */
135
+ export function checkSpent(logs, { receiptDigest, approvalNonce } = {}) {
136
+ if (!isDigest(receiptDigest)) throw new TypeError("receiptDigest must be sha256:<64 hex>");
137
+ if (typeof approvalNonce !== "string" || approvalNonce.length === 0) throw new TypeError("approvalNonce must be a non-empty string");
138
+ const all = [];
139
+ const supplied = Array.isArray(logs) ? logs : [logs];
140
+ for (const l of supplied) for (const e of entriesOf(l)) all.push(e);
141
+
142
+ const invalid = all.filter((e) => !verifySpendEntry(e).ok);
143
+ if (invalid.length > 0) {
144
+ return Object.freeze({
145
+ state: "unreadable",
146
+ reason: `${invalid.length} entry/entries in the supplied log(s) fail their own signature`,
147
+ matches: invalid.length,
148
+ sources: supplied.length,
149
+ });
150
+ }
151
+ const sameApproval = all.filter((e) => e?.receiptDigest === receiptDigest);
152
+ const exact = sameApproval.filter((e) => e?.approvalNonce === approvalNonce);
153
+ const otherNonce = sameApproval.filter((e) => e?.approvalNonce !== approvalNonce);
154
+
155
+ if (exact.length > 0 && otherNonce.length > 0) {
156
+ return Object.freeze({ state: "conflict", reason: "the same approval appears under two different nonces", matches: sameApproval.length, sources: supplied.length, entries: Object.freeze(sameApproval) });
157
+ }
158
+ if (exact.length > 0) {
159
+ return Object.freeze({ state: "spent", reason: null, matches: exact.length, sources: supplied.length, entries: Object.freeze(exact) });
160
+ }
161
+ if (otherNonce.length > 0) {
162
+ return Object.freeze({ state: "conflict", reason: "this approval was already spent under a different nonce", matches: otherNonce.length, sources: supplied.length, entries: Object.freeze(otherNonce) });
163
+ }
164
+ return Object.freeze({ state: "unspent", reason: null, matches: 0, sources: supplied.length });
165
+ }
166
+
167
+ /** Read a JSON spend log from disk. A missing file is an empty log, not an error. */
168
+ export function readSpendLog(path) {
169
+ try {
170
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
171
+ const entries = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.entries) ? parsed.entries : [];
172
+ return Object.freeze({ spendVersion: SPEND_VERSION, schema: SPEND_SCHEMA, path, entries: Object.freeze(entries) });
173
+ } catch (err) {
174
+ if (err && err.code === "ENOENT") return createSpendLog({ path });
175
+ throw err;
176
+ }
177
+ }
178
+
179
+ function writeSpendLog(path, entries) {
180
+ const body = JSON.stringify({ spendVersion: SPEND_VERSION, schema: SPEND_SCHEMA, entries }, null, 2);
181
+ const tmp = `${path}.${process.pid}.tmp`;
182
+ writeFileSync(tmp, body + "\n", { mode: 0o600 });
183
+ const fd = openSync(tmp, "r");
184
+ try {
185
+ fsyncSync(fd);
186
+ } finally {
187
+ closeSync(fd);
188
+ }
189
+ renameSync(tmp, path);
190
+ }
191
+
192
+ function acquire(path, timeoutMs) {
193
+ const lock = `${path}.lock`;
194
+ const deadline = Date.now() + timeoutMs;
195
+ for (;;) {
196
+ try {
197
+ const fd = openSync(lock, "wx", 0o600);
198
+ writeFileSync(fd, String(process.pid));
199
+ closeSync(fd);
200
+ return lock;
201
+ } catch (err) {
202
+ if (err.code !== "EEXIST") throw err;
203
+ if (Date.now() >= deadline) return null;
204
+ }
205
+ }
206
+ }
207
+
208
+ /**
209
+ * claimSpend({ path, receiptDigest, approvalNonce, at, orderRef, privateKeyPem })
210
+ *
211
+ * The cross-process primitive: take the lock, read the whole log, decide, and
212
+ * append under the same lock. Two workers racing for the same approval produce
213
+ * exactly one `ok: true`; the loser sees `spent` and the winning entry.
214
+ *
215
+ * Returns `busy` when the lock could not be acquired in `timeoutMs` — a refusal
216
+ * to guess, not a decision that the spend is free.
217
+ */
218
+ export function claimSpend({ path, receiptDigest, approvalNonce, at, orderRef = null, privateKeyPem, timeoutMs = 2000 } = {}) {
219
+ if (typeof path !== "string" || path.length === 0) throw new TypeError("claimSpend requires a log path");
220
+ const entry = makeSpendEntry({ receiptDigest, approvalNonce, at, orderRef, privateKeyPem });
221
+ const lock = acquire(path, Math.max(1, timeoutMs));
222
+ if (!lock) return Object.freeze({ ok: false, state: "busy", reason: `lock not acquired within ${timeoutMs}ms`, entry: null, entries: Object.freeze([]) });
223
+ try {
224
+ const log = readSpendLog(path);
225
+ const verdict = checkSpent(log, { receiptDigest, approvalNonce });
226
+ if (verdict.state !== "unspent") {
227
+ return Object.freeze({ ok: false, state: verdict.state, reason: verdict.reason, entry: null, entries: log.entries });
228
+ }
229
+ const entries = [...log.entries, entry];
230
+ writeSpendLog(path, entries);
231
+ return Object.freeze({ ok: true, state: "spent", reason: null, entry, entries: Object.freeze(entries) });
232
+ } finally {
233
+ try {
234
+ unlinkSync(lock);
235
+ } catch {
236
+ /* a lost lock file is not a failed spend */
237
+ }
238
+ }
239
+ }
240
+
241
+ /**
242
+ * mergeLogs(logs) — the cross-system fold. Returns every distinct spend key plus
243
+ * the approvals that appear under more than one nonce. Two honest systems that
244
+ * exchanged logs end up with the same conflict list, which is the point.
245
+ */
246
+ export function mergeLogs(logs) {
247
+ const all = [];
248
+ for (const l of Array.isArray(logs) ? logs : [logs]) for (const e of entriesOf(l)) all.push(e);
249
+ const bySpend = new Map();
250
+ const byApproval = new Map();
251
+ for (const e of all) {
252
+ if (!verifySpendEntry(e).ok) continue;
253
+ bySpend.set(e.spendKey, e);
254
+ const list = byApproval.get(e.receiptDigest) ?? [];
255
+ list.push(e);
256
+ byApproval.set(e.receiptDigest, list);
257
+ }
258
+ const conflicts = [];
259
+ for (const [receiptDigest, list] of byApproval) {
260
+ const nonces = new Set(list.map((e) => e.approvalNonce));
261
+ if (nonces.size > 1) conflicts.push(Object.freeze({ receiptDigest, nonces: Object.freeze([...nonces]), entries: Object.freeze(list) }));
262
+ }
263
+ return Object.freeze({
264
+ spendVersion: SPEND_VERSION,
265
+ entries: Object.freeze([...bySpend.values()]),
266
+ uniqueSpends: bySpend.size,
267
+ conflicts: Object.freeze(conflicts),
268
+ });
269
+ }
270
+
271
+ export function selfCheck() {
272
+ const checks = [];
273
+ const { generateIssuerKey } = anchorForSelfCheck();
274
+ const key = generateIssuerKey();
275
+ const receiptDigest = "sha256:" + "c".repeat(64);
276
+ const e1 = makeSpendEntry({ receiptDigest, approvalNonce: "n1", at: "2026-01-01T00:00:00Z", privateKeyPem: key.privateKeyPem });
277
+ checks.push({ name: "a spend entry verifies", pass: verifySpendEntry(e1).ok === true });
278
+ checks.push({ name: "same approval+nonce reads spent", pass: checkSpent([e1], { receiptDigest, approvalNonce: "n1" }).state === "spent" });
279
+ checks.push({ name: "same approval, other nonce reads conflict", pass: checkSpent([e1], { receiptDigest, approvalNonce: "n2" }).state === "conflict" });
280
+ checks.push({ name: "unknown approval reads unspent", pass: checkSpent([e1], { receiptDigest: "sha256:" + "d".repeat(64), approvalNonce: "n1" }).state === "unspent" });
281
+ const tampered = { ...e1, orderRef: "changed" };
282
+ checks.push({ name: "tampered entry makes the log unreadable", pass: checkSpent([tampered], { receiptDigest, approvalNonce: "n1" }).state === "unreadable" });
283
+ const e2 = makeSpendEntry({ receiptDigest, approvalNonce: "n2", at: "2026-01-02T00:00:00Z", privateKeyPem: key.privateKeyPem });
284
+ checks.push({ name: "merging two logs surfaces the conflict", pass: mergeLogs([[e1], [e2]]).conflicts.length === 1 });
285
+ return Object.freeze({ ok: checks.every((c) => c.pass), checks });
286
+ }
287
+
288
+ import { generateIssuerKey as generateIssuerKeyFromAnchor } from "./anchor.mjs";
289
+ function anchorForSelfCheck() {
290
+ return { generateIssuerKey: generateIssuerKeyFromAnchor };
291
+ }
package/trust.mjs ADDED
@@ -0,0 +1,322 @@
1
+ /**
2
+ * CoreGuard Key Trust (CG-KEYS/1) — who signed, whether they were allowed to,
3
+ * and what happens when that answer changes.
4
+ *
5
+ * A signature proves that whoever holds a private key signed some bytes. It
6
+ * does not prove that the signer is the party you mean, that they still are, or
7
+ * that they were when they signed. Those are three different questions, and
8
+ * this module answers each one separately:
9
+ *
10
+ * trust a key is trusted because it is PINNED by the verifier (offline,
11
+ * no PKI assumption), or because a pinned key signed a rotation
12
+ * statement that leads to it. Trust is never inferred from the key
13
+ * embedded in an attestation: that is self-certification, which is
14
+ * exactly the input an attacker controls.
15
+ * rotation the old key signs a statement that names the new public key and
16
+ * an overlap window. Records signed inside the overlap stay valid;
17
+ * new signatures from the old key after it are refused. The chain
18
+ * verifies offline from the pinned root, with no registry.
19
+ * revocation the key (or a verified successor) signs a statement with a time
20
+ * and whether it is retroactive. A non-retroactive revocation says
21
+ * "stop trusting new signatures"; a retroactive one says "and the
22
+ * old ones were never good". That is the difference between a
23
+ * routine rotation and a compromise, and a vocabulary that cannot
24
+ * say it forces every consumer to guess.
25
+ *
26
+ * Verification is time-aware by construction: `issuedAt` is part of the signed
27
+ * body, so trust is evaluated at the moment the attestation claims, not at the
28
+ * moment somebody got around to checking. A caller asking "is this key good
29
+ * now" calls `checkKey` with its own clock; nothing here reads a clock.
30
+ *
31
+ * BOUNDARY (standing, load-bearing):
32
+ * - An `unknown` key is not a failed signature. It is NOT_CHECKED with a
33
+ * reason, returned as such so a caller cannot render "I have no opinion"
34
+ * as "this is forged".
35
+ * - Trust here is about keys, never about people: a trusted key says the same
36
+ * party signed, not that the record is correct or the merchant honest.
37
+ * - Statements are pure data. No key server, no OCSP, no callback: freshness
38
+ * is whatever the verifier's own keyring says, stated rather than hidden
39
+ * behind a network call.
40
+ */
41
+
42
+ import { createPrivateKey, createPublicKey, sign, verify } from "node:crypto";
43
+ import { generateIssuerKey, keyIdFor, signAttestation, verifyAttestation } from "./anchor.mjs";
44
+
45
+ export const KEYS_VERSION = "CG-KEYS/1";
46
+ export const KEYS_SCHEMA = "coreguard.keyring/1";
47
+ export const KEY_STATUSES = Object.freeze(["trusted", "rotated", "revoked", "expired", "not-yet-valid", "unknown"]);
48
+
49
+ function canonicalJson(value) {
50
+ if (value === null || typeof value !== "object") return JSON.stringify(value ?? null);
51
+ if (Array.isArray(value)) return "[" + value.map((v) => canonicalJson(v)).join(",") + "]";
52
+ const keys = Object.keys(value).sort();
53
+ return "{" + keys.map((k) => JSON.stringify(k) + ":" + canonicalJson(value[k])).join(",") + "}";
54
+ }
55
+
56
+ const iso = (value, field) => {
57
+ if (typeof value !== "string" || Number.isNaN(Date.parse(value))) throw new TypeError(`${field} must be an ISO-8601 timestamp`);
58
+ return value;
59
+ };
60
+
61
+ const publicFromPrivate = (privateKeyPem) =>
62
+ createPublicKey(createPrivateKey(privateKeyPem)).export({ type: "spki", format: "pem" }).toString();
63
+
64
+ const rotationBody = (r) => ({
65
+ keysVersion: r.keysVersion,
66
+ schema: r.schema,
67
+ type: "rotate",
68
+ from: r.from,
69
+ to: r.to,
70
+ toPublicKeyPem: r.toPublicKeyPem,
71
+ at: r.at,
72
+ overlapUntil: r.overlapUntil,
73
+ });
74
+
75
+ const revocationBody = (r) => ({
76
+ keysVersion: r.keysVersion,
77
+ schema: r.schema,
78
+ type: "revoke",
79
+ keyId: r.keyId,
80
+ by: r.by,
81
+ at: r.at,
82
+ retroactive: r.retroactive,
83
+ reason: r.reason,
84
+ });
85
+
86
+ function signedBy(publicKeyPem, body, signature) {
87
+ try {
88
+ return verify(null, Buffer.from(canonicalJson(body), "utf8"), publicKeyPem, Buffer.from(signature, "base64"));
89
+ } catch {
90
+ return false;
91
+ }
92
+ }
93
+
94
+ /** A keyring is plain data: safe to write to disk, diff, or hand to an auditor. */
95
+ export function createKeyring({ id = "keyring" } = {}) {
96
+ return Object.freeze({
97
+ keysVersion: KEYS_VERSION,
98
+ schema: KEYS_SCHEMA,
99
+ id,
100
+ pinned: Object.freeze([]),
101
+ rotations: Object.freeze([]),
102
+ revocations: Object.freeze([]),
103
+ });
104
+ }
105
+
106
+ /** Pin a key as a trust root. The verifier must already believe this key. */
107
+ export function pinKey(keyring, { publicKeyPem, issuer = null, notBefore = null, notAfter = null } = {}) {
108
+ if (typeof publicKeyPem !== "string" || !publicKeyPem.includes("PUBLIC KEY")) {
109
+ throw new TypeError("publicKeyPem must be an SPKI PEM string");
110
+ }
111
+ const key = Object.freeze({
112
+ keyId: keyIdFor(publicKeyPem),
113
+ publicKeyPem,
114
+ issuer,
115
+ notBefore: notBefore ? iso(notBefore, "notBefore") : null,
116
+ notAfter: notAfter ? iso(notAfter, "notAfter") : null,
117
+ });
118
+ if (keyring.pinned.some((k) => k.keyId === key.keyId)) return keyring;
119
+ return Object.freeze({ ...keyring, pinned: Object.freeze([...keyring.pinned, key]) });
120
+ }
121
+
122
+ /** rotateKey(keyring, { privateKeyPem, newPublicKeyPem, at, overlapUntil }) */
123
+ export function rotateKey(keyring, { privateKeyPem, newPublicKeyPem, at, overlapUntil } = {}) {
124
+ if (typeof newPublicKeyPem !== "string" || !newPublicKeyPem.includes("PUBLIC KEY")) {
125
+ throw new TypeError("newPublicKeyPem must be an SPKI PEM string");
126
+ }
127
+ const statement = {
128
+ keysVersion: KEYS_VERSION,
129
+ schema: KEYS_SCHEMA,
130
+ type: "rotate",
131
+ from: keyIdFor(publicFromPrivate(privateKeyPem)),
132
+ to: keyIdFor(newPublicKeyPem),
133
+ toPublicKeyPem: newPublicKeyPem,
134
+ at: iso(at, "at"),
135
+ overlapUntil: iso(overlapUntil, "overlapUntil"),
136
+ };
137
+ if (Date.parse(statement.overlapUntil) < Date.parse(statement.at)) {
138
+ throw new TypeError("overlapUntil must not precede at");
139
+ }
140
+ const signature = sign(null, Buffer.from(canonicalJson(statement), "utf8"), privateKeyPem).toString("base64");
141
+ return Object.freeze({ ...keyring, rotations: Object.freeze([...keyring.rotations, Object.freeze({ ...statement, signature })]) });
142
+ }
143
+
144
+ /** revokeKey(keyring, { privateKeyPem, keyId, at, retroactive, reason }) */
145
+ export function revokeKey(keyring, { privateKeyPem, keyId, at, retroactive = false, reason = null } = {}) {
146
+ if (typeof keyId !== "string" || !/^[0-9a-f]{64}$/.test(keyId)) throw new TypeError("keyId must be a 64-character hex id");
147
+ const statement = {
148
+ keysVersion: KEYS_VERSION,
149
+ schema: KEYS_SCHEMA,
150
+ type: "revoke",
151
+ keyId,
152
+ by: keyIdFor(publicFromPrivate(privateKeyPem)),
153
+ at: iso(at, "at"),
154
+ retroactive: retroactive === true,
155
+ reason: typeof reason === "string" ? reason : null,
156
+ };
157
+ const signature = sign(null, Buffer.from(canonicalJson(statement), "utf8"), privateKeyPem).toString("base64");
158
+ return Object.freeze({ ...keyring, revocations: Object.freeze([...keyring.revocations, Object.freeze({ ...statement, signature })]) });
159
+ }
160
+
161
+ /**
162
+ * The trust closure: pinned roots plus every key reachable through a rotation
163
+ * statement that verifies against a key already in the closure. Iterated to a
164
+ * fixpoint, so A→B→C is trusted exactly when both links verify.
165
+ */
166
+ function trustClosure(keyring) {
167
+ const keys = new Map();
168
+ for (const k of keyring.pinned) keys.set(k.keyId, { ...k, depth: 0, from: null });
169
+ const links = new Map();
170
+ let changed = true;
171
+ while (changed) {
172
+ changed = false;
173
+ for (const r of keyring.rotations) {
174
+ const parent = keys.get(r.from);
175
+ if (!parent) continue;
176
+ if (r.to !== keyIdFor(r.toPublicKeyPem)) continue;
177
+ if (!signedBy(parent.publicKeyPem, rotationBody(r), r.signature)) continue;
178
+ if (!links.has(r.from)) links.set(r.from, Object.freeze({ to: r.to, at: r.at, overlapUntil: r.overlapUntil }));
179
+ if (!keys.has(r.to)) {
180
+ keys.set(r.to, Object.freeze({ keyId: r.to, publicKeyPem: r.toPublicKeyPem, issuer: parent.issuer, notBefore: null, notAfter: null, depth: parent.depth + 1, from: r.from }));
181
+ changed = true;
182
+ }
183
+ }
184
+ }
185
+ return { keys, links };
186
+ }
187
+
188
+ function checkKeyInner(keyring, keyId, when, seen) {
189
+ const t = Date.parse(when);
190
+ const { keys, links } = trustClosure(keyring);
191
+ const key = keys.get(keyId);
192
+ if (!key) {
193
+ return Object.freeze({
194
+ keyId,
195
+ status: "unknown",
196
+ trustedAtTime: false,
197
+ acceptsNew: false,
198
+ at: when,
199
+ reason: "key is not in this keyring's trust closure",
200
+ chainFrom: null,
201
+ });
202
+ }
203
+ const base = { keyId, at: when, issuer: key.issuer ?? null, chainFrom: key.from ?? null, depth: key.depth };
204
+
205
+ for (const r of keyring.revocations.filter((x) => x.keyId === keyId)) {
206
+ const signer = keys.get(r.by);
207
+ if (!signer) continue;
208
+ if (!signedBy(signer.publicKeyPem, revocationBody(r), r.signature)) continue;
209
+ const self = r.by === keyId;
210
+ const authorised = self || (seen.has(r.by) ? false : (seen.add(r.by), checkKeyInner(keyring, r.by, r.at, seen).trustedAtTime === true));
211
+ if (!authorised) continue;
212
+ if (r.retroactive === true) {
213
+ return Object.freeze({ ...base, status: "revoked", trustedAtTime: false, acceptsNew: false, reason: r.reason ?? "retroactive revocation" });
214
+ }
215
+ if (t >= Date.parse(r.at)) {
216
+ return Object.freeze({ ...base, status: "revoked", trustedAtTime: false, acceptsNew: false, reason: r.reason ?? `revoked at ${r.at}` });
217
+ }
218
+ }
219
+
220
+ if (key.notAfter && t > Date.parse(key.notAfter)) {
221
+ return Object.freeze({ ...base, status: "expired", trustedAtTime: false, acceptsNew: false, reason: `notAfter ${key.notAfter}` });
222
+ }
223
+ if (key.notBefore && t < Date.parse(key.notBefore)) {
224
+ return Object.freeze({ ...base, status: "not-yet-valid", trustedAtTime: false, acceptsNew: false, reason: `notBefore ${key.notBefore}` });
225
+ }
226
+
227
+ const successor = links.get(keyId);
228
+ if (successor && t > Date.parse(successor.overlapUntil)) {
229
+ return Object.freeze({ ...base, status: "rotated", trustedAtTime: false, acceptsNew: false, rotatedTo: successor.to, reason: `overlap ended ${successor.overlapUntil}` });
230
+ }
231
+ return Object.freeze({
232
+ ...base,
233
+ status: "trusted",
234
+ trustedAtTime: true,
235
+ acceptsNew: !successor,
236
+ rotatedTo: successor ? successor.to : null,
237
+ reason: null,
238
+ });
239
+ }
240
+
241
+ /**
242
+ * checkKey(keyring, { keyId, at })
243
+ *
244
+ * trusted in the closure and valid at `at`
245
+ * rotated genuine, but past its overlap: only records it signed before
246
+ * `overlapUntil` are good, and new signatures are refused
247
+ * revoked a revocation applies at `at`, or retroactively
248
+ * expired outside the pinned validity window
249
+ * not-yet-valid before `notBefore`
250
+ * unknown this keyring has no opinion — NOT_CHECKED, not forged
251
+ */
252
+ export function checkKey(keyring, { keyId, at } = {}) {
253
+ if (!keyring || typeof keyring !== "object") throw new TypeError("checkKey requires a keyring");
254
+ if (typeof keyId !== "string") throw new TypeError("keyId must be a string");
255
+ return checkKeyInner(keyring, keyId, iso(at, "at"), new Set([keyId]));
256
+ }
257
+
258
+ /**
259
+ * verifyWithTrust(attestation, keyring)
260
+ *
261
+ * Two checks, kept apart in the output so triage can tell them apart:
262
+ * signature the bytes verify against the key the attestation carries
263
+ * trust that key was trusted at the moment the attestation claims
264
+ *
265
+ * `ok` requires both. An unknown key is NOT_CHECKED; a signature that verifies
266
+ * under a revoked or rotated key is VERIFICATION_FAILED, with the key status
267
+ * named. Neither is ever reported as "absent".
268
+ */
269
+ export function verifyWithTrust(attestation, keyring) {
270
+ const checks = [];
271
+ if (!attestation || typeof attestation !== "object") {
272
+ return Object.freeze({ ok: false, keyStatus: "unknown", outcome: "NOT_CHECKED", checks: Object.freeze([{ name: "attestation is an object", ok: false }]) });
273
+ }
274
+ const sig = verifyAttestation(attestation);
275
+ checks.push({ name: "attestation verifies against its own key", ok: sig.ok });
276
+ const status = checkKey(keyring, { keyId: attestation?.issuer?.keyId, at: attestation?.issuedAt ?? new Date(0).toISOString() });
277
+ checks.push({ name: `key status at issuedAt: ${status.status}`, ok: status.trustedAtTime === true });
278
+ const ok = sig.ok && status.trustedAtTime === true;
279
+ const outcome = ok ? "VERIFIED" : status.status === "unknown" ? "NOT_CHECKED" : "VERIFICATION_FAILED";
280
+ return Object.freeze({
281
+ ok,
282
+ keyStatus: status.status,
283
+ outcome,
284
+ acceptsNew: status.acceptsNew === true,
285
+ reason: ok ? null : status.reason ?? "signature did not verify",
286
+ checks: Object.freeze(checks),
287
+ signatureOk: sig.ok,
288
+ chain: status.chainFrom ? { from: status.chainFrom, depth: status.depth ?? null } : null,
289
+ });
290
+ }
291
+
292
+ export function selfCheck() {
293
+ const checks = [];
294
+ const a = generateIssuerKey();
295
+ const b = generateIssuerKey();
296
+ const subject = { kind: "receipt", digest: "sha256:" + "b".repeat(64) };
297
+ let ring = pinKey(createKeyring({ id: "selfcheck" }), { publicKeyPem: a.publicKeyPem, issuer: "self" });
298
+ const att = signAttestation({ subject, issuedAt: "2026-01-01T00:00:00Z", privateKeyPem: a.privateKeyPem });
299
+
300
+ checks.push({ name: "pinned key verifies its own attestation", pass: verifyWithTrust(att, ring).ok === true });
301
+
302
+ const unpinned = verifyWithTrust(att, createKeyring());
303
+ checks.push({ name: "unknown key is NOT_CHECKED, not failed", pass: unpinned.outcome === "NOT_CHECKED" && unpinned.keyStatus === "unknown" });
304
+
305
+ const rotated = rotateKey(ring, { privateKeyPem: a.privateKeyPem, newPublicKeyPem: b.publicKeyPem, at: "2026-02-01T00:00:00Z", overlapUntil: "2026-02-08T00:00:00Z" });
306
+ checks.push({ name: "successor key is trusted through the rotation chain", pass: checkKey(rotated, { keyId: keyIdFor(b.publicKeyPem), at: "2026-02-02T00:00:00Z" }).status === "trusted" });
307
+ checks.push({ name: "old key inside the overlap stays valid", pass: checkKey(rotated, { keyId: keyIdFor(a.publicKeyPem), at: "2026-02-03T00:00:00Z" }).trustedAtTime === true });
308
+ checks.push({ name: "old key after the overlap is rotated, not trusted", pass: checkKey(rotated, { keyId: keyIdFor(a.publicKeyPem), at: "2026-03-01T00:00:00Z" }).status === "rotated" });
309
+
310
+ const late = signAttestation({ subject, issuedAt: "2026-03-01T00:00:00Z", privateKeyPem: a.privateKeyPem });
311
+ checks.push({ name: "post-overlap signature by the old key is refused", pass: verifyWithTrust(late, rotated).outcome === "VERIFICATION_FAILED" });
312
+
313
+ const retro = revokeKey(ring, { privateKeyPem: a.privateKeyPem, keyId: keyIdFor(a.publicKeyPem), at: "2026-01-15T00:00:00Z", retroactive: true, reason: "compromise" });
314
+ checks.push({ name: "retroactive revocation invalidates a past attestation", pass: verifyWithTrust(att, retro).ok === false && verifyWithTrust(att, retro).keyStatus === "revoked" });
315
+
316
+ const forward = revokeKey(ring, { privateKeyPem: a.privateKeyPem, keyId: keyIdFor(a.publicKeyPem), at: "2026-01-15T00:00:00Z", retroactive: false });
317
+ checks.push({ name: "non-retroactive revocation keeps records from before it", pass: verifyWithTrust(att, forward).ok === true });
318
+ const after = signAttestation({ subject, issuedAt: "2026-02-01T00:00:00Z", privateKeyPem: a.privateKeyPem });
319
+ checks.push({ name: "non-retroactive revocation refuses records after it", pass: verifyWithTrust(after, forward).ok === false });
320
+
321
+ return Object.freeze({ ok: checks.every((c) => c.pass), checks });
322
+ }