@decionis/agentsafe 0.3.0 → 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 (72) hide show
  1. package/README.md +181 -121
  2. package/dist/Cli.js +5 -0
  3. package/dist/Cli.js.map +1 -1
  4. package/dist/TrustedExecutor.d.ts.map +1 -1
  5. package/dist/TrustedExecutor.js +1 -0
  6. package/dist/TrustedExecutor.js.map +1 -1
  7. package/dist/adapters/EffectAwareGrantVerifier.d.ts +5 -2
  8. package/dist/adapters/EffectAwareGrantVerifier.d.ts.map +1 -1
  9. package/dist/adapters/EffectAwareGrantVerifier.js +9 -0
  10. package/dist/adapters/EffectAwareGrantVerifier.js.map +1 -1
  11. package/dist/adapters/banking/BankingAction.d.ts +2 -2
  12. package/dist/adapters/cards/CardHoldSeal.d.ts +29 -0
  13. package/dist/adapters/cards/CardHoldSeal.d.ts.map +1 -0
  14. package/dist/adapters/cards/CardHoldSeal.js +87 -0
  15. package/dist/adapters/cards/CardHoldSeal.js.map +1 -0
  16. package/dist/adapters/cards/CardHoldStore.d.ts +102 -0
  17. package/dist/adapters/cards/CardHoldStore.d.ts.map +1 -0
  18. package/dist/adapters/cards/CardHoldStore.js +9 -0
  19. package/dist/adapters/cards/CardHoldStore.js.map +1 -0
  20. package/dist/adapters/cards/CardHolds.d.ts +19 -0
  21. package/dist/adapters/cards/CardHolds.d.ts.map +1 -0
  22. package/dist/adapters/cards/CardHolds.js +57 -0
  23. package/dist/adapters/cards/CardHolds.js.map +1 -0
  24. package/dist/adapters/cards/HeldCardGrants.d.ts +41 -42
  25. package/dist/adapters/cards/HeldCardGrants.d.ts.map +1 -1
  26. package/dist/adapters/cards/HeldCardGrants.js +112 -22
  27. package/dist/adapters/cards/HeldCardGrants.js.map +1 -1
  28. package/dist/adapters/cards/PostgresCardHolds.d.ts +95 -0
  29. package/dist/adapters/cards/PostgresCardHolds.d.ts.map +1 -0
  30. package/dist/adapters/cards/PostgresCardHolds.js +411 -0
  31. package/dist/adapters/cards/PostgresCardHolds.js.map +1 -0
  32. package/dist/cli/Cards.d.ts +5 -0
  33. package/dist/cli/Cards.d.ts.map +1 -0
  34. package/dist/cli/Cards.js +48 -0
  35. package/dist/cli/Cards.js.map +1 -0
  36. package/dist/cli/Help.d.ts.map +1 -1
  37. package/dist/cli/Help.js +1 -0
  38. package/dist/cli/Help.js.map +1 -1
  39. package/dist/config/ConfigKeys.d.ts +2 -2
  40. package/dist/config/ConfigKeys.d.ts.map +1 -1
  41. package/dist/config/ConfigKeys.js +12 -0
  42. package/dist/config/ConfigKeys.js.map +1 -1
  43. package/dist/config/ExecutorConfig.d.ts +53 -0
  44. package/dist/config/ExecutorConfig.d.ts.map +1 -1
  45. package/dist/config/ExecutorConfig.js +88 -0
  46. package/dist/config/ExecutorConfig.js.map +1 -1
  47. package/dist/http/Routes.d.ts +7 -0
  48. package/dist/http/Routes.d.ts.map +1 -1
  49. package/dist/http/Routes.js +7 -1
  50. package/dist/http/Routes.js.map +1 -1
  51. package/dist/identity/Authenticator.d.ts.map +1 -1
  52. package/dist/identity/Authenticator.js +5 -2
  53. package/dist/identity/Authenticator.js.map +1 -1
  54. package/dist/identity/PrincipalsFile.d.ts +3 -1
  55. package/dist/identity/PrincipalsFile.d.ts.map +1 -1
  56. package/dist/identity/PrincipalsFile.js +1 -0
  57. package/dist/identity/PrincipalsFile.js.map +1 -1
  58. package/dist/incident/SecurityEvents.d.ts +9 -0
  59. package/dist/incident/SecurityEvents.d.ts.map +1 -1
  60. package/dist/incident/SecurityEvents.js +3 -0
  61. package/dist/incident/SecurityEvents.js.map +1 -1
  62. package/dist/service/EscalationResolver.d.ts +30 -6
  63. package/dist/service/EscalationResolver.d.ts.map +1 -1
  64. package/dist/service/EscalationResolver.js +2 -0
  65. package/dist/service/EscalationResolver.js.map +1 -1
  66. package/dist/service/Requests.d.ts +17 -0
  67. package/dist/service/Requests.d.ts.map +1 -1
  68. package/dist/service/TrustedExecutorService.d.ts +77 -4
  69. package/dist/service/TrustedExecutorService.d.ts.map +1 -1
  70. package/dist/service/TrustedExecutorService.js +451 -56
  71. package/dist/service/TrustedExecutorService.js.map +1 -1
  72. package/package.json +2 -2
@@ -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";
@@ -7,8 +8,11 @@ import { BankingAdapter, BankingActionError } from "../adapters/banking/BankingA
7
8
  import { isBankingActionName } from "../adapters/banking/BankingAction.js";
8
9
  import { matchCardAuthorization } from "../adapters/cards/CardAuthorizationMatcher.js";
9
10
  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";
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";
12
16
  import { jcsDigest } from "../adapters/JcsDigest.js";
13
17
  import { HashChain } from "../audit/HashChain.js";
14
18
  import { EVIDENCE_STREAM, HashChainedAuditSink } from "../audit/HashChainedAuditSink.js";
@@ -119,6 +123,8 @@ async function signBundle(secrets, payload) {
119
123
  const key = await importPKCS8(pem, "EdDSA");
120
124
  return await new CompactSign(payload).setProtectedHeader({ alg: "EdDSA" }).sign(key);
121
125
  }
126
+ /** The provider id an escalation requirement names for Decionis Presence. */
127
+ const DECIONIS_PRESENCE_PROVIDER = "decionis";
122
128
  export class TrustedExecutorService {
123
129
  config;
124
130
  secrets;
@@ -142,9 +148,16 @@ export class TrustedExecutorService {
142
148
  unsubscribeMetrics;
143
149
  effects;
144
150
  cards;
151
+ cardsTimer;
145
152
  edge;
146
153
  hasher = new CanonicalIntentHasher();
147
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();
148
161
  /** Bound before any await: one authorization id may claim only one request. */
149
162
  cardClaims = new Map();
150
163
  constructor(config, secrets, capture, registry, registered, clients, posture, egress,
@@ -158,6 +171,8 @@ export class TrustedExecutorService {
158
171
  effects,
159
172
  /** Card grants held for the issuer's authorization, and the authorizations that claimed one. */
160
173
  cards,
174
+ /** The shared hold store's hourly sweep, while it runs. */
175
+ cardsTimer = null,
161
176
  /** The edge evaluator, when the configuration asks for it. */
162
177
  edge = null) {
163
178
  this.config = config;
@@ -182,6 +197,7 @@ export class TrustedExecutorService {
182
197
  this.unsubscribeMetrics = unsubscribeMetrics;
183
198
  this.effects = effects;
184
199
  this.cards = cards;
200
+ this.cardsTimer = cardsTimer;
185
201
  this.edge = edge;
186
202
  }
187
203
  /**
@@ -354,7 +370,51 @@ export class TrustedExecutorService {
354
370
  for (const stop of unsubscribeRotations)
355
371
  stop();
356
372
  unsubscribeEvents();
357
- }, effects, new HeldCardGrants(), edge);
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 }),
417
+ });
358
418
  }
359
419
  /** The credential the configuration's kind names, over the secret store and the guarded fetch. */
360
420
  static credential(config, secrets, fetchImpl) {
@@ -433,6 +493,20 @@ export class TrustedExecutorService {
433
493
  async startEdge() {
434
494
  await this.edge?.start();
435
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
+ }
436
510
  /** The actions this process can run, for `/ready`. */
437
511
  get actions() {
438
512
  return this.registered.filter((action) => this.registry.has(action));
@@ -440,6 +514,10 @@ export class TrustedExecutorService {
440
514
  /** Stops following credential rotation and closes every outbound connection; the service answers nothing new after this. */
441
515
  close() {
442
516
  this.edge?.stop();
517
+ if (this.cardsTimer !== null)
518
+ clearInterval(this.cardsTimer);
519
+ this.cardsTimer = null;
520
+ void this.cards.close().catch(() => undefined);
443
521
  this.clients.close();
444
522
  this.egress.close();
445
523
  this.jwt?.stop();
@@ -576,7 +654,8 @@ export class TrustedExecutorService {
576
654
  this.events.emit({ event: "SEPARATION_OF_DUTIES_VIOLATED", principal: proposer.id });
577
655
  throw new ServiceError(422, "SEPARATION_OF_DUTIES_VIOLATED");
578
656
  }
579
- const captured = this.captureIntent(request, proposer);
657
+ const velocity = await this.cardVelocity(request);
658
+ const captured = this.captureIntent(request, proposer, velocity);
580
659
  // Every line this proposal causes names the proposer, whichever
581
660
  // transport asked; the door's own scope, when there is one, agrees.
582
661
  return await RequestContext.run({ principal: proposer.id }, async () => {
@@ -591,7 +670,7 @@ export class TrustedExecutorService {
591
670
  try {
592
671
  this.assertNotHalted(captured);
593
672
  this.assertWithinLimits(captured, "CHECK");
594
- this.assertCardSpendable(captured);
673
+ await this.assertCardSpendable(captured);
595
674
  }
596
675
  catch (error) {
597
676
  if (error instanceof ServiceError)
@@ -640,23 +719,25 @@ export class TrustedExecutorService {
640
719
  });
641
720
  }
642
721
  /**
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.
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.
646
726
  */
647
- assertCardSpendable(captured) {
727
+ async assertCardSpendable(captured) {
648
728
  if (!isCardActionName(captured.intent.action))
649
729
  return;
650
730
  // An intent presented back is re-read here, so a card number written into
651
731
  // one after capture is refused like one in a proposal.
652
- let cardTokenRef;
732
+ let purchase;
653
733
  try {
654
- cardTokenRef = cardPurchaseOf(captured.intent.parameters).cardTokenRef;
734
+ purchase = cardPurchaseOf(captured.intent.parameters);
655
735
  }
656
736
  catch (error) {
657
737
  throw new ServiceError(422, error.code);
658
738
  }
659
- if (this.cards.spendable(cardTokenRef)) {
739
+ const key = { cardTokenRef: purchase.cardTokenRef, merchantId: purchase.merchantId };
740
+ if (await this.cards.spendable(key)) {
660
741
  throw new ServiceError(409, "CARD_GRANT_ALREADY_HELD");
661
742
  }
662
743
  }
@@ -729,7 +810,13 @@ export class TrustedExecutorService {
729
810
  * intent past its lifetime is refused before anything is asked.
730
811
  */
731
812
  async resume(input, caller) {
732
- const proposer = this.proposer(caller);
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);
733
820
  const parsed = EscalationResumeSchema.safeParse(input);
734
821
  if (!parsed.success)
735
822
  throw new ServiceError(400, "REQUEST_INVALID");
@@ -737,11 +824,14 @@ export class TrustedExecutorService {
737
824
  // An attestation needs no escalation shape: it is evidence for a fresh
738
825
  // evaluation, which any enforcing executor can ask for.
739
826
  const attested = resume.mode === "ATTESTATION";
827
+ if (proposer === null && !attested)
828
+ throw new ServiceError(403, "ROLE_FORBIDDEN");
740
829
  if (this.config.mode === "SHADOW" || (!attested && this.config.escalation.mode === "NONE")) {
741
830
  throw new ServiceError(409, "ESCALATION_NOT_CONFIGURED");
742
831
  }
743
832
  const captured = this.presented(resume.intent);
744
- this.assertOwn(captured, proposer);
833
+ if (proposer !== null)
834
+ this.assertOwn(captured, proposer);
745
835
  if (Date.parse(captured.intent.expiresAt) <= Date.now()) {
746
836
  throw new ServiceError(409, "INTENT_EXPIRED");
747
837
  }
@@ -749,10 +839,10 @@ export class TrustedExecutorService {
749
839
  throw new ServiceError(422, "ACTION_NOT_REGISTERED");
750
840
  }
751
841
  this.assertPosture();
752
- return await RequestContext.run({ principal: proposer.id }, async () => {
842
+ return await RequestContext.run({ principal: presenter.id }, async () => {
753
843
  try {
754
844
  this.assertNotHalted(captured);
755
- this.assertCardSpendable(captured);
845
+ await this.assertCardSpendable(captured);
756
846
  }
757
847
  catch (error) {
758
848
  if (error instanceof ServiceError)
@@ -867,6 +957,16 @@ export class TrustedExecutorService {
867
957
  }
868
958
  return principal;
869
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
+ }
870
970
  operator(caller, scope) {
871
971
  if (caller === undefined || caller.role !== "OPERATOR")
872
972
  throw new ServiceError(403, "ROLE_FORBIDDEN");
@@ -884,7 +984,24 @@ export class TrustedExecutorService {
884
984
  if (!own)
885
985
  throw new ServiceError(403, "INTENT_PRINCIPAL_MISMATCH");
886
986
  }
887
- 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 = {}) {
888
1005
  // A BEAP action carries its own canonical form in the parameters, so the
889
1006
  // transport's name and target are derived from it rather than trusted,
890
1007
  // and the digests the authority binds its grant to are computed here
@@ -894,6 +1011,16 @@ export class TrustedExecutorService {
894
1011
  ? this.bindBanking(request, proposer)
895
1012
  : null;
896
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 };
897
1024
  const trusted = {
898
1025
  tenantId: proposer.tenantId,
899
1026
  actor: proposer.actor,
@@ -902,11 +1029,11 @@ export class TrustedExecutorService {
902
1029
  operation: this.config.downstream.operation,
903
1030
  environment: this.config.downstream.environment,
904
1031
  },
905
- context: { caller_principal: proposer.id, ...(bound === null ? {} : bound.context) },
1032
+ context,
906
1033
  idempotencyKey: request.idempotency_key,
907
1034
  ...(request.correlation_id === undefined ? {} : { correlationId: request.correlation_id }),
908
1035
  ...(bound === null ? {} : { expectedEffectDigest: bound.expectedEffectDigest }),
909
- ...(card === null ? {} : { expectedEffectDigest: card }),
1036
+ ...(card === null ? {} : { expectedEffectDigest: card.expectedEffectDigest }),
910
1037
  };
911
1038
  const parameters = request.proposal.parameters ?? {};
912
1039
  try {
@@ -952,12 +1079,46 @@ export class TrustedExecutorService {
952
1079
  target: request.proposal.target,
953
1080
  parameters: request.proposal.parameters ?? {},
954
1081
  });
955
- return prepareCardPurchase(purchase).expectedEffectDigest;
1082
+ return {
1083
+ expectedEffectDigest: prepareCardPurchase(purchase).expectedEffectDigest,
1084
+ cardTokenRef: purchase.cardTokenRef,
1085
+ };
956
1086
  }
957
1087
  catch (error) {
958
1088
  throw new ServiceError(422, error.code);
959
1089
  }
960
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
+ }
961
1122
  /**
962
1123
  * The two digests a banking intent is bound to, taken from the profile's
963
1124
  * own arithmetic. This reaches nothing: `prepare` is pure, which is why
@@ -1113,22 +1274,32 @@ export class TrustedExecutorService {
1113
1274
  let handoff = null;
1114
1275
  let unavailable = false;
1115
1276
  if (decision.verdict === "ESCALATE" && !decision.failClosed) {
1116
- const state = await escalation.handoff(captured, decision);
1117
- if (state !== null)
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 };
1124
- else if (this.config.escalation.mode !== "NONE")
1125
- 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
+ }
1126
1296
  }
1127
1297
  return this.response(captured, decision, outcome, handoff, unavailable ? ["ESCALATION_HANDOFF_UNAVAILABLE"] : []);
1128
1298
  }
1129
1299
  /**
1130
1300
  * 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
1301
+ * grant for the issuer's authorization, keyed by the card and the
1302
+ * merchant. Nothing is
1132
1303
  * claimed and nothing runs; the hard ceilings are committed now, because
1133
1304
  * this is the last moment this process decides anything about the amount.
1134
1305
  * A refusal comes back as the executor's own blocked result.
@@ -1143,7 +1314,7 @@ export class TrustedExecutorService {
1143
1314
  return outcome;
1144
1315
  }
1145
1316
  const purchase = cardPurchaseOf(captured.intent.parameters);
1146
- const stored = this.cards.hold({
1317
+ const stored = await this.cards.hold({
1147
1318
  cardTokenRef: purchase.cardTokenRef,
1148
1319
  amountMinor: purchase.amountMinor,
1149
1320
  currency: purchase.currency,
@@ -1195,13 +1366,31 @@ export class TrustedExecutorService {
1195
1366
  * the issuer's policy, not this process's.
1196
1367
  */
1197
1368
  async authorizeCard(input, caller) {
1198
- this.operator(caller, "cards.authorize");
1369
+ const operator = this.operator(caller, "cards.authorize");
1199
1370
  const request = TrustedExecutorService.cardRequest(() => cardAuthorizationOf(input));
1200
- const previous = this.cards.claimed(request.authorization_id);
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
+ }
1201
1378
  if (previous !== undefined) {
1202
1379
  if (jcsDigest(previous.request) === jcsDigest(request)) {
1203
1380
  return previous.answer;
1204
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
+ }
1205
1394
  return this.noMatch(null, "AUTHORIZATION_ID_REUSED");
1206
1395
  }
1207
1396
  const digest = jcsDigest(request);
@@ -1216,7 +1405,7 @@ export class TrustedExecutorService {
1216
1405
  }
1217
1406
  // Reserve the id synchronously, before journal/claim I/O can yield to a
1218
1407
  // conflicting request. Identical concurrent retries share the same result.
1219
- const answer = Promise.resolve().then(() => this.claimCard(request));
1408
+ const answer = Promise.resolve().then(() => this.claimCard(request, operator.id));
1220
1409
  this.cardClaims.set(request.authorization_id, { digest, answer });
1221
1410
  try {
1222
1411
  return await answer;
@@ -1225,21 +1414,54 @@ export class TrustedExecutorService {
1225
1414
  this.cardClaims.delete(request.authorization_id);
1226
1415
  }
1227
1416
  }
1228
- async claimCard(request) {
1417
+ async claimCard(request, callerId, evaluated = false) {
1229
1418
  if (this.haltSwitch.current.halted)
1230
1419
  return this.noMatch(null, "EXECUTOR_HALTED");
1231
1420
  if (this.posture.degraded)
1232
1421
  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;
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");
1243
1465
  const { captured, decision } = matched.held;
1244
1466
  const intentId = captured.intent.intentId;
1245
1467
  try {
@@ -1288,17 +1510,164 @@ export class TrustedExecutorService {
1288
1510
  grant_id: authorization.grantId,
1289
1511
  lease_expires_at: lease,
1290
1512
  };
1291
- this.cards.recordClaim(request.authorization_id, {
1292
- grant: matched,
1293
- request,
1294
- authorization,
1295
- leaseExpiresAtMs: Date.parse(lease),
1296
- answer,
1297
- });
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
+ }
1298
1529
  this.metrics.executions.inc({ outcome: "CARD_AUTHORIZATION_MATCHED" });
1299
1530
  this.events.emit({ event: "CARD_AUTHORIZATION_MATCHED", intent_id: intentId });
1300
1531
  return answer;
1301
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
+ }
1302
1671
  /**
1303
1672
  * What the issuer did with an authorization it was told to approve. An
1304
1673
  * approval is the effect, compared with what the grant authorised; a
@@ -1311,12 +1680,21 @@ export class TrustedExecutorService {
1311
1680
  if (!isCardReference(authorizationId))
1312
1681
  throw new ServiceError(400, "REQUEST_INVALID");
1313
1682
  const result = TrustedExecutorService.cardRequest(() => cardAuthorizationResultOf(input));
1314
- const claim = this.cards.claimed(authorizationId);
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
+ }
1315
1692
  if (claim === undefined)
1316
1693
  throw new ServiceError(404, "CARD_AUTHORIZATION_UNKNOWN");
1317
- if (claim.settled)
1694
+ // Settled once, by the one rule every replica shares.
1695
+ if (claim.settled || !(await this.cards.settle(authorizationId))) {
1318
1696
  throw new ServiceError(409, "CARD_RESULT_ALREADY_RECORDED");
1319
- claim.settled = true;
1697
+ }
1320
1698
  const { grant, authorization } = claim;
1321
1699
  const { captured } = grant.held;
1322
1700
  const leaseExpired = Date.now() > claim.leaseExpiresAtMs;
@@ -1401,6 +1779,23 @@ export class TrustedExecutorService {
1401
1779
  throw new ServiceError(code === "CARD_PAN_REFUSED" ? 422 : 400, code);
1402
1780
  }
1403
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
+ }
1404
1799
  static cardView(request) {
1405
1800
  return {
1406
1801
  cardTokenRef: request.card_token_ref,