@decionis/agentsafe 0.2.5 → 0.4.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 (299) hide show
  1. package/README.md +264 -89
  2. package/dist/Cli.js +24 -0
  3. package/dist/Cli.js.map +1 -1
  4. package/dist/Index.d.ts +10 -4
  5. package/dist/Index.d.ts.map +1 -1
  6. package/dist/Index.js +8 -2
  7. package/dist/Index.js.map +1 -1
  8. package/dist/TrustedExecutor.d.ts.map +1 -1
  9. package/dist/TrustedExecutor.js +2 -0
  10. package/dist/TrustedExecutor.js.map +1 -1
  11. package/dist/adapters/AdapterActionHandler.d.ts.map +1 -1
  12. package/dist/adapters/AdapterActionHandler.js +8 -4
  13. package/dist/adapters/AdapterActionHandler.js.map +1 -1
  14. package/dist/adapters/EffectAdapter.d.ts +6 -1
  15. package/dist/adapters/EffectAdapter.d.ts.map +1 -1
  16. package/dist/adapters/EffectAdapter.js +7 -1
  17. package/dist/adapters/EffectAdapter.js.map +1 -1
  18. package/dist/adapters/EffectAwareGrantVerifier.d.ts +5 -2
  19. package/dist/adapters/EffectAwareGrantVerifier.d.ts.map +1 -1
  20. package/dist/adapters/EffectAwareGrantVerifier.js +9 -0
  21. package/dist/adapters/EffectAwareGrantVerifier.js.map +1 -1
  22. package/dist/adapters/banking/BankingAction.d.ts +2 -2
  23. package/dist/adapters/banking/CoreBankingHttpAdapter.d.ts.map +1 -1
  24. package/dist/adapters/banking/CoreBankingHttpAdapter.js +4 -4
  25. package/dist/adapters/banking/CoreBankingHttpAdapter.js.map +1 -1
  26. package/dist/adapters/cards/CardAuthorizationMatcher.d.ts +44 -0
  27. package/dist/adapters/cards/CardAuthorizationMatcher.d.ts.map +1 -0
  28. package/dist/adapters/cards/CardAuthorizationMatcher.js +39 -0
  29. package/dist/adapters/cards/CardAuthorizationMatcher.js.map +1 -0
  30. package/dist/adapters/cards/CardEffect.d.ts +52 -0
  31. package/dist/adapters/cards/CardEffect.d.ts.map +1 -0
  32. package/dist/adapters/cards/CardEffect.js +117 -0
  33. package/dist/adapters/cards/CardEffect.js.map +1 -0
  34. package/dist/adapters/cards/CardHandlers.d.ts +15 -0
  35. package/dist/adapters/cards/CardHandlers.d.ts.map +1 -0
  36. package/dist/adapters/cards/CardHandlers.js +26 -0
  37. package/dist/adapters/cards/CardHandlers.js.map +1 -0
  38. package/dist/adapters/cards/CardHoldSeal.d.ts +29 -0
  39. package/dist/adapters/cards/CardHoldSeal.d.ts.map +1 -0
  40. package/dist/adapters/cards/CardHoldSeal.js +87 -0
  41. package/dist/adapters/cards/CardHoldSeal.js.map +1 -0
  42. package/dist/adapters/cards/CardHoldStore.d.ts +102 -0
  43. package/dist/adapters/cards/CardHoldStore.d.ts.map +1 -0
  44. package/dist/adapters/cards/CardHoldStore.js +9 -0
  45. package/dist/adapters/cards/CardHoldStore.js.map +1 -0
  46. package/dist/adapters/cards/CardHolds.d.ts +19 -0
  47. package/dist/adapters/cards/CardHolds.d.ts.map +1 -0
  48. package/dist/adapters/cards/CardHolds.js +57 -0
  49. package/dist/adapters/cards/CardHolds.js.map +1 -0
  50. package/dist/adapters/cards/CardPurchase.d.ts +61 -0
  51. package/dist/adapters/cards/CardPurchase.d.ts.map +1 -0
  52. package/dist/adapters/cards/CardPurchase.js +116 -0
  53. package/dist/adapters/cards/CardPurchase.js.map +1 -0
  54. package/dist/adapters/cards/HeldCardGrants.d.ts +69 -0
  55. package/dist/adapters/cards/HeldCardGrants.d.ts.map +1 -0
  56. package/dist/adapters/cards/HeldCardGrants.js +169 -0
  57. package/dist/adapters/cards/HeldCardGrants.js.map +1 -0
  58. package/dist/adapters/cards/Pan.d.ts +17 -0
  59. package/dist/adapters/cards/Pan.d.ts.map +1 -0
  60. package/dist/adapters/cards/Pan.js +52 -0
  61. package/dist/adapters/cards/Pan.js.map +1 -0
  62. package/dist/adapters/cards/PostgresCardHolds.d.ts +95 -0
  63. package/dist/adapters/cards/PostgresCardHolds.d.ts.map +1 -0
  64. package/dist/adapters/cards/PostgresCardHolds.js +411 -0
  65. package/dist/adapters/cards/PostgresCardHolds.js.map +1 -0
  66. package/dist/adapters/mcp/McpGuard.d.ts.map +1 -1
  67. package/dist/adapters/mcp/McpGuard.js +9 -4
  68. package/dist/adapters/mcp/McpGuard.js.map +1 -1
  69. package/dist/audit/HashChain.d.ts +8 -2
  70. package/dist/audit/HashChain.d.ts.map +1 -1
  71. package/dist/audit/HashChain.js +14 -2
  72. package/dist/audit/HashChain.js.map +1 -1
  73. package/dist/cli/Cards.d.ts +5 -0
  74. package/dist/cli/Cards.d.ts.map +1 -0
  75. package/dist/cli/Cards.js +48 -0
  76. package/dist/cli/Cards.js.map +1 -0
  77. package/dist/cli/Commands.d.ts +1 -1
  78. package/dist/cli/Commands.d.ts.map +1 -1
  79. package/dist/cli/Commands.js +5 -0
  80. package/dist/cli/Commands.js.map +1 -1
  81. package/dist/cli/Edge.d.ts +4 -0
  82. package/dist/cli/Edge.d.ts.map +1 -0
  83. package/dist/cli/Edge.js +250 -0
  84. package/dist/cli/Edge.js.map +1 -0
  85. package/dist/cli/Help.d.ts.map +1 -1
  86. package/dist/cli/Help.js +9 -0
  87. package/dist/cli/Help.js.map +1 -1
  88. package/dist/cli/Host.d.ts +36 -0
  89. package/dist/cli/Host.d.ts.map +1 -0
  90. package/dist/cli/Host.js +247 -0
  91. package/dist/cli/Host.js.map +1 -0
  92. package/dist/cli/TcpBrokerCli.d.ts +4 -0
  93. package/dist/cli/TcpBrokerCli.d.ts.map +1 -0
  94. package/dist/cli/TcpBrokerCli.js +93 -0
  95. package/dist/cli/TcpBrokerCli.js.map +1 -0
  96. package/dist/cli/TcpClientCli.d.ts +16 -0
  97. package/dist/cli/TcpClientCli.d.ts.map +1 -0
  98. package/dist/cli/TcpClientCli.js +175 -0
  99. package/dist/cli/TcpClientCli.js.map +1 -0
  100. package/dist/config/ConfigKeys.d.ts +2 -2
  101. package/dist/config/ConfigKeys.d.ts.map +1 -1
  102. package/dist/config/ConfigKeys.js +31 -0
  103. package/dist/config/ConfigKeys.js.map +1 -1
  104. package/dist/config/ExecutorConfig.d.ts +115 -0
  105. package/dist/config/ExecutorConfig.d.ts.map +1 -1
  106. package/dist/config/ExecutorConfig.js +212 -0
  107. package/dist/config/ExecutorConfig.js.map +1 -1
  108. package/dist/edge/EdgeLicence.d.ts +25 -0
  109. package/dist/edge/EdgeLicence.d.ts.map +1 -0
  110. package/dist/edge/EdgeLicence.js +42 -0
  111. package/dist/edge/EdgeLicence.js.map +1 -0
  112. package/dist/edge/EdgeReplay.d.ts +45 -0
  113. package/dist/edge/EdgeReplay.d.ts.map +1 -0
  114. package/dist/edge/EdgeReplay.js +69 -0
  115. package/dist/edge/EdgeReplay.js.map +1 -0
  116. package/dist/edge/Entitlement.d.ts +57 -0
  117. package/dist/edge/Entitlement.d.ts.map +1 -0
  118. package/dist/edge/Entitlement.js +139 -0
  119. package/dist/edge/Entitlement.js.map +1 -0
  120. package/dist/edge/EntitlementEvaluation.d.ts +66 -0
  121. package/dist/edge/EntitlementEvaluation.d.ts.map +1 -0
  122. package/dist/edge/EntitlementEvaluation.js +74 -0
  123. package/dist/edge/EntitlementEvaluation.js.map +1 -0
  124. package/dist/edge/UsageCount.d.ts +40 -0
  125. package/dist/edge/UsageCount.d.ts.map +1 -0
  126. package/dist/edge/UsageCount.js +140 -0
  127. package/dist/edge/UsageCount.js.map +1 -0
  128. package/dist/edge/UsageKeyRegistration.d.ts +34 -0
  129. package/dist/edge/UsageKeyRegistration.d.ts.map +1 -0
  130. package/dist/edge/UsageKeyRegistration.js +74 -0
  131. package/dist/edge/UsageKeyRegistration.js.map +1 -0
  132. package/dist/edge/UsageMeter.d.ts +89 -0
  133. package/dist/edge/UsageMeter.d.ts.map +1 -0
  134. package/dist/edge/UsageMeter.js +275 -0
  135. package/dist/edge/UsageMeter.js.map +1 -0
  136. package/dist/edge/UsagePeriod.d.ts +23 -0
  137. package/dist/edge/UsagePeriod.d.ts.map +1 -0
  138. package/dist/edge/UsagePeriod.js +31 -0
  139. package/dist/edge/UsagePeriod.js.map +1 -0
  140. package/dist/edge/UsageReport.d.ts +92 -0
  141. package/dist/edge/UsageReport.d.ts.map +1 -0
  142. package/dist/edge/UsageReport.js +153 -0
  143. package/dist/edge/UsageReport.js.map +1 -0
  144. package/dist/edge/UsageTally.d.ts +63 -0
  145. package/dist/edge/UsageTally.d.ts.map +1 -0
  146. package/dist/edge/UsageTally.js +89 -0
  147. package/dist/edge/UsageTally.js.map +1 -0
  148. package/dist/egress/EgressError.d.ts +7 -1
  149. package/dist/egress/EgressError.d.ts.map +1 -1
  150. package/dist/egress/EgressError.js.map +1 -1
  151. package/dist/egress/EgressPolicy.d.ts +16 -3
  152. package/dist/egress/EgressPolicy.d.ts.map +1 -1
  153. package/dist/egress/EgressPolicy.js +33 -3
  154. package/dist/egress/EgressPolicy.js.map +1 -1
  155. package/dist/egress/GuardedFetch.d.ts +38 -1
  156. package/dist/egress/GuardedFetch.d.ts.map +1 -1
  157. package/dist/egress/GuardedFetch.js +52 -7
  158. package/dist/egress/GuardedFetch.js.map +1 -1
  159. package/dist/egress/TcpClient.d.ts +103 -0
  160. package/dist/egress/TcpClient.d.ts.map +1 -0
  161. package/dist/egress/TcpClient.js +490 -0
  162. package/dist/egress/TcpClient.js.map +1 -0
  163. package/dist/egress/TcpControlClient.d.ts +49 -0
  164. package/dist/egress/TcpControlClient.d.ts.map +1 -0
  165. package/dist/egress/TcpControlClient.js +186 -0
  166. package/dist/egress/TcpControlClient.js.map +1 -0
  167. package/dist/gateway/ForwardHandler.d.ts.map +1 -1
  168. package/dist/gateway/ForwardHandler.js +7 -4
  169. package/dist/gateway/ForwardHandler.js.map +1 -1
  170. package/dist/gateway/Gateway.d.ts +190 -10
  171. package/dist/gateway/Gateway.d.ts.map +1 -1
  172. package/dist/gateway/Gateway.js +465 -62
  173. package/dist/gateway/Gateway.js.map +1 -1
  174. package/dist/gateway/GatewayConfig.d.ts +67 -0
  175. package/dist/gateway/GatewayConfig.d.ts.map +1 -1
  176. package/dist/gateway/GatewayConfig.js +149 -2
  177. package/dist/gateway/GatewayConfig.js.map +1 -1
  178. package/dist/gateway/InterceptedRequest.d.ts +9 -2
  179. package/dist/gateway/InterceptedRequest.d.ts.map +1 -1
  180. package/dist/gateway/InterceptedRequest.js +41 -9
  181. package/dist/gateway/InterceptedRequest.js.map +1 -1
  182. package/dist/gateway/RateLimit.d.ts +29 -0
  183. package/dist/gateway/RateLimit.d.ts.map +1 -0
  184. package/dist/gateway/RateLimit.js +33 -0
  185. package/dist/gateway/RateLimit.js.map +1 -0
  186. package/dist/gateway/RefusalSampler.d.ts +28 -0
  187. package/dist/gateway/RefusalSampler.d.ts.map +1 -0
  188. package/dist/gateway/RefusalSampler.js +52 -0
  189. package/dist/gateway/RefusalSampler.js.map +1 -0
  190. package/dist/gateway/RouteTable.d.ts +3 -0
  191. package/dist/gateway/RouteTable.d.ts.map +1 -1
  192. package/dist/gateway/RouteTable.js +44 -7
  193. package/dist/gateway/RouteTable.js.map +1 -1
  194. package/dist/gateway/Upstream.d.ts +26 -0
  195. package/dist/gateway/Upstream.d.ts.map +1 -1
  196. package/dist/gateway/Upstream.js +41 -2
  197. package/dist/gateway/Upstream.js.map +1 -1
  198. package/dist/gateway/UpstreamProof.d.ts +235 -0
  199. package/dist/gateway/UpstreamProof.d.ts.map +1 -0
  200. package/dist/gateway/UpstreamProof.js +375 -0
  201. package/dist/gateway/UpstreamProof.js.map +1 -0
  202. package/dist/handlers/ForwardRequestHandler.d.ts +5 -1
  203. package/dist/handlers/ForwardRequestHandler.d.ts.map +1 -1
  204. package/dist/handlers/ForwardRequestHandler.js +12 -2
  205. package/dist/handlers/ForwardRequestHandler.js.map +1 -1
  206. package/dist/hosted/TenantHost.d.ts +180 -0
  207. package/dist/hosted/TenantHost.d.ts.map +1 -0
  208. package/dist/hosted/TenantHost.js +432 -0
  209. package/dist/hosted/TenantHost.js.map +1 -0
  210. package/dist/hosted/TenantRegistry.d.ts +73 -0
  211. package/dist/hosted/TenantRegistry.d.ts.map +1 -0
  212. package/dist/hosted/TenantRegistry.js +123 -0
  213. package/dist/hosted/TenantRegistry.js.map +1 -0
  214. package/dist/http/ExecutorHttpServer.d.ts +7 -0
  215. package/dist/http/ExecutorHttpServer.d.ts.map +1 -1
  216. package/dist/http/ExecutorHttpServer.js +30 -5
  217. package/dist/http/ExecutorHttpServer.js.map +1 -1
  218. package/dist/http/GatewayHttpServer.d.ts +55 -3
  219. package/dist/http/GatewayHttpServer.d.ts.map +1 -1
  220. package/dist/http/GatewayHttpServer.js +157 -17
  221. package/dist/http/GatewayHttpServer.js.map +1 -1
  222. package/dist/http/RedirectServer.d.ts +26 -0
  223. package/dist/http/RedirectServer.d.ts.map +1 -0
  224. package/dist/http/RedirectServer.js +62 -0
  225. package/dist/http/RedirectServer.js.map +1 -0
  226. package/dist/http/Routes.d.ts +24 -0
  227. package/dist/http/Routes.d.ts.map +1 -1
  228. package/dist/http/Routes.js +28 -1
  229. package/dist/http/Routes.js.map +1 -1
  230. package/dist/http/TcpBroker.d.ts +57 -0
  231. package/dist/http/TcpBroker.d.ts.map +1 -0
  232. package/dist/http/TcpBroker.js +299 -0
  233. package/dist/http/TcpBroker.js.map +1 -0
  234. package/dist/http/TcpHostRelay.d.ts +24 -0
  235. package/dist/http/TcpHostRelay.d.ts.map +1 -0
  236. package/dist/http/TcpHostRelay.js +194 -0
  237. package/dist/http/TcpHostRelay.js.map +1 -0
  238. package/dist/http/TcpRelayStreams.d.ts +24 -0
  239. package/dist/http/TcpRelayStreams.d.ts.map +1 -0
  240. package/dist/http/TcpRelayStreams.js +128 -0
  241. package/dist/http/TcpRelayStreams.js.map +1 -0
  242. package/dist/http/TlsListener.d.ts +3 -1
  243. package/dist/http/TlsListener.d.ts.map +1 -1
  244. package/dist/http/TlsListener.js +7 -2
  245. package/dist/http/TlsListener.js.map +1 -1
  246. package/dist/identity/Authenticator.d.ts.map +1 -1
  247. package/dist/identity/Authenticator.js +5 -2
  248. package/dist/identity/Authenticator.js.map +1 -1
  249. package/dist/identity/PrincipalsFile.d.ts +5 -1
  250. package/dist/identity/PrincipalsFile.d.ts.map +1 -1
  251. package/dist/identity/PrincipalsFile.js +2 -0
  252. package/dist/identity/PrincipalsFile.js.map +1 -1
  253. package/dist/incident/Metrics.d.ts +2 -0
  254. package/dist/incident/Metrics.d.ts.map +1 -1
  255. package/dist/incident/Metrics.js +10 -0
  256. package/dist/incident/Metrics.js.map +1 -1
  257. package/dist/incident/SecurityEvents.d.ts +98 -0
  258. package/dist/incident/SecurityEvents.d.ts.map +1 -1
  259. package/dist/incident/SecurityEvents.js +96 -2
  260. package/dist/incident/SecurityEvents.js.map +1 -1
  261. package/dist/journal/ExecutionJournal.d.ts +27 -0
  262. package/dist/journal/ExecutionJournal.d.ts.map +1 -1
  263. package/dist/journal/ExecutionJournal.js +28 -0
  264. package/dist/journal/ExecutionJournal.js.map +1 -1
  265. package/dist/journal/FileExecutionJournal.d.ts +2 -1
  266. package/dist/journal/FileExecutionJournal.d.ts.map +1 -1
  267. package/dist/journal/FileExecutionJournal.js +4 -1
  268. package/dist/journal/FileExecutionJournal.js.map +1 -1
  269. package/dist/journal/InMemoryExecutionJournal.d.ts +2 -1
  270. package/dist/journal/InMemoryExecutionJournal.d.ts.map +1 -1
  271. package/dist/journal/InMemoryExecutionJournal.js +4 -1
  272. package/dist/journal/InMemoryExecutionJournal.js.map +1 -1
  273. package/dist/service/AuthorityClients.d.ts +8 -1
  274. package/dist/service/AuthorityClients.d.ts.map +1 -1
  275. package/dist/service/AuthorityClients.js +33 -5
  276. package/dist/service/AuthorityClients.js.map +1 -1
  277. package/dist/service/EdgeRuntime.d.ts +73 -0
  278. package/dist/service/EdgeRuntime.d.ts.map +1 -0
  279. package/dist/service/EdgeRuntime.js +209 -0
  280. package/dist/service/EdgeRuntime.js.map +1 -0
  281. package/dist/service/EscalationResolver.d.ts +109 -5
  282. package/dist/service/EscalationResolver.d.ts.map +1 -1
  283. package/dist/service/EscalationResolver.js +41 -3
  284. package/dist/service/EscalationResolver.js.map +1 -1
  285. package/dist/service/Requests.d.ts +45 -2
  286. package/dist/service/Requests.d.ts.map +1 -1
  287. package/dist/service/TrustedExecutorService.d.ts +144 -1
  288. package/dist/service/TrustedExecutorService.d.ts.map +1 -1
  289. package/dist/service/TrustedExecutorService.js +866 -37
  290. package/dist/service/TrustedExecutorService.js.map +1 -1
  291. package/dist/tcp/TcpWire.d.ts +18 -0
  292. package/dist/tcp/TcpWire.d.ts.map +1 -0
  293. package/dist/tcp/TcpWire.js +114 -0
  294. package/dist/tcp/TcpWire.js.map +1 -0
  295. package/dist/verify/VerifyAuditChain.d.ts +5 -0
  296. package/dist/verify/VerifyAuditChain.d.ts.map +1 -1
  297. package/dist/verify/VerifyAuditChain.js +20 -4
  298. package/dist/verify/VerifyAuditChain.js.map +1 -1
  299. package/package.json +7 -3
@@ -1,3 +1,4 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { AuditRecorder, CanonicalIntentHasher, ExecutionIntentSchema, IntentCapture, } from "@decionis/agent-safe-pipeline";
2
3
  import { readFileSync } from "node:fs";
3
4
  import { EffectEvidenceRegister } from "../adapters/EffectEvidenceRegister.js";
@@ -5,13 +6,21 @@ import { effectBlock } from "../adapters/AdapterActionHandler.js";
5
6
  import { bindBankingAction, BindingError } from "../adapters/banking/BankingIntentBinder.js";
6
7
  import { BankingAdapter, BankingActionError } from "../adapters/banking/BankingAdapter.js";
7
8
  import { isBankingActionName } from "../adapters/banking/BankingAction.js";
9
+ import { matchCardAuthorization } from "../adapters/cards/CardAuthorizationMatcher.js";
10
+ import { cardExecutionResult, cardResultRecord, prepareCardPurchase, } from "../adapters/cards/CardEffect.js";
11
+ import { bindCardPurchase, CardActionError, cardAuthorizationOf, cardAuthorizationResultOf, cardPurchaseOf, isCardActionName, isCardReference, CARD_PURCHASE_ACTION, cardTarget, } from "../adapters/cards/CardPurchase.js";
12
+ import { postgresCardHolds } from "../adapters/cards/CardHolds.js";
13
+ import { CardHoldSeal } from "../adapters/cards/CardHoldSeal.js";
14
+ import { HeldCardGrants } from "../adapters/cards/HeldCardGrants.js";
15
+ import { CardHoldStoreError } from "../adapters/cards/PostgresCardHolds.js";
16
+ import { jcsDigest } from "../adapters/JcsDigest.js";
8
17
  import { HashChain } from "../audit/HashChain.js";
9
18
  import { EVIDENCE_STREAM, HashChainedAuditSink } from "../audit/HashChainedAuditSink.js";
10
19
  import { HaltSwitch } from "../incident/HaltSwitch.js";
11
20
  import { InMemoryExecutionJournal } from "../journal/InMemoryExecutionJournal.js";
12
21
  import { StartupReconciler } from "../journal/StartupReconciler.js";
13
22
  import { HardLimits } from "../limits/HardLimits.js";
14
- import { callerPrincipal, JournaledRegistry } from "../handlers/JournaledActionHandler.js";
23
+ import { callerPrincipal, JournaledRegistry, requestDigest, } from "../handlers/JournaledActionHandler.js";
15
24
  import { clockSkewGuard } from "../time/ClockSkewGuard.js";
16
25
  import { PrivateKeyJwtCredential } from "../credential/PrivateKeyJwtCredential.js";
17
26
  import { SignedRequestCredential } from "../credential/SignedRequestCredential.js";
@@ -28,9 +37,10 @@ import { EvidenceError, EvidenceExport, LineWindow, } from "../incident/Evidence
28
37
  import { RequestContext } from "../http/RequestContext.js";
29
38
  import { AuthorityClients } from "./AuthorityClients.js";
30
39
  import { packageVersion } from "../Version.js";
31
- import { EscalationHandoffSchema, } from "./EscalationResolver.js";
40
+ import { EscalationResumeSchema, } from "./EscalationResolver.js";
32
41
  import { ProposalRequestSchema, ReconciliationRequestSchema, } from "./Requests.js";
33
42
  import { HaltRequestSchema, ResumeRequestSchema } from "./Requests.js";
43
+ import { EdgeRuntime } from "./EdgeRuntime.js";
34
44
  import { ServiceError } from "./ServiceError.js";
35
45
  /**
36
46
  * The execution boundary as one process. In `ENFORCEMENT` it asks Decionis,
@@ -90,6 +100,20 @@ function nonSecretConfiguration(config) {
90
100
  window_seconds: config.limits.windowSeconds,
91
101
  },
92
102
  max_clock_skew_ms: config.maxClockSkewMs,
103
+ decision: {
104
+ authority: config.decision.authority,
105
+ edge: config.edge === null
106
+ ? null
107
+ : {
108
+ org_id: config.edge.orgId,
109
+ bundle_source: config.edge.bundle.source,
110
+ refresh_seconds: config.edge.refreshSeconds,
111
+ on_unavailable: config.edge.onUnavailable,
112
+ replay_store: config.edge.replay.store,
113
+ usage_reports: config.edge.usage.signing,
114
+ installation_id: config.edge.usage.installationId,
115
+ },
116
+ },
93
117
  };
94
118
  }
95
119
  /** An Ed25519 detached JWS over the manifest, from the configured key. */
@@ -99,6 +123,8 @@ async function signBundle(secrets, payload) {
99
123
  const key = await importPKCS8(pem, "EdDSA");
100
124
  return await new CompactSign(payload).setProtectedHeader({ alg: "EdDSA" }).sign(key);
101
125
  }
126
+ /** The provider id an escalation requirement names for Decionis Presence. */
127
+ const DECIONIS_PRESENCE_PROVIDER = "decionis";
102
128
  export class TrustedExecutorService {
103
129
  config;
104
130
  secrets;
@@ -120,15 +146,35 @@ export class TrustedExecutorService {
120
146
  haltSwitch;
121
147
  limits;
122
148
  unsubscribeMetrics;
149
+ effects;
150
+ cards;
151
+ cardsTimer;
152
+ edge;
123
153
  hasher = new CanonicalIntentHasher();
124
154
  recovery = null;
155
+ /**
156
+ * Authorizations evaluated at the commit boundary and escalated, by id:
157
+ * answered the same way until their intent expires, so a platform that
158
+ * re-presents one is told the same thing and nothing is evaluated twice.
159
+ */
160
+ pendingCommits = new Map();
161
+ /** Bound before any await: one authorization id may claim only one request. */
162
+ cardClaims = new Map();
125
163
  constructor(config, secrets, capture, registry, registered, clients, posture, egress,
126
164
  /** Where an incident's evidence is written, when the configuration names a directory. */
127
165
  evidence,
128
166
  /** The security stream this service writes to; a test drives the halt through it. */
129
167
  events, chain, metrics, principals,
130
168
  /** The workload token verifier, when the configuration names a JWKS; the door uses it. */
131
- jwt, credential, audit, journal, haltSwitch, limits, unsubscribeMetrics) {
169
+ jwt, credential, audit, journal, haltSwitch, limits, unsubscribeMetrics,
170
+ /** The effect observations the verifier finalizes with; the cards family registers into it. */
171
+ effects,
172
+ /** Card grants held for the issuer's authorization, and the authorizations that claimed one. */
173
+ cards,
174
+ /** The shared hold store's hourly sweep, while it runs. */
175
+ cardsTimer = null,
176
+ /** The edge evaluator, when the configuration asks for it. */
177
+ edge = null) {
132
178
  this.config = config;
133
179
  this.secrets = secrets;
134
180
  this.capture = capture;
@@ -149,6 +195,10 @@ export class TrustedExecutorService {
149
195
  this.haltSwitch = haltSwitch;
150
196
  this.limits = limits;
151
197
  this.unsubscribeMetrics = unsubscribeMetrics;
198
+ this.effects = effects;
199
+ this.cards = cards;
200
+ this.cardsTimer = cardsTimer;
201
+ this.edge = edge;
152
202
  }
153
203
  /**
154
204
  * Wires the boundary. `handlers` is the adopter's seam: it registers what
@@ -172,8 +222,9 @@ export class TrustedExecutorService {
172
222
  const auditWindow = new LineWindow(config.evidence.windowLines);
173
223
  const securityWindow = new LineWindow(config.evidence.windowLines);
174
224
  events.tap((line) => securityWindow.push(line));
225
+ const evidenceWriter = auditWindow.tee(emit);
175
226
  const audit = new AuditRecorder({
176
- sink: new HashChainedAuditSink(auditWindow.tee(emit), chain),
227
+ sink: new HashChainedAuditSink(evidenceWriter, chain),
177
228
  failurePolicy: "REQUIRE_BEFORE_EXECUTION",
178
229
  });
179
230
  // Every connection this process opens, the authority's and the Presence
@@ -239,8 +290,25 @@ export class TrustedExecutorService {
239
290
  observe: (skew) => metrics.clockSkew.set(skew),
240
291
  onExceeded: (skew) => halt.halt("CLOCK_SKEW", `${skew}ms from the authority`),
241
292
  });
293
+ // The edge evaluator, built once: a module that is not a valid ABI 3
294
+ // module refuses the start here, before anything listens.
295
+ const edge = EdgeRuntime.create({
296
+ config,
297
+ secrets,
298
+ apiKey: () => secrets.get("DECIONIS_API_KEY").use((value) => value.toString("utf8")),
299
+ fetch: egress.fetch,
300
+ events,
301
+ chain,
302
+ write: evidenceWriter,
303
+ ...(dependencies.loadEdgeModule === undefined
304
+ ? {}
305
+ : { loadModule: dependencies.loadEdgeModule }),
306
+ ...(dependencies.loadPg === undefined ? {} : { loadPg: dependencies.loadPg }),
307
+ ...(dependencies.clock === undefined ? {} : { clock: dependencies.clock }),
308
+ });
242
309
  const clients = new AuthorityClients({
243
310
  config,
311
+ edge,
244
312
  secrets,
245
313
  registry,
246
314
  audit,
@@ -248,6 +316,11 @@ export class TrustedExecutorService {
248
316
  fetch: authorityFetch,
249
317
  effects,
250
318
  observer: { id: config.banking.adapterId, version: config.banking.adapterVersion },
319
+ // A recovery reference is the caller's claim; the journal is what this
320
+ // process dispatched, so reconciliation is held against it.
321
+ attempts: {
322
+ authorizationsOf: async (captured) => await journal.authorizationsOf(captured.intent.intentId),
323
+ },
251
324
  ...(dependencies.presence === undefined ? {} : { presence: dependencies.presence }),
252
325
  });
253
326
  const posture = dependencies.posture ?? { degraded: false };
@@ -297,6 +370,50 @@ export class TrustedExecutorService {
297
370
  for (const stop of unsubscribeRotations)
298
371
  stop();
299
372
  unsubscribeEvents();
373
+ }, effects, TrustedExecutorService.cardHolds(config, secrets, clients, dependencies), null, edge);
374
+ }
375
+ /**
376
+ * Where card holds live: this process, or the store every replica shares,
377
+ * whose rows are sealed under the hold key. A hold or a claim another
378
+ * replica made is admitted here through the executor's own checks, with
379
+ * the claim material that replica sealed.
380
+ */
381
+ static cardHolds(config, secrets, clients, dependencies) {
382
+ const clock = dependencies.clock;
383
+ if (config.cards.holds.store === "memory") {
384
+ return new HeldCardGrants(clock === undefined ? {} : { clock });
385
+ }
386
+ const { table, namespace } = config.cards.holds;
387
+ return postgresCardHolds({
388
+ databaseUrl: () => secrets
389
+ .get("EXECUTOR_CARD_HOLDS_DATABASE_URL")
390
+ .use((value) => value.toString("utf8").trim()),
391
+ seal: () => secrets
392
+ .get("EXECUTOR_CARD_HOLDS_KEY")
393
+ .use((value) => CardHoldSeal.fromText(value.toString("utf8"))),
394
+ namespace,
395
+ table,
396
+ adopt: {
397
+ hold: async (captured, decision) => {
398
+ const { executor } = clients.current();
399
+ const outcome = await executor.adoptHold(captured, decision);
400
+ return outcome.outcome === "HELD" ? { held: outcome.held, executor } : null;
401
+ },
402
+ claim: (captured, decision, authorization, material) => {
403
+ const { executor } = clients.current();
404
+ try {
405
+ return {
406
+ held: executor.adoptClaim(captured, decision, authorization, material),
407
+ executor,
408
+ };
409
+ }
410
+ catch {
411
+ return null;
412
+ }
413
+ },
414
+ },
415
+ ...(dependencies.loadPg === undefined ? {} : { load: dependencies.loadPg }),
416
+ ...(clock === undefined ? {} : { clock }),
300
417
  });
301
418
  }
302
419
  /** The credential the configuration's kind names, over the secret store and the guarded fetch. */
@@ -368,12 +485,39 @@ export class TrustedExecutorService {
368
485
  get escalationMode() {
369
486
  return this.config.escalation.mode;
370
487
  }
488
+ /**
489
+ * Loads the edge evaluator's first bundle and starts its refresh schedule.
490
+ * A first fetch that fails is not a refusal to start: until a bundle
491
+ * loads, decisions follow the configured `onUnavailable`.
492
+ */
493
+ async startEdge() {
494
+ await this.edge?.start();
495
+ }
496
+ /**
497
+ * Probes the shared hold store, when there is one: a store that cannot be
498
+ * reached is a refusal to start, since no authorization could then match,
499
+ * and then sweeps it hourly for what lapsed.
500
+ */
501
+ async startCards() {
502
+ if (this.cards.kind === "memory")
503
+ return;
504
+ await this.cards.ready();
505
+ this.cardsTimer ??= setInterval(() => {
506
+ void this.cards.cleanup().catch(() => undefined);
507
+ }, 60 * 60_000);
508
+ this.cardsTimer.unref();
509
+ }
371
510
  /** The actions this process can run, for `/ready`. */
372
511
  get actions() {
373
512
  return this.registered.filter((action) => this.registry.has(action));
374
513
  }
375
514
  /** Stops following credential rotation and closes every outbound connection; the service answers nothing new after this. */
376
515
  close() {
516
+ this.edge?.stop();
517
+ if (this.cardsTimer !== null)
518
+ clearInterval(this.cardsTimer);
519
+ this.cardsTimer = null;
520
+ void this.cards.close().catch(() => undefined);
377
521
  this.clients.close();
378
522
  this.egress.close();
379
523
  this.jwt?.stop();
@@ -510,7 +654,8 @@ export class TrustedExecutorService {
510
654
  this.events.emit({ event: "SEPARATION_OF_DUTIES_VIOLATED", principal: proposer.id });
511
655
  throw new ServiceError(422, "SEPARATION_OF_DUTIES_VIOLATED");
512
656
  }
513
- const captured = this.captureIntent(request, proposer);
657
+ const velocity = await this.cardVelocity(request);
658
+ const captured = this.captureIntent(request, proposer, velocity);
514
659
  // Every line this proposal causes names the proposer, whichever
515
660
  // transport asked; the door's own scope, when there is one, agrees.
516
661
  return await RequestContext.run({ principal: proposer.id }, async () => {
@@ -525,6 +670,7 @@ export class TrustedExecutorService {
525
670
  try {
526
671
  this.assertNotHalted(captured);
527
672
  this.assertWithinLimits(captured, "CHECK");
673
+ await this.assertCardSpendable(captured);
528
674
  }
529
675
  catch (error) {
530
676
  if (error instanceof ServiceError)
@@ -572,6 +718,29 @@ export class TrustedExecutorService {
572
718
  reasonCodes: [reason],
573
719
  });
574
720
  }
721
+ /**
722
+ * One spendable hold per card and merchant: a purchase at a merchant where
723
+ * the card already has one waits until it is authorised or expires,
724
+ * refused before the authority is asked so the refusal costs no dossier
725
+ * and no grant. The same card at another merchant holds in parallel.
726
+ */
727
+ async assertCardSpendable(captured) {
728
+ if (!isCardActionName(captured.intent.action))
729
+ return;
730
+ // An intent presented back is re-read here, so a card number written into
731
+ // one after capture is refused like one in a proposal.
732
+ let purchase;
733
+ try {
734
+ purchase = cardPurchaseOf(captured.intent.parameters);
735
+ }
736
+ catch (error) {
737
+ throw new ServiceError(422, error.code);
738
+ }
739
+ const key = { cardTokenRef: purchase.cardTokenRef, merchantId: purchase.merchantId };
740
+ if (await this.cards.spendable(key)) {
741
+ throw new ServiceError(409, "CARD_GRANT_ALREADY_HELD");
742
+ }
743
+ }
575
744
  /** The host's own ceilings, before the authority is asked and again before the run. */
576
745
  assertWithinLimits(captured, stage) {
577
746
  if (this.limits === null)
@@ -600,8 +769,10 @@ export class TrustedExecutorService {
600
769
  this.assertOwn(captured, proposer);
601
770
  const outcome = await RequestContext.run({ principal: proposer.id }, () => this.clients.current().executor.reconcile(captured, parsed.data.reference));
602
771
  // A resolved attempt is closed in the journal, so the next start does not
603
- // ask the provider about it again.
604
- if (outcome.outcome !== "UNKNOWN_AFTER_DISPATCH") {
772
+ // ask the provider about it again. A refused reconciliation resolved
773
+ // nothing: closing on it would let any presented reference, however
774
+ // wrong, take a genuinely open attempt off the next start's list.
775
+ if (outcome.outcome === "COMPLETED" || outcome.outcome === "DEFINITELY_NOT_EXECUTED") {
605
776
  try {
606
777
  await this.journal.append({
607
778
  record: "RECONCILED",
@@ -639,15 +810,28 @@ export class TrustedExecutorService {
639
810
  * intent past its lifetime is refused before anything is asked.
640
811
  */
641
812
  async resume(input, caller) {
642
- const proposer = this.proposer(caller);
643
- const parsed = EscalationHandoffSchema.safeParse(input);
813
+ // The proposer that holds the intent resumes it. An operator holding
814
+ // `escalations.resume` (the issuer app's backend, where a cardholder's
815
+ // tap lands) may present a presence provider's attestation for an intent
816
+ // it did not propose, and nothing else: the authority binds the
817
+ // attestation to the intent hash, so the operator adds no authority.
818
+ const proposer = caller?.role === "OPERATOR" ? null : this.proposer(caller);
819
+ const presenter = proposer ?? TrustedExecutorService.presenter(caller);
820
+ const parsed = EscalationResumeSchema.safeParse(input);
644
821
  if (!parsed.success)
645
822
  throw new ServiceError(400, "REQUEST_INVALID");
646
- if (this.config.mode === "SHADOW" || this.config.escalation.mode === "NONE") {
823
+ const resume = parsed.data;
824
+ // An attestation needs no escalation shape: it is evidence for a fresh
825
+ // evaluation, which any enforcing executor can ask for.
826
+ const attested = resume.mode === "ATTESTATION";
827
+ if (proposer === null && !attested)
828
+ throw new ServiceError(403, "ROLE_FORBIDDEN");
829
+ if (this.config.mode === "SHADOW" || (!attested && this.config.escalation.mode === "NONE")) {
647
830
  throw new ServiceError(409, "ESCALATION_NOT_CONFIGURED");
648
831
  }
649
- const captured = this.presented(parsed.data.intent);
650
- this.assertOwn(captured, proposer);
832
+ const captured = this.presented(resume.intent);
833
+ if (proposer !== null)
834
+ this.assertOwn(captured, proposer);
651
835
  if (Date.parse(captured.intent.expiresAt) <= Date.now()) {
652
836
  throw new ServiceError(409, "INTENT_EXPIRED");
653
837
  }
@@ -655,9 +839,10 @@ export class TrustedExecutorService {
655
839
  throw new ServiceError(422, "ACTION_NOT_REGISTERED");
656
840
  }
657
841
  this.assertPosture();
658
- return await RequestContext.run({ principal: proposer.id }, async () => {
842
+ return await RequestContext.run({ principal: presenter.id }, async () => {
659
843
  try {
660
844
  this.assertNotHalted(captured);
845
+ await this.assertCardSpendable(captured);
661
846
  }
662
847
  catch (error) {
663
848
  if (error instanceof ServiceError)
@@ -665,16 +850,13 @@ export class TrustedExecutorService {
665
850
  throw error;
666
851
  }
667
852
  const { escalation, executor } = this.clients.current();
668
- const resolution = await escalation.resume(captured, parsed.data);
853
+ if (resume.mode === "ATTESTATION") {
854
+ const decision = await escalation.attest(captured, resume.attestation);
855
+ return await this.decide(captured, decision, executor);
856
+ }
857
+ const resolution = await escalation.resume(captured, resume);
669
858
  if (resolution.kind === "DECISION") {
670
- if (resolution.decision.verdict === "ALLOW" && !resolution.decision.failClosed) {
671
- this.assertWithinLimits(captured, "COMMIT");
672
- await this.openAttempt(captured, resolution.decision);
673
- }
674
- const outcome = await executor.run(captured, resolution.decision);
675
- await this.closeAttempt(captured, resolution.decision, outcome);
676
- this.metrics.executions.inc({ outcome: outcome.outcome });
677
- return this.response(captured, resolution.decision, outcome, null);
859
+ return await this.decide(captured, resolution.decision, executor);
678
860
  }
679
861
  if (resolution.kind === "PENDING") {
680
862
  return this.held(captured, "ESCALATE", resolution.reasonCodes, false, {
@@ -685,6 +867,26 @@ export class TrustedExecutorService {
685
867
  return this.held(captured, "BLOCK", resolution.reasonCodes, resolution.failClosed, null);
686
868
  });
687
869
  }
870
+ /**
871
+ * A fresh decision on a resumed escalation: a card purchase's grant is held
872
+ * for the issuer, anything else runs once on an `ALLOW`.
873
+ */
874
+ async decide(captured, decision, executor) {
875
+ if (isCardActionName(captured.intent.action)) {
876
+ const held = await this.holdCard(captured, decision, executor);
877
+ if ("mode" in held)
878
+ return held;
879
+ return this.response(captured, decision, held, null);
880
+ }
881
+ if (decision.verdict === "ALLOW" && !decision.failClosed) {
882
+ this.assertWithinLimits(captured, "COMMIT");
883
+ await this.openAttempt(captured, decision);
884
+ }
885
+ const outcome = await executor.run(captured, decision);
886
+ await this.closeAttempt(captured, decision, outcome);
887
+ this.metrics.executions.inc({ outcome: outcome.outcome });
888
+ return this.response(captured, decision, outcome, null);
889
+ }
688
890
  /**
689
891
  * The attempt, on disk, before the executor may run it. A journal that
690
892
  * cannot take the record refuses the proposal rather than executing
@@ -755,6 +957,16 @@ export class TrustedExecutorService {
755
957
  }
756
958
  return principal;
757
959
  }
960
+ /**
961
+ * An operator may present an attestation only under `escalations.resume`;
962
+ * without it the operator is no presenter at all, and the refusal is the
963
+ * door's: a role the route does not admit.
964
+ */
965
+ static presenter(caller) {
966
+ if (!caller.scopes.has("escalations.resume"))
967
+ throw new ServiceError(403, "ROLE_FORBIDDEN");
968
+ return caller;
969
+ }
758
970
  operator(caller, scope) {
759
971
  if (caller === undefined || caller.role !== "OPERATOR")
760
972
  throw new ServiceError(403, "ROLE_FORBIDDEN");
@@ -772,7 +984,24 @@ export class TrustedExecutorService {
772
984
  if (!own)
773
985
  throw new ServiceError(403, "INTENT_PRINCIPAL_MISMATCH");
774
986
  }
775
- captureIntent(request, proposer) {
987
+ /**
988
+ * The burst on this card, counted before capture because the store may be
989
+ * shared and is asked asynchronously; a purchase the binder will refuse
990
+ * is not counted, and the binder's own refusal follows.
991
+ */
992
+ async cardVelocity(request) {
993
+ if (!isCardActionName(request.proposal.action))
994
+ return null;
995
+ let purchase;
996
+ try {
997
+ purchase = cardPurchaseOf(request.proposal.parameters);
998
+ }
999
+ catch {
1000
+ return null;
1001
+ }
1002
+ return await this.cards.velocity(purchase.cardTokenRef);
1003
+ }
1004
+ captureIntent(request, proposer, velocity = null, extra = {}) {
776
1005
  // A BEAP action carries its own canonical form in the parameters, so the
777
1006
  // transport's name and target are derived from it rather than trusted,
778
1007
  // and the digests the authority binds its grant to are computed here
@@ -781,6 +1010,17 @@ export class TrustedExecutorService {
781
1010
  const bound = isBankingActionName(request.proposal.action)
782
1011
  ? this.bindBanking(request, proposer)
783
1012
  : null;
1013
+ const card = isCardActionName(request.proposal.action) ? this.bindCard(request) : null;
1014
+ const context = {
1015
+ caller_principal: proposer.id,
1016
+ ...(bound === null ? {} : bound.context),
1017
+ ...extra,
1018
+ };
1019
+ // The burst on this card, counted here because policy counts nothing over
1020
+ // time: how many purchases were held for it and claimed lately. Numbers
1021
+ // only; the card reference stays in the parameters.
1022
+ if (card !== null && velocity !== null)
1023
+ context["card_velocity"] = { ...velocity };
784
1024
  const trusted = {
785
1025
  tenantId: proposer.tenantId,
786
1026
  actor: proposer.actor,
@@ -789,10 +1029,11 @@ export class TrustedExecutorService {
789
1029
  operation: this.config.downstream.operation,
790
1030
  environment: this.config.downstream.environment,
791
1031
  },
792
- context: { caller_principal: proposer.id, ...(bound === null ? {} : bound.context) },
1032
+ context,
793
1033
  idempotencyKey: request.idempotency_key,
794
1034
  ...(request.correlation_id === undefined ? {} : { correlationId: request.correlation_id }),
795
1035
  ...(bound === null ? {} : { expectedEffectDigest: bound.expectedEffectDigest }),
1036
+ ...(card === null ? {} : { expectedEffectDigest: card.expectedEffectDigest }),
796
1037
  };
797
1038
  const parameters = request.proposal.parameters ?? {};
798
1039
  try {
@@ -827,6 +1068,57 @@ export class TrustedExecutorService {
827
1068
  throw new ServiceError(422, "BANKING_ACTION_INVALID");
828
1069
  }
829
1070
  }
1071
+ /**
1072
+ * The cards binder: the purchase is read and refused here, a card number
1073
+ * above all, and the target is derived from the card. What comes back is
1074
+ * the expected-effect digest the authority binds its grant to.
1075
+ */
1076
+ bindCard(request) {
1077
+ try {
1078
+ const purchase = bindCardPurchase({
1079
+ target: request.proposal.target,
1080
+ parameters: request.proposal.parameters ?? {},
1081
+ });
1082
+ return {
1083
+ expectedEffectDigest: prepareCardPurchase(purchase).expectedEffectDigest,
1084
+ cardTokenRef: purchase.cardTokenRef,
1085
+ };
1086
+ }
1087
+ catch (error) {
1088
+ throw new ServiceError(422, error.code);
1089
+ }
1090
+ }
1091
+ /** The hold's routing as the handoff carries it, from the decision when the authority said. */
1092
+ static attestationRequirement(decision) {
1093
+ const routing = decision.escalationRequirement;
1094
+ if (routing === undefined)
1095
+ return null;
1096
+ return {
1097
+ requirement_id: routing.requirementId,
1098
+ expires_at: routing.expiresAt,
1099
+ selector: routing.selector === null
1100
+ ? null
1101
+ : {
1102
+ kind: routing.selector.kind,
1103
+ ...(routing.selector.roleId === undefined
1104
+ ? {}
1105
+ : { role_id: routing.selector.roleId }),
1106
+ },
1107
+ verification: routing.verification === null
1108
+ ? null
1109
+ : {
1110
+ provider: routing.verification.provider,
1111
+ methods: [...routing.verification.methods],
1112
+ level: routing.verification.level,
1113
+ },
1114
+ };
1115
+ }
1116
+ /** Whether the policy sent the hold to a presence provider other than Decionis Presence. */
1117
+ static routedToProvider(requirement) {
1118
+ return (requirement !== null &&
1119
+ requirement.verification !== null &&
1120
+ requirement.verification.provider !== DECIONIS_PRESENCE_PROVIDER);
1121
+ }
830
1122
  /**
831
1123
  * The two digests a banking intent is bound to, taken from the profile's
832
1124
  * own arithmetic. This reaches nothing: `prepare` is pure, which is why
@@ -957,26 +1249,562 @@ export class TrustedExecutorService {
957
1249
  async enforce(captured) {
958
1250
  const { escalation, executor } = this.clients.current();
959
1251
  const decision = await escalation.evaluate(captured);
960
- // Every decision goes through the executor, an ESCALATE or BLOCK included,
961
- // so the audit stream carries the refusal as well as the execution.
962
- if (decision.verdict === "ALLOW" && !decision.failClosed) {
963
- this.assertWithinLimits(captured, "COMMIT");
964
- await this.openAttempt(captured, decision);
1252
+ const card = isCardActionName(captured.intent.action);
1253
+ let outcome;
1254
+ if (card) {
1255
+ // A card purchase is answered before the issuer ever asks: on an ALLOW
1256
+ // the grant is held, not claimed, and the response says so.
1257
+ const held = await this.holdCard(captured, decision, executor);
1258
+ if ("mode" in held)
1259
+ return held;
1260
+ outcome = held;
1261
+ }
1262
+ else {
1263
+ // Every decision goes through the executor, an ESCALATE or BLOCK
1264
+ // included, so the audit stream carries the refusal as well as the
1265
+ // execution.
1266
+ if (decision.verdict === "ALLOW" && !decision.failClosed) {
1267
+ this.assertWithinLimits(captured, "COMMIT");
1268
+ await this.openAttempt(captured, decision);
1269
+ }
1270
+ outcome = await executor.run(captured, decision);
1271
+ await this.closeAttempt(captured, decision, outcome);
1272
+ this.metrics.executions.inc({ outcome: outcome.outcome });
965
1273
  }
966
- const outcome = await executor.run(captured, decision);
967
- await this.closeAttempt(captured, decision, outcome);
968
- this.metrics.executions.inc({ outcome: outcome.outcome });
969
1274
  let handoff = null;
970
1275
  let unavailable = false;
971
1276
  if (decision.verdict === "ESCALATE" && !decision.failClosed) {
972
- const state = await escalation.handoff(captured, decision);
973
- if (state !== null)
974
- handoff = { ...state, intent: captured.intent };
975
- else if (this.config.escalation.mode !== "NONE")
976
- unavailable = true;
1277
+ const requirement = TrustedExecutorService.attestationRequirement(decision);
1278
+ if (TrustedExecutorService.routedToProvider(requirement)) {
1279
+ // The policy sent this hold to a third-party presence provider (a
1280
+ // cardholder's tap through the issuer's app): no Presence ceremony
1281
+ // is asked for, and only that provider's attestation resumes it.
1282
+ handoff = { mode: "ATTESTATION", intent: captured.intent, requirement };
1283
+ }
1284
+ else {
1285
+ const state = await escalation.handoff(captured, decision);
1286
+ if (state !== null)
1287
+ handoff = { ...state, intent: captured.intent };
1288
+ // A cardholder's tap needs no Presence ceremony: whatever shape this
1289
+ // executor escalates in, a card purchase can be resumed with an
1290
+ // attestation over the intent it is handed here.
1291
+ else if (card)
1292
+ handoff = { mode: "ATTESTATION", intent: captured.intent, requirement };
1293
+ else if (this.config.escalation.mode !== "NONE")
1294
+ unavailable = true;
1295
+ }
977
1296
  }
978
1297
  return this.response(captured, decision, outcome, handoff, unavailable ? ["ESCALATION_HANDOFF_UNAVAILABLE"] : []);
979
1298
  }
1299
+ /**
1300
+ * Admits a card purchase's decision exactly as a run would and holds its
1301
+ * grant for the issuer's authorization, keyed by the card and the
1302
+ * merchant. Nothing is
1303
+ * claimed and nothing runs; the hard ceilings are committed now, because
1304
+ * this is the last moment this process decides anything about the amount.
1305
+ * A refusal comes back as the executor's own blocked result.
1306
+ */
1307
+ async holdCard(captured, decision, executor) {
1308
+ if (decision.verdict === "ALLOW" && !decision.failClosed) {
1309
+ this.assertWithinLimits(captured, "COMMIT");
1310
+ }
1311
+ const outcome = await executor.hold(captured, decision);
1312
+ if (outcome.outcome !== "HELD") {
1313
+ this.metrics.executions.inc({ outcome: outcome.outcome });
1314
+ return outcome;
1315
+ }
1316
+ const purchase = cardPurchaseOf(captured.intent.parameters);
1317
+ const stored = await this.cards.hold({
1318
+ cardTokenRef: purchase.cardTokenRef,
1319
+ amountMinor: purchase.amountMinor,
1320
+ currency: purchase.currency,
1321
+ merchantId: purchase.merchantId,
1322
+ mcc: purchase.mcc ?? null,
1323
+ expiresAtMs: Date.parse(outcome.held.expiresAt),
1324
+ used: false,
1325
+ purchase,
1326
+ prepared: prepareCardPurchase(purchase),
1327
+ held: outcome.held,
1328
+ executor,
1329
+ });
1330
+ // A card that gained a spendable hold while this one was being decided,
1331
+ // or a full store: the grant is left unclaimed and expires with no effect.
1332
+ const status = stored ? "HELD_FOR_AUTHORIZATION" : "BLOCKED";
1333
+ this.metrics.executions.inc({ outcome: status });
1334
+ if (stored)
1335
+ this.events.emit({ event: "CARD_GRANT_HELD", intent_id: captured.intent.intentId });
1336
+ return {
1337
+ mode: "ENFORCEMENT",
1338
+ intent_id: captured.intent.intentId,
1339
+ intent_hash: captured.intentHash,
1340
+ verdict: decision.verdict,
1341
+ decision_id: decision.decisionId,
1342
+ dossier_id: decision.dossierId,
1343
+ reason_codes: stored
1344
+ ? [...decision.reasonCodes]
1345
+ : [...decision.reasonCodes, "CARD_HOLD_UNAVAILABLE"],
1346
+ fail_closed: false,
1347
+ outcome: status,
1348
+ executed: false,
1349
+ authorization: null,
1350
+ finalization: null,
1351
+ result: stored
1352
+ ? { status: "HELD_FOR_AUTHORIZATION", expires_at: outcome.held.expiresAt }
1353
+ : null,
1354
+ effect: null,
1355
+ recovery: null,
1356
+ escalation: null,
1357
+ };
1358
+ }
1359
+ /**
1360
+ * The issuer's real-time authorization hook. The answer has to come back in
1361
+ * milliseconds, so the only network call is the claim itself: the match is
1362
+ * pure, against a grant decided before the card was presented. A match
1363
+ * claims the grant once, and a second authorization for it is a
1364
+ * `NO_MATCH`; an issuer retrying the same authorization is given the same
1365
+ * answer, with no second claim. What `NO_MATCH` means for the purchase is
1366
+ * the issuer's policy, not this process's.
1367
+ */
1368
+ async authorizeCard(input, caller) {
1369
+ const operator = this.operator(caller, "cards.authorize");
1370
+ const request = TrustedExecutorService.cardRequest(() => cardAuthorizationOf(input));
1371
+ let previous;
1372
+ try {
1373
+ previous = await this.cards.claimed(request.authorization_id);
1374
+ }
1375
+ catch {
1376
+ return this.noMatch(null, "CARD_HOLDS_UNAVAILABLE");
1377
+ }
1378
+ if (previous !== undefined) {
1379
+ if (jcsDigest(previous.request) === jcsDigest(request)) {
1380
+ return previous.answer;
1381
+ }
1382
+ // An issuer that may present the same authorization for more, up to
1383
+ // the ceiling and before its result, is answered from the same claim:
1384
+ // nothing new is claimed, and the result records the final amount.
1385
+ if (this.config.cards.authorizations === "incremental" &&
1386
+ TrustedExecutorService.incrementOf(previous, request) &&
1387
+ (await this.cards.amend(request.authorization_id, request))) {
1388
+ this.events.emit({
1389
+ event: "CARD_AUTHORIZATION_INCREMENTED",
1390
+ intent_id: previous.answer.intent_id,
1391
+ });
1392
+ return previous.answer;
1393
+ }
1394
+ return this.noMatch(null, "AUTHORIZATION_ID_REUSED");
1395
+ }
1396
+ const digest = jcsDigest(request);
1397
+ const pending = this.cardClaims.get(request.authorization_id);
1398
+ if (pending !== undefined) {
1399
+ return pending.digest === digest
1400
+ ? await pending.answer
1401
+ : this.noMatch(null, "AUTHORIZATION_ID_REUSED");
1402
+ }
1403
+ if (this.cardClaims.size >= 10_000) {
1404
+ return this.noMatch(null, "CARD_AUTHORIZATION_CAPACITY_EXCEEDED");
1405
+ }
1406
+ // Reserve the id synchronously, before journal/claim I/O can yield to a
1407
+ // conflicting request. Identical concurrent retries share the same result.
1408
+ const answer = Promise.resolve().then(() => this.claimCard(request, operator.id));
1409
+ this.cardClaims.set(request.authorization_id, { digest, answer });
1410
+ try {
1411
+ return await answer;
1412
+ }
1413
+ finally {
1414
+ this.cardClaims.delete(request.authorization_id);
1415
+ }
1416
+ }
1417
+ async claimCard(request, callerId, evaluated = false) {
1418
+ if (this.haltSwitch.current.halted)
1419
+ return this.noMatch(null, "EXECUTOR_HALTED");
1420
+ if (this.posture.degraded)
1421
+ return this.noMatch(null, "POSTURE_DEGRADED");
1422
+ let record;
1423
+ try {
1424
+ record = await this.cards.grant({
1425
+ cardTokenRef: request.card_token_ref,
1426
+ merchantId: request.merchant_id,
1427
+ });
1428
+ }
1429
+ catch {
1430
+ return this.noMatch(null, "CARD_HOLDS_UNAVAILABLE");
1431
+ }
1432
+ if (record === undefined) {
1433
+ // A hold the commit-boundary evaluation just made and the store cannot
1434
+ // show is not evaluated again: the answer says the hold was lost.
1435
+ if (evaluated)
1436
+ return this.noMatch(null, "CARD_HOLD_UNAVAILABLE");
1437
+ return await this.withoutGrant(request, callerId);
1438
+ }
1439
+ const match = matchCardAuthorization(record, TrustedExecutorService.cardView(request), Date.now());
1440
+ if (match.decision === "NO_MATCH")
1441
+ return this.noMatch(record.intentId, match.code);
1442
+ // The hold with a handle this process can claim; one another replica
1443
+ // made is admitted here first, through the executor's own checks.
1444
+ let matched;
1445
+ try {
1446
+ matched = await record.open();
1447
+ }
1448
+ catch {
1449
+ return this.noMatch(record.intentId, "CARD_HOLDS_UNAVAILABLE");
1450
+ }
1451
+ if (matched === null)
1452
+ return this.noMatch(record.intentId, "GRANT_CLAIM_REFUSED");
1453
+ // Spent before anything else is awaited, by the one rule every replica
1454
+ // shares, so a concurrent authorization for the same grant finds it used
1455
+ // rather than racing this one to the claim.
1456
+ let spent;
1457
+ try {
1458
+ spent = await this.cards.spend(matched);
1459
+ }
1460
+ catch {
1461
+ return this.noMatch(record.intentId, "CARD_HOLDS_UNAVAILABLE");
1462
+ }
1463
+ if (!spent)
1464
+ return this.noMatch(record.intentId, "GRANT_ALREADY_USED");
1465
+ const { captured, decision } = matched.held;
1466
+ const intentId = captured.intent.intentId;
1467
+ try {
1468
+ await this.openAttempt(captured, decision);
1469
+ }
1470
+ catch {
1471
+ return this.noMatch(intentId, "JOURNAL_UNAVAILABLE");
1472
+ }
1473
+ const claim = await matched.executor.claimHeld(matched.held);
1474
+ if (claim.outcome !== "CLAIMED") {
1475
+ await this.closeAttempt(captured, decision, claim);
1476
+ this.metrics.executions.inc({ outcome: claim.outcome });
1477
+ return this.noMatch(intentId, "GRANT_CLAIM_REFUSED");
1478
+ }
1479
+ const authorization = claim.authorization;
1480
+ // The claim is made durable before the issuer is told to approve: there is
1481
+ // no effect without a record a restart can find, exactly as for a run.
1482
+ try {
1483
+ await this.journal.append({
1484
+ record: "GRANT_CLAIMED",
1485
+ at: new Date().toISOString(),
1486
+ intent_id: intentId,
1487
+ intent_hash: captured.intentHash,
1488
+ idempotency_key: captured.intent.idempotencyKey,
1489
+ grant_id: authorization.grantId,
1490
+ expires_at: authorization.expiresAt,
1491
+ request_digest: requestDigest(captured.intent.parameters),
1492
+ });
1493
+ }
1494
+ catch {
1495
+ this.events.emit({ event: "JOURNAL_WRITE_FAILED", record: "GRANT_CLAIMED" });
1496
+ if (this.config.evidence.journalRequired) {
1497
+ const finalization = await matched.executor.settleHeld(matched.held, "FAILED");
1498
+ await this.closeCardAttempt(captured, "DEFINITELY_NOT_EXECUTED", false, finalization);
1499
+ return this.noMatch(intentId, "JOURNAL_UNAVAILABLE");
1500
+ }
1501
+ }
1502
+ const lease = authorization.leaseExpiresAt ?? authorization.expiresAt;
1503
+ const answer = {
1504
+ decision: "APPROVE",
1505
+ authorization_id: request.authorization_id,
1506
+ intent_id: intentId,
1507
+ intent_hash: captured.intentHash,
1508
+ decision_id: authorization.decisionId,
1509
+ dossier_id: authorization.dossierId,
1510
+ grant_id: authorization.grantId,
1511
+ lease_expires_at: lease,
1512
+ };
1513
+ try {
1514
+ await this.cards.recordClaim(request.authorization_id, {
1515
+ grant: matched,
1516
+ request,
1517
+ authorization,
1518
+ leaseExpiresAtMs: Date.parse(lease),
1519
+ answer,
1520
+ material: matched.executor.claimMaterial(authorization),
1521
+ });
1522
+ }
1523
+ catch {
1524
+ // The claim is journaled and the issuer is answered; a record the
1525
+ // shared store could not keep is a result this replica alone can
1526
+ // settle, which the journal's open attempt still shows.
1527
+ this.events.emit({ event: "CARD_CLAIM_RECORD_FAILED", intent_id: intentId });
1528
+ }
1529
+ this.metrics.executions.inc({ outcome: "CARD_AUTHORIZATION_MATCHED" });
1530
+ this.events.emit({ event: "CARD_AUTHORIZATION_MATCHED", intent_id: intentId });
1531
+ return answer;
1532
+ }
1533
+ /**
1534
+ * An authorization with no hold. By default it is `NO_MATCH`: nothing was
1535
+ * decided before the card was presented. A deployment that evaluates at
1536
+ * the commit boundary answers it from an evaluation made now, and one
1537
+ * already evaluated and escalated is answered the same way until its
1538
+ * intent expires, so a platform that re-presents it is told the same thing
1539
+ * and nothing is evaluated twice. Once the tap has resumed the hold, the
1540
+ * re-presented authorization finds it before it gets here.
1541
+ */
1542
+ async withoutGrant(request, callerId) {
1543
+ if (this.config.cards.noGrant !== "evaluate")
1544
+ return this.noMatch(null, "NO_GRANT");
1545
+ const pending = this.pendingCommits.get(request.authorization_id);
1546
+ if (pending !== undefined) {
1547
+ if (Date.parse(pending.answer.expires_at) <= Date.now()) {
1548
+ this.pendingCommits.delete(request.authorization_id);
1549
+ }
1550
+ else if (pending.digest === jcsDigest(request)) {
1551
+ return pending.answer;
1552
+ }
1553
+ else {
1554
+ return this.noMatch(pending.answer.intent_id, "AUTHORIZATION_ID_REUSED");
1555
+ }
1556
+ }
1557
+ return await this.evaluateAtCommit(request, callerId);
1558
+ }
1559
+ /**
1560
+ * The commit boundary: the authorization becomes the intent, captured as
1561
+ * the commit actor the deployment names and evaluated now, with the
1562
+ * authorization's id in the intent's context so the dossier says what it
1563
+ * decided about. An `ALLOW` is held and claimed in this same call. An
1564
+ * `ESCALATE` is `PENDING`, with the handoff: a platform that can pend keeps
1565
+ * the authorization waiting, the tap arrives through `POST /v1/escalations`
1566
+ * with the handoff's intent, and the re-presented authorization matches the
1567
+ * hold the tap left. A `BLOCK`, a refusal this host makes on its own, and
1568
+ * an authority that did not answer are `NO_MATCH` with their code. In
1569
+ * shadow the evaluation is observed and the authorization is `NO_MATCH`.
1570
+ */
1571
+ async evaluateAtCommit(request, callerId) {
1572
+ const commit = this.config.cards.commit;
1573
+ if (commit === null)
1574
+ return this.noMatch(null, "NO_GRANT");
1575
+ const parameters = {
1576
+ cardTokenRef: request.card_token_ref,
1577
+ amountMinor: request.amount_minor,
1578
+ currency: request.currency,
1579
+ merchantId: request.merchant_id,
1580
+ ...(request.mcc === undefined ? {} : { mcc: request.mcc }),
1581
+ };
1582
+ const proposal = {
1583
+ proposal: {
1584
+ action: CARD_PURCHASE_ACTION,
1585
+ target: cardTarget({ cardTokenRef: request.card_token_ref }),
1586
+ parameters,
1587
+ },
1588
+ idempotency_key: TrustedExecutorService.commitIdempotencyKey(request.authorization_id),
1589
+ };
1590
+ const identity = {
1591
+ id: callerId,
1592
+ tenantId: commit.tenantId,
1593
+ actor: commit.actor,
1594
+ };
1595
+ let captured;
1596
+ try {
1597
+ captured = this.captureIntent(proposal, identity, await this.cards.velocity(request.card_token_ref), {
1598
+ commit_boundary: "ISSUER_HOOK",
1599
+ card_authorization: { authorization_id: request.authorization_id },
1600
+ });
1601
+ }
1602
+ catch (error) {
1603
+ return this.noMatch(null, error instanceof ServiceError ? error.code : "PROPOSAL_INVALID");
1604
+ }
1605
+ return await RequestContext.run({ principal: callerId }, async () => {
1606
+ if (this.config.mode === "SHADOW") {
1607
+ const observed = await this.observe(captured);
1608
+ this.metrics.proposals.inc({ verdict: observed.verdict ?? "NONE" });
1609
+ return this.noMatch(captured.intent.intentId, "SHADOW_OBSERVED");
1610
+ }
1611
+ try {
1612
+ this.assertNotHalted(captured);
1613
+ this.assertWithinLimits(captured, "CHECK");
1614
+ }
1615
+ catch (error) {
1616
+ if (!(error instanceof ServiceError))
1617
+ throw error;
1618
+ await this.recordRefusal(captured, error.code);
1619
+ return this.noMatch(captured.intent.intentId, error.code);
1620
+ }
1621
+ let answer;
1622
+ try {
1623
+ answer = await this.enforceAfterPosture(captured);
1624
+ }
1625
+ catch (error) {
1626
+ if (!(error instanceof ServiceError))
1627
+ throw error;
1628
+ return this.noMatch(captured.intent.intentId, error.code);
1629
+ }
1630
+ this.metrics.proposals.inc({ verdict: answer.verdict ?? "NONE" });
1631
+ if (answer.outcome === "HELD_FOR_AUTHORIZATION") {
1632
+ return await this.claimCard(request, callerId, true);
1633
+ }
1634
+ if (answer.verdict === "ESCALATE" && answer.escalation !== null) {
1635
+ const pending = {
1636
+ decision: "PENDING",
1637
+ authorization_id: request.authorization_id,
1638
+ intent_id: answer.intent_id,
1639
+ intent_hash: answer.intent_hash,
1640
+ decision_id: answer.decision_id,
1641
+ dossier_id: answer.dossier_id,
1642
+ expires_at: captured.intent.expiresAt,
1643
+ escalation: answer.escalation,
1644
+ };
1645
+ this.rememberPending(request, pending);
1646
+ this.metrics.executions.inc({ outcome: "CARD_AUTHORIZATION_PENDING" });
1647
+ this.events.emit({ event: "CARD_AUTHORIZATION_PENDING", intent_id: answer.intent_id });
1648
+ return pending;
1649
+ }
1650
+ return this.noMatch(answer.intent_id, answer.fail_closed ? "AUTHORITY_UNAVAILABLE" : "POLICY_BLOCK");
1651
+ });
1652
+ }
1653
+ /** Bounded like the claims: a full map forgets its oldest, whose intent is nearest its expiry. */
1654
+ rememberPending(request, answer) {
1655
+ if (this.pendingCommits.size >= 10_000) {
1656
+ const oldest = this.pendingCommits.keys().next().value;
1657
+ this.pendingCommits.delete(oldest);
1658
+ }
1659
+ this.pendingCommits.set(request.authorization_id, {
1660
+ digest: jcsDigest(request),
1661
+ answer,
1662
+ });
1663
+ }
1664
+ /** The intent's idempotency key names the authorization; one too long for the key is named by its digest. */
1665
+ static commitIdempotencyKey(authorizationId) {
1666
+ const key = `card-authorization:${authorizationId}`;
1667
+ if (key.length <= 180)
1668
+ return key;
1669
+ return `card-authorization:sha256:${createHash("sha256").update(authorizationId, "utf8").digest("hex")}`;
1670
+ }
1671
+ /**
1672
+ * What the issuer did with an authorization it was told to approve. An
1673
+ * approval is the effect, compared with what the grant authorised; a
1674
+ * decline is a refusal; and a result after the claim's lease is recorded
1675
+ * as indeterminate, because the authority no longer accepts a commit for
1676
+ * it. Recorded once.
1677
+ */
1678
+ async settleCard(authorizationId, input, caller) {
1679
+ this.operator(caller, "cards.authorize");
1680
+ if (!isCardReference(authorizationId))
1681
+ throw new ServiceError(400, "REQUEST_INVALID");
1682
+ const result = TrustedExecutorService.cardRequest(() => cardAuthorizationResultOf(input));
1683
+ let claim;
1684
+ try {
1685
+ claim = await this.cards.claimed(authorizationId);
1686
+ }
1687
+ catch (error) {
1688
+ if (error instanceof CardHoldStoreError)
1689
+ throw new ServiceError(503, error.code);
1690
+ throw new ServiceError(503, "CARD_HOLDS_UNAVAILABLE");
1691
+ }
1692
+ if (claim === undefined)
1693
+ throw new ServiceError(404, "CARD_AUTHORIZATION_UNKNOWN");
1694
+ // Settled once, by the one rule every replica shares.
1695
+ if (claim.settled || !(await this.cards.settle(authorizationId))) {
1696
+ throw new ServiceError(409, "CARD_RESULT_ALREADY_RECORDED");
1697
+ }
1698
+ const { grant, authorization } = claim;
1699
+ const { captured } = grant.held;
1700
+ const leaseExpired = Date.now() > claim.leaseExpiresAtMs;
1701
+ const record = cardResultRecord({
1702
+ purchase: grant.purchase,
1703
+ prepared: grant.prepared,
1704
+ authorization: claim.request,
1705
+ result,
1706
+ leaseExpired,
1707
+ observer: { id: this.config.banking.adapterId, version: this.config.banking.adapterVersion },
1708
+ correlationId: captured.intent.intentId,
1709
+ idempotencyKey: captured.intent.idempotencyKey,
1710
+ observedAt: new Date().toISOString(),
1711
+ });
1712
+ // The verifier finalizes with exactly this observation, by the
1713
+ // authorization it belongs to.
1714
+ this.effects.attach(authorization, record);
1715
+ const finalization = await grant.executor.settleHeld(grant.held, record.outcome);
1716
+ const executed = record.outcome === "COMMITTED" ? true : record.outcome === "FAILED" ? false : null;
1717
+ await this.closeCardAttempt(captured, record.outcome === "COMMITTED"
1718
+ ? "COMPLETED"
1719
+ : record.outcome === "FAILED"
1720
+ ? "DEFINITELY_NOT_EXECUTED"
1721
+ : "INDETERMINATE_AFTER_LEASE", executed, finalization);
1722
+ this.metrics.executions.inc({ outcome: `CARD_${record.outcome}` });
1723
+ if (finalization === "PENDING") {
1724
+ this.events.emit({
1725
+ event: "FINALIZATION_PENDING",
1726
+ intent_id: captured.intent.intentId,
1727
+ outcome: record.outcome,
1728
+ });
1729
+ }
1730
+ this.metrics.finalizations.inc({ status: finalization });
1731
+ this.events.emit({
1732
+ event: "CARD_AUTHORIZATION_SETTLED",
1733
+ intent_id: captured.intent.intentId,
1734
+ outcome: record.outcome,
1735
+ });
1736
+ const effect = this.effect(captured, cardExecutionResult(record));
1737
+ return {
1738
+ authorization_id: authorizationId,
1739
+ intent_id: captured.intent.intentId,
1740
+ intent_hash: captured.intentHash,
1741
+ outcome: record.outcome,
1742
+ executed,
1743
+ finalization,
1744
+ reason_codes: [
1745
+ ...(leaseExpired ? ["CLAIM_LEASE_EXPIRED"] : []),
1746
+ ...TrustedExecutorService.effectReasons(effect),
1747
+ ],
1748
+ effect,
1749
+ };
1750
+ }
1751
+ /** A card attempt's end, in the journal, so a restart does not ask about it again. */
1752
+ async closeCardAttempt(captured, outcome, executed, finalization) {
1753
+ try {
1754
+ await this.journal.append({
1755
+ record: "ATTEMPT_CLOSED",
1756
+ at: new Date().toISOString(),
1757
+ intent_id: captured.intent.intentId,
1758
+ intent_hash: captured.intentHash,
1759
+ outcome,
1760
+ executed,
1761
+ finalization,
1762
+ });
1763
+ }
1764
+ catch {
1765
+ this.events.emit({ event: "JOURNAL_WRITE_FAILED", record: "ATTEMPT_CLOSED" });
1766
+ }
1767
+ }
1768
+ noMatch(intentId, code) {
1769
+ this.events.emit({ event: "CARD_AUTHORIZATION_NO_MATCH", intent_id: intentId, code });
1770
+ return { decision: "NO_MATCH", code };
1771
+ }
1772
+ /** A card request read, or the refusal that names why; a card number is its own refusal. */
1773
+ static cardRequest(read) {
1774
+ try {
1775
+ return read();
1776
+ }
1777
+ catch (error) {
1778
+ const code = error instanceof CardActionError ? error.code : "REQUEST_INVALID";
1779
+ throw new ServiceError(code === "CARD_PAN_REFUSED" ? 422 : 400, code);
1780
+ }
1781
+ }
1782
+ /**
1783
+ * Whether a re-presented authorization is an increment of the claim it
1784
+ * names: the same card, currency, merchant and category, for more than
1785
+ * before and no more than the grant's ceiling, while the claim is still
1786
+ * open and inside its lease.
1787
+ */
1788
+ static incrementOf(previous, request) {
1789
+ const before = previous.request;
1790
+ return (!previous.settled &&
1791
+ Date.now() <= previous.leaseExpiresAtMs &&
1792
+ request.card_token_ref === before.card_token_ref &&
1793
+ request.currency === before.currency &&
1794
+ request.merchant_id === before.merchant_id &&
1795
+ (request.mcc ?? null) === (before.mcc ?? null) &&
1796
+ request.amount_minor > before.amount_minor &&
1797
+ request.amount_minor <= previous.grant.amountMinor);
1798
+ }
1799
+ static cardView(request) {
1800
+ return {
1801
+ cardTokenRef: request.card_token_ref,
1802
+ amountMinor: request.amount_minor,
1803
+ currency: request.currency,
1804
+ merchantId: request.merchant_id,
1805
+ mcc: request.mcc ?? null,
1806
+ };
1807
+ }
980
1808
  response(captured, decision, outcome, handoff, extraReasonCodes = []) {
981
1809
  const effect = this.effect(captured, outcome.result);
982
1810
  // A finalization the authority did not take is the authority's lease
@@ -1001,6 +1829,7 @@ export class TrustedExecutorService {
1001
1829
  reason_codes: [
1002
1830
  ...decision.reasonCodes,
1003
1831
  ...("reason" in outcome && outcome.reason !== "DECISION_NOT_ALLOW" ? [outcome.reason] : []),
1832
+ ...("code" in outcome && outcome.code !== undefined ? [outcome.code] : []),
1004
1833
  ...TrustedExecutorService.effectReasons(effect),
1005
1834
  ...extraReasonCodes,
1006
1835
  ],