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