@decionis/agentsafe 0.2.5 → 0.3.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 (271) hide show
  1. package/README.md +135 -20
  2. package/dist/Cli.js +19 -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 +1 -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/banking/CoreBankingHttpAdapter.d.ts.map +1 -1
  19. package/dist/adapters/banking/CoreBankingHttpAdapter.js +4 -4
  20. package/dist/adapters/banking/CoreBankingHttpAdapter.js.map +1 -1
  21. package/dist/adapters/cards/CardAuthorizationMatcher.d.ts +44 -0
  22. package/dist/adapters/cards/CardAuthorizationMatcher.d.ts.map +1 -0
  23. package/dist/adapters/cards/CardAuthorizationMatcher.js +39 -0
  24. package/dist/adapters/cards/CardAuthorizationMatcher.js.map +1 -0
  25. package/dist/adapters/cards/CardEffect.d.ts +52 -0
  26. package/dist/adapters/cards/CardEffect.d.ts.map +1 -0
  27. package/dist/adapters/cards/CardEffect.js +117 -0
  28. package/dist/adapters/cards/CardEffect.js.map +1 -0
  29. package/dist/adapters/cards/CardHandlers.d.ts +15 -0
  30. package/dist/adapters/cards/CardHandlers.d.ts.map +1 -0
  31. package/dist/adapters/cards/CardHandlers.js +26 -0
  32. package/dist/adapters/cards/CardHandlers.js.map +1 -0
  33. package/dist/adapters/cards/CardPurchase.d.ts +61 -0
  34. package/dist/adapters/cards/CardPurchase.d.ts.map +1 -0
  35. package/dist/adapters/cards/CardPurchase.js +116 -0
  36. package/dist/adapters/cards/CardPurchase.js.map +1 -0
  37. package/dist/adapters/cards/HeldCardGrants.d.ts +70 -0
  38. package/dist/adapters/cards/HeldCardGrants.d.ts.map +1 -0
  39. package/dist/adapters/cards/HeldCardGrants.js +79 -0
  40. package/dist/adapters/cards/HeldCardGrants.js.map +1 -0
  41. package/dist/adapters/cards/Pan.d.ts +17 -0
  42. package/dist/adapters/cards/Pan.d.ts.map +1 -0
  43. package/dist/adapters/cards/Pan.js +52 -0
  44. package/dist/adapters/cards/Pan.js.map +1 -0
  45. package/dist/adapters/mcp/McpGuard.d.ts.map +1 -1
  46. package/dist/adapters/mcp/McpGuard.js +9 -4
  47. package/dist/adapters/mcp/McpGuard.js.map +1 -1
  48. package/dist/audit/HashChain.d.ts +8 -2
  49. package/dist/audit/HashChain.d.ts.map +1 -1
  50. package/dist/audit/HashChain.js +14 -2
  51. package/dist/audit/HashChain.js.map +1 -1
  52. package/dist/cli/Commands.d.ts +1 -1
  53. package/dist/cli/Commands.d.ts.map +1 -1
  54. package/dist/cli/Commands.js +5 -0
  55. package/dist/cli/Commands.js.map +1 -1
  56. package/dist/cli/Edge.d.ts +4 -0
  57. package/dist/cli/Edge.d.ts.map +1 -0
  58. package/dist/cli/Edge.js +250 -0
  59. package/dist/cli/Edge.js.map +1 -0
  60. package/dist/cli/Help.d.ts.map +1 -1
  61. package/dist/cli/Help.js +8 -0
  62. package/dist/cli/Help.js.map +1 -1
  63. package/dist/cli/Host.d.ts +36 -0
  64. package/dist/cli/Host.d.ts.map +1 -0
  65. package/dist/cli/Host.js +247 -0
  66. package/dist/cli/Host.js.map +1 -0
  67. package/dist/cli/TcpBrokerCli.d.ts +4 -0
  68. package/dist/cli/TcpBrokerCli.d.ts.map +1 -0
  69. package/dist/cli/TcpBrokerCli.js +93 -0
  70. package/dist/cli/TcpBrokerCli.js.map +1 -0
  71. package/dist/cli/TcpClientCli.d.ts +16 -0
  72. package/dist/cli/TcpClientCli.d.ts.map +1 -0
  73. package/dist/cli/TcpClientCli.js +175 -0
  74. package/dist/cli/TcpClientCli.js.map +1 -0
  75. package/dist/config/ConfigKeys.d.ts +2 -2
  76. package/dist/config/ConfigKeys.d.ts.map +1 -1
  77. package/dist/config/ConfigKeys.js +19 -0
  78. package/dist/config/ConfigKeys.js.map +1 -1
  79. package/dist/config/ExecutorConfig.d.ts +62 -0
  80. package/dist/config/ExecutorConfig.d.ts.map +1 -1
  81. package/dist/config/ExecutorConfig.js +124 -0
  82. package/dist/config/ExecutorConfig.js.map +1 -1
  83. package/dist/edge/EdgeLicence.d.ts +25 -0
  84. package/dist/edge/EdgeLicence.d.ts.map +1 -0
  85. package/dist/edge/EdgeLicence.js +42 -0
  86. package/dist/edge/EdgeLicence.js.map +1 -0
  87. package/dist/edge/EdgeReplay.d.ts +45 -0
  88. package/dist/edge/EdgeReplay.d.ts.map +1 -0
  89. package/dist/edge/EdgeReplay.js +69 -0
  90. package/dist/edge/EdgeReplay.js.map +1 -0
  91. package/dist/edge/Entitlement.d.ts +57 -0
  92. package/dist/edge/Entitlement.d.ts.map +1 -0
  93. package/dist/edge/Entitlement.js +139 -0
  94. package/dist/edge/Entitlement.js.map +1 -0
  95. package/dist/edge/EntitlementEvaluation.d.ts +66 -0
  96. package/dist/edge/EntitlementEvaluation.d.ts.map +1 -0
  97. package/dist/edge/EntitlementEvaluation.js +74 -0
  98. package/dist/edge/EntitlementEvaluation.js.map +1 -0
  99. package/dist/edge/UsageCount.d.ts +40 -0
  100. package/dist/edge/UsageCount.d.ts.map +1 -0
  101. package/dist/edge/UsageCount.js +140 -0
  102. package/dist/edge/UsageCount.js.map +1 -0
  103. package/dist/edge/UsageKeyRegistration.d.ts +34 -0
  104. package/dist/edge/UsageKeyRegistration.d.ts.map +1 -0
  105. package/dist/edge/UsageKeyRegistration.js +74 -0
  106. package/dist/edge/UsageKeyRegistration.js.map +1 -0
  107. package/dist/edge/UsageMeter.d.ts +89 -0
  108. package/dist/edge/UsageMeter.d.ts.map +1 -0
  109. package/dist/edge/UsageMeter.js +275 -0
  110. package/dist/edge/UsageMeter.js.map +1 -0
  111. package/dist/edge/UsagePeriod.d.ts +23 -0
  112. package/dist/edge/UsagePeriod.d.ts.map +1 -0
  113. package/dist/edge/UsagePeriod.js +31 -0
  114. package/dist/edge/UsagePeriod.js.map +1 -0
  115. package/dist/edge/UsageReport.d.ts +92 -0
  116. package/dist/edge/UsageReport.d.ts.map +1 -0
  117. package/dist/edge/UsageReport.js +153 -0
  118. package/dist/edge/UsageReport.js.map +1 -0
  119. package/dist/edge/UsageTally.d.ts +63 -0
  120. package/dist/edge/UsageTally.d.ts.map +1 -0
  121. package/dist/edge/UsageTally.js +89 -0
  122. package/dist/edge/UsageTally.js.map +1 -0
  123. package/dist/egress/EgressError.d.ts +7 -1
  124. package/dist/egress/EgressError.d.ts.map +1 -1
  125. package/dist/egress/EgressError.js.map +1 -1
  126. package/dist/egress/EgressPolicy.d.ts +16 -3
  127. package/dist/egress/EgressPolicy.d.ts.map +1 -1
  128. package/dist/egress/EgressPolicy.js +33 -3
  129. package/dist/egress/EgressPolicy.js.map +1 -1
  130. package/dist/egress/GuardedFetch.d.ts +38 -1
  131. package/dist/egress/GuardedFetch.d.ts.map +1 -1
  132. package/dist/egress/GuardedFetch.js +52 -7
  133. package/dist/egress/GuardedFetch.js.map +1 -1
  134. package/dist/egress/TcpClient.d.ts +103 -0
  135. package/dist/egress/TcpClient.d.ts.map +1 -0
  136. package/dist/egress/TcpClient.js +490 -0
  137. package/dist/egress/TcpClient.js.map +1 -0
  138. package/dist/egress/TcpControlClient.d.ts +49 -0
  139. package/dist/egress/TcpControlClient.d.ts.map +1 -0
  140. package/dist/egress/TcpControlClient.js +186 -0
  141. package/dist/egress/TcpControlClient.js.map +1 -0
  142. package/dist/gateway/ForwardHandler.d.ts.map +1 -1
  143. package/dist/gateway/ForwardHandler.js +7 -4
  144. package/dist/gateway/ForwardHandler.js.map +1 -1
  145. package/dist/gateway/Gateway.d.ts +190 -10
  146. package/dist/gateway/Gateway.d.ts.map +1 -1
  147. package/dist/gateway/Gateway.js +465 -62
  148. package/dist/gateway/Gateway.js.map +1 -1
  149. package/dist/gateway/GatewayConfig.d.ts +67 -0
  150. package/dist/gateway/GatewayConfig.d.ts.map +1 -1
  151. package/dist/gateway/GatewayConfig.js +149 -2
  152. package/dist/gateway/GatewayConfig.js.map +1 -1
  153. package/dist/gateway/InterceptedRequest.d.ts +9 -2
  154. package/dist/gateway/InterceptedRequest.d.ts.map +1 -1
  155. package/dist/gateway/InterceptedRequest.js +41 -9
  156. package/dist/gateway/InterceptedRequest.js.map +1 -1
  157. package/dist/gateway/RateLimit.d.ts +29 -0
  158. package/dist/gateway/RateLimit.d.ts.map +1 -0
  159. package/dist/gateway/RateLimit.js +33 -0
  160. package/dist/gateway/RateLimit.js.map +1 -0
  161. package/dist/gateway/RefusalSampler.d.ts +28 -0
  162. package/dist/gateway/RefusalSampler.d.ts.map +1 -0
  163. package/dist/gateway/RefusalSampler.js +52 -0
  164. package/dist/gateway/RefusalSampler.js.map +1 -0
  165. package/dist/gateway/RouteTable.d.ts +3 -0
  166. package/dist/gateway/RouteTable.d.ts.map +1 -1
  167. package/dist/gateway/RouteTable.js +44 -7
  168. package/dist/gateway/RouteTable.js.map +1 -1
  169. package/dist/gateway/Upstream.d.ts +26 -0
  170. package/dist/gateway/Upstream.d.ts.map +1 -1
  171. package/dist/gateway/Upstream.js +41 -2
  172. package/dist/gateway/Upstream.js.map +1 -1
  173. package/dist/gateway/UpstreamProof.d.ts +235 -0
  174. package/dist/gateway/UpstreamProof.d.ts.map +1 -0
  175. package/dist/gateway/UpstreamProof.js +375 -0
  176. package/dist/gateway/UpstreamProof.js.map +1 -0
  177. package/dist/handlers/ForwardRequestHandler.d.ts +5 -1
  178. package/dist/handlers/ForwardRequestHandler.d.ts.map +1 -1
  179. package/dist/handlers/ForwardRequestHandler.js +12 -2
  180. package/dist/handlers/ForwardRequestHandler.js.map +1 -1
  181. package/dist/hosted/TenantHost.d.ts +180 -0
  182. package/dist/hosted/TenantHost.d.ts.map +1 -0
  183. package/dist/hosted/TenantHost.js +432 -0
  184. package/dist/hosted/TenantHost.js.map +1 -0
  185. package/dist/hosted/TenantRegistry.d.ts +73 -0
  186. package/dist/hosted/TenantRegistry.d.ts.map +1 -0
  187. package/dist/hosted/TenantRegistry.js +123 -0
  188. package/dist/hosted/TenantRegistry.js.map +1 -0
  189. package/dist/http/ExecutorHttpServer.d.ts +7 -0
  190. package/dist/http/ExecutorHttpServer.d.ts.map +1 -1
  191. package/dist/http/ExecutorHttpServer.js +30 -5
  192. package/dist/http/ExecutorHttpServer.js.map +1 -1
  193. package/dist/http/GatewayHttpServer.d.ts +55 -3
  194. package/dist/http/GatewayHttpServer.d.ts.map +1 -1
  195. package/dist/http/GatewayHttpServer.js +157 -17
  196. package/dist/http/GatewayHttpServer.js.map +1 -1
  197. package/dist/http/RedirectServer.d.ts +26 -0
  198. package/dist/http/RedirectServer.d.ts.map +1 -0
  199. package/dist/http/RedirectServer.js +62 -0
  200. package/dist/http/RedirectServer.js.map +1 -0
  201. package/dist/http/Routes.d.ts +17 -0
  202. package/dist/http/Routes.d.ts.map +1 -1
  203. package/dist/http/Routes.js +21 -0
  204. package/dist/http/Routes.js.map +1 -1
  205. package/dist/http/TcpBroker.d.ts +57 -0
  206. package/dist/http/TcpBroker.d.ts.map +1 -0
  207. package/dist/http/TcpBroker.js +299 -0
  208. package/dist/http/TcpBroker.js.map +1 -0
  209. package/dist/http/TcpHostRelay.d.ts +24 -0
  210. package/dist/http/TcpHostRelay.d.ts.map +1 -0
  211. package/dist/http/TcpHostRelay.js +194 -0
  212. package/dist/http/TcpHostRelay.js.map +1 -0
  213. package/dist/http/TcpRelayStreams.d.ts +24 -0
  214. package/dist/http/TcpRelayStreams.d.ts.map +1 -0
  215. package/dist/http/TcpRelayStreams.js +128 -0
  216. package/dist/http/TcpRelayStreams.js.map +1 -0
  217. package/dist/http/TlsListener.d.ts +3 -1
  218. package/dist/http/TlsListener.d.ts.map +1 -1
  219. package/dist/http/TlsListener.js +7 -2
  220. package/dist/http/TlsListener.js.map +1 -1
  221. package/dist/identity/PrincipalsFile.d.ts +3 -1
  222. package/dist/identity/PrincipalsFile.d.ts.map +1 -1
  223. package/dist/identity/PrincipalsFile.js +1 -0
  224. package/dist/identity/PrincipalsFile.js.map +1 -1
  225. package/dist/incident/Metrics.d.ts +2 -0
  226. package/dist/incident/Metrics.d.ts.map +1 -1
  227. package/dist/incident/Metrics.js +10 -0
  228. package/dist/incident/Metrics.js.map +1 -1
  229. package/dist/incident/SecurityEvents.d.ts +89 -0
  230. package/dist/incident/SecurityEvents.d.ts.map +1 -1
  231. package/dist/incident/SecurityEvents.js +93 -2
  232. package/dist/incident/SecurityEvents.js.map +1 -1
  233. package/dist/journal/ExecutionJournal.d.ts +27 -0
  234. package/dist/journal/ExecutionJournal.d.ts.map +1 -1
  235. package/dist/journal/ExecutionJournal.js +28 -0
  236. package/dist/journal/ExecutionJournal.js.map +1 -1
  237. package/dist/journal/FileExecutionJournal.d.ts +2 -1
  238. package/dist/journal/FileExecutionJournal.d.ts.map +1 -1
  239. package/dist/journal/FileExecutionJournal.js +4 -1
  240. package/dist/journal/FileExecutionJournal.js.map +1 -1
  241. package/dist/journal/InMemoryExecutionJournal.d.ts +2 -1
  242. package/dist/journal/InMemoryExecutionJournal.d.ts.map +1 -1
  243. package/dist/journal/InMemoryExecutionJournal.js +4 -1
  244. package/dist/journal/InMemoryExecutionJournal.js.map +1 -1
  245. package/dist/service/AuthorityClients.d.ts +8 -1
  246. package/dist/service/AuthorityClients.d.ts.map +1 -1
  247. package/dist/service/AuthorityClients.js +33 -5
  248. package/dist/service/AuthorityClients.js.map +1 -1
  249. package/dist/service/EdgeRuntime.d.ts +73 -0
  250. package/dist/service/EdgeRuntime.d.ts.map +1 -0
  251. package/dist/service/EdgeRuntime.js +209 -0
  252. package/dist/service/EdgeRuntime.js.map +1 -0
  253. package/dist/service/EscalationResolver.d.ts +82 -2
  254. package/dist/service/EscalationResolver.d.ts.map +1 -1
  255. package/dist/service/EscalationResolver.js +39 -3
  256. package/dist/service/EscalationResolver.js.map +1 -1
  257. package/dist/service/Requests.d.ts +28 -2
  258. package/dist/service/Requests.d.ts.map +1 -1
  259. package/dist/service/TrustedExecutorService.d.ts +71 -1
  260. package/dist/service/TrustedExecutorService.d.ts.map +1 -1
  261. package/dist/service/TrustedExecutorService.js +461 -27
  262. package/dist/service/TrustedExecutorService.js.map +1 -1
  263. package/dist/tcp/TcpWire.d.ts +18 -0
  264. package/dist/tcp/TcpWire.d.ts.map +1 -0
  265. package/dist/tcp/TcpWire.js +114 -0
  266. package/dist/tcp/TcpWire.js.map +1 -0
  267. package/dist/verify/VerifyAuditChain.d.ts +5 -0
  268. package/dist/verify/VerifyAuditChain.d.ts.map +1 -1
  269. package/dist/verify/VerifyAuditChain.js +20 -4
  270. package/dist/verify/VerifyAuditChain.js.map +1 -1
  271. package/package.json +7 -3
@@ -5,13 +5,18 @@ import { effectBlock } from "../adapters/AdapterActionHandler.js";
5
5
  import { bindBankingAction, BindingError } from "../adapters/banking/BankingIntentBinder.js";
6
6
  import { BankingAdapter, BankingActionError } from "../adapters/banking/BankingAdapter.js";
7
7
  import { isBankingActionName } from "../adapters/banking/BankingAction.js";
8
+ import { matchCardAuthorization } from "../adapters/cards/CardAuthorizationMatcher.js";
9
+ import { cardExecutionResult, cardResultRecord, prepareCardPurchase, } from "../adapters/cards/CardEffect.js";
10
+ import { bindCardPurchase, CardActionError, cardAuthorizationOf, cardAuthorizationResultOf, cardPurchaseOf, isCardActionName, isCardReference, } from "../adapters/cards/CardPurchase.js";
11
+ import { HeldCardGrants, } from "../adapters/cards/HeldCardGrants.js";
12
+ import { jcsDigest } from "../adapters/JcsDigest.js";
8
13
  import { HashChain } from "../audit/HashChain.js";
9
14
  import { EVIDENCE_STREAM, HashChainedAuditSink } from "../audit/HashChainedAuditSink.js";
10
15
  import { HaltSwitch } from "../incident/HaltSwitch.js";
11
16
  import { InMemoryExecutionJournal } from "../journal/InMemoryExecutionJournal.js";
12
17
  import { StartupReconciler } from "../journal/StartupReconciler.js";
13
18
  import { HardLimits } from "../limits/HardLimits.js";
14
- import { callerPrincipal, JournaledRegistry } from "../handlers/JournaledActionHandler.js";
19
+ import { callerPrincipal, JournaledRegistry, requestDigest, } from "../handlers/JournaledActionHandler.js";
15
20
  import { clockSkewGuard } from "../time/ClockSkewGuard.js";
16
21
  import { PrivateKeyJwtCredential } from "../credential/PrivateKeyJwtCredential.js";
17
22
  import { SignedRequestCredential } from "../credential/SignedRequestCredential.js";
@@ -28,9 +33,10 @@ import { EvidenceError, EvidenceExport, LineWindow, } from "../incident/Evidence
28
33
  import { RequestContext } from "../http/RequestContext.js";
29
34
  import { AuthorityClients } from "./AuthorityClients.js";
30
35
  import { packageVersion } from "../Version.js";
31
- import { EscalationHandoffSchema, } from "./EscalationResolver.js";
36
+ import { EscalationResumeSchema, } from "./EscalationResolver.js";
32
37
  import { ProposalRequestSchema, ReconciliationRequestSchema, } from "./Requests.js";
33
38
  import { HaltRequestSchema, ResumeRequestSchema } from "./Requests.js";
39
+ import { EdgeRuntime } from "./EdgeRuntime.js";
34
40
  import { ServiceError } from "./ServiceError.js";
35
41
  /**
36
42
  * The execution boundary as one process. In `ENFORCEMENT` it asks Decionis,
@@ -90,6 +96,20 @@ function nonSecretConfiguration(config) {
90
96
  window_seconds: config.limits.windowSeconds,
91
97
  },
92
98
  max_clock_skew_ms: config.maxClockSkewMs,
99
+ decision: {
100
+ authority: config.decision.authority,
101
+ edge: config.edge === null
102
+ ? null
103
+ : {
104
+ org_id: config.edge.orgId,
105
+ bundle_source: config.edge.bundle.source,
106
+ refresh_seconds: config.edge.refreshSeconds,
107
+ on_unavailable: config.edge.onUnavailable,
108
+ replay_store: config.edge.replay.store,
109
+ usage_reports: config.edge.usage.signing,
110
+ installation_id: config.edge.usage.installationId,
111
+ },
112
+ },
93
113
  };
94
114
  }
95
115
  /** An Ed25519 detached JWS over the manifest, from the configured key. */
@@ -120,15 +140,26 @@ export class TrustedExecutorService {
120
140
  haltSwitch;
121
141
  limits;
122
142
  unsubscribeMetrics;
143
+ effects;
144
+ cards;
145
+ edge;
123
146
  hasher = new CanonicalIntentHasher();
124
147
  recovery = null;
148
+ /** Bound before any await: one authorization id may claim only one request. */
149
+ cardClaims = new Map();
125
150
  constructor(config, secrets, capture, registry, registered, clients, posture, egress,
126
151
  /** Where an incident's evidence is written, when the configuration names a directory. */
127
152
  evidence,
128
153
  /** The security stream this service writes to; a test drives the halt through it. */
129
154
  events, chain, metrics, principals,
130
155
  /** The workload token verifier, when the configuration names a JWKS; the door uses it. */
131
- jwt, credential, audit, journal, haltSwitch, limits, unsubscribeMetrics) {
156
+ jwt, credential, audit, journal, haltSwitch, limits, unsubscribeMetrics,
157
+ /** The effect observations the verifier finalizes with; the cards family registers into it. */
158
+ effects,
159
+ /** Card grants held for the issuer's authorization, and the authorizations that claimed one. */
160
+ cards,
161
+ /** The edge evaluator, when the configuration asks for it. */
162
+ edge = null) {
132
163
  this.config = config;
133
164
  this.secrets = secrets;
134
165
  this.capture = capture;
@@ -149,6 +180,9 @@ export class TrustedExecutorService {
149
180
  this.haltSwitch = haltSwitch;
150
181
  this.limits = limits;
151
182
  this.unsubscribeMetrics = unsubscribeMetrics;
183
+ this.effects = effects;
184
+ this.cards = cards;
185
+ this.edge = edge;
152
186
  }
153
187
  /**
154
188
  * Wires the boundary. `handlers` is the adopter's seam: it registers what
@@ -172,8 +206,9 @@ export class TrustedExecutorService {
172
206
  const auditWindow = new LineWindow(config.evidence.windowLines);
173
207
  const securityWindow = new LineWindow(config.evidence.windowLines);
174
208
  events.tap((line) => securityWindow.push(line));
209
+ const evidenceWriter = auditWindow.tee(emit);
175
210
  const audit = new AuditRecorder({
176
- sink: new HashChainedAuditSink(auditWindow.tee(emit), chain),
211
+ sink: new HashChainedAuditSink(evidenceWriter, chain),
177
212
  failurePolicy: "REQUIRE_BEFORE_EXECUTION",
178
213
  });
179
214
  // Every connection this process opens, the authority's and the Presence
@@ -239,8 +274,25 @@ export class TrustedExecutorService {
239
274
  observe: (skew) => metrics.clockSkew.set(skew),
240
275
  onExceeded: (skew) => halt.halt("CLOCK_SKEW", `${skew}ms from the authority`),
241
276
  });
277
+ // The edge evaluator, built once: a module that is not a valid ABI 3
278
+ // module refuses the start here, before anything listens.
279
+ const edge = EdgeRuntime.create({
280
+ config,
281
+ secrets,
282
+ apiKey: () => secrets.get("DECIONIS_API_KEY").use((value) => value.toString("utf8")),
283
+ fetch: egress.fetch,
284
+ events,
285
+ chain,
286
+ write: evidenceWriter,
287
+ ...(dependencies.loadEdgeModule === undefined
288
+ ? {}
289
+ : { loadModule: dependencies.loadEdgeModule }),
290
+ ...(dependencies.loadPg === undefined ? {} : { loadPg: dependencies.loadPg }),
291
+ ...(dependencies.clock === undefined ? {} : { clock: dependencies.clock }),
292
+ });
242
293
  const clients = new AuthorityClients({
243
294
  config,
295
+ edge,
244
296
  secrets,
245
297
  registry,
246
298
  audit,
@@ -248,6 +300,11 @@ export class TrustedExecutorService {
248
300
  fetch: authorityFetch,
249
301
  effects,
250
302
  observer: { id: config.banking.adapterId, version: config.banking.adapterVersion },
303
+ // A recovery reference is the caller's claim; the journal is what this
304
+ // process dispatched, so reconciliation is held against it.
305
+ attempts: {
306
+ authorizationsOf: async (captured) => await journal.authorizationsOf(captured.intent.intentId),
307
+ },
251
308
  ...(dependencies.presence === undefined ? {} : { presence: dependencies.presence }),
252
309
  });
253
310
  const posture = dependencies.posture ?? { degraded: false };
@@ -297,7 +354,7 @@ export class TrustedExecutorService {
297
354
  for (const stop of unsubscribeRotations)
298
355
  stop();
299
356
  unsubscribeEvents();
300
- });
357
+ }, effects, new HeldCardGrants(), edge);
301
358
  }
302
359
  /** The credential the configuration's kind names, over the secret store and the guarded fetch. */
303
360
  static credential(config, secrets, fetchImpl) {
@@ -368,12 +425,21 @@ export class TrustedExecutorService {
368
425
  get escalationMode() {
369
426
  return this.config.escalation.mode;
370
427
  }
428
+ /**
429
+ * Loads the edge evaluator's first bundle and starts its refresh schedule.
430
+ * A first fetch that fails is not a refusal to start: until a bundle
431
+ * loads, decisions follow the configured `onUnavailable`.
432
+ */
433
+ async startEdge() {
434
+ await this.edge?.start();
435
+ }
371
436
  /** The actions this process can run, for `/ready`. */
372
437
  get actions() {
373
438
  return this.registered.filter((action) => this.registry.has(action));
374
439
  }
375
440
  /** Stops following credential rotation and closes every outbound connection; the service answers nothing new after this. */
376
441
  close() {
442
+ this.edge?.stop();
377
443
  this.clients.close();
378
444
  this.egress.close();
379
445
  this.jwt?.stop();
@@ -525,6 +591,7 @@ export class TrustedExecutorService {
525
591
  try {
526
592
  this.assertNotHalted(captured);
527
593
  this.assertWithinLimits(captured, "CHECK");
594
+ this.assertCardSpendable(captured);
528
595
  }
529
596
  catch (error) {
530
597
  if (error instanceof ServiceError)
@@ -572,6 +639,27 @@ export class TrustedExecutorService {
572
639
  reasonCodes: [reason],
573
640
  });
574
641
  }
642
+ /**
643
+ * One spendable hold per card: a purchase on a card that already has one
644
+ * waits until it is authorised or expires, refused before the authority is
645
+ * asked so the refusal costs no dossier and no grant.
646
+ */
647
+ assertCardSpendable(captured) {
648
+ if (!isCardActionName(captured.intent.action))
649
+ return;
650
+ // An intent presented back is re-read here, so a card number written into
651
+ // one after capture is refused like one in a proposal.
652
+ let cardTokenRef;
653
+ try {
654
+ cardTokenRef = cardPurchaseOf(captured.intent.parameters).cardTokenRef;
655
+ }
656
+ catch (error) {
657
+ throw new ServiceError(422, error.code);
658
+ }
659
+ if (this.cards.spendable(cardTokenRef)) {
660
+ throw new ServiceError(409, "CARD_GRANT_ALREADY_HELD");
661
+ }
662
+ }
575
663
  /** The host's own ceilings, before the authority is asked and again before the run. */
576
664
  assertWithinLimits(captured, stage) {
577
665
  if (this.limits === null)
@@ -600,8 +688,10 @@ export class TrustedExecutorService {
600
688
  this.assertOwn(captured, proposer);
601
689
  const outcome = await RequestContext.run({ principal: proposer.id }, () => this.clients.current().executor.reconcile(captured, parsed.data.reference));
602
690
  // 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") {
691
+ // ask the provider about it again. A refused reconciliation resolved
692
+ // nothing: closing on it would let any presented reference, however
693
+ // wrong, take a genuinely open attempt off the next start's list.
694
+ if (outcome.outcome === "COMPLETED" || outcome.outcome === "DEFINITELY_NOT_EXECUTED") {
605
695
  try {
606
696
  await this.journal.append({
607
697
  record: "RECONCILED",
@@ -640,13 +730,17 @@ export class TrustedExecutorService {
640
730
  */
641
731
  async resume(input, caller) {
642
732
  const proposer = this.proposer(caller);
643
- const parsed = EscalationHandoffSchema.safeParse(input);
733
+ const parsed = EscalationResumeSchema.safeParse(input);
644
734
  if (!parsed.success)
645
735
  throw new ServiceError(400, "REQUEST_INVALID");
646
- if (this.config.mode === "SHADOW" || this.config.escalation.mode === "NONE") {
736
+ const resume = parsed.data;
737
+ // An attestation needs no escalation shape: it is evidence for a fresh
738
+ // evaluation, which any enforcing executor can ask for.
739
+ const attested = resume.mode === "ATTESTATION";
740
+ if (this.config.mode === "SHADOW" || (!attested && this.config.escalation.mode === "NONE")) {
647
741
  throw new ServiceError(409, "ESCALATION_NOT_CONFIGURED");
648
742
  }
649
- const captured = this.presented(parsed.data.intent);
743
+ const captured = this.presented(resume.intent);
650
744
  this.assertOwn(captured, proposer);
651
745
  if (Date.parse(captured.intent.expiresAt) <= Date.now()) {
652
746
  throw new ServiceError(409, "INTENT_EXPIRED");
@@ -658,6 +752,7 @@ export class TrustedExecutorService {
658
752
  return await RequestContext.run({ principal: proposer.id }, async () => {
659
753
  try {
660
754
  this.assertNotHalted(captured);
755
+ this.assertCardSpendable(captured);
661
756
  }
662
757
  catch (error) {
663
758
  if (error instanceof ServiceError)
@@ -665,16 +760,13 @@ export class TrustedExecutorService {
665
760
  throw error;
666
761
  }
667
762
  const { escalation, executor } = this.clients.current();
668
- const resolution = await escalation.resume(captured, parsed.data);
763
+ if (resume.mode === "ATTESTATION") {
764
+ const decision = await escalation.attest(captured, resume.attestation);
765
+ return await this.decide(captured, decision, executor);
766
+ }
767
+ const resolution = await escalation.resume(captured, resume);
669
768
  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);
769
+ return await this.decide(captured, resolution.decision, executor);
678
770
  }
679
771
  if (resolution.kind === "PENDING") {
680
772
  return this.held(captured, "ESCALATE", resolution.reasonCodes, false, {
@@ -685,6 +777,26 @@ export class TrustedExecutorService {
685
777
  return this.held(captured, "BLOCK", resolution.reasonCodes, resolution.failClosed, null);
686
778
  });
687
779
  }
780
+ /**
781
+ * A fresh decision on a resumed escalation: a card purchase's grant is held
782
+ * for the issuer, anything else runs once on an `ALLOW`.
783
+ */
784
+ async decide(captured, decision, executor) {
785
+ if (isCardActionName(captured.intent.action)) {
786
+ const held = await this.holdCard(captured, decision, executor);
787
+ if ("mode" in held)
788
+ return held;
789
+ return this.response(captured, decision, held, null);
790
+ }
791
+ if (decision.verdict === "ALLOW" && !decision.failClosed) {
792
+ this.assertWithinLimits(captured, "COMMIT");
793
+ await this.openAttempt(captured, decision);
794
+ }
795
+ const outcome = await executor.run(captured, decision);
796
+ await this.closeAttempt(captured, decision, outcome);
797
+ this.metrics.executions.inc({ outcome: outcome.outcome });
798
+ return this.response(captured, decision, outcome, null);
799
+ }
688
800
  /**
689
801
  * The attempt, on disk, before the executor may run it. A journal that
690
802
  * cannot take the record refuses the proposal rather than executing
@@ -781,6 +893,7 @@ export class TrustedExecutorService {
781
893
  const bound = isBankingActionName(request.proposal.action)
782
894
  ? this.bindBanking(request, proposer)
783
895
  : null;
896
+ const card = isCardActionName(request.proposal.action) ? this.bindCard(request) : null;
784
897
  const trusted = {
785
898
  tenantId: proposer.tenantId,
786
899
  actor: proposer.actor,
@@ -793,6 +906,7 @@ export class TrustedExecutorService {
793
906
  idempotencyKey: request.idempotency_key,
794
907
  ...(request.correlation_id === undefined ? {} : { correlationId: request.correlation_id }),
795
908
  ...(bound === null ? {} : { expectedEffectDigest: bound.expectedEffectDigest }),
909
+ ...(card === null ? {} : { expectedEffectDigest: card }),
796
910
  };
797
911
  const parameters = request.proposal.parameters ?? {};
798
912
  try {
@@ -827,6 +941,23 @@ export class TrustedExecutorService {
827
941
  throw new ServiceError(422, "BANKING_ACTION_INVALID");
828
942
  }
829
943
  }
944
+ /**
945
+ * The cards binder: the purchase is read and refused here, a card number
946
+ * above all, and the target is derived from the card. What comes back is
947
+ * the expected-effect digest the authority binds its grant to.
948
+ */
949
+ bindCard(request) {
950
+ try {
951
+ const purchase = bindCardPurchase({
952
+ target: request.proposal.target,
953
+ parameters: request.proposal.parameters ?? {},
954
+ });
955
+ return prepareCardPurchase(purchase).expectedEffectDigest;
956
+ }
957
+ catch (error) {
958
+ throw new ServiceError(422, error.code);
959
+ }
960
+ }
830
961
  /**
831
962
  * The two digests a banking intent is bound to, taken from the profile's
832
963
  * own arithmetic. This reaches nothing: `prepare` is pure, which is why
@@ -957,26 +1088,328 @@ export class TrustedExecutorService {
957
1088
  async enforce(captured) {
958
1089
  const { escalation, executor } = this.clients.current();
959
1090
  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);
1091
+ const card = isCardActionName(captured.intent.action);
1092
+ let outcome;
1093
+ if (card) {
1094
+ // A card purchase is answered before the issuer ever asks: on an ALLOW
1095
+ // the grant is held, not claimed, and the response says so.
1096
+ const held = await this.holdCard(captured, decision, executor);
1097
+ if ("mode" in held)
1098
+ return held;
1099
+ outcome = held;
1100
+ }
1101
+ else {
1102
+ // Every decision goes through the executor, an ESCALATE or BLOCK
1103
+ // included, so the audit stream carries the refusal as well as the
1104
+ // execution.
1105
+ if (decision.verdict === "ALLOW" && !decision.failClosed) {
1106
+ this.assertWithinLimits(captured, "COMMIT");
1107
+ await this.openAttempt(captured, decision);
1108
+ }
1109
+ outcome = await executor.run(captured, decision);
1110
+ await this.closeAttempt(captured, decision, outcome);
1111
+ this.metrics.executions.inc({ outcome: outcome.outcome });
965
1112
  }
966
- const outcome = await executor.run(captured, decision);
967
- await this.closeAttempt(captured, decision, outcome);
968
- this.metrics.executions.inc({ outcome: outcome.outcome });
969
1113
  let handoff = null;
970
1114
  let unavailable = false;
971
1115
  if (decision.verdict === "ESCALATE" && !decision.failClosed) {
972
1116
  const state = await escalation.handoff(captured, decision);
973
1117
  if (state !== null)
974
1118
  handoff = { ...state, intent: captured.intent };
1119
+ // A cardholder's tap needs no Presence ceremony: whatever shape this
1120
+ // executor escalates in, a card purchase can be resumed with an
1121
+ // attestation over the intent it is handed here.
1122
+ else if (card)
1123
+ handoff = { mode: "ATTESTATION", intent: captured.intent };
975
1124
  else if (this.config.escalation.mode !== "NONE")
976
1125
  unavailable = true;
977
1126
  }
978
1127
  return this.response(captured, decision, outcome, handoff, unavailable ? ["ESCALATION_HANDOFF_UNAVAILABLE"] : []);
979
1128
  }
1129
+ /**
1130
+ * Admits a card purchase's decision exactly as a run would and holds its
1131
+ * grant for the issuer's authorization, keyed by the card. Nothing is
1132
+ * claimed and nothing runs; the hard ceilings are committed now, because
1133
+ * this is the last moment this process decides anything about the amount.
1134
+ * A refusal comes back as the executor's own blocked result.
1135
+ */
1136
+ async holdCard(captured, decision, executor) {
1137
+ if (decision.verdict === "ALLOW" && !decision.failClosed) {
1138
+ this.assertWithinLimits(captured, "COMMIT");
1139
+ }
1140
+ const outcome = await executor.hold(captured, decision);
1141
+ if (outcome.outcome !== "HELD") {
1142
+ this.metrics.executions.inc({ outcome: outcome.outcome });
1143
+ return outcome;
1144
+ }
1145
+ const purchase = cardPurchaseOf(captured.intent.parameters);
1146
+ const stored = this.cards.hold({
1147
+ cardTokenRef: purchase.cardTokenRef,
1148
+ amountMinor: purchase.amountMinor,
1149
+ currency: purchase.currency,
1150
+ merchantId: purchase.merchantId,
1151
+ mcc: purchase.mcc ?? null,
1152
+ expiresAtMs: Date.parse(outcome.held.expiresAt),
1153
+ used: false,
1154
+ purchase,
1155
+ prepared: prepareCardPurchase(purchase),
1156
+ held: outcome.held,
1157
+ executor,
1158
+ });
1159
+ // A card that gained a spendable hold while this one was being decided,
1160
+ // or a full store: the grant is left unclaimed and expires with no effect.
1161
+ const status = stored ? "HELD_FOR_AUTHORIZATION" : "BLOCKED";
1162
+ this.metrics.executions.inc({ outcome: status });
1163
+ if (stored)
1164
+ this.events.emit({ event: "CARD_GRANT_HELD", intent_id: captured.intent.intentId });
1165
+ return {
1166
+ mode: "ENFORCEMENT",
1167
+ intent_id: captured.intent.intentId,
1168
+ intent_hash: captured.intentHash,
1169
+ verdict: decision.verdict,
1170
+ decision_id: decision.decisionId,
1171
+ dossier_id: decision.dossierId,
1172
+ reason_codes: stored
1173
+ ? [...decision.reasonCodes]
1174
+ : [...decision.reasonCodes, "CARD_HOLD_UNAVAILABLE"],
1175
+ fail_closed: false,
1176
+ outcome: status,
1177
+ executed: false,
1178
+ authorization: null,
1179
+ finalization: null,
1180
+ result: stored
1181
+ ? { status: "HELD_FOR_AUTHORIZATION", expires_at: outcome.held.expiresAt }
1182
+ : null,
1183
+ effect: null,
1184
+ recovery: null,
1185
+ escalation: null,
1186
+ };
1187
+ }
1188
+ /**
1189
+ * The issuer's real-time authorization hook. The answer has to come back in
1190
+ * milliseconds, so the only network call is the claim itself: the match is
1191
+ * pure, against a grant decided before the card was presented. A match
1192
+ * claims the grant once, and a second authorization for it is a
1193
+ * `NO_MATCH`; an issuer retrying the same authorization is given the same
1194
+ * answer, with no second claim. What `NO_MATCH` means for the purchase is
1195
+ * the issuer's policy, not this process's.
1196
+ */
1197
+ async authorizeCard(input, caller) {
1198
+ this.operator(caller, "cards.authorize");
1199
+ const request = TrustedExecutorService.cardRequest(() => cardAuthorizationOf(input));
1200
+ const previous = this.cards.claimed(request.authorization_id);
1201
+ if (previous !== undefined) {
1202
+ if (jcsDigest(previous.request) === jcsDigest(request)) {
1203
+ return previous.answer;
1204
+ }
1205
+ return this.noMatch(null, "AUTHORIZATION_ID_REUSED");
1206
+ }
1207
+ const digest = jcsDigest(request);
1208
+ const pending = this.cardClaims.get(request.authorization_id);
1209
+ if (pending !== undefined) {
1210
+ return pending.digest === digest
1211
+ ? await pending.answer
1212
+ : this.noMatch(null, "AUTHORIZATION_ID_REUSED");
1213
+ }
1214
+ if (this.cardClaims.size >= 10_000) {
1215
+ return this.noMatch(null, "CARD_AUTHORIZATION_CAPACITY_EXCEEDED");
1216
+ }
1217
+ // Reserve the id synchronously, before journal/claim I/O can yield to a
1218
+ // conflicting request. Identical concurrent retries share the same result.
1219
+ const answer = Promise.resolve().then(() => this.claimCard(request));
1220
+ this.cardClaims.set(request.authorization_id, { digest, answer });
1221
+ try {
1222
+ return await answer;
1223
+ }
1224
+ finally {
1225
+ this.cardClaims.delete(request.authorization_id);
1226
+ }
1227
+ }
1228
+ async claimCard(request) {
1229
+ if (this.haltSwitch.current.halted)
1230
+ return this.noMatch(null, "EXECUTOR_HALTED");
1231
+ if (this.posture.degraded)
1232
+ return this.noMatch(null, "POSTURE_DEGRADED");
1233
+ const grant = this.cards.grant(request.card_token_ref);
1234
+ const match = matchCardAuthorization(grant, TrustedExecutorService.cardView(request), Date.now());
1235
+ if (match.decision === "NO_MATCH") {
1236
+ return this.noMatch(grant?.held.captured.intent.intentId ?? null, match.code);
1237
+ }
1238
+ // A match is only ever against a grant.
1239
+ const matched = grant;
1240
+ // Spent before anything is awaited, so a concurrent authorization for the
1241
+ // same grant finds it used rather than racing this one to the claim.
1242
+ matched.used = true;
1243
+ const { captured, decision } = matched.held;
1244
+ const intentId = captured.intent.intentId;
1245
+ try {
1246
+ await this.openAttempt(captured, decision);
1247
+ }
1248
+ catch {
1249
+ return this.noMatch(intentId, "JOURNAL_UNAVAILABLE");
1250
+ }
1251
+ const claim = await matched.executor.claimHeld(matched.held);
1252
+ if (claim.outcome !== "CLAIMED") {
1253
+ await this.closeAttempt(captured, decision, claim);
1254
+ this.metrics.executions.inc({ outcome: claim.outcome });
1255
+ return this.noMatch(intentId, "GRANT_CLAIM_REFUSED");
1256
+ }
1257
+ const authorization = claim.authorization;
1258
+ // The claim is made durable before the issuer is told to approve: there is
1259
+ // no effect without a record a restart can find, exactly as for a run.
1260
+ try {
1261
+ await this.journal.append({
1262
+ record: "GRANT_CLAIMED",
1263
+ at: new Date().toISOString(),
1264
+ intent_id: intentId,
1265
+ intent_hash: captured.intentHash,
1266
+ idempotency_key: captured.intent.idempotencyKey,
1267
+ grant_id: authorization.grantId,
1268
+ expires_at: authorization.expiresAt,
1269
+ request_digest: requestDigest(captured.intent.parameters),
1270
+ });
1271
+ }
1272
+ catch {
1273
+ this.events.emit({ event: "JOURNAL_WRITE_FAILED", record: "GRANT_CLAIMED" });
1274
+ if (this.config.evidence.journalRequired) {
1275
+ const finalization = await matched.executor.settleHeld(matched.held, "FAILED");
1276
+ await this.closeCardAttempt(captured, "DEFINITELY_NOT_EXECUTED", false, finalization);
1277
+ return this.noMatch(intentId, "JOURNAL_UNAVAILABLE");
1278
+ }
1279
+ }
1280
+ const lease = authorization.leaseExpiresAt ?? authorization.expiresAt;
1281
+ const answer = {
1282
+ decision: "APPROVE",
1283
+ authorization_id: request.authorization_id,
1284
+ intent_id: intentId,
1285
+ intent_hash: captured.intentHash,
1286
+ decision_id: authorization.decisionId,
1287
+ dossier_id: authorization.dossierId,
1288
+ grant_id: authorization.grantId,
1289
+ lease_expires_at: lease,
1290
+ };
1291
+ this.cards.recordClaim(request.authorization_id, {
1292
+ grant: matched,
1293
+ request,
1294
+ authorization,
1295
+ leaseExpiresAtMs: Date.parse(lease),
1296
+ answer,
1297
+ });
1298
+ this.metrics.executions.inc({ outcome: "CARD_AUTHORIZATION_MATCHED" });
1299
+ this.events.emit({ event: "CARD_AUTHORIZATION_MATCHED", intent_id: intentId });
1300
+ return answer;
1301
+ }
1302
+ /**
1303
+ * What the issuer did with an authorization it was told to approve. An
1304
+ * approval is the effect, compared with what the grant authorised; a
1305
+ * decline is a refusal; and a result after the claim's lease is recorded
1306
+ * as indeterminate, because the authority no longer accepts a commit for
1307
+ * it. Recorded once.
1308
+ */
1309
+ async settleCard(authorizationId, input, caller) {
1310
+ this.operator(caller, "cards.authorize");
1311
+ if (!isCardReference(authorizationId))
1312
+ throw new ServiceError(400, "REQUEST_INVALID");
1313
+ const result = TrustedExecutorService.cardRequest(() => cardAuthorizationResultOf(input));
1314
+ const claim = this.cards.claimed(authorizationId);
1315
+ if (claim === undefined)
1316
+ throw new ServiceError(404, "CARD_AUTHORIZATION_UNKNOWN");
1317
+ if (claim.settled)
1318
+ throw new ServiceError(409, "CARD_RESULT_ALREADY_RECORDED");
1319
+ claim.settled = true;
1320
+ const { grant, authorization } = claim;
1321
+ const { captured } = grant.held;
1322
+ const leaseExpired = Date.now() > claim.leaseExpiresAtMs;
1323
+ const record = cardResultRecord({
1324
+ purchase: grant.purchase,
1325
+ prepared: grant.prepared,
1326
+ authorization: claim.request,
1327
+ result,
1328
+ leaseExpired,
1329
+ observer: { id: this.config.banking.adapterId, version: this.config.banking.adapterVersion },
1330
+ correlationId: captured.intent.intentId,
1331
+ idempotencyKey: captured.intent.idempotencyKey,
1332
+ observedAt: new Date().toISOString(),
1333
+ });
1334
+ // The verifier finalizes with exactly this observation, by the
1335
+ // authorization it belongs to.
1336
+ this.effects.attach(authorization, record);
1337
+ const finalization = await grant.executor.settleHeld(grant.held, record.outcome);
1338
+ const executed = record.outcome === "COMMITTED" ? true : record.outcome === "FAILED" ? false : null;
1339
+ await this.closeCardAttempt(captured, record.outcome === "COMMITTED"
1340
+ ? "COMPLETED"
1341
+ : record.outcome === "FAILED"
1342
+ ? "DEFINITELY_NOT_EXECUTED"
1343
+ : "INDETERMINATE_AFTER_LEASE", executed, finalization);
1344
+ this.metrics.executions.inc({ outcome: `CARD_${record.outcome}` });
1345
+ if (finalization === "PENDING") {
1346
+ this.events.emit({
1347
+ event: "FINALIZATION_PENDING",
1348
+ intent_id: captured.intent.intentId,
1349
+ outcome: record.outcome,
1350
+ });
1351
+ }
1352
+ this.metrics.finalizations.inc({ status: finalization });
1353
+ this.events.emit({
1354
+ event: "CARD_AUTHORIZATION_SETTLED",
1355
+ intent_id: captured.intent.intentId,
1356
+ outcome: record.outcome,
1357
+ });
1358
+ const effect = this.effect(captured, cardExecutionResult(record));
1359
+ return {
1360
+ authorization_id: authorizationId,
1361
+ intent_id: captured.intent.intentId,
1362
+ intent_hash: captured.intentHash,
1363
+ outcome: record.outcome,
1364
+ executed,
1365
+ finalization,
1366
+ reason_codes: [
1367
+ ...(leaseExpired ? ["CLAIM_LEASE_EXPIRED"] : []),
1368
+ ...TrustedExecutorService.effectReasons(effect),
1369
+ ],
1370
+ effect,
1371
+ };
1372
+ }
1373
+ /** A card attempt's end, in the journal, so a restart does not ask about it again. */
1374
+ async closeCardAttempt(captured, outcome, executed, finalization) {
1375
+ try {
1376
+ await this.journal.append({
1377
+ record: "ATTEMPT_CLOSED",
1378
+ at: new Date().toISOString(),
1379
+ intent_id: captured.intent.intentId,
1380
+ intent_hash: captured.intentHash,
1381
+ outcome,
1382
+ executed,
1383
+ finalization,
1384
+ });
1385
+ }
1386
+ catch {
1387
+ this.events.emit({ event: "JOURNAL_WRITE_FAILED", record: "ATTEMPT_CLOSED" });
1388
+ }
1389
+ }
1390
+ noMatch(intentId, code) {
1391
+ this.events.emit({ event: "CARD_AUTHORIZATION_NO_MATCH", intent_id: intentId, code });
1392
+ return { decision: "NO_MATCH", code };
1393
+ }
1394
+ /** A card request read, or the refusal that names why; a card number is its own refusal. */
1395
+ static cardRequest(read) {
1396
+ try {
1397
+ return read();
1398
+ }
1399
+ catch (error) {
1400
+ const code = error instanceof CardActionError ? error.code : "REQUEST_INVALID";
1401
+ throw new ServiceError(code === "CARD_PAN_REFUSED" ? 422 : 400, code);
1402
+ }
1403
+ }
1404
+ static cardView(request) {
1405
+ return {
1406
+ cardTokenRef: request.card_token_ref,
1407
+ amountMinor: request.amount_minor,
1408
+ currency: request.currency,
1409
+ merchantId: request.merchant_id,
1410
+ mcc: request.mcc ?? null,
1411
+ };
1412
+ }
980
1413
  response(captured, decision, outcome, handoff, extraReasonCodes = []) {
981
1414
  const effect = this.effect(captured, outcome.result);
982
1415
  // A finalization the authority did not take is the authority's lease
@@ -1001,6 +1434,7 @@ export class TrustedExecutorService {
1001
1434
  reason_codes: [
1002
1435
  ...decision.reasonCodes,
1003
1436
  ...("reason" in outcome && outcome.reason !== "DECISION_NOT_ALLOW" ? [outcome.reason] : []),
1437
+ ...("code" in outcome && outcome.code !== undefined ? [outcome.code] : []),
1004
1438
  ...TrustedExecutorService.effectReasons(effect),
1005
1439
  ...extraReasonCodes,
1006
1440
  ],