@devlab.group/agent-commerce 2.6.0 → 2.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -12
- package/dist/ap2.d.ts +1 -1
- package/dist/ap2.js +5 -5
- package/dist/{chunk-ES3V6ECS.js → chunk-77HLISG4.js} +3 -2
- package/dist/chunk-77HLISG4.js.map +1 -0
- package/dist/{chunk-5ZYXBCDX.js → chunk-D7FPSGUQ.js} +25 -4
- package/dist/chunk-D7FPSGUQ.js.map +1 -0
- package/dist/{chunk-G3EYYHKF.js → chunk-DJRWYDKJ.js} +3 -3
- package/dist/{chunk-G3EYYHKF.js.map → chunk-DJRWYDKJ.js.map} +1 -1
- package/dist/{chunk-M6MQ3FYS.js → chunk-EMKITGVV.js} +4 -4
- package/dist/chunk-EMKITGVV.js.map +1 -0
- package/dist/chunk-IWXVQYG5.js +6 -0
- package/dist/chunk-IWXVQYG5.js.map +1 -0
- package/dist/chunk-O3ACF45K.js +8 -0
- package/dist/{chunk-M6BSXXTF.js.map → chunk-O3ACF45K.js.map} +1 -1
- package/dist/{chunk-M6WW6QIT.js → chunk-WDD2ZUR3.js} +5 -3
- package/dist/chunk-WDD2ZUR3.js.map +1 -0
- package/dist/{chunk-M52FBNJX.js → chunk-YHNTTMED.js} +6 -4
- package/dist/chunk-YHNTTMED.js.map +1 -0
- package/dist/{chunk-DRLBML7Z.js → chunk-ZSIUZPNB.js} +175 -74
- package/dist/chunk-ZSIUZPNB.js.map +1 -0
- package/dist/cli/{ap2-2YMYA2H6.js → ap2-5FFGSW6F.js} +10 -11
- package/dist/cli/ap2-5FFGSW6F.js.map +1 -0
- package/dist/cli/{chunk-5K4XEAZV.js → chunk-3IEXJ7I3.js} +25 -4
- package/dist/cli/chunk-3IEXJ7I3.js.map +1 -0
- package/dist/cli/{chunk-VJH6RYRK.js → chunk-3NVJAQRO.js} +3 -3
- package/dist/cli/{chunk-VJH6RYRK.js.map → chunk-3NVJAQRO.js.map} +1 -1
- package/dist/cli/{chunk-GET3CZGR.js → chunk-55AI6CLW.js} +6 -4
- package/dist/cli/chunk-55AI6CLW.js.map +1 -0
- package/dist/cli/{chunk-YOF7IK4V.js → chunk-5K2JDM4G.js} +177 -76
- package/dist/cli/chunk-5K2JDM4G.js.map +1 -0
- package/dist/cli/{chunk-NSYSMDQN.js → chunk-5TID36YG.js} +57 -29
- package/dist/cli/chunk-5TID36YG.js.map +1 -0
- package/dist/cli/{chunk-3NOMLMJW.js → chunk-66NTYSXI.js} +3 -3
- package/dist/cli/{chunk-3NOMLMJW.js.map → chunk-66NTYSXI.js.map} +1 -1
- package/dist/cli/{chunk-VJ4EO4LE.js → chunk-6EBDOH37.js} +3 -3
- package/dist/cli/{chunk-VJ4EO4LE.js.map → chunk-6EBDOH37.js.map} +1 -1
- package/dist/cli/{chunk-YWG2ZN3L.js → chunk-AGQ4U7IN.js} +5 -5
- package/dist/cli/chunk-AGQ4U7IN.js.map +1 -0
- package/dist/cli/chunk-APC5BTQM.js +6 -0
- package/dist/cli/chunk-APC5BTQM.js.map +1 -0
- package/dist/cli/{chunk-SYQLJXIU.js → chunk-C5YISPT6.js} +3 -3
- package/dist/cli/chunk-C5YISPT6.js.map +1 -0
- package/dist/cli/chunk-DKWO6LLX.js +34 -0
- package/dist/cli/chunk-DKWO6LLX.js.map +1 -0
- package/dist/cli/{chunk-SPAYKVUP.js → chunk-FL4HPCD4.js} +3 -2
- package/dist/cli/chunk-FL4HPCD4.js.map +1 -0
- package/dist/cli/{chunk-3EQBCFZY.js → chunk-H7EBJ4I3.js} +3 -3
- package/dist/cli/{chunk-3EQBCFZY.js.map → chunk-H7EBJ4I3.js.map} +1 -1
- package/dist/cli/{chunk-PTL7SNOI.js → chunk-OETKXDGA.js} +467 -122
- package/dist/cli/chunk-OETKXDGA.js.map +1 -0
- package/dist/cli/{chunk-DHFMIBPG.js → chunk-PLHPKXAT.js} +6 -6
- package/dist/cli/{chunk-DHFMIBPG.js.map → chunk-PLHPKXAT.js.map} +1 -1
- package/dist/cli/{chunk-TFV3K6YS.js → chunk-VSSSU4AU.js} +3 -3
- package/dist/cli/{chunk-TFV3K6YS.js.map → chunk-VSSSU4AU.js.map} +1 -1
- package/dist/cli/chunk-ZCW56PZ3.js +8 -0
- package/dist/cli/{chunk-4KLYFXMW.js.map → chunk-ZCW56PZ3.js.map} +1 -1
- package/dist/cli/{chunk-AZL7RPFU.js → chunk-ZFVQWOGG.js} +64 -16
- package/dist/cli/chunk-ZFVQWOGG.js.map +1 -0
- package/dist/cli/config-WT5HHDRR.js +13 -0
- package/dist/cli/{config-3K65QJ22.js.map → config-WT5HHDRR.js.map} +1 -1
- package/dist/cli/index.js +51 -37
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/{mcp-6F64A7KE.js → mcp-HHGNOUKE.js} +7 -7
- package/dist/cli/{mcp-6F64A7KE.js.map → mcp-HHGNOUKE.js.map} +1 -1
- package/dist/cli/payment-providers-EWXZFBIE.js +6 -0
- package/dist/cli/{payment-providers-2ITS6KNR.js.map → payment-providers-EWXZFBIE.js.map} +1 -1
- package/dist/cli/{provider-5BGG5YKQ.js → provider-XUPLYNQ7.js} +9 -9
- package/dist/cli/{provider-5BGG5YKQ.js.map → provider-XUPLYNQ7.js.map} +1 -1
- package/dist/cli/receipts-3DSV4DIK.js +9 -0
- package/dist/cli/{receipts-I4IIE7U6.js.map → receipts-3DSV4DIK.js.map} +1 -1
- package/dist/cli/reconcile-GS25MQ42.js +4 -0
- package/dist/cli/{reconcile-55WNCSFC.js.map → reconcile-GS25MQ42.js.map} +1 -1
- package/dist/cli/{run-2P6ZGFUE.js → run-7KLKW3HE.js} +107 -35
- package/dist/cli/run-7KLKW3HE.js.map +1 -0
- package/dist/cli/{x402-4LPIIELI.js → x402-HP4E3QET.js} +11 -10
- package/dist/cli/x402-HP4E3QET.js.map +1 -0
- package/dist/{guardrails-CX_jYXvZ.d.ts → guardrails-CeyLS1ou.d.ts} +2 -2
- package/dist/index.d.ts +23 -13
- package/dist/index.js +660 -170
- package/dist/index.js.map +1 -1
- package/dist/mcp.d.ts +2 -2
- package/dist/mcp.js +4 -4
- package/dist/mpp.js +5 -5
- package/dist/{protocol-adapter-1WbtM3xG.d.ts → protocol-adapter-DdFL5LBU.d.ts} +12 -2
- package/dist/{runtime-B-kARa2f.d.ts → runtime-BmaSp2Ce.d.ts} +31 -3
- package/dist/{store-kIIMpUA-.d.ts → store-BVvMzpuV.d.ts} +25 -8
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +156 -2
- package/dist/testing.js.map +1 -1
- package/dist/{transaction-Dv0UFGg5.d.ts → transaction-BXXJltZ-.d.ts} +1 -1
- package/dist/x402.d.ts +7 -2
- package/dist/x402.js +7 -6
- package/dist/x402.js.map +1 -1
- package/package.json +13 -29
- package/dist/chunk-5ZYXBCDX.js.map +0 -1
- package/dist/chunk-DRLBML7Z.js.map +0 -1
- package/dist/chunk-ES3V6ECS.js.map +0 -1
- package/dist/chunk-M52FBNJX.js.map +0 -1
- package/dist/chunk-M6BSXXTF.js +0 -8
- package/dist/chunk-M6MQ3FYS.js.map +0 -1
- package/dist/chunk-M6WW6QIT.js.map +0 -1
- package/dist/cli/ap2-2YMYA2H6.js.map +0 -1
- package/dist/cli/chunk-4KLYFXMW.js +0 -8
- package/dist/cli/chunk-5K4XEAZV.js.map +0 -1
- package/dist/cli/chunk-6R6WJ4FD.js +0 -18
- package/dist/cli/chunk-6R6WJ4FD.js.map +0 -1
- package/dist/cli/chunk-AZL7RPFU.js.map +0 -1
- package/dist/cli/chunk-FHCFR2GS.js +0 -17
- package/dist/cli/chunk-FHCFR2GS.js.map +0 -1
- package/dist/cli/chunk-GET3CZGR.js.map +0 -1
- package/dist/cli/chunk-NSYSMDQN.js.map +0 -1
- package/dist/cli/chunk-PTL7SNOI.js.map +0 -1
- package/dist/cli/chunk-SPAYKVUP.js.map +0 -1
- package/dist/cli/chunk-SYQLJXIU.js.map +0 -1
- package/dist/cli/chunk-YOF7IK4V.js.map +0 -1
- package/dist/cli/chunk-YWG2ZN3L.js.map +0 -1
- package/dist/cli/config-3K65QJ22.js +0 -12
- package/dist/cli/payment-providers-2ITS6KNR.js +0 -6
- package/dist/cli/receipts-I4IIE7U6.js +0 -8
- package/dist/cli/reconcile-55WNCSFC.js +0 -4
- package/dist/cli/run-2P6ZGFUE.js.map +0 -1
- package/dist/cli/x402-4LPIIELI.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
|
-
import { openSqliteDatabase, AP2_SPEC_VERSION, AP2_MODES, AP2_DEFAULT_CLOCK_SKEW_SECONDS, AP2_JWK_MEMBERS, AP2_KEY_TYPE, AP2_SIGNING_ALGORITHM, AP2_JWK_CURVE, AP2_JWK_COORDINATE_BYTES, AP2_MAX_CLOCK_SKEW_SECONDS } from './chunk-
|
|
2
|
-
import { readCappedBody, createBearerCheck, MCP_TOOL_NAME_PATTERN, settlementResponse, joinUrl, settlementResponseFromDetails, settlementFailure, x402ErrorCode, x402RefusalStatus } from './chunk-
|
|
1
|
+
import { openSqliteDatabase, AP2_SPEC_VERSION, AP2_MODES, AP2_DEFAULT_CLOCK_SKEW_SECONDS, AP2_JWK_MEMBERS, AP2_KEY_TYPE, AP2_SIGNING_ALGORITHM, AP2_JWK_CURVE, AP2_JWK_COORDINATE_BYTES, AP2_MAX_CLOCK_SKEW_SECONDS } from './chunk-DJRWYDKJ.js';
|
|
2
|
+
import { readCappedBody, createBearerCheck, MCP_TOOL_NAME_PATTERN, settlementResponse, joinUrl, settlementResponseFromDetails, settlementFailure, x402ErrorCode, x402RefusalStatus } from './chunk-77HLISG4.js';
|
|
3
3
|
import { MPP_DEFAULT_NETWORK, isMppNetwork, MPP_NETWORKS, MPP_DEFAULT_PAYMENT_FLOW, MPP_MIN_CHALLENGE_SECRET_LENGTH, MPP_PROFILE } from './chunk-6Z2H53CG.js';
|
|
4
|
-
import { contentDigest, CONTENT_DIGEST_METADATA_KEY, mppProblem, mppProblemDetail } from './chunk-
|
|
5
|
-
import { X402_PAYMENT_FLOWS, validateCustomNetworks, findX402Network, X402_DEFAULT_PAYMENT_FLOW, resolveX402Deployment, resolveDeploymentMode, requireX402Network, resolveX402Option, isEvmAddress, isEvmZeroAddress, SETTLE_AFTER_BACKEND_METADATA_KEY, x402OfferName, REUSE_REJECTED_AUTHORIZATION_METADATA_KEY, canonicalJson } from './chunk-
|
|
6
|
-
import { PACKAGE_VERSION } from './chunk-
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
|
|
4
|
+
import { contentDigest, CONTENT_DIGEST_METADATA_KEY, mppProblem, mppProblemDetail } from './chunk-D7FPSGUQ.js';
|
|
5
|
+
import { X402_PAYMENT_FLOWS, validateCustomNetworks, findX402Network, X402_DEFAULT_PAYMENT_FLOW, resolveX402Deployment, resolveDeploymentMode, requireX402Network, resolveX402Option, isEvmAddress, isEvmZeroAddress, SETTLE_AFTER_BACKEND_METADATA_KEY, x402OfferName, REUSE_REJECTED_AUTHORIZATION_METADATA_KEY, canonicalJson } from './chunk-EMKITGVV.js';
|
|
6
|
+
import { PACKAGE_VERSION } from './chunk-O3ACF45K.js';
|
|
7
|
+
import { PAYMENT_KEY_ENDPOINT_PREFIX } from './chunk-IWXVQYG5.js';
|
|
8
|
+
import { hasMethodGroup } from './chunk-WDD2ZUR3.js';
|
|
9
|
+
import { RESERVED_INPUT_FIELDS, PROTOCOL_NAMES, PAYMENT_METHOD_NAMES, PAYMENT_HEADER, AUTHORIZATION_HEADER, CommerceError, systemClock, NOOP_LOGGER, transactionState, DEFAULT_BACKEND_TIMEOUT_MS, isCommerceError, describeError, isHttpProtocolAdapter, toLogInfo, toCommerceError, extractReservedInputFields, parseAuthorizationHeader, toPaymentRequiredEnvelope, PAYMENT_REQUIRED_HEADER, PAYMENT_RESPONSE_HEADER, toErrorEnvelope, DELIVERY_SUMMARY_META_KEY, toDeliverySummary, PAYMENT_INPUT_FIELD, AUTHORIZATION_INPUT_FIELD, parseAuthorizationSubmission, RECONCILIATION_METADATA_KEY, TRANSACTION_STATES, redactedErrorText } from './chunk-YHNTTMED.js';
|
|
10
|
+
export { AUTHORIZATION_HEADER, AUTHORIZATION_INPUT_FIELD, COMMERCE_ERROR_CODES, COMMERCE_ERROR_HTTP_STATUS, COMMERCE_EVENT_TYPES, CommerceError, DEFAULT_BACKEND_TIMEOUT_MS, DELIVERY_SUMMARY_META_KEY, MAX_AUTHORIZATION_HEADER_BYTES, NOOP_LOGGER, PAYMENT_HEADER, PAYMENT_INPUT_FIELD, PAYMENT_METHOD_NAMES, PAYMENT_REQUIRED_HEADER, PAYMENT_RESPONSE_HEADER, PROTOCOL_NAMES, RECONCILIATION_METADATA_KEY, RESERVED_INPUT_FIELDS, RETRYABLE_ERROR_CODES, TRANSACTION_STATES, extractReservedInputFields, isCommerceError, isHttpProtocolAdapter, isPaymentRequiredEnvelope, parseAuthorizationHeader, parseAuthorizationSubmission, systemClock, toCommerceError, toDeliverySummary, toErrorEnvelope, toPaymentRequiredEnvelope, transactionState } from './chunk-YHNTTMED.js';
|
|
10
11
|
import { isRecord } from './chunk-2CJNA7MS.js';
|
|
11
12
|
import { promises, accessSync, constants, existsSync } from 'fs';
|
|
12
13
|
import * as path from 'path';
|
|
@@ -853,8 +854,8 @@ var MerchantSchema = z.object({
|
|
|
853
854
|
var ServerSchema = z.object({
|
|
854
855
|
port: NumberOrString,
|
|
855
856
|
host: z.string().min(1),
|
|
856
|
-
//
|
|
857
|
-
//
|
|
857
|
+
// Operator routes (/api/receipts, /api/events, /api/payment-attempts,
|
|
858
|
+
// /api/transactions and the resolve route) return 404 without this token
|
|
858
859
|
adminToken: z.string().min(1).optional(),
|
|
859
860
|
// Browser origins allowed to call the gateway; none by default. A request
|
|
860
861
|
// with any other `Origin` gets 403 on every route. Entries match the
|
|
@@ -887,7 +888,10 @@ var RESERVED_GATEWAY_PATHS = [
|
|
|
887
888
|
"/api/resources/:id/invoke",
|
|
888
889
|
"/api/receipts",
|
|
889
890
|
"/api/events",
|
|
890
|
-
"/api/payment-attempts"
|
|
891
|
+
"/api/payment-attempts",
|
|
892
|
+
"/api/payment-attempts/:id/resolve",
|
|
893
|
+
"/api/transactions",
|
|
894
|
+
"/api/transactions/:id"
|
|
891
895
|
];
|
|
892
896
|
var MountPathSchema = z.string().min(1).refine((value) => value.startsWith("/"), {
|
|
893
897
|
message: 'must start with "/" - it is an absolute gateway path, e.g. "/mcp".'
|
|
@@ -910,7 +914,7 @@ var AcpIdempotencySchema = z.object({
|
|
|
910
914
|
retentionHours: NumberOrString.optional(),
|
|
911
915
|
merchantIdempotent: z.boolean().optional()
|
|
912
916
|
}).strict();
|
|
913
|
-
var AcpCheckoutSchema = z.object({ operations: z.record(z.string().min(1)) }).strict();
|
|
917
|
+
var AcpCheckoutSchema = z.object({ operations: z.record(z.string(), z.string().min(1)) }).strict();
|
|
914
918
|
var AcpDiscoverySchema = z.object({
|
|
915
919
|
documentationUrl: z.string().min(1).optional(),
|
|
916
920
|
supportedCurrencies: z.array(z.string().min(1)).optional(),
|
|
@@ -991,14 +995,20 @@ var ResourceEntrySchema = z.object({
|
|
|
991
995
|
paymentFlow: z.enum(X402_PAYMENT_FLOWS).optional(),
|
|
992
996
|
// This resource's own x402 offers, in place of `payments.x402` options
|
|
993
997
|
x402: z.object({ accepts: z.array(X402OptionSchema) }).strict().optional(),
|
|
994
|
-
authorization: z.object({ required: z.array(z.string().min(1)).min(1) }).strict().optional()
|
|
998
|
+
authorization: z.object({ required: z.array(z.string().min(1)).min(1) }).strict().optional(),
|
|
999
|
+
idempotency: z.object({
|
|
1000
|
+
merchantKey: BooleanOrString.optional(),
|
|
1001
|
+
redelivery: z.object({
|
|
1002
|
+
retentionHours: NumberOrString.optional(),
|
|
1003
|
+
required: BooleanOrString.optional()
|
|
1004
|
+
}).strict().optional()
|
|
1005
|
+
}).strict().optional()
|
|
995
1006
|
}).strict();
|
|
996
1007
|
var ResourcesMapSchema = z.record(z.string().min(1), ResourceEntrySchema);
|
|
997
1008
|
var FacilitatorAuthSchema = z.discriminatedUnion("type", [
|
|
998
1009
|
z.object({ type: z.literal("none") }).strict(),
|
|
999
1010
|
z.object({ type: z.literal("bearer"), token: z.string().min(1) }).strict(),
|
|
1000
|
-
// Coinbase Developer Platform
|
|
1001
|
-
// which signs a fresh JWT per request.
|
|
1011
|
+
// Coinbase Developer Platform: the gateway signs a fresh JWT per request
|
|
1002
1012
|
z.object({
|
|
1003
1013
|
type: z.literal("cdp"),
|
|
1004
1014
|
apiKeyId: z.string().min(1),
|
|
@@ -1109,6 +1119,333 @@ var RawConfigSchema = z.object({
|
|
|
1109
1119
|
payments: PaymentsSchema,
|
|
1110
1120
|
authorization: AuthorizationSchema.optional()
|
|
1111
1121
|
}).strict();
|
|
1122
|
+
function createFlow(request, transactionId) {
|
|
1123
|
+
return { request, transactionId, persistenceFailures: [], journaled: false, chargeRisk: false };
|
|
1124
|
+
}
|
|
1125
|
+
function failuresOf(flow) {
|
|
1126
|
+
return flow.persistenceFailures.length > 0 ? { persistenceFailures: [...flow.persistenceFailures] } : {};
|
|
1127
|
+
}
|
|
1128
|
+
function sha256(text) {
|
|
1129
|
+
return `sha256:${createHash("sha256").update(text, "utf8").digest("hex")}`;
|
|
1130
|
+
}
|
|
1131
|
+
function inputDigest(input) {
|
|
1132
|
+
const json = canonicalJson(input);
|
|
1133
|
+
return json !== void 0 ? sha256(json) : void 0;
|
|
1134
|
+
}
|
|
1135
|
+
function configDigest(resource, requirement) {
|
|
1136
|
+
const terms = {
|
|
1137
|
+
resourceId: resource.id,
|
|
1138
|
+
pricing: resource.pricing,
|
|
1139
|
+
paymentMethods: resource.paymentMethods,
|
|
1140
|
+
authorization: resource.authorization?.required ?? [],
|
|
1141
|
+
requirement: {
|
|
1142
|
+
provider: requirement.provider,
|
|
1143
|
+
amount: requirement.amount,
|
|
1144
|
+
currency: requirement.currency,
|
|
1145
|
+
destination: requirement.destination ?? null,
|
|
1146
|
+
network: requirement.network ?? null,
|
|
1147
|
+
asset: requirement.asset ?? null,
|
|
1148
|
+
settleAfterBackend: requirement.metadata?.[SETTLE_AFTER_BACKEND_METADATA_KEY] === true
|
|
1149
|
+
}
|
|
1150
|
+
};
|
|
1151
|
+
return sha256(canonicalJson(terms) ?? JSON.stringify(terms));
|
|
1152
|
+
}
|
|
1153
|
+
function newTransaction(flow, resource, requirement, verification, digest, authorization) {
|
|
1154
|
+
const raw = verification.metadata?.[RECONCILIATION_METADATA_KEY];
|
|
1155
|
+
const locator = isRecord(raw) ? raw : void 0;
|
|
1156
|
+
const expiresAt = typeof locator?.["expiresAt"] === "string" ? locator["expiresAt"] : void 0;
|
|
1157
|
+
const network = verification.network ?? requirement.network;
|
|
1158
|
+
const asset = verification.asset ?? requirement.asset;
|
|
1159
|
+
return {
|
|
1160
|
+
id: flow.transactionId,
|
|
1161
|
+
protocol: flow.request.protocol,
|
|
1162
|
+
...network !== void 0 ? { network } : {},
|
|
1163
|
+
...asset !== void 0 ? { asset } : {},
|
|
1164
|
+
...locator !== void 0 ? { locator } : {},
|
|
1165
|
+
...expiresAt !== void 0 ? { expiresAt } : {},
|
|
1166
|
+
...authorization !== void 0 ? { authorization } : {},
|
|
1167
|
+
...digest !== void 0 ? { inputDigest: digest } : {},
|
|
1168
|
+
configDigest: configDigest(resource, requirement)
|
|
1169
|
+
};
|
|
1170
|
+
}
|
|
1171
|
+
function sha256Hex(text) {
|
|
1172
|
+
return createHash("sha256").update(text).digest("hex");
|
|
1173
|
+
}
|
|
1174
|
+
function paidOperationKey(operation) {
|
|
1175
|
+
const { deployment, resourceId, replayKey, inputDigest: digest, clientKey, payer } = operation;
|
|
1176
|
+
if (digest === void 0) return void 0;
|
|
1177
|
+
const identity = clientKey && payer ? `retry:${sha256Hex(clientKey)}:${payer}` : replayKey;
|
|
1178
|
+
return sha256Hex(JSON.stringify(["paid-operation", deployment, resourceId, identity, digest]));
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
// src/core/execution/pipeline/retry.ts
|
|
1182
|
+
var MAX_REDELIVERY_RETENTION_HOURS = 8760;
|
|
1183
|
+
var IN_FLIGHT_RETRY_AFTER_SECONDS = 1;
|
|
1184
|
+
var REFUSALS = {
|
|
1185
|
+
conflict: {
|
|
1186
|
+
reason: "payment_identifier_conflict",
|
|
1187
|
+
message: "This payment identifier belongs to another request"
|
|
1188
|
+
},
|
|
1189
|
+
"in-flight": {
|
|
1190
|
+
reason: "payment_identifier_in_flight",
|
|
1191
|
+
message: "A request with this payment identifier is in progress"
|
|
1192
|
+
},
|
|
1193
|
+
unresolved: {
|
|
1194
|
+
reason: "payment_identifier_unresolved",
|
|
1195
|
+
message: "The earlier request with this payment identifier may have been charged and has no stored response"
|
|
1196
|
+
}
|
|
1197
|
+
};
|
|
1198
|
+
function assertRetrySupport(resource, store, deployment, requestId) {
|
|
1199
|
+
const { merchantKey, redelivery } = resource.idempotency ?? {};
|
|
1200
|
+
if (merchantKey !== true && redelivery === void 0) return void 0;
|
|
1201
|
+
const invalid3 = (message) => new CommerceError("CONFIG_INVALID", message, {
|
|
1202
|
+
...requestId !== void 0 ? { requestId } : {},
|
|
1203
|
+
resourceId: resource.id
|
|
1204
|
+
});
|
|
1205
|
+
const unsupported2 = (needs) => invalid3(`Resource "${resource.id}" sets idempotency, which requires ${needs}`);
|
|
1206
|
+
const hours = redelivery?.retentionHours;
|
|
1207
|
+
if (hours !== void 0 && !(Number.isInteger(hours) && hours >= 1 && hours <= MAX_REDELIVERY_RETENTION_HOURS)) {
|
|
1208
|
+
throw invalid3(
|
|
1209
|
+
`Resource "${resource.id}" sets idempotency.redelivery.retentionHours outside 1 to ${MAX_REDELIVERY_RETENTION_HOURS}`
|
|
1210
|
+
);
|
|
1211
|
+
}
|
|
1212
|
+
if (deployment === void 0) throw unsupported2("the pipeline's deployment option");
|
|
1213
|
+
if (redelivery === void 0) return { deployment };
|
|
1214
|
+
if (!hasMethodGroup(store, "idempotency_claims") || !hasMethodGroup(store, "response_redelivery")) {
|
|
1215
|
+
throw unsupported2("a store with idempotency claims and getIdempotencyKey");
|
|
1216
|
+
}
|
|
1217
|
+
return { deployment, store };
|
|
1218
|
+
}
|
|
1219
|
+
function createRetryGate(ctx) {
|
|
1220
|
+
const { options, safeEmit, safePersist, buildEvent } = ctx;
|
|
1221
|
+
async function open(flow, resource, provider, validInput, support, pipelineStart) {
|
|
1222
|
+
const { request } = flow;
|
|
1223
|
+
const retentionHours = resource.idempotency?.redelivery?.retentionHours;
|
|
1224
|
+
const { payment } = request;
|
|
1225
|
+
if (support?.store === void 0 || retentionHours === void 0 || payment === void 0) {
|
|
1226
|
+
return void 0;
|
|
1227
|
+
}
|
|
1228
|
+
const clientKey = request.retryKey ?? await providerRetryKey(flow, resource, provider, payment);
|
|
1229
|
+
if (clientKey === void 0) return void 0;
|
|
1230
|
+
const fingerprint = inputDigest(validInput);
|
|
1231
|
+
if (fingerprint === void 0) {
|
|
1232
|
+
throw await rejected(
|
|
1233
|
+
flow,
|
|
1234
|
+
resource,
|
|
1235
|
+
provider,
|
|
1236
|
+
new CommerceError(
|
|
1237
|
+
"INPUT_INVALID",
|
|
1238
|
+
`Input for resource "${resource.id}" is not I-JSON, so a retry key cannot identify it`,
|
|
1239
|
+
{ requestId: request.requestId, resourceId: resource.id }
|
|
1240
|
+
)
|
|
1241
|
+
);
|
|
1242
|
+
}
|
|
1243
|
+
const { store } = support;
|
|
1244
|
+
const { authorization } = request;
|
|
1245
|
+
const ticket = {
|
|
1246
|
+
kind: "retry",
|
|
1247
|
+
store,
|
|
1248
|
+
scope: {
|
|
1249
|
+
deployment: support.deployment,
|
|
1250
|
+
endpoint: `${PAYMENT_KEY_ENDPOINT_PREFIX}${resource.id}`,
|
|
1251
|
+
key: sha256Hex(clientKey)
|
|
1252
|
+
},
|
|
1253
|
+
fingerprint,
|
|
1254
|
+
expiresAt: new Date(
|
|
1255
|
+
options.clock.now().getTime() + retentionHours * 60 * 60 * 1e3
|
|
1256
|
+
).toISOString(),
|
|
1257
|
+
clientKey,
|
|
1258
|
+
proofDigest: sha256Hex(`${payment.method}:${payment.payload}`),
|
|
1259
|
+
...authorization !== void 0 ? { authorizationDigest: sha256Hex(`${authorization.method}:${authorization.payload}`) } : {}
|
|
1260
|
+
};
|
|
1261
|
+
const existing = await reading(
|
|
1262
|
+
flow,
|
|
1263
|
+
resource,
|
|
1264
|
+
() => store.getIdempotencyKey(ticket.scope, fingerprint)
|
|
1265
|
+
);
|
|
1266
|
+
if (existing?.kind === "in-flight" || existing?.kind === "unresolved") {
|
|
1267
|
+
if (existing.owner !== ticket.proofDigest) return ticket;
|
|
1268
|
+
throw await refusal(flow, resource, provider, existing.kind);
|
|
1269
|
+
}
|
|
1270
|
+
if (existing?.kind !== "replay") return ticket;
|
|
1271
|
+
const stored = readStoredDelivery(existing.body);
|
|
1272
|
+
return stored?.proofDigest === ticket.proofDigest && authorizes(resource, stored, ticket) ? redeliver(flow, resource, provider, existing.status, stored, pipelineStart) : ticket;
|
|
1273
|
+
}
|
|
1274
|
+
async function claim(flow, resource, provider, ticket, verification, pipelineStart) {
|
|
1275
|
+
const { scope, fingerprint, expiresAt, proofDigest } = ticket;
|
|
1276
|
+
const claimed = await reading(
|
|
1277
|
+
flow,
|
|
1278
|
+
resource,
|
|
1279
|
+
() => ticket.store.claimIdempotencyKey(scope, fingerprint, expiresAt, proofDigest)
|
|
1280
|
+
);
|
|
1281
|
+
const replay = await acceptOrRefuse(flow, resource, provider, claimed);
|
|
1282
|
+
if (replay === void 0) return void 0;
|
|
1283
|
+
const stored = await storedDelivery(flow, resource, provider, replay);
|
|
1284
|
+
const samePayer = verification.payer !== void 0 && verification.payer === stored.payer;
|
|
1285
|
+
if (!samePayer || !authorizes(resource, stored, ticket)) {
|
|
1286
|
+
throw await refusal(flow, resource, provider, "conflict");
|
|
1287
|
+
}
|
|
1288
|
+
return redeliver(flow, resource, provider, replay.status, stored, pipelineStart);
|
|
1289
|
+
}
|
|
1290
|
+
async function finishDelivered(flow, ticket, verification, response, receipt) {
|
|
1291
|
+
const contentType = response.headers["content-type"];
|
|
1292
|
+
const stored = {
|
|
1293
|
+
proofDigest: ticket.proofDigest,
|
|
1294
|
+
...ticket.authorizationDigest !== void 0 ? { authorizationDigest: ticket.authorizationDigest } : {},
|
|
1295
|
+
// Record the verified buyer; settlement may name a fee payer instead
|
|
1296
|
+
...verification.payer !== void 0 ? { payer: verification.payer } : {},
|
|
1297
|
+
// Keep only Content-Type; never persist a backend Set-Cookie header
|
|
1298
|
+
...contentType !== void 0 ? { contentType } : {},
|
|
1299
|
+
body: response.body ?? null,
|
|
1300
|
+
receiptId: receipt.id
|
|
1301
|
+
};
|
|
1302
|
+
const receiptSaved = !flow.persistenceFailures.includes("receipt");
|
|
1303
|
+
const update = { kind: "completed", status: response.status, body: stored };
|
|
1304
|
+
if (receiptSaved && await write(flow, ticket, update)) return;
|
|
1305
|
+
if (!flow.persistenceFailures.includes("response")) flow.persistenceFailures.push("response");
|
|
1306
|
+
await write(flow, ticket, { kind: "unresolved" });
|
|
1307
|
+
}
|
|
1308
|
+
async function finishFailed(flow, ticket) {
|
|
1309
|
+
await write(flow, ticket, { kind: flow.chargeRisk ? "unresolved" : "released" });
|
|
1310
|
+
}
|
|
1311
|
+
function write(flow, ticket, update) {
|
|
1312
|
+
return safePersist(
|
|
1313
|
+
flow,
|
|
1314
|
+
() => ticket.store.updateIdempotencyKey(ticket.scope, update),
|
|
1315
|
+
`updateIdempotencyKey(${update.kind})`,
|
|
1316
|
+
"response"
|
|
1317
|
+
);
|
|
1318
|
+
}
|
|
1319
|
+
async function reading(flow, resource, read) {
|
|
1320
|
+
try {
|
|
1321
|
+
return await read();
|
|
1322
|
+
} catch (error) {
|
|
1323
|
+
throw new CommerceError("STORAGE_ERROR", "Payment retry state could not be read", {
|
|
1324
|
+
requestId: flow.request.requestId,
|
|
1325
|
+
resourceId: resource.id,
|
|
1326
|
+
cause: error
|
|
1327
|
+
});
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
async function acceptOrRefuse(flow, resource, provider, claimed) {
|
|
1331
|
+
if (claimed === void 0 || claimed.kind === "reserved") return void 0;
|
|
1332
|
+
if (claimed.kind === "replay") return claimed;
|
|
1333
|
+
throw await refusal(flow, resource, provider, claimed.kind);
|
|
1334
|
+
}
|
|
1335
|
+
async function storedDelivery(flow, resource, provider, replay) {
|
|
1336
|
+
const stored = readStoredDelivery(replay.body);
|
|
1337
|
+
if (stored === void 0) throw await refusal(flow, resource, provider, "unresolved");
|
|
1338
|
+
return stored;
|
|
1339
|
+
}
|
|
1340
|
+
function refusal(flow, resource, provider, kind) {
|
|
1341
|
+
const { reason, message } = REFUSALS[kind];
|
|
1342
|
+
const inFlight = kind === "in-flight";
|
|
1343
|
+
return rejected(
|
|
1344
|
+
flow,
|
|
1345
|
+
resource,
|
|
1346
|
+
provider,
|
|
1347
|
+
new CommerceError("PAYMENT_REPLAYED", message, {
|
|
1348
|
+
requestId: flow.request.requestId,
|
|
1349
|
+
resourceId: resource.id,
|
|
1350
|
+
details: {
|
|
1351
|
+
reason,
|
|
1352
|
+
...inFlight ? { retryAfterSeconds: IN_FLIGHT_RETRY_AFTER_SECONDS } : {}
|
|
1353
|
+
},
|
|
1354
|
+
...inFlight ? { retryable: true } : {}
|
|
1355
|
+
})
|
|
1356
|
+
);
|
|
1357
|
+
}
|
|
1358
|
+
async function rejected(flow, resource, provider, error) {
|
|
1359
|
+
const reason = error.details?.["reason"];
|
|
1360
|
+
await safeEmit(
|
|
1361
|
+
buildEvent(flow, {
|
|
1362
|
+
type: "payment.rejected",
|
|
1363
|
+
resourceId: resource.id,
|
|
1364
|
+
adapter: flow.request.protocol,
|
|
1365
|
+
paymentProvider: provider.name,
|
|
1366
|
+
status: "error",
|
|
1367
|
+
data: { reason: typeof reason === "string" ? reason : error.code }
|
|
1368
|
+
})
|
|
1369
|
+
);
|
|
1370
|
+
if (error.requestId !== void 0) return error;
|
|
1371
|
+
return new CommerceError(error.code, error.message, {
|
|
1372
|
+
requestId: flow.request.requestId,
|
|
1373
|
+
resourceId: error.resourceId ?? resource.id,
|
|
1374
|
+
httpStatus: error.httpStatus,
|
|
1375
|
+
retryable: error.retryable,
|
|
1376
|
+
...error.details !== void 0 ? { details: error.details } : {},
|
|
1377
|
+
...error.cause !== void 0 ? { cause: error.cause } : {}
|
|
1378
|
+
});
|
|
1379
|
+
}
|
|
1380
|
+
async function providerRetryKey(flow, resource, provider, submission) {
|
|
1381
|
+
try {
|
|
1382
|
+
return provider.retryKey?.({ resource, submission });
|
|
1383
|
+
} catch (error) {
|
|
1384
|
+
const typed = isCommerceError(error) ? error : new CommerceError("PAYMENT_PROVIDER_UNAVAILABLE", "Payment provider is unavailable", {
|
|
1385
|
+
cause: error
|
|
1386
|
+
});
|
|
1387
|
+
throw await rejected(flow, resource, provider, typed);
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1390
|
+
async function redeliver(flow, resource, provider, status, stored, pipelineStart) {
|
|
1391
|
+
const { request } = flow;
|
|
1392
|
+
const receipt = await reading(flow, resource, () => options.store.getReceipt(stored.receiptId));
|
|
1393
|
+
if (receipt?.payment === void 0) {
|
|
1394
|
+
throw await refusal(flow, resource, provider, "unresolved");
|
|
1395
|
+
}
|
|
1396
|
+
const durationMs = Math.round(options.clock.monotonicMs() - pipelineStart);
|
|
1397
|
+
const original = receipt.transactionId;
|
|
1398
|
+
await safeEmit(
|
|
1399
|
+
buildEvent(flow, {
|
|
1400
|
+
type: "resource.delivered",
|
|
1401
|
+
resourceId: resource.id,
|
|
1402
|
+
adapter: request.protocol,
|
|
1403
|
+
status: "ok",
|
|
1404
|
+
durationMs,
|
|
1405
|
+
data: {
|
|
1406
|
+
redelivered: true,
|
|
1407
|
+
...original !== void 0 ? { originalTransactionId: original } : {}
|
|
1408
|
+
}
|
|
1409
|
+
})
|
|
1410
|
+
);
|
|
1411
|
+
return {
|
|
1412
|
+
kind: "delivered",
|
|
1413
|
+
requestId: request.requestId,
|
|
1414
|
+
transactionId: flow.transactionId,
|
|
1415
|
+
resourceId: resource.id,
|
|
1416
|
+
backendStatus: status,
|
|
1417
|
+
body: stored.body,
|
|
1418
|
+
headers: stored.contentType !== void 0 ? { "content-type": stored.contentType } : {},
|
|
1419
|
+
payment: receipt.payment,
|
|
1420
|
+
receipt,
|
|
1421
|
+
durationMs,
|
|
1422
|
+
redelivered: true
|
|
1423
|
+
};
|
|
1424
|
+
}
|
|
1425
|
+
return { open, claim, finishDelivered, finishFailed };
|
|
1426
|
+
}
|
|
1427
|
+
function authorizes(resource, stored, ticket) {
|
|
1428
|
+
if ((resource.authorization?.required.length ?? 0) === 0) return true;
|
|
1429
|
+
return stored.authorizationDigest !== void 0 && stored.authorizationDigest === ticket.authorizationDigest;
|
|
1430
|
+
}
|
|
1431
|
+
function readStoredDelivery(value) {
|
|
1432
|
+
if (!isRecord(value) || !Object.hasOwn(value, "body")) return void 0;
|
|
1433
|
+
const { proofDigest, authorizationDigest, payer, contentType, body, receiptId } = value;
|
|
1434
|
+
if (typeof proofDigest !== "string" || typeof receiptId !== "string") return void 0;
|
|
1435
|
+
if (authorizationDigest !== void 0 && typeof authorizationDigest !== "string") {
|
|
1436
|
+
return void 0;
|
|
1437
|
+
}
|
|
1438
|
+
if (payer !== void 0 && typeof payer !== "string") return void 0;
|
|
1439
|
+
if (contentType !== void 0 && typeof contentType !== "string") return void 0;
|
|
1440
|
+
return {
|
|
1441
|
+
proofDigest,
|
|
1442
|
+
...authorizationDigest !== void 0 ? { authorizationDigest } : {},
|
|
1443
|
+
...payer !== void 0 ? { payer } : {},
|
|
1444
|
+
...contentType !== void 0 ? { contentType } : {},
|
|
1445
|
+
body,
|
|
1446
|
+
receiptId
|
|
1447
|
+
};
|
|
1448
|
+
}
|
|
1112
1449
|
|
|
1113
1450
|
// src/core/execution/backend-request.ts
|
|
1114
1451
|
var NEVER_FORWARDED_HEADER = /^(authorization|cookie|set-cookie|host|content-length|content-type|connection|keep-alive|te|trailer|transfer-encoding|upgrade|idempotency-key|proxy-.*)$/;
|
|
@@ -1456,56 +1793,6 @@ function safeStringify(value) {
|
|
|
1456
1793
|
function isAbortError(error) {
|
|
1457
1794
|
return error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
|
|
1458
1795
|
}
|
|
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
|
-
}
|
|
1509
1796
|
var SUPPORTED_TYPES = /* @__PURE__ */ new Set([
|
|
1510
1797
|
"object",
|
|
1511
1798
|
"string",
|
|
@@ -1770,9 +2057,15 @@ function replayError(error, requirement) {
|
|
|
1770
2057
|
}
|
|
1771
2058
|
|
|
1772
2059
|
// src/core/execution/pipeline/admission.ts
|
|
1773
|
-
function createPaymentAdmission(ctx, authorizeAndReserve) {
|
|
2060
|
+
function createPaymentAdmission(ctx, authorizeAndReserve, retryGate) {
|
|
1774
2061
|
const { options, safeEmit, buildEvent } = ctx;
|
|
1775
|
-
return async function admitPayment(flow, request, resource, pricing, validInput) {
|
|
2062
|
+
return async function admitPayment(flow, request, resource, pricing, validInput, pipelineStart) {
|
|
2063
|
+
const support = assertRetrySupport(
|
|
2064
|
+
resource,
|
|
2065
|
+
options.store,
|
|
2066
|
+
options.deployment,
|
|
2067
|
+
request.requestId
|
|
2068
|
+
);
|
|
1776
2069
|
const provider = pickProvider(options.paymentProviders, resource.paymentMethods);
|
|
1777
2070
|
if (!provider) {
|
|
1778
2071
|
throw new CommerceError(
|
|
@@ -1790,6 +2083,15 @@ function createPaymentAdmission(ctx, authorizeAndReserve) {
|
|
|
1790
2083
|
resource,
|
|
1791
2084
|
request.requestId
|
|
1792
2085
|
);
|
|
2086
|
+
const retry = await retryGate.open(
|
|
2087
|
+
flow,
|
|
2088
|
+
resource,
|
|
2089
|
+
provider,
|
|
2090
|
+
validInput,
|
|
2091
|
+
support,
|
|
2092
|
+
pipelineStart
|
|
2093
|
+
);
|
|
2094
|
+
if (retry?.kind === "delivered") return retry;
|
|
1793
2095
|
let requirement;
|
|
1794
2096
|
try {
|
|
1795
2097
|
requirement = await provider.createRequirement({
|
|
@@ -1894,77 +2196,104 @@ function createPaymentAdmission(ctx, authorizeAndReserve) {
|
|
|
1894
2196
|
});
|
|
1895
2197
|
}
|
|
1896
2198
|
const replayKey = verification.replayKey;
|
|
1897
|
-
const
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
2199
|
+
const digest = retry?.fingerprint ?? inputDigest(validInput);
|
|
2200
|
+
if (retry !== void 0) {
|
|
2201
|
+
const stored = await retryGate.claim(
|
|
2202
|
+
flow,
|
|
2203
|
+
resource,
|
|
2204
|
+
provider,
|
|
2205
|
+
retry,
|
|
2206
|
+
verification,
|
|
2207
|
+
pipelineStart
|
|
2208
|
+
);
|
|
2209
|
+
if (stored !== void 0) return stored;
|
|
2210
|
+
}
|
|
1905
2211
|
try {
|
|
1906
|
-
const
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
...verification.payer !== void 0 ? { payer: verification.payer } : {},
|
|
1914
|
-
...verification.payee !== void 0 ? { payee: verification.payee } : {},
|
|
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
|
-
)
|
|
1924
|
-
});
|
|
1925
|
-
flow.journaled = attempt.transactionId === flow.transactionId && options.store.recordTransactionStep !== void 0;
|
|
1926
|
-
} catch (error) {
|
|
1927
|
-
const mapped = toCommerceError(
|
|
1928
|
-
error,
|
|
1929
|
-
"STORAGE_ERROR",
|
|
1930
|
-
"Payment attempt could not be recorded"
|
|
2212
|
+
const hold = await authorizeAndReserve(
|
|
2213
|
+
flow,
|
|
2214
|
+
request,
|
|
2215
|
+
resource,
|
|
2216
|
+
authProviders,
|
|
2217
|
+
requirement,
|
|
2218
|
+
validInput
|
|
1931
2219
|
);
|
|
1932
|
-
|
|
2220
|
+
try {
|
|
2221
|
+
const attempt = await options.store.reservePaymentAttempt({
|
|
2222
|
+
requestId: request.requestId,
|
|
2223
|
+
resourceId: resource.id,
|
|
2224
|
+
provider: provider.name,
|
|
2225
|
+
replayKey,
|
|
2226
|
+
amount: verification.amount,
|
|
2227
|
+
currency: verification.currency,
|
|
2228
|
+
...verification.payer !== void 0 ? { payer: verification.payer } : {},
|
|
2229
|
+
...verification.payee !== void 0 ? { payee: verification.payee } : {},
|
|
2230
|
+
...requirement.metadata?.[REUSE_REJECTED_AUTHORIZATION_METADATA_KEY] === true ? { reclaimRejected: true } : {},
|
|
2231
|
+
transaction: newTransaction(
|
|
2232
|
+
flow,
|
|
2233
|
+
resource,
|
|
2234
|
+
requirement,
|
|
2235
|
+
verification,
|
|
2236
|
+
digest,
|
|
2237
|
+
hold !== void 0 ? { ...hold.record, reservationId: hold.reservationId } : void 0
|
|
2238
|
+
)
|
|
2239
|
+
});
|
|
2240
|
+
flow.journaled = attempt.transactionId === flow.transactionId && options.store.recordTransactionStep !== void 0;
|
|
2241
|
+
} catch (error) {
|
|
2242
|
+
const mapped = toCommerceError(
|
|
2243
|
+
error,
|
|
2244
|
+
"STORAGE_ERROR",
|
|
2245
|
+
"Payment attempt could not be recorded"
|
|
2246
|
+
);
|
|
2247
|
+
await hold?.finalize("release");
|
|
2248
|
+
await safeEmit(
|
|
2249
|
+
buildEvent(flow, {
|
|
2250
|
+
type: "payment.rejected",
|
|
2251
|
+
resourceId: resource.id,
|
|
2252
|
+
adapter: request.protocol,
|
|
2253
|
+
paymentProvider: provider.name,
|
|
2254
|
+
status: "error",
|
|
2255
|
+
data: { reason: mapped.code }
|
|
2256
|
+
})
|
|
2257
|
+
);
|
|
2258
|
+
throw replayError(mapped, requirement);
|
|
2259
|
+
}
|
|
1933
2260
|
await safeEmit(
|
|
1934
2261
|
buildEvent(flow, {
|
|
1935
|
-
type: "payment.
|
|
2262
|
+
type: "payment.verified",
|
|
1936
2263
|
resourceId: resource.id,
|
|
1937
2264
|
adapter: request.protocol,
|
|
1938
2265
|
paymentProvider: provider.name,
|
|
1939
|
-
status: "
|
|
1940
|
-
data: { reason: mapped.code }
|
|
2266
|
+
status: "ok"
|
|
1941
2267
|
})
|
|
1942
2268
|
);
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
await safeEmit(
|
|
1946
|
-
buildEvent(flow, {
|
|
1947
|
-
type: "payment.verified",
|
|
2269
|
+
const merchantKey = support !== void 0 && resource.idempotency?.merchantKey === true ? paidOperationKey({
|
|
2270
|
+
deployment: support.deployment,
|
|
1948
2271
|
resourceId: resource.id,
|
|
1949
|
-
adapter: request.protocol,
|
|
1950
|
-
paymentProvider: provider.name,
|
|
1951
|
-
status: "ok"
|
|
1952
|
-
})
|
|
1953
|
-
);
|
|
1954
|
-
return {
|
|
1955
|
-
kind: "admitted",
|
|
1956
|
-
settleArgs: {
|
|
1957
|
-
flow,
|
|
1958
|
-
request,
|
|
1959
|
-
resource,
|
|
1960
|
-
provider,
|
|
1961
|
-
requirement,
|
|
1962
|
-
payment,
|
|
1963
|
-
verification,
|
|
1964
2272
|
replayKey,
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
2273
|
+
inputDigest: digest,
|
|
2274
|
+
...retry !== void 0 ? { clientKey: retry.clientKey } : {},
|
|
2275
|
+
...verification.payer !== void 0 ? { payer: verification.payer } : {}
|
|
2276
|
+
}) : void 0;
|
|
2277
|
+
return {
|
|
2278
|
+
kind: "admitted",
|
|
2279
|
+
settleArgs: {
|
|
2280
|
+
flow,
|
|
2281
|
+
request,
|
|
2282
|
+
resource,
|
|
2283
|
+
provider,
|
|
2284
|
+
requirement,
|
|
2285
|
+
payment,
|
|
2286
|
+
verification,
|
|
2287
|
+
replayKey,
|
|
2288
|
+
hold,
|
|
2289
|
+
...merchantKey !== void 0 ? { merchantKey } : {},
|
|
2290
|
+
...retry !== void 0 ? { retry } : {}
|
|
2291
|
+
}
|
|
2292
|
+
};
|
|
2293
|
+
} catch (error) {
|
|
2294
|
+
if (retry !== void 0) await retryGate.finishFailed(flow, retry);
|
|
2295
|
+
throw error;
|
|
2296
|
+
}
|
|
1968
2297
|
};
|
|
1969
2298
|
async function refusalFor(verification, requirement, request, resource) {
|
|
1970
2299
|
const ids = { requestId: request.requestId, resourceId: resource.id };
|
|
@@ -2090,6 +2419,7 @@ function createSettlement(ctx) {
|
|
|
2090
2419
|
hold
|
|
2091
2420
|
} = args;
|
|
2092
2421
|
await recordStep(flow, { kind: "settling" });
|
|
2422
|
+
flow.chargeRisk = true;
|
|
2093
2423
|
let settlement;
|
|
2094
2424
|
try {
|
|
2095
2425
|
settlement = await provider.settle({
|
|
@@ -2102,6 +2432,7 @@ function createSettlement(ctx) {
|
|
|
2102
2432
|
} catch (error) {
|
|
2103
2433
|
const notSubmitted = notSubmittedReason(error);
|
|
2104
2434
|
if (notSubmitted !== void 0) {
|
|
2435
|
+
flow.chargeRisk = false;
|
|
2105
2436
|
await finalizeHold(flow, hold, "release");
|
|
2106
2437
|
await safePersist(
|
|
2107
2438
|
flow,
|
|
@@ -2172,6 +2503,7 @@ function createSettlement(ctx) {
|
|
|
2172
2503
|
});
|
|
2173
2504
|
}
|
|
2174
2505
|
if (settlement.status !== "settled") {
|
|
2506
|
+
flow.chargeRisk = false;
|
|
2175
2507
|
await finalizeHold(flow, hold, "release");
|
|
2176
2508
|
await safePersist(
|
|
2177
2509
|
flow,
|
|
@@ -2293,7 +2625,8 @@ function createExecutionPipeline(options) {
|
|
|
2293
2625
|
const ctx = createPipelineContext(options);
|
|
2294
2626
|
const { safeEmit, safePersist, recordStep, buildEvent } = ctx;
|
|
2295
2627
|
const { settle, abandonSettlement } = createSettlement(ctx);
|
|
2296
|
-
const
|
|
2628
|
+
const retryGate = createRetryGate(ctx);
|
|
2629
|
+
const admitPayment = createPaymentAdmission(ctx, createAuthorizeAndReserve(ctx), retryGate);
|
|
2297
2630
|
async function execute(request) {
|
|
2298
2631
|
const pipelineStart = options.clock.monotonicMs();
|
|
2299
2632
|
const resource = options.resources.get(request.resourceId);
|
|
@@ -2357,12 +2690,22 @@ function createExecutionPipeline(options) {
|
|
|
2357
2690
|
}
|
|
2358
2691
|
let settleArgs;
|
|
2359
2692
|
if (resource.pricing.type === "fixed") {
|
|
2360
|
-
const admission = await admitPayment(
|
|
2361
|
-
|
|
2693
|
+
const admission = await admitPayment(
|
|
2694
|
+
flow,
|
|
2695
|
+
request,
|
|
2696
|
+
resource,
|
|
2697
|
+
resource.pricing,
|
|
2698
|
+
validInput,
|
|
2699
|
+
pipelineStart
|
|
2700
|
+
);
|
|
2701
|
+
if (admission.kind !== "admitted") return admission;
|
|
2362
2702
|
settleArgs = admission.settleArgs;
|
|
2363
2703
|
}
|
|
2364
2704
|
try {
|
|
2365
2705
|
return await settleAndDeliver(flow, resource, validInput, settleArgs, pipelineStart);
|
|
2706
|
+
} catch (error) {
|
|
2707
|
+
if (settleArgs?.retry !== void 0) await retryGate.finishFailed(flow, settleArgs.retry);
|
|
2708
|
+
throw error;
|
|
2366
2709
|
} finally {
|
|
2367
2710
|
await recordStep(flow, { kind: "completed", ...failuresOf(flow) });
|
|
2368
2711
|
}
|
|
@@ -2384,13 +2727,14 @@ function createExecutionPipeline(options) {
|
|
|
2384
2727
|
deadlineAt: backendDeadline(options.clock.now(), resource)
|
|
2385
2728
|
});
|
|
2386
2729
|
const backendStart = options.clock.monotonicMs();
|
|
2730
|
+
const idempotencyKey = request.idempotencyKey ?? settleArgs?.merchantKey;
|
|
2387
2731
|
let backendResponse;
|
|
2388
2732
|
try {
|
|
2389
2733
|
backendResponse = await options.backend.call(resource.handler, {
|
|
2390
2734
|
requestId: request.requestId,
|
|
2391
2735
|
resourceId: resource.id,
|
|
2392
2736
|
input: validInput,
|
|
2393
|
-
...
|
|
2737
|
+
...idempotencyKey !== void 0 ? { idempotencyKey } : {},
|
|
2394
2738
|
...request.backendHeaders !== void 0 ? { backendHeaders: request.backendHeaders } : {}
|
|
2395
2739
|
});
|
|
2396
2740
|
} catch (error) {
|
|
@@ -2483,6 +2827,15 @@ function createExecutionPipeline(options) {
|
|
|
2483
2827
|
transactionId: flow.transactionId
|
|
2484
2828
|
};
|
|
2485
2829
|
await saveReceipt(flow, receipt, "saveReceipt");
|
|
2830
|
+
if (settleArgs?.retry !== void 0) {
|
|
2831
|
+
await retryGate.finishDelivered(
|
|
2832
|
+
flow,
|
|
2833
|
+
settleArgs.retry,
|
|
2834
|
+
settleArgs.verification,
|
|
2835
|
+
backendResponse,
|
|
2836
|
+
receipt
|
|
2837
|
+
);
|
|
2838
|
+
}
|
|
2486
2839
|
const totalDurationMs = Math.round(options.clock.monotonicMs() - pipelineStart);
|
|
2487
2840
|
const failures = failuresOf(flow);
|
|
2488
2841
|
await safeEmit(
|
|
@@ -2856,6 +3209,7 @@ function validateResourceSchemaKeywords(id, path2, schema) {
|
|
|
2856
3209
|
// src/config/schema/resources.ts
|
|
2857
3210
|
var SUPPORTED_PROTOCOLS = new Set(PROTOCOL_NAMES);
|
|
2858
3211
|
var SUPPORTED_PAYMENT_METHODS = new Set(PAYMENT_METHOD_NAMES);
|
|
3212
|
+
var DEFAULT_REDELIVERY_RETENTION_HOURS = 24;
|
|
2859
3213
|
function normalizeResource(id, entry, protocols, x402, mpp, ap2) {
|
|
2860
3214
|
if (entry.input !== void 0) validateResourceSchemaKeywords(id, "input", entry.input);
|
|
2861
3215
|
const inputProperties = entry.input?.["properties"];
|
|
@@ -3018,6 +3372,7 @@ function normalizeResource(id, entry, protocols, x402, mpp, ap2) {
|
|
|
3018
3372
|
{ details: { path: `resources.${id}.mimeType`, resourceId: id } }
|
|
3019
3373
|
);
|
|
3020
3374
|
}
|
|
3375
|
+
const idempotency = normalizeResourceIdempotency(id, entry, paymentMethods);
|
|
3021
3376
|
const pricing = entry.pricing.type === "free" ? { type: "free" } : { type: "fixed", amount: entry.pricing.amount, currency: entry.pricing.currency };
|
|
3022
3377
|
const authorization = normalizeResourceAuthorization(id, entry, pricing, ap2);
|
|
3023
3378
|
return {
|
|
@@ -3041,7 +3396,44 @@ function normalizeResource(id, entry, protocols, x402, mpp, ap2) {
|
|
|
3041
3396
|
pricing,
|
|
3042
3397
|
exposedVia: entry.expose,
|
|
3043
3398
|
paymentMethods,
|
|
3044
|
-
...authorization !== void 0 ? { authorization } : {}
|
|
3399
|
+
...authorization !== void 0 ? { authorization } : {},
|
|
3400
|
+
...idempotency !== void 0 ? { idempotency } : {}
|
|
3401
|
+
};
|
|
3402
|
+
}
|
|
3403
|
+
function normalizeResourceIdempotency(id, entry, paymentMethods) {
|
|
3404
|
+
const raw = entry.idempotency;
|
|
3405
|
+
if (raw === void 0) return void 0;
|
|
3406
|
+
const path2 = `resources.${id}.idempotency`;
|
|
3407
|
+
const refuse = (problem, at) => new CommerceError("CONFIG_INVALID", `Resource "${id}" sets ${problem}`, {
|
|
3408
|
+
details: { path: at, resourceId: id }
|
|
3409
|
+
});
|
|
3410
|
+
if (entry.pricing.type !== "fixed") {
|
|
3411
|
+
throw refuse("idempotency, which requires fixed pricing", path2);
|
|
3412
|
+
}
|
|
3413
|
+
if (raw.merchantKey === void 0 && raw.redelivery === void 0) {
|
|
3414
|
+
throw refuse("idempotency without merchantKey or redelivery", path2);
|
|
3415
|
+
}
|
|
3416
|
+
let redelivery;
|
|
3417
|
+
if (raw.redelivery !== void 0) {
|
|
3418
|
+
const required = toBoolean(raw.redelivery.required ?? false, `${path2}.redelivery.required`);
|
|
3419
|
+
if (required && !paymentMethods.includes("x402")) {
|
|
3420
|
+
throw refuse(
|
|
3421
|
+
'idempotency.redelivery.required, which requires "x402" in payments',
|
|
3422
|
+
`${path2}.redelivery.required`
|
|
3423
|
+
);
|
|
3424
|
+
}
|
|
3425
|
+
redelivery = {
|
|
3426
|
+
retentionHours: toNumber(
|
|
3427
|
+
raw.redelivery.retentionHours ?? DEFAULT_REDELIVERY_RETENTION_HOURS,
|
|
3428
|
+
`${path2}.redelivery.retentionHours`,
|
|
3429
|
+
{ min: 1, max: MAX_REDELIVERY_RETENTION_HOURS }
|
|
3430
|
+
),
|
|
3431
|
+
required
|
|
3432
|
+
};
|
|
3433
|
+
}
|
|
3434
|
+
return {
|
|
3435
|
+
...raw.merchantKey !== void 0 ? { merchantKey: toBoolean(raw.merchantKey, `${path2}.merchantKey`) } : {},
|
|
3436
|
+
...redelivery !== void 0 ? { redelivery } : {}
|
|
3045
3437
|
};
|
|
3046
3438
|
}
|
|
3047
3439
|
var PRICING_AMOUNT_PATTERN = /^\d+(?:\.\d+)?$/;
|
|
@@ -3589,7 +3981,12 @@ var SECRET_FIELD_NAMES = [
|
|
|
3589
3981
|
"adminToken",
|
|
3590
3982
|
"token"
|
|
3591
3983
|
];
|
|
3592
|
-
var SECRET_HEADERS = [
|
|
3984
|
+
var SECRET_HEADERS = [
|
|
3985
|
+
"authorization",
|
|
3986
|
+
PAYMENT_HEADER,
|
|
3987
|
+
AUTHORIZATION_HEADER,
|
|
3988
|
+
"idempotency-key"
|
|
3989
|
+
];
|
|
3593
3990
|
var REDACT_PATHS = [
|
|
3594
3991
|
...SECRET_HEADERS.map((name) => `req.headers[${JSON.stringify(name)}]`),
|
|
3595
3992
|
...SECRET_FIELD_NAMES,
|
|
@@ -3811,6 +4208,13 @@ async function alignHold(transaction, target, deps) {
|
|
|
3811
4208
|
return holdEntry(transaction, target, true);
|
|
3812
4209
|
}
|
|
3813
4210
|
|
|
4211
|
+
// src/core/idempotency-key.ts
|
|
4212
|
+
var MAX_IDEMPOTENCY_KEY_LENGTH = 255;
|
|
4213
|
+
var USABLE_KEY = new RegExp(`^[\\x20-\\x7e]{1,${MAX_IDEMPOTENCY_KEY_LENGTH}}$`);
|
|
4214
|
+
function isUsableIdempotencyKey(value) {
|
|
4215
|
+
return USABLE_KEY.test(value);
|
|
4216
|
+
}
|
|
4217
|
+
|
|
3814
4218
|
// src/gateway/public-resource.ts
|
|
3815
4219
|
function toPublicResource(resource) {
|
|
3816
4220
|
return {
|
|
@@ -4295,6 +4699,7 @@ async function handleInvoke(request, reply, options) {
|
|
|
4295
4699
|
paymentMethod = resource.paymentMethods[0];
|
|
4296
4700
|
const paymentValue = paymentProof(request, paymentMethod);
|
|
4297
4701
|
const payment = paymentValue !== void 0 && paymentMethod !== void 0 ? { method: paymentMethod, payload: paymentValue } : void 0;
|
|
4702
|
+
const retryKey = paymentMethod === "mpp" && resource.idempotency?.redelivery !== void 0 ? mppRetryKey(request, resourceId) : void 0;
|
|
4298
4703
|
const authorization = parseAuthorizationHeader(
|
|
4299
4704
|
request.headers[AUTHORIZATION_HEADER],
|
|
4300
4705
|
request.id
|
|
@@ -4307,6 +4712,7 @@ async function handleInvoke(request, reply, options) {
|
|
|
4307
4712
|
protocol: "http",
|
|
4308
4713
|
receivedAt: options.clock.nowIso(),
|
|
4309
4714
|
...payment !== void 0 ? { payment } : {},
|
|
4715
|
+
...retryKey !== void 0 ? { retryKey } : {},
|
|
4310
4716
|
...authorization !== void 0 ? { authorization } : {},
|
|
4311
4717
|
...digest !== void 0 ? { metadata: { [CONTENT_DIGEST_METADATA_KEY]: digest } } : {}
|
|
4312
4718
|
};
|
|
@@ -4345,11 +4751,13 @@ async function handleInvoke(request, reply, options) {
|
|
|
4345
4751
|
encodeHeaderDocument(settlementResponse(outcome.payment))
|
|
4346
4752
|
);
|
|
4347
4753
|
const receipt = outcome.payment.metadata?.["receipt"];
|
|
4348
|
-
|
|
4754
|
+
const success = outcome.backendStatus >= 200 && outcome.backendStatus < 300;
|
|
4755
|
+
if (outcome.payment.provider === "mpp" && typeof receipt === "string" && (success || outcome.redelivered !== true)) {
|
|
4349
4756
|
reply.header("payment-receipt", receipt);
|
|
4350
4757
|
}
|
|
4351
4758
|
reply.header("cache-control", "private");
|
|
4352
4759
|
}
|
|
4760
|
+
if (outcome.redelivered === true) reply.header("idempotent-replayed", "true");
|
|
4353
4761
|
const contentType = relayedContentType(outcome.headers?.["content-type"], outcome.body);
|
|
4354
4762
|
if (contentType !== void 0) reply.type(contentType);
|
|
4355
4763
|
if (typeof outcome.body === "string") {
|
|
@@ -4389,9 +4797,14 @@ var MPP_PROBLEM_CODES = /* @__PURE__ */ new Set([
|
|
|
4389
4797
|
]);
|
|
4390
4798
|
function sendInvokeError(reply, error, paymentMethod) {
|
|
4391
4799
|
const details = error.details;
|
|
4800
|
+
const reason = typeof details?.["reason"] === "string" ? details["reason"] : void 0;
|
|
4392
4801
|
if (PROVIDER_UNAVAILABLE_CODES.has(error.code)) {
|
|
4393
4802
|
reply.header("retry-after", String(PROVIDER_RETRY_AFTER_SECONDS));
|
|
4394
4803
|
}
|
|
4804
|
+
const retryAfter = details?.["retryAfterSeconds"];
|
|
4805
|
+
if (typeof retryAfter === "number" && Number.isSafeInteger(retryAfter) && retryAfter >= 0) {
|
|
4806
|
+
reply.header("retry-after", String(retryAfter));
|
|
4807
|
+
}
|
|
4395
4808
|
const settled = settlementResponseFromDetails(details);
|
|
4396
4809
|
if (settled !== void 0) {
|
|
4397
4810
|
reply.header(PAYMENT_RESPONSE_HEADER, encodeHeaderDocument(settled));
|
|
@@ -4415,12 +4828,12 @@ function sendInvokeError(reply, error, paymentMethod) {
|
|
|
4415
4828
|
reply.header("cache-control", "no-store");
|
|
4416
4829
|
}
|
|
4417
4830
|
const envelope = toErrorEnvelope(error);
|
|
4418
|
-
if (paymentMethod === "mpp" && MPP_PROBLEM_CODES.has(error.code)) {
|
|
4831
|
+
if (paymentMethod === "mpp" && (MPP_PROBLEM_CODES.has(error.code) || reason?.startsWith("payment_identifier_") === true)) {
|
|
4419
4832
|
const { status: _envelopeStatus, ...members } = envelope;
|
|
4420
|
-
const
|
|
4421
|
-
reply.header("content-type", "application/problem+json").status(
|
|
4422
|
-
...mppProblem(error.code,
|
|
4423
|
-
status:
|
|
4833
|
+
const problemStatus = reason === "payment_identifier_conflict" ? 422 : error.httpStatus;
|
|
4834
|
+
reply.header("content-type", "application/problem+json").status(problemStatus).send({
|
|
4835
|
+
...mppProblem(error.code, problemStatus, reason),
|
|
4836
|
+
status: problemStatus,
|
|
4424
4837
|
// The reason token stays in `message` and `details.reason`
|
|
4425
4838
|
detail: mppProblemDetail(reason, error.message),
|
|
4426
4839
|
...members
|
|
@@ -4430,6 +4843,21 @@ function sendInvokeError(reply, error, paymentMethod) {
|
|
|
4430
4843
|
const status = paymentMethod === "x402" ? x402RefusalStatus(error.code, error.httpStatus, details?.["reason"]) : error.httpStatus;
|
|
4431
4844
|
reply.status(status).send(envelope);
|
|
4432
4845
|
}
|
|
4846
|
+
var SF_STRING = /^"((?:[\x20\x21\x23-\x5b\x5d-\x7e]|\\["\\])*)"$/;
|
|
4847
|
+
function mppRetryKey(request, resourceId) {
|
|
4848
|
+
const value = request.headers["idempotency-key"];
|
|
4849
|
+
if (value === void 0) return void 0;
|
|
4850
|
+
if (typeof value === "string") {
|
|
4851
|
+
const trimmed = value.trim();
|
|
4852
|
+
const key = trimmed.startsWith('"') ? SF_STRING.exec(trimmed)?.[1]?.replace(/\\(["\\])/g, "$1") : trimmed;
|
|
4853
|
+
if (key !== void 0 && isUsableIdempotencyKey(key)) return key;
|
|
4854
|
+
}
|
|
4855
|
+
throw new CommerceError(
|
|
4856
|
+
"INPUT_INVALID",
|
|
4857
|
+
"The Idempotency-Key header must be 1 to 255 printable ASCII characters",
|
|
4858
|
+
{ requestId: request.id, resourceId, details: { reason: "payment_identifier_invalid" } }
|
|
4859
|
+
);
|
|
4860
|
+
}
|
|
4433
4861
|
function paymentProof(request, method) {
|
|
4434
4862
|
if (method === "mpp") {
|
|
4435
4863
|
const value2 = request.headers.authorization;
|
|
@@ -4490,6 +4918,25 @@ function withProviderBackedMethodsFirst(resource, providers) {
|
|
|
4490
4918
|
];
|
|
4491
4919
|
return ordered.some((method, i) => method !== resource.paymentMethods[i]) ? { ...resource, paymentMethods: ordered } : resource;
|
|
4492
4920
|
}
|
|
4921
|
+
async function recoverPaymentKeys(store, logger) {
|
|
4922
|
+
if (!hasMethodGroup(store, "idempotency_claims") || !hasMethodGroup(store, "response_redelivery")) {
|
|
4923
|
+
return;
|
|
4924
|
+
}
|
|
4925
|
+
let recovered;
|
|
4926
|
+
try {
|
|
4927
|
+
recovered = await store.recoverIdempotencyKeys({
|
|
4928
|
+
release: false,
|
|
4929
|
+
endpointPrefix: PAYMENT_KEY_ENDPOINT_PREFIX
|
|
4930
|
+
});
|
|
4931
|
+
} catch (error) {
|
|
4932
|
+
throw new CommerceError("STORAGE_ERROR", "Payment retry keys could not be recovered", {
|
|
4933
|
+
cause: error
|
|
4934
|
+
});
|
|
4935
|
+
}
|
|
4936
|
+
if (recovered > 0) {
|
|
4937
|
+
logger.warn({ recovered }, "Payment retry keys left in flight are now unresolved");
|
|
4938
|
+
}
|
|
4939
|
+
}
|
|
4493
4940
|
async function createGateway(options) {
|
|
4494
4941
|
const clock = options.clock ?? systemClock;
|
|
4495
4942
|
const ids = options.ids ?? createDefaultIdGenerator();
|
|
@@ -4501,6 +4948,10 @@ async function createGateway(options) {
|
|
|
4501
4948
|
(resource) => withProviderBackedMethodsFirst(resource, options.paymentProviders)
|
|
4502
4949
|
)
|
|
4503
4950
|
);
|
|
4951
|
+
for (const resource of resources.list()) {
|
|
4952
|
+
assertRetrySupport(resource, options.store, options.config.merchant.publicBaseUrl);
|
|
4953
|
+
}
|
|
4954
|
+
await recoverPaymentKeys(options.store, logger);
|
|
4504
4955
|
const events = createStoreEventSink({ store: options.store, logger });
|
|
4505
4956
|
const pipeline = createExecutionPipeline({
|
|
4506
4957
|
resources,
|
|
@@ -4511,7 +4962,8 @@ async function createGateway(options) {
|
|
|
4511
4962
|
events,
|
|
4512
4963
|
logger,
|
|
4513
4964
|
clock,
|
|
4514
|
-
ids
|
|
4965
|
+
ids,
|
|
4966
|
+
deployment: options.config.merchant.publicBaseUrl
|
|
4515
4967
|
});
|
|
4516
4968
|
const server = Fastify({
|
|
4517
4969
|
// Same cap as adapter mounts, which enforce it on the socket instead
|
|
@@ -5011,7 +5463,8 @@ function paymentFailureMetadata(error, network) {
|
|
|
5011
5463
|
[X402_PAYMENT_RECEIPTS_KEY]: [settled]
|
|
5012
5464
|
};
|
|
5013
5465
|
}
|
|
5014
|
-
const
|
|
5466
|
+
const reason = error.details?.["reason"];
|
|
5467
|
+
const code = error.code.startsWith("PAYMENT_") || typeof reason === "string" && reason.startsWith("payment_identifier_") ? x402ErrorCode(error.code, reason, error.details?.["network"]) : error.code.toLowerCase();
|
|
5015
5468
|
const failure = settlementFailure(error.details);
|
|
5016
5469
|
const receipt = failure["network"] === "" && network !== void 0 ? { ...failure, network } : failure;
|
|
5017
5470
|
return {
|
|
@@ -5315,6 +5768,17 @@ async function resumePayment(context, pendingPayments, id, params) {
|
|
|
5315
5768
|
)
|
|
5316
5769
|
);
|
|
5317
5770
|
}
|
|
5771
|
+
function withoutRetryDelay(error) {
|
|
5772
|
+
if (error.details?.["reason"] !== "payment_identifier_in_flight") return error;
|
|
5773
|
+
const { retryAfterSeconds: _delay, ...details } = error.details;
|
|
5774
|
+
return new CommerceError(error.code, error.message, {
|
|
5775
|
+
httpStatus: error.httpStatus,
|
|
5776
|
+
retryable: false,
|
|
5777
|
+
details,
|
|
5778
|
+
...error.requestId !== void 0 ? { requestId: error.requestId } : {},
|
|
5779
|
+
...error.resourceId !== void 0 ? { resourceId: error.resourceId } : {}
|
|
5780
|
+
});
|
|
5781
|
+
}
|
|
5318
5782
|
async function payPending(context, pending, payload, identity) {
|
|
5319
5783
|
const requestId = context.ids.next("a2a");
|
|
5320
5784
|
const request = {
|
|
@@ -5343,16 +5807,19 @@ async function payPending(context, pending, payload, identity) {
|
|
|
5343
5807
|
}
|
|
5344
5808
|
error = new CommerceError("PAYMENT_INVALID", "The payment was not accepted.", { requestId });
|
|
5345
5809
|
} catch (err) {
|
|
5346
|
-
error = toCommerceError(err);
|
|
5810
|
+
error = withoutRetryDelay(toCommerceError(err));
|
|
5347
5811
|
context.logger.warn(
|
|
5348
5812
|
{ resourceId: pending.resourceId, requestId, err: toLogInfo(error) },
|
|
5349
5813
|
"a2a adapter: x402 extension payment failed"
|
|
5350
5814
|
);
|
|
5351
5815
|
}
|
|
5352
5816
|
const metadata = paymentFailureMetadata(error, pending.network);
|
|
5817
|
+
const reason = error.details?.["reason"];
|
|
5353
5818
|
let text = "Payment failed.";
|
|
5354
5819
|
if (metadata[X402_PAYMENT_STATUS_KEY] === "payment-completed") {
|
|
5355
5820
|
text = "Payment settled, but the resource could not be delivered.";
|
|
5821
|
+
} else if (typeof reason === "string" && reason.startsWith("payment_identifier_")) {
|
|
5822
|
+
text = error.message;
|
|
5356
5823
|
} else if (!error.code.startsWith("PAYMENT_")) {
|
|
5357
5824
|
text = "The resource could not be delivered.";
|
|
5358
5825
|
}
|
|
@@ -5842,7 +6309,7 @@ function sha2562(value) {
|
|
|
5842
6309
|
|
|
5843
6310
|
// src/protocols/acp/idempotency/store.ts
|
|
5844
6311
|
var SCHEMA_VERSION = 2;
|
|
5845
|
-
var ACP_MAX_IDEMPOTENCY_KEY_LENGTH =
|
|
6312
|
+
var ACP_MAX_IDEMPOTENCY_KEY_LENGTH = MAX_IDEMPOTENCY_KEY_LENGTH;
|
|
5846
6313
|
function createAcpIdempotencyStore(options) {
|
|
5847
6314
|
const logger = options.logger ?? NOOP_LOGGER;
|
|
5848
6315
|
const now = options.now ?? (() => Date.now());
|
|
@@ -10263,9 +10730,6 @@ function forwardedHeaders(req, requestId) {
|
|
|
10263
10730
|
}
|
|
10264
10731
|
return forwarded;
|
|
10265
10732
|
}
|
|
10266
|
-
function isUsableIdempotencyKey(value) {
|
|
10267
|
-
return value.length > 0 && value.length <= ACP_MAX_IDEMPOTENCY_KEY_LENGTH && isVisibleAscii(value);
|
|
10268
|
-
}
|
|
10269
10733
|
function normalizeRequestId(value) {
|
|
10270
10734
|
if (value === void 0) return void 0;
|
|
10271
10735
|
const trimmed = value.trim().slice(0, ACP_MAX_REQUEST_ID_LENGTH);
|
|
@@ -10620,7 +11084,7 @@ var AcpProtocolAdapter = class {
|
|
|
10620
11084
|
const release = merchantIdempotent === true;
|
|
10621
11085
|
const store = this.store;
|
|
10622
11086
|
if (hasMethodGroup(store, "idempotency_claims")) {
|
|
10623
|
-
const recovered = await store.recoverIdempotencyKeys({ release });
|
|
11087
|
+
const recovered = await store.recoverIdempotencyKeys({ release, endpointPrefix: "/" });
|
|
10624
11088
|
warnOrphanedClaims(context.logger, recovered, release);
|
|
10625
11089
|
return backendOverReceiptStore(store, context.clock, retentionHours);
|
|
10626
11090
|
}
|
|
@@ -11433,23 +11897,37 @@ function createHoldMethods(db, clock) {
|
|
|
11433
11897
|
}
|
|
11434
11898
|
|
|
11435
11899
|
// src/storage/receipts/idempotency.ts
|
|
11900
|
+
var ENDPOINT_HAS_PREFIX = "substr(endpoint, 1, length(@prefix)) = @prefix";
|
|
11436
11901
|
var scopeParams = (scope) => ({
|
|
11437
11902
|
deployment: scope.deployment,
|
|
11438
11903
|
endpoint: scope.endpoint,
|
|
11439
11904
|
idempotency_key: scope.key
|
|
11440
11905
|
});
|
|
11906
|
+
function claimOf(row, fingerprint) {
|
|
11907
|
+
if (row.fingerprint !== fingerprint) return { kind: "conflict" };
|
|
11908
|
+
const body = row.body_json === null ? null : JSON.parse(row.body_json);
|
|
11909
|
+
if (row.state === "completed") return { kind: "replay", status: row.status ?? 500, body };
|
|
11910
|
+
const kind = row.state === "unresolved" ? "unresolved" : "in-flight";
|
|
11911
|
+
const owner = isRecord(body) ? body["owner"] : void 0;
|
|
11912
|
+
return typeof owner === "string" ? { kind, owner } : { kind };
|
|
11913
|
+
}
|
|
11914
|
+
function hasExpired(row, endpoint, now) {
|
|
11915
|
+
if (row.expires_at > now) return false;
|
|
11916
|
+
return row.state === "completed" || row.state === "unresolved" && endpoint.startsWith(PAYMENT_KEY_ENDPOINT_PREFIX);
|
|
11917
|
+
}
|
|
11441
11918
|
function createIdempotencyMethods(db, clock) {
|
|
11442
11919
|
const SCOPE = "deployment = @deployment AND endpoint = @endpoint AND idempotency_key = @idempotency_key";
|
|
11443
11920
|
const selectClaim = db.prepare(
|
|
11444
|
-
`SELECT state, fingerprint, status, body_json FROM idempotency_keys WHERE ${SCOPE}`
|
|
11921
|
+
`SELECT state, fingerprint, status, body_json, expires_at FROM idempotency_keys WHERE ${SCOPE}`
|
|
11445
11922
|
);
|
|
11446
11923
|
const insertClaim = db.prepare(
|
|
11447
11924
|
`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)`
|
|
11925
|
+
(deployment, endpoint, idempotency_key, fingerprint, state, body_json, created_at, expires_at)
|
|
11926
|
+
VALUES (@deployment, @endpoint, @idempotency_key, @fingerprint, 'in_flight', @body_json, @created_at, @expires_at)`
|
|
11450
11927
|
);
|
|
11451
|
-
const
|
|
11452
|
-
|
|
11928
|
+
const expireFinished = db.prepare(
|
|
11929
|
+
`DELETE FROM idempotency_keys WHERE expires_at <= @now
|
|
11930
|
+
AND (state = 'completed' OR (state = 'unresolved' AND ${ENDPOINT_HAS_PREFIX}))`
|
|
11453
11931
|
);
|
|
11454
11932
|
const completeClaim = db.prepare(
|
|
11455
11933
|
`UPDATE idempotency_keys SET state = 'completed', status = @status, body_json = @body_json
|
|
@@ -11459,42 +11937,46 @@ function createIdempotencyMethods(db, clock) {
|
|
|
11459
11937
|
`UPDATE idempotency_keys SET state = 'unresolved' WHERE ${SCOPE}`
|
|
11460
11938
|
);
|
|
11461
11939
|
const deleteClaim = db.prepare(`DELETE FROM idempotency_keys WHERE ${SCOPE}`);
|
|
11462
|
-
const
|
|
11940
|
+
const IN_FLIGHT = `state = 'in_flight' AND ${ENDPOINT_HAS_PREFIX}`;
|
|
11941
|
+
const releaseInFlight = db.prepare(`DELETE FROM idempotency_keys WHERE ${IN_FLIGHT}`);
|
|
11463
11942
|
const unresolveInFlight = db.prepare(
|
|
11464
|
-
|
|
11943
|
+
`UPDATE idempotency_keys SET state = 'unresolved' WHERE ${IN_FLIGHT}`
|
|
11465
11944
|
);
|
|
11466
11945
|
const claim = db.transaction(
|
|
11467
|
-
(scope, fingerprint, expiresAt) => {
|
|
11946
|
+
(scope, fingerprint, expiresAt, owner) => {
|
|
11468
11947
|
const now = clock.nowIso();
|
|
11469
|
-
|
|
11948
|
+
expireFinished.run({ now, prefix: PAYMENT_KEY_ENDPOINT_PREFIX });
|
|
11470
11949
|
const existing = selectClaim.get(scopeParams(scope));
|
|
11471
11950
|
if (existing === void 0) {
|
|
11472
11951
|
insertClaim.run({
|
|
11473
11952
|
...scopeParams(scope),
|
|
11474
11953
|
fingerprint,
|
|
11954
|
+
body_json: owner !== void 0 ? JSON.stringify({ owner }) : null,
|
|
11475
11955
|
created_at: now,
|
|
11476
11956
|
expires_at: expiresAt
|
|
11477
11957
|
});
|
|
11478
11958
|
return { kind: "reserved" };
|
|
11479
11959
|
}
|
|
11480
|
-
|
|
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
|
-
};
|
|
11960
|
+
return claimOf(existing, fingerprint);
|
|
11488
11961
|
}
|
|
11489
11962
|
);
|
|
11490
11963
|
return {
|
|
11491
|
-
async claimIdempotencyKey(scope, fingerprint, expiresAt) {
|
|
11964
|
+
async claimIdempotencyKey(scope, fingerprint, expiresAt, owner) {
|
|
11492
11965
|
try {
|
|
11493
|
-
return claim.immediate(scope, fingerprint, storedIso(expiresAt, "expiresAt"));
|
|
11966
|
+
return claim.immediate(scope, fingerprint, storedIso(expiresAt, "expiresAt"), owner);
|
|
11494
11967
|
} catch (err) {
|
|
11495
11968
|
throw toCommerceError(err, "STORAGE_ERROR", "Failed to claim idempotency key");
|
|
11496
11969
|
}
|
|
11497
11970
|
},
|
|
11971
|
+
async getIdempotencyKey(scope, fingerprint) {
|
|
11972
|
+
try {
|
|
11973
|
+
const existing = selectClaim.get(scopeParams(scope));
|
|
11974
|
+
if (existing === void 0) return void 0;
|
|
11975
|
+
return hasExpired(existing, scope.endpoint, clock.nowIso()) ? void 0 : claimOf(existing, fingerprint);
|
|
11976
|
+
} catch (err) {
|
|
11977
|
+
throw toCommerceError(err, "STORAGE_ERROR", "Failed to read idempotency key");
|
|
11978
|
+
}
|
|
11979
|
+
},
|
|
11498
11980
|
async updateIdempotencyKey(scope, update) {
|
|
11499
11981
|
try {
|
|
11500
11982
|
switch (update.kind) {
|
|
@@ -11516,9 +11998,10 @@ function createIdempotencyMethods(db, clock) {
|
|
|
11516
11998
|
throw toCommerceError(err, "STORAGE_ERROR", "Failed to update idempotency key");
|
|
11517
11999
|
}
|
|
11518
12000
|
},
|
|
11519
|
-
async recoverIdempotencyKeys(
|
|
12001
|
+
async recoverIdempotencyKeys({ release, endpointPrefix = "" }) {
|
|
11520
12002
|
try {
|
|
11521
|
-
|
|
12003
|
+
const recover = release ? releaseInFlight : unresolveInFlight;
|
|
12004
|
+
return recover.run({ prefix: endpointPrefix }).changes;
|
|
11522
12005
|
} catch (err) {
|
|
11523
12006
|
throw toCommerceError(err, "STORAGE_ERROR", "Failed to recover idempotency keys");
|
|
11524
12007
|
}
|
|
@@ -12040,7 +12523,9 @@ function storeOn(db, options) {
|
|
|
12040
12523
|
`SELECT COUNT(*) AS count FROM authorization_holds h WHERE ${ORPHAN_HOLD_WHERE}`
|
|
12041
12524
|
);
|
|
12042
12525
|
const countUnresolvedKeysStmt = db.prepare(
|
|
12043
|
-
|
|
12526
|
+
`SELECT COUNT(*) FILTER (WHERE ${ENDPOINT_HAS_PREFIX} AND expires_at > @now) AS payment,
|
|
12527
|
+
COUNT(*) FILTER (WHERE NOT ${ENDPOINT_HAS_PREFIX}) AS other
|
|
12528
|
+
FROM idempotency_keys WHERE state = 'unresolved'`
|
|
12044
12529
|
);
|
|
12045
12530
|
const countLiveTasksStmt = db.prepare(
|
|
12046
12531
|
"SELECT COUNT(*) AS count FROM pending_tasks WHERE expires_at > ?"
|
|
@@ -12291,10 +12776,15 @@ function storeOn(db, options) {
|
|
|
12291
12776
|
unresolvedTransactions[state] = (unresolvedTransactions[state] ?? 0) + 1;
|
|
12292
12777
|
}
|
|
12293
12778
|
const orphansBefore = new Date(Date.parse(now) - orphanHoldMinAgeMs).toISOString();
|
|
12779
|
+
const unresolvedKeys = countUnresolvedKeysStmt.get({
|
|
12780
|
+
prefix: PAYMENT_KEY_ENDPOINT_PREFIX,
|
|
12781
|
+
now
|
|
12782
|
+
});
|
|
12294
12783
|
return {
|
|
12295
12784
|
unresolvedTransactions,
|
|
12296
12785
|
orphanHolds: countOrphanHoldsStmt.get(orphansBefore)?.count ?? 0,
|
|
12297
|
-
unresolvedIdempotencyKeys:
|
|
12786
|
+
unresolvedIdempotencyKeys: unresolvedKeys?.other ?? 0,
|
|
12787
|
+
unresolvedPaymentKeys: unresolvedKeys?.payment ?? 0,
|
|
12298
12788
|
unexpiredPendingTasks: countLiveTasksStmt.get(now)?.count ?? 0,
|
|
12299
12789
|
legacyImports: legacyImportsStmt.all().map((row) => ({
|
|
12300
12790
|
source: row.source,
|