@devlab.group/agent-commerce 2.4.1 → 2.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +168 -16
- package/dist/ap2.d.ts +42 -17
- package/dist/ap2.js +83 -27
- package/dist/ap2.js.map +1 -1
- package/dist/{chunk-CXWC5LWM.js → chunk-DRLBML7Z.js} +661 -75
- package/dist/chunk-DRLBML7Z.js.map +1 -0
- package/dist/{chunk-WZW5ORZH.js → chunk-G3EYYHKF.js} +3 -3
- package/dist/{chunk-WZW5ORZH.js.map → chunk-G3EYYHKF.js.map} +1 -1
- package/dist/chunk-GA3O2A7R.js +92 -0
- package/dist/chunk-GA3O2A7R.js.map +1 -0
- package/dist/{chunk-DTKU3Z2M.js → chunk-M52FBNJX.js} +36 -5
- package/dist/chunk-M52FBNJX.js.map +1 -0
- package/dist/chunk-M6BSXXTF.js +8 -0
- package/dist/chunk-M6BSXXTF.js.map +1 -0
- package/dist/{chunk-QPV3EGJO.js → chunk-M6MQ3FYS.js} +25 -4
- package/dist/chunk-M6MQ3FYS.js.map +1 -0
- package/dist/chunk-M6WW6QIT.js +18 -0
- package/dist/chunk-M6WW6QIT.js.map +1 -0
- package/dist/cli/{ap2-GWSP4LYY.js → ap2-2YMYA2H6.js} +85 -29
- package/dist/cli/ap2-2YMYA2H6.js.map +1 -0
- package/dist/cli/{chunk-OZ4LAWBK.js → chunk-3NOMLMJW.js} +29 -8
- package/dist/cli/chunk-3NOMLMJW.js.map +1 -0
- package/dist/cli/chunk-4KLYFXMW.js +8 -0
- package/dist/cli/{chunk-ITWNSS2B.js.map → chunk-4KLYFXMW.js.map} +1 -1
- package/dist/cli/chunk-663ALDZA.js +92 -0
- package/dist/cli/chunk-663ALDZA.js.map +1 -0
- package/dist/cli/chunk-6R6WJ4FD.js +18 -0
- package/dist/cli/chunk-6R6WJ4FD.js.map +1 -0
- package/dist/cli/{chunk-G2JEY7MB.js → chunk-AZL7RPFU.js} +39 -33
- package/dist/cli/chunk-AZL7RPFU.js.map +1 -0
- package/dist/cli/chunk-DHFMIBPG.js +107 -0
- package/dist/cli/chunk-DHFMIBPG.js.map +1 -0
- package/dist/cli/{chunk-QQ3WY5L3.js → chunk-GET3CZGR.js} +36 -104
- package/dist/cli/chunk-GET3CZGR.js.map +1 -0
- package/dist/cli/chunk-NSYSMDQN.js +1544 -0
- package/dist/cli/chunk-NSYSMDQN.js.map +1 -0
- package/dist/cli/{chunk-PIMFPCNZ.js → chunk-PTL7SNOI.js} +313 -138
- package/dist/cli/chunk-PTL7SNOI.js.map +1 -0
- package/dist/cli/chunk-SYQLJXIU.js +105 -0
- package/dist/cli/chunk-SYQLJXIU.js.map +1 -0
- package/dist/cli/chunk-TFV3K6YS.js +373 -0
- package/dist/cli/chunk-TFV3K6YS.js.map +1 -0
- package/dist/cli/{chunk-3MGAJ5FX.js → chunk-VJ4EO4LE.js} +3 -3
- package/dist/cli/{chunk-3MGAJ5FX.js.map → chunk-VJ4EO4LE.js.map} +1 -1
- package/dist/cli/chunk-VJH6RYRK.js +119 -0
- package/dist/cli/chunk-VJH6RYRK.js.map +1 -0
- package/dist/cli/{chunk-TNMLDPUO.js → chunk-YOF7IK4V.js} +663 -77
- package/dist/cli/chunk-YOF7IK4V.js.map +1 -0
- package/dist/cli/{chunk-WYOGIANL.js → chunk-YWG2ZN3L.js} +4 -4
- package/dist/cli/{chunk-WYOGIANL.js.map → chunk-YWG2ZN3L.js.map} +1 -1
- package/dist/cli/config-3K65QJ22.js +12 -0
- package/dist/cli/{config-UI4EDG4L.js.map → config-3K65QJ22.js.map} +1 -1
- package/dist/cli/index.js +753 -212
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/{mcp-PGBRWZVA.js → mcp-6F64A7KE.js} +5 -4
- package/dist/cli/mcp-6F64A7KE.js.map +1 -0
- package/dist/cli/{near-5AY3HWYF.js → near-U6365VFX.js} +15 -4
- package/dist/cli/near-U6365VFX.js.map +1 -0
- package/dist/cli/payment-providers-2ITS6KNR.js +6 -0
- package/dist/cli/payment-providers-2ITS6KNR.js.map +1 -0
- package/dist/cli/{provider-I2ESL6RS.js → provider-5BGG5YKQ.js} +53 -24
- package/dist/cli/provider-5BGG5YKQ.js.map +1 -0
- package/dist/cli/receipts-I4IIE7U6.js +8 -0
- package/dist/cli/receipts-I4IIE7U6.js.map +1 -0
- package/dist/cli/reconcile-55WNCSFC.js +4 -0
- package/dist/cli/reconcile-55WNCSFC.js.map +1 -0
- package/dist/cli/{run-JK4ERPJV.js → run-2P6ZGFUE.js} +356 -173
- package/dist/cli/run-2P6ZGFUE.js.map +1 -0
- package/dist/cli/svm-KDSPDFJG.js +48 -0
- package/dist/cli/svm-KDSPDFJG.js.map +1 -0
- package/dist/cli/{x402-7WBFZQXV.js → x402-4LPIIELI.js} +10 -9
- package/dist/cli/x402-4LPIIELI.js.map +1 -0
- package/dist/index.d.ts +116 -113
- package/dist/index.js +1928 -351
- package/dist/index.js.map +1 -1
- package/dist/logger-CllGwQ8i.d.ts +19 -0
- package/dist/mcp.d.ts +3 -2
- package/dist/mcp.js +2 -1
- package/dist/mcp.js.map +1 -1
- package/dist/mpp.d.ts +2 -1
- package/dist/mpp.js +48 -19
- package/dist/mpp.js.map +1 -1
- package/dist/{near-D6C42VPE.js → near-FH7HPZV3.js} +15 -4
- package/dist/near-FH7HPZV3.js.map +1 -0
- package/dist/{protocol-adapter-C9odYl6l.d.ts → protocol-adapter-1WbtM3xG.d.ts} +12 -85
- package/dist/{runtime-Cl_BLVZV.d.ts → runtime-B-kARa2f.d.ts} +218 -15
- package/dist/store-kIIMpUA-.d.ts +372 -0
- package/dist/svm-KNC3PHMS.js +48 -0
- package/dist/svm-KNC3PHMS.js.map +1 -0
- package/dist/testing.d.ts +51 -0
- package/dist/testing.js +1896 -0
- package/dist/testing.js.map +1 -0
- package/dist/transaction-Dv0UFGg5.d.ts +129 -0
- package/dist/{types-j7MnUXYN.d.ts → types-DWqjz81-.d.ts} +5 -2
- package/dist/x402.d.ts +2 -1
- package/dist/x402.js +6 -5
- package/dist/x402.js.map +1 -1
- package/package.json +5 -1
- package/dist/authorization-DjAecwuW.d.ts +0 -115
- package/dist/chunk-CXWC5LWM.js.map +0 -1
- package/dist/chunk-DTKU3Z2M.js.map +0 -1
- package/dist/chunk-KA2AX5FH.js +0 -44
- package/dist/chunk-KA2AX5FH.js.map +0 -1
- package/dist/chunk-QPV3EGJO.js.map +0 -1
- package/dist/cli/ap2-GWSP4LYY.js.map +0 -1
- package/dist/cli/chunk-G2JEY7MB.js.map +0 -1
- package/dist/cli/chunk-GJIMDMYT.js +0 -639
- package/dist/cli/chunk-GJIMDMYT.js.map +0 -1
- package/dist/cli/chunk-ITWNSS2B.js +0 -8
- package/dist/cli/chunk-OSTCU6ZK.js +0 -44
- package/dist/cli/chunk-OSTCU6ZK.js.map +0 -1
- package/dist/cli/chunk-OZ4LAWBK.js.map +0 -1
- package/dist/cli/chunk-PIMFPCNZ.js.map +0 -1
- package/dist/cli/chunk-QQ3WY5L3.js.map +0 -1
- package/dist/cli/chunk-TNMLDPUO.js.map +0 -1
- package/dist/cli/config-UI4EDG4L.js +0 -11
- package/dist/cli/mcp-PGBRWZVA.js.map +0 -1
- package/dist/cli/near-5AY3HWYF.js.map +0 -1
- package/dist/cli/provider-I2ESL6RS.js.map +0 -1
- package/dist/cli/run-JK4ERPJV.js.map +0 -1
- package/dist/cli/svm-3MMYFPC7.js +0 -33
- package/dist/cli/svm-3MMYFPC7.js.map +0 -1
- package/dist/cli/x402-7WBFZQXV.js.map +0 -1
- package/dist/near-D6C42VPE.js.map +0 -1
- package/dist/svm-QEUAUNPQ.js +0 -33
- package/dist/svm-QEUAUNPQ.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,23 +1,27 @@
|
|
|
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-
|
|
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-G3EYYHKF.js';
|
|
2
2
|
import { readCappedBody, createBearerCheck, MCP_TOOL_NAME_PATTERN, settlementResponse, joinUrl, settlementResponseFromDetails, settlementFailure, x402ErrorCode, x402RefusalStatus } from './chunk-ES3V6ECS.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
4
|
import { contentDigest, CONTENT_DIGEST_METADATA_KEY, mppProblem, mppProblemDetail } from './chunk-5ZYXBCDX.js';
|
|
5
|
-
import { X402_PAYMENT_FLOWS, validateCustomNetworks, findX402Network, X402_DEFAULT_PAYMENT_FLOW, resolveX402Deployment,
|
|
6
|
-
import {
|
|
7
|
-
|
|
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-M6MQ3FYS.js';
|
|
6
|
+
import { PACKAGE_VERSION } from './chunk-M6BSXXTF.js';
|
|
7
|
+
import { hasMethodGroup } from './chunk-M6WW6QIT.js';
|
|
8
|
+
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-M52FBNJX.js';
|
|
9
|
+
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-M52FBNJX.js';
|
|
8
10
|
import { isRecord } from './chunk-2CJNA7MS.js';
|
|
9
|
-
import { promises, accessSync, constants } from 'fs';
|
|
11
|
+
import { promises, accessSync, constants, existsSync } from 'fs';
|
|
10
12
|
import * as path from 'path';
|
|
13
|
+
import { resolve } from 'path';
|
|
11
14
|
import { parse, YAMLError } from 'yaml';
|
|
12
15
|
import { z } from 'zod';
|
|
16
|
+
import { randomUUID, createHash } from 'crypto';
|
|
13
17
|
import { isDeepStrictEqual } from 'util';
|
|
14
18
|
import Fastify from 'fastify';
|
|
15
|
-
import { randomUUID, createHash } from 'crypto';
|
|
16
19
|
import { createRequire } from 'module';
|
|
17
20
|
import pino from 'pino';
|
|
18
21
|
import { Transform } from 'stream';
|
|
19
22
|
import Ajv2020 from 'ajv/dist/2020.js';
|
|
20
23
|
import addFormats from 'ajv-formats';
|
|
24
|
+
import Database from 'better-sqlite3';
|
|
21
25
|
|
|
22
26
|
// src/config/env.ts
|
|
23
27
|
var PLACEHOLDER_PATTERN = /\$\{([A-Za-z_][A-Za-z0-9_]*)(:-([^}]*))?\}/g;
|
|
@@ -212,10 +216,10 @@ function normalizeAcp(raw) {
|
|
|
212
216
|
'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
217
|
);
|
|
214
218
|
}
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
"protocols.acp.idempotency is
|
|
219
|
+
const idempotency = raw.idempotency ?? {};
|
|
220
|
+
if (idempotency.path !== void 0) {
|
|
221
|
+
console.warn(
|
|
222
|
+
"[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
223
|
);
|
|
220
224
|
}
|
|
221
225
|
const discovery = raw.discovery;
|
|
@@ -224,13 +228,13 @@ function normalizeAcp(raw) {
|
|
|
224
228
|
mountPath,
|
|
225
229
|
auth: raw.auth,
|
|
226
230
|
idempotency: {
|
|
227
|
-
path:
|
|
231
|
+
...idempotency.path !== void 0 ? { path: idempotency.path } : {},
|
|
228
232
|
retentionHours: toNumber(
|
|
229
|
-
|
|
233
|
+
idempotency.retentionHours ?? ACP_RETENTION_HOURS,
|
|
230
234
|
"protocols.acp.idempotency.retentionHours",
|
|
231
235
|
{ min: ACP_RETENTION_HOURS }
|
|
232
236
|
),
|
|
233
|
-
merchantIdempotent:
|
|
237
|
+
merchantIdempotent: idempotency.merchantIdempotent ?? false
|
|
234
238
|
},
|
|
235
239
|
checkout: { operations: normalizeAcpOperations(raw.checkout) },
|
|
236
240
|
// Built key by key so absent metadata stays absent rather than `undefined`
|
|
@@ -361,8 +365,6 @@ function closedObjectProperties(schema) {
|
|
|
361
365
|
if (!isRecord(schema) || schema["additionalProperties"] !== false) return void 0;
|
|
362
366
|
return isRecord(schema["properties"]) ? schema["properties"] : {};
|
|
363
367
|
}
|
|
364
|
-
|
|
365
|
-
// src/config/schema/ap2.ts
|
|
366
368
|
var SUPPORTED_AUTHORIZATION_METHODS = /* @__PURE__ */ new Set(["ap2"]);
|
|
367
369
|
function ap2Invalid(path2, message, extra = {}) {
|
|
368
370
|
return new CommerceError("CONFIG_INVALID", message, { details: { path: path2, ...extra } });
|
|
@@ -384,10 +386,9 @@ function normalizeAp2(raw) {
|
|
|
384
386
|
`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
387
|
);
|
|
386
388
|
}
|
|
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"
|
|
389
|
+
if (raw.replay !== void 0) {
|
|
390
|
+
console.warn(
|
|
391
|
+
"[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
392
|
);
|
|
392
393
|
}
|
|
393
394
|
const mandateIssuers = normalizeIssuers(
|
|
@@ -416,7 +417,7 @@ function normalizeAp2(raw) {
|
|
|
416
417
|
raw.requireMandateExpiry ?? false,
|
|
417
418
|
"authorization.ap2.requireMandateExpiry"
|
|
418
419
|
),
|
|
419
|
-
replay: { path: raw.replay.path }
|
|
420
|
+
...raw.replay !== void 0 ? { replay: { path: raw.replay.path } } : {}
|
|
420
421
|
};
|
|
421
422
|
}
|
|
422
423
|
function normalizeIssuers(raw, path2) {
|
|
@@ -511,16 +512,25 @@ function validateJwk(jwk, kid, path2) {
|
|
|
511
512
|
}
|
|
512
513
|
return normalized;
|
|
513
514
|
}
|
|
514
|
-
function
|
|
515
|
-
|
|
515
|
+
function validateLegacyStoresIsolated(ap2, acp, receiptsPath) {
|
|
516
|
+
const files = [
|
|
517
|
+
["authorization.ap2.replay.path", ap2?.enabled ? ap2.replay?.path : void 0],
|
|
518
|
+
["protocols.acp.idempotency.path", acp.enabled ? acp.idempotency.path : void 0]
|
|
519
|
+
];
|
|
516
520
|
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`
|
|
521
|
+
for (const [key, path2] of files) {
|
|
522
|
+
if (path2 === void 0 || path2 === ":memory:") continue;
|
|
523
|
+
const clash = others.find(
|
|
524
|
+
([, other]) => other !== ":memory:" && resolve(other) === resolve(path2)
|
|
523
525
|
);
|
|
526
|
+
if (clash !== void 0) {
|
|
527
|
+
throw new CommerceError(
|
|
528
|
+
"CONFIG_INVALID",
|
|
529
|
+
`${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`,
|
|
530
|
+
{ details: { path: key } }
|
|
531
|
+
);
|
|
532
|
+
}
|
|
533
|
+
others.push([key, path2]);
|
|
524
534
|
}
|
|
525
535
|
}
|
|
526
536
|
function normalizeResourceAuthorization(id, entry, pricing, ap2) {
|
|
@@ -896,7 +906,7 @@ var MountPathSchema = z.string().min(1).refine((value) => value.startsWith("/"),
|
|
|
896
906
|
);
|
|
897
907
|
var AcpAuthSchema = z.object({ type: z.literal("bearer"), token: z.string().min(1) }).strict();
|
|
898
908
|
var AcpIdempotencySchema = z.object({
|
|
899
|
-
path: z.string().min(1),
|
|
909
|
+
path: z.string().min(1).optional(),
|
|
900
910
|
retentionHours: NumberOrString.optional(),
|
|
901
911
|
merchantIdempotent: z.boolean().optional()
|
|
902
912
|
}).strict();
|
|
@@ -1169,7 +1179,7 @@ var TRAVERSAL_PATH_VALUES = /* @__PURE__ */ new Set(["", ".", ".."]);
|
|
|
1169
1179
|
function applyPathTemplate(template, input, context) {
|
|
1170
1180
|
const remaining = { ...input };
|
|
1171
1181
|
let missing;
|
|
1172
|
-
let
|
|
1182
|
+
let invalid3;
|
|
1173
1183
|
const url = template.replace(PATH_PARAM_PATTERN, (_match, key) => {
|
|
1174
1184
|
if (!Object.hasOwn(remaining, key)) {
|
|
1175
1185
|
missing = key;
|
|
@@ -1179,7 +1189,7 @@ function applyPathTemplate(template, input, context) {
|
|
|
1179
1189
|
delete remaining[key];
|
|
1180
1190
|
const raw = stringifyPrimitive(value);
|
|
1181
1191
|
if (TRAVERSAL_PATH_VALUES.has(raw)) {
|
|
1182
|
-
|
|
1192
|
+
invalid3 = key;
|
|
1183
1193
|
return "";
|
|
1184
1194
|
}
|
|
1185
1195
|
return encodeURIComponent(raw);
|
|
@@ -1190,10 +1200,10 @@ function applyPathTemplate(template, input, context) {
|
|
|
1190
1200
|
details: { field: missing }
|
|
1191
1201
|
});
|
|
1192
1202
|
}
|
|
1193
|
-
if (
|
|
1194
|
-
throw new CommerceError("INPUT_INVALID", `Path parameter "${
|
|
1203
|
+
if (invalid3 !== void 0) {
|
|
1204
|
+
throw new CommerceError("INPUT_INVALID", `Path parameter "${invalid3}" is not a valid value`, {
|
|
1195
1205
|
...context,
|
|
1196
|
-
details: { field:
|
|
1206
|
+
details: { field: invalid3 }
|
|
1197
1207
|
});
|
|
1198
1208
|
}
|
|
1199
1209
|
return { url, remaining };
|
|
@@ -1446,6 +1456,56 @@ function safeStringify(value) {
|
|
|
1446
1456
|
function isAbortError(error) {
|
|
1447
1457
|
return error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
|
|
1448
1458
|
}
|
|
1459
|
+
function createFlow(request, transactionId) {
|
|
1460
|
+
return { request, transactionId, persistenceFailures: [], journaled: false };
|
|
1461
|
+
}
|
|
1462
|
+
function failuresOf(flow) {
|
|
1463
|
+
return flow.persistenceFailures.length > 0 ? { persistenceFailures: [...flow.persistenceFailures] } : {};
|
|
1464
|
+
}
|
|
1465
|
+
function sha256(text) {
|
|
1466
|
+
return `sha256:${createHash("sha256").update(text, "utf8").digest("hex")}`;
|
|
1467
|
+
}
|
|
1468
|
+
function inputDigest(input) {
|
|
1469
|
+
const json = canonicalJson(input);
|
|
1470
|
+
return json !== void 0 ? sha256(json) : void 0;
|
|
1471
|
+
}
|
|
1472
|
+
function configDigest(resource, requirement) {
|
|
1473
|
+
const terms = {
|
|
1474
|
+
resourceId: resource.id,
|
|
1475
|
+
pricing: resource.pricing,
|
|
1476
|
+
paymentMethods: resource.paymentMethods,
|
|
1477
|
+
authorization: resource.authorization?.required ?? [],
|
|
1478
|
+
requirement: {
|
|
1479
|
+
provider: requirement.provider,
|
|
1480
|
+
amount: requirement.amount,
|
|
1481
|
+
currency: requirement.currency,
|
|
1482
|
+
destination: requirement.destination ?? null,
|
|
1483
|
+
network: requirement.network ?? null,
|
|
1484
|
+
asset: requirement.asset ?? null,
|
|
1485
|
+
settleAfterBackend: requirement.metadata?.[SETTLE_AFTER_BACKEND_METADATA_KEY] === true
|
|
1486
|
+
}
|
|
1487
|
+
};
|
|
1488
|
+
return sha256(canonicalJson(terms) ?? JSON.stringify(terms));
|
|
1489
|
+
}
|
|
1490
|
+
function newTransaction(flow, resource, requirement, verification, validInput, authorization) {
|
|
1491
|
+
const raw = verification.metadata?.[RECONCILIATION_METADATA_KEY];
|
|
1492
|
+
const locator = isRecord(raw) ? raw : void 0;
|
|
1493
|
+
const expiresAt = typeof locator?.["expiresAt"] === "string" ? locator["expiresAt"] : void 0;
|
|
1494
|
+
const network = verification.network ?? requirement.network;
|
|
1495
|
+
const asset = verification.asset ?? requirement.asset;
|
|
1496
|
+
const digest = inputDigest(validInput);
|
|
1497
|
+
return {
|
|
1498
|
+
id: flow.transactionId,
|
|
1499
|
+
protocol: flow.request.protocol,
|
|
1500
|
+
...network !== void 0 ? { network } : {},
|
|
1501
|
+
...asset !== void 0 ? { asset } : {},
|
|
1502
|
+
...locator !== void 0 ? { locator } : {},
|
|
1503
|
+
...expiresAt !== void 0 ? { expiresAt } : {},
|
|
1504
|
+
...authorization !== void 0 ? { authorization } : {},
|
|
1505
|
+
...digest !== void 0 ? { inputDigest: digest } : {},
|
|
1506
|
+
configDigest: configDigest(resource, requirement)
|
|
1507
|
+
};
|
|
1508
|
+
}
|
|
1449
1509
|
var SUPPORTED_TYPES = /* @__PURE__ */ new Set([
|
|
1450
1510
|
"object",
|
|
1451
1511
|
"string",
|
|
@@ -1588,16 +1648,15 @@ function resolveAuthorizationProviders(providers, resource, requestId) {
|
|
|
1588
1648
|
}
|
|
1589
1649
|
function createAuthorizeAndReserve(ctx) {
|
|
1590
1650
|
const { options, safeEmit, buildEvent } = ctx;
|
|
1591
|
-
async function authorizeAndReserve(request, resource, providers, requirement, input) {
|
|
1651
|
+
async function authorizeAndReserve(flow, request, resource, providers, requirement, input) {
|
|
1592
1652
|
if (providers.length === 0) return void 0;
|
|
1593
1653
|
const submission = request.authorization;
|
|
1594
1654
|
const provider = providers.find((candidate) => candidate.name === submission?.method);
|
|
1595
1655
|
const unmet = providers.filter((candidate) => candidate !== provider).map((c) => c.name);
|
|
1596
1656
|
if (submission === void 0 || provider === void 0 || unmet.length > 0) {
|
|
1597
1657
|
await safeEmit(
|
|
1598
|
-
buildEvent({
|
|
1658
|
+
buildEvent(flow, {
|
|
1599
1659
|
type: "authorization.rejected",
|
|
1600
|
-
requestId: request.requestId,
|
|
1601
1660
|
resourceId: resource.id,
|
|
1602
1661
|
adapter: request.protocol,
|
|
1603
1662
|
status: "error",
|
|
@@ -1634,9 +1693,8 @@ function createAuthorizeAndReserve(ctx) {
|
|
|
1634
1693
|
}
|
|
1635
1694
|
);
|
|
1636
1695
|
await safeEmit(
|
|
1637
|
-
buildEvent({
|
|
1696
|
+
buildEvent(flow, {
|
|
1638
1697
|
type: "authorization.rejected",
|
|
1639
|
-
requestId: request.requestId,
|
|
1640
1698
|
resourceId: resource.id,
|
|
1641
1699
|
adapter: request.protocol,
|
|
1642
1700
|
status: "error",
|
|
@@ -1646,9 +1704,8 @@ function createAuthorizeAndReserve(ctx) {
|
|
|
1646
1704
|
throw mapped;
|
|
1647
1705
|
}
|
|
1648
1706
|
await safeEmit(
|
|
1649
|
-
buildEvent({
|
|
1707
|
+
buildEvent(flow, {
|
|
1650
1708
|
type: "authorization.verified",
|
|
1651
|
-
requestId: request.requestId,
|
|
1652
1709
|
resourceId: resource.id,
|
|
1653
1710
|
adapter: request.protocol,
|
|
1654
1711
|
status: "ok",
|
|
@@ -1662,14 +1719,17 @@ function createAuthorizeAndReserve(ctx) {
|
|
|
1662
1719
|
reference: verification.reference,
|
|
1663
1720
|
...verification.metadata !== void 0 ? { metadata: verification.metadata } : {}
|
|
1664
1721
|
},
|
|
1722
|
+
reservationId: verification.reservationId,
|
|
1665
1723
|
async finalize(action) {
|
|
1666
1724
|
try {
|
|
1667
1725
|
await provider[action](verification.reservationId, context);
|
|
1726
|
+
return true;
|
|
1668
1727
|
} catch (error) {
|
|
1669
1728
|
options.logger.error(
|
|
1670
1729
|
{ err: describeError(error), requestId: request.requestId, action },
|
|
1671
1730
|
"Authorization finalization failed; the reservation stays reserved"
|
|
1672
1731
|
);
|
|
1732
|
+
return false;
|
|
1673
1733
|
}
|
|
1674
1734
|
}
|
|
1675
1735
|
};
|
|
@@ -1689,10 +1749,12 @@ function retryChallenge(requirement, reason) {
|
|
|
1689
1749
|
};
|
|
1690
1750
|
}
|
|
1691
1751
|
var FINISHED_ATTEMPT_STATUSES = /* @__PURE__ */ new Set(["settled", "rejected"]);
|
|
1752
|
+
function isFinishedAttempt(status) {
|
|
1753
|
+
return typeof status === "string" && FINISHED_ATTEMPT_STATUSES.has(status);
|
|
1754
|
+
}
|
|
1692
1755
|
function replayError(error, requirement) {
|
|
1693
1756
|
if (error.code !== "PAYMENT_REPLAYED") return error;
|
|
1694
|
-
const
|
|
1695
|
-
const finished = typeof status === "string" && FINISHED_ATTEMPT_STATUSES.has(status);
|
|
1757
|
+
const finished = isFinishedAttempt(error.details?.["attemptStatus"]);
|
|
1696
1758
|
const network = requirement.network;
|
|
1697
1759
|
if (!finished && network === void 0) return error;
|
|
1698
1760
|
return new CommerceError("PAYMENT_REPLAYED", error.message, {
|
|
@@ -1710,7 +1772,7 @@ function replayError(error, requirement) {
|
|
|
1710
1772
|
// src/core/execution/pipeline/admission.ts
|
|
1711
1773
|
function createPaymentAdmission(ctx, authorizeAndReserve) {
|
|
1712
1774
|
const { options, safeEmit, buildEvent } = ctx;
|
|
1713
|
-
return async function admitPayment(request, resource, pricing, validInput) {
|
|
1775
|
+
return async function admitPayment(flow, request, resource, pricing, validInput) {
|
|
1714
1776
|
const provider = pickProvider(options.paymentProviders, resource.paymentMethods);
|
|
1715
1777
|
if (!provider) {
|
|
1716
1778
|
throw new CommerceError(
|
|
@@ -1749,9 +1811,8 @@ function createPaymentAdmission(ctx, authorizeAndReserve) {
|
|
|
1749
1811
|
}
|
|
1750
1812
|
if (!request.payment) {
|
|
1751
1813
|
await safeEmit(
|
|
1752
|
-
buildEvent({
|
|
1814
|
+
buildEvent(flow, {
|
|
1753
1815
|
type: "payment.required",
|
|
1754
|
-
requestId: request.requestId,
|
|
1755
1816
|
resourceId: resource.id,
|
|
1756
1817
|
adapter: request.protocol,
|
|
1757
1818
|
paymentProvider: provider.name
|
|
@@ -1760,6 +1821,7 @@ function createPaymentAdmission(ctx, authorizeAndReserve) {
|
|
|
1760
1821
|
return {
|
|
1761
1822
|
kind: "payment-required",
|
|
1762
1823
|
requestId: request.requestId,
|
|
1824
|
+
transactionId: flow.transactionId,
|
|
1763
1825
|
resourceId: resource.id,
|
|
1764
1826
|
requirement,
|
|
1765
1827
|
...authProviders.length > 0 ? { authorization: authProviders.map((p) => p.requirement) } : {}
|
|
@@ -1790,9 +1852,8 @@ function createPaymentAdmission(ctx, authorizeAndReserve) {
|
|
|
1790
1852
|
...retryChallenge(requirement)
|
|
1791
1853
|
});
|
|
1792
1854
|
await safeEmit(
|
|
1793
|
-
buildEvent({
|
|
1855
|
+
buildEvent(flow, {
|
|
1794
1856
|
type: "payment.rejected",
|
|
1795
|
-
requestId: request.requestId,
|
|
1796
1857
|
resourceId: resource.id,
|
|
1797
1858
|
adapter: request.protocol,
|
|
1798
1859
|
paymentProvider: provider.name,
|
|
@@ -1803,32 +1864,23 @@ function createPaymentAdmission(ctx, authorizeAndReserve) {
|
|
|
1803
1864
|
throw mapped;
|
|
1804
1865
|
}
|
|
1805
1866
|
if (verification.status !== "verified") {
|
|
1867
|
+
const refusal = await refusalFor(verification, requirement, request, resource);
|
|
1806
1868
|
await safeEmit(
|
|
1807
|
-
buildEvent({
|
|
1869
|
+
buildEvent(flow, {
|
|
1808
1870
|
type: "payment.rejected",
|
|
1809
|
-
requestId: request.requestId,
|
|
1810
1871
|
resourceId: resource.id,
|
|
1811
1872
|
adapter: request.protocol,
|
|
1812
1873
|
paymentProvider: provider.name,
|
|
1813
1874
|
status: "error",
|
|
1814
|
-
data: verification.rejectionReason ? { reason: verification.rejectionReason } : {}
|
|
1875
|
+
data: refusal.code !== "PAYMENT_INVALID" ? { reason: refusal.code } : verification.rejectionReason ? { reason: verification.rejectionReason } : {}
|
|
1815
1876
|
})
|
|
1816
1877
|
);
|
|
1817
|
-
throw
|
|
1818
|
-
"PAYMENT_INVALID",
|
|
1819
|
-
verification.rejectionReason ?? "Payment was rejected",
|
|
1820
|
-
{
|
|
1821
|
-
requestId: request.requestId,
|
|
1822
|
-
resourceId: resource.id,
|
|
1823
|
-
...retryChallenge(requirement, verification.rejectionReason)
|
|
1824
|
-
}
|
|
1825
|
-
);
|
|
1878
|
+
throw refusal;
|
|
1826
1879
|
}
|
|
1827
1880
|
if (!verification.replayKey) {
|
|
1828
1881
|
await safeEmit(
|
|
1829
|
-
buildEvent({
|
|
1882
|
+
buildEvent(flow, {
|
|
1830
1883
|
type: "payment.rejected",
|
|
1831
|
-
requestId: request.requestId,
|
|
1832
1884
|
resourceId: resource.id,
|
|
1833
1885
|
adapter: request.protocol,
|
|
1834
1886
|
paymentProvider: provider.name,
|
|
@@ -1843,6 +1895,7 @@ function createPaymentAdmission(ctx, authorizeAndReserve) {
|
|
|
1843
1895
|
}
|
|
1844
1896
|
const replayKey = verification.replayKey;
|
|
1845
1897
|
const hold = await authorizeAndReserve(
|
|
1898
|
+
flow,
|
|
1846
1899
|
request,
|
|
1847
1900
|
resource,
|
|
1848
1901
|
authProviders,
|
|
@@ -1850,7 +1903,7 @@ function createPaymentAdmission(ctx, authorizeAndReserve) {
|
|
|
1850
1903
|
validInput
|
|
1851
1904
|
);
|
|
1852
1905
|
try {
|
|
1853
|
-
await options.store.reservePaymentAttempt({
|
|
1906
|
+
const attempt = await options.store.reservePaymentAttempt({
|
|
1854
1907
|
requestId: request.requestId,
|
|
1855
1908
|
resourceId: resource.id,
|
|
1856
1909
|
provider: provider.name,
|
|
@@ -1859,8 +1912,17 @@ function createPaymentAdmission(ctx, authorizeAndReserve) {
|
|
|
1859
1912
|
currency: verification.currency,
|
|
1860
1913
|
...verification.payer !== void 0 ? { payer: verification.payer } : {},
|
|
1861
1914
|
...verification.payee !== void 0 ? { payee: verification.payee } : {},
|
|
1862
|
-
...requirement.metadata?.[REUSE_REJECTED_AUTHORIZATION_METADATA_KEY] === true ? { reclaimRejected: true } : {}
|
|
1915
|
+
...requirement.metadata?.[REUSE_REJECTED_AUTHORIZATION_METADATA_KEY] === true ? { reclaimRejected: true } : {},
|
|
1916
|
+
transaction: newTransaction(
|
|
1917
|
+
flow,
|
|
1918
|
+
resource,
|
|
1919
|
+
requirement,
|
|
1920
|
+
verification,
|
|
1921
|
+
validInput,
|
|
1922
|
+
hold !== void 0 ? { ...hold.record, reservationId: hold.reservationId } : void 0
|
|
1923
|
+
)
|
|
1863
1924
|
});
|
|
1925
|
+
flow.journaled = attempt.transactionId === flow.transactionId && options.store.recordTransactionStep !== void 0;
|
|
1864
1926
|
} catch (error) {
|
|
1865
1927
|
const mapped = toCommerceError(
|
|
1866
1928
|
error,
|
|
@@ -1869,9 +1931,8 @@ function createPaymentAdmission(ctx, authorizeAndReserve) {
|
|
|
1869
1931
|
);
|
|
1870
1932
|
await hold?.finalize("release");
|
|
1871
1933
|
await safeEmit(
|
|
1872
|
-
buildEvent({
|
|
1934
|
+
buildEvent(flow, {
|
|
1873
1935
|
type: "payment.rejected",
|
|
1874
|
-
requestId: request.requestId,
|
|
1875
1936
|
resourceId: resource.id,
|
|
1876
1937
|
adapter: request.protocol,
|
|
1877
1938
|
paymentProvider: provider.name,
|
|
@@ -1882,9 +1943,8 @@ function createPaymentAdmission(ctx, authorizeAndReserve) {
|
|
|
1882
1943
|
throw replayError(mapped, requirement);
|
|
1883
1944
|
}
|
|
1884
1945
|
await safeEmit(
|
|
1885
|
-
buildEvent({
|
|
1946
|
+
buildEvent(flow, {
|
|
1886
1947
|
type: "payment.verified",
|
|
1887
|
-
requestId: request.requestId,
|
|
1888
1948
|
resourceId: resource.id,
|
|
1889
1949
|
adapter: request.protocol,
|
|
1890
1950
|
paymentProvider: provider.name,
|
|
@@ -1894,6 +1954,7 @@ function createPaymentAdmission(ctx, authorizeAndReserve) {
|
|
|
1894
1954
|
return {
|
|
1895
1955
|
kind: "admitted",
|
|
1896
1956
|
settleArgs: {
|
|
1957
|
+
flow,
|
|
1897
1958
|
request,
|
|
1898
1959
|
resource,
|
|
1899
1960
|
provider,
|
|
@@ -1905,6 +1966,37 @@ function createPaymentAdmission(ctx, authorizeAndReserve) {
|
|
|
1905
1966
|
}
|
|
1906
1967
|
};
|
|
1907
1968
|
};
|
|
1969
|
+
async function refusalFor(verification, requirement, request, resource) {
|
|
1970
|
+
const ids = { requestId: request.requestId, resourceId: resource.id };
|
|
1971
|
+
if (verification.replayKey !== void 0) {
|
|
1972
|
+
let attempt;
|
|
1973
|
+
try {
|
|
1974
|
+
attempt = await options.store.findPaymentAttemptByReplayKey?.(verification.replayKey);
|
|
1975
|
+
} catch (error) {
|
|
1976
|
+
return new CommerceError("STORAGE_ERROR", "Payment attempt could not be read", {
|
|
1977
|
+
...ids,
|
|
1978
|
+
cause: error
|
|
1979
|
+
});
|
|
1980
|
+
}
|
|
1981
|
+
if (attempt !== void 0 && !isFinishedAttempt(attempt.status)) {
|
|
1982
|
+
return replayError(
|
|
1983
|
+
new CommerceError("PAYMENT_REPLAYED", "Payment authorization has already been used", {
|
|
1984
|
+
...ids,
|
|
1985
|
+
details: { attemptStatus: attempt.status }
|
|
1986
|
+
}),
|
|
1987
|
+
requirement
|
|
1988
|
+
);
|
|
1989
|
+
}
|
|
1990
|
+
}
|
|
1991
|
+
return new CommerceError(
|
|
1992
|
+
"PAYMENT_INVALID",
|
|
1993
|
+
verification.rejectionReason ?? "Payment was rejected",
|
|
1994
|
+
{
|
|
1995
|
+
...ids,
|
|
1996
|
+
...retryChallenge(requirement, verification.rejectionReason)
|
|
1997
|
+
}
|
|
1998
|
+
);
|
|
1999
|
+
}
|
|
1908
2000
|
}
|
|
1909
2001
|
function pickProvider(providers, methods) {
|
|
1910
2002
|
for (const method of methods) {
|
|
@@ -1915,6 +2007,11 @@ function pickProvider(providers, methods) {
|
|
|
1915
2007
|
}
|
|
1916
2008
|
|
|
1917
2009
|
// src/core/execution/pipeline/context.ts
|
|
2010
|
+
var HOLD_STATES = {
|
|
2011
|
+
consume: "consumed",
|
|
2012
|
+
release: "released",
|
|
2013
|
+
markUncertain: "uncertain"
|
|
2014
|
+
};
|
|
1918
2015
|
function createPipelineContext(options) {
|
|
1919
2016
|
async function safeEmit(event) {
|
|
1920
2017
|
try {
|
|
@@ -1926,27 +2023,73 @@ function createPipelineContext(options) {
|
|
|
1926
2023
|
);
|
|
1927
2024
|
}
|
|
1928
2025
|
}
|
|
1929
|
-
async function safePersist(op, label,
|
|
2026
|
+
async function safePersist(flow, op, label, failure) {
|
|
1930
2027
|
try {
|
|
1931
2028
|
await op();
|
|
2029
|
+
return true;
|
|
1932
2030
|
} catch (error) {
|
|
1933
2031
|
options.logger.error(
|
|
1934
|
-
{
|
|
2032
|
+
{
|
|
2033
|
+
err: describeError(error),
|
|
2034
|
+
requestId: flow.request.requestId,
|
|
2035
|
+
transactionId: flow.transactionId
|
|
2036
|
+
},
|
|
1935
2037
|
`Persistence failed: ${label}`
|
|
1936
2038
|
);
|
|
2039
|
+
if (failure !== void 0 && !flow.persistenceFailures.includes(failure)) {
|
|
2040
|
+
flow.persistenceFailures.push(failure);
|
|
2041
|
+
}
|
|
2042
|
+
return false;
|
|
2043
|
+
}
|
|
2044
|
+
}
|
|
2045
|
+
async function recordStep(flow, step) {
|
|
2046
|
+
const record = options.store.recordTransactionStep;
|
|
2047
|
+
if (!flow.journaled || record === void 0) return;
|
|
2048
|
+
const full = {
|
|
2049
|
+
...step,
|
|
2050
|
+
transactionId: flow.transactionId,
|
|
2051
|
+
at: options.clock.nowIso()
|
|
2052
|
+
};
|
|
2053
|
+
await safePersist(
|
|
2054
|
+
flow,
|
|
2055
|
+
() => record.call(options.store, full),
|
|
2056
|
+
`recordTransactionStep(${step.kind})`,
|
|
2057
|
+
"journal"
|
|
2058
|
+
);
|
|
2059
|
+
}
|
|
2060
|
+
async function finalizeHold(flow, hold, action) {
|
|
2061
|
+
if (hold !== void 0 && await hold.finalize(action)) {
|
|
2062
|
+
await recordStep(flow, { kind: "hold", hold: HOLD_STATES[action] });
|
|
1937
2063
|
}
|
|
1938
2064
|
}
|
|
1939
|
-
function buildEvent(partial) {
|
|
1940
|
-
return {
|
|
2065
|
+
function buildEvent(flow, partial) {
|
|
2066
|
+
return {
|
|
2067
|
+
id: options.ids.next("evt"),
|
|
2068
|
+
at: options.clock.nowIso(),
|
|
2069
|
+
requestId: flow.request.requestId,
|
|
2070
|
+
transactionId: flow.transactionId,
|
|
2071
|
+
...partial
|
|
2072
|
+
};
|
|
1941
2073
|
}
|
|
1942
|
-
return { options, safeEmit, safePersist, buildEvent };
|
|
2074
|
+
return { options, safeEmit, safePersist, recordStep, finalizeHold, buildEvent };
|
|
1943
2075
|
}
|
|
1944
2076
|
|
|
1945
2077
|
// src/core/execution/pipeline/settlement.ts
|
|
1946
2078
|
function createSettlement(ctx) {
|
|
1947
|
-
const { options, safeEmit, safePersist, buildEvent } = ctx;
|
|
2079
|
+
const { options, safeEmit, safePersist, recordStep, finalizeHold, buildEvent } = ctx;
|
|
1948
2080
|
async function settle(args) {
|
|
1949
|
-
const {
|
|
2081
|
+
const {
|
|
2082
|
+
flow,
|
|
2083
|
+
request,
|
|
2084
|
+
resource,
|
|
2085
|
+
provider,
|
|
2086
|
+
requirement,
|
|
2087
|
+
payment,
|
|
2088
|
+
verification,
|
|
2089
|
+
replayKey,
|
|
2090
|
+
hold
|
|
2091
|
+
} = args;
|
|
2092
|
+
await recordStep(flow, { kind: "settling" });
|
|
1950
2093
|
let settlement;
|
|
1951
2094
|
try {
|
|
1952
2095
|
settlement = await provider.settle({
|
|
@@ -1959,25 +2102,29 @@ function createSettlement(ctx) {
|
|
|
1959
2102
|
} catch (error) {
|
|
1960
2103
|
const notSubmitted = notSubmittedReason(error);
|
|
1961
2104
|
if (notSubmitted !== void 0) {
|
|
1962
|
-
await hold
|
|
2105
|
+
await finalizeHold(flow, hold, "release");
|
|
1963
2106
|
await safePersist(
|
|
2107
|
+
flow,
|
|
1964
2108
|
() => options.store.updatePaymentAttempt({
|
|
1965
2109
|
replayKey,
|
|
1966
2110
|
status: "rejected",
|
|
1967
2111
|
rejectionReason: notSubmitted
|
|
1968
2112
|
}),
|
|
1969
2113
|
"updatePaymentAttempt(not-submitted)",
|
|
1970
|
-
|
|
2114
|
+
"payment-attempt"
|
|
1971
2115
|
);
|
|
1972
2116
|
await safeEmit(
|
|
1973
|
-
buildEvent({
|
|
2117
|
+
buildEvent(flow, {
|
|
1974
2118
|
type: "payment.rejected",
|
|
1975
|
-
requestId: request.requestId,
|
|
1976
2119
|
resourceId: resource.id,
|
|
1977
2120
|
adapter: request.protocol,
|
|
1978
2121
|
paymentProvider: provider.name,
|
|
1979
2122
|
status: "error",
|
|
1980
|
-
data: {
|
|
2123
|
+
data: {
|
|
2124
|
+
reason: "settlement-not-submitted",
|
|
2125
|
+
providerReason: notSubmitted,
|
|
2126
|
+
...failuresOf(flow)
|
|
2127
|
+
}
|
|
1981
2128
|
})
|
|
1982
2129
|
);
|
|
1983
2130
|
throw new CommerceError(
|
|
@@ -1987,8 +2134,9 @@ function createSettlement(ctx) {
|
|
|
1987
2134
|
);
|
|
1988
2135
|
}
|
|
1989
2136
|
const txHash = settlementTxHash(error);
|
|
1990
|
-
await hold
|
|
2137
|
+
await finalizeHold(flow, hold, "markUncertain");
|
|
1991
2138
|
await safePersist(
|
|
2139
|
+
flow,
|
|
1992
2140
|
() => options.store.updatePaymentAttempt({
|
|
1993
2141
|
replayKey,
|
|
1994
2142
|
status: "settlement-uncertain",
|
|
@@ -1996,19 +2144,19 @@ function createSettlement(ctx) {
|
|
|
1996
2144
|
...error instanceof Error ? { rejectionReason: error.message } : {}
|
|
1997
2145
|
}),
|
|
1998
2146
|
"updatePaymentAttempt(settlement-uncertain)",
|
|
1999
|
-
|
|
2147
|
+
"payment-attempt"
|
|
2000
2148
|
);
|
|
2001
2149
|
await safeEmit(
|
|
2002
|
-
buildEvent({
|
|
2150
|
+
buildEvent(flow, {
|
|
2003
2151
|
type: "payment.rejected",
|
|
2004
|
-
requestId: request.requestId,
|
|
2005
2152
|
resourceId: resource.id,
|
|
2006
2153
|
adapter: request.protocol,
|
|
2007
2154
|
paymentProvider: provider.name,
|
|
2008
2155
|
status: "error",
|
|
2009
2156
|
data: {
|
|
2010
2157
|
reason: "settlement-uncertain",
|
|
2011
|
-
...txHash !== void 0 ? { transactionHash: txHash } : {}
|
|
2158
|
+
...txHash !== void 0 ? { transactionHash: txHash } : {},
|
|
2159
|
+
...failuresOf(flow)
|
|
2012
2160
|
}
|
|
2013
2161
|
})
|
|
2014
2162
|
);
|
|
@@ -2024,8 +2172,9 @@ function createSettlement(ctx) {
|
|
|
2024
2172
|
});
|
|
2025
2173
|
}
|
|
2026
2174
|
if (settlement.status !== "settled") {
|
|
2027
|
-
await hold
|
|
2175
|
+
await finalizeHold(flow, hold, "release");
|
|
2028
2176
|
await safePersist(
|
|
2177
|
+
flow,
|
|
2029
2178
|
() => options.store.updatePaymentAttempt({
|
|
2030
2179
|
replayKey,
|
|
2031
2180
|
status: "rejected",
|
|
@@ -2033,17 +2182,19 @@ function createSettlement(ctx) {
|
|
|
2033
2182
|
...settlement.externalReference !== void 0 ? { externalReference: settlement.externalReference } : {}
|
|
2034
2183
|
}),
|
|
2035
2184
|
"updatePaymentAttempt(rejected)",
|
|
2036
|
-
|
|
2185
|
+
"payment-attempt"
|
|
2037
2186
|
);
|
|
2038
2187
|
await safeEmit(
|
|
2039
|
-
buildEvent({
|
|
2188
|
+
buildEvent(flow, {
|
|
2040
2189
|
type: "payment.rejected",
|
|
2041
|
-
requestId: request.requestId,
|
|
2042
2190
|
resourceId: resource.id,
|
|
2043
2191
|
adapter: request.protocol,
|
|
2044
2192
|
paymentProvider: provider.name,
|
|
2045
2193
|
status: "error",
|
|
2046
|
-
data:
|
|
2194
|
+
data: {
|
|
2195
|
+
...settlement.rejectionReason ? { reason: settlement.rejectionReason } : {},
|
|
2196
|
+
...failuresOf(flow)
|
|
2197
|
+
}
|
|
2047
2198
|
})
|
|
2048
2199
|
);
|
|
2049
2200
|
const rejectionDetails = retryChallenge(requirement, settlement.rejectionReason).details;
|
|
@@ -2061,20 +2212,20 @@ function createSettlement(ctx) {
|
|
|
2061
2212
|
}
|
|
2062
2213
|
);
|
|
2063
2214
|
}
|
|
2064
|
-
await hold
|
|
2215
|
+
await finalizeHold(flow, hold, "consume");
|
|
2065
2216
|
await safePersist(
|
|
2217
|
+
flow,
|
|
2066
2218
|
() => options.store.updatePaymentAttempt({
|
|
2067
2219
|
replayKey,
|
|
2068
2220
|
status: "settled",
|
|
2069
2221
|
...settlement.externalReference !== void 0 ? { externalReference: settlement.externalReference } : {}
|
|
2070
2222
|
}),
|
|
2071
2223
|
"updatePaymentAttempt(settled)",
|
|
2072
|
-
|
|
2224
|
+
"payment-attempt"
|
|
2073
2225
|
);
|
|
2074
2226
|
await safeEmit(
|
|
2075
|
-
buildEvent({
|
|
2227
|
+
buildEvent(flow, {
|
|
2076
2228
|
type: "payment.settled",
|
|
2077
|
-
requestId: request.requestId,
|
|
2078
2229
|
resourceId: resource.id,
|
|
2079
2230
|
adapter: request.protocol,
|
|
2080
2231
|
paymentProvider: provider.name,
|
|
@@ -2084,26 +2235,26 @@ function createSettlement(ctx) {
|
|
|
2084
2235
|
return settlement;
|
|
2085
2236
|
}
|
|
2086
2237
|
async function abandonSettlement(args, backendErrorCode) {
|
|
2087
|
-
const { request, resource, provider, replayKey, hold } = args;
|
|
2088
|
-
await hold
|
|
2238
|
+
const { flow, request, resource, provider, replayKey, hold } = args;
|
|
2239
|
+
await finalizeHold(flow, hold, "release");
|
|
2089
2240
|
await safePersist(
|
|
2241
|
+
flow,
|
|
2090
2242
|
() => options.store.updatePaymentAttempt({
|
|
2091
2243
|
replayKey,
|
|
2092
2244
|
status: "rejected",
|
|
2093
2245
|
rejectionReason: "backend_failed"
|
|
2094
2246
|
}),
|
|
2095
2247
|
"updatePaymentAttempt(backend-failed)",
|
|
2096
|
-
|
|
2248
|
+
"payment-attempt"
|
|
2097
2249
|
);
|
|
2098
2250
|
await safeEmit(
|
|
2099
|
-
buildEvent({
|
|
2251
|
+
buildEvent(flow, {
|
|
2100
2252
|
type: "payment.rejected",
|
|
2101
|
-
requestId: request.requestId,
|
|
2102
2253
|
resourceId: resource.id,
|
|
2103
2254
|
adapter: request.protocol,
|
|
2104
2255
|
paymentProvider: provider.name,
|
|
2105
2256
|
status: "error",
|
|
2106
|
-
data: { reason: "backend-failed", backendErrorCode }
|
|
2257
|
+
data: { reason: "backend-failed", backendErrorCode, ...failuresOf(flow) }
|
|
2107
2258
|
})
|
|
2108
2259
|
);
|
|
2109
2260
|
}
|
|
@@ -2140,7 +2291,7 @@ function createExecutionPipeline(options) {
|
|
|
2140
2291
|
return compiled;
|
|
2141
2292
|
}
|
|
2142
2293
|
const ctx = createPipelineContext(options);
|
|
2143
|
-
const { safeEmit, safePersist, buildEvent } = ctx;
|
|
2294
|
+
const { safeEmit, safePersist, recordStep, buildEvent } = ctx;
|
|
2144
2295
|
const { settle, abandonSettlement } = createSettlement(ctx);
|
|
2145
2296
|
const admitPayment = createPaymentAdmission(ctx, createAuthorizeAndReserve(ctx));
|
|
2146
2297
|
async function execute(request) {
|
|
@@ -2156,10 +2307,10 @@ function createExecutionPipeline(options) {
|
|
|
2156
2307
|
}
|
|
2157
2308
|
);
|
|
2158
2309
|
}
|
|
2310
|
+
const flow = createFlow(request, options.ids.next("txn"));
|
|
2159
2311
|
await safeEmit(
|
|
2160
|
-
buildEvent({
|
|
2312
|
+
buildEvent(flow, {
|
|
2161
2313
|
type: "resource.requested",
|
|
2162
|
-
requestId: request.requestId,
|
|
2163
2314
|
resourceId: resource.id,
|
|
2164
2315
|
adapter: request.protocol
|
|
2165
2316
|
})
|
|
@@ -2204,20 +2355,34 @@ function createExecutionPipeline(options) {
|
|
|
2204
2355
|
}
|
|
2205
2356
|
);
|
|
2206
2357
|
}
|
|
2207
|
-
let
|
|
2208
|
-
let authorization;
|
|
2209
|
-
let deferredSettlement;
|
|
2358
|
+
let settleArgs;
|
|
2210
2359
|
if (resource.pricing.type === "fixed") {
|
|
2211
|
-
const admission = await admitPayment(request, resource, resource.pricing, validInput);
|
|
2360
|
+
const admission = await admitPayment(flow, request, resource, resource.pricing, validInput);
|
|
2212
2361
|
if (admission.kind === "payment-required") return admission;
|
|
2213
|
-
|
|
2214
|
-
|
|
2362
|
+
settleArgs = admission.settleArgs;
|
|
2363
|
+
}
|
|
2364
|
+
try {
|
|
2365
|
+
return await settleAndDeliver(flow, resource, validInput, settleArgs, pipelineStart);
|
|
2366
|
+
} finally {
|
|
2367
|
+
await recordStep(flow, { kind: "completed", ...failuresOf(flow) });
|
|
2368
|
+
}
|
|
2369
|
+
}
|
|
2370
|
+
async function settleAndDeliver(flow, resource, validInput, settleArgs, pipelineStart) {
|
|
2371
|
+
const { request } = flow;
|
|
2372
|
+
const authorization = settleArgs?.hold?.record;
|
|
2373
|
+
let paymentResult;
|
|
2374
|
+
let deferredSettlement;
|
|
2375
|
+
if (settleArgs !== void 0) {
|
|
2215
2376
|
if (settleArgs.requirement.metadata?.[SETTLE_AFTER_BACKEND_METADATA_KEY] === true) {
|
|
2216
2377
|
deferredSettlement = settleArgs;
|
|
2217
2378
|
} else {
|
|
2218
2379
|
paymentResult = await settle(settleArgs);
|
|
2219
2380
|
}
|
|
2220
2381
|
}
|
|
2382
|
+
await recordStep(flow, {
|
|
2383
|
+
kind: "backend-dispatched",
|
|
2384
|
+
deadlineAt: backendDeadline(options.clock.now(), resource)
|
|
2385
|
+
});
|
|
2221
2386
|
const backendStart = options.clock.monotonicMs();
|
|
2222
2387
|
let backendResponse;
|
|
2223
2388
|
try {
|
|
@@ -2230,18 +2395,23 @@ function createExecutionPipeline(options) {
|
|
|
2230
2395
|
});
|
|
2231
2396
|
} catch (error) {
|
|
2232
2397
|
const commerceError = toCommerceError(error, "BACKEND_ERROR", "Backend call failed");
|
|
2233
|
-
await
|
|
2234
|
-
|
|
2398
|
+
await recordStep(flow, {
|
|
2399
|
+
kind: "backend-result",
|
|
2400
|
+
status: backendErrorStatus(commerceError),
|
|
2401
|
+
errorCode: commerceError.code
|
|
2402
|
+
});
|
|
2403
|
+
const backendFailed = (data = {}) => safeEmit(
|
|
2404
|
+
buildEvent(flow, {
|
|
2235
2405
|
type: "backend.failed",
|
|
2236
|
-
requestId: request.requestId,
|
|
2237
2406
|
resourceId: resource.id,
|
|
2238
2407
|
adapter: request.protocol,
|
|
2239
2408
|
status: "error",
|
|
2240
2409
|
durationMs: Math.round(options.clock.monotonicMs() - backendStart),
|
|
2241
|
-
data: { code: commerceError.code }
|
|
2410
|
+
data: { code: commerceError.code, ...data }
|
|
2242
2411
|
})
|
|
2243
2412
|
);
|
|
2244
2413
|
if (deferredSettlement !== void 0) {
|
|
2414
|
+
await backendFailed();
|
|
2245
2415
|
await abandonSettlement(deferredSettlement, commerceError.code);
|
|
2246
2416
|
throw commerceError;
|
|
2247
2417
|
}
|
|
@@ -2255,13 +2425,11 @@ function createExecutionPipeline(options) {
|
|
|
2255
2425
|
protocol: request.protocol,
|
|
2256
2426
|
payment: paymentResult,
|
|
2257
2427
|
...authorization !== void 0 ? { authorization } : {},
|
|
2258
|
-
metadata: { delivered: false, backendErrorCode: commerceError.code }
|
|
2428
|
+
metadata: { delivered: false, backendErrorCode: commerceError.code },
|
|
2429
|
+
transactionId: flow.transactionId
|
|
2259
2430
|
};
|
|
2260
|
-
await
|
|
2261
|
-
|
|
2262
|
-
"saveReceipt(backend-failed-after-settlement)",
|
|
2263
|
-
request.requestId
|
|
2264
|
-
);
|
|
2431
|
+
await saveReceipt(flow, failedReceipt, "saveReceipt(backend-failed-after-settlement)");
|
|
2432
|
+
await backendFailed(failuresOf(flow));
|
|
2265
2433
|
throw new CommerceError(
|
|
2266
2434
|
"BACKEND_ERROR",
|
|
2267
2435
|
"Payment settled but the backend call failed; the payment was not refunded automatically",
|
|
@@ -2285,12 +2453,13 @@ function createExecutionPipeline(options) {
|
|
|
2285
2453
|
}
|
|
2286
2454
|
);
|
|
2287
2455
|
}
|
|
2456
|
+
await backendFailed();
|
|
2288
2457
|
throw commerceError;
|
|
2289
2458
|
}
|
|
2459
|
+
await recordStep(flow, { kind: "backend-result", status: backendResponse.status });
|
|
2290
2460
|
await safeEmit(
|
|
2291
|
-
buildEvent({
|
|
2461
|
+
buildEvent(flow, {
|
|
2292
2462
|
type: "backend.called",
|
|
2293
|
-
requestId: request.requestId,
|
|
2294
2463
|
resourceId: resource.id,
|
|
2295
2464
|
adapter: request.protocol,
|
|
2296
2465
|
status: "ok",
|
|
@@ -2310,34 +2479,48 @@ function createExecutionPipeline(options) {
|
|
|
2310
2479
|
durationMs: backendResponse.durationMs,
|
|
2311
2480
|
protocol: request.protocol,
|
|
2312
2481
|
...paymentResult !== void 0 ? { payment: paymentResult } : {},
|
|
2313
|
-
...authorization !== void 0 ? { authorization } : {}
|
|
2482
|
+
...authorization !== void 0 ? { authorization } : {},
|
|
2483
|
+
transactionId: flow.transactionId
|
|
2314
2484
|
};
|
|
2315
|
-
await
|
|
2485
|
+
await saveReceipt(flow, receipt, "saveReceipt");
|
|
2316
2486
|
const totalDurationMs = Math.round(options.clock.monotonicMs() - pipelineStart);
|
|
2487
|
+
const failures = failuresOf(flow);
|
|
2317
2488
|
await safeEmit(
|
|
2318
|
-
buildEvent({
|
|
2489
|
+
buildEvent(flow, {
|
|
2319
2490
|
type: "resource.delivered",
|
|
2320
|
-
requestId: request.requestId,
|
|
2321
2491
|
resourceId: resource.id,
|
|
2322
2492
|
adapter: request.protocol,
|
|
2323
2493
|
status: "ok",
|
|
2324
|
-
durationMs: totalDurationMs
|
|
2494
|
+
durationMs: totalDurationMs,
|
|
2495
|
+
...failures.persistenceFailures !== void 0 ? { data: failures } : {}
|
|
2325
2496
|
})
|
|
2326
2497
|
);
|
|
2327
2498
|
return {
|
|
2328
2499
|
kind: "delivered",
|
|
2329
2500
|
requestId: request.requestId,
|
|
2501
|
+
transactionId: flow.transactionId,
|
|
2330
2502
|
resourceId: resource.id,
|
|
2331
2503
|
backendStatus: backendResponse.status,
|
|
2332
2504
|
body: backendResponse.body,
|
|
2333
2505
|
headers: backendResponse.headers,
|
|
2334
2506
|
...paymentResult !== void 0 ? { payment: paymentResult } : {},
|
|
2335
2507
|
receipt,
|
|
2336
|
-
durationMs: totalDurationMs
|
|
2508
|
+
durationMs: totalDurationMs,
|
|
2509
|
+
...failures
|
|
2337
2510
|
};
|
|
2338
2511
|
}
|
|
2512
|
+
async function saveReceipt(flow, receipt, label) {
|
|
2513
|
+
if (await safePersist(flow, () => options.store.saveReceipt(receipt), label, "receipt")) {
|
|
2514
|
+
await recordStep(flow, { kind: "receipt", receiptId: receipt.id });
|
|
2515
|
+
}
|
|
2516
|
+
}
|
|
2339
2517
|
return { execute };
|
|
2340
2518
|
}
|
|
2519
|
+
var BACKEND_DEADLINE_MARGIN_MS = 5e3;
|
|
2520
|
+
function backendDeadline(dispatchedAt, resource) {
|
|
2521
|
+
const timeoutMs = resource.handler.timeoutMs ?? DEFAULT_BACKEND_TIMEOUT_MS;
|
|
2522
|
+
return new Date(dispatchedAt.getTime() + timeoutMs + BACKEND_DEADLINE_MARGIN_MS).toISOString();
|
|
2523
|
+
}
|
|
2341
2524
|
function backendErrorStatus(error) {
|
|
2342
2525
|
const status = error.details?.["status"];
|
|
2343
2526
|
return typeof status === "number" ? status : 0;
|
|
@@ -2914,9 +3097,7 @@ function normalize(raw) {
|
|
|
2914
3097
|
const x402 = x402Settings?.config;
|
|
2915
3098
|
const mpp = normalizeMpp(raw.payments.mpp);
|
|
2916
3099
|
const ap2 = normalizeAp2(raw.authorization?.ap2);
|
|
2917
|
-
|
|
2918
|
-
validateReplayStoreIsolated(ap2.replay.path, raw.storage.receipts.path, protocols.acp);
|
|
2919
|
-
}
|
|
3100
|
+
validateLegacyStoresIsolated(ap2, protocols.acp, raw.storage.receipts.path);
|
|
2920
3101
|
const resources = Object.entries(raw.resources).map(
|
|
2921
3102
|
([id, entry]) => normalizeResource(id, entry, protocols, x402Settings, mpp, ap2)
|
|
2922
3103
|
);
|
|
@@ -3468,6 +3649,168 @@ function wrapPino(instance) {
|
|
|
3468
3649
|
return logger;
|
|
3469
3650
|
}
|
|
3470
3651
|
|
|
3652
|
+
// src/core/execution/reconcile.ts
|
|
3653
|
+
var DEFAULT_RECONCILE_MIN_AGE_MS = 15 * 60 * 1e3;
|
|
3654
|
+
function journalOf(store) {
|
|
3655
|
+
const {
|
|
3656
|
+
listTransactions,
|
|
3657
|
+
getTransaction,
|
|
3658
|
+
getPaymentAttempt,
|
|
3659
|
+
resolvePaymentAttempt,
|
|
3660
|
+
recordTransactionStep
|
|
3661
|
+
} = store;
|
|
3662
|
+
if (!listTransactions || !getTransaction || !getPaymentAttempt || !resolvePaymentAttempt || !recordTransactionStep) {
|
|
3663
|
+
throw new CommerceError("STORAGE_ERROR", "The receipt store has no transaction journal");
|
|
3664
|
+
}
|
|
3665
|
+
return {
|
|
3666
|
+
listTransactions: listTransactions.bind(store),
|
|
3667
|
+
getTransaction: getTransaction.bind(store),
|
|
3668
|
+
getPaymentAttempt: getPaymentAttempt.bind(store),
|
|
3669
|
+
resolvePaymentAttempt: resolvePaymentAttempt.bind(store),
|
|
3670
|
+
recordTransactionStep: recordTransactionStep.bind(store)
|
|
3671
|
+
};
|
|
3672
|
+
}
|
|
3673
|
+
var REFUSAL_MESSAGES = {
|
|
3674
|
+
already_resolved: "The payment attempt already has a resolution",
|
|
3675
|
+
not_resolvable: "Only reserved, settlement-uncertain and failed payment attempts can be resolved",
|
|
3676
|
+
too_recent: "The payment attempt is reserved and may still be in flight; retry once it is 15 minutes old",
|
|
3677
|
+
not_expired: "The recorded authorization expiry is still in the future",
|
|
3678
|
+
expiry_unknown: "No expiry is recorded for this authorization; confirm that it has expired"
|
|
3679
|
+
};
|
|
3680
|
+
var MAX_ACTOR_LENGTH = 256;
|
|
3681
|
+
var MAX_REASON_LENGTH = 1024;
|
|
3682
|
+
var MAX_REFERENCE_LENGTH = 256;
|
|
3683
|
+
var RESOLVABLE = [
|
|
3684
|
+
"reserved",
|
|
3685
|
+
"settlement-uncertain",
|
|
3686
|
+
"failed"
|
|
3687
|
+
];
|
|
3688
|
+
async function resolveManually(options) {
|
|
3689
|
+
const { clock, logger, attemptId, status, externalReference } = options;
|
|
3690
|
+
if (status !== "settled" && status !== "rejected") {
|
|
3691
|
+
throw invalid("status", 'status must be "settled" or "rejected"');
|
|
3692
|
+
}
|
|
3693
|
+
const actor = requiredText(options.actor, "actor", MAX_ACTOR_LENGTH);
|
|
3694
|
+
const reason = requiredText(options.reason, "reason", MAX_REASON_LENGTH);
|
|
3695
|
+
if (externalReference !== void 0) {
|
|
3696
|
+
requiredText(externalReference, "externalReference", MAX_REFERENCE_LENGTH);
|
|
3697
|
+
}
|
|
3698
|
+
const journal = journalOf(options.store);
|
|
3699
|
+
const attempt = await journal.getPaymentAttempt(attemptId);
|
|
3700
|
+
if (attempt === void 0) {
|
|
3701
|
+
throw new CommerceError("RESOURCE_NOT_FOUND", `Payment attempt "${attemptId}" was not found`);
|
|
3702
|
+
}
|
|
3703
|
+
const refuse = (refusal, current2 = attempt) => ({
|
|
3704
|
+
resolved: false,
|
|
3705
|
+
refusal,
|
|
3706
|
+
message: REFUSAL_MESSAGES[refusal],
|
|
3707
|
+
attempt: current2
|
|
3708
|
+
});
|
|
3709
|
+
if (attempt.resolution !== void 0) return refuse("already_resolved");
|
|
3710
|
+
if (!RESOLVABLE.includes(attempt.status)) return refuse("not_resolvable");
|
|
3711
|
+
if (attempt.status === "reserved" && !(clock.now().getTime() - Date.parse(attempt.createdAt) >= DEFAULT_RECONCILE_MIN_AGE_MS)) {
|
|
3712
|
+
return refuse("too_recent");
|
|
3713
|
+
}
|
|
3714
|
+
const transaction = attempt.transactionId !== void 0 ? await journal.getTransaction(attempt.transactionId) : void 0;
|
|
3715
|
+
if (status === "rejected") {
|
|
3716
|
+
const expiresAt = Date.parse(transaction?.payment.expiresAt ?? "");
|
|
3717
|
+
if (expiresAt > clock.now().getTime()) return refuse("not_expired");
|
|
3718
|
+
if (Number.isNaN(expiresAt) && options.confirmExpired !== true) {
|
|
3719
|
+
return refuse("expiry_unknown");
|
|
3720
|
+
}
|
|
3721
|
+
}
|
|
3722
|
+
const written = await journal.resolvePaymentAttempt({
|
|
3723
|
+
attemptId,
|
|
3724
|
+
expectedStatus: attempt.status,
|
|
3725
|
+
status,
|
|
3726
|
+
...status === "rejected" ? { rejectionReason: "not_settled" } : {},
|
|
3727
|
+
resolution: {
|
|
3728
|
+
method: "manual",
|
|
3729
|
+
actor,
|
|
3730
|
+
reason,
|
|
3731
|
+
at: clock.nowIso(),
|
|
3732
|
+
...externalReference !== void 0 ? { externalReference } : {}
|
|
3733
|
+
}
|
|
3734
|
+
});
|
|
3735
|
+
const current = await journal.getPaymentAttempt(attemptId) ?? attempt;
|
|
3736
|
+
if (!written) {
|
|
3737
|
+
return refuse(
|
|
3738
|
+
current.resolution !== void 0 ? "already_resolved" : "not_resolvable",
|
|
3739
|
+
current
|
|
3740
|
+
);
|
|
3741
|
+
}
|
|
3742
|
+
const resolved = transaction !== void 0 ? await journal.getTransaction(transaction.id) : void 0;
|
|
3743
|
+
const target = resolved !== void 0 ? holdTarget(resolved) : void 0;
|
|
3744
|
+
const hold = resolved !== void 0 && target !== void 0 ? await alignHold(resolved, target, {
|
|
3745
|
+
journal,
|
|
3746
|
+
authorizationProviders: options.authorizationProviders,
|
|
3747
|
+
clock,
|
|
3748
|
+
logger
|
|
3749
|
+
}) : void 0;
|
|
3750
|
+
return { resolved: true, attempt: current, ...hold !== void 0 ? { hold } : {} };
|
|
3751
|
+
}
|
|
3752
|
+
function requiredText(value, field, max) {
|
|
3753
|
+
if (value.trim() === "" || value.length > max) {
|
|
3754
|
+
throw invalid(field, `${field} must be non-empty and at most ${max} characters`);
|
|
3755
|
+
}
|
|
3756
|
+
return value;
|
|
3757
|
+
}
|
|
3758
|
+
function invalid(field, message) {
|
|
3759
|
+
return new CommerceError("INPUT_INVALID", message, { details: { field } });
|
|
3760
|
+
}
|
|
3761
|
+
function holdTarget(transaction) {
|
|
3762
|
+
const hold = transaction.authorization?.hold;
|
|
3763
|
+
if (hold !== "reserved" && hold !== "uncertain") return void 0;
|
|
3764
|
+
if (transaction.payment.status === "settled") return "consumed";
|
|
3765
|
+
if (transaction.payment.status === "rejected") return "released";
|
|
3766
|
+
return void 0;
|
|
3767
|
+
}
|
|
3768
|
+
function holdEntry(transaction, hold, written, reason) {
|
|
3769
|
+
return {
|
|
3770
|
+
transactionId: transaction.id,
|
|
3771
|
+
attemptId: transaction.payment.attemptId,
|
|
3772
|
+
method: transaction.authorization?.method ?? "",
|
|
3773
|
+
hold,
|
|
3774
|
+
written,
|
|
3775
|
+
...reason !== void 0 ? { reason } : {}
|
|
3776
|
+
};
|
|
3777
|
+
}
|
|
3778
|
+
async function alignHold(transaction, target, deps) {
|
|
3779
|
+
const authorization = transaction.authorization;
|
|
3780
|
+
const provider = deps.authorizationProviders.find(
|
|
3781
|
+
(candidate) => candidate.name === authorization?.method
|
|
3782
|
+
);
|
|
3783
|
+
if (authorization === void 0 || provider === void 0) {
|
|
3784
|
+
return holdEntry(transaction, target, false, "provider_not_enabled");
|
|
3785
|
+
}
|
|
3786
|
+
const context = { requestId: transaction.requestId, resourceId: transaction.resourceId };
|
|
3787
|
+
try {
|
|
3788
|
+
if (target === "consumed") await provider.consume(authorization.reservationId, context);
|
|
3789
|
+
else await provider.release(authorization.reservationId, context);
|
|
3790
|
+
} catch (err) {
|
|
3791
|
+
deps.logger?.warn(
|
|
3792
|
+
{ transactionId: transaction.id, method: provider.name, err: redactedErrorText(err) },
|
|
3793
|
+
"reconcile: authorization provider threw"
|
|
3794
|
+
);
|
|
3795
|
+
return holdEntry(transaction, target, false, "provider_error");
|
|
3796
|
+
}
|
|
3797
|
+
try {
|
|
3798
|
+
await deps.journal.recordTransactionStep({
|
|
3799
|
+
transactionId: transaction.id,
|
|
3800
|
+
at: deps.clock.nowIso(),
|
|
3801
|
+
kind: "hold",
|
|
3802
|
+
hold: target
|
|
3803
|
+
});
|
|
3804
|
+
} catch (err) {
|
|
3805
|
+
deps.logger?.warn(
|
|
3806
|
+
{ transactionId: transaction.id, err: redactedErrorText(err) },
|
|
3807
|
+
"reconcile: could not record the hold update"
|
|
3808
|
+
);
|
|
3809
|
+
return holdEntry(transaction, target, false, "journal_error");
|
|
3810
|
+
}
|
|
3811
|
+
return holdEntry(transaction, target, true);
|
|
3812
|
+
}
|
|
3813
|
+
|
|
3471
3814
|
// src/gateway/public-resource.ts
|
|
3472
3815
|
function toPublicResource(resource) {
|
|
3473
3816
|
return {
|
|
@@ -3721,6 +4064,15 @@ function buildWellKnownDocument(options) {
|
|
|
3721
4064
|
|
|
3722
4065
|
// src/gateway/routes.ts
|
|
3723
4066
|
var X402_V1_PAYMENT_HEADER = "x-payment";
|
|
4067
|
+
var RESOLVE_BODY_LIMIT_BYTES = 4096;
|
|
4068
|
+
var RESOLVE_FIELDS = [
|
|
4069
|
+
"status",
|
|
4070
|
+
"actor",
|
|
4071
|
+
"reason",
|
|
4072
|
+
"externalReference",
|
|
4073
|
+
"confirmExpired"
|
|
4074
|
+
];
|
|
4075
|
+
var TRANSACTION_EVENT_LIMIT = 50;
|
|
3724
4076
|
function registerRoutes(options) {
|
|
3725
4077
|
const { server } = options;
|
|
3726
4078
|
const readinessProbe = createReadinessProbe({
|
|
@@ -3788,6 +4140,113 @@ function registerRoutes(options) {
|
|
|
3788
4140
|
)
|
|
3789
4141
|
)
|
|
3790
4142
|
);
|
|
4143
|
+
const { store, clock } = options;
|
|
4144
|
+
const journal = () => journalOf(store);
|
|
4145
|
+
const withAge = (transaction) => ({
|
|
4146
|
+
...transaction,
|
|
4147
|
+
ageSeconds: Math.max(
|
|
4148
|
+
0,
|
|
4149
|
+
Math.floor((clock.now().getTime() - Date.parse(transaction.createdAt)) / 1e3)
|
|
4150
|
+
)
|
|
4151
|
+
});
|
|
4152
|
+
server.get(
|
|
4153
|
+
"/api/transactions",
|
|
4154
|
+
{ onRequest: tokenHook },
|
|
4155
|
+
operatorHandler(async (request) => {
|
|
4156
|
+
const query = request.query;
|
|
4157
|
+
const limit = parseLimit(query["limit"]);
|
|
4158
|
+
const state = parseText(query["state"]);
|
|
4159
|
+
if (state !== void 0 && !TRANSACTION_STATES.includes(state)) {
|
|
4160
|
+
throw new CommerceError("INPUT_INVALID", `Unknown transaction state "${state}"`, {
|
|
4161
|
+
details: { field: "state" }
|
|
4162
|
+
});
|
|
4163
|
+
}
|
|
4164
|
+
const requestId = parseText(query["requestId"]);
|
|
4165
|
+
const cursor = parseText(query["cursor"]);
|
|
4166
|
+
const page = await journal().listTransactions({
|
|
4167
|
+
...limit !== void 0 ? { limit } : {},
|
|
4168
|
+
...parseFlag(query["unresolved"], "unresolved") ? { unresolved: true } : {},
|
|
4169
|
+
...state !== void 0 ? { state } : {},
|
|
4170
|
+
...requestId !== void 0 ? { requestId } : {},
|
|
4171
|
+
...cursor !== void 0 ? { cursor } : {}
|
|
4172
|
+
});
|
|
4173
|
+
return {
|
|
4174
|
+
transactions: page.transactions.map(withAge),
|
|
4175
|
+
...page.nextCursor !== void 0 ? { nextCursor: page.nextCursor } : {}
|
|
4176
|
+
};
|
|
4177
|
+
})
|
|
4178
|
+
);
|
|
4179
|
+
server.get(
|
|
4180
|
+
"/api/transactions/:id",
|
|
4181
|
+
{ onRequest: tokenHook },
|
|
4182
|
+
operatorHandler(async (request) => {
|
|
4183
|
+
const id = request.params.id;
|
|
4184
|
+
const transaction = await journal().getTransaction(id);
|
|
4185
|
+
if (transaction === void 0) {
|
|
4186
|
+
throw new CommerceError("RESOURCE_NOT_FOUND", `Transaction "${id}" was not found`);
|
|
4187
|
+
}
|
|
4188
|
+
const [attempt, receipt, events] = await Promise.all([
|
|
4189
|
+
journal().getPaymentAttempt(transaction.payment.attemptId),
|
|
4190
|
+
transaction.receiptId !== void 0 ? store.getReceipt(transaction.receiptId) : void 0,
|
|
4191
|
+
store.listEvents({ requestId: transaction.requestId, limit: TRANSACTION_EVENT_LIMIT })
|
|
4192
|
+
]);
|
|
4193
|
+
return {
|
|
4194
|
+
transaction: withAge(transaction),
|
|
4195
|
+
...attempt !== void 0 ? { attempt } : {},
|
|
4196
|
+
...receipt !== void 0 ? { receipt } : {},
|
|
4197
|
+
events
|
|
4198
|
+
};
|
|
4199
|
+
})
|
|
4200
|
+
);
|
|
4201
|
+
server.post(
|
|
4202
|
+
"/api/payment-attempts/:id/resolve",
|
|
4203
|
+
{ onRequest: tokenHook, bodyLimit: RESOLVE_BODY_LIMIT_BYTES },
|
|
4204
|
+
operatorHandler(async (request) => {
|
|
4205
|
+
const result = await resolveManually({
|
|
4206
|
+
store,
|
|
4207
|
+
authorizationProviders: options.authorizationProviders,
|
|
4208
|
+
clock,
|
|
4209
|
+
logger: options.logger,
|
|
4210
|
+
attemptId: request.params.id,
|
|
4211
|
+
...parseResolveBody(request.body)
|
|
4212
|
+
});
|
|
4213
|
+
if (!result.resolved) {
|
|
4214
|
+
throw new CommerceError("INPUT_INVALID", result.message, {
|
|
4215
|
+
httpStatus: 409,
|
|
4216
|
+
details: { reason: result.refusal, attemptStatus: result.attempt.status }
|
|
4217
|
+
});
|
|
4218
|
+
}
|
|
4219
|
+
return {
|
|
4220
|
+
attempt: result.attempt,
|
|
4221
|
+
...result.hold !== void 0 ? { hold: result.hold } : {}
|
|
4222
|
+
};
|
|
4223
|
+
})
|
|
4224
|
+
);
|
|
4225
|
+
}
|
|
4226
|
+
function parseResolveBody(body) {
|
|
4227
|
+
if (!isRecord(body)) {
|
|
4228
|
+
throw new CommerceError("INPUT_INVALID", "The request body must be a JSON object");
|
|
4229
|
+
}
|
|
4230
|
+
const field = (name, type, required) => {
|
|
4231
|
+
const value = body[name];
|
|
4232
|
+
if (value === void 0 && required || value !== void 0 && typeof value !== type) {
|
|
4233
|
+
throw new CommerceError("INPUT_INVALID", `Field "${name}" must be a ${type}`, {
|
|
4234
|
+
details: { field: name }
|
|
4235
|
+
});
|
|
4236
|
+
}
|
|
4237
|
+
};
|
|
4238
|
+
const unknownField = Object.keys(body).find((name) => !RESOLVE_FIELDS.includes(name));
|
|
4239
|
+
if (unknownField !== void 0) {
|
|
4240
|
+
throw new CommerceError("INPUT_INVALID", `Unknown field "${unknownField}"`, {
|
|
4241
|
+
details: { field: unknownField }
|
|
4242
|
+
});
|
|
4243
|
+
}
|
|
4244
|
+
field("status", "string", true);
|
|
4245
|
+
field("actor", "string", true);
|
|
4246
|
+
field("reason", "string", true);
|
|
4247
|
+
field("externalReference", "string", false);
|
|
4248
|
+
field("confirmExpired", "boolean", false);
|
|
4249
|
+
return body;
|
|
3791
4250
|
}
|
|
3792
4251
|
var bodyDigests = /* @__PURE__ */ new WeakMap();
|
|
3793
4252
|
function digestingStream(request) {
|
|
@@ -3803,13 +4262,10 @@ function digestingStream(request) {
|
|
|
3803
4262
|
}
|
|
3804
4263
|
});
|
|
3805
4264
|
}
|
|
3806
|
-
function
|
|
4265
|
+
function operatorHandler(handle) {
|
|
3807
4266
|
return async (request, reply) => {
|
|
3808
4267
|
try {
|
|
3809
|
-
|
|
3810
|
-
const limit = parseLimit(query["limit"]);
|
|
3811
|
-
const page = await list(limit !== void 0 ? { limit } : {}, query);
|
|
3812
|
-
return { [key]: page };
|
|
4268
|
+
return await handle(request, reply);
|
|
3813
4269
|
} catch (error) {
|
|
3814
4270
|
const commerceError = toCommerceError(error);
|
|
3815
4271
|
reply.status(commerceError.httpStatus).send(toErrorEnvelope(commerceError));
|
|
@@ -3817,6 +4273,14 @@ function ledgerHandler(key, list) {
|
|
|
3817
4273
|
}
|
|
3818
4274
|
};
|
|
3819
4275
|
}
|
|
4276
|
+
function ledgerHandler(key, list) {
|
|
4277
|
+
return operatorHandler(async (request) => {
|
|
4278
|
+
const query = request.query;
|
|
4279
|
+
const limit = parseLimit(query["limit"]);
|
|
4280
|
+
const page = await list(limit !== void 0 ? { limit } : {}, query);
|
|
4281
|
+
return { [key]: page };
|
|
4282
|
+
});
|
|
4283
|
+
}
|
|
3820
4284
|
async function handleInvoke(request, reply, options) {
|
|
3821
4285
|
const resourceId = request.params.id;
|
|
3822
4286
|
let paymentMethod;
|
|
@@ -3997,6 +4461,10 @@ function parseLimit(value) {
|
|
|
3997
4461
|
}
|
|
3998
4462
|
return n;
|
|
3999
4463
|
}
|
|
4464
|
+
function parseText(value) {
|
|
4465
|
+
if (Array.isArray(value)) return parseText(value[0]);
|
|
4466
|
+
return typeof value === "string" && value !== "" ? value : void 0;
|
|
4467
|
+
}
|
|
4000
4468
|
function parseFlag(value, field) {
|
|
4001
4469
|
if (Array.isArray(value)) return parseFlag(value[0], field);
|
|
4002
4470
|
if (value === void 0 || value === "false") return false;
|
|
@@ -4108,8 +4576,14 @@ async function createGateway(options) {
|
|
|
4108
4576
|
return { url };
|
|
4109
4577
|
},
|
|
4110
4578
|
async close() {
|
|
4579
|
+
const sweep = setInterval(() => server.server.closeIdleConnections(), 100);
|
|
4580
|
+
sweep.unref();
|
|
4581
|
+
try {
|
|
4582
|
+
await server.close();
|
|
4583
|
+
} finally {
|
|
4584
|
+
clearInterval(sweep);
|
|
4585
|
+
}
|
|
4111
4586
|
await stopAdapters(adapterRuntimes, logger);
|
|
4112
|
-
await server.close();
|
|
4113
4587
|
},
|
|
4114
4588
|
server
|
|
4115
4589
|
};
|
|
@@ -4258,21 +4732,20 @@ var A2A_CALL_SHAPE = 'one data part {"resource": "<skill id>", "input": {...}}';
|
|
|
4258
4732
|
function userRoleProblem(role) {
|
|
4259
4733
|
return role === A2A_USER_ROLE ? void 0 : `Unsupported message role "${String(role)}": only ${A2A_USER_ROLE} is accepted.`;
|
|
4260
4734
|
}
|
|
4261
|
-
var UnknownRecord = z.record(z.string(), z.unknown());
|
|
4262
4735
|
var MessageSchema = z.object({
|
|
4263
4736
|
role: z.string(),
|
|
4264
4737
|
messageId: z.string().optional(),
|
|
4265
|
-
parts: z.array(
|
|
4738
|
+
parts: z.array(z.unknown()),
|
|
4266
4739
|
taskId: z.string().optional(),
|
|
4267
4740
|
contextId: z.string().optional(),
|
|
4268
|
-
referenceTaskIds: z.array(z.
|
|
4741
|
+
referenceTaskIds: z.array(z.unknown()).optional()
|
|
4269
4742
|
});
|
|
4270
4743
|
var ParamsSchema = z.object({
|
|
4271
4744
|
message: MessageSchema,
|
|
4272
4745
|
taskId: z.string().optional(),
|
|
4273
4746
|
contextId: z.string().optional()
|
|
4274
4747
|
});
|
|
4275
|
-
function
|
|
4748
|
+
function invalid2(message) {
|
|
4276
4749
|
return new CommerceError("INPUT_INVALID", message);
|
|
4277
4750
|
}
|
|
4278
4751
|
function unsupported(message, a2aErrorCode) {
|
|
@@ -4286,7 +4759,7 @@ function assertNoContinuation(params) {
|
|
|
4286
4759
|
const message = params.message;
|
|
4287
4760
|
if (params.taskId !== void 0 || message.taskId !== void 0) {
|
|
4288
4761
|
throw unsupported(
|
|
4289
|
-
"Task not found:
|
|
4762
|
+
"Task not found: only a task waiting for payment can be continued, so send a request with no taskId.",
|
|
4290
4763
|
A2A_ERROR_TASK_NOT_FOUND
|
|
4291
4764
|
);
|
|
4292
4765
|
}
|
|
@@ -4313,7 +4786,7 @@ function assertSupportedPart(part) {
|
|
|
4313
4786
|
);
|
|
4314
4787
|
}
|
|
4315
4788
|
if (!("data" in part)) {
|
|
4316
|
-
throw
|
|
4789
|
+
throw invalid2('Message part carries no "data": send a structured data part.');
|
|
4317
4790
|
}
|
|
4318
4791
|
const mediaType = part["mediaType"];
|
|
4319
4792
|
if (mediaType !== void 0 && mediaType !== A2A_JSON_MEDIA_TYPE) {
|
|
@@ -4326,21 +4799,21 @@ function assertSupportedPart(part) {
|
|
|
4326
4799
|
function parseInvocation(rawParams) {
|
|
4327
4800
|
const parsed = ParamsSchema.safeParse(rawParams);
|
|
4328
4801
|
if (!parsed.success) {
|
|
4329
|
-
throw
|
|
4802
|
+
throw invalid2(
|
|
4330
4803
|
'Request must carry a "message" with a "role" and a "parts" array of structured data parts.'
|
|
4331
4804
|
);
|
|
4332
4805
|
}
|
|
4333
4806
|
const params = parsed.data;
|
|
4334
4807
|
const message = params.message;
|
|
4335
4808
|
if (message.messageId === void 0 || message.messageId.length === 0) {
|
|
4336
|
-
throw
|
|
4809
|
+
throw invalid2('Message must carry a non-empty "messageId".');
|
|
4337
4810
|
}
|
|
4338
4811
|
const messageId = message.messageId;
|
|
4339
4812
|
assertNoContinuation(params);
|
|
4340
4813
|
const roleProblem = userRoleProblem(message.role);
|
|
4341
|
-
if (roleProblem !== void 0) throw
|
|
4814
|
+
if (roleProblem !== void 0) throw invalid2(roleProblem);
|
|
4342
4815
|
if (message.parts.length === 0) {
|
|
4343
|
-
throw
|
|
4816
|
+
throw invalid2("Message carries no parts: send exactly one structured data part.");
|
|
4344
4817
|
}
|
|
4345
4818
|
if (message.parts.length > 1) {
|
|
4346
4819
|
throw unsupported(
|
|
@@ -4348,22 +4821,23 @@ function parseInvocation(rawParams) {
|
|
|
4348
4821
|
);
|
|
4349
4822
|
}
|
|
4350
4823
|
const part = message.parts[0];
|
|
4351
|
-
if (part === void 0) throw
|
|
4824
|
+
if (part === void 0) throw invalid2("Message carries no parts.");
|
|
4825
|
+
if (!isRecord(part)) throw invalid2("Message part must be a JSON object.");
|
|
4352
4826
|
assertSupportedPart(part);
|
|
4353
4827
|
const data = part["data"];
|
|
4354
4828
|
if (!isRecord(data)) {
|
|
4355
|
-
throw
|
|
4829
|
+
throw invalid2('Message part "data" must be a JSON object.');
|
|
4356
4830
|
}
|
|
4357
4831
|
const resourceId = data["resource"];
|
|
4358
4832
|
if (typeof resourceId !== "string") {
|
|
4359
|
-
throw
|
|
4833
|
+
throw invalid2('Message part data must carry a "resource" string naming a canonical resource.');
|
|
4360
4834
|
}
|
|
4361
4835
|
if (resourceId.length === 0) {
|
|
4362
|
-
throw
|
|
4836
|
+
throw invalid2('Message part data "resource" must not be empty.');
|
|
4363
4837
|
}
|
|
4364
4838
|
const rawInput = data["input"];
|
|
4365
4839
|
if (rawInput !== void 0 && !isRecord(rawInput)) {
|
|
4366
|
-
throw
|
|
4840
|
+
throw invalid2('Message part data "input" must be a JSON object.');
|
|
4367
4841
|
}
|
|
4368
4842
|
return { resourceId, input: rawInput ?? {}, messageId };
|
|
4369
4843
|
}
|
|
@@ -4385,6 +4859,11 @@ function requestsX402Extension(header2) {
|
|
|
4385
4859
|
(value) => value.split(",").some((uri) => uri.trim() === A2A_X402_EXTENSION_URI)
|
|
4386
4860
|
);
|
|
4387
4861
|
}
|
|
4862
|
+
function expiryMs(nowMs, expiresAt) {
|
|
4863
|
+
const requested = expiresAt !== void 0 ? Date.parse(expiresAt) : Number.NaN;
|
|
4864
|
+
const ttl = Number.isFinite(requested) ? requested - nowMs : DEFAULT_PENDING_TTL_MS;
|
|
4865
|
+
return nowMs + Math.min(Math.max(ttl, 0), MAX_PENDING_TTL_MS);
|
|
4866
|
+
}
|
|
4388
4867
|
function createPendingPayments(clock, maxEntries = MAX_PENDING_PAYMENTS) {
|
|
4389
4868
|
const tasks = /* @__PURE__ */ new Map();
|
|
4390
4869
|
const now = () => clock.now().getTime();
|
|
@@ -4394,28 +4873,27 @@ function createPendingPayments(clock, maxEntries = MAX_PENDING_PAYMENTS) {
|
|
|
4394
4873
|
if (pending.expiresAtMs <= at) tasks.delete(taskId);
|
|
4395
4874
|
}
|
|
4396
4875
|
}
|
|
4876
|
+
function get(taskId) {
|
|
4877
|
+
const pending = tasks.get(taskId);
|
|
4878
|
+
if (pending === void 0) return void 0;
|
|
4879
|
+
if (pending.expiresAtMs <= now()) {
|
|
4880
|
+
tasks.delete(taskId);
|
|
4881
|
+
return void 0;
|
|
4882
|
+
}
|
|
4883
|
+
return pending;
|
|
4884
|
+
}
|
|
4397
4885
|
return {
|
|
4398
|
-
/** Holds a purchase until `expiresAt`; returns false, holding nothing, when full */
|
|
4399
4886
|
put(taskId, pending, expiresAt) {
|
|
4400
4887
|
purgeExpired();
|
|
4401
4888
|
if (tasks.size >= maxEntries) return false;
|
|
4402
|
-
|
|
4403
|
-
const ttl = Number.isFinite(requested) ? requested - now() : DEFAULT_PENDING_TTL_MS;
|
|
4404
|
-
const expiresAtMs = now() + Math.min(Math.max(ttl, 0), MAX_PENDING_TTL_MS);
|
|
4405
|
-
tasks.set(taskId, { ...pending, expiresAtMs });
|
|
4889
|
+
tasks.set(taskId, { ...pending, expiresAtMs: expiryMs(now(), expiresAt) });
|
|
4406
4890
|
return true;
|
|
4407
4891
|
},
|
|
4408
|
-
get
|
|
4409
|
-
|
|
4410
|
-
|
|
4411
|
-
if (pending.expiresAtMs <= now()) {
|
|
4412
|
-
tasks.delete(taskId);
|
|
4413
|
-
return void 0;
|
|
4414
|
-
}
|
|
4415
|
-
return pending;
|
|
4416
|
-
},
|
|
4417
|
-
delete(taskId) {
|
|
4892
|
+
get,
|
|
4893
|
+
take(taskId) {
|
|
4894
|
+
const pending = get(taskId);
|
|
4418
4895
|
tasks.delete(taskId);
|
|
4896
|
+
return pending;
|
|
4419
4897
|
},
|
|
4420
4898
|
size() {
|
|
4421
4899
|
return tasks.size;
|
|
@@ -4425,6 +4903,73 @@ function createPendingPayments(clock, maxEntries = MAX_PENDING_PAYMENTS) {
|
|
|
4425
4903
|
}
|
|
4426
4904
|
};
|
|
4427
4905
|
}
|
|
4906
|
+
function createStoredPendingPayments(store, clock, maxTasks = MAX_PENDING_PAYMENTS) {
|
|
4907
|
+
const mandates = /* @__PURE__ */ new Map();
|
|
4908
|
+
const now = () => clock.now().getTime();
|
|
4909
|
+
function purgeExpired() {
|
|
4910
|
+
const at = now();
|
|
4911
|
+
for (const [taskId, held] of mandates) {
|
|
4912
|
+
if (held.expiresAtMs <= at) mandates.delete(taskId);
|
|
4913
|
+
}
|
|
4914
|
+
}
|
|
4915
|
+
function toPending(task2) {
|
|
4916
|
+
const { contextId, network } = task2.adapterData ?? {};
|
|
4917
|
+
if (task2.protocol !== "a2a" || typeof contextId !== "string") return void 0;
|
|
4918
|
+
purgeExpired();
|
|
4919
|
+
const authorization = mandates.get(task2.id)?.authorization;
|
|
4920
|
+
return {
|
|
4921
|
+
contextId,
|
|
4922
|
+
resourceId: task2.resourceId,
|
|
4923
|
+
input: task2.input,
|
|
4924
|
+
...authorization !== void 0 ? { authorization } : {},
|
|
4925
|
+
...typeof network === "string" ? { network } : {},
|
|
4926
|
+
expiresAtMs: Date.parse(task2.expiresAt)
|
|
4927
|
+
};
|
|
4928
|
+
}
|
|
4929
|
+
return {
|
|
4930
|
+
async put(taskId, pending, expiresAt) {
|
|
4931
|
+
const expiresAtMs = expiryMs(now(), expiresAt);
|
|
4932
|
+
const held = await store.putPendingTask(
|
|
4933
|
+
{
|
|
4934
|
+
id: taskId,
|
|
4935
|
+
protocol: "a2a",
|
|
4936
|
+
resourceId: pending.resourceId,
|
|
4937
|
+
input: pending.input,
|
|
4938
|
+
adapterData: {
|
|
4939
|
+
contextId: pending.contextId,
|
|
4940
|
+
...pending.network !== void 0 ? { network: pending.network } : {}
|
|
4941
|
+
},
|
|
4942
|
+
expiresAt: new Date(expiresAtMs).toISOString()
|
|
4943
|
+
},
|
|
4944
|
+
{ maxTasks }
|
|
4945
|
+
);
|
|
4946
|
+
purgeExpired();
|
|
4947
|
+
mandates.delete(taskId);
|
|
4948
|
+
if (held && pending.authorization !== void 0) {
|
|
4949
|
+
mandates.set(taskId, { authorization: pending.authorization, expiresAtMs });
|
|
4950
|
+
}
|
|
4951
|
+
return held;
|
|
4952
|
+
},
|
|
4953
|
+
async get(taskId) {
|
|
4954
|
+
const task2 = await store.getPendingTask(taskId);
|
|
4955
|
+
return task2 !== void 0 ? toPending(task2) : void 0;
|
|
4956
|
+
},
|
|
4957
|
+
async take(taskId) {
|
|
4958
|
+
const task2 = await store.takePendingTask(taskId);
|
|
4959
|
+
if (task2 === void 0) return void 0;
|
|
4960
|
+
const pending = toPending(task2);
|
|
4961
|
+
if (pending === void 0) {
|
|
4962
|
+
await store.putPendingTask(task2, { maxTasks: Number.MAX_SAFE_INTEGER });
|
|
4963
|
+
return void 0;
|
|
4964
|
+
}
|
|
4965
|
+
mandates.delete(taskId);
|
|
4966
|
+
return pending;
|
|
4967
|
+
},
|
|
4968
|
+
clear() {
|
|
4969
|
+
mandates.clear();
|
|
4970
|
+
}
|
|
4971
|
+
};
|
|
4972
|
+
}
|
|
4428
4973
|
function readPaymentSubmission(message) {
|
|
4429
4974
|
const metadata = isRecord(message) ? message["metadata"] : void 0;
|
|
4430
4975
|
if (!isRecord(metadata)) return void 0;
|
|
@@ -4614,8 +5159,8 @@ var A2A_UNSUPPORTED = [
|
|
|
4614
5159
|
"authenticated extended agent cards",
|
|
4615
5160
|
"A2A authentication schemes",
|
|
4616
5161
|
"artifact types beyond Agent Commerce outcome data",
|
|
4617
|
-
//
|
|
4618
|
-
"x402 extension payments across gateway
|
|
5162
|
+
// Instances with separate receipt stores cannot resume each other's tasks
|
|
5163
|
+
"x402 extension payments across gateway instances"
|
|
4619
5164
|
];
|
|
4620
5165
|
function buildDescriptor(implementationVersion) {
|
|
4621
5166
|
return {
|
|
@@ -4704,7 +5249,7 @@ async function resumePayment(context, pendingPayments, id, params) {
|
|
|
4704
5249
|
const message = isRecord(params) ? params["message"] : void 0;
|
|
4705
5250
|
const taskId = isRecord(message) ? message["taskId"] : void 0;
|
|
4706
5251
|
if (context === void 0 || typeof taskId !== "string") return void 0;
|
|
4707
|
-
const pending = pendingPayments?.get(taskId);
|
|
5252
|
+
const pending = await pendingPayments?.get(taskId);
|
|
4708
5253
|
if (pending === void 0) return void 0;
|
|
4709
5254
|
const messageId = isRecord(message) ? message["messageId"] : void 0;
|
|
4710
5255
|
if (typeof messageId !== "string" || messageId.length === 0) {
|
|
@@ -4724,19 +5269,21 @@ async function resumePayment(context, pendingPayments, id, params) {
|
|
|
4724
5269
|
`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".`
|
|
4725
5270
|
);
|
|
4726
5271
|
}
|
|
4727
|
-
let
|
|
4728
|
-
if (authorization === void 0 && submission.kind === "submitted") {
|
|
5272
|
+
let followUp;
|
|
5273
|
+
if (pending.authorization === void 0 && submission.kind === "submitted") {
|
|
4729
5274
|
try {
|
|
4730
|
-
|
|
5275
|
+
followUp = readFollowUpAuthorization(message);
|
|
4731
5276
|
} catch (err) {
|
|
4732
5277
|
return jsonRpcError(id, JSONRPC_INVALID_PARAMS, toCommerceError(err).message);
|
|
4733
5278
|
}
|
|
4734
5279
|
}
|
|
4735
|
-
pendingPayments?.
|
|
5280
|
+
const taken = await pendingPayments?.take(taskId);
|
|
5281
|
+
if (taken === void 0) return void 0;
|
|
5282
|
+
const authorization = taken.authorization ?? followUp;
|
|
4736
5283
|
const statusMessageId = context.ids.next("a2a-msg");
|
|
4737
5284
|
const identity = {
|
|
4738
5285
|
taskId,
|
|
4739
|
-
contextId:
|
|
5286
|
+
contextId: taken.contextId,
|
|
4740
5287
|
artifactId: context.ids.next("a2a-artifact"),
|
|
4741
5288
|
statusMessageId,
|
|
4742
5289
|
timestamp: context.clock.nowIso()
|
|
@@ -4744,7 +5291,7 @@ async function resumePayment(context, pendingPayments, id, params) {
|
|
|
4744
5291
|
if (submission.kind === "rejected") {
|
|
4745
5292
|
const declined = {
|
|
4746
5293
|
id: taskId,
|
|
4747
|
-
contextId:
|
|
5294
|
+
contextId: taken.contextId,
|
|
4748
5295
|
status: { state: A2A_TASK_STATE_FAILED, timestamp: identity.timestamp },
|
|
4749
5296
|
artifacts: []
|
|
4750
5297
|
};
|
|
@@ -4762,7 +5309,7 @@ async function resumePayment(context, pendingPayments, id, params) {
|
|
|
4762
5309
|
id,
|
|
4763
5310
|
await payPending(
|
|
4764
5311
|
context,
|
|
4765
|
-
{ ...
|
|
5312
|
+
{ ...taken, ...authorization !== void 0 ? { authorization } : {} },
|
|
4766
5313
|
submission.payload,
|
|
4767
5314
|
identity
|
|
4768
5315
|
)
|
|
@@ -4826,6 +5373,7 @@ var A2aProtocolAdapter = class {
|
|
|
4826
5373
|
agentName;
|
|
4827
5374
|
agentDescription;
|
|
4828
5375
|
agentVersion;
|
|
5376
|
+
store;
|
|
4829
5377
|
context;
|
|
4830
5378
|
started = false;
|
|
4831
5379
|
// The card lists only a2a-exposed resources, but a caller can name any id,
|
|
@@ -4843,6 +5391,7 @@ var A2aProtocolAdapter = class {
|
|
|
4843
5391
|
this.agentName = options.agentName ?? A2A_DEFAULT_AGENT_NAME;
|
|
4844
5392
|
this.agentDescription = options.agentDescription ?? DEFAULT_AGENT_DESCRIPTION;
|
|
4845
5393
|
this.agentVersion = options.agentVersion ?? PACKAGE_VERSION;
|
|
5394
|
+
this.store = options.store;
|
|
4846
5395
|
this.descriptor = buildDescriptor(PACKAGE_VERSION);
|
|
4847
5396
|
this.additionalHttpRoutes = [
|
|
4848
5397
|
{
|
|
@@ -4874,7 +5423,7 @@ var A2aProtocolAdapter = class {
|
|
|
4874
5423
|
mountPath: this.mountPath,
|
|
4875
5424
|
resources
|
|
4876
5425
|
});
|
|
4877
|
-
this.pendingPayments = createPendingPayments(context.clock);
|
|
5426
|
+
this.pendingPayments = hasMethodGroup(this.store, "pending_tasks") ? createStoredPendingPayments(this.store, context.clock) : createPendingPayments(context.clock);
|
|
4878
5427
|
this.cardBody = JSON.stringify(this.card);
|
|
4879
5428
|
this.cardEtag = `"${createHash("sha256").update(this.cardBody).digest("base64url")}"`;
|
|
4880
5429
|
this.started = true;
|
|
@@ -5075,7 +5624,7 @@ var A2aProtocolAdapter = class {
|
|
|
5075
5624
|
return taskResult(id, task2);
|
|
5076
5625
|
}
|
|
5077
5626
|
const network = outcome.requirement.network;
|
|
5078
|
-
const held = this.pendingPayments?.put(
|
|
5627
|
+
const held = await this.pendingPayments?.put(
|
|
5079
5628
|
identity.taskId,
|
|
5080
5629
|
{
|
|
5081
5630
|
contextId: identity.contextId,
|
|
@@ -5273,10 +5822,10 @@ function writeAcpFailure(res, failure, headers = {}) {
|
|
|
5273
5822
|
writeAcpJson(res, failure.status, failure.error, headers);
|
|
5274
5823
|
}
|
|
5275
5824
|
function operationKey(scope) {
|
|
5276
|
-
return
|
|
5825
|
+
return sha2562(`acp-operation:${scope.deployment}:${scope.endpoint}:${scope.key}`);
|
|
5277
5826
|
}
|
|
5278
5827
|
function requestFingerprint(body) {
|
|
5279
|
-
return
|
|
5828
|
+
return sha2562(canonicalize(body));
|
|
5280
5829
|
}
|
|
5281
5830
|
function canonicalize(value) {
|
|
5282
5831
|
if (value === null) return "null";
|
|
@@ -5287,7 +5836,7 @@ function canonicalize(value) {
|
|
|
5287
5836
|
}
|
|
5288
5837
|
return JSON.stringify(value) ?? "null";
|
|
5289
5838
|
}
|
|
5290
|
-
function
|
|
5839
|
+
function sha2562(value) {
|
|
5291
5840
|
return createHash("sha256").update(value, "utf8").digest("hex");
|
|
5292
5841
|
}
|
|
5293
5842
|
|
|
@@ -5387,23 +5936,22 @@ function createAcpIdempotencyStore(options) {
|
|
|
5387
5936
|
};
|
|
5388
5937
|
}
|
|
5389
5938
|
function resolveOrphanedClaims(db, logger, release) {
|
|
5939
|
+
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();
|
|
5940
|
+
warnOrphanedClaims(logger, changes, release);
|
|
5941
|
+
}
|
|
5942
|
+
function warnOrphanedClaims(logger, count, release) {
|
|
5943
|
+
if (count === 0) return;
|
|
5390
5944
|
if (release) {
|
|
5391
|
-
const { changes: changes2 } = db.prepare("DELETE FROM acp_idempotency WHERE state = 'in_flight'").run();
|
|
5392
|
-
if (changes2 > 0) {
|
|
5393
|
-
logger.warn(
|
|
5394
|
-
{ released: changes2 },
|
|
5395
|
-
"acp idempotency: freed claims left in flight by an earlier process; merchant deduplication is enabled"
|
|
5396
|
-
);
|
|
5397
|
-
}
|
|
5398
|
-
return;
|
|
5399
|
-
}
|
|
5400
|
-
const { changes } = db.prepare("UPDATE acp_idempotency SET state = 'unresolved' WHERE state = 'in_flight'").run();
|
|
5401
|
-
if (changes > 0) {
|
|
5402
5945
|
logger.warn(
|
|
5403
|
-
{
|
|
5404
|
-
"acp idempotency:
|
|
5946
|
+
{ released: count },
|
|
5947
|
+
"acp idempotency: freed claims left in flight by an earlier process; merchant deduplication is enabled"
|
|
5405
5948
|
);
|
|
5949
|
+
return;
|
|
5406
5950
|
}
|
|
5951
|
+
logger.warn(
|
|
5952
|
+
{ unresolved: count },
|
|
5953
|
+
"acp idempotency: marked claims left in flight by an earlier process as unresolved; reconcile these operations against the merchant before trusting a retry"
|
|
5954
|
+
);
|
|
5407
5955
|
}
|
|
5408
5956
|
function migrate(db, logger) {
|
|
5409
5957
|
const current = db.pragma("user_version", { simple: true });
|
|
@@ -9958,6 +10506,27 @@ function reachedFor(error) {
|
|
|
9958
10506
|
function notReached(failure) {
|
|
9959
10507
|
return { response: asResponse(failure), reached: "no" };
|
|
9960
10508
|
}
|
|
10509
|
+
function backendOverReceiptStore(store, clock, retentionHours) {
|
|
10510
|
+
const retentionMs = retentionHours * 60 * 60 * 1e3;
|
|
10511
|
+
return {
|
|
10512
|
+
claim: (scope, fingerprint) => store.claimIdempotencyKey(
|
|
10513
|
+
scope,
|
|
10514
|
+
fingerprint,
|
|
10515
|
+
new Date(clock.now().getTime() + retentionMs).toISOString()
|
|
10516
|
+
),
|
|
10517
|
+
complete: (scope, { status, body }) => store.updateIdempotencyKey(scope, { kind: "completed", status, body }),
|
|
10518
|
+
markUnresolved: (scope) => store.updateIdempotencyKey(scope, { kind: "unresolved" }),
|
|
10519
|
+
release: (scope) => store.updateIdempotencyKey(scope, { kind: "released" })
|
|
10520
|
+
};
|
|
10521
|
+
}
|
|
10522
|
+
function backendOverFileStore(store) {
|
|
10523
|
+
return {
|
|
10524
|
+
claim: async (scope, fingerprint) => store.claim(scope, fingerprint),
|
|
10525
|
+
complete: async (scope, response) => store.complete(scope, response),
|
|
10526
|
+
markUnresolved: async (scope) => store.markUnresolved(scope),
|
|
10527
|
+
release: async (scope) => store.release(scope)
|
|
10528
|
+
};
|
|
10529
|
+
}
|
|
9961
10530
|
var AcpProtocolAdapter = class {
|
|
9962
10531
|
name = "acp";
|
|
9963
10532
|
mountPath;
|
|
@@ -9972,7 +10541,10 @@ var AcpProtocolAdapter = class {
|
|
|
9972
10541
|
*/
|
|
9973
10542
|
deployment;
|
|
9974
10543
|
discoveryMetadata;
|
|
10544
|
+
store;
|
|
9975
10545
|
idempotency;
|
|
10546
|
+
// Track the file opened by this adapter so borrowed receipt stores stay open
|
|
10547
|
+
fileStore;
|
|
9976
10548
|
resources = /* @__PURE__ */ new Map();
|
|
9977
10549
|
context;
|
|
9978
10550
|
started = false;
|
|
@@ -9984,6 +10556,7 @@ var AcpProtocolAdapter = class {
|
|
|
9984
10556
|
this.isAuthorized = createBearerCheck(options.token);
|
|
9985
10557
|
this.operations = options.operations;
|
|
9986
10558
|
this.idempotencyOptions = options.idempotency;
|
|
10559
|
+
this.store = options.store;
|
|
9987
10560
|
this.discoveryMetadata = options.discovery;
|
|
9988
10561
|
this.descriptor = buildDescriptor2(PACKAGE_VERSION);
|
|
9989
10562
|
this.additionalHttpRoutes = [
|
|
@@ -10002,12 +10575,12 @@ var AcpProtocolAdapter = class {
|
|
|
10002
10575
|
mountPath: this.mountPath,
|
|
10003
10576
|
...this.discoveryMetadata !== void 0 ? { metadata: this.discoveryMetadata } : {}
|
|
10004
10577
|
});
|
|
10005
|
-
const
|
|
10006
|
-
if (
|
|
10578
|
+
const invalid3 = validateAcpDocument("discoveryResponse", document);
|
|
10579
|
+
if (invalid3 !== void 0) {
|
|
10007
10580
|
throw new CommerceError(
|
|
10008
10581
|
"CONFIG_INVALID",
|
|
10009
|
-
`ACP discovery document does not conform to the ${this.descriptor.supportedSpec} snapshot at "${
|
|
10010
|
-
{ details: { path:
|
|
10582
|
+
`ACP discovery document does not conform to the ${this.descriptor.supportedSpec} snapshot at "${invalid3.path ?? "$"}" (${invalid3.code}) - check protocols.acp.discovery`,
|
|
10583
|
+
{ details: { path: invalid3.path ?? "$", code: invalid3.code } }
|
|
10011
10584
|
);
|
|
10012
10585
|
}
|
|
10013
10586
|
const exposed = new Map(
|
|
@@ -10028,12 +10601,7 @@ var AcpProtocolAdapter = class {
|
|
|
10028
10601
|
}
|
|
10029
10602
|
this.resources = resolved;
|
|
10030
10603
|
this.deployment = context.publicBaseUrl;
|
|
10031
|
-
this.idempotency =
|
|
10032
|
-
path: this.idempotencyOptions.path,
|
|
10033
|
-
retentionHours: this.idempotencyOptions.retentionHours,
|
|
10034
|
-
releaseOrphans: this.idempotencyOptions.merchantIdempotent === true,
|
|
10035
|
-
logger: context.logger
|
|
10036
|
-
});
|
|
10604
|
+
this.idempotency = await this.openIdempotency(context);
|
|
10037
10605
|
this.discovery = document;
|
|
10038
10606
|
this.started = true;
|
|
10039
10607
|
context.logger.info(
|
|
@@ -10045,6 +10613,32 @@ var AcpProtocolAdapter = class {
|
|
|
10045
10613
|
"acp adapter started"
|
|
10046
10614
|
);
|
|
10047
10615
|
}
|
|
10616
|
+
// Recover claims at adapter start, not when the shared store opens for
|
|
10617
|
+
// another consumer
|
|
10618
|
+
async openIdempotency(context) {
|
|
10619
|
+
const { path: path2, retentionHours, merchantIdempotent } = this.idempotencyOptions;
|
|
10620
|
+
const release = merchantIdempotent === true;
|
|
10621
|
+
const store = this.store;
|
|
10622
|
+
if (hasMethodGroup(store, "idempotency_claims")) {
|
|
10623
|
+
const recovered = await store.recoverIdempotencyKeys({ release });
|
|
10624
|
+
warnOrphanedClaims(context.logger, recovered, release);
|
|
10625
|
+
return backendOverReceiptStore(store, context.clock, retentionHours);
|
|
10626
|
+
}
|
|
10627
|
+
if (path2 === void 0) {
|
|
10628
|
+
throw new CommerceError(
|
|
10629
|
+
"CONFIG_INVALID",
|
|
10630
|
+
"ACP idempotency needs a receipt store with idempotency methods or a file - set protocols.acp.idempotency.path",
|
|
10631
|
+
{ details: { path: "protocols.acp.idempotency.path" } }
|
|
10632
|
+
);
|
|
10633
|
+
}
|
|
10634
|
+
this.fileStore = createAcpIdempotencyStore({
|
|
10635
|
+
path: path2,
|
|
10636
|
+
retentionHours,
|
|
10637
|
+
releaseOrphans: release,
|
|
10638
|
+
logger: context.logger
|
|
10639
|
+
});
|
|
10640
|
+
return backendOverFileStore(this.fileStore);
|
|
10641
|
+
}
|
|
10048
10642
|
/** `GET /.well-known/acp.json`: public, unauthenticated, cacheable */
|
|
10049
10643
|
async handleDiscovery(req, res) {
|
|
10050
10644
|
try {
|
|
@@ -10122,7 +10716,7 @@ var AcpProtocolAdapter = class {
|
|
|
10122
10716
|
return (await this.runCheckout(request)).response;
|
|
10123
10717
|
}
|
|
10124
10718
|
const scope = { deployment, endpoint: request.route.path, key };
|
|
10125
|
-
const claim = store.claim(scope, requestFingerprint(request.body));
|
|
10719
|
+
const claim = await store.claim(scope, requestFingerprint(request.body));
|
|
10126
10720
|
switch (claim.kind) {
|
|
10127
10721
|
case "in-flight":
|
|
10128
10722
|
return {
|
|
@@ -10161,15 +10755,15 @@ var AcpProtocolAdapter = class {
|
|
|
10161
10755
|
try {
|
|
10162
10756
|
outcome = await this.runCheckout(request, operationKey(scope));
|
|
10163
10757
|
} catch (err) {
|
|
10164
|
-
store.markUnresolved(scope);
|
|
10758
|
+
await store.markUnresolved(scope);
|
|
10165
10759
|
throw err;
|
|
10166
10760
|
}
|
|
10167
10761
|
if (outcome.response.status < 500) {
|
|
10168
|
-
store.complete(scope, outcome.response);
|
|
10762
|
+
await store.complete(scope, outcome.response);
|
|
10169
10763
|
} else if (outcome.reached === "no" || this.idempotencyOptions.merchantIdempotent === true) {
|
|
10170
|
-
store.release(scope);
|
|
10764
|
+
await store.release(scope);
|
|
10171
10765
|
} else {
|
|
10172
|
-
store.markUnresolved(scope);
|
|
10766
|
+
await store.markUnresolved(scope);
|
|
10173
10767
|
}
|
|
10174
10768
|
return outcome.response;
|
|
10175
10769
|
}
|
|
@@ -10269,7 +10863,8 @@ var AcpProtocolAdapter = class {
|
|
|
10269
10863
|
this.started = false;
|
|
10270
10864
|
this.discovery = void 0;
|
|
10271
10865
|
this.resources = /* @__PURE__ */ new Map();
|
|
10272
|
-
this.
|
|
10866
|
+
this.fileStore?.close();
|
|
10867
|
+
this.fileStore = void 0;
|
|
10273
10868
|
this.idempotency = void 0;
|
|
10274
10869
|
this.deployment = void 0;
|
|
10275
10870
|
this.context = void 0;
|
|
@@ -10279,109 +10874,6 @@ function createAcpAdapter(options) {
|
|
|
10279
10874
|
return new AcpProtocolAdapter(options);
|
|
10280
10875
|
}
|
|
10281
10876
|
|
|
10282
|
-
// src/storage/receipts/redact.ts
|
|
10283
|
-
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;
|
|
10284
|
-
var REDACTED = "[REDACTED]";
|
|
10285
|
-
function isSecretKey(key) {
|
|
10286
|
-
return SECRET_KEY_PATTERN.test(key);
|
|
10287
|
-
}
|
|
10288
|
-
function redact(value) {
|
|
10289
|
-
return redactValue(value);
|
|
10290
|
-
}
|
|
10291
|
-
function redactValue(value) {
|
|
10292
|
-
if (Array.isArray(value)) {
|
|
10293
|
-
return value.map(redactValue);
|
|
10294
|
-
}
|
|
10295
|
-
if (value !== null && typeof value === "object") {
|
|
10296
|
-
const out = {};
|
|
10297
|
-
for (const [key, inner] of Object.entries(value)) {
|
|
10298
|
-
out[key] = isSecretKey(key) ? REDACTED : redactValue(inner);
|
|
10299
|
-
}
|
|
10300
|
-
return out;
|
|
10301
|
-
}
|
|
10302
|
-
return value;
|
|
10303
|
-
}
|
|
10304
|
-
|
|
10305
|
-
// src/storage/receipts/rows.ts
|
|
10306
|
-
function receiptToRow(receipt) {
|
|
10307
|
-
return {
|
|
10308
|
-
id: receipt.id,
|
|
10309
|
-
request_id: receipt.requestId,
|
|
10310
|
-
resource_id: receipt.resourceId,
|
|
10311
|
-
payment_json: receipt.payment !== void 0 ? JSON.stringify(redact(receipt.payment)) : null,
|
|
10312
|
-
delivered_at: receipt.deliveredAt,
|
|
10313
|
-
backend_status: receipt.backendStatus,
|
|
10314
|
-
duration_ms: receipt.durationMs ?? null,
|
|
10315
|
-
protocol: receipt.protocol ?? null,
|
|
10316
|
-
metadata_json: receipt.metadata !== void 0 ? JSON.stringify(redact(receipt.metadata)) : null,
|
|
10317
|
-
authorization_json: receipt.authorization !== void 0 ? JSON.stringify(redact(receipt.authorization)) : null
|
|
10318
|
-
};
|
|
10319
|
-
}
|
|
10320
|
-
function rowToReceipt(row) {
|
|
10321
|
-
const payment = row.payment_json !== null ? JSON.parse(row.payment_json) : void 0;
|
|
10322
|
-
const metadata = row.metadata_json !== null ? JSON.parse(row.metadata_json) : void 0;
|
|
10323
|
-
const authorization = row.authorization_json !== null ? JSON.parse(row.authorization_json) : void 0;
|
|
10324
|
-
return {
|
|
10325
|
-
id: row.id,
|
|
10326
|
-
requestId: row.request_id,
|
|
10327
|
-
resourceId: row.resource_id,
|
|
10328
|
-
deliveredAt: row.delivered_at,
|
|
10329
|
-
backendStatus: row.backend_status,
|
|
10330
|
-
...payment !== void 0 ? { payment } : {},
|
|
10331
|
-
...row.duration_ms !== null ? { durationMs: row.duration_ms } : {},
|
|
10332
|
-
...row.protocol !== null ? { protocol: row.protocol } : {},
|
|
10333
|
-
...metadata !== void 0 ? { metadata } : {},
|
|
10334
|
-
...authorization !== void 0 ? { authorization } : {}
|
|
10335
|
-
};
|
|
10336
|
-
}
|
|
10337
|
-
function eventToRow(event) {
|
|
10338
|
-
return {
|
|
10339
|
-
id: event.id,
|
|
10340
|
-
type: event.type,
|
|
10341
|
-
request_id: event.requestId,
|
|
10342
|
-
resource_id: event.resourceId ?? null,
|
|
10343
|
-
at: event.at,
|
|
10344
|
-
adapter: event.adapter ?? null,
|
|
10345
|
-
payment_provider: event.paymentProvider ?? null,
|
|
10346
|
-
duration_ms: event.durationMs ?? null,
|
|
10347
|
-
status: event.status ?? null,
|
|
10348
|
-
data_json: event.data !== void 0 ? JSON.stringify(redact(event.data)) : null
|
|
10349
|
-
};
|
|
10350
|
-
}
|
|
10351
|
-
function rowToEvent(row) {
|
|
10352
|
-
const data = row.data_json !== null ? JSON.parse(row.data_json) : void 0;
|
|
10353
|
-
return {
|
|
10354
|
-
id: row.id,
|
|
10355
|
-
type: row.type,
|
|
10356
|
-
requestId: row.request_id,
|
|
10357
|
-
at: row.at,
|
|
10358
|
-
...row.resource_id !== null ? { resourceId: row.resource_id } : {},
|
|
10359
|
-
...row.adapter !== null ? { adapter: row.adapter } : {},
|
|
10360
|
-
...row.payment_provider !== null ? { paymentProvider: row.payment_provider } : {},
|
|
10361
|
-
...row.duration_ms !== null ? { durationMs: row.duration_ms } : {},
|
|
10362
|
-
...row.status !== null ? { status: row.status } : {},
|
|
10363
|
-
...data !== void 0 ? { data } : {}
|
|
10364
|
-
};
|
|
10365
|
-
}
|
|
10366
|
-
function rowToPaymentAttempt(row) {
|
|
10367
|
-
return {
|
|
10368
|
-
id: row.id,
|
|
10369
|
-
requestId: row.request_id,
|
|
10370
|
-
resourceId: row.resource_id,
|
|
10371
|
-
provider: row.provider,
|
|
10372
|
-
replayKey: row.replay_key,
|
|
10373
|
-
status: row.status,
|
|
10374
|
-
amount: row.amount,
|
|
10375
|
-
currency: row.currency,
|
|
10376
|
-
...row.payer !== null ? { payer: row.payer } : {},
|
|
10377
|
-
...row.payee !== null ? { payee: row.payee } : {},
|
|
10378
|
-
...row.external_reference !== null ? { externalReference: row.external_reference } : {},
|
|
10379
|
-
...row.rejection_reason !== null ? { rejectionReason: row.rejection_reason } : {},
|
|
10380
|
-
createdAt: row.created_at,
|
|
10381
|
-
updatedAt: row.updated_at
|
|
10382
|
-
};
|
|
10383
|
-
}
|
|
10384
|
-
|
|
10385
10877
|
// src/storage/receipts/schema.ts
|
|
10386
10878
|
var MIGRATIONS = [
|
|
10387
10879
|
{
|
|
@@ -10473,13 +10965,118 @@ var MIGRATIONS = [
|
|
|
10473
10965
|
CREATE INDEX IF NOT EXISTS idx_payment_attempt_history_request_id ON payment_attempt_history(request_id);
|
|
10474
10966
|
`);
|
|
10475
10967
|
}
|
|
10968
|
+
},
|
|
10969
|
+
{
|
|
10970
|
+
version: 4,
|
|
10971
|
+
up(db) {
|
|
10972
|
+
db.exec(`
|
|
10973
|
+
CREATE TABLE IF NOT EXISTS transactions (
|
|
10974
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
10975
|
+
id TEXT NOT NULL UNIQUE,
|
|
10976
|
+
request_id TEXT NOT NULL,
|
|
10977
|
+
resource_id TEXT NOT NULL,
|
|
10978
|
+
protocol TEXT NOT NULL,
|
|
10979
|
+
state TEXT NOT NULL,
|
|
10980
|
+
provider TEXT NOT NULL,
|
|
10981
|
+
attempt_id TEXT NOT NULL,
|
|
10982
|
+
replay_key TEXT NOT NULL,
|
|
10983
|
+
network TEXT,
|
|
10984
|
+
asset TEXT,
|
|
10985
|
+
authorization_json TEXT,
|
|
10986
|
+
reservation_id TEXT,
|
|
10987
|
+
locator_json TEXT,
|
|
10988
|
+
expires_at TEXT,
|
|
10989
|
+
input_digest TEXT,
|
|
10990
|
+
config_digest TEXT NOT NULL,
|
|
10991
|
+
settling_at TEXT,
|
|
10992
|
+
backend_dispatched_at TEXT,
|
|
10993
|
+
backend_deadline_at TEXT,
|
|
10994
|
+
backend_status INTEGER,
|
|
10995
|
+
backend_error_code TEXT,
|
|
10996
|
+
receipt_id TEXT,
|
|
10997
|
+
persistence_failures_json TEXT,
|
|
10998
|
+
completed_at TEXT,
|
|
10999
|
+
created_at TEXT NOT NULL,
|
|
11000
|
+
updated_at TEXT NOT NULL
|
|
11001
|
+
);
|
|
11002
|
+
CREATE INDEX IF NOT EXISTS idx_transactions_state_seq ON transactions(state, seq);
|
|
11003
|
+
CREATE INDEX IF NOT EXISTS idx_transactions_request_id ON transactions(request_id);
|
|
11004
|
+
CREATE INDEX IF NOT EXISTS idx_transactions_replay_key ON transactions(replay_key);
|
|
11005
|
+
|
|
11006
|
+
ALTER TABLE receipts ADD COLUMN transaction_id TEXT;
|
|
11007
|
+
ALTER TABLE events ADD COLUMN transaction_id TEXT;
|
|
11008
|
+
ALTER TABLE payment_attempts ADD COLUMN transaction_id TEXT;
|
|
11009
|
+
ALTER TABLE payment_attempts ADD COLUMN resolution_json TEXT;
|
|
11010
|
+
ALTER TABLE payment_attempt_history ADD COLUMN transaction_id TEXT;
|
|
11011
|
+
ALTER TABLE payment_attempt_history ADD COLUMN resolution_json TEXT;
|
|
11012
|
+
CREATE INDEX IF NOT EXISTS idx_payment_attempt_history_id ON payment_attempt_history(id);
|
|
11013
|
+
`);
|
|
11014
|
+
}
|
|
11015
|
+
},
|
|
11016
|
+
{
|
|
11017
|
+
version: 5,
|
|
11018
|
+
up(db) {
|
|
11019
|
+
db.exec(`
|
|
11020
|
+
CREATE TABLE IF NOT EXISTS authorization_holds (
|
|
11021
|
+
reference TEXT PRIMARY KEY,
|
|
11022
|
+
method TEXT NOT NULL,
|
|
11023
|
+
binding_reference TEXT NOT NULL,
|
|
11024
|
+
resource_id TEXT NOT NULL,
|
|
11025
|
+
request_id TEXT NOT NULL,
|
|
11026
|
+
state TEXT NOT NULL
|
|
11027
|
+
CHECK (state IN ('reserved', 'consumed', 'released', 'uncertain')),
|
|
11028
|
+
metadata_json TEXT,
|
|
11029
|
+
created_at TEXT NOT NULL,
|
|
11030
|
+
updated_at TEXT NOT NULL
|
|
11031
|
+
);
|
|
11032
|
+
CREATE INDEX IF NOT EXISTS idx_authorization_holds_binding ON authorization_holds(binding_reference);
|
|
11033
|
+
CREATE INDEX IF NOT EXISTS idx_authorization_holds_request_id ON authorization_holds(request_id);
|
|
11034
|
+
CREATE INDEX IF NOT EXISTS idx_authorization_holds_state_updated ON authorization_holds(state, updated_at);
|
|
11035
|
+
|
|
11036
|
+
CREATE TABLE IF NOT EXISTS idempotency_keys (
|
|
11037
|
+
deployment TEXT NOT NULL,
|
|
11038
|
+
endpoint TEXT NOT NULL,
|
|
11039
|
+
idempotency_key TEXT NOT NULL,
|
|
11040
|
+
fingerprint TEXT NOT NULL,
|
|
11041
|
+
state TEXT NOT NULL,
|
|
11042
|
+
status INTEGER,
|
|
11043
|
+
body_json TEXT,
|
|
11044
|
+
created_at TEXT NOT NULL,
|
|
11045
|
+
expires_at TEXT NOT NULL,
|
|
11046
|
+
PRIMARY KEY (deployment, endpoint, idempotency_key)
|
|
11047
|
+
);
|
|
11048
|
+
CREATE INDEX IF NOT EXISTS idx_idempotency_keys_expires_at ON idempotency_keys(expires_at);
|
|
11049
|
+
|
|
11050
|
+
CREATE TABLE IF NOT EXISTS pending_tasks (
|
|
11051
|
+
id TEXT PRIMARY KEY,
|
|
11052
|
+
protocol TEXT NOT NULL,
|
|
11053
|
+
resource_id TEXT NOT NULL,
|
|
11054
|
+
input_json TEXT NOT NULL,
|
|
11055
|
+
adapter_data_json TEXT,
|
|
11056
|
+
created_at TEXT NOT NULL,
|
|
11057
|
+
expires_at TEXT NOT NULL
|
|
11058
|
+
);
|
|
11059
|
+
CREATE INDEX IF NOT EXISTS idx_pending_tasks_expires_at ON pending_tasks(expires_at);
|
|
11060
|
+
|
|
11061
|
+
-- path is NULL when the feature started with nothing to import
|
|
11062
|
+
CREATE TABLE IF NOT EXISTS legacy_imports (
|
|
11063
|
+
source TEXT PRIMARY KEY,
|
|
11064
|
+
path TEXT,
|
|
11065
|
+
rows INTEGER NOT NULL,
|
|
11066
|
+
imported_at TEXT NOT NULL
|
|
11067
|
+
);
|
|
11068
|
+
`);
|
|
11069
|
+
}
|
|
10476
11070
|
}
|
|
10477
11071
|
];
|
|
10478
11072
|
var SCHEMA_VERSION2 = MIGRATIONS.at(-1)?.version ?? 0;
|
|
10479
|
-
function
|
|
11073
|
+
function hasTable(db, name) {
|
|
11074
|
+
return db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name) !== void 0;
|
|
11075
|
+
}
|
|
11076
|
+
function migrate2(db, target = SCHEMA_VERSION2) {
|
|
10480
11077
|
const current = db.pragma("user_version", { simple: true });
|
|
10481
11078
|
for (const migration of MIGRATIONS) {
|
|
10482
|
-
if (migration.version <= current) continue;
|
|
11079
|
+
if (migration.version <= current || migration.version > target) continue;
|
|
10483
11080
|
const apply = db.transaction(() => {
|
|
10484
11081
|
migration.up(db);
|
|
10485
11082
|
db.pragma(`user_version = ${migration.version}`);
|
|
@@ -10488,15 +11085,683 @@ function migrate2(db) {
|
|
|
10488
11085
|
}
|
|
10489
11086
|
}
|
|
10490
11087
|
|
|
10491
|
-
// src/storage/receipts/
|
|
11088
|
+
// src/storage/receipts/legacy-import.ts
|
|
11089
|
+
var NOTHING = { rows: 0, write: () => {
|
|
11090
|
+
} };
|
|
11091
|
+
var SOURCES = [
|
|
11092
|
+
{
|
|
11093
|
+
name: "ap2-replay",
|
|
11094
|
+
option: "ap2Replay",
|
|
11095
|
+
feature: "ap2",
|
|
11096
|
+
key: "authorization.ap2.replay.path",
|
|
11097
|
+
usedSql: `SELECT 1 FROM receipts WHERE authorization_json IS NOT NULL
|
|
11098
|
+
UNION ALL SELECT 1 FROM transactions WHERE authorization_json IS NOT NULL LIMIT 1`,
|
|
11099
|
+
read(file) {
|
|
11100
|
+
if (!hasTable(file, "ap2_authorizations")) return NOTHING;
|
|
11101
|
+
const rows = file.prepare(
|
|
11102
|
+
`SELECT reference, checkout_jti, mandate_issuer, checkout_issuer, resource_id,
|
|
11103
|
+
request_id, state, created_at, updated_at
|
|
11104
|
+
FROM ap2_authorizations`
|
|
11105
|
+
).all();
|
|
11106
|
+
return {
|
|
11107
|
+
rows: rows.length,
|
|
11108
|
+
write(db) {
|
|
11109
|
+
const insert = db.prepare(
|
|
11110
|
+
`INSERT INTO authorization_holds
|
|
11111
|
+
(reference, method, binding_reference, resource_id, request_id, state,
|
|
11112
|
+
metadata_json, created_at, updated_at)
|
|
11113
|
+
VALUES (@reference, 'ap2', @checkout_jti, @resource_id, @request_id, @state,
|
|
11114
|
+
@metadata_json, @created_at, @updated_at)
|
|
11115
|
+
ON CONFLICT (reference) DO UPDATE SET
|
|
11116
|
+
binding_reference = excluded.binding_reference, resource_id = excluded.resource_id,
|
|
11117
|
+
request_id = excluded.request_id, state = excluded.state,
|
|
11118
|
+
metadata_json = excluded.metadata_json, updated_at = excluded.updated_at
|
|
11119
|
+
WHERE authorization_holds.state = 'released'`
|
|
11120
|
+
);
|
|
11121
|
+
for (const row of rows) {
|
|
11122
|
+
insert.run({
|
|
11123
|
+
...row,
|
|
11124
|
+
metadata_json: JSON.stringify({
|
|
11125
|
+
mandateIssuer: row.mandate_issuer,
|
|
11126
|
+
checkoutIssuer: row.checkout_issuer
|
|
11127
|
+
})
|
|
11128
|
+
});
|
|
11129
|
+
}
|
|
11130
|
+
}
|
|
11131
|
+
};
|
|
11132
|
+
}
|
|
11133
|
+
},
|
|
11134
|
+
{
|
|
11135
|
+
name: "acp-idempotency",
|
|
11136
|
+
option: "acpIdempotency",
|
|
11137
|
+
feature: "acp",
|
|
11138
|
+
key: "protocols.acp.idempotency.path",
|
|
11139
|
+
usedSql: "SELECT 1 FROM events WHERE adapter = 'acp' LIMIT 1",
|
|
11140
|
+
read(file, logger) {
|
|
11141
|
+
if (!hasTable(file, "acp_idempotency")) return NOTHING;
|
|
11142
|
+
if (file.pragma("user_version", { simple: true }) < 2) {
|
|
11143
|
+
const { count } = file.prepare("SELECT COUNT(*) AS count FROM acp_idempotency WHERE state != 'completed'").get();
|
|
11144
|
+
if (count > 0) {
|
|
11145
|
+
logger.warn(
|
|
11146
|
+
{ unresolved: count },
|
|
11147
|
+
"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"
|
|
11148
|
+
);
|
|
11149
|
+
}
|
|
11150
|
+
return NOTHING;
|
|
11151
|
+
}
|
|
11152
|
+
const rows = file.prepare(
|
|
11153
|
+
`SELECT deployment, endpoint, idempotency_key, fingerprint, state, status, body_json,
|
|
11154
|
+
created_at, expires_at
|
|
11155
|
+
FROM acp_idempotency`
|
|
11156
|
+
).all();
|
|
11157
|
+
return {
|
|
11158
|
+
rows: rows.length,
|
|
11159
|
+
write(db) {
|
|
11160
|
+
const insert = db.prepare(
|
|
11161
|
+
`INSERT INTO idempotency_keys
|
|
11162
|
+
(deployment, endpoint, idempotency_key, fingerprint, state, status, body_json,
|
|
11163
|
+
created_at, expires_at)
|
|
11164
|
+
VALUES (@deployment, @endpoint, @idempotency_key, @fingerprint, @state, @status,
|
|
11165
|
+
@body_json, @created_at, @expires_at)
|
|
11166
|
+
ON CONFLICT DO NOTHING`
|
|
11167
|
+
);
|
|
11168
|
+
for (const row of rows) insert.run(row);
|
|
11169
|
+
}
|
|
11170
|
+
};
|
|
11171
|
+
}
|
|
11172
|
+
}
|
|
11173
|
+
];
|
|
11174
|
+
function storageError(message, details, cause) {
|
|
11175
|
+
return new CommerceError("STORAGE_ERROR", message, { details, cause });
|
|
11176
|
+
}
|
|
11177
|
+
function selectMarker(db, source) {
|
|
11178
|
+
return db.prepare("SELECT path FROM legacy_imports WHERE source = ?").get(source);
|
|
11179
|
+
}
|
|
11180
|
+
var usedBefore = (db, source) => db.prepare(source.usedSql).get() !== void 0;
|
|
11181
|
+
function missingLegacyImports(db) {
|
|
11182
|
+
const recorded = hasTable(db, "legacy_imports");
|
|
11183
|
+
return SOURCES.filter(
|
|
11184
|
+
(source) => !(recorded && selectMarker(db, source.name) !== void 0) && usedBefore(db, source)
|
|
11185
|
+
).map((source) => source.name);
|
|
11186
|
+
}
|
|
11187
|
+
function importLegacyStores(db, receiptsPath, options, clock, logger) {
|
|
11188
|
+
const recordMarker = db.prepare(
|
|
11189
|
+
`INSERT INTO legacy_imports (source, path, rows, imported_at) VALUES (?, ?, ?, ?)
|
|
11190
|
+
ON CONFLICT (source) DO UPDATE SET
|
|
11191
|
+
path = excluded.path, rows = excluded.rows, imported_at = excluded.imported_at`
|
|
11192
|
+
);
|
|
11193
|
+
const locks = [];
|
|
11194
|
+
const release = () => {
|
|
11195
|
+
for (const lock of locks.splice(0)) lock.close();
|
|
11196
|
+
};
|
|
11197
|
+
try {
|
|
11198
|
+
for (const source of SOURCES) {
|
|
11199
|
+
const given = options[source.option];
|
|
11200
|
+
const marker = selectMarker(db, source.name);
|
|
11201
|
+
const importedPath = marker?.path ?? void 0;
|
|
11202
|
+
const path2 = given !== void 0 && given !== ":memory:" ? resolve(given) : void 0;
|
|
11203
|
+
if (path2 !== void 0 && receiptsPath !== ":memory:" && path2 === resolve(receiptsPath)) {
|
|
11204
|
+
throw storageError(`${source.key} names the receipt database "${path2}"`, {
|
|
11205
|
+
key: source.key,
|
|
11206
|
+
path: path2
|
|
11207
|
+
});
|
|
11208
|
+
}
|
|
11209
|
+
if (path2 !== void 0 && importedPath !== void 0 && importedPath !== path2) {
|
|
11210
|
+
throw storageError(
|
|
11211
|
+
`${source.key} names "${path2}", but "${importedPath}" was imported from it already. Point ${source.key} back at the imported file, or remove the key.`,
|
|
11212
|
+
{ key: source.key, path: path2, importedPath }
|
|
11213
|
+
);
|
|
11214
|
+
}
|
|
11215
|
+
if (path2 === void 0 || !existsSync(path2)) {
|
|
11216
|
+
if (marker === void 0 && options.enabled?.[source.feature] === true) {
|
|
11217
|
+
if (given !== ":memory:" && usedBefore(db, source)) {
|
|
11218
|
+
throw forgottenKey(source, path2);
|
|
11219
|
+
}
|
|
11220
|
+
recordMarker.run(source.name, null, 0, clock.nowIso());
|
|
11221
|
+
}
|
|
11222
|
+
if (given !== void 0) {
|
|
11223
|
+
logger.info(
|
|
11224
|
+
{ key: source.key, path: path2 ?? given },
|
|
11225
|
+
"deprecated store has no file to import; the key can be removed"
|
|
11226
|
+
);
|
|
11227
|
+
}
|
|
11228
|
+
continue;
|
|
11229
|
+
}
|
|
11230
|
+
let file;
|
|
11231
|
+
try {
|
|
11232
|
+
file = new Database(path2, { fileMustExist: true });
|
|
11233
|
+
file.exec("BEGIN EXCLUSIVE");
|
|
11234
|
+
} catch (cause) {
|
|
11235
|
+
file?.close();
|
|
11236
|
+
const cantOpen = cause.code === "SQLITE_CANTOPEN";
|
|
11237
|
+
if (importedPath !== void 0 && cantOpen) {
|
|
11238
|
+
logger.warn(
|
|
11239
|
+
{ key: source.key, path: path2 },
|
|
11240
|
+
"deprecated store file cannot be opened to lock it; its rows are already imported"
|
|
11241
|
+
);
|
|
11242
|
+
continue;
|
|
11243
|
+
}
|
|
11244
|
+
throw storageError(
|
|
11245
|
+
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)}`,
|
|
11246
|
+
{ key: source.key, path: path2 },
|
|
11247
|
+
cause
|
|
11248
|
+
);
|
|
11249
|
+
}
|
|
11250
|
+
locks.push(file);
|
|
11251
|
+
if (importedPath !== void 0) continue;
|
|
11252
|
+
let imported;
|
|
11253
|
+
try {
|
|
11254
|
+
imported = source.read(file, logger);
|
|
11255
|
+
} catch (cause) {
|
|
11256
|
+
throw storageError(
|
|
11257
|
+
`${source.key} "${path2}" cannot be read for import: ${cause instanceof Error ? cause.message : String(cause)}`,
|
|
11258
|
+
{ key: source.key, path: path2 },
|
|
11259
|
+
cause
|
|
11260
|
+
);
|
|
11261
|
+
}
|
|
11262
|
+
db.transaction(() => {
|
|
11263
|
+
imported.write(db);
|
|
11264
|
+
recordMarker.run(source.name, path2, imported.rows, clock.nowIso());
|
|
11265
|
+
})();
|
|
11266
|
+
logger.info(
|
|
11267
|
+
{ key: source.key, path: path2, rows: imported.rows },
|
|
11268
|
+
"imported deprecated store file; it stays locked against writes while this gateway runs"
|
|
11269
|
+
);
|
|
11270
|
+
}
|
|
11271
|
+
} catch (err) {
|
|
11272
|
+
release();
|
|
11273
|
+
throw toCommerceError(err, "STORAGE_ERROR", "Failed to import deprecated store files");
|
|
11274
|
+
}
|
|
11275
|
+
return release;
|
|
11276
|
+
}
|
|
11277
|
+
function forgottenKey(source, path2) {
|
|
11278
|
+
return storageError(
|
|
11279
|
+
`${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.`,
|
|
11280
|
+
{ key: source.key, ...path2 !== void 0 ? { path: path2 } : {} }
|
|
11281
|
+
);
|
|
11282
|
+
}
|
|
11283
|
+
|
|
11284
|
+
// src/storage/receipts/params.ts
|
|
10492
11285
|
var DEFAULT_LIST_LIMIT = 50;
|
|
10493
11286
|
var MAX_LIST_LIMIT = 500;
|
|
10494
11287
|
function clampListLimit(limit) {
|
|
10495
11288
|
const base = limit !== void 0 && Number.isFinite(limit) ? limit : DEFAULT_LIST_LIMIT;
|
|
10496
11289
|
return Math.min(Math.max(Math.trunc(base), 1), MAX_LIST_LIMIT);
|
|
10497
11290
|
}
|
|
11291
|
+
function storedIso(value, field) {
|
|
11292
|
+
const ms = Date.parse(value);
|
|
11293
|
+
if (!Number.isFinite(ms)) {
|
|
11294
|
+
throw new CommerceError("STORAGE_ERROR", `${field} is not a valid timestamp`);
|
|
11295
|
+
}
|
|
11296
|
+
return new Date(ms).toISOString();
|
|
11297
|
+
}
|
|
11298
|
+
|
|
11299
|
+
// src/storage/receipts/redact.ts
|
|
11300
|
+
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;
|
|
11301
|
+
var REDACTED = "[REDACTED]";
|
|
11302
|
+
function isSecretKey(key) {
|
|
11303
|
+
return SECRET_KEY_PATTERN.test(key);
|
|
11304
|
+
}
|
|
11305
|
+
function redact(value) {
|
|
11306
|
+
return redactValue(value);
|
|
11307
|
+
}
|
|
11308
|
+
function redactValue(value) {
|
|
11309
|
+
if (Array.isArray(value)) {
|
|
11310
|
+
return value.map(redactValue);
|
|
11311
|
+
}
|
|
11312
|
+
if (value !== null && typeof value === "object") {
|
|
11313
|
+
const out = {};
|
|
11314
|
+
for (const [key, inner] of Object.entries(value)) {
|
|
11315
|
+
out[key] = isSecretKey(key) ? REDACTED : redactValue(inner);
|
|
11316
|
+
}
|
|
11317
|
+
return out;
|
|
11318
|
+
}
|
|
11319
|
+
return value;
|
|
11320
|
+
}
|
|
11321
|
+
|
|
11322
|
+
// src/storage/receipts/holds.ts
|
|
11323
|
+
var TRANSITION_TARGETS = /* @__PURE__ */ new Set(["consumed", "released", "uncertain"]);
|
|
11324
|
+
var ORPHAN_HOLD_WHERE = `h.state = 'reserved' AND h.updated_at < ?
|
|
11325
|
+
AND NOT EXISTS (SELECT 1 FROM payment_attempts a WHERE a.request_id = h.request_id)
|
|
11326
|
+
AND NOT EXISTS (SELECT 1 FROM payment_attempt_history p WHERE p.request_id = h.request_id)`;
|
|
11327
|
+
function rowToHold(row) {
|
|
11328
|
+
return {
|
|
11329
|
+
method: row.method,
|
|
11330
|
+
reference: row.reference,
|
|
11331
|
+
bindingReference: row.binding_reference,
|
|
11332
|
+
resourceId: row.resource_id,
|
|
11333
|
+
requestId: row.request_id,
|
|
11334
|
+
...row.metadata_json !== null ? { metadata: JSON.parse(row.metadata_json) } : {},
|
|
11335
|
+
state: row.state,
|
|
11336
|
+
createdAt: row.created_at,
|
|
11337
|
+
updatedAt: row.updated_at
|
|
11338
|
+
};
|
|
11339
|
+
}
|
|
11340
|
+
function createHoldMethods(db, clock) {
|
|
11341
|
+
const selectHold = db.prepare(
|
|
11342
|
+
"SELECT * FROM authorization_holds WHERE reference = ?"
|
|
11343
|
+
);
|
|
11344
|
+
const selectLiveBinding = db.prepare(
|
|
11345
|
+
`SELECT state FROM authorization_holds
|
|
11346
|
+
WHERE binding_reference = ? AND reference != ? AND state != 'released' LIMIT 1`
|
|
11347
|
+
);
|
|
11348
|
+
const insertHold = db.prepare(
|
|
11349
|
+
`INSERT INTO authorization_holds
|
|
11350
|
+
(reference, method, binding_reference, resource_id, request_id, state, metadata_json, created_at, updated_at)
|
|
11351
|
+
VALUES (@reference, @method, @binding_reference, @resource_id, @request_id, 'reserved', @metadata_json, @at, @at)`
|
|
11352
|
+
);
|
|
11353
|
+
const reReserveHold = db.prepare(
|
|
11354
|
+
`UPDATE authorization_holds
|
|
11355
|
+
SET state = 'reserved', method = @method, binding_reference = @binding_reference,
|
|
11356
|
+
resource_id = @resource_id, request_id = @request_id,
|
|
11357
|
+
metadata_json = @metadata_json, updated_at = @at
|
|
11358
|
+
WHERE reference = @reference AND state = 'released'`
|
|
11359
|
+
);
|
|
11360
|
+
const transitionHold = db.prepare(
|
|
11361
|
+
`UPDATE authorization_holds SET state = @state, updated_at = @at
|
|
11362
|
+
WHERE reference = @reference AND state IN ('reserved', 'uncertain')
|
|
11363
|
+
AND (@request_id IS NULL OR request_id = @request_id)`
|
|
11364
|
+
);
|
|
11365
|
+
const listOrphans = db.prepare(
|
|
11366
|
+
`SELECT h.* FROM authorization_holds h WHERE ${ORPHAN_HOLD_WHERE}
|
|
11367
|
+
ORDER BY h.updated_at, h.reference LIMIT ?`
|
|
11368
|
+
);
|
|
11369
|
+
const reserve = db.transaction(
|
|
11370
|
+
(reservation) => {
|
|
11371
|
+
const existing = selectHold.get(reservation.reference);
|
|
11372
|
+
if (existing !== void 0 && existing.state !== "released") {
|
|
11373
|
+
return { kind: "replayed", state: existing.state };
|
|
11374
|
+
}
|
|
11375
|
+
const binding = selectLiveBinding.get(reservation.bindingReference, reservation.reference);
|
|
11376
|
+
if (binding !== void 0) {
|
|
11377
|
+
return { kind: "replayed", state: binding.state };
|
|
11378
|
+
}
|
|
11379
|
+
const params = {
|
|
11380
|
+
reference: reservation.reference,
|
|
11381
|
+
method: reservation.method,
|
|
11382
|
+
binding_reference: reservation.bindingReference,
|
|
11383
|
+
resource_id: reservation.resourceId,
|
|
11384
|
+
request_id: reservation.requestId,
|
|
11385
|
+
metadata_json: reservation.metadata !== void 0 ? JSON.stringify(redact(reservation.metadata)) : null,
|
|
11386
|
+
at: clock.nowIso()
|
|
11387
|
+
};
|
|
11388
|
+
(existing !== void 0 ? reReserveHold : insertHold).run(params);
|
|
11389
|
+
return { kind: "reserved" };
|
|
11390
|
+
}
|
|
11391
|
+
);
|
|
11392
|
+
const transition = db.transaction(
|
|
11393
|
+
(reference, to, requestId) => {
|
|
11394
|
+
const { changes } = transitionHold.run({
|
|
11395
|
+
reference,
|
|
11396
|
+
state: to,
|
|
11397
|
+
request_id: requestId ?? null,
|
|
11398
|
+
at: clock.nowIso()
|
|
11399
|
+
});
|
|
11400
|
+
if (changes > 0) return true;
|
|
11401
|
+
const row = selectHold.get(reference);
|
|
11402
|
+
if (row === void 0) return false;
|
|
11403
|
+
if (requestId !== void 0 && row.request_id !== requestId) return to === "released";
|
|
11404
|
+
return row.state === to;
|
|
11405
|
+
}
|
|
11406
|
+
);
|
|
11407
|
+
return {
|
|
11408
|
+
async reserveAuthorizationHold(reservation) {
|
|
11409
|
+
try {
|
|
11410
|
+
return reserve.immediate(reservation);
|
|
11411
|
+
} catch (err) {
|
|
11412
|
+
throw toCommerceError(err, "STORAGE_ERROR", "Failed to reserve authorization hold");
|
|
11413
|
+
}
|
|
11414
|
+
},
|
|
11415
|
+
async transitionAuthorizationHold(reference, to, requestId) {
|
|
11416
|
+
try {
|
|
11417
|
+
if (!TRANSITION_TARGETS.has(to)) {
|
|
11418
|
+
throw new CommerceError("STORAGE_ERROR", `Invalid authorization hold target: ${to}`);
|
|
11419
|
+
}
|
|
11420
|
+
return transition.immediate(reference, to, requestId);
|
|
11421
|
+
} catch (err) {
|
|
11422
|
+
throw toCommerceError(err, "STORAGE_ERROR", "Failed to update authorization hold");
|
|
11423
|
+
}
|
|
11424
|
+
},
|
|
11425
|
+
async getAuthorizationHoldState(reference) {
|
|
11426
|
+
return selectHold.get(reference)?.state;
|
|
11427
|
+
},
|
|
11428
|
+
async listOrphanAuthorizationHolds(options) {
|
|
11429
|
+
const before = storedIso(options.updatedBefore, "updatedBefore");
|
|
11430
|
+
return listOrphans.all(before, clampListLimit(options.limit)).map(rowToHold);
|
|
11431
|
+
}
|
|
11432
|
+
};
|
|
11433
|
+
}
|
|
11434
|
+
|
|
11435
|
+
// src/storage/receipts/idempotency.ts
|
|
11436
|
+
var scopeParams = (scope) => ({
|
|
11437
|
+
deployment: scope.deployment,
|
|
11438
|
+
endpoint: scope.endpoint,
|
|
11439
|
+
idempotency_key: scope.key
|
|
11440
|
+
});
|
|
11441
|
+
function createIdempotencyMethods(db, clock) {
|
|
11442
|
+
const SCOPE = "deployment = @deployment AND endpoint = @endpoint AND idempotency_key = @idempotency_key";
|
|
11443
|
+
const selectClaim = db.prepare(
|
|
11444
|
+
`SELECT state, fingerprint, status, body_json FROM idempotency_keys WHERE ${SCOPE}`
|
|
11445
|
+
);
|
|
11446
|
+
const insertClaim = db.prepare(
|
|
11447
|
+
`INSERT INTO idempotency_keys
|
|
11448
|
+
(deployment, endpoint, idempotency_key, fingerprint, state, created_at, expires_at)
|
|
11449
|
+
VALUES (@deployment, @endpoint, @idempotency_key, @fingerprint, 'in_flight', @created_at, @expires_at)`
|
|
11450
|
+
);
|
|
11451
|
+
const expireCompleted = db.prepare(
|
|
11452
|
+
"DELETE FROM idempotency_keys WHERE expires_at <= ? AND state = 'completed'"
|
|
11453
|
+
);
|
|
11454
|
+
const completeClaim = db.prepare(
|
|
11455
|
+
`UPDATE idempotency_keys SET state = 'completed', status = @status, body_json = @body_json
|
|
11456
|
+
WHERE ${SCOPE}`
|
|
11457
|
+
);
|
|
11458
|
+
const markUnresolved = db.prepare(
|
|
11459
|
+
`UPDATE idempotency_keys SET state = 'unresolved' WHERE ${SCOPE}`
|
|
11460
|
+
);
|
|
11461
|
+
const deleteClaim = db.prepare(`DELETE FROM idempotency_keys WHERE ${SCOPE}`);
|
|
11462
|
+
const releaseInFlight = db.prepare("DELETE FROM idempotency_keys WHERE state = 'in_flight'");
|
|
11463
|
+
const unresolveInFlight = db.prepare(
|
|
11464
|
+
"UPDATE idempotency_keys SET state = 'unresolved' WHERE state = 'in_flight'"
|
|
11465
|
+
);
|
|
11466
|
+
const claim = db.transaction(
|
|
11467
|
+
(scope, fingerprint, expiresAt) => {
|
|
11468
|
+
const now = clock.nowIso();
|
|
11469
|
+
expireCompleted.run(now);
|
|
11470
|
+
const existing = selectClaim.get(scopeParams(scope));
|
|
11471
|
+
if (existing === void 0) {
|
|
11472
|
+
insertClaim.run({
|
|
11473
|
+
...scopeParams(scope),
|
|
11474
|
+
fingerprint,
|
|
11475
|
+
created_at: now,
|
|
11476
|
+
expires_at: expiresAt
|
|
11477
|
+
});
|
|
11478
|
+
return { kind: "reserved" };
|
|
11479
|
+
}
|
|
11480
|
+
if (existing.fingerprint !== fingerprint) return { kind: "conflict" };
|
|
11481
|
+
if (existing.state === "unresolved") return { kind: "unresolved" };
|
|
11482
|
+
if (existing.state !== "completed") return { kind: "in-flight" };
|
|
11483
|
+
return {
|
|
11484
|
+
kind: "replay",
|
|
11485
|
+
status: existing.status ?? 500,
|
|
11486
|
+
body: existing.body_json === null ? null : JSON.parse(existing.body_json)
|
|
11487
|
+
};
|
|
11488
|
+
}
|
|
11489
|
+
);
|
|
11490
|
+
return {
|
|
11491
|
+
async claimIdempotencyKey(scope, fingerprint, expiresAt) {
|
|
11492
|
+
try {
|
|
11493
|
+
return claim.immediate(scope, fingerprint, storedIso(expiresAt, "expiresAt"));
|
|
11494
|
+
} catch (err) {
|
|
11495
|
+
throw toCommerceError(err, "STORAGE_ERROR", "Failed to claim idempotency key");
|
|
11496
|
+
}
|
|
11497
|
+
},
|
|
11498
|
+
async updateIdempotencyKey(scope, update) {
|
|
11499
|
+
try {
|
|
11500
|
+
switch (update.kind) {
|
|
11501
|
+
case "completed":
|
|
11502
|
+
completeClaim.run({
|
|
11503
|
+
...scopeParams(scope),
|
|
11504
|
+
status: update.status,
|
|
11505
|
+
body_json: JSON.stringify(update.body ?? null)
|
|
11506
|
+
});
|
|
11507
|
+
break;
|
|
11508
|
+
case "unresolved":
|
|
11509
|
+
markUnresolved.run(scopeParams(scope));
|
|
11510
|
+
break;
|
|
11511
|
+
case "released":
|
|
11512
|
+
deleteClaim.run(scopeParams(scope));
|
|
11513
|
+
break;
|
|
11514
|
+
}
|
|
11515
|
+
} catch (err) {
|
|
11516
|
+
throw toCommerceError(err, "STORAGE_ERROR", "Failed to update idempotency key");
|
|
11517
|
+
}
|
|
11518
|
+
},
|
|
11519
|
+
async recoverIdempotencyKeys(options) {
|
|
11520
|
+
try {
|
|
11521
|
+
return (options.release ? releaseInFlight : unresolveInFlight).run().changes;
|
|
11522
|
+
} catch (err) {
|
|
11523
|
+
throw toCommerceError(err, "STORAGE_ERROR", "Failed to recover idempotency keys");
|
|
11524
|
+
}
|
|
11525
|
+
}
|
|
11526
|
+
};
|
|
11527
|
+
}
|
|
11528
|
+
|
|
11529
|
+
// src/storage/receipts/pending-tasks.ts
|
|
11530
|
+
function rowToTask(row) {
|
|
11531
|
+
return {
|
|
11532
|
+
id: row.id,
|
|
11533
|
+
protocol: row.protocol,
|
|
11534
|
+
resourceId: row.resource_id,
|
|
11535
|
+
input: JSON.parse(row.input_json),
|
|
11536
|
+
...row.adapter_data_json !== null ? { adapterData: JSON.parse(row.adapter_data_json) } : {},
|
|
11537
|
+
expiresAt: row.expires_at
|
|
11538
|
+
};
|
|
11539
|
+
}
|
|
11540
|
+
function withoutReservedFields(input) {
|
|
11541
|
+
return Object.fromEntries(
|
|
11542
|
+
Object.entries(input).filter(([key]) => !RESERVED_INPUT_FIELDS.includes(key))
|
|
11543
|
+
);
|
|
11544
|
+
}
|
|
11545
|
+
var SWEEP_EXPIRED = "DELETE FROM pending_tasks WHERE expires_at <= ?";
|
|
11546
|
+
function sweepExpiredPendingTasks(db, now) {
|
|
11547
|
+
db.prepare(SWEEP_EXPIRED).run(now);
|
|
11548
|
+
}
|
|
11549
|
+
function createPendingTaskMethods(db, clock) {
|
|
11550
|
+
const sweepExpired = db.prepare(SWEEP_EXPIRED);
|
|
11551
|
+
const countLive = db.prepare(
|
|
11552
|
+
"SELECT COUNT(*) AS count FROM pending_tasks WHERE expires_at > ?"
|
|
11553
|
+
);
|
|
11554
|
+
const upsertTask = db.prepare(
|
|
11555
|
+
`INSERT OR REPLACE INTO pending_tasks
|
|
11556
|
+
(id, protocol, resource_id, input_json, adapter_data_json, created_at, expires_at)
|
|
11557
|
+
VALUES (@id, @protocol, @resource_id, @input_json, @adapter_data_json, @created_at, @expires_at)`
|
|
11558
|
+
);
|
|
11559
|
+
const selectLive = db.prepare(
|
|
11560
|
+
"SELECT * FROM pending_tasks WHERE id = ? AND expires_at > ?"
|
|
11561
|
+
);
|
|
11562
|
+
const takeLive = db.prepare(
|
|
11563
|
+
"DELETE FROM pending_tasks WHERE id = ? AND expires_at > ? RETURNING *"
|
|
11564
|
+
);
|
|
11565
|
+
const put = db.transaction((task2, maxTasks, expiresAt) => {
|
|
11566
|
+
const now = clock.nowIso();
|
|
11567
|
+
sweepExpired.run(now);
|
|
11568
|
+
if ((countLive.get(now)?.count ?? 0) >= maxTasks) return false;
|
|
11569
|
+
upsertTask.run({
|
|
11570
|
+
id: task2.id,
|
|
11571
|
+
protocol: task2.protocol,
|
|
11572
|
+
resource_id: task2.resourceId,
|
|
11573
|
+
input_json: JSON.stringify(withoutReservedFields(task2.input)),
|
|
11574
|
+
adapter_data_json: task2.adapterData !== void 0 ? JSON.stringify(task2.adapterData) : null,
|
|
11575
|
+
created_at: now,
|
|
11576
|
+
expires_at: expiresAt
|
|
11577
|
+
});
|
|
11578
|
+
return true;
|
|
11579
|
+
});
|
|
11580
|
+
return {
|
|
11581
|
+
async putPendingTask(task2, options) {
|
|
11582
|
+
try {
|
|
11583
|
+
if (!Number.isInteger(options.maxTasks) || options.maxTasks < 0) {
|
|
11584
|
+
throw new CommerceError("STORAGE_ERROR", "maxTasks must be a non-negative integer");
|
|
11585
|
+
}
|
|
11586
|
+
return put.immediate(task2, options.maxTasks, storedIso(task2.expiresAt, "expiresAt"));
|
|
11587
|
+
} catch (err) {
|
|
11588
|
+
throw toCommerceError(err, "STORAGE_ERROR", "Failed to store pending task");
|
|
11589
|
+
}
|
|
11590
|
+
},
|
|
11591
|
+
async getPendingTask(id) {
|
|
11592
|
+
const row = selectLive.get(id, clock.nowIso());
|
|
11593
|
+
return row !== void 0 ? rowToTask(row) : void 0;
|
|
11594
|
+
},
|
|
11595
|
+
async takePendingTask(id) {
|
|
11596
|
+
try {
|
|
11597
|
+
const now = clock.nowIso();
|
|
11598
|
+
sweepExpired.run(now);
|
|
11599
|
+
const row = takeLive.get(id, now);
|
|
11600
|
+
return row !== void 0 ? rowToTask(row) : void 0;
|
|
11601
|
+
} catch (err) {
|
|
11602
|
+
throw toCommerceError(err, "STORAGE_ERROR", "Failed to take pending task");
|
|
11603
|
+
}
|
|
11604
|
+
}
|
|
11605
|
+
};
|
|
11606
|
+
}
|
|
11607
|
+
|
|
11608
|
+
// src/storage/receipts/rows.ts
|
|
11609
|
+
function receiptToRow(receipt) {
|
|
11610
|
+
return {
|
|
11611
|
+
id: receipt.id,
|
|
11612
|
+
request_id: receipt.requestId,
|
|
11613
|
+
resource_id: receipt.resourceId,
|
|
11614
|
+
payment_json: receipt.payment !== void 0 ? JSON.stringify(redact(receipt.payment)) : null,
|
|
11615
|
+
delivered_at: receipt.deliveredAt,
|
|
11616
|
+
backend_status: receipt.backendStatus,
|
|
11617
|
+
duration_ms: receipt.durationMs ?? null,
|
|
11618
|
+
protocol: receipt.protocol ?? null,
|
|
11619
|
+
metadata_json: receipt.metadata !== void 0 ? JSON.stringify(redact(receipt.metadata)) : null,
|
|
11620
|
+
authorization_json: receipt.authorization !== void 0 ? JSON.stringify(redact(receipt.authorization)) : null,
|
|
11621
|
+
transaction_id: receipt.transactionId ?? null
|
|
11622
|
+
};
|
|
11623
|
+
}
|
|
11624
|
+
function rowToReceipt(row) {
|
|
11625
|
+
const payment = row.payment_json !== null ? JSON.parse(row.payment_json) : void 0;
|
|
11626
|
+
const metadata = row.metadata_json !== null ? JSON.parse(row.metadata_json) : void 0;
|
|
11627
|
+
const authorization = row.authorization_json !== null ? JSON.parse(row.authorization_json) : void 0;
|
|
11628
|
+
return {
|
|
11629
|
+
id: row.id,
|
|
11630
|
+
requestId: row.request_id,
|
|
11631
|
+
resourceId: row.resource_id,
|
|
11632
|
+
deliveredAt: row.delivered_at,
|
|
11633
|
+
backendStatus: row.backend_status,
|
|
11634
|
+
...payment !== void 0 ? { payment } : {},
|
|
11635
|
+
...row.duration_ms !== null ? { durationMs: row.duration_ms } : {},
|
|
11636
|
+
...row.protocol !== null ? { protocol: row.protocol } : {},
|
|
11637
|
+
...metadata !== void 0 ? { metadata } : {},
|
|
11638
|
+
...authorization !== void 0 ? { authorization } : {},
|
|
11639
|
+
...row.transaction_id !== null ? { transactionId: row.transaction_id } : {}
|
|
11640
|
+
};
|
|
11641
|
+
}
|
|
11642
|
+
function eventToRow(event) {
|
|
11643
|
+
return {
|
|
11644
|
+
id: event.id,
|
|
11645
|
+
type: event.type,
|
|
11646
|
+
request_id: event.requestId,
|
|
11647
|
+
resource_id: event.resourceId ?? null,
|
|
11648
|
+
at: event.at,
|
|
11649
|
+
adapter: event.adapter ?? null,
|
|
11650
|
+
payment_provider: event.paymentProvider ?? null,
|
|
11651
|
+
duration_ms: event.durationMs ?? null,
|
|
11652
|
+
status: event.status ?? null,
|
|
11653
|
+
data_json: event.data !== void 0 ? JSON.stringify(redact(event.data)) : null,
|
|
11654
|
+
transaction_id: event.transactionId ?? null
|
|
11655
|
+
};
|
|
11656
|
+
}
|
|
11657
|
+
function rowToEvent(row) {
|
|
11658
|
+
const data = row.data_json !== null ? JSON.parse(row.data_json) : void 0;
|
|
11659
|
+
return {
|
|
11660
|
+
id: row.id,
|
|
11661
|
+
type: row.type,
|
|
11662
|
+
requestId: row.request_id,
|
|
11663
|
+
at: row.at,
|
|
11664
|
+
...row.resource_id !== null ? { resourceId: row.resource_id } : {},
|
|
11665
|
+
...row.adapter !== null ? { adapter: row.adapter } : {},
|
|
11666
|
+
...row.payment_provider !== null ? { paymentProvider: row.payment_provider } : {},
|
|
11667
|
+
...row.duration_ms !== null ? { durationMs: row.duration_ms } : {},
|
|
11668
|
+
...row.status !== null ? { status: row.status } : {},
|
|
11669
|
+
...data !== void 0 ? { data } : {},
|
|
11670
|
+
...row.transaction_id !== null ? { transactionId: row.transaction_id } : {}
|
|
11671
|
+
};
|
|
11672
|
+
}
|
|
11673
|
+
function rowToPaymentAttempt(row) {
|
|
11674
|
+
return {
|
|
11675
|
+
id: row.id,
|
|
11676
|
+
requestId: row.request_id,
|
|
11677
|
+
resourceId: row.resource_id,
|
|
11678
|
+
provider: row.provider,
|
|
11679
|
+
replayKey: row.replay_key,
|
|
11680
|
+
status: row.status,
|
|
11681
|
+
amount: row.amount,
|
|
11682
|
+
currency: row.currency,
|
|
11683
|
+
...row.payer !== null ? { payer: row.payer } : {},
|
|
11684
|
+
...row.payee !== null ? { payee: row.payee } : {},
|
|
11685
|
+
...row.external_reference !== null ? { externalReference: row.external_reference } : {},
|
|
11686
|
+
...row.rejection_reason !== null ? { rejectionReason: row.rejection_reason } : {},
|
|
11687
|
+
createdAt: row.created_at,
|
|
11688
|
+
updatedAt: row.updated_at,
|
|
11689
|
+
...row.transaction_id !== null ? { transactionId: row.transaction_id } : {},
|
|
11690
|
+
...row.resolution_json !== null ? { resolution: JSON.parse(row.resolution_json) } : {}
|
|
11691
|
+
};
|
|
11692
|
+
}
|
|
11693
|
+
function rowToTransaction(row, now) {
|
|
11694
|
+
const status = row.payment_status;
|
|
11695
|
+
const backend = row.backend_dispatched_at !== null && row.backend_deadline_at !== null ? {
|
|
11696
|
+
dispatchedAt: row.backend_dispatched_at,
|
|
11697
|
+
deadlineAt: row.backend_deadline_at,
|
|
11698
|
+
...row.backend_status !== null ? { status: row.backend_status } : {},
|
|
11699
|
+
...row.backend_error_code !== null ? { errorCode: row.backend_error_code } : {}
|
|
11700
|
+
} : void 0;
|
|
11701
|
+
const completedAt = row.completed_at ?? void 0;
|
|
11702
|
+
const authorization = row.authorization_json !== null && row.reservation_id !== null ? {
|
|
11703
|
+
...JSON.parse(row.authorization_json),
|
|
11704
|
+
reservationId: row.reservation_id
|
|
11705
|
+
} : void 0;
|
|
11706
|
+
return {
|
|
11707
|
+
id: row.id,
|
|
11708
|
+
requestId: row.request_id,
|
|
11709
|
+
resourceId: row.resource_id,
|
|
11710
|
+
protocol: row.protocol,
|
|
11711
|
+
state: transactionState(
|
|
11712
|
+
{
|
|
11713
|
+
payment: { status },
|
|
11714
|
+
...backend !== void 0 ? { backend } : {},
|
|
11715
|
+
...completedAt !== void 0 ? { completedAt } : {}
|
|
11716
|
+
},
|
|
11717
|
+
now
|
|
11718
|
+
),
|
|
11719
|
+
payment: {
|
|
11720
|
+
provider: row.provider,
|
|
11721
|
+
attemptId: row.attempt_id,
|
|
11722
|
+
replayKey: row.replay_key,
|
|
11723
|
+
status,
|
|
11724
|
+
amount: row.payment_amount,
|
|
11725
|
+
currency: row.payment_currency,
|
|
11726
|
+
...row.network !== null ? { network: row.network } : {},
|
|
11727
|
+
...row.asset !== null ? { asset: row.asset } : {},
|
|
11728
|
+
...row.payment_payee !== null ? { payee: row.payment_payee } : {},
|
|
11729
|
+
...row.payment_external_reference !== null ? { externalReference: row.payment_external_reference } : {},
|
|
11730
|
+
...row.locator_json !== null ? { locator: JSON.parse(row.locator_json) } : {},
|
|
11731
|
+
...row.settling_at !== null ? { settlingAt: row.settling_at } : {},
|
|
11732
|
+
...row.expires_at !== null ? { expiresAt: row.expires_at } : {}
|
|
11733
|
+
},
|
|
11734
|
+
...authorization !== void 0 ? { authorization } : {},
|
|
11735
|
+
...backend !== void 0 ? { backend } : {},
|
|
11736
|
+
...row.receipt_id !== null ? { receiptId: row.receipt_id } : {},
|
|
11737
|
+
...row.input_digest !== null ? { inputDigest: row.input_digest } : {},
|
|
11738
|
+
configDigest: row.config_digest,
|
|
11739
|
+
...row.persistence_failures_json !== null ? { persistenceFailures: JSON.parse(row.persistence_failures_json) } : {},
|
|
11740
|
+
createdAt: row.created_at,
|
|
11741
|
+
updatedAt: row.updated_at,
|
|
11742
|
+
...completedAt !== void 0 ? { completedAt } : {}
|
|
11743
|
+
};
|
|
11744
|
+
}
|
|
11745
|
+
|
|
11746
|
+
// src/storage/receipts/store.ts
|
|
10498
11747
|
var UNDELIVERED = "backend_status NOT BETWEEN 200 AND 299";
|
|
10499
11748
|
var UNCERTAIN = "status IN ('settlement-uncertain', 'failed')";
|
|
11749
|
+
var TRANSACTION_SELECT = `
|
|
11750
|
+
SELECT t.*,
|
|
11751
|
+
COALESCE(a.status, h.status) AS payment_status,
|
|
11752
|
+
COALESCE(a.amount, h.amount) AS payment_amount,
|
|
11753
|
+
COALESCE(a.currency, h.currency) AS payment_currency,
|
|
11754
|
+
COALESCE(a.payee, h.payee) AS payment_payee,
|
|
11755
|
+
COALESCE(a.external_reference, h.external_reference) AS payment_external_reference
|
|
11756
|
+
FROM transactions t
|
|
11757
|
+
LEFT JOIN payment_attempts a ON a.id = t.attempt_id
|
|
11758
|
+
LEFT JOIN payment_attempt_history h ON a.id IS NULL AND h.seq = (
|
|
11759
|
+
SELECT MAX(seq) FROM payment_attempt_history
|
|
11760
|
+
WHERE replay_key = t.replay_key AND id = t.attempt_id
|
|
11761
|
+
)`;
|
|
11762
|
+
var TIME_DEPENDENT = "t.backend_deadline_at IS NOT NULL AND t.completed_at IS NULL";
|
|
11763
|
+
var RESOLVED_STATES = ["delivered", "payment-failed"];
|
|
11764
|
+
var CURSOR_PATTERN = /^[1-9][0-9]{0,15}$/;
|
|
10500
11765
|
var defaultIds = {
|
|
10501
11766
|
next: (prefix) => prefix !== void 0 ? `${prefix}_${randomUUID()}` : randomUUID()
|
|
10502
11767
|
};
|
|
@@ -10504,16 +11769,23 @@ function isUniqueConstraintOn(err, column) {
|
|
|
10504
11769
|
return err instanceof Error && "code" in err && err.code === "SQLITE_CONSTRAINT_UNIQUE" && err.message.includes(column);
|
|
10505
11770
|
}
|
|
10506
11771
|
function createSqliteReceiptStore(options) {
|
|
11772
|
+
const db = openSqliteDatabase({
|
|
11773
|
+
path: options.path,
|
|
11774
|
+
label: "Receipt database",
|
|
11775
|
+
logger: options.logger ?? NOOP_LOGGER
|
|
11776
|
+
});
|
|
11777
|
+
migrate2(db);
|
|
11778
|
+
return storeOn(db, options);
|
|
11779
|
+
}
|
|
11780
|
+
function storeOn(db, options) {
|
|
10507
11781
|
const logger = options.logger ?? NOOP_LOGGER;
|
|
10508
11782
|
const clock = options.clock ?? systemClock;
|
|
10509
11783
|
const ids = options.ids ?? defaultIds;
|
|
10510
11784
|
const path2 = options.path;
|
|
10511
11785
|
const isFileBacked = path2 !== ":memory:";
|
|
10512
|
-
const db = openSqliteDatabase({ path: path2, label: "Receipt database", logger });
|
|
10513
|
-
migrate2(db);
|
|
10514
11786
|
const insertReceiptStmt = db.prepare(
|
|
10515
|
-
`INSERT INTO receipts (id, request_id, resource_id, payment_json, delivered_at, backend_status, duration_ms, protocol, metadata_json, authorization_json)
|
|
10516
|
-
VALUES (@id, @request_id, @resource_id, @payment_json, @delivered_at, @backend_status, @duration_ms, @protocol, @metadata_json, @authorization_json)`
|
|
11787
|
+
`INSERT INTO receipts (id, request_id, resource_id, payment_json, delivered_at, backend_status, duration_ms, protocol, metadata_json, authorization_json, transaction_id)
|
|
11788
|
+
VALUES (@id, @request_id, @resource_id, @payment_json, @delivered_at, @backend_status, @duration_ms, @protocol, @metadata_json, @authorization_json, @transaction_id)`
|
|
10517
11789
|
);
|
|
10518
11790
|
const getReceiptStmt = db.prepare("SELECT * FROM receipts WHERE id = ?");
|
|
10519
11791
|
const listReceiptsStmt = db.prepare(
|
|
@@ -10535,8 +11807,8 @@ function createSqliteReceiptStore(options) {
|
|
|
10535
11807
|
`SELECT COUNT(*) AS count FROM receipts WHERE ${UNDELIVERED}`
|
|
10536
11808
|
);
|
|
10537
11809
|
const insertEventStmt = db.prepare(
|
|
10538
|
-
`INSERT INTO events (id, type, request_id, resource_id, at, adapter, payment_provider, duration_ms, status, data_json)
|
|
10539
|
-
VALUES (@id, @type, @request_id, @resource_id, @at, @adapter, @payment_provider, @duration_ms, @status, @data_json)`
|
|
11810
|
+
`INSERT INTO events (id, type, request_id, resource_id, at, adapter, payment_provider, duration_ms, status, data_json, transaction_id)
|
|
11811
|
+
VALUES (@id, @type, @request_id, @resource_id, @at, @adapter, @payment_provider, @duration_ms, @status, @data_json, @transaction_id)`
|
|
10540
11812
|
);
|
|
10541
11813
|
const listEventsStmt = db.prepare(
|
|
10542
11814
|
"SELECT * FROM events ORDER BY at DESC, seq DESC LIMIT ?"
|
|
@@ -10545,13 +11817,13 @@ function createSqliteReceiptStore(options) {
|
|
|
10545
11817
|
"SELECT * FROM events WHERE request_id = ? ORDER BY at DESC, seq DESC LIMIT ?"
|
|
10546
11818
|
);
|
|
10547
11819
|
const insertPaymentAttemptStmt = db.prepare(
|
|
10548
|
-
`INSERT INTO payment_attempts (id, request_id, resource_id, provider, replay_key, status, amount, currency, payer, payee, external_reference, rejection_reason, created_at, updated_at)
|
|
10549
|
-
VALUES (@id, @request_id, @resource_id, @provider, @replay_key, @status, @amount, @currency, @payer, @payee, @external_reference, @rejection_reason, @created_at, @updated_at)
|
|
11820
|
+
`INSERT INTO payment_attempts (id, request_id, resource_id, provider, replay_key, status, amount, currency, payer, payee, external_reference, rejection_reason, created_at, updated_at, transaction_id)
|
|
11821
|
+
VALUES (@id, @request_id, @resource_id, @provider, @replay_key, @status, @amount, @currency, @payer, @payee, @external_reference, @rejection_reason, @created_at, @updated_at, @transaction_id)
|
|
10550
11822
|
RETURNING *`
|
|
10551
11823
|
);
|
|
10552
11824
|
const archiveRejectedAttemptStmt = db.prepare(
|
|
10553
|
-
`INSERT INTO payment_attempt_history (id, request_id, resource_id, provider, replay_key, status, amount, currency, payer, payee, external_reference, rejection_reason, created_at, updated_at, superseded_at)
|
|
10554
|
-
SELECT id, request_id, resource_id, provider, replay_key, status, amount, currency, payer, payee, external_reference, rejection_reason, created_at, updated_at, @created_at
|
|
11825
|
+
`INSERT INTO payment_attempt_history (id, request_id, resource_id, provider, replay_key, status, amount, currency, payer, payee, external_reference, rejection_reason, created_at, updated_at, superseded_at, transaction_id, resolution_json)
|
|
11826
|
+
SELECT id, request_id, resource_id, provider, replay_key, status, amount, currency, payer, payee, external_reference, rejection_reason, created_at, updated_at, @created_at, transaction_id, resolution_json
|
|
10555
11827
|
FROM payment_attempts
|
|
10556
11828
|
WHERE replay_key = @replay_key AND provider = @provider AND status = 'rejected'`
|
|
10557
11829
|
);
|
|
@@ -10559,7 +11831,8 @@ function createSqliteReceiptStore(options) {
|
|
|
10559
11831
|
`UPDATE payment_attempts SET id = @id, request_id = @request_id, resource_id = @resource_id,
|
|
10560
11832
|
status = 'reserved', amount = @amount, currency = @currency,
|
|
10561
11833
|
payer = @payer, payee = @payee, external_reference = NULL, rejection_reason = NULL,
|
|
10562
|
-
created_at = @created_at, updated_at = @updated_at
|
|
11834
|
+
created_at = @created_at, updated_at = @updated_at,
|
|
11835
|
+
transaction_id = @transaction_id, resolution_json = NULL
|
|
10563
11836
|
WHERE replay_key = @replay_key AND provider = @provider AND status = 'rejected'
|
|
10564
11837
|
RETURNING *`
|
|
10565
11838
|
);
|
|
@@ -10568,7 +11841,7 @@ function createSqliteReceiptStore(options) {
|
|
|
10568
11841
|
external_reference = COALESCE(@external_reference, external_reference),
|
|
10569
11842
|
rejection_reason = COALESCE(@rejection_reason, rejection_reason),
|
|
10570
11843
|
updated_at = @updated_at
|
|
10571
|
-
WHERE replay_key = @replay_key`
|
|
11844
|
+
WHERE replay_key = @replay_key AND resolution_json IS NULL`
|
|
10572
11845
|
);
|
|
10573
11846
|
const listPaymentAttemptsStmt = db.prepare(
|
|
10574
11847
|
"SELECT * FROM payment_attempts ORDER BY created_at DESC, seq DESC LIMIT ?"
|
|
@@ -10585,22 +11858,212 @@ function createSqliteReceiptStore(options) {
|
|
|
10585
11858
|
const countUncertainPaymentAttemptsStmt = db.prepare(
|
|
10586
11859
|
`SELECT COUNT(*) AS count FROM payment_attempts WHERE ${UNCERTAIN}`
|
|
10587
11860
|
);
|
|
10588
|
-
const paymentAttemptStatusStmt = db.prepare(
|
|
10589
|
-
|
|
11861
|
+
const paymentAttemptStatusStmt = db.prepare("SELECT id, status, resolution_json FROM payment_attempts WHERE replay_key = ?");
|
|
11862
|
+
const insertTransactionStmt = db.prepare(
|
|
11863
|
+
`INSERT INTO transactions (id, request_id, resource_id, protocol, state, provider, attempt_id, replay_key, network, asset, authorization_json, reservation_id, locator_json, expires_at, input_digest, config_digest, created_at, updated_at)
|
|
11864
|
+
VALUES (@id, @request_id, @resource_id, @protocol, @state, @provider, @attempt_id, @replay_key, @network, @asset, @authorization_json, @reservation_id, @locator_json, @expires_at, @input_digest, @config_digest, @created_at, @created_at)`
|
|
11865
|
+
);
|
|
11866
|
+
const getTransactionStmt = db.prepare(
|
|
11867
|
+
`${TRANSACTION_SELECT} WHERE t.id = ?`
|
|
11868
|
+
);
|
|
11869
|
+
const transactionsOfAttemptStmt = db.prepare(
|
|
11870
|
+
`SELECT t.id FROM payment_attempts a
|
|
11871
|
+
JOIN transactions t ON t.replay_key = a.replay_key AND t.attempt_id = a.id
|
|
11872
|
+
WHERE a.replay_key = ?`
|
|
11873
|
+
);
|
|
11874
|
+
const transactionsOfAttemptIdStmt = db.prepare(
|
|
11875
|
+
`SELECT t.id FROM payment_attempts a
|
|
11876
|
+
JOIN transactions t ON t.replay_key = a.replay_key AND t.attempt_id = a.id
|
|
11877
|
+
WHERE a.id = ?`
|
|
11878
|
+
);
|
|
11879
|
+
const setTransactionStateStmt = db.prepare("UPDATE transactions SET state = ? WHERE id = ?");
|
|
11880
|
+
const stepStmts = {
|
|
11881
|
+
settling: db.prepare(
|
|
11882
|
+
"UPDATE transactions SET settling_at = @at, updated_at = @at WHERE id = @id"
|
|
11883
|
+
),
|
|
11884
|
+
// A transaction without an authorization has no hold to record
|
|
11885
|
+
hold: db.prepare(
|
|
11886
|
+
`UPDATE transactions SET authorization_json = json_set(authorization_json, '$.hold', @hold), updated_at = @at
|
|
11887
|
+
WHERE id = @id AND authorization_json IS NOT NULL`
|
|
11888
|
+
),
|
|
11889
|
+
"backend-dispatched": db.prepare(
|
|
11890
|
+
`UPDATE transactions SET backend_dispatched_at = @at, backend_deadline_at = @deadline_at, updated_at = @at
|
|
11891
|
+
WHERE id = @id`
|
|
11892
|
+
),
|
|
11893
|
+
// Preserve a backend result even when the dispatch step was not saved:
|
|
11894
|
+
// use the result time for missing dispatch and deadline timestamps
|
|
11895
|
+
"backend-result": db.prepare(
|
|
11896
|
+
`UPDATE transactions SET backend_status = @status, backend_error_code = @error_code,
|
|
11897
|
+
backend_dispatched_at = COALESCE(backend_dispatched_at, @at),
|
|
11898
|
+
backend_deadline_at = COALESCE(backend_deadline_at, @at), updated_at = @at
|
|
11899
|
+
WHERE id = @id`
|
|
11900
|
+
),
|
|
11901
|
+
receipt: db.prepare(
|
|
11902
|
+
"UPDATE transactions SET receipt_id = @receipt_id, updated_at = @at WHERE id = @id"
|
|
11903
|
+
),
|
|
11904
|
+
completed: db.prepare(
|
|
11905
|
+
`UPDATE transactions SET completed_at = @at, persistence_failures_json = @persistence_failures_json, updated_at = @at
|
|
11906
|
+
WHERE id = @id`
|
|
11907
|
+
)
|
|
11908
|
+
};
|
|
11909
|
+
const getPaymentAttemptStmt = db.prepare(
|
|
11910
|
+
"SELECT * FROM payment_attempts WHERE id = ?"
|
|
11911
|
+
);
|
|
11912
|
+
const getArchivedPaymentAttemptStmt = db.prepare(
|
|
11913
|
+
"SELECT * FROM payment_attempt_history WHERE id = ? ORDER BY seq DESC LIMIT 1"
|
|
11914
|
+
);
|
|
11915
|
+
const paymentAttemptByReplayKeyStmt = db.prepare(
|
|
11916
|
+
"SELECT * FROM payment_attempts WHERE replay_key = ?"
|
|
11917
|
+
);
|
|
11918
|
+
const resolvePaymentAttemptStmt = db.prepare(
|
|
11919
|
+
`UPDATE payment_attempts SET status = @status,
|
|
11920
|
+
rejection_reason = COALESCE(@rejection_reason, rejection_reason),
|
|
11921
|
+
external_reference = COALESCE(@external_reference, external_reference),
|
|
11922
|
+
resolution_json = @resolution_json, updated_at = @updated_at
|
|
11923
|
+
WHERE id = @id AND status = @expected_status AND resolution_json IS NULL`
|
|
10590
11924
|
);
|
|
10591
|
-
|
|
10592
|
-
(
|
|
10593
|
-
|
|
10594
|
-
|
|
11925
|
+
function refreshTransactionState(id, now) {
|
|
11926
|
+
const row = getTransactionStmt.get(id);
|
|
11927
|
+
if (row !== void 0) setTransactionStateStmt.run(rowToTransaction(row, now).state, id);
|
|
11928
|
+
}
|
|
11929
|
+
const reserve = db.transaction(
|
|
11930
|
+
(reservation, params) => {
|
|
11931
|
+
let row;
|
|
11932
|
+
if (reservation.reclaimRejected === true) {
|
|
11933
|
+
archiveRejectedAttemptStmt.run(params);
|
|
11934
|
+
row = reclaimPaymentAttemptStmt.get(params);
|
|
11935
|
+
}
|
|
11936
|
+
row ??= insertPaymentAttemptStmt.get({
|
|
11937
|
+
...params,
|
|
11938
|
+
status: "reserved",
|
|
11939
|
+
external_reference: null,
|
|
11940
|
+
rejection_reason: null
|
|
11941
|
+
});
|
|
11942
|
+
const txn = reservation.transaction;
|
|
11943
|
+
if (txn !== void 0) {
|
|
11944
|
+
const { reservationId, ...authorization } = txn.authorization ?? {};
|
|
11945
|
+
insertTransactionStmt.run({
|
|
11946
|
+
id: txn.id,
|
|
11947
|
+
request_id: reservation.requestId,
|
|
11948
|
+
resource_id: reservation.resourceId,
|
|
11949
|
+
protocol: txn.protocol,
|
|
11950
|
+
state: transactionState({ payment: { status: "reserved" } }, row.created_at),
|
|
11951
|
+
provider: reservation.provider,
|
|
11952
|
+
attempt_id: row.id,
|
|
11953
|
+
replay_key: reservation.replayKey,
|
|
11954
|
+
network: txn.network ?? null,
|
|
11955
|
+
asset: txn.asset ?? null,
|
|
11956
|
+
authorization_json: reservationId !== void 0 ? JSON.stringify(redact({ ...authorization, hold: "reserved" })) : null,
|
|
11957
|
+
reservation_id: reservationId ?? null,
|
|
11958
|
+
locator_json: txn.locator !== void 0 ? JSON.stringify(redact(txn.locator)) : null,
|
|
11959
|
+
expires_at: txn.expiresAt ?? null,
|
|
11960
|
+
input_digest: txn.inputDigest ?? null,
|
|
11961
|
+
config_digest: txn.configDigest,
|
|
11962
|
+
created_at: row.created_at
|
|
11963
|
+
});
|
|
11964
|
+
}
|
|
11965
|
+
return row;
|
|
11966
|
+
}
|
|
11967
|
+
);
|
|
11968
|
+
const updateAttempt = db.transaction((update, now) => {
|
|
11969
|
+
const { changes } = updatePaymentAttemptStmt.run({
|
|
11970
|
+
replay_key: update.replayKey,
|
|
11971
|
+
status: update.status,
|
|
11972
|
+
external_reference: update.externalReference ?? null,
|
|
11973
|
+
rejection_reason: update.rejectionReason ?? null,
|
|
11974
|
+
updated_at: now
|
|
11975
|
+
});
|
|
11976
|
+
for (const { id } of transactionsOfAttemptStmt.all(update.replayKey)) {
|
|
11977
|
+
refreshTransactionState(id, now);
|
|
11978
|
+
}
|
|
11979
|
+
return changes;
|
|
11980
|
+
});
|
|
11981
|
+
const recordStep = db.transaction((step) => {
|
|
11982
|
+
const base = { id: step.transactionId, at: step.at };
|
|
11983
|
+
let changes;
|
|
11984
|
+
switch (step.kind) {
|
|
11985
|
+
case "settling":
|
|
11986
|
+
changes = stepStmts.settling.run(base).changes;
|
|
11987
|
+
break;
|
|
11988
|
+
case "hold":
|
|
11989
|
+
changes = stepStmts.hold.run({ ...base, hold: step.hold }).changes;
|
|
11990
|
+
break;
|
|
11991
|
+
case "backend-dispatched":
|
|
11992
|
+
changes = stepStmts["backend-dispatched"].run({
|
|
11993
|
+
...base,
|
|
11994
|
+
deadline_at: step.deadlineAt
|
|
11995
|
+
}).changes;
|
|
11996
|
+
break;
|
|
11997
|
+
case "backend-result":
|
|
11998
|
+
changes = stepStmts["backend-result"].run({
|
|
11999
|
+
...base,
|
|
12000
|
+
status: step.status,
|
|
12001
|
+
error_code: step.errorCode ?? null
|
|
12002
|
+
}).changes;
|
|
12003
|
+
break;
|
|
12004
|
+
case "receipt":
|
|
12005
|
+
changes = stepStmts.receipt.run({ ...base, receipt_id: step.receiptId }).changes;
|
|
12006
|
+
break;
|
|
12007
|
+
case "completed":
|
|
12008
|
+
changes = stepStmts.completed.run({
|
|
12009
|
+
...base,
|
|
12010
|
+
persistence_failures_json: step.persistenceFailures !== void 0 && step.persistenceFailures.length > 0 ? JSON.stringify(step.persistenceFailures) : null
|
|
12011
|
+
}).changes;
|
|
12012
|
+
break;
|
|
12013
|
+
}
|
|
12014
|
+
if (changes > 0) refreshTransactionState(step.transactionId, step.at);
|
|
12015
|
+
return changes;
|
|
12016
|
+
});
|
|
12017
|
+
const resolveAttempt = db.transaction(
|
|
12018
|
+
(request, now) => {
|
|
12019
|
+
const { changes } = resolvePaymentAttemptStmt.run({
|
|
12020
|
+
id: request.attemptId,
|
|
12021
|
+
expected_status: request.expectedStatus,
|
|
12022
|
+
status: request.status,
|
|
12023
|
+
rejection_reason: request.rejectionReason ?? null,
|
|
12024
|
+
// An operator's reference is unverified; it stays in resolution_json only
|
|
12025
|
+
external_reference: request.resolution.method === "reconcile" ? request.resolution.externalReference ?? null : null,
|
|
12026
|
+
resolution_json: JSON.stringify(redact(request.resolution)),
|
|
12027
|
+
updated_at: now
|
|
12028
|
+
});
|
|
12029
|
+
if (changes === 0) return false;
|
|
12030
|
+
for (const { id } of transactionsOfAttemptIdStmt.all(request.attemptId)) {
|
|
12031
|
+
refreshTransactionState(id, now);
|
|
12032
|
+
}
|
|
12033
|
+
return true;
|
|
10595
12034
|
}
|
|
10596
12035
|
);
|
|
12036
|
+
const unresolvedTransactionsStmt = db.prepare(
|
|
12037
|
+
`${TRANSACTION_SELECT} WHERE t.state NOT IN (?, ?)`
|
|
12038
|
+
);
|
|
12039
|
+
const countOrphanHoldsStmt = db.prepare(
|
|
12040
|
+
`SELECT COUNT(*) AS count FROM authorization_holds h WHERE ${ORPHAN_HOLD_WHERE}`
|
|
12041
|
+
);
|
|
12042
|
+
const countUnresolvedKeysStmt = db.prepare(
|
|
12043
|
+
"SELECT COUNT(*) AS count FROM idempotency_keys WHERE state = 'unresolved'"
|
|
12044
|
+
);
|
|
12045
|
+
const countLiveTasksStmt = db.prepare(
|
|
12046
|
+
"SELECT COUNT(*) AS count FROM pending_tasks WHERE expires_at > ?"
|
|
12047
|
+
);
|
|
12048
|
+
const legacyImportsStmt = db.prepare(
|
|
12049
|
+
"SELECT source, path, rows, imported_at FROM legacy_imports WHERE path IS NOT NULL ORDER BY source"
|
|
12050
|
+
);
|
|
10597
12051
|
let closed = false;
|
|
12052
|
+
let releaseLegacyLocks;
|
|
10598
12053
|
const descriptor = {
|
|
10599
12054
|
name: "sqlite-receipt-store",
|
|
10600
12055
|
kind: "storage",
|
|
10601
12056
|
implementationVersion: PACKAGE_VERSION,
|
|
10602
12057
|
supportedSpec: `sqlite-schema-v${SCHEMA_VERSION2}`,
|
|
10603
|
-
capabilities: [
|
|
12058
|
+
capabilities: [
|
|
12059
|
+
"receipts",
|
|
12060
|
+
"events",
|
|
12061
|
+
"payment-attempts",
|
|
12062
|
+
"transactions",
|
|
12063
|
+
"idempotency-keys",
|
|
12064
|
+
"authorization-holds",
|
|
12065
|
+
"pending-tasks"
|
|
12066
|
+
],
|
|
10604
12067
|
status: "stable"
|
|
10605
12068
|
};
|
|
10606
12069
|
const store = {
|
|
@@ -10612,6 +12075,16 @@ function createSqliteReceiptStore(options) {
|
|
|
10612
12075
|
`Receipt store schema version mismatch (found ${version}, expected ${SCHEMA_VERSION2})`
|
|
10613
12076
|
);
|
|
10614
12077
|
}
|
|
12078
|
+
if (!db.readonly) sweepExpiredPendingTasks(db, clock.nowIso());
|
|
12079
|
+
if (options.legacyStores !== void 0 && releaseLegacyLocks === void 0) {
|
|
12080
|
+
releaseLegacyLocks = importLegacyStores(
|
|
12081
|
+
db,
|
|
12082
|
+
options.path,
|
|
12083
|
+
options.legacyStores,
|
|
12084
|
+
clock,
|
|
12085
|
+
logger
|
|
12086
|
+
);
|
|
12087
|
+
}
|
|
10615
12088
|
},
|
|
10616
12089
|
async appendEvent(event) {
|
|
10617
12090
|
try {
|
|
@@ -10640,17 +12113,12 @@ function createSqliteReceiptStore(options) {
|
|
|
10640
12113
|
payer: reservation.payer ?? null,
|
|
10641
12114
|
payee: reservation.payee ?? null,
|
|
10642
12115
|
created_at: now,
|
|
10643
|
-
updated_at: now
|
|
12116
|
+
updated_at: now,
|
|
12117
|
+
transaction_id: reservation.transaction?.id ?? null
|
|
10644
12118
|
};
|
|
10645
12119
|
let row;
|
|
10646
12120
|
try {
|
|
10647
|
-
row = (reservation
|
|
10648
|
-
insertPaymentAttemptStmt.get({
|
|
10649
|
-
...params,
|
|
10650
|
-
status: "reserved",
|
|
10651
|
-
external_reference: null,
|
|
10652
|
-
rejection_reason: null
|
|
10653
|
-
});
|
|
12121
|
+
row = reserve.immediate(reservation, params);
|
|
10654
12122
|
} catch (err) {
|
|
10655
12123
|
if (isUniqueConstraintOn(err, "payment_attempts.replay_key")) {
|
|
10656
12124
|
const existing = paymentAttemptStatusStmt.get(reservation.replayKey);
|
|
@@ -10670,14 +12138,23 @@ function createSqliteReceiptStore(options) {
|
|
|
10670
12138
|
},
|
|
10671
12139
|
async updatePaymentAttempt(update) {
|
|
10672
12140
|
try {
|
|
10673
|
-
|
|
10674
|
-
|
|
10675
|
-
|
|
10676
|
-
|
|
10677
|
-
|
|
10678
|
-
|
|
10679
|
-
|
|
10680
|
-
|
|
12141
|
+
if (updateAttempt(update, clock.nowIso()) === 0) {
|
|
12142
|
+
const existing = paymentAttemptStatusStmt.get(update.replayKey);
|
|
12143
|
+
if (existing?.resolution_json != null) {
|
|
12144
|
+
logger.warn(
|
|
12145
|
+
{
|
|
12146
|
+
attemptId: existing.id,
|
|
12147
|
+
resolvedStatus: existing.status,
|
|
12148
|
+
status: update.status,
|
|
12149
|
+
...update.externalReference !== void 0 ? { externalReference: update.externalReference } : {}
|
|
12150
|
+
},
|
|
12151
|
+
"receipt-store: payment attempt already resolved; update not applied"
|
|
12152
|
+
);
|
|
12153
|
+
throw new CommerceError(
|
|
12154
|
+
"STORAGE_ERROR",
|
|
12155
|
+
`Payment attempt ${existing.id} is already resolved; the update was not applied`
|
|
12156
|
+
);
|
|
12157
|
+
}
|
|
10681
12158
|
throw new CommerceError(
|
|
10682
12159
|
"STORAGE_ERROR",
|
|
10683
12160
|
`No payment attempt found for replayKey=${update.replayKey}`
|
|
@@ -10729,6 +12206,105 @@ function createSqliteReceiptStore(options) {
|
|
|
10729
12206
|
const rows = listOptions.requestId !== void 0 ? (uncertain ? listUncertainPaymentAttemptsByRequestStmt : listPaymentAttemptsByRequestStmt).all(listOptions.requestId, limit) : (uncertain ? listUncertainPaymentAttemptsStmt : listPaymentAttemptsStmt).all(limit);
|
|
10730
12207
|
return rows.map(rowToPaymentAttempt);
|
|
10731
12208
|
},
|
|
12209
|
+
async recordTransactionStep(step) {
|
|
12210
|
+
try {
|
|
12211
|
+
if (recordStep(step) === 0) {
|
|
12212
|
+
throw new CommerceError(
|
|
12213
|
+
"STORAGE_ERROR",
|
|
12214
|
+
step.kind === "hold" ? `No transaction with an authorization hold found for transactionId=${step.transactionId}` : `No transaction found for transactionId=${step.transactionId}`
|
|
12215
|
+
);
|
|
12216
|
+
}
|
|
12217
|
+
} catch (err) {
|
|
12218
|
+
throw toCommerceError(err, "STORAGE_ERROR", "Failed to record transaction step");
|
|
12219
|
+
}
|
|
12220
|
+
},
|
|
12221
|
+
async getTransaction(id) {
|
|
12222
|
+
const row = getTransactionStmt.get(id);
|
|
12223
|
+
return row !== void 0 ? rowToTransaction(row, clock.nowIso()) : void 0;
|
|
12224
|
+
},
|
|
12225
|
+
async listTransactions(listOptions = {}) {
|
|
12226
|
+
const { cursor, state, unresolved, pendingHold, requestId } = listOptions;
|
|
12227
|
+
if (cursor !== void 0 && !CURSOR_PATTERN.test(cursor)) {
|
|
12228
|
+
throw new CommerceError("INPUT_INVALID", "Malformed transaction list cursor");
|
|
12229
|
+
}
|
|
12230
|
+
const limit = clampListLimit(listOptions.limit);
|
|
12231
|
+
const where = [];
|
|
12232
|
+
const params = [];
|
|
12233
|
+
if (cursor !== void 0) {
|
|
12234
|
+
where.push("t.seq < ?");
|
|
12235
|
+
params.push(Number(cursor));
|
|
12236
|
+
}
|
|
12237
|
+
if (requestId !== void 0) {
|
|
12238
|
+
where.push("t.request_id = ?");
|
|
12239
|
+
params.push(requestId);
|
|
12240
|
+
}
|
|
12241
|
+
if (state !== void 0) {
|
|
12242
|
+
where.push(`(t.state = ? OR (${TIME_DEPENDENT}))`);
|
|
12243
|
+
params.push(state);
|
|
12244
|
+
}
|
|
12245
|
+
if (pendingHold === true) {
|
|
12246
|
+
where.push("json_extract(t.authorization_json, '$.hold') IN ('reserved', 'uncertain')");
|
|
12247
|
+
}
|
|
12248
|
+
if (unresolved === true) {
|
|
12249
|
+
where.push(`t.state NOT IN (${RESOLVED_STATES.map(() => "?").join(", ")})`);
|
|
12250
|
+
params.push(...RESOLVED_STATES);
|
|
12251
|
+
}
|
|
12252
|
+
const rows = db.prepare(
|
|
12253
|
+
`${TRANSACTION_SELECT}${where.length > 0 ? ` WHERE ${where.join(" AND ")}` : ""} ORDER BY t.seq DESC LIMIT ?`
|
|
12254
|
+
).all(...params, limit);
|
|
12255
|
+
const now = clock.nowIso();
|
|
12256
|
+
const resolved = RESOLVED_STATES;
|
|
12257
|
+
const transactions = rows.map((row) => rowToTransaction(row, now)).filter(
|
|
12258
|
+
(t) => (state === void 0 || t.state === state) && (unresolved !== true || !resolved.includes(t.state))
|
|
12259
|
+
);
|
|
12260
|
+
const last = rows.at(-1);
|
|
12261
|
+
return {
|
|
12262
|
+
transactions,
|
|
12263
|
+
...rows.length === limit && last !== void 0 ? { nextCursor: String(last.seq) } : {}
|
|
12264
|
+
};
|
|
12265
|
+
},
|
|
12266
|
+
async getPaymentAttempt(id) {
|
|
12267
|
+
const row = getPaymentAttemptStmt.get(id) ?? getArchivedPaymentAttemptStmt.get(id);
|
|
12268
|
+
return row !== void 0 ? rowToPaymentAttempt(row) : void 0;
|
|
12269
|
+
},
|
|
12270
|
+
async findPaymentAttemptByReplayKey(replayKey) {
|
|
12271
|
+
const row = paymentAttemptByReplayKeyStmt.get(replayKey);
|
|
12272
|
+
return row !== void 0 ? rowToPaymentAttempt(row) : void 0;
|
|
12273
|
+
},
|
|
12274
|
+
async resolvePaymentAttempt(request) {
|
|
12275
|
+
try {
|
|
12276
|
+
return resolveAttempt(request, clock.nowIso());
|
|
12277
|
+
} catch (err) {
|
|
12278
|
+
throw toCommerceError(err, "STORAGE_ERROR", "Failed to resolve payment attempt");
|
|
12279
|
+
}
|
|
12280
|
+
},
|
|
12281
|
+
...createIdempotencyMethods(db, clock),
|
|
12282
|
+
...createHoldMethods(db, clock),
|
|
12283
|
+
...createPendingTaskMethods(db, clock),
|
|
12284
|
+
// Reads all unresolved transactions at once. Page this query if large
|
|
12285
|
+
// journals make operator diagnostics too costly.
|
|
12286
|
+
async summary({ orphanHoldMinAgeMs }) {
|
|
12287
|
+
const now = clock.nowIso();
|
|
12288
|
+
const unresolvedTransactions = {};
|
|
12289
|
+
for (const row of unresolvedTransactionsStmt.all(...RESOLVED_STATES)) {
|
|
12290
|
+
const { state } = rowToTransaction(row, now);
|
|
12291
|
+
unresolvedTransactions[state] = (unresolvedTransactions[state] ?? 0) + 1;
|
|
12292
|
+
}
|
|
12293
|
+
const orphansBefore = new Date(Date.parse(now) - orphanHoldMinAgeMs).toISOString();
|
|
12294
|
+
return {
|
|
12295
|
+
unresolvedTransactions,
|
|
12296
|
+
orphanHolds: countOrphanHoldsStmt.get(orphansBefore)?.count ?? 0,
|
|
12297
|
+
unresolvedIdempotencyKeys: countUnresolvedKeysStmt.get()?.count ?? 0,
|
|
12298
|
+
unexpiredPendingTasks: countLiveTasksStmt.get(now)?.count ?? 0,
|
|
12299
|
+
legacyImports: legacyImportsStmt.all().map((row) => ({
|
|
12300
|
+
source: row.source,
|
|
12301
|
+
path: row.path,
|
|
12302
|
+
rows: row.rows,
|
|
12303
|
+
importedAt: row.imported_at
|
|
12304
|
+
})),
|
|
12305
|
+
missingLegacyImports: missingLegacyImports(db)
|
|
12306
|
+
};
|
|
12307
|
+
},
|
|
10732
12308
|
descriptor,
|
|
10733
12309
|
async health() {
|
|
10734
12310
|
const startedAt = clock.monotonicMs();
|
|
@@ -10787,6 +12363,7 @@ function createSqliteReceiptStore(options) {
|
|
|
10787
12363
|
async close() {
|
|
10788
12364
|
if (!closed) {
|
|
10789
12365
|
closed = true;
|
|
12366
|
+
releaseLegacyLocks?.();
|
|
10790
12367
|
db.close();
|
|
10791
12368
|
}
|
|
10792
12369
|
}
|