@intentrax/sdk 1.6.0 → 1.7.0

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.
@@ -0,0 +1,503 @@
1
+ // Offline verifier for local assurance bundles.
2
+ //
3
+ // Ported from examples/effect-assurance-demo/src/verifier.mjs (PRs #449,
4
+ // #477), trimmed to the single-mandate, no-budget bundles the sandbox makes.
5
+ // Inputs: a bundle and, normally, the run's LOCAL key set. No network, no
6
+ // clock: every check is relative to timestamps inside the signed records.
7
+ //
8
+ // Output: the same eight per-dimension assessments and the same §5.4 verdict
9
+ // rule as the demo, then the sandbox ceiling: the reported `verdict` is the
10
+ // weaker of the derived verdict and LOCAL_NON_TRUST_BEARING. The ceiling is
11
+ // unconditional. It does not depend on which key set is pinned, because the
12
+ // only key sets this verifier accepts are local, non-trust-bearing ones.
13
+ //
14
+ // Optional (B3, ported from the demo, PR #481): a bundle may carry third-party
15
+ // signed authorization decisions (`external_decisions`). They are assessed
16
+ // against a separately pinned issuer key set as the optional dimension
17
+ // EXTERNAL_AUTHORIZATION, which appears only when the bundle carries them or
18
+ // the relying party names an issuer. They never change AUTHORIZATION and never
19
+ // lift the ceiling.
20
+
21
+ import { digest, canonicalJson } from "./canonical.mjs";
22
+ import { verifyEnvelope, envelopeDigest, PAYLOAD_TYPES } from "./envelope.mjs";
23
+ import { evaluate, actionDigest } from "./authority.mjs";
24
+ import { assessEffect } from "./effect-verifier.mjs";
25
+ import { effectFor } from "./effects.mjs";
26
+ import { BUNDLE_SCHEMA, BUNDLE_FIELDS, OPTIONAL_BUNDLE_FIELDS, sealComponents } from "./bundle.mjs";
27
+ import { LOCAL_ENVIRONMENT, ROLES } from "./keys.mjs";
28
+ import { isoMs } from "./time.mjs";
29
+ import {
30
+ DIMENSIONS, OPTIONAL_DIMENSIONS, PROFILES, PROVENANCE, GLOBAL_LIMITATIONS, LOCAL_VERDICT_CEILING, applyLocalCeiling,
31
+ deriveVerdict, strongerProfile,
32
+ } from "./model.mjs";
33
+ import { assessExternalAuthorization, wrapperIntegrityReasons, EXTERNAL_LIMITATION_TEXT } from "./external-decision.mjs";
34
+
35
+ export const REPORT_SCHEMA = "intentrax.local.sandbox_verification_report/0.1";
36
+
37
+ const LIMITATION_TEXT = {
38
+ SOURCE_RESPONSE_NOT_THIRD_PARTY_SIGNED:
39
+ "The read was not signed by the system that was read. It is attested by the sandbox's local effect-verifier " +
40
+ "key (distinct from the executor key), not re-verifiable from the source itself.",
41
+ SYNTHETIC_SOURCE: "The system read is the sandbox's in-memory synthetic store, not a real system.",
42
+ USER_SUPPLIED_CHECK_NOT_INDEPENDENT:
43
+ "The read-only check was supplied by the developer whose action is being checked. It is not an " +
44
+ "Intentrax-pulled authoritative read, and it is only as independent and correct as that code.",
45
+ USER_CHECK_READ_ONLY_BY_CONTRACT_ONLY:
46
+ "The check is read-only by contract. The sandbox cannot enforce that the check has no side effects.",
47
+ EFFECT_NOT_ATTRIBUTED_TO_THIS_EXECUTION:
48
+ "State matches, but nothing links it to this execution; it may pre-date the action.",
49
+ AGENT_IDENTITY_NOT_AUTHENTICATED: "The agent's identity is a string in the sandbox.",
50
+ POLICY_EVALUATOR_SHARED_WITH_ISSUER:
51
+ "The verifier re-runs the same evaluator as the local decision service; a shared bug would affect both.",
52
+ SELF_REPORTED_NOT_INDEPENDENT:
53
+ "Execution reports come from the executor; a valid signature shows who said it, not that it is true.",
54
+ COVERAGE_PARTIAL: "Only the declared coverage boundary of the resource was observed.",
55
+ ...EXTERNAL_LIMITATION_TEXT,
56
+ };
57
+
58
+ function limitation(code) {
59
+ return { code, text: LIMITATION_TEXT[code] ?? code };
60
+ }
61
+
62
+ function assessment(dimension, result, extra = {}) {
63
+ return {
64
+ dimension,
65
+ result,
66
+ provenance: extra.provenance ?? null,
67
+ coverage: extra.coverage ?? null,
68
+ freshness: extra.freshness ?? null,
69
+ evidence_digests: extra.evidence_digests ?? [],
70
+ reasons: extra.reasons ?? [],
71
+ limitations: (extra.limitations ?? []).map(limitation),
72
+ detail: extra.detail ?? null,
73
+ };
74
+ }
75
+
76
+ function same(a, b) {
77
+ try {
78
+ return canonicalJson(a) === canonicalJson(b);
79
+ } catch {
80
+ return false;
81
+ }
82
+ }
83
+
84
+ function isObj(v) {
85
+ return v !== null && typeof v === "object" && !Array.isArray(v);
86
+ }
87
+
88
+ // Options:
89
+ // pinned Map from loadLocalKeySet(), or null
90
+ // issuerKeys relying party's pinned EXTERNAL issuer key set
91
+ // (external-decision.mjs loadPinnedIssuerKeySet),
92
+ // or null: external decisions are then NOT_ASSESSED
93
+ // externalAuthorizationIssuers issuers the relying party's assurance profile
94
+ // names: makes EXTERNAL_AUTHORIZATION required and
95
+ // only those issuers' decisions satisfy it
96
+ export function verifyLocalBundle(bundle, { pinned = null, issuerKeys = null, externalAuthorizationIssuers = [] } = {}) {
97
+ if (!Array.isArray(externalAuthorizationIssuers) || !externalAuthorizationIssuers.every((x) => typeof x === "string" && x)) {
98
+ throw new TypeError("externalAuthorizationIssuers must be an array of non-empty strings");
99
+ }
100
+ const opts = { externalAuthorizationIssuers };
101
+ const A = {};
102
+ const set = (a) => {
103
+ A[a.dimension] = a;
104
+ };
105
+ const integrityReasons = [];
106
+
107
+ // ---- 0. structure -------------------------------------------------------
108
+ const hasExternal = isObj(bundle) && Object.prototype.hasOwnProperty.call(bundle, "external_decisions");
109
+ const structOk = isObj(bundle)
110
+ && same(Object.keys(bundle).sort(), hasExternal ? [...BUNDLE_FIELDS, ...OPTIONAL_BUNDLE_FIELDS].sort() : BUNDLE_FIELDS)
111
+ && (!hasExternal || Array.isArray(bundle.external_decisions))
112
+ && bundle.schema_version === BUNDLE_SCHEMA
113
+ && typeof bundle.bundle_id === "string"
114
+ && Object.prototype.hasOwnProperty.call(PROFILES, bundle.assurance_profile)
115
+ && isObj(bundle.policy)
116
+ && ["mandates", "execution_reports", "effect_evidence", "source_observations"].every((k) => Array.isArray(bundle[k]))
117
+ && bundle.mandates.length === 1
118
+ && isObj(bundle.decision) && isObj(bundle.seal)
119
+ && bundle.source_observations.every(isObj);
120
+ if (!structOk) {
121
+ return finish(bundle, null, {
122
+ RECORD_INTEGRITY: assessment("RECORD_INTEGRITY", "FAILED", { reasons: ["BUNDLE_MALFORMED_OR_NOT_A_LOCAL_SANDBOX_BUNDLE"] }),
123
+ }, pinned, opts);
124
+ }
125
+ if (bundle.environment !== LOCAL_ENVIRONMENT || bundle.trust_bearing !== false) {
126
+ integrityReasons.push("BUNDLE_NOT_LABELLED_LOCAL_NON_TRUST_BEARING");
127
+ }
128
+
129
+ // ---- 1. signatures, roles, key validity ---------------------------------
130
+ const slots = [
131
+ ["mandates[0]", bundle.mandates[0], PAYLOAD_TYPES.MANDATE],
132
+ ["decision", bundle.decision, PAYLOAD_TYPES.DECISION],
133
+ ...bundle.execution_reports.map((e, i) => ["execution_reports[" + i + "]", e, PAYLOAD_TYPES.EXECUTION_REPORT]),
134
+ ...bundle.effect_evidence.map((e, i) => ["effect_evidence[" + i + "]", e, PAYLOAD_TYPES.EFFECT_EVIDENCE]),
135
+ ["seal", bundle.seal, PAYLOAD_TYPES.BUNDLE_SEAL],
136
+ ];
137
+ const authReasons = [];
138
+ const authResults = [];
139
+ const signers = new Map();
140
+ for (const [where, env, type] of slots) {
141
+ if (!isObj(env) || env.payload_type !== type) {
142
+ integrityReasons.push("PAYLOAD_TYPE_SLOT_MISMATCH:" + where);
143
+ authResults.push("FAILED");
144
+ continue;
145
+ }
146
+ const v = verifyEnvelope(env, { pinned });
147
+ if (v.integrity !== "VERIFIED") integrityReasons.push(v.reasons.join("|") + ":" + where);
148
+ authResults.push(v.authenticity);
149
+ if (v.authenticity !== "VERIFIED") {
150
+ authReasons.push(...v.reasons.map((r) => r + ":" + where + (v.key_id ? "(" + v.key_id + ")" : "")));
151
+ continue;
152
+ }
153
+ signers.set(env, v.signer);
154
+ const p = env.payload ?? {};
155
+ const named = type === PAYLOAD_TYPES.MANDATE ? p.issuer
156
+ : type === PAYLOAD_TYPES.EXECUTION_REPORT ? p.executor_principal
157
+ : type === PAYLOAD_TYPES.EFFECT_EVIDENCE ? p.retrieval_principal_ref
158
+ : v.signer.principal;
159
+ if (named !== v.signer.principal) {
160
+ authResults[authResults.length - 1] = "FAILED";
161
+ authReasons.push("SIGNER_PRINCIPAL_MISMATCH:" + where);
162
+ }
163
+ }
164
+ const authResult = authResults.includes("FAILED") ? "FAILED"
165
+ : authResults.includes("INSUFFICIENT_EVIDENCE") ? "INSUFFICIENT_EVIDENCE"
166
+ : authResults.includes("NOT_ASSESSED") ? "NOT_ASSESSED"
167
+ : "VERIFIED";
168
+ set(assessment("SIGNER_AUTHENTICITY", authResult, {
169
+ provenance: PROVENANCE.VERIFIER_COMPUTED,
170
+ reasons: [...new Set(authReasons)],
171
+ limitations: [],
172
+ detail: {
173
+ trust_anchors: pinned ? "LOCAL_KEY_SET (environment local, trust_bearing false)" : "NONE (integrity against self-asserted keys only)",
174
+ trust_bearing: false,
175
+ },
176
+ }));
177
+
178
+ // ---- 2. seal ------------------------------------------------------------
179
+ const seal = isObj(bundle.seal.payload) ? bundle.seal.payload : {};
180
+ try {
181
+ if (seal.bundle_id !== bundle.bundle_id) integrityReasons.push("SEAL_BUNDLE_ID_MISMATCH");
182
+ if (seal.bundle_schema_version !== bundle.schema_version) integrityReasons.push("SEAL_SCHEMA_MISMATCH");
183
+ if (seal.assurance_profile !== bundle.assurance_profile) integrityReasons.push("SEAL_PROFILE_MISMATCH");
184
+ if (seal.environment !== LOCAL_ENVIRONMENT || seal.trust_bearing !== false
185
+ || seal.environment !== bundle.environment || seal.trust_bearing !== bundle.trust_bearing) {
186
+ integrityReasons.push("SEAL_ENVIRONMENT_MISMATCH");
187
+ }
188
+ const comps = sealComponents(bundle);
189
+ // The component SET must match too: stripping an optional component (e.g.
190
+ // external_decisions) must not silently drop it from the check.
191
+ if (!same(Object.keys(comps).sort(), Object.keys(isObj(seal.components) ? seal.components : {}).sort())) {
192
+ integrityReasons.push("SEAL_COMPONENT_SET_MISMATCH");
193
+ }
194
+ for (const k of Object.keys(comps)) {
195
+ if (!same(comps[k], seal.components?.[k])) integrityReasons.push("SEAL_COMPONENT_MISMATCH:" + k);
196
+ }
197
+ } catch {
198
+ integrityReasons.push("SEAL_UNCOMPUTABLE");
199
+ }
200
+
201
+ // ---- 3. cross-component bindings ----------------------------------------
202
+ const d = isObj(bundle.decision.payload) ? bundle.decision.payload : {};
203
+ const reports = bundle.execution_reports.map((e) => (isObj(e?.payload) ? e.payload : {}));
204
+ const evidence = bundle.effect_evidence.map((e) => (isObj(e?.payload) ? e.payload : {}));
205
+ try {
206
+ const decisionDigest = envelopeDigest(bundle.decision);
207
+ if (d.policy_digest !== digest(bundle.policy)) integrityReasons.push("DECISION_POLICY_BINDING_MISMATCH");
208
+ if (!same(d.mandate_chain_digests, bundle.mandates.map(envelopeDigest))) {
209
+ integrityReasons.push("DECISION_MANDATE_BINDING_MISMATCH");
210
+ }
211
+ if (d.request_digest !== digest(d.request) || d.action_digest !== actionDigest(d.request)) {
212
+ integrityReasons.push("DECISION_REQUEST_BINDING_MISMATCH");
213
+ }
214
+ const reportDigests = bundle.execution_reports.map(envelopeDigest);
215
+ reports.forEach((r, i) => {
216
+ if (r.decision_id !== d.decision_id || r.decision_digest !== decisionDigest || r.action_digest !== d.action_digest) {
217
+ integrityReasons.push("REPORT_DECISION_BINDING_MISMATCH:" + i);
218
+ }
219
+ if (r.sequence !== i + 1) integrityReasons.push("REPORT_SEQUENCE_GAP:" + i);
220
+ });
221
+ const obsDigests = bundle.source_observations.map((o) => digest(o));
222
+ evidence.forEach((ev, i) => {
223
+ if (ev.decision_id !== d.decision_id || ev.decision_digest !== decisionDigest) {
224
+ integrityReasons.push("EVIDENCE_DECISION_BINDING_MISMATCH:" + i);
225
+ }
226
+ if (!reportDigests.includes(ev.execution_report_digest)) integrityReasons.push("EVIDENCE_REPORT_BINDING_MISMATCH:" + i);
227
+ if (!obsDigests.includes(ev.observation_digest)) integrityReasons.push("EVIDENCE_OBSERVATION_BINDING_MISMATCH:" + i);
228
+ });
229
+ if (hasExternal) {
230
+ bundle.external_decisions.forEach((x, i) => integrityReasons.push(...wrapperIntegrityReasons(x, d, i)));
231
+ }
232
+ } catch {
233
+ integrityReasons.push("BINDINGS_UNCOMPUTABLE");
234
+ }
235
+
236
+ set(assessment("RECORD_INTEGRITY", integrityReasons.length ? "FAILED" : "VERIFIED", {
237
+ provenance: PROVENANCE.VERIFIER_COMPUTED,
238
+ coverage: { scope: "COMPLETE", coverage_boundary: "Every component listed in the bundle seal." },
239
+ evidence_digests: [envelopeDigestSafe(bundle.seal)],
240
+ reasons: [...new Set(integrityReasons)],
241
+ }));
242
+
243
+ if (integrityReasons.length) {
244
+ return finish(bundle, d, A, pinned, opts);
245
+ }
246
+
247
+ const denied = d.outcome === "DENY";
248
+ const guard = (dimension, fn) => {
249
+ try {
250
+ set(fn());
251
+ } catch (err) {
252
+ set(assessment(dimension, "FAILED", { reasons: ["VERIFIER_EXCEPTION:" + err.message] }));
253
+ }
254
+ };
255
+
256
+ // ---- 4. AUTHORIZATION: re-evaluate, don't trust -------------------------
257
+ guard("AUTHORIZATION", () => {
258
+ const reasons = [];
259
+ const re = evaluate({
260
+ request: d.request,
261
+ mandate: bundle.mandates[0].payload,
262
+ policy: bundle.policy,
263
+ policyDigest: digest(bundle.policy),
264
+ at: d.decided_at,
265
+ });
266
+ for (const k of ["outcome", "reasons", "required_assurance_profile"]) {
267
+ if (!same(re[k], d[k])) reasons.push("DECISION_NOT_REPRODUCIBLE:" + k);
268
+ }
269
+ if (denied && (reports.length || evidence.length)) reasons.push("EXECUTED_DESPITE_DENIAL");
270
+ if (!denied && reports.length) {
271
+ // Strict timestamps (explicit offset; #491 parity); any unparseable one is outside.
272
+ const started = isoMs(reports[0].started_at);
273
+ const decidedAt = isoMs(d.decided_at);
274
+ const executeBefore = isoMs(d.execute_before);
275
+ if (started === null || decidedAt === null || executeBefore === null
276
+ || !(started >= decidedAt && started < executeBefore)) {
277
+ reasons.push("EXECUTION_OUTSIDE_DECISION_WINDOW");
278
+ }
279
+ }
280
+ return assessment("AUTHORIZATION", reasons.length ? "CONTRADICTED" : "VERIFIED", {
281
+ provenance: PROVENANCE.INTENTRAX_DECISION,
282
+ reasons,
283
+ evidence_digests: [envelopeDigest(bundle.decision), digest(bundle.policy)],
284
+ limitations: ["AGENT_IDENTITY_NOT_AUTHENTICATED", "POLICY_EVALUATOR_SHARED_WITH_ISSUER"],
285
+ detail: {
286
+ outcome: d.outcome,
287
+ decision_reasons: d.reasons,
288
+ decided_at: d.decided_at,
289
+ mandate_id: d.mandate_id,
290
+ policy: d.policy_id + "@" + d.policy_version,
291
+ signed_by: "local decision-service key (not trust-bearing)",
292
+ },
293
+ });
294
+ });
295
+
296
+ // ---- 5. EXECUTION_REPORTED / EXECUTION_ATTESTED -------------------------
297
+ const latestReportIdx = reports.length - 1;
298
+ const latestReport = reports[latestReportIdx] ?? null;
299
+ guard("EXECUTION_REPORTED", () => {
300
+ if (!latestReport) {
301
+ return assessment("EXECUTION_REPORTED", denied ? "NOT_APPLICABLE" : "INSUFFICIENT_EVIDENCE", {
302
+ reasons: denied ? ["DENIED_BEFORE_EXECUTION"] : ["NO_EXECUTION_REPORT"],
303
+ });
304
+ }
305
+ return assessment("EXECUTION_REPORTED", "REPORTED", {
306
+ provenance: PROVENANCE.SELF_REPORTED,
307
+ evidence_digests: bundle.execution_reports.map(envelopeDigest),
308
+ limitations: ["SELF_REPORTED_NOT_INDEPENDENT"],
309
+ detail: { status: latestReport.status, sequence: latestReport.sequence, downstream: latestReport.downstream },
310
+ });
311
+ });
312
+ set(assessment("EXECUTION_ATTESTED", denied ? "NOT_APPLICABLE" : "NOT_ASSESSED", {
313
+ reasons: denied ? [] : ["NO_IN_PATH_ENFORCEMENT_COMPONENT"],
314
+ }));
315
+
316
+ // ---- 6. EFFECT_OBSERVED / EFFECT_CONFIRMED: recompute -------------------
317
+ guard("EFFECT_OBSERVED", () => {
318
+ if (denied) {
319
+ set(assessment("EFFECT_CONFIRMED", "NOT_APPLICABLE", { reasons: ["DENIED_BEFORE_EXECUTION"] }));
320
+ return assessment("EFFECT_OBSERVED", "NOT_APPLICABLE", { reasons: ["DENIED_BEFORE_EXECUTION"] });
321
+ }
322
+ const latestDigest = latestReport ? envelopeDigest(bundle.execution_reports[latestReportIdx]) : null;
323
+ const candidates = bundle.effect_evidence
324
+ .map((env, i) => ({ env, ev: evidence[i] }))
325
+ .filter(({ ev }) => ev.execution_report_digest === latestDigest)
326
+ // Latest attestation wins; an unparseable attested_at sorts first, so it
327
+ // can never be picked over a well-formed one.
328
+ .map((c) => ({ ...c, at: isoMs(c.ev.attested_at) ?? -Infinity }))
329
+ .sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0));
330
+ if (!candidates.length) {
331
+ const reasons = [latestReport ? "NO_EFFECT_EVIDENCE_FOR_LATEST_REPORT" : "NO_EXECUTION_REPORT"];
332
+ set(assessment("EFFECT_CONFIRMED", "INSUFFICIENT_EVIDENCE", { reasons }));
333
+ return assessment("EFFECT_OBSERVED", "INSUFFICIENT_EVIDENCE", { reasons });
334
+ }
335
+ if (!pinned || A.SIGNER_AUTHENTICITY.result !== "VERIFIED") {
336
+ const reasons = [pinned ? "SIGNERS_NOT_AUTHENTICATED" : "NO_LOCAL_KEY_SET"];
337
+ set(assessment("EFFECT_CONFIRMED", "NOT_ASSESSED", { reasons }));
338
+ return assessment("EFFECT_OBSERVED", "NOT_ASSESSED", { reasons });
339
+ }
340
+ // Recompute EVERY evidence object bound to the latest report: a later read
341
+ // must not silently override an earlier one that disagrees.
342
+ const eff = effectFor(d.request.operation);
343
+ const recheck = ({ env, ev }) => {
344
+ const observation = bundle.source_observations.find((o) => digest(o) === ev.observation_digest) ?? null;
345
+ const evSigner = signers.get(env);
346
+ const re = assessEffect({
347
+ request: d.request,
348
+ report: latestReport,
349
+ retrievalMethod: ev.retrieval_method,
350
+ retrievalPrincipal: ev.retrieval_principal_ref,
351
+ expectedRetrievalPrincipal: evSigner && evSigner.role === ROLES.EFFECT_VERIFIER ? evSigner.principal : "(unknown)",
352
+ observation,
353
+ observedAt: ev.observed_at,
354
+ });
355
+ const mismatches = [];
356
+ const cmp = (name, signed, recomputed) => {
357
+ if (!same(signed, recomputed)) mismatches.push(name);
358
+ };
359
+ cmp("result", ev.result, re.result);
360
+ cmp("reasons", ev.reasons, re.reasons);
361
+ cmp("limitations", ev.limitations, re.limitations);
362
+ cmp("claimed_effect", ev.claimed_effect, { operation: d.request.operation, resource: d.request.resource, outcome: re.claimed_outcome });
363
+ cmp("expected_state_digest", ev.expected_state_digest, re.expected_state_digest);
364
+ cmp("observed_state_digest", ev.observed_state_digest, re.observed_state_digest);
365
+ cmp("evidence_digest", ev.evidence_digest, re.evidence_digest);
366
+ cmp("source_authentication", ev.source_authentication, re.source_authentication);
367
+ cmp("read_kind", ev.read_kind, observation ? observation.read_kind : null);
368
+ cmp("freshness", [ev.freshness?.finality, ev.freshness?.max_age_seconds], [re.finality, re.max_age_seconds]);
369
+ cmp("target", ev.resource_id, d.request.resource);
370
+ cmp("coverage_boundary", ev.coverage_boundary, eff.coverage_boundary);
371
+ return { ev, re, observation, mismatches };
372
+ };
373
+ const checked = candidates.map(recheck);
374
+ const broken = checked.find((c) => c.mismatches.length);
375
+ const { ev, re, observation } = checked[checked.length - 1];
376
+ const mismatches = broken ? broken.mismatches.map((m) => m + "@" + broken.ev.evidence_id) : [];
377
+ const finals = checked.filter((c) => c.re.result === "CONFIRMED" || c.re.result === "CONTRADICTED");
378
+ const conflict = new Set(finals.map((c) => c.re.result)).size > 1;
379
+
380
+ const provenance = re.source_authentication === "LOCAL_EFFECT_VERIFIER_READ" ? PROVENANCE.THIRD_PARTY_ATTESTED
381
+ : PROVENANCE.SELF_REPORTED;
382
+ const common = {
383
+ provenance,
384
+ coverage: { scope: "PARTIAL", coverage_boundary: ev.coverage_boundary },
385
+ freshness: { observed_at: ev.observed_at, max_age_seconds: re.max_age_seconds, finality: re.finality },
386
+ evidence_digests: [re.evidence_digest, re.expected_state_digest, re.observed_state_digest].filter(Boolean),
387
+ };
388
+ if (mismatches.length) {
389
+ const reasons = mismatches.map((m) => "SIGNED_EVIDENCE_DISAGREES_WITH_RECOMPUTATION:" + m);
390
+ set(assessment("EFFECT_CONFIRMED", "FAILED", { ...common, reasons }));
391
+ return assessment("EFFECT_OBSERVED", "FAILED", { ...common, reasons });
392
+ }
393
+ const lims = ["COVERAGE_PARTIAL", ...re.limitations];
394
+ set(assessment("EFFECT_CONFIRMED", conflict ? "CONTRADICTED" : re.result, {
395
+ ...common,
396
+ provenance: PROVENANCE.VERIFIER_COMPUTED,
397
+ reasons: conflict ? ["CONFLICTING_OBSERVATIONS", ...re.reasons] : re.reasons,
398
+ limitations: lims,
399
+ detail: {
400
+ claimed_outcome: re.claimed_outcome,
401
+ compared: "expected_state_digest (from the signed decision) vs observed_state_digest (from the read)",
402
+ read_provenance: provenance,
403
+ observations: checked.map((c) => ({ evidence_id: c.ev.evidence_id, observed_at: c.ev.observed_at, result: c.re.result })),
404
+ },
405
+ }));
406
+ return assessment("EFFECT_OBSERVED", re.observed_result, {
407
+ ...common,
408
+ reasons: re.reasons,
409
+ limitations: lims,
410
+ detail: {
411
+ retrieval_method: ev.retrieval_method,
412
+ retrieval_principal_ref: ev.retrieval_principal_ref,
413
+ read_kind: observation ? observation.read_kind : null,
414
+ source_authentication: re.source_authentication,
415
+ check_module: observation ? observation.check_module : null,
416
+ },
417
+ });
418
+ });
419
+
420
+ // ---- 7. CAUSAL_CHAIN ----------------------------------------------------
421
+ set(assessment("CAUSAL_CHAIN", "NOT_APPLICABLE", { reasons: ["SINGLE_MANDATE_NO_BUDGET"] }));
422
+
423
+ // ---- 8. EXTERNAL_AUTHORIZATION (optional; B3) ---------------------------
424
+ // Evidence, never trust: verified only against the relying party's pinned
425
+ // issuer keys, and it never alters AUTHORIZATION above.
426
+ if (hasExternal || externalAuthorizationIssuers.length) {
427
+ guard("EXTERNAL_AUTHORIZATION", () => {
428
+ const body = assessExternalAuthorization({
429
+ wrappers: hasExternal ? bundle.external_decisions : [],
430
+ d,
431
+ reports,
432
+ effectConfirmed: A.EFFECT_CONFIRMED?.result ?? null,
433
+ issuerKeys,
434
+ authorizationIssuers: externalAuthorizationIssuers,
435
+ });
436
+ return assessment("EXTERNAL_AUTHORIZATION", body.result, body);
437
+ });
438
+ }
439
+
440
+ return finish(bundle, d, A, pinned, opts);
441
+ }
442
+
443
+ function envelopeDigestSafe(env) {
444
+ try {
445
+ return envelopeDigest(env);
446
+ } catch {
447
+ return null;
448
+ }
449
+ }
450
+
451
+ function finish(bundle, d, A, pinned, opts = {}) {
452
+ const externalIssuers = opts.externalAuthorizationIssuers ?? [];
453
+ const external = externalIssuers.length > 0
454
+ || (isObj(bundle) && Object.prototype.hasOwnProperty.call(bundle, "external_decisions"));
455
+ // Optional dimensions appear only when relevant, so ordinary reports keep
456
+ // exactly the eight core dimensions.
457
+ const dims = [...DIMENSIONS, ...OPTIONAL_DIMENSIONS.filter((x) => x === "EXTERNAL_AUTHORIZATION" && external)];
458
+ for (const dim of dims) {
459
+ if (!A[dim]) A[dim] = assessment(dim, "NOT_ASSESSED", { reasons: ["NOT_REACHED"] });
460
+ }
461
+ const declared = isObj(bundle) && Object.prototype.hasOwnProperty.call(PROFILES, bundle.assurance_profile)
462
+ ? bundle.assurance_profile
463
+ : "DECISION_RECORD";
464
+ const required = d && Object.prototype.hasOwnProperty.call(PROFILES, d.required_assurance_profile)
465
+ ? d.required_assurance_profile
466
+ : declared;
467
+ const profile = strongerProfile(declared, required);
468
+ const extraRequired = externalIssuers.length ? ["EXTERNAL_AUTHORIZATION"] : [];
469
+ const results = Object.fromEntries(dims.map((k) => [k, A[k].result]));
470
+ const uncapped = deriveVerdict(results, profile, { extraRequired });
471
+ const verdict = applyLocalCeiling(uncapped);
472
+ const effectOutcome = A.EFFECT_CONFIRMED.result === "CONFIRMED" ? A.EFFECT_CONFIRMED.detail?.claimed_outcome ?? null : null;
473
+ const decisionOutcome = d && typeof d.outcome === "string" ? d.outcome : null;
474
+ const summaryParts = [verdict + "(" + profile + ")"];
475
+ if (decisionOutcome) summaryParts.push("decision " + decisionOutcome + (d.reasons?.length ? " [" + d.reasons.join(",") + "]" : ""));
476
+ summaryParts.push("EFFECT_CONFIRMED " + A.EFFECT_CONFIRMED.result);
477
+ if (external) {
478
+ const outcomes = (A.EXTERNAL_AUTHORIZATION.detail?.decisions ?? [])
479
+ .filter((x) => x.signature === "VALID_PINNED_KEY" && x.outcome).map((x) => x.outcome + " by " + x.issuer);
480
+ summaryParts.push("external " + A.EXTERNAL_AUTHORIZATION.result + (outcomes.length ? " [" + outcomes.join(",") + "]" : ""));
481
+ }
482
+ const lims = new Map();
483
+ for (const l of GLOBAL_LIMITATIONS) lims.set(l.code, l);
484
+ for (const dim of dims) for (const l of A[dim].limitations) lims.set(l.code, l);
485
+ return {
486
+ schema_version: REPORT_SCHEMA,
487
+ bundle_id: isObj(bundle) ? bundle.bundle_id ?? null : null,
488
+ environment: LOCAL_ENVIRONMENT,
489
+ trust_bearing: false,
490
+ production_assurance: false,
491
+ trust_anchors: pinned ? "LOCAL_KEY_SET" : "NONE",
492
+ assurance_profile: profile,
493
+ required_dimensions: [...new Set([...PROFILES[profile], ...extraRequired])],
494
+ verdict,
495
+ verdict_ceiling: LOCAL_VERDICT_CEILING,
496
+ uncapped_verdict: uncapped,
497
+ decision_outcome: decisionOutcome,
498
+ effect_outcome: effectOutcome,
499
+ summary: summaryParts.join(" · "),
500
+ assessments: dims.map((k) => A[k]),
501
+ limitations: [...lims.values()],
502
+ };
503
+ }