@rightkit/release 0.6.7 → 0.6.10

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.
Files changed (53) hide show
  1. package/README.md +35 -10
  2. package/admission-files.mjs +1 -1
  3. package/app-check.mjs +94 -20
  4. package/assemble-app-command.mjs +151 -0
  5. package/assembled-app.mjs +445 -0
  6. package/bin/darwin/rightkit-swap +0 -0
  7. package/bin/darwin/rightkit-swap.sign.json +6 -0
  8. package/bin/rightkit-gate.mjs +957 -83
  9. package/build-launch.mjs +88 -0
  10. package/build-ownership.mjs +1231 -0
  11. package/build-release.mjs +2 -1
  12. package/cargo-contract.mjs +3 -1
  13. package/cargo-target-shim.mjs +166 -0
  14. package/class-a-launch-guard.mjs +126 -0
  15. package/cli/right-release.mjs +3 -1
  16. package/codesign-shim.mjs +11 -1
  17. package/deterministic-scans.mjs +807 -56
  18. package/development-signing.mjs +4 -1
  19. package/development.mjs +110 -20
  20. package/door-policy.mjs +61 -6
  21. package/door.mjs +23 -0
  22. package/gate-executor.mjs +14 -2
  23. package/gate-stages.mjs +15 -5
  24. package/heavy-command.mjs +3 -2
  25. package/install-app.mjs +11 -2
  26. package/install-assembled-app.mjs +423 -0
  27. package/ios-dev.mjs +70 -3
  28. package/linux-artifacts.mjs +93 -0
  29. package/local-publish.mjs +161 -26
  30. package/managed-cargo.mjs +47 -5
  31. package/managed-root-guard.mjs +34 -0
  32. package/native-helpers.mjs +355 -0
  33. package/package-recipe-targets.mjs +52 -7
  34. package/package.json +5 -3
  35. package/pipeline-receipts.mjs +302 -302
  36. package/project-type.mjs +2 -2
  37. package/provenance-verify.mjs +115 -0
  38. package/publish-cargo.mjs +8 -6
  39. package/qa-admission-policy.json +10 -1
  40. package/recipe-build.mjs +73 -5
  41. package/release-config.mjs +1 -1
  42. package/release.mjs +15 -5
  43. package/rightkit-versions.json +13 -7
  44. package/snapshot-check.mjs +306 -0
  45. package/snapshot-git.mjs +166 -0
  46. package/snapshot-request.mjs +161 -0
  47. package/snapshot-root-config.mjs +76 -0
  48. package/snapshot.mjs +856 -0
  49. package/stage-commands.mjs +60 -0
  50. package/stage-sidecar.mjs +57 -7
  51. package/test-command.mjs +17 -4
  52. package/unit-gate.mjs +259 -0
  53. package/web-build.mjs +38 -6
@@ -1,302 +1,302 @@
1
- // Pipeline stage receipts and their verifier (architecture-v3 sections 4-5, "Receipts").
2
- //
3
- // A receipt records a fact about one stage of one request. It never authorizes execution alone: the
4
- // broker (RustRight) signs receipts and issues short-lived capabilities; this module only checks that
5
- // a chain of receipts is well formed, linked, fresh and complete. Signature checking is an injected
6
- // interface (`verifySignature`); this module does no cryptography beyond SHA-256 hashing and invents none.
7
- //
8
- // Chain: ADMISSION -> SCAN_A -> ROUTE -> SCAN_B -> BUILD -> SIGN -> QUALIFIED -> PUBLISH_INTENT -> PUBLISHED.
9
- // Each stage requires exactly its predecessor; `parents` carries that predecessor's receipt hash.
10
- import crypto from "node:crypto";
11
- import { canonicalJson, digestScanSet, scanClassOf } from "./deterministic-scans.mjs";
12
-
13
- export const RECEIPT_SCHEMA = "rightkit.pipeline-receipt/1";
14
- export const STAGES = Object.freeze(["ADMISSION", "SCAN_A", "ROUTE", "SCAN_B", "BUILD", "SIGN", "QUALIFIED", "PUBLISH_INTENT", "PUBLISHED"]);
15
- export const OPERATIONS = Object.freeze(["dev", "build", "qualify", "sign", "publish"]);
16
- /** The last stage each operation may reach. */
17
- export const OPERATION_LAST_STAGE = Object.freeze({ dev: "BUILD", build: "BUILD", sign: "SIGN", qualify: "QUALIFIED", publish: "PUBLISHED" });
18
- /** Each stage requires only these predecessors. */
19
- export const PREREQUISITES = Object.freeze({
20
- ADMISSION: [], SCAN_A: ["ADMISSION"], ROUTE: ["SCAN_A"], SCAN_B: ["ROUTE"], BUILD: ["SCAN_B"],
21
- SIGN: ["BUILD"], QUALIFIED: ["SIGN"], PUBLISH_INTENT: ["QUALIFIED"], PUBLISHED: ["PUBLISH_INTENT"],
22
- });
23
- const RELEASE_ID_STAGES = new Set(["SIGN", "QUALIFIED", "PUBLISH_INTENT", "PUBLISHED"]);
24
- /** Stages only a publishable request may reach: signing and everything after it. A dev or non-publishable chain stops at BUILD. */
25
- const PUBLISHABLE_ONLY_STAGES = new Set(RELEASE_ID_STAGES);
26
-
27
- /**
28
- * What ADMISSION's evidence allows for `stage`, as [{ code, message }]. ADMISSION is the sole authority:
29
- * a missing or malformed ADMISSION authorizes nothing, and `publishable` must be exactly true to reach SIGN or later.
30
- */
31
- function admissionProblems(admission, stage) {
32
- const out = [];
33
- if (!admission) return [{ code: "STAGE_NOT_AUTHORIZED", message: `no valid ADMISSION evidence authorizes ${stage}` }];
34
- if (!Array.isArray(admission.authorizedStages) || !admission.authorizedStages.includes(stage)) out.push({ code: "STAGE_NOT_AUTHORIZED", message: `ADMISSION does not authorize ${stage}` });
35
- if (admission.publishable !== true && PUBLISHABLE_ONLY_STAGES.has(stage)) out.push({ code: "NOT_PUBLISHABLE", message: `ADMISSION does not mark this request publishable:true; it cannot reach ${stage}` });
36
- return out;
37
- }
38
-
39
- const ENVELOPE_STRINGS = ["receiptId", "jobId", "requestId", "repositoryId", "commit", "inputDigest", "configDigest", "policyDigest", "stagePlanDigest", "runtimeDigest", "executor", "issuedAt", "expiresAt", "keyId", "signature"];
40
- const HEX64 = /^[0-9a-f]{64}$/;
41
- const sha256 = (value) => crypto.createHash("sha256").update(value).digest("hex");
42
-
43
- /** Domain-separated bytes a signature covers: receipt type bound in, signature field excluded. */
44
- export function signingBytes(receipt) {
45
- const { signature, ...rest } = receipt;
46
- return Buffer.from(`${RECEIPT_SCHEMA}\0${receipt.type}\0${canonicalJson(rest)}`, "utf8");
47
- }
48
-
49
- /** The hash a child receipt records in `parents`: covers the whole receipt including its signature. */
50
- export function receiptHash(receipt) {
51
- return sha256(Buffer.concat([Buffer.from(`${RECEIPT_SCHEMA}.hash\0`, "utf8"), Buffer.from(canonicalJson(receipt), "utf8")]));
52
- }
53
-
54
- /** In-memory request ledger for tests and single-process brokers: records which job owns a requestId. */
55
- export function createMemoryLedger() {
56
- const owners = new Map(); const consumed = new Set();
57
- return {
58
- requestOwner: (requestId) => owners.get(requestId),
59
- isConsumed: (receiptId) => consumed.has(receiptId),
60
- record(chain) { for (const r of chain) { if (!owners.has(r.requestId)) owners.set(r.requestId, r.jobId); consumed.add(r.receiptId); } },
61
- };
62
- }
63
-
64
- const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
65
- const nonEmptyString = (v) => typeof v === "string" && v.trim() !== "";
66
- const isHex = (v) => typeof v === "string" && HEX64.test(v);
67
- const nonEmptyArray = (v) => Array.isArray(v) && v.length > 0;
68
-
69
- /** Stage-specific evidence checks. Each returns a list of problem messages. */
70
- const STAGE_EVIDENCE = {
71
- ADMISSION(e) {
72
- const p = [];
73
- for (const f of ["inputManifestDigest", "dependencyManifestDigest", "toolchainManifestDigest"]) if (!isHex(e[f])) p.push(`${f} must be a sha256 hex digest`);
74
- if (!nonEmptyArray(e.authorizedStages) || e.authorizedStages.some((s) => !STAGES.includes(s))) p.push("authorizedStages must list known stages");
75
- if (typeof e.publishable !== "boolean") p.push("publishable must be a boolean");
76
- return p;
77
- },
78
- SCAN_A: (e, ctx) => scanEvidence(e, "A", ctx),
79
- ROUTE(e, ctx) {
80
- const p = [];
81
- const d = e.decision;
82
- if (!isObj(d)) return ["decision is required"];
83
- if (!["local", "ci"].includes(d.executor)) p.push("decision.executor must be local or ci");
84
- if (!["public", "private"].includes(d.visibility)) p.push("decision.visibility must be public or private (unknown visibility is rejected)");
85
- if (d.visibility === "private" && d.executor !== "local") p.push("a private repository never routes to CI");
86
- if (typeof d.localGrant !== "boolean") p.push("decision.localGrant must be a boolean");
87
- if (d.executor === "local" && !nonEmptyString(String(e.leaseFence ?? ""))) p.push("a local route needs a leaseFence");
88
- if (d.executor === "ci" && !isObj(e.dispatchBinding)) p.push("a CI route needs a dispatchBinding");
89
- if (!nonEmptyString(d.policyVersion)) p.push("decision.policyVersion is required");
90
- return p;
91
- },
92
- SCAN_B: (e, ctx) => scanEvidence(e, "B", ctx),
93
- BUILD(e) {
94
- const p = [];
95
- if (!isHex(e.artifactManifestDigest)) p.push("artifactManifestDigest must be a sha256 hex digest");
96
- if (!nonEmptyArray(e.artifacts) || e.artifacts.some((a) => !nonEmptyString(a?.path) || !isHex(a?.sha256))) p.push("artifacts must list path and sha256 for every output");
97
- for (const f of ["generationEvidenceDigest", "provenanceDigest"]) if (!isHex(e[f])) p.push(`${f} must be a sha256 hex digest`);
98
- if (!nonEmptyArray(e.targetMatrix)) p.push("targetMatrix must list the built targets");
99
- return p;
100
- },
101
- SIGN(e, ctx) {
102
- const p = [];
103
- if (!["SIGN", "SEAL"].includes(e.mode)) p.push("mode must be SIGN or SEAL");
104
- for (const f of ["inputManifestDigest", "outputManifestDigest", "signingEvidenceDigest"]) if (!isHex(e[f])) p.push(`${f} must be a sha256 hex digest`);
105
- if (!nonEmptyString(e.signingProfile)) p.push("signingProfile is required");
106
- const build = ctx.byStage.BUILD;
107
- if (build && e.inputManifestDigest !== build.evidence?.artifactManifestDigest) p.push("inputManifestDigest does not equal the BUILD artifactManifestDigest");
108
- return p;
109
- },
110
- QUALIFIED(e, ctx) {
111
- const p = [];
112
- if (!isHex(e.artifactManifestDigest)) p.push("artifactManifestDigest must be a sha256 hex digest");
113
- if (!nonEmptyArray(e.testMatrix) || e.testMatrix.some((t) => !nonEmptyString(t?.name) || t?.status !== "pass")) p.push("testMatrix must be non-empty and every row must pass");
114
- const sign = ctx.byStage.SIGN;
115
- if (sign && e.artifactManifestDigest !== sign.evidence?.outputManifestDigest) p.push("artifactManifestDigest does not equal the SIGN outputManifestDigest (qualification covers the final signed bytes)");
116
- return p;
117
- },
118
- PUBLISH_INTENT(e, ctx) {
119
- const p = [];
120
- if (!isHex(e.releaseManifestDigest)) p.push("releaseManifestDigest must be a sha256 hex digest");
121
- if (!nonEmptyArray(e.destinations) || e.destinations.some((d) => !nonEmptyString(d?.id) || !nonEmptyString(d?.identity) || !nonEmptyString(d?.version) || !isHex(d?.expectedDigest) || !nonEmptyString(d?.idempotencyKey))) {
122
- p.push("destinations must name id, identity, version, expectedDigest and idempotencyKey");
123
- }
124
- const q = ctx.byStage.QUALIFIED;
125
- if (q && e.releaseManifestDigest !== q.evidence?.artifactManifestDigest) p.push("releaseManifestDigest does not equal the QUALIFIED artifactManifestDigest");
126
- return p;
127
- },
128
- PUBLISHED(e, ctx) {
129
- const p = [];
130
- const intent = ctx.byStage.PUBLISH_INTENT;
131
- if (!nonEmptyArray(e.entries)) return ["entries must list every destination outcome"];
132
- for (const d of intent?.evidence?.destinations ?? []) {
133
- const entry = e.entries.find((x) => x?.destinationId === d.id);
134
- if (!entry) p.push(`no entry for destination ${d.id}`);
135
- else if (entry.outcome !== "verified") p.push(`destination ${d.id} is ${entry.outcome}, not verified`);
136
- else if (entry.remoteDigest !== d.expectedDigest) p.push(`destination ${d.id} readback digest differs from the intent`);
137
- }
138
- return p;
139
- },
140
- };
141
-
142
- function scanEvidence(e, cls, ctx) {
143
- const p = [];
144
- const other = cls === "A" ? "B" : "A";
145
- if (e.scanClass !== cls) p.push(`scanClass must be ${cls}`);
146
- if (!nonEmptyArray(e.scans)) return [...p, "scans must list every required scan result"];
147
- if (cls === "A" && !isHex(e.advisorySnapshotDigest)) p.push("advisorySnapshotDigest must be a sha256 hex digest");
148
- if (cls === "A" && !nonEmptyString(e.advisorySnapshotTime)) p.push("advisorySnapshotTime is required");
149
- for (const s of e.scans) {
150
- const derived = scanClassOf(s?.id);
151
- if (s?.class === other || derived === other) p.push(`${cls === "A" ? "SCAN_A claims" : "SCAN_B carries"} class ${other} scan ${s?.id}`);
152
- else if (s?.class !== cls) p.push(`scan ${s?.id} has class ${s?.class}, expected ${cls}`);
153
- if (s?.status !== "pass") p.push(`scan ${s?.id} is ${s?.status}, not pass`);
154
- }
155
- const ids = new Set(e.scans.map((s) => s?.id));
156
- const required = ctx.requiredScans?.[cls];
157
- const declared = Array.isArray(e.requiredScanIds) ? e.requiredScanIds : null;
158
- if (!declared) p.push("requiredScanIds is required");
159
- // The required set comes only from the injected policy matrix. A receipt's own declaration is never trusted:
160
- // without the policy, verification fails closed.
161
- if (!Array.isArray(required) || required.some((id) => typeof id !== "string")) {
162
- p.push(`trusted required scan set for class ${cls} is not supplied by policy; verification fails closed`);
163
- return p;
164
- }
165
- for (const id of required) if (!ids.has(id)) p.push(`required class ${cls} scan ${id} is missing`);
166
- if (declared && canonicalJson([...required].sort()) !== canonicalJson([...declared].sort())) p.push(`requiredScanIds differ from the trusted class ${cls} set`);
167
- if (e.scanSetDigest !== digestScanSet(e.scans)) p.push("scanSetDigest does not match the listed scans");
168
- if (cls === "B" && !nonEmptyArray(required)) p.push("SCAN_B must require at least one class B scan");
169
- return p;
170
- }
171
-
172
- /**
173
- * Verify a chain of receipts (ADMISSION first, ending at the stage being authorized).
174
- *
175
- * options:
176
- * verifySignature({ receipt, keyId, signingBytes, signature }) -> boolean REQUIRED (the broker supplies keys)
177
- * now ISO string or Date, default current time
178
- * expected { requestId, operation, inputDigest, stage, repositoryId, commit, jobId, releaseId, targetSet } (each optional but checked when given)
179
- * requiredScans { A: [ids], B: [ids] } trusted required sets from the policy matrix: REQUIRED; absence rejects (NO_SCAN_POLICY)
180
- * ledger { requestOwner(requestId), isConsumed(receiptId) } REQUIRED: without it verification fails (NO_LEDGER)
181
- * keyAllowed (keyId, receipt) -> boolean, for revocations
182
- * Returns { ok, problems: [{ code, stage, message }], head }. Never throws on a bad receipt.
183
- */
184
- export function verifyReceiptChain(chain, options = {}) {
185
- const problems = [];
186
- const bad = (code, stage, message) => problems.push({ code, stage: stage ?? null, message });
187
- if (typeof options.verifySignature !== "function") return { ok: false, problems: [{ code: "NO_SIGNATURE_VERIFIER", stage: null, message: "a signature verifier must be supplied by the broker" }], head: null };
188
- if (!Array.isArray(chain) || chain.length === 0) return { ok: false, problems: [{ code: "EMPTY_CHAIN", stage: null, message: "no receipts" }], head: null };
189
- const now = new Date(options.now ?? Date.now()).getTime();
190
- const expected = options.expected ?? {};
191
- const byStage = {};
192
- let previous = null;
193
- // Replay protection is mandatory: without a ledger the chain cannot be proven fresh, so it fails closed.
194
- if (typeof options.ledger?.requestOwner !== "function" || typeof options.ledger?.isConsumed !== "function") {
195
- bad("NO_LEDGER", null, "a request ledger with requestOwner and isConsumed must be supplied; replay cannot be ruled out without it");
196
- }
197
- // One release id for the whole chain: the ADMISSION one when it has it, else the first release-stage one.
198
- const releaseRef = chain.find((r) => isObj(r) && nonEmptyString(r.releaseId))?.releaseId;
199
- // ADMISSION fixes which stages may run and whether the request may publish at all.
200
- const admission = isObj(chain[0]) && chain[0].type === "ADMISSION" && isObj(chain[0].evidence) ? chain[0].evidence : null;
201
-
202
- chain.forEach((receipt, index) => {
203
- const stage = isObj(receipt) ? receipt.type : null;
204
- if (!isObj(receipt)) { bad("MALFORMED", null, `receipt ${index} is not an object`); return; }
205
- if (receipt.schema !== RECEIPT_SCHEMA) bad("SCHEMA", stage, `schema must be ${RECEIPT_SCHEMA}`);
206
- if (!STAGES.includes(stage)) { bad("UNKNOWN_STAGE", stage, `unknown receipt type ${JSON.stringify(stage)}`); return; }
207
- const wantStage = STAGES[index];
208
- if (stage !== wantStage) bad("WRONG_STAGE", stage, `position ${index} requires ${wantStage}, got ${stage}`);
209
- for (const f of ENVELOPE_STRINGS) if (!nonEmptyString(receipt[f])) bad("ENVELOPE", stage, `${f} is required`);
210
- if (!Number.isInteger(receipt.attempt) || receipt.attempt < 1) bad("ENVELOPE", stage, "attempt must be an integer >= 1");
211
- if (!Array.isArray(receipt.targetSet)) bad("ENVELOPE", stage, "targetSet must be an array");
212
- if (!OPERATIONS.includes(receipt.operation)) bad("WRONG_OPERATION", stage, `unknown operation ${JSON.stringify(receipt.operation)}`);
213
- if (RELEASE_ID_STAGES.has(stage) && !nonEmptyString(receipt.releaseId)) bad("ENVELOPE", stage, "releaseId is required");
214
- if (!isObj(receipt.evidence)) bad("EVIDENCE", stage, "evidence is required");
215
-
216
- // The operation bounds how far a request may go.
217
- const last = OPERATION_LAST_STAGE[receipt.operation];
218
- if (last && STAGES.indexOf(stage) > STAGES.indexOf(last)) bad("WRONG_OPERATION", stage, `operation ${receipt.operation} does not authorize ${stage}`);
219
-
220
- // ADMISSION bounds the chain: only its authorized stages, and nothing from SIGN on unless publishable:true.
221
- for (const x of admissionProblems(admission, stage)) bad(x.code, stage, x.message);
222
-
223
- // Binding to the caller's expectations.
224
- if (expected.requestId !== undefined && receipt.requestId !== expected.requestId) bad("WRONG_REQUEST_ID", stage, "requestId differs from the expected request");
225
- if (expected.operation !== undefined && receipt.operation !== expected.operation) bad("WRONG_OPERATION", stage, `operation ${receipt.operation} differs from expected ${expected.operation}`);
226
- if (expected.inputDigest !== undefined && receipt.inputDigest !== expected.inputDigest) bad("WRONG_INPUT_DIGEST", stage, "inputDigest differs from the expected input");
227
- for (const f of ["repositoryId", "commit", "jobId", "releaseId"]) if (expected[f] !== undefined && receipt[f] !== expected[f]) bad("BINDING", stage, `${f} differs from the expected value`);
228
- if (expected.targetSet !== undefined && canonicalJson(receipt.targetSet ?? null) !== canonicalJson(expected.targetSet)) bad("BINDING", stage, "targetSet differs from the expected value");
229
- if (releaseRef !== undefined && receipt.releaseId !== undefined && receipt.releaseId !== releaseRef) bad("BINDING", stage, "releaseId differs from the chain's release");
230
-
231
- // Consistency across the chain.
232
- const first = chain[0];
233
- if (index > 0 && isObj(first)) {
234
- for (const f of ["requestId", "jobId", "repositoryId", "commit", "inputDigest", "configDigest", "policyDigest", "stagePlanDigest", "operation", "targetSet"]) {
235
- if (f === "targetSet" ? canonicalJson(receipt[f] ?? null) !== canonicalJson(first[f] ?? null) : receipt[f] !== first[f]) bad(f === "requestId" ? "WRONG_REQUEST_ID" : f === "inputDigest" ? "WRONG_INPUT_DIGEST" : f === "operation" ? "WRONG_OPERATION" : "BINDING", stage, `${f} differs from the ADMISSION receipt`);
236
- }
237
- }
238
-
239
- // Freshness.
240
- const issued = Date.parse(receipt.issuedAt); const expires = Date.parse(receipt.expiresAt);
241
- if (Number.isNaN(issued) || Number.isNaN(expires)) bad("ENVELOPE", stage, "issuedAt and expiresAt must be ISO timestamps");
242
- else {
243
- if (expires <= issued) bad("ENVELOPE", stage, "expiresAt must be after issuedAt");
244
- if (expires <= now) bad("EXPIRED", stage, `expired at ${receipt.expiresAt}`);
245
- if (issued > now + 60_000) bad("ENVELOPE", stage, "issuedAt is in the future");
246
- if (previous && issued < Date.parse(previous.issuedAt)) bad("ORDER", stage, "issued before its parent receipt");
247
- }
248
-
249
- // Hash chain.
250
- const wantParents = previous ? [receiptHash(previous)] : [];
251
- if (!Array.isArray(receipt.parents) || canonicalJson(receipt.parents) !== canonicalJson(wantParents)) bad("BROKEN_CHAIN", stage, previous ? `parents must be exactly [hash of ${previous.type}]` : "ADMISSION has no parents");
252
-
253
- // Replay (the ledger is required; see NO_LEDGER above).
254
- if (typeof options.ledger?.requestOwner === "function" && typeof options.ledger?.isConsumed === "function") {
255
- const owner = options.ledger.requestOwner(receipt.requestId);
256
- if (owner !== undefined && owner !== receipt.jobId) bad("REPLAYED_REQUEST_ID", stage, "requestId already belongs to another job");
257
- if (options.ledger.isConsumed(receipt.receiptId)) bad("REPLAYED_RECEIPT", stage, "receipt already consumed");
258
- }
259
-
260
- // Signature (injected).
261
- if (options.keyAllowed && !options.keyAllowed(receipt.keyId, receipt)) bad("KEY_REVOKED", stage, `key ${receipt.keyId} is not allowed for this receipt`);
262
- let signatureOk = false;
263
- try { signatureOk = options.verifySignature({ receipt, keyId: receipt.keyId, signingBytes: signingBytes(receipt), signature: receipt.signature }) === true; } catch { signatureOk = false; }
264
- if (!signatureOk) bad("BAD_SIGNATURE", stage, "signature did not verify");
265
-
266
- byStage[stage] = receipt;
267
- // Stage evidence last: it can look at the earlier stages collected so far.
268
- if (isObj(receipt.evidence) && STAGE_EVIDENCE[stage]) {
269
- for (const message of STAGE_EVIDENCE[stage](receipt.evidence, { byStage, requiredScans: options.requiredScans })) {
270
- const code = /trusted required scan set/.test(message) ? "NO_SCAN_POLICY" : /missing|claims|carries/.test(message) && (stage === "SCAN_A" || stage === "SCAN_B") ? (/claims|carries/.test(message) ? "SCAN_CLASS_MIX" : "SCAN_INCOMPLETE") : "EVIDENCE";
271
- bad(code, stage, message);
272
- }
273
- }
274
- previous = receipt;
275
- });
276
-
277
- const head = chain[chain.length - 1];
278
- if (expected.stage !== undefined) {
279
- if (!STAGES.includes(expected.stage)) bad("WRONG_STAGE", null, `unknown expected stage ${expected.stage}`);
280
- else if (head?.type !== expected.stage) bad("WRONG_STAGE", head?.type, `chain ends at ${head?.type}, expected ${expected.stage}`);
281
- }
282
- return { ok: problems.length === 0, problems, head: isObj(head) ? { type: head.type, hash: receiptHash(head) } : null };
283
- }
284
-
285
- /**
286
- * Verify that a new stage may start: the chain so far must verify and end at the stage `stage` requires.
287
- * Returns the same result shape; `authorizes` is the stage the chain authorizes next (or null).
288
- */
289
- export function authorizeNextStage(chain, stage, options = {}) {
290
- const need = PREREQUISITES[stage];
291
- if (!need) return { ok: false, problems: [{ code: "UNKNOWN_STAGE", stage, message: `unknown stage ${stage}` }], head: null, authorizes: null };
292
- if (need.length === 0) return { ok: !chain?.length, problems: chain?.length ? [{ code: "WRONG_STAGE", stage, message: "ADMISSION starts a chain" }] : [], head: null, authorizes: chain?.length ? null : stage };
293
- const result = verifyReceiptChain(chain, { ...options, expected: { ...(options.expected ?? {}), stage: need[0] } });
294
- // The requested stage itself must sit inside the operation's boundary and ADMISSION's authorized stages.
295
- const first = Array.isArray(chain) ? chain[0] : null;
296
- const last = OPERATION_LAST_STAGE[first?.operation];
297
- if (!last || STAGES.indexOf(stage) > STAGES.indexOf(last)) result.problems.push({ code: "WRONG_OPERATION", stage, message: `operation ${first?.operation} does not authorize ${stage}` });
298
- const admission = first?.type === "ADMISSION" && isObj(first.evidence) ? first.evidence : null;
299
- for (const x of admissionProblems(admission, stage)) result.problems.push({ code: x.code, stage, message: x.message });
300
- result.ok = result.problems.length === 0;
301
- return { ...result, authorizes: result.ok ? stage : null };
302
- }
1
+ // Pipeline stage receipts and their verifier (architecture-v3 sections 4-5, "Receipts").
2
+ //
3
+ // A receipt records a fact about one stage of one request. It never authorizes execution alone: the
4
+ // broker (RustRight) signs receipts and issues short-lived capabilities; this module only checks that
5
+ // a chain of receipts is well formed, linked, fresh and complete. Signature checking is an injected
6
+ // interface (`verifySignature`); this module does no cryptography beyond SHA-256 hashing and invents none.
7
+ //
8
+ // Chain: ADMISSION -> SCAN_A -> ROUTE -> SCAN_B -> BUILD -> SIGN -> QUALIFIED -> PUBLISH_INTENT -> PUBLISHED.
9
+ // Each stage requires exactly its predecessor; `parents` carries that predecessor's receipt hash.
10
+ import crypto from "node:crypto";
11
+ import { canonicalJson, digestScanSet, scanClassOf } from "./deterministic-scans.mjs";
12
+
13
+ export const RECEIPT_SCHEMA = "rightkit.pipeline-receipt/1";
14
+ export const STAGES = Object.freeze(["ADMISSION", "SCAN_A", "ROUTE", "SCAN_B", "BUILD", "SIGN", "QUALIFIED", "PUBLISH_INTENT", "PUBLISHED"]);
15
+ export const OPERATIONS = Object.freeze(["dev", "build", "qualify", "sign", "publish"]);
16
+ /** The last stage each operation may reach. */
17
+ export const OPERATION_LAST_STAGE = Object.freeze({ dev: "BUILD", build: "BUILD", sign: "SIGN", qualify: "QUALIFIED", publish: "PUBLISHED" });
18
+ /** Each stage requires only these predecessors. */
19
+ export const PREREQUISITES = Object.freeze({
20
+ ADMISSION: [], SCAN_A: ["ADMISSION"], ROUTE: ["SCAN_A"], SCAN_B: ["ROUTE"], BUILD: ["SCAN_B"],
21
+ SIGN: ["BUILD"], QUALIFIED: ["SIGN"], PUBLISH_INTENT: ["QUALIFIED"], PUBLISHED: ["PUBLISH_INTENT"],
22
+ });
23
+ const RELEASE_ID_STAGES = new Set(["SIGN", "QUALIFIED", "PUBLISH_INTENT", "PUBLISHED"]);
24
+ /** Stages only a publishable request may reach: signing and everything after it. A dev or non-publishable chain stops at BUILD. */
25
+ const PUBLISHABLE_ONLY_STAGES = new Set(RELEASE_ID_STAGES);
26
+
27
+ /**
28
+ * What ADMISSION's evidence allows for `stage`, as [{ code, message }]. ADMISSION is the sole authority:
29
+ * a missing or malformed ADMISSION authorizes nothing, and `publishable` must be exactly true to reach SIGN or later.
30
+ */
31
+ function admissionProblems(admission, stage) {
32
+ const out = [];
33
+ if (!admission) return [{ code: "STAGE_NOT_AUTHORIZED", message: `no valid ADMISSION evidence authorizes ${stage}` }];
34
+ if (!Array.isArray(admission.authorizedStages) || !admission.authorizedStages.includes(stage)) out.push({ code: "STAGE_NOT_AUTHORIZED", message: `ADMISSION does not authorize ${stage}` });
35
+ if (admission.publishable !== true && PUBLISHABLE_ONLY_STAGES.has(stage)) out.push({ code: "NOT_PUBLISHABLE", message: `ADMISSION does not mark this request publishable:true; it cannot reach ${stage}` });
36
+ return out;
37
+ }
38
+
39
+ const ENVELOPE_STRINGS = ["receiptId", "jobId", "requestId", "repositoryId", "commit", "inputDigest", "configDigest", "policyDigest", "stagePlanDigest", "runtimeDigest", "executor", "issuedAt", "expiresAt", "keyId", "signature"];
40
+ const HEX64 = /^[0-9a-f]{64}$/;
41
+ const sha256 = (value) => crypto.createHash("sha256").update(value).digest("hex");
42
+
43
+ /** Domain-separated bytes a signature covers: receipt type bound in, signature field excluded. */
44
+ export function signingBytes(receipt) {
45
+ const { signature, ...rest } = receipt;
46
+ return Buffer.from(`${RECEIPT_SCHEMA}\0${receipt.type}\0${canonicalJson(rest)}`, "utf8");
47
+ }
48
+
49
+ /** The hash a child receipt records in `parents`: covers the whole receipt including its signature. */
50
+ export function receiptHash(receipt) {
51
+ return sha256(Buffer.concat([Buffer.from(`${RECEIPT_SCHEMA}.hash\0`, "utf8"), Buffer.from(canonicalJson(receipt), "utf8")]));
52
+ }
53
+
54
+ /** In-memory request ledger for tests and single-process brokers: records which job owns a requestId. */
55
+ export function createMemoryLedger() {
56
+ const owners = new Map(); const consumed = new Set();
57
+ return {
58
+ requestOwner: (requestId) => owners.get(requestId),
59
+ isConsumed: (receiptId) => consumed.has(receiptId),
60
+ record(chain) { for (const r of chain) { if (!owners.has(r.requestId)) owners.set(r.requestId, r.jobId); consumed.add(r.receiptId); } },
61
+ };
62
+ }
63
+
64
+ const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
65
+ const nonEmptyString = (v) => typeof v === "string" && v.trim() !== "";
66
+ const isHex = (v) => typeof v === "string" && HEX64.test(v);
67
+ const nonEmptyArray = (v) => Array.isArray(v) && v.length > 0;
68
+
69
+ /** Stage-specific evidence checks. Each returns a list of problem messages. */
70
+ const STAGE_EVIDENCE = {
71
+ ADMISSION(e) {
72
+ const p = [];
73
+ for (const f of ["inputManifestDigest", "dependencyManifestDigest", "toolchainManifestDigest"]) if (!isHex(e[f])) p.push(`${f} must be a sha256 hex digest`);
74
+ if (!nonEmptyArray(e.authorizedStages) || e.authorizedStages.some((s) => !STAGES.includes(s))) p.push("authorizedStages must list known stages");
75
+ if (typeof e.publishable !== "boolean") p.push("publishable must be a boolean");
76
+ return p;
77
+ },
78
+ SCAN_A: (e, ctx) => scanEvidence(e, "A", ctx),
79
+ ROUTE(e, ctx) {
80
+ const p = [];
81
+ const d = e.decision;
82
+ if (!isObj(d)) return ["decision is required"];
83
+ if (!["local", "ci"].includes(d.executor)) p.push("decision.executor must be local or ci");
84
+ if (!["public", "private"].includes(d.visibility)) p.push("decision.visibility must be public or private (unknown visibility is rejected)");
85
+ if (d.visibility === "private" && d.executor !== "local") p.push("a private repository never routes to CI");
86
+ if (typeof d.localGrant !== "boolean") p.push("decision.localGrant must be a boolean");
87
+ if (d.executor === "local" && !nonEmptyString(String(e.leaseFence ?? ""))) p.push("a local route needs a leaseFence");
88
+ if (d.executor === "ci" && !isObj(e.dispatchBinding)) p.push("a CI route needs a dispatchBinding");
89
+ if (!nonEmptyString(d.policyVersion)) p.push("decision.policyVersion is required");
90
+ return p;
91
+ },
92
+ SCAN_B: (e, ctx) => scanEvidence(e, "B", ctx),
93
+ BUILD(e) {
94
+ const p = [];
95
+ if (!isHex(e.artifactManifestDigest)) p.push("artifactManifestDigest must be a sha256 hex digest");
96
+ if (!nonEmptyArray(e.artifacts) || e.artifacts.some((a) => !nonEmptyString(a?.path) || !isHex(a?.sha256))) p.push("artifacts must list path and sha256 for every output");
97
+ for (const f of ["generationEvidenceDigest", "provenanceDigest"]) if (!isHex(e[f])) p.push(`${f} must be a sha256 hex digest`);
98
+ if (!nonEmptyArray(e.targetMatrix)) p.push("targetMatrix must list the built targets");
99
+ return p;
100
+ },
101
+ SIGN(e, ctx) {
102
+ const p = [];
103
+ if (!["SIGN", "SEAL"].includes(e.mode)) p.push("mode must be SIGN or SEAL");
104
+ for (const f of ["inputManifestDigest", "outputManifestDigest", "signingEvidenceDigest"]) if (!isHex(e[f])) p.push(`${f} must be a sha256 hex digest`);
105
+ if (!nonEmptyString(e.signingProfile)) p.push("signingProfile is required");
106
+ const build = ctx.byStage.BUILD;
107
+ if (build && e.inputManifestDigest !== build.evidence?.artifactManifestDigest) p.push("inputManifestDigest does not equal the BUILD artifactManifestDigest");
108
+ return p;
109
+ },
110
+ QUALIFIED(e, ctx) {
111
+ const p = [];
112
+ if (!isHex(e.artifactManifestDigest)) p.push("artifactManifestDigest must be a sha256 hex digest");
113
+ if (!nonEmptyArray(e.testMatrix) || e.testMatrix.some((t) => !nonEmptyString(t?.name) || t?.status !== "pass")) p.push("testMatrix must be non-empty and every row must pass");
114
+ const sign = ctx.byStage.SIGN;
115
+ if (sign && e.artifactManifestDigest !== sign.evidence?.outputManifestDigest) p.push("artifactManifestDigest does not equal the SIGN outputManifestDigest (qualification covers the final signed bytes)");
116
+ return p;
117
+ },
118
+ PUBLISH_INTENT(e, ctx) {
119
+ const p = [];
120
+ if (!isHex(e.releaseManifestDigest)) p.push("releaseManifestDigest must be a sha256 hex digest");
121
+ if (!nonEmptyArray(e.destinations) || e.destinations.some((d) => !nonEmptyString(d?.id) || !nonEmptyString(d?.identity) || !nonEmptyString(d?.version) || !isHex(d?.expectedDigest) || !nonEmptyString(d?.idempotencyKey))) {
122
+ p.push("destinations must name id, identity, version, expectedDigest and idempotencyKey");
123
+ }
124
+ const q = ctx.byStage.QUALIFIED;
125
+ if (q && e.releaseManifestDigest !== q.evidence?.artifactManifestDigest) p.push("releaseManifestDigest does not equal the QUALIFIED artifactManifestDigest");
126
+ return p;
127
+ },
128
+ PUBLISHED(e, ctx) {
129
+ const p = [];
130
+ const intent = ctx.byStage.PUBLISH_INTENT;
131
+ if (!nonEmptyArray(e.entries)) return ["entries must list every destination outcome"];
132
+ for (const d of intent?.evidence?.destinations ?? []) {
133
+ const entry = e.entries.find((x) => x?.destinationId === d.id);
134
+ if (!entry) p.push(`no entry for destination ${d.id}`);
135
+ else if (entry.outcome !== "verified") p.push(`destination ${d.id} is ${entry.outcome}, not verified`);
136
+ else if (entry.remoteDigest !== d.expectedDigest) p.push(`destination ${d.id} readback digest differs from the intent`);
137
+ }
138
+ return p;
139
+ },
140
+ };
141
+
142
+ function scanEvidence(e, cls, ctx) {
143
+ const p = [];
144
+ const other = cls === "A" ? "B" : "A";
145
+ if (e.scanClass !== cls) p.push(`scanClass must be ${cls}`);
146
+ if (!nonEmptyArray(e.scans)) return [...p, "scans must list every required scan result"];
147
+ if (cls === "A" && !isHex(e.advisorySnapshotDigest)) p.push("advisorySnapshotDigest must be a sha256 hex digest");
148
+ if (cls === "A" && !nonEmptyString(e.advisorySnapshotTime)) p.push("advisorySnapshotTime is required");
149
+ for (const s of e.scans) {
150
+ const derived = scanClassOf(s?.id);
151
+ if (s?.class === other || derived === other) p.push(`${cls === "A" ? "SCAN_A claims" : "SCAN_B carries"} class ${other} scan ${s?.id}`);
152
+ else if (s?.class !== cls) p.push(`scan ${s?.id} has class ${s?.class}, expected ${cls}`);
153
+ if (s?.status !== "pass") p.push(`scan ${s?.id} is ${s?.status}, not pass`);
154
+ }
155
+ const ids = new Set(e.scans.map((s) => s?.id));
156
+ const required = ctx.requiredScans?.[cls];
157
+ const declared = Array.isArray(e.requiredScanIds) ? e.requiredScanIds : null;
158
+ if (!declared) p.push("requiredScanIds is required");
159
+ // The required set comes only from the injected policy matrix. A receipt's own declaration is never trusted:
160
+ // without the policy, verification fails closed.
161
+ if (!Array.isArray(required) || required.some((id) => typeof id !== "string")) {
162
+ p.push(`trusted required scan set for class ${cls} is not supplied by policy; verification fails closed`);
163
+ return p;
164
+ }
165
+ for (const id of required) if (!ids.has(id)) p.push(`required class ${cls} scan ${id} is missing`);
166
+ if (declared && canonicalJson([...required].sort()) !== canonicalJson([...declared].sort())) p.push(`requiredScanIds differ from the trusted class ${cls} set`);
167
+ if (e.scanSetDigest !== digestScanSet(e.scans)) p.push("scanSetDigest does not match the listed scans");
168
+ if (cls === "B" && !nonEmptyArray(required)) p.push("SCAN_B must require at least one class B scan");
169
+ return p;
170
+ }
171
+
172
+ /**
173
+ * Verify a chain of receipts (ADMISSION first, ending at the stage being authorized).
174
+ *
175
+ * options:
176
+ * verifySignature({ receipt, keyId, signingBytes, signature }) -> boolean REQUIRED (the broker supplies keys)
177
+ * now ISO string or Date, default current time
178
+ * expected { requestId, operation, inputDigest, stage, repositoryId, commit, jobId, releaseId, targetSet } (each optional but checked when given)
179
+ * requiredScans { A: [ids], B: [ids] } trusted required sets from the policy matrix: REQUIRED; absence rejects (NO_SCAN_POLICY)
180
+ * ledger { requestOwner(requestId), isConsumed(receiptId) } REQUIRED: without it verification fails (NO_LEDGER)
181
+ * keyAllowed (keyId, receipt) -> boolean, for revocations
182
+ * Returns { ok, problems: [{ code, stage, message }], head }. Never throws on a bad receipt.
183
+ */
184
+ export function verifyReceiptChain(chain, options = {}) {
185
+ const problems = [];
186
+ const bad = (code, stage, message) => problems.push({ code, stage: stage ?? null, message });
187
+ if (typeof options.verifySignature !== "function") return { ok: false, problems: [{ code: "NO_SIGNATURE_VERIFIER", stage: null, message: "a signature verifier must be supplied by the broker" }], head: null };
188
+ if (!Array.isArray(chain) || chain.length === 0) return { ok: false, problems: [{ code: "EMPTY_CHAIN", stage: null, message: "no receipts" }], head: null };
189
+ const now = new Date(options.now ?? Date.now()).getTime();
190
+ const expected = options.expected ?? {};
191
+ const byStage = {};
192
+ let previous = null;
193
+ // Replay protection is mandatory: without a ledger the chain cannot be proven fresh, so it fails closed.
194
+ if (typeof options.ledger?.requestOwner !== "function" || typeof options.ledger?.isConsumed !== "function") {
195
+ bad("NO_LEDGER", null, "a request ledger with requestOwner and isConsumed must be supplied; replay cannot be ruled out without it");
196
+ }
197
+ // One release id for the whole chain: the ADMISSION one when it has it, else the first release-stage one.
198
+ const releaseRef = chain.find((r) => isObj(r) && nonEmptyString(r.releaseId))?.releaseId;
199
+ // ADMISSION fixes which stages may run and whether the request may publish at all.
200
+ const admission = isObj(chain[0]) && chain[0].type === "ADMISSION" && isObj(chain[0].evidence) ? chain[0].evidence : null;
201
+
202
+ chain.forEach((receipt, index) => {
203
+ const stage = isObj(receipt) ? receipt.type : null;
204
+ if (!isObj(receipt)) { bad("MALFORMED", null, `receipt ${index} is not an object`); return; }
205
+ if (receipt.schema !== RECEIPT_SCHEMA) bad("SCHEMA", stage, `schema must be ${RECEIPT_SCHEMA}`);
206
+ if (!STAGES.includes(stage)) { bad("UNKNOWN_STAGE", stage, `unknown receipt type ${JSON.stringify(stage)}`); return; }
207
+ const wantStage = STAGES[index];
208
+ if (stage !== wantStage) bad("WRONG_STAGE", stage, `position ${index} requires ${wantStage}, got ${stage}`);
209
+ for (const f of ENVELOPE_STRINGS) if (!nonEmptyString(receipt[f])) bad("ENVELOPE", stage, `${f} is required`);
210
+ if (!Number.isInteger(receipt.attempt) || receipt.attempt < 1) bad("ENVELOPE", stage, "attempt must be an integer >= 1");
211
+ if (!Array.isArray(receipt.targetSet)) bad("ENVELOPE", stage, "targetSet must be an array");
212
+ if (!OPERATIONS.includes(receipt.operation)) bad("WRONG_OPERATION", stage, `unknown operation ${JSON.stringify(receipt.operation)}`);
213
+ if (RELEASE_ID_STAGES.has(stage) && !nonEmptyString(receipt.releaseId)) bad("ENVELOPE", stage, "releaseId is required");
214
+ if (!isObj(receipt.evidence)) bad("EVIDENCE", stage, "evidence is required");
215
+
216
+ // The operation bounds how far a request may go.
217
+ const last = OPERATION_LAST_STAGE[receipt.operation];
218
+ if (last && STAGES.indexOf(stage) > STAGES.indexOf(last)) bad("WRONG_OPERATION", stage, `operation ${receipt.operation} does not authorize ${stage}`);
219
+
220
+ // ADMISSION bounds the chain: only its authorized stages, and nothing from SIGN on unless publishable:true.
221
+ for (const x of admissionProblems(admission, stage)) bad(x.code, stage, x.message);
222
+
223
+ // Binding to the caller's expectations.
224
+ if (expected.requestId !== undefined && receipt.requestId !== expected.requestId) bad("WRONG_REQUEST_ID", stage, "requestId differs from the expected request");
225
+ if (expected.operation !== undefined && receipt.operation !== expected.operation) bad("WRONG_OPERATION", stage, `operation ${receipt.operation} differs from expected ${expected.operation}`);
226
+ if (expected.inputDigest !== undefined && receipt.inputDigest !== expected.inputDigest) bad("WRONG_INPUT_DIGEST", stage, "inputDigest differs from the expected input");
227
+ for (const f of ["repositoryId", "commit", "jobId", "releaseId"]) if (expected[f] !== undefined && receipt[f] !== expected[f]) bad("BINDING", stage, `${f} differs from the expected value`);
228
+ if (expected.targetSet !== undefined && canonicalJson(receipt.targetSet ?? null) !== canonicalJson(expected.targetSet)) bad("BINDING", stage, "targetSet differs from the expected value");
229
+ if (releaseRef !== undefined && receipt.releaseId !== undefined && receipt.releaseId !== releaseRef) bad("BINDING", stage, "releaseId differs from the chain's release");
230
+
231
+ // Consistency across the chain.
232
+ const first = chain[0];
233
+ if (index > 0 && isObj(first)) {
234
+ for (const f of ["requestId", "jobId", "repositoryId", "commit", "inputDigest", "configDigest", "policyDigest", "stagePlanDigest", "operation", "targetSet"]) {
235
+ if (f === "targetSet" ? canonicalJson(receipt[f] ?? null) !== canonicalJson(first[f] ?? null) : receipt[f] !== first[f]) bad(f === "requestId" ? "WRONG_REQUEST_ID" : f === "inputDigest" ? "WRONG_INPUT_DIGEST" : f === "operation" ? "WRONG_OPERATION" : "BINDING", stage, `${f} differs from the ADMISSION receipt`);
236
+ }
237
+ }
238
+
239
+ // Freshness.
240
+ const issued = Date.parse(receipt.issuedAt); const expires = Date.parse(receipt.expiresAt);
241
+ if (Number.isNaN(issued) || Number.isNaN(expires)) bad("ENVELOPE", stage, "issuedAt and expiresAt must be ISO timestamps");
242
+ else {
243
+ if (expires <= issued) bad("ENVELOPE", stage, "expiresAt must be after issuedAt");
244
+ if (expires <= now) bad("EXPIRED", stage, `expired at ${receipt.expiresAt}`);
245
+ if (issued > now + 60_000) bad("ENVELOPE", stage, "issuedAt is in the future");
246
+ if (previous && issued < Date.parse(previous.issuedAt)) bad("ORDER", stage, "issued before its parent receipt");
247
+ }
248
+
249
+ // Hash chain.
250
+ const wantParents = previous ? [receiptHash(previous)] : [];
251
+ if (!Array.isArray(receipt.parents) || canonicalJson(receipt.parents) !== canonicalJson(wantParents)) bad("BROKEN_CHAIN", stage, previous ? `parents must be exactly [hash of ${previous.type}]` : "ADMISSION has no parents");
252
+
253
+ // Replay (the ledger is required; see NO_LEDGER above).
254
+ if (typeof options.ledger?.requestOwner === "function" && typeof options.ledger?.isConsumed === "function") {
255
+ const owner = options.ledger.requestOwner(receipt.requestId);
256
+ if (owner !== undefined && owner !== receipt.jobId) bad("REPLAYED_REQUEST_ID", stage, "requestId already belongs to another job");
257
+ if (options.ledger.isConsumed(receipt.receiptId)) bad("REPLAYED_RECEIPT", stage, "receipt already consumed");
258
+ }
259
+
260
+ // Signature (injected).
261
+ if (options.keyAllowed && !options.keyAllowed(receipt.keyId, receipt)) bad("KEY_REVOKED", stage, `key ${receipt.keyId} is not allowed for this receipt`);
262
+ let signatureOk = false;
263
+ try { signatureOk = options.verifySignature({ receipt, keyId: receipt.keyId, signingBytes: signingBytes(receipt), signature: receipt.signature }) === true; } catch { signatureOk = false; }
264
+ if (!signatureOk) bad("BAD_SIGNATURE", stage, "signature did not verify");
265
+
266
+ byStage[stage] = receipt;
267
+ // Stage evidence last: it can look at the earlier stages collected so far.
268
+ if (isObj(receipt.evidence) && STAGE_EVIDENCE[stage]) {
269
+ for (const message of STAGE_EVIDENCE[stage](receipt.evidence, { byStage, requiredScans: options.requiredScans })) {
270
+ const code = /trusted required scan set/.test(message) ? "NO_SCAN_POLICY" : /missing|claims|carries/.test(message) && (stage === "SCAN_A" || stage === "SCAN_B") ? (/claims|carries/.test(message) ? "SCAN_CLASS_MIX" : "SCAN_INCOMPLETE") : "EVIDENCE";
271
+ bad(code, stage, message);
272
+ }
273
+ }
274
+ previous = receipt;
275
+ });
276
+
277
+ const head = chain[chain.length - 1];
278
+ if (expected.stage !== undefined) {
279
+ if (!STAGES.includes(expected.stage)) bad("WRONG_STAGE", null, `unknown expected stage ${expected.stage}`);
280
+ else if (head?.type !== expected.stage) bad("WRONG_STAGE", head?.type, `chain ends at ${head?.type}, expected ${expected.stage}`);
281
+ }
282
+ return { ok: problems.length === 0, problems, head: isObj(head) ? { type: head.type, hash: receiptHash(head) } : null };
283
+ }
284
+
285
+ /**
286
+ * Verify that a new stage may start: the chain so far must verify and end at the stage `stage` requires.
287
+ * Returns the same result shape; `authorizes` is the stage the chain authorizes next (or null).
288
+ */
289
+ export function authorizeNextStage(chain, stage, options = {}) {
290
+ const need = PREREQUISITES[stage];
291
+ if (!need) return { ok: false, problems: [{ code: "UNKNOWN_STAGE", stage, message: `unknown stage ${stage}` }], head: null, authorizes: null };
292
+ if (need.length === 0) return { ok: !chain?.length, problems: chain?.length ? [{ code: "WRONG_STAGE", stage, message: "ADMISSION starts a chain" }] : [], head: null, authorizes: chain?.length ? null : stage };
293
+ const result = verifyReceiptChain(chain, { ...options, expected: { ...(options.expected ?? {}), stage: need[0] } });
294
+ // The requested stage itself must sit inside the operation's boundary and ADMISSION's authorized stages.
295
+ const first = Array.isArray(chain) ? chain[0] : null;
296
+ const last = OPERATION_LAST_STAGE[first?.operation];
297
+ if (!last || STAGES.indexOf(stage) > STAGES.indexOf(last)) result.problems.push({ code: "WRONG_OPERATION", stage, message: `operation ${first?.operation} does not authorize ${stage}` });
298
+ const admission = first?.type === "ADMISSION" && isObj(first.evidence) ? first.evidence : null;
299
+ for (const x of admissionProblems(admission, stage)) result.problems.push({ code: x.code, stage, message: x.message });
300
+ result.ok = result.problems.length === 0;
301
+ return { ...result, authorizes: result.ok ? stage : null };
302
+ }