@decionis/agentsafe 0.3.0 → 0.5.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 (74) hide show
  1. package/README.md +187 -122
  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 +34 -7
  63. package/dist/service/EscalationResolver.d.ts.map +1 -1
  64. package/dist/service/EscalationResolver.js +9 -4
  65. package/dist/service/EscalationResolver.js.map +1 -1
  66. package/dist/service/Requests.d.ts +29 -5
  67. package/dist/service/Requests.d.ts.map +1 -1
  68. package/dist/service/Requests.js +14 -0
  69. package/dist/service/Requests.js.map +1 -1
  70. package/dist/service/TrustedExecutorService.d.ts +77 -4
  71. package/dist/service/TrustedExecutorService.d.ts.map +1 -1
  72. package/dist/service/TrustedExecutorService.js +463 -64
  73. package/dist/service/TrustedExecutorService.js.map +1 -1
  74. 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,12 +654,17 @@ 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);
659
+ // A producer's signed signals travel beside the intent as evidence, never
660
+ // inside it: the authority verifies them and keeps their facts, and this
661
+ // process keeps nothing of the tokens.
662
+ const evidence = request.signals === undefined ? undefined : { signals: request.signals };
580
663
  // Every line this proposal causes names the proposer, whichever
581
664
  // transport asked; the door's own scope, when there is one, agrees.
582
665
  return await RequestContext.run({ principal: proposer.id }, async () => {
583
666
  if (this.config.mode === "SHADOW") {
584
- const observed = await this.observe(captured);
667
+ const observed = await this.observe(captured, evidence);
585
668
  this.metrics.proposals.inc({ verdict: observed.verdict ?? "NONE" });
586
669
  return observed;
587
670
  }
@@ -591,21 +674,21 @@ export class TrustedExecutorService {
591
674
  try {
592
675
  this.assertNotHalted(captured);
593
676
  this.assertWithinLimits(captured, "CHECK");
594
- this.assertCardSpendable(captured);
677
+ await this.assertCardSpendable(captured);
595
678
  }
596
679
  catch (error) {
597
680
  if (error instanceof ServiceError)
598
681
  await this.recordRefusal(captured, error.code);
599
682
  throw error;
600
683
  }
601
- const answer = await this.enforceAfterPosture(captured);
684
+ const answer = await this.enforceAfterPosture(captured, evidence);
602
685
  this.metrics.proposals.inc({ verdict: answer.verdict ?? "NONE" });
603
686
  return answer;
604
687
  });
605
688
  }
606
- async enforceAfterPosture(captured) {
689
+ async enforceAfterPosture(captured, evidence) {
607
690
  this.assertPosture();
608
- return await this.enforce(captured);
691
+ return await this.enforce(captured, evidence);
609
692
  }
610
693
  /** The stop, checked after the intent is captured and before any authority is asked. */
611
694
  assertNotHalted(captured) {
@@ -640,23 +723,25 @@ export class TrustedExecutorService {
640
723
  });
641
724
  }
642
725
  /**
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.
726
+ * One spendable hold per card and merchant: a purchase at a merchant where
727
+ * the card already has one waits until it is authorised or expires,
728
+ * refused before the authority is asked so the refusal costs no dossier
729
+ * and no grant. The same card at another merchant holds in parallel.
646
730
  */
647
- assertCardSpendable(captured) {
731
+ async assertCardSpendable(captured) {
648
732
  if (!isCardActionName(captured.intent.action))
649
733
  return;
650
734
  // An intent presented back is re-read here, so a card number written into
651
735
  // one after capture is refused like one in a proposal.
652
- let cardTokenRef;
736
+ let purchase;
653
737
  try {
654
- cardTokenRef = cardPurchaseOf(captured.intent.parameters).cardTokenRef;
738
+ purchase = cardPurchaseOf(captured.intent.parameters);
655
739
  }
656
740
  catch (error) {
657
741
  throw new ServiceError(422, error.code);
658
742
  }
659
- if (this.cards.spendable(cardTokenRef)) {
743
+ const key = { cardTokenRef: purchase.cardTokenRef, merchantId: purchase.merchantId };
744
+ if (await this.cards.spendable(key)) {
660
745
  throw new ServiceError(409, "CARD_GRANT_ALREADY_HELD");
661
746
  }
662
747
  }
@@ -729,7 +814,13 @@ export class TrustedExecutorService {
729
814
  * intent past its lifetime is refused before anything is asked.
730
815
  */
731
816
  async resume(input, caller) {
732
- const proposer = this.proposer(caller);
817
+ // The proposer that holds the intent resumes it. An operator holding
818
+ // `escalations.resume` (the issuer app's backend, where a cardholder's
819
+ // tap lands) may present a presence provider's attestation for an intent
820
+ // it did not propose, and nothing else: the authority binds the
821
+ // attestation to the intent hash, so the operator adds no authority.
822
+ const proposer = caller?.role === "OPERATOR" ? null : this.proposer(caller);
823
+ const presenter = proposer ?? TrustedExecutorService.presenter(caller);
733
824
  const parsed = EscalationResumeSchema.safeParse(input);
734
825
  if (!parsed.success)
735
826
  throw new ServiceError(400, "REQUEST_INVALID");
@@ -737,11 +828,14 @@ export class TrustedExecutorService {
737
828
  // An attestation needs no escalation shape: it is evidence for a fresh
738
829
  // evaluation, which any enforcing executor can ask for.
739
830
  const attested = resume.mode === "ATTESTATION";
831
+ if (proposer === null && !attested)
832
+ throw new ServiceError(403, "ROLE_FORBIDDEN");
740
833
  if (this.config.mode === "SHADOW" || (!attested && this.config.escalation.mode === "NONE")) {
741
834
  throw new ServiceError(409, "ESCALATION_NOT_CONFIGURED");
742
835
  }
743
836
  const captured = this.presented(resume.intent);
744
- this.assertOwn(captured, proposer);
837
+ if (proposer !== null)
838
+ this.assertOwn(captured, proposer);
745
839
  if (Date.parse(captured.intent.expiresAt) <= Date.now()) {
746
840
  throw new ServiceError(409, "INTENT_EXPIRED");
747
841
  }
@@ -749,10 +843,10 @@ export class TrustedExecutorService {
749
843
  throw new ServiceError(422, "ACTION_NOT_REGISTERED");
750
844
  }
751
845
  this.assertPosture();
752
- return await RequestContext.run({ principal: proposer.id }, async () => {
846
+ return await RequestContext.run({ principal: presenter.id }, async () => {
753
847
  try {
754
848
  this.assertNotHalted(captured);
755
- this.assertCardSpendable(captured);
849
+ await this.assertCardSpendable(captured);
756
850
  }
757
851
  catch (error) {
758
852
  if (error instanceof ServiceError)
@@ -867,6 +961,16 @@ export class TrustedExecutorService {
867
961
  }
868
962
  return principal;
869
963
  }
964
+ /**
965
+ * An operator may present an attestation only under `escalations.resume`;
966
+ * without it the operator is no presenter at all, and the refusal is the
967
+ * door's: a role the route does not admit.
968
+ */
969
+ static presenter(caller) {
970
+ if (!caller.scopes.has("escalations.resume"))
971
+ throw new ServiceError(403, "ROLE_FORBIDDEN");
972
+ return caller;
973
+ }
870
974
  operator(caller, scope) {
871
975
  if (caller === undefined || caller.role !== "OPERATOR")
872
976
  throw new ServiceError(403, "ROLE_FORBIDDEN");
@@ -884,7 +988,24 @@ export class TrustedExecutorService {
884
988
  if (!own)
885
989
  throw new ServiceError(403, "INTENT_PRINCIPAL_MISMATCH");
886
990
  }
887
- captureIntent(request, proposer) {
991
+ /**
992
+ * The burst on this card, counted before capture because the store may be
993
+ * shared and is asked asynchronously; a purchase the binder will refuse
994
+ * is not counted, and the binder's own refusal follows.
995
+ */
996
+ async cardVelocity(request) {
997
+ if (!isCardActionName(request.proposal.action))
998
+ return null;
999
+ let purchase;
1000
+ try {
1001
+ purchase = cardPurchaseOf(request.proposal.parameters);
1002
+ }
1003
+ catch {
1004
+ return null;
1005
+ }
1006
+ return await this.cards.velocity(purchase.cardTokenRef);
1007
+ }
1008
+ captureIntent(request, proposer, velocity = null, extra = {}) {
888
1009
  // A BEAP action carries its own canonical form in the parameters, so the
889
1010
  // transport's name and target are derived from it rather than trusted,
890
1011
  // and the digests the authority binds its grant to are computed here
@@ -894,6 +1015,16 @@ export class TrustedExecutorService {
894
1015
  ? this.bindBanking(request, proposer)
895
1016
  : null;
896
1017
  const card = isCardActionName(request.proposal.action) ? this.bindCard(request) : null;
1018
+ const context = {
1019
+ caller_principal: proposer.id,
1020
+ ...(bound === null ? {} : bound.context),
1021
+ ...extra,
1022
+ };
1023
+ // The burst on this card, counted here because policy counts nothing over
1024
+ // time: how many purchases were held for it and claimed lately. Numbers
1025
+ // only; the card reference stays in the parameters.
1026
+ if (card !== null && velocity !== null)
1027
+ context["card_velocity"] = { ...velocity };
897
1028
  const trusted = {
898
1029
  tenantId: proposer.tenantId,
899
1030
  actor: proposer.actor,
@@ -902,11 +1033,11 @@ export class TrustedExecutorService {
902
1033
  operation: this.config.downstream.operation,
903
1034
  environment: this.config.downstream.environment,
904
1035
  },
905
- context: { caller_principal: proposer.id, ...(bound === null ? {} : bound.context) },
1036
+ context,
906
1037
  idempotencyKey: request.idempotency_key,
907
1038
  ...(request.correlation_id === undefined ? {} : { correlationId: request.correlation_id }),
908
1039
  ...(bound === null ? {} : { expectedEffectDigest: bound.expectedEffectDigest }),
909
- ...(card === null ? {} : { expectedEffectDigest: card }),
1040
+ ...(card === null ? {} : { expectedEffectDigest: card.expectedEffectDigest }),
910
1041
  };
911
1042
  const parameters = request.proposal.parameters ?? {};
912
1043
  try {
@@ -952,12 +1083,46 @@ export class TrustedExecutorService {
952
1083
  target: request.proposal.target,
953
1084
  parameters: request.proposal.parameters ?? {},
954
1085
  });
955
- return prepareCardPurchase(purchase).expectedEffectDigest;
1086
+ return {
1087
+ expectedEffectDigest: prepareCardPurchase(purchase).expectedEffectDigest,
1088
+ cardTokenRef: purchase.cardTokenRef,
1089
+ };
956
1090
  }
957
1091
  catch (error) {
958
1092
  throw new ServiceError(422, error.code);
959
1093
  }
960
1094
  }
1095
+ /** The hold's routing as the handoff carries it, from the decision when the authority said. */
1096
+ static attestationRequirement(decision) {
1097
+ const routing = decision.escalationRequirement;
1098
+ if (routing === undefined)
1099
+ return null;
1100
+ return {
1101
+ requirement_id: routing.requirementId,
1102
+ expires_at: routing.expiresAt,
1103
+ selector: routing.selector === null
1104
+ ? null
1105
+ : {
1106
+ kind: routing.selector.kind,
1107
+ ...(routing.selector.roleId === undefined
1108
+ ? {}
1109
+ : { role_id: routing.selector.roleId }),
1110
+ },
1111
+ verification: routing.verification === null
1112
+ ? null
1113
+ : {
1114
+ provider: routing.verification.provider,
1115
+ methods: [...routing.verification.methods],
1116
+ level: routing.verification.level,
1117
+ },
1118
+ };
1119
+ }
1120
+ /** Whether the policy sent the hold to a presence provider other than Decionis Presence. */
1121
+ static routedToProvider(requirement) {
1122
+ return (requirement !== null &&
1123
+ requirement.verification !== null &&
1124
+ requirement.verification.provider !== DECIONIS_PRESENCE_PROVIDER);
1125
+ }
961
1126
  /**
962
1127
  * The two digests a banking intent is bound to, taken from the profile's
963
1128
  * own arithmetic. This reaches nothing: `prepare` is pure, which is why
@@ -1057,14 +1222,14 @@ export class TrustedExecutorService {
1057
1222
  throw new ServiceError(400, "INTENT_INVALID");
1058
1223
  }
1059
1224
  }
1060
- async observe(captured) {
1225
+ async observe(captured, evidence) {
1061
1226
  const shadow = this.clients.current().shadow;
1062
1227
  if (shadow === null)
1063
1228
  throw new ServiceError(500, "MODE_MISMATCH");
1064
1229
  // The production action, if any, runs in the caller. What this process
1065
1230
  // contributes in shadow is the observation and its evidence, never an
1066
1231
  // execution and never a grant.
1067
- const comparison = await shadow.compare(captured, () => null);
1232
+ const comparison = await shadow.compare(captured, () => null, evidence === undefined ? {} : { evidence });
1068
1233
  const observation = comparison.observation;
1069
1234
  return {
1070
1235
  mode: "SHADOW",
@@ -1085,9 +1250,9 @@ export class TrustedExecutorService {
1085
1250
  escalation: null,
1086
1251
  };
1087
1252
  }
1088
- async enforce(captured) {
1253
+ async enforce(captured, evidence) {
1089
1254
  const { escalation, executor } = this.clients.current();
1090
- const decision = await escalation.evaluate(captured);
1255
+ const decision = await escalation.evaluate(captured, evidence);
1091
1256
  const card = isCardActionName(captured.intent.action);
1092
1257
  let outcome;
1093
1258
  if (card) {
@@ -1113,22 +1278,32 @@ export class TrustedExecutorService {
1113
1278
  let handoff = null;
1114
1279
  let unavailable = false;
1115
1280
  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;
1281
+ const requirement = TrustedExecutorService.attestationRequirement(decision);
1282
+ if (TrustedExecutorService.routedToProvider(requirement)) {
1283
+ // The policy sent this hold to a third-party presence provider (a
1284
+ // cardholder's tap through the issuer's app): no Presence ceremony
1285
+ // is asked for, and only that provider's attestation resumes it.
1286
+ handoff = { mode: "ATTESTATION", intent: captured.intent, requirement };
1287
+ }
1288
+ else {
1289
+ const state = await escalation.handoff(captured, decision);
1290
+ if (state !== null)
1291
+ handoff = { ...state, intent: captured.intent };
1292
+ // A cardholder's tap needs no Presence ceremony: whatever shape this
1293
+ // executor escalates in, a card purchase can be resumed with an
1294
+ // attestation over the intent it is handed here.
1295
+ else if (card)
1296
+ handoff = { mode: "ATTESTATION", intent: captured.intent, requirement };
1297
+ else if (this.config.escalation.mode !== "NONE")
1298
+ unavailable = true;
1299
+ }
1126
1300
  }
1127
1301
  return this.response(captured, decision, outcome, handoff, unavailable ? ["ESCALATION_HANDOFF_UNAVAILABLE"] : []);
1128
1302
  }
1129
1303
  /**
1130
1304
  * 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
1305
+ * grant for the issuer's authorization, keyed by the card and the
1306
+ * merchant. Nothing is
1132
1307
  * claimed and nothing runs; the hard ceilings are committed now, because
1133
1308
  * this is the last moment this process decides anything about the amount.
1134
1309
  * A refusal comes back as the executor's own blocked result.
@@ -1143,7 +1318,7 @@ export class TrustedExecutorService {
1143
1318
  return outcome;
1144
1319
  }
1145
1320
  const purchase = cardPurchaseOf(captured.intent.parameters);
1146
- const stored = this.cards.hold({
1321
+ const stored = await this.cards.hold({
1147
1322
  cardTokenRef: purchase.cardTokenRef,
1148
1323
  amountMinor: purchase.amountMinor,
1149
1324
  currency: purchase.currency,
@@ -1195,13 +1370,31 @@ export class TrustedExecutorService {
1195
1370
  * the issuer's policy, not this process's.
1196
1371
  */
1197
1372
  async authorizeCard(input, caller) {
1198
- this.operator(caller, "cards.authorize");
1373
+ const operator = this.operator(caller, "cards.authorize");
1199
1374
  const request = TrustedExecutorService.cardRequest(() => cardAuthorizationOf(input));
1200
- const previous = this.cards.claimed(request.authorization_id);
1375
+ let previous;
1376
+ try {
1377
+ previous = await this.cards.claimed(request.authorization_id);
1378
+ }
1379
+ catch {
1380
+ return this.noMatch(null, "CARD_HOLDS_UNAVAILABLE");
1381
+ }
1201
1382
  if (previous !== undefined) {
1202
1383
  if (jcsDigest(previous.request) === jcsDigest(request)) {
1203
1384
  return previous.answer;
1204
1385
  }
1386
+ // An issuer that may present the same authorization for more, up to
1387
+ // the ceiling and before its result, is answered from the same claim:
1388
+ // nothing new is claimed, and the result records the final amount.
1389
+ if (this.config.cards.authorizations === "incremental" &&
1390
+ TrustedExecutorService.incrementOf(previous, request) &&
1391
+ (await this.cards.amend(request.authorization_id, request))) {
1392
+ this.events.emit({
1393
+ event: "CARD_AUTHORIZATION_INCREMENTED",
1394
+ intent_id: previous.answer.intent_id,
1395
+ });
1396
+ return previous.answer;
1397
+ }
1205
1398
  return this.noMatch(null, "AUTHORIZATION_ID_REUSED");
1206
1399
  }
1207
1400
  const digest = jcsDigest(request);
@@ -1216,7 +1409,7 @@ export class TrustedExecutorService {
1216
1409
  }
1217
1410
  // Reserve the id synchronously, before journal/claim I/O can yield to a
1218
1411
  // conflicting request. Identical concurrent retries share the same result.
1219
- const answer = Promise.resolve().then(() => this.claimCard(request));
1412
+ const answer = Promise.resolve().then(() => this.claimCard(request, operator.id));
1220
1413
  this.cardClaims.set(request.authorization_id, { digest, answer });
1221
1414
  try {
1222
1415
  return await answer;
@@ -1225,21 +1418,54 @@ export class TrustedExecutorService {
1225
1418
  this.cardClaims.delete(request.authorization_id);
1226
1419
  }
1227
1420
  }
1228
- async claimCard(request) {
1421
+ async claimCard(request, callerId, evaluated = false) {
1229
1422
  if (this.haltSwitch.current.halted)
1230
1423
  return this.noMatch(null, "EXECUTOR_HALTED");
1231
1424
  if (this.posture.degraded)
1232
1425
  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;
1426
+ let record;
1427
+ try {
1428
+ record = await this.cards.grant({
1429
+ cardTokenRef: request.card_token_ref,
1430
+ merchantId: request.merchant_id,
1431
+ });
1432
+ }
1433
+ catch {
1434
+ return this.noMatch(null, "CARD_HOLDS_UNAVAILABLE");
1435
+ }
1436
+ if (record === undefined) {
1437
+ // A hold the commit-boundary evaluation just made and the store cannot
1438
+ // show is not evaluated again: the answer says the hold was lost.
1439
+ if (evaluated)
1440
+ return this.noMatch(null, "CARD_HOLD_UNAVAILABLE");
1441
+ return await this.withoutGrant(request, callerId);
1442
+ }
1443
+ const match = matchCardAuthorization(record, TrustedExecutorService.cardView(request), Date.now());
1444
+ if (match.decision === "NO_MATCH")
1445
+ return this.noMatch(record.intentId, match.code);
1446
+ // The hold with a handle this process can claim; one another replica
1447
+ // made is admitted here first, through the executor's own checks.
1448
+ let matched;
1449
+ try {
1450
+ matched = await record.open();
1451
+ }
1452
+ catch {
1453
+ return this.noMatch(record.intentId, "CARD_HOLDS_UNAVAILABLE");
1454
+ }
1455
+ if (matched === null)
1456
+ return this.noMatch(record.intentId, "GRANT_CLAIM_REFUSED");
1457
+ // Spent before anything else is awaited, by the one rule every replica
1458
+ // shares, so a concurrent authorization for the same grant finds it used
1459
+ // rather than racing this one to the claim.
1460
+ let spent;
1461
+ try {
1462
+ spent = await this.cards.spend(matched);
1463
+ }
1464
+ catch {
1465
+ return this.noMatch(record.intentId, "CARD_HOLDS_UNAVAILABLE");
1466
+ }
1467
+ if (!spent)
1468
+ return this.noMatch(record.intentId, "GRANT_ALREADY_USED");
1243
1469
  const { captured, decision } = matched.held;
1244
1470
  const intentId = captured.intent.intentId;
1245
1471
  try {
@@ -1288,17 +1514,164 @@ export class TrustedExecutorService {
1288
1514
  grant_id: authorization.grantId,
1289
1515
  lease_expires_at: lease,
1290
1516
  };
1291
- this.cards.recordClaim(request.authorization_id, {
1292
- grant: matched,
1293
- request,
1294
- authorization,
1295
- leaseExpiresAtMs: Date.parse(lease),
1296
- answer,
1297
- });
1517
+ try {
1518
+ await this.cards.recordClaim(request.authorization_id, {
1519
+ grant: matched,
1520
+ request,
1521
+ authorization,
1522
+ leaseExpiresAtMs: Date.parse(lease),
1523
+ answer,
1524
+ material: matched.executor.claimMaterial(authorization),
1525
+ });
1526
+ }
1527
+ catch {
1528
+ // The claim is journaled and the issuer is answered; a record the
1529
+ // shared store could not keep is a result this replica alone can
1530
+ // settle, which the journal's open attempt still shows.
1531
+ this.events.emit({ event: "CARD_CLAIM_RECORD_FAILED", intent_id: intentId });
1532
+ }
1298
1533
  this.metrics.executions.inc({ outcome: "CARD_AUTHORIZATION_MATCHED" });
1299
1534
  this.events.emit({ event: "CARD_AUTHORIZATION_MATCHED", intent_id: intentId });
1300
1535
  return answer;
1301
1536
  }
1537
+ /**
1538
+ * An authorization with no hold. By default it is `NO_MATCH`: nothing was
1539
+ * decided before the card was presented. A deployment that evaluates at
1540
+ * the commit boundary answers it from an evaluation made now, and one
1541
+ * already evaluated and escalated is answered the same way until its
1542
+ * intent expires, so a platform that re-presents it is told the same thing
1543
+ * and nothing is evaluated twice. Once the tap has resumed the hold, the
1544
+ * re-presented authorization finds it before it gets here.
1545
+ */
1546
+ async withoutGrant(request, callerId) {
1547
+ if (this.config.cards.noGrant !== "evaluate")
1548
+ return this.noMatch(null, "NO_GRANT");
1549
+ const pending = this.pendingCommits.get(request.authorization_id);
1550
+ if (pending !== undefined) {
1551
+ if (Date.parse(pending.answer.expires_at) <= Date.now()) {
1552
+ this.pendingCommits.delete(request.authorization_id);
1553
+ }
1554
+ else if (pending.digest === jcsDigest(request)) {
1555
+ return pending.answer;
1556
+ }
1557
+ else {
1558
+ return this.noMatch(pending.answer.intent_id, "AUTHORIZATION_ID_REUSED");
1559
+ }
1560
+ }
1561
+ return await this.evaluateAtCommit(request, callerId);
1562
+ }
1563
+ /**
1564
+ * The commit boundary: the authorization becomes the intent, captured as
1565
+ * the commit actor the deployment names and evaluated now, with the
1566
+ * authorization's id in the intent's context so the dossier says what it
1567
+ * decided about. An `ALLOW` is held and claimed in this same call. An
1568
+ * `ESCALATE` is `PENDING`, with the handoff: a platform that can pend keeps
1569
+ * the authorization waiting, the tap arrives through `POST /v1/escalations`
1570
+ * with the handoff's intent, and the re-presented authorization matches the
1571
+ * hold the tap left. A `BLOCK`, a refusal this host makes on its own, and
1572
+ * an authority that did not answer are `NO_MATCH` with their code. In
1573
+ * shadow the evaluation is observed and the authorization is `NO_MATCH`.
1574
+ */
1575
+ async evaluateAtCommit(request, callerId) {
1576
+ const commit = this.config.cards.commit;
1577
+ if (commit === null)
1578
+ return this.noMatch(null, "NO_GRANT");
1579
+ const parameters = {
1580
+ cardTokenRef: request.card_token_ref,
1581
+ amountMinor: request.amount_minor,
1582
+ currency: request.currency,
1583
+ merchantId: request.merchant_id,
1584
+ ...(request.mcc === undefined ? {} : { mcc: request.mcc }),
1585
+ };
1586
+ const proposal = {
1587
+ proposal: {
1588
+ action: CARD_PURCHASE_ACTION,
1589
+ target: cardTarget({ cardTokenRef: request.card_token_ref }),
1590
+ parameters,
1591
+ },
1592
+ idempotency_key: TrustedExecutorService.commitIdempotencyKey(request.authorization_id),
1593
+ };
1594
+ const identity = {
1595
+ id: callerId,
1596
+ tenantId: commit.tenantId,
1597
+ actor: commit.actor,
1598
+ };
1599
+ let captured;
1600
+ try {
1601
+ captured = this.captureIntent(proposal, identity, await this.cards.velocity(request.card_token_ref), {
1602
+ commit_boundary: "ISSUER_HOOK",
1603
+ card_authorization: { authorization_id: request.authorization_id },
1604
+ });
1605
+ }
1606
+ catch (error) {
1607
+ return this.noMatch(null, error instanceof ServiceError ? error.code : "PROPOSAL_INVALID");
1608
+ }
1609
+ return await RequestContext.run({ principal: callerId }, async () => {
1610
+ if (this.config.mode === "SHADOW") {
1611
+ const observed = await this.observe(captured);
1612
+ this.metrics.proposals.inc({ verdict: observed.verdict ?? "NONE" });
1613
+ return this.noMatch(captured.intent.intentId, "SHADOW_OBSERVED");
1614
+ }
1615
+ try {
1616
+ this.assertNotHalted(captured);
1617
+ this.assertWithinLimits(captured, "CHECK");
1618
+ }
1619
+ catch (error) {
1620
+ if (!(error instanceof ServiceError))
1621
+ throw error;
1622
+ await this.recordRefusal(captured, error.code);
1623
+ return this.noMatch(captured.intent.intentId, error.code);
1624
+ }
1625
+ let answer;
1626
+ try {
1627
+ answer = await this.enforceAfterPosture(captured);
1628
+ }
1629
+ catch (error) {
1630
+ if (!(error instanceof ServiceError))
1631
+ throw error;
1632
+ return this.noMatch(captured.intent.intentId, error.code);
1633
+ }
1634
+ this.metrics.proposals.inc({ verdict: answer.verdict ?? "NONE" });
1635
+ if (answer.outcome === "HELD_FOR_AUTHORIZATION") {
1636
+ return await this.claimCard(request, callerId, true);
1637
+ }
1638
+ if (answer.verdict === "ESCALATE" && answer.escalation !== null) {
1639
+ const pending = {
1640
+ decision: "PENDING",
1641
+ authorization_id: request.authorization_id,
1642
+ intent_id: answer.intent_id,
1643
+ intent_hash: answer.intent_hash,
1644
+ decision_id: answer.decision_id,
1645
+ dossier_id: answer.dossier_id,
1646
+ expires_at: captured.intent.expiresAt,
1647
+ escalation: answer.escalation,
1648
+ };
1649
+ this.rememberPending(request, pending);
1650
+ this.metrics.executions.inc({ outcome: "CARD_AUTHORIZATION_PENDING" });
1651
+ this.events.emit({ event: "CARD_AUTHORIZATION_PENDING", intent_id: answer.intent_id });
1652
+ return pending;
1653
+ }
1654
+ return this.noMatch(answer.intent_id, answer.fail_closed ? "AUTHORITY_UNAVAILABLE" : "POLICY_BLOCK");
1655
+ });
1656
+ }
1657
+ /** Bounded like the claims: a full map forgets its oldest, whose intent is nearest its expiry. */
1658
+ rememberPending(request, answer) {
1659
+ if (this.pendingCommits.size >= 10_000) {
1660
+ const oldest = this.pendingCommits.keys().next().value;
1661
+ this.pendingCommits.delete(oldest);
1662
+ }
1663
+ this.pendingCommits.set(request.authorization_id, {
1664
+ digest: jcsDigest(request),
1665
+ answer,
1666
+ });
1667
+ }
1668
+ /** The intent's idempotency key names the authorization; one too long for the key is named by its digest. */
1669
+ static commitIdempotencyKey(authorizationId) {
1670
+ const key = `card-authorization:${authorizationId}`;
1671
+ if (key.length <= 180)
1672
+ return key;
1673
+ return `card-authorization:sha256:${createHash("sha256").update(authorizationId, "utf8").digest("hex")}`;
1674
+ }
1302
1675
  /**
1303
1676
  * What the issuer did with an authorization it was told to approve. An
1304
1677
  * approval is the effect, compared with what the grant authorised; a
@@ -1311,12 +1684,21 @@ export class TrustedExecutorService {
1311
1684
  if (!isCardReference(authorizationId))
1312
1685
  throw new ServiceError(400, "REQUEST_INVALID");
1313
1686
  const result = TrustedExecutorService.cardRequest(() => cardAuthorizationResultOf(input));
1314
- const claim = this.cards.claimed(authorizationId);
1687
+ let claim;
1688
+ try {
1689
+ claim = await this.cards.claimed(authorizationId);
1690
+ }
1691
+ catch (error) {
1692
+ if (error instanceof CardHoldStoreError)
1693
+ throw new ServiceError(503, error.code);
1694
+ throw new ServiceError(503, "CARD_HOLDS_UNAVAILABLE");
1695
+ }
1315
1696
  if (claim === undefined)
1316
1697
  throw new ServiceError(404, "CARD_AUTHORIZATION_UNKNOWN");
1317
- if (claim.settled)
1698
+ // Settled once, by the one rule every replica shares.
1699
+ if (claim.settled || !(await this.cards.settle(authorizationId))) {
1318
1700
  throw new ServiceError(409, "CARD_RESULT_ALREADY_RECORDED");
1319
- claim.settled = true;
1701
+ }
1320
1702
  const { grant, authorization } = claim;
1321
1703
  const { captured } = grant.held;
1322
1704
  const leaseExpired = Date.now() > claim.leaseExpiresAtMs;
@@ -1401,6 +1783,23 @@ export class TrustedExecutorService {
1401
1783
  throw new ServiceError(code === "CARD_PAN_REFUSED" ? 422 : 400, code);
1402
1784
  }
1403
1785
  }
1786
+ /**
1787
+ * Whether a re-presented authorization is an increment of the claim it
1788
+ * names: the same card, currency, merchant and category, for more than
1789
+ * before and no more than the grant's ceiling, while the claim is still
1790
+ * open and inside its lease.
1791
+ */
1792
+ static incrementOf(previous, request) {
1793
+ const before = previous.request;
1794
+ return (!previous.settled &&
1795
+ Date.now() <= previous.leaseExpiresAtMs &&
1796
+ request.card_token_ref === before.card_token_ref &&
1797
+ request.currency === before.currency &&
1798
+ request.merchant_id === before.merchant_id &&
1799
+ (request.mcc ?? null) === (before.mcc ?? null) &&
1800
+ request.amount_minor > before.amount_minor &&
1801
+ request.amount_minor <= previous.grant.amountMinor);
1802
+ }
1404
1803
  static cardView(request) {
1405
1804
  return {
1406
1805
  cardTokenRef: request.card_token_ref,