@emilia-protocol/gate 0.11.0 → 0.13.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.
- package/CHANGELOG.md +58 -0
- package/README.md +252 -0
- package/action-control-manifest.js +3 -268
- package/action-escrow-custodian.js +3 -394
- package/action-escrow-evidence.js +3 -858
- package/action-escrow-package.js +3 -1668
- package/action-escrow-postgres.js +3 -337
- package/action-escrow-state.js +3 -396
- package/action-escrow-verifiers.js +3 -331
- package/action-escrow.js +3 -2447
- package/action-packs.js +3 -140
- package/adapters/_kit.js +3 -104
- package/adapters/aws.js +3 -108
- package/adapters/cloudflare.js +3 -54
- package/adapters/gcp.js +3 -70
- package/adapters/github.js +3 -109
- package/adapters/jira.js +3 -55
- package/adapters/k8s.js +3 -70
- package/adapters/linear.js +3 -55
- package/adapters/salesforce.js +3 -55
- package/adapters/stripe.js +3 -81
- package/adapters/supabase.js +3 -121
- package/adapters/terraform.js +3 -59
- package/adapters/vercel.js +3 -84
- package/aec-execution.js +3 -312
- package/breakglass.js +3 -582
- package/capability-receipt.js +4 -0
- package/cf1-conformance.js +3 -106
- package/challenge-store.js +3 -69
- package/control-plane.js +3 -340
- package/coverage.js +3 -721
- package/demo.mjs +1 -1
- package/deployment-attestation.js +3 -247
- package/dist/action-control-manifest.d.ts +82 -0
- package/dist/action-control-manifest.d.ts.map +1 -0
- package/dist/action-control-manifest.js +422 -0
- package/dist/action-control-manifest.js.map +1 -0
- package/dist/action-escrow-custodian.d.ts +74 -0
- package/dist/action-escrow-custodian.d.ts.map +1 -0
- package/dist/action-escrow-custodian.js +363 -0
- package/dist/action-escrow-custodian.js.map +1 -0
- package/dist/action-escrow-evidence.d.ts +130 -0
- package/dist/action-escrow-evidence.d.ts.map +1 -0
- package/dist/action-escrow-evidence.js +1012 -0
- package/dist/action-escrow-evidence.js.map +1 -0
- package/dist/action-escrow-package.d.ts +10 -0
- package/dist/action-escrow-package.d.ts.map +1 -0
- package/dist/action-escrow-package.js +1583 -0
- package/dist/action-escrow-package.js.map +1 -0
- package/dist/action-escrow-postgres.d.ts +62 -0
- package/dist/action-escrow-postgres.d.ts.map +1 -0
- package/dist/action-escrow-postgres.js +339 -0
- package/dist/action-escrow-postgres.js.map +1 -0
- package/dist/action-escrow-state.d.ts +141 -0
- package/dist/action-escrow-state.d.ts.map +1 -0
- package/dist/action-escrow-state.js +413 -0
- package/dist/action-escrow-state.js.map +1 -0
- package/dist/action-escrow-verifiers.d.ts +65 -0
- package/dist/action-escrow-verifiers.d.ts.map +1 -0
- package/dist/action-escrow-verifiers.js +421 -0
- package/dist/action-escrow-verifiers.js.map +1 -0
- package/dist/action-escrow.d.ts +112 -0
- package/dist/action-escrow.d.ts.map +1 -0
- package/dist/action-escrow.js +2661 -0
- package/dist/action-escrow.js.map +1 -0
- package/dist/action-packs.d.ts +54 -0
- package/dist/action-packs.d.ts.map +1 -0
- package/dist/action-packs.js +143 -0
- package/dist/action-packs.js.map +1 -0
- package/dist/adapters/_kit.d.ts +50 -0
- package/dist/adapters/_kit.d.ts.map +1 -0
- package/dist/adapters/_kit.js +98 -0
- package/dist/adapters/_kit.js.map +1 -0
- package/dist/adapters/aws.d.ts +158 -0
- package/dist/adapters/aws.d.ts.map +1 -0
- package/dist/adapters/aws.js +136 -0
- package/dist/adapters/aws.js.map +1 -0
- package/dist/adapters/cloudflare.d.ts +116 -0
- package/dist/adapters/cloudflare.d.ts.map +1 -0
- package/dist/adapters/cloudflare.js +75 -0
- package/dist/adapters/cloudflare.js.map +1 -0
- package/dist/adapters/gcp.d.ts +139 -0
- package/dist/adapters/gcp.d.ts.map +1 -0
- package/dist/adapters/gcp.js +69 -0
- package/dist/adapters/gcp.js.map +1 -0
- package/dist/adapters/github.d.ts +123 -0
- package/dist/adapters/github.d.ts.map +1 -0
- package/dist/adapters/github.js +105 -0
- package/dist/adapters/github.js.map +1 -0
- package/dist/adapters/jira.d.ts +109 -0
- package/dist/adapters/jira.d.ts.map +1 -0
- package/dist/adapters/jira.js +54 -0
- package/dist/adapters/jira.js.map +1 -0
- package/dist/adapters/k8s.d.ts +139 -0
- package/dist/adapters/k8s.d.ts.map +1 -0
- package/dist/adapters/k8s.js +69 -0
- package/dist/adapters/k8s.js.map +1 -0
- package/dist/adapters/linear.d.ts +109 -0
- package/dist/adapters/linear.d.ts.map +1 -0
- package/dist/adapters/linear.js +54 -0
- package/dist/adapters/linear.js.map +1 -0
- package/dist/adapters/salesforce.d.ts +109 -0
- package/dist/adapters/salesforce.d.ts.map +1 -0
- package/dist/adapters/salesforce.js +54 -0
- package/dist/adapters/salesforce.js.map +1 -0
- package/dist/adapters/stripe.d.ts +116 -0
- package/dist/adapters/stripe.d.ts.map +1 -0
- package/dist/adapters/stripe.js +77 -0
- package/dist/adapters/stripe.js.map +1 -0
- package/dist/adapters/supabase.d.ts +127 -0
- package/dist/adapters/supabase.d.ts.map +1 -0
- package/dist/adapters/supabase.js +112 -0
- package/dist/adapters/supabase.js.map +1 -0
- package/dist/adapters/terraform.d.ts +109 -0
- package/dist/adapters/terraform.d.ts.map +1 -0
- package/dist/adapters/terraform.js +58 -0
- package/dist/adapters/terraform.js.map +1 -0
- package/dist/adapters/vercel.d.ts +114 -0
- package/dist/adapters/vercel.d.ts.map +1 -0
- package/dist/adapters/vercel.js +81 -0
- package/dist/adapters/vercel.js.map +1 -0
- package/dist/aec-execution.d.ts +107 -0
- package/dist/aec-execution.d.ts.map +1 -0
- package/dist/aec-execution.js +334 -0
- package/dist/aec-execution.js.map +1 -0
- package/dist/breakglass.d.ts +205 -0
- package/dist/breakglass.d.ts.map +1 -0
- package/dist/breakglass.js +627 -0
- package/dist/breakglass.js.map +1 -0
- package/dist/capability-receipt.d.ts +601 -0
- package/dist/capability-receipt.d.ts.map +1 -0
- package/dist/capability-receipt.js +1177 -0
- package/dist/capability-receipt.js.map +1 -0
- package/dist/cf1-conformance.d.ts +83 -0
- package/dist/cf1-conformance.d.ts.map +1 -0
- package/dist/cf1-conformance.js +94 -0
- package/dist/cf1-conformance.js.map +1 -0
- package/dist/challenge-store.d.ts +20 -0
- package/dist/challenge-store.d.ts.map +1 -0
- package/dist/challenge-store.js +62 -0
- package/dist/challenge-store.js.map +1 -0
- package/dist/control-plane.d.ts +136 -0
- package/dist/control-plane.d.ts.map +1 -0
- package/dist/control-plane.js +349 -0
- package/dist/control-plane.js.map +1 -0
- package/dist/coverage.d.ts +156 -0
- package/dist/coverage.d.ts.map +1 -0
- package/dist/coverage.js +768 -0
- package/dist/coverage.js.map +1 -0
- package/dist/deployment-attestation.d.ts +93 -0
- package/dist/deployment-attestation.d.ts.map +1 -0
- package/dist/deployment-attestation.js +262 -0
- package/dist/deployment-attestation.js.map +1 -0
- package/dist/eg1-conformance.d.ts +286 -0
- package/dist/eg1-conformance.d.ts.map +1 -0
- package/dist/eg1-conformance.js +379 -0
- package/dist/eg1-conformance.js.map +1 -0
- package/dist/enterprise.d.ts +88 -0
- package/dist/enterprise.d.ts.map +1 -0
- package/dist/enterprise.js +194 -0
- package/dist/enterprise.js.map +1 -0
- package/dist/evidence-postgres.d.ts +123 -0
- package/dist/evidence-postgres.d.ts.map +1 -0
- package/dist/evidence-postgres.js +343 -0
- package/dist/evidence-postgres.js.map +1 -0
- package/dist/evidence.d.ts +113 -0
- package/dist/evidence.d.ts.map +1 -0
- package/dist/evidence.js +369 -0
- package/dist/evidence.js.map +1 -0
- package/dist/execution-binding.d.ts +49 -0
- package/dist/execution-binding.d.ts.map +1 -0
- package/dist/execution-binding.js +243 -0
- package/dist/execution-binding.js.map +1 -0
- package/dist/formal-runtime-map.d.ts +42 -0
- package/dist/formal-runtime-map.d.ts.map +1 -0
- package/dist/formal-runtime-map.js +23 -0
- package/dist/formal-runtime-map.js.map +1 -0
- package/dist/index.d.ts +1002 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1736 -0
- package/dist/index.js.map +1 -0
- package/dist/key-registry.d.ts +60 -0
- package/dist/key-registry.d.ts.map +1 -0
- package/dist/key-registry.js +144 -0
- package/dist/key-registry.js.map +1 -0
- package/dist/mcp.d.ts +53 -0
- package/dist/mcp.d.ts.map +1 -0
- package/dist/mcp.js +112 -0
- package/dist/mcp.js.map +1 -0
- package/dist/metering.d.ts +80 -0
- package/dist/metering.d.ts.map +1 -0
- package/dist/metering.js +227 -0
- package/dist/metering.js.map +1 -0
- package/dist/metrics.d.ts +68 -0
- package/dist/metrics.d.ts.map +1 -0
- package/dist/metrics.js +242 -0
- package/dist/metrics.js.map +1 -0
- package/dist/network-witness.d.ts +167 -0
- package/dist/network-witness.d.ts.map +1 -0
- package/dist/network-witness.js +520 -0
- package/dist/network-witness.js.map +1 -0
- package/dist/protocol-state.d.ts +141 -0
- package/dist/protocol-state.d.ts.map +1 -0
- package/dist/protocol-state.js +106 -0
- package/dist/protocol-state.js.map +1 -0
- package/dist/receipt-program.d.ts +59 -0
- package/dist/receipt-program.d.ts.map +1 -0
- package/dist/receipt-program.js +1053 -0
- package/dist/receipt-program.js.map +1 -0
- package/dist/reliance-kernel.d.ts +66 -0
- package/dist/reliance-kernel.d.ts.map +1 -0
- package/dist/reliance-kernel.js +103 -0
- package/dist/reliance-kernel.js.map +1 -0
- package/dist/reliance-packet.d.ts +67 -0
- package/dist/reliance-packet.d.ts.map +1 -0
- package/dist/reliance-packet.js +176 -0
- package/dist/reliance-packet.js.map +1 -0
- package/dist/remedy-program-postgres.d.ts +37 -0
- package/dist/remedy-program-postgres.d.ts.map +1 -0
- package/dist/remedy-program-postgres.js +291 -0
- package/dist/remedy-program-postgres.js.map +1 -0
- package/dist/remedy-program-receipt.d.ts +97 -0
- package/dist/remedy-program-receipt.d.ts.map +1 -0
- package/dist/remedy-program-receipt.js +817 -0
- package/dist/remedy-program-receipt.js.map +1 -0
- package/dist/remedy-program.d.ts +76 -0
- package/dist/remedy-program.d.ts.map +1 -0
- package/dist/remedy-program.js +1346 -0
- package/dist/remedy-program.js.map +1 -0
- package/dist/reports/art14.d.ts +101 -0
- package/dist/reports/art14.d.ts.map +1 -0
- package/dist/reports/art14.js +340 -0
- package/dist/reports/art14.js.map +1 -0
- package/dist/reports/assurance-package.d.ts +197 -0
- package/dist/reports/assurance-package.d.ts.map +1 -0
- package/dist/reports/assurance-package.js +313 -0
- package/dist/reports/assurance-package.js.map +1 -0
- package/dist/reports/auditor-workpaper.d.ts +194 -0
- package/dist/reports/auditor-workpaper.d.ts.map +1 -0
- package/dist/reports/auditor-workpaper.js +545 -0
- package/dist/reports/auditor-workpaper.js.map +1 -0
- package/dist/reports/external-verification.d.ts +76 -0
- package/dist/reports/external-verification.d.ts.map +1 -0
- package/dist/reports/external-verification.js +209 -0
- package/dist/reports/external-verification.js.map +1 -0
- package/dist/reports/reperform.d.ts +122 -0
- package/dist/reports/reperform.d.ts.map +1 -0
- package/dist/reports/reperform.js +432 -0
- package/dist/reports/reperform.js.map +1 -0
- package/dist/reports/underwriter.d.ts +127 -0
- package/dist/reports/underwriter.d.ts.map +1 -0
- package/dist/reports/underwriter.js +348 -0
- package/dist/reports/underwriter.js.map +1 -0
- package/dist/retention.d.ts +88 -0
- package/dist/retention.d.ts.map +1 -0
- package/dist/retention.js +90 -0
- package/dist/retention.js.map +1 -0
- package/dist/roster.d.ts +113 -0
- package/dist/roster.d.ts.map +1 -0
- package/dist/roster.js +261 -0
- package/dist/roster.js.map +1 -0
- package/dist/runtime-monitor.d.ts +132 -0
- package/dist/runtime-monitor.d.ts.map +1 -0
- package/dist/runtime-monitor.js +197 -0
- package/dist/runtime-monitor.js.map +1 -0
- package/dist/settlement.d.ts +68 -0
- package/dist/settlement.d.ts.map +1 -0
- package/dist/settlement.js +306 -0
- package/dist/settlement.js.map +1 -0
- package/dist/siem.d.ts +261 -0
- package/dist/siem.d.ts.map +1 -0
- package/dist/siem.js +247 -0
- package/dist/siem.js.map +1 -0
- package/dist/store-postgres.d.ts +107 -0
- package/dist/store-postgres.d.ts.map +1 -0
- package/dist/store-postgres.js +152 -0
- package/dist/store-postgres.js.map +1 -0
- package/dist/store.d.ts +95 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/store.js +202 -0
- package/dist/store.js.map +1 -0
- package/dist/strict-json.d.ts +14 -0
- package/dist/strict-json.d.ts.map +1 -0
- package/dist/strict-json.js +132 -0
- package/dist/strict-json.js.map +1 -0
- package/dist/trust-program-adapters.d.ts +122 -0
- package/dist/trust-program-adapters.d.ts.map +1 -0
- package/dist/trust-program-adapters.js +802 -0
- package/dist/trust-program-adapters.js.map +1 -0
- package/dist/trust-program-postgres.d.ts +41 -0
- package/dist/trust-program-postgres.d.ts.map +1 -0
- package/dist/trust-program-postgres.js +346 -0
- package/dist/trust-program-postgres.js.map +1 -0
- package/dist/trust-program-revocation.d.ts +206 -0
- package/dist/trust-program-revocation.d.ts.map +1 -0
- package/dist/trust-program-revocation.js +600 -0
- package/dist/trust-program-revocation.js.map +1 -0
- package/dist/trust-program.d.ts +197 -0
- package/dist/trust-program.d.ts.map +1 -0
- package/dist/trust-program.js +1351 -0
- package/dist/trust-program.js.map +1 -0
- package/dist/witness-postgres.d.ts +43 -0
- package/dist/witness-postgres.d.ts.map +1 -0
- package/dist/witness-postgres.js +92 -0
- package/dist/witness-postgres.js.map +1 -0
- package/dist/zk-range-proof.d.ts +78 -0
- package/dist/zk-range-proof.d.ts.map +1 -0
- package/dist/zk-range-proof.js +228 -0
- package/dist/zk-range-proof.js.map +1 -0
- package/eg1-conformance.js +3 -404
- package/enterprise.js +3 -180
- package/ep-assure.mjs +1 -0
- package/evidence-postgres.js +3 -356
- package/evidence.js +4 -360
- package/execution-binding.js +3 -212
- package/formal-runtime-map.js +4 -0
- package/index.js +4 -1249
- package/key-registry.js +3 -134
- package/mcp.js +3 -109
- package/metering.js +3 -226
- package/metrics.js +3 -231
- package/network-witness.js +3 -499
- package/package.json +31 -2
- package/receipt-program.js +4 -0
- package/reliance-kernel.js +3 -112
- package/reliance-packet.js +3 -175
- package/remedy-program-postgres.js +4 -0
- package/remedy-program-receipt.js +4 -0
- package/remedy-program.js +4 -0
- package/reports/art14.js +0 -0
- package/reports/assurance-package.js +2 -312
- package/reports/auditor-workpaper.js +3 -537
- package/reports/external-verification.js +3 -222
- package/reports/reperform.js +3 -424
- package/reports/underwriter.js +3 -339
- package/retention.js +3 -84
- package/roster.js +3 -264
- package/runtime-monitor.js +4 -0
- package/settlement.js +3 -299
- package/siem.js +3 -235
- package/src/action-control-manifest.ts +424 -0
- package/src/action-escrow-custodian.ts +427 -0
- package/src/action-escrow-evidence.ts +1178 -0
- package/src/action-escrow-package.ts +1821 -0
- package/src/action-escrow-postgres.ts +366 -0
- package/src/action-escrow-state.ts +498 -0
- package/src/action-escrow-verifiers.ts +484 -0
- package/src/action-escrow.ts +3039 -0
- package/src/action-packs.ts +170 -0
- package/src/adapters/_kit.ts +117 -0
- package/src/adapters/aws.ts +142 -0
- package/src/adapters/cloudflare.ts +78 -0
- package/src/adapters/gcp.ts +71 -0
- package/src/adapters/github.ts +110 -0
- package/src/adapters/jira.ts +56 -0
- package/src/adapters/k8s.ts +71 -0
- package/src/adapters/linear.ts +56 -0
- package/src/adapters/salesforce.ts +56 -0
- package/src/adapters/stripe.ts +82 -0
- package/src/adapters/supabase.ts +122 -0
- package/src/adapters/terraform.ts +60 -0
- package/src/adapters/vercel.ts +85 -0
- package/src/aec-execution.ts +354 -0
- package/src/breakglass.ts +647 -0
- package/src/capability-receipt.ts +1258 -0
- package/src/cf1-conformance.ts +120 -0
- package/src/challenge-store.ts +70 -0
- package/src/control-plane.ts +374 -0
- package/src/coverage.ts +832 -0
- package/src/deployment-attestation.ts +259 -0
- package/src/eg1-conformance.ts +471 -0
- package/src/enterprise.ts +195 -0
- package/src/evidence-postgres.ts +374 -0
- package/src/evidence.ts +367 -0
- package/src/execution-binding.ts +236 -0
- package/src/formal-runtime-map.ts +24 -0
- package/src/index.ts +2122 -0
- package/src/key-registry.ts +150 -0
- package/src/mcp.ts +120 -0
- package/src/metering.ts +237 -0
- package/src/metrics.ts +232 -0
- package/src/network-witness.ts +585 -0
- package/src/protocol-state.ts +143 -0
- package/src/protocol-state.typecheck.ts +94 -0
- package/src/receipt-program.ts +1105 -0
- package/src/reliance-kernel.ts +119 -0
- package/src/reliance-packet.ts +206 -0
- package/src/remedy-program-postgres.ts +367 -0
- package/src/remedy-program-receipt.ts +891 -0
- package/src/remedy-program.ts +1388 -0
- package/src/reports/art14.ts +361 -0
- package/src/reports/assurance-package.ts +330 -0
- package/src/reports/auditor-workpaper.ts +558 -0
- package/src/reports/external-verification.ts +232 -0
- package/src/reports/reperform.ts +441 -0
- package/src/reports/underwriter.ts +356 -0
- package/src/retention.ts +100 -0
- package/src/roster.ts +273 -0
- package/src/runtime-monitor.ts +217 -0
- package/src/settlement.ts +313 -0
- package/src/siem.ts +247 -0
- package/src/store-postgres.ts +167 -0
- package/src/store.ts +214 -0
- package/src/strict-json.ts +115 -0
- package/src/trust-program-adapters.ts +847 -0
- package/src/trust-program-postgres.ts +429 -0
- package/src/trust-program-revocation.ts +751 -0
- package/src/trust-program.ts +1460 -0
- package/src/witness-postgres.ts +106 -0
- package/src/zk-range-proof.ts +250 -0
- package/store-postgres.js +3 -161
- package/store.js +4 -198
- package/strict-json.js +3 -102
- package/trust-program-adapters.js +4 -0
- package/trust-program-postgres.js +4 -0
- package/trust-program-revocation.js +4 -0
- package/trust-program.js +4 -0
- package/witness-postgres.js +3 -96
- package/zk-range-proof.js +4 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1736 @@
|
|
|
1
|
+
// @ts-nocheck
|
|
2
|
+
/**
|
|
3
|
+
* @emilia-protocol/gate — EMILIA Gate: the Consequence Firewall.
|
|
4
|
+
* @license Apache-2.0
|
|
5
|
+
*
|
|
6
|
+
* Deny-by-default enforcement for consequential machine actions. A guarded
|
|
7
|
+
* action runs ONLY if it arrives with a receipt that is:
|
|
8
|
+
* 1. valid — Ed25519 over canonical JSON, signed by a pinned issuer;
|
|
9
|
+
* 2. in-scope — bound to the exact action the manifest guards;
|
|
10
|
+
* 3. sufficiently — meets the action's required assurance tier, and the
|
|
11
|
+
* assured credited tier is CRYPTOGRAPHICALLY VERIFIED, not read
|
|
12
|
+
* from self-asserted payload fields: class_a requires a
|
|
13
|
+
* valid WebAuthn device signoff, quorum requires a valid
|
|
14
|
+
* EP-QUORUM-v1 (distinct humans + distinct keys +
|
|
15
|
+
* threshold + per-signer assertions);
|
|
16
|
+
* 4. fresh — within max age; and
|
|
17
|
+
* 5. unused — not a replay (one-time consumption).
|
|
18
|
+
* Otherwise it is refused with a machine-readable Receipt-Required challenge
|
|
19
|
+
* (HTTP 428). Every decision is appended to a tamper-evident evidence log.
|
|
20
|
+
*
|
|
21
|
+
* It is NOT authentication ("who are you") and NOT permissions ("are you
|
|
22
|
+
* allowed here"). It is a policy-enforcement point that requires portable proof
|
|
23
|
+
* a named human authorized THIS exact action before the world is mutated.
|
|
24
|
+
*
|
|
25
|
+
* Composes @emilia-protocol/require-receipt (manifest + verify + challenge) and
|
|
26
|
+
* adds the three things a firewall needs over a bare verifier: assurance-tier
|
|
27
|
+
* enforcement, replay defense, and the evidence log. Fails closed.
|
|
28
|
+
*/
|
|
29
|
+
import crypto from 'node:crypto';
|
|
30
|
+
import { verifyEmiliaReceipt, receiptChallenge, receiptRequiredHeader, validateActionRiskManifest, findActionRequirement, evaluateReceiptAssurance, validatePinnedQuorumPolicy, receiptAssuranceTier as receiptAssuranceTierFromProof, parseReceiptCarrier, RECEIPT_REQUIRED_STATUS, RECEIPT_REQUIRED_HEADER, } from '@emilia-protocol/require-receipt';
|
|
31
|
+
import { verifyWebAuthnSignoff, verifyQuorum } from '@emilia-protocol/verify';
|
|
32
|
+
import { MemoryConsumptionStore, isSecureConsumptionStore } from './store.js';
|
|
33
|
+
import { canonicalEvidenceJson, createAtomicEvidenceLog, createEvidenceLog, createMemoryAtomicEvidenceBackend, } from './evidence.js';
|
|
34
|
+
import { DEFAULT_GATE_MANIFEST, HIGH_RISK_ACTION_PACKS, createDefaultActionRiskManifest } from './action-packs.js';
|
|
35
|
+
import { hashCanonical, verifyExecutionBinding } from './execution-binding.js';
|
|
36
|
+
import { buildReliancePacket, ADMISSIBILITY_VERDICTS } from './reliance-packet.js';
|
|
37
|
+
import { createEg1Harness, makeGateInvoke, runEg1, EG1_DEFAULT_SELECTOR } from './eg1-conformance.js';
|
|
38
|
+
import { CF1_VERSION, CF1_CHECKS, runCf1 } from './cf1-conformance.js';
|
|
39
|
+
import { createKeyRegistry, asKeyRegistry } from './key-registry.js';
|
|
40
|
+
import { classifyRetention, buildRetentionExport } from './retention.js';
|
|
41
|
+
import { ACTION_CONTROL_MANIFEST_VERSION, createDefaultActionControlManifest, findActionControl, resolveActionControl, validateActionControlManifest, } from './action-control-manifest.js';
|
|
42
|
+
import { createRuntimeMonitor, RUNTIME_MONITOR_VERSION, RUNTIME_MONITOR_MODES, RUNTIME_INVARIANTS, } from './runtime-monitor.js';
|
|
43
|
+
import { FORMAL_RUNTIME_BRIDGE_VERSION, FORMAL_RUNTIME_SPEC, FORMAL_RUNTIME_CONFIG, FORMAL_RUNTIME_INVARIANT_MAP, } from './formal-runtime-map.js';
|
|
44
|
+
import { CAPABILITY_RECEIPT_VERSION, CAPABILITY_STATE_VERSION, CAPABILITY_SHARE_VERSION, CAPABILITY_SCOPE_PROFILE, CAPABILITY_CAID_SCOPE_PROFILE, CAPABILITY_STATE_DDL, CAPABILITY_SQL, capabilityBaseReceiptDigest, capabilityActionDigest, verifyCapabilityScope, mintCapabilityReceipt, verifyCapabilityReceipt, splitCapabilitySecret, reconstructCapabilitySecret, createMemoryCapabilityStore, createPostgresCapabilityStore, executeWithCapability, executeWithThreshold, reconcileCapabilityOperation, } from './capability-receipt.js';
|
|
45
|
+
import { ZK_RANGE_RECEIPT_VERSION, ZK_RANGE_SCHEME, ZK_RANGE_BACKEND_PACKAGE, deriveZkRangeBases, loadBulletproofBackend, mintZkRangeReceipt, verifyZkRangeReceipt, } from './zk-range-proof.js';
|
|
46
|
+
import { mintBreakGlassAuthorization, verifyBreakGlass, consumeBreakGlass, buildBreakGlassEvidence, runBreakGlass, BREAKGLASS_VERSION, BREAKGLASS_EVIDENCE_KIND, } from './breakglass.js';
|
|
47
|
+
export { MemoryConsumptionStore, canonicalEvidenceJson, createEvidenceLog, createAtomicEvidenceLog, createMemoryAtomicEvidenceBackend, };
|
|
48
|
+
export { createDurableConsumptionStore, createMemoryBackend, isSecureConsumptionStore, DURABLE_CONSUMPTION_VERSION, } from './store.js';
|
|
49
|
+
export { createDurableChallengeStore, challengeStorageKey, challengeBodyDigest, DURABLE_CHALLENGE_STORE_VERSION } from './challenge-store.js';
|
|
50
|
+
export { createKeyRegistry, asKeyRegistry } from './key-registry.js';
|
|
51
|
+
export { classifyRetention, buildRetentionExport, RETENTION_EXPORT_VERSION } from './retention.js';
|
|
52
|
+
export { DEFAULT_GATE_MANIFEST, HIGH_RISK_ACTION_PACKS, createDefaultActionRiskManifest };
|
|
53
|
+
export { ACTION_CONTROL_MANIFEST_VERSION, ACTION_CONTROL_SCHEMA_URL, ACTION_CONTROL_CONFORMANCE_LEVEL, ACTION_CONTROL_DEFAULTS, ACTION_CONTROL_EVIDENCE_PROFILES, ACTION_CONTROL_CONFORMANCE_CHECKS, toActionControl, createDefaultActionControlManifest, findActionControl, resolveActionControl, validateActionControlManifest, } from './action-control-manifest.js';
|
|
54
|
+
export { EXECUTION_BINDING_VERSION, canonicalize, hashCanonical, materialFieldsFor, verifyExecutionBinding } from './execution-binding.js';
|
|
55
|
+
export { RELIANCE_PACKET_VERSION, ADMISSIBILITY_VERDICTS, buildReliancePacket } from './reliance-packet.js';
|
|
56
|
+
export { EXTERNAL_VERIFICATION_STATEMENT_VERSION, EXTERNAL_VERIFICATION_DOMAIN, externalVerificationDigest, signExternalVerificationStatement, verifyExternalVerificationStatement, } from './reports/external-verification.js';
|
|
57
|
+
export { EG1_VERSION, EG1_CHECKS, EG1_DEFAULT_ACTION, EG1_DEFAULT_SELECTOR, createEg1Harness, makeGateInvoke, runEg1, mintDeviceSignoff, mintQuorumEvidence, } from './eg1-conformance.js';
|
|
58
|
+
export { CF1_VERSION, CF1_CHECKS, runCf1 } from './cf1-conformance.js';
|
|
59
|
+
export { mintBreakGlassAuthorization, verifyBreakGlass, consumeBreakGlass, buildBreakGlassEvidence, runBreakGlass, BREAKGLASS_VERSION, BREAKGLASS_EVIDENCE_KIND, };
|
|
60
|
+
export { createRuntimeMonitor, RUNTIME_MONITOR_VERSION, RUNTIME_MONITOR_MODES, RUNTIME_INVARIANTS } from './runtime-monitor.js';
|
|
61
|
+
export { FORMAL_RUNTIME_BRIDGE_VERSION, FORMAL_RUNTIME_SPEC, FORMAL_RUNTIME_CONFIG, FORMAL_RUNTIME_INVARIANT_MAP, } from './formal-runtime-map.js';
|
|
62
|
+
export { CAPABILITY_RECEIPT_VERSION, CAPABILITY_STATE_VERSION, CAPABILITY_SHARE_VERSION, CAPABILITY_SCOPE_PROFILE, CAPABILITY_CAID_SCOPE_PROFILE, CAPABILITY_STATE_DDL, CAPABILITY_SQL, capabilityBaseReceiptDigest, capabilityActionDigest, verifyCapabilityScope, mintCapabilityReceipt, verifyCapabilityReceipt, splitCapabilitySecret, reconstructCapabilitySecret, createMemoryCapabilityStore, createPostgresCapabilityStore, executeWithCapability, executeWithThreshold, reconcileCapabilityOperation, delegateCapabilityReceipt, } from './capability-receipt.js';
|
|
63
|
+
export { ZK_RANGE_RECEIPT_VERSION, ZK_RANGE_SCHEME, ZK_RANGE_BACKEND_PACKAGE, deriveZkRangeBases, loadBulletproofBackend, mintZkRangeReceipt, verifyZkRangeReceipt, } from './zk-range-proof.js';
|
|
64
|
+
export { RECEIPT_PROGRAM_VERSION, RECEIPT_PROGRAM_CERTIFICATE_VERSION, RECEIPT_PROGRAM_SIGNATURE_ALGORITHM, createReceiptProgramKernel, verifyReceiptProgramCertificate, } from './receipt-program.js';
|
|
65
|
+
export { TRUST_PROGRAM_VERSION, TRUST_STAGE_RECEIPT_VERSION, validateTrustProgram, trustProgramDigest, verifyTrustStageReceipt, createMemoryTrustProgramStore, createTrustProgramKernel, } from './trust-program.js';
|
|
66
|
+
export { TRUST_PROGRAM_REVOCATION_TARGET_VERSION, deriveTrustProgramRevocationTargetObject, deriveTrustProgramRevocationTarget, verifyTrustProgramRevocation, applyTrustProgramRevocation, } from './trust-program-revocation.js';
|
|
67
|
+
export { REMEDY_PROGRAM_VERSION, createRemedyMemoryStore, createRemedyProgramKernel, } from './remedy-program.js';
|
|
68
|
+
export { ACTION_REMEDY_RECEIPT_VERSION, REMEDY_PROGRAM_RECEIPT_VERSION, ACTION_REMEDY_RECEIPT_DOMAIN, expectedRemedyProgramReceiptBindings, remedyProgramReceiptSigningBytes, issueRemedyProgramReceipt, signRemedyProgramReceipt, createRemedyProgramReceipt, verifyRemedyProgramReceipt, } from './remedy-program-receipt.js';
|
|
69
|
+
export { REMEDY_PROGRAM_PG_STORE_VERSION, REMEDY_PROGRAM_MAX_STATE_BYTES, REMEDY_PROGRAM_MAX_FORWARD_SKEW_MINUTES, REMEDY_PROGRAM_POSTGRES_SQL, createRemedyProgramPostgresStore, } from './remedy-program-postgres.js';
|
|
70
|
+
export const ASSURANCE_TIERS = ['software', 'class_a', 'quorum'];
|
|
71
|
+
const TIER_RANK = { software: 0, class_a: 1, quorum: 2 };
|
|
72
|
+
const CAPABILITY_FAILURE_STATUS = 409;
|
|
73
|
+
function gateOutcomeError(cause, { outcome, reason, authorization, execution, result = null }) {
|
|
74
|
+
const error = new Error(cause?.message ?? `EMILIA Gate terminal outcome: ${reason}`, { cause });
|
|
75
|
+
error.code = 'EMILIA_GATE_TERMINAL_OUTCOME';
|
|
76
|
+
let authorizationEvidence = null;
|
|
77
|
+
let executionEvidence = null;
|
|
78
|
+
let resultSnapshot = null;
|
|
79
|
+
try {
|
|
80
|
+
authorizationEvidence = structuredClone(authorization?.evidence ?? null);
|
|
81
|
+
}
|
|
82
|
+
catch { /* unavailable */ }
|
|
83
|
+
try {
|
|
84
|
+
executionEvidence = structuredClone(execution ?? null);
|
|
85
|
+
}
|
|
86
|
+
catch { /* unavailable */ }
|
|
87
|
+
try {
|
|
88
|
+
resultSnapshot = structuredClone(result);
|
|
89
|
+
}
|
|
90
|
+
catch { /* unavailable */ }
|
|
91
|
+
Object.defineProperty(error, 'emiliaGateOutcome', {
|
|
92
|
+
value: Object.freeze({
|
|
93
|
+
outcome,
|
|
94
|
+
reason,
|
|
95
|
+
authorizationEvidence,
|
|
96
|
+
execution: executionEvidence,
|
|
97
|
+
result: resultSnapshot,
|
|
98
|
+
}),
|
|
99
|
+
enumerable: false,
|
|
100
|
+
configurable: false,
|
|
101
|
+
writable: false,
|
|
102
|
+
});
|
|
103
|
+
return error;
|
|
104
|
+
}
|
|
105
|
+
function safeCanonicalHash(value) {
|
|
106
|
+
try {
|
|
107
|
+
return hashCanonical(value);
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Capability spending is intentionally bound to the executor's observed
|
|
115
|
+
* monetary action, not to a presenter-selected amount. The default action
|
|
116
|
+
* packs use `amount_usd`; integrations that use the generic `amount` field
|
|
117
|
+
* are supported as well. A missing or mismatched amount/currency fails closed
|
|
118
|
+
* before the capability store is touched.
|
|
119
|
+
*/
|
|
120
|
+
function verifyCapabilityActionBinding({ capability, observedAction } = {}) {
|
|
121
|
+
if (capability === null || capability === undefined)
|
|
122
|
+
return { ok: true, required: false };
|
|
123
|
+
const action = capability?.action;
|
|
124
|
+
if (!action || typeof action !== 'object' || Array.isArray(action)
|
|
125
|
+
|| !Number.isSafeInteger(action.amount) || action.amount <= 0
|
|
126
|
+
|| typeof action.currency !== 'string' || action.currency.length === 0) {
|
|
127
|
+
return { ok: false, reason: 'capability_action_invalid', required: true };
|
|
128
|
+
}
|
|
129
|
+
const observedAmount = Number.isSafeInteger(observedAction?.amount)
|
|
130
|
+
? observedAction.amount
|
|
131
|
+
: observedAction?.amount_usd;
|
|
132
|
+
const observedCurrency = observedAction?.currency;
|
|
133
|
+
if (observedAmount !== action.amount || observedCurrency !== action.currency) {
|
|
134
|
+
return {
|
|
135
|
+
ok: false,
|
|
136
|
+
reason: 'capability_action_binding_failed',
|
|
137
|
+
required: true,
|
|
138
|
+
capability_amount: action.amount,
|
|
139
|
+
capability_currency: action.currency,
|
|
140
|
+
observed_amount: observedAmount ?? null,
|
|
141
|
+
observed_currency: observedCurrency ?? null,
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
return {
|
|
145
|
+
ok: true,
|
|
146
|
+
required: true,
|
|
147
|
+
amount: action.amount,
|
|
148
|
+
currency: action.currency,
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
function capabilitySummary(capability, operationId = null) {
|
|
152
|
+
return {
|
|
153
|
+
capability_id: capability?.capabilityReceipt?.capability?.id ?? null,
|
|
154
|
+
operation_id: operationId ?? capability?.operationId ?? null,
|
|
155
|
+
amount: capability?.action?.amount ?? null,
|
|
156
|
+
currency: capability?.action?.currency ?? null,
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Re-check the material execution fields at the proof-recording boundary.
|
|
161
|
+
* Authorization-time binding proves what was observed before the effect; this
|
|
162
|
+
* second check proves the execution record carries the same observation. A
|
|
163
|
+
* reliance packet must not be able to reuse an earlier green binding after the
|
|
164
|
+
* executor reports different system-of-record values.
|
|
165
|
+
*/
|
|
166
|
+
function bindExecutionProof({ authorization, observedAction, binding }) {
|
|
167
|
+
if (!binding?.required)
|
|
168
|
+
return binding;
|
|
169
|
+
const requirement = authorization?.requirement || {
|
|
170
|
+
execution_binding: { required_fields: binding.required_fields || [] },
|
|
171
|
+
};
|
|
172
|
+
const replay = verifyExecutionBinding({
|
|
173
|
+
requirement,
|
|
174
|
+
receipt: { payload: { claim: observedAction || {} } },
|
|
175
|
+
observedAction,
|
|
176
|
+
});
|
|
177
|
+
const matchesAuthorization = replay.ok
|
|
178
|
+
&& typeof binding.observed_hash === 'string'
|
|
179
|
+
&& replay.observed_hash === binding.observed_hash;
|
|
180
|
+
return {
|
|
181
|
+
...binding,
|
|
182
|
+
execution_observed_hash: replay.observed_hash,
|
|
183
|
+
execution_mismatched_fields: replay.mismatched_fields || [],
|
|
184
|
+
execution_missing_observed_fields: replay.missing_observed_fields || [],
|
|
185
|
+
execution_binding_match: matchesAuthorization,
|
|
186
|
+
ok: binding.ok === true && matchesAuthorization,
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Structurally compare a PRE-COMPUTED admissibility block with a profile hash.
|
|
191
|
+
* This helper does NOT authenticate the block or establish evaluator provenance.
|
|
192
|
+
* An execution gate must first verify a signature over the packet or recompute
|
|
193
|
+
* the verdict from trusted evidence. createGate enforces that boundary through
|
|
194
|
+
* its verifyAdmissibilityPacket callback whenever a profile is pinned.
|
|
195
|
+
*
|
|
196
|
+
* @param {{id?:string, profile_hash:string}} pinned the profile the relying party requires
|
|
197
|
+
* @param {object|null} presented a reliance packet, or its `.admissibility` block,
|
|
198
|
+
* as produced by buildReliancePacket / the relying party's evaluator
|
|
199
|
+
* @returns {{ok:boolean, reason:string|null, pinned_hash:string|null, presented_hash:string|null, verdict:string|null}}
|
|
200
|
+
* ok:true ONLY when the presented profile_hash equals the pinned hash AND the
|
|
201
|
+
* verdict is exactly 'admissible'. Every other case fails closed with a distinct reason.
|
|
202
|
+
*/
|
|
203
|
+
export function verifyAdmissibilityAgainstPinnedProfile(pinned, presented) {
|
|
204
|
+
const pinnedHash = pinned && typeof pinned.profile_hash === 'string' ? pinned.profile_hash : null;
|
|
205
|
+
// A pin with no hash is a misconfiguration: refuse, do not silently pass.
|
|
206
|
+
if (!pinnedHash) {
|
|
207
|
+
return { ok: false, reason: 'pinned_profile_missing_hash', pinned_hash: null, presented_hash: null, verdict: null };
|
|
208
|
+
}
|
|
209
|
+
// Accept either a full reliance packet (has .admissibility) or the block itself.
|
|
210
|
+
const adm = presented && typeof presented === 'object'
|
|
211
|
+
? (presented.admissibility !== undefined ? presented.admissibility : presented)
|
|
212
|
+
: null;
|
|
213
|
+
if (!adm || typeof adm !== 'object') {
|
|
214
|
+
return { ok: false, reason: 'admissibility_profile_pinned_but_absent', pinned_hash: pinnedHash, presented_hash: null, verdict: null };
|
|
215
|
+
}
|
|
216
|
+
const presentedHash = typeof adm.profile_hash === 'string' ? adm.profile_hash : null;
|
|
217
|
+
const verdict = typeof adm.verdict === 'string' ? adm.verdict : null;
|
|
218
|
+
// Constant-work equality is unnecessary (hashes are public), but the mismatch
|
|
219
|
+
// MUST be a distinct, named refusal: a presented verdict for a DIFFERENT bar is
|
|
220
|
+
// not evidence about the pinned bar.
|
|
221
|
+
if (presentedHash === null || presentedHash !== pinnedHash) {
|
|
222
|
+
return { ok: false, reason: 'profile_hash_mismatch', pinned_hash: pinnedHash, presented_hash: presentedHash, verdict };
|
|
223
|
+
}
|
|
224
|
+
// Verdict must be recognized AND exactly 'admissible'. Any other closed-set
|
|
225
|
+
// member (missing_evidence/stale/conflicted/unverifiable), an unrecognized
|
|
226
|
+
// string, or a missing verdict fails closed and names the verdict it saw.
|
|
227
|
+
if (verdict === null || !ADMISSIBILITY_VERDICTS.includes(verdict)) {
|
|
228
|
+
return { ok: false, reason: 'admissibility_verdict_unrecognized', pinned_hash: pinnedHash, presented_hash: presentedHash, verdict };
|
|
229
|
+
}
|
|
230
|
+
if (verdict !== 'admissible') {
|
|
231
|
+
return { ok: false, reason: `admissibility_not_admissible:${verdict}`, pinned_hash: pinnedHash, presented_hash: presentedHash, verdict };
|
|
232
|
+
}
|
|
233
|
+
return { ok: true, reason: null, pinned_hash: pinnedHash, presented_hash: presentedHash, verdict };
|
|
234
|
+
}
|
|
235
|
+
export function receiptAssuranceTier(doc, opts = {}) {
|
|
236
|
+
const detail = { tier: 'software', quorum: null, signoff: null };
|
|
237
|
+
// --- Path (a): pinned assurance proof / caller-supplied verifier. ---
|
|
238
|
+
// Never inferred from receipt fields without a pinned key or explicit verifier.
|
|
239
|
+
let proofTier = 'software';
|
|
240
|
+
try {
|
|
241
|
+
proofTier = receiptAssuranceTierFromProof(doc, opts) || 'software';
|
|
242
|
+
}
|
|
243
|
+
catch {
|
|
244
|
+
proofTier = 'software';
|
|
245
|
+
}
|
|
246
|
+
if ((TIER_RANK[proofTier] ?? 0) > (TIER_RANK[detail.tier] ?? 0))
|
|
247
|
+
detail.tier = proofTier;
|
|
248
|
+
// --- Path (b): self-contained embedded per-signer evidence (DoD audit fix). ---
|
|
249
|
+
const p = doc?.payload || {};
|
|
250
|
+
const verifyOpts = {
|
|
251
|
+
...(opts.rpId ? { rpId: opts.rpId } : {}),
|
|
252
|
+
...(Array.isArray(opts.allowedOrigins) ? { allowedOrigins: opts.allowedOrigins } : {}),
|
|
253
|
+
};
|
|
254
|
+
// The relying party's PINNED approver public keys (base64url SPKI-DER strings).
|
|
255
|
+
// An embedded approver key elevates the tier only if it is in this set, unless
|
|
256
|
+
// the caller explicitly opts into the self-contained mode.
|
|
257
|
+
const allowEmbedded = opts.allowEmbeddedApproverKeys === true;
|
|
258
|
+
const keyIsTrusted = (k, approver) => allowEmbedded
|
|
259
|
+
|| Boolean(findPinnedApproverKey(opts.approverKeys, k, approver));
|
|
260
|
+
// quorum: a real, self-contained EP-QUORUM-v1 evidence document. Accept it
|
|
261
|
+
// under payload.quorum or payload.claim.quorum. It only counts if it is a full
|
|
262
|
+
// quorum document (policy + members with WebAuthn signoffs) AND verifyQuorum
|
|
263
|
+
// returns valid. A bare {signers,threshold} block has no members to verify and
|
|
264
|
+
// therefore CANNOT be credited quorum. The cryptographic verification runs
|
|
265
|
+
// regardless (so `detail.quorum` reports validity), but the tier elevates only
|
|
266
|
+
// when every member's embedded approver key is pinned (or the caller opted in).
|
|
267
|
+
const q = p.quorum || p.claim?.quorum;
|
|
268
|
+
if (detail.tier !== 'quorum' && isQuorumEvidence(q)) {
|
|
269
|
+
const policy = validatePinnedQuorumPolicy((opts.quorumPolicy || opts.quorum_policy));
|
|
270
|
+
const trustedMembers = Array.isArray(q.members) ? q.members.map((member) => {
|
|
271
|
+
const entry = findPinnedApproverKey(opts.approverKeys, member?.approver_public_key, member?.signoff?.context?.approver);
|
|
272
|
+
return entry ? { ...member, approver_public_key: entry.public_key } : null;
|
|
273
|
+
}) : [];
|
|
274
|
+
const membersTrusted = trustedMembers.length > 0 && trustedMembers.every(Boolean);
|
|
275
|
+
const qr = policy.ok && membersTrusted
|
|
276
|
+
? verifyQuorum({ ...q, policy: policy.policy, members: trustedMembers }, verifyOpts)
|
|
277
|
+
: { valid: false, checks: {} };
|
|
278
|
+
detail.quorum = {
|
|
279
|
+
valid: qr.valid,
|
|
280
|
+
checks: qr.checks,
|
|
281
|
+
policy_pinned: policy.ok,
|
|
282
|
+
embedded_keys_trusted: membersTrusted,
|
|
283
|
+
approvers: qr.valid
|
|
284
|
+
? trustedMembers.map((member) => member?.signoff?.context?.approver).filter(nonEmptyString)
|
|
285
|
+
: [],
|
|
286
|
+
roles: qr.valid
|
|
287
|
+
? trustedMembers.map((member) => ({
|
|
288
|
+
subject: member?.signoff?.context?.approver ?? null,
|
|
289
|
+
role: member?.role ?? null,
|
|
290
|
+
}))
|
|
291
|
+
: [],
|
|
292
|
+
refusal: !policy.ok ? policy.reason : (!membersTrusted ? 'quorum_member_key_unpinned' : null),
|
|
293
|
+
};
|
|
294
|
+
if (qr.valid && policy.ok && membersTrusted)
|
|
295
|
+
detail.tier = 'quorum';
|
|
296
|
+
}
|
|
297
|
+
// class_a: a verifiable WebAuthn device signoff. The signoff evidence is
|
|
298
|
+
// {context, webauthn}; the approver key travels with it (signoff.approver_public_key)
|
|
299
|
+
// or alongside it (payload.approver_public_key). That key elevates the tier only
|
|
300
|
+
// when it is pinned by the relying party (or the caller opted into embedded keys).
|
|
301
|
+
if ((TIER_RANK[detail.tier] ?? 0) < TIER_RANK.class_a) {
|
|
302
|
+
const so = p.signoff || p.claim?.signoff;
|
|
303
|
+
if (isSignoffEvidence(so)) {
|
|
304
|
+
const keyId = p.approver_key_id || p.claim?.approver_key_id;
|
|
305
|
+
const pinnedById = typeof keyId === 'string' && opts.approverKeys
|
|
306
|
+
&& typeof opts.approverKeys === 'object' && !Array.isArray(opts.approverKeys)
|
|
307
|
+
? opts.approverKeys[keyId]
|
|
308
|
+
: null;
|
|
309
|
+
const key = pinnedById?.public_key
|
|
310
|
+
|| so.approver_public_key || p.approver_public_key || p.claim?.approver_public_key;
|
|
311
|
+
if (key) {
|
|
312
|
+
const sr = verifyWebAuthnSignoff(so, key, verifyOpts);
|
|
313
|
+
const sourceHash = p.claim?.source_receipt_action_hash;
|
|
314
|
+
// Acquisition terminal receipts carry a second, explicit signoff
|
|
315
|
+
// binding. Enforce it whenever present without retroactively changing
|
|
316
|
+
// the contract for ordinary receipts whose signoff directly supports
|
|
317
|
+
// the receipt itself.
|
|
318
|
+
const transitiveBinding = sourceHash === undefined
|
|
319
|
+
|| (typeof sourceHash === 'string'
|
|
320
|
+
&& so?.context?.action_hash === sourceHash
|
|
321
|
+
&& p.claim?.approver === so?.context?.approver);
|
|
322
|
+
const trusted = (pinnedById?.key_class === 'A'
|
|
323
|
+
&& pinnedById?.approver_id === so?.context?.approver)
|
|
324
|
+
|| keyIsTrusted(key, so?.context?.approver);
|
|
325
|
+
detail.signoff = {
|
|
326
|
+
valid: sr.valid && transitiveBinding,
|
|
327
|
+
checks: sr.checks,
|
|
328
|
+
embedded_key_trusted: trusted,
|
|
329
|
+
approver: so?.context?.approver ?? null,
|
|
330
|
+
};
|
|
331
|
+
if (sr.valid && transitiveBinding && trusted
|
|
332
|
+
&& (TIER_RANK[detail.tier] ?? 0) < TIER_RANK.class_a)
|
|
333
|
+
detail.tier = 'class_a';
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
return opts.detail ? detail : detail.tier;
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* The set of PINNED approver public keys (base64url SPKI-DER strings) a relying
|
|
341
|
+
* party trusts, from the same `approverKeys` map path (a) uses. Accepts either a
|
|
342
|
+
* map of { keyId: { public_key } } (the EP-ASSURANCE-PROOF-v1 shape) or a plain
|
|
343
|
+
* array/set of key strings. Used to decide whether a receipt-embedded approver
|
|
344
|
+
* key may elevate the path-(b) tier. Never throws.
|
|
345
|
+
*/
|
|
346
|
+
function spkiFingerprint(value) {
|
|
347
|
+
try {
|
|
348
|
+
const key = crypto.createPublicKey({ key: Buffer.from(value, 'base64url'), format: 'der', type: 'spki' });
|
|
349
|
+
return crypto.createHash('sha256').update(key.export({ type: 'spki', format: 'der' })).digest('hex');
|
|
350
|
+
}
|
|
351
|
+
catch {
|
|
352
|
+
return null;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
function findPinnedApproverKey(approverKeys, presentedKey, approver) {
|
|
356
|
+
if (!approverKeys || typeof approverKeys !== 'object' || Array.isArray(approverKeys))
|
|
357
|
+
return null;
|
|
358
|
+
const presentedFingerprint = spkiFingerprint(presentedKey);
|
|
359
|
+
if (!presentedFingerprint || typeof approver !== 'string' || !approver)
|
|
360
|
+
return null;
|
|
361
|
+
const matches = Object.values(approverKeys).filter((entry) => entry && typeof entry === 'object'
|
|
362
|
+
&& entry.approver_id === approver
|
|
363
|
+
&& spkiFingerprint(entry.public_key) === presentedFingerprint);
|
|
364
|
+
return matches.length === 1 ? matches[0] : null;
|
|
365
|
+
}
|
|
366
|
+
/** A quorum evidence doc must carry members with per-signer signoffs to be verifiable. */
|
|
367
|
+
function isQuorumEvidence(q) {
|
|
368
|
+
return !!q && typeof q === 'object' && q.policy && Array.isArray(q.members) && q.members.length > 0
|
|
369
|
+
&& typeof q.action_hash === 'string' && q.action_hash.length > 0;
|
|
370
|
+
}
|
|
371
|
+
/** A device signoff must carry the WebAuthn assertion material to be verifiable. */
|
|
372
|
+
function isSignoffEvidence(s) {
|
|
373
|
+
return !!s && typeof s === 'object' && s.context && s.webauthn;
|
|
374
|
+
}
|
|
375
|
+
function nonEmptyString(value) {
|
|
376
|
+
return typeof value === 'string' && value.length > 0 ? value : null;
|
|
377
|
+
}
|
|
378
|
+
function businessAuthorizationSource(requirement) {
|
|
379
|
+
if (!requirement || typeof requirement !== 'object')
|
|
380
|
+
return null;
|
|
381
|
+
const nested = requirement.business_authorization
|
|
382
|
+
|| requirement.businessAuthorization
|
|
383
|
+
|| requirement.authorization_requirement
|
|
384
|
+
|| requirement.authorizationRequirement
|
|
385
|
+
|| requirement.authorization_policy
|
|
386
|
+
|| requirement.authorizationPolicy
|
|
387
|
+
|| requirement.business_policy
|
|
388
|
+
|| requirement.control?.business_authorization
|
|
389
|
+
|| requirement.control?.authorization_requirement
|
|
390
|
+
|| requirement.control?.authorization_policy;
|
|
391
|
+
if (nested && typeof nested === 'object' && !Array.isArray(nested))
|
|
392
|
+
return nested;
|
|
393
|
+
const hasDirect = [
|
|
394
|
+
'policy', 'business_policy', 'policy_id', 'policy_hash', 'tenant_id', 'allowed_approvers',
|
|
395
|
+
'allowed_approver_subjects', 'allowed_approver_roles',
|
|
396
|
+
].some((field) => Object.prototype.hasOwnProperty.call(requirement, field));
|
|
397
|
+
return hasDirect ? requirement : null;
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* Normalize the relying party's business-authorization pin for one action.
|
|
401
|
+
*
|
|
402
|
+
* Canonical manifest shape:
|
|
403
|
+
* business_authorization: {
|
|
404
|
+
* policy: { id, hash }, tenant_id,
|
|
405
|
+
* allowed_approvers: [{ subject, role }]
|
|
406
|
+
* }
|
|
407
|
+
*
|
|
408
|
+
* Flat policy_id/policy_hash and approver aliases are accepted so an existing
|
|
409
|
+
* manifest can add the control without changing its surrounding schema. Once
|
|
410
|
+
* any part is configured, every part is required; a partial pin is invalid.
|
|
411
|
+
*/
|
|
412
|
+
export function businessAuthorizationRequirement(requirement) {
|
|
413
|
+
const source = businessAuthorizationSource(requirement);
|
|
414
|
+
if (!source) {
|
|
415
|
+
return {
|
|
416
|
+
configured: false, ok: true, reason: null,
|
|
417
|
+
policy_id: null, policy_hash: null, tenant_id: null, allowed_approvers: [],
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
const policy = source.policy && typeof source.policy === 'object' && !Array.isArray(source.policy)
|
|
421
|
+
? source.policy
|
|
422
|
+
: (source.business_policy && typeof source.business_policy === 'object' && !Array.isArray(source.business_policy)
|
|
423
|
+
? source.business_policy : {});
|
|
424
|
+
const root = requirement && typeof requirement === 'object' ? requirement : {};
|
|
425
|
+
const policyId = nonEmptyString(source.policy_id ?? source.id ?? policy.policy_id ?? policy.id ?? root.policy_id);
|
|
426
|
+
const policyHash = nonEmptyString(source.policy_hash ?? source.hash ?? policy.policy_hash ?? policy.hash ?? root.policy_hash);
|
|
427
|
+
const tenantId = nonEmptyString(source.tenant_id ?? source.tenant ?? source.organization_id
|
|
428
|
+
?? root.tenant_id ?? root.tenant ?? root.organization_id);
|
|
429
|
+
const rawApprovers = source.allowed_approvers ?? source.approvers ?? source.approver_roster
|
|
430
|
+
?? root.allowed_approvers ?? root.approvers ?? root.approver_roster;
|
|
431
|
+
const subjects = source.allowed_approver_subjects ?? source.approver_subjects
|
|
432
|
+
?? root.allowed_approver_subjects ?? root.approver_subjects;
|
|
433
|
+
const roles = source.allowed_approver_roles ?? source.approver_roles
|
|
434
|
+
?? root.allowed_approver_roles ?? root.approver_roles;
|
|
435
|
+
let allowed = [];
|
|
436
|
+
if (Array.isArray(rawApprovers)) {
|
|
437
|
+
allowed = rawApprovers.map((entry) => {
|
|
438
|
+
if (typeof entry === 'string')
|
|
439
|
+
return { subject: entry, role: null };
|
|
440
|
+
if (!entry || typeof entry !== 'object' || Array.isArray(entry))
|
|
441
|
+
return { subject: null, role: null };
|
|
442
|
+
return {
|
|
443
|
+
subject: nonEmptyString(entry.subject ?? entry.approver ?? entry.principal_id),
|
|
444
|
+
role: nonEmptyString(entry.role ?? entry.approver_role),
|
|
445
|
+
};
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
else if (Array.isArray(subjects)) {
|
|
449
|
+
const validRoles = Array.isArray(roles) ? roles.filter((role) => nonEmptyString(role)) : [];
|
|
450
|
+
allowed = subjects.flatMap((subject) => {
|
|
451
|
+
if (!validRoles.length)
|
|
452
|
+
return [{ subject: nonEmptyString(subject), role: null }];
|
|
453
|
+
return validRoles.map((role) => ({ subject: nonEmptyString(subject), role }));
|
|
454
|
+
});
|
|
455
|
+
}
|
|
456
|
+
const malformed = !policyId || !policyHash || !tenantId || allowed.length === 0
|
|
457
|
+
|| allowed.some((entry) => !entry.subject || !entry.role);
|
|
458
|
+
const duplicate = new Set(allowed.map((entry) => `${entry.subject}\u0000${entry.role}`)).size !== allowed.length;
|
|
459
|
+
return {
|
|
460
|
+
configured: true,
|
|
461
|
+
ok: !malformed && !duplicate,
|
|
462
|
+
reason: malformed ? 'business_authorization_incomplete'
|
|
463
|
+
: (duplicate ? 'business_authorization_duplicate_approver' : null),
|
|
464
|
+
policy_id: policyId,
|
|
465
|
+
policy_hash: policyHash,
|
|
466
|
+
tenant_id: tenantId,
|
|
467
|
+
allowed_approvers: allowed,
|
|
468
|
+
};
|
|
469
|
+
}
|
|
470
|
+
function signedString(candidates) {
|
|
471
|
+
const present = candidates.filter((value) => value !== undefined && value !== null);
|
|
472
|
+
if (!present.length)
|
|
473
|
+
return { ok: true, value: null };
|
|
474
|
+
if (present.some((value) => !nonEmptyString(value)))
|
|
475
|
+
return { ok: false, value: null };
|
|
476
|
+
const distinct = [...new Set(present)];
|
|
477
|
+
return distinct.length === 1 ? { ok: true, value: distinct[0] } : { ok: false, value: null };
|
|
478
|
+
}
|
|
479
|
+
function receiptRoleAssertions(receipt, tierResult) {
|
|
480
|
+
const claim = receipt?.payload?.claim || {};
|
|
481
|
+
const assertions = [];
|
|
482
|
+
const arrays = [claim.approvers, claim.approver_authorizations, claim.approver_roles];
|
|
483
|
+
for (const entries of arrays) {
|
|
484
|
+
if (!Array.isArray(entries))
|
|
485
|
+
continue;
|
|
486
|
+
for (const entry of entries) {
|
|
487
|
+
if (!entry || typeof entry !== 'object' || Array.isArray(entry))
|
|
488
|
+
continue;
|
|
489
|
+
const subject = nonEmptyString(entry.subject ?? entry.approver ?? entry.principal_id);
|
|
490
|
+
const role = nonEmptyString(entry.role ?? entry.approver_role);
|
|
491
|
+
if (subject && role)
|
|
492
|
+
assertions.push({ subject, role });
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
const singleSubject = nonEmptyString(claim.approver ?? claim.approver_subject);
|
|
496
|
+
const singleRole = nonEmptyString(claim.approver_role ?? claim.role);
|
|
497
|
+
if (singleSubject && singleRole)
|
|
498
|
+
assertions.push({ subject: singleSubject, role: singleRole });
|
|
499
|
+
if (tierResult?.quorum?.valid === true) {
|
|
500
|
+
for (const member of (receipt?.payload?.quorum?.members || [])) {
|
|
501
|
+
const subject = nonEmptyString(member?.signoff?.context?.approver);
|
|
502
|
+
const role = nonEmptyString(member?.role);
|
|
503
|
+
if (subject && role)
|
|
504
|
+
assertions.push({ subject, role });
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
return assertions;
|
|
508
|
+
}
|
|
509
|
+
function verifiedApproverSubjects(assurance, tierResult) {
|
|
510
|
+
const subjects = new Set(Array.isArray(assurance?.approvers) ? assurance.approvers.filter(nonEmptyString) : []);
|
|
511
|
+
if (tierResult?.signoff?.valid === true && nonEmptyString(tierResult.signoff.approver)) {
|
|
512
|
+
subjects.add(tierResult.signoff.approver);
|
|
513
|
+
}
|
|
514
|
+
if (tierResult?.quorum?.valid === true) {
|
|
515
|
+
for (const subject of (tierResult.quorum.approvers || [])) {
|
|
516
|
+
if (nonEmptyString(subject))
|
|
517
|
+
subjects.add(subject);
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
return [...subjects].sort();
|
|
521
|
+
}
|
|
522
|
+
/**
|
|
523
|
+
* Verify signed business-policy and tenant fields plus the cryptographically
|
|
524
|
+
* credited human approvers against one action's relying-party pins.
|
|
525
|
+
* @returns {{required:boolean, ok:boolean, reason:string|null, expected:object, evaluated:{policy_id:string|null, policy_hash:string|null, tenant_id:string|null, approvers:{subject:string, roles:string[]}[]}}}
|
|
526
|
+
*/
|
|
527
|
+
export function verifyBusinessAuthorization({ requirement, receipt, assurance, tierResult } = {}) {
|
|
528
|
+
const expected = businessAuthorizationRequirement(requirement);
|
|
529
|
+
const claim = receipt?.payload?.claim || {};
|
|
530
|
+
const payload = receipt?.payload || {};
|
|
531
|
+
const policyId = signedString([claim.policy_id, payload.policy_id]);
|
|
532
|
+
const policyHash = signedString([claim.policy_hash, payload.policy_hash]);
|
|
533
|
+
const tenantId = signedString([
|
|
534
|
+
claim.tenant_id, claim.organization_id, payload.tenant_id, payload.organization_id,
|
|
535
|
+
]);
|
|
536
|
+
const subjects = verifiedApproverSubjects(assurance, tierResult);
|
|
537
|
+
const roleAssertions = receiptRoleAssertions(receipt, tierResult);
|
|
538
|
+
const evaluatedApprovers = subjects.map((subject) => {
|
|
539
|
+
const asserted = [...new Set(roleAssertions.filter((entry) => entry.subject === subject).map((entry) => entry.role))];
|
|
540
|
+
return { subject, roles: asserted };
|
|
541
|
+
});
|
|
542
|
+
const evaluated = {
|
|
543
|
+
policy_id: policyId.value,
|
|
544
|
+
policy_hash: policyHash.value,
|
|
545
|
+
tenant_id: tenantId.value,
|
|
546
|
+
approvers: evaluatedApprovers,
|
|
547
|
+
};
|
|
548
|
+
const base = { required: expected.configured, ok: true, reason: null, expected, evaluated };
|
|
549
|
+
if (!expected.configured)
|
|
550
|
+
return base;
|
|
551
|
+
if (!expected.ok)
|
|
552
|
+
return { ...base, ok: false, reason: expected.reason };
|
|
553
|
+
if (!policyId.ok)
|
|
554
|
+
return { ...base, ok: false, reason: 'business_policy_id_ambiguous' };
|
|
555
|
+
if (!policyHash.ok)
|
|
556
|
+
return { ...base, ok: false, reason: 'business_policy_hash_ambiguous' };
|
|
557
|
+
if (!tenantId.ok)
|
|
558
|
+
return { ...base, ok: false, reason: 'business_tenant_ambiguous' };
|
|
559
|
+
if (policyId.value !== expected.policy_id)
|
|
560
|
+
return { ...base, ok: false, reason: 'business_policy_id_mismatch' };
|
|
561
|
+
if (policyHash.value !== expected.policy_hash)
|
|
562
|
+
return { ...base, ok: false, reason: 'business_policy_hash_mismatch' };
|
|
563
|
+
if (tenantId.value !== expected.tenant_id)
|
|
564
|
+
return { ...base, ok: false, reason: 'business_tenant_mismatch' };
|
|
565
|
+
if (!subjects.length)
|
|
566
|
+
return { ...base, ok: false, reason: 'business_approver_required' };
|
|
567
|
+
for (const approver of evaluatedApprovers) {
|
|
568
|
+
const allowedForSubject = expected.allowed_approvers.filter((entry) => entry.subject === approver.subject);
|
|
569
|
+
if (!allowedForSubject.length)
|
|
570
|
+
return { ...base, ok: false, reason: 'business_approver_not_allowed' };
|
|
571
|
+
// The early `if (!expected.ok) return ...` above guarantees every allowed_approvers
|
|
572
|
+
// entry has a non-null role (a null role would have made businessAuthorizationRequirement
|
|
573
|
+
// mark the manifest malformed and expected.ok false).
|
|
574
|
+
const allowedRoles = new Set(allowedForSubject.map((entry) => entry.role));
|
|
575
|
+
if (approver.roles.length && !approver.roles.some((role) => allowedRoles.has(role))) {
|
|
576
|
+
return { ...base, ok: false, reason: 'business_approver_role_not_allowed' };
|
|
577
|
+
}
|
|
578
|
+
// The manifest is the authoritative subject-to-role assignment. When the
|
|
579
|
+
// receipt does not repeat a role, record the pinned role rather than trusting
|
|
580
|
+
// an unsigned/free-text role label from elsewhere.
|
|
581
|
+
if (!approver.roles.length)
|
|
582
|
+
approver.roles = [...allowedRoles].sort();
|
|
583
|
+
}
|
|
584
|
+
return base;
|
|
585
|
+
}
|
|
586
|
+
export function createGate({ manifest = null, trustedKeys = [], maxAgeSec = 900, store, log, capabilityStore = null, capabilityTrustedIssuerKeys = [], capabilityCaidResolver = null, allowInlineKey = false, allowEphemeralStore = false, strictEvidence = true, now = Date.now, keyRegistry = null, approverKeys = {}, approver_keys = null, verifyAssurance = null, rpId = null, allowedOrigins = [], quorumPolicy = null, quorumPolicies = {}, requiredAdmissibilityProfile = null, verifyAdmissibilityPacket = null, allowEmbeddedApproverKeys = false, runtimeMonitor = createRuntimeMonitor({ now }) } = {}) {
|
|
587
|
+
// Production key custody: a registry (rotation + revocation) supersedes a flat
|
|
588
|
+
// trustedKeys list. A flat list is coerced to an always-valid registry, so
|
|
589
|
+
// existing callers are unchanged.
|
|
590
|
+
const registry = keyRegistry ? asKeyRegistry(keyRegistry) : (trustedKeys.length ? asKeyRegistry(trustedKeys) : null);
|
|
591
|
+
const usesActionControlManifest = manifest?.['@version'] === ACTION_CONTROL_MANIFEST_VERSION;
|
|
592
|
+
if (manifest) {
|
|
593
|
+
const m = usesActionControlManifest
|
|
594
|
+
? validateActionControlManifest(manifest)
|
|
595
|
+
: validateActionRiskManifest(manifest);
|
|
596
|
+
if (!m.ok)
|
|
597
|
+
throw new Error(`EMILIA Gate: invalid ${usesActionControlManifest ? 'action-control' : 'action-risk'} manifest: ${m.errors.join('; ')}`);
|
|
598
|
+
for (const [index, actionRequirement] of (manifest.actions || []).entries()) {
|
|
599
|
+
if (actionRequirement?.receipt_required !== true)
|
|
600
|
+
continue;
|
|
601
|
+
const business = businessAuthorizationRequirement(actionRequirement);
|
|
602
|
+
if (business.configured && !business.ok) {
|
|
603
|
+
throw new Error(`EMILIA Gate: invalid action-risk manifest: actions[${index}].business_authorization ${business.reason}`);
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
if (allowInlineKey) {
|
|
608
|
+
// eslint-disable-next-line no-console
|
|
609
|
+
console.warn('EMILIA Gate: allowInlineKey=true accepts a receipt\'s OWN key. This proves INTEGRITY (the receipt was not tampered with) but NOT issuer TRUST (anyone can mint a receipt with their own key). Use for demos only; pin trustedKeys in production.');
|
|
610
|
+
}
|
|
611
|
+
if (capabilityStore && (typeof capabilityStore.registerCapability !== 'function'
|
|
612
|
+
|| typeof capabilityStore.reserveSpend !== 'function'
|
|
613
|
+
|| typeof capabilityStore.commitSpend !== 'function')) {
|
|
614
|
+
throw new Error('EMILIA Gate capabilityStore must implement registerCapability(), reserveSpend(), and commitSpend()');
|
|
615
|
+
}
|
|
616
|
+
if (capabilityStore && (!Array.isArray(capabilityTrustedIssuerKeys)
|
|
617
|
+
|| capabilityTrustedIssuerKeys.length === 0
|
|
618
|
+
|| capabilityTrustedIssuerKeys.some((key) => typeof key !== 'string' || key.length === 0))) {
|
|
619
|
+
throw new Error('EMILIA Gate capabilityTrustedIssuerKeys must explicitly pin at least one capability issuer');
|
|
620
|
+
}
|
|
621
|
+
const effectiveCapabilityTrustedIssuerKeys = [...capabilityTrustedIssuerKeys];
|
|
622
|
+
// Replay defense is only sound if the store is shared, ownership-fenced, and
|
|
623
|
+
// permanent. This is a security property in every environment; NODE_ENV must
|
|
624
|
+
// never silently decide whether a receipt can be replayed.
|
|
625
|
+
let consumption = store;
|
|
626
|
+
if (!consumption) {
|
|
627
|
+
if (!allowEphemeralStore)
|
|
628
|
+
throw new Error('EMILIA Gate requires a durable, ownership-fenced, permanent consumption store. '
|
|
629
|
+
+ 'Pass allowEphemeralStore:true only for an explicit test/demo gate.');
|
|
630
|
+
consumption = new MemoryConsumptionStore();
|
|
631
|
+
}
|
|
632
|
+
for (const method of ['consume', 'reserve', 'commit']) {
|
|
633
|
+
if (typeof consumption?.[method] !== 'function') {
|
|
634
|
+
throw new Error(`EMILIA Gate consumption store must implement ${method}()`);
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
if (!allowEphemeralStore && !isSecureConsumptionStore(consumption)) {
|
|
638
|
+
throw new Error('EMILIA Gate requires a durable, ownership-fenced, permanent consumption store. '
|
|
639
|
+
+ 'Pass allowEphemeralStore:true only for an explicit test/demo gate.');
|
|
640
|
+
}
|
|
641
|
+
const evidence = log || createEvidenceLog({ strict: strictEvidence });
|
|
642
|
+
function resolveRequirement(selector) {
|
|
643
|
+
if (!manifest)
|
|
644
|
+
return null;
|
|
645
|
+
const controlResolution = usesActionControlManifest
|
|
646
|
+
? resolveActionControl(manifest, selector)
|
|
647
|
+
: null;
|
|
648
|
+
const raw = usesActionControlManifest
|
|
649
|
+
? (controlResolution?.status === 'one'
|
|
650
|
+
? controlResolution.action
|
|
651
|
+
: (controlResolution?.status === 'ambiguous'
|
|
652
|
+
? {
|
|
653
|
+
action_type: selector.action_type || selector.action || 'ambiguous.action',
|
|
654
|
+
receipt_required: true,
|
|
655
|
+
assurance_class: 'quorum',
|
|
656
|
+
__resolution_ambiguous: true,
|
|
657
|
+
ambiguous_action_ids: controlResolution.action_ids,
|
|
658
|
+
}
|
|
659
|
+
: null))
|
|
660
|
+
: findActionRequirement(manifest, selector);
|
|
661
|
+
if (!raw || !usesActionControlManifest)
|
|
662
|
+
return raw;
|
|
663
|
+
// Action Control v0.2 keeps enforcement details under `control`; the Gate's
|
|
664
|
+
// existing execution/business checks consume the normalized flat view.
|
|
665
|
+
// The original object remains available under `control` for evidence.
|
|
666
|
+
return {
|
|
667
|
+
...raw,
|
|
668
|
+
execution_binding: raw.control?.execution_binding || raw.execution_binding,
|
|
669
|
+
authorization: raw.control?.authorization || null,
|
|
670
|
+
caid_selector: raw.control?.execution_binding?.caid_selector
|
|
671
|
+
|| raw.control?.caid_selector
|
|
672
|
+
|| raw.execution_binding?.caid_selector
|
|
673
|
+
|| null,
|
|
674
|
+
};
|
|
675
|
+
}
|
|
676
|
+
function acquisitionChallengeOptions(requirement, selector, requiredTier, observed = null) {
|
|
677
|
+
const observedHash = observed ? safeCanonicalHash(observed) : null;
|
|
678
|
+
const acquisition = requirement?.authorization || requirement?.control?.authorization || undefined;
|
|
679
|
+
return {
|
|
680
|
+
status: RECEIPT_REQUIRED_STATUS,
|
|
681
|
+
assuranceClass: requiredTier,
|
|
682
|
+
maxAgeSec,
|
|
683
|
+
manifest: selector.manifestUrl
|
|
684
|
+
|| (usesActionControlManifest ? manifest?.service?.manifest_url : null),
|
|
685
|
+
// An acquisition endpoint whose POST contract requires an exact action
|
|
686
|
+
// hash is a dead end unless this executor actually observed and hashed
|
|
687
|
+
// the system-of-record action. Do not advertise a machine-completable
|
|
688
|
+
// flow from a type-only challenge.
|
|
689
|
+
authorization: !usesActionControlManifest || observedHash ? acquisition : undefined,
|
|
690
|
+
requiredFields: requirement?.execution_binding?.required_fields
|
|
691
|
+
|| requirement?.control?.execution_binding?.required_fields
|
|
692
|
+
|| undefined,
|
|
693
|
+
caidSelector: requirement?.caid_selector || requirement?.control?.caid_selector || undefined,
|
|
694
|
+
actionHash: observedHash ? `sha256:${observedHash}` : undefined,
|
|
695
|
+
};
|
|
696
|
+
}
|
|
697
|
+
async function check({ selector = {}, receipt = null, observedAction = null, consumptionMode = 'consume', admissibilityProfile = null, reliancePacket: presentedPacket = null, admissibility = null, capability = null } = {}) {
|
|
698
|
+
const requirement = /** @type {any} */ (resolveRequirement(selector));
|
|
699
|
+
const action = requirement?.action_type || selector.action_type || selector.action || null;
|
|
700
|
+
const guarded = Boolean(requirement && requirement.receipt_required !== false);
|
|
701
|
+
const runtimeCycleId = runtimeMonitor?.beginCheck({
|
|
702
|
+
action,
|
|
703
|
+
receipt_id: receipt?.payload?.receipt_id ?? null,
|
|
704
|
+
});
|
|
705
|
+
// Assurance tier the action requires (cryptographically checked below). For a
|
|
706
|
+
// manifest-guarded action the tier MUST be declared explicitly: never fall
|
|
707
|
+
// back to the weakest 'software' tier because assurance_class was omitted —
|
|
708
|
+
// that would let a guarded, possibly critical, action accept a bare
|
|
709
|
+
// machine-signed receipt (a fail-open). A guarded requirement with no tier
|
|
710
|
+
// is a misconfiguration and fails closed just below. Only selector-only
|
|
711
|
+
// checks (no manifest requirement) use the documented 'software' default.
|
|
712
|
+
const declaredRequiredTier = requirement
|
|
713
|
+
? requirement.assurance_class
|
|
714
|
+
: (selector.assurance_class || 'software');
|
|
715
|
+
const requiredTier = runtimeMonitor?.minimumAssuranceTier(declaredRequiredTier) ?? declaredRequiredTier;
|
|
716
|
+
const pinnedQuorumPolicy = requirement?.quorum_policy
|
|
717
|
+
|| (quorumPolicies && typeof quorumPolicies === 'object' ? quorumPolicies[action] : null)
|
|
718
|
+
|| quorumPolicy;
|
|
719
|
+
const observed = observedAction || selector.observedAction || selector.actionDetails || null;
|
|
720
|
+
const businessExpected = businessAuthorizationRequirement(requirement);
|
|
721
|
+
let businessEvaluation = {
|
|
722
|
+
required: businessExpected.configured,
|
|
723
|
+
ok: !businessExpected.configured,
|
|
724
|
+
reason: null,
|
|
725
|
+
expected: businessExpected,
|
|
726
|
+
evaluated: { policy_id: null, policy_hash: null, tenant_id: null, approvers: [] },
|
|
727
|
+
};
|
|
728
|
+
async function decide(allow, status, reason, extra = {}) {
|
|
729
|
+
let runtimeExtra = {};
|
|
730
|
+
// Cast to the real transition()/fail() runtime shape: the auto-inferred union
|
|
731
|
+
// widens `ok` to `boolean` on both branches, which defeats the `!runtimeDecision.ok`
|
|
732
|
+
// narrowing below (TS can't discriminate on a non-literal, same-typed property).
|
|
733
|
+
const runtimeDecision = runtimeMonitor?.recordDecision(runtimeCycleId, {
|
|
734
|
+
allow,
|
|
735
|
+
status,
|
|
736
|
+
reason,
|
|
737
|
+
guarded,
|
|
738
|
+
receipt_id: receipt?.payload?.receipt_id ?? null,
|
|
739
|
+
});
|
|
740
|
+
if (runtimeDecision && !runtimeDecision.ok) {
|
|
741
|
+
allow = false;
|
|
742
|
+
status = RECEIPT_REQUIRED_STATUS;
|
|
743
|
+
reason = runtimeDecision.reason;
|
|
744
|
+
runtimeExtra = { runtime_monitor: runtimeDecision.event };
|
|
745
|
+
}
|
|
746
|
+
const entry = {
|
|
747
|
+
kind: 'decision',
|
|
748
|
+
at: new Date(typeof now === 'function' ? now() : now).toISOString(),
|
|
749
|
+
action,
|
|
750
|
+
allow,
|
|
751
|
+
status,
|
|
752
|
+
reason,
|
|
753
|
+
selector: { ...selector },
|
|
754
|
+
required_tier: requiredTier,
|
|
755
|
+
receipt_id: receipt?.payload?.receipt_id ?? null,
|
|
756
|
+
subject: receipt?.payload?.subject ?? null,
|
|
757
|
+
observed_action_hash: observed ? safeCanonicalHash(observed) : null,
|
|
758
|
+
business_authorization: businessEvaluation,
|
|
759
|
+
evaluated_policy_id: businessEvaluation.evaluated.policy_id,
|
|
760
|
+
evaluated_policy_hash: businessEvaluation.evaluated.policy_hash,
|
|
761
|
+
evaluated_tenant_id: businessEvaluation.evaluated.tenant_id,
|
|
762
|
+
evaluated_approvers: businessEvaluation.evaluated.approvers,
|
|
763
|
+
...extra,
|
|
764
|
+
...runtimeExtra,
|
|
765
|
+
};
|
|
766
|
+
let record;
|
|
767
|
+
try {
|
|
768
|
+
record = await evidence.record(entry);
|
|
769
|
+
}
|
|
770
|
+
catch (e) {
|
|
771
|
+
// The decision could not be durably recorded. Fail CLOSED: never
|
|
772
|
+
// authorize an action we cannot account for. Downgrade any allow to a
|
|
773
|
+
// refusal and best-effort note the downgrade (non-fatal if that fails too).
|
|
774
|
+
allow = false;
|
|
775
|
+
status = RECEIPT_REQUIRED_STATUS;
|
|
776
|
+
reason = 'evidence_log_failed';
|
|
777
|
+
try {
|
|
778
|
+
record = await evidence.record({ ...entry, allow: false, status, reason, evidence_error: String(e?.message ?? e) });
|
|
779
|
+
}
|
|
780
|
+
catch {
|
|
781
|
+
record = null;
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
const out = { allow, status, reason, action, requirement, evidence: record };
|
|
785
|
+
if (runtimeCycleId)
|
|
786
|
+
Object.defineProperty(out, '_runtime_cycle_id', {
|
|
787
|
+
value: runtimeCycleId,
|
|
788
|
+
enumerable: false,
|
|
789
|
+
});
|
|
790
|
+
if (!allow) {
|
|
791
|
+
const challengeOptions = acquisitionChallengeOptions(requirement, selector, requiredTier, observed);
|
|
792
|
+
out.challenge = receiptChallenge(action, reason, challengeOptions);
|
|
793
|
+
out.header = receiptRequiredHeader({ action, ...challengeOptions });
|
|
794
|
+
}
|
|
795
|
+
return out;
|
|
796
|
+
}
|
|
797
|
+
const runtimeSafeMode = runtimeMonitor?.getMode() !== RUNTIME_MONITOR_MODES.NORMAL;
|
|
798
|
+
const runtimePreflight = runtimeMonitor?.preflight({ hasReceipt: Boolean(receipt) });
|
|
799
|
+
if (runtimePreflight && !runtimePreflight.ok) {
|
|
800
|
+
return decide(false, RECEIPT_REQUIRED_STATUS, runtimePreflight.reason, {
|
|
801
|
+
runtime_mode: runtimePreflight.mode,
|
|
802
|
+
});
|
|
803
|
+
}
|
|
804
|
+
if (requirement?.__resolution_ambiguous === true) {
|
|
805
|
+
return decide(false, RECEIPT_REQUIRED_STATUS, 'manifest_selector_ambiguous', {
|
|
806
|
+
ambiguous_action_ids: requirement.ambiguous_action_ids,
|
|
807
|
+
});
|
|
808
|
+
}
|
|
809
|
+
// Manifest present and this selector is not guarded (or explicitly not required): pass through.
|
|
810
|
+
// A runtime safe mode disables pass-through so every action must present
|
|
811
|
+
// cryptographic signoff before the monitor permits execution again.
|
|
812
|
+
if (manifest && (!requirement || requirement.receipt_required === false) && !runtimeSafeMode) {
|
|
813
|
+
return decide(true, 200, 'not_guarded');
|
|
814
|
+
}
|
|
815
|
+
// Guarded, but no receipt was presented.
|
|
816
|
+
if (!receipt) {
|
|
817
|
+
return decide(false, RECEIPT_REQUIRED_STATUS, 'receipt_required');
|
|
818
|
+
}
|
|
819
|
+
// A capability issuance receipt is not a bearer bypass around the budget
|
|
820
|
+
// path. The marker is inside the signed claim; stripping it breaks the
|
|
821
|
+
// receipt signature. Such a receipt is accepted only while the capability
|
|
822
|
+
// executor supplies the signed envelope and durable budget context.
|
|
823
|
+
if (receipt?.payload?.claim?.capability_only === true && !capability) {
|
|
824
|
+
return decide(false, RECEIPT_REQUIRED_STATUS, 'capability_required');
|
|
825
|
+
}
|
|
826
|
+
// A manifest-guarded action that declares no assurance_class is a
|
|
827
|
+
// misconfiguration. Fail CLOSED rather than defaulting to the weakest tier
|
|
828
|
+
// (which would accept a bare machine-signed receipt for a guarded action).
|
|
829
|
+
// validateActionRiskManifest also rejects such a manifest at author time;
|
|
830
|
+
// this is defense in depth for a manifest loaded without re-validation.
|
|
831
|
+
if (requirement && requirement.receipt_required !== false && !requiredTier) {
|
|
832
|
+
return decide(false, RECEIPT_REQUIRED_STATUS, 'manifest_missing_assurance_class');
|
|
833
|
+
}
|
|
834
|
+
// Signature / freshness / action-binding / outcome. Production key custody:
|
|
835
|
+
// resolve the issuer keys valid (and not revoked) at THIS receipt's issuance
|
|
836
|
+
// time. A revoked or out-of-window key is excluded, so its signature does not
|
|
837
|
+
// verify and the action is refused (fail closed).
|
|
838
|
+
const effectiveKeys = registry
|
|
839
|
+
? registry.keysValidAt(receipt?.payload?.created_at)
|
|
840
|
+
: trustedKeys;
|
|
841
|
+
const observedActionHash = usesActionControlManifest && observed
|
|
842
|
+
? safeCanonicalHash(observed)
|
|
843
|
+
: null;
|
|
844
|
+
if (usesActionControlManifest && observed && !observedActionHash) {
|
|
845
|
+
return decide(false, RECEIPT_REQUIRED_STATUS, 'observed_action_invalid');
|
|
846
|
+
}
|
|
847
|
+
const v = verifyEmiliaReceipt(receipt, {
|
|
848
|
+
trustedKeys: effectiveKeys,
|
|
849
|
+
allowInlineKey,
|
|
850
|
+
action,
|
|
851
|
+
maxAgeSec,
|
|
852
|
+
now,
|
|
853
|
+
...(usesActionControlManifest && observed ? {
|
|
854
|
+
actionHash: `sha256:${observedActionHash}`,
|
|
855
|
+
requiredFields: requirement?.execution_binding?.required_fields,
|
|
856
|
+
caidSelector: requirement?.caid_selector || undefined,
|
|
857
|
+
} : {}),
|
|
858
|
+
});
|
|
859
|
+
if (!v.ok) {
|
|
860
|
+
return decide(false, RECEIPT_REQUIRED_STATUS, `receipt_rejected:${v.reason}`, { rejected: v });
|
|
861
|
+
}
|
|
862
|
+
// Assurance tier. CRYPTOGRAPHICALLY VERIFIED — never inferred from
|
|
863
|
+
// self-asserted payload fields. The credited tier is the HIGHER of two
|
|
864
|
+
// independent proof paths:
|
|
865
|
+
// (a) pinned assurance proof (payload.assurance_proof verified against
|
|
866
|
+
// pinned approverKeys) or a caller-supplied verifyAssurance hook;
|
|
867
|
+
// (b) self-contained embedded per-signer evidence (EP-QUORUM-v1 /
|
|
868
|
+
// WebAuthn device signoff) re-verified via verifyQuorum /
|
|
869
|
+
// verifyWebAuthnSignoff (DoD audit fix).
|
|
870
|
+
// A receipt that only CLAIMS a higher tier earns 'software' and is refused.
|
|
871
|
+
const needRank = TIER_RANK[requiredTier];
|
|
872
|
+
if (needRank === undefined) {
|
|
873
|
+
return decide(false, RECEIPT_REQUIRED_STATUS, 'unknown_required_tier', { have_tier: 'software', need_tier: requiredTier, assurance_tier_source: 'cryptographic_verification' });
|
|
874
|
+
}
|
|
875
|
+
if (needRank >= TIER_RANK.class_a && typeof verifyAssurance !== 'function'
|
|
876
|
+
&& (typeof rpId !== 'string' || !rpId
|
|
877
|
+
|| !Array.isArray(allowedOrigins) || allowedOrigins.length === 0
|
|
878
|
+
|| allowedOrigins.some((origin) => typeof origin !== 'string' || !origin))) {
|
|
879
|
+
return decide(false, RECEIPT_REQUIRED_STATUS, 'assurance_context_unpinned', {
|
|
880
|
+
have_tier: 'software', need_tier: requiredTier,
|
|
881
|
+
assurance_tier_source: 'cryptographic_verification',
|
|
882
|
+
});
|
|
883
|
+
}
|
|
884
|
+
if (requiredTier === 'quorum' && typeof verifyAssurance !== 'function') {
|
|
885
|
+
const policy = validatePinnedQuorumPolicy(pinnedQuorumPolicy);
|
|
886
|
+
if (!policy.ok) {
|
|
887
|
+
return decide(false, RECEIPT_REQUIRED_STATUS, policy.reason, {
|
|
888
|
+
have_tier: 'software', need_tier: requiredTier,
|
|
889
|
+
assurance_tier_source: 'cryptographic_verification',
|
|
890
|
+
});
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
const assurance = evaluateReceiptAssurance(receipt, requiredTier, {
|
|
894
|
+
approverKeys: approver_keys || approverKeys,
|
|
895
|
+
verifyAssurance,
|
|
896
|
+
rpId,
|
|
897
|
+
allowedOrigins,
|
|
898
|
+
quorumPolicy: pinnedQuorumPolicy,
|
|
899
|
+
});
|
|
900
|
+
// detail:true guarantees receiptAssuranceTier returns the AssuranceTierDetail
|
|
901
|
+
// object branch, not the plain tier string.
|
|
902
|
+
const tierResult = receiptAssuranceTier(receipt, {
|
|
903
|
+
rpId, allowedOrigins, detail: true, approverKeys: approver_keys || approverKeys,
|
|
904
|
+
verifyAssurance, quorumPolicy: pinnedQuorumPolicy,
|
|
905
|
+
// Trust-laundering guard: a receipt-embedded approver key does NOT elevate
|
|
906
|
+
// the tier unless it is in the pinned approverKeys set, or the operator
|
|
907
|
+
// explicitly opted into the self-contained embedded-evidence mode. DEFAULT OFF.
|
|
908
|
+
allowEmbeddedApproverKeys,
|
|
909
|
+
});
|
|
910
|
+
// Take the strongest tier either path proves.
|
|
911
|
+
const have = (TIER_RANK[assurance.have] ?? 0) >= (TIER_RANK[tierResult.tier] ?? 0)
|
|
912
|
+
? assurance.have : tierResult.tier;
|
|
913
|
+
if ((TIER_RANK[have] ?? 0) < needRank) {
|
|
914
|
+
// The credited tier (from either proof path) is below what the action
|
|
915
|
+
// requires. The canonical machine-readable reason is 'assurance_too_low';
|
|
916
|
+
// main's proof-path detail (e.g. 'assurance_proof_required') is surfaced
|
|
917
|
+
// separately so callers keep the diagnostic without changing the contract.
|
|
918
|
+
return decide(false, RECEIPT_REQUIRED_STATUS, 'assurance_too_low', {
|
|
919
|
+
have_tier: have, need_tier: requiredTier,
|
|
920
|
+
assurance_tier_source: 'cryptographic_verification',
|
|
921
|
+
assurance_detail: assurance.reason || null,
|
|
922
|
+
tier_evidence: { quorum: tierResult.quorum, signoff: tierResult.signoff },
|
|
923
|
+
});
|
|
924
|
+
}
|
|
925
|
+
// Business authorization is a distinct trust root from receipt issuer
|
|
926
|
+
// integrity and assurance tier. The signed claim must name the exact policy
|
|
927
|
+
// id+hash and tenant this action requirement pins, and the humans who
|
|
928
|
+
// cryptographically earned the tier must belong to its subject/role roster.
|
|
929
|
+
// This runs BEFORE execution binding, admissibility, and receipt reservation.
|
|
930
|
+
businessEvaluation = verifyBusinessAuthorization({
|
|
931
|
+
requirement,
|
|
932
|
+
receipt,
|
|
933
|
+
assurance,
|
|
934
|
+
tierResult,
|
|
935
|
+
});
|
|
936
|
+
if (!businessEvaluation.ok) {
|
|
937
|
+
return decide(false, RECEIPT_REQUIRED_STATUS, businessEvaluation.reason, {
|
|
938
|
+
have_tier: have,
|
|
939
|
+
assurance_tier_source: 'cryptographic_verification',
|
|
940
|
+
});
|
|
941
|
+
}
|
|
942
|
+
// The high-risk action packs define material fields that must be observed
|
|
943
|
+
// by the executor from the system of record. A signed, harmless-looking
|
|
944
|
+
// claim cannot authorize a different real mutation.
|
|
945
|
+
const executionBinding = verifyExecutionBinding({ requirement, receipt, observedAction: observed });
|
|
946
|
+
if (!executionBinding.ok) {
|
|
947
|
+
return decide(false, RECEIPT_REQUIRED_STATUS, 'execution_binding_failed', { execution_binding: executionBinding, have_tier: have, assurance_tier_source: 'cryptographic_verification' });
|
|
948
|
+
}
|
|
949
|
+
// OPT-IN admissibility pinning. When the caller pins a required admissibility
|
|
950
|
+
// profile {id, profile_hash} (gate-level requiredAdmissibilityProfile, a
|
|
951
|
+
// per-call admissibilityProfile, or selector.admissibilityProfile), the gate
|
|
952
|
+
// REFUSES unless a presented reliance packet's admissibility block was computed
|
|
953
|
+
// against the SAME pinned profile_hash AND carries an 'admissible' verdict. The
|
|
954
|
+
// gate does NOT re-evaluate raw evidence and does NOT define the bar — the
|
|
955
|
+
// relying party's own evaluator produced the verdict OFFLINE against its pinned
|
|
956
|
+
// profile. Checked BEFORE consumption so a mismatch never burns the receipt.
|
|
957
|
+
// When no profile is pinned, this whole block is inert — behavior is
|
|
958
|
+
// byte-for-byte unchanged from the pre-admissibility gate.
|
|
959
|
+
const pinnedProfile = admissibilityProfile || selector.admissibilityProfile || requiredAdmissibilityProfile;
|
|
960
|
+
let trustedAdmissibility = null;
|
|
961
|
+
if (pinnedProfile) {
|
|
962
|
+
const presentedAdmissibility = admissibility ?? presentedPacket ?? selector.reliancePacket ?? selector.admissibility ?? null;
|
|
963
|
+
if (typeof verifyAdmissibilityPacket !== 'function') {
|
|
964
|
+
return decide(false, RECEIPT_REQUIRED_STATUS, 'admissibility_verifier_required', {
|
|
965
|
+
pinned_profile: { id: pinnedProfile.id ?? null, profile_hash: pinnedProfile.profile_hash ?? null },
|
|
966
|
+
have_tier: have,
|
|
967
|
+
assurance_tier_source: 'cryptographic_verification',
|
|
968
|
+
});
|
|
969
|
+
}
|
|
970
|
+
try {
|
|
971
|
+
trustedAdmissibility = await verifyAdmissibilityPacket({
|
|
972
|
+
pinned_profile: structuredClone(pinnedProfile),
|
|
973
|
+
presented: structuredClone(presentedAdmissibility),
|
|
974
|
+
receipt: structuredClone(receipt),
|
|
975
|
+
selector: structuredClone(selector),
|
|
976
|
+
observed_action: observed === null ? null : structuredClone(observed),
|
|
977
|
+
});
|
|
978
|
+
}
|
|
979
|
+
catch {
|
|
980
|
+
return decide(false, RECEIPT_REQUIRED_STATUS, 'admissibility_verification_failed', {
|
|
981
|
+
pinned_profile: { id: pinnedProfile.id ?? null, profile_hash: pinnedProfile.profile_hash ?? null },
|
|
982
|
+
have_tier: have,
|
|
983
|
+
assurance_tier_source: 'cryptographic_verification',
|
|
984
|
+
});
|
|
985
|
+
}
|
|
986
|
+
const adm = verifyAdmissibilityAgainstPinnedProfile(pinnedProfile, trustedAdmissibility);
|
|
987
|
+
if (!adm.ok) {
|
|
988
|
+
return decide(false, RECEIPT_REQUIRED_STATUS, adm.reason, {
|
|
989
|
+
admissibility_check: adm,
|
|
990
|
+
pinned_profile: { id: pinnedProfile.id ?? null, profile_hash: pinnedProfile.profile_hash ?? null },
|
|
991
|
+
have_tier: have,
|
|
992
|
+
assurance_tier_source: 'cryptographic_verification',
|
|
993
|
+
});
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
const capabilityBinding = verifyCapabilityActionBinding({ capability, observedAction: observed });
|
|
997
|
+
if (!capabilityBinding.ok) {
|
|
998
|
+
return decide(false, RECEIPT_REQUIRED_STATUS, capabilityBinding.reason, {
|
|
999
|
+
capability: {
|
|
1000
|
+
...capabilitySummary(capability, capability?.operationId),
|
|
1001
|
+
...capabilityBinding,
|
|
1002
|
+
},
|
|
1003
|
+
have_tier: have,
|
|
1004
|
+
assurance_tier_source: 'cryptographic_verification',
|
|
1005
|
+
});
|
|
1006
|
+
}
|
|
1007
|
+
// One-time consumption (replay defense). Require a stable, issuer-generated
|
|
1008
|
+
// receipt_id — never fall back to a content hash, whose canonicalization can
|
|
1009
|
+
// differ across language implementations and silently break replay detection
|
|
1010
|
+
// when services of different languages share a store.
|
|
1011
|
+
const receiptId = receipt?.payload?.receipt_id;
|
|
1012
|
+
if (!receiptId) {
|
|
1013
|
+
return decide(false, RECEIPT_REQUIRED_STATUS, 'receipt_rejected:missing_receipt_id');
|
|
1014
|
+
}
|
|
1015
|
+
let fresh;
|
|
1016
|
+
if (consumptionMode === 'reserve') {
|
|
1017
|
+
if (typeof consumption.reserve !== 'function') {
|
|
1018
|
+
return decide(false, RECEIPT_REQUIRED_STATUS, 'consumption_store_lacks_reserve', { consumption_key: receiptId });
|
|
1019
|
+
}
|
|
1020
|
+
fresh = await consumption.reserve(receiptId);
|
|
1021
|
+
}
|
|
1022
|
+
else if (consumptionMode === 'none') {
|
|
1023
|
+
fresh = true;
|
|
1024
|
+
}
|
|
1025
|
+
else {
|
|
1026
|
+
fresh = await consumption.consume(receiptId);
|
|
1027
|
+
}
|
|
1028
|
+
if (!fresh) {
|
|
1029
|
+
return decide(false, RECEIPT_REQUIRED_STATUS, 'replay_refused', { consumption_key: receiptId });
|
|
1030
|
+
}
|
|
1031
|
+
const allowExtra = {
|
|
1032
|
+
signer: v.signer,
|
|
1033
|
+
outcome: v.outcome,
|
|
1034
|
+
have_tier: have,
|
|
1035
|
+
assurance_tier_source: 'cryptographic_verification',
|
|
1036
|
+
execution_binding: executionBinding,
|
|
1037
|
+
consumption_mode: consumptionMode,
|
|
1038
|
+
...(capability ? { capability: { ...capabilitySummary(capability, capability?.operationId), ...capabilityBinding } } : {}),
|
|
1039
|
+
};
|
|
1040
|
+
// Carry the admissibility block (from the presented packet) onto the decision
|
|
1041
|
+
// so a reliance packet built from this decision embeds the verdict the relying
|
|
1042
|
+
// party's evaluator computed. Only when something was actually presented.
|
|
1043
|
+
const presentedAdmForAllow = pinnedProfile
|
|
1044
|
+
? trustedAdmissibility
|
|
1045
|
+
: (admissibility ?? presentedPacket ?? selector.reliancePacket ?? selector.admissibility ?? null);
|
|
1046
|
+
if (presentedAdmForAllow) {
|
|
1047
|
+
const admBlock = presentedAdmForAllow.admissibility !== undefined ? presentedAdmForAllow.admissibility : presentedAdmForAllow;
|
|
1048
|
+
if (admBlock)
|
|
1049
|
+
allowExtra.admissibility = admBlock;
|
|
1050
|
+
}
|
|
1051
|
+
return decide(true, 200, 'allow', allowExtra);
|
|
1052
|
+
}
|
|
1053
|
+
async function requestGateInput(req, opts = {}) {
|
|
1054
|
+
let selector = typeof opts.selector === 'function'
|
|
1055
|
+
? await opts.selector(req)
|
|
1056
|
+
: { ...(opts.selector || {}) };
|
|
1057
|
+
if (!selector || typeof selector !== 'object' || Array.isArray(selector))
|
|
1058
|
+
selector = {};
|
|
1059
|
+
if (opts.action && !selector.action_type) {
|
|
1060
|
+
selector.action_type = typeof opts.action === 'function' ? await opts.action(req) : opts.action;
|
|
1061
|
+
}
|
|
1062
|
+
let receipt = typeof opts.receipt === 'function' ? await opts.receipt(req) : (opts.receipt ?? null);
|
|
1063
|
+
if (!receipt) {
|
|
1064
|
+
const hdr = req.headers?.['x-emilia-receipt'];
|
|
1065
|
+
if (hdr)
|
|
1066
|
+
receipt = parseReceiptCarrier(hdr);
|
|
1067
|
+
if (!receipt && req.body?.emilia_receipt)
|
|
1068
|
+
receipt = req.body.emilia_receipt;
|
|
1069
|
+
}
|
|
1070
|
+
const observedAction = typeof opts.observedAction === 'function'
|
|
1071
|
+
? await opts.observedAction(req)
|
|
1072
|
+
: (opts.observedAction || req.emiliaObservedAction || null);
|
|
1073
|
+
const admissibilityProfile = typeof opts.admissibilityProfile === 'function'
|
|
1074
|
+
? await opts.admissibilityProfile(req)
|
|
1075
|
+
: (opts.admissibilityProfile ?? null);
|
|
1076
|
+
const presentedPacket = typeof opts.reliancePacket === 'function'
|
|
1077
|
+
? await opts.reliancePacket(req)
|
|
1078
|
+
: (opts.reliancePacket ?? opts.admissibility ?? null);
|
|
1079
|
+
const capability = typeof opts.capability === 'function'
|
|
1080
|
+
? await opts.capability(req)
|
|
1081
|
+
: (opts.capability ?? req.emiliaCapability ?? req.body?.emilia_capability ?? null);
|
|
1082
|
+
return { selector, receipt, observedAction, admissibilityProfile, reliancePacket: presentedPacket, capability };
|
|
1083
|
+
}
|
|
1084
|
+
function sendRefusal(res, authorization) {
|
|
1085
|
+
if (typeof res?.setHeader === 'function' && authorization.header) {
|
|
1086
|
+
res.setHeader(RECEIPT_REQUIRED_HEADER, authorization.header);
|
|
1087
|
+
}
|
|
1088
|
+
if (typeof res?.setHeader === 'function') {
|
|
1089
|
+
res.setHeader('content-type', 'application/problem+json');
|
|
1090
|
+
res.setHeader('cache-control', 'no-store');
|
|
1091
|
+
}
|
|
1092
|
+
if (typeof res?.status === 'function' && typeof res?.json === 'function') {
|
|
1093
|
+
return res.status(authorization.status).json(authorization.challenge);
|
|
1094
|
+
}
|
|
1095
|
+
if (res)
|
|
1096
|
+
res.statusCode = authorization.status;
|
|
1097
|
+
if (typeof res?.end === 'function') {
|
|
1098
|
+
return res.end(JSON.stringify(authorization.challenge));
|
|
1099
|
+
}
|
|
1100
|
+
return authorization;
|
|
1101
|
+
}
|
|
1102
|
+
/**
|
|
1103
|
+
* Express/Connect route wrapper. The route handler itself is the effect
|
|
1104
|
+
* callback owned by gate.run(), so authorization, receipt reservation,
|
|
1105
|
+
* execution, consumption, and evidence form one lifecycle.
|
|
1106
|
+
*/
|
|
1107
|
+
function route(handler, opts = {}) {
|
|
1108
|
+
if (typeof handler !== 'function')
|
|
1109
|
+
throw new Error('EMILIA Gate route(): handler is required');
|
|
1110
|
+
return async function emiliaGateRoute(req, res) {
|
|
1111
|
+
const input = await requestGateInput(req, opts);
|
|
1112
|
+
const out = await run(input, async (authorization) => {
|
|
1113
|
+
req.emiliaGate = authorization;
|
|
1114
|
+
return handler(req, res, authorization);
|
|
1115
|
+
});
|
|
1116
|
+
if (!out.ok)
|
|
1117
|
+
return sendRefusal(res, out.refusal || out.authorization);
|
|
1118
|
+
req.emiliaGate = out.authorization;
|
|
1119
|
+
req.emiliaGateExecution = out.execution;
|
|
1120
|
+
req.emiliaReliancePacket = out.packet;
|
|
1121
|
+
return out.result;
|
|
1122
|
+
};
|
|
1123
|
+
}
|
|
1124
|
+
/**
|
|
1125
|
+
* @deprecated Middleware cannot prove that code after next() actually ran.
|
|
1126
|
+
* It therefore fails closed without parsing or consuming a presented receipt.
|
|
1127
|
+
* Use gate.route(handler, opts), gate.guard(), or gate.run().
|
|
1128
|
+
*/
|
|
1129
|
+
function middleware(opts = {}) {
|
|
1130
|
+
return async function emiliaGateDeprecatedMiddleware(req, res) {
|
|
1131
|
+
const selector = typeof opts.selector === 'function'
|
|
1132
|
+
? await opts.selector(req)
|
|
1133
|
+
: { ...(opts.selector || {}) };
|
|
1134
|
+
const action = (selector && (selector.action_type || selector.action))
|
|
1135
|
+
|| (typeof opts.action === 'function' ? await opts.action(req) : opts.action)
|
|
1136
|
+
|| null;
|
|
1137
|
+
const reason = 'unsafe_middleware_deprecated';
|
|
1138
|
+
const challenge = receiptChallenge(action, reason, {
|
|
1139
|
+
status: RECEIPT_REQUIRED_STATUS,
|
|
1140
|
+
assuranceClass: selector?.assurance_class || null,
|
|
1141
|
+
maxAgeSec,
|
|
1142
|
+
manifest: selector?.manifestUrl,
|
|
1143
|
+
});
|
|
1144
|
+
const authorization = {
|
|
1145
|
+
allow: false,
|
|
1146
|
+
status: RECEIPT_REQUIRED_STATUS,
|
|
1147
|
+
reason,
|
|
1148
|
+
action,
|
|
1149
|
+
challenge,
|
|
1150
|
+
header: receiptRequiredHeader({ action, assuranceClass: selector?.assurance_class || null, maxAgeSec }),
|
|
1151
|
+
};
|
|
1152
|
+
return sendRefusal(res, authorization);
|
|
1153
|
+
};
|
|
1154
|
+
}
|
|
1155
|
+
/**
|
|
1156
|
+
* Emit a post-execution receipt bound to a prior authorization decision — the
|
|
1157
|
+
* "execution emits proof" half of the loop (maps to the EP Commit seal). It
|
|
1158
|
+
* commits to the exact authorization decision (`authorizes_decision` = that
|
|
1159
|
+
* decision's evidence hash), so authorization and execution are one chain.
|
|
1160
|
+
*/
|
|
1161
|
+
async function recordExecution({ authorization, outcome = 'executed', detail, observedAction = null, executionBinding = null } = {}) {
|
|
1162
|
+
const auth = authorization?.evidence || authorization || {};
|
|
1163
|
+
const authorizationBinding = authorization?.evidence?.execution_binding
|
|
1164
|
+
|| authorization?.execution_binding
|
|
1165
|
+
|| executionBinding
|
|
1166
|
+
|| null;
|
|
1167
|
+
const boundExecution = bindExecutionProof({
|
|
1168
|
+
authorization,
|
|
1169
|
+
observedAction,
|
|
1170
|
+
binding: authorizationBinding,
|
|
1171
|
+
});
|
|
1172
|
+
return evidence.record({
|
|
1173
|
+
kind: 'execution',
|
|
1174
|
+
at: new Date(typeof now === 'function' ? now() : now).toISOString(),
|
|
1175
|
+
authorizes_decision: auth.hash ?? null,
|
|
1176
|
+
action: authorization?.action ?? auth.action ?? null,
|
|
1177
|
+
receipt_id: auth.receipt_id ?? null,
|
|
1178
|
+
outcome, // 'executed' | 'failed'
|
|
1179
|
+
observed_action_hash: observedAction ? safeCanonicalHash(observedAction) : null,
|
|
1180
|
+
execution_binding: boundExecution,
|
|
1181
|
+
...(detail !== undefined ? { detail } : {}),
|
|
1182
|
+
});
|
|
1183
|
+
}
|
|
1184
|
+
async function recordCapabilityEvent({ authorization, capability, outcome, reason = null } = {}) {
|
|
1185
|
+
return evidence.record({
|
|
1186
|
+
kind: 'capability',
|
|
1187
|
+
at: new Date(typeof now === 'function' ? now() : now).toISOString(),
|
|
1188
|
+
authorizes_decision: authorization?.evidence?.hash ?? null,
|
|
1189
|
+
action: authorization?.action ?? null,
|
|
1190
|
+
...capabilitySummary(capability, capability?.operationId),
|
|
1191
|
+
outcome,
|
|
1192
|
+
...(reason ? { reason } : {}),
|
|
1193
|
+
});
|
|
1194
|
+
}
|
|
1195
|
+
function capabilityRefusal({ authorization = null, capability = null, reason, status = CAPABILITY_FAILURE_STATUS, event = null } = {}) {
|
|
1196
|
+
const body = {
|
|
1197
|
+
rejected: {
|
|
1198
|
+
type: 'capability',
|
|
1199
|
+
reason,
|
|
1200
|
+
...capabilitySummary(capability, capability?.operationId),
|
|
1201
|
+
},
|
|
1202
|
+
};
|
|
1203
|
+
return {
|
|
1204
|
+
ok: false,
|
|
1205
|
+
status,
|
|
1206
|
+
body,
|
|
1207
|
+
authorization,
|
|
1208
|
+
refusal: {
|
|
1209
|
+
allow: false,
|
|
1210
|
+
status,
|
|
1211
|
+
reason,
|
|
1212
|
+
action: authorization?.action ?? null,
|
|
1213
|
+
challenge: body,
|
|
1214
|
+
header: null,
|
|
1215
|
+
},
|
|
1216
|
+
capability: { reason, ...capabilitySummary(capability, capability?.operationId) },
|
|
1217
|
+
evidence: event,
|
|
1218
|
+
};
|
|
1219
|
+
}
|
|
1220
|
+
/**
|
|
1221
|
+
* Capability-backed execution is the real Marvel guard path. The ordinary
|
|
1222
|
+
* EP receipt is verified first without consuming it; the capability store
|
|
1223
|
+
* then reserves the exact observed monetary amount before the effect. A
|
|
1224
|
+
* successful effect commits the reservation, while an exception commits it
|
|
1225
|
+
* as indeterminate so the budget can never silently reopen.
|
|
1226
|
+
*/
|
|
1227
|
+
async function runCapability({ selector = {}, receipt = null, observedAction = null, admissibilityProfile = null, reliancePacket: presentedPacket = null, admissibility = null, capability = null } = {}, fn, opts = {}) {
|
|
1228
|
+
if (!capabilityStore)
|
|
1229
|
+
return capabilityRefusal({ capability, reason: 'capability_store_required', status: 500 });
|
|
1230
|
+
if (!capability || typeof capability !== 'object' || Array.isArray(capability)
|
|
1231
|
+
|| !capability.capabilityReceipt || !capability.action) {
|
|
1232
|
+
return capabilityRefusal({ capability, reason: 'capability_request_invalid' });
|
|
1233
|
+
}
|
|
1234
|
+
if (typeof capability.operationId !== 'string' || capability.operationId.length === 0
|
|
1235
|
+
|| Buffer.byteLength(capability.operationId, 'utf8') > 128) {
|
|
1236
|
+
return capabilityRefusal({ capability, reason: 'capability_operation_id_required' });
|
|
1237
|
+
}
|
|
1238
|
+
const operationId = capability.operationId;
|
|
1239
|
+
const context = { ...capability, operationId };
|
|
1240
|
+
const baseReceipt = capability.capabilityReceipt.receipt;
|
|
1241
|
+
if (receipt && safeCanonicalHash(receipt) !== safeCanonicalHash(baseReceipt)) {
|
|
1242
|
+
return capabilityRefusal({ capability: context, reason: 'capability_receipt_mismatch' });
|
|
1243
|
+
}
|
|
1244
|
+
let authorization = null;
|
|
1245
|
+
let effectError = null;
|
|
1246
|
+
let effectStarted = false;
|
|
1247
|
+
const capabilityGate = {
|
|
1248
|
+
check: (input = {}) => check({
|
|
1249
|
+
...input,
|
|
1250
|
+
capability: {
|
|
1251
|
+
capabilityReceipt: context.capabilityReceipt,
|
|
1252
|
+
action: context.action,
|
|
1253
|
+
operationId,
|
|
1254
|
+
},
|
|
1255
|
+
}),
|
|
1256
|
+
};
|
|
1257
|
+
const executeAction = async (_action, executionContext) => {
|
|
1258
|
+
authorization = executionContext.authorization;
|
|
1259
|
+
const runtimeCycleId = authorization?._runtime_cycle_id;
|
|
1260
|
+
const runtimeStart = runtimeMonitor?.beginExecution(runtimeCycleId, authorization);
|
|
1261
|
+
if (runtimeStart && !runtimeStart.ok) {
|
|
1262
|
+
const error = new Error(`EMILIA Gate runtime monitor refused capability execution (${runtimeStart.reason})`);
|
|
1263
|
+
error.code = 'EMILIA_RUNTIME_MONITOR_REFUSED';
|
|
1264
|
+
throw error;
|
|
1265
|
+
}
|
|
1266
|
+
effectStarted = true;
|
|
1267
|
+
try {
|
|
1268
|
+
const value = await fn(authorization, {
|
|
1269
|
+
operationId,
|
|
1270
|
+
providerIdempotencyKey: operationId,
|
|
1271
|
+
actionDigest: executionContext.action_digest,
|
|
1272
|
+
observedAction: executionContext.observed_action,
|
|
1273
|
+
});
|
|
1274
|
+
runtimeMonitor?.effectReturned(runtimeCycleId);
|
|
1275
|
+
return value;
|
|
1276
|
+
}
|
|
1277
|
+
catch (error) {
|
|
1278
|
+
effectError = error;
|
|
1279
|
+
runtimeMonitor?.effectFailed(runtimeCycleId);
|
|
1280
|
+
throw error;
|
|
1281
|
+
}
|
|
1282
|
+
};
|
|
1283
|
+
const executorInput = {
|
|
1284
|
+
capabilityReceipt: context.capabilityReceipt,
|
|
1285
|
+
action: context.action,
|
|
1286
|
+
store: capabilityStore,
|
|
1287
|
+
gate: capabilityGate,
|
|
1288
|
+
selector,
|
|
1289
|
+
observedAction,
|
|
1290
|
+
trustedIssuerKeys: effectiveCapabilityTrustedIssuerKeys,
|
|
1291
|
+
resolveCaid: capabilityCaidResolver,
|
|
1292
|
+
operationId,
|
|
1293
|
+
now,
|
|
1294
|
+
executeAction,
|
|
1295
|
+
};
|
|
1296
|
+
const capabilityResult = Array.isArray(context.shares)
|
|
1297
|
+
? await executeWithThreshold(/** @type {any} */ ({ ...executorInput, shares: context.shares }))
|
|
1298
|
+
: await executeWithCapability(/** @type {any} */ ({ ...executorInput, secret: context.secret }));
|
|
1299
|
+
authorization = authorization || capabilityResult.authorization || null;
|
|
1300
|
+
const runtimeCycleId = authorization?._runtime_cycle_id;
|
|
1301
|
+
if (capabilityResult.ok) {
|
|
1302
|
+
runtimeMonitor?.consumptionCommitted(runtimeCycleId);
|
|
1303
|
+
if (opts.recordExecution === false) {
|
|
1304
|
+
runtimeMonitor?.executionSkipped(runtimeCycleId);
|
|
1305
|
+
return { ok: true, result: capabilityResult.result, authorization, execution: null, packet: null, capability: capabilityResult };
|
|
1306
|
+
}
|
|
1307
|
+
let execution = null;
|
|
1308
|
+
try {
|
|
1309
|
+
execution = await recordExecution({
|
|
1310
|
+
authorization,
|
|
1311
|
+
outcome: 'executed',
|
|
1312
|
+
observedAction,
|
|
1313
|
+
detail: { capability: { ...capabilitySummary(context, operationId), outcome: 'executed' } },
|
|
1314
|
+
});
|
|
1315
|
+
runtimeMonitor?.executionRecorded(runtimeCycleId);
|
|
1316
|
+
const packet = await reliancePacket({ authorization, execution });
|
|
1317
|
+
return { ok: true, result: capabilityResult.result, authorization, execution, packet, capability: capabilityResult };
|
|
1318
|
+
}
|
|
1319
|
+
catch (error) {
|
|
1320
|
+
throw gateOutcomeError(error, {
|
|
1321
|
+
outcome: 'executed',
|
|
1322
|
+
reason: execution ? 'reliance_packet_unavailable' : 'execution_evidence_unavailable',
|
|
1323
|
+
authorization,
|
|
1324
|
+
execution,
|
|
1325
|
+
result: capabilityResult.result,
|
|
1326
|
+
});
|
|
1327
|
+
}
|
|
1328
|
+
}
|
|
1329
|
+
if (effectStarted && (capabilityResult.reason === 'effect_indeterminate'
|
|
1330
|
+
|| capabilityResult.reason === 'capability_commit_indeterminate')) {
|
|
1331
|
+
if (capabilityResult.reason === 'effect_indeterminate')
|
|
1332
|
+
runtimeMonitor?.consumptionCommitted(runtimeCycleId);
|
|
1333
|
+
let execution = null;
|
|
1334
|
+
if (opts.recordExecution !== false) {
|
|
1335
|
+
try {
|
|
1336
|
+
execution = await recordExecution({
|
|
1337
|
+
authorization,
|
|
1338
|
+
outcome: 'indeterminate',
|
|
1339
|
+
observedAction,
|
|
1340
|
+
detail: {
|
|
1341
|
+
code: 'effect_attempted_outcome_unknown',
|
|
1342
|
+
capability: { ...capabilitySummary(context, operationId), outcome: 'indeterminate' },
|
|
1343
|
+
},
|
|
1344
|
+
});
|
|
1345
|
+
}
|
|
1346
|
+
catch (error) {
|
|
1347
|
+
throw gateOutcomeError(effectError ?? error, {
|
|
1348
|
+
outcome: 'indeterminate',
|
|
1349
|
+
reason: 'execution_evidence_unavailable',
|
|
1350
|
+
authorization,
|
|
1351
|
+
execution: null,
|
|
1352
|
+
});
|
|
1353
|
+
}
|
|
1354
|
+
}
|
|
1355
|
+
if (capabilityResult.reason === 'effect_indeterminate' && opts.recordExecution !== false) {
|
|
1356
|
+
runtimeMonitor?.executionRecorded(runtimeCycleId);
|
|
1357
|
+
}
|
|
1358
|
+
if (effectError) {
|
|
1359
|
+
throw gateOutcomeError(effectError, {
|
|
1360
|
+
outcome: 'indeterminate',
|
|
1361
|
+
reason: capabilityResult.reason,
|
|
1362
|
+
authorization,
|
|
1363
|
+
execution,
|
|
1364
|
+
});
|
|
1365
|
+
}
|
|
1366
|
+
return capabilityRefusal({ authorization, capability: context, reason: capabilityResult.reason, event: execution });
|
|
1367
|
+
}
|
|
1368
|
+
if (authorization?.allow === true) {
|
|
1369
|
+
const event = await recordCapabilityEvent({
|
|
1370
|
+
authorization,
|
|
1371
|
+
capability: context,
|
|
1372
|
+
outcome: 'refused',
|
|
1373
|
+
reason: capabilityResult.reason,
|
|
1374
|
+
});
|
|
1375
|
+
runtimeMonitor?.capabilityRefused(runtimeCycleId);
|
|
1376
|
+
return capabilityRefusal({ authorization, capability: context, reason: capabilityResult.reason, event });
|
|
1377
|
+
}
|
|
1378
|
+
if (authorization) {
|
|
1379
|
+
return {
|
|
1380
|
+
ok: false,
|
|
1381
|
+
status: authorization.status,
|
|
1382
|
+
body: authorization.challenge,
|
|
1383
|
+
authorization,
|
|
1384
|
+
refusal: authorization,
|
|
1385
|
+
capability: { reason: capabilityResult.reason, ...capabilitySummary(context, operationId) },
|
|
1386
|
+
};
|
|
1387
|
+
}
|
|
1388
|
+
return capabilityRefusal({ authorization, capability: context, reason: capabilityResult.reason, status: RECEIPT_REQUIRED_STATUS });
|
|
1389
|
+
}
|
|
1390
|
+
/**
|
|
1391
|
+
* Recommended end-to-end path. Reserves the receipt, runs the side effect,
|
|
1392
|
+
* commits one-time consumption after the effect attempt, and records execution.
|
|
1393
|
+
* Once the executor is invoked, an exception is an INDETERMINATE outcome: the
|
|
1394
|
+
* external effect may have happened before its response was lost. The receipt
|
|
1395
|
+
* is therefore committed (or left reserved if the store is unavailable),
|
|
1396
|
+
* never released automatically. Callers that need retries must make the
|
|
1397
|
+
* downstream effect idempotent under the receipt id and reconcile its result.
|
|
1398
|
+
*/
|
|
1399
|
+
async function run({ selector = {}, receipt = null, observedAction = null, admissibilityProfile = null, reliancePacket: presentedPacket = null, admissibility = null, capability = null } = {}, fn, opts = {}) {
|
|
1400
|
+
if (typeof fn !== 'function')
|
|
1401
|
+
throw new Error('EMILIA Gate run(): fn is required');
|
|
1402
|
+
if (capability) {
|
|
1403
|
+
return runCapability({ selector, receipt, observedAction, admissibilityProfile, reliancePacket: presentedPacket, admissibility, capability }, fn, opts);
|
|
1404
|
+
}
|
|
1405
|
+
const authorization = await check({ selector, receipt, observedAction, consumptionMode: 'reserve', admissibilityProfile, reliancePacket: presentedPacket, admissibility });
|
|
1406
|
+
if (!authorization.allow) {
|
|
1407
|
+
return { ok: false, status: authorization.status, body: authorization.challenge, authorization };
|
|
1408
|
+
}
|
|
1409
|
+
const receiptId = authorization.evidence?.receipt_id;
|
|
1410
|
+
const runtimeCycleId = authorization._runtime_cycle_id;
|
|
1411
|
+
if (runtimeMonitor && runtimeCycleId) {
|
|
1412
|
+
const runtimeStart = runtimeMonitor.beginExecution(runtimeCycleId, authorization);
|
|
1413
|
+
if (!runtimeStart.ok) {
|
|
1414
|
+
const error = new Error(`EMILIA Gate runtime monitor refused execution (${runtimeStart.reason})`);
|
|
1415
|
+
error.code = 'EMILIA_RUNTIME_MONITOR_REFUSED';
|
|
1416
|
+
throw error;
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
let phase = 'reserved';
|
|
1420
|
+
let consumptionCommitted = false;
|
|
1421
|
+
let result = null;
|
|
1422
|
+
let execution = null;
|
|
1423
|
+
try {
|
|
1424
|
+
phase = 'effect_attempted';
|
|
1425
|
+
result = await fn(authorization);
|
|
1426
|
+
phase = 'effect_returned';
|
|
1427
|
+
runtimeMonitor?.effectReturned(runtimeCycleId);
|
|
1428
|
+
if (typeof consumption.commit === 'function')
|
|
1429
|
+
await consumption.commit(receiptId);
|
|
1430
|
+
consumptionCommitted = true;
|
|
1431
|
+
phase = 'consumed';
|
|
1432
|
+
runtimeMonitor?.consumptionCommitted(runtimeCycleId);
|
|
1433
|
+
if (opts.recordExecution === false) {
|
|
1434
|
+
runtimeMonitor?.executionSkipped(runtimeCycleId);
|
|
1435
|
+
return { ok: true, result, authorization, execution: null, packet: null };
|
|
1436
|
+
}
|
|
1437
|
+
phase = 'recording_execution';
|
|
1438
|
+
execution = await recordExecution({ authorization, outcome: 'executed', observedAction });
|
|
1439
|
+
runtimeMonitor?.executionRecorded(runtimeCycleId);
|
|
1440
|
+
phase = 'execution_recorded';
|
|
1441
|
+
const packet = await reliancePacket({ authorization, execution });
|
|
1442
|
+
return { ok: true, result, authorization, execution, packet };
|
|
1443
|
+
}
|
|
1444
|
+
catch (e) {
|
|
1445
|
+
if (consumptionCommitted
|
|
1446
|
+
&& ['consumed', 'recording_execution', 'execution_recorded'].includes(phase)) {
|
|
1447
|
+
throw gateOutcomeError(e, {
|
|
1448
|
+
outcome: 'executed',
|
|
1449
|
+
reason: execution ? 'reliance_packet_unavailable' : 'execution_evidence_unavailable',
|
|
1450
|
+
authorization,
|
|
1451
|
+
execution,
|
|
1452
|
+
result,
|
|
1453
|
+
});
|
|
1454
|
+
}
|
|
1455
|
+
if (runtimeMonitor && runtimeCycleId && (phase === 'effect_attempted' || phase === 'effect_returned')) {
|
|
1456
|
+
runtimeMonitor.effectFailed(runtimeCycleId);
|
|
1457
|
+
}
|
|
1458
|
+
// An exception after invoking fn() cannot establish that no external
|
|
1459
|
+
// effect occurred. Burn the approval if possible; if storage is down, the
|
|
1460
|
+
// ownership-fenced reservation remains and still blocks replay.
|
|
1461
|
+
let consumptionError = null;
|
|
1462
|
+
if (!consumptionCommitted && phase !== 'reserved' && typeof consumption.commit === 'function') {
|
|
1463
|
+
try {
|
|
1464
|
+
await consumption.commit(receiptId);
|
|
1465
|
+
consumptionCommitted = true;
|
|
1466
|
+
phase = 'consumed';
|
|
1467
|
+
runtimeMonitor?.consumptionCommitted(runtimeCycleId);
|
|
1468
|
+
}
|
|
1469
|
+
catch (commitError) {
|
|
1470
|
+
consumptionError = commitError;
|
|
1471
|
+
}
|
|
1472
|
+
}
|
|
1473
|
+
let indeterminateExecution = null;
|
|
1474
|
+
if (opts.recordExecution !== false && phase !== 'recording_execution') {
|
|
1475
|
+
try {
|
|
1476
|
+
indeterminateExecution = await recordExecution({
|
|
1477
|
+
authorization,
|
|
1478
|
+
outcome: 'indeterminate',
|
|
1479
|
+
// Exception text frequently contains provider payloads, record IDs,
|
|
1480
|
+
// or secrets. The caller still receives the original exception;
|
|
1481
|
+
// the portable evidence record carries only the closed outcome.
|
|
1482
|
+
detail: { code: 'effect_attempted_outcome_unknown' },
|
|
1483
|
+
observedAction,
|
|
1484
|
+
});
|
|
1485
|
+
const runtimeState = runtimeMonitor?.getState(runtimeCycleId);
|
|
1486
|
+
if (runtimeState && runtimeState.complete !== true) {
|
|
1487
|
+
runtimeMonitor?.executionRecorded(runtimeCycleId);
|
|
1488
|
+
}
|
|
1489
|
+
}
|
|
1490
|
+
catch (recordError) {
|
|
1491
|
+
if (!consumptionError)
|
|
1492
|
+
consumptionError = recordError;
|
|
1493
|
+
}
|
|
1494
|
+
}
|
|
1495
|
+
if (consumptionError && e && typeof e === 'object') {
|
|
1496
|
+
e.consumption_error = String(consumptionError?.message ?? consumptionError);
|
|
1497
|
+
}
|
|
1498
|
+
throw gateOutcomeError(e, {
|
|
1499
|
+
outcome: 'indeterminate',
|
|
1500
|
+
reason: 'effect_attempted_outcome_unknown',
|
|
1501
|
+
authorization,
|
|
1502
|
+
execution: indeterminateExecution,
|
|
1503
|
+
});
|
|
1504
|
+
}
|
|
1505
|
+
}
|
|
1506
|
+
/**
|
|
1507
|
+
* Wrap any function so it runs only behind a passing gate check, and (unless
|
|
1508
|
+
* disabled) emits an execution receipt after it runs — the full firewall loop:
|
|
1509
|
+
* request -> check -> execute -> execution receipt. Framework-agnostic.
|
|
1510
|
+
*/
|
|
1511
|
+
function guard(fn, opts = {}) {
|
|
1512
|
+
return async function guarded(...args) {
|
|
1513
|
+
// Guard providers may load the selector, receipt, or system-of-record
|
|
1514
|
+
// action asynchronously. Resolve each one before check() so a Promise
|
|
1515
|
+
// object can never be mistaken for a selector/receipt and accidentally
|
|
1516
|
+
// bypass the manifest's guarded action requirement.
|
|
1517
|
+
const selector = typeof opts.selector === 'function'
|
|
1518
|
+
? await opts.selector(...args)
|
|
1519
|
+
: (opts.selector || {});
|
|
1520
|
+
const receipt = typeof opts.receipt === 'function'
|
|
1521
|
+
? await opts.receipt(...args)
|
|
1522
|
+
: (opts.receipt ?? null);
|
|
1523
|
+
const observedAction = typeof opts.observedAction === 'function'
|
|
1524
|
+
? await opts.observedAction(...args)
|
|
1525
|
+
: (opts.observedAction || selector.observedAction || null);
|
|
1526
|
+
const admissibilityProfile = typeof opts.admissibilityProfile === 'function'
|
|
1527
|
+
? await opts.admissibilityProfile(...args)
|
|
1528
|
+
: (opts.admissibilityProfile ?? null);
|
|
1529
|
+
const presentedPacket = typeof opts.reliancePacket === 'function'
|
|
1530
|
+
? await opts.reliancePacket(...args)
|
|
1531
|
+
: (opts.reliancePacket ?? opts.admissibility ?? null);
|
|
1532
|
+
const capability = typeof opts.capability === 'function'
|
|
1533
|
+
? await opts.capability(...args)
|
|
1534
|
+
: (opts.capability ?? null);
|
|
1535
|
+
const out = await run({ selector, receipt, observedAction, admissibilityProfile, reliancePacket: presentedPacket, capability }, () => fn(...args), { recordExecution: opts.recordExecution });
|
|
1536
|
+
if (!out.ok) {
|
|
1537
|
+
const refusal = out.refusal || out.authorization;
|
|
1538
|
+
const e = new Error(`EMILIA Gate refused (${refusal.reason})`);
|
|
1539
|
+
e.code = 'EMILIA_RECEIPT_REQUIRED';
|
|
1540
|
+
e.gate = refusal;
|
|
1541
|
+
throw e;
|
|
1542
|
+
}
|
|
1543
|
+
return out.result;
|
|
1544
|
+
};
|
|
1545
|
+
}
|
|
1546
|
+
async function reliancePacket({ authorization, execution = null, binding = null, admissibility = null } = {}) {
|
|
1547
|
+
// The admissibility block rides on the authorization decision's evidence when
|
|
1548
|
+
// a reliance packet was presented at check() time; an explicit `admissibility`
|
|
1549
|
+
// arg overrides it. buildReliancePacket fails closed on a non-'admissible'
|
|
1550
|
+
// block, so a do_not_rely verdict can never be laundered into rely here.
|
|
1551
|
+
const adm = admissibility
|
|
1552
|
+
?? authorization?.evidence?.admissibility
|
|
1553
|
+
?? authorization?.admissibility
|
|
1554
|
+
?? null;
|
|
1555
|
+
return buildReliancePacket({
|
|
1556
|
+
decision: authorization,
|
|
1557
|
+
execution,
|
|
1558
|
+
evidence,
|
|
1559
|
+
manifest,
|
|
1560
|
+
binding: binding || execution?.execution_binding || null,
|
|
1561
|
+
admissibility: adm,
|
|
1562
|
+
});
|
|
1563
|
+
}
|
|
1564
|
+
/** Retention classification over this gate's evidence log (hot/cold/expired/legal-hold). */
|
|
1565
|
+
function retention(opts = {}) {
|
|
1566
|
+
return classifyRetention(evidence.all(), opts);
|
|
1567
|
+
}
|
|
1568
|
+
/** The auditor/SIEM export manifest for this gate's evidence log. */
|
|
1569
|
+
function retentionExport(opts = {}) {
|
|
1570
|
+
return buildRetentionExport(evidence.all(), opts);
|
|
1571
|
+
}
|
|
1572
|
+
return {
|
|
1573
|
+
check, run, recordExecution, route, wrapRoute: route, middleware, guard, reliancePacket, evidence,
|
|
1574
|
+
store: consumption, capabilityStore, keyRegistry: registry, retention, retentionExport,
|
|
1575
|
+
};
|
|
1576
|
+
}
|
|
1577
|
+
export function createTrustedActionFirewall(opts = {}) {
|
|
1578
|
+
const { manifest = createDefaultActionRiskManifest(), ...rest } = opts;
|
|
1579
|
+
return createGate({ ...rest, manifest });
|
|
1580
|
+
}
|
|
1581
|
+
/**
|
|
1582
|
+
* EG-1 conformance for an existing gate. The gate MUST have been built trusting
|
|
1583
|
+
* `harness.publicKey` (otherwise every valid receipt is rejected and the gate
|
|
1584
|
+
* cannot earn EG-1). Returns the EG-1 JSON report.
|
|
1585
|
+
* @param {object} [o]
|
|
1586
|
+
* @param {object} [o.gate] an EMILIA Gate (createGate/createTrustedActionFirewall)
|
|
1587
|
+
* @param {object} [o.harness] the harness whose key the gate trusts (createEg1Harness)
|
|
1588
|
+
* @param {object} [o.action] the high-risk action to exercise
|
|
1589
|
+
* @param {object} [o.selector] the manifest selector for that action
|
|
1590
|
+
*/
|
|
1591
|
+
export async function gateConformance({ gate, harness, action, selector = EG1_DEFAULT_SELECTOR } = {}) {
|
|
1592
|
+
if (!gate || typeof gate.run !== 'function') {
|
|
1593
|
+
throw new Error('gateConformance requires a gate built trusting harness.publicKey');
|
|
1594
|
+
}
|
|
1595
|
+
if (!harness)
|
|
1596
|
+
throw new Error('gateConformance requires the harness whose key the gate trusts');
|
|
1597
|
+
const act = action || harness.action;
|
|
1598
|
+
const invoke = makeGateInvoke(gate, { selector, action: act });
|
|
1599
|
+
return runEg1({ invoke, harness, action: act });
|
|
1600
|
+
}
|
|
1601
|
+
/**
|
|
1602
|
+
* Self-certify the reference gate: build a default Consequence Firewall that
|
|
1603
|
+
* trusts a fresh EG-1 harness key, then run all eight checks. This is the
|
|
1604
|
+
* canonical "EMILIA Gate earns EG-1" proof — runnable as a CLI (`eg1.mjs`),
|
|
1605
|
+
* shown on /gate, and the template an adopter copies for their integration.
|
|
1606
|
+
* @param {{now?: any}} [o]
|
|
1607
|
+
*/
|
|
1608
|
+
export async function gateConformanceSelfTest({ now } = {}) {
|
|
1609
|
+
const harness = createEg1Harness({ now });
|
|
1610
|
+
const gate = createTrustedActionFirewall({
|
|
1611
|
+
trustedKeys: [harness.publicKey], approverKeys: harness.approverKeys,
|
|
1612
|
+
rpId: harness.rpId, allowedOrigins: harness.allowedOrigins,
|
|
1613
|
+
now, allowEphemeralStore: true,
|
|
1614
|
+
});
|
|
1615
|
+
return gateConformance({ gate, harness });
|
|
1616
|
+
}
|
|
1617
|
+
/**
|
|
1618
|
+
* CF-1 (Consequence Firewall) conformance for an existing gate. Runs the eight
|
|
1619
|
+
* EG-1 runtime checks plus the three CF-1 category checks: the action is
|
|
1620
|
+
* declared consequential by the manifest, a gate pinned to the WRONG issuer key
|
|
1621
|
+
* refuses a valid receipt, and the allowed run emits offline-verifiable reliance
|
|
1622
|
+
* evidence. The `gate` MUST trust `harness.publicKey`; `wrongGate` MUST trust a
|
|
1623
|
+
* DIFFERENT key (otherwise wrong_authority_refused cannot be demonstrated).
|
|
1624
|
+
* @param {object} [o]
|
|
1625
|
+
* @param {object} [o.gate] an EMILIA Gate trusting harness.publicKey
|
|
1626
|
+
* @param {object} [o.wrongGate] a sibling gate trusting a different (wrong) key
|
|
1627
|
+
* @param {object} [o.harness] from createEg1Harness()
|
|
1628
|
+
* @param {object} [o.manifest] the action-risk manifest (to resolve the requirement)
|
|
1629
|
+
* @param {object} [o.selector] the manifest selector for the action
|
|
1630
|
+
* @param {object} [o.action] the high-risk action to exercise
|
|
1631
|
+
*/
|
|
1632
|
+
export async function cf1Conformance({ gate, wrongGate, harness, manifest = null, selector = EG1_DEFAULT_SELECTOR, action } = {}) {
|
|
1633
|
+
if (!gate || typeof gate.run !== 'function')
|
|
1634
|
+
throw new Error('cf1Conformance requires a gate built trusting harness.publicKey');
|
|
1635
|
+
if (!harness)
|
|
1636
|
+
throw new Error('cf1Conformance requires the harness whose key the gate trusts');
|
|
1637
|
+
const act = action || harness.action;
|
|
1638
|
+
const invoke = makeGateInvoke(gate, { selector, action: act });
|
|
1639
|
+
const wrongInvoke = (wrongGate && typeof wrongGate.run === 'function')
|
|
1640
|
+
? makeGateInvoke(wrongGate, { selector, action: act }) : undefined;
|
|
1641
|
+
const requirement = manifest ? findActionRequirement(manifest, selector) : null;
|
|
1642
|
+
return runCf1({ invoke, wrongInvoke, harness, action: act, requirement });
|
|
1643
|
+
}
|
|
1644
|
+
/**
|
|
1645
|
+
* Self-certify the reference gate against CF-1: a default Trusted Action
|
|
1646
|
+
* Firewall trusting a fresh harness key, a sibling firewall trusting a DIFFERENT
|
|
1647
|
+
* key (for wrong_authority_refused), and the default action-risk manifest (for
|
|
1648
|
+
* consequential_action_declared). The canonical "reference gate earns CF-1"
|
|
1649
|
+
* proof — runnable as a CLI (`cf1.mjs`).
|
|
1650
|
+
* @param {{now?: any}} [o]
|
|
1651
|
+
*/
|
|
1652
|
+
export async function cf1ConformanceSelfTest({ now } = {}) {
|
|
1653
|
+
const harness = createEg1Harness({ now });
|
|
1654
|
+
const manifest = createDefaultActionRiskManifest();
|
|
1655
|
+
const gate = createTrustedActionFirewall({
|
|
1656
|
+
trustedKeys: [harness.publicKey], approverKeys: harness.approverKeys,
|
|
1657
|
+
rpId: harness.rpId, allowedOrigins: harness.allowedOrigins,
|
|
1658
|
+
now, allowEphemeralStore: true,
|
|
1659
|
+
});
|
|
1660
|
+
const wrongHarness = createEg1Harness({ now });
|
|
1661
|
+
const wrongGate = createTrustedActionFirewall({
|
|
1662
|
+
trustedKeys: [wrongHarness.publicKey], approverKeys: wrongHarness.approverKeys,
|
|
1663
|
+
rpId: wrongHarness.rpId, allowedOrigins: wrongHarness.allowedOrigins,
|
|
1664
|
+
now, allowEphemeralStore: true,
|
|
1665
|
+
});
|
|
1666
|
+
return cf1Conformance({ gate, wrongGate, harness, manifest, selector: EG1_DEFAULT_SELECTOR, action: harness.action });
|
|
1667
|
+
}
|
|
1668
|
+
export default {
|
|
1669
|
+
createGate,
|
|
1670
|
+
createTrustedActionFirewall,
|
|
1671
|
+
runBreakGlass,
|
|
1672
|
+
receiptAssuranceTier,
|
|
1673
|
+
businessAuthorizationRequirement,
|
|
1674
|
+
verifyBusinessAuthorization,
|
|
1675
|
+
verifyAdmissibilityAgainstPinnedProfile,
|
|
1676
|
+
ADMISSIBILITY_VERDICTS,
|
|
1677
|
+
MemoryConsumptionStore,
|
|
1678
|
+
createEvidenceLog,
|
|
1679
|
+
createAtomicEvidenceLog,
|
|
1680
|
+
createMemoryAtomicEvidenceBackend,
|
|
1681
|
+
ASSURANCE_TIERS,
|
|
1682
|
+
DEFAULT_GATE_MANIFEST,
|
|
1683
|
+
HIGH_RISK_ACTION_PACKS,
|
|
1684
|
+
gateConformance,
|
|
1685
|
+
gateConformanceSelfTest,
|
|
1686
|
+
cf1Conformance,
|
|
1687
|
+
cf1ConformanceSelfTest,
|
|
1688
|
+
CF1_VERSION,
|
|
1689
|
+
CF1_CHECKS,
|
|
1690
|
+
runCf1,
|
|
1691
|
+
createEg1Harness,
|
|
1692
|
+
runEg1,
|
|
1693
|
+
createKeyRegistry,
|
|
1694
|
+
asKeyRegistry,
|
|
1695
|
+
classifyRetention,
|
|
1696
|
+
buildRetentionExport,
|
|
1697
|
+
createDefaultActionControlManifest,
|
|
1698
|
+
findActionControl,
|
|
1699
|
+
resolveActionControl,
|
|
1700
|
+
validateActionControlManifest,
|
|
1701
|
+
createRuntimeMonitor,
|
|
1702
|
+
RUNTIME_MONITOR_VERSION,
|
|
1703
|
+
RUNTIME_MONITOR_MODES,
|
|
1704
|
+
RUNTIME_INVARIANTS,
|
|
1705
|
+
FORMAL_RUNTIME_BRIDGE_VERSION,
|
|
1706
|
+
FORMAL_RUNTIME_SPEC,
|
|
1707
|
+
FORMAL_RUNTIME_CONFIG,
|
|
1708
|
+
FORMAL_RUNTIME_INVARIANT_MAP,
|
|
1709
|
+
CAPABILITY_RECEIPT_VERSION,
|
|
1710
|
+
CAPABILITY_STATE_VERSION,
|
|
1711
|
+
CAPABILITY_SHARE_VERSION,
|
|
1712
|
+
CAPABILITY_SCOPE_PROFILE,
|
|
1713
|
+
CAPABILITY_CAID_SCOPE_PROFILE,
|
|
1714
|
+
CAPABILITY_STATE_DDL,
|
|
1715
|
+
CAPABILITY_SQL,
|
|
1716
|
+
capabilityBaseReceiptDigest,
|
|
1717
|
+
capabilityActionDigest,
|
|
1718
|
+
verifyCapabilityScope,
|
|
1719
|
+
mintCapabilityReceipt,
|
|
1720
|
+
verifyCapabilityReceipt,
|
|
1721
|
+
splitCapabilitySecret,
|
|
1722
|
+
reconstructCapabilitySecret,
|
|
1723
|
+
createMemoryCapabilityStore,
|
|
1724
|
+
createPostgresCapabilityStore,
|
|
1725
|
+
executeWithCapability,
|
|
1726
|
+
executeWithThreshold,
|
|
1727
|
+
reconcileCapabilityOperation,
|
|
1728
|
+
ZK_RANGE_RECEIPT_VERSION,
|
|
1729
|
+
ZK_RANGE_SCHEME,
|
|
1730
|
+
ZK_RANGE_BACKEND_PACKAGE,
|
|
1731
|
+
deriveZkRangeBases,
|
|
1732
|
+
loadBulletproofBackend,
|
|
1733
|
+
mintZkRangeReceipt,
|
|
1734
|
+
verifyZkRangeReceipt,
|
|
1735
|
+
};
|
|
1736
|
+
//# sourceMappingURL=index.js.map
|