@devlab.group/agent-commerce 2.5.0 → 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 +63 -11
- package/dist/ap2.d.ts +19 -6
- package/dist/ap2.js +56 -18
- package/dist/ap2.js.map +1 -1
- package/dist/{chunk-FKQK5XZA.js → chunk-DRLBML7Z.js} +13 -11
- package/dist/chunk-DRLBML7Z.js.map +1 -0
- package/dist/{chunk-VUCMBGUR.js → chunk-G3EYYHKF.js} +3 -3
- package/dist/{chunk-VUCMBGUR.js.map → chunk-G3EYYHKF.js.map} +1 -1
- package/dist/{chunk-3OTCFFFT.js → chunk-M52FBNJX.js} +3 -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-4K7FIBJM.js → chunk-M6MQ3FYS.js} +3 -3
- package/dist/{chunk-4K7FIBJM.js.map → chunk-M6MQ3FYS.js.map} +1 -1
- package/dist/chunk-M6WW6QIT.js +18 -0
- package/dist/chunk-M6WW6QIT.js.map +1 -0
- package/dist/cli/{ap2-YAPLERSC.js → ap2-2YMYA2H6.js} +57 -20
- package/dist/cli/ap2-2YMYA2H6.js.map +1 -0
- package/dist/cli/{chunk-5R7DM5LM.js → chunk-3NOMLMJW.js} +26 -26
- package/dist/cli/chunk-3NOMLMJW.js.map +1 -0
- package/dist/cli/chunk-4KLYFXMW.js +8 -0
- package/dist/cli/{chunk-M7NXVRU5.js.map → chunk-4KLYFXMW.js.map} +1 -1
- package/dist/cli/chunk-6R6WJ4FD.js +18 -0
- package/dist/cli/chunk-6R6WJ4FD.js.map +1 -0
- package/dist/cli/{chunk-2J2IQQ4X.js → chunk-AZL7RPFU.js} +37 -32
- package/dist/cli/chunk-AZL7RPFU.js.map +1 -0
- package/dist/cli/{chunk-JFVRG2HH.js → chunk-DHFMIBPG.js} +7 -7
- package/dist/cli/chunk-DHFMIBPG.js.map +1 -0
- package/dist/cli/{chunk-IDY2735M.js → chunk-GET3CZGR.js} +2 -2
- package/dist/cli/chunk-GET3CZGR.js.map +1 -0
- package/dist/cli/{chunk-QLUCNPRT.js → chunk-NSYSMDQN.js} +831 -169
- package/dist/cli/chunk-NSYSMDQN.js.map +1 -0
- package/dist/cli/{chunk-Z34UMZBB.js → chunk-PTL7SNOI.js} +83 -57
- package/dist/cli/chunk-PTL7SNOI.js.map +1 -0
- package/dist/cli/{chunk-2UPPX3FJ.js → chunk-TFV3K6YS.js} +75 -13
- package/dist/cli/chunk-TFV3K6YS.js.map +1 -0
- package/dist/cli/{chunk-NIU5EMSB.js → chunk-VJH6RYRK.js} +5 -5
- package/dist/cli/{chunk-NIU5EMSB.js.map → chunk-VJH6RYRK.js.map} +1 -1
- package/dist/cli/{chunk-QA2OPHBF.js → chunk-YOF7IK4V.js} +14 -13
- package/dist/cli/chunk-YOF7IK4V.js.map +1 -0
- package/dist/cli/{chunk-4H2QLHQI.js → chunk-YWG2ZN3L.js} +3 -3
- package/dist/cli/{chunk-4H2QLHQI.js.map → chunk-YWG2ZN3L.js.map} +1 -1
- package/dist/cli/config-3K65QJ22.js +12 -0
- package/dist/cli/{config-BWFMN2ZB.js.map → config-3K65QJ22.js.map} +1 -1
- package/dist/cli/index.js +524 -230
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/{mcp-KZEMXLHR.js → mcp-6F64A7KE.js} +4 -4
- package/dist/cli/{mcp-KZEMXLHR.js.map → mcp-6F64A7KE.js.map} +1 -1
- package/dist/cli/payment-providers-2ITS6KNR.js +6 -0
- package/dist/cli/{payment-providers-SZL36H3Y.js.map → payment-providers-2ITS6KNR.js.map} +1 -1
- package/dist/cli/{provider-6TKB5ADJ.js → provider-5BGG5YKQ.js} +34 -16
- package/dist/cli/provider-5BGG5YKQ.js.map +1 -0
- package/dist/cli/receipts-I4IIE7U6.js +8 -0
- package/dist/cli/{receipts-ZGLJWMQG.js.map → receipts-I4IIE7U6.js.map} +1 -1
- package/dist/cli/reconcile-55WNCSFC.js +4 -0
- package/dist/cli/{reconcile-IC22MJD5.js.map → reconcile-55WNCSFC.js.map} +1 -1
- package/dist/cli/{run-ZTYPQI4D.js → run-2P6ZGFUE.js} +220 -73
- package/dist/cli/run-2P6ZGFUE.js.map +1 -0
- package/dist/cli/{x402-WLYBLODI.js → x402-4LPIIELI.js} +8 -8
- package/dist/cli/{x402-WLYBLODI.js.map → x402-4LPIIELI.js.map} +1 -1
- package/dist/index.d.ts +104 -201
- package/dist/index.js +1048 -262
- package/dist/index.js.map +1 -1
- package/dist/logger-CllGwQ8i.d.ts +19 -0
- package/dist/mcp.d.ts +3 -1
- package/dist/mcp.js +2 -1
- package/dist/mcp.js.map +1 -1
- package/dist/mpp.d.ts +2 -1
- package/dist/mpp.js +31 -12
- package/dist/mpp.js.map +1 -1
- package/dist/{protocol-adapter-DEXpdp8m.d.ts → protocol-adapter-1WbtM3xG.d.ts} +5 -132
- package/dist/{runtime-Dz2fSO-P.d.ts → runtime-B-kARa2f.d.ts} +5 -20
- package/dist/store-kIIMpUA-.d.ts +372 -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 +5 -4
- package/dist/x402.js.map +1 -1
- package/package.json +5 -1
- package/dist/chunk-3OTCFFFT.js.map +0 -1
- package/dist/chunk-FKQK5XZA.js.map +0 -1
- package/dist/cli/ap2-YAPLERSC.js.map +0 -1
- package/dist/cli/chunk-2J2IQQ4X.js.map +0 -1
- package/dist/cli/chunk-2UPPX3FJ.js.map +0 -1
- package/dist/cli/chunk-5R7DM5LM.js.map +0 -1
- package/dist/cli/chunk-IDY2735M.js.map +0 -1
- package/dist/cli/chunk-JFVRG2HH.js.map +0 -1
- package/dist/cli/chunk-M7NXVRU5.js +0 -8
- package/dist/cli/chunk-QA2OPHBF.js.map +0 -1
- package/dist/cli/chunk-QLUCNPRT.js.map +0 -1
- package/dist/cli/chunk-Z34UMZBB.js.map +0 -1
- package/dist/cli/config-BWFMN2ZB.js +0 -12
- package/dist/cli/payment-providers-SZL36H3Y.js +0 -6
- package/dist/cli/provider-6TKB5ADJ.js.map +0 -1
- package/dist/cli/receipts-ZGLJWMQG.js +0 -8
- package/dist/cli/reconcile-IC22MJD5.js +0 -4
- package/dist/cli/run-ZTYPQI4D.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,13 +1,16 @@
|
|
|
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, resolveDeploymentMode, requireX402Network, resolveX402Option, isEvmAddress, isEvmZeroAddress, SETTLE_AFTER_BACKEND_METADATA_KEY, x402OfferName, REUSE_REJECTED_AUTHORIZATION_METADATA_KEY, canonicalJson } from './chunk-
|
|
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';
|
|
13
16
|
import { randomUUID, createHash } from 'crypto';
|
|
@@ -18,6 +21,7 @@ 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();
|
|
@@ -1739,10 +1749,12 @@ function retryChallenge(requirement, reason) {
|
|
|
1739
1749
|
};
|
|
1740
1750
|
}
|
|
1741
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
|
+
}
|
|
1742
1755
|
function replayError(error, requirement) {
|
|
1743
1756
|
if (error.code !== "PAYMENT_REPLAYED") return error;
|
|
1744
|
-
const
|
|
1745
|
-
const finished = typeof status === "string" && FINISHED_ATTEMPT_STATUSES.has(status);
|
|
1757
|
+
const finished = isFinishedAttempt(error.details?.["attemptStatus"]);
|
|
1746
1758
|
const network = requirement.network;
|
|
1747
1759
|
if (!finished && network === void 0) return error;
|
|
1748
1760
|
return new CommerceError("PAYMENT_REPLAYED", error.message, {
|
|
@@ -1852,6 +1864,7 @@ function createPaymentAdmission(ctx, authorizeAndReserve) {
|
|
|
1852
1864
|
throw mapped;
|
|
1853
1865
|
}
|
|
1854
1866
|
if (verification.status !== "verified") {
|
|
1867
|
+
const refusal = await refusalFor(verification, requirement, request, resource);
|
|
1855
1868
|
await safeEmit(
|
|
1856
1869
|
buildEvent(flow, {
|
|
1857
1870
|
type: "payment.rejected",
|
|
@@ -1859,18 +1872,10 @@ function createPaymentAdmission(ctx, authorizeAndReserve) {
|
|
|
1859
1872
|
adapter: request.protocol,
|
|
1860
1873
|
paymentProvider: provider.name,
|
|
1861
1874
|
status: "error",
|
|
1862
|
-
data: verification.rejectionReason ? { reason: verification.rejectionReason } : {}
|
|
1875
|
+
data: refusal.code !== "PAYMENT_INVALID" ? { reason: refusal.code } : verification.rejectionReason ? { reason: verification.rejectionReason } : {}
|
|
1863
1876
|
})
|
|
1864
1877
|
);
|
|
1865
|
-
throw
|
|
1866
|
-
"PAYMENT_INVALID",
|
|
1867
|
-
verification.rejectionReason ?? "Payment was rejected",
|
|
1868
|
-
{
|
|
1869
|
-
requestId: request.requestId,
|
|
1870
|
-
resourceId: resource.id,
|
|
1871
|
-
...retryChallenge(requirement, verification.rejectionReason)
|
|
1872
|
-
}
|
|
1873
|
-
);
|
|
1878
|
+
throw refusal;
|
|
1874
1879
|
}
|
|
1875
1880
|
if (!verification.replayKey) {
|
|
1876
1881
|
await safeEmit(
|
|
@@ -1961,6 +1966,37 @@ function createPaymentAdmission(ctx, authorizeAndReserve) {
|
|
|
1961
1966
|
}
|
|
1962
1967
|
};
|
|
1963
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
|
+
}
|
|
1964
2000
|
}
|
|
1965
2001
|
function pickProvider(providers, methods) {
|
|
1966
2002
|
for (const method of methods) {
|
|
@@ -3061,9 +3097,7 @@ function normalize(raw) {
|
|
|
3061
3097
|
const x402 = x402Settings?.config;
|
|
3062
3098
|
const mpp = normalizeMpp(raw.payments.mpp);
|
|
3063
3099
|
const ap2 = normalizeAp2(raw.authorization?.ap2);
|
|
3064
|
-
|
|
3065
|
-
validateReplayStoreIsolated(ap2.replay.path, raw.storage.receipts.path, protocols.acp);
|
|
3066
|
-
}
|
|
3100
|
+
validateLegacyStoresIsolated(ap2, protocols.acp, raw.storage.receipts.path);
|
|
3067
3101
|
const resources = Object.entries(raw.resources).map(
|
|
3068
3102
|
([id, entry]) => normalizeResource(id, entry, protocols, x402Settings, mpp, ap2)
|
|
3069
3103
|
);
|
|
@@ -4542,8 +4576,14 @@ async function createGateway(options) {
|
|
|
4542
4576
|
return { url };
|
|
4543
4577
|
},
|
|
4544
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
|
+
}
|
|
4545
4586
|
await stopAdapters(adapterRuntimes, logger);
|
|
4546
|
-
await server.close();
|
|
4547
4587
|
},
|
|
4548
4588
|
server
|
|
4549
4589
|
};
|
|
@@ -4719,7 +4759,7 @@ function assertNoContinuation(params) {
|
|
|
4719
4759
|
const message = params.message;
|
|
4720
4760
|
if (params.taskId !== void 0 || message.taskId !== void 0) {
|
|
4721
4761
|
throw unsupported(
|
|
4722
|
-
"Task not found:
|
|
4762
|
+
"Task not found: only a task waiting for payment can be continued, so send a request with no taskId.",
|
|
4723
4763
|
A2A_ERROR_TASK_NOT_FOUND
|
|
4724
4764
|
);
|
|
4725
4765
|
}
|
|
@@ -4819,6 +4859,11 @@ function requestsX402Extension(header2) {
|
|
|
4819
4859
|
(value) => value.split(",").some((uri) => uri.trim() === A2A_X402_EXTENSION_URI)
|
|
4820
4860
|
);
|
|
4821
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
|
+
}
|
|
4822
4867
|
function createPendingPayments(clock, maxEntries = MAX_PENDING_PAYMENTS) {
|
|
4823
4868
|
const tasks = /* @__PURE__ */ new Map();
|
|
4824
4869
|
const now = () => clock.now().getTime();
|
|
@@ -4828,28 +4873,27 @@ function createPendingPayments(clock, maxEntries = MAX_PENDING_PAYMENTS) {
|
|
|
4828
4873
|
if (pending.expiresAtMs <= at) tasks.delete(taskId);
|
|
4829
4874
|
}
|
|
4830
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
|
+
}
|
|
4831
4885
|
return {
|
|
4832
|
-
/** Holds a purchase until `expiresAt`; returns false, holding nothing, when full */
|
|
4833
4886
|
put(taskId, pending, expiresAt) {
|
|
4834
4887
|
purgeExpired();
|
|
4835
4888
|
if (tasks.size >= maxEntries) return false;
|
|
4836
|
-
|
|
4837
|
-
const ttl = Number.isFinite(requested) ? requested - now() : DEFAULT_PENDING_TTL_MS;
|
|
4838
|
-
const expiresAtMs = now() + Math.min(Math.max(ttl, 0), MAX_PENDING_TTL_MS);
|
|
4839
|
-
tasks.set(taskId, { ...pending, expiresAtMs });
|
|
4889
|
+
tasks.set(taskId, { ...pending, expiresAtMs: expiryMs(now(), expiresAt) });
|
|
4840
4890
|
return true;
|
|
4841
4891
|
},
|
|
4842
|
-
get
|
|
4843
|
-
|
|
4844
|
-
|
|
4845
|
-
if (pending.expiresAtMs <= now()) {
|
|
4846
|
-
tasks.delete(taskId);
|
|
4847
|
-
return void 0;
|
|
4848
|
-
}
|
|
4849
|
-
return pending;
|
|
4850
|
-
},
|
|
4851
|
-
delete(taskId) {
|
|
4892
|
+
get,
|
|
4893
|
+
take(taskId) {
|
|
4894
|
+
const pending = get(taskId);
|
|
4852
4895
|
tasks.delete(taskId);
|
|
4896
|
+
return pending;
|
|
4853
4897
|
},
|
|
4854
4898
|
size() {
|
|
4855
4899
|
return tasks.size;
|
|
@@ -4859,6 +4903,73 @@ function createPendingPayments(clock, maxEntries = MAX_PENDING_PAYMENTS) {
|
|
|
4859
4903
|
}
|
|
4860
4904
|
};
|
|
4861
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
|
+
}
|
|
4862
4973
|
function readPaymentSubmission(message) {
|
|
4863
4974
|
const metadata = isRecord(message) ? message["metadata"] : void 0;
|
|
4864
4975
|
if (!isRecord(metadata)) return void 0;
|
|
@@ -5048,8 +5159,8 @@ var A2A_UNSUPPORTED = [
|
|
|
5048
5159
|
"authenticated extended agent cards",
|
|
5049
5160
|
"A2A authentication schemes",
|
|
5050
5161
|
"artifact types beyond Agent Commerce outcome data",
|
|
5051
|
-
//
|
|
5052
|
-
"x402 extension payments across gateway
|
|
5162
|
+
// Instances with separate receipt stores cannot resume each other's tasks
|
|
5163
|
+
"x402 extension payments across gateway instances"
|
|
5053
5164
|
];
|
|
5054
5165
|
function buildDescriptor(implementationVersion) {
|
|
5055
5166
|
return {
|
|
@@ -5138,7 +5249,7 @@ async function resumePayment(context, pendingPayments, id, params) {
|
|
|
5138
5249
|
const message = isRecord(params) ? params["message"] : void 0;
|
|
5139
5250
|
const taskId = isRecord(message) ? message["taskId"] : void 0;
|
|
5140
5251
|
if (context === void 0 || typeof taskId !== "string") return void 0;
|
|
5141
|
-
const pending = pendingPayments?.get(taskId);
|
|
5252
|
+
const pending = await pendingPayments?.get(taskId);
|
|
5142
5253
|
if (pending === void 0) return void 0;
|
|
5143
5254
|
const messageId = isRecord(message) ? message["messageId"] : void 0;
|
|
5144
5255
|
if (typeof messageId !== "string" || messageId.length === 0) {
|
|
@@ -5158,19 +5269,21 @@ async function resumePayment(context, pendingPayments, id, params) {
|
|
|
5158
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".`
|
|
5159
5270
|
);
|
|
5160
5271
|
}
|
|
5161
|
-
let
|
|
5162
|
-
if (authorization === void 0 && submission.kind === "submitted") {
|
|
5272
|
+
let followUp;
|
|
5273
|
+
if (pending.authorization === void 0 && submission.kind === "submitted") {
|
|
5163
5274
|
try {
|
|
5164
|
-
|
|
5275
|
+
followUp = readFollowUpAuthorization(message);
|
|
5165
5276
|
} catch (err) {
|
|
5166
5277
|
return jsonRpcError(id, JSONRPC_INVALID_PARAMS, toCommerceError(err).message);
|
|
5167
5278
|
}
|
|
5168
5279
|
}
|
|
5169
|
-
pendingPayments?.
|
|
5280
|
+
const taken = await pendingPayments?.take(taskId);
|
|
5281
|
+
if (taken === void 0) return void 0;
|
|
5282
|
+
const authorization = taken.authorization ?? followUp;
|
|
5170
5283
|
const statusMessageId = context.ids.next("a2a-msg");
|
|
5171
5284
|
const identity = {
|
|
5172
5285
|
taskId,
|
|
5173
|
-
contextId:
|
|
5286
|
+
contextId: taken.contextId,
|
|
5174
5287
|
artifactId: context.ids.next("a2a-artifact"),
|
|
5175
5288
|
statusMessageId,
|
|
5176
5289
|
timestamp: context.clock.nowIso()
|
|
@@ -5178,7 +5291,7 @@ async function resumePayment(context, pendingPayments, id, params) {
|
|
|
5178
5291
|
if (submission.kind === "rejected") {
|
|
5179
5292
|
const declined = {
|
|
5180
5293
|
id: taskId,
|
|
5181
|
-
contextId:
|
|
5294
|
+
contextId: taken.contextId,
|
|
5182
5295
|
status: { state: A2A_TASK_STATE_FAILED, timestamp: identity.timestamp },
|
|
5183
5296
|
artifacts: []
|
|
5184
5297
|
};
|
|
@@ -5196,7 +5309,7 @@ async function resumePayment(context, pendingPayments, id, params) {
|
|
|
5196
5309
|
id,
|
|
5197
5310
|
await payPending(
|
|
5198
5311
|
context,
|
|
5199
|
-
{ ...
|
|
5312
|
+
{ ...taken, ...authorization !== void 0 ? { authorization } : {} },
|
|
5200
5313
|
submission.payload,
|
|
5201
5314
|
identity
|
|
5202
5315
|
)
|
|
@@ -5260,6 +5373,7 @@ var A2aProtocolAdapter = class {
|
|
|
5260
5373
|
agentName;
|
|
5261
5374
|
agentDescription;
|
|
5262
5375
|
agentVersion;
|
|
5376
|
+
store;
|
|
5263
5377
|
context;
|
|
5264
5378
|
started = false;
|
|
5265
5379
|
// The card lists only a2a-exposed resources, but a caller can name any id,
|
|
@@ -5277,6 +5391,7 @@ var A2aProtocolAdapter = class {
|
|
|
5277
5391
|
this.agentName = options.agentName ?? A2A_DEFAULT_AGENT_NAME;
|
|
5278
5392
|
this.agentDescription = options.agentDescription ?? DEFAULT_AGENT_DESCRIPTION;
|
|
5279
5393
|
this.agentVersion = options.agentVersion ?? PACKAGE_VERSION;
|
|
5394
|
+
this.store = options.store;
|
|
5280
5395
|
this.descriptor = buildDescriptor(PACKAGE_VERSION);
|
|
5281
5396
|
this.additionalHttpRoutes = [
|
|
5282
5397
|
{
|
|
@@ -5308,7 +5423,7 @@ var A2aProtocolAdapter = class {
|
|
|
5308
5423
|
mountPath: this.mountPath,
|
|
5309
5424
|
resources
|
|
5310
5425
|
});
|
|
5311
|
-
this.pendingPayments = createPendingPayments(context.clock);
|
|
5426
|
+
this.pendingPayments = hasMethodGroup(this.store, "pending_tasks") ? createStoredPendingPayments(this.store, context.clock) : createPendingPayments(context.clock);
|
|
5312
5427
|
this.cardBody = JSON.stringify(this.card);
|
|
5313
5428
|
this.cardEtag = `"${createHash("sha256").update(this.cardBody).digest("base64url")}"`;
|
|
5314
5429
|
this.started = true;
|
|
@@ -5509,7 +5624,7 @@ var A2aProtocolAdapter = class {
|
|
|
5509
5624
|
return taskResult(id, task2);
|
|
5510
5625
|
}
|
|
5511
5626
|
const network = outcome.requirement.network;
|
|
5512
|
-
const held = this.pendingPayments?.put(
|
|
5627
|
+
const held = await this.pendingPayments?.put(
|
|
5513
5628
|
identity.taskId,
|
|
5514
5629
|
{
|
|
5515
5630
|
contextId: identity.contextId,
|
|
@@ -5821,23 +5936,22 @@ function createAcpIdempotencyStore(options) {
|
|
|
5821
5936
|
};
|
|
5822
5937
|
}
|
|
5823
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;
|
|
5824
5944
|
if (release) {
|
|
5825
|
-
const { changes: changes2 } = db.prepare("DELETE FROM acp_idempotency WHERE state = 'in_flight'").run();
|
|
5826
|
-
if (changes2 > 0) {
|
|
5827
|
-
logger.warn(
|
|
5828
|
-
{ released: changes2 },
|
|
5829
|
-
"acp idempotency: freed claims left in flight by an earlier process; merchant deduplication is enabled"
|
|
5830
|
-
);
|
|
5831
|
-
}
|
|
5832
|
-
return;
|
|
5833
|
-
}
|
|
5834
|
-
const { changes } = db.prepare("UPDATE acp_idempotency SET state = 'unresolved' WHERE state = 'in_flight'").run();
|
|
5835
|
-
if (changes > 0) {
|
|
5836
5945
|
logger.warn(
|
|
5837
|
-
{
|
|
5838
|
-
"acp idempotency:
|
|
5946
|
+
{ released: count },
|
|
5947
|
+
"acp idempotency: freed claims left in flight by an earlier process; merchant deduplication is enabled"
|
|
5839
5948
|
);
|
|
5949
|
+
return;
|
|
5840
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
|
+
);
|
|
5841
5955
|
}
|
|
5842
5956
|
function migrate(db, logger) {
|
|
5843
5957
|
const current = db.pragma("user_version", { simple: true });
|
|
@@ -10392,6 +10506,27 @@ function reachedFor(error) {
|
|
|
10392
10506
|
function notReached(failure) {
|
|
10393
10507
|
return { response: asResponse(failure), reached: "no" };
|
|
10394
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
|
+
}
|
|
10395
10530
|
var AcpProtocolAdapter = class {
|
|
10396
10531
|
name = "acp";
|
|
10397
10532
|
mountPath;
|
|
@@ -10406,7 +10541,10 @@ var AcpProtocolAdapter = class {
|
|
|
10406
10541
|
*/
|
|
10407
10542
|
deployment;
|
|
10408
10543
|
discoveryMetadata;
|
|
10544
|
+
store;
|
|
10409
10545
|
idempotency;
|
|
10546
|
+
// Track the file opened by this adapter so borrowed receipt stores stay open
|
|
10547
|
+
fileStore;
|
|
10410
10548
|
resources = /* @__PURE__ */ new Map();
|
|
10411
10549
|
context;
|
|
10412
10550
|
started = false;
|
|
@@ -10418,6 +10556,7 @@ var AcpProtocolAdapter = class {
|
|
|
10418
10556
|
this.isAuthorized = createBearerCheck(options.token);
|
|
10419
10557
|
this.operations = options.operations;
|
|
10420
10558
|
this.idempotencyOptions = options.idempotency;
|
|
10559
|
+
this.store = options.store;
|
|
10421
10560
|
this.discoveryMetadata = options.discovery;
|
|
10422
10561
|
this.descriptor = buildDescriptor2(PACKAGE_VERSION);
|
|
10423
10562
|
this.additionalHttpRoutes = [
|
|
@@ -10462,12 +10601,7 @@ var AcpProtocolAdapter = class {
|
|
|
10462
10601
|
}
|
|
10463
10602
|
this.resources = resolved;
|
|
10464
10603
|
this.deployment = context.publicBaseUrl;
|
|
10465
|
-
this.idempotency =
|
|
10466
|
-
path: this.idempotencyOptions.path,
|
|
10467
|
-
retentionHours: this.idempotencyOptions.retentionHours,
|
|
10468
|
-
releaseOrphans: this.idempotencyOptions.merchantIdempotent === true,
|
|
10469
|
-
logger: context.logger
|
|
10470
|
-
});
|
|
10604
|
+
this.idempotency = await this.openIdempotency(context);
|
|
10471
10605
|
this.discovery = document;
|
|
10472
10606
|
this.started = true;
|
|
10473
10607
|
context.logger.info(
|
|
@@ -10479,6 +10613,32 @@ var AcpProtocolAdapter = class {
|
|
|
10479
10613
|
"acp adapter started"
|
|
10480
10614
|
);
|
|
10481
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
|
+
}
|
|
10482
10642
|
/** `GET /.well-known/acp.json`: public, unauthenticated, cacheable */
|
|
10483
10643
|
async handleDiscovery(req, res) {
|
|
10484
10644
|
try {
|
|
@@ -10556,7 +10716,7 @@ var AcpProtocolAdapter = class {
|
|
|
10556
10716
|
return (await this.runCheckout(request)).response;
|
|
10557
10717
|
}
|
|
10558
10718
|
const scope = { deployment, endpoint: request.route.path, key };
|
|
10559
|
-
const claim = store.claim(scope, requestFingerprint(request.body));
|
|
10719
|
+
const claim = await store.claim(scope, requestFingerprint(request.body));
|
|
10560
10720
|
switch (claim.kind) {
|
|
10561
10721
|
case "in-flight":
|
|
10562
10722
|
return {
|
|
@@ -10595,15 +10755,15 @@ var AcpProtocolAdapter = class {
|
|
|
10595
10755
|
try {
|
|
10596
10756
|
outcome = await this.runCheckout(request, operationKey(scope));
|
|
10597
10757
|
} catch (err) {
|
|
10598
|
-
store.markUnresolved(scope);
|
|
10758
|
+
await store.markUnresolved(scope);
|
|
10599
10759
|
throw err;
|
|
10600
10760
|
}
|
|
10601
10761
|
if (outcome.response.status < 500) {
|
|
10602
|
-
store.complete(scope, outcome.response);
|
|
10762
|
+
await store.complete(scope, outcome.response);
|
|
10603
10763
|
} else if (outcome.reached === "no" || this.idempotencyOptions.merchantIdempotent === true) {
|
|
10604
|
-
store.release(scope);
|
|
10764
|
+
await store.release(scope);
|
|
10605
10765
|
} else {
|
|
10606
|
-
store.markUnresolved(scope);
|
|
10766
|
+
await store.markUnresolved(scope);
|
|
10607
10767
|
}
|
|
10608
10768
|
return outcome.response;
|
|
10609
10769
|
}
|
|
@@ -10703,7 +10863,8 @@ var AcpProtocolAdapter = class {
|
|
|
10703
10863
|
this.started = false;
|
|
10704
10864
|
this.discovery = void 0;
|
|
10705
10865
|
this.resources = /* @__PURE__ */ new Map();
|
|
10706
|
-
this.
|
|
10866
|
+
this.fileStore?.close();
|
|
10867
|
+
this.fileStore = void 0;
|
|
10707
10868
|
this.idempotency = void 0;
|
|
10708
10869
|
this.deployment = void 0;
|
|
10709
10870
|
this.context = void 0;
|
|
@@ -10713,167 +10874,6 @@ function createAcpAdapter(options) {
|
|
|
10713
10874
|
return new AcpProtocolAdapter(options);
|
|
10714
10875
|
}
|
|
10715
10876
|
|
|
10716
|
-
// src/storage/receipts/redact.ts
|
|
10717
|
-
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;
|
|
10718
|
-
var REDACTED = "[REDACTED]";
|
|
10719
|
-
function isSecretKey(key) {
|
|
10720
|
-
return SECRET_KEY_PATTERN.test(key);
|
|
10721
|
-
}
|
|
10722
|
-
function redact(value) {
|
|
10723
|
-
return redactValue(value);
|
|
10724
|
-
}
|
|
10725
|
-
function redactValue(value) {
|
|
10726
|
-
if (Array.isArray(value)) {
|
|
10727
|
-
return value.map(redactValue);
|
|
10728
|
-
}
|
|
10729
|
-
if (value !== null && typeof value === "object") {
|
|
10730
|
-
const out = {};
|
|
10731
|
-
for (const [key, inner] of Object.entries(value)) {
|
|
10732
|
-
out[key] = isSecretKey(key) ? REDACTED : redactValue(inner);
|
|
10733
|
-
}
|
|
10734
|
-
return out;
|
|
10735
|
-
}
|
|
10736
|
-
return value;
|
|
10737
|
-
}
|
|
10738
|
-
|
|
10739
|
-
// src/storage/receipts/rows.ts
|
|
10740
|
-
function receiptToRow(receipt) {
|
|
10741
|
-
return {
|
|
10742
|
-
id: receipt.id,
|
|
10743
|
-
request_id: receipt.requestId,
|
|
10744
|
-
resource_id: receipt.resourceId,
|
|
10745
|
-
payment_json: receipt.payment !== void 0 ? JSON.stringify(redact(receipt.payment)) : null,
|
|
10746
|
-
delivered_at: receipt.deliveredAt,
|
|
10747
|
-
backend_status: receipt.backendStatus,
|
|
10748
|
-
duration_ms: receipt.durationMs ?? null,
|
|
10749
|
-
protocol: receipt.protocol ?? null,
|
|
10750
|
-
metadata_json: receipt.metadata !== void 0 ? JSON.stringify(redact(receipt.metadata)) : null,
|
|
10751
|
-
authorization_json: receipt.authorization !== void 0 ? JSON.stringify(redact(receipt.authorization)) : null,
|
|
10752
|
-
transaction_id: receipt.transactionId ?? null
|
|
10753
|
-
};
|
|
10754
|
-
}
|
|
10755
|
-
function rowToReceipt(row) {
|
|
10756
|
-
const payment = row.payment_json !== null ? JSON.parse(row.payment_json) : void 0;
|
|
10757
|
-
const metadata = row.metadata_json !== null ? JSON.parse(row.metadata_json) : void 0;
|
|
10758
|
-
const authorization = row.authorization_json !== null ? JSON.parse(row.authorization_json) : void 0;
|
|
10759
|
-
return {
|
|
10760
|
-
id: row.id,
|
|
10761
|
-
requestId: row.request_id,
|
|
10762
|
-
resourceId: row.resource_id,
|
|
10763
|
-
deliveredAt: row.delivered_at,
|
|
10764
|
-
backendStatus: row.backend_status,
|
|
10765
|
-
...payment !== void 0 ? { payment } : {},
|
|
10766
|
-
...row.duration_ms !== null ? { durationMs: row.duration_ms } : {},
|
|
10767
|
-
...row.protocol !== null ? { protocol: row.protocol } : {},
|
|
10768
|
-
...metadata !== void 0 ? { metadata } : {},
|
|
10769
|
-
...authorization !== void 0 ? { authorization } : {},
|
|
10770
|
-
...row.transaction_id !== null ? { transactionId: row.transaction_id } : {}
|
|
10771
|
-
};
|
|
10772
|
-
}
|
|
10773
|
-
function eventToRow(event) {
|
|
10774
|
-
return {
|
|
10775
|
-
id: event.id,
|
|
10776
|
-
type: event.type,
|
|
10777
|
-
request_id: event.requestId,
|
|
10778
|
-
resource_id: event.resourceId ?? null,
|
|
10779
|
-
at: event.at,
|
|
10780
|
-
adapter: event.adapter ?? null,
|
|
10781
|
-
payment_provider: event.paymentProvider ?? null,
|
|
10782
|
-
duration_ms: event.durationMs ?? null,
|
|
10783
|
-
status: event.status ?? null,
|
|
10784
|
-
data_json: event.data !== void 0 ? JSON.stringify(redact(event.data)) : null,
|
|
10785
|
-
transaction_id: event.transactionId ?? null
|
|
10786
|
-
};
|
|
10787
|
-
}
|
|
10788
|
-
function rowToEvent(row) {
|
|
10789
|
-
const data = row.data_json !== null ? JSON.parse(row.data_json) : void 0;
|
|
10790
|
-
return {
|
|
10791
|
-
id: row.id,
|
|
10792
|
-
type: row.type,
|
|
10793
|
-
requestId: row.request_id,
|
|
10794
|
-
at: row.at,
|
|
10795
|
-
...row.resource_id !== null ? { resourceId: row.resource_id } : {},
|
|
10796
|
-
...row.adapter !== null ? { adapter: row.adapter } : {},
|
|
10797
|
-
...row.payment_provider !== null ? { paymentProvider: row.payment_provider } : {},
|
|
10798
|
-
...row.duration_ms !== null ? { durationMs: row.duration_ms } : {},
|
|
10799
|
-
...row.status !== null ? { status: row.status } : {},
|
|
10800
|
-
...data !== void 0 ? { data } : {},
|
|
10801
|
-
...row.transaction_id !== null ? { transactionId: row.transaction_id } : {}
|
|
10802
|
-
};
|
|
10803
|
-
}
|
|
10804
|
-
function rowToPaymentAttempt(row) {
|
|
10805
|
-
return {
|
|
10806
|
-
id: row.id,
|
|
10807
|
-
requestId: row.request_id,
|
|
10808
|
-
resourceId: row.resource_id,
|
|
10809
|
-
provider: row.provider,
|
|
10810
|
-
replayKey: row.replay_key,
|
|
10811
|
-
status: row.status,
|
|
10812
|
-
amount: row.amount,
|
|
10813
|
-
currency: row.currency,
|
|
10814
|
-
...row.payer !== null ? { payer: row.payer } : {},
|
|
10815
|
-
...row.payee !== null ? { payee: row.payee } : {},
|
|
10816
|
-
...row.external_reference !== null ? { externalReference: row.external_reference } : {},
|
|
10817
|
-
...row.rejection_reason !== null ? { rejectionReason: row.rejection_reason } : {},
|
|
10818
|
-
createdAt: row.created_at,
|
|
10819
|
-
updatedAt: row.updated_at,
|
|
10820
|
-
...row.transaction_id !== null ? { transactionId: row.transaction_id } : {},
|
|
10821
|
-
...row.resolution_json !== null ? { resolution: JSON.parse(row.resolution_json) } : {}
|
|
10822
|
-
};
|
|
10823
|
-
}
|
|
10824
|
-
function rowToTransaction(row, now) {
|
|
10825
|
-
const status = row.payment_status;
|
|
10826
|
-
const backend = row.backend_dispatched_at !== null && row.backend_deadline_at !== null ? {
|
|
10827
|
-
dispatchedAt: row.backend_dispatched_at,
|
|
10828
|
-
deadlineAt: row.backend_deadline_at,
|
|
10829
|
-
...row.backend_status !== null ? { status: row.backend_status } : {},
|
|
10830
|
-
...row.backend_error_code !== null ? { errorCode: row.backend_error_code } : {}
|
|
10831
|
-
} : void 0;
|
|
10832
|
-
const completedAt = row.completed_at ?? void 0;
|
|
10833
|
-
const authorization = row.authorization_json !== null && row.reservation_id !== null ? {
|
|
10834
|
-
...JSON.parse(row.authorization_json),
|
|
10835
|
-
reservationId: row.reservation_id
|
|
10836
|
-
} : void 0;
|
|
10837
|
-
return {
|
|
10838
|
-
id: row.id,
|
|
10839
|
-
requestId: row.request_id,
|
|
10840
|
-
resourceId: row.resource_id,
|
|
10841
|
-
protocol: row.protocol,
|
|
10842
|
-
state: transactionState(
|
|
10843
|
-
{
|
|
10844
|
-
payment: { status },
|
|
10845
|
-
...backend !== void 0 ? { backend } : {},
|
|
10846
|
-
...completedAt !== void 0 ? { completedAt } : {}
|
|
10847
|
-
},
|
|
10848
|
-
now
|
|
10849
|
-
),
|
|
10850
|
-
payment: {
|
|
10851
|
-
provider: row.provider,
|
|
10852
|
-
attemptId: row.attempt_id,
|
|
10853
|
-
replayKey: row.replay_key,
|
|
10854
|
-
status,
|
|
10855
|
-
amount: row.payment_amount,
|
|
10856
|
-
currency: row.payment_currency,
|
|
10857
|
-
...row.network !== null ? { network: row.network } : {},
|
|
10858
|
-
...row.asset !== null ? { asset: row.asset } : {},
|
|
10859
|
-
...row.payment_payee !== null ? { payee: row.payment_payee } : {},
|
|
10860
|
-
...row.payment_external_reference !== null ? { externalReference: row.payment_external_reference } : {},
|
|
10861
|
-
...row.locator_json !== null ? { locator: JSON.parse(row.locator_json) } : {},
|
|
10862
|
-
...row.settling_at !== null ? { settlingAt: row.settling_at } : {},
|
|
10863
|
-
...row.expires_at !== null ? { expiresAt: row.expires_at } : {}
|
|
10864
|
-
},
|
|
10865
|
-
...authorization !== void 0 ? { authorization } : {},
|
|
10866
|
-
...backend !== void 0 ? { backend } : {},
|
|
10867
|
-
...row.receipt_id !== null ? { receiptId: row.receipt_id } : {},
|
|
10868
|
-
...row.input_digest !== null ? { inputDigest: row.input_digest } : {},
|
|
10869
|
-
configDigest: row.config_digest,
|
|
10870
|
-
...row.persistence_failures_json !== null ? { persistenceFailures: JSON.parse(row.persistence_failures_json) } : {},
|
|
10871
|
-
createdAt: row.created_at,
|
|
10872
|
-
updatedAt: row.updated_at,
|
|
10873
|
-
...completedAt !== void 0 ? { completedAt } : {}
|
|
10874
|
-
};
|
|
10875
|
-
}
|
|
10876
|
-
|
|
10877
10877
|
// src/storage/receipts/schema.ts
|
|
10878
10878
|
var MIGRATIONS = [
|
|
10879
10879
|
{
|
|
@@ -11012,9 +11012,67 @@ var MIGRATIONS = [
|
|
|
11012
11012
|
CREATE INDEX IF NOT EXISTS idx_payment_attempt_history_id ON payment_attempt_history(id);
|
|
11013
11013
|
`);
|
|
11014
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
|
+
}
|
|
11015
11070
|
}
|
|
11016
11071
|
];
|
|
11017
11072
|
var SCHEMA_VERSION2 = MIGRATIONS.at(-1)?.version ?? 0;
|
|
11073
|
+
function hasTable(db, name) {
|
|
11074
|
+
return db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name) !== void 0;
|
|
11075
|
+
}
|
|
11018
11076
|
function migrate2(db, target = SCHEMA_VERSION2) {
|
|
11019
11077
|
const current = db.pragma("user_version", { simple: true });
|
|
11020
11078
|
for (const migration of MIGRATIONS) {
|
|
@@ -11027,13 +11085,665 @@ function migrate2(db, target = SCHEMA_VERSION2) {
|
|
|
11027
11085
|
}
|
|
11028
11086
|
}
|
|
11029
11087
|
|
|
11030
|
-
// 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
|
|
11031
11285
|
var DEFAULT_LIST_LIMIT = 50;
|
|
11032
11286
|
var MAX_LIST_LIMIT = 500;
|
|
11033
11287
|
function clampListLimit(limit) {
|
|
11034
11288
|
const base = limit !== void 0 && Number.isFinite(limit) ? limit : DEFAULT_LIST_LIMIT;
|
|
11035
11289
|
return Math.min(Math.max(Math.trunc(base), 1), MAX_LIST_LIMIT);
|
|
11036
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
|
|
11037
11747
|
var UNDELIVERED = "backend_status NOT BETWEEN 200 AND 299";
|
|
11038
11748
|
var UNCERTAIN = "status IN ('settlement-uncertain', 'failed')";
|
|
11039
11749
|
var TRANSACTION_SELECT = `
|
|
@@ -11059,13 +11769,20 @@ function isUniqueConstraintOn(err, column) {
|
|
|
11059
11769
|
return err instanceof Error && "code" in err && err.code === "SQLITE_CONSTRAINT_UNIQUE" && err.message.includes(column);
|
|
11060
11770
|
}
|
|
11061
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) {
|
|
11062
11781
|
const logger = options.logger ?? NOOP_LOGGER;
|
|
11063
11782
|
const clock = options.clock ?? systemClock;
|
|
11064
11783
|
const ids = options.ids ?? defaultIds;
|
|
11065
11784
|
const path2 = options.path;
|
|
11066
11785
|
const isFileBacked = path2 !== ":memory:";
|
|
11067
|
-
const db = openSqliteDatabase({ path: path2, label: "Receipt database", logger });
|
|
11068
|
-
migrate2(db);
|
|
11069
11786
|
const insertReceiptStmt = db.prepare(
|
|
11070
11787
|
`INSERT INTO receipts (id, request_id, resource_id, payment_json, delivered_at, backend_status, duration_ms, protocol, metadata_json, authorization_json, transaction_id)
|
|
11071
11788
|
VALUES (@id, @request_id, @resource_id, @payment_json, @delivered_at, @backend_status, @duration_ms, @protocol, @metadata_json, @authorization_json, @transaction_id)`
|
|
@@ -11195,6 +11912,9 @@ function createSqliteReceiptStore(options) {
|
|
|
11195
11912
|
const getArchivedPaymentAttemptStmt = db.prepare(
|
|
11196
11913
|
"SELECT * FROM payment_attempt_history WHERE id = ? ORDER BY seq DESC LIMIT 1"
|
|
11197
11914
|
);
|
|
11915
|
+
const paymentAttemptByReplayKeyStmt = db.prepare(
|
|
11916
|
+
"SELECT * FROM payment_attempts WHERE replay_key = ?"
|
|
11917
|
+
);
|
|
11198
11918
|
const resolvePaymentAttemptStmt = db.prepare(
|
|
11199
11919
|
`UPDATE payment_attempts SET status = @status,
|
|
11200
11920
|
rejection_reason = COALESCE(@rejection_reason, rejection_reason),
|
|
@@ -11313,13 +12033,37 @@ function createSqliteReceiptStore(options) {
|
|
|
11313
12033
|
return true;
|
|
11314
12034
|
}
|
|
11315
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
|
+
);
|
|
11316
12051
|
let closed = false;
|
|
12052
|
+
let releaseLegacyLocks;
|
|
11317
12053
|
const descriptor = {
|
|
11318
12054
|
name: "sqlite-receipt-store",
|
|
11319
12055
|
kind: "storage",
|
|
11320
12056
|
implementationVersion: PACKAGE_VERSION,
|
|
11321
12057
|
supportedSpec: `sqlite-schema-v${SCHEMA_VERSION2}`,
|
|
11322
|
-
capabilities: [
|
|
12058
|
+
capabilities: [
|
|
12059
|
+
"receipts",
|
|
12060
|
+
"events",
|
|
12061
|
+
"payment-attempts",
|
|
12062
|
+
"transactions",
|
|
12063
|
+
"idempotency-keys",
|
|
12064
|
+
"authorization-holds",
|
|
12065
|
+
"pending-tasks"
|
|
12066
|
+
],
|
|
11323
12067
|
status: "stable"
|
|
11324
12068
|
};
|
|
11325
12069
|
const store = {
|
|
@@ -11331,6 +12075,16 @@ function createSqliteReceiptStore(options) {
|
|
|
11331
12075
|
`Receipt store schema version mismatch (found ${version}, expected ${SCHEMA_VERSION2})`
|
|
11332
12076
|
);
|
|
11333
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
|
+
}
|
|
11334
12088
|
},
|
|
11335
12089
|
async appendEvent(event) {
|
|
11336
12090
|
try {
|
|
@@ -11513,6 +12267,10 @@ function createSqliteReceiptStore(options) {
|
|
|
11513
12267
|
const row = getPaymentAttemptStmt.get(id) ?? getArchivedPaymentAttemptStmt.get(id);
|
|
11514
12268
|
return row !== void 0 ? rowToPaymentAttempt(row) : void 0;
|
|
11515
12269
|
},
|
|
12270
|
+
async findPaymentAttemptByReplayKey(replayKey) {
|
|
12271
|
+
const row = paymentAttemptByReplayKeyStmt.get(replayKey);
|
|
12272
|
+
return row !== void 0 ? rowToPaymentAttempt(row) : void 0;
|
|
12273
|
+
},
|
|
11516
12274
|
async resolvePaymentAttempt(request) {
|
|
11517
12275
|
try {
|
|
11518
12276
|
return resolveAttempt(request, clock.nowIso());
|
|
@@ -11520,6 +12278,33 @@ function createSqliteReceiptStore(options) {
|
|
|
11520
12278
|
throw toCommerceError(err, "STORAGE_ERROR", "Failed to resolve payment attempt");
|
|
11521
12279
|
}
|
|
11522
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
|
+
},
|
|
11523
12308
|
descriptor,
|
|
11524
12309
|
async health() {
|
|
11525
12310
|
const startedAt = clock.monotonicMs();
|
|
@@ -11578,6 +12363,7 @@ function createSqliteReceiptStore(options) {
|
|
|
11578
12363
|
async close() {
|
|
11579
12364
|
if (!closed) {
|
|
11580
12365
|
closed = true;
|
|
12366
|
+
releaseLegacyLocks?.();
|
|
11581
12367
|
db.close();
|
|
11582
12368
|
}
|
|
11583
12369
|
}
|