@devlab.group/agent-commerce 2.5.0 → 2.7.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.
- package/README.md +78 -21
- package/dist/ap2.d.ts +19 -6
- package/dist/ap2.js +56 -18
- package/dist/ap2.js.map +1 -1
- package/dist/{chunk-ES3V6ECS.js → chunk-77HLISG4.js} +3 -2
- package/dist/chunk-77HLISG4.js.map +1 -0
- package/dist/{chunk-5ZYXBCDX.js → chunk-D7FPSGUQ.js} +25 -4
- package/dist/chunk-D7FPSGUQ.js.map +1 -0
- package/dist/{chunk-VUCMBGUR.js → chunk-DJRWYDKJ.js} +3 -3
- package/dist/{chunk-VUCMBGUR.js.map → chunk-DJRWYDKJ.js.map} +1 -1
- package/dist/{chunk-4K7FIBJM.js → chunk-EMKITGVV.js} +4 -4
- package/dist/chunk-EMKITGVV.js.map +1 -0
- package/dist/chunk-IWXVQYG5.js +6 -0
- package/dist/chunk-IWXVQYG5.js.map +1 -0
- package/dist/chunk-O3ACF45K.js +8 -0
- package/dist/chunk-O3ACF45K.js.map +1 -0
- package/dist/chunk-WDD2ZUR3.js +20 -0
- package/dist/chunk-WDD2ZUR3.js.map +1 -0
- package/dist/{chunk-3OTCFFFT.js → chunk-YHNTTMED.js} +7 -7
- package/dist/chunk-YHNTTMED.js.map +1 -0
- package/dist/{chunk-FKQK5XZA.js → chunk-ZSIUZPNB.js} +183 -80
- package/dist/chunk-ZSIUZPNB.js.map +1 -0
- package/dist/cli/{ap2-YAPLERSC.js → ap2-5FFGSW6F.js} +61 -25
- package/dist/cli/ap2-5FFGSW6F.js.map +1 -0
- package/dist/cli/{chunk-5K4XEAZV.js → chunk-3IEXJ7I3.js} +25 -4
- package/dist/cli/chunk-3IEXJ7I3.js.map +1 -0
- package/dist/cli/{chunk-NIU5EMSB.js → chunk-3NVJAQRO.js} +5 -5
- package/dist/cli/{chunk-NIU5EMSB.js.map → chunk-3NVJAQRO.js.map} +1 -1
- package/dist/cli/{chunk-IDY2735M.js → chunk-55AI6CLW.js} +6 -4
- package/dist/cli/chunk-55AI6CLW.js.map +1 -0
- package/dist/cli/{chunk-QA2OPHBF.js → chunk-5K2JDM4G.js} +185 -83
- package/dist/cli/chunk-5K2JDM4G.js.map +1 -0
- package/dist/cli/{chunk-QLUCNPRT.js → chunk-5TID36YG.js} +860 -170
- package/dist/cli/chunk-5TID36YG.js.map +1 -0
- package/dist/cli/{chunk-5R7DM5LM.js → chunk-66NTYSXI.js} +27 -27
- package/dist/cli/chunk-66NTYSXI.js.map +1 -0
- package/dist/cli/{chunk-VJ4EO4LE.js → chunk-6EBDOH37.js} +3 -3
- package/dist/cli/{chunk-VJ4EO4LE.js.map → chunk-6EBDOH37.js.map} +1 -1
- package/dist/cli/{chunk-4H2QLHQI.js → chunk-AGQ4U7IN.js} +5 -5
- package/dist/cli/chunk-AGQ4U7IN.js.map +1 -0
- package/dist/cli/chunk-APC5BTQM.js +6 -0
- package/dist/cli/chunk-APC5BTQM.js.map +1 -0
- package/dist/cli/{chunk-SYQLJXIU.js → chunk-C5YISPT6.js} +3 -3
- package/dist/cli/chunk-C5YISPT6.js.map +1 -0
- package/dist/cli/chunk-DKWO6LLX.js +34 -0
- package/dist/cli/chunk-DKWO6LLX.js.map +1 -0
- package/dist/cli/{chunk-SPAYKVUP.js → chunk-FL4HPCD4.js} +3 -2
- package/dist/cli/chunk-FL4HPCD4.js.map +1 -0
- package/dist/cli/{chunk-3EQBCFZY.js → chunk-H7EBJ4I3.js} +3 -3
- package/dist/cli/{chunk-3EQBCFZY.js.map → chunk-H7EBJ4I3.js.map} +1 -1
- package/dist/cli/{chunk-Z34UMZBB.js → chunk-OETKXDGA.js} +546 -175
- package/dist/cli/chunk-OETKXDGA.js.map +1 -0
- package/dist/cli/{chunk-JFVRG2HH.js → chunk-PLHPKXAT.js} +8 -8
- package/dist/cli/chunk-PLHPKXAT.js.map +1 -0
- package/dist/cli/{chunk-2UPPX3FJ.js → chunk-VSSSU4AU.js} +76 -14
- package/dist/cli/chunk-VSSSU4AU.js.map +1 -0
- package/dist/cli/chunk-ZCW56PZ3.js +8 -0
- package/dist/cli/{chunk-M7NXVRU5.js.map → chunk-ZCW56PZ3.js.map} +1 -1
- package/dist/cli/{chunk-2J2IQQ4X.js → chunk-ZFVQWOGG.js} +95 -42
- package/dist/cli/chunk-ZFVQWOGG.js.map +1 -0
- package/dist/cli/config-WT5HHDRR.js +13 -0
- package/dist/cli/{config-BWFMN2ZB.js.map → config-WT5HHDRR.js.map} +1 -1
- package/dist/cli/index.js +560 -252
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/{mcp-KZEMXLHR.js → mcp-HHGNOUKE.js} +7 -7
- package/dist/cli/{mcp-KZEMXLHR.js.map → mcp-HHGNOUKE.js.map} +1 -1
- package/dist/cli/payment-providers-EWXZFBIE.js +6 -0
- package/dist/cli/{payment-providers-SZL36H3Y.js.map → payment-providers-EWXZFBIE.js.map} +1 -1
- package/dist/cli/{provider-6TKB5ADJ.js → provider-XUPLYNQ7.js} +36 -18
- package/dist/cli/provider-XUPLYNQ7.js.map +1 -0
- package/dist/cli/receipts-3DSV4DIK.js +9 -0
- package/dist/cli/{receipts-ZGLJWMQG.js.map → receipts-3DSV4DIK.js.map} +1 -1
- package/dist/cli/reconcile-GS25MQ42.js +4 -0
- package/dist/cli/{reconcile-IC22MJD5.js.map → reconcile-GS25MQ42.js.map} +1 -1
- package/dist/cli/{run-ZTYPQI4D.js → run-7KLKW3HE.js} +310 -91
- package/dist/cli/run-7KLKW3HE.js.map +1 -0
- package/dist/cli/{x402-WLYBLODI.js → x402-HP4E3QET.js} +11 -10
- package/dist/cli/x402-HP4E3QET.js.map +1 -0
- package/dist/{guardrails-CX_jYXvZ.d.ts → guardrails-CeyLS1ou.d.ts} +2 -2
- package/dist/index.d.ts +119 -206
- package/dist/index.js +1703 -427
- package/dist/index.js.map +1 -1
- package/dist/logger-CllGwQ8i.d.ts +19 -0
- package/dist/mcp.d.ts +3 -1
- package/dist/mcp.js +4 -3
- package/dist/mcp.js.map +1 -1
- package/dist/mpp.d.ts +2 -1
- package/dist/mpp.js +32 -13
- package/dist/mpp.js.map +1 -1
- package/dist/{protocol-adapter-DEXpdp8m.d.ts → protocol-adapter-DdFL5LBU.d.ts} +15 -132
- package/dist/{runtime-Dz2fSO-P.d.ts → runtime-BmaSp2Ce.d.ts} +36 -23
- package/dist/store-BVvMzpuV.d.ts +389 -0
- package/dist/testing.d.ts +51 -0
- package/dist/testing.js +2050 -0
- package/dist/testing.js.map +1 -0
- package/dist/transaction-BXXJltZ-.d.ts +129 -0
- package/dist/{types-j7MnUXYN.d.ts → types-DWqjz81-.d.ts} +5 -2
- package/dist/x402.d.ts +9 -3
- package/dist/x402.js +7 -5
- package/dist/x402.js.map +1 -1
- package/package.json +17 -29
- package/dist/chunk-3OTCFFFT.js.map +0 -1
- package/dist/chunk-4K7FIBJM.js.map +0 -1
- package/dist/chunk-5ZYXBCDX.js.map +0 -1
- package/dist/chunk-ES3V6ECS.js.map +0 -1
- package/dist/chunk-FKQK5XZA.js.map +0 -1
- package/dist/cli/ap2-YAPLERSC.js.map +0 -1
- package/dist/cli/chunk-2J2IQQ4X.js.map +0 -1
- package/dist/cli/chunk-2UPPX3FJ.js.map +0 -1
- package/dist/cli/chunk-4H2QLHQI.js.map +0 -1
- package/dist/cli/chunk-5K4XEAZV.js.map +0 -1
- package/dist/cli/chunk-5R7DM5LM.js.map +0 -1
- package/dist/cli/chunk-FHCFR2GS.js +0 -17
- package/dist/cli/chunk-FHCFR2GS.js.map +0 -1
- package/dist/cli/chunk-IDY2735M.js.map +0 -1
- package/dist/cli/chunk-JFVRG2HH.js.map +0 -1
- package/dist/cli/chunk-M7NXVRU5.js +0 -8
- package/dist/cli/chunk-QA2OPHBF.js.map +0 -1
- package/dist/cli/chunk-QLUCNPRT.js.map +0 -1
- package/dist/cli/chunk-SPAYKVUP.js.map +0 -1
- package/dist/cli/chunk-SYQLJXIU.js.map +0 -1
- package/dist/cli/chunk-Z34UMZBB.js.map +0 -1
- package/dist/cli/config-BWFMN2ZB.js +0 -12
- package/dist/cli/payment-providers-SZL36H3Y.js +0 -6
- package/dist/cli/provider-6TKB5ADJ.js.map +0 -1
- package/dist/cli/receipts-ZGLJWMQG.js +0 -8
- package/dist/cli/reconcile-IC22MJD5.js +0 -4
- package/dist/cli/run-ZTYPQI4D.js.map +0 -1
- package/dist/cli/x402-WLYBLODI.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,13 +1,17 @@
|
|
|
1
|
-
import { openSqliteDatabase, AP2_SPEC_VERSION, AP2_MODES, AP2_DEFAULT_CLOCK_SKEW_SECONDS, AP2_JWK_MEMBERS, AP2_KEY_TYPE, AP2_SIGNING_ALGORITHM, AP2_JWK_CURVE, AP2_JWK_COORDINATE_BYTES, AP2_MAX_CLOCK_SKEW_SECONDS } from './chunk-
|
|
2
|
-
import { readCappedBody, createBearerCheck, MCP_TOOL_NAME_PATTERN, settlementResponse, joinUrl, settlementResponseFromDetails, settlementFailure, x402ErrorCode, x402RefusalStatus } from './chunk-
|
|
1
|
+
import { openSqliteDatabase, AP2_SPEC_VERSION, AP2_MODES, AP2_DEFAULT_CLOCK_SKEW_SECONDS, AP2_JWK_MEMBERS, AP2_KEY_TYPE, AP2_SIGNING_ALGORITHM, AP2_JWK_CURVE, AP2_JWK_COORDINATE_BYTES, AP2_MAX_CLOCK_SKEW_SECONDS } from './chunk-DJRWYDKJ.js';
|
|
2
|
+
import { readCappedBody, createBearerCheck, MCP_TOOL_NAME_PATTERN, settlementResponse, joinUrl, settlementResponseFromDetails, settlementFailure, x402ErrorCode, x402RefusalStatus } from './chunk-77HLISG4.js';
|
|
3
3
|
import { MPP_DEFAULT_NETWORK, isMppNetwork, MPP_NETWORKS, MPP_DEFAULT_PAYMENT_FLOW, MPP_MIN_CHALLENGE_SECRET_LENGTH, MPP_PROFILE } from './chunk-6Z2H53CG.js';
|
|
4
|
-
import { contentDigest, CONTENT_DIGEST_METADATA_KEY, mppProblem, mppProblemDetail } from './chunk-
|
|
5
|
-
import { X402_PAYMENT_FLOWS, validateCustomNetworks, findX402Network, X402_DEFAULT_PAYMENT_FLOW, resolveX402Deployment, resolveDeploymentMode, requireX402Network, resolveX402Option, isEvmAddress, isEvmZeroAddress, SETTLE_AFTER_BACKEND_METADATA_KEY, x402OfferName, REUSE_REJECTED_AUTHORIZATION_METADATA_KEY, canonicalJson } from './chunk-
|
|
6
|
-
import {
|
|
7
|
-
|
|
4
|
+
import { contentDigest, CONTENT_DIGEST_METADATA_KEY, mppProblem, mppProblemDetail } from './chunk-D7FPSGUQ.js';
|
|
5
|
+
import { X402_PAYMENT_FLOWS, validateCustomNetworks, findX402Network, X402_DEFAULT_PAYMENT_FLOW, resolveX402Deployment, resolveDeploymentMode, requireX402Network, resolveX402Option, isEvmAddress, isEvmZeroAddress, SETTLE_AFTER_BACKEND_METADATA_KEY, x402OfferName, REUSE_REJECTED_AUTHORIZATION_METADATA_KEY, canonicalJson } from './chunk-EMKITGVV.js';
|
|
6
|
+
import { PACKAGE_VERSION } from './chunk-O3ACF45K.js';
|
|
7
|
+
import { PAYMENT_KEY_ENDPOINT_PREFIX } from './chunk-IWXVQYG5.js';
|
|
8
|
+
import { hasMethodGroup } from './chunk-WDD2ZUR3.js';
|
|
9
|
+
import { RESERVED_INPUT_FIELDS, PROTOCOL_NAMES, PAYMENT_METHOD_NAMES, PAYMENT_HEADER, AUTHORIZATION_HEADER, CommerceError, systemClock, NOOP_LOGGER, transactionState, DEFAULT_BACKEND_TIMEOUT_MS, isCommerceError, describeError, isHttpProtocolAdapter, toLogInfo, toCommerceError, extractReservedInputFields, parseAuthorizationHeader, toPaymentRequiredEnvelope, PAYMENT_REQUIRED_HEADER, PAYMENT_RESPONSE_HEADER, toErrorEnvelope, DELIVERY_SUMMARY_META_KEY, toDeliverySummary, PAYMENT_INPUT_FIELD, AUTHORIZATION_INPUT_FIELD, parseAuthorizationSubmission, RECONCILIATION_METADATA_KEY, TRANSACTION_STATES, redactedErrorText } from './chunk-YHNTTMED.js';
|
|
10
|
+
export { AUTHORIZATION_HEADER, AUTHORIZATION_INPUT_FIELD, COMMERCE_ERROR_CODES, COMMERCE_ERROR_HTTP_STATUS, COMMERCE_EVENT_TYPES, CommerceError, DEFAULT_BACKEND_TIMEOUT_MS, DELIVERY_SUMMARY_META_KEY, MAX_AUTHORIZATION_HEADER_BYTES, NOOP_LOGGER, PAYMENT_HEADER, PAYMENT_INPUT_FIELD, PAYMENT_METHOD_NAMES, PAYMENT_REQUIRED_HEADER, PAYMENT_RESPONSE_HEADER, PROTOCOL_NAMES, RECONCILIATION_METADATA_KEY, RESERVED_INPUT_FIELDS, RETRYABLE_ERROR_CODES, TRANSACTION_STATES, extractReservedInputFields, isCommerceError, isHttpProtocolAdapter, isPaymentRequiredEnvelope, parseAuthorizationHeader, parseAuthorizationSubmission, systemClock, toCommerceError, toDeliverySummary, toErrorEnvelope, toPaymentRequiredEnvelope, transactionState } from './chunk-YHNTTMED.js';
|
|
8
11
|
import { isRecord } from './chunk-2CJNA7MS.js';
|
|
9
|
-
import { promises, accessSync, constants } from 'fs';
|
|
12
|
+
import { promises, accessSync, constants, existsSync } from 'fs';
|
|
10
13
|
import * as path from 'path';
|
|
14
|
+
import { resolve } from 'path';
|
|
11
15
|
import { parse, YAMLError } from 'yaml';
|
|
12
16
|
import { z } from 'zod';
|
|
13
17
|
import { randomUUID, createHash } from 'crypto';
|
|
@@ -18,6 +22,7 @@ import pino from 'pino';
|
|
|
18
22
|
import { Transform } from 'stream';
|
|
19
23
|
import Ajv2020 from 'ajv/dist/2020.js';
|
|
20
24
|
import addFormats from 'ajv-formats';
|
|
25
|
+
import Database from 'better-sqlite3';
|
|
21
26
|
|
|
22
27
|
// src/config/env.ts
|
|
23
28
|
var PLACEHOLDER_PATTERN = /\$\{([A-Za-z_][A-Za-z0-9_]*)(:-([^}]*))?\}/g;
|
|
@@ -212,10 +217,10 @@ function normalizeAcp(raw) {
|
|
|
212
217
|
'protocols.acp.auth is required when ACP is enabled - every ACP checkout endpoint is authenticated, and "bearer" is the only scheme supported in this release'
|
|
213
218
|
);
|
|
214
219
|
}
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
"protocols.acp.idempotency is
|
|
220
|
+
const idempotency = raw.idempotency ?? {};
|
|
221
|
+
if (idempotency.path !== void 0) {
|
|
222
|
+
console.warn(
|
|
223
|
+
"[agent-commerce] protocols.acp.idempotency.path is deprecated: the receipt database holds ACP idempotency claims. The first start imports this file and keeps it locked while the gateway runs. Remove the key once no 2.5.x gateway uses the file; 3.0.0 stops reading it."
|
|
219
224
|
);
|
|
220
225
|
}
|
|
221
226
|
const discovery = raw.discovery;
|
|
@@ -224,13 +229,13 @@ function normalizeAcp(raw) {
|
|
|
224
229
|
mountPath,
|
|
225
230
|
auth: raw.auth,
|
|
226
231
|
idempotency: {
|
|
227
|
-
path:
|
|
232
|
+
...idempotency.path !== void 0 ? { path: idempotency.path } : {},
|
|
228
233
|
retentionHours: toNumber(
|
|
229
|
-
|
|
234
|
+
idempotency.retentionHours ?? ACP_RETENTION_HOURS,
|
|
230
235
|
"protocols.acp.idempotency.retentionHours",
|
|
231
236
|
{ min: ACP_RETENTION_HOURS }
|
|
232
237
|
),
|
|
233
|
-
merchantIdempotent:
|
|
238
|
+
merchantIdempotent: idempotency.merchantIdempotent ?? false
|
|
234
239
|
},
|
|
235
240
|
checkout: { operations: normalizeAcpOperations(raw.checkout) },
|
|
236
241
|
// Built key by key so absent metadata stays absent rather than `undefined`
|
|
@@ -361,8 +366,6 @@ function closedObjectProperties(schema) {
|
|
|
361
366
|
if (!isRecord(schema) || schema["additionalProperties"] !== false) return void 0;
|
|
362
367
|
return isRecord(schema["properties"]) ? schema["properties"] : {};
|
|
363
368
|
}
|
|
364
|
-
|
|
365
|
-
// src/config/schema/ap2.ts
|
|
366
369
|
var SUPPORTED_AUTHORIZATION_METHODS = /* @__PURE__ */ new Set(["ap2"]);
|
|
367
370
|
function ap2Invalid(path2, message, extra = {}) {
|
|
368
371
|
return new CommerceError("CONFIG_INVALID", message, { details: { path: path2, ...extra } });
|
|
@@ -384,10 +387,9 @@ function normalizeAp2(raw) {
|
|
|
384
387
|
`authorization.ap2.mode "${mode}" is not supported. Supported: ${AP2_MODES.join(", ")}. Autonomous mode needs open mandates, agent key binding and constraint evaluation, none of which this release implements.`
|
|
385
388
|
);
|
|
386
389
|
}
|
|
387
|
-
if (raw.replay
|
|
388
|
-
|
|
389
|
-
"authorization.ap2.replay"
|
|
390
|
-
"authorization.ap2.replay is required when AP2 is enabled - it names the SQLite file recording which mandates have been spent, and without it a verified mandate could authorize a second settlement"
|
|
390
|
+
if (raw.replay !== void 0) {
|
|
391
|
+
console.warn(
|
|
392
|
+
"[agent-commerce] authorization.ap2.replay.path is deprecated: the receipt database holds AP2 mandate holds. The first start imports this file and keeps it locked while the gateway runs. Remove the key once no 2.5.x gateway uses the file; 3.0.0 stops reading it."
|
|
391
393
|
);
|
|
392
394
|
}
|
|
393
395
|
const mandateIssuers = normalizeIssuers(
|
|
@@ -416,7 +418,7 @@ function normalizeAp2(raw) {
|
|
|
416
418
|
raw.requireMandateExpiry ?? false,
|
|
417
419
|
"authorization.ap2.requireMandateExpiry"
|
|
418
420
|
),
|
|
419
|
-
replay: { path: raw.replay.path }
|
|
421
|
+
...raw.replay !== void 0 ? { replay: { path: raw.replay.path } } : {}
|
|
420
422
|
};
|
|
421
423
|
}
|
|
422
424
|
function normalizeIssuers(raw, path2) {
|
|
@@ -511,16 +513,25 @@ function validateJwk(jwk, kid, path2) {
|
|
|
511
513
|
}
|
|
512
514
|
return normalized;
|
|
513
515
|
}
|
|
514
|
-
function
|
|
515
|
-
|
|
516
|
+
function validateLegacyStoresIsolated(ap2, acp, receiptsPath) {
|
|
517
|
+
const files = [
|
|
518
|
+
["authorization.ap2.replay.path", ap2?.enabled ? ap2.replay?.path : void 0],
|
|
519
|
+
["protocols.acp.idempotency.path", acp.enabled ? acp.idempotency.path : void 0]
|
|
520
|
+
];
|
|
516
521
|
const others = [["storage.receipts.path", receiptsPath]];
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
"authorization.ap2.replay.path",
|
|
522
|
-
`authorization.ap2.replay.path is the same file as ${otherPath} ("${replayPath}") - the AP2 replay store keeps its own schema and must not share a database with another store`
|
|
522
|
+
for (const [key, path2] of files) {
|
|
523
|
+
if (path2 === void 0 || path2 === ":memory:") continue;
|
|
524
|
+
const clash = others.find(
|
|
525
|
+
([, other]) => other !== ":memory:" && resolve(other) === resolve(path2)
|
|
523
526
|
);
|
|
527
|
+
if (clash !== void 0) {
|
|
528
|
+
throw new CommerceError(
|
|
529
|
+
"CONFIG_INVALID",
|
|
530
|
+
`${key} is the same file as ${clash[0]} ("${resolve(path2)}") - a deprecated store file is imported into the receipt database and then locked, so it must be a separate file`,
|
|
531
|
+
{ details: { path: key } }
|
|
532
|
+
);
|
|
533
|
+
}
|
|
534
|
+
others.push([key, path2]);
|
|
524
535
|
}
|
|
525
536
|
}
|
|
526
537
|
function normalizeResourceAuthorization(id, entry, pricing, ap2) {
|
|
@@ -843,8 +854,8 @@ var MerchantSchema = z.object({
|
|
|
843
854
|
var ServerSchema = z.object({
|
|
844
855
|
port: NumberOrString,
|
|
845
856
|
host: z.string().min(1),
|
|
846
|
-
//
|
|
847
|
-
//
|
|
857
|
+
// Operator routes (/api/receipts, /api/events, /api/payment-attempts,
|
|
858
|
+
// /api/transactions and the resolve route) return 404 without this token
|
|
848
859
|
adminToken: z.string().min(1).optional(),
|
|
849
860
|
// Browser origins allowed to call the gateway; none by default. A request
|
|
850
861
|
// with any other `Origin` gets 403 on every route. Entries match the
|
|
@@ -877,7 +888,10 @@ var RESERVED_GATEWAY_PATHS = [
|
|
|
877
888
|
"/api/resources/:id/invoke",
|
|
878
889
|
"/api/receipts",
|
|
879
890
|
"/api/events",
|
|
880
|
-
"/api/payment-attempts"
|
|
891
|
+
"/api/payment-attempts",
|
|
892
|
+
"/api/payment-attempts/:id/resolve",
|
|
893
|
+
"/api/transactions",
|
|
894
|
+
"/api/transactions/:id"
|
|
881
895
|
];
|
|
882
896
|
var MountPathSchema = z.string().min(1).refine((value) => value.startsWith("/"), {
|
|
883
897
|
message: 'must start with "/" - it is an absolute gateway path, e.g. "/mcp".'
|
|
@@ -896,11 +910,11 @@ var MountPathSchema = z.string().min(1).refine((value) => value.startsWith("/"),
|
|
|
896
910
|
);
|
|
897
911
|
var AcpAuthSchema = z.object({ type: z.literal("bearer"), token: z.string().min(1) }).strict();
|
|
898
912
|
var AcpIdempotencySchema = z.object({
|
|
899
|
-
path: z.string().min(1),
|
|
913
|
+
path: z.string().min(1).optional(),
|
|
900
914
|
retentionHours: NumberOrString.optional(),
|
|
901
915
|
merchantIdempotent: z.boolean().optional()
|
|
902
916
|
}).strict();
|
|
903
|
-
var AcpCheckoutSchema = z.object({ operations: z.record(z.string().min(1)) }).strict();
|
|
917
|
+
var AcpCheckoutSchema = z.object({ operations: z.record(z.string(), z.string().min(1)) }).strict();
|
|
904
918
|
var AcpDiscoverySchema = z.object({
|
|
905
919
|
documentationUrl: z.string().min(1).optional(),
|
|
906
920
|
supportedCurrencies: z.array(z.string().min(1)).optional(),
|
|
@@ -981,14 +995,20 @@ var ResourceEntrySchema = z.object({
|
|
|
981
995
|
paymentFlow: z.enum(X402_PAYMENT_FLOWS).optional(),
|
|
982
996
|
// This resource's own x402 offers, in place of `payments.x402` options
|
|
983
997
|
x402: z.object({ accepts: z.array(X402OptionSchema) }).strict().optional(),
|
|
984
|
-
authorization: z.object({ required: z.array(z.string().min(1)).min(1) }).strict().optional()
|
|
998
|
+
authorization: z.object({ required: z.array(z.string().min(1)).min(1) }).strict().optional(),
|
|
999
|
+
idempotency: z.object({
|
|
1000
|
+
merchantKey: BooleanOrString.optional(),
|
|
1001
|
+
redelivery: z.object({
|
|
1002
|
+
retentionHours: NumberOrString.optional(),
|
|
1003
|
+
required: BooleanOrString.optional()
|
|
1004
|
+
}).strict().optional()
|
|
1005
|
+
}).strict().optional()
|
|
985
1006
|
}).strict();
|
|
986
1007
|
var ResourcesMapSchema = z.record(z.string().min(1), ResourceEntrySchema);
|
|
987
1008
|
var FacilitatorAuthSchema = z.discriminatedUnion("type", [
|
|
988
1009
|
z.object({ type: z.literal("none") }).strict(),
|
|
989
1010
|
z.object({ type: z.literal("bearer"), token: z.string().min(1) }).strict(),
|
|
990
|
-
// Coinbase Developer Platform
|
|
991
|
-
// which signs a fresh JWT per request.
|
|
1011
|
+
// Coinbase Developer Platform: the gateway signs a fresh JWT per request
|
|
992
1012
|
z.object({
|
|
993
1013
|
type: z.literal("cdp"),
|
|
994
1014
|
apiKeyId: z.string().min(1),
|
|
@@ -1099,6 +1119,333 @@ var RawConfigSchema = z.object({
|
|
|
1099
1119
|
payments: PaymentsSchema,
|
|
1100
1120
|
authorization: AuthorizationSchema.optional()
|
|
1101
1121
|
}).strict();
|
|
1122
|
+
function createFlow(request, transactionId) {
|
|
1123
|
+
return { request, transactionId, persistenceFailures: [], journaled: false, chargeRisk: false };
|
|
1124
|
+
}
|
|
1125
|
+
function failuresOf(flow) {
|
|
1126
|
+
return flow.persistenceFailures.length > 0 ? { persistenceFailures: [...flow.persistenceFailures] } : {};
|
|
1127
|
+
}
|
|
1128
|
+
function sha256(text) {
|
|
1129
|
+
return `sha256:${createHash("sha256").update(text, "utf8").digest("hex")}`;
|
|
1130
|
+
}
|
|
1131
|
+
function inputDigest(input) {
|
|
1132
|
+
const json = canonicalJson(input);
|
|
1133
|
+
return json !== void 0 ? sha256(json) : void 0;
|
|
1134
|
+
}
|
|
1135
|
+
function configDigest(resource, requirement) {
|
|
1136
|
+
const terms = {
|
|
1137
|
+
resourceId: resource.id,
|
|
1138
|
+
pricing: resource.pricing,
|
|
1139
|
+
paymentMethods: resource.paymentMethods,
|
|
1140
|
+
authorization: resource.authorization?.required ?? [],
|
|
1141
|
+
requirement: {
|
|
1142
|
+
provider: requirement.provider,
|
|
1143
|
+
amount: requirement.amount,
|
|
1144
|
+
currency: requirement.currency,
|
|
1145
|
+
destination: requirement.destination ?? null,
|
|
1146
|
+
network: requirement.network ?? null,
|
|
1147
|
+
asset: requirement.asset ?? null,
|
|
1148
|
+
settleAfterBackend: requirement.metadata?.[SETTLE_AFTER_BACKEND_METADATA_KEY] === true
|
|
1149
|
+
}
|
|
1150
|
+
};
|
|
1151
|
+
return sha256(canonicalJson(terms) ?? JSON.stringify(terms));
|
|
1152
|
+
}
|
|
1153
|
+
function newTransaction(flow, resource, requirement, verification, digest, authorization) {
|
|
1154
|
+
const raw = verification.metadata?.[RECONCILIATION_METADATA_KEY];
|
|
1155
|
+
const locator = isRecord(raw) ? raw : void 0;
|
|
1156
|
+
const expiresAt = typeof locator?.["expiresAt"] === "string" ? locator["expiresAt"] : void 0;
|
|
1157
|
+
const network = verification.network ?? requirement.network;
|
|
1158
|
+
const asset = verification.asset ?? requirement.asset;
|
|
1159
|
+
return {
|
|
1160
|
+
id: flow.transactionId,
|
|
1161
|
+
protocol: flow.request.protocol,
|
|
1162
|
+
...network !== void 0 ? { network } : {},
|
|
1163
|
+
...asset !== void 0 ? { asset } : {},
|
|
1164
|
+
...locator !== void 0 ? { locator } : {},
|
|
1165
|
+
...expiresAt !== void 0 ? { expiresAt } : {},
|
|
1166
|
+
...authorization !== void 0 ? { authorization } : {},
|
|
1167
|
+
...digest !== void 0 ? { inputDigest: digest } : {},
|
|
1168
|
+
configDigest: configDigest(resource, requirement)
|
|
1169
|
+
};
|
|
1170
|
+
}
|
|
1171
|
+
function sha256Hex(text) {
|
|
1172
|
+
return createHash("sha256").update(text).digest("hex");
|
|
1173
|
+
}
|
|
1174
|
+
function paidOperationKey(operation) {
|
|
1175
|
+
const { deployment, resourceId, replayKey, inputDigest: digest, clientKey, payer } = operation;
|
|
1176
|
+
if (digest === void 0) return void 0;
|
|
1177
|
+
const identity = clientKey && payer ? `retry:${sha256Hex(clientKey)}:${payer}` : replayKey;
|
|
1178
|
+
return sha256Hex(JSON.stringify(["paid-operation", deployment, resourceId, identity, digest]));
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
// src/core/execution/pipeline/retry.ts
|
|
1182
|
+
var MAX_REDELIVERY_RETENTION_HOURS = 8760;
|
|
1183
|
+
var IN_FLIGHT_RETRY_AFTER_SECONDS = 1;
|
|
1184
|
+
var REFUSALS = {
|
|
1185
|
+
conflict: {
|
|
1186
|
+
reason: "payment_identifier_conflict",
|
|
1187
|
+
message: "This payment identifier belongs to another request"
|
|
1188
|
+
},
|
|
1189
|
+
"in-flight": {
|
|
1190
|
+
reason: "payment_identifier_in_flight",
|
|
1191
|
+
message: "A request with this payment identifier is in progress"
|
|
1192
|
+
},
|
|
1193
|
+
unresolved: {
|
|
1194
|
+
reason: "payment_identifier_unresolved",
|
|
1195
|
+
message: "The earlier request with this payment identifier may have been charged and has no stored response"
|
|
1196
|
+
}
|
|
1197
|
+
};
|
|
1198
|
+
function assertRetrySupport(resource, store, deployment, requestId) {
|
|
1199
|
+
const { merchantKey, redelivery } = resource.idempotency ?? {};
|
|
1200
|
+
if (merchantKey !== true && redelivery === void 0) return void 0;
|
|
1201
|
+
const invalid3 = (message) => new CommerceError("CONFIG_INVALID", message, {
|
|
1202
|
+
...requestId !== void 0 ? { requestId } : {},
|
|
1203
|
+
resourceId: resource.id
|
|
1204
|
+
});
|
|
1205
|
+
const unsupported2 = (needs) => invalid3(`Resource "${resource.id}" sets idempotency, which requires ${needs}`);
|
|
1206
|
+
const hours = redelivery?.retentionHours;
|
|
1207
|
+
if (hours !== void 0 && !(Number.isInteger(hours) && hours >= 1 && hours <= MAX_REDELIVERY_RETENTION_HOURS)) {
|
|
1208
|
+
throw invalid3(
|
|
1209
|
+
`Resource "${resource.id}" sets idempotency.redelivery.retentionHours outside 1 to ${MAX_REDELIVERY_RETENTION_HOURS}`
|
|
1210
|
+
);
|
|
1211
|
+
}
|
|
1212
|
+
if (deployment === void 0) throw unsupported2("the pipeline's deployment option");
|
|
1213
|
+
if (redelivery === void 0) return { deployment };
|
|
1214
|
+
if (!hasMethodGroup(store, "idempotency_claims") || !hasMethodGroup(store, "response_redelivery")) {
|
|
1215
|
+
throw unsupported2("a store with idempotency claims and getIdempotencyKey");
|
|
1216
|
+
}
|
|
1217
|
+
return { deployment, store };
|
|
1218
|
+
}
|
|
1219
|
+
function createRetryGate(ctx) {
|
|
1220
|
+
const { options, safeEmit, safePersist, buildEvent } = ctx;
|
|
1221
|
+
async function open(flow, resource, provider, validInput, support, pipelineStart) {
|
|
1222
|
+
const { request } = flow;
|
|
1223
|
+
const retentionHours = resource.idempotency?.redelivery?.retentionHours;
|
|
1224
|
+
const { payment } = request;
|
|
1225
|
+
if (support?.store === void 0 || retentionHours === void 0 || payment === void 0) {
|
|
1226
|
+
return void 0;
|
|
1227
|
+
}
|
|
1228
|
+
const clientKey = request.retryKey ?? await providerRetryKey(flow, resource, provider, payment);
|
|
1229
|
+
if (clientKey === void 0) return void 0;
|
|
1230
|
+
const fingerprint = inputDigest(validInput);
|
|
1231
|
+
if (fingerprint === void 0) {
|
|
1232
|
+
throw await rejected(
|
|
1233
|
+
flow,
|
|
1234
|
+
resource,
|
|
1235
|
+
provider,
|
|
1236
|
+
new CommerceError(
|
|
1237
|
+
"INPUT_INVALID",
|
|
1238
|
+
`Input for resource "${resource.id}" is not I-JSON, so a retry key cannot identify it`,
|
|
1239
|
+
{ requestId: request.requestId, resourceId: resource.id }
|
|
1240
|
+
)
|
|
1241
|
+
);
|
|
1242
|
+
}
|
|
1243
|
+
const { store } = support;
|
|
1244
|
+
const { authorization } = request;
|
|
1245
|
+
const ticket = {
|
|
1246
|
+
kind: "retry",
|
|
1247
|
+
store,
|
|
1248
|
+
scope: {
|
|
1249
|
+
deployment: support.deployment,
|
|
1250
|
+
endpoint: `${PAYMENT_KEY_ENDPOINT_PREFIX}${resource.id}`,
|
|
1251
|
+
key: sha256Hex(clientKey)
|
|
1252
|
+
},
|
|
1253
|
+
fingerprint,
|
|
1254
|
+
expiresAt: new Date(
|
|
1255
|
+
options.clock.now().getTime() + retentionHours * 60 * 60 * 1e3
|
|
1256
|
+
).toISOString(),
|
|
1257
|
+
clientKey,
|
|
1258
|
+
proofDigest: sha256Hex(`${payment.method}:${payment.payload}`),
|
|
1259
|
+
...authorization !== void 0 ? { authorizationDigest: sha256Hex(`${authorization.method}:${authorization.payload}`) } : {}
|
|
1260
|
+
};
|
|
1261
|
+
const existing = await reading(
|
|
1262
|
+
flow,
|
|
1263
|
+
resource,
|
|
1264
|
+
() => store.getIdempotencyKey(ticket.scope, fingerprint)
|
|
1265
|
+
);
|
|
1266
|
+
if (existing?.kind === "in-flight" || existing?.kind === "unresolved") {
|
|
1267
|
+
if (existing.owner !== ticket.proofDigest) return ticket;
|
|
1268
|
+
throw await refusal(flow, resource, provider, existing.kind);
|
|
1269
|
+
}
|
|
1270
|
+
if (existing?.kind !== "replay") return ticket;
|
|
1271
|
+
const stored = readStoredDelivery(existing.body);
|
|
1272
|
+
return stored?.proofDigest === ticket.proofDigest && authorizes(resource, stored, ticket) ? redeliver(flow, resource, provider, existing.status, stored, pipelineStart) : ticket;
|
|
1273
|
+
}
|
|
1274
|
+
async function claim(flow, resource, provider, ticket, verification, pipelineStart) {
|
|
1275
|
+
const { scope, fingerprint, expiresAt, proofDigest } = ticket;
|
|
1276
|
+
const claimed = await reading(
|
|
1277
|
+
flow,
|
|
1278
|
+
resource,
|
|
1279
|
+
() => ticket.store.claimIdempotencyKey(scope, fingerprint, expiresAt, proofDigest)
|
|
1280
|
+
);
|
|
1281
|
+
const replay = await acceptOrRefuse(flow, resource, provider, claimed);
|
|
1282
|
+
if (replay === void 0) return void 0;
|
|
1283
|
+
const stored = await storedDelivery(flow, resource, provider, replay);
|
|
1284
|
+
const samePayer = verification.payer !== void 0 && verification.payer === stored.payer;
|
|
1285
|
+
if (!samePayer || !authorizes(resource, stored, ticket)) {
|
|
1286
|
+
throw await refusal(flow, resource, provider, "conflict");
|
|
1287
|
+
}
|
|
1288
|
+
return redeliver(flow, resource, provider, replay.status, stored, pipelineStart);
|
|
1289
|
+
}
|
|
1290
|
+
async function finishDelivered(flow, ticket, verification, response, receipt) {
|
|
1291
|
+
const contentType = response.headers["content-type"];
|
|
1292
|
+
const stored = {
|
|
1293
|
+
proofDigest: ticket.proofDigest,
|
|
1294
|
+
...ticket.authorizationDigest !== void 0 ? { authorizationDigest: ticket.authorizationDigest } : {},
|
|
1295
|
+
// Record the verified buyer; settlement may name a fee payer instead
|
|
1296
|
+
...verification.payer !== void 0 ? { payer: verification.payer } : {},
|
|
1297
|
+
// Keep only Content-Type; never persist a backend Set-Cookie header
|
|
1298
|
+
...contentType !== void 0 ? { contentType } : {},
|
|
1299
|
+
body: response.body ?? null,
|
|
1300
|
+
receiptId: receipt.id
|
|
1301
|
+
};
|
|
1302
|
+
const receiptSaved = !flow.persistenceFailures.includes("receipt");
|
|
1303
|
+
const update = { kind: "completed", status: response.status, body: stored };
|
|
1304
|
+
if (receiptSaved && await write(flow, ticket, update)) return;
|
|
1305
|
+
if (!flow.persistenceFailures.includes("response")) flow.persistenceFailures.push("response");
|
|
1306
|
+
await write(flow, ticket, { kind: "unresolved" });
|
|
1307
|
+
}
|
|
1308
|
+
async function finishFailed(flow, ticket) {
|
|
1309
|
+
await write(flow, ticket, { kind: flow.chargeRisk ? "unresolved" : "released" });
|
|
1310
|
+
}
|
|
1311
|
+
function write(flow, ticket, update) {
|
|
1312
|
+
return safePersist(
|
|
1313
|
+
flow,
|
|
1314
|
+
() => ticket.store.updateIdempotencyKey(ticket.scope, update),
|
|
1315
|
+
`updateIdempotencyKey(${update.kind})`,
|
|
1316
|
+
"response"
|
|
1317
|
+
);
|
|
1318
|
+
}
|
|
1319
|
+
async function reading(flow, resource, read) {
|
|
1320
|
+
try {
|
|
1321
|
+
return await read();
|
|
1322
|
+
} catch (error) {
|
|
1323
|
+
throw new CommerceError("STORAGE_ERROR", "Payment retry state could not be read", {
|
|
1324
|
+
requestId: flow.request.requestId,
|
|
1325
|
+
resourceId: resource.id,
|
|
1326
|
+
cause: error
|
|
1327
|
+
});
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
async function acceptOrRefuse(flow, resource, provider, claimed) {
|
|
1331
|
+
if (claimed === void 0 || claimed.kind === "reserved") return void 0;
|
|
1332
|
+
if (claimed.kind === "replay") return claimed;
|
|
1333
|
+
throw await refusal(flow, resource, provider, claimed.kind);
|
|
1334
|
+
}
|
|
1335
|
+
async function storedDelivery(flow, resource, provider, replay) {
|
|
1336
|
+
const stored = readStoredDelivery(replay.body);
|
|
1337
|
+
if (stored === void 0) throw await refusal(flow, resource, provider, "unresolved");
|
|
1338
|
+
return stored;
|
|
1339
|
+
}
|
|
1340
|
+
function refusal(flow, resource, provider, kind) {
|
|
1341
|
+
const { reason, message } = REFUSALS[kind];
|
|
1342
|
+
const inFlight = kind === "in-flight";
|
|
1343
|
+
return rejected(
|
|
1344
|
+
flow,
|
|
1345
|
+
resource,
|
|
1346
|
+
provider,
|
|
1347
|
+
new CommerceError("PAYMENT_REPLAYED", message, {
|
|
1348
|
+
requestId: flow.request.requestId,
|
|
1349
|
+
resourceId: resource.id,
|
|
1350
|
+
details: {
|
|
1351
|
+
reason,
|
|
1352
|
+
...inFlight ? { retryAfterSeconds: IN_FLIGHT_RETRY_AFTER_SECONDS } : {}
|
|
1353
|
+
},
|
|
1354
|
+
...inFlight ? { retryable: true } : {}
|
|
1355
|
+
})
|
|
1356
|
+
);
|
|
1357
|
+
}
|
|
1358
|
+
async function rejected(flow, resource, provider, error) {
|
|
1359
|
+
const reason = error.details?.["reason"];
|
|
1360
|
+
await safeEmit(
|
|
1361
|
+
buildEvent(flow, {
|
|
1362
|
+
type: "payment.rejected",
|
|
1363
|
+
resourceId: resource.id,
|
|
1364
|
+
adapter: flow.request.protocol,
|
|
1365
|
+
paymentProvider: provider.name,
|
|
1366
|
+
status: "error",
|
|
1367
|
+
data: { reason: typeof reason === "string" ? reason : error.code }
|
|
1368
|
+
})
|
|
1369
|
+
);
|
|
1370
|
+
if (error.requestId !== void 0) return error;
|
|
1371
|
+
return new CommerceError(error.code, error.message, {
|
|
1372
|
+
requestId: flow.request.requestId,
|
|
1373
|
+
resourceId: error.resourceId ?? resource.id,
|
|
1374
|
+
httpStatus: error.httpStatus,
|
|
1375
|
+
retryable: error.retryable,
|
|
1376
|
+
...error.details !== void 0 ? { details: error.details } : {},
|
|
1377
|
+
...error.cause !== void 0 ? { cause: error.cause } : {}
|
|
1378
|
+
});
|
|
1379
|
+
}
|
|
1380
|
+
async function providerRetryKey(flow, resource, provider, submission) {
|
|
1381
|
+
try {
|
|
1382
|
+
return provider.retryKey?.({ resource, submission });
|
|
1383
|
+
} catch (error) {
|
|
1384
|
+
const typed = isCommerceError(error) ? error : new CommerceError("PAYMENT_PROVIDER_UNAVAILABLE", "Payment provider is unavailable", {
|
|
1385
|
+
cause: error
|
|
1386
|
+
});
|
|
1387
|
+
throw await rejected(flow, resource, provider, typed);
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1390
|
+
async function redeliver(flow, resource, provider, status, stored, pipelineStart) {
|
|
1391
|
+
const { request } = flow;
|
|
1392
|
+
const receipt = await reading(flow, resource, () => options.store.getReceipt(stored.receiptId));
|
|
1393
|
+
if (receipt?.payment === void 0) {
|
|
1394
|
+
throw await refusal(flow, resource, provider, "unresolved");
|
|
1395
|
+
}
|
|
1396
|
+
const durationMs = Math.round(options.clock.monotonicMs() - pipelineStart);
|
|
1397
|
+
const original = receipt.transactionId;
|
|
1398
|
+
await safeEmit(
|
|
1399
|
+
buildEvent(flow, {
|
|
1400
|
+
type: "resource.delivered",
|
|
1401
|
+
resourceId: resource.id,
|
|
1402
|
+
adapter: request.protocol,
|
|
1403
|
+
status: "ok",
|
|
1404
|
+
durationMs,
|
|
1405
|
+
data: {
|
|
1406
|
+
redelivered: true,
|
|
1407
|
+
...original !== void 0 ? { originalTransactionId: original } : {}
|
|
1408
|
+
}
|
|
1409
|
+
})
|
|
1410
|
+
);
|
|
1411
|
+
return {
|
|
1412
|
+
kind: "delivered",
|
|
1413
|
+
requestId: request.requestId,
|
|
1414
|
+
transactionId: flow.transactionId,
|
|
1415
|
+
resourceId: resource.id,
|
|
1416
|
+
backendStatus: status,
|
|
1417
|
+
body: stored.body,
|
|
1418
|
+
headers: stored.contentType !== void 0 ? { "content-type": stored.contentType } : {},
|
|
1419
|
+
payment: receipt.payment,
|
|
1420
|
+
receipt,
|
|
1421
|
+
durationMs,
|
|
1422
|
+
redelivered: true
|
|
1423
|
+
};
|
|
1424
|
+
}
|
|
1425
|
+
return { open, claim, finishDelivered, finishFailed };
|
|
1426
|
+
}
|
|
1427
|
+
function authorizes(resource, stored, ticket) {
|
|
1428
|
+
if ((resource.authorization?.required.length ?? 0) === 0) return true;
|
|
1429
|
+
return stored.authorizationDigest !== void 0 && stored.authorizationDigest === ticket.authorizationDigest;
|
|
1430
|
+
}
|
|
1431
|
+
function readStoredDelivery(value) {
|
|
1432
|
+
if (!isRecord(value) || !Object.hasOwn(value, "body")) return void 0;
|
|
1433
|
+
const { proofDigest, authorizationDigest, payer, contentType, body, receiptId } = value;
|
|
1434
|
+
if (typeof proofDigest !== "string" || typeof receiptId !== "string") return void 0;
|
|
1435
|
+
if (authorizationDigest !== void 0 && typeof authorizationDigest !== "string") {
|
|
1436
|
+
return void 0;
|
|
1437
|
+
}
|
|
1438
|
+
if (payer !== void 0 && typeof payer !== "string") return void 0;
|
|
1439
|
+
if (contentType !== void 0 && typeof contentType !== "string") return void 0;
|
|
1440
|
+
return {
|
|
1441
|
+
proofDigest,
|
|
1442
|
+
...authorizationDigest !== void 0 ? { authorizationDigest } : {},
|
|
1443
|
+
...payer !== void 0 ? { payer } : {},
|
|
1444
|
+
...contentType !== void 0 ? { contentType } : {},
|
|
1445
|
+
body,
|
|
1446
|
+
receiptId
|
|
1447
|
+
};
|
|
1448
|
+
}
|
|
1102
1449
|
|
|
1103
1450
|
// src/core/execution/backend-request.ts
|
|
1104
1451
|
var NEVER_FORWARDED_HEADER = /^(authorization|cookie|set-cookie|host|content-length|content-type|connection|keep-alive|te|trailer|transfer-encoding|upgrade|idempotency-key|proxy-.*)$/;
|
|
@@ -1446,56 +1793,6 @@ function safeStringify(value) {
|
|
|
1446
1793
|
function isAbortError(error) {
|
|
1447
1794
|
return error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
|
|
1448
1795
|
}
|
|
1449
|
-
function createFlow(request, transactionId) {
|
|
1450
|
-
return { request, transactionId, persistenceFailures: [], journaled: false };
|
|
1451
|
-
}
|
|
1452
|
-
function failuresOf(flow) {
|
|
1453
|
-
return flow.persistenceFailures.length > 0 ? { persistenceFailures: [...flow.persistenceFailures] } : {};
|
|
1454
|
-
}
|
|
1455
|
-
function sha256(text) {
|
|
1456
|
-
return `sha256:${createHash("sha256").update(text, "utf8").digest("hex")}`;
|
|
1457
|
-
}
|
|
1458
|
-
function inputDigest(input) {
|
|
1459
|
-
const json = canonicalJson(input);
|
|
1460
|
-
return json !== void 0 ? sha256(json) : void 0;
|
|
1461
|
-
}
|
|
1462
|
-
function configDigest(resource, requirement) {
|
|
1463
|
-
const terms = {
|
|
1464
|
-
resourceId: resource.id,
|
|
1465
|
-
pricing: resource.pricing,
|
|
1466
|
-
paymentMethods: resource.paymentMethods,
|
|
1467
|
-
authorization: resource.authorization?.required ?? [],
|
|
1468
|
-
requirement: {
|
|
1469
|
-
provider: requirement.provider,
|
|
1470
|
-
amount: requirement.amount,
|
|
1471
|
-
currency: requirement.currency,
|
|
1472
|
-
destination: requirement.destination ?? null,
|
|
1473
|
-
network: requirement.network ?? null,
|
|
1474
|
-
asset: requirement.asset ?? null,
|
|
1475
|
-
settleAfterBackend: requirement.metadata?.[SETTLE_AFTER_BACKEND_METADATA_KEY] === true
|
|
1476
|
-
}
|
|
1477
|
-
};
|
|
1478
|
-
return sha256(canonicalJson(terms) ?? JSON.stringify(terms));
|
|
1479
|
-
}
|
|
1480
|
-
function newTransaction(flow, resource, requirement, verification, validInput, authorization) {
|
|
1481
|
-
const raw = verification.metadata?.[RECONCILIATION_METADATA_KEY];
|
|
1482
|
-
const locator = isRecord(raw) ? raw : void 0;
|
|
1483
|
-
const expiresAt = typeof locator?.["expiresAt"] === "string" ? locator["expiresAt"] : void 0;
|
|
1484
|
-
const network = verification.network ?? requirement.network;
|
|
1485
|
-
const asset = verification.asset ?? requirement.asset;
|
|
1486
|
-
const digest = inputDigest(validInput);
|
|
1487
|
-
return {
|
|
1488
|
-
id: flow.transactionId,
|
|
1489
|
-
protocol: flow.request.protocol,
|
|
1490
|
-
...network !== void 0 ? { network } : {},
|
|
1491
|
-
...asset !== void 0 ? { asset } : {},
|
|
1492
|
-
...locator !== void 0 ? { locator } : {},
|
|
1493
|
-
...expiresAt !== void 0 ? { expiresAt } : {},
|
|
1494
|
-
...authorization !== void 0 ? { authorization } : {},
|
|
1495
|
-
...digest !== void 0 ? { inputDigest: digest } : {},
|
|
1496
|
-
configDigest: configDigest(resource, requirement)
|
|
1497
|
-
};
|
|
1498
|
-
}
|
|
1499
1796
|
var SUPPORTED_TYPES = /* @__PURE__ */ new Set([
|
|
1500
1797
|
"object",
|
|
1501
1798
|
"string",
|
|
@@ -1739,10 +2036,12 @@ function retryChallenge(requirement, reason) {
|
|
|
1739
2036
|
};
|
|
1740
2037
|
}
|
|
1741
2038
|
var FINISHED_ATTEMPT_STATUSES = /* @__PURE__ */ new Set(["settled", "rejected"]);
|
|
2039
|
+
function isFinishedAttempt(status) {
|
|
2040
|
+
return typeof status === "string" && FINISHED_ATTEMPT_STATUSES.has(status);
|
|
2041
|
+
}
|
|
1742
2042
|
function replayError(error, requirement) {
|
|
1743
2043
|
if (error.code !== "PAYMENT_REPLAYED") return error;
|
|
1744
|
-
const
|
|
1745
|
-
const finished = typeof status === "string" && FINISHED_ATTEMPT_STATUSES.has(status);
|
|
2044
|
+
const finished = isFinishedAttempt(error.details?.["attemptStatus"]);
|
|
1746
2045
|
const network = requirement.network;
|
|
1747
2046
|
if (!finished && network === void 0) return error;
|
|
1748
2047
|
return new CommerceError("PAYMENT_REPLAYED", error.message, {
|
|
@@ -1758,9 +2057,15 @@ function replayError(error, requirement) {
|
|
|
1758
2057
|
}
|
|
1759
2058
|
|
|
1760
2059
|
// src/core/execution/pipeline/admission.ts
|
|
1761
|
-
function createPaymentAdmission(ctx, authorizeAndReserve) {
|
|
2060
|
+
function createPaymentAdmission(ctx, authorizeAndReserve, retryGate) {
|
|
1762
2061
|
const { options, safeEmit, buildEvent } = ctx;
|
|
1763
|
-
return async function admitPayment(flow, request, resource, pricing, validInput) {
|
|
2062
|
+
return async function admitPayment(flow, request, resource, pricing, validInput, pipelineStart) {
|
|
2063
|
+
const support = assertRetrySupport(
|
|
2064
|
+
resource,
|
|
2065
|
+
options.store,
|
|
2066
|
+
options.deployment,
|
|
2067
|
+
request.requestId
|
|
2068
|
+
);
|
|
1764
2069
|
const provider = pickProvider(options.paymentProviders, resource.paymentMethods);
|
|
1765
2070
|
if (!provider) {
|
|
1766
2071
|
throw new CommerceError(
|
|
@@ -1778,6 +2083,15 @@ function createPaymentAdmission(ctx, authorizeAndReserve) {
|
|
|
1778
2083
|
resource,
|
|
1779
2084
|
request.requestId
|
|
1780
2085
|
);
|
|
2086
|
+
const retry = await retryGate.open(
|
|
2087
|
+
flow,
|
|
2088
|
+
resource,
|
|
2089
|
+
provider,
|
|
2090
|
+
validInput,
|
|
2091
|
+
support,
|
|
2092
|
+
pipelineStart
|
|
2093
|
+
);
|
|
2094
|
+
if (retry?.kind === "delivered") return retry;
|
|
1781
2095
|
let requirement;
|
|
1782
2096
|
try {
|
|
1783
2097
|
requirement = await provider.createRequirement({
|
|
@@ -1852,6 +2166,7 @@ function createPaymentAdmission(ctx, authorizeAndReserve) {
|
|
|
1852
2166
|
throw mapped;
|
|
1853
2167
|
}
|
|
1854
2168
|
if (verification.status !== "verified") {
|
|
2169
|
+
const refusal = await refusalFor(verification, requirement, request, resource);
|
|
1855
2170
|
await safeEmit(
|
|
1856
2171
|
buildEvent(flow, {
|
|
1857
2172
|
type: "payment.rejected",
|
|
@@ -1859,18 +2174,10 @@ function createPaymentAdmission(ctx, authorizeAndReserve) {
|
|
|
1859
2174
|
adapter: request.protocol,
|
|
1860
2175
|
paymentProvider: provider.name,
|
|
1861
2176
|
status: "error",
|
|
1862
|
-
data: verification.rejectionReason ? { reason: verification.rejectionReason } : {}
|
|
2177
|
+
data: refusal.code !== "PAYMENT_INVALID" ? { reason: refusal.code } : verification.rejectionReason ? { reason: verification.rejectionReason } : {}
|
|
1863
2178
|
})
|
|
1864
2179
|
);
|
|
1865
|
-
throw
|
|
1866
|
-
"PAYMENT_INVALID",
|
|
1867
|
-
verification.rejectionReason ?? "Payment was rejected",
|
|
1868
|
-
{
|
|
1869
|
-
requestId: request.requestId,
|
|
1870
|
-
resourceId: resource.id,
|
|
1871
|
-
...retryChallenge(requirement, verification.rejectionReason)
|
|
1872
|
-
}
|
|
1873
|
-
);
|
|
2180
|
+
throw refusal;
|
|
1874
2181
|
}
|
|
1875
2182
|
if (!verification.replayKey) {
|
|
1876
2183
|
await safeEmit(
|
|
@@ -1889,78 +2196,136 @@ function createPaymentAdmission(ctx, authorizeAndReserve) {
|
|
|
1889
2196
|
});
|
|
1890
2197
|
}
|
|
1891
2198
|
const replayKey = verification.replayKey;
|
|
1892
|
-
const
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
2199
|
+
const digest = retry?.fingerprint ?? inputDigest(validInput);
|
|
2200
|
+
if (retry !== void 0) {
|
|
2201
|
+
const stored = await retryGate.claim(
|
|
2202
|
+
flow,
|
|
2203
|
+
resource,
|
|
2204
|
+
provider,
|
|
2205
|
+
retry,
|
|
2206
|
+
verification,
|
|
2207
|
+
pipelineStart
|
|
2208
|
+
);
|
|
2209
|
+
if (stored !== void 0) return stored;
|
|
2210
|
+
}
|
|
1900
2211
|
try {
|
|
1901
|
-
const
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
...verification.payer !== void 0 ? { payer: verification.payer } : {},
|
|
1909
|
-
...verification.payee !== void 0 ? { payee: verification.payee } : {},
|
|
1910
|
-
...requirement.metadata?.[REUSE_REJECTED_AUTHORIZATION_METADATA_KEY] === true ? { reclaimRejected: true } : {},
|
|
1911
|
-
transaction: newTransaction(
|
|
1912
|
-
flow,
|
|
1913
|
-
resource,
|
|
1914
|
-
requirement,
|
|
1915
|
-
verification,
|
|
1916
|
-
validInput,
|
|
1917
|
-
hold !== void 0 ? { ...hold.record, reservationId: hold.reservationId } : void 0
|
|
1918
|
-
)
|
|
1919
|
-
});
|
|
1920
|
-
flow.journaled = attempt.transactionId === flow.transactionId && options.store.recordTransactionStep !== void 0;
|
|
1921
|
-
} catch (error) {
|
|
1922
|
-
const mapped = toCommerceError(
|
|
1923
|
-
error,
|
|
1924
|
-
"STORAGE_ERROR",
|
|
1925
|
-
"Payment attempt could not be recorded"
|
|
2212
|
+
const hold = await authorizeAndReserve(
|
|
2213
|
+
flow,
|
|
2214
|
+
request,
|
|
2215
|
+
resource,
|
|
2216
|
+
authProviders,
|
|
2217
|
+
requirement,
|
|
2218
|
+
validInput
|
|
1926
2219
|
);
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
type: "payment.rejected",
|
|
2220
|
+
try {
|
|
2221
|
+
const attempt = await options.store.reservePaymentAttempt({
|
|
2222
|
+
requestId: request.requestId,
|
|
1931
2223
|
resourceId: resource.id,
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
2224
|
+
provider: provider.name,
|
|
2225
|
+
replayKey,
|
|
2226
|
+
amount: verification.amount,
|
|
2227
|
+
currency: verification.currency,
|
|
2228
|
+
...verification.payer !== void 0 ? { payer: verification.payer } : {},
|
|
2229
|
+
...verification.payee !== void 0 ? { payee: verification.payee } : {},
|
|
2230
|
+
...requirement.metadata?.[REUSE_REJECTED_AUTHORIZATION_METADATA_KEY] === true ? { reclaimRejected: true } : {},
|
|
2231
|
+
transaction: newTransaction(
|
|
2232
|
+
flow,
|
|
2233
|
+
resource,
|
|
2234
|
+
requirement,
|
|
2235
|
+
verification,
|
|
2236
|
+
digest,
|
|
2237
|
+
hold !== void 0 ? { ...hold.record, reservationId: hold.reservationId } : void 0
|
|
2238
|
+
)
|
|
2239
|
+
});
|
|
2240
|
+
flow.journaled = attempt.transactionId === flow.transactionId && options.store.recordTransactionStep !== void 0;
|
|
2241
|
+
} catch (error) {
|
|
2242
|
+
const mapped = toCommerceError(
|
|
2243
|
+
error,
|
|
2244
|
+
"STORAGE_ERROR",
|
|
2245
|
+
"Payment attempt could not be recorded"
|
|
2246
|
+
);
|
|
2247
|
+
await hold?.finalize("release");
|
|
2248
|
+
await safeEmit(
|
|
2249
|
+
buildEvent(flow, {
|
|
2250
|
+
type: "payment.rejected",
|
|
2251
|
+
resourceId: resource.id,
|
|
2252
|
+
adapter: request.protocol,
|
|
2253
|
+
paymentProvider: provider.name,
|
|
2254
|
+
status: "error",
|
|
2255
|
+
data: { reason: mapped.code }
|
|
2256
|
+
})
|
|
2257
|
+
);
|
|
2258
|
+
throw replayError(mapped, requirement);
|
|
2259
|
+
}
|
|
2260
|
+
await safeEmit(
|
|
2261
|
+
buildEvent(flow, {
|
|
2262
|
+
type: "payment.verified",
|
|
2263
|
+
resourceId: resource.id,
|
|
2264
|
+
adapter: request.protocol,
|
|
2265
|
+
paymentProvider: provider.name,
|
|
2266
|
+
status: "ok"
|
|
2267
|
+
})
|
|
1937
2268
|
);
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
await safeEmit(
|
|
1941
|
-
buildEvent(flow, {
|
|
1942
|
-
type: "payment.verified",
|
|
2269
|
+
const merchantKey = support !== void 0 && resource.idempotency?.merchantKey === true ? paidOperationKey({
|
|
2270
|
+
deployment: support.deployment,
|
|
1943
2271
|
resourceId: resource.id,
|
|
1944
|
-
adapter: request.protocol,
|
|
1945
|
-
paymentProvider: provider.name,
|
|
1946
|
-
status: "ok"
|
|
1947
|
-
})
|
|
1948
|
-
);
|
|
1949
|
-
return {
|
|
1950
|
-
kind: "admitted",
|
|
1951
|
-
settleArgs: {
|
|
1952
|
-
flow,
|
|
1953
|
-
request,
|
|
1954
|
-
resource,
|
|
1955
|
-
provider,
|
|
1956
|
-
requirement,
|
|
1957
|
-
payment,
|
|
1958
|
-
verification,
|
|
1959
2272
|
replayKey,
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
2273
|
+
inputDigest: digest,
|
|
2274
|
+
...retry !== void 0 ? { clientKey: retry.clientKey } : {},
|
|
2275
|
+
...verification.payer !== void 0 ? { payer: verification.payer } : {}
|
|
2276
|
+
}) : void 0;
|
|
2277
|
+
return {
|
|
2278
|
+
kind: "admitted",
|
|
2279
|
+
settleArgs: {
|
|
2280
|
+
flow,
|
|
2281
|
+
request,
|
|
2282
|
+
resource,
|
|
2283
|
+
provider,
|
|
2284
|
+
requirement,
|
|
2285
|
+
payment,
|
|
2286
|
+
verification,
|
|
2287
|
+
replayKey,
|
|
2288
|
+
hold,
|
|
2289
|
+
...merchantKey !== void 0 ? { merchantKey } : {},
|
|
2290
|
+
...retry !== void 0 ? { retry } : {}
|
|
2291
|
+
}
|
|
2292
|
+
};
|
|
2293
|
+
} catch (error) {
|
|
2294
|
+
if (retry !== void 0) await retryGate.finishFailed(flow, retry);
|
|
2295
|
+
throw error;
|
|
2296
|
+
}
|
|
1963
2297
|
};
|
|
2298
|
+
async function refusalFor(verification, requirement, request, resource) {
|
|
2299
|
+
const ids = { requestId: request.requestId, resourceId: resource.id };
|
|
2300
|
+
if (verification.replayKey !== void 0) {
|
|
2301
|
+
let attempt;
|
|
2302
|
+
try {
|
|
2303
|
+
attempt = await options.store.findPaymentAttemptByReplayKey?.(verification.replayKey);
|
|
2304
|
+
} catch (error) {
|
|
2305
|
+
return new CommerceError("STORAGE_ERROR", "Payment attempt could not be read", {
|
|
2306
|
+
...ids,
|
|
2307
|
+
cause: error
|
|
2308
|
+
});
|
|
2309
|
+
}
|
|
2310
|
+
if (attempt !== void 0 && !isFinishedAttempt(attempt.status)) {
|
|
2311
|
+
return replayError(
|
|
2312
|
+
new CommerceError("PAYMENT_REPLAYED", "Payment authorization has already been used", {
|
|
2313
|
+
...ids,
|
|
2314
|
+
details: { attemptStatus: attempt.status }
|
|
2315
|
+
}),
|
|
2316
|
+
requirement
|
|
2317
|
+
);
|
|
2318
|
+
}
|
|
2319
|
+
}
|
|
2320
|
+
return new CommerceError(
|
|
2321
|
+
"PAYMENT_INVALID",
|
|
2322
|
+
verification.rejectionReason ?? "Payment was rejected",
|
|
2323
|
+
{
|
|
2324
|
+
...ids,
|
|
2325
|
+
...retryChallenge(requirement, verification.rejectionReason)
|
|
2326
|
+
}
|
|
2327
|
+
);
|
|
2328
|
+
}
|
|
1964
2329
|
}
|
|
1965
2330
|
function pickProvider(providers, methods) {
|
|
1966
2331
|
for (const method of methods) {
|
|
@@ -2054,6 +2419,7 @@ function createSettlement(ctx) {
|
|
|
2054
2419
|
hold
|
|
2055
2420
|
} = args;
|
|
2056
2421
|
await recordStep(flow, { kind: "settling" });
|
|
2422
|
+
flow.chargeRisk = true;
|
|
2057
2423
|
let settlement;
|
|
2058
2424
|
try {
|
|
2059
2425
|
settlement = await provider.settle({
|
|
@@ -2066,6 +2432,7 @@ function createSettlement(ctx) {
|
|
|
2066
2432
|
} catch (error) {
|
|
2067
2433
|
const notSubmitted = notSubmittedReason(error);
|
|
2068
2434
|
if (notSubmitted !== void 0) {
|
|
2435
|
+
flow.chargeRisk = false;
|
|
2069
2436
|
await finalizeHold(flow, hold, "release");
|
|
2070
2437
|
await safePersist(
|
|
2071
2438
|
flow,
|
|
@@ -2136,6 +2503,7 @@ function createSettlement(ctx) {
|
|
|
2136
2503
|
});
|
|
2137
2504
|
}
|
|
2138
2505
|
if (settlement.status !== "settled") {
|
|
2506
|
+
flow.chargeRisk = false;
|
|
2139
2507
|
await finalizeHold(flow, hold, "release");
|
|
2140
2508
|
await safePersist(
|
|
2141
2509
|
flow,
|
|
@@ -2257,7 +2625,8 @@ function createExecutionPipeline(options) {
|
|
|
2257
2625
|
const ctx = createPipelineContext(options);
|
|
2258
2626
|
const { safeEmit, safePersist, recordStep, buildEvent } = ctx;
|
|
2259
2627
|
const { settle, abandonSettlement } = createSettlement(ctx);
|
|
2260
|
-
const
|
|
2628
|
+
const retryGate = createRetryGate(ctx);
|
|
2629
|
+
const admitPayment = createPaymentAdmission(ctx, createAuthorizeAndReserve(ctx), retryGate);
|
|
2261
2630
|
async function execute(request) {
|
|
2262
2631
|
const pipelineStart = options.clock.monotonicMs();
|
|
2263
2632
|
const resource = options.resources.get(request.resourceId);
|
|
@@ -2321,12 +2690,22 @@ function createExecutionPipeline(options) {
|
|
|
2321
2690
|
}
|
|
2322
2691
|
let settleArgs;
|
|
2323
2692
|
if (resource.pricing.type === "fixed") {
|
|
2324
|
-
const admission = await admitPayment(
|
|
2325
|
-
|
|
2693
|
+
const admission = await admitPayment(
|
|
2694
|
+
flow,
|
|
2695
|
+
request,
|
|
2696
|
+
resource,
|
|
2697
|
+
resource.pricing,
|
|
2698
|
+
validInput,
|
|
2699
|
+
pipelineStart
|
|
2700
|
+
);
|
|
2701
|
+
if (admission.kind !== "admitted") return admission;
|
|
2326
2702
|
settleArgs = admission.settleArgs;
|
|
2327
2703
|
}
|
|
2328
2704
|
try {
|
|
2329
2705
|
return await settleAndDeliver(flow, resource, validInput, settleArgs, pipelineStart);
|
|
2706
|
+
} catch (error) {
|
|
2707
|
+
if (settleArgs?.retry !== void 0) await retryGate.finishFailed(flow, settleArgs.retry);
|
|
2708
|
+
throw error;
|
|
2330
2709
|
} finally {
|
|
2331
2710
|
await recordStep(flow, { kind: "completed", ...failuresOf(flow) });
|
|
2332
2711
|
}
|
|
@@ -2348,13 +2727,14 @@ function createExecutionPipeline(options) {
|
|
|
2348
2727
|
deadlineAt: backendDeadline(options.clock.now(), resource)
|
|
2349
2728
|
});
|
|
2350
2729
|
const backendStart = options.clock.monotonicMs();
|
|
2730
|
+
const idempotencyKey = request.idempotencyKey ?? settleArgs?.merchantKey;
|
|
2351
2731
|
let backendResponse;
|
|
2352
2732
|
try {
|
|
2353
2733
|
backendResponse = await options.backend.call(resource.handler, {
|
|
2354
2734
|
requestId: request.requestId,
|
|
2355
2735
|
resourceId: resource.id,
|
|
2356
2736
|
input: validInput,
|
|
2357
|
-
...
|
|
2737
|
+
...idempotencyKey !== void 0 ? { idempotencyKey } : {},
|
|
2358
2738
|
...request.backendHeaders !== void 0 ? { backendHeaders: request.backendHeaders } : {}
|
|
2359
2739
|
});
|
|
2360
2740
|
} catch (error) {
|
|
@@ -2447,6 +2827,15 @@ function createExecutionPipeline(options) {
|
|
|
2447
2827
|
transactionId: flow.transactionId
|
|
2448
2828
|
};
|
|
2449
2829
|
await saveReceipt(flow, receipt, "saveReceipt");
|
|
2830
|
+
if (settleArgs?.retry !== void 0) {
|
|
2831
|
+
await retryGate.finishDelivered(
|
|
2832
|
+
flow,
|
|
2833
|
+
settleArgs.retry,
|
|
2834
|
+
settleArgs.verification,
|
|
2835
|
+
backendResponse,
|
|
2836
|
+
receipt
|
|
2837
|
+
);
|
|
2838
|
+
}
|
|
2450
2839
|
const totalDurationMs = Math.round(options.clock.monotonicMs() - pipelineStart);
|
|
2451
2840
|
const failures = failuresOf(flow);
|
|
2452
2841
|
await safeEmit(
|
|
@@ -2820,6 +3209,7 @@ function validateResourceSchemaKeywords(id, path2, schema) {
|
|
|
2820
3209
|
// src/config/schema/resources.ts
|
|
2821
3210
|
var SUPPORTED_PROTOCOLS = new Set(PROTOCOL_NAMES);
|
|
2822
3211
|
var SUPPORTED_PAYMENT_METHODS = new Set(PAYMENT_METHOD_NAMES);
|
|
3212
|
+
var DEFAULT_REDELIVERY_RETENTION_HOURS = 24;
|
|
2823
3213
|
function normalizeResource(id, entry, protocols, x402, mpp, ap2) {
|
|
2824
3214
|
if (entry.input !== void 0) validateResourceSchemaKeywords(id, "input", entry.input);
|
|
2825
3215
|
const inputProperties = entry.input?.["properties"];
|
|
@@ -2982,6 +3372,7 @@ function normalizeResource(id, entry, protocols, x402, mpp, ap2) {
|
|
|
2982
3372
|
{ details: { path: `resources.${id}.mimeType`, resourceId: id } }
|
|
2983
3373
|
);
|
|
2984
3374
|
}
|
|
3375
|
+
const idempotency = normalizeResourceIdempotency(id, entry, paymentMethods);
|
|
2985
3376
|
const pricing = entry.pricing.type === "free" ? { type: "free" } : { type: "fixed", amount: entry.pricing.amount, currency: entry.pricing.currency };
|
|
2986
3377
|
const authorization = normalizeResourceAuthorization(id, entry, pricing, ap2);
|
|
2987
3378
|
return {
|
|
@@ -3005,7 +3396,44 @@ function normalizeResource(id, entry, protocols, x402, mpp, ap2) {
|
|
|
3005
3396
|
pricing,
|
|
3006
3397
|
exposedVia: entry.expose,
|
|
3007
3398
|
paymentMethods,
|
|
3008
|
-
...authorization !== void 0 ? { authorization } : {}
|
|
3399
|
+
...authorization !== void 0 ? { authorization } : {},
|
|
3400
|
+
...idempotency !== void 0 ? { idempotency } : {}
|
|
3401
|
+
};
|
|
3402
|
+
}
|
|
3403
|
+
function normalizeResourceIdempotency(id, entry, paymentMethods) {
|
|
3404
|
+
const raw = entry.idempotency;
|
|
3405
|
+
if (raw === void 0) return void 0;
|
|
3406
|
+
const path2 = `resources.${id}.idempotency`;
|
|
3407
|
+
const refuse = (problem, at) => new CommerceError("CONFIG_INVALID", `Resource "${id}" sets ${problem}`, {
|
|
3408
|
+
details: { path: at, resourceId: id }
|
|
3409
|
+
});
|
|
3410
|
+
if (entry.pricing.type !== "fixed") {
|
|
3411
|
+
throw refuse("idempotency, which requires fixed pricing", path2);
|
|
3412
|
+
}
|
|
3413
|
+
if (raw.merchantKey === void 0 && raw.redelivery === void 0) {
|
|
3414
|
+
throw refuse("idempotency without merchantKey or redelivery", path2);
|
|
3415
|
+
}
|
|
3416
|
+
let redelivery;
|
|
3417
|
+
if (raw.redelivery !== void 0) {
|
|
3418
|
+
const required = toBoolean(raw.redelivery.required ?? false, `${path2}.redelivery.required`);
|
|
3419
|
+
if (required && !paymentMethods.includes("x402")) {
|
|
3420
|
+
throw refuse(
|
|
3421
|
+
'idempotency.redelivery.required, which requires "x402" in payments',
|
|
3422
|
+
`${path2}.redelivery.required`
|
|
3423
|
+
);
|
|
3424
|
+
}
|
|
3425
|
+
redelivery = {
|
|
3426
|
+
retentionHours: toNumber(
|
|
3427
|
+
raw.redelivery.retentionHours ?? DEFAULT_REDELIVERY_RETENTION_HOURS,
|
|
3428
|
+
`${path2}.redelivery.retentionHours`,
|
|
3429
|
+
{ min: 1, max: MAX_REDELIVERY_RETENTION_HOURS }
|
|
3430
|
+
),
|
|
3431
|
+
required
|
|
3432
|
+
};
|
|
3433
|
+
}
|
|
3434
|
+
return {
|
|
3435
|
+
...raw.merchantKey !== void 0 ? { merchantKey: toBoolean(raw.merchantKey, `${path2}.merchantKey`) } : {},
|
|
3436
|
+
...redelivery !== void 0 ? { redelivery } : {}
|
|
3009
3437
|
};
|
|
3010
3438
|
}
|
|
3011
3439
|
var PRICING_AMOUNT_PATTERN = /^\d+(?:\.\d+)?$/;
|
|
@@ -3061,9 +3489,7 @@ function normalize(raw) {
|
|
|
3061
3489
|
const x402 = x402Settings?.config;
|
|
3062
3490
|
const mpp = normalizeMpp(raw.payments.mpp);
|
|
3063
3491
|
const ap2 = normalizeAp2(raw.authorization?.ap2);
|
|
3064
|
-
|
|
3065
|
-
validateReplayStoreIsolated(ap2.replay.path, raw.storage.receipts.path, protocols.acp);
|
|
3066
|
-
}
|
|
3492
|
+
validateLegacyStoresIsolated(ap2, protocols.acp, raw.storage.receipts.path);
|
|
3067
3493
|
const resources = Object.entries(raw.resources).map(
|
|
3068
3494
|
([id, entry]) => normalizeResource(id, entry, protocols, x402Settings, mpp, ap2)
|
|
3069
3495
|
);
|
|
@@ -3555,7 +3981,12 @@ var SECRET_FIELD_NAMES = [
|
|
|
3555
3981
|
"adminToken",
|
|
3556
3982
|
"token"
|
|
3557
3983
|
];
|
|
3558
|
-
var SECRET_HEADERS = [
|
|
3984
|
+
var SECRET_HEADERS = [
|
|
3985
|
+
"authorization",
|
|
3986
|
+
PAYMENT_HEADER,
|
|
3987
|
+
AUTHORIZATION_HEADER,
|
|
3988
|
+
"idempotency-key"
|
|
3989
|
+
];
|
|
3559
3990
|
var REDACT_PATHS = [
|
|
3560
3991
|
...SECRET_HEADERS.map((name) => `req.headers[${JSON.stringify(name)}]`),
|
|
3561
3992
|
...SECRET_FIELD_NAMES,
|
|
@@ -3777,6 +4208,13 @@ async function alignHold(transaction, target, deps) {
|
|
|
3777
4208
|
return holdEntry(transaction, target, true);
|
|
3778
4209
|
}
|
|
3779
4210
|
|
|
4211
|
+
// src/core/idempotency-key.ts
|
|
4212
|
+
var MAX_IDEMPOTENCY_KEY_LENGTH = 255;
|
|
4213
|
+
var USABLE_KEY = new RegExp(`^[\\x20-\\x7e]{1,${MAX_IDEMPOTENCY_KEY_LENGTH}}$`);
|
|
4214
|
+
function isUsableIdempotencyKey(value) {
|
|
4215
|
+
return USABLE_KEY.test(value);
|
|
4216
|
+
}
|
|
4217
|
+
|
|
3780
4218
|
// src/gateway/public-resource.ts
|
|
3781
4219
|
function toPublicResource(resource) {
|
|
3782
4220
|
return {
|
|
@@ -4261,6 +4699,7 @@ async function handleInvoke(request, reply, options) {
|
|
|
4261
4699
|
paymentMethod = resource.paymentMethods[0];
|
|
4262
4700
|
const paymentValue = paymentProof(request, paymentMethod);
|
|
4263
4701
|
const payment = paymentValue !== void 0 && paymentMethod !== void 0 ? { method: paymentMethod, payload: paymentValue } : void 0;
|
|
4702
|
+
const retryKey = paymentMethod === "mpp" && resource.idempotency?.redelivery !== void 0 ? mppRetryKey(request, resourceId) : void 0;
|
|
4264
4703
|
const authorization = parseAuthorizationHeader(
|
|
4265
4704
|
request.headers[AUTHORIZATION_HEADER],
|
|
4266
4705
|
request.id
|
|
@@ -4273,6 +4712,7 @@ async function handleInvoke(request, reply, options) {
|
|
|
4273
4712
|
protocol: "http",
|
|
4274
4713
|
receivedAt: options.clock.nowIso(),
|
|
4275
4714
|
...payment !== void 0 ? { payment } : {},
|
|
4715
|
+
...retryKey !== void 0 ? { retryKey } : {},
|
|
4276
4716
|
...authorization !== void 0 ? { authorization } : {},
|
|
4277
4717
|
...digest !== void 0 ? { metadata: { [CONTENT_DIGEST_METADATA_KEY]: digest } } : {}
|
|
4278
4718
|
};
|
|
@@ -4311,11 +4751,13 @@ async function handleInvoke(request, reply, options) {
|
|
|
4311
4751
|
encodeHeaderDocument(settlementResponse(outcome.payment))
|
|
4312
4752
|
);
|
|
4313
4753
|
const receipt = outcome.payment.metadata?.["receipt"];
|
|
4314
|
-
|
|
4754
|
+
const success = outcome.backendStatus >= 200 && outcome.backendStatus < 300;
|
|
4755
|
+
if (outcome.payment.provider === "mpp" && typeof receipt === "string" && (success || outcome.redelivered !== true)) {
|
|
4315
4756
|
reply.header("payment-receipt", receipt);
|
|
4316
4757
|
}
|
|
4317
4758
|
reply.header("cache-control", "private");
|
|
4318
4759
|
}
|
|
4760
|
+
if (outcome.redelivered === true) reply.header("idempotent-replayed", "true");
|
|
4319
4761
|
const contentType = relayedContentType(outcome.headers?.["content-type"], outcome.body);
|
|
4320
4762
|
if (contentType !== void 0) reply.type(contentType);
|
|
4321
4763
|
if (typeof outcome.body === "string") {
|
|
@@ -4355,9 +4797,14 @@ var MPP_PROBLEM_CODES = /* @__PURE__ */ new Set([
|
|
|
4355
4797
|
]);
|
|
4356
4798
|
function sendInvokeError(reply, error, paymentMethod) {
|
|
4357
4799
|
const details = error.details;
|
|
4800
|
+
const reason = typeof details?.["reason"] === "string" ? details["reason"] : void 0;
|
|
4358
4801
|
if (PROVIDER_UNAVAILABLE_CODES.has(error.code)) {
|
|
4359
4802
|
reply.header("retry-after", String(PROVIDER_RETRY_AFTER_SECONDS));
|
|
4360
4803
|
}
|
|
4804
|
+
const retryAfter = details?.["retryAfterSeconds"];
|
|
4805
|
+
if (typeof retryAfter === "number" && Number.isSafeInteger(retryAfter) && retryAfter >= 0) {
|
|
4806
|
+
reply.header("retry-after", String(retryAfter));
|
|
4807
|
+
}
|
|
4361
4808
|
const settled = settlementResponseFromDetails(details);
|
|
4362
4809
|
if (settled !== void 0) {
|
|
4363
4810
|
reply.header(PAYMENT_RESPONSE_HEADER, encodeHeaderDocument(settled));
|
|
@@ -4381,12 +4828,12 @@ function sendInvokeError(reply, error, paymentMethod) {
|
|
|
4381
4828
|
reply.header("cache-control", "no-store");
|
|
4382
4829
|
}
|
|
4383
4830
|
const envelope = toErrorEnvelope(error);
|
|
4384
|
-
if (paymentMethod === "mpp" && MPP_PROBLEM_CODES.has(error.code)) {
|
|
4831
|
+
if (paymentMethod === "mpp" && (MPP_PROBLEM_CODES.has(error.code) || reason?.startsWith("payment_identifier_") === true)) {
|
|
4385
4832
|
const { status: _envelopeStatus, ...members } = envelope;
|
|
4386
|
-
const
|
|
4387
|
-
reply.header("content-type", "application/problem+json").status(
|
|
4388
|
-
...mppProblem(error.code,
|
|
4389
|
-
status:
|
|
4833
|
+
const problemStatus = reason === "payment_identifier_conflict" ? 422 : error.httpStatus;
|
|
4834
|
+
reply.header("content-type", "application/problem+json").status(problemStatus).send({
|
|
4835
|
+
...mppProblem(error.code, problemStatus, reason),
|
|
4836
|
+
status: problemStatus,
|
|
4390
4837
|
// The reason token stays in `message` and `details.reason`
|
|
4391
4838
|
detail: mppProblemDetail(reason, error.message),
|
|
4392
4839
|
...members
|
|
@@ -4396,6 +4843,21 @@ function sendInvokeError(reply, error, paymentMethod) {
|
|
|
4396
4843
|
const status = paymentMethod === "x402" ? x402RefusalStatus(error.code, error.httpStatus, details?.["reason"]) : error.httpStatus;
|
|
4397
4844
|
reply.status(status).send(envelope);
|
|
4398
4845
|
}
|
|
4846
|
+
var SF_STRING = /^"((?:[\x20\x21\x23-\x5b\x5d-\x7e]|\\["\\])*)"$/;
|
|
4847
|
+
function mppRetryKey(request, resourceId) {
|
|
4848
|
+
const value = request.headers["idempotency-key"];
|
|
4849
|
+
if (value === void 0) return void 0;
|
|
4850
|
+
if (typeof value === "string") {
|
|
4851
|
+
const trimmed = value.trim();
|
|
4852
|
+
const key = trimmed.startsWith('"') ? SF_STRING.exec(trimmed)?.[1]?.replace(/\\(["\\])/g, "$1") : trimmed;
|
|
4853
|
+
if (key !== void 0 && isUsableIdempotencyKey(key)) return key;
|
|
4854
|
+
}
|
|
4855
|
+
throw new CommerceError(
|
|
4856
|
+
"INPUT_INVALID",
|
|
4857
|
+
"The Idempotency-Key header must be 1 to 255 printable ASCII characters",
|
|
4858
|
+
{ requestId: request.id, resourceId, details: { reason: "payment_identifier_invalid" } }
|
|
4859
|
+
);
|
|
4860
|
+
}
|
|
4399
4861
|
function paymentProof(request, method) {
|
|
4400
4862
|
if (method === "mpp") {
|
|
4401
4863
|
const value2 = request.headers.authorization;
|
|
@@ -4456,6 +4918,25 @@ function withProviderBackedMethodsFirst(resource, providers) {
|
|
|
4456
4918
|
];
|
|
4457
4919
|
return ordered.some((method, i) => method !== resource.paymentMethods[i]) ? { ...resource, paymentMethods: ordered } : resource;
|
|
4458
4920
|
}
|
|
4921
|
+
async function recoverPaymentKeys(store, logger) {
|
|
4922
|
+
if (!hasMethodGroup(store, "idempotency_claims") || !hasMethodGroup(store, "response_redelivery")) {
|
|
4923
|
+
return;
|
|
4924
|
+
}
|
|
4925
|
+
let recovered;
|
|
4926
|
+
try {
|
|
4927
|
+
recovered = await store.recoverIdempotencyKeys({
|
|
4928
|
+
release: false,
|
|
4929
|
+
endpointPrefix: PAYMENT_KEY_ENDPOINT_PREFIX
|
|
4930
|
+
});
|
|
4931
|
+
} catch (error) {
|
|
4932
|
+
throw new CommerceError("STORAGE_ERROR", "Payment retry keys could not be recovered", {
|
|
4933
|
+
cause: error
|
|
4934
|
+
});
|
|
4935
|
+
}
|
|
4936
|
+
if (recovered > 0) {
|
|
4937
|
+
logger.warn({ recovered }, "Payment retry keys left in flight are now unresolved");
|
|
4938
|
+
}
|
|
4939
|
+
}
|
|
4459
4940
|
async function createGateway(options) {
|
|
4460
4941
|
const clock = options.clock ?? systemClock;
|
|
4461
4942
|
const ids = options.ids ?? createDefaultIdGenerator();
|
|
@@ -4467,6 +4948,10 @@ async function createGateway(options) {
|
|
|
4467
4948
|
(resource) => withProviderBackedMethodsFirst(resource, options.paymentProviders)
|
|
4468
4949
|
)
|
|
4469
4950
|
);
|
|
4951
|
+
for (const resource of resources.list()) {
|
|
4952
|
+
assertRetrySupport(resource, options.store, options.config.merchant.publicBaseUrl);
|
|
4953
|
+
}
|
|
4954
|
+
await recoverPaymentKeys(options.store, logger);
|
|
4470
4955
|
const events = createStoreEventSink({ store: options.store, logger });
|
|
4471
4956
|
const pipeline = createExecutionPipeline({
|
|
4472
4957
|
resources,
|
|
@@ -4477,7 +4962,8 @@ async function createGateway(options) {
|
|
|
4477
4962
|
events,
|
|
4478
4963
|
logger,
|
|
4479
4964
|
clock,
|
|
4480
|
-
ids
|
|
4965
|
+
ids,
|
|
4966
|
+
deployment: options.config.merchant.publicBaseUrl
|
|
4481
4967
|
});
|
|
4482
4968
|
const server = Fastify({
|
|
4483
4969
|
// Same cap as adapter mounts, which enforce it on the socket instead
|
|
@@ -4542,8 +5028,14 @@ async function createGateway(options) {
|
|
|
4542
5028
|
return { url };
|
|
4543
5029
|
},
|
|
4544
5030
|
async close() {
|
|
5031
|
+
const sweep = setInterval(() => server.server.closeIdleConnections(), 100);
|
|
5032
|
+
sweep.unref();
|
|
5033
|
+
try {
|
|
5034
|
+
await server.close();
|
|
5035
|
+
} finally {
|
|
5036
|
+
clearInterval(sweep);
|
|
5037
|
+
}
|
|
4545
5038
|
await stopAdapters(adapterRuntimes, logger);
|
|
4546
|
-
await server.close();
|
|
4547
5039
|
},
|
|
4548
5040
|
server
|
|
4549
5041
|
};
|
|
@@ -4719,7 +5211,7 @@ function assertNoContinuation(params) {
|
|
|
4719
5211
|
const message = params.message;
|
|
4720
5212
|
if (params.taskId !== void 0 || message.taskId !== void 0) {
|
|
4721
5213
|
throw unsupported(
|
|
4722
|
-
"Task not found:
|
|
5214
|
+
"Task not found: only a task waiting for payment can be continued, so send a request with no taskId.",
|
|
4723
5215
|
A2A_ERROR_TASK_NOT_FOUND
|
|
4724
5216
|
);
|
|
4725
5217
|
}
|
|
@@ -4819,6 +5311,11 @@ function requestsX402Extension(header2) {
|
|
|
4819
5311
|
(value) => value.split(",").some((uri) => uri.trim() === A2A_X402_EXTENSION_URI)
|
|
4820
5312
|
);
|
|
4821
5313
|
}
|
|
5314
|
+
function expiryMs(nowMs, expiresAt) {
|
|
5315
|
+
const requested = expiresAt !== void 0 ? Date.parse(expiresAt) : Number.NaN;
|
|
5316
|
+
const ttl = Number.isFinite(requested) ? requested - nowMs : DEFAULT_PENDING_TTL_MS;
|
|
5317
|
+
return nowMs + Math.min(Math.max(ttl, 0), MAX_PENDING_TTL_MS);
|
|
5318
|
+
}
|
|
4822
5319
|
function createPendingPayments(clock, maxEntries = MAX_PENDING_PAYMENTS) {
|
|
4823
5320
|
const tasks = /* @__PURE__ */ new Map();
|
|
4824
5321
|
const now = () => clock.now().getTime();
|
|
@@ -4828,28 +5325,27 @@ function createPendingPayments(clock, maxEntries = MAX_PENDING_PAYMENTS) {
|
|
|
4828
5325
|
if (pending.expiresAtMs <= at) tasks.delete(taskId);
|
|
4829
5326
|
}
|
|
4830
5327
|
}
|
|
5328
|
+
function get(taskId) {
|
|
5329
|
+
const pending = tasks.get(taskId);
|
|
5330
|
+
if (pending === void 0) return void 0;
|
|
5331
|
+
if (pending.expiresAtMs <= now()) {
|
|
5332
|
+
tasks.delete(taskId);
|
|
5333
|
+
return void 0;
|
|
5334
|
+
}
|
|
5335
|
+
return pending;
|
|
5336
|
+
}
|
|
4831
5337
|
return {
|
|
4832
|
-
/** Holds a purchase until `expiresAt`; returns false, holding nothing, when full */
|
|
4833
5338
|
put(taskId, pending, expiresAt) {
|
|
4834
5339
|
purgeExpired();
|
|
4835
5340
|
if (tasks.size >= maxEntries) return false;
|
|
4836
|
-
|
|
4837
|
-
const ttl = Number.isFinite(requested) ? requested - now() : DEFAULT_PENDING_TTL_MS;
|
|
4838
|
-
const expiresAtMs = now() + Math.min(Math.max(ttl, 0), MAX_PENDING_TTL_MS);
|
|
4839
|
-
tasks.set(taskId, { ...pending, expiresAtMs });
|
|
5341
|
+
tasks.set(taskId, { ...pending, expiresAtMs: expiryMs(now(), expiresAt) });
|
|
4840
5342
|
return true;
|
|
4841
5343
|
},
|
|
4842
|
-
get
|
|
4843
|
-
|
|
4844
|
-
|
|
4845
|
-
if (pending.expiresAtMs <= now()) {
|
|
4846
|
-
tasks.delete(taskId);
|
|
4847
|
-
return void 0;
|
|
4848
|
-
}
|
|
4849
|
-
return pending;
|
|
4850
|
-
},
|
|
4851
|
-
delete(taskId) {
|
|
5344
|
+
get,
|
|
5345
|
+
take(taskId) {
|
|
5346
|
+
const pending = get(taskId);
|
|
4852
5347
|
tasks.delete(taskId);
|
|
5348
|
+
return pending;
|
|
4853
5349
|
},
|
|
4854
5350
|
size() {
|
|
4855
5351
|
return tasks.size;
|
|
@@ -4859,6 +5355,73 @@ function createPendingPayments(clock, maxEntries = MAX_PENDING_PAYMENTS) {
|
|
|
4859
5355
|
}
|
|
4860
5356
|
};
|
|
4861
5357
|
}
|
|
5358
|
+
function createStoredPendingPayments(store, clock, maxTasks = MAX_PENDING_PAYMENTS) {
|
|
5359
|
+
const mandates = /* @__PURE__ */ new Map();
|
|
5360
|
+
const now = () => clock.now().getTime();
|
|
5361
|
+
function purgeExpired() {
|
|
5362
|
+
const at = now();
|
|
5363
|
+
for (const [taskId, held] of mandates) {
|
|
5364
|
+
if (held.expiresAtMs <= at) mandates.delete(taskId);
|
|
5365
|
+
}
|
|
5366
|
+
}
|
|
5367
|
+
function toPending(task2) {
|
|
5368
|
+
const { contextId, network } = task2.adapterData ?? {};
|
|
5369
|
+
if (task2.protocol !== "a2a" || typeof contextId !== "string") return void 0;
|
|
5370
|
+
purgeExpired();
|
|
5371
|
+
const authorization = mandates.get(task2.id)?.authorization;
|
|
5372
|
+
return {
|
|
5373
|
+
contextId,
|
|
5374
|
+
resourceId: task2.resourceId,
|
|
5375
|
+
input: task2.input,
|
|
5376
|
+
...authorization !== void 0 ? { authorization } : {},
|
|
5377
|
+
...typeof network === "string" ? { network } : {},
|
|
5378
|
+
expiresAtMs: Date.parse(task2.expiresAt)
|
|
5379
|
+
};
|
|
5380
|
+
}
|
|
5381
|
+
return {
|
|
5382
|
+
async put(taskId, pending, expiresAt) {
|
|
5383
|
+
const expiresAtMs = expiryMs(now(), expiresAt);
|
|
5384
|
+
const held = await store.putPendingTask(
|
|
5385
|
+
{
|
|
5386
|
+
id: taskId,
|
|
5387
|
+
protocol: "a2a",
|
|
5388
|
+
resourceId: pending.resourceId,
|
|
5389
|
+
input: pending.input,
|
|
5390
|
+
adapterData: {
|
|
5391
|
+
contextId: pending.contextId,
|
|
5392
|
+
...pending.network !== void 0 ? { network: pending.network } : {}
|
|
5393
|
+
},
|
|
5394
|
+
expiresAt: new Date(expiresAtMs).toISOString()
|
|
5395
|
+
},
|
|
5396
|
+
{ maxTasks }
|
|
5397
|
+
);
|
|
5398
|
+
purgeExpired();
|
|
5399
|
+
mandates.delete(taskId);
|
|
5400
|
+
if (held && pending.authorization !== void 0) {
|
|
5401
|
+
mandates.set(taskId, { authorization: pending.authorization, expiresAtMs });
|
|
5402
|
+
}
|
|
5403
|
+
return held;
|
|
5404
|
+
},
|
|
5405
|
+
async get(taskId) {
|
|
5406
|
+
const task2 = await store.getPendingTask(taskId);
|
|
5407
|
+
return task2 !== void 0 ? toPending(task2) : void 0;
|
|
5408
|
+
},
|
|
5409
|
+
async take(taskId) {
|
|
5410
|
+
const task2 = await store.takePendingTask(taskId);
|
|
5411
|
+
if (task2 === void 0) return void 0;
|
|
5412
|
+
const pending = toPending(task2);
|
|
5413
|
+
if (pending === void 0) {
|
|
5414
|
+
await store.putPendingTask(task2, { maxTasks: Number.MAX_SAFE_INTEGER });
|
|
5415
|
+
return void 0;
|
|
5416
|
+
}
|
|
5417
|
+
mandates.delete(taskId);
|
|
5418
|
+
return pending;
|
|
5419
|
+
},
|
|
5420
|
+
clear() {
|
|
5421
|
+
mandates.clear();
|
|
5422
|
+
}
|
|
5423
|
+
};
|
|
5424
|
+
}
|
|
4862
5425
|
function readPaymentSubmission(message) {
|
|
4863
5426
|
const metadata = isRecord(message) ? message["metadata"] : void 0;
|
|
4864
5427
|
if (!isRecord(metadata)) return void 0;
|
|
@@ -4900,7 +5463,8 @@ function paymentFailureMetadata(error, network) {
|
|
|
4900
5463
|
[X402_PAYMENT_RECEIPTS_KEY]: [settled]
|
|
4901
5464
|
};
|
|
4902
5465
|
}
|
|
4903
|
-
const
|
|
5466
|
+
const reason = error.details?.["reason"];
|
|
5467
|
+
const code = error.code.startsWith("PAYMENT_") || typeof reason === "string" && reason.startsWith("payment_identifier_") ? x402ErrorCode(error.code, reason, error.details?.["network"]) : error.code.toLowerCase();
|
|
4904
5468
|
const failure = settlementFailure(error.details);
|
|
4905
5469
|
const receipt = failure["network"] === "" && network !== void 0 ? { ...failure, network } : failure;
|
|
4906
5470
|
return {
|
|
@@ -5048,8 +5612,8 @@ var A2A_UNSUPPORTED = [
|
|
|
5048
5612
|
"authenticated extended agent cards",
|
|
5049
5613
|
"A2A authentication schemes",
|
|
5050
5614
|
"artifact types beyond Agent Commerce outcome data",
|
|
5051
|
-
//
|
|
5052
|
-
"x402 extension payments across gateway
|
|
5615
|
+
// Instances with separate receipt stores cannot resume each other's tasks
|
|
5616
|
+
"x402 extension payments across gateway instances"
|
|
5053
5617
|
];
|
|
5054
5618
|
function buildDescriptor(implementationVersion) {
|
|
5055
5619
|
return {
|
|
@@ -5138,7 +5702,7 @@ async function resumePayment(context, pendingPayments, id, params) {
|
|
|
5138
5702
|
const message = isRecord(params) ? params["message"] : void 0;
|
|
5139
5703
|
const taskId = isRecord(message) ? message["taskId"] : void 0;
|
|
5140
5704
|
if (context === void 0 || typeof taskId !== "string") return void 0;
|
|
5141
|
-
const pending = pendingPayments?.get(taskId);
|
|
5705
|
+
const pending = await pendingPayments?.get(taskId);
|
|
5142
5706
|
if (pending === void 0) return void 0;
|
|
5143
5707
|
const messageId = isRecord(message) ? message["messageId"] : void 0;
|
|
5144
5708
|
if (typeof messageId !== "string" || messageId.length === 0) {
|
|
@@ -5158,19 +5722,21 @@ async function resumePayment(context, pendingPayments, id, params) {
|
|
|
5158
5722
|
`For a pending task, set "${X402_PAYMENT_STATUS_KEY}" to "payment-submitted" and provide a "${X402_PAYMENT_PAYLOAD_KEY}" object, or set it to "payment-rejected".`
|
|
5159
5723
|
);
|
|
5160
5724
|
}
|
|
5161
|
-
let
|
|
5162
|
-
if (authorization === void 0 && submission.kind === "submitted") {
|
|
5725
|
+
let followUp;
|
|
5726
|
+
if (pending.authorization === void 0 && submission.kind === "submitted") {
|
|
5163
5727
|
try {
|
|
5164
|
-
|
|
5728
|
+
followUp = readFollowUpAuthorization(message);
|
|
5165
5729
|
} catch (err) {
|
|
5166
5730
|
return jsonRpcError(id, JSONRPC_INVALID_PARAMS, toCommerceError(err).message);
|
|
5167
5731
|
}
|
|
5168
5732
|
}
|
|
5169
|
-
pendingPayments?.
|
|
5733
|
+
const taken = await pendingPayments?.take(taskId);
|
|
5734
|
+
if (taken === void 0) return void 0;
|
|
5735
|
+
const authorization = taken.authorization ?? followUp;
|
|
5170
5736
|
const statusMessageId = context.ids.next("a2a-msg");
|
|
5171
5737
|
const identity = {
|
|
5172
5738
|
taskId,
|
|
5173
|
-
contextId:
|
|
5739
|
+
contextId: taken.contextId,
|
|
5174
5740
|
artifactId: context.ids.next("a2a-artifact"),
|
|
5175
5741
|
statusMessageId,
|
|
5176
5742
|
timestamp: context.clock.nowIso()
|
|
@@ -5178,7 +5744,7 @@ async function resumePayment(context, pendingPayments, id, params) {
|
|
|
5178
5744
|
if (submission.kind === "rejected") {
|
|
5179
5745
|
const declined = {
|
|
5180
5746
|
id: taskId,
|
|
5181
|
-
contextId:
|
|
5747
|
+
contextId: taken.contextId,
|
|
5182
5748
|
status: { state: A2A_TASK_STATE_FAILED, timestamp: identity.timestamp },
|
|
5183
5749
|
artifacts: []
|
|
5184
5750
|
};
|
|
@@ -5196,12 +5762,23 @@ async function resumePayment(context, pendingPayments, id, params) {
|
|
|
5196
5762
|
id,
|
|
5197
5763
|
await payPending(
|
|
5198
5764
|
context,
|
|
5199
|
-
{ ...
|
|
5765
|
+
{ ...taken, ...authorization !== void 0 ? { authorization } : {} },
|
|
5200
5766
|
submission.payload,
|
|
5201
5767
|
identity
|
|
5202
5768
|
)
|
|
5203
5769
|
);
|
|
5204
5770
|
}
|
|
5771
|
+
function withoutRetryDelay(error) {
|
|
5772
|
+
if (error.details?.["reason"] !== "payment_identifier_in_flight") return error;
|
|
5773
|
+
const { retryAfterSeconds: _delay, ...details } = error.details;
|
|
5774
|
+
return new CommerceError(error.code, error.message, {
|
|
5775
|
+
httpStatus: error.httpStatus,
|
|
5776
|
+
retryable: false,
|
|
5777
|
+
details,
|
|
5778
|
+
...error.requestId !== void 0 ? { requestId: error.requestId } : {},
|
|
5779
|
+
...error.resourceId !== void 0 ? { resourceId: error.resourceId } : {}
|
|
5780
|
+
});
|
|
5781
|
+
}
|
|
5205
5782
|
async function payPending(context, pending, payload, identity) {
|
|
5206
5783
|
const requestId = context.ids.next("a2a");
|
|
5207
5784
|
const request = {
|
|
@@ -5230,16 +5807,19 @@ async function payPending(context, pending, payload, identity) {
|
|
|
5230
5807
|
}
|
|
5231
5808
|
error = new CommerceError("PAYMENT_INVALID", "The payment was not accepted.", { requestId });
|
|
5232
5809
|
} catch (err) {
|
|
5233
|
-
error = toCommerceError(err);
|
|
5810
|
+
error = withoutRetryDelay(toCommerceError(err));
|
|
5234
5811
|
context.logger.warn(
|
|
5235
5812
|
{ resourceId: pending.resourceId, requestId, err: toLogInfo(error) },
|
|
5236
5813
|
"a2a adapter: x402 extension payment failed"
|
|
5237
5814
|
);
|
|
5238
5815
|
}
|
|
5239
5816
|
const metadata = paymentFailureMetadata(error, pending.network);
|
|
5817
|
+
const reason = error.details?.["reason"];
|
|
5240
5818
|
let text = "Payment failed.";
|
|
5241
5819
|
if (metadata[X402_PAYMENT_STATUS_KEY] === "payment-completed") {
|
|
5242
5820
|
text = "Payment settled, but the resource could not be delivered.";
|
|
5821
|
+
} else if (typeof reason === "string" && reason.startsWith("payment_identifier_")) {
|
|
5822
|
+
text = error.message;
|
|
5243
5823
|
} else if (!error.code.startsWith("PAYMENT_")) {
|
|
5244
5824
|
text = "The resource could not be delivered.";
|
|
5245
5825
|
}
|
|
@@ -5260,6 +5840,7 @@ var A2aProtocolAdapter = class {
|
|
|
5260
5840
|
agentName;
|
|
5261
5841
|
agentDescription;
|
|
5262
5842
|
agentVersion;
|
|
5843
|
+
store;
|
|
5263
5844
|
context;
|
|
5264
5845
|
started = false;
|
|
5265
5846
|
// The card lists only a2a-exposed resources, but a caller can name any id,
|
|
@@ -5277,6 +5858,7 @@ var A2aProtocolAdapter = class {
|
|
|
5277
5858
|
this.agentName = options.agentName ?? A2A_DEFAULT_AGENT_NAME;
|
|
5278
5859
|
this.agentDescription = options.agentDescription ?? DEFAULT_AGENT_DESCRIPTION;
|
|
5279
5860
|
this.agentVersion = options.agentVersion ?? PACKAGE_VERSION;
|
|
5861
|
+
this.store = options.store;
|
|
5280
5862
|
this.descriptor = buildDescriptor(PACKAGE_VERSION);
|
|
5281
5863
|
this.additionalHttpRoutes = [
|
|
5282
5864
|
{
|
|
@@ -5308,7 +5890,7 @@ var A2aProtocolAdapter = class {
|
|
|
5308
5890
|
mountPath: this.mountPath,
|
|
5309
5891
|
resources
|
|
5310
5892
|
});
|
|
5311
|
-
this.pendingPayments = createPendingPayments(context.clock);
|
|
5893
|
+
this.pendingPayments = hasMethodGroup(this.store, "pending_tasks") ? createStoredPendingPayments(this.store, context.clock) : createPendingPayments(context.clock);
|
|
5312
5894
|
this.cardBody = JSON.stringify(this.card);
|
|
5313
5895
|
this.cardEtag = `"${createHash("sha256").update(this.cardBody).digest("base64url")}"`;
|
|
5314
5896
|
this.started = true;
|
|
@@ -5509,7 +6091,7 @@ var A2aProtocolAdapter = class {
|
|
|
5509
6091
|
return taskResult(id, task2);
|
|
5510
6092
|
}
|
|
5511
6093
|
const network = outcome.requirement.network;
|
|
5512
|
-
const held = this.pendingPayments?.put(
|
|
6094
|
+
const held = await this.pendingPayments?.put(
|
|
5513
6095
|
identity.taskId,
|
|
5514
6096
|
{
|
|
5515
6097
|
contextId: identity.contextId,
|
|
@@ -5727,7 +6309,7 @@ function sha2562(value) {
|
|
|
5727
6309
|
|
|
5728
6310
|
// src/protocols/acp/idempotency/store.ts
|
|
5729
6311
|
var SCHEMA_VERSION = 2;
|
|
5730
|
-
var ACP_MAX_IDEMPOTENCY_KEY_LENGTH =
|
|
6312
|
+
var ACP_MAX_IDEMPOTENCY_KEY_LENGTH = MAX_IDEMPOTENCY_KEY_LENGTH;
|
|
5731
6313
|
function createAcpIdempotencyStore(options) {
|
|
5732
6314
|
const logger = options.logger ?? NOOP_LOGGER;
|
|
5733
6315
|
const now = options.now ?? (() => Date.now());
|
|
@@ -5821,23 +6403,22 @@ function createAcpIdempotencyStore(options) {
|
|
|
5821
6403
|
};
|
|
5822
6404
|
}
|
|
5823
6405
|
function resolveOrphanedClaims(db, logger, release) {
|
|
6406
|
+
const { changes } = release ? db.prepare("DELETE FROM acp_idempotency WHERE state = 'in_flight'").run() : db.prepare("UPDATE acp_idempotency SET state = 'unresolved' WHERE state = 'in_flight'").run();
|
|
6407
|
+
warnOrphanedClaims(logger, changes, release);
|
|
6408
|
+
}
|
|
6409
|
+
function warnOrphanedClaims(logger, count, release) {
|
|
6410
|
+
if (count === 0) return;
|
|
5824
6411
|
if (release) {
|
|
5825
|
-
const { changes: changes2 } = db.prepare("DELETE FROM acp_idempotency WHERE state = 'in_flight'").run();
|
|
5826
|
-
if (changes2 > 0) {
|
|
5827
|
-
logger.warn(
|
|
5828
|
-
{ released: changes2 },
|
|
5829
|
-
"acp idempotency: freed claims left in flight by an earlier process; merchant deduplication is enabled"
|
|
5830
|
-
);
|
|
5831
|
-
}
|
|
5832
|
-
return;
|
|
5833
|
-
}
|
|
5834
|
-
const { changes } = db.prepare("UPDATE acp_idempotency SET state = 'unresolved' WHERE state = 'in_flight'").run();
|
|
5835
|
-
if (changes > 0) {
|
|
5836
6412
|
logger.warn(
|
|
5837
|
-
{
|
|
5838
|
-
"acp idempotency:
|
|
6413
|
+
{ released: count },
|
|
6414
|
+
"acp idempotency: freed claims left in flight by an earlier process; merchant deduplication is enabled"
|
|
5839
6415
|
);
|
|
6416
|
+
return;
|
|
5840
6417
|
}
|
|
6418
|
+
logger.warn(
|
|
6419
|
+
{ unresolved: count },
|
|
6420
|
+
"acp idempotency: marked claims left in flight by an earlier process as unresolved; reconcile these operations against the merchant before trusting a retry"
|
|
6421
|
+
);
|
|
5841
6422
|
}
|
|
5842
6423
|
function migrate(db, logger) {
|
|
5843
6424
|
const current = db.pragma("user_version", { simple: true });
|
|
@@ -10149,9 +10730,6 @@ function forwardedHeaders(req, requestId) {
|
|
|
10149
10730
|
}
|
|
10150
10731
|
return forwarded;
|
|
10151
10732
|
}
|
|
10152
|
-
function isUsableIdempotencyKey(value) {
|
|
10153
|
-
return value.length > 0 && value.length <= ACP_MAX_IDEMPOTENCY_KEY_LENGTH && isVisibleAscii(value);
|
|
10154
|
-
}
|
|
10155
10733
|
function normalizeRequestId(value) {
|
|
10156
10734
|
if (value === void 0) return void 0;
|
|
10157
10735
|
const trimmed = value.trim().slice(0, ACP_MAX_REQUEST_ID_LENGTH);
|
|
@@ -10392,6 +10970,27 @@ function reachedFor(error) {
|
|
|
10392
10970
|
function notReached(failure) {
|
|
10393
10971
|
return { response: asResponse(failure), reached: "no" };
|
|
10394
10972
|
}
|
|
10973
|
+
function backendOverReceiptStore(store, clock, retentionHours) {
|
|
10974
|
+
const retentionMs = retentionHours * 60 * 60 * 1e3;
|
|
10975
|
+
return {
|
|
10976
|
+
claim: (scope, fingerprint) => store.claimIdempotencyKey(
|
|
10977
|
+
scope,
|
|
10978
|
+
fingerprint,
|
|
10979
|
+
new Date(clock.now().getTime() + retentionMs).toISOString()
|
|
10980
|
+
),
|
|
10981
|
+
complete: (scope, { status, body }) => store.updateIdempotencyKey(scope, { kind: "completed", status, body }),
|
|
10982
|
+
markUnresolved: (scope) => store.updateIdempotencyKey(scope, { kind: "unresolved" }),
|
|
10983
|
+
release: (scope) => store.updateIdempotencyKey(scope, { kind: "released" })
|
|
10984
|
+
};
|
|
10985
|
+
}
|
|
10986
|
+
function backendOverFileStore(store) {
|
|
10987
|
+
return {
|
|
10988
|
+
claim: async (scope, fingerprint) => store.claim(scope, fingerprint),
|
|
10989
|
+
complete: async (scope, response) => store.complete(scope, response),
|
|
10990
|
+
markUnresolved: async (scope) => store.markUnresolved(scope),
|
|
10991
|
+
release: async (scope) => store.release(scope)
|
|
10992
|
+
};
|
|
10993
|
+
}
|
|
10395
10994
|
var AcpProtocolAdapter = class {
|
|
10396
10995
|
name = "acp";
|
|
10397
10996
|
mountPath;
|
|
@@ -10406,7 +11005,10 @@ var AcpProtocolAdapter = class {
|
|
|
10406
11005
|
*/
|
|
10407
11006
|
deployment;
|
|
10408
11007
|
discoveryMetadata;
|
|
11008
|
+
store;
|
|
10409
11009
|
idempotency;
|
|
11010
|
+
// Track the file opened by this adapter so borrowed receipt stores stay open
|
|
11011
|
+
fileStore;
|
|
10410
11012
|
resources = /* @__PURE__ */ new Map();
|
|
10411
11013
|
context;
|
|
10412
11014
|
started = false;
|
|
@@ -10418,6 +11020,7 @@ var AcpProtocolAdapter = class {
|
|
|
10418
11020
|
this.isAuthorized = createBearerCheck(options.token);
|
|
10419
11021
|
this.operations = options.operations;
|
|
10420
11022
|
this.idempotencyOptions = options.idempotency;
|
|
11023
|
+
this.store = options.store;
|
|
10421
11024
|
this.discoveryMetadata = options.discovery;
|
|
10422
11025
|
this.descriptor = buildDescriptor2(PACKAGE_VERSION);
|
|
10423
11026
|
this.additionalHttpRoutes = [
|
|
@@ -10462,12 +11065,7 @@ var AcpProtocolAdapter = class {
|
|
|
10462
11065
|
}
|
|
10463
11066
|
this.resources = resolved;
|
|
10464
11067
|
this.deployment = context.publicBaseUrl;
|
|
10465
|
-
this.idempotency =
|
|
10466
|
-
path: this.idempotencyOptions.path,
|
|
10467
|
-
retentionHours: this.idempotencyOptions.retentionHours,
|
|
10468
|
-
releaseOrphans: this.idempotencyOptions.merchantIdempotent === true,
|
|
10469
|
-
logger: context.logger
|
|
10470
|
-
});
|
|
11068
|
+
this.idempotency = await this.openIdempotency(context);
|
|
10471
11069
|
this.discovery = document;
|
|
10472
11070
|
this.started = true;
|
|
10473
11071
|
context.logger.info(
|
|
@@ -10479,6 +11077,32 @@ var AcpProtocolAdapter = class {
|
|
|
10479
11077
|
"acp adapter started"
|
|
10480
11078
|
);
|
|
10481
11079
|
}
|
|
11080
|
+
// Recover claims at adapter start, not when the shared store opens for
|
|
11081
|
+
// another consumer
|
|
11082
|
+
async openIdempotency(context) {
|
|
11083
|
+
const { path: path2, retentionHours, merchantIdempotent } = this.idempotencyOptions;
|
|
11084
|
+
const release = merchantIdempotent === true;
|
|
11085
|
+
const store = this.store;
|
|
11086
|
+
if (hasMethodGroup(store, "idempotency_claims")) {
|
|
11087
|
+
const recovered = await store.recoverIdempotencyKeys({ release, endpointPrefix: "/" });
|
|
11088
|
+
warnOrphanedClaims(context.logger, recovered, release);
|
|
11089
|
+
return backendOverReceiptStore(store, context.clock, retentionHours);
|
|
11090
|
+
}
|
|
11091
|
+
if (path2 === void 0) {
|
|
11092
|
+
throw new CommerceError(
|
|
11093
|
+
"CONFIG_INVALID",
|
|
11094
|
+
"ACP idempotency needs a receipt store with idempotency methods or a file - set protocols.acp.idempotency.path",
|
|
11095
|
+
{ details: { path: "protocols.acp.idempotency.path" } }
|
|
11096
|
+
);
|
|
11097
|
+
}
|
|
11098
|
+
this.fileStore = createAcpIdempotencyStore({
|
|
11099
|
+
path: path2,
|
|
11100
|
+
retentionHours,
|
|
11101
|
+
releaseOrphans: release,
|
|
11102
|
+
logger: context.logger
|
|
11103
|
+
});
|
|
11104
|
+
return backendOverFileStore(this.fileStore);
|
|
11105
|
+
}
|
|
10482
11106
|
/** `GET /.well-known/acp.json`: public, unauthenticated, cacheable */
|
|
10483
11107
|
async handleDiscovery(req, res) {
|
|
10484
11108
|
try {
|
|
@@ -10556,7 +11180,7 @@ var AcpProtocolAdapter = class {
|
|
|
10556
11180
|
return (await this.runCheckout(request)).response;
|
|
10557
11181
|
}
|
|
10558
11182
|
const scope = { deployment, endpoint: request.route.path, key };
|
|
10559
|
-
const claim = store.claim(scope, requestFingerprint(request.body));
|
|
11183
|
+
const claim = await store.claim(scope, requestFingerprint(request.body));
|
|
10560
11184
|
switch (claim.kind) {
|
|
10561
11185
|
case "in-flight":
|
|
10562
11186
|
return {
|
|
@@ -10595,15 +11219,15 @@ var AcpProtocolAdapter = class {
|
|
|
10595
11219
|
try {
|
|
10596
11220
|
outcome = await this.runCheckout(request, operationKey(scope));
|
|
10597
11221
|
} catch (err) {
|
|
10598
|
-
store.markUnresolved(scope);
|
|
11222
|
+
await store.markUnresolved(scope);
|
|
10599
11223
|
throw err;
|
|
10600
11224
|
}
|
|
10601
11225
|
if (outcome.response.status < 500) {
|
|
10602
|
-
store.complete(scope, outcome.response);
|
|
11226
|
+
await store.complete(scope, outcome.response);
|
|
10603
11227
|
} else if (outcome.reached === "no" || this.idempotencyOptions.merchantIdempotent === true) {
|
|
10604
|
-
store.release(scope);
|
|
11228
|
+
await store.release(scope);
|
|
10605
11229
|
} else {
|
|
10606
|
-
store.markUnresolved(scope);
|
|
11230
|
+
await store.markUnresolved(scope);
|
|
10607
11231
|
}
|
|
10608
11232
|
return outcome.response;
|
|
10609
11233
|
}
|
|
@@ -10703,7 +11327,8 @@ var AcpProtocolAdapter = class {
|
|
|
10703
11327
|
this.started = false;
|
|
10704
11328
|
this.discovery = void 0;
|
|
10705
11329
|
this.resources = /* @__PURE__ */ new Map();
|
|
10706
|
-
this.
|
|
11330
|
+
this.fileStore?.close();
|
|
11331
|
+
this.fileStore = void 0;
|
|
10707
11332
|
this.idempotency = void 0;
|
|
10708
11333
|
this.deployment = void 0;
|
|
10709
11334
|
this.context = void 0;
|
|
@@ -10713,187 +11338,26 @@ function createAcpAdapter(options) {
|
|
|
10713
11338
|
return new AcpProtocolAdapter(options);
|
|
10714
11339
|
}
|
|
10715
11340
|
|
|
10716
|
-
// src/storage/receipts/
|
|
10717
|
-
var
|
|
10718
|
-
|
|
10719
|
-
|
|
10720
|
-
|
|
10721
|
-
|
|
10722
|
-
|
|
10723
|
-
|
|
10724
|
-
|
|
10725
|
-
|
|
10726
|
-
|
|
10727
|
-
|
|
10728
|
-
|
|
10729
|
-
|
|
10730
|
-
|
|
10731
|
-
|
|
10732
|
-
|
|
10733
|
-
|
|
10734
|
-
|
|
10735
|
-
|
|
10736
|
-
return value;
|
|
10737
|
-
}
|
|
10738
|
-
|
|
10739
|
-
// src/storage/receipts/rows.ts
|
|
10740
|
-
function receiptToRow(receipt) {
|
|
10741
|
-
return {
|
|
10742
|
-
id: receipt.id,
|
|
10743
|
-
request_id: receipt.requestId,
|
|
10744
|
-
resource_id: receipt.resourceId,
|
|
10745
|
-
payment_json: receipt.payment !== void 0 ? JSON.stringify(redact(receipt.payment)) : null,
|
|
10746
|
-
delivered_at: receipt.deliveredAt,
|
|
10747
|
-
backend_status: receipt.backendStatus,
|
|
10748
|
-
duration_ms: receipt.durationMs ?? null,
|
|
10749
|
-
protocol: receipt.protocol ?? null,
|
|
10750
|
-
metadata_json: receipt.metadata !== void 0 ? JSON.stringify(redact(receipt.metadata)) : null,
|
|
10751
|
-
authorization_json: receipt.authorization !== void 0 ? JSON.stringify(redact(receipt.authorization)) : null,
|
|
10752
|
-
transaction_id: receipt.transactionId ?? null
|
|
10753
|
-
};
|
|
10754
|
-
}
|
|
10755
|
-
function rowToReceipt(row) {
|
|
10756
|
-
const payment = row.payment_json !== null ? JSON.parse(row.payment_json) : void 0;
|
|
10757
|
-
const metadata = row.metadata_json !== null ? JSON.parse(row.metadata_json) : void 0;
|
|
10758
|
-
const authorization = row.authorization_json !== null ? JSON.parse(row.authorization_json) : void 0;
|
|
10759
|
-
return {
|
|
10760
|
-
id: row.id,
|
|
10761
|
-
requestId: row.request_id,
|
|
10762
|
-
resourceId: row.resource_id,
|
|
10763
|
-
deliveredAt: row.delivered_at,
|
|
10764
|
-
backendStatus: row.backend_status,
|
|
10765
|
-
...payment !== void 0 ? { payment } : {},
|
|
10766
|
-
...row.duration_ms !== null ? { durationMs: row.duration_ms } : {},
|
|
10767
|
-
...row.protocol !== null ? { protocol: row.protocol } : {},
|
|
10768
|
-
...metadata !== void 0 ? { metadata } : {},
|
|
10769
|
-
...authorization !== void 0 ? { authorization } : {},
|
|
10770
|
-
...row.transaction_id !== null ? { transactionId: row.transaction_id } : {}
|
|
10771
|
-
};
|
|
10772
|
-
}
|
|
10773
|
-
function eventToRow(event) {
|
|
10774
|
-
return {
|
|
10775
|
-
id: event.id,
|
|
10776
|
-
type: event.type,
|
|
10777
|
-
request_id: event.requestId,
|
|
10778
|
-
resource_id: event.resourceId ?? null,
|
|
10779
|
-
at: event.at,
|
|
10780
|
-
adapter: event.adapter ?? null,
|
|
10781
|
-
payment_provider: event.paymentProvider ?? null,
|
|
10782
|
-
duration_ms: event.durationMs ?? null,
|
|
10783
|
-
status: event.status ?? null,
|
|
10784
|
-
data_json: event.data !== void 0 ? JSON.stringify(redact(event.data)) : null,
|
|
10785
|
-
transaction_id: event.transactionId ?? null
|
|
10786
|
-
};
|
|
10787
|
-
}
|
|
10788
|
-
function rowToEvent(row) {
|
|
10789
|
-
const data = row.data_json !== null ? JSON.parse(row.data_json) : void 0;
|
|
10790
|
-
return {
|
|
10791
|
-
id: row.id,
|
|
10792
|
-
type: row.type,
|
|
10793
|
-
requestId: row.request_id,
|
|
10794
|
-
at: row.at,
|
|
10795
|
-
...row.resource_id !== null ? { resourceId: row.resource_id } : {},
|
|
10796
|
-
...row.adapter !== null ? { adapter: row.adapter } : {},
|
|
10797
|
-
...row.payment_provider !== null ? { paymentProvider: row.payment_provider } : {},
|
|
10798
|
-
...row.duration_ms !== null ? { durationMs: row.duration_ms } : {},
|
|
10799
|
-
...row.status !== null ? { status: row.status } : {},
|
|
10800
|
-
...data !== void 0 ? { data } : {},
|
|
10801
|
-
...row.transaction_id !== null ? { transactionId: row.transaction_id } : {}
|
|
10802
|
-
};
|
|
10803
|
-
}
|
|
10804
|
-
function rowToPaymentAttempt(row) {
|
|
10805
|
-
return {
|
|
10806
|
-
id: row.id,
|
|
10807
|
-
requestId: row.request_id,
|
|
10808
|
-
resourceId: row.resource_id,
|
|
10809
|
-
provider: row.provider,
|
|
10810
|
-
replayKey: row.replay_key,
|
|
10811
|
-
status: row.status,
|
|
10812
|
-
amount: row.amount,
|
|
10813
|
-
currency: row.currency,
|
|
10814
|
-
...row.payer !== null ? { payer: row.payer } : {},
|
|
10815
|
-
...row.payee !== null ? { payee: row.payee } : {},
|
|
10816
|
-
...row.external_reference !== null ? { externalReference: row.external_reference } : {},
|
|
10817
|
-
...row.rejection_reason !== null ? { rejectionReason: row.rejection_reason } : {},
|
|
10818
|
-
createdAt: row.created_at,
|
|
10819
|
-
updatedAt: row.updated_at,
|
|
10820
|
-
...row.transaction_id !== null ? { transactionId: row.transaction_id } : {},
|
|
10821
|
-
...row.resolution_json !== null ? { resolution: JSON.parse(row.resolution_json) } : {}
|
|
10822
|
-
};
|
|
10823
|
-
}
|
|
10824
|
-
function rowToTransaction(row, now) {
|
|
10825
|
-
const status = row.payment_status;
|
|
10826
|
-
const backend = row.backend_dispatched_at !== null && row.backend_deadline_at !== null ? {
|
|
10827
|
-
dispatchedAt: row.backend_dispatched_at,
|
|
10828
|
-
deadlineAt: row.backend_deadline_at,
|
|
10829
|
-
...row.backend_status !== null ? { status: row.backend_status } : {},
|
|
10830
|
-
...row.backend_error_code !== null ? { errorCode: row.backend_error_code } : {}
|
|
10831
|
-
} : void 0;
|
|
10832
|
-
const completedAt = row.completed_at ?? void 0;
|
|
10833
|
-
const authorization = row.authorization_json !== null && row.reservation_id !== null ? {
|
|
10834
|
-
...JSON.parse(row.authorization_json),
|
|
10835
|
-
reservationId: row.reservation_id
|
|
10836
|
-
} : void 0;
|
|
10837
|
-
return {
|
|
10838
|
-
id: row.id,
|
|
10839
|
-
requestId: row.request_id,
|
|
10840
|
-
resourceId: row.resource_id,
|
|
10841
|
-
protocol: row.protocol,
|
|
10842
|
-
state: transactionState(
|
|
10843
|
-
{
|
|
10844
|
-
payment: { status },
|
|
10845
|
-
...backend !== void 0 ? { backend } : {},
|
|
10846
|
-
...completedAt !== void 0 ? { completedAt } : {}
|
|
10847
|
-
},
|
|
10848
|
-
now
|
|
10849
|
-
),
|
|
10850
|
-
payment: {
|
|
10851
|
-
provider: row.provider,
|
|
10852
|
-
attemptId: row.attempt_id,
|
|
10853
|
-
replayKey: row.replay_key,
|
|
10854
|
-
status,
|
|
10855
|
-
amount: row.payment_amount,
|
|
10856
|
-
currency: row.payment_currency,
|
|
10857
|
-
...row.network !== null ? { network: row.network } : {},
|
|
10858
|
-
...row.asset !== null ? { asset: row.asset } : {},
|
|
10859
|
-
...row.payment_payee !== null ? { payee: row.payment_payee } : {},
|
|
10860
|
-
...row.payment_external_reference !== null ? { externalReference: row.payment_external_reference } : {},
|
|
10861
|
-
...row.locator_json !== null ? { locator: JSON.parse(row.locator_json) } : {},
|
|
10862
|
-
...row.settling_at !== null ? { settlingAt: row.settling_at } : {},
|
|
10863
|
-
...row.expires_at !== null ? { expiresAt: row.expires_at } : {}
|
|
10864
|
-
},
|
|
10865
|
-
...authorization !== void 0 ? { authorization } : {},
|
|
10866
|
-
...backend !== void 0 ? { backend } : {},
|
|
10867
|
-
...row.receipt_id !== null ? { receiptId: row.receipt_id } : {},
|
|
10868
|
-
...row.input_digest !== null ? { inputDigest: row.input_digest } : {},
|
|
10869
|
-
configDigest: row.config_digest,
|
|
10870
|
-
...row.persistence_failures_json !== null ? { persistenceFailures: JSON.parse(row.persistence_failures_json) } : {},
|
|
10871
|
-
createdAt: row.created_at,
|
|
10872
|
-
updatedAt: row.updated_at,
|
|
10873
|
-
...completedAt !== void 0 ? { completedAt } : {}
|
|
10874
|
-
};
|
|
10875
|
-
}
|
|
10876
|
-
|
|
10877
|
-
// src/storage/receipts/schema.ts
|
|
10878
|
-
var MIGRATIONS = [
|
|
10879
|
-
{
|
|
10880
|
-
version: 1,
|
|
10881
|
-
up(db) {
|
|
10882
|
-
db.exec(`
|
|
10883
|
-
CREATE TABLE IF NOT EXISTS receipts (
|
|
10884
|
-
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
10885
|
-
id TEXT NOT NULL UNIQUE,
|
|
10886
|
-
request_id TEXT NOT NULL,
|
|
10887
|
-
resource_id TEXT NOT NULL,
|
|
10888
|
-
payment_json TEXT,
|
|
10889
|
-
delivered_at TEXT NOT NULL,
|
|
10890
|
-
backend_status INTEGER NOT NULL,
|
|
10891
|
-
duration_ms INTEGER,
|
|
10892
|
-
protocol TEXT,
|
|
10893
|
-
metadata_json TEXT
|
|
10894
|
-
);
|
|
10895
|
-
CREATE INDEX IF NOT EXISTS idx_receipts_request_id ON receipts(request_id);
|
|
10896
|
-
CREATE INDEX IF NOT EXISTS idx_receipts_delivered_at ON receipts(delivered_at);
|
|
11341
|
+
// src/storage/receipts/schema.ts
|
|
11342
|
+
var MIGRATIONS = [
|
|
11343
|
+
{
|
|
11344
|
+
version: 1,
|
|
11345
|
+
up(db) {
|
|
11346
|
+
db.exec(`
|
|
11347
|
+
CREATE TABLE IF NOT EXISTS receipts (
|
|
11348
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
11349
|
+
id TEXT NOT NULL UNIQUE,
|
|
11350
|
+
request_id TEXT NOT NULL,
|
|
11351
|
+
resource_id TEXT NOT NULL,
|
|
11352
|
+
payment_json TEXT,
|
|
11353
|
+
delivered_at TEXT NOT NULL,
|
|
11354
|
+
backend_status INTEGER NOT NULL,
|
|
11355
|
+
duration_ms INTEGER,
|
|
11356
|
+
protocol TEXT,
|
|
11357
|
+
metadata_json TEXT
|
|
11358
|
+
);
|
|
11359
|
+
CREATE INDEX IF NOT EXISTS idx_receipts_request_id ON receipts(request_id);
|
|
11360
|
+
CREATE INDEX IF NOT EXISTS idx_receipts_delivered_at ON receipts(delivered_at);
|
|
10897
11361
|
|
|
10898
11362
|
CREATE TABLE IF NOT EXISTS events (
|
|
10899
11363
|
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
@@ -11012,9 +11476,67 @@ var MIGRATIONS = [
|
|
|
11012
11476
|
CREATE INDEX IF NOT EXISTS idx_payment_attempt_history_id ON payment_attempt_history(id);
|
|
11013
11477
|
`);
|
|
11014
11478
|
}
|
|
11479
|
+
},
|
|
11480
|
+
{
|
|
11481
|
+
version: 5,
|
|
11482
|
+
up(db) {
|
|
11483
|
+
db.exec(`
|
|
11484
|
+
CREATE TABLE IF NOT EXISTS authorization_holds (
|
|
11485
|
+
reference TEXT PRIMARY KEY,
|
|
11486
|
+
method TEXT NOT NULL,
|
|
11487
|
+
binding_reference TEXT NOT NULL,
|
|
11488
|
+
resource_id TEXT NOT NULL,
|
|
11489
|
+
request_id TEXT NOT NULL,
|
|
11490
|
+
state TEXT NOT NULL
|
|
11491
|
+
CHECK (state IN ('reserved', 'consumed', 'released', 'uncertain')),
|
|
11492
|
+
metadata_json TEXT,
|
|
11493
|
+
created_at TEXT NOT NULL,
|
|
11494
|
+
updated_at TEXT NOT NULL
|
|
11495
|
+
);
|
|
11496
|
+
CREATE INDEX IF NOT EXISTS idx_authorization_holds_binding ON authorization_holds(binding_reference);
|
|
11497
|
+
CREATE INDEX IF NOT EXISTS idx_authorization_holds_request_id ON authorization_holds(request_id);
|
|
11498
|
+
CREATE INDEX IF NOT EXISTS idx_authorization_holds_state_updated ON authorization_holds(state, updated_at);
|
|
11499
|
+
|
|
11500
|
+
CREATE TABLE IF NOT EXISTS idempotency_keys (
|
|
11501
|
+
deployment TEXT NOT NULL,
|
|
11502
|
+
endpoint TEXT NOT NULL,
|
|
11503
|
+
idempotency_key TEXT NOT NULL,
|
|
11504
|
+
fingerprint TEXT NOT NULL,
|
|
11505
|
+
state TEXT NOT NULL,
|
|
11506
|
+
status INTEGER,
|
|
11507
|
+
body_json TEXT,
|
|
11508
|
+
created_at TEXT NOT NULL,
|
|
11509
|
+
expires_at TEXT NOT NULL,
|
|
11510
|
+
PRIMARY KEY (deployment, endpoint, idempotency_key)
|
|
11511
|
+
);
|
|
11512
|
+
CREATE INDEX IF NOT EXISTS idx_idempotency_keys_expires_at ON idempotency_keys(expires_at);
|
|
11513
|
+
|
|
11514
|
+
CREATE TABLE IF NOT EXISTS pending_tasks (
|
|
11515
|
+
id TEXT PRIMARY KEY,
|
|
11516
|
+
protocol TEXT NOT NULL,
|
|
11517
|
+
resource_id TEXT NOT NULL,
|
|
11518
|
+
input_json TEXT NOT NULL,
|
|
11519
|
+
adapter_data_json TEXT,
|
|
11520
|
+
created_at TEXT NOT NULL,
|
|
11521
|
+
expires_at TEXT NOT NULL
|
|
11522
|
+
);
|
|
11523
|
+
CREATE INDEX IF NOT EXISTS idx_pending_tasks_expires_at ON pending_tasks(expires_at);
|
|
11524
|
+
|
|
11525
|
+
-- path is NULL when the feature started with nothing to import
|
|
11526
|
+
CREATE TABLE IF NOT EXISTS legacy_imports (
|
|
11527
|
+
source TEXT PRIMARY KEY,
|
|
11528
|
+
path TEXT,
|
|
11529
|
+
rows INTEGER NOT NULL,
|
|
11530
|
+
imported_at TEXT NOT NULL
|
|
11531
|
+
);
|
|
11532
|
+
`);
|
|
11533
|
+
}
|
|
11015
11534
|
}
|
|
11016
11535
|
];
|
|
11017
11536
|
var SCHEMA_VERSION2 = MIGRATIONS.at(-1)?.version ?? 0;
|
|
11537
|
+
function hasTable(db, name) {
|
|
11538
|
+
return db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name) !== void 0;
|
|
11539
|
+
}
|
|
11018
11540
|
function migrate2(db, target = SCHEMA_VERSION2) {
|
|
11019
11541
|
const current = db.pragma("user_version", { simple: true });
|
|
11020
11542
|
for (const migration of MIGRATIONS) {
|
|
@@ -11027,13 +11549,684 @@ function migrate2(db, target = SCHEMA_VERSION2) {
|
|
|
11027
11549
|
}
|
|
11028
11550
|
}
|
|
11029
11551
|
|
|
11030
|
-
// src/storage/receipts/
|
|
11552
|
+
// src/storage/receipts/legacy-import.ts
|
|
11553
|
+
var NOTHING = { rows: 0, write: () => {
|
|
11554
|
+
} };
|
|
11555
|
+
var SOURCES = [
|
|
11556
|
+
{
|
|
11557
|
+
name: "ap2-replay",
|
|
11558
|
+
option: "ap2Replay",
|
|
11559
|
+
feature: "ap2",
|
|
11560
|
+
key: "authorization.ap2.replay.path",
|
|
11561
|
+
usedSql: `SELECT 1 FROM receipts WHERE authorization_json IS NOT NULL
|
|
11562
|
+
UNION ALL SELECT 1 FROM transactions WHERE authorization_json IS NOT NULL LIMIT 1`,
|
|
11563
|
+
read(file) {
|
|
11564
|
+
if (!hasTable(file, "ap2_authorizations")) return NOTHING;
|
|
11565
|
+
const rows = file.prepare(
|
|
11566
|
+
`SELECT reference, checkout_jti, mandate_issuer, checkout_issuer, resource_id,
|
|
11567
|
+
request_id, state, created_at, updated_at
|
|
11568
|
+
FROM ap2_authorizations`
|
|
11569
|
+
).all();
|
|
11570
|
+
return {
|
|
11571
|
+
rows: rows.length,
|
|
11572
|
+
write(db) {
|
|
11573
|
+
const insert = db.prepare(
|
|
11574
|
+
`INSERT INTO authorization_holds
|
|
11575
|
+
(reference, method, binding_reference, resource_id, request_id, state,
|
|
11576
|
+
metadata_json, created_at, updated_at)
|
|
11577
|
+
VALUES (@reference, 'ap2', @checkout_jti, @resource_id, @request_id, @state,
|
|
11578
|
+
@metadata_json, @created_at, @updated_at)
|
|
11579
|
+
ON CONFLICT (reference) DO UPDATE SET
|
|
11580
|
+
binding_reference = excluded.binding_reference, resource_id = excluded.resource_id,
|
|
11581
|
+
request_id = excluded.request_id, state = excluded.state,
|
|
11582
|
+
metadata_json = excluded.metadata_json, updated_at = excluded.updated_at
|
|
11583
|
+
WHERE authorization_holds.state = 'released'`
|
|
11584
|
+
);
|
|
11585
|
+
for (const row of rows) {
|
|
11586
|
+
insert.run({
|
|
11587
|
+
...row,
|
|
11588
|
+
metadata_json: JSON.stringify({
|
|
11589
|
+
mandateIssuer: row.mandate_issuer,
|
|
11590
|
+
checkoutIssuer: row.checkout_issuer
|
|
11591
|
+
})
|
|
11592
|
+
});
|
|
11593
|
+
}
|
|
11594
|
+
}
|
|
11595
|
+
};
|
|
11596
|
+
}
|
|
11597
|
+
},
|
|
11598
|
+
{
|
|
11599
|
+
name: "acp-idempotency",
|
|
11600
|
+
option: "acpIdempotency",
|
|
11601
|
+
feature: "acp",
|
|
11602
|
+
key: "protocols.acp.idempotency.path",
|
|
11603
|
+
usedSql: "SELECT 1 FROM events WHERE adapter = 'acp' LIMIT 1",
|
|
11604
|
+
read(file, logger) {
|
|
11605
|
+
if (!hasTable(file, "acp_idempotency")) return NOTHING;
|
|
11606
|
+
if (file.pragma("user_version", { simple: true }) < 2) {
|
|
11607
|
+
const { count } = file.prepare("SELECT COUNT(*) AS count FROM acp_idempotency WHERE state != 'completed'").get();
|
|
11608
|
+
if (count > 0) {
|
|
11609
|
+
logger.warn(
|
|
11610
|
+
{ unresolved: count },
|
|
11611
|
+
"acp idempotency: the schema v1 file holds claims keyed by an old bearer-token digest, which are not imported; reconcile these operations against the merchant before trusting a retry"
|
|
11612
|
+
);
|
|
11613
|
+
}
|
|
11614
|
+
return NOTHING;
|
|
11615
|
+
}
|
|
11616
|
+
const rows = file.prepare(
|
|
11617
|
+
`SELECT deployment, endpoint, idempotency_key, fingerprint, state, status, body_json,
|
|
11618
|
+
created_at, expires_at
|
|
11619
|
+
FROM acp_idempotency`
|
|
11620
|
+
).all();
|
|
11621
|
+
return {
|
|
11622
|
+
rows: rows.length,
|
|
11623
|
+
write(db) {
|
|
11624
|
+
const insert = db.prepare(
|
|
11625
|
+
`INSERT INTO idempotency_keys
|
|
11626
|
+
(deployment, endpoint, idempotency_key, fingerprint, state, status, body_json,
|
|
11627
|
+
created_at, expires_at)
|
|
11628
|
+
VALUES (@deployment, @endpoint, @idempotency_key, @fingerprint, @state, @status,
|
|
11629
|
+
@body_json, @created_at, @expires_at)
|
|
11630
|
+
ON CONFLICT DO NOTHING`
|
|
11631
|
+
);
|
|
11632
|
+
for (const row of rows) insert.run(row);
|
|
11633
|
+
}
|
|
11634
|
+
};
|
|
11635
|
+
}
|
|
11636
|
+
}
|
|
11637
|
+
];
|
|
11638
|
+
function storageError(message, details, cause) {
|
|
11639
|
+
return new CommerceError("STORAGE_ERROR", message, { details, cause });
|
|
11640
|
+
}
|
|
11641
|
+
function selectMarker(db, source) {
|
|
11642
|
+
return db.prepare("SELECT path FROM legacy_imports WHERE source = ?").get(source);
|
|
11643
|
+
}
|
|
11644
|
+
var usedBefore = (db, source) => db.prepare(source.usedSql).get() !== void 0;
|
|
11645
|
+
function missingLegacyImports(db) {
|
|
11646
|
+
const recorded = hasTable(db, "legacy_imports");
|
|
11647
|
+
return SOURCES.filter(
|
|
11648
|
+
(source) => !(recorded && selectMarker(db, source.name) !== void 0) && usedBefore(db, source)
|
|
11649
|
+
).map((source) => source.name);
|
|
11650
|
+
}
|
|
11651
|
+
function importLegacyStores(db, receiptsPath, options, clock, logger) {
|
|
11652
|
+
const recordMarker = db.prepare(
|
|
11653
|
+
`INSERT INTO legacy_imports (source, path, rows, imported_at) VALUES (?, ?, ?, ?)
|
|
11654
|
+
ON CONFLICT (source) DO UPDATE SET
|
|
11655
|
+
path = excluded.path, rows = excluded.rows, imported_at = excluded.imported_at`
|
|
11656
|
+
);
|
|
11657
|
+
const locks = [];
|
|
11658
|
+
const release = () => {
|
|
11659
|
+
for (const lock of locks.splice(0)) lock.close();
|
|
11660
|
+
};
|
|
11661
|
+
try {
|
|
11662
|
+
for (const source of SOURCES) {
|
|
11663
|
+
const given = options[source.option];
|
|
11664
|
+
const marker = selectMarker(db, source.name);
|
|
11665
|
+
const importedPath = marker?.path ?? void 0;
|
|
11666
|
+
const path2 = given !== void 0 && given !== ":memory:" ? resolve(given) : void 0;
|
|
11667
|
+
if (path2 !== void 0 && receiptsPath !== ":memory:" && path2 === resolve(receiptsPath)) {
|
|
11668
|
+
throw storageError(`${source.key} names the receipt database "${path2}"`, {
|
|
11669
|
+
key: source.key,
|
|
11670
|
+
path: path2
|
|
11671
|
+
});
|
|
11672
|
+
}
|
|
11673
|
+
if (path2 !== void 0 && importedPath !== void 0 && importedPath !== path2) {
|
|
11674
|
+
throw storageError(
|
|
11675
|
+
`${source.key} names "${path2}", but "${importedPath}" was imported from it already. Point ${source.key} back at the imported file, or remove the key.`,
|
|
11676
|
+
{ key: source.key, path: path2, importedPath }
|
|
11677
|
+
);
|
|
11678
|
+
}
|
|
11679
|
+
if (path2 === void 0 || !existsSync(path2)) {
|
|
11680
|
+
if (marker === void 0 && options.enabled?.[source.feature] === true) {
|
|
11681
|
+
if (given !== ":memory:" && usedBefore(db, source)) {
|
|
11682
|
+
throw forgottenKey(source, path2);
|
|
11683
|
+
}
|
|
11684
|
+
recordMarker.run(source.name, null, 0, clock.nowIso());
|
|
11685
|
+
}
|
|
11686
|
+
if (given !== void 0) {
|
|
11687
|
+
logger.info(
|
|
11688
|
+
{ key: source.key, path: path2 ?? given },
|
|
11689
|
+
"deprecated store has no file to import; the key can be removed"
|
|
11690
|
+
);
|
|
11691
|
+
}
|
|
11692
|
+
continue;
|
|
11693
|
+
}
|
|
11694
|
+
let file;
|
|
11695
|
+
try {
|
|
11696
|
+
file = new Database(path2, { fileMustExist: true });
|
|
11697
|
+
file.exec("BEGIN EXCLUSIVE");
|
|
11698
|
+
} catch (cause) {
|
|
11699
|
+
file?.close();
|
|
11700
|
+
const cantOpen = cause.code === "SQLITE_CANTOPEN";
|
|
11701
|
+
if (importedPath !== void 0 && cantOpen) {
|
|
11702
|
+
logger.warn(
|
|
11703
|
+
{ key: source.key, path: path2 },
|
|
11704
|
+
"deprecated store file cannot be opened to lock it; its rows are already imported"
|
|
11705
|
+
);
|
|
11706
|
+
continue;
|
|
11707
|
+
}
|
|
11708
|
+
throw storageError(
|
|
11709
|
+
cantOpen ? `${source.key} "${path2}" cannot be opened to import it, as on a read-only mount. Make its directory writable for the first start of this version, or copy the file somewhere writable and point the key at the copy.` : `${source.key} "${path2}" cannot be locked for import: ${cause instanceof Error ? cause.message : String(cause)}`,
|
|
11710
|
+
{ key: source.key, path: path2 },
|
|
11711
|
+
cause
|
|
11712
|
+
);
|
|
11713
|
+
}
|
|
11714
|
+
locks.push(file);
|
|
11715
|
+
if (importedPath !== void 0) continue;
|
|
11716
|
+
let imported;
|
|
11717
|
+
try {
|
|
11718
|
+
imported = source.read(file, logger);
|
|
11719
|
+
} catch (cause) {
|
|
11720
|
+
throw storageError(
|
|
11721
|
+
`${source.key} "${path2}" cannot be read for import: ${cause instanceof Error ? cause.message : String(cause)}`,
|
|
11722
|
+
{ key: source.key, path: path2 },
|
|
11723
|
+
cause
|
|
11724
|
+
);
|
|
11725
|
+
}
|
|
11726
|
+
db.transaction(() => {
|
|
11727
|
+
imported.write(db);
|
|
11728
|
+
recordMarker.run(source.name, path2, imported.rows, clock.nowIso());
|
|
11729
|
+
})();
|
|
11730
|
+
logger.info(
|
|
11731
|
+
{ key: source.key, path: path2, rows: imported.rows },
|
|
11732
|
+
"imported deprecated store file; it stays locked against writes while this gateway runs"
|
|
11733
|
+
);
|
|
11734
|
+
}
|
|
11735
|
+
} catch (err) {
|
|
11736
|
+
release();
|
|
11737
|
+
throw toCommerceError(err, "STORAGE_ERROR", "Failed to import deprecated store files");
|
|
11738
|
+
}
|
|
11739
|
+
return release;
|
|
11740
|
+
}
|
|
11741
|
+
function forgottenKey(source, path2) {
|
|
11742
|
+
return storageError(
|
|
11743
|
+
`${source.feature.toUpperCase()} ran on this receipt database before, but ${source.key} ${path2 === void 0 ? "is not set" : `names a missing file "${path2}"`}, so its records would be lost. Set ${source.key} to the file the previous version used to import them, or to an empty file to accept the loss.`,
|
|
11744
|
+
{ key: source.key, ...path2 !== void 0 ? { path: path2 } : {} }
|
|
11745
|
+
);
|
|
11746
|
+
}
|
|
11747
|
+
|
|
11748
|
+
// src/storage/receipts/params.ts
|
|
11031
11749
|
var DEFAULT_LIST_LIMIT = 50;
|
|
11032
11750
|
var MAX_LIST_LIMIT = 500;
|
|
11033
11751
|
function clampListLimit(limit) {
|
|
11034
11752
|
const base = limit !== void 0 && Number.isFinite(limit) ? limit : DEFAULT_LIST_LIMIT;
|
|
11035
11753
|
return Math.min(Math.max(Math.trunc(base), 1), MAX_LIST_LIMIT);
|
|
11036
11754
|
}
|
|
11755
|
+
function storedIso(value, field) {
|
|
11756
|
+
const ms = Date.parse(value);
|
|
11757
|
+
if (!Number.isFinite(ms)) {
|
|
11758
|
+
throw new CommerceError("STORAGE_ERROR", `${field} is not a valid timestamp`);
|
|
11759
|
+
}
|
|
11760
|
+
return new Date(ms).toISOString();
|
|
11761
|
+
}
|
|
11762
|
+
|
|
11763
|
+
// src/storage/receipts/redact.ts
|
|
11764
|
+
var SECRET_KEY_PATTERN = /private[-_ ]?key|secret|password|mnemonic|seed[-_ ]?phrase|api[-_ ]?key|authoriz(e|ation)|^auth$|auth[-_]?header|payment[-_ ]?proof|^proof$|x-payment|signature|signed[-_ ]?message|token|bearer|credential|cookie|session|jwt/i;
|
|
11765
|
+
var REDACTED = "[REDACTED]";
|
|
11766
|
+
function isSecretKey(key) {
|
|
11767
|
+
return SECRET_KEY_PATTERN.test(key);
|
|
11768
|
+
}
|
|
11769
|
+
function redact(value) {
|
|
11770
|
+
return redactValue(value);
|
|
11771
|
+
}
|
|
11772
|
+
function redactValue(value) {
|
|
11773
|
+
if (Array.isArray(value)) {
|
|
11774
|
+
return value.map(redactValue);
|
|
11775
|
+
}
|
|
11776
|
+
if (value !== null && typeof value === "object") {
|
|
11777
|
+
const out = {};
|
|
11778
|
+
for (const [key, inner] of Object.entries(value)) {
|
|
11779
|
+
out[key] = isSecretKey(key) ? REDACTED : redactValue(inner);
|
|
11780
|
+
}
|
|
11781
|
+
return out;
|
|
11782
|
+
}
|
|
11783
|
+
return value;
|
|
11784
|
+
}
|
|
11785
|
+
|
|
11786
|
+
// src/storage/receipts/holds.ts
|
|
11787
|
+
var TRANSITION_TARGETS = /* @__PURE__ */ new Set(["consumed", "released", "uncertain"]);
|
|
11788
|
+
var ORPHAN_HOLD_WHERE = `h.state = 'reserved' AND h.updated_at < ?
|
|
11789
|
+
AND NOT EXISTS (SELECT 1 FROM payment_attempts a WHERE a.request_id = h.request_id)
|
|
11790
|
+
AND NOT EXISTS (SELECT 1 FROM payment_attempt_history p WHERE p.request_id = h.request_id)`;
|
|
11791
|
+
function rowToHold(row) {
|
|
11792
|
+
return {
|
|
11793
|
+
method: row.method,
|
|
11794
|
+
reference: row.reference,
|
|
11795
|
+
bindingReference: row.binding_reference,
|
|
11796
|
+
resourceId: row.resource_id,
|
|
11797
|
+
requestId: row.request_id,
|
|
11798
|
+
...row.metadata_json !== null ? { metadata: JSON.parse(row.metadata_json) } : {},
|
|
11799
|
+
state: row.state,
|
|
11800
|
+
createdAt: row.created_at,
|
|
11801
|
+
updatedAt: row.updated_at
|
|
11802
|
+
};
|
|
11803
|
+
}
|
|
11804
|
+
function createHoldMethods(db, clock) {
|
|
11805
|
+
const selectHold = db.prepare(
|
|
11806
|
+
"SELECT * FROM authorization_holds WHERE reference = ?"
|
|
11807
|
+
);
|
|
11808
|
+
const selectLiveBinding = db.prepare(
|
|
11809
|
+
`SELECT state FROM authorization_holds
|
|
11810
|
+
WHERE binding_reference = ? AND reference != ? AND state != 'released' LIMIT 1`
|
|
11811
|
+
);
|
|
11812
|
+
const insertHold = db.prepare(
|
|
11813
|
+
`INSERT INTO authorization_holds
|
|
11814
|
+
(reference, method, binding_reference, resource_id, request_id, state, metadata_json, created_at, updated_at)
|
|
11815
|
+
VALUES (@reference, @method, @binding_reference, @resource_id, @request_id, 'reserved', @metadata_json, @at, @at)`
|
|
11816
|
+
);
|
|
11817
|
+
const reReserveHold = db.prepare(
|
|
11818
|
+
`UPDATE authorization_holds
|
|
11819
|
+
SET state = 'reserved', method = @method, binding_reference = @binding_reference,
|
|
11820
|
+
resource_id = @resource_id, request_id = @request_id,
|
|
11821
|
+
metadata_json = @metadata_json, updated_at = @at
|
|
11822
|
+
WHERE reference = @reference AND state = 'released'`
|
|
11823
|
+
);
|
|
11824
|
+
const transitionHold = db.prepare(
|
|
11825
|
+
`UPDATE authorization_holds SET state = @state, updated_at = @at
|
|
11826
|
+
WHERE reference = @reference AND state IN ('reserved', 'uncertain')
|
|
11827
|
+
AND (@request_id IS NULL OR request_id = @request_id)`
|
|
11828
|
+
);
|
|
11829
|
+
const listOrphans = db.prepare(
|
|
11830
|
+
`SELECT h.* FROM authorization_holds h WHERE ${ORPHAN_HOLD_WHERE}
|
|
11831
|
+
ORDER BY h.updated_at, h.reference LIMIT ?`
|
|
11832
|
+
);
|
|
11833
|
+
const reserve = db.transaction(
|
|
11834
|
+
(reservation) => {
|
|
11835
|
+
const existing = selectHold.get(reservation.reference);
|
|
11836
|
+
if (existing !== void 0 && existing.state !== "released") {
|
|
11837
|
+
return { kind: "replayed", state: existing.state };
|
|
11838
|
+
}
|
|
11839
|
+
const binding = selectLiveBinding.get(reservation.bindingReference, reservation.reference);
|
|
11840
|
+
if (binding !== void 0) {
|
|
11841
|
+
return { kind: "replayed", state: binding.state };
|
|
11842
|
+
}
|
|
11843
|
+
const params = {
|
|
11844
|
+
reference: reservation.reference,
|
|
11845
|
+
method: reservation.method,
|
|
11846
|
+
binding_reference: reservation.bindingReference,
|
|
11847
|
+
resource_id: reservation.resourceId,
|
|
11848
|
+
request_id: reservation.requestId,
|
|
11849
|
+
metadata_json: reservation.metadata !== void 0 ? JSON.stringify(redact(reservation.metadata)) : null,
|
|
11850
|
+
at: clock.nowIso()
|
|
11851
|
+
};
|
|
11852
|
+
(existing !== void 0 ? reReserveHold : insertHold).run(params);
|
|
11853
|
+
return { kind: "reserved" };
|
|
11854
|
+
}
|
|
11855
|
+
);
|
|
11856
|
+
const transition = db.transaction(
|
|
11857
|
+
(reference, to, requestId) => {
|
|
11858
|
+
const { changes } = transitionHold.run({
|
|
11859
|
+
reference,
|
|
11860
|
+
state: to,
|
|
11861
|
+
request_id: requestId ?? null,
|
|
11862
|
+
at: clock.nowIso()
|
|
11863
|
+
});
|
|
11864
|
+
if (changes > 0) return true;
|
|
11865
|
+
const row = selectHold.get(reference);
|
|
11866
|
+
if (row === void 0) return false;
|
|
11867
|
+
if (requestId !== void 0 && row.request_id !== requestId) return to === "released";
|
|
11868
|
+
return row.state === to;
|
|
11869
|
+
}
|
|
11870
|
+
);
|
|
11871
|
+
return {
|
|
11872
|
+
async reserveAuthorizationHold(reservation) {
|
|
11873
|
+
try {
|
|
11874
|
+
return reserve.immediate(reservation);
|
|
11875
|
+
} catch (err) {
|
|
11876
|
+
throw toCommerceError(err, "STORAGE_ERROR", "Failed to reserve authorization hold");
|
|
11877
|
+
}
|
|
11878
|
+
},
|
|
11879
|
+
async transitionAuthorizationHold(reference, to, requestId) {
|
|
11880
|
+
try {
|
|
11881
|
+
if (!TRANSITION_TARGETS.has(to)) {
|
|
11882
|
+
throw new CommerceError("STORAGE_ERROR", `Invalid authorization hold target: ${to}`);
|
|
11883
|
+
}
|
|
11884
|
+
return transition.immediate(reference, to, requestId);
|
|
11885
|
+
} catch (err) {
|
|
11886
|
+
throw toCommerceError(err, "STORAGE_ERROR", "Failed to update authorization hold");
|
|
11887
|
+
}
|
|
11888
|
+
},
|
|
11889
|
+
async getAuthorizationHoldState(reference) {
|
|
11890
|
+
return selectHold.get(reference)?.state;
|
|
11891
|
+
},
|
|
11892
|
+
async listOrphanAuthorizationHolds(options) {
|
|
11893
|
+
const before = storedIso(options.updatedBefore, "updatedBefore");
|
|
11894
|
+
return listOrphans.all(before, clampListLimit(options.limit)).map(rowToHold);
|
|
11895
|
+
}
|
|
11896
|
+
};
|
|
11897
|
+
}
|
|
11898
|
+
|
|
11899
|
+
// src/storage/receipts/idempotency.ts
|
|
11900
|
+
var ENDPOINT_HAS_PREFIX = "substr(endpoint, 1, length(@prefix)) = @prefix";
|
|
11901
|
+
var scopeParams = (scope) => ({
|
|
11902
|
+
deployment: scope.deployment,
|
|
11903
|
+
endpoint: scope.endpoint,
|
|
11904
|
+
idempotency_key: scope.key
|
|
11905
|
+
});
|
|
11906
|
+
function claimOf(row, fingerprint) {
|
|
11907
|
+
if (row.fingerprint !== fingerprint) return { kind: "conflict" };
|
|
11908
|
+
const body = row.body_json === null ? null : JSON.parse(row.body_json);
|
|
11909
|
+
if (row.state === "completed") return { kind: "replay", status: row.status ?? 500, body };
|
|
11910
|
+
const kind = row.state === "unresolved" ? "unresolved" : "in-flight";
|
|
11911
|
+
const owner = isRecord(body) ? body["owner"] : void 0;
|
|
11912
|
+
return typeof owner === "string" ? { kind, owner } : { kind };
|
|
11913
|
+
}
|
|
11914
|
+
function hasExpired(row, endpoint, now) {
|
|
11915
|
+
if (row.expires_at > now) return false;
|
|
11916
|
+
return row.state === "completed" || row.state === "unresolved" && endpoint.startsWith(PAYMENT_KEY_ENDPOINT_PREFIX);
|
|
11917
|
+
}
|
|
11918
|
+
function createIdempotencyMethods(db, clock) {
|
|
11919
|
+
const SCOPE = "deployment = @deployment AND endpoint = @endpoint AND idempotency_key = @idempotency_key";
|
|
11920
|
+
const selectClaim = db.prepare(
|
|
11921
|
+
`SELECT state, fingerprint, status, body_json, expires_at FROM idempotency_keys WHERE ${SCOPE}`
|
|
11922
|
+
);
|
|
11923
|
+
const insertClaim = db.prepare(
|
|
11924
|
+
`INSERT INTO idempotency_keys
|
|
11925
|
+
(deployment, endpoint, idempotency_key, fingerprint, state, body_json, created_at, expires_at)
|
|
11926
|
+
VALUES (@deployment, @endpoint, @idempotency_key, @fingerprint, 'in_flight', @body_json, @created_at, @expires_at)`
|
|
11927
|
+
);
|
|
11928
|
+
const expireFinished = db.prepare(
|
|
11929
|
+
`DELETE FROM idempotency_keys WHERE expires_at <= @now
|
|
11930
|
+
AND (state = 'completed' OR (state = 'unresolved' AND ${ENDPOINT_HAS_PREFIX}))`
|
|
11931
|
+
);
|
|
11932
|
+
const completeClaim = db.prepare(
|
|
11933
|
+
`UPDATE idempotency_keys SET state = 'completed', status = @status, body_json = @body_json
|
|
11934
|
+
WHERE ${SCOPE}`
|
|
11935
|
+
);
|
|
11936
|
+
const markUnresolved = db.prepare(
|
|
11937
|
+
`UPDATE idempotency_keys SET state = 'unresolved' WHERE ${SCOPE}`
|
|
11938
|
+
);
|
|
11939
|
+
const deleteClaim = db.prepare(`DELETE FROM idempotency_keys WHERE ${SCOPE}`);
|
|
11940
|
+
const IN_FLIGHT = `state = 'in_flight' AND ${ENDPOINT_HAS_PREFIX}`;
|
|
11941
|
+
const releaseInFlight = db.prepare(`DELETE FROM idempotency_keys WHERE ${IN_FLIGHT}`);
|
|
11942
|
+
const unresolveInFlight = db.prepare(
|
|
11943
|
+
`UPDATE idempotency_keys SET state = 'unresolved' WHERE ${IN_FLIGHT}`
|
|
11944
|
+
);
|
|
11945
|
+
const claim = db.transaction(
|
|
11946
|
+
(scope, fingerprint, expiresAt, owner) => {
|
|
11947
|
+
const now = clock.nowIso();
|
|
11948
|
+
expireFinished.run({ now, prefix: PAYMENT_KEY_ENDPOINT_PREFIX });
|
|
11949
|
+
const existing = selectClaim.get(scopeParams(scope));
|
|
11950
|
+
if (existing === void 0) {
|
|
11951
|
+
insertClaim.run({
|
|
11952
|
+
...scopeParams(scope),
|
|
11953
|
+
fingerprint,
|
|
11954
|
+
body_json: owner !== void 0 ? JSON.stringify({ owner }) : null,
|
|
11955
|
+
created_at: now,
|
|
11956
|
+
expires_at: expiresAt
|
|
11957
|
+
});
|
|
11958
|
+
return { kind: "reserved" };
|
|
11959
|
+
}
|
|
11960
|
+
return claimOf(existing, fingerprint);
|
|
11961
|
+
}
|
|
11962
|
+
);
|
|
11963
|
+
return {
|
|
11964
|
+
async claimIdempotencyKey(scope, fingerprint, expiresAt, owner) {
|
|
11965
|
+
try {
|
|
11966
|
+
return claim.immediate(scope, fingerprint, storedIso(expiresAt, "expiresAt"), owner);
|
|
11967
|
+
} catch (err) {
|
|
11968
|
+
throw toCommerceError(err, "STORAGE_ERROR", "Failed to claim idempotency key");
|
|
11969
|
+
}
|
|
11970
|
+
},
|
|
11971
|
+
async getIdempotencyKey(scope, fingerprint) {
|
|
11972
|
+
try {
|
|
11973
|
+
const existing = selectClaim.get(scopeParams(scope));
|
|
11974
|
+
if (existing === void 0) return void 0;
|
|
11975
|
+
return hasExpired(existing, scope.endpoint, clock.nowIso()) ? void 0 : claimOf(existing, fingerprint);
|
|
11976
|
+
} catch (err) {
|
|
11977
|
+
throw toCommerceError(err, "STORAGE_ERROR", "Failed to read idempotency key");
|
|
11978
|
+
}
|
|
11979
|
+
},
|
|
11980
|
+
async updateIdempotencyKey(scope, update) {
|
|
11981
|
+
try {
|
|
11982
|
+
switch (update.kind) {
|
|
11983
|
+
case "completed":
|
|
11984
|
+
completeClaim.run({
|
|
11985
|
+
...scopeParams(scope),
|
|
11986
|
+
status: update.status,
|
|
11987
|
+
body_json: JSON.stringify(update.body ?? null)
|
|
11988
|
+
});
|
|
11989
|
+
break;
|
|
11990
|
+
case "unresolved":
|
|
11991
|
+
markUnresolved.run(scopeParams(scope));
|
|
11992
|
+
break;
|
|
11993
|
+
case "released":
|
|
11994
|
+
deleteClaim.run(scopeParams(scope));
|
|
11995
|
+
break;
|
|
11996
|
+
}
|
|
11997
|
+
} catch (err) {
|
|
11998
|
+
throw toCommerceError(err, "STORAGE_ERROR", "Failed to update idempotency key");
|
|
11999
|
+
}
|
|
12000
|
+
},
|
|
12001
|
+
async recoverIdempotencyKeys({ release, endpointPrefix = "" }) {
|
|
12002
|
+
try {
|
|
12003
|
+
const recover = release ? releaseInFlight : unresolveInFlight;
|
|
12004
|
+
return recover.run({ prefix: endpointPrefix }).changes;
|
|
12005
|
+
} catch (err) {
|
|
12006
|
+
throw toCommerceError(err, "STORAGE_ERROR", "Failed to recover idempotency keys");
|
|
12007
|
+
}
|
|
12008
|
+
}
|
|
12009
|
+
};
|
|
12010
|
+
}
|
|
12011
|
+
|
|
12012
|
+
// src/storage/receipts/pending-tasks.ts
|
|
12013
|
+
function rowToTask(row) {
|
|
12014
|
+
return {
|
|
12015
|
+
id: row.id,
|
|
12016
|
+
protocol: row.protocol,
|
|
12017
|
+
resourceId: row.resource_id,
|
|
12018
|
+
input: JSON.parse(row.input_json),
|
|
12019
|
+
...row.adapter_data_json !== null ? { adapterData: JSON.parse(row.adapter_data_json) } : {},
|
|
12020
|
+
expiresAt: row.expires_at
|
|
12021
|
+
};
|
|
12022
|
+
}
|
|
12023
|
+
function withoutReservedFields(input) {
|
|
12024
|
+
return Object.fromEntries(
|
|
12025
|
+
Object.entries(input).filter(([key]) => !RESERVED_INPUT_FIELDS.includes(key))
|
|
12026
|
+
);
|
|
12027
|
+
}
|
|
12028
|
+
var SWEEP_EXPIRED = "DELETE FROM pending_tasks WHERE expires_at <= ?";
|
|
12029
|
+
function sweepExpiredPendingTasks(db, now) {
|
|
12030
|
+
db.prepare(SWEEP_EXPIRED).run(now);
|
|
12031
|
+
}
|
|
12032
|
+
function createPendingTaskMethods(db, clock) {
|
|
12033
|
+
const sweepExpired = db.prepare(SWEEP_EXPIRED);
|
|
12034
|
+
const countLive = db.prepare(
|
|
12035
|
+
"SELECT COUNT(*) AS count FROM pending_tasks WHERE expires_at > ?"
|
|
12036
|
+
);
|
|
12037
|
+
const upsertTask = db.prepare(
|
|
12038
|
+
`INSERT OR REPLACE INTO pending_tasks
|
|
12039
|
+
(id, protocol, resource_id, input_json, adapter_data_json, created_at, expires_at)
|
|
12040
|
+
VALUES (@id, @protocol, @resource_id, @input_json, @adapter_data_json, @created_at, @expires_at)`
|
|
12041
|
+
);
|
|
12042
|
+
const selectLive = db.prepare(
|
|
12043
|
+
"SELECT * FROM pending_tasks WHERE id = ? AND expires_at > ?"
|
|
12044
|
+
);
|
|
12045
|
+
const takeLive = db.prepare(
|
|
12046
|
+
"DELETE FROM pending_tasks WHERE id = ? AND expires_at > ? RETURNING *"
|
|
12047
|
+
);
|
|
12048
|
+
const put = db.transaction((task2, maxTasks, expiresAt) => {
|
|
12049
|
+
const now = clock.nowIso();
|
|
12050
|
+
sweepExpired.run(now);
|
|
12051
|
+
if ((countLive.get(now)?.count ?? 0) >= maxTasks) return false;
|
|
12052
|
+
upsertTask.run({
|
|
12053
|
+
id: task2.id,
|
|
12054
|
+
protocol: task2.protocol,
|
|
12055
|
+
resource_id: task2.resourceId,
|
|
12056
|
+
input_json: JSON.stringify(withoutReservedFields(task2.input)),
|
|
12057
|
+
adapter_data_json: task2.adapterData !== void 0 ? JSON.stringify(task2.adapterData) : null,
|
|
12058
|
+
created_at: now,
|
|
12059
|
+
expires_at: expiresAt
|
|
12060
|
+
});
|
|
12061
|
+
return true;
|
|
12062
|
+
});
|
|
12063
|
+
return {
|
|
12064
|
+
async putPendingTask(task2, options) {
|
|
12065
|
+
try {
|
|
12066
|
+
if (!Number.isInteger(options.maxTasks) || options.maxTasks < 0) {
|
|
12067
|
+
throw new CommerceError("STORAGE_ERROR", "maxTasks must be a non-negative integer");
|
|
12068
|
+
}
|
|
12069
|
+
return put.immediate(task2, options.maxTasks, storedIso(task2.expiresAt, "expiresAt"));
|
|
12070
|
+
} catch (err) {
|
|
12071
|
+
throw toCommerceError(err, "STORAGE_ERROR", "Failed to store pending task");
|
|
12072
|
+
}
|
|
12073
|
+
},
|
|
12074
|
+
async getPendingTask(id) {
|
|
12075
|
+
const row = selectLive.get(id, clock.nowIso());
|
|
12076
|
+
return row !== void 0 ? rowToTask(row) : void 0;
|
|
12077
|
+
},
|
|
12078
|
+
async takePendingTask(id) {
|
|
12079
|
+
try {
|
|
12080
|
+
const now = clock.nowIso();
|
|
12081
|
+
sweepExpired.run(now);
|
|
12082
|
+
const row = takeLive.get(id, now);
|
|
12083
|
+
return row !== void 0 ? rowToTask(row) : void 0;
|
|
12084
|
+
} catch (err) {
|
|
12085
|
+
throw toCommerceError(err, "STORAGE_ERROR", "Failed to take pending task");
|
|
12086
|
+
}
|
|
12087
|
+
}
|
|
12088
|
+
};
|
|
12089
|
+
}
|
|
12090
|
+
|
|
12091
|
+
// src/storage/receipts/rows.ts
|
|
12092
|
+
function receiptToRow(receipt) {
|
|
12093
|
+
return {
|
|
12094
|
+
id: receipt.id,
|
|
12095
|
+
request_id: receipt.requestId,
|
|
12096
|
+
resource_id: receipt.resourceId,
|
|
12097
|
+
payment_json: receipt.payment !== void 0 ? JSON.stringify(redact(receipt.payment)) : null,
|
|
12098
|
+
delivered_at: receipt.deliveredAt,
|
|
12099
|
+
backend_status: receipt.backendStatus,
|
|
12100
|
+
duration_ms: receipt.durationMs ?? null,
|
|
12101
|
+
protocol: receipt.protocol ?? null,
|
|
12102
|
+
metadata_json: receipt.metadata !== void 0 ? JSON.stringify(redact(receipt.metadata)) : null,
|
|
12103
|
+
authorization_json: receipt.authorization !== void 0 ? JSON.stringify(redact(receipt.authorization)) : null,
|
|
12104
|
+
transaction_id: receipt.transactionId ?? null
|
|
12105
|
+
};
|
|
12106
|
+
}
|
|
12107
|
+
function rowToReceipt(row) {
|
|
12108
|
+
const payment = row.payment_json !== null ? JSON.parse(row.payment_json) : void 0;
|
|
12109
|
+
const metadata = row.metadata_json !== null ? JSON.parse(row.metadata_json) : void 0;
|
|
12110
|
+
const authorization = row.authorization_json !== null ? JSON.parse(row.authorization_json) : void 0;
|
|
12111
|
+
return {
|
|
12112
|
+
id: row.id,
|
|
12113
|
+
requestId: row.request_id,
|
|
12114
|
+
resourceId: row.resource_id,
|
|
12115
|
+
deliveredAt: row.delivered_at,
|
|
12116
|
+
backendStatus: row.backend_status,
|
|
12117
|
+
...payment !== void 0 ? { payment } : {},
|
|
12118
|
+
...row.duration_ms !== null ? { durationMs: row.duration_ms } : {},
|
|
12119
|
+
...row.protocol !== null ? { protocol: row.protocol } : {},
|
|
12120
|
+
...metadata !== void 0 ? { metadata } : {},
|
|
12121
|
+
...authorization !== void 0 ? { authorization } : {},
|
|
12122
|
+
...row.transaction_id !== null ? { transactionId: row.transaction_id } : {}
|
|
12123
|
+
};
|
|
12124
|
+
}
|
|
12125
|
+
function eventToRow(event) {
|
|
12126
|
+
return {
|
|
12127
|
+
id: event.id,
|
|
12128
|
+
type: event.type,
|
|
12129
|
+
request_id: event.requestId,
|
|
12130
|
+
resource_id: event.resourceId ?? null,
|
|
12131
|
+
at: event.at,
|
|
12132
|
+
adapter: event.adapter ?? null,
|
|
12133
|
+
payment_provider: event.paymentProvider ?? null,
|
|
12134
|
+
duration_ms: event.durationMs ?? null,
|
|
12135
|
+
status: event.status ?? null,
|
|
12136
|
+
data_json: event.data !== void 0 ? JSON.stringify(redact(event.data)) : null,
|
|
12137
|
+
transaction_id: event.transactionId ?? null
|
|
12138
|
+
};
|
|
12139
|
+
}
|
|
12140
|
+
function rowToEvent(row) {
|
|
12141
|
+
const data = row.data_json !== null ? JSON.parse(row.data_json) : void 0;
|
|
12142
|
+
return {
|
|
12143
|
+
id: row.id,
|
|
12144
|
+
type: row.type,
|
|
12145
|
+
requestId: row.request_id,
|
|
12146
|
+
at: row.at,
|
|
12147
|
+
...row.resource_id !== null ? { resourceId: row.resource_id } : {},
|
|
12148
|
+
...row.adapter !== null ? { adapter: row.adapter } : {},
|
|
12149
|
+
...row.payment_provider !== null ? { paymentProvider: row.payment_provider } : {},
|
|
12150
|
+
...row.duration_ms !== null ? { durationMs: row.duration_ms } : {},
|
|
12151
|
+
...row.status !== null ? { status: row.status } : {},
|
|
12152
|
+
...data !== void 0 ? { data } : {},
|
|
12153
|
+
...row.transaction_id !== null ? { transactionId: row.transaction_id } : {}
|
|
12154
|
+
};
|
|
12155
|
+
}
|
|
12156
|
+
function rowToPaymentAttempt(row) {
|
|
12157
|
+
return {
|
|
12158
|
+
id: row.id,
|
|
12159
|
+
requestId: row.request_id,
|
|
12160
|
+
resourceId: row.resource_id,
|
|
12161
|
+
provider: row.provider,
|
|
12162
|
+
replayKey: row.replay_key,
|
|
12163
|
+
status: row.status,
|
|
12164
|
+
amount: row.amount,
|
|
12165
|
+
currency: row.currency,
|
|
12166
|
+
...row.payer !== null ? { payer: row.payer } : {},
|
|
12167
|
+
...row.payee !== null ? { payee: row.payee } : {},
|
|
12168
|
+
...row.external_reference !== null ? { externalReference: row.external_reference } : {},
|
|
12169
|
+
...row.rejection_reason !== null ? { rejectionReason: row.rejection_reason } : {},
|
|
12170
|
+
createdAt: row.created_at,
|
|
12171
|
+
updatedAt: row.updated_at,
|
|
12172
|
+
...row.transaction_id !== null ? { transactionId: row.transaction_id } : {},
|
|
12173
|
+
...row.resolution_json !== null ? { resolution: JSON.parse(row.resolution_json) } : {}
|
|
12174
|
+
};
|
|
12175
|
+
}
|
|
12176
|
+
function rowToTransaction(row, now) {
|
|
12177
|
+
const status = row.payment_status;
|
|
12178
|
+
const backend = row.backend_dispatched_at !== null && row.backend_deadline_at !== null ? {
|
|
12179
|
+
dispatchedAt: row.backend_dispatched_at,
|
|
12180
|
+
deadlineAt: row.backend_deadline_at,
|
|
12181
|
+
...row.backend_status !== null ? { status: row.backend_status } : {},
|
|
12182
|
+
...row.backend_error_code !== null ? { errorCode: row.backend_error_code } : {}
|
|
12183
|
+
} : void 0;
|
|
12184
|
+
const completedAt = row.completed_at ?? void 0;
|
|
12185
|
+
const authorization = row.authorization_json !== null && row.reservation_id !== null ? {
|
|
12186
|
+
...JSON.parse(row.authorization_json),
|
|
12187
|
+
reservationId: row.reservation_id
|
|
12188
|
+
} : void 0;
|
|
12189
|
+
return {
|
|
12190
|
+
id: row.id,
|
|
12191
|
+
requestId: row.request_id,
|
|
12192
|
+
resourceId: row.resource_id,
|
|
12193
|
+
protocol: row.protocol,
|
|
12194
|
+
state: transactionState(
|
|
12195
|
+
{
|
|
12196
|
+
payment: { status },
|
|
12197
|
+
...backend !== void 0 ? { backend } : {},
|
|
12198
|
+
...completedAt !== void 0 ? { completedAt } : {}
|
|
12199
|
+
},
|
|
12200
|
+
now
|
|
12201
|
+
),
|
|
12202
|
+
payment: {
|
|
12203
|
+
provider: row.provider,
|
|
12204
|
+
attemptId: row.attempt_id,
|
|
12205
|
+
replayKey: row.replay_key,
|
|
12206
|
+
status,
|
|
12207
|
+
amount: row.payment_amount,
|
|
12208
|
+
currency: row.payment_currency,
|
|
12209
|
+
...row.network !== null ? { network: row.network } : {},
|
|
12210
|
+
...row.asset !== null ? { asset: row.asset } : {},
|
|
12211
|
+
...row.payment_payee !== null ? { payee: row.payment_payee } : {},
|
|
12212
|
+
...row.payment_external_reference !== null ? { externalReference: row.payment_external_reference } : {},
|
|
12213
|
+
...row.locator_json !== null ? { locator: JSON.parse(row.locator_json) } : {},
|
|
12214
|
+
...row.settling_at !== null ? { settlingAt: row.settling_at } : {},
|
|
12215
|
+
...row.expires_at !== null ? { expiresAt: row.expires_at } : {}
|
|
12216
|
+
},
|
|
12217
|
+
...authorization !== void 0 ? { authorization } : {},
|
|
12218
|
+
...backend !== void 0 ? { backend } : {},
|
|
12219
|
+
...row.receipt_id !== null ? { receiptId: row.receipt_id } : {},
|
|
12220
|
+
...row.input_digest !== null ? { inputDigest: row.input_digest } : {},
|
|
12221
|
+
configDigest: row.config_digest,
|
|
12222
|
+
...row.persistence_failures_json !== null ? { persistenceFailures: JSON.parse(row.persistence_failures_json) } : {},
|
|
12223
|
+
createdAt: row.created_at,
|
|
12224
|
+
updatedAt: row.updated_at,
|
|
12225
|
+
...completedAt !== void 0 ? { completedAt } : {}
|
|
12226
|
+
};
|
|
12227
|
+
}
|
|
12228
|
+
|
|
12229
|
+
// src/storage/receipts/store.ts
|
|
11037
12230
|
var UNDELIVERED = "backend_status NOT BETWEEN 200 AND 299";
|
|
11038
12231
|
var UNCERTAIN = "status IN ('settlement-uncertain', 'failed')";
|
|
11039
12232
|
var TRANSACTION_SELECT = `
|
|
@@ -11059,13 +12252,20 @@ function isUniqueConstraintOn(err, column) {
|
|
|
11059
12252
|
return err instanceof Error && "code" in err && err.code === "SQLITE_CONSTRAINT_UNIQUE" && err.message.includes(column);
|
|
11060
12253
|
}
|
|
11061
12254
|
function createSqliteReceiptStore(options) {
|
|
12255
|
+
const db = openSqliteDatabase({
|
|
12256
|
+
path: options.path,
|
|
12257
|
+
label: "Receipt database",
|
|
12258
|
+
logger: options.logger ?? NOOP_LOGGER
|
|
12259
|
+
});
|
|
12260
|
+
migrate2(db);
|
|
12261
|
+
return storeOn(db, options);
|
|
12262
|
+
}
|
|
12263
|
+
function storeOn(db, options) {
|
|
11062
12264
|
const logger = options.logger ?? NOOP_LOGGER;
|
|
11063
12265
|
const clock = options.clock ?? systemClock;
|
|
11064
12266
|
const ids = options.ids ?? defaultIds;
|
|
11065
12267
|
const path2 = options.path;
|
|
11066
12268
|
const isFileBacked = path2 !== ":memory:";
|
|
11067
|
-
const db = openSqliteDatabase({ path: path2, label: "Receipt database", logger });
|
|
11068
|
-
migrate2(db);
|
|
11069
12269
|
const insertReceiptStmt = db.prepare(
|
|
11070
12270
|
`INSERT INTO receipts (id, request_id, resource_id, payment_json, delivered_at, backend_status, duration_ms, protocol, metadata_json, authorization_json, transaction_id)
|
|
11071
12271
|
VALUES (@id, @request_id, @resource_id, @payment_json, @delivered_at, @backend_status, @duration_ms, @protocol, @metadata_json, @authorization_json, @transaction_id)`
|
|
@@ -11195,6 +12395,9 @@ function createSqliteReceiptStore(options) {
|
|
|
11195
12395
|
const getArchivedPaymentAttemptStmt = db.prepare(
|
|
11196
12396
|
"SELECT * FROM payment_attempt_history WHERE id = ? ORDER BY seq DESC LIMIT 1"
|
|
11197
12397
|
);
|
|
12398
|
+
const paymentAttemptByReplayKeyStmt = db.prepare(
|
|
12399
|
+
"SELECT * FROM payment_attempts WHERE replay_key = ?"
|
|
12400
|
+
);
|
|
11198
12401
|
const resolvePaymentAttemptStmt = db.prepare(
|
|
11199
12402
|
`UPDATE payment_attempts SET status = @status,
|
|
11200
12403
|
rejection_reason = COALESCE(@rejection_reason, rejection_reason),
|
|
@@ -11313,13 +12516,39 @@ function createSqliteReceiptStore(options) {
|
|
|
11313
12516
|
return true;
|
|
11314
12517
|
}
|
|
11315
12518
|
);
|
|
12519
|
+
const unresolvedTransactionsStmt = db.prepare(
|
|
12520
|
+
`${TRANSACTION_SELECT} WHERE t.state NOT IN (?, ?)`
|
|
12521
|
+
);
|
|
12522
|
+
const countOrphanHoldsStmt = db.prepare(
|
|
12523
|
+
`SELECT COUNT(*) AS count FROM authorization_holds h WHERE ${ORPHAN_HOLD_WHERE}`
|
|
12524
|
+
);
|
|
12525
|
+
const countUnresolvedKeysStmt = db.prepare(
|
|
12526
|
+
`SELECT COUNT(*) FILTER (WHERE ${ENDPOINT_HAS_PREFIX} AND expires_at > @now) AS payment,
|
|
12527
|
+
COUNT(*) FILTER (WHERE NOT ${ENDPOINT_HAS_PREFIX}) AS other
|
|
12528
|
+
FROM idempotency_keys WHERE state = 'unresolved'`
|
|
12529
|
+
);
|
|
12530
|
+
const countLiveTasksStmt = db.prepare(
|
|
12531
|
+
"SELECT COUNT(*) AS count FROM pending_tasks WHERE expires_at > ?"
|
|
12532
|
+
);
|
|
12533
|
+
const legacyImportsStmt = db.prepare(
|
|
12534
|
+
"SELECT source, path, rows, imported_at FROM legacy_imports WHERE path IS NOT NULL ORDER BY source"
|
|
12535
|
+
);
|
|
11316
12536
|
let closed = false;
|
|
12537
|
+
let releaseLegacyLocks;
|
|
11317
12538
|
const descriptor = {
|
|
11318
12539
|
name: "sqlite-receipt-store",
|
|
11319
12540
|
kind: "storage",
|
|
11320
12541
|
implementationVersion: PACKAGE_VERSION,
|
|
11321
12542
|
supportedSpec: `sqlite-schema-v${SCHEMA_VERSION2}`,
|
|
11322
|
-
capabilities: [
|
|
12543
|
+
capabilities: [
|
|
12544
|
+
"receipts",
|
|
12545
|
+
"events",
|
|
12546
|
+
"payment-attempts",
|
|
12547
|
+
"transactions",
|
|
12548
|
+
"idempotency-keys",
|
|
12549
|
+
"authorization-holds",
|
|
12550
|
+
"pending-tasks"
|
|
12551
|
+
],
|
|
11323
12552
|
status: "stable"
|
|
11324
12553
|
};
|
|
11325
12554
|
const store = {
|
|
@@ -11331,6 +12560,16 @@ function createSqliteReceiptStore(options) {
|
|
|
11331
12560
|
`Receipt store schema version mismatch (found ${version}, expected ${SCHEMA_VERSION2})`
|
|
11332
12561
|
);
|
|
11333
12562
|
}
|
|
12563
|
+
if (!db.readonly) sweepExpiredPendingTasks(db, clock.nowIso());
|
|
12564
|
+
if (options.legacyStores !== void 0 && releaseLegacyLocks === void 0) {
|
|
12565
|
+
releaseLegacyLocks = importLegacyStores(
|
|
12566
|
+
db,
|
|
12567
|
+
options.path,
|
|
12568
|
+
options.legacyStores,
|
|
12569
|
+
clock,
|
|
12570
|
+
logger
|
|
12571
|
+
);
|
|
12572
|
+
}
|
|
11334
12573
|
},
|
|
11335
12574
|
async appendEvent(event) {
|
|
11336
12575
|
try {
|
|
@@ -11513,6 +12752,10 @@ function createSqliteReceiptStore(options) {
|
|
|
11513
12752
|
const row = getPaymentAttemptStmt.get(id) ?? getArchivedPaymentAttemptStmt.get(id);
|
|
11514
12753
|
return row !== void 0 ? rowToPaymentAttempt(row) : void 0;
|
|
11515
12754
|
},
|
|
12755
|
+
async findPaymentAttemptByReplayKey(replayKey) {
|
|
12756
|
+
const row = paymentAttemptByReplayKeyStmt.get(replayKey);
|
|
12757
|
+
return row !== void 0 ? rowToPaymentAttempt(row) : void 0;
|
|
12758
|
+
},
|
|
11516
12759
|
async resolvePaymentAttempt(request) {
|
|
11517
12760
|
try {
|
|
11518
12761
|
return resolveAttempt(request, clock.nowIso());
|
|
@@ -11520,6 +12763,38 @@ function createSqliteReceiptStore(options) {
|
|
|
11520
12763
|
throw toCommerceError(err, "STORAGE_ERROR", "Failed to resolve payment attempt");
|
|
11521
12764
|
}
|
|
11522
12765
|
},
|
|
12766
|
+
...createIdempotencyMethods(db, clock),
|
|
12767
|
+
...createHoldMethods(db, clock),
|
|
12768
|
+
...createPendingTaskMethods(db, clock),
|
|
12769
|
+
// Reads all unresolved transactions at once. Page this query if large
|
|
12770
|
+
// journals make operator diagnostics too costly.
|
|
12771
|
+
async summary({ orphanHoldMinAgeMs }) {
|
|
12772
|
+
const now = clock.nowIso();
|
|
12773
|
+
const unresolvedTransactions = {};
|
|
12774
|
+
for (const row of unresolvedTransactionsStmt.all(...RESOLVED_STATES)) {
|
|
12775
|
+
const { state } = rowToTransaction(row, now);
|
|
12776
|
+
unresolvedTransactions[state] = (unresolvedTransactions[state] ?? 0) + 1;
|
|
12777
|
+
}
|
|
12778
|
+
const orphansBefore = new Date(Date.parse(now) - orphanHoldMinAgeMs).toISOString();
|
|
12779
|
+
const unresolvedKeys = countUnresolvedKeysStmt.get({
|
|
12780
|
+
prefix: PAYMENT_KEY_ENDPOINT_PREFIX,
|
|
12781
|
+
now
|
|
12782
|
+
});
|
|
12783
|
+
return {
|
|
12784
|
+
unresolvedTransactions,
|
|
12785
|
+
orphanHolds: countOrphanHoldsStmt.get(orphansBefore)?.count ?? 0,
|
|
12786
|
+
unresolvedIdempotencyKeys: unresolvedKeys?.other ?? 0,
|
|
12787
|
+
unresolvedPaymentKeys: unresolvedKeys?.payment ?? 0,
|
|
12788
|
+
unexpiredPendingTasks: countLiveTasksStmt.get(now)?.count ?? 0,
|
|
12789
|
+
legacyImports: legacyImportsStmt.all().map((row) => ({
|
|
12790
|
+
source: row.source,
|
|
12791
|
+
path: row.path,
|
|
12792
|
+
rows: row.rows,
|
|
12793
|
+
importedAt: row.imported_at
|
|
12794
|
+
})),
|
|
12795
|
+
missingLegacyImports: missingLegacyImports(db)
|
|
12796
|
+
};
|
|
12797
|
+
},
|
|
11523
12798
|
descriptor,
|
|
11524
12799
|
async health() {
|
|
11525
12800
|
const startedAt = clock.monotonicMs();
|
|
@@ -11578,6 +12853,7 @@ function createSqliteReceiptStore(options) {
|
|
|
11578
12853
|
async close() {
|
|
11579
12854
|
if (!closed) {
|
|
11580
12855
|
closed = true;
|
|
12856
|
+
releaseLegacyLocks?.();
|
|
11581
12857
|
db.close();
|
|
11582
12858
|
}
|
|
11583
12859
|
}
|