@devlab.group/agent-commerce 2.4.1 → 2.6.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 (126) hide show
  1. package/README.md +168 -16
  2. package/dist/ap2.d.ts +42 -17
  3. package/dist/ap2.js +83 -27
  4. package/dist/ap2.js.map +1 -1
  5. package/dist/{chunk-CXWC5LWM.js → chunk-DRLBML7Z.js} +661 -75
  6. package/dist/chunk-DRLBML7Z.js.map +1 -0
  7. package/dist/{chunk-WZW5ORZH.js → chunk-G3EYYHKF.js} +3 -3
  8. package/dist/{chunk-WZW5ORZH.js.map → chunk-G3EYYHKF.js.map} +1 -1
  9. package/dist/chunk-GA3O2A7R.js +92 -0
  10. package/dist/chunk-GA3O2A7R.js.map +1 -0
  11. package/dist/{chunk-DTKU3Z2M.js → chunk-M52FBNJX.js} +36 -5
  12. package/dist/chunk-M52FBNJX.js.map +1 -0
  13. package/dist/chunk-M6BSXXTF.js +8 -0
  14. package/dist/chunk-M6BSXXTF.js.map +1 -0
  15. package/dist/{chunk-QPV3EGJO.js → chunk-M6MQ3FYS.js} +25 -4
  16. package/dist/chunk-M6MQ3FYS.js.map +1 -0
  17. package/dist/chunk-M6WW6QIT.js +18 -0
  18. package/dist/chunk-M6WW6QIT.js.map +1 -0
  19. package/dist/cli/{ap2-GWSP4LYY.js → ap2-2YMYA2H6.js} +85 -29
  20. package/dist/cli/ap2-2YMYA2H6.js.map +1 -0
  21. package/dist/cli/{chunk-OZ4LAWBK.js → chunk-3NOMLMJW.js} +29 -8
  22. package/dist/cli/chunk-3NOMLMJW.js.map +1 -0
  23. package/dist/cli/chunk-4KLYFXMW.js +8 -0
  24. package/dist/cli/{chunk-ITWNSS2B.js.map → chunk-4KLYFXMW.js.map} +1 -1
  25. package/dist/cli/chunk-663ALDZA.js +92 -0
  26. package/dist/cli/chunk-663ALDZA.js.map +1 -0
  27. package/dist/cli/chunk-6R6WJ4FD.js +18 -0
  28. package/dist/cli/chunk-6R6WJ4FD.js.map +1 -0
  29. package/dist/cli/{chunk-G2JEY7MB.js → chunk-AZL7RPFU.js} +39 -33
  30. package/dist/cli/chunk-AZL7RPFU.js.map +1 -0
  31. package/dist/cli/chunk-DHFMIBPG.js +107 -0
  32. package/dist/cli/chunk-DHFMIBPG.js.map +1 -0
  33. package/dist/cli/{chunk-QQ3WY5L3.js → chunk-GET3CZGR.js} +36 -104
  34. package/dist/cli/chunk-GET3CZGR.js.map +1 -0
  35. package/dist/cli/chunk-NSYSMDQN.js +1544 -0
  36. package/dist/cli/chunk-NSYSMDQN.js.map +1 -0
  37. package/dist/cli/{chunk-PIMFPCNZ.js → chunk-PTL7SNOI.js} +313 -138
  38. package/dist/cli/chunk-PTL7SNOI.js.map +1 -0
  39. package/dist/cli/chunk-SYQLJXIU.js +105 -0
  40. package/dist/cli/chunk-SYQLJXIU.js.map +1 -0
  41. package/dist/cli/chunk-TFV3K6YS.js +373 -0
  42. package/dist/cli/chunk-TFV3K6YS.js.map +1 -0
  43. package/dist/cli/{chunk-3MGAJ5FX.js → chunk-VJ4EO4LE.js} +3 -3
  44. package/dist/cli/{chunk-3MGAJ5FX.js.map → chunk-VJ4EO4LE.js.map} +1 -1
  45. package/dist/cli/chunk-VJH6RYRK.js +119 -0
  46. package/dist/cli/chunk-VJH6RYRK.js.map +1 -0
  47. package/dist/cli/{chunk-TNMLDPUO.js → chunk-YOF7IK4V.js} +663 -77
  48. package/dist/cli/chunk-YOF7IK4V.js.map +1 -0
  49. package/dist/cli/{chunk-WYOGIANL.js → chunk-YWG2ZN3L.js} +4 -4
  50. package/dist/cli/{chunk-WYOGIANL.js.map → chunk-YWG2ZN3L.js.map} +1 -1
  51. package/dist/cli/config-3K65QJ22.js +12 -0
  52. package/dist/cli/{config-UI4EDG4L.js.map → config-3K65QJ22.js.map} +1 -1
  53. package/dist/cli/index.js +753 -212
  54. package/dist/cli/index.js.map +1 -1
  55. package/dist/cli/{mcp-PGBRWZVA.js → mcp-6F64A7KE.js} +5 -4
  56. package/dist/cli/mcp-6F64A7KE.js.map +1 -0
  57. package/dist/cli/{near-5AY3HWYF.js → near-U6365VFX.js} +15 -4
  58. package/dist/cli/near-U6365VFX.js.map +1 -0
  59. package/dist/cli/payment-providers-2ITS6KNR.js +6 -0
  60. package/dist/cli/payment-providers-2ITS6KNR.js.map +1 -0
  61. package/dist/cli/{provider-I2ESL6RS.js → provider-5BGG5YKQ.js} +53 -24
  62. package/dist/cli/provider-5BGG5YKQ.js.map +1 -0
  63. package/dist/cli/receipts-I4IIE7U6.js +8 -0
  64. package/dist/cli/receipts-I4IIE7U6.js.map +1 -0
  65. package/dist/cli/reconcile-55WNCSFC.js +4 -0
  66. package/dist/cli/reconcile-55WNCSFC.js.map +1 -0
  67. package/dist/cli/{run-JK4ERPJV.js → run-2P6ZGFUE.js} +356 -173
  68. package/dist/cli/run-2P6ZGFUE.js.map +1 -0
  69. package/dist/cli/svm-KDSPDFJG.js +48 -0
  70. package/dist/cli/svm-KDSPDFJG.js.map +1 -0
  71. package/dist/cli/{x402-7WBFZQXV.js → x402-4LPIIELI.js} +10 -9
  72. package/dist/cli/x402-4LPIIELI.js.map +1 -0
  73. package/dist/index.d.ts +116 -113
  74. package/dist/index.js +1928 -351
  75. package/dist/index.js.map +1 -1
  76. package/dist/logger-CllGwQ8i.d.ts +19 -0
  77. package/dist/mcp.d.ts +3 -2
  78. package/dist/mcp.js +2 -1
  79. package/dist/mcp.js.map +1 -1
  80. package/dist/mpp.d.ts +2 -1
  81. package/dist/mpp.js +48 -19
  82. package/dist/mpp.js.map +1 -1
  83. package/dist/{near-D6C42VPE.js → near-FH7HPZV3.js} +15 -4
  84. package/dist/near-FH7HPZV3.js.map +1 -0
  85. package/dist/{protocol-adapter-C9odYl6l.d.ts → protocol-adapter-1WbtM3xG.d.ts} +12 -85
  86. package/dist/{runtime-Cl_BLVZV.d.ts → runtime-B-kARa2f.d.ts} +218 -15
  87. package/dist/store-kIIMpUA-.d.ts +372 -0
  88. package/dist/svm-KNC3PHMS.js +48 -0
  89. package/dist/svm-KNC3PHMS.js.map +1 -0
  90. package/dist/testing.d.ts +51 -0
  91. package/dist/testing.js +1896 -0
  92. package/dist/testing.js.map +1 -0
  93. package/dist/transaction-Dv0UFGg5.d.ts +129 -0
  94. package/dist/{types-j7MnUXYN.d.ts → types-DWqjz81-.d.ts} +5 -2
  95. package/dist/x402.d.ts +2 -1
  96. package/dist/x402.js +6 -5
  97. package/dist/x402.js.map +1 -1
  98. package/package.json +5 -1
  99. package/dist/authorization-DjAecwuW.d.ts +0 -115
  100. package/dist/chunk-CXWC5LWM.js.map +0 -1
  101. package/dist/chunk-DTKU3Z2M.js.map +0 -1
  102. package/dist/chunk-KA2AX5FH.js +0 -44
  103. package/dist/chunk-KA2AX5FH.js.map +0 -1
  104. package/dist/chunk-QPV3EGJO.js.map +0 -1
  105. package/dist/cli/ap2-GWSP4LYY.js.map +0 -1
  106. package/dist/cli/chunk-G2JEY7MB.js.map +0 -1
  107. package/dist/cli/chunk-GJIMDMYT.js +0 -639
  108. package/dist/cli/chunk-GJIMDMYT.js.map +0 -1
  109. package/dist/cli/chunk-ITWNSS2B.js +0 -8
  110. package/dist/cli/chunk-OSTCU6ZK.js +0 -44
  111. package/dist/cli/chunk-OSTCU6ZK.js.map +0 -1
  112. package/dist/cli/chunk-OZ4LAWBK.js.map +0 -1
  113. package/dist/cli/chunk-PIMFPCNZ.js.map +0 -1
  114. package/dist/cli/chunk-QQ3WY5L3.js.map +0 -1
  115. package/dist/cli/chunk-TNMLDPUO.js.map +0 -1
  116. package/dist/cli/config-UI4EDG4L.js +0 -11
  117. package/dist/cli/mcp-PGBRWZVA.js.map +0 -1
  118. package/dist/cli/near-5AY3HWYF.js.map +0 -1
  119. package/dist/cli/provider-I2ESL6RS.js.map +0 -1
  120. package/dist/cli/run-JK4ERPJV.js.map +0 -1
  121. package/dist/cli/svm-3MMYFPC7.js +0 -33
  122. package/dist/cli/svm-3MMYFPC7.js.map +0 -1
  123. package/dist/cli/x402-7WBFZQXV.js.map +0 -1
  124. package/dist/near-D6C42VPE.js.map +0 -1
  125. package/dist/svm-QEUAUNPQ.js +0 -33
  126. package/dist/svm-QEUAUNPQ.js.map +0 -1
package/README.md CHANGED
@@ -70,8 +70,8 @@ agent-commerce doctor
70
70
  ```
71
71
 
72
72
  Requires **Node >= 22**. The package includes the `agent-commerce` CLI
73
- (`init`, `validate`, `start`, `doctor`, `demo`, `import openapi`, `version`) and
74
- a library for embedding the gateway.
73
+ (`init`, `validate`, `start`, `doctor`, `reconcile`, `resolve`, `demo`,
74
+ `import openapi`, `version`) and a library for embedding the gateway.
75
75
  The default install excludes optional protocol, payment and authorization
76
76
  peers. The OpenAPI parser is a regular dependency because import is part of the
77
77
  CLI.
@@ -84,9 +84,10 @@ agent-commerce start --config config.yaml --env-file .env
84
84
  Install the optional peers for the features you enable, listed below. Missing
85
85
  startup imports stop the gateway with an error naming the package; missing
86
86
  Solana, NEAR or CDP peers fail provider health checks or payment requests.
87
- `start`, `validate` and `doctor` accept `--env-file <path>` to load environment
88
- variables before reading the config. Variables already set in the environment
89
- take precedence. To embed the gateway in your own process, use the library:
87
+ `start`, `validate`, `doctor`, `reconcile` and `resolve` accept `--env-file <path>` to
88
+ load environment variables before reading the config. Variables already set in
89
+ the environment take precedence. To embed the gateway in your own process, use
90
+ the library:
90
91
 
91
92
  ```ts
92
93
  import { createGateway, loadConfig, receipts } from '@devlab.group/agent-commerce';
@@ -147,6 +148,34 @@ missing package.
147
148
  `facilitator.auth.type: cdp` and brings the larger CDP dependency tree. A
148
149
  facilitator with a static token can use `auth.type: bearer` without it.
149
150
 
151
+ ### Testing a custom store
152
+
153
+ `createGateway` accepts a custom `ReceiptStore`. The experimental `./testing`
154
+ entry exports conformance cases to test it. The cases use `node:assert/strict`
155
+ and import no test runner or optional peers, so you can wrap them with your
156
+ runner:
157
+
158
+ ```ts
159
+ import { receiptStoreConformanceCases } from '@devlab.group/agent-commerce/testing';
160
+ import { it } from 'vitest';
161
+
162
+ const cases = await receiptStoreConformanceCases(({ clock }) => ({
163
+ store: createMyStore({ clock }),
164
+ }));
165
+ for (const c of cases) it.skipIf(c.skip !== undefined)(c.name, () => c.run());
166
+ ```
167
+
168
+ Have the factory return a new, empty store for each case. The suite calls
169
+ `init()` and `close()`. Pass the supplied `clock` to the store so expiry cases
170
+ can advance time without waiting.
171
+
172
+ Each optional method group, such as authorization holds, must be implemented
173
+ in full or omitted; one case checks this. Cases that need missing methods are
174
+ marked to skip. Durability cases also skip unless the factory returns `reopen()`,
175
+ which must close the current store and open another over the same data.
176
+ Concurrency cases submit competing reservations, resolutions, idempotency
177
+ claims and pending-task takes, then check that exactly one caller wins.
178
+
150
179
  ## Integrate with an AI coding agent
151
180
 
152
181
  The repository includes an experimental [Agent Skills](https://agentskills.io)
@@ -309,12 +338,20 @@ prints the `unsupported` lists for A2A, ACP and AP2 when they are enabled.
309
338
 
310
339
  ### Versioning
311
340
 
312
- Minor releases may break experimental configurations, integrations or types.
313
- This applies to MPP, A2A, ACP, AP2, ERC-8409 quotes and
314
- `agent-commerce import openapi`.
315
- Runtime adapters and providers report `status: experimental` in
316
- `GET /.well-known/agent-commerce`. Pin an exact version and test upgrades
317
- before deploying them. Since 2.1, some supported x402 behavior and types
341
+ Minor releases may break experimental configurations, integrations or types:
342
+ MPP, A2A, ACP, AP2, ERC-8409 quotes, `agent-commerce import openapi`,
343
+ `PaymentProvider.reconcile`, the `ReceiptStore` methods and types added in
344
+ 2.6.0, and the `./testing` entry.
345
+
346
+ The journal's `Transaction` type, `ReceiptStore` journal methods and
347
+ `/api/transactions` response shape are supported. The `transactionId` fields,
348
+ `receiptCommitted` and flags accepted by `reconcile` and `resolve` are also
349
+ supported.
350
+
351
+ Experimental runtime adapters and providers identify themselves with
352
+ `status: experimental` in `GET /.well-known/agent-commerce`. Pin experimental
353
+ integrations to an exact version and test upgrades before deployment.
354
+ Since 2.1, some supported x402 behavior and types
318
355
  differ from 2.0; see [Upgrading from 2.0 to 2.x](docs/migration-2.1.md).
319
356
 
320
357
  ## Payment model
@@ -461,10 +498,11 @@ INFO ACP disabled
461
498
  INFO AP2 disabled
462
499
  PASS Payments x402 v2 (scheme=exact) enabled - LOCAL dev chain (eip155:31337), destination=0x7099…79C8, facilitator=local (in-process), paymentFlow=authorization
463
500
  INFO Payments (MPP) MPP not configured
464
- PASS Storage sqlite schema v3 writable; receipts=2
501
+ PASS Storage sqlite schema v5 writable; receipts=2
502
+ PASS Transactions none unresolved
465
503
  PASS Protocol versions reported by gateway /.well-known/agent-commerce
466
504
 
467
- Score: 7/7 checks passed
505
+ Score: 8/8 checks passed
468
506
  ```
469
507
 
470
508
  `doctor` compares live settlement terms with local config for each rail and
@@ -474,6 +512,117 @@ failing offers when health is published; reasons appear in gateway debug logs.
474
512
 
475
513
  Exits non-zero if anything fails. `--json` for machines.
476
514
 
515
+ ### `agent-commerce reconcile`
516
+
517
+ ```bash
518
+ npm run agent-commerce -- reconcile --config config.yaml --dry-run
519
+ ```
520
+
521
+ Resolves attempts whose settlement outcome the gateway did not learn:
522
+ `settlement-uncertain` and legacy `failed` attempts, plus `reserved` attempts in
523
+ the journal at least `--min-age` old (default `15m`). The payment provider
524
+ checks chain evidence and returns:
525
+
526
+ - **settled**: a final transfer matches the authorization. The attempt becomes
527
+ `settled` with its transaction ID.
528
+ - **not settled**: final chain state shows the authorization unused after its
529
+ last valid second on EVM or its `maxBlockHeight` on NEAR. The attempt becomes
530
+ `rejected` with reason `not_settled`. Solana reconciliation does not return
531
+ this result: blockhash expiry alone does not prove nonpayment.
532
+ - **unknown**: the evidence is inconclusive. The report includes a reason and,
533
+ when available, a time to try again. The attempt remains unresolved.
534
+
535
+ The command builds payment providers as `start` does without starting a
536
+ listener. It does not call a facilitator, broadcast, refund or retry delivery.
537
+ Each resolution records `--actor` (default: the OS user) and the evidence.
538
+ `--dry-run` checks evidence without recording resolutions; it still opens and
539
+ initializes the receipt database. `--json` prints the report for machines.
540
+ `--limit` caps payment checks and hold updates separately. Journal entries are
541
+ checked by state: `payment-uncertain`, `payment-pending`, then
542
+ `delivery-started`, newest first within each group. Only eligible payment
543
+ attempts are considered. A capped batch of attempts without journal entries
544
+ follows.
545
+ It exits 0 after a completed run, even if attempts remain unresolved, and 1 if
546
+ the run fails to complete. If a store error stops a hold scan, the command
547
+ prints the report, preserving any saved resolutions, and exits 1.
548
+ `reconcile` and `resolve` refuse receipt databases below schema v5 without
549
+ migrating them. Back up the database, then start the gateway once before
550
+ retrying either command.
551
+
552
+ Each family needs its own evidence:
553
+
554
+ - **EVM**: uses the recorded transaction hash or searches logs for a used nonce
555
+ near the attempt's creation time, within its validity bounds. The log search
556
+ covers at most 200,000 blocks. If no match is found and part of the candidate
557
+ range remains unsearched, it returns `unknown` (`search_window_too_wide`).
558
+ - **Solana**: uses the recorded transaction signature or searches a known
559
+ payer's history near the attempt's creation time. Only successful finalized
560
+ transactions count. A search that reaches its page cap returns `unknown`
561
+ (`history_too_long`). Otherwise, a missing match gives `not_expired` while
562
+ the blockhash is valid at `confirmed` commitment, then `blockhash_expired`.
563
+ - **NEAR**: uses the recorded transaction hash and relayer IDs from the
564
+ facilitator's `/supported`. Both are needed to prove `settled`. Without
565
+ them, final access-key state can still prove `not-settled` after expiry;
566
+ other cases remain `unknown`.
567
+
568
+ Coverage is partial: EVM reconciliation (x402 EIP-3009 and Permit2, and MPP)
569
+ is tested on Anvil, Solana on `solana-test-validator` and NEAR on a local
570
+ sandbox. Public-network validation is pending. EVM and NEAR can report
571
+ `not_final` while a referenced transaction awaits finality.
572
+
573
+ With `authorization.ap2` enabled, reconciliation also updates AP2 holds on
574
+ resolved payments: `settled` consumes the mandate; `rejected` releases it.
575
+ It updates holds in the receipt database without verifying mandates.
576
+ The report's `holds` list (`--json`) covers pending holds whose payments are
577
+ resolved in the database. It also attempts to release `reserved` holds older
578
+ than `--min-age` whose request has no current or archived payment attempt.
579
+ The pipeline reserves an attempt before calling settlement. Scanned orphan
580
+ holds appear in `orphanHolds`; dry runs list at most one page of them.
581
+ Dry runs write no resolutions or hold changes, but still open and initialize
582
+ the database.
583
+ Later runs can retry holds left pending after earlier payment resolutions,
584
+ including those recorded by `resolve` while AP2 was disabled.
585
+
586
+ ### `agent-commerce resolve`
587
+
588
+ ```bash
589
+ npm run agent-commerce -- resolve <attemptId> --status settled --reason "transfer seen in explorer" --reference 0x...
590
+ ```
591
+
592
+ Records an operator's verdict on one unresolved payment attempt, including
593
+ one `reconcile` left `unknown`. Only `reserved`, `settlement-uncertain` and
594
+ legacy `failed` attempts can be resolved, once each:
595
+
596
+ - `--status settled` has no expiry check. `--reference` records an unchecked
597
+ operator claim in the resolution; it does not replace the attempt's recorded
598
+ transaction ID.
599
+ - A `reserved` attempt younger than 15 minutes is refused (`too_recent`),
600
+ because the gateway may still be settling it.
601
+ - `--status rejected` is refused while the recorded expiry is in the future.
602
+ Without a valid recorded expiry, `--confirm-expired` is required. This
603
+ includes Solana and NEAR attempts and those written before the journal.
604
+
605
+ `--actor` is a caller-supplied label and defaults to the OS user. The command
606
+ opens the receipt database directly and works with the gateway running or
607
+ stopped. With AP2 enabled, it attempts the same hold update as `reconcile`.
608
+ If the provider is disabled, its call fails, or the hold's journal write fails,
609
+ the command reports the update as pending with a warning. A later `reconcile`
610
+ run can retry it.
611
+ `POST /api/payment-attempts/:id/resolve` applies the same rules over HTTP;
612
+ the admin token controls access without identifying the operator. Exit 0
613
+ means the resolution was written; 1 means a refusal or error.
614
+
615
+ ### `agent-commerce backup`
616
+
617
+ ```bash
618
+ npm run agent-commerce -- backup --out ./backups/2026-11-01
619
+ ```
620
+
621
+ Copies the receipt database into a new or empty directory with a `backup.json`
622
+ manifest. It also copies existing, unimported legacy files configured for enabled
623
+ AP2 or ACP. It can run alongside a live gateway. See [Storage](docs/storage.md)
624
+ for restore and shutdown instructions.
625
+
477
626
  ### `agent-commerce version`
478
627
 
479
628
  ```bash
@@ -493,9 +642,11 @@ reachable by anyone else, know the split:
493
642
  - **Agent routes** (`/api/resources/:id/invoke`, `/mcp`, the A2A mount) are
494
643
  unauthenticated by design - paid resources are protected by payment, not by a
495
644
  password. ACP is the exception: its checkout routes require a bearer token.
496
- - **Operator routes** (`/api/receipts`, `/api/events`, `/api/payment-attempts`)
497
- expose the merchant's commerce ledger: payer addresses, amounts and settlement
498
- hashes. They require `server.adminToken` and return **404** if none is configured.
645
+ - **Operator routes** (`/api/receipts`, `/api/events`, `/api/payment-attempts`,
646
+ `/api/transactions`) expose the merchant's commerce ledger: payer addresses,
647
+ amounts and settlement hashes. `POST /api/payment-attempts/:id/resolve`
648
+ records a resolution. They require `server.adminToken` and return **404** if
649
+ none is configured.
499
650
  - **Browsers** are governed by `server.allowedOrigins`, an explicit allowlist
500
651
  that defaults to empty.
501
652
  - **There is no rate limiting.** A free resource is an unauthenticated proxy to
@@ -539,6 +690,7 @@ they are added to a release.
539
690
  | [Protocols](docs/protocols.md) | supported and unsupported protocol features |
540
691
  | [AP2](docs/protocols/ap2.md) | mandate verification and the trust model |
541
692
  | [Configuration](docs/configuration.md) | `config.yaml` reference |
693
+ | [Storage](docs/storage.md) | upgrade, backup, restore and shutdown |
542
694
  | [Upgrading from 2.0](docs/migration-2.1.md) | changes that can break a 2.0 setup |
543
695
  | [Smoke tests](docs/smoke-tests.md) | settling on public networks, by hand |
544
696
  | [OpenAPI import](docs/openapi-import.md) | generate resources from an existing API |
package/dist/ap2.d.ts CHANGED
@@ -1,7 +1,9 @@
1
- import { E as EnabledAp2Config } from './types-j7MnUXYN.js';
2
- export { A as AP2_CHECKOUT_MANDATE_VCT, a as AP2_CHECKOUT_PROFILE, b as AP2_DEFAULT_CLOCK_SKEW_SECONDS, c as AP2_MAX_CLOCK_SKEW_SECONDS, d as AP2_SIGNING_ALGORITHM, e as AP2_SPEC_VERSION, f as Ap2AuthorizationConfig, g as Ap2Mode, h as Ap2TrustedIssuer, i as Ap2TrustedKey } from './types-j7MnUXYN.js';
3
- import { AuthorizationProvider } from './index.js';
4
- import { Clock, Logger } from './index.js';
1
+ import { E as EnabledAp2Config } from './types-DWqjz81-.js';
2
+ export { A as AP2_CHECKOUT_MANDATE_VCT, a as AP2_CHECKOUT_PROFILE, b as AP2_DEFAULT_CLOCK_SKEW_SECONDS, c as AP2_MAX_CLOCK_SKEW_SECONDS, d as AP2_SIGNING_ALGORITHM, e as AP2_SPEC_VERSION, f as Ap2AuthorizationConfig, g as Ap2Mode, h as Ap2TrustedIssuer, i as Ap2TrustedKey } from './types-DWqjz81-.js';
3
+ import { AuthorizationProvider, Clock } from './index.js';
4
+ import { Logger } from './index.js';
5
+ import { ReceiptStore } from './index.js';
6
+ import './transaction-Dv0UFGg5.js';
5
7
 
6
8
  /**
7
9
  * A private ES256 key: either a private JWK (the pair of the public one in the
@@ -92,9 +94,9 @@ declare const AP2_REJECTION_REASONS: readonly ["malformed_presentation", "untrus
92
94
  type Ap2RejectionReason = (typeof AP2_REJECTION_REASONS)[number];
93
95
 
94
96
  /**
95
- * `released` is "nothing happened" and the only state a mandate can be
96
- * presented from again. `uncertain` is a settlement whose outcome we never
97
- * learned: not reusable, but findable by an operator reconciling by hand.
97
+ * `released` permits another reservation; other states block reuse.
98
+ * `uncertain` records an unknown settlement outcome and stays blocked until
99
+ * payment resolution is followed by a consume or release update.
98
100
  */
99
101
  type Ap2AuthorizationState = 'reserved' | 'consumed' | 'released' | 'uncertain';
100
102
  /**
@@ -118,20 +120,33 @@ interface Ap2ReservationRequest {
118
120
  type Ap2ReservationResult = {
119
121
  readonly kind: 'reserved';
120
122
  }
121
- /** Already reserved, consumed, or of uncertain outcome. Never re-spendable */
123
+ /** Already reserved, consumed or uncertain; refuse this reservation */
122
124
  | {
123
125
  readonly kind: 'replayed';
124
126
  readonly state: Ap2AuthorizationState;
125
127
  };
128
+ type TransitionResult = boolean | void;
126
129
  interface Ap2ReplayStore {
127
130
  /** Atomically claim a mandate, or report that something already holds it */
128
131
  reserve(request: Ap2ReservationRequest): Ap2ReservationResult;
129
- /** Settlement succeeded: spend it permanently */
130
- consume(reference: string): void;
131
- /** Nothing happened: hand it back so a corrected retry can use it */
132
- release(reference: string): void;
133
- /** Settlement outcome unknown. Not reusable, and flagged for a human */
134
- markUncertain(reference: string): void;
132
+ /**
133
+ * Mark the mandate permanently spent, targeting only the supplied
134
+ * `requestId` when present. Returns true when the matching reservation is
135
+ * consumed, including on a repeated call, and false otherwise.
136
+ */
137
+ consume(reference: string, requestId?: string): TransitionResult;
138
+ /**
139
+ * Release a reservation for reuse. Returns true if it is released or the
140
+ * supplied `requestId` differs from the current holder; a different holder
141
+ * is left unchanged. Returns false otherwise.
142
+ */
143
+ release(reference: string, requestId?: string): TransitionResult;
144
+ /**
145
+ * Record an unknown settlement outcome for operator review and block reuse.
146
+ * Returns true when the matching reservation is uncertain, including on a
147
+ * repeated call, and false otherwise.
148
+ */
149
+ markUncertain(reference: string, requestId?: string): TransitionResult;
135
150
  /** Current state, for tests and diagnostics */
136
151
  stateOf(reference: string): Ap2AuthorizationState | undefined;
137
152
  close(): void;
@@ -141,7 +156,9 @@ interface Ap2ReplayStore {
141
156
  * The AP2 authorization provider: the seam between core's generic contract and
142
157
  * the mandate machinery.
143
158
  *
144
- * It owns its replay store, so whoever creates it must call `close()`:
159
+ * Choose the first available backend: `replayStore`, a receipt store with all
160
+ * hold methods, or the deprecated replay file. Creators must call `close()`:
161
+ * it closes the legacy replay backend but leaves the receipt store open.
145
162
  * `createGateway` does not close authorization providers.
146
163
  */
147
164
 
@@ -149,11 +166,19 @@ interface Ap2AuthorizationProviderOptions {
149
166
  readonly config: EnabledAp2Config;
150
167
  readonly clock?: Clock;
151
168
  readonly logger?: Logger;
152
- /** Injectable so tests need not touch the filesystem */
169
+ /**
170
+ * Holds mandates when all authorization-hold methods are present and no
171
+ * `replayStore` is supplied. `close()` leaves this shared store open.
172
+ */
173
+ readonly store?: ReceiptStore;
174
+ /**
175
+ * Takes precedence over `store`, and `close()` closes it.
176
+ * @deprecated Pass `store`; 3.0.0 removes this option.
177
+ */
153
178
  readonly replayStore?: Ap2ReplayStore;
154
179
  }
155
180
  interface Ap2AuthorizationProvider extends AuthorizationProvider {
156
- /** Closes the replay store */
181
+ /** Close the legacy replay store opened or supplied; leave the receipt store open */
157
182
  close(): void;
158
183
  }
159
184
  declare function createAp2AuthorizationProvider(options: Ap2AuthorizationProviderOptions): Ap2AuthorizationProvider;
package/dist/ap2.js CHANGED
@@ -1,6 +1,8 @@
1
- import { AP2_CHECKOUT_MANDATE_VCT, AP2_SIGNING_ALGORITHM, AP2_DIGEST_ALGORITHM, AP2_CHECKOUT_PROFILE, AP2_SPEC_VERSION, AP2_KEY_TYPE, AP2_JWK_CURVE, openSqliteDatabase } from './chunk-WZW5ORZH.js';
2
- export { AP2_CHECKOUT_MANDATE_VCT, AP2_CHECKOUT_PROFILE, AP2_DEFAULT_CLOCK_SKEW_SECONDS, AP2_MAX_CLOCK_SKEW_SECONDS, AP2_SIGNING_ALGORITHM, AP2_SPEC_VERSION } from './chunk-WZW5ORZH.js';
3
- import { systemClock, NOOP_LOGGER, CommerceError, PACKAGE_VERSION } from './chunk-DTKU3Z2M.js';
1
+ import { AP2_CHECKOUT_MANDATE_VCT, AP2_SIGNING_ALGORITHM, AP2_DIGEST_ALGORITHM, AP2_CHECKOUT_PROFILE, AP2_SPEC_VERSION, AP2_KEY_TYPE, AP2_JWK_CURVE, openSqliteDatabase } from './chunk-G3EYYHKF.js';
2
+ export { AP2_CHECKOUT_MANDATE_VCT, AP2_CHECKOUT_PROFILE, AP2_DEFAULT_CLOCK_SKEW_SECONDS, AP2_MAX_CLOCK_SKEW_SECONDS, AP2_SIGNING_ALGORITHM, AP2_SPEC_VERSION } from './chunk-G3EYYHKF.js';
3
+ import { PACKAGE_VERSION } from './chunk-M6BSXXTF.js';
4
+ import { hasMethodGroup } from './chunk-M6WW6QIT.js';
5
+ import { systemClock, NOOP_LOGGER, CommerceError } from './chunk-M52FBNJX.js';
4
6
  import { isRecord } from './chunk-2CJNA7MS.js';
5
7
  import { SignJWT, importPKCS8, importJWK, jwtVerify, decodeProtectedHeader, decodeJwt } from 'jose';
6
8
  import canonicalize from 'canonicalize';
@@ -276,7 +278,11 @@ function createAp2ReplayStore(options) {
276
278
  );
277
279
  const transition = db.prepare(
278
280
  `UPDATE ap2_authorizations SET state = @state, updated_at = @at
279
- WHERE reference = @reference AND state = 'reserved'`
281
+ WHERE reference = @reference AND state IN ('reserved', 'uncertain')
282
+ AND (@request_id IS NULL OR request_id = @request_id)`
283
+ );
284
+ const selectHolder = db.prepare(
285
+ "SELECT state, request_id FROM ap2_authorizations WHERE reference = ?"
280
286
  );
281
287
  const reserveTx = db.transaction((request) => {
282
288
  const at = new Date(now()).toISOString();
@@ -303,22 +309,32 @@ function createAp2ReplayStore(options) {
303
309
  });
304
310
  return { kind: "reserved" };
305
311
  });
306
- const move = (reference, state) => {
307
- transition.run({ reference, state, at: new Date(now()).toISOString() });
312
+ const move = (reference, state, requestId) => {
313
+ const { changes } = transition.run({
314
+ reference,
315
+ state,
316
+ request_id: requestId ?? null,
317
+ at: new Date(now()).toISOString()
318
+ });
319
+ if (changes > 0) return true;
320
+ const row = selectHolder.get(reference);
321
+ if (row === void 0) return false;
322
+ if (requestId !== void 0 && row.request_id !== requestId) return state === "released";
323
+ return row.state === state;
308
324
  };
309
325
  let closed = false;
310
326
  return {
311
327
  reserve(request) {
312
328
  return reserveTx(request);
313
329
  },
314
- consume(reference) {
315
- move(reference, "consumed");
330
+ consume(reference, requestId) {
331
+ return move(reference, "consumed", requestId);
316
332
  },
317
- release(reference) {
318
- move(reference, "released");
333
+ release(reference, requestId) {
334
+ return move(reference, "released", requestId);
319
335
  },
320
- markUncertain(reference) {
321
- move(reference, "uncertain");
336
+ markUncertain(reference, requestId) {
337
+ return move(reference, "uncertain", requestId);
322
338
  },
323
339
  stateOf(reference) {
324
340
  return selectByReference.get(reference)?.state;
@@ -618,11 +634,53 @@ function createAp2MandateVerifier(options) {
618
634
  }
619
635
 
620
636
  // src/authorization/ap2/provider.ts
637
+ var HOLD_STATES = {
638
+ consume: "consumed",
639
+ release: "released",
640
+ markUncertain: "uncertain"
641
+ };
642
+ function fileHolds(replay) {
643
+ return {
644
+ reserve: async (request) => replay.reserve(request),
645
+ transition: async (action, reference, requestId) => replay[action](reference, requestId),
646
+ stateOf: async (reference) => replay.stateOf(reference),
647
+ close: () => replay.close()
648
+ };
649
+ }
650
+ function storeHolds(store) {
651
+ return {
652
+ reserve: (request) => store.reserveAuthorizationHold({
653
+ method: "ap2",
654
+ reference: request.reference,
655
+ bindingReference: request.checkoutJti,
656
+ resourceId: request.resourceId,
657
+ requestId: request.requestId,
658
+ metadata: { mandateIssuer: request.mandateIssuer, checkoutIssuer: request.checkoutIssuer }
659
+ }),
660
+ transition: (action, reference, requestId) => store.transitionAuthorizationHold(reference, HOLD_STATES[action], requestId),
661
+ stateOf: (reference) => store.getAuthorizationHoldState(reference),
662
+ close: () => {
663
+ }
664
+ };
665
+ }
666
+ function openHolds(options, logger) {
667
+ if (options.replayStore !== void 0) return fileHolds(options.replayStore);
668
+ if (hasMethodGroup(options.store, "authorization_holds")) return storeHolds(options.store);
669
+ const path = options.config.replay?.path;
670
+ if (path === void 0) {
671
+ throw new CommerceError(
672
+ "CONFIG_INVALID",
673
+ "AP2 needs somewhere to record spent mandates: pass a receipt store with authorization holds, or set authorization.ap2.replay.path",
674
+ { details: { path: "authorization.ap2.replay.path" } }
675
+ );
676
+ }
677
+ return fileHolds(createAp2ReplayStore({ path, logger }));
678
+ }
621
679
  function createAp2AuthorizationProvider(options) {
622
680
  const clock = options.clock ?? systemClock;
623
681
  const logger = options.logger ?? NOOP_LOGGER;
624
682
  const verifier = createAp2MandateVerifier({ config: options.config, clock });
625
- const replay = options.replayStore ?? createAp2ReplayStore({ path: options.config.replay.path, logger });
683
+ const holds = openHolds(options, logger);
626
684
  const requirement = {
627
685
  method: "ap2",
628
686
  version: AP2_SPEC_VERSION,
@@ -637,7 +695,7 @@ function createAp2AuthorizationProvider(options) {
637
695
  await bindMandateToPurchase(mandate, context, errorContext);
638
696
  let reservation;
639
697
  try {
640
- reservation = replay.reserve({
698
+ reservation = await holds.reserve({
641
699
  reference: mandate.reference,
642
700
  checkoutJti: mandate.checkoutJwtId,
643
701
  mandateIssuer: mandate.mandateIssuer,
@@ -669,33 +727,31 @@ function createAp2AuthorizationProvider(options) {
669
727
  }
670
728
  };
671
729
  }
672
- const finalize = (action, reservationId, context) => {
730
+ const finalize = async (action, reservationId, context) => {
731
+ let applied;
673
732
  try {
674
- replay[action](reservationId);
733
+ applied = await holds.transition(action, reservationId, context.requestId);
675
734
  } catch (cause) {
676
735
  throw ap2Unavailable(`replay store could not record ${action}`, { ...context, cause });
677
736
  }
737
+ if (applied === false) {
738
+ throw ap2Unavailable(`replay store holds no matching reservation to ${action}`, context);
739
+ }
678
740
  };
679
741
  return {
680
742
  name: "ap2",
681
743
  descriptor: buildAp2Descriptor(PACKAGE_VERSION),
682
744
  requirement,
683
745
  verifyAndReserve,
684
- async consume(reservationId, context) {
685
- finalize("consume", reservationId, context);
686
- },
687
- async release(reservationId, context) {
688
- finalize("release", reservationId, context);
689
- },
690
- async markUncertain(reservationId, context) {
691
- finalize("markUncertain", reservationId, context);
692
- },
746
+ consume: (reservationId, context) => finalize("consume", reservationId, context),
747
+ release: (reservationId, context) => finalize("release", reservationId, context),
748
+ markUncertain: (reservationId, context) => finalize("markUncertain", reservationId, context),
693
749
  async health() {
694
750
  const startedAt = clock.monotonicMs();
695
751
  const checkedAt = clock.nowIso();
696
752
  let available = true;
697
753
  try {
698
- replay.stateOf("health-probe");
754
+ await holds.stateOf("health-probe");
699
755
  } catch {
700
756
  available = false;
701
757
  }
@@ -712,7 +768,7 @@ function createAp2AuthorizationProvider(options) {
712
768
  };
713
769
  },
714
770
  close() {
715
- replay.close();
771
+ holds.close();
716
772
  }
717
773
  };
718
774
  }