@devlab.group/agent-commerce 2.6.0 → 2.7.1
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-M6MQ3FYS.js → chunk-5AO5N2XY.js} +11 -5
- package/dist/chunk-5AO5N2XY.js.map +1 -0
- package/dist/{chunk-DRLBML7Z.js → chunk-5VW32JPV.js} +191 -78
- package/dist/chunk-5VW32JPV.js.map +1 -0
- 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-IGXQMAKM.js +8 -0
- package/dist/{chunk-M6BSXXTF.js.map → chunk-IGXQMAKM.js.map} +1 -1
- package/dist/chunk-IWXVQYG5.js +6 -0
- package/dist/chunk-IWXVQYG5.js.map +1 -0
- 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/cli/{ap2-2YMYA2H6.js → ap2-NTYL7H4I.js} +10 -11
- package/dist/cli/ap2-NTYL7H4I.js.map +1 -0
- package/dist/cli/chunk-2M2RF3CT.js +8 -0
- package/dist/cli/{chunk-4KLYFXMW.js.map → chunk-2M2RF3CT.js.map} +1 -1
- 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-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-NSYSMDQN.js → chunk-A42BCWZ2.js} +57 -29
- package/dist/cli/chunk-A42BCWZ2.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-YOF7IK4V.js → chunk-EVCIEKHN.js} +193 -80
- package/dist/cli/chunk-EVCIEKHN.js.map +1 -0
- package/dist/cli/{chunk-YWG2ZN3L.js → chunk-FETTSOMT.js} +12 -6
- package/dist/cli/chunk-FETTSOMT.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-AZL7RPFU.js → chunk-GBBG66O6.js} +77 -16
- package/dist/cli/chunk-GBBG66O6.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-DHFMIBPG.js → chunk-MBPOKPQM.js} +6 -6
- package/dist/cli/{chunk-DHFMIBPG.js.map → chunk-MBPOKPQM.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-TFV3K6YS.js → chunk-VSSSU4AU.js} +3 -3
- package/dist/cli/{chunk-TFV3K6YS.js.map → chunk-VSSSU4AU.js.map} +1 -1
- package/dist/cli/config-ODN4IEMZ.js +13 -0
- package/dist/cli/{config-3K65QJ22.js.map → config-ODN4IEMZ.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-V27OKTOV.js} +7 -7
- package/dist/cli/{mcp-6F64A7KE.js.map → mcp-V27OKTOV.js.map} +1 -1
- package/dist/cli/payment-providers-SUATT75K.js +6 -0
- package/dist/cli/{payment-providers-2ITS6KNR.js.map → payment-providers-SUATT75K.js.map} +1 -1
- package/dist/cli/{provider-5BGG5YKQ.js → provider-C3QDAXMR.js} +9 -9
- package/dist/cli/{provider-5BGG5YKQ.js.map → provider-C3QDAXMR.js.map} +1 -1
- package/dist/cli/receipts-ZS3VZ2D4.js +9 -0
- package/dist/cli/{receipts-I4IIE7U6.js.map → receipts-ZS3VZ2D4.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-WYFZUO5D.js} +142 -46
- package/dist/cli/run-WYFZUO5D.js.map +1 -0
- package/dist/cli/{svm-KDSPDFJG.js → svm-NBZY7H6W.js} +9 -6
- package/dist/cli/svm-NBZY7H6W.js.map +1 -0
- package/dist/cli/{x402-4LPIIELI.js → x402-UGLZ3LA7.js} +11 -10
- package/dist/cli/x402-UGLZ3LA7.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 +708 -181
- 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-DQwbKhnc.d.ts} +25 -8
- package/dist/{svm-KNC3PHMS.js → svm-4HR5OEP7.js} +9 -6
- package/dist/svm-4HR5OEP7.js.map +1 -0
- 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/svm-KDSPDFJG.js.map +0 -1
- package/dist/cli/x402-4LPIIELI.js.map +0 -1
- package/dist/svm-KNC3PHMS.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/config/env.ts","../../src/config/schema/values.ts","../../src/config/schema/acp.ts","../../src/config/schema/ap2.ts","../../src/config/schema/x402.ts","../../src/config/schema/mpp.ts","../../src/config/schema/raw.ts","../../src/config/schema/backend.ts","../../src/config/schema/resource-schema.ts","../../src/config/schema/resources.ts","../../src/config/schema/normalize.ts","../../src/config/schema/index.ts","../../src/config/load.ts"],"names":["path","options","fs","parseYaml"],"mappings":";;;;;;;;;;;;;;;;AAqBA,IAAM,mBAAA,GAAsB,6CAAA;AAG5B,IAAM,WAAA,GAAc,eAAA;AAGpB,IAAM,eAAA,GAAkB,0CAAA;AAGxB,IAAM,kBAAA,GAAqB,gBAAA;AAEpB,SAAS,aAAA,CAAc,KAAA,EAAgB,GAAA,EAAwBA,KAAAA,GAAO,GAAA,EAAc;AACzF,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,IAAA,OAAO,gBAAA,CAAiB,KAAA,EAAO,GAAA,EAAKA,KAAI,CAAA;AAAA,EAC1C;AACA,EAAA,IAAI,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA,EAAG;AACx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AAA,CAAA;AAAA,IACvB,OAAA,EAAS;AAAA,MACP,eAAe,KAAA,CAAM,IAAA;AAAA,MACrB,GAAI,KAAA,KAAU,MAAA,GAAY,EAAC,GAAI,EAAE,IAAA,EAAM,KAAA,CAAM,IAAA,EAAM,MAAA,EAAQ,KAAA,CAAM,GAAA;AAAI;AACvE,GACF;AACF;AAEA,SAAS,iBAAA,CACP,YAAA,EACA,GAAA,EACA,GAAA,EACQ;AACR,EAAA,IAAI,YAAA,EAAc,OAAY,IAAA,CAAA,OAAA,CAAQ,GAAA,EAAK,YAAY,CAAA;AACvD,EAAA,MAAM,OAAA,GAAU,IAAI,mBAAmB,CAAA;AACvC,EAAA,IAAI,OAAA,EAAS,OAAY,IAAA,CAAA,OAAA,CAAQ,GAAA,EAAK,OAAO,CAAA;AAC7C,EAAA,OAAY,IAAA,CAAA,OAAA,CAAQ,KAAK,uBAAuB,CAAA;AAClD","file":"chunk-AZL7RPFU.js","sourcesContent":["/**\n * `${VAR}` / `${VAR:-default}` substitution over a parsed YAML value.\n *\n * Only string leaves change; the caller coerces numeric and boolean strings\n * afterwards. `${VAR}` requires `VAR` in `env`, where an empty string counts as\n * present. `${VAR:-default}` uses `default` when `VAR` is absent or empty, as a\n * shell does. An unresolved placeholder fails config loading, so startup never\n * proceeds with a missing secret. There is no escape for a literal `${NAME}`.\n *\n * Anything else brace-shaped is refused, including nesting (`${A:-${B}}`) and\n * shell forms (`${VAR-x}`, `${VAR:=x}`, `${VAR:?x}`) that would otherwise load\n * as literal text: `adminToken: ${ADMIN_TOKEN-fallback}` would make that\n * literal the ledger credential. A bare `$VAR` is left alone, so values may\n * contain a dollar sign.\n *\n * The template rules are checked before substitution, and errors name the\n * variable and the config path, never a resolved value.\n */\nimport { CommerceError } from '../core';\nimport { isRecord } from '../core/is-record';\n\nconst PLACEHOLDER_PATTERN = /\\$\\{([A-Za-z_][A-Za-z0-9_]*)(:-([^}]*))?\\}/g;\n\n// An innermost brace token: `${`, then no braces, then `}`\nconst BRACE_TOKEN = /\\$\\{[^{}]*\\}/g;\n\n// PLACEHOLDER_PATTERN's grammar, anchored, for validating one token\nconst SUPPORTED_TOKEN = /^\\$\\{[A-Za-z_][A-Za-z0-9_]*(:-[^}]*)?\\}$/;\n\n// A placeholder whose default segment opens another placeholder\nconst NESTED_PLACEHOLDER = /\\$\\{[^{}]*\\$\\{/;\n\nexport function substituteEnv(value: unknown, env: NodeJS.ProcessEnv, path = '$'): unknown {\n if (typeof value === 'string') {\n return substituteString(value, env, path);\n }\n if (Array.isArray(value)) {\n return value.map((entry, index) => substituteEnv(entry, env, `${path}[${index}]`));\n }\n if (isRecord(value)) {\n const result: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n result[key] = substituteEnv(entry, env, `${path}.${key}`);\n }\n return result;\n }\n return value;\n}\n\nfunction substituteString(value: string, env: NodeJS.ProcessEnv, path: string): string {\n assertTemplateIsSupported(value, path);\n return substituteOnce(value, env, path);\n}\n\n/**\n * Refuses a template this module cannot honor, before any substitution runs.\n *\n * For `${A:-${B}}`, `[^}]*` cannot span the inner `}`, so the match consumes\n * `${A:-${B` and leaves a stray `}`. With `A` set, substitution would succeed\n * and append that `}` to the value unnoticed, so `adminToken` would become a\n * credential the operator does not hold.\n */\nfunction assertTemplateIsSupported(value: string, path: string): void {\n if (NESTED_PLACEHOLDER.test(value)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration value at \"${path}\" nests placeholders (e.g. \"\\${A:-\\${B}}\"), which is not supported: the inner one is not resolved and its closing brace ends up in the value. Use a plain default, or set the variable.`,\n { details: { path } },\n );\n }\n\n for (const [token] of value.matchAll(BRACE_TOKEN)) {\n if (SUPPORTED_TOKEN.test(token)) continue;\n // Quotes the token, not the value; before substitution it holds no secret\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration value at \"${path}\" contains \"${token}\", which is not a supported placeholder. Only \"\\${VAR}\" and \"\\${VAR:-default}\" are recognized; shell forms such as \"\\${VAR-default}\", \"\\${VAR:=default}\" and \"\\${VAR:?message}\" would load as literal text.`,\n { details: { path, token } },\n );\n }\n}\n\nfunction substituteOnce(value: string, env: NodeJS.ProcessEnv, path: string): string {\n return value.replace(\n PLACEHOLDER_PATTERN,\n (_match, name: string, hasDefault: string | undefined, def: string | undefined) => {\n const envValue = env[name];\n\n if (hasDefault !== undefined) {\n if (envValue === undefined || envValue === '') return def ?? '';\n return envValue;\n }\n\n if (envValue === undefined) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Unresolved environment variable \"\\${${name}}\" referenced at config path \"${path}\"`,\n { details: { variable: name, path } },\n );\n }\n return envValue;\n },\n );\n}\n","// Readers for leaves that env substitution may have turned into strings, and addresses\nimport { CommerceError } from '../../core';\nimport { isEvmAddress, isEvmZeroAddress } from '../../payments/x402/addresses';\n\nexport function toNumber(\n value: number | string,\n path: string,\n bounds: { min?: number; max?: number } = {},\n): number {\n // Plain decimal digits only. `Number('')` is 0, which `server.port` accepts\n // (\"let the OS pick\"), so an empty `${PORT:-}` would bind a random port.\n // `Number` also accepts `\"0x50\"` and `\"1e3\"` for fields documented as decimal.\n if (typeof value === 'string' && !/^\\s*\\d+\\s*$/.test(value)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration value at \"${path}\" must be an integer written in decimal digits (got ${value === '' ? 'an empty string' : `\"${value}\"`})`,\n { details: { path } },\n );\n }\n const n = typeof value === 'number' ? value : Number(value);\n if (!Number.isFinite(n) || !Number.isInteger(n)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration value at \"${path}\" must be an integer`,\n {\n details: { path },\n },\n );\n }\n if (bounds.min !== undefined && n < bounds.min) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration value at \"${path}\" must be >= ${bounds.min}`,\n {\n details: { path },\n },\n );\n }\n if (bounds.max !== undefined && n > bounds.max) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration value at \"${path}\" must be <= ${bounds.max}`,\n {\n details: { path },\n },\n );\n }\n return n;\n}\n\nexport function toBoolean(value: boolean | string, path: string): boolean {\n if (typeof value === 'boolean') return value;\n const normalized = value.trim().toLowerCase();\n if (normalized === 'true') return true;\n if (normalized === 'false') return false;\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration value at \"${path}\" must be a boolean (\"true\" or \"false\")`,\n { details: { path } },\n );\n}\n\nexport function validateAddress(path: string, value: string): void {\n if (!isEvmAddress(value)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration value at \"${path}\" is not a plausible address (expected \"0x\" followed by 40 hex characters)`,\n { details: { path } },\n );\n }\n if (isEvmZeroAddress(value)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration value at \"${path}\" must not be the zero address`,\n {\n details: { path },\n },\n );\n }\n}\n","// The ACP checkout adapter's settings and its operation-to-resource mapping\nimport { CommerceError, type CommerceResource } from '../../core';\nimport { isRecord } from '../../core/is-record';\nimport {\n ACP_CHECKOUT_OPERATIONS,\n ACP_OPERATION_INPUT_KEYS,\n ACP_OPERATION_OPTIONAL_INPUT_KEYS,\n ACP_SESSION_ID_INPUT_KEY,\n type AcpCheckoutOperation,\n} from '../../protocols/acp/constants';\nimport type { RawConfig } from './raw';\nimport type { AcpProtocolConfig } from './types';\nimport { toBoolean, toNumber } from './values';\n\n// Applied when `protocols.acp` is absent or names no mount\nconst DEFAULT_ACP_MOUNT_PATH = '/acp';\n\n// Idempotency records must outlive ACP's 24-hour retry window, or a replayed\n// key could pass an expired record and run a checkout side effect twice. It is\n// both the default and the floor.\nconst ACP_RETENTION_HOURS = 24;\n\ntype RawAcp = NonNullable<RawConfig['protocols']['acp']>;\n\ntype EnabledAcpConfig = Extract<AcpProtocolConfig, { enabled: true }>;\n\nfunction acpInvalid(\n path: string,\n message: string,\n extra: Record<string, unknown> = {},\n): CommerceError {\n return new CommerceError('CONFIG_INVALID', message, { details: { path, ...extra } });\n}\n\nexport function normalizeAcp(raw: RawAcp | undefined): AcpProtocolConfig {\n const mountPath = raw?.mountPath ?? DEFAULT_ACP_MOUNT_PATH;\n if (raw === undefined || !toBoolean(raw.enabled, 'protocols.acp.enabled')) {\n return { enabled: false, mountPath };\n }\n\n if (raw.auth === undefined) {\n throw acpInvalid(\n 'protocols.acp.auth',\n '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',\n );\n }\n const idempotency = raw.idempotency ?? {};\n if (idempotency.path !== undefined) {\n console.warn(\n '[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.',\n );\n }\n const discovery = raw.discovery;\n\n return {\n enabled: true,\n mountPath,\n auth: raw.auth,\n idempotency: {\n ...(idempotency.path !== undefined ? { path: idempotency.path } : {}),\n retentionHours: toNumber(\n idempotency.retentionHours ?? ACP_RETENTION_HOURS,\n 'protocols.acp.idempotency.retentionHours',\n { min: ACP_RETENTION_HOURS },\n ),\n merchantIdempotent: idempotency.merchantIdempotent ?? false,\n },\n checkout: { operations: normalizeAcpOperations(raw.checkout) },\n // Built key by key so absent metadata stays absent rather than `undefined`\n ...(discovery !== undefined\n ? {\n discovery: {\n ...(discovery.documentationUrl !== undefined\n ? { documentationUrl: discovery.documentationUrl }\n : {}),\n ...(discovery.supportedCurrencies !== undefined\n ? { supportedCurrencies: discovery.supportedCurrencies }\n : {}),\n ...(discovery.supportedLocales !== undefined\n ? { supportedLocales: discovery.supportedLocales }\n : {}),\n ...(discovery.interventionTypes !== undefined\n ? { interventionTypes: discovery.interventionTypes }\n : {}),\n },\n }\n : {}),\n };\n}\n\n// All five operations, each on its own resource. ACP discovery advertises\n// `checkout` as one service, so a partial mapping is refused. Operations differ\n// in method, input and success status, so one resource cannot serve two.\nfunction normalizeAcpOperations(\n checkout: RawAcp['checkout'],\n): Readonly<Record<AcpCheckoutOperation, string>> {\n const configured: Record<string, string> = checkout?.operations ?? {};\n\n for (const key of Object.keys(configured)) {\n if (!(ACP_CHECKOUT_OPERATIONS as readonly string[]).includes(key)) {\n throw acpInvalid(\n `protocols.acp.checkout.operations.${key}`,\n `protocols.acp.checkout.operations names unknown ACP checkout operation \"${key}\". Supported: ${ACP_CHECKOUT_OPERATIONS.join(', ')}.`,\n );\n }\n }\n\n const operations: Record<string, string> = {};\n const claimedBy = new Map<string, AcpCheckoutOperation>();\n for (const operation of ACP_CHECKOUT_OPERATIONS) {\n const path = `protocols.acp.checkout.operations.${operation}`;\n const resourceId = configured[operation];\n if (resourceId === undefined) {\n throw acpInvalid(\n path,\n `${path} is required when ACP is enabled - all five checkout operations must be mapped, since ACP discovery advertises the checkout service as a whole`,\n );\n }\n const claimed = claimedBy.get(resourceId);\n if (claimed !== undefined) {\n throw acpInvalid(\n path,\n `${path} maps resource \"${resourceId}\", which is already mapped to \"${claimed}\" - each ACP checkout operation needs its own resource`,\n { resourceId },\n );\n }\n claimedBy.set(resourceId, operation);\n operations[operation] = resourceId;\n }\n return operations as Record<AcpCheckoutOperation, string>;\n}\n\nexport function validateAcpCheckoutMapping(\n acp: EnabledAcpConfig,\n resources: readonly CommerceResource[],\n): void {\n const byId = new Map(resources.map((resource) => [resource.id, resource]));\n\n for (const operation of ACP_CHECKOUT_OPERATIONS) {\n const resourceId = acp.checkout.operations[operation];\n const path = `protocols.acp.checkout.operations.${operation}`;\n const resource = byId.get(resourceId);\n if (resource === undefined) {\n throw acpInvalid(\n path,\n `${path} maps resource \"${resourceId}\", which is not defined under \"resources\"`,\n { resourceId },\n );\n }\n if (!resource.exposedVia.includes('acp')) {\n throw acpInvalid(\n path,\n `Resource \"${resourceId}\" implements ACP operation \"${operation}\" but does not list \"acp\" in its expose - the mapping says which resource serves the operation, expose says ACP may invoke it, and both are required`,\n { resourceId },\n );\n }\n // ACP checkout carries the merchant's own purchase payment (`payment_data`\n // on completion), and ACP has no wire form for our payment-required\n // outcome, so the invocation itself must be free\n if (resource.pricing.type !== 'free' || resource.paymentMethods.length > 0) {\n throw acpInvalid(\n path,\n `Resource \"${resourceId}\" implements ACP operation \"${operation}\" and must use pricing.type \"free\" with no \"payments\" - ACP checkout carries the merchant's own purchase payment, so the gateway does not also charge for the invocation`,\n { resourceId },\n );\n }\n validateAcpOperationInput(path, operation, resource);\n }\n}\n\n// A schema that forbids a key the adapter sends, or requires one it may not\n// send, fails requests with INPUT_INVALID. Refused at load instead. An optional\n// key counts as sent: a closed cancel schema without `body` would pass a bare\n// cancel and refuse every one that carries `intent_trace`. Normalization has\n// already closed every object node that omits additionalProperties, so the\n// check also looks inside `path` and `body`: a bare `body: { type: object }`\n// arrives here accepting no key at all.\nfunction validateAcpOperationInput(\n path: string,\n operation: AcpCheckoutOperation,\n resource: CommerceResource,\n): void {\n const schema = resource.inputSchema;\n if (schema === undefined) return;\n const keys: readonly string[] = ACP_OPERATION_INPUT_KEYS[operation];\n const optionalKeys: readonly string[] = ACP_OPERATION_OPTIONAL_INPUT_KEYS[operation] ?? [];\n const sent = [...keys, ...optionalKeys];\n\n const topLevel = closedObjectProperties(schema);\n if (topLevel !== undefined) {\n for (const key of sent) {\n if (!Object.hasOwn(topLevel, key)) {\n const when = keys.includes(key) ? 'always sends' : 'sends when the caller supplies it';\n throw acpInvalid(\n path,\n `Resource \"${resource.id}\" implements ACP operation \"${operation}\" but its input schema sets additionalProperties: false without declaring \"${key}\", which the adapter ${when} for this operation`,\n { resourceId: resource.id },\n );\n }\n }\n }\n\n const declared = isRecord(schema['properties']) ? schema['properties'] : {};\n const pathKeys = closedObjectProperties(declared['path']);\n if (\n sent.includes('path') &&\n pathKeys !== undefined &&\n !Object.hasOwn(pathKeys, ACP_SESSION_ID_INPUT_KEY)\n ) {\n throw acpInvalid(\n path,\n `Resource \"${resource.id}\" implements ACP operation \"${operation}\" but its \"path\" schema sets additionalProperties: false without declaring \"${ACP_SESSION_ID_INPUT_KEY}\", which the adapter always sends inside \"path\"`,\n { resourceId: resource.id },\n );\n }\n const bodyKeys = closedObjectProperties(declared['body']);\n if (sent.includes('body') && bodyKeys !== undefined && Object.keys(bodyKeys).length === 0) {\n throw acpInvalid(\n path,\n `Resource \"${resource.id}\" implements ACP operation \"${operation}\" but its \"body\" schema accepts no keys, so it refuses every ACP document. Config load closes an object schema that omits additionalProperties: declare body as { type: object, additionalProperties: true }`,\n { resourceId: resource.id },\n );\n }\n\n const required = schema['required'];\n if (Array.isArray(required)) {\n for (const entry of required) {\n if (typeof entry === 'string' && !keys.includes(entry)) {\n throw acpInvalid(\n path,\n `Resource \"${resource.id}\" implements ACP operation \"${operation}\" but its input schema requires \"${entry}\", which that operation does not always supply (it always sends: ${keys.join(', ')})`,\n { resourceId: resource.id },\n );\n }\n }\n }\n}\n\n// The declared properties of a closed object schema, or undefined when the\n// schema accepts keys it does not declare\nfunction closedObjectProperties(schema: unknown): Record<string, unknown> | undefined {\n if (!isRecord(schema) || schema['additionalProperties'] !== false) return undefined;\n return isRecord(schema['properties']) ? schema['properties'] : {};\n}\n","// AP2 mandate verification settings and each resource's authorization requirement\nimport { resolve } from 'node:path';\nimport type { z } from 'zod';\nimport {\n AP2_DEFAULT_CLOCK_SKEW_SECONDS,\n AP2_JWK_COORDINATE_BYTES,\n AP2_JWK_CURVE,\n AP2_JWK_MEMBERS,\n AP2_KEY_TYPE,\n AP2_MAX_CLOCK_SKEW_SECONDS,\n AP2_MODES,\n AP2_SIGNING_ALGORITHM,\n AP2_SPEC_VERSION,\n} from '../../authorization/ap2/constants';\nimport type {\n Ap2AuthorizationConfig,\n Ap2Mode,\n Ap2TrustedIssuer,\n} from '../../authorization/ap2/types';\nimport {\n type AuthorizationMethodName,\n CommerceError,\n type CommerceResource,\n type Pricing,\n} from '../../core';\nimport type { Ap2IssuerSchema, RawConfig, RawResourceEntry } from './raw';\nimport type { AcpProtocolConfig } from './types';\nimport { toBoolean, toNumber } from './values';\n\nconst SUPPORTED_AUTHORIZATION_METHODS: ReadonlySet<string> = new Set(['ap2']);\n\ntype RawAp2 = NonNullable<NonNullable<RawConfig['authorization']>['ap2']>;\n\nfunction ap2Invalid(\n path: string,\n message: string,\n extra: Record<string, unknown> = {},\n): CommerceError {\n return new CommerceError('CONFIG_INVALID', message, { details: { path, ...extra } });\n}\n\nexport function normalizeAp2(raw: RawAp2 | undefined): Ap2AuthorizationConfig | undefined {\n if (raw === undefined) return undefined;\n if (!toBoolean(raw.enabled, 'authorization.ap2.enabled')) return { enabled: false };\n\n const specVersion = raw.specVersion ?? AP2_SPEC_VERSION;\n if (specVersion !== AP2_SPEC_VERSION) {\n throw ap2Invalid(\n 'authorization.ap2.specVersion',\n `authorization.ap2.specVersion \"${specVersion}\" is not supported - this gateway verifies against the tagged AP2 release ${AP2_SPEC_VERSION} only`,\n );\n }\n\n const mode = raw.mode ?? AP2_MODES[0];\n if (!(AP2_MODES as readonly string[]).includes(mode)) {\n throw ap2Invalid(\n 'authorization.ap2.mode',\n `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.`,\n );\n }\n\n if (raw.replay !== undefined) {\n console.warn(\n '[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.',\n );\n }\n\n const mandateIssuers = normalizeIssuers(\n raw.trust?.mandateIssuers,\n 'authorization.ap2.trust.mandateIssuers',\n );\n const checkoutIssuers = normalizeIssuers(\n raw.trust?.checkoutIssuers,\n 'authorization.ap2.trust.checkoutIssuers',\n );\n\n return {\n enabled: true,\n specVersion: AP2_SPEC_VERSION,\n mode: mode as Ap2Mode,\n trust: { mandateIssuers, checkoutIssuers },\n clockSkewSeconds: toNumber(\n raw.clockSkewSeconds ?? AP2_DEFAULT_CLOCK_SKEW_SECONDS,\n 'authorization.ap2.clockSkewSeconds',\n { min: 0, max: AP2_MAX_CLOCK_SKEW_SECONDS },\n ),\n requireMandateAudience: toBoolean(\n raw.requireMandateAudience ?? false,\n 'authorization.ap2.requireMandateAudience',\n ),\n requireMandateExpiry: toBoolean(\n raw.requireMandateExpiry ?? false,\n 'authorization.ap2.requireMandateExpiry',\n ),\n ...(raw.replay !== undefined ? { replay: { path: raw.replay.path } } : {}),\n };\n}\n\n// Both issuer lists must be non-empty when AP2 is on: verification checks the\n// issuer's signature over the Checkout Mandate and the merchant's over the\n// checkout JWT it binds. An empty list would fail every mandate at request\n// time instead of at load.\nfunction normalizeIssuers(\n raw: readonly z.infer<typeof Ap2IssuerSchema>[] | undefined,\n path: string,\n): readonly Ap2TrustedIssuer[] {\n if (raw === undefined || raw.length === 0) {\n throw ap2Invalid(\n path,\n `${path} is required when AP2 is enabled and must name at least one issuer - trust is operator-configured and static, so an empty list means no mandate can ever verify`,\n );\n }\n\n const seen = new Set<string>();\n return raw.map((entry, index) => {\n const entryPath = `${path}.${index}`;\n if (seen.has(entry.issuer)) {\n throw ap2Invalid(\n `${entryPath}.issuer`,\n `${entryPath}.issuer \"${entry.issuer}\" is listed twice - key lookup resolves by issuer, so a second entry for the same one is silently unreachable. Merge the keys into one entry instead (which is also how a rotation overlaps an old and a new key).`,\n { issuer: entry.issuer },\n );\n }\n seen.add(entry.issuer);\n\n const kids = new Set<string>();\n const keys = entry.keys.map((key, keyIndex) => {\n const keyPath = `${entryPath}.keys.${keyIndex}`;\n if (kids.has(key.kid)) {\n throw ap2Invalid(\n `${keyPath}.kid`,\n `${keyPath}.kid \"${key.kid}\" is listed twice for issuer \"${entry.issuer}\" - a kid selects exactly one key, so which of the two verifies a signature would be undefined`,\n { issuer: entry.issuer, kid: key.kid },\n );\n }\n kids.add(key.kid);\n return { kid: key.kid, jwk: validateJwk(key.jwk, key.kid, keyPath) };\n });\n\n return { issuer: entry.issuer, audience: entry.audience, keys };\n });\n}\n\n// Accepts only a public P-256 key. Every member is checked at load rather than\n// by the JOSE library at the first purchase, so a bad key fails the deploy\n// instead of a buyer's valid mandate.\nfunction validateJwk(\n jwk: Record<string, unknown>,\n kid: string,\n path: string,\n): Readonly<Record<string, string>> {\n const fail = (detail: string): never => {\n throw ap2Invalid(`${path}.jwk`, `${path}.jwk (kid \"${kid}\") ${detail}`, { kid });\n };\n\n for (const member of Object.keys(jwk)) {\n if ((AP2_JWK_MEMBERS as readonly string[]).includes(member)) continue;\n // `d` (an EC private scalar) or `k` (a symmetric key) means signing\n // material was pasted where only verification material belongs, which the\n // operator needs to hear about specifically\n if (member === 'd' || member === 'k') {\n fail(\n `carries private key material (\"${member}\"). The gateway verifies signatures and never produces them; publish only the public half. Treat the pasted key as compromised and rotate it.`,\n );\n }\n fail(\n `has unsupported member \"${member}\". Allowed: ${AP2_JWK_MEMBERS.join(', ')}. Members naming a URL are refused on purpose - keys are configured inline and never fetched.`,\n );\n }\n\n const value = (member: string): string => {\n const raw = jwk[member];\n if (typeof raw !== 'string' || raw.length === 0) {\n fail(`must give \"${member}\" as a non-empty string`);\n }\n return raw as string;\n };\n\n if (value('kty') !== AP2_KEY_TYPE) {\n fail(\n `must have kty \"${AP2_KEY_TYPE}\" (got \"${value('kty')}\") - ${AP2_SIGNING_ALGORITHM} is the only accepted algorithm`,\n );\n }\n if (value('crv') !== AP2_JWK_CURVE) {\n fail(\n `must be on curve \"${AP2_JWK_CURVE}\" (got \"${value('crv')}\") - ${AP2_SIGNING_ALGORITHM} is the only accepted algorithm`,\n );\n }\n for (const coordinate of ['x', 'y'] as const) {\n const encoded = value(coordinate);\n if (!/^[A-Za-z0-9_-]+$/.test(encoded)) {\n fail(`coordinate \"${coordinate}\" is not base64url (no padding, no \"+\" or \"/\")`);\n }\n if (Buffer.from(encoded, 'base64url').length !== AP2_JWK_COORDINATE_BYTES) {\n fail(\n `coordinate \"${coordinate}\" decodes to ${Buffer.from(encoded, 'base64url').length} bytes; a ${AP2_JWK_CURVE} coordinate is ${AP2_JWK_COORDINATE_BYTES}`,\n );\n }\n }\n if (jwk['alg'] !== undefined && value('alg') !== AP2_SIGNING_ALGORITHM) {\n fail(`declares alg \"${value('alg')}\"; only ${AP2_SIGNING_ALGORITHM} is accepted`);\n }\n if (jwk['use'] !== undefined && value('use') !== 'sig') {\n fail(`declares use \"${value('use')}\"; a verification key must be \"sig\"`);\n }\n if (jwk['kid'] !== undefined && value('kid') !== kid) {\n fail(`declares kid \"${value('kid')}\", which disagrees with the configured kid \"${kid}\"`);\n }\n\n const normalized: Record<string, string> = {};\n for (const member of AP2_JWK_MEMBERS) {\n if (jwk[member] !== undefined) normalized[member] = value(member);\n }\n return normalized;\n}\n\n// Legacy imports hold write locks, so reject source paths whose resolved\n// path matches another source or the receipt database\nexport function validateLegacyStoresIsolated(\n ap2: Ap2AuthorizationConfig | undefined,\n acp: AcpProtocolConfig,\n receiptsPath: string,\n): void {\n const files: [string, string | undefined][] = [\n ['authorization.ap2.replay.path', ap2?.enabled ? ap2.replay?.path : undefined],\n ['protocols.acp.idempotency.path', acp.enabled ? acp.idempotency.path : undefined],\n ];\n const others: [string, string][] = [['storage.receipts.path', receiptsPath]];\n for (const [key, path] of files) {\n // Every `:memory:` handle is its own private database, so equal strings do\n // not collide\n if (path === undefined || path === ':memory:') continue;\n const clash = others.find(\n ([, other]) => other !== ':memory:' && resolve(other) === resolve(path),\n );\n if (clash !== undefined) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `${key} is the same file as ${clash[0]} (\"${resolve(path)}\") - a deprecated store file is imported into the receipt database and then locked, so it must be a separate file`,\n { details: { path: key } },\n );\n }\n others.push([key, path]);\n }\n}\n\n// Resolves a resource's `authorization.required` list against the configured\n// provider. A requirement that cannot be enforced is refused: the resource\n// would look protected in config and settle unprotected.\nexport function normalizeResourceAuthorization(\n id: string,\n entry: RawResourceEntry,\n pricing: Pricing,\n ap2: Ap2AuthorizationConfig | undefined,\n): CommerceResource['authorization'] | undefined {\n const required = entry.authorization?.required;\n if (required === undefined) return undefined;\n\n const path = `resources.${id}.authorization.required`;\n const methods: AuthorizationMethodName[] = [];\n for (const method of required) {\n if (!SUPPORTED_AUTHORIZATION_METHODS.has(method)) {\n throw ap2Invalid(\n path,\n `Resource \"${id}\" requires unsupported authorization method \"${method}\". Supported: ${[...SUPPORTED_AUTHORIZATION_METHODS].join(', ')}.`,\n { resourceId: id, method },\n );\n }\n if (methods.includes(method as AuthorizationMethodName)) {\n throw ap2Invalid(path, `Resource \"${id}\" lists authorization method \"${method}\" twice`, {\n resourceId: id,\n method,\n });\n }\n if (method === 'ap2' && (ap2 === undefined || !ap2.enabled)) {\n throw ap2Invalid(\n path,\n `Resource \"${id}\" requires authorization method \"ap2\", which is not configured or not enabled under authorization.ap2`,\n { resourceId: id, method },\n );\n }\n methods.push(method as AuthorizationMethodName);\n }\n\n // A mandate binds an exact amount and currency and never unlocks a resource\n // by itself, so it only means something on a fixed-price resource\n if (pricing.type !== 'fixed') {\n throw ap2Invalid(\n path,\n `Resource \"${id}\" requires authorization but its pricing is \"${pricing.type}\" - authorization proves a purchase was approved and never replaces payment, so it applies to fixed-price paid resources only in this release`,\n { resourceId: id },\n );\n }\n\n return { required: methods };\n}\n","// The x402 rail: direct or listed options, declared networks and the facilitator\nimport type { z } from 'zod';\nimport { CommerceError } from '../../core';\nimport { resolveX402Deployment, type X402FacilitatorConfig } from '../../payments/x402/guardrails';\nimport {\n type CustomNetworkDeclaration,\n findX402Network,\n validateCustomNetworks,\n} from '../../payments/x402/networks';\nimport { resolveX402Option, type X402OptionInput } from '../../payments/x402/options';\nimport { X402_DEFAULT_PAYMENT_FLOW } from '../../payments/x402/payment-flow';\nimport type { FacilitatorSchema, RawConfig } from './raw';\nimport type { GatewayConfig, X402OptionConfig } from './types';\nimport { toBoolean, toNumber } from './values';\n\ntype X402Config = NonNullable<GatewayConfig['payments']['x402']>;\n\n// One offer list: the rail's options or a resource's own accepts\nexport interface X402OfferTerms {\n /** Every option, resolved, in order */\n readonly options: readonly X402OptionConfig[];\n /**\n * Default symbols for options omitting `asset`; prices must use USD or\n * the shared symbol\n */\n readonly defaultAssetSymbols: readonly string[];\n}\n\nexport interface NormalizedX402 extends X402OfferTerms {\n readonly config: X402Config;\n /** Resources with their own `x402.accepts`, by id; each replaces the rail's options */\n readonly resources: Readonly<Record<string, X402OfferTerms>>;\n}\n\nfunction x402Invalid(message: string, path: string): CommerceError {\n return new CommerceError('CONFIG_INVALID', message, { details: { path } });\n}\n\n// The fields of one option, as they appear directly under `payments.x402`\nconst DIRECT_OPTION_FIELDS = [\n 'network',\n 'payTo',\n 'asset',\n 'assetName',\n 'assetVersion',\n 'assetDecimals',\n 'assetTransferMethod',\n] as const;\n\ntype RawX402 = NonNullable<RawConfig['payments']['x402']>;\n\n// An entry of `options`, or `payments.x402` itself in the direct form\ninterface RawX402Option {\n readonly scheme?: string | undefined;\n readonly network?: string | undefined;\n readonly payTo?: string | undefined;\n readonly asset?: string | undefined;\n readonly assetName?: string | undefined;\n readonly assetVersion?: string | undefined;\n readonly assetDecimals?: number | string | undefined;\n readonly assetTransferMethod?: string | undefined;\n}\n\nfunction x402OptionInput(raw: RawX402Option, path: string): X402OptionInput {\n return {\n ...(raw.scheme !== undefined ? { scheme: raw.scheme } : {}),\n network: raw.network as string,\n payTo: raw.payTo as string,\n ...(raw.asset !== undefined ? { asset: raw.asset } : {}),\n ...(raw.assetName !== undefined ? { assetName: raw.assetName } : {}),\n ...(raw.assetVersion !== undefined ? { assetVersion: raw.assetVersion } : {}),\n ...(raw.assetTransferMethod !== undefined\n ? { assetTransferMethod: raw.assetTransferMethod }\n : {}),\n ...(raw.assetDecimals !== undefined\n ? {\n assetDecimals: toNumber(raw.assetDecimals, `${path}.assetDecimals`, { min: 0, max: 36 }),\n }\n : {}),\n };\n}\n\n/**\n * Resolves direct `payments.x402` fields like a one-entry `options` array,\n * preserving config form. Resource `x402.accepts` uses the same resolution\n * and rail-level networks, RPC endpoints, facilitator and mainnet settings.\n */\nexport function normalizeX402(raw: RawX402, resources: RawConfig['resources']): NormalizedX402 {\n const at = 'payments.x402';\n const direct = DIRECT_OPTION_FIELDS.filter((field) => raw[field] !== undefined);\n if (raw.options !== undefined && direct.length > 0) {\n throw x402Invalid(\n `${at}: give the option either under ${at}.options or directly (${direct.join(', ')}), not both`,\n `${at}.options`,\n );\n }\n if (raw.options?.length === 0) {\n throw x402Invalid(`${at}.options is empty; list at least one option`, `${at}.options`);\n }\n if (raw.options === undefined) {\n for (const field of ['network', 'payTo'] as const) {\n if (raw[field] === undefined) {\n throw x402Invalid(\n `${at}.${field} is required, unless the options are listed under ${at}.options`,\n `${at}.${field}`,\n );\n }\n }\n }\n\n // `kind` and `displayName` declare a network; `rpcUrl` alone sets the\n // endpoint of a built-in or declared one\n const settings = raw.networks ?? {};\n const declared: Record<string, CustomNetworkDeclaration> = {};\n for (const [id, entry] of Object.entries(settings)) {\n if (entry.kind === undefined && entry.displayName === undefined) continue;\n if (entry.kind === undefined || entry.displayName === undefined) {\n const path = `${at}.networks.${id}`;\n throw x402Invalid(`${path}: declaring a network needs both kind and displayName`, path);\n }\n declared[id] = { kind: entry.kind, displayName: entry.displayName };\n }\n const networks = Object.keys(declared).length > 0 ? declared : undefined;\n if (networks !== undefined) validateCustomNetworks(networks, `${at}.networks`);\n for (const id of Object.keys(settings)) {\n if (!findX402Network(id, networks)) {\n const path = `${at}.networks.${id}`;\n throw x402Invalid(\n `${path}: \"${id}\" is not a known network; declare it with kind and displayName`,\n path,\n );\n }\n }\n\n const facilitator = normalizeFacilitator(raw.facilitator);\n const allowMainnet =\n raw.allowMainnet !== undefined ? toBoolean(raw.allowMainnet, `${at}.allowMainnet`) : undefined;\n const allowUnauthenticatedFacilitator =\n raw.allowUnauthenticatedFacilitator !== undefined\n ? toBoolean(raw.allowUnauthenticatedFacilitator, `${at}.allowUnauthenticatedFacilitator`)\n : undefined;\n\n // Shared by every list, so the rail and its resources use one RPC endpoint\n // per network and one deployment mode\n const rpcOwners = new Map<string, string>();\n let firstMode: string | undefined;\n const resolveList = (entries: readonly (readonly [string, RawX402Option])[]): X402OfferTerms => {\n const resolved = entries.map(([path, entry]) =>\n resolveX402Option(x402OptionInput(entry, path), path, networks),\n );\n const seen = new Set<string>();\n const options = resolved.map((option, i): X402OptionConfig => {\n const path = entries[i]?.[0] as string;\n const network = option.network.id;\n // Require distinct RPC endpoints so each network's health check reads its chain\n const rpcUrl = settings[network]?.rpcUrl ?? raw.rpcUrl;\n if (rpcUrl === undefined) {\n throw x402Invalid(\n `${path}.network: no RPC endpoint for ${network}; set ${at}.rpcUrl or ${at}.networks.${network}.rpcUrl`,\n `${at}.rpcUrl`,\n );\n }\n // Parsed, so `https://rpc.example` and `https://rpc.example/` are one endpoint\n const endpoint = new URL(rpcUrl).href;\n const owner = rpcOwners.get(endpoint);\n if (owner !== undefined && owner !== network) {\n throw x402Invalid(\n `${at}: ${owner} and ${network} would use the same RPC endpoint; give each network its own ${at}.networks.<id>.rpcUrl`,\n `${at}.networks`,\n );\n }\n rpcOwners.set(endpoint, network);\n\n // EVM addresses compare case-insensitively; Solana and NEAR exactly\n const comparable = (value: string) =>\n option.network.family === 'evm' ? value.toLowerCase() : value;\n const key = `${network}|${comparable(option.asset)}|${comparable(option.payTo)}`;\n if (seen.has(key)) {\n throw x402Invalid(\n `${path}: repeats an earlier option, the same asset to the same payTo on ${network}`,\n path,\n );\n }\n seen.add(key);\n\n // The provider makes the same call at construction; running it here lets\n // `agent-commerce validate` report an unsafe deployment before boot\n const { mode } = resolveX402Deployment({\n network,\n payTo: option.payTo,\n asset: option.asset,\n ...(option.assetName !== undefined ? { assetName: option.assetName } : {}),\n ...(option.assetVersion !== undefined ? { assetVersion: option.assetVersion } : {}),\n facilitator,\n ...(allowMainnet !== undefined ? { allowMainnet } : {}),\n ...(allowUnauthenticatedFacilitator !== undefined\n ? { allowUnauthenticatedFacilitator }\n : {}),\n ...(networks !== undefined ? { customNetworks: networks } : {}),\n // resolveX402Option required the token's own metadata\n allowOtherEvmToken: true,\n });\n // Keep all offers in one deployment mode: local, testnet or mainnet\n if (firstMode !== undefined && mode !== firstMode) {\n throw x402Invalid(\n `${path}.network: ${network} is a ${mode} network, but the first option is on a ${firstMode} one; every option must be on the same kind of network`,\n `${path}.network`,\n );\n }\n firstMode = mode;\n\n return {\n network,\n rpcUrl,\n asset: option.asset,\n ...(option.assetName !== undefined ? { assetName: option.assetName } : {}),\n ...(option.assetVersion !== undefined ? { assetVersion: option.assetVersion } : {}),\n assetDecimals: option.assetDecimals,\n payTo: option.payTo,\n ...(option.assetTransferMethod === 'permit2'\n ? { assetTransferMethod: 'permit2' as const }\n : {}),\n };\n });\n return {\n options,\n defaultAssetSymbols: [\n ...new Set(resolved.flatMap((option) => option.defaultAssetSymbol ?? [])),\n ],\n };\n };\n\n const rail = resolveList(\n raw.options !== undefined\n ? raw.options.map((option, i) => [`${at}.options[${i}]`, option] as const)\n : [[at, raw]],\n );\n const resourceTerms: Record<string, X402OfferTerms> = {};\n for (const [id, entry] of Object.entries(resources)) {\n const accepts = entry.x402?.accepts;\n if (accepts === undefined) continue;\n const path = `resources.${id}.x402.accepts`;\n if (accepts.length === 0) {\n throw x402Invalid(`${path} is empty; list at least one option`, path);\n }\n resourceTerms[id] = resolveList(accepts.map((option, i) => [`${path}[${i}]`, option] as const));\n }\n const options = rail.options;\n const first = options[0] as X402OptionConfig;\n const resourceOptions = Object.fromEntries(\n Object.entries(resourceTerms).map(([id, terms]) => [id, terms.options]),\n );\n\n // The provider validates the private key and derives the issuer at construction,\n // keeping viem out of config loading\n let quote: X402Config['quote'];\n if (raw.quote !== undefined && toBoolean(raw.quote.enabled, `${at}.quote.enabled`)) {\n if (raw.quote.signerPrivateKey === undefined) {\n throw x402Invalid(\n `${at}.quote.signerPrivateKey is required when quotes are enabled`,\n `${at}.quote.signerPrivateKey`,\n );\n }\n quote = { signerPrivateKey: raw.quote.signerPrivateKey };\n }\n\n const config: X402Config = {\n enabled: toBoolean(raw.enabled, `${at}.enabled`),\n ...first,\n maxTimeoutSeconds: toNumber(raw.maxTimeoutSeconds, `${at}.maxTimeoutSeconds`, { min: 1 }),\n paymentFlow: raw.paymentFlow ?? X402_DEFAULT_PAYMENT_FLOW,\n facilitator,\n ...(allowMainnet !== undefined ? { allowMainnet } : {}),\n ...(allowUnauthenticatedFacilitator !== undefined ? { allowUnauthenticatedFacilitator } : {}),\n ...(networks !== undefined ? { networks } : {}),\n options,\n ...(Object.keys(resourceOptions).length > 0 ? { resourceOptions } : {}),\n ...(quote !== undefined ? { quote } : {}),\n };\n\n return { config, ...rail, resources: resourceTerms };\n}\n\nexport function normalizeFacilitator(\n raw: z.infer<typeof FacilitatorSchema>,\n): X402FacilitatorConfig {\n return raw.mode === 'local'\n ? { mode: 'local', signerPrivateKey: raw.signerPrivateKey }\n : { mode: 'remote', url: raw.url, auth: raw.auth ?? { type: 'none' } };\n}\n","// The MPP rail's settings\nimport { CommerceError } from '../../core';\nimport {\n isMppNetwork,\n MPP_DEFAULT_NETWORK,\n MPP_DEFAULT_PAYMENT_FLOW,\n MPP_MIN_CHALLENGE_SECRET_LENGTH,\n MPP_NETWORKS,\n} from '../../payments/mpp/constants';\nimport { resolveX402Deployment } from '../../payments/x402/guardrails';\nimport type { RawConfig } from './raw';\nimport type { GatewayConfig } from './types';\nimport { toBoolean, toNumber, validateAddress } from './values';\nimport { normalizeFacilitator } from './x402';\n\nexport type NormalizedMpp = NonNullable<GatewayConfig['payments']['mpp']>;\n\nexport function normalizeMpp(raw: RawConfig['payments']['mpp']): NormalizedMpp | undefined {\n if (raw === undefined) return undefined;\n const network = raw.network ?? MPP_DEFAULT_NETWORK;\n if (!isMppNetwork(network)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `payments.mpp.network must be one of ${MPP_NETWORKS.join(', ')}`,\n { details: { path: 'payments.mpp.network' } },\n );\n }\n const mpp: NormalizedMpp = {\n enabled: toBoolean(raw.enabled, 'payments.mpp.enabled'),\n network,\n rpcUrl: raw.rpcUrl,\n asset: raw.asset,\n assetName: raw.assetName,\n assetVersion: raw.assetVersion,\n recipient: raw.recipient,\n realm: raw.realm,\n challengeSecret: raw.challengeSecret,\n ...(raw.challengeTtlSeconds !== undefined\n ? {\n challengeTtlSeconds: toNumber(\n raw.challengeTtlSeconds,\n 'payments.mpp.challengeTtlSeconds',\n { min: 1 },\n ),\n }\n : {}),\n paymentFlow: raw.paymentFlow ?? MPP_DEFAULT_PAYMENT_FLOW,\n facilitator: normalizeFacilitator(raw.facilitator),\n ...(raw.allowMainnet !== undefined\n ? { allowMainnet: toBoolean(raw.allowMainnet, 'payments.mpp.allowMainnet') }\n : {}),\n ...(raw.allowUnauthenticatedFacilitator !== undefined\n ? {\n allowUnauthenticatedFacilitator: toBoolean(\n raw.allowUnauthenticatedFacilitator,\n 'payments.mpp.allowUnauthenticatedFacilitator',\n ),\n }\n : {}),\n };\n validateAddress('payments.mpp.recipient', mpp.recipient);\n validateAddress('payments.mpp.asset', mpp.asset);\n // mppx refuses CR or LF in a quoted challenge parameter\n if (/[\\r\\n]/.test(mpp.realm)) {\n throw new CommerceError('CONFIG_INVALID', 'payments.mpp.realm must be a single line', {\n details: { path: 'payments.mpp.realm' },\n });\n }\n // Length only: the secret itself never appears in an error\n if (mpp.challengeSecret.length < MPP_MIN_CHALLENGE_SECRET_LENGTH) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `payments.mpp.challengeSecret must have length at least ${MPP_MIN_CHALLENGE_SECRET_LENGTH}`,\n { details: { path: 'payments.mpp.challengeSecret' } },\n );\n }\n // The shared x402 address, facilitator and mainnet guards, reported under the\n // MPP config path\n resolveX402Deployment({\n network: mpp.network,\n payTo: mpp.recipient,\n asset: mpp.asset,\n assetName: mpp.assetName,\n assetVersion: mpp.assetVersion,\n facilitator: mpp.facilitator,\n ...(mpp.allowMainnet !== undefined ? { allowMainnet: mpp.allowMainnet } : {}),\n ...(mpp.allowUnauthenticatedFacilitator !== undefined\n ? { allowUnauthenticatedFacilitator: mpp.allowUnauthenticatedFacilitator }\n : {}),\n configPath: 'payments.mpp',\n payToField: 'recipient',\n });\n return mpp;\n}\n","// The Zod schemas for `config.yaml`: shape only, before any business rule\nimport { type ZodTypeAny, z } from 'zod';\nimport { X402_PAYMENT_FLOWS } from '../../payments/x402/payment-flow';\nimport { ACP_WELL_KNOWN_PATH } from '../../protocols/acp/constants';\n\nexport const SUPPORTED_CONFIG_VERSION = 1;\n\n// A number, or a numeric string from env substitution\nconst NumberOrString = z.union([z.number(), z.string()]);\n\n// A boolean, or a \"true\"/\"false\" string from env substitution\nconst BooleanOrString = z.union([z.boolean(), z.string()]);\n\n// A media type as in a Content-Type header: `type/subtype`, then any parameters\nconst MediaType = z\n .string()\n .regex(/^[A-Za-z0-9][\\w!#$&^.+-]*\\/[A-Za-z0-9][\\w!#$&^.+-]*(?:[ \\t]*;.*)?$/, {\n message: 'must be a media type such as application/json',\n });\n\n// An RPC endpoint. The message never echoes the value, which can carry an API key\nconst RpcUrl = z\n .string()\n .min(1)\n .refine(isHttpUrl, { message: 'must be an http:// or https:// URL' });\n\nfunction isHttpUrl(value: string): boolean {\n try {\n const { protocol } = new URL(value);\n return protocol === 'http:' || protocol === 'https:';\n } catch {\n return false;\n }\n}\n\nconst MerchantSchema = z\n .object({\n id: z.string().min(1),\n name: z.string().min(1),\n publicBaseUrl: z.string().min(1),\n })\n .strict();\n\nconst ServerSchema = z\n .object({\n port: NumberOrString,\n host: z.string().min(1),\n // Required for /api/receipts, /api/events and /api/payment-attempts;\n // these routes return 404 when the token is unset\n adminToken: z.string().min(1).optional(),\n // Browser origins allowed to call the gateway; none by default. A request\n // with any other `Origin` gets 403 on every route. Entries match the\n // `Origin` header exactly (ignoring case), so `\"*\"` and a trailing slash\n // would match nothing: a silent lockout that an operator might \"fix\" by\n // disabling the check. Both are refused with a pointer.\n allowedOrigins: z\n .array(\n z\n .string()\n .min(1)\n .refine((origin) => origin !== '*', {\n message:\n 'wildcard \"*\" is not supported - allowedOrigins entries are matched literally against the browser\\'s Origin header, so \"*\" would match nothing. List each scheme://host[:port] explicitly.',\n })\n .refine((origin) => !origin.endsWith('/'), {\n message:\n 'must not end with \"/\" - a browser Origin header never has a trailing slash, so this entry would match nothing. Use e.g. \"http://localhost:5173\".',\n }),\n )\n .optional(),\n })\n .strict();\n\nconst StorageSchema = z\n .object({\n receipts: z\n .object({\n driver: z.literal('sqlite'),\n path: z.string().min(1),\n })\n .strict(),\n })\n .strict();\n\n// Every path the gateway registers (`src/gateway/routes.ts`), plus the fixed\n// discovery paths adapters own. A mount equal to one duplicates that route; a\n// mount that is a prefix of one swallows it through its `${mountPath}/*` wildcard.\nconst RESERVED_GATEWAY_PATHS = [\n '/health',\n '/ready',\n '/.well-known/agent-commerce',\n // Fixed by the A2A specification and served by the adapter\n '/.well-known/agent-card.json',\n // Fixed by the ACP specification\n ACP_WELL_KNOWN_PATH,\n '/api/resources',\n '/api/resources/:id/invoke',\n '/api/receipts',\n '/api/events',\n '/api/payment-attempts',\n] as const;\n\n// A bad `mountPath` would throw inside Fastify route registration at\n// `server.ready()`, failing the whole gateway with an opaque `FST_ERR_*`.\n// Checked here it is a CONFIG_INVALID naming the value. Pattern syntax (`:`,\n// `*`) is refused because the mount registers its own wildcard.\nconst MountPathSchema = z\n .string()\n .min(1)\n .refine((value) => value.startsWith('/'), {\n message: 'must start with \"/\" - it is an absolute gateway path, e.g. \"/mcp\".',\n })\n .refine((value) => !/[:*?\\s]/.test(value), {\n message:\n 'must not contain \":\", \"*\", \"?\" or whitespace - the mount is a literal path prefix, not a Fastify route pattern, and registers its own wildcard.',\n })\n .refine(\n (value) => {\n const base = value.replace(/\\/+$/, '');\n return !RESERVED_GATEWAY_PATHS.some(\n (reserved) => reserved === base || reserved.startsWith(`${base}/`),\n );\n },\n {\n message: `must not collide with a route the gateway already serves (${RESERVED_GATEWAY_PATHS.join(', ')}); pick a dedicated prefix such as \"/mcp\".`,\n },\n );\n\n// Bearer is the only ACP auth scheme; there is no `none`\nconst AcpAuthSchema = z.object({ type: z.literal('bearer'), token: z.string().min(1) }).strict();\n\nconst AcpIdempotencySchema = z\n .object({\n path: z.string().min(1).optional(),\n retentionHours: NumberOrString.optional(),\n merchantIdempotent: z.boolean().optional(),\n })\n .strict();\n\n// Operation names are checked against `ACP_CHECKOUT_OPERATIONS` in the\n// business pass, which names a missing or misspelled operation\nconst AcpCheckoutSchema = z.object({ operations: z.record(z.string().min(1)) }).strict();\n\n// Optional discovery metadata, omitted when not configured\nconst AcpDiscoverySchema = z\n .object({\n documentationUrl: z.string().min(1).optional(),\n supportedCurrencies: z.array(z.string().min(1)).optional(),\n supportedLocales: z.array(z.string().min(1)).optional(),\n interventionTypes: z.array(z.string().min(1)).optional(),\n })\n .strict();\n\nconst ProtocolsSchema = z\n .object({\n http: z.object({ enabled: BooleanOrString }).strict(),\n mcp: z\n .object({\n enabled: BooleanOrString,\n mountPath: MountPathSchema,\n })\n .strict(),\n // Optional; A2A is off unless configured\n a2a: z\n .object({\n enabled: BooleanOrString,\n mountPath: MountPathSchema.optional(),\n })\n .strict()\n .optional(),\n // Optional and off by default. The business pass requires the sub-blocks\n // only when ACP is enabled, so a disabled placeholder stays valid and an\n // enabled block gets a message naming what it lacks.\n acp: z\n .object({\n enabled: BooleanOrString,\n mountPath: MountPathSchema.optional(),\n auth: AcpAuthSchema.optional(),\n idempotency: AcpIdempotencySchema.optional(),\n checkout: AcpCheckoutSchema.optional(),\n discovery: AcpDiscoverySchema.optional(),\n })\n .strict()\n .optional(),\n })\n .strict();\n\nconst BackendMethodSchema = z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']);\n\n// Strict, so a typo like `bodyy` fails at load instead of silently meaning\n// \"no body binding\"\nconst BackendInputBindingsSchema = z\n .object({\n path: z.string().min(1).optional(),\n query: z.string().min(1).optional(),\n body: z.string().min(1).optional(),\n })\n .strict();\n\nconst BackendHandlerSchema = z\n .object({\n type: z.literal('http'),\n method: BackendMethodSchema,\n url: z.string().min(1),\n headers: z.record(z.string(), z.string()).optional(),\n timeoutMs: NumberOrString.optional(),\n inputBindings: BackendInputBindingsSchema.optional(),\n })\n .strict();\n\nconst PricingSchema = z.discriminatedUnion('type', [\n z.object({ type: z.literal('free') }).strict(),\n z\n .object({\n type: z.literal('fixed'),\n amount: z.string().min(1),\n currency: z.string().min(1),\n })\n .strict(),\n z\n .object({\n type: z.literal('dynamic'),\n resolver: z.string().min(1),\n })\n .strict(),\n]);\n\nconst JsonSchemaValueSchema: ZodTypeAny = z.record(z.string(), z.unknown());\n\n// Settlement network, payee and token, resolved by x402/options.ts. Network\n// and payee fields follow the SDK's `PaymentOption`; asset fields override defaults\nconst X402OptionSchema = z\n .object({\n scheme: z.string().min(1).optional(),\n network: z.string().min(1),\n payTo: z.string().min(1),\n asset: z.string().min(1).optional(),\n assetName: z.string().min(1).optional(),\n assetVersion: z.string().min(1).optional(),\n assetDecimals: NumberOrString.optional(),\n assetTransferMethod: z.string().min(1).optional(),\n })\n .strict();\n\nconst ResourceEntrySchema = z\n .object({\n name: z.string().min(1),\n description: z.string().optional(),\n input: JsonSchemaValueSchema.optional(),\n output: JsonSchemaValueSchema.optional(),\n // What the backend returns; x402 challenges declare it, `application/json` by default\n mimeType: MediaType.optional(),\n backend: BackendHandlerSchema,\n pricing: PricingSchema,\n expose: z.array(z.string().min(1)).min(1),\n payments: z.array(z.string().min(1)).optional(),\n paymentFlow: z.enum(X402_PAYMENT_FLOWS).optional(),\n // This resource's own x402 offers, in place of `payments.x402` options\n x402: z\n .object({ accepts: z.array(X402OptionSchema) })\n .strict()\n .optional(),\n authorization: z\n .object({ required: z.array(z.string().min(1)).min(1) })\n .strict()\n .optional(),\n })\n .strict();\n\nconst ResourcesMapSchema = z.record(z.string().min(1), ResourceEntrySchema);\n\n// Facilitator credentials. `none` and `bearer` fit any facilitator; `cdp` is\n// the one vendor-specific type. Any other type is refused at load.\nconst FacilitatorAuthSchema = z.discriminatedUnion('type', [\n z.object({ type: z.literal('none') }).strict(),\n z.object({ type: z.literal('bearer'), token: z.string().min(1) }).strict(),\n // Coinbase Developer Platform. Needs the optional peer `@coinbase/x402`,\n // which signs a fresh JWT per request.\n z\n .object({\n type: z.literal('cdp'),\n apiKeyId: z.string().min(1),\n apiKeySecret: z.string().min(1),\n })\n .strict(),\n]);\n\nexport const FacilitatorSchema = z.discriminatedUnion('mode', [\n z\n .object({\n mode: z.literal('local'),\n signerPrivateKey: z.string().min(1),\n })\n .strict(),\n z\n .object({\n mode: z.literal('remote'),\n url: z.string().min(1),\n // Absent auth sends no credential and normalizes to `{ type: 'none' }`,\n // which on mainnet requires `allowUnauthenticatedFacilitator`\n auth: FacilitatorAuthSchema.optional(),\n })\n .strict(),\n]);\n\n// Per-network settings: `kind` and `displayName` declare a network outside\n// the registry; `rpcUrl` is that network's endpoint, built in or declared\nconst X402NetworkSettingsSchema = z\n .object({\n kind: z.enum(['testnet', 'mainnet']).optional(),\n displayName: z.string().min(1).optional(),\n rpcUrl: RpcUrl.optional(),\n })\n .strict();\n\nconst X402Schema = z\n .object({\n enabled: BooleanOrString,\n // Accept direct fields or an `options` array, never both\n network: z.string().min(1).optional(),\n payTo: z.string().min(1).optional(),\n asset: z.string().min(1).optional(),\n assetName: z.string().min(1).optional(),\n assetVersion: z.string().min(1).optional(),\n assetDecimals: NumberOrString.optional(),\n assetTransferMethod: z.string().min(1).optional(),\n options: z.array(X402OptionSchema).optional(),\n networks: z.record(z.string().min(1), X402NetworkSettingsSchema).optional(),\n // The RPC for every network without its own `networks.<id>.rpcUrl`\n rpcUrl: RpcUrl.optional(),\n maxTimeoutSeconds: NumberOrString,\n // `authorization` (the x402 default) settles after the backend call\n paymentFlow: z.enum(X402_PAYMENT_FLOWS).optional(),\n facilitator: FacilitatorSchema,\n // Real funds. Never defaulted; see src/payments/x402/guardrails.ts\n allowMainnet: BooleanOrString.optional(),\n // Accepts credential-free facilitator access on mainnet. Never defaulted\n allowUnauthenticatedFacilitator: BooleanOrString.optional(),\n // Experimental ERC-8409 quotes; signing a quote transfers no funds\n quote: z\n .object({\n enabled: BooleanOrString,\n signerPrivateKey: z.string().min(1).optional(),\n })\n .strict()\n .optional(),\n })\n .strict();\n\nconst MppSchema = z\n .object({\n enabled: BooleanOrString,\n network: z.string().min(1).optional(),\n rpcUrl: RpcUrl,\n asset: z.string().min(1),\n assetName: z.string().min(1),\n assetVersion: z.string().min(1),\n recipient: z.string().min(1),\n realm: z.string().min(1),\n challengeSecret: z.string().min(1),\n challengeTtlSeconds: NumberOrString.optional(),\n // Same values as `payments.x402.paymentFlow`; the default is `upfront`\n paymentFlow: z.enum(X402_PAYMENT_FLOWS).optional(),\n facilitator: FacilitatorSchema,\n // Real funds. Never defaulted; see src/payments/x402/guardrails.ts\n allowMainnet: BooleanOrString.optional(),\n // Accepts credential-free facilitator access on mainnet. Never defaulted\n allowUnauthenticatedFacilitator: BooleanOrString.optional(),\n })\n .strict();\n\nconst PaymentsSchema = z\n .object({\n x402: X402Schema.optional(),\n mpp: MppSchema.optional(),\n })\n .strict();\n\n// A public verification key, inline only: no `jwksUri`, `jku` or discovery\n// URL. AP2 leaves secure key distribution open, and fetching keys would mean\n// fetching from a location a mandate can influence. The business pass checks\n// the JWK's members against `AP2_JWK_MEMBERS`, which also keeps out `x5u`.\nconst Ap2KeySchema = z\n .object({\n kid: z.string().min(1),\n jwk: z.record(z.string(), z.unknown()),\n })\n .strict();\n\nexport const Ap2IssuerSchema = z\n .object({\n issuer: z.string().min(1),\n // Required, not defaulted: without it a mandate minted for another\n // merchant would verify here\n audience: z.string().min(1),\n keys: z.array(Ap2KeySchema).min(1),\n })\n .strict();\n\nconst Ap2Schema = z\n .object({\n enabled: BooleanOrString,\n specVersion: z.string().min(1).optional(),\n mode: z.string().min(1).optional(),\n trust: z\n .object({\n mandateIssuers: z.array(Ap2IssuerSchema).optional(),\n checkoutIssuers: z.array(Ap2IssuerSchema).optional(),\n })\n .strict()\n .optional(),\n clockSkewSeconds: NumberOrString.optional(),\n requireMandateAudience: BooleanOrString.optional(),\n requireMandateExpiry: BooleanOrString.optional(),\n replay: z\n .object({ path: z.string().min(1) })\n .strict()\n .optional(),\n })\n .strict();\n\n// Optional and off by default. The business pass requires the sub-blocks only\n// when AP2 is enabled, and names the missing piece.\nconst AuthorizationSchema = z.object({ ap2: Ap2Schema.optional() }).strict();\n\nexport const RawConfigSchema = z\n .object({\n version: z.literal(SUPPORTED_CONFIG_VERSION),\n merchant: MerchantSchema,\n server: ServerSchema,\n storage: StorageSchema,\n protocols: ProtocolsSchema,\n resources: ResourcesMapSchema,\n payments: PaymentsSchema,\n authorization: AuthorizationSchema.optional(),\n })\n .strict();\n\nexport type RawConfig = z.infer<typeof RawConfigSchema>;\n\nexport type RawResourceEntry = z.infer<typeof ResourceEntrySchema>;\n","// A resource's backend request: input bindings, path parameters, URL and headers\nimport { CommerceError, RESERVED_INPUT_FIELDS } from '../../core';\nimport {\n extractPathParameterNames,\n findUnparsedBraceToken,\n isObjectSchemaNode,\n} from '../../core/execution';\nimport { isRecord } from '../../core/is-record';\nimport type { RawResourceEntry } from './raw';\n\n/**\n * Checks `backend.inputBindings` against the input schema at load. Schemas are\n * closed by default at every depth, so a binding naming an undeclared property\n * could never be supplied, and on a paid resource the backend would get an\n * incomplete request after payment.\n *\n * Returns the schema node `{param}` names must be declared in: the path group\n * with bindings, the whole input without.\n */\nexport function validateInputBindings(\n id: string,\n backend: RawResourceEntry['backend'],\n input: Record<string, unknown> | undefined,\n): { readonly schema: Record<string, unknown> | undefined; readonly where: string } {\n const legacy = { schema: input, where: 'its input schema' } as const;\n const bindings = backend.inputBindings;\n const templated = extractPathParameterNames(backend.url).length > 0;\n if (bindings === undefined) return legacy;\n\n const path = `resources.${id}.backend.inputBindings`;\n const fail = (message: string, details: Record<string, unknown> = {}): never => {\n throw new CommerceError('CONFIG_INVALID', `Resource \"${id}\" ${message}`, {\n details: { path, resourceId: id, ...details },\n });\n };\n\n const entries = Object.entries(bindings).filter(\n (entry): entry is [string, string] => entry[1] !== undefined,\n );\n if (entries.length === 0) {\n fail('has an empty backend.inputBindings - remove the block to use the default mapping');\n }\n if (backend.method === 'GET' || backend.method === 'DELETE') {\n if (bindings.body !== undefined) {\n fail(\n `binds a request body on a ${backend.method}, which sends none - the value would be silently dropped`,\n );\n }\n }\n if (templated && bindings.path === undefined) {\n fail(\n 'has backend.url path parameters but no \"path\" binding - in explicit binding mode nothing else supplies them, so every call would fail to reach the backend',\n );\n }\n\n const seen = new Map<string, string>();\n const properties = isRecord(input?.['properties']) ? input['properties'] : {};\n const required = new Set(\n Array.isArray(input?.['required'])\n ? input['required'].filter((value): value is string => typeof value === 'string')\n : [],\n );\n\n for (const [location, property] of entries) {\n if (RESERVED_INPUT_FIELDS.includes(property)) {\n fail(`binds \"${location}\" to \"${property}\", which is reserved by the gateway`, { location });\n }\n const other = seen.get(property);\n if (other !== undefined) {\n fail(`binds both \"${other}\" and \"${location}\" to the input property \"${property}\"`, {\n location,\n property,\n });\n }\n seen.set(property, location);\n\n if (!Object.hasOwn(properties, property)) {\n fail(\n `binds \"${location}\" to input property \"${property}\", which the input schema does not declare - the schema is closed, so a caller could never supply it`,\n { location, property },\n );\n }\n // `body` may be any JSON value; only the path and query groups are read as\n // name/value pairs\n const declared = properties[property];\n if (location !== 'body' && isRecord(declared) && !isObjectSchemaNode(declared)) {\n fail(\n `binds \"${location}\" to input property \"${property}\", which is not an object schema - ${location} parameters are read as an object of name/value pairs`,\n { location, property },\n );\n }\n }\n\n if (templated && bindings.path !== undefined && !required.has(bindings.path)) {\n fail(\n `binds path parameters to input property \"${bindings.path}\" without listing it in the input schema's \"required\" - a caller that omits it cannot supply any path parameter, so the request could never be built`,\n { property: bindings.path },\n );\n }\n\n if (bindings.path === undefined) return { schema: undefined, where: 'its input schema' };\n const group = properties[bindings.path];\n return {\n schema: isRecord(group) ? group : undefined,\n where: `input.properties.${bindings.path}`,\n };\n}\n\n/**\n * Every `{param}` in `backend.url` must be declared in `properties` and listed\n * in `required`. Otherwise a call can arrive without it, and core's\n * `validateBackendRequestShape` rejects the request, which for a schema that\n * never declares the parameter means every call. Checked at load so\n * `validate` and `doctor` report it; the runtime check covers a hand-built\n * `CommerceResource`.\n */\nexport function validatePathParametersDeclared(\n id: string,\n url: string,\n input: Record<string, unknown> | undefined,\n where: string,\n): void {\n // A brace token the grammar does not recognize is neither extracted nor\n // substituted, so it would reach the backend as a percent-encoded literal\n const stray = findUnparsedBraceToken(url);\n if (stray !== undefined) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has backend.url containing \"${stray}\", which is not a valid path parameter (allowed characters: A-Z a-z 0-9 _ . -). It would reach the backend as literal text, so a paid resource would take payment for a request the backend cannot serve`,\n { details: { path: `resources.${id}.backend.url`, resourceId: id, token: stray } },\n );\n }\n\n const params = extractPathParameterNames(url);\n if (params.length === 0) return;\n\n // Everything before the first `{` must be a complete origin followed by the\n // path's leading `/`. In the host, every other `{param}` defense fails open:\n // `http://{host}/api` parses, the runtime prefix check skips a prefix that\n // is not a URL, and `encodeURIComponent` keeps dots. Caller input would pick\n // the host the gateway calls, such as a metadata service or an internal\n // address, and `http://{region}.api.internal/...` looks ordinary enough to\n // be written by mistake.\n const firstBrace = url.indexOf('{');\n if (firstBrace !== -1) {\n const prefix = url.slice(0, firstBrace);\n let origin: string | undefined;\n try {\n const parsedPrefix = new URL(prefix);\n origin = parsedPrefix.hostname === '' ? undefined : parsedPrefix.origin;\n } catch {\n // Not a URL: the parameter starts before the authority is complete\n }\n if (origin === undefined || !prefix.startsWith(`${origin}/`)) {\n // The URL is not quoted: it may carry a key substituted from the environment\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has a backend.url parameter before the end of the host. A caller-supplied value would choose which host the gateway calls, which is request forgery with the gateway's own network position. Parameters are supported inside the path and query only`,\n { details: { path: `resources.${id}.backend.url`, resourceId: id } },\n );\n }\n }\n\n const propertiesRaw = input?.['properties'];\n const properties = isRecord(propertiesRaw) ? propertiesRaw : {};\n const requiredRaw = input?.['required'];\n const required = new Set(\n Array.isArray(requiredRaw)\n ? requiredRaw.filter((entry): entry is string => typeof entry === 'string')\n : [],\n );\n\n for (const param of params) {\n const path = `resources.${id}.backend.url`;\n if (!Object.hasOwn(properties, param)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has backend.url path parameter \"{${param}}\" which is not declared in ${where} - the caller has no way to supply it, so every call would be refused`,\n { details: { path, resourceId: id, param } },\n );\n }\n if (!required.has(param)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has backend.url path parameter \"{${param}}\" declared in ${where} but not listed in its \"required\" - a call that omits it would be refused`,\n { details: { path, resourceId: id, param } },\n );\n }\n }\n}\n\n// `{param}` templates parse as URLs (the WHATWG parser percent-encodes the\n// braces), so this refuses only malformed URLs and non-http(s) schemes\nexport function validateBackendUrl(id: string, url: string): void {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n // The URL is not quoted: it may carry a key substituted from the environment\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has an invalid backend.url: must be an absolute http:// or https:// URL`,\n { details: { path: `resources.${id}.backend.url`, resourceId: id } },\n );\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has a backend.url with scheme \"${parsed.protocol}\": must be http:// or https://`,\n { details: { path: `resources.${id}.backend.url`, resourceId: id } },\n );\n }\n}\n\n// Checked with fetch's own `Headers` rules. Otherwise an illegal name, or a\n// substituted value with a line break inside it, would load cleanly and then\n// refuse every call. The error names the key, never the value, which may be a\n// credential.\nexport function validateBackendHeaders(\n id: string,\n headers: Record<string, string> | undefined,\n): void {\n for (const [name, value] of Object.entries(headers ?? {})) {\n try {\n new Headers([[name, value]]);\n } catch {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has backend header \"${name}\" with an illegal name or value (a name must be an HTTP token; a value must not contain NUL, a character above U+00FF, or a line break except at either end, which fetch trims)`,\n { details: { path: `resources.${id}.backend.headers.${name}`, resourceId: id } },\n );\n }\n }\n}\n","// A resource's input schema: the default closed object and the keywords the validator supports\nimport { CommerceError } from '../../core';\nimport { isObjectSchemaNode } from '../../core/execution';\nimport { isRecord } from '../../core/is-record';\n\n/**\n * Closes every object schema at every depth: a node without\n * `additionalProperties` gets `false`, so unknown keys never reach the\n * merchant's API. An explicit value, including `true`, is kept.\n *\n * JSON Schema itself defaults to open, and core's validator enforces\n * `additionalProperties` only where a node states it, so this recurses into\n * `properties`, `items` and schema-valued `additionalProperties`, the same\n * places the validator descends. Object-ness comes from `isObjectSchemaNode`,\n * the validator's own definition.\n */\nexport function defaultClosedObjectSchema(\n schema: Record<string, unknown>,\n): Record<string, unknown> {\n const isObjectSchema = isObjectSchemaNode(schema);\n const result: Record<string, unknown> = { ...schema };\n\n if (isObjectSchema) {\n const properties = schema['properties'];\n if (isRecord(properties)) {\n result['properties'] = Object.fromEntries(\n Object.entries(properties).map(([key, sub]) => [\n key,\n isRecord(sub) ? defaultClosedObjectSchema(sub) : sub,\n ]),\n );\n }\n if (!Object.hasOwn(schema, 'additionalProperties')) {\n result['additionalProperties'] = false;\n }\n }\n\n const items = schema['items'];\n if (isRecord(items)) {\n result['items'] = defaultClosedObjectSchema(items);\n }\n\n // `additionalProperties: {schema}` (a map of typed objects) is closed too.\n // Not conditional on `isObjectSchema`: the validator applies the subschema\n // wherever it finds one.\n const additional = schema['additionalProperties'];\n if (isRecord(additional)) {\n result['additionalProperties'] = defaultClosedObjectSchema(additional);\n }\n\n return result;\n}\n\n// The input schema of a resource that declares no `input:`. Declaring nothing\n// accepts nothing: without this, `compileJsonSchema(undefined)` would accept\n// any input and forward every key to the backend. A no-argument resource\n// omitting `input:` is a legitimate shape, so it is not refused.\nexport const EMPTY_CLOSED_OBJECT_SCHEMA: Record<string, unknown> = {\n type: 'object',\n properties: {},\n additionalProperties: false,\n};\n\n// Keywords core's validator ignores (see `execution/validation.ts` for the\n// enforced subset). Config warns at load, since an operator who writes\n// `pattern` cannot otherwise tell that it is not enforced.\nconst UNSUPPORTED_SCHEMA_KEYWORDS = [\n 'pattern',\n 'minLength',\n 'maxLength',\n 'format',\n 'minimum',\n 'maximum',\n 'exclusiveMinimum',\n 'exclusiveMaximum',\n 'multipleOf',\n 'oneOf',\n 'anyOf',\n 'allOf',\n 'not',\n '$ref',\n 'const',\n 'patternProperties',\n 'minItems',\n 'maxItems',\n 'uniqueItems',\n];\n\n// `type` set to something that rules out \"object\". No `type` at all does not\n// exclude it: the validator treats `properties`/`required` alone as an object\n// schema.\nfunction excludesObjectType(schema: Record<string, unknown>): boolean {\n const type = schema['type'];\n if (type === undefined || type === 'object') return false;\n if (Array.isArray(type)) return !type.includes('object');\n return true;\n}\n\n/**\n * Walks a resource's input schema once. Warns about unenforced keywords and\n * tuple `items`. Rejects a node whose `type` rules out \"object\" while it\n * declares `properties` or `required`, which then go unchecked (often a\n * copy-pasted sibling whose `type` was never updated), and a closed node\n * requiring a property it never declares, which no input can satisfy.\n */\nexport function validateResourceSchemaKeywords(\n id: string,\n path: string,\n schema: Record<string, unknown>,\n): void {\n for (const keyword of UNSUPPORTED_SCHEMA_KEYWORDS) {\n if (Object.hasOwn(schema, keyword)) {\n console.warn(\n `[agent-commerce] resource \"${id}\" ${path} uses JSON Schema keyword \"${keyword}\", which this gateway does not enforce (see src/core/execution/validation.ts for the supported subset). Remove it or treat it as documentation only.`,\n );\n }\n }\n if (\n (Object.hasOwn(schema, 'properties') || Object.hasOwn(schema, 'required')) &&\n excludesObjectType(schema)\n ) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" ${path} declares \"properties\" and/or \"required\" but its \"type\" (${JSON.stringify(schema['type'])}) does not include \"object\" - the validator will never route a value through either check under that type, so this schema claims to constrain input it does not actually enforce. Remove \"properties\"/\"required\", or include \"object\" in \"type\".`,\n { details: { path: `resources.${id}.${path}`, resourceId: id } },\n );\n }\n // A closed node that requires a property it never declares rejects that\n // property as unknown, so no input can satisfy it and every call would 400.\n // Only when the node is closed: an explicit `additionalProperties`\n // other than `false` leaves the name reachable.\n const requiredRaw = schema['required'];\n const closed = !Object.hasOwn(schema, 'additionalProperties')\n ? true\n : schema['additionalProperties'] === false;\n if (Array.isArray(requiredRaw) && closed && isObjectSchemaNode(schema)) {\n const declared = isRecord(schema['properties']) ? schema['properties'] : {};\n const undeclared = requiredRaw.filter(\n (name): name is string => typeof name === 'string' && !Object.hasOwn(declared, name),\n );\n if (undeclared.length > 0) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" ${path} lists ${undeclared.map((n) => `\"${n}\"`).join(', ')} in \"required\" but does not declare ${undeclared.length === 1 ? 'it' : 'them'} in \"properties\". The schema is closed (additionalProperties: false), so ${undeclared.length === 1 ? 'that name is' : 'those names are'} rejected as an unknown key and no input can ever satisfy this schema. Declare ${undeclared.length === 1 ? 'it' : 'them'} in \"properties\".`,\n { details: { path: `resources.${id}.${path}`, resourceId: id, undeclared } },\n );\n }\n }\n\n const properties = schema['properties'];\n if (isRecord(properties)) {\n for (const [key, sub] of Object.entries(properties)) {\n if (isRecord(sub)) validateResourceSchemaKeywords(id, `${path}.properties.${key}`, sub);\n }\n }\n const additional = schema['additionalProperties'];\n if (isRecord(additional)) {\n validateResourceSchemaKeywords(id, `${path}.additionalProperties`, additional);\n }\n const items = schema['items'];\n if (isRecord(items)) {\n validateResourceSchemaKeywords(id, `${path}.items`, items);\n } else if (Array.isArray(items)) {\n // Tuple-form `items` is valid JSON Schema, but the validator supports only\n // one schema for every element, so a tuple enforces nothing\n console.warn(\n `[agent-commerce] resource \"${id}\" ${path}.items is a tuple (an array of schemas), which this gateway does not enforce - only a single schema applied to every array element is supported (see src/core/execution/validation.ts). Each position's schema is unenforced; treat it as documentation only.`,\n );\n }\n}\n","// Resources: exposure, pricing, payment rails and backend handler\nimport type { Ap2AuthorizationConfig } from '../../authorization/ap2/types';\nimport {\n CommerceError,\n type CommerceResource,\n PAYMENT_METHOD_NAMES,\n PROTOCOL_NAMES,\n type Pricing,\n RESERVED_INPUT_FIELDS,\n} from '../../core';\nimport { MPP_PROFILE } from '../../payments/mpp/constants';\nimport { MCP_TOOL_NAME_PATTERN } from '../../protocols/mcp/constants';\nimport { normalizeResourceAuthorization } from './ap2';\nimport {\n validateBackendHeaders,\n validateBackendUrl,\n validateInputBindings,\n validatePathParametersDeclared,\n} from './backend';\nimport type { NormalizedMpp } from './mpp';\nimport type { RawResourceEntry } from './raw';\nimport {\n defaultClosedObjectSchema,\n EMPTY_CLOSED_OBJECT_SCHEMA,\n validateResourceSchemaKeywords,\n} from './resource-schema';\nimport type { NormalizedProtocols } from './types';\nimport { toNumber } from './values';\nimport type { NormalizedX402 } from './x402';\n\nconst SUPPORTED_PROTOCOLS: ReadonlySet<string> = new Set(PROTOCOL_NAMES);\n\nconst SUPPORTED_PAYMENT_METHODS: ReadonlySet<string> = new Set(PAYMENT_METHOD_NAMES);\n\nexport function normalizeResource(\n id: string,\n entry: RawResourceEntry,\n protocols: NormalizedProtocols,\n x402: NormalizedX402 | undefined,\n mpp: NormalizedMpp | undefined,\n ap2: Ap2AuthorizationConfig | undefined,\n): CommerceResource {\n if (entry.input !== undefined) validateResourceSchemaKeywords(id, 'input', entry.input);\n\n const inputProperties = entry.input?.['properties'];\n if (inputProperties && typeof inputProperties === 'object') {\n for (const reserved of RESERVED_INPUT_FIELDS) {\n if (!(reserved in inputProperties)) continue;\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" declares an input property \"${reserved}\", which is reserved by the gateway`,\n {\n details: {\n path: `resources.${id}.input.properties.${reserved}`,\n resourceId: id,\n },\n },\n );\n }\n }\n\n for (const protocol of entry.expose) {\n if (!SUPPORTED_PROTOCOLS.has(protocol)) {\n const hint = protocol === 'ucp' ? ' (UCP is planned, not supported in this release)' : '';\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" exposes unsupported protocol \"${protocol}\"${hint}. Supported: ${PROTOCOL_NAMES.join(', ')}.`,\n { details: { path: `resources.${id}.expose`, resourceId: id, protocol } },\n );\n }\n }\n if (entry.expose.includes('mcp')) {\n if (!protocols.mcp.enabled) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" is exposed via \"mcp\" but protocols.mcp.enabled is false`,\n { details: { path: `resources.${id}.expose`, resourceId: id } },\n );\n }\n if (!MCP_TOOL_NAME_PATTERN.test(id)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" is exposed via \"mcp\" but its id is not a legal MCP tool name (allowed: A-Z, a-z, 0-9, \"_\", \"-\", \".\", 1-128 chars)`,\n { details: { path: `resources.${id}`, resourceId: id } },\n );\n }\n }\n if (entry.expose.includes('a2a') && !protocols.a2a.enabled) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" is exposed via \"a2a\" but protocols.a2a.enabled is false`,\n { details: { path: `resources.${id}.expose`, resourceId: id } },\n );\n }\n if (entry.expose.includes('acp') && !protocols.acp.enabled) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" is exposed via \"acp\" but protocols.acp.enabled is false`,\n { details: { path: `resources.${id}.expose`, resourceId: id } },\n );\n }\n if (entry.expose.includes('http') && !protocols.http.enabled) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" is exposed via \"http\" but protocols.http.enabled is false`,\n { details: { path: `resources.${id}.expose`, resourceId: id } },\n );\n }\n\n validateBackendUrl(id, entry.backend.url);\n validateBackendHeaders(id, entry.backend.headers);\n const pathScope = validateInputBindings(id, entry.backend, entry.input);\n validatePathParametersDeclared(id, entry.backend.url, pathScope.schema, pathScope.where);\n\n if (entry.pricing.type === 'dynamic') {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" uses pricing.type \"dynamic\", which is not supported in this release`,\n { details: { path: `resources.${id}.pricing.type`, resourceId: id } },\n );\n }\n\n const paymentMethods = entry.payments ?? [];\n\n if (entry.x402 !== undefined) {\n const at = `resources.${id}.x402`;\n if (x402 === undefined) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" sets x402.accepts, but payments.x402 is not configured`,\n { details: { path: at, resourceId: id } },\n );\n }\n if (entry.pricing.type !== 'fixed' || !paymentMethods.includes('x402')) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" sets x402.accepts, which requires fixed pricing and \"x402\" in payments`,\n { details: { path: at, resourceId: id } },\n );\n }\n }\n // The resource's own offers, or the rail's\n const offers = x402 !== undefined ? (x402.resources[id] ?? x402) : undefined;\n\n if (entry.pricing.type === 'fixed') {\n // An x402 price is charged in every option's token, so the coarsest one\n // bounds it. MPP checks its own token's decimals below.\n const decimals = paymentMethods.includes('x402')\n ? offers?.options.map((option) => option.assetDecimals)\n : undefined;\n validatePricingAmount(id, entry.pricing.amount, decimals && Math.min(...decimals));\n }\n\n if (entry.pricing.type === 'fixed') {\n if (paymentMethods.length === 0) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has fixed pricing but declares no \"payments\" (a paid resource must name at least one payment method)`,\n { details: { path: `resources.${id}.payments`, resourceId: id } },\n );\n }\n for (const method of paymentMethods) {\n if (!SUPPORTED_PAYMENT_METHODS.has(method)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" names unsupported payment method \"${method}\". Supported: ${PAYMENT_METHOD_NAMES.join(', ')}.`,\n { details: { path: `resources.${id}.payments`, resourceId: id, method } },\n );\n }\n }\n // At least one named rail must be enabled, not every one. `runGateway`\n // checks again at composition as defense in depth.\n const enabledRails = [\n ...(x402?.config.enabled ? ['x402'] : []),\n ...(mpp?.enabled ? ['mpp'] : []),\n ];\n if (!paymentMethods.some((method) => enabledRails.includes(method))) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" names payment method(s) \"${paymentMethods.join(', ')}\", none of which is configured and enabled under \"payments\"`,\n { details: { path: `resources.${id}.payments`, resourceId: id, paymentMethods } },\n );\n }\n // An offer in the network's default stablecoin, named or not, charges the\n // price in that token, so the price must name that token or USD\n const symbols = offers?.defaultAssetSymbols ?? [];\n const currency = entry.pricing.currency;\n if (\n x402?.config.enabled &&\n symbols.length > 0 &&\n paymentMethods.includes('x402') &&\n currency !== 'USD' &&\n !(symbols.length === 1 && currency === symbols[0])\n ) {\n const tokens = symbols.join(' and ');\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" is priced in ${currency}, but x402 settles in ${tokens}, the default asset of its network. Price it in ${symbols.length === 1 ? `${tokens} or ` : ''}USD.`,\n { details: { path: `resources.${id}.pricing.currency`, resourceId: id } },\n );\n }\n // MPP fixes the currency label and decimal precision for every resource it serves\n if (mpp?.enabled && paymentMethods.includes('mpp')) {\n if (entry.pricing.currency !== MPP_PROFILE.assetSymbol) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" is priced in ${entry.pricing.currency}, but MPP charges ${MPP_PROFILE.assetSymbol}`,\n { details: { path: `resources.${id}.pricing.currency`, resourceId: id } },\n );\n }\n validatePricingAmount(id, entry.pricing.amount, MPP_PROFILE.assetDecimals);\n }\n }\n\n if (\n entry.paymentFlow !== undefined &&\n (entry.pricing.type !== 'fixed' ||\n !paymentMethods.some((method) => method === 'x402' || method === 'mpp'))\n ) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" sets paymentFlow, which requires fixed pricing and \"x402\" or \"mpp\" in payments`,\n { details: { path: `resources.${id}.paymentFlow`, resourceId: id } },\n );\n }\n\n if (\n entry.mimeType !== undefined &&\n (entry.pricing.type !== 'fixed' || !paymentMethods.includes('x402'))\n ) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" sets mimeType, which requires fixed pricing and \"x402\" in payments`,\n { details: { path: `resources.${id}.mimeType`, resourceId: id } },\n );\n }\n\n const pricing: Pricing =\n entry.pricing.type === 'free'\n ? { type: 'free' }\n : { type: 'fixed', amount: entry.pricing.amount, currency: entry.pricing.currency };\n\n const authorization = normalizeResourceAuthorization(id, entry, pricing, ap2);\n\n return {\n id,\n name: entry.name,\n ...(entry.description !== undefined ? { description: entry.description } : {}),\n inputSchema:\n entry.input !== undefined\n ? defaultClosedObjectSchema(entry.input)\n : EMPTY_CLOSED_OBJECT_SCHEMA,\n ...(entry.output !== undefined ? { outputSchema: entry.output } : {}),\n handler: {\n type: 'http',\n method: entry.backend.method,\n url: entry.backend.url,\n ...(entry.backend.headers !== undefined ? { headers: entry.backend.headers } : {}),\n ...(entry.backend.timeoutMs !== undefined\n ? {\n timeoutMs: toNumber(entry.backend.timeoutMs, `resources.${id}.backend.timeoutMs`, {\n min: 1,\n }),\n }\n : {}),\n ...(entry.backend.inputBindings !== undefined\n ? { inputBindings: pickDefined(entry.backend.inputBindings) }\n : {}),\n },\n pricing,\n exposedVia: entry.expose as CommerceResource['exposedVia'],\n paymentMethods: paymentMethods as CommerceResource['paymentMethods'],\n ...(authorization !== undefined ? { authorization } : {}),\n };\n}\n\n// A plain decimal: no currency symbol, thousands separator, sign or exponent.\n// \"0,01\", \"$0.01\", \"1e-2\" and \"-1\" would otherwise load and then fail every\n// purchase.\nconst PRICING_AMOUNT_PATTERN = /^\\d+(?:\\.\\d+)?$/;\n\nconst ZERO_AMOUNT_PATTERN = /^0(?:\\.0+)?$/;\n\nfunction validatePricingAmount(id: string, amount: string, decimals: number | undefined): void {\n const path = `resources.${id}.pricing.amount`;\n if (!PRICING_AMOUNT_PATTERN.test(amount)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has pricing.amount \"${amount}\", which is not a plain positive decimal (no currency symbol, no thousands separator, no exponent - e.g. \"0.01\")`,\n { details: { path, resourceId: id } },\n );\n }\n if (ZERO_AMOUNT_PATTERN.test(amount)) {\n // A zero-priced paid resource would settle a zero-value transfer\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has pricing.amount \"0\" - a paid resource cannot cost zero; use \"pricing: { type: free }\" instead`,\n { details: { path, resourceId: id } },\n );\n }\n if (decimals !== undefined) {\n const fractionalDigits = amount.includes('.') ? (amount.split('.')[1]?.length ?? 0) : 0;\n if (fractionalDigits > decimals) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has pricing.amount \"${amount}\" with more precision (${fractionalDigits} fractional digits) than the configured asset supports (${decimals} decimals)`,\n { details: { path, resourceId: id } },\n );\n }\n }\n}\n\n// Strips absent optional keys so the result satisfies `exactOptionalPropertyTypes`\nfunction pickDefined<T extends Record<string, string | undefined>>(\n value: T,\n): { [K in keyof T]?: string } {\n return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined)) as {\n [K in keyof T]?: string;\n };\n}\n","// The business-rule pass: coerces leaves and checks cross-references across sections\nimport { CommerceError } from '../../core';\nimport { normalizeAcp, validateAcpCheckoutMapping } from './acp';\nimport { normalizeAp2, validateLegacyStoresIsolated } from './ap2';\nimport { normalizeMpp } from './mpp';\nimport { type RawConfig, SUPPORTED_CONFIG_VERSION } from './raw';\nimport { normalizeResource } from './resources';\nimport type { GatewayConfig, NormalizedProtocols } from './types';\nimport { toBoolean, toNumber } from './values';\nimport { normalizeX402 } from './x402';\n\n// Applied when `protocols.a2a` is absent or names no mount\nconst DEFAULT_A2A_MOUNT_PATH = '/a2a';\n\nexport function normalize(raw: RawConfig): GatewayConfig {\n const protocols = {\n http: { enabled: toBoolean(raw.protocols.http.enabled, 'protocols.http.enabled') },\n mcp: {\n enabled: toBoolean(raw.protocols.mcp.enabled, 'protocols.mcp.enabled'),\n mountPath: raw.protocols.mcp.mountPath,\n },\n a2a: {\n enabled: toBoolean(raw.protocols.a2a?.enabled ?? false, 'protocols.a2a.enabled'),\n mountPath: raw.protocols.a2a?.mountPath ?? DEFAULT_A2A_MOUNT_PATH,\n },\n acp: normalizeAcp(raw.protocols.acp),\n };\n validateMountPaths(protocols);\n\n const x402Settings =\n raw.payments.x402 !== undefined ? normalizeX402(raw.payments.x402, raw.resources) : undefined;\n const x402 = x402Settings?.config;\n\n const mpp = normalizeMpp(raw.payments.mpp);\n\n const ap2 = normalizeAp2(raw.authorization?.ap2);\n validateLegacyStoresIsolated(ap2, protocols.acp, raw.storage.receipts.path);\n\n const resources = Object.entries(raw.resources).map(([id, entry]) =>\n normalizeResource(id, entry, protocols, x402Settings, mpp, ap2),\n );\n // CommerceResource has no payment-flow field. Each listed rail carries the\n // overrides; the selected rail applies them.\n const flowOverrides = (rail: 'x402' | 'mpp') => {\n const flows = Object.fromEntries(\n resources.flatMap((resource) => {\n const flow = raw.resources[resource.id]?.paymentFlow;\n return flow !== undefined && resource.paymentMethods.includes(rail)\n ? [[resource.id, flow]]\n : [];\n }),\n );\n return Object.keys(flows).length > 0 ? { resourcePaymentFlows: flows } : {};\n };\n // The same holds for media types, which only x402 challenges carry\n const mimeTypes = Object.fromEntries(\n resources.flatMap((resource) => {\n const mimeType = raw.resources[resource.id]?.mimeType;\n return mimeType !== undefined ? [[resource.id, mimeType]] : [];\n }),\n );\n const x402WithFlows =\n x402 !== undefined\n ? {\n ...x402,\n ...flowOverrides('x402'),\n ...(Object.keys(mimeTypes).length > 0 ? { resourceMimeTypes: mimeTypes } : {}),\n }\n : x402;\n const mppWithFlows = mpp !== undefined ? { ...mpp, ...flowOverrides('mpp') } : mpp;\n if (protocols.acp.enabled) validateAcpCheckoutMapping(protocols.acp, resources);\n // Require an exposed resource so the enabled adapter publishes a skill\n if (protocols.a2a.enabled && !resources.some((r) => r.exposedVia.includes('a2a'))) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n 'protocols.a2a.enabled is true but no resource lists \"a2a\" in its expose',\n { details: { path: 'protocols.a2a.enabled' } },\n );\n }\n\n return {\n version: SUPPORTED_CONFIG_VERSION,\n merchant: {\n id: raw.merchant.id,\n name: raw.merchant.name,\n publicBaseUrl: raw.merchant.publicBaseUrl,\n },\n // Port 0 lets the OS pick a free port, for tests and throwaway instances\n server: {\n port: toNumber(raw.server.port, 'server.port', { min: 0, max: 65535 }),\n host: raw.server.host,\n ...(raw.server.adminToken !== undefined ? { adminToken: raw.server.adminToken } : {}),\n allowedOrigins: raw.server.allowedOrigins ?? [],\n },\n storage: { receipts: { driver: 'sqlite', path: raw.storage.receipts.path } },\n protocols,\n resources,\n payments: {\n ...(x402WithFlows !== undefined ? { x402: x402WithFlows } : {}),\n ...(mppWithFlows !== undefined ? { mpp: mppWithFlows } : {}),\n },\n ...(ap2 !== undefined ? { authorization: { ap2 } } : {}),\n };\n}\n\n// Two enabled mounts may not overlap: each registers a `${mountPath}/*`\n// wildcard, so a shared prefix lets one adapter answer for the other. Disabled\n// protocols mount nothing and are not compared.\nfunction validateMountPaths(protocols: NormalizedProtocols): void {\n const mounts = (\n [\n ['mcp', protocols.mcp],\n ['a2a', protocols.a2a],\n ['acp', protocols.acp],\n ] as const\n ).filter(([, p]) => p.enabled);\n\n for (const [index, [nameA, a]] of mounts.entries()) {\n for (const [nameB, b] of mounts.slice(index + 1)) {\n const baseA = a.mountPath.replace(/\\/+$/, '');\n const baseB = b.mountPath.replace(/\\/+$/, '');\n if (baseA === baseB || baseA.startsWith(`${baseB}/`) || baseB.startsWith(`${baseA}/`)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `protocols.${nameA}.mountPath (\"${a.mountPath}\") collides with protocols.${nameB}.mountPath (\"${b.mountPath}\") - each mount registers a wildcard, so overlapping prefixes cannot both be served`,\n { details: { path: `protocols.${nameA}.mountPath` } },\n );\n }\n }\n }\n}\n","/**\n * `config.yaml` schema, validation and normalization into the canonical\n * `GatewayConfig` (docs/contracts.md).\n *\n * 1. Zod validates shape: types, required fields, unknown keys. Numeric and\n * boolean leaves accept their native type or a string, because env\n * substitution produces strings. Zod transforms interact badly with\n * `.strict()` inference, so coercion happens in plain TypeScript in step 2.\n * 2. A business-rule pass coerces those leaves and checks what needs a\n * specific message: cross-references, disabled protocols and payment\n * methods, dynamic pricing, addresses, duplicate trust entries.\n *\n * Env substitution (`${VAR}` / `${VAR:-default}`) runs over the raw value\n * before both steps, so numeric and boolean fields can be templated. The one\n * exception is `version:`, checked before substitution: it decides whether this\n * parser understands the document at all, so it cannot depend on the\n * environment.\n */\nimport type { ZodError, ZodIssue, z } from 'zod';\nimport { CommerceError } from '../../core';\nimport { isRecord } from '../../core/is-record';\nimport { substituteEnv } from '../env';\nimport { normalize } from './normalize';\nimport { RawConfigSchema, SUPPORTED_CONFIG_VERSION } from './raw';\nimport type { GatewayConfig } from './types';\n\nexport function parseConfig(raw: unknown, env: NodeJS.ProcessEnv): GatewayConfig {\n if (!isRecord(raw)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n 'Configuration root must be a mapping (object) at \"$\"',\n {\n details: { path: '$' },\n },\n );\n }\n\n checkVersion(raw);\n\n const substituted = substituteEnv(raw, env);\n const parsed = parseWithZod(RawConfigSchema, substituted);\n return normalize(parsed);\n}\n\nfunction checkVersion(raw: Record<string, unknown>): void {\n if (!('version' in raw)) {\n throw new CommerceError('CONFIG_INVALID', 'Configuration is missing required field \"version\"', {\n details: { path: 'version' },\n });\n }\n const version = raw['version'];\n if (version !== SUPPORTED_CONFIG_VERSION) {\n const hint = typeof version === 'string' ? ', written as a number without quotes' : '';\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Unsupported config version \"${String(version)}\": this gateway only supports version ${SUPPORTED_CONFIG_VERSION}${hint}`,\n { details: { path: 'version', supported: SUPPORTED_CONFIG_VERSION } },\n );\n }\n}\n\nfunction parseWithZod<T>(schema: z.ZodType<T>, value: unknown): T {\n const result = schema.safeParse(value);\n if (!result.success) {\n throw zodErrorToConfigError(result.error);\n }\n return result.data;\n}\n\nfunction zodErrorToConfigError(error: ZodError): CommerceError {\n const issues = error.issues.map(describeIssue);\n const first = issues[0];\n const message = first\n ? `Configuration invalid at \"${first.path}\": ${first.message}`\n : 'Configuration invalid';\n return new CommerceError('CONFIG_INVALID', message, { details: { issues } });\n}\n\nfunction describeIssue(issue: ZodIssue): { path: string; message: string; code: string } {\n const path = issue.path.length > 0 ? issue.path.join('.') : '$';\n return { path, message: issue.message, code: issue.code };\n}\n\nexport type {\n AcpDiscoveryConfig,\n AcpProtocolConfig,\n GatewayConfig,\n X402OptionConfig,\n} from './types';\n","/**\n * Locates and parses `config.yaml`, then hands the raw value to `parseConfig`\n * for validation\n */\nimport { promises as fs } from 'node:fs';\nimport * as path from 'node:path';\nimport { parse as parseYaml, YAMLError } from 'yaml';\nimport { CommerceError } from '../core';\nimport { DEFAULT_CONFIG_FILENAME } from './filename';\nimport { type GatewayConfig, parseConfig } from './schema';\n\nconst CONFIG_PATH_ENV_VAR = 'AGENT_COMMERCE_CONFIG';\n\nexport interface LoadConfigOptions {\n readonly path?: string;\n readonly env?: NodeJS.ProcessEnv;\n readonly cwd?: string;\n}\n\nexport async function loadConfig(options: LoadConfigOptions = {}): Promise<GatewayConfig> {\n const env = options.env ?? process.env;\n const cwd = options.cwd ?? process.cwd();\n const configPath = resolveConfigPath(options.path, env, cwd);\n\n let text: string;\n try {\n text = await fs.readFile(configPath, 'utf8');\n } catch (error) {\n throw new CommerceError('CONFIG_INVALID', `Could not read configuration file \"${configPath}\"`, {\n details: { path: configPath },\n cause: error,\n });\n }\n\n let raw: unknown;\n try {\n raw = parseYaml(text);\n } catch (error) {\n const { reason, details } = describeYamlError(error);\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration file \"${configPath}\" is not valid YAML: ${reason}`,\n {\n details: { path: configPath, ...details },\n // Kept for programmatic callers. Never print it: its `.message` quotes\n // the source line (see describeYamlError).\n cause: error,\n },\n );\n }\n\n return parseConfig(raw, env);\n}\n\n// Plain-English phrasing for common YAML error codes. Fixed strings, so they\n// never carry file content; an unlisted code is shown bare.\nconst YAML_ERROR_EXPLANATIONS: Readonly<Record<string, string>> = {\n DUPLICATE_KEY: 'map keys must be unique',\n BAD_INDENT: 'bad indentation',\n TAB_AS_INDENT: 'tabs cannot be used for indentation',\n MISSING_CHAR: 'a required character is missing',\n BLOCK_AS_IMPLICIT_KEY: 'a block value cannot be used as a key (missing quotes, or a stray colon)',\n MULTILINE_IMPLICIT_KEY: 'a key spans multiple lines (missing quotes, or a stray colon)',\n UNEXPECTED_TOKEN: 'unexpected token',\n};\n\n/**\n * Describes a YAML failure from the error's structured `code` and `linePos`\n * only. The `yaml` package's `message` quotes the source line, and a syntax\n * error next to an inline secret (`server.adminToken`, a facilitator\n * `signerPrivateKey`) would print it in `validate` and `doctor` output.\n */\nfunction describeYamlError(error: unknown): {\n reason: string;\n details: Record<string, unknown>;\n} {\n if (!(error instanceof YAMLError)) {\n return { reason: 'unknown YAML parse error', details: {} };\n }\n const start = error.linePos?.[0];\n const where =\n start === undefined ? '' : ` at line ${String(start.line)}, column ${String(start.col)}`;\n const explanation = YAML_ERROR_EXPLANATIONS[error.code];\n const what = explanation === undefined ? error.code : `${error.code} (${explanation})`;\n return {\n reason: `${what}${where}`,\n details: {\n yamlErrorCode: error.code,\n ...(start === undefined ? {} : { line: start.line, column: start.col }),\n },\n };\n}\n\nfunction resolveConfigPath(\n explicitPath: string | undefined,\n env: NodeJS.ProcessEnv,\n cwd: string,\n): string {\n if (explicitPath) return path.resolve(cwd, explicitPath);\n const fromEnv = env[CONFIG_PATH_ENV_VAR];\n if (fromEnv) return path.resolve(cwd, fromEnv);\n return path.resolve(cwd, DEFAULT_CONFIG_FILENAME);\n}\n"]}
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
// src/authorization/ap2/constants.ts
|
|
2
|
-
var AP2_SPEC_VERSION = "0.2.0";
|
|
3
|
-
var AP2_MODES = ["direct"];
|
|
4
|
-
var AP2_SIGNING_ALGORITHM = "ES256";
|
|
5
|
-
var AP2_KEY_TYPE = "EC";
|
|
6
|
-
var AP2_JWK_CURVE = "P-256";
|
|
7
|
-
var AP2_JWK_COORDINATE_BYTES = 32;
|
|
8
|
-
var AP2_JWK_MEMBERS = ["kty", "crv", "x", "y", "kid", "alg", "use"];
|
|
9
|
-
var AP2_CHECKOUT_MANDATE_VCT = "mandate.checkout.1";
|
|
10
|
-
var AP2_CHECKOUT_PROFILE = "agent-commerce/ap2/checkout/v1";
|
|
11
|
-
var AP2_DIGEST_ALGORITHM = "sha-256";
|
|
12
|
-
var AP2_DEFAULT_CLOCK_SKEW_SECONDS = 60;
|
|
13
|
-
var AP2_MAX_CLOCK_SKEW_SECONDS = 300;
|
|
14
|
-
|
|
15
|
-
export { AP2_CHECKOUT_MANDATE_VCT, AP2_CHECKOUT_PROFILE, AP2_DEFAULT_CLOCK_SKEW_SECONDS, AP2_DIGEST_ALGORITHM, AP2_JWK_COORDINATE_BYTES, AP2_JWK_CURVE, AP2_JWK_MEMBERS, AP2_KEY_TYPE, AP2_MAX_CLOCK_SKEW_SECONDS, AP2_MODES, AP2_SIGNING_ALGORITHM, AP2_SPEC_VERSION };
|
|
16
|
-
//# sourceMappingURL=chunk-FHCFR2GS.js.map
|
|
17
|
-
//# sourceMappingURL=chunk-FHCFR2GS.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/authorization/ap2/constants.ts"],"names":[],"mappings":";AAQO,IAAM,gBAAA,GAAmB;AAOzB,IAAM,SAAA,GAAY,CAAC,QAAQ;AAO3B,IAAM,qBAAA,GAAwB;AAG9B,IAAM,YAAA,GAAe;AACrB,IAAM,aAAA,GAAgB;AAGtB,IAAM,wBAAA,GAA2B;AAOjC,IAAM,eAAA,GAAkB,CAAC,KAAA,EAAO,KAAA,EAAO,KAAK,GAAA,EAAK,KAAA,EAAO,OAAO,KAAK;AAOpE,IAAM,wBAAA,GAA2B;AAQjC,IAAM,oBAAA,GAAuB;AAO7B,IAAM,oBAAA,GAAuB;AAG7B,IAAM,8BAAA,GAAiC;AAMvC,IAAM,0BAAA,GAA6B","file":"chunk-FHCFR2GS.js","sourcesContent":["/**\n * Pinned AP2 identifiers and key policy.\n *\n * AP2 v0.2.0 (2026-04-28, commit b4587ac) is the tagged release this gateway\n * verifies against; unversioned `main` is never implemented against. Config,\n * the verifier and `doctor` all read these, so a bump lands in one place.\n */\n\nexport const AP2_SPEC_VERSION = '0.2.0';\n\n/**\n * Direct only. Autonomous mode needs open mandates, cnf-bound agent keys and\n * constraint evaluation over `checkout.line_items`, none of which is\n * implemented, so it is refused rather than partly served.\n */\nexport const AP2_MODES = ['direct'] as const;\nexport type Ap2Mode = (typeof AP2_MODES)[number];\n\n/**\n * A single algorithm, so `alg=none` and the HMAC family are excluded by\n * construction rather than by a denylist\n */\nexport const AP2_SIGNING_ALGORITHM = 'ES256';\n\n/** The key type and curve ES256 implies. Any other pair is refused at load */\nexport const AP2_KEY_TYPE = 'EC';\nexport const AP2_JWK_CURVE = 'P-256';\n\n/** Byte length of a P-256 coordinate, before base64url encoding */\nexport const AP2_JWK_COORDINATE_BYTES = 32;\n\n/**\n * JWK members a verification key may carry. An allowlist, so private material\n * (`d`) and URL members (`x5u`, `jku`) are refused without the list naming\n * them. Keys are configured inline and never fetched; see docs/security.md.\n */\nexport const AP2_JWK_MEMBERS = ['kty', 'crv', 'x', 'y', 'kid', 'alg', 'use'] as const;\n\n/**\n * Compared against this literal, never as a prefix. `mandate.checkout.open.1`\n * carries spending constraints nothing here evaluates, so accepting it would\n * tell a buyer their limits were checked when nothing read them.\n */\nexport const AP2_CHECKOUT_MANDATE_VCT = 'mandate.checkout.1';\n\n/**\n * Merchant checkout JWTs declare this gateway-specific profile; AP2 leaves\n * the checkout payload out of scope. The identifier is a namespace that\n * clients do not dereference. Merchants sign it into each checkout JWT, so\n * changing the expected value would reject previously signed JWTs.\n */\nexport const AP2_CHECKOUT_PROFILE = 'agent-commerce/ap2/checkout/v1';\n\n/**\n * The only accepted SD-JWT `_sd_alg` (an absent one means sha-256). Any other\n * value is refused rather than hashed as sha-256, which would check a\n * presentation under an algorithm it never claimed.\n */\nexport const AP2_DIGEST_ALGORITHM = 'sha-256';\n\n/** Seconds of clock skew tolerated on mandate and checkout time claims */\nexport const AP2_DEFAULT_CLOCK_SKEW_SECONDS = 60;\n\n/**\n * Skew as wide as a mandate's validity window would stop `exp` rejecting\n * anything. An operator who needs more than five minutes has a clock to fix.\n */\nexport const AP2_MAX_CLOCK_SKEW_SECONDS = 300;\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/core/domain/payment.ts","../../src/core/interfaces/runtime.ts","../../src/core/domain/common.ts","../../src/core/domain/resource.ts","../../src/core/domain/transaction.ts","../../src/core/domain/wire.ts","../../src/core/interfaces/logger.ts","../../src/core/interfaces/protocol-adapter.ts"],"names":[],"mappings":";;;;AAuBO,IAAM,2BAAA,GAA8B;;;ACRpC,IAAM,WAAA,GAAqB;AAAA,EAChC,GAAA,EAAK,sBAAM,IAAI,IAAA,EAAK;AAAA,EACpB,MAAA,EAAQ,MAAA,iBAAM,IAAI,IAAA,IAAO,WAAA,EAAY;AAAA,EACrC,WAAA,EAAa,MAAM,WAAA,CAAY,GAAA;AACjC;;;ACNA,IAAM,kBAAA,GAAiD;AAAA,EACrD,IAAA,EAAM,IAAA;AAAA,EACN,GAAA,EAAK,IAAA;AAAA,EACL,GAAA,EAAK,IAAA;AAAA,EACL,GAAA,EAAK;AACP,CAAA;AAMO,IAAM,iBAA0C,MAAA,CAAO,IAAA;AAAA,EAC5D;AACF;AAaA,IAAM,wBAAA,GAA4D,EAAE,IAAA,EAAM,IAAA,EAAM,KAAK,IAAA,EAAK;AAGnF,IAAM,uBAAqD,MAAA,CAAO,IAAA;AAAA,EACvE;AACF;;;ACCO,IAAM,0BAAA,GAA6B;;;AChCnC,IAAM,kBAAA,GAAqB;AAAA,EAChC,iBAAA;AAAA,EACA,gBAAA;AAAA,EACA,mBAAA;AAAA,EACA,qBAAA;AAAA,EACA,kBAAA;AAAA,EACA,kBAAA;AAAA,EACA;AACF;AAkFA,IAAM,SAAA,GAAY,CAAC,MAAA,KAA4B,MAAA,IAAU,OAAO,MAAA,IAAU,GAAA;AAOnE,SAAS,gBAAA,CACd,OACA,GAAA,EACqC;AACrC,EAAA,MAAM,EAAE,OAAA,EAAS,OAAA,EAAS,WAAA,EAAY,G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ACJ,OAAO,YAAA,KAAiB,QAAA,IAAY,YAAA,CAAa,MAAA,GAAS,CAAA,IAAK,MAAA,KAAW,MAAA,GACrE,EAAE,MAAA,EAAQ,OAAA,EAAS,cAAa,GACjC,MAAA;AACN,EAAA,MAAM,aAAA,GAAgB,4BAAA,CAA6B,kBAAA,EAAoB,SAAS,CAAA;AAEhF,EAAA,OAAO;AAAA,IACL,KAAA;AAAA,IACA,GAAI,OAAA,KAAY,MAAA,GAAY,EAAE,OAAA,KAAY,EAAC;AAAA,IAC3C,GAAI,aAAA,KAAkB,MAAA,GAAY,EAAE,aAAA,KAAkB;AAAC,GACzD;AACF;;;ACzVO,IAAM,WAAA,GAAsB;AAAA,EACjC,OAAO,MAAM;AAAA,EAAC,CAAA;AAAA,EACd,MAAM,MAAM;AAAA,EAAC,CAAA;AAAA,EACb,MAAM,MAAM;AAAA,EAAC,CAAA;AAAA,EACb,OAAO,MAAM;AAAA,EAAC,CAAA;AAAA,EACd,OAAO,MAAM;AACf;;;AC0DO,SAAS,sBAAsB,OAAA,EAA0D;AAC9F,EAAA,OAAO,OAAQ,QAAgC,UAAA,KAAe,UAAA;AAChE","file":"chunk-GET3CZGR.js","sourcesContent":["/**\n * Canonical payment model. FROZEN CONTRACT.\n *\n * Core decides that a payment is required and for how much. Payment providers\n * decide how the challenge is encoded, verified and settled. No x402- or\n * EVM-specific type may appear in this file.\n */\nimport type {\n AdapterDescriptor,\n AdapterHealth,\n DecimalAmount,\n IsoTimestamp,\n PaymentMethodName,\n} from './common';\nimport type { PaymentAttempt } from './receipt';\nimport type { CommerceResource } from './resource';\n\n/**\n * `PaymentResult.metadata` key for public coordinates returned by `verify`\n * for later provider reconciliation. Core must store the value unchanged and\n * interpret only `expiresAt`. Never include signatures, payloads or\n * transaction bytes. Experimental: may change in a minor release.\n */\nexport const RECONCILIATION_METADATA_KEY = 'reconciliation';\n\n/**\n * Provider-native payment challenge, opaque to core. For x402 the `accepts`\n * entries are x402 `PaymentRequirements` objects, passed to protocol adapters\n * verbatim.\n */\nexport interface PaymentChallenge {\n readonly provider: PaymentMethodName;\n /** Provider protocol version, e.g. the x402 `x402Version` value as a string */\n readonly version: string;\n readonly accepts: readonly Readonly<Record<string, unknown>>[];\n /**\n * The provider's own challenge document, verbatim: for x402 v2 the\n * `PaymentRequired` object a buyer's client consumes, for MPP an object\n * carrying the serialized `WWW-Authenticate` challenge. Opaque to core.\n *\n * `accepts` alone is not that document: x402 v2 carries the resource\n * description and protocol version on the envelope. Adapters with a native\n * channel for it (x402's `PAYMENT-REQUIRED` header, MPP's `WWW-Authenticate`)\n * send it there as is, so every surface offers the same challenge.\n */\n readonly envelope?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * What the buyer must pay, in canonical terms, plus the provider-native\n * challenge the buyer's client needs to construct a payment\n */\nexport interface PaymentRequirement {\n readonly id: string;\n readonly requestId: string;\n readonly resourceId: string;\n readonly provider: PaymentMethodName;\n readonly amount: DecimalAmount;\n readonly currency: string;\n /**\n * Merchant-controlled settlement destination, never a gateway-owned wallet.\n * Multi-offer challenges omit this, `network` and `asset`; selection\n * supplies the chosen offer's terms.\n */\n readonly destination?: string;\n readonly network?: string;\n readonly asset?: string;\n readonly expiresAt?: IsoTimestamp;\n readonly challenge: PaymentChallenge;\n readonly metadata?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * Opaque payment proof supplied by the buyer's client. For x402 over HTTP it is\n * the base64 `PAYMENT-SIGNATURE` header value; over MCP and A2A it is the same\n * string in the reserved `_payment` input field.\n */\nexport interface PaymentSubmission {\n readonly method: PaymentMethodName;\n readonly payload: string;\n}\n\n/** Outcome of verification or settlement */\nexport interface PaymentResult {\n readonly status: 'verified' | 'settled' | 'rejected';\n readonly provider: PaymentMethodName;\n /** Settlement reference, e.g. an on-chain transaction hash */\n readonly externalReference?: string;\n readonly payer?: string;\n readonly payee?: string;\n readonly amount: DecimalAmount;\n readonly currency: string;\n readonly network?: string;\n readonly asset?: string;\n /**\n * Stable, provider-computed identity of the payment authorization.\n *\n * The pipeline reserves this key before settlement and rejects a second\n * request presenting it with `PAYMENT_REPLAYED`. Providers must derive it\n * only from the authorization (payer, nonce, asset, network), so the same\n * authorization always maps to the same key. A `rejected` result may also\n * carry it so a store lookup can identify an unfinished attempt even when\n * verification rejects the proof because its transfer has landed.\n */\n readonly replayKey?: string;\n /** Machine-readable rejection reason when status is `rejected` */\n readonly rejectionReason?: string;\n readonly settledAt?: IsoTimestamp;\n readonly metadata?: Readonly<Record<string, unknown>>;\n}\n\n/** Input to {@link PaymentProvider.createRequirement} */\nexport interface PaymentContext {\n readonly requestId: string;\n readonly resource: CommerceResource;\n readonly amount: DecimalAmount;\n readonly currency: string;\n readonly requestedAt: IsoTimestamp;\n /**\n * Validated resource input used to build the backend request. The pipeline\n * sets this field on every createRequirement call. A rail may bind its\n * challenge to the input but must not send it to a third party.\n */\n readonly input?: unknown;\n readonly metadata?: Readonly<Record<string, unknown>>;\n}\n\n/** Input to {@link PaymentProvider.verify} */\nexport interface PaymentVerificationContext {\n readonly requestId: string;\n readonly resource: CommerceResource;\n readonly requirement: PaymentRequirement;\n readonly submission: PaymentSubmission;\n}\n\n/** Input to {@link PaymentProvider.settle} */\nexport interface PaymentSettlementContext extends PaymentVerificationContext {\n readonly verification: PaymentResult;\n}\n\n/** Input to {@link PaymentProvider.reconcile}. Experimental: may change in a minor release */\nexport interface PaymentReconciliationContext {\n readonly attempt: PaymentAttempt;\n /** Coordinates from `verify`; optional for compatibility with pre-2.5.0 attempts */\n readonly locator?: Readonly<Record<string, unknown>>;\n readonly now: IsoTimestamp;\n}\n\n/** Chain evidence for resolving an attempt. Experimental: may change in a minor release */\nexport interface PaymentReconciliationResult {\n /**\n * Report `settled` only with a final transfer record for this authorization.\n * Report `not-settled` only when a state read proves it unused after it can\n * no longer land; missing logs or receipts are insufficient. Otherwise,\n * report `unknown`.\n */\n readonly outcome: 'settled' | 'not-settled' | 'unknown';\n /** A machine-readable token, such as `not_final` */\n readonly reason: string;\n readonly externalReference?: string;\n /** Public chain facts only */\n readonly evidence?: Readonly<Record<string, unknown>>;\n /** For `unknown`, the earliest time a different answer is possible, if known */\n readonly retryAfter?: IsoTimestamp;\n}\n\n/**\n * Contract every payment rail implements. Implementations must be\n * non-custodial: they orchestrate an external payment protocol and never hold\n * buyer or merchant production signing keys.\n */\nexport interface PaymentProvider {\n readonly name: PaymentMethodName;\n readonly descriptor: AdapterDescriptor;\n\n /**\n * Build the requirement and its challenge. The pipeline calls it for every\n * paid request, including one that already carries a proof to verify.\n */\n createRequirement(context: PaymentContext): Promise<PaymentRequirement>;\n\n /**\n * Selects a proof's offer before verification, returning its destination,\n * network, asset and metadata while preserving `id` and the full `challenge`.\n * Verification, authorization, replay reservation and settlement use the result.\n * This hook must not verify, reserve or settle. If no unique offer matches,\n * return the original requirement for `verify` to reject.\n */\n selectRequirement?(context: PaymentVerificationContext): Promise<PaymentRequirement>;\n\n /**\n * Validate a submitted proof against the requirement. Must return `rejected`\n * or throw a `CommerceError` rather than an untyped error, and must never\n * move funds.\n */\n verify(context: PaymentVerificationContext): Promise<PaymentResult>;\n\n /**\n * Execute settlement. Called only after `verify` returned `verified` and the\n * replay key was reserved. A settlement verdict, including a rejection, is a\n * returned result; the pipeline records any throw as settlement-uncertain.\n */\n settle(context: PaymentSettlementContext): Promise<PaymentResult>;\n\n /**\n * Read chain evidence for an attempt with an unknown outcome. Implementations\n * must not write, broadcast or call a facilitator. Providers without this\n * hook require manual resolution. Experimental: may change in a minor release.\n */\n reconcile?(context: PaymentReconciliationContext): Promise<PaymentReconciliationResult>;\n\n health(): Promise<AdapterHealth>;\n}\n","// Time and ids are injected so tests can be deterministic\nimport type { IsoTimestamp } from '../domain/common';\n\nexport interface Clock {\n now(): Date;\n nowIso(): IsoTimestamp;\n /** Milliseconds since an arbitrary origin; use for durations only */\n monotonicMs(): number;\n}\n\nexport interface IdGenerator {\n /** Opaque, collision-resistant identifier */\n next(prefix?: string): string;\n}\n\nexport const systemClock: Clock = {\n now: () => new Date(),\n nowIso: () => new Date().toISOString(),\n monotonicMs: () => performance.now(),\n};\n","// Shared primitive aliases for the canonical domain model. FROZEN CONTRACT\n\n/**\n * A JSON Schema document (in practice a draft 2020-12 subset). Deliberately\n * loose: adapters translate it to their own schema representation. Never treat\n * it as trusted input without validation.\n */\nexport type JsonSchema = Record<string, unknown>;\n\n/** Protocol surfaces a resource can be exposed through */\nexport type ProtocolName = 'http' | 'mcp' | 'a2a' | 'acp';\n\n// A Record over the union fails to compile when a name is missing or extra\nconst PROTOCOL_NAME_KEYS: Record<ProtocolName, true> = {\n http: true,\n mcp: true,\n a2a: true,\n acp: true,\n};\n\n/**\n * The same names as a value, for code that checks one at runtime: config\n * validation and the OpenAPI importer's `--expose`\n */\nexport const PROTOCOL_NAMES: readonly ProtocolName[] = Object.keys(\n PROTOCOL_NAME_KEYS,\n) as ProtocolName[];\n\n/**\n * Payment rails a resource can accept.\n *\n * A resource's list is an ordered candidate list, not a buyer-selected menu.\n * The pipeline uses the first method with an enabled provider, and a\n * rejection ends the request instead of trying another rail. Config requires at\n * least one named rail to be enabled and permits others that are not.\n */\nexport type PaymentMethodName = 'x402' | 'mpp';\n\n// Checked for completeness the same way as PROTOCOL_NAME_KEYS\nconst PAYMENT_METHOD_NAME_KEYS: Record<PaymentMethodName, true> = { x402: true, mpp: true };\n\n/** The same names as a value, for config validation */\nexport const PAYMENT_METHOD_NAMES: readonly PaymentMethodName[] = Object.keys(\n PAYMENT_METHOD_NAME_KEYS,\n) as PaymentMethodName[];\n\n/**\n * Authorization methods a resource can require. Neither a transport nor a\n * payment rail: it proves the purchase was approved, and sits beside the\n * payment rather than replacing it.\n */\nexport type AuthorizationMethodName = 'ap2';\n\n/** ISO-8601 timestamp string, always UTC with millisecond precision */\nexport type IsoTimestamp = string;\n\n/**\n * A decimal amount as a string in the currency's display unit (for example\n * \"0.01\" USDC), never a float and never base units. Payment providers convert\n * it to on-chain base units.\n */\nexport type DecimalAmount = string;\n\n/** Health of an individual adapter or subsystem */\nexport interface AdapterHealth {\n readonly status: 'pass' | 'warn' | 'fail';\n readonly detail?: string;\n readonly checkedAt: IsoTimestamp;\n readonly durationMs?: number;\n /**\n * Results per checked part, such as each x402 offer. Names and statuses\n * may be published; exclude diagnostic detail.\n */\n readonly components?: readonly AdapterHealthComponent[];\n}\n\n/** One part of an {@link AdapterHealth} result */\nexport interface AdapterHealthComponent {\n readonly name: string;\n readonly status: 'pass' | 'warn' | 'fail';\n}\n\n/** Describes an adapter's supported surface for diagnostics */\nexport interface AdapterDescriptor {\n readonly name: string;\n readonly kind: 'protocol' | 'payment' | 'storage' | 'authorization';\n /** Version of this adapter implementation, independent of the spec */\n readonly implementationVersion: string;\n /** Exact pinned specification revision this adapter targets */\n readonly supportedSpec: string;\n readonly capabilities: readonly string[];\n readonly status: 'stable' | 'experimental' | 'planned';\n /** Capabilities explicitly not implemented, printed by `doctor` */\n readonly unsupported?: readonly string[];\n}\n","// Canonical resource model. FROZEN CONTRACT\nimport type {\n AuthorizationMethodName,\n DecimalAmount,\n JsonSchema,\n PaymentMethodName,\n ProtocolName,\n} from './common';\n\n/** HTTP methods a backend handler may use */\nexport type BackendMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n/**\n * How the gateway calls the merchant's existing backend.\n *\n * Backend URLs come from operator configuration only, never from users or\n * agents (docs/security.md, SSRF). Secret header values belong in `${ENV_VAR}`\n * placeholders resolved by the config loader, not in plaintext configuration.\n */\nexport interface BackendHandler {\n readonly type: 'http';\n readonly method: BackendMethod;\n readonly url: string;\n readonly headers?: Readonly<Record<string, string>>;\n /** Hard upper bound on the backend call. Defaults to `DEFAULT_BACKEND_TIMEOUT_MS` */\n readonly timeoutMs?: number;\n /**\n * Names the top-level input properties carrying each part of the request.\n *\n * When absent, `{param}` values come from top-level input and everything left\n * over becomes the query string (GET/DELETE) or the whole JSON body\n * (POST/PUT/PATCH). That cannot express an operation with path, query and\n * body at once, such as `POST /users/{userId}/orders?notify=true`.\n *\n * When present, each group comes from its named property, and top-level input\n * that no binding names is not forwarded.\n */\n readonly inputBindings?: {\n readonly path?: string;\n readonly query?: string;\n readonly body?: string;\n };\n}\n\n/** Default backend timeout when a resource does not specify one */\nexport const DEFAULT_BACKEND_TIMEOUT_MS = 10_000;\n\n/**\n * Canonical pricing. `dynamic` exists in the type for forward compatibility;\n * config validation rejects it and the pipeline refuses it as defense in depth.\n */\nexport type Pricing =\n | { readonly type: 'free' }\n | {\n readonly type: 'fixed';\n readonly amount: DecimalAmount;\n readonly currency: string;\n }\n | {\n readonly type: 'dynamic';\n readonly resolver: string;\n };\n\n/**\n * A merchant capability exposed to agents. Protocol adapters map it outward and\n * never define their own parallel notion of a resource.\n */\nexport interface CommerceResource {\n readonly id: string;\n readonly name: string;\n readonly description?: string;\n readonly inputSchema?: JsonSchema;\n readonly outputSchema?: JsonSchema;\n readonly handler: BackendHandler;\n readonly pricing: Pricing;\n readonly exposedVia: readonly ProtocolName[];\n readonly paymentMethods: readonly PaymentMethodName[];\n /**\n * Authorization the buyer must present in addition to payment. Opt-in per\n * resource. It sits beside `paymentMethods`, not inside it, because an\n * authorization method is not a payment rail and must never be selectable as\n * one.\n */\n readonly authorization?: {\n readonly required: readonly AuthorizationMethodName[];\n };\n}\n\n/** Read-only view of every configured resource */\nexport interface ResourceRegistry {\n get(id: string): CommerceResource | undefined;\n list(): readonly CommerceResource[];\n /** Resources exposed through a given protocol surface */\n listExposedVia(protocol: ProtocolName): readonly CommerceResource[];\n has(id: string): boolean;\n}\n","/**\n * Canonical transaction model. FROZEN CONTRACT.\n *\n * A transaction links a paid purchase's request, payment attempt, optional\n * authorization hold, backend call and receipt by ID. PaymentAttempt owns the\n * payment status; journal readers must read it from the attempt rather than\n * maintain a separate copy.\n */\nimport type { AuthorizationRecord } from './authorization';\nimport type { DecimalAmount, IsoTimestamp, PaymentMethodName, ProtocolName } from './common';\nimport type { PaymentAttempt } from './receipt';\n\n/** States derived by {@link transactionState} */\nexport const TRANSACTION_STATES = [\n 'payment-pending',\n 'payment-failed',\n 'payment-uncertain',\n 'settled-undelivered',\n 'delivery-started',\n 'delivery-unknown',\n 'delivered',\n] as const;\n\n/**\n * Open to state names added by later releases; consumers must handle values\n * outside {@link TRANSACTION_STATES}\n */\nexport type TransactionState = (typeof TRANSACTION_STATES)[number] | (string & {});\n\n/** Last hold state communicated to the authorization provider */\nexport type AuthorizationHoldState = 'reserved' | 'consumed' | 'released' | 'uncertain';\n\n/**\n * Store writes reported as failed during an execution. Consumers must handle\n * unlisted labels that later releases may add.\n */\nexport type PersistenceFailure = 'payment-attempt' | 'receipt' | 'journal' | (string & {});\n\n/**\n * Journal record for a paid purchase, starting with replay reservation.\n * Store only references and digests, never payment proofs, signatures, mandates\n * or input bodies.\n */\nexport interface Transaction {\n readonly id: string;\n /** The request that created it */\n readonly requestId: string;\n readonly resourceId: string;\n readonly protocol: ProtocolName;\n /** Cached derived state; readers must recompute it with {@link transactionState} */\n readonly state: TransactionState;\n readonly payment: {\n readonly provider: PaymentMethodName;\n readonly attemptId: string;\n readonly replayKey: string;\n /** Read from PaymentAttempt, not maintained independently */\n readonly status: PaymentAttempt['status'];\n readonly amount: DecimalAmount;\n readonly currency: string;\n readonly network?: string;\n readonly asset?: string;\n readonly payee?: string;\n readonly externalReference?: string;\n /**\n * Public coordinates for the provider's `reconcile` hook, governed by\n * `RECONCILIATION_METADATA_KEY`\n */\n readonly locator?: Readonly<Record<string, unknown>>;\n /** When the provider's `settle` was called */\n readonly settlingAt?: IsoTimestamp;\n /** The authorization cannot land after this */\n readonly expiresAt?: IsoTimestamp;\n };\n readonly authorization?: AuthorizationRecord & {\n /** The handle the authorization provider consumes or releases */\n readonly reservationId: string;\n readonly hold: AuthorizationHoldState;\n };\n readonly backend?: {\n readonly dispatchedAt: IsoTimestamp;\n /** Dispatch time plus the backend timeout and a margin */\n readonly deadlineAt: IsoTimestamp;\n /** 0 if the call ended without a status, such as a timeout or transport failure */\n readonly status?: number;\n readonly errorCode?: string;\n };\n readonly receiptId?: string;\n /** `sha256:` followed by the canonical JSON input digest in hex; omit for non-I-JSON input */\n readonly inputDigest?: string;\n /** Digest of pricing and settlement terms, excluding credentials */\n readonly configDigest: string;\n readonly persistenceFailures?: readonly PersistenceFailure[];\n readonly createdAt: IsoTimestamp;\n readonly updatedAt: IsoTimestamp;\n /** Time of the pipeline's last journal write before returning the outcome */\n readonly completedAt?: IsoTimestamp;\n}\n\n/** What {@link transactionState} reads */\nexport type TransactionFacts = Pick<Transaction, 'backend' | 'completedAt'> & {\n readonly payment: Pick<Transaction['payment'], 'status'>;\n};\n\nconst isSuccess = (status: number): boolean => status >= 200 && status <= 299;\n\n/**\n * Derive state from payment status, backend facts and pipeline completion.\n * For a settled payment, a dispatched call with no result after `deadlineAt`\n * means `delivery-unknown`; a timeout does not prove that the backend never ran.\n */\nexport function transactionState(\n facts: TransactionFacts,\n now: IsoTimestamp,\n): (typeof TRANSACTION_STATES)[number] {\n const { payment, backend, completedAt } = facts;\n if (payment.status === 'settlement-uncertain' || payment.status === 'failed') {\n return 'payment-uncertain';\n }\n if (payment.status === 'rejected') return 'payment-failed';\n\n // Invalid timestamps make the comparison false, treating the deadline as passed\n const waiting =\n backend !== undefined &&\n completedAt === undefined &&\n Date.parse(now) < Date.parse(backend.deadlineAt);\n if (payment.status !== 'settled') {\n return waiting && backend?.status === undefined ? 'delivery-started' : 'payment-pending';\n }\n\n if (backend === undefined) return 'settled-undelivered';\n const { status } = backend;\n if (status !== undefined && status !== 0 && !isSuccess(status)) return 'settled-undelivered';\n if (status !== undefined && isSuccess(status) && completedAt !== undefined) return 'delivered';\n // Wait until the deadline for a missing result or an unfinished 2xx flow.\n // Status 0 means the call already ended without a response.\n if (status !== 0 && waiting) return 'delivery-started';\n return 'delivery-unknown';\n}\n","/**\n * Gateway-defined wire envelopes and carriers. FROZEN CONTRACT.\n *\n * The HTTP routes and the MCP and A2A adapters build their \"payment required\"\n * and \"error\" bodies with these helpers, so those surfaces send the same\n * shapes. The ACP adapter maps errors to ACP's own error format instead.\n */\n\nimport { CommerceError, type CommerceErrorCode } from '../errors';\nimport { isRecord } from '../is-record';\nimport type { AuthorizationRequirement, AuthorizationSubmission } from './authorization';\nimport type { DecimalAmount, IsoTimestamp, PaymentMethodName } from './common';\nimport type { PaymentSubmission } from './payment';\nimport type { DeliveredOutcome, PaymentRequiredOutcome } from './request';\nimport type { CommerceResource } from './resource';\n\n/**\n * Reserved input property carrying a payment proof on protocols with no header\n * channel (MCP tool calls, A2A message data). HTTP uses a header instead.\n */\nexport const PAYMENT_INPUT_FIELD = '_payment';\n\n/**\n * HTTP request header carrying an x402 payment proof. MPP proofs use\n * `Authorization: Payment ...` instead.\n *\n * The x402 v2 header names, lowercased as Node presents incoming headers. v1's\n * `X-PAYMENT` / `X-PAYMENT-RESPONSE` pair is not accepted: honoring both\n * versions would mean two verification paths for the same money.\n */\nexport const PAYMENT_HEADER = 'payment-signature';\n\n/** HTTP response header carrying the settlement result */\nexport const PAYMENT_RESPONSE_HEADER = 'payment-response';\n\n/**\n * Reserved input property carrying an authorization proof, the counterpart of\n * {@link PAYMENT_INPUT_FIELD}.\n *\n * `_payment` is a bare string whose method is taken from the resource's first\n * payment method. This field is a `{ method, payload }` object, because the\n * method of a security control should be stated, not inferred.\n */\nexport const AUTHORIZATION_INPUT_FIELD = '_authorization';\n\n/**\n * Every input property name the gateway claims for itself. The config loader\n * rejects a resource declaring one, protocol adapters lift them out of client\n * input, and the pipeline strips them again as defense in depth.\n */\nexport const RESERVED_INPUT_FIELDS: readonly string[] = [\n PAYMENT_INPUT_FIELD,\n AUTHORIZATION_INPUT_FIELD,\n];\n\n/**\n * HTTP request header carrying the authorization proof: base64url-encoded JSON\n * of the same `{ method, payload }` object the reserved input field carries.\n *\n * An Agent Commerce carrier, not a header from any authorization\n * specification. It is namespaced rather than reusing `Authorization`, which\n * already carries other credentials, including MPP payment proofs.\n */\nexport const AUTHORIZATION_HEADER = 'agent-authorization';\n\n/**\n * Hard cap on the encoded `Agent-Authorization` header.\n *\n * Node's default limit is 16 KiB across all request headers, and a request over\n * it is refused before the gateway sees it. Capping well below that gives an\n * oversized proof a deterministic `AUTHORIZATION_INVALID` naming the limit.\n */\nexport const MAX_AUTHORIZATION_HEADER_BYTES = 8192;\n\n/**\n * HTTP response header carrying the base64 x402 challenge on a 402.\n *\n * The body still carries the richer {@link PaymentRequiredEnvelope}, the only\n * channel MCP has, but an x402 v2 client reads the challenge from this header\n * and ignores the body, so both are sent.\n */\nexport const PAYMENT_REQUIRED_HEADER = 'payment-required';\n\n/**\n * Key under which a protocol adapter attaches a {@link DeliverySummary} to its\n * result metadata: MCP's `CallToolResult._meta` and the A2A task artifact's\n * metadata.\n *\n * Part of the frozen contract because producer and consumer must agree on it;\n * both import this constant. Follows MCP's `<namespace>/<name>` convention for\n * `_meta` keys.\n */\nexport const DELIVERY_SUMMARY_META_KEY = 'agent-commerce/delivery';\n\nexport interface PaymentRequiredEnvelope {\n readonly status: 'payment-required';\n readonly code: 'PAYMENT_REQUIRED';\n readonly requestId: string;\n readonly resourceId: string;\n readonly message: string;\n readonly payment: {\n readonly provider: PaymentMethodName;\n readonly version: string;\n readonly amount: DecimalAmount;\n readonly currency: string;\n /**\n * @deprecated Read `accepts`: x402 offers use `payTo`; MPP challenges use\n * `request.recipient`. Omitted for multi-offer x402 challenges.\n */\n readonly destination?: string;\n /**\n * @deprecated Read `accepts`: x402 offers use `network`; MPP challenges use\n * the numeric `request.methodDetails.chainId`\n */\n readonly network?: string;\n /**\n * @deprecated Read `accepts`: x402 offers use `asset`; MPP challenges use\n * `request.currency`\n */\n readonly asset?: string;\n readonly expiresAt?: IsoTimestamp;\n /** Provider-native requirement objects, passed through verbatim */\n readonly accepts: readonly Readonly<Record<string, unknown>>[];\n /**\n * The provider's own challenge document, verbatim (see\n * {@link PaymentChallenge.envelope}). Present for providers that have one;\n * a buyer's protocol client can hand it straight to its SDK.\n */\n readonly envelope?: Readonly<Record<string, unknown>>;\n };\n /**\n * Present only when the resource also requires an authorization proof, so a\n * client learns before it spends anything that paying alone will not get the\n * resource delivered. A client that ignores the field sees the plain\n * envelope. The proof comes from the merchant's own approval flow, outside\n * the gateway.\n */\n readonly authorization?: {\n readonly required: readonly AuthorizationRequirement[];\n };\n}\n\nexport interface ErrorEnvelope {\n readonly status: 'error';\n readonly code: CommerceErrorCode;\n readonly message: string;\n readonly retryable: boolean;\n readonly requestId?: string;\n readonly resourceId?: string;\n readonly details?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * What a buyer learns about their own completed purchase: the request, whether\n * it settled, and the settlement reference they can check on-chain. The\n * merchant's ledger is not theirs to read, which is why `/api/receipts` is an\n * operator route behind `server.adminToken`.\n */\nexport interface DeliverySummary {\n readonly requestId: string;\n readonly resourceId: string;\n readonly receiptId: string;\n /** `false` marks a failed receipt write; do not treat `receiptId` as proof of persistence */\n readonly receiptCommitted?: false;\n readonly deliveredAt: IsoTimestamp;\n readonly payment?: {\n readonly status: 'verified' | 'settled' | 'rejected';\n readonly amount: DecimalAmount;\n readonly currency: string;\n /** Settlement reference, e.g. an on-chain transaction hash */\n readonly externalReference?: string;\n readonly network?: string;\n };\n}\n\n/** Build the payer-facing summary of a delivered outcome */\nexport function toDeliverySummary(outcome: DeliveredOutcome): DeliverySummary {\n const p = outcome.payment;\n return {\n requestId: outcome.requestId,\n resourceId: outcome.resourceId,\n receiptId: outcome.receipt.id,\n ...(outcome.persistenceFailures?.includes('receipt') ? { receiptCommitted: false } : {}),\n deliveredAt: outcome.receipt.deliveredAt,\n ...(p !== undefined\n ? {\n payment: {\n status: p.status,\n amount: p.amount,\n currency: p.currency,\n ...(p.externalReference !== undefined\n ? { externalReference: p.externalReference }\n : {}),\n ...(p.network !== undefined ? { network: p.network } : {}),\n },\n }\n : {}),\n };\n}\n\nexport function toPaymentRequiredEnvelope(\n outcome: PaymentRequiredOutcome,\n): PaymentRequiredEnvelope {\n const r = outcome.requirement;\n return {\n status: 'payment-required',\n code: 'PAYMENT_REQUIRED',\n requestId: outcome.requestId,\n resourceId: outcome.resourceId,\n message: `Payment of ${r.amount} ${r.currency} is required for resource \"${outcome.resourceId}\". Retry with a ${r.provider} payment proof.`,\n payment: {\n provider: r.provider,\n version: r.challenge.version,\n amount: r.amount,\n currency: r.currency,\n ...(r.destination !== undefined ? { destination: r.destination } : {}),\n ...(r.network !== undefined ? { network: r.network } : {}),\n ...(r.asset !== undefined ? { asset: r.asset } : {}),\n ...(r.expiresAt !== undefined ? { expiresAt: r.expiresAt } : {}),\n accepts: r.challenge.accepts,\n ...(r.challenge.envelope !== undefined ? { envelope: r.challenge.envelope } : {}),\n },\n ...(outcome.authorization !== undefined && outcome.authorization.length > 0\n ? { authorization: { required: outcome.authorization } }\n : {}),\n };\n}\n\nexport function toErrorEnvelope(error: CommerceError): ErrorEnvelope {\n const info = error.toInfo();\n return {\n status: 'error',\n code: info.code,\n message: info.message,\n retryable: info.retryable,\n ...(info.requestId !== undefined ? { requestId: info.requestId } : {}),\n ...(info.resourceId !== undefined ? { resourceId: info.resourceId } : {}),\n ...(info.details !== undefined ? { details: info.details } : {}),\n };\n}\n\nexport function isPaymentRequiredEnvelope(value: unknown): value is PaymentRequiredEnvelope {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as PaymentRequiredEnvelope).status === 'payment-required' &&\n typeof (value as PaymentRequiredEnvelope).payment === 'object'\n );\n}\n\n/**\n * Parses the `{ method, payload }` authorization object, whichever carrier\n * brought it. Absent returns `undefined`; malformed throws\n * `AUTHORIZATION_INVALID`.\n *\n * An unusable `_payment` is dropped, which leaves the buyer a 402 to act on. A\n * dropped authorization would instead come back as \"not authorized\", with no\n * way to tell a rejected mandate from a typo in the object around it.\n */\nexport function parseAuthorizationSubmission(\n value: unknown,\n requestId?: string,\n): AuthorizationSubmission | undefined {\n if (value === undefined || value === null) return undefined;\n\n const fail = (detail: string): never => {\n throw new CommerceError('AUTHORIZATION_INVALID', `Malformed authorization: ${detail}`, {\n ...(requestId !== undefined ? { requestId } : {}),\n });\n };\n\n if (!isRecord(value)) {\n return fail(`expected an object with \"method\" and \"payload\", got ${typeof value}`);\n }\n const method = value['method'];\n const payload = value['payload'];\n\n // Compared against the literal rather than a registry: a second method needs\n // a second verifier, a deliberate addition rather than a string that starts\n // working because a client sent it\n if (method !== 'ap2') {\n fail(`unsupported method ${typeof method === 'string' ? `\"${method}\"` : typeof method}`);\n }\n if (typeof payload !== 'string' || payload.length === 0) {\n fail('\"payload\" must be a non-empty string');\n }\n\n return { method: 'ap2', payload: payload as string };\n}\n\n/**\n * Decodes the base64url JSON `Agent-Authorization` header. The size check runs\n * on the encoded value, so an oversized header costs a length comparison rather\n * than a decode and a JSON parse.\n */\nexport function parseAuthorizationHeader(\n raw: string | readonly string[] | undefined,\n requestId?: string,\n): AuthorizationSubmission | undefined {\n const value = Array.isArray(raw) ? raw[0] : (raw as string | undefined);\n if (value === undefined || value.length === 0) return undefined;\n\n const fail = (detail: string): never => {\n throw new CommerceError('AUTHORIZATION_INVALID', `Malformed authorization: ${detail}`, {\n ...(requestId !== undefined ? { requestId } : {}),\n });\n };\n\n if (Buffer.byteLength(value, 'utf8') > MAX_AUTHORIZATION_HEADER_BYTES) {\n fail(`header exceeds the ${MAX_AUTHORIZATION_HEADER_BYTES}-byte limit`);\n }\n\n let decoded: unknown;\n try {\n decoded = JSON.parse(Buffer.from(value, 'base64url').toString('utf8'));\n } catch {\n // Nothing from the exception is repeated back: a JSON parse error quotes\n // the input it choked on, which here is whatever the caller sent\n fail('header is not base64url-encoded JSON');\n }\n return parseAuthorizationSubmission(decoded, requestId);\n}\n\n/**\n * Splits raw client input into resource input plus the reserved fields, for\n * protocols that carry them in the input object (MCP tool arguments, A2A\n * message data). HTTP carries both in headers.\n *\n * A payment proof is labeled with the resource's first payment method.\n * `createGateway` puts provider-backed methods first so the label matches the\n * pipeline's selection; a custom registry must keep that order. A resource with\n * no payment method gets no payment proof, so the request reaches the pipeline\n * unpaid.\n */\nexport function extractReservedInputFields(\n rawInput: Record<string, unknown>,\n resource: CommerceResource | undefined,\n requestId?: string,\n): {\n input: Record<string, unknown>;\n payment?: PaymentSubmission;\n authorization?: AuthorizationSubmission;\n} {\n const {\n [PAYMENT_INPUT_FIELD]: paymentValue,\n [AUTHORIZATION_INPUT_FIELD]: authorizationValue,\n ...input\n } = rawInput;\n\n const method = resource?.paymentMethods[0];\n const payment =\n typeof paymentValue === 'string' && paymentValue.length > 0 && method !== undefined\n ? ({ method, payload: paymentValue } satisfies PaymentSubmission)\n : undefined;\n const authorization = parseAuthorizationSubmission(authorizationValue, requestId);\n\n return {\n input,\n ...(payment !== undefined ? { payment } : {}),\n ...(authorization !== undefined ? { authorization } : {}),\n };\n}\n","/**\n * Minimal structural logger. Core does not depend on pino; the gateway injects\n * a pino instance that satisfies this shape.\n *\n * Never log secrets: private keys, seed phrases, Authorization headers or\n * payment authorization payloads.\n */\nexport interface Logger {\n debug(obj: Record<string, unknown>, msg?: string): void;\n info(obj: Record<string, unknown>, msg?: string): void;\n warn(obj: Record<string, unknown>, msg?: string): void;\n error(obj: Record<string, unknown>, msg?: string): void;\n child(bindings: Record<string, unknown>): Logger;\n}\n\n/** A logger that discards everything */\nexport const NOOP_LOGGER: Logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n child: () => NOOP_LOGGER,\n};\n","/**\n * Protocol adapter boundary. FROZEN CONTRACT.\n *\n * An adapter translates a protocol's wire format into a `CanonicalRequest`,\n * hands it to the execution pipeline and maps the outcome back. It must not\n * call merchant backends, implement payment logic or hold its own copy of the\n * canonical model. A failure while starting or serving one adapter must not\n * stop the others.\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { AdapterDescriptor, AdapterHealth, ProtocolName } from '../domain/common';\nimport type { EventSink } from '../domain/event';\nimport type { ExecutionPipeline } from '../domain/request';\nimport type { ResourceRegistry } from '../domain/resource';\nimport type { Logger } from './logger';\nimport type { Clock, IdGenerator } from './runtime';\n\n/** Everything an adapter is given. Nothing else is available to it */\nexport interface ProtocolAdapterContext {\n readonly pipeline: ExecutionPipeline;\n readonly resources: ResourceRegistry;\n readonly events: EventSink;\n readonly logger: Logger;\n readonly clock: Clock;\n readonly ids: IdGenerator;\n /** Externally reachable base URL of the gateway, from config */\n readonly publicBaseUrl: string;\n}\n\nexport interface ProtocolAdapter {\n readonly name: ProtocolName;\n readonly descriptor: AdapterDescriptor;\n\n start(context: ProtocolAdapterContext): Promise<void>;\n health(): Promise<AdapterHealth>;\n stop(): Promise<void>;\n}\n\n/**\n * A protocol adapter served over HTTP. The gateway mounts `handleHttp` at\n * `mountPath` with raw Node request and response objects, so adapters stay\n * independent of the HTTP framework.\n *\n * Guarantee: `req` arrives with its body stream unread. The gateway suppresses\n * every body parser on the mount, so an adapter whose SDK reads the body itself\n * (MCP's Streamable HTTP transport) can do so. The adapter owns reading,\n * size-limiting beyond the gateway's own cap, and parsing.\n *\n * The guarantee can break silently. Fastify prefers its exact-match\n * `application/json` and `text/plain` parsers over a `'*'` wildcard, so a\n * wildcard no-op alone lets the JSON parser drain the body and the adapter\n * reads an empty stream. The MCP conformance suite drives `handleHttp` over a\n * bare `node:http` server and cannot catch it, so any change to adapter mounting\n * needs a test that POSTs a JSON body through the real gateway and asserts the\n * adapter received it intact.\n */\nexport interface HttpProtocolAdapter extends ProtocolAdapter {\n /** Path prefix the gateway mounts this adapter at, e.g. '/mcp' */\n readonly mountPath: string;\n handleHttp(req: IncomingMessage, res: ServerResponse): Promise<void>;\n /**\n * Fixed paths this adapter owns outside its mount, for protocols whose\n * specification pins a discovery URL (A2A's `/.well-known/agent-card.json`).\n * The gateway mounts them with the same guarantees as `mountPath`: unread\n * body, concurrency cap and failure isolation.\n */\n readonly additionalHttpRoutes?: readonly AdapterHttpRoute[];\n}\n\n/**\n * One fixed, method-scoped route owned by an adapter. Unlike `mountPath` it\n * registers no wildcard and matches exactly the path given.\n */\nexport interface AdapterHttpRoute {\n readonly method: 'GET' | 'POST';\n /** Absolute gateway path, e.g. '/.well-known/agent-card.json' */\n readonly path: string;\n handleHttp(req: IncomingMessage, res: ServerResponse): Promise<void>;\n}\n\nexport function isHttpProtocolAdapter(adapter: ProtocolAdapter): adapter is HttpProtocolAdapter {\n return typeof (adapter as HttpProtocolAdapter).handleHttp === 'function';\n}\n"]}
|