@devlab.group/agent-commerce 1.2.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -18
- package/dist/{chunk-EIACECVM.js → chunk-N3DNLXGC.js} +4 -4
- package/dist/chunk-N3DNLXGC.js.map +1 -0
- package/dist/{chunk-5TKNTWMC.js → chunk-TBZA6Z5B.js} +3 -3
- package/dist/{chunk-5TKNTWMC.js.map → chunk-TBZA6Z5B.js.map} +1 -1
- package/dist/cli/index.js +387 -52
- package/dist/cli/index.js.map +1 -1
- package/dist/index.d.ts +153 -6
- package/dist/index.js +5359 -201
- package/dist/index.js.map +1 -1
- package/dist/mcp.d.ts +2 -2
- package/dist/mcp.js +1 -1
- package/dist/{protocol-adapter-BAKGnuZ4.d.ts → protocol-adapter-DTFGWGXq.d.ts} +2 -2
- package/dist/{runtime-Bqg9qW3t.d.ts → runtime-Plk5Peqi.d.ts} +3 -3
- package/dist/x402.d.ts +1 -1
- package/dist/x402.js +3 -3
- package/package.json +3 -1
- package/dist/chunk-EIACECVM.js.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/config/env.ts","../src/config/filename.ts","../src/core/execution/backend-http.ts","../src/core/execution/event-bus.ts","../src/core/execution/validation.ts","../src/core/execution/pipeline.ts","../src/core/execution/registry.ts","../src/config/schema.ts","../src/config/load.ts","../src/gateway/ids.ts","../src/gateway/logger.ts","../src/gateway/access-control.ts","../src/gateway/adapters.ts","../src/gateway/public-resource.ts","../src/gateway/readiness.ts","../src/gateway/well-known.ts","../src/gateway/routes.ts","../src/gateway/server.ts","../src/storage/receipts/redact.ts","../src/storage/receipts/rows.ts","../src/storage/receipts/schema.ts","../src/storage/receipts/store.ts"],"names":["path","isPlainObject","durationMs","url","describeError","fs","parseYaml","randomUUID","fsConstants"],"mappings":";;;;;;;;;;;;;;;AAoCA,IAAM,mBAAA,GAAsB,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AA,EAAU,cAAA,EAAe;AAAA,YAC3C;AAAA,WACF;AACA,UAAA,OAAO;AAAA,YACL,MAAA,EAAQ,MAAA;AAAA,YACR,MAAA,EAAQ,uBAAA;AAAA,YACR,SAAA,EAAW,MAAM,MAAA,EAAO;AAAA,YACxB,UAAA,EAAY,KAAA,CAAM,WAAA,EAAY,GAAI;AAAA,WACpC;AAAA,QACF;AACA,QAAA,OAAO;AAAA,UACL,MAAA,EAAQ,MAAA;AAAA,UACR,MAAA,EAAQ,kBAAkB,cAAc,CAAA,SAAA,CAAA;AAAA,UACxC,SAAA,EAAW,MAAM,MAAA,EAAO;AAAA,UACxB,UAAA,EAAY,KAAA,CAAM,WAAA,EAAY,GAAI;AAAA,SACpC;AAAA,MACF,SAAS,GAAA,EAAK;AACZ,QAAA,MAAA,CAAO,IAAA;AAAA,UACL,EAAE,KAAK,GAAA,YAAe,KAAA,GAAQ,IAAI,OAAA,GAAU,MAAA,CAAO,GAAG,CAAA,EAAE;AAAA,UACxD;AAAA,SACF;AACA,QAAA,OAAO;AAAA,UACL,MAAA,EAAQ,MAAA;AAAA,UACR,MAAA,EAAQ,mBAAA;AAAA,UACR,SAAA,EAAW,MAAM,MAAA,EAAO;AAAA,UACxB,UAAA,EAAY,KAAA,CAAM,WAAA,EAAY,GAAI;AAAA,SACpC;AAAA,MACF;AAAA,IACF,CAAA;AAAA,IAEA,MAAM,KAAA,GAAuB;AAC3B,MAAA,IAAI,CAAC,MAAA,EAAQ;AACX,QAAA,MAAA,GAAS,IAAA;AACT,QAAA,EAAA,CAAG,KAAA,EAAM;AAAA,MACX;AAAA,IACF;AAAA,GACF;AAEA,EAAA,OAAO,KAAA;AACT","file":"index.js","sourcesContent":["/**\n * `${VAR}` / `${VAR:-default}` substitution over an arbitrary parsed-YAML value.\n *\n * Only string leaves are touched; numbers/booleans/null pass through untouched\n * (the caller coerces the *resulting* string back into a number/boolean where\n * the schema expects one). An unresolved placeholder fails config loading\n * immediately — startup must never proceed with an unresolved secret. That\n * includes one left behind by a *nested* placeholder such as `${A:-${B}}`,\n * which is rejected rather than silently passed through. There is no\n * escape syntax for a literal `${NAME}`; nothing in this config format needs\n * one, and adding it would mean two ways to write every value.\n *\n * `${VAR}` (no default) requires `VAR` to be present in `env` (any value,\n * including an empty string, counts as present).\n * `${VAR:-default}` falls back to `default` when `VAR` is absent OR empty,\n * matching common shell semantics.\n *\n * Anything else brace-shaped is refused: `${VAR-x}`, `${VAR:=x}`, `${VAR:?x}`\n * are valid *shell* and would otherwise load as literal strings. That is\n * harmless where a downstream check rejects the literal, and quietly wrong for\n * a free-string field — `adminToken: ${ADMIN_TOKEN-fallback}` would run the\n * gateway with that literal as the ledger credential while the operator\n * believed an env secret gated it. A bare `$VAR` is deliberately left alone: it\n * is not brace-shaped, and refusing it would reject values that legitimately\n * contain a dollar sign.\n *\n * Every rule above is decided from the **template**, before substitution.\n * Deciding afterwards is how `${A:-${B}}` used to corrupt a value on the one\n * branch its guard did not cover, and how a resolved secret containing a\n * `${…}`-shaped fragment used to get quoted back in the error text.\n *\n * The resolved *value* of a variable is never included in any error message —\n * only the variable *name* and the config path are.\n */\nimport { CommerceError } from '../core/index.js';\n\nconst PLACEHOLDER_PATTERN = /\\$\\{([A-Za-z_][A-Za-z0-9_]*)(:-([^}]*))?\\}/g;\n\n/** An innermost brace token: `${` … `}` with no braces between. */\nconst BRACE_TOKEN = /\\$\\{[^{}]*\\}/g;\n\n/** The same grammar as PLACEHOLDER_PATTERN, 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 (isPlainObject(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 honour, before any substitution runs.\n *\n * `${A:-${B}}` is the case that motivated this. `[^}]*` cannot span the inner\n * `}`, so the match consumes `${A:-${B` and leaves a stray `}` behind. When `A`\n * is unset the leftover `${B}` was visible afterwards and got caught; when `A`\n * is *set* — the normal case, and the whole reason someone writes a default —\n * substitution succeeded and the stray `}` was appended to the resolved value\n * with nothing to notice it. For `adminToken` that means the gateway compares\n * against a credential the operator does not hold, with no diagnostic.\n *\n * Deciding from the template covers both branches with one rule, and means no\n * error message is ever derived from a resolved value.\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 BRACE_TOKEN.lastIndex = 0;\n for (const [token] of value.matchAll(BRACE_TOKEN)) {\n if (SUPPORTED_TOKEN.test(token)) continue;\n // The token itself, never the surrounding value: this runs pre-substitution,\n // so it cannot contain a resolved 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 recognised; 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\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n","/**\n * The default configuration filename, in one place.\n *\n * Deliberately its own module with **no imports**: `src/cli` reaches the rest\n * of `src/config` only through a dynamic import (see\n * `src/cli/lib/config-client.ts`), so that a broken config module cannot take\n * down commands that never read configuration. A leaf file holding a single\n * string has no module graph to break, so the CLI can import it directly\n * without reopening that seam — and `init`'s default output path, `--config`'s\n * help text and the loader's own lookup cannot drift apart, which is what\n * three separate copies of this string invited.\n */\nexport const DEFAULT_CONFIG_FILENAME = 'config.yaml';\n","/**\n * The only outbound HTTP path to a merchant backend.\n *\n * - Uses global `fetch` and always applies a bound timeout via `AbortSignal.timeout`.\n * - `redirect: 'manual'` - a 3xx response is treated as a `BACKEND_ERROR`, never\n * followed (SSRF hardening).\n * - `{param}` segments in `handler.url` are filled from validated input and\n * URL-encoded; whatever remains goes to the query string (GET/DELETE) or a\n * JSON body (POST/PUT/PATCH). `handler.inputBindings` replaces that\n * leftover rule with one that names each group explicitly - see\n * `buildBackendRequestParts`.\n */\nimport {\n type BackendHandler,\n type BackendMethod,\n DEFAULT_BACKEND_TIMEOUT_MS,\n} from '../domain/resource.js';\nimport { CommerceError } from '../errors/index.js';\nimport type { BackendExecutor, BackendRequest, BackendResponse } from '../interfaces/backend.js';\nimport { type Logger, NOOP_LOGGER } from '../interfaces/logger.js';\n\nconst MAX_BODY_SNIPPET_LENGTH = 512;\n/**\n * The one canonical `{param}` grammar. Extraction, substitution, the config\n * gate and `doctor`'s probe all go through it.\n *\n * `-` and `.` are admitted: `/report/{report-id}` is ordinary\n * REST, and under the previous `[a-zA-Z0-9_]+` class it matched *nothing*. It\n * was therefore invisible to the config gate, survived substitution as a\n * literal, and a paid resource settled the buyer's payment before sending\n * `/report/%7Breport-id%7D` to a backend that 404s - the earlier money bug,\n * reachable again through the character class rather than through the check.\n */\nconst PATH_PARAM_PATTERN = /\\{([a-zA-Z0-9_.-]+)\\}/g;\n/** A hostile or broken backend can otherwise materialise an arbitrarily\n * large response in memory - AbortSignal.timeout bounds it by *time*, not\n * bytes. 1 MB is generous for a JSON API response. */\nconst MAX_RESPONSE_BODY_BYTES = 1024 * 1024;\n\nexport interface HttpBackendExecutorOptions {\n /** Override for `fetch`, used in tests. Defaults to the global implementation. */\n readonly fetchImpl?: typeof fetch;\n /** A non-2xx backend body is logged here (debug), never shipped to the client. */\n readonly logger?: Logger;\n}\n\nexport class HttpBackendExecutor implements BackendExecutor {\n private readonly fetchImpl: typeof fetch;\n private readonly logger: Logger;\n\n constructor(options: HttpBackendExecutorOptions = {}) {\n this.fetchImpl = options.fetchImpl ?? fetch;\n this.logger = options.logger ?? NOOP_LOGGER;\n }\n\n async call(handler: BackendHandler, request: BackendRequest): Promise<BackendResponse> {\n const timeoutMs = handler.timeoutMs ?? DEFAULT_BACKEND_TIMEOUT_MS;\n const inputRecord = isPlainObject(request.input) ? request.input : {};\n\n const context = { requestId: request.requestId, resourceId: request.resourceId };\n // Throws INPUT_INVALID for every shape problem. The pipeline already ran\n // the same call pre-payment through validateBackendRequestShape(); this is\n // defence in depth for a caller that bypasses it, not the normal path.\n const parts = buildBackendRequestParts(handler, inputRecord, context);\n\n let target: URL;\n try {\n target = new URL(parts.url);\n } catch (error) {\n throw new CommerceError('BACKEND_ERROR', 'Backend URL could not be constructed from input', {\n ...context,\n details: { reason: 'invalid-url' },\n cause: error,\n });\n }\n\n // Belt-and-braces beyond the per-parameter check above: whatever the\n // templated path resolved to must still live under the template's own\n // literal (pre-`{param}`) prefix. Templating something other than a path\n // segment (e.g. the host) is not a documented usage; if the literal\n // prefix does not even parse as a URL, skip this extra check rather than\n // fail a request the per-parameter check already covers.\n const literalPrefix = handler.url.split('{')[0] ?? handler.url;\n try {\n const literalPrefixPathname = new URL(literalPrefix).pathname;\n if (!target.pathname.startsWith(literalPrefixPathname)) {\n throw new CommerceError(\n 'INPUT_INVALID',\n 'Path parameters resolved outside the configured backend path',\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n },\n );\n }\n } catch (error) {\n if (error instanceof CommerceError) throw error;\n }\n\n const headers: Record<string, string> = { ...(handler.headers ?? {}) };\n let body: string | undefined;\n\n //.set() REPLACES an existing param, so without this check a caller\n // input key with the same name as an operator-baked-in query param\n // (?apikey=SECRET in handler.url) silently overwrites it.\n // Shared with validateBackendRequestShape() - that copy runs\n // *before* payment, this one is defence in depth.\n checkQueryCollision(target, parts.query, context);\n for (const [key, value] of Object.entries(parts.query)) {\n target.searchParams.set(key, stringifyPrimitive(value));\n }\n if (parts.body !== undefined) {\n body = JSON.stringify(parts.body.value);\n // A configured Content-Type stays authoritative: a backend wanting\n // `application/vnd.x+json` says so in config and we do not override it.\n if (!hasHeader(headers, 'content-type')) {\n headers['content-type'] = 'application/json';\n }\n }\n\n const started = performance.now();\n let response: Response;\n try {\n response = await this.fetchImpl(target, {\n method: handler.method,\n headers,\n ...(body !== undefined ? { body } : {}),\n redirect: 'manual',\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (error) {\n const durationMs = Math.round(performance.now() - started);\n if (isAbortError(error)) {\n throw new CommerceError(\n 'BACKEND_TIMEOUT',\n `Backend request timed out after ${timeoutMs}ms`,\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: { timeoutMs, durationMs },\n cause: error,\n },\n );\n }\n throw new CommerceError('BACKEND_ERROR', 'Backend request failed (transport error)', {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: { durationMs },\n cause: error,\n });\n }\n const durationMs = Math.round(performance.now() - started);\n\n const isRedirect =\n response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400);\n if (isRedirect) {\n throw new CommerceError(\n 'BACKEND_ERROR',\n 'Backend responded with a redirect, which is not followed',\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: { status: response.status, reason: 'redirect-not-followed' },\n },\n );\n }\n\n const responseHeaders = headersToRecord(response.headers);\n const contentType = response.headers.get('content-type') ?? '';\n let parsedBody: unknown;\n try {\n parsedBody = await parseBody(response, contentType);\n } catch (error) {\n const tooLarge =\n error instanceof Error && error.message.startsWith('response-body-too-large');\n throw new CommerceError(\n 'BACKEND_ERROR',\n tooLarge\n ? 'Backend response exceeded the maximum allowed size'\n : 'Backend response could not be read',\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: tooLarge\n ? { reason: 'response-too-large', maxBytes: MAX_RESPONSE_BODY_BYTES }\n : { reason: 'read-error' },\n cause: error,\n },\n );\n }\n\n if (response.status < 200 || response.status >= 300) {\n // The backend status is ours to state; the backend's own response body\n // is not - a merchant backend in verbose/dev-error mode routinely\n // emits stack traces, hostnames or SQL fragments, and this gateway is\n // not the one who gets to decide those are safe to forward to whoever\n // called the (possibly free, possibly unauthenticated) resource. Log\n // it for the operator; never put it in a client-visible field.\n this.logger.debug(\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n status: response.status,\n bodySnippet: truncateSnippet(parsedBody),\n },\n 'Backend responded with a non-2xx status',\n );\n throw new CommerceError('BACKEND_ERROR', `Backend responded with status ${response.status}`, {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: { status: response.status },\n });\n }\n\n return {\n status: response.status,\n headers: responseHeaders,\n body: parsedBody,\n durationMs,\n };\n }\n}\n\n/**\n * The traversal and query-collision checks below must run before payment,\n * not only inside `call()` - pipeline step 6, which is *after*\n * verify -> reserve -> settle.\n * Both throw INPUT_INVALID, which schema validation (step 2) cannot catch\n * (it validates against `resource.inputSchema`, which knows nothing about\n * the URL template a bad value would collide with). Concretely: a paid,\n * path-templated resource called with `{ city: \"\" }` would settle the buyer's\n * payment on-chain and then never call the backend - payment without\n * delivery, no refund, no release of the reserved authorisation. Both\n * checks are pure functions of `(handler.url, input)` with no I/O, so the\n * pipeline calls this immediately after schema validation, *before* price\n * resolution - before any payment provider is even selected. `call()` keeps\n * its own copy as defence in depth (it is a public class; the pipeline is\n * not the only possible caller).\n */\n/**\n * `{param}` names in a `backend.url` template, in declaration order.\n * Exported so `src/config`'s `normaliseResource` can\n * cross-check every template parameter against the resource's input schema\n * at config load - the same regex, not a second copy that could silently\n * drift out of sync with what this file actually treats as a path\n * parameter.\n */\nexport function extractPathParameterNames(url: string): string[] {\n return [...url.matchAll(PATH_PARAM_PATTERN)].map((match) => match[1] as string);\n}\n\n/**\n * A brace left over after every legal `{param}` is removed, or `undefined`.\n *\n * Widening the grammar fixes the *common* spelling; it cannot fix every one.\n * `{report id}`, `{a/b}`, `{}` and an unbalanced `{` still match nothing, and\n * \"matches nothing\" is precisely the silent-literal shape that costs a buyer\n * money on a paid resource. So the rule is inverted: rather than enumerating\n * what is illegal, anything brace-shaped that is *not* a recognised parameter\n * is refused at config load. Exported so `src/config` applies it - the\n * grammar and its residue must never live in two files.\n */\nexport function findUnparsedBraceToken(url: string): string | undefined {\n const residue = url.replace(PATH_PARAM_PATTERN, '');\n const index = residue.search(/[{}]/);\n if (index === -1) return undefined;\n // Report the offending run, not just the character, so the error is fixable.\n const token = /\\{[^{}]*\\}?|\\}/.exec(residue.slice(index));\n return token?.[0] ?? residue[index];\n}\n\nexport function validateBackendRequestShape(\n handler: BackendHandler,\n input: unknown,\n context: ShapeContext,\n): void {\n const inputRecord = isPlainObject(input) ? input : {};\n\n // Every shape error - missing or invalid path parameter, a bound group that\n // is not an object - throws INPUT_INVALID from here, before payment.\n const parts = buildBackendRequestParts(handler, inputRecord, context);\n\n let target: URL;\n try {\n target = new URL(parts.url);\n } catch {\n return; // call() surfaces the real BACKEND_ERROR for an unparseable URL.\n }\n checkQueryCollision(target, parts.query, context);\n}\n\ntype ShapeContext = { readonly requestId: string; readonly resourceId: string };\n\n/** The path-templated URL plus the query and body values a request carries. */\ninterface BackendRequestParts {\n readonly url: string;\n readonly query: Record<string, unknown>;\n /** Present when a JSON body should be sent; `value` is what gets encoded. */\n readonly body?: { readonly value: unknown };\n}\n\nfunction acceptsBody(method: BackendMethod): boolean {\n return method !== 'GET' && method !== 'DELETE';\n}\n\n/**\n * Split validated input into URL, query and body according to\n * `handler.inputBindings` - the single place either mode is decided, so\n * `call()` and the pre-payment `validateBackendRequestShape()` can never\n * disagree about what request the input describes.\n *\n * Throws only `CommerceError('INPUT_INVALID')`, which is what makes it safe to\n * run before pricing.\n */\nfunction buildBackendRequestParts(\n handler: BackendHandler,\n input: Record<string, unknown>,\n context: ShapeContext,\n): BackendRequestParts {\n const bindings = handler.inputBindings;\n if (bindings === undefined) {\n const { url, remaining } = applyPathTemplate(handler.url, input, context);\n return acceptsBody(handler.method)\n ? { url, query: {}, body: { value: remaining } }\n : { url, query: remaining };\n }\n\n const pathValues =\n bindings.path === undefined ? {} : resolveBoundGroup(input, bindings.path, 'path', context);\n const { url } = applyPathTemplate(handler.url, pathValues, context);\n const query =\n bindings.query === undefined ? {} : resolveBoundGroup(input, bindings.query, 'query', context);\n\n // An absent body value sends no body at all rather than `null`: a request\n // body the operation does not require is simply not there. A body the\n // operation *does* require is caught one step earlier, by `required` in the\n // resource's input schema - also before payment.\n const bodyValue = bindings.body === undefined ? undefined : input[bindings.body];\n if (bodyValue === undefined || !acceptsBody(handler.method)) return { url, query };\n return { url, query, body: { value: bodyValue } };\n}\n\nfunction resolveBoundGroup(\n input: Record<string, unknown>,\n key: string,\n kind: 'path' | 'query',\n context: ShapeContext,\n): Record<string, unknown> {\n const value = input[key];\n if (value === undefined) return {};\n if (!isPlainObject(value)) {\n throw new CommerceError(\n 'INPUT_INVALID',\n `Input \"${key}\" must be an object of ${kind} parameters`,\n { ...context, details: { field: key } },\n );\n }\n return value;\n}\n\nfunction checkQueryCollision(\n target: URL,\n remaining: Record<string, unknown>,\n context: { readonly requestId: string; readonly resourceId: string },\n): void {\n const templateKeys = new Set(target.searchParams.keys());\n for (const key of Object.keys(remaining)) {\n if (templateKeys.has(key)) {\n throw new CommerceError(\n 'INPUT_INVALID',\n `Input key \"${key}\" collides with a query parameter already set on backend.url`,\n { requestId: context.requestId, resourceId: context.resourceId, details: { field: key } },\n );\n }\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n// encodeURIComponent does not escape \".\" - a raw \"..\"/\".\" path-parameter\n// value survives it and new URL() then normalises the segment away, letting\n// a caller step outside the template's own directory (bounded traversal:\n// slashes ARE escaped, so only removing segments, never adding them). Reject\n// these exact values at substitution time instead of shipping them.\nconst TRAVERSAL_PATH_VALUES = new Set(['', '.', '..']);\n\nfunction applyPathTemplate(\n template: string,\n input: Record<string, unknown>,\n context: ShapeContext,\n): { url: string; remaining: Record<string, unknown> } {\n const remaining: Record<string, unknown> = { ...input };\n let missing: string | undefined;\n let invalid: string | undefined;\n const url = template.replace(PATH_PARAM_PATTERN, (_match, key: string) => {\n // Object.hasOwn, not `key in remaining`: `in` also matches inherited\n // Object.prototype names (\"constructor\", \"toString\", …), which a\n // config-authored template naming a path param after one of them would\n // otherwise silently resolve to the wrong (inherited) value.\n if (!Object.hasOwn(remaining, key)) {\n missing = key;\n return '';\n }\n const value = remaining[key];\n delete remaining[key];\n const raw = stringifyPrimitive(value);\n if (TRAVERSAL_PATH_VALUES.has(raw)) {\n invalid = key;\n return '';\n }\n return encodeURIComponent(raw);\n });\n if (missing !== undefined) {\n // Tempting to shrug this off as a config/schema mismatch rather than bad\n // caller input. But a paid, `{param}`-templated resource whose input can\n // never supply it would reach settle() on every call - the buyer pays, the\n // backend is never called, no refund. `normaliseResource` (src/config) is\n // the root-cause fix, rejecting the shape at config load; throwing here\n // stops a hand-built `CommerceResource` from reintroducing the money bug\n // by skipping config validation.\n throw new CommerceError('INPUT_INVALID', `Path parameter \"${missing}\" was not supplied`, {\n ...context,\n details: { field: missing },\n });\n }\n if (invalid !== undefined) {\n throw new CommerceError('INPUT_INVALID', `Path parameter \"${invalid}\" is not a valid value`, {\n ...context,\n details: { field: invalid },\n });\n }\n return { url, remaining };\n}\n\nfunction stringifyPrimitive(value: unknown): string {\n if (value === undefined || value === null) return '';\n if (typeof value === 'string') return value;\n if (typeof value === 'number' || typeof value === 'boolean') return String(value);\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nfunction hasHeader(headers: Record<string, string>, name: string): boolean {\n const target = name.toLowerCase();\n return Object.keys(headers).some((key) => key.toLowerCase() === target);\n}\n\nfunction headersToRecord(headers: Headers): Record<string, string> {\n const record: Record<string, string> = {};\n headers.forEach((value, key) => {\n record[key] = value;\n });\n return record;\n}\n\nasync function readBodyCapped(response: Response, maxBytes: number): Promise<string> {\n if (!response.body) return '';\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel();\n throw new Error(`response-body-too-large:${maxBytes}`);\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n return Buffer.concat(chunks).toString('utf8');\n}\n\nasync function parseBody(response: Response, contentType: string): Promise<unknown> {\n const text = await readBodyCapped(response, MAX_RESPONSE_BODY_BYTES);\n if (text.length === 0) return text;\n if (contentType.includes('json')) {\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n }\n return text;\n}\n\nfunction truncateSnippet(body: unknown): string {\n const text = typeof body === 'string' ? body : safeStringify(body);\n return text.length > MAX_BODY_SNIPPET_LENGTH\n ? `${text.slice(0, MAX_BODY_SNIPPET_LENGTH)}…`\n : text;\n}\n\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\nfunction isAbortError(error: unknown): boolean {\n return error instanceof Error && (error.name === 'TimeoutError' || error.name === 'AbortError');\n}\n","/**\n * Fan-out `EventSink`: persists every event to the receipt store and notifies\n * in-process subscribers (the gateway's SSE feed). Never throws to the caller —\n * a store or subscriber failure is caught and logged.\n */\nimport type { CommerceEvent, EventSink } from '../domain/event.js';\nimport type { Logger } from '../interfaces/logger.js';\nimport type { Clock, IdGenerator } from '../interfaces/runtime.js';\nimport type { ReceiptStore } from '../interfaces/store.js';\n\nexport interface CreateEventBusOptions {\n readonly store: ReceiptStore;\n readonly logger: Logger;\n /** Reserved for callers that want the bus to mint ids/timestamps itself. */\n readonly ids?: IdGenerator;\n readonly clock?: Clock;\n}\n\nexport interface EventBus extends EventSink {\n /** Subscribe to every emitted event. Returns an unsubscribe function. */\n subscribe(fn: (event: CommerceEvent) => void): () => void;\n}\n\nexport function createEventBus(options: CreateEventBusOptions): EventBus {\n const subscribers = new Set<(event: CommerceEvent) => void>();\n\n return {\n async emit(event: CommerceEvent): Promise<void> {\n try {\n await options.store.appendEvent(event);\n } catch (error) {\n options.logger.error(\n { err: describeError(error), eventType: event.type, requestId: event.requestId },\n 'Failed to persist commerce event',\n );\n }\n\n for (const subscriber of subscribers) {\n try {\n subscriber(event);\n } catch (error) {\n options.logger.error(\n { err: describeError(error), eventType: event.type, requestId: event.requestId },\n 'Event subscriber threw',\n );\n }\n }\n },\n\n subscribe(fn: (event: CommerceEvent) => void): () => void {\n subscribers.add(fn);\n return () => {\n subscribers.delete(fn);\n };\n },\n };\n}\n\nfunction describeError(error: unknown): { message: string; name?: string } {\n if (error instanceof Error) {\n return { message: error.message, name: error.name };\n }\n return { message: String(error) };\n}\n","/**\n * A small, honest JSON Schema validator for resource input.\n *\n * Supported subset (draft-2020-12 vocabulary, structural only):\n * - `type`: \"object\" | \"string\" | \"number\" | \"integer\" | \"boolean\" | \"array\" | \"null\",\n * or an array of any of those (draft-2020-12 union form, e.g. `[\"object\",\"null\"]`)\n * - `properties` (object schemas, validated recursively)\n * - `required` (string[])\n * - `additionalProperties` (boolean, or a schema applied to extra properties)\n * - `enum` (array of allowed literal values, deep-equality compared)\n * - `items` (single schema applied to every array element — no tuple form)\n *\n * Explicitly NOT supported and silently ignored (never enforced):\n * `minLength`, `maxLength`, `pattern`, `format`, `minimum`, `maximum`,\n * `exclusiveMinimum/Maximum`, `multipleOf`, `oneOf`, `anyOf`, `allOf`, `not`,\n * `$ref`, `const`, `patternProperties`, `minItems`, `maxItems`, `uniqueItems`,\n * tuple-style `items` arrays. An unrecognised `type` value is not enforced\n * either. This is a deliberate, documented limitation of this release — do\n * not assume any of the above is validated.\n */\nimport type { JsonSchema } from '../domain/common.js';\n\nexport interface FieldError {\n readonly path: string;\n readonly message: string;\n}\n\nexport type ValidationResult =\n | { readonly valid: true; readonly value: unknown }\n | { readonly valid: false; readonly errors: readonly FieldError[] };\n\nexport type Validator = (input: unknown) => ValidationResult;\n\nconst SUPPORTED_TYPES = new Set([\n 'object',\n 'string',\n 'number',\n 'integer',\n 'boolean',\n 'array',\n 'null',\n]);\n\n/** Compile a resource `inputSchema` into a reusable validator function. */\nexport function compileJsonSchema(schema: JsonSchema | undefined): Validator {\n return (input: unknown): ValidationResult => {\n if (schema === undefined) return { valid: true, value: input };\n const errors = validateNode(schema, input, '$');\n return errors.length === 0 ? { valid: true, value: input } : { valid: false, errors };\n };\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction matchesType(type: string, value: unknown): boolean {\n switch (type) {\n case 'object':\n return isPlainObject(value);\n case 'array':\n return Array.isArray(value);\n case 'string':\n return typeof value === 'string';\n case 'boolean':\n return typeof value === 'boolean';\n case 'number':\n return typeof value === 'number' && Number.isFinite(value);\n case 'integer':\n return typeof value === 'number' && Number.isInteger(value);\n case 'null':\n return value === null;\n default:\n return true;\n }\n}\n\nfunction describeType(value: unknown): string {\n if (value === null) return 'null';\n if (Array.isArray(value)) return 'array';\n return typeof value;\n}\n\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (typeof a !== typeof b) return false;\n if (a === null || b === null) return false;\n if (typeof a !== 'object') return false;\n try {\n return JSON.stringify(a) === JSON.stringify(b);\n } catch {\n return false;\n }\n}\n\nfunction own(obj: Record<string, unknown>, key: string): unknown {\n return Object.hasOwn(obj, key) ? obj[key] : undefined;\n}\n\n/**\n * `type` may be a single string or (draft-2020-12) an array of strings,\n * e.g. `[\"object\", \"null\"]`. Only recognised when every entry is a string —\n * same conservative \"skip rather than guess\" rule the single-string form\n * already followed for an unrecognised type name.\n */\nfunction typeList(raw: unknown): string[] | undefined {\n if (typeof raw === 'string') return [raw];\n if (Array.isArray(raw) && raw.every((entry): entry is string => typeof entry === 'string')) {\n return raw;\n }\n return undefined;\n}\n\n/**\n * A bare `type === 'object'` string comparison is not enough: `type:\n * [\"object\", \"null\"]` — valid JSON Schema — would never route into\n * `validateObject`, so neither `required` nor `additionalProperties` would be\n * enforced on it, while `defaultClosedObjectSchema` (src/config) stamps\n * `additionalProperties: false` on it believing it closed. Also treats a node\n * with `properties`/`required` and no `type`\n * at all as an object schema, the same shape config's own stamping already\n * recognises via a bare `properties` check — a schema author relying on\n * `type` being implied by `properties` should not be silently unenforced.\n *\n * **exported**, and now the only definition of \"this node is\n * an object schema\" in the codebase. `src/config`'s `defaultClosedObjectSchema`\n * carried its own — `declaresObjectType || properties` — one keyword short of\n * this one, so a schema declaring only `required` was stamped by neither:\n * config left it open and this validator then enforced nothing on it, quietly\n * forwarding every unknown caller key to the merchant's backend while\n * docs/security.md promised \"closed by default at every level\". These two\n * definitions have been aligned once already; keeping them as two definitions\n * is what let them drift again.\n */\nexport function isObjectSchemaNode(schema: Record<string, unknown>): boolean {\n const types = typeList(schema['type']);\n if (types !== undefined) return types.includes('object');\n return Object.hasOwn(schema, 'properties') || Object.hasOwn(schema, 'required');\n}\n\nfunction validateNode(schema: JsonSchema, value: unknown, path: string): FieldError[] {\n const errors: FieldError[] = [];\n const types = typeList(own(schema, 'type'));\n const recognisedTypes = types?.filter((entry) => SUPPORTED_TYPES.has(entry));\n\n if (\n types !== undefined &&\n recognisedTypes !== undefined &&\n recognisedTypes.length === types.length &&\n types.length > 0\n ) {\n if (!types.some((entry) => matchesType(entry, value))) {\n errors.push({\n path,\n message: `expected type \"${types.join(' | ')}\" but got ${describeType(value)}`,\n });\n return errors;\n }\n }\n\n const enumRaw = own(schema, 'enum');\n if (Array.isArray(enumRaw)) {\n const allowed = enumRaw as unknown[];\n if (!allowed.some((candidate) => deepEqual(candidate, value))) {\n errors.push({ path, message: `must be one of ${JSON.stringify(allowed)}` });\n }\n }\n\n if (isObjectSchemaNode(schema) && isPlainObject(value)) {\n errors.push(...validateObject(schema, value, path));\n } else if ((types?.includes('array') ?? false) && Array.isArray(value)) {\n errors.push(...validateArray(schema, value, path));\n }\n\n return errors;\n}\n\nfunction validateObject(\n schema: JsonSchema,\n value: Record<string, unknown>,\n path: string,\n): FieldError[] {\n const errors: FieldError[] = [];\n const propsRaw = own(schema, 'properties');\n const properties = isPlainObject(propsRaw) ? propsRaw : {};\n const requiredRaw = own(schema, 'required');\n const required = Array.isArray(requiredRaw)\n ? requiredRaw.filter((entry): entry is string => typeof entry === 'string')\n : [];\n\n for (const key of required) {\n // Object.hasOwn, not `in`: `in` walks the prototype chain, so a schema\n // requiring \"toString\"/\"constructor\"/\"valueOf\"/\"hasOwnProperty\"/\n // \"__proto__\" could never actually enforce it — those names are always\n // present via inheritance, so `!(key in value)` is always false. This is\n // the same bug class every other lookup in this file already\n // guards against by using own().\n if (!Object.hasOwn(value, key)) {\n errors.push({ path: `${path}.${key}`, message: 'is required' });\n }\n }\n\n const additional = own(schema, 'additionalProperties');\n\n for (const key of Object.keys(value)) {\n // Object.hasOwn, not `properties[key]`: a plain-object lookup for\n // \"__proto__\"/\"constructor\"/\"toString\"/\"valueOf\"/\"hasOwnProperty\" resolves\n // to an inherited Object.prototype member instead of undefined, so those\n // keys would otherwise silently skip the additionalProperties check below.\n const propSchemaRaw = own(properties, key);\n if (propSchemaRaw !== undefined) {\n if (isPlainObject(propSchemaRaw)) {\n errors.push(...validateNode(propSchemaRaw, value[key], `${path}.${key}`));\n }\n continue;\n }\n if (additional === false) {\n errors.push({ path: `${path}.${key}`, message: 'additional property not allowed' });\n } else if (isPlainObject(additional)) {\n errors.push(...validateNode(additional, value[key], `${path}.${key}`));\n }\n }\n\n return errors;\n}\n\nfunction validateArray(schema: JsonSchema, value: unknown[], path: string): FieldError[] {\n const errors: FieldError[] = [];\n const itemsRaw = own(schema, 'items');\n if (isPlainObject(itemsRaw)) {\n value.forEach((item, index) => {\n errors.push(...validateNode(itemsRaw, item, `${path}[${index}]`));\n });\n }\n return errors;\n}\n","/**\n * The single execution path every protocol adapter converges on.\n *\n * Order is a security boundary — do not reorder:\n * 1. resolve resource RESOURCE_NOT_FOUND\n * 2. strip `_payment`, validate input INPUT_INVALID\n * 3. resolve price\n * 4. free -> straight to backend\n * 5. paid -> pick provider -> createRequirement -> (challenge | verify ->\n * reserve replay key -> settle), fail closed at every step\n * 6. call backend BACKEND_TIMEOUT / BACKEND_ERROR\n * 7. persist receipt, emit events, return outcome\n */\n\nimport type { PaymentMethodName } from '../domain/common.js';\nimport type { CommerceEvent, EventSink } from '../domain/event.js';\nimport type { PaymentProvider, PaymentRequirement, PaymentResult } from '../domain/payment.js';\nimport type { CommerceReceipt } from '../domain/receipt.js';\nimport type { CanonicalRequest, ExecutionOutcome, ExecutionPipeline } from '../domain/request.js';\nimport type { CommerceResource, ResourceRegistry } from '../domain/resource.js';\nimport { PAYMENT_INPUT_FIELD } from '../domain/wire.js';\nimport { CommerceError, isCommerceError, toCommerceError } from '../errors/index.js';\nimport type { BackendExecutor, BackendResponse } from '../interfaces/backend.js';\nimport type { Logger } from '../interfaces/logger.js';\nimport type { Clock, IdGenerator } from '../interfaces/runtime.js';\nimport type { ReceiptStore } from '../interfaces/store.js';\nimport { validateBackendRequestShape } from './backend-http.js';\nimport { compileJsonSchema, type Validator } from './validation.js';\n\nexport interface CreateExecutionPipelineOptions {\n readonly resources: ResourceRegistry;\n readonly paymentProviders: readonly PaymentProvider[];\n readonly store: ReceiptStore;\n readonly backend: BackendExecutor;\n readonly events: EventSink;\n readonly logger: Logger;\n readonly clock: Clock;\n readonly ids: IdGenerator;\n}\n\nexport function createExecutionPipeline(\n options: CreateExecutionPipelineOptions,\n): ExecutionPipeline {\n const validators = new Map<string, Validator>();\n\n function getValidator(resource: CommerceResource): Validator {\n const cached = validators.get(resource.id);\n if (cached) return cached;\n const compiled = compileJsonSchema(resource.inputSchema);\n validators.set(resource.id, compiled);\n return compiled;\n }\n\n async function safeEmit(event: CommerceEvent): Promise<void> {\n try {\n await options.events.emit(event);\n } catch (error) {\n options.logger.error(\n { err: describeError(error), eventType: event.type, requestId: event.requestId },\n 'Event sink failed; commerce flow continues',\n );\n }\n }\n\n async function safePersist(\n op: () => Promise<void>,\n label: string,\n requestId: string,\n ): Promise<void> {\n try {\n await op();\n } catch (error) {\n options.logger.error(\n { err: describeError(error), requestId },\n `Persistence failed: ${label}`,\n );\n }\n }\n\n function buildEvent(partial: Omit<CommerceEvent, 'id' | 'at'>): CommerceEvent {\n return { id: options.ids.next('evt'), at: options.clock.nowIso(), ...partial };\n }\n\n async function execute(request: CanonicalRequest): Promise<ExecutionOutcome> {\n const pipelineStart = options.clock.monotonicMs();\n\n // 1. resolve resource\n const resource = options.resources.get(request.resourceId);\n // Same code, same message as a genuine miss: `expose` is an admin scoping\n // decision enforced on the one execution path every adapter shares — a\n // caller on a protocol the resource isn't exposed via must not be able to\n // distinguish \"doesn't exist\" from \"exists but not for you\".\n if (!resource || !resource.exposedVia.includes(request.protocol)) {\n throw new CommerceError(\n 'RESOURCE_NOT_FOUND',\n `Resource \"${request.resourceId}\" was not found`,\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n },\n );\n }\n\n await safeEmit(\n buildEvent({\n type: 'resource.requested',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n }),\n );\n\n // 2. strip reserved payment field, then validate input\n const strippedInput = stripPaymentField(request.input);\n const validation = getValidator(resource)(strippedInput);\n if (!validation.valid) {\n throw new CommerceError(\n 'INPUT_INVALID',\n `Input for resource \"${resource.id}\" failed validation`,\n {\n requestId: request.requestId,\n resourceId: resource.id,\n details: { errors: validation.errors },\n },\n );\n }\n const validInput = validation.value;\n\n // validate the backend request shape (path-traversal, query-param\n // collision) here — before price resolution, so a resource that fails\n // this check never reaches payment. Both checks are pure functions of\n // (handler.url, input); doing them at pipeline step 6 (inside the actual\n // backend call) meant a bad value like `{ city: \"\" }` against a paid,\n // path-templated resource settled the buyer's payment and then never\n // called the backend at all — payment without delivery. call() keeps its\n // own copy of these checks as defence in depth.\n validateBackendRequestShape(resource.handler, validInput, {\n requestId: request.requestId,\n resourceId: resource.id,\n });\n\n // 3. resolve price\n if (resource.pricing.type === 'dynamic') {\n // Config validation rejects this before the gateway starts; this is defence-in-depth.\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${resource.id}\" uses unsupported dynamic pricing`,\n {\n requestId: request.requestId,\n resourceId: resource.id,\n },\n );\n }\n\n let paymentResult: PaymentResult | undefined;\n\n if (resource.pricing.type === 'fixed') {\n const pricing = resource.pricing;\n const provider = pickProvider(options.paymentProviders, resource.paymentMethods);\n if (!provider) {\n throw new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n `No enabled payment provider for resource \"${resource.id}\"`,\n {\n requestId: request.requestId,\n resourceId: resource.id,\n details: { paymentMethods: resource.paymentMethods },\n },\n );\n }\n\n let requirement: PaymentRequirement;\n try {\n requirement = await provider.createRequirement({\n requestId: request.requestId,\n resource,\n amount: pricing.amount,\n currency: pricing.currency,\n requestedAt: options.clock.nowIso(),\n });\n } catch (error) {\n throw isCommerceError(error)\n ? error\n : new CommerceError('PAYMENT_PROVIDER_UNAVAILABLE', 'Payment provider is unavailable', {\n requestId: request.requestId,\n resourceId: resource.id,\n cause: error,\n });\n }\n\n if (!request.payment) {\n await safeEmit(\n buildEvent({\n type: 'payment.required',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n }),\n );\n return {\n kind: 'payment-required',\n requestId: request.requestId,\n resourceId: resource.id,\n requirement,\n };\n }\n\n const payment = request.payment;\n\n let verification: PaymentResult;\n try {\n verification = await provider.verify({\n requestId: request.requestId,\n resource,\n requirement,\n submission: payment,\n });\n } catch (error) {\n // Any typed CommerceError the provider throws is rethrown as-is (a\n // provider can legitimately fail with STORAGE_ERROR, etc. — flattening\n // every code to PAYMENT_INVALID would hide the real cause and the\n // real, possibly-retryable HTTP status). Only a genuinely untyped\n // throw is mapped, with a fixed client-facing message — never the\n // raw error's own message.\n const mapped = isCommerceError(error)\n ? error\n : new CommerceError('PAYMENT_INVALID', 'Payment verification failed', {\n requestId: request.requestId,\n resourceId: resource.id,\n cause: error,\n });\n await safeEmit(\n buildEvent({\n type: 'payment.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: { reason: mapped.code },\n }),\n );\n throw mapped;\n }\n\n if (verification.status !== 'verified') {\n await safeEmit(\n buildEvent({\n type: 'payment.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: verification.rejectionReason ? { reason: verification.rejectionReason } : {},\n }),\n );\n throw new CommerceError(\n 'PAYMENT_INVALID',\n verification.rejectionReason ?? 'Payment was rejected',\n {\n requestId: request.requestId,\n resourceId: resource.id,\n },\n );\n }\n\n if (!verification.replayKey) {\n await safeEmit(\n buildEvent({\n type: 'payment.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: { reason: 'missing-replay-key' },\n }),\n );\n throw new CommerceError('PAYMENT_INVALID', 'Payment provider did not return a replay key', {\n requestId: request.requestId,\n resourceId: resource.id,\n });\n }\n const replayKey = verification.replayKey;\n\n try {\n await options.store.reservePaymentAttempt({\n requestId: request.requestId,\n resourceId: resource.id,\n provider: provider.name,\n replayKey,\n amount: verification.amount,\n currency: verification.currency,\n ...(verification.payer !== undefined ? { payer: verification.payer } : {}),\n ...(verification.payee !== undefined ? { payee: verification.payee } : {}),\n });\n } catch (error) {\n // The store contract only promises PAYMENT_REPLAYED for an actual\n // duplicate replayKey (already a CommerceError with that code, so\n // isCommerceError below preserves it as-is). Anything else — a disk-\n // full error, a dropped connection — is a storage failure, not a\n // replay, and must not be mislabelled as one: telling a buyer\n // \"duplicate payment\" for a transient outage is actively false, and\n // poisons any alerting keyed on replay counts.\n const mapped = toCommerceError(\n error,\n 'STORAGE_ERROR',\n 'Payment attempt could not be recorded',\n );\n await safeEmit(\n buildEvent({\n type: 'payment.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: { reason: mapped.code },\n }),\n );\n throw mapped;\n }\n\n await safeEmit(\n buildEvent({\n type: 'payment.verified',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'ok',\n }),\n );\n\n let settlement: PaymentResult;\n try {\n settlement = await provider.settle({\n requestId: request.requestId,\n resource,\n requirement,\n submission: payment,\n verification,\n });\n } catch (error) {\n // / \"the RPC did not answer\" and \"the transfer did not\n // happen\" are different facts. A provider that broadcast a settlement\n // transaction and then failed to confirm it throws\n // PAYMENT_PROVIDER_UNAVAILABLE with details.transactionHash attached\n // (the hash is known before confirmation). Recording that as plain\n // `failed` would tell the merchant's reconciliation artefact a\n // falsehood — the buyer's funds may already have moved. The resource\n // is still not delivered either way: only what gets *recorded*\n // changes, never the fail-closed outcome.\n const uncertainTxHash = uncertainSettlementTxHash(error);\n await safePersist(\n () =>\n options.store.updatePaymentAttempt(\n uncertainTxHash !== undefined\n ? { replayKey, status: 'settlement-uncertain', externalReference: uncertainTxHash }\n : {\n replayKey,\n status: 'failed',\n ...(error instanceof Error ? { rejectionReason: error.message } : {}),\n },\n ),\n uncertainTxHash !== undefined\n ? 'updatePaymentAttempt(settlement-uncertain)'\n : 'updatePaymentAttempt(failed)',\n request.requestId,\n );\n await safeEmit(\n buildEvent({\n type: 'payment.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data:\n uncertainTxHash !== undefined\n ? { reason: 'settlement-uncertain', transactionHash: uncertainTxHash }\n : { reason: 'settlement-threw' },\n }),\n );\n // The merchant's record now tells the truth (above); the buyer must\n // too — they are the party whose funds may have moved, and the\n // client-visible error is their only way to find out. Code stays\n // PAYMENT_SETTLEMENT_FAILED (not PAYMENT_PROVIDER_UNAVAILABLE, which\n // is retryable) — a retry would reuse the already-reserved replay\n // key. The transaction hash is safe to disclose: it's the buyer's\n // own payment, public on-chain the moment it lands. Nothing else\n // from the underlying error travels — only this flag and the hash.\n throw new CommerceError(\n 'PAYMENT_SETTLEMENT_FAILED',\n uncertainTxHash !== undefined\n ? 'Settlement could not be confirmed'\n : 'Payment settlement failed',\n {\n requestId: request.requestId,\n resourceId: resource.id,\n cause: error,\n ...(uncertainTxHash !== undefined\n ? { details: { settlementUncertain: true, transactionHash: uncertainTxHash } }\n : {}),\n },\n );\n }\n\n if (settlement.status !== 'settled') {\n await safePersist(\n () =>\n options.store.updatePaymentAttempt({\n replayKey,\n status: 'rejected',\n ...(settlement.rejectionReason !== undefined\n ? { rejectionReason: settlement.rejectionReason }\n : {}),\n }),\n 'updatePaymentAttempt(rejected)',\n request.requestId,\n );\n await safeEmit(\n buildEvent({\n type: 'payment.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: settlement.rejectionReason ? { reason: settlement.rejectionReason } : {},\n }),\n );\n throw new CommerceError(\n 'PAYMENT_SETTLEMENT_FAILED',\n settlement.rejectionReason ?? 'Settlement was rejected',\n {\n requestId: request.requestId,\n resourceId: resource.id,\n },\n );\n }\n\n await safePersist(\n () =>\n options.store.updatePaymentAttempt({\n replayKey,\n status: 'settled',\n ...(settlement.externalReference !== undefined\n ? { externalReference: settlement.externalReference }\n : {}),\n }),\n 'updatePaymentAttempt(settled)',\n request.requestId,\n );\n await safeEmit(\n buildEvent({\n type: 'payment.settled',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'ok',\n }),\n );\n\n paymentResult = settlement;\n }\n\n // 6. call backend\n const backendStart = options.clock.monotonicMs();\n let backendResponse: BackendResponse;\n try {\n backendResponse = await options.backend.call(resource.handler, {\n requestId: request.requestId,\n resourceId: resource.id,\n input: validInput,\n });\n } catch (error) {\n const commerceError = toCommerceError(error, 'BACKEND_ERROR', 'Backend call failed');\n await safeEmit(\n buildEvent({\n type: 'backend.failed',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n status: 'error',\n durationMs: Math.round(options.clock.monotonicMs() - backendStart),\n data: { code: commerceError.code },\n }),\n );\n\n if (paymentResult !== undefined) {\n // Settlement already succeeded (verify -> reserve -> settle all\n // completed) before the backend call failed, so the\n // uncertain-settlement rule (\"the merchant's record now tells the\n // truth; the buyer must too\") applies to this far more common\n // *certain*-loss branch as well, not only to the uncertain-RPC-timeout\n // one 100 lines above. A backend 500 is more likely than an RPC\n // confirmation timeout, so disclosing strictly *less* here than there\n // would be backwards. The tx hash is\n // safe to disclose: it is the buyer's own payment, public\n // on-chain the moment it lands.\n const failedReceipt: CommerceReceipt = {\n id: options.ids.next('receipt'),\n requestId: request.requestId,\n resourceId: resource.id,\n deliveredAt: options.clock.nowIso(),\n backendStatus: backendErrorStatus(commerceError),\n protocol: request.protocol,\n payment: paymentResult,\n metadata: { delivered: false, backendErrorCode: commerceError.code },\n };\n await safePersist(\n () => options.store.saveReceipt(failedReceipt),\n 'saveReceipt(backend-failed-after-settlement)',\n request.requestId,\n );\n\n throw new CommerceError(\n 'BACKEND_ERROR',\n 'Payment settled but the backend call failed; the payment was not refunded automatically',\n {\n requestId: request.requestId,\n resourceId: resource.id,\n cause: commerceError,\n details: {\n payment: {\n status: paymentResult.status,\n provider: paymentResult.provider,\n amount: paymentResult.amount,\n currency: paymentResult.currency,\n ...(paymentResult.network !== undefined ? { network: paymentResult.network } : {}),\n ...(paymentResult.externalReference !== undefined\n ? { externalReference: paymentResult.externalReference }\n : {}),\n },\n },\n },\n );\n }\n\n throw commerceError;\n }\n\n await safeEmit(\n buildEvent({\n type: 'backend.called',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n status: 'ok',\n durationMs: backendResponse.durationMs,\n data: { status: backendResponse.status },\n }),\n );\n\n // 7. persist receipt, emit final event, return outcome\n const receipt: CommerceReceipt = {\n id: options.ids.next('receipt'),\n requestId: request.requestId,\n resourceId: resource.id,\n deliveredAt: options.clock.nowIso(),\n backendStatus: backendResponse.status,\n durationMs: backendResponse.durationMs,\n protocol: request.protocol,\n ...(paymentResult !== undefined ? { payment: paymentResult } : {}),\n };\n\n await safePersist(() => options.store.saveReceipt(receipt), 'saveReceipt', request.requestId);\n\n const totalDurationMs = Math.round(options.clock.monotonicMs() - pipelineStart);\n\n await safeEmit(\n buildEvent({\n type: 'resource.delivered',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n status: 'ok',\n durationMs: totalDurationMs,\n }),\n );\n\n return {\n kind: 'delivered',\n requestId: request.requestId,\n resourceId: resource.id,\n backendStatus: backendResponse.status,\n body: backendResponse.body,\n headers: backendResponse.headers,\n ...(paymentResult !== undefined ? { payment: paymentResult } : {}),\n receipt,\n durationMs: totalDurationMs,\n };\n }\n\n return { execute };\n}\n\n/** The HTTP status the backend actually returned, when known (backend-http.ts\n * attaches it as `details.status` for a non-2xx response). 0 means \"no\n * response was received at all\" (timeout/transport failure) — distinct from\n * any real HTTP status. */\nfunction backendErrorStatus(error: CommerceError): number {\n const status = error.details?.['status'];\n return typeof status === 'number' ? status : 0;\n}\n\nfunction uncertainSettlementTxHash(error: unknown): string | undefined {\n if (!isCommerceError(error) || error.code !== 'PAYMENT_PROVIDER_UNAVAILABLE') return undefined;\n const hash = error.details?.['transactionHash'];\n return typeof hash === 'string' ? hash : undefined;\n}\n\nfunction pickProvider(\n providers: readonly PaymentProvider[],\n methods: readonly PaymentMethodName[],\n): PaymentProvider | undefined {\n for (const method of methods) {\n const found = providers.find((provider) => provider.name === method);\n if (found) return found;\n }\n return undefined;\n}\n\nconst RESERVED_INPUT_KEYS = new Set([PAYMENT_INPUT_FIELD, '__proto__']);\n\nfunction stripPaymentField(input: unknown): unknown {\n if (typeof input !== 'object' || input === null || Array.isArray(input)) return input;\n const record = input as Record<string, unknown>;\n // Object.hasOwn: `in` would also match inherited names and strip things\n // that were never actually present on this input.\n const hasReserved = [...RESERVED_INPUT_KEYS].some((key) => Object.hasOwn(record, key));\n if (!hasReserved) return input;\n const rest: Record<string, unknown> = {};\n for (const key of Object.keys(record)) {\n // \"__proto__\" is dropped, not just excluded from the reserved-field\n // check: `rest[key] = record[key]` for key === \"__proto__\" would invoke\n // the inherited setter and reassign rest's own prototype instead of\n // creating a data property (belt-and-braces — validation.ts's\n // Object.hasOwn fix is the primary control).\n if (!RESERVED_INPUT_KEYS.has(key)) rest[key] = record[key];\n }\n return rest;\n}\n\nfunction describeError(error: unknown): { message: string; name?: string } {\n if (error instanceof Error) return { message: error.message, name: error.name };\n return { message: String(error) };\n}\n","/**\n * In-memory implementation of the frozen `ResourceRegistry` interface.\n */\nimport type { ProtocolName } from '../domain/common.js';\nimport type { CommerceResource, ResourceRegistry } from '../domain/resource.js';\nimport { CommerceError } from '../errors/index.js';\n\nexport class ResourceRegistryImpl implements ResourceRegistry {\n private readonly byId = new Map<string, CommerceResource>();\n private readonly ordered: readonly CommerceResource[];\n\n constructor(resources: readonly CommerceResource[]) {\n for (const resource of resources) {\n if (this.byId.has(resource.id)) {\n throw new CommerceError('CONFIG_INVALID', `Duplicate resource id \"${resource.id}\"`, {\n details: { resourceId: resource.id },\n });\n }\n this.byId.set(resource.id, resource);\n }\n this.ordered = [...resources];\n }\n\n get(id: string): CommerceResource | undefined {\n return this.byId.get(id);\n }\n\n list(): readonly CommerceResource[] {\n return this.ordered;\n }\n\n listExposedVia(protocol: ProtocolName): readonly CommerceResource[] {\n return this.ordered.filter((resource) => resource.exposedVia.includes(protocol));\n }\n\n has(id: string): boolean {\n return this.byId.has(id);\n }\n}\n\n/** Build a `ResourceRegistry` from a validated list of canonical resources. */\nexport function createResourceRegistry(resources: readonly CommerceResource[]): ResourceRegistry {\n return new ResourceRegistryImpl(resources);\n}\n","/**\n * `config.yaml` schema, validation and normalisation into the\n * canonical `GatewayConfig` (docs/contracts.md).\n *\n * Two-phase validation:\n * 1. Zod validates *shape* (types, required fields, unknown-key rejection).\n * Numeric/boolean leaves accept either their native type or a string\n * (env substitution always produces a string), and are left as-is here -\n * Zod's typed transforms have surprising inference interactions with\n * `.strict()` objects, so numeric/boolean coercion is done explicitly,\n * in plain TypeScript, in the normalisation pass below.\n * 2. A manual business-rule pass validates cross-references that need a\n * specific, actionable message (duplicate ids, disabled protocols/payment\n * methods, dynamic pricing, destination-address plausibility) and\n * performs the numeric/boolean coercion.\n *\n * Env substitution (`${VAR}` / `${VAR:-default}`) runs over the raw parsed\n * value *before* either phase, so numeric/boolean fields can be templated too.\n * One exception, deliberate: `checkVersion` runs **before** substitution, so\n * `version:` cannot itself be templated. It is the compatibility gate that\n * decides whether this parser understands the document at all; resolving\n * environment variables to find out which schema version to expect would be\n * backwards. The order is intended; `version:` is the one exception to the\n * substitution rule, which this sentence exists to record.\n */\n\nimport { type ZodError, type ZodIssue, type ZodTypeAny, z } from 'zod';\nimport {\n extractPathParameterNames,\n findUnparsedBraceToken,\n isObjectSchemaNode,\n} from '../core/execution/index.js';\nimport {\n CommerceError,\n type CommerceResource,\n PAYMENT_INPUT_FIELD,\n PROTOCOL_NAMES,\n type Pricing,\n} from '../core/index.js';\nimport { resolveX402Deployment, type X402FacilitatorConfig } from '../payments/x402/guardrails.js';\nimport { substituteEnv } from './env.js';\n\nconst SUPPORTED_CONFIG_VERSION = 1;\n\n/** `0x` + 40 hex chars. Checksum-insensitive: casing is not enforced. */\nconst ADDRESS_PATTERN = /^0x[0-9a-fA-F]{40}$/;\nconst ZERO_ADDRESS_PATTERN = /^0x0{40}$/i;\n\n/**\n * A resource `id` doubles as its MCP tool name (protocol-mcp registers one\n * tool per resource, named by id). Value verified against the regex actually\n * shipped in the installed `@modelcontextprotocol/sdk@1.30.0`\n * (`shared/toolNameValidation.js`, SEP-986 \"Specify Format for Tool Names\") -\n * not duplicated as an SDK dependency, since config stays protocol-agnostic.\n */\nconst MCP_TOOL_NAME_PATTERN = /^[A-Za-z0-9._-]{1,128}$/;\n\n// ---------------------------------------------------------------------------\n// Zod schema for the *shape* of the raw (post-substitution) document.\n// ---------------------------------------------------------------------------\n\n/** Accepts a real number or a (post env-substitution) numeric string. */\nconst NumberOrString = z.union([z.number(), z.string()]);\n/** Accepts a real boolean or a (post env-substitution) \"true\"/\"false\" string. */\nconst BooleanOrString = z.union([z.boolean(), z.string()]);\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 /** Shared secret gating /api/receipts, /api/events, /api/events/stream. No token -> those routes 404. */\n adminToken: z.string().min(1).optional(),\n /** Browser origins allowed to read the dashboard-facing routes. Empty by default: closed. */\n // Entries are matched literally against the browser's\n // `Origin` header, so `\"*\"` and a trailing slash match nothing at all -\n // fail-closed (a lockout, not a bypass), but silently, and a lockout with\n // no explanation is the kind of thing an operator \"fixes\" by disabling the\n // check. Reject those two shapes with a pointer instead.\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/**\n * Every path the gateway registers itself (`src/gateway/routes.ts`), plus the\n * fixed discovery paths adapters own. An adapter mount that equals one of\n * these makes Fastify's `.all()` a duplicate of the registered route; one that\n * is a path-prefix of them swallows their 404s through the mount's\n * `${mountPath}/*` wildcard.\n */\nconst RESERVED_GATEWAY_PATHS = [\n '/health',\n '/ready',\n '/.well-known/agent-commerce',\n // Fixed by the A2A specification, so it is the adapter's to serve and never\n // a configurable mount's to claim.\n '/.well-known/agent-card.json',\n '/api/resources',\n '/api/resources/:id/invoke',\n '/api/receipts',\n '/api/events',\n '/api/events/stream',\n] as const;\n\n/**\n * `mountPath` reaches Fastify as a route pattern, and a bad one throws inside\n * route registration - deferred to `server.ready()`, so `createGateway` fails\n * wholesale with an opaque `FST_ERR_*` instead of the adapter alone degrading.\n * Catching the shape here turns that into a CONFIG_INVALID naming the value.\n * Fastify pattern syntax (`:param`, `*`) is rejected rather than supported:\n * the mount registers its own wildcard, so a pattern here has no meaning.\n */\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\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 block: A2A is off unless an operator asks for it, and an\n // existing config predating the adapter stays valid.\n a2a: z\n .object({\n enabled: BooleanOrString,\n mountPath: MountPathSchema.optional(),\n })\n .strict()\n .optional(),\n })\n .strict();\n\n/** Applied when `protocols.a2a` is absent or names no mount. */\nconst DEFAULT_A2A_MOUNT_PATH = '/a2a';\n\nconst BackendMethodSchema = z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']);\n\n/**\n * Names the top-level input properties carrying each part of the backend\n * request. Strict: a typo like `bodyy` must fail at load, not silently mean\n * \"no body binding\" and ship a request missing its payload.\n */\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\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 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 })\n .strict();\n\nconst ResourcesMapSchema = z.record(z.string().min(1), ResourceEntrySchema);\n\n/**\n * Facilitator credentials, kept generic on purpose: x402 facilitators are not\n * a single-vendor category, and an auth block shaped around one provider's\n * credentials would make the abstraction a fiction. A facilitator needing\n * per-request signed credentials is refused rather than sent nothing.\n */\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; a static header cannot express it.\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\nconst 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 means \"this facilitator takes no credential\" - an explicit\n // statement, normalised to `{ type: 'none' }` below. On a mainnet that\n // combination is refused outright, so the default can never quietly\n // become an unauthenticated production facilitator.\n auth: FacilitatorAuthSchema.optional(),\n })\n .strict(),\n]);\n\nconst X402Schema = z\n .object({\n enabled: BooleanOrString,\n network: z.string().min(1),\n rpcUrl: z.string().min(1),\n asset: z.string().min(1),\n assetName: z.string().min(1),\n assetVersion: z.string().min(1),\n assetDecimals: NumberOrString,\n payTo: z.string().min(1),\n maxTimeoutSeconds: NumberOrString,\n facilitator: FacilitatorSchema,\n /** Real funds. Never defaulted - see src/payments/x402/guardrails.ts. */\n allowMainnet: BooleanOrString.optional(),\n /** Accepts a mainnet facilitator that takes no credential. Never defaulted. */\n allowUnauthenticatedFacilitator: BooleanOrString.optional(),\n })\n .strict();\n\nconst PaymentsSchema = z\n .object({\n x402: X402Schema.optional(),\n })\n .strict();\n\nconst 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 })\n .strict();\n\ntype RawConfig = z.infer<typeof RawConfigSchema>;\ntype RawResourceEntry = z.infer<typeof ResourceEntrySchema>;\n\n// ---------------------------------------------------------------------------\n// Public shape (docs/contracts.md - exact).\n// ---------------------------------------------------------------------------\n\nexport interface GatewayConfig {\n readonly version: 1;\n readonly merchant: { readonly id: string; readonly name: string; readonly publicBaseUrl: string };\n readonly server: {\n readonly port: number;\n readonly host: string;\n readonly adminToken?: string;\n readonly allowedOrigins: readonly string[];\n };\n readonly storage: { readonly receipts: { readonly driver: 'sqlite'; readonly path: string } };\n readonly protocols: {\n readonly http: { readonly enabled: boolean };\n readonly mcp: { readonly enabled: boolean; readonly mountPath: string };\n readonly a2a: { readonly enabled: boolean; readonly mountPath: string };\n };\n /** Canonical resources, already normalised. */\n readonly resources: readonly CommerceResource[];\n readonly payments: {\n readonly x402?: {\n readonly enabled: boolean;\n readonly network: string;\n readonly rpcUrl: string;\n readonly asset: string;\n readonly assetName: string;\n readonly assetVersion: string;\n readonly assetDecimals: number;\n readonly payTo: string;\n readonly maxTimeoutSeconds: number;\n readonly facilitator: X402FacilitatorConfig;\n readonly allowMainnet?: boolean;\n readonly allowUnauthenticatedFacilitator?: boolean;\n };\n };\n}\n\n// ---------------------------------------------------------------------------\n// Entry point\n// ---------------------------------------------------------------------------\n\nexport function parseConfig(raw: unknown, env: NodeJS.ProcessEnv): GatewayConfig {\n if (typeof raw !== 'object' || raw === null || Array.isArray(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 as Record<string, unknown>);\n\n const substituted = substituteEnv(raw, env);\n const parsed = parseWithZod(RawConfigSchema, substituted);\n return normalise(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 rawVersion = raw['version'];\n const version = typeof rawVersion === 'string' ? Number(rawVersion) : rawVersion;\n if (version !== SUPPORTED_CONFIG_VERSION) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Unsupported config version \"${String(rawVersion)}\": this gateway only supports version ${SUPPORTED_CONFIG_VERSION}`,\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\n// ---------------------------------------------------------------------------\n// Numeric / boolean coercion (explicit, not via Zod - see file header).\n// ---------------------------------------------------------------------------\n\nfunction toNumber(\n value: number | string,\n path: string,\n bounds: { min?: number; max?: number } = {},\n): number {\n // `Number('')` is 0 - finite, integral, and inside\n // `server.port`'s deliberate `min: 0` (\"let the OS pick\"). So `port: ${PORT:-}`\n // or an exported-but-empty PORT validated PASS and the gateway bound a random\n // port, after which `doctor` derived `http://127.0.0.1:0`, failed to connect,\n // and reported the gateway unreachable while it was serving. `Number` also\n // accepts `\"0x50\"` (80) and `\"1e3\"` (1000) for fields that are decimal\n // integers everywhere they are documented. Require plain digits instead.\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\nfunction 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\n// ---------------------------------------------------------------------------\n// Business-rule validation + normalisation into the canonical shape.\n// ---------------------------------------------------------------------------\n\nconst SUPPORTED_PROTOCOLS: ReadonlySet<string> = new Set(PROTOCOL_NAMES);\nconst SUPPORTED_PAYMENT_METHODS = new Set(['x402']);\n\nfunction normalise(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 };\n validateMountPaths(protocols);\n\n const x402Raw = raw.payments.x402;\n const facilitator: X402FacilitatorConfig | undefined =\n x402Raw === undefined\n ? undefined\n : x402Raw.facilitator.mode === 'local'\n ? { mode: 'local', signerPrivateKey: x402Raw.facilitator.signerPrivateKey }\n : {\n mode: 'remote',\n url: x402Raw.facilitator.url,\n auth: x402Raw.facilitator.auth ?? { type: 'none' },\n };\n const x402 =\n x402Raw && facilitator\n ? {\n enabled: toBoolean(x402Raw.enabled, 'payments.x402.enabled'),\n network: x402Raw.network,\n rpcUrl: x402Raw.rpcUrl,\n asset: x402Raw.asset,\n assetName: x402Raw.assetName,\n assetVersion: x402Raw.assetVersion,\n assetDecimals: toNumber(x402Raw.assetDecimals, 'payments.x402.assetDecimals', {\n min: 0,\n max: 36,\n }),\n payTo: x402Raw.payTo,\n maxTimeoutSeconds: toNumber(\n x402Raw.maxTimeoutSeconds,\n 'payments.x402.maxTimeoutSeconds',\n {\n min: 1,\n },\n ),\n facilitator,\n ...(x402Raw.allowMainnet !== undefined\n ? { allowMainnet: toBoolean(x402Raw.allowMainnet, 'payments.x402.allowMainnet') }\n : {}),\n ...(x402Raw.allowUnauthenticatedFacilitator !== undefined\n ? {\n allowUnauthenticatedFacilitator: toBoolean(\n x402Raw.allowUnauthenticatedFacilitator,\n 'payments.x402.allowUnauthenticatedFacilitator',\n ),\n }\n : {}),\n }\n : undefined;\n\n if (x402) {\n validateAddress('payments.x402.payTo', x402.payTo);\n validateAddress('payments.x402.asset', x402.asset);\n // The same call the provider makes at construction, run here so\n // `agent-commerce validate` reports an unsafe deployment where an operator\n // expects to hear about it, rather than at first boot.\n resolveX402Deployment({\n network: x402.network,\n payTo: x402.payTo,\n asset: x402.asset,\n assetName: x402.assetName,\n assetVersion: x402.assetVersion,\n facilitator: x402.facilitator,\n ...(x402.allowMainnet !== undefined ? { allowMainnet: x402.allowMainnet } : {}),\n ...(x402.allowUnauthenticatedFacilitator !== undefined\n ? { allowUnauthenticatedFacilitator: x402.allowUnauthenticatedFacilitator }\n : {}),\n });\n }\n\n const resources = Object.entries(raw.resources).map(([id, entry]) =>\n normaliseResource(id, entry, protocols, x402),\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 // min 0, not 1: port 0 is the standard \"let the OS pick a free port\"\n // convention, useful for tests and ephemeral dev/demo 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 ...(x402 !== undefined ? { x402 } : {}),\n },\n };\n}\n\ninterface NormalisedProtocols {\n readonly http: { readonly enabled: boolean };\n readonly mcp: { readonly enabled: boolean; readonly mountPath: string };\n readonly a2a: { readonly enabled: boolean; readonly mountPath: string };\n}\n\n/**\n * Two enabled mounts may not overlap: each registers a `${mountPath}/*`\n * wildcard, so a shared prefix means one adapter silently answers for the\n * other. Disabled protocols mount nothing and are not compared.\n */\nfunction validateMountPaths(protocols: NormalisedProtocols): void {\n const mounts = (\n [\n ['mcp', protocols.mcp],\n ['a2a', protocols.a2a],\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\ninterface NormalisedX402 {\n readonly enabled: boolean;\n readonly assetDecimals: number;\n}\n\nfunction normaliseResource(\n id: string,\n entry: RawResourceEntry,\n protocols: NormalisedProtocols,\n x402: NormalisedX402 | undefined,\n): CommerceResource {\n if (entry.input !== undefined) validateResourceSchemaKeywords(id, 'input', entry.input);\n\n const inputProperties = entry.input?.['properties'];\n if (\n inputProperties &&\n typeof inputProperties === 'object' &&\n PAYMENT_INPUT_FIELD in inputProperties\n ) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" declares an input property \"${PAYMENT_INPUT_FIELD}\", which is reserved for payment proofs`,\n {\n details: {\n path: `resources.${id}.input.properties.${PAYMENT_INPUT_FIELD}`,\n resourceId: id,\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: http, mcp, a2a.`,\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('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 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 if (entry.pricing.type === 'fixed') {\n validatePricingAmount(id, entry.pricing.amount, x402);\n }\n\n const paymentMethods = entry.payments ?? [];\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: x402.`,\n { details: { path: `resources.${id}.payments`, resourceId: id, method } },\n );\n }\n if (method === 'x402' && (!x402 || !x402.enabled)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" names payment method \"x402\" which is not configured or not enabled under payments.x402`,\n { details: { path: `resources.${id}.payments`, resourceId: id, method } },\n );\n }\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 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 };\n}\n\n/**\n * `{param}` templates (e.g. `.../weather/{city}`) parse fine as a URL - the\n * WHATWG parser just percent-encodes the braces - so this only rejects\n * genuinely malformed strings and non-http(s) schemes, not templating.\n */\n/**\n * Permissive-by-default is the wrong default for a value forwarded to\n * someone else's API: an object schema that\n * omits `additionalProperties` defaults, per JSON Schema itself, to\n * \"anything goes\" - so default it to `false` here instead, unless the\n * operator set it explicitly (including explicitly to `true`, which is\n * respected).\n *\n * An earlier fix only stamped the ROOT schema, so\n * `filter: { type: object }` *looked* closed (the top level really was)\n * while every key one level down under `properties.filter` still passed\n * verbatim - `core`'s validator (execution/validation.ts) only enforces\n * `additionalProperties` where the schema states it explicitly, at every\n * level independently. Recurse into `properties` and `items` the same way\n * `validateResourceSchemaKeywords` below already does, so \"closed\" actually\n * means closed at every depth, not just the one an operator happened to\n * write `additionalProperties: false` on.\n *\n * `type` can be an array (`[\"object\",\"null\"]`, valid JSON\n * Schema) - a bare `=== 'object'` string comparison missed it, so a schema\n * in that shape got stamped as open. `declaresObjectType` below is the same\n * check `core`'s validator now makes (`execution/validation.ts`'s\n * `isObjectSchemaNode`) so the two stay in agreement.\n */\nfunction defaultClosedObjectSchema(schema: Record<string, unknown>): Record<string, unknown> {\n // imported, never re-implemented. The local predicate this\n // replaces recognised `type`/`properties` but not `required`, while core's\n // validator recognised `properties`/`required` - so `input: { required: [q] }`\n // was an object to the validator and not to the stamper, and every unknown\n // key sailed through to the merchant backend. One definition, one drift.\n const isObjectSchema = isObjectSchemaNode(schema);\n const result: Record<string, unknown> = { ...schema };\n\n if (isObjectSchema) {\n const properties = schema['properties'];\n if (isPlainObject(properties)) {\n result['properties'] = Object.fromEntries(\n Object.entries(properties).map(([key, sub]) => [\n key,\n isPlainObject(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 (isPlainObject(items)) {\n result['items'] = defaultClosedObjectSchema(items);\n }\n\n // The third place this stamper drifted from the validator, after `required`\n // and tuple `items`. `additionalProperties: {schema}` is the idiomatic\n // \"map of typed objects\" shape, and core's validator applies that subschema\n // recursively at unbounded depth - so without this branch, every node under\n // it stayed open and unknown keys reached the merchant backend. Recursion\n // here is not conditional on `isObjectSchema`: the validator applies the\n // subschema wherever it finds one.\n const additional = schema['additionalProperties'];\n if (isPlainObject(additional)) {\n result['additionalProperties'] = defaultClosedObjectSchema(additional);\n }\n\n return result;\n}\n\n/**\n * A resource that declares no `input:` at all got\n * `inputSchema: undefined`, and `compileJsonSchema(undefined)` is an\n * always-valid validator - every caller key was forwarded to the merchant\n * backend verbatim. The decision: default \"declared nothing\" to \"accepts\n * nothing\" (an empty closed object) rather than rejecting the config at load\n * time - a no-argument resource that omits `input:` is a legitimate shape,\n * and rejecting it would break every existing config that uses it.\n */\nconst EMPTY_CLOSED_OBJECT_SCHEMA: Record<string, unknown> = {\n type: 'object',\n properties: {},\n additionalProperties: false,\n};\n\n/**\n * `src/core`'s validator only enforces the subset documented in\n * `execution/validation.ts` (type/properties/required/additionalProperties/\n * enum/items) - everything else (`pattern`, `minLength`, `format`, `oneOf`,\n * …) is silently ignored at runtime. An operator who writes `pattern` and\n * never sees it enforced has no way to know that from the config alone, so\n * warn at load time instead of letting them find out the hard way.\n */\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\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** `type` explicitly set to something that rules out \"object\" (a bare\n * value, or an array not containing \"object\"). `undefined` - no `type` at\n * all - is deliberately NOT treated as excluding: core's validator treats\n * `properties`/`required` with no `type` as an object schema, so that shape\n * is fine, not another instance of this bug. */\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, both warning (existing, unenforced\n * keywords) and rejecting (a node whose declared `type`\n * cannot structurally be an object, yet which still carries `properties` or\n * `required`). The `properties`/`required`-with-no-`type` shape is not\n * this function's problem any more, since the\n * validator now treats that shape as an object; what's still a trap is a\n * `type` that actively rules \"object\" out while `properties`/`required`\n * imply it was meant to be one, e.g. a copy-pasted sibling schema whose\n * `type` was never updated. Rejecting (not just warning) here is the\n * decision - a warning is exactly what let this bug class ship silently in\n * the first place (`validate`/`doctor` both said PASS).\n */\nfunction 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 // eslint-disable-next-line no-console\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 // the other half. Closing a `required`-only node is\n // correct JSON Schema and quietly unsatisfiable: `required: [\"q\"]` demands a\n // property that `properties` never declares, so the stamped\n // `additionalProperties: false` rejects `q` as an unknown key - the schema\n // can never be satisfied by any input at all. Fail-closed, so no money is at\n // risk, but every call would 400 with a config that loaded cleanly. Say so\n // at load instead. Only when the node really will be closed: an explicit\n // `additionalProperties` 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 = isPlainObject(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 (isPlainObject(properties)) {\n for (const [key, sub] of Object.entries(properties)) {\n if (isPlainObject(sub)) validateResourceSchemaKeywords(id, `${path}.properties.${key}`, sub);\n }\n }\n const additional = schema['additionalProperties'];\n if (isPlainObject(additional)) {\n validateResourceSchemaKeywords(id, `${path}.additionalProperties`, additional);\n }\n const items = schema['items'];\n if (isPlainObject(items)) {\n validateResourceSchemaKeywords(id, `${path}.items`, items);\n } else if (Array.isArray(items)) {\n // tuple-form `items` (an array of per-position\n // schemas) is valid JSON Schema, but `core`'s validator only supports\n // the single-schema form applied to every element - a tuple silently\n // enforces nothing, invisibly rather than wrongly, so warn the same way\n // an unsupported keyword does.\n // eslint-disable-next-line no-console\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\n/**\n * `amount: z.string().min(1)` alone let \"0,01\", \"$0.01\", \"1e-2\", \"-1\" and an\n * over-precise \"0.0000001\" all pass config + `doctor`, then throw on every\n * purchase. A plain\n * positive decimal only - no currency symbol, no thousands separator, no\n * exponent notation.\n */\nconst PRICING_AMOUNT_PATTERN = /^\\d+(?:\\.\\d+)?$/;\nconst ZERO_AMOUNT_PATTERN = /^0(?:\\.0+)?$/;\n\nfunction validatePricingAmount(id: string, amount: string, x402: NormalisedX402 | 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 settles a zero-value transfer, which is\n // nonsense - if something is free, it should say so.\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 (x402 !== undefined) {\n const fractionalDigits = amount.includes('.') ? (amount.split('.')[1]?.length ?? 0) : 0;\n if (fractionalDigits > x402.assetDecimals) {\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 (${x402.assetDecimals} decimals)`,\n { details: { path, resourceId: id } },\n );\n }\n }\n}\n\n/**\n * `backend.inputBindings` names top-level input properties; this is the gate\n * that makes those names mean something at load time rather than at the first\n * paid call. Input schemas are closed by default at every depth\n * (`defaultClosedObjectSchema`), so a binding naming a property the schema\n * never declares can never be satisfied - the group would be silently empty\n * on every request, which on a paid resource is payment for a request the\n * backend receives incomplete.\n *\n * Returns the schema node `{param}` declarations must be found in: the path\n * group in explicit mode, the whole input in legacy mode.\n */\nfunction 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 = isPlainObject(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 (property === PAYMENT_INPUT_FIELD) {\n fail(\n `binds \"${location}\" to \"${PAYMENT_INPUT_FIELD}\", which is reserved for payment proofs`,\n { location },\n );\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 legitimately be any JSON value; only the two groups the\n // executor iterates as key/value pairs have to be objects.\n const declared = properties[property];\n if (location !== 'body' && isPlainObject(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: isPlainObject(group) ? group : undefined,\n where: `input.properties.${bindings.path}`,\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\n/**\n * The root-cause half. `validateBackendRequestShape`\n * (src/core) rejects a missing path parameter at request time - after\n * schema validation but, without this check, on every single call, because\n * a schema that never declares `{city}` can never satisfy it. A paid\n * resource in that shape settles the buyer's payment and then always fails\n * to reach the backend: no refund, replay key burned, on every call, not an\n * unlucky one. Every `{param}` in `backend.url` must be BOTH declared in\n * `properties` AND listed in `required` - an optional value hits the exact\n * same \"caller structurally cannot supply it on every call that omits it\"\n * problem as an undeclared one, just less often. This is the config-load\n * gate `agent-commerce validate`/`doctor` catch it at; the runtime\n * `INPUT_INVALID` in `validateBackendRequestShape` is defence in depth for\n * a hand-built `CommerceResource` this check never saw.\n */\nfunction validatePathParametersDeclared(\n id: string,\n url: string,\n input: Record<string, unknown> | undefined,\n where: string,\n): void {\n // Before anything else: a brace token the canonical grammar does not\n // recognise is neither extracted here nor substituted at request time, so it\n // would travel to the backend as a percent-encoded literal. On a paid\n // resource that is payment-without-delivery on every single call. Refuse it\n // at load rather than letting \"matches nothing\" mean \"nothing to check\".\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 be sent to the backend literally, so a paid resource would settle payment and then never reach the backend`,\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 // Every defence around `{param}` guards the *path* position, and in the host\n // position all of them fail open at once: `new URL('http://{host}/api')`\n // parses (the hostname is literally `{host}`) so the URL check passes; the\n // runtime containment check is skipped because its literal prefix\n // (`http://`) does not itself parse as a URL; and `encodeURIComponent` does\n // not escape dots, so a hostname survives it whole. Caller input then chooses\n // which host the gateway calls - the metadata service, an internal address,\n // anything. `http://{region}.api.internal/...` is an ordinary-looking\n // multi-tenant template, so this is refused here rather than warned about.\n //\n // The rule: everything before the first `{` must already be a complete\n // authority - a parseable origin followed by the path's leading `/`.\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 at all - the parameter starts before the authority is done.\n }\n if (origin === undefined || !prefix.startsWith(`${origin}/`)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has a backend.url parameter before the end of the host (\"${url}\"). 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 = isPlainObject(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 settle payment (if priced) and then fail to reach the backend`,\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 caller that omits it hits the same unservable-request problem as an undeclared parameter`,\n { details: { path, resourceId: id, param } },\n );\n }\n }\n}\n\nfunction validateBackendUrl(id: string, url: string): void {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has an invalid backend.url \"${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\nfunction validateAddress(path: string, value: string): void {\n if (!ADDRESS_PATTERN.test(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 (ZERO_ADDRESS_PATTERN.test(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","/**\n * Locates and parses `config.yaml`, then hands the raw value to\n * `parseConfig`. Never trusts raw YAML before Zod 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/index.js';\nimport { DEFAULT_CONFIG_FILENAME } from './filename.js';\nimport { type GatewayConfig, parseConfig } from './schema.js';\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 // Retained for programmatic callers. Nothing in the CLI prints a\n // `cause`, and nothing should start: this is the object whose\n // `.message` carries the source excerpt (see below).\n cause: error,\n },\n );\n }\n\n return parseConfig(raw, env);\n}\n\n/**\n * A YAML failure described from the error's *structured* fields only.\n *\n * Deliberately not `error.message`: the `yaml` package builds that message\n * with a **code frame excerpt of the source line**, so a syntax error next to\n * an inline secret would reproduce it verbatim into `validate`/`doctor` output — including `doctor --json`, the output most\n * likely to be pasted into an issue or captured by CI:\n *\n * … is not valid YAML: Nested mappings are not allowed … at line 2, column 15:\n *\n * adminToken: super-secret-token-value\n * ^\n *\n * `server.adminToken` and `payments.x402.facilitator.signerPrivateKey` are\n * both legal as inline literals, so this was a real sink rather than a\n * hypothetical one — and it contradicted `validate`'s own promise never to\n * print a resolved value: it never printed a resolved `${ENV}`, only an\n * inlined one. `code` and `linePos` locate the fault exactly as well and\n * cannot contain file content.\n */\n/**\n * Plain-English phrasing for the codes an operator actually hits, so replacing\n * the excerpt does not also cost the diagnostic its readability. These are\n * fixed strings chosen here — they can never contain file content, which is\n * the entire property that matters. Anything unlisted degrades to the bare\n * code, which is still precise.\n */\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\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","/** Default `IdGenerator` used when the caller does not inject one. */\nimport { randomUUID } from 'node:crypto';\nimport type { IdGenerator } from '../core/index.js';\n\nexport function createDefaultIdGenerator(): IdGenerator {\n return {\n next(prefix?: string): string {\n const id = randomUUID();\n return prefix ? `${prefix}_${id}` : id;\n },\n };\n}\n","/**\n * Pino logger factory with redaction. Never log secrets: Authorization\n * headers, the payment-signature header, private keys, seeds, mnemonics,\n * signatures.\n *\n * Two independent things are built here, deliberately not the same pino\n * instance (Fastify's `loggerInstance` option forces its generic `Logger`\n * type into `FastifyInstance`, which then conflicts with our own `Logger`\n * shape under `exactOptionalPropertyTypes`):\n * - `fastifyLoggerOptions()` — a plain options object handed to Fastify's\n * `logger` option, so Fastify builds its own internally-typed pino\n * instance (still redacted, still pino-pretty in development) for HTTP\n * access logs.\n * - `createGatewayLogger()` — a standalone pino instance wrapped to the\n * `src/core` `Logger` shape, injected into the\n * execution pipeline and protocol adapters.\n * Both share the same redaction paths and level/pretty-print policy.\n */\n\nimport { createRequire } from 'node:module';\nimport type { FastifyReply, FastifyRequest } from 'fastify';\nimport pino, { type LoggerOptions, type Logger as PinoLogger } from 'pino';\nimport type { Logger } from '../core/index.js';\n\n/**\n * Absolute path to pino-pretty, or `undefined` when it is not installed.\n *\n * pino-pretty is a **devDependency**: it is a developer-experience nicety and\n * making every consumer of the published package install it (and its\n * transitive tree) to get log lines would be the wrong trade. But the pretty\n * default keys off `NODE_ENV`, which is unset in a normal consumer process —\n * so \"development\" was inferred and `pino()` threw\n * `unable to determine transport target for \"pino-pretty\"`, taking down\n * `createGateway()` for anyone importing the library. The clean-consumer test\n * caught it; nothing in the repo could, because here it is always installed.\n *\n * Resolving it ourselves answers the only question that matters — *is it\n * actually there* — and passing the resolved absolute path (rather than the\n * bare name) removes the second failure mode, where pino resolves transport\n * targets from a different directory than we do.\n */\nconst PINO_PRETTY_PATH: string | undefined = (() => {\n try {\n return createRequire(import.meta.url).resolve('pino-pretty');\n } catch {\n return undefined;\n }\n})();\n\n// pino/fast-redact paths below are single-level wildcards: '*.privateKey'\n// matches privateKey one level deep (e.g. `wallet.privateKey`), not at\n// arbitrary nesting (`a.b.privateKey` is not covered). Nothing leaks today\n// because every call site funnels through describeError(), which extracts\n// only {message, name} before logging — never a raw caught object — but that\n// is a property of current call sites, not of this redact config. Do not log\n// a raw object that might carry a secret at depth > 1 without either\n// extending these paths or hand-picking safe fields first.\nconst SECRET_FIELD_NAMES = [\n 'privateKey',\n 'signerPrivateKey',\n 'signature',\n 'seed',\n 'mnemonic',\n 'secret',\n 'apiKey',\n 'adminToken',\n 'token',\n] as const;\n\n/**\n * The bare top-level form was missing — `'*.privateKey'`\n * matches `{ wallet: { privateKey } }` but not `{ privateKey }`, so a\n * `logger.error({ privateKey })` would have printed it. Both forms are\n * generated now. The depth limit is real and unchanged: fast-redact wildcards\n * are single-level, so a secret at depth ≥ 2 is still not covered, and the\n * documentation says so rather than promising \"any field\".\n */\nexport const REDACT_PATHS: readonly string[] = [\n 'req.headers.authorization',\n 'req.headers[\"payment-signature\"]',\n ...SECRET_FIELD_NAMES,\n ...SECRET_FIELD_NAMES.map((name) => `*.${name}`),\n];\n\nexport interface CreateGatewayLoggerOptions {\n readonly level?: string;\n readonly name?: string;\n readonly nodeEnv?: string;\n readonly prettyPrint?: boolean;\n}\n\nexport interface CreatedGatewayLogger {\n /** Raw pino instance, not shared with Fastify — see file header. */\n readonly pino: PinoLogger;\n /** `src/core` `Logger`-shaped wrapper. */\n readonly core: Logger;\n}\n\nfunction baseLoggerOptions(options: CreateGatewayLoggerOptions): LoggerOptions {\n const nodeEnv = options.nodeEnv ?? process.env['NODE_ENV'] ?? 'development';\n // Never spawn a pino-pretty worker thread in tests: many short-lived\n // Fastify/pino instances are created per test run, and pretty-printing is a\n // pure developer-experience nicety, not a functional requirement there.\n const wantPretty = options.prettyPrint ?? (nodeEnv !== 'production' && nodeEnv !== 'test');\n // Asked for *and* available. An explicit `prettyPrint: true` cannot conjure\n // an uninstalled module, so it degrades to JSON rather than throwing —\n // pretty-printing is cosmetic, and losing colour beats losing the gateway.\n const usePretty = wantPretty && PINO_PRETTY_PATH !== undefined;\n\n return {\n level: options.level ?? process.env['LOG_LEVEL'] ?? (nodeEnv === 'test' ? 'silent' : 'info'),\n ...(options.name !== undefined ? { name: options.name } : {}),\n redact: { paths: [...REDACT_PATHS], censor: '[REDACTED]' },\n ...(usePretty ? { transport: { target: PINO_PRETTY_PATH as string } } : {}),\n };\n}\n\n/**\n * Strips the query string from a request URL before it reaches a log line\n * or an echoed-back response body. The admin token is header-only, with no\n * `?adminToken=` exception for the SSE route (see access-control.ts's doc\n * comment), so this is not the only thing keeping it out of logs — but any\n * query parameter, on any route, could carry something sensitive, and a\n * blanket redaction costs nothing to keep. Single source of truth: every place that puts a\n * request URL in front of a log or a client must call this, not re-derive\n * its own redaction — two redactors drift (Fastify's\n * default 404 handler built its own message string from the raw URL,\n * bypassing the `req` serializer below entirely; see server.ts's\n * `setNotFoundHandler`, which uses this same function).\n */\nexport function sanitizeUrl(url: string | undefined): string | undefined {\n if (url === undefined) return undefined;\n const queryIndex = url.indexOf('?');\n return queryIndex === -1 ? url : `${url.slice(0, queryIndex)}?[REDACTED]`;\n}\n\n/** Overrides (not extends) Fastify's default `req` serializer — see sanitizeUrl. */\nfunction redactedReqSerializer(req: {\n method?: string;\n url?: string;\n host?: string;\n ip?: string;\n socket?: { remotePort?: number };\n}): Record<string, unknown> {\n return {\n method: req.method,\n url: sanitizeUrl(req.url),\n host: req.host,\n remoteAddress: req.ip,\n remotePort: req.socket?.remotePort,\n };\n}\n\n/** Plain options object for Fastify's own `logger` option (see file header). */\nexport function fastifyLoggerOptions(options: CreateGatewayLoggerOptions = {}): LoggerOptions {\n return {\n ...baseLoggerOptions(options),\n serializers: { req: redactedReqSerializer },\n };\n}\n\n/**\n * Fastify's own default 404 handler (four-oh-four.js's `basic404` ->\n * log-controller.js's `routeNotFound`) builds its log line by interpolating\n * `request.raw.url` into a template string — bypassing the `req` serializer\n * above entirely, since it's a plain string, not a structured log call.\n * Registering a `setNotFoundHandler` replaces Fastify's internal one outright\n * (it is only ever invoked when none is set), so this is the only fix point.\n * Exported (not inlined in server.ts) so production and tests share the exact\n * same handler — a second, test-only reimplementation is exactly the kind of\n * thing that quietly drifts from what actually ships.\n */\nexport function buildNotFoundHandler(): (request: FastifyRequest, reply: FastifyReply) => void {\n return (request, reply) => {\n const safeUrl = sanitizeUrl(request.raw.url) ?? '';\n const message = `Route ${request.method}:${safeUrl} not found`;\n request.log.info(message);\n reply.code(404).send({ message, error: 'Not Found', statusCode: 404 });\n };\n}\n\nexport function createGatewayLogger(\n options: CreateGatewayLoggerOptions = {},\n): CreatedGatewayLogger {\n const instance = pino(baseLoggerOptions(options));\n return { pino: instance, core: wrapPino(instance) };\n}\n\nfunction wrapPino(instance: PinoLogger): Logger {\n const logger: Logger = {\n debug: (obj, msg) => instance.debug(obj, msg),\n info: (obj, msg) => instance.info(obj, msg),\n warn: (obj, msg) => instance.warn(obj, msg),\n error: (obj, msg) => instance.error(obj, msg),\n child: (bindings) => wrapPino(instance.child(bindings)),\n };\n return logger;\n}\n","/**\n * `onRequest` hooks doing two separate jobs:\n * - `buildAccessControlHook` (global, registered once): DNS-rebinding Host\n * defence + allowlisted CORS for browser traffic. Neither is path-keyed,\n * so this stays a single hook on the whole server.\n * - `buildOperatorTokenHook` (per-route, registered on each of the three\n * ledger routes individually): the `server.adminToken` gate.\n *\n * Why per-route and not the global hook: a global gate has only\n * `request.url`'s path to match against a literal string set. Fastify's\n * router (find-my-way) percent-*decodes* before matching, so such a gate\n * compares the *raw, still-encoded* string. `/api/%72eceipts` is \"not an\n * operator path\" to the gate and *is* `/api/receipts` to the router — a full\n * bypass with no precondition beyond network reach. A per-route hook removes\n * the whole bug class rather than guarding one instance of it: Fastify only invokes it\n * once routing has already matched this exact route, so there is no path\n * string left to attack — nothing here compares against `request.url` at\n * all.\n */\nimport { createHash, timingSafeEqual } from 'node:crypto';\nimport type { FastifyReply, FastifyRequest } from 'fastify';\n\nconst CORS_METHODS = 'GET,POST,DELETE,OPTIONS';\nconst CORS_HEADERS = 'content-type,payment-signature,x-request-id,authorization';\n/**\n * Without this a browser client can read neither the challenge nor the\n * settlement result: cross-origin JS only sees the CORS-safelisted response\n * headers unless they are named here.\n */\nconst CORS_EXPOSED_HEADERS = 'payment-required,payment-response,x-request-id';\n\nexport interface AccessControlOptions {\n readonly publicBaseUrl: string;\n readonly allowedOrigins: readonly string[];\n}\n\nexport function buildAccessControlHook(\n options: AccessControlOptions,\n): (request: FastifyRequest, reply: FastifyReply) => Promise<void> {\n // Compare case-insensitively (matches the Host check below) — an\n // operator's mis-cased allowedOrigins entry should not lock out the real\n // dashboard behind a generic 403 with no hint why. The *response* header\n // still echoes the browser's own Origin verbatim (not the lowercased\n // form): CORS requires a byte-for-byte match against what the browser\n // sent, and browsers always send Origin already lowercased in practice, so\n // this loses nothing while fixing the config-typo case.\n const allowedOrigins = new Set(options.allowedOrigins.map((origin) => origin.toLowerCase()));\n const publicHostname = hostnameOf(options.publicBaseUrl);\n\n return async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n // 1. Host validation (DNS-rebinding defence) — every request, browser or not.\n const host = request.headers.host;\n if (!isAllowedHost(host, publicHostname)) {\n reply.status(403).send({ status: 'error', code: 'FORBIDDEN', message: 'Host not allowed' });\n return;\n }\n\n // 2. CORS, only for requests that carry an Origin (browser traffic). A\n // request with no Origin (the normal case for agents/MCP clients) gets no\n // CORS header at all.\n const origin = request.headers.origin;\n if (origin !== undefined) {\n if (!allowedOrigins.has(origin.toLowerCase())) {\n reply\n .status(403)\n .send({ status: 'error', code: 'FORBIDDEN', message: 'Origin not allowed' });\n return;\n }\n reply.header('access-control-allow-origin', origin);\n reply.header('access-control-allow-methods', CORS_METHODS);\n reply.header('access-control-allow-headers', CORS_HEADERS);\n reply.header('access-control-expose-headers', CORS_EXPOSED_HEADERS);\n reply.header('vary', 'Origin');\n if (request.method === 'OPTIONS') {\n // Preflight: never carries credentials, so it must not hit a\n // downstream per-route token gate — the browser only sends the real\n // request afterward.\n reply.status(204).send();\n }\n }\n };\n}\n\n/**\n * Per-route token gate — register via `{ onRequest: buildOperatorTokenHook(...) }`\n * on each ledger route's own definition, not the global hook. Closed by\n * default: no token configured => 404 (fail closed, indistinguishable from\n * \"route doesn't exist\"). Token configured but missing/wrong => 401.\n *\n * Header-only, with no exception for the SSE route. `EventSource` cannot send\n * headers, which makes a `?adminToken=` query parameter tempting; the\n * dashboard uses its authenticated polling fallback instead — see\n * SECURITY.md. A token in a query string leaks through Referer, browser\n * history and proxy logs.\n */\nexport function buildOperatorTokenHook(\n adminToken: string | undefined,\n): (request: FastifyRequest, reply: FastifyReply) => Promise<void> {\n // async, matching buildAccessControlHook's convention: a plain 2-arg\n // function that returns `void` (not a Promise) is ambiguous to Fastify's\n // hook runner, which otherwise waits on a 3rd `done` callback that never\n // comes.\n return async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n if (!adminToken) {\n reply.status(404).send();\n return;\n }\n if (!isValidAdminToken(request.headers.authorization, adminToken)) {\n reply\n .status(401)\n .send({ status: 'error', code: 'UNAUTHORIZED', message: 'Admin token required' });\n }\n };\n}\n\n/** `new URL()` handles port-stripping and IPv6 bracket notation; no need to hand-roll it. */\nfunction hostnameOf(value: string): string {\n try {\n const hostname = new URL(\n value.includes('://') ? value : `http://${value}`,\n ).hostname.toLowerCase();\n // URL#hostname keeps the brackets on an IPv6 literal (\"[::1]\"); strip them\n // so it compares equal to the plain \"::1\" form.\n return hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;\n } catch {\n return '';\n }\n}\n\n// Loopback aliases are always trusted regardless of configured publicBaseUrl:\n// a DNS-rebinding attacker's page sends its OWN hostname as Host, never the\n// literal string \"localhost\"/\"127.0.0.1\"/\"::1\" — so allowing these can never\n// reintroduce the attack this check exists to stop, and it keeps local\n// dev/test setups (where the bind host and the configured publicBaseUrl\n// legitimately differ, e.g. 127.0.0.1 vs. localhost) working without\n// requiring them to match exactly.\nconst LOOPBACK_HOSTNAMES = new Set(['localhost', '127.0.0.1', '::1']);\n\nfunction isAllowedHost(hostHeader: string | undefined, publicHostname: string): boolean {\n if (!hostHeader) return false;\n const hostname = hostnameOf(hostHeader);\n return hostname !== '' && (hostname === publicHostname || LOOPBACK_HOSTNAMES.has(hostname));\n}\n\nfunction isValidAdminToken(authHeader: string | undefined, adminToken: string): boolean {\n const provided = authHeader?.startsWith('Bearer ')\n ? authHeader.slice('Bearer '.length)\n : undefined;\n if (provided === undefined) return false;\n // Hash both sides first: timingSafeEqual throws on unequal-length buffers,\n // and a thrown-vs-not branch is itself a timing/type oracle on the token's\n // length. SHA-256 digests are always 32 bytes, so the comparison is\n // constant-shape regardless of what the caller sent.\n return timingSafeEqual(hashToken(provided), hashToken(adminToken));\n}\n\nfunction hashToken(value: string): Buffer {\n return createHash('sha256').update(value, 'utf8').digest();\n}\n","/**\n * Adapter isolation: a failing adapter must not\n * prevent the server from starting or other adapters from working.\n *\n * `HttpProtocolAdapter`s are mounted at `adapter.mountPath` inside an\n * encapsulated Fastify plugin that never lets Fastify consume the request\n * body — the adapter's own transport (MCP's Streamable HTTP) reads\n * `request.raw` itself, so we register a wildcard content-type parser that\n * is a deliberate no-op, then hand the adapter the raw Node req/res and\n * `reply.hijack()` so Fastify does not also try to send a response.\n *\n * Fastify enforces `bodyLimit` *inside* the content-type parser — a\n * parser that never touches the payload never enforces it, so this mount had\n * no body cap at all, and the SDK's Streamable HTTP transport buffers the\n * whole request into memory with no cap of its own (unauthenticated, no\n * handshake needed). MOUNT_BODY_LIMIT_BYTES is enforced by tallying bytes on\n * the underlying *socket* (not the request stream) as they arrive and\n * destroying the connection past the cap: `Content-Length` alone is\n * insufficient (chunked encoding has none), and observing the socket's own\n * 'data' event doesn't compete with however the adapter reads the body —\n * Node's HTTP module already keeps the socket flowing internally to feed its\n * parser, so an extra listener is pure fan-out, never a second consumer. It\n * can only ever say \"stop\", never corrupt or steal a byte the adapter needs.\n */\n\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';\nimport {\n type AdapterHealth,\n type Clock,\n CommerceError,\n type HttpProtocolAdapter,\n isHttpProtocolAdapter,\n type Logger,\n type ProtocolAdapter,\n type ProtocolAdapterContext,\n toErrorEnvelope,\n} from '../core/index.js';\n\n/**\n * A separate, larger (1 MB) cap for this mount is tempting — MCP tool\n * payloads can legitimately carry more data than a REST-style invoke body.\n * It matches `server.ts`'s route `bodyLimit` (256 KB) anyway: the adapter\n * closes the batch-fan-out half (bounded concurrency, stop-on-disconnect),\n * but the SDK transport still parses the whole array before adapter code\n * ever runs, so\n * this cap is the only lever left on the first-request parse-time memory\n * spike, and a smaller cap admits proportionally fewer batch entries. One\n * documented number is also simpler to state correctly than \"two caps,\n * enforced two different ways\" — which is how `/mcp` ended up with no cap\n * at all in the first place (see docs/security.md). `server.ts` imports\n * this rather than defining its own, so there is exactly one number, not\n * two that happen to currently agree.\n */\nexport const MOUNT_BODY_LIMIT_BYTES = 256 * 1024;\n\nexport interface AdapterRuntime {\n readonly adapter: ProtocolAdapter;\n /** Set only when `start()` threw; a failed adapter is never re-queried live. */\n readonly startFailure?: AdapterHealth;\n}\n\nexport interface StartAndMountOptions {\n readonly server: FastifyInstance;\n readonly adapters: readonly ProtocolAdapter[];\n readonly context: ProtocolAdapterContext;\n readonly logger: Logger;\n readonly clock: Clock;\n}\n\nexport async function startAndMountAdapters(\n options: StartAndMountOptions,\n): Promise<AdapterRuntime[]> {\n // Before anything starts: two adapters claiming the same path is a\n // composition-root bug, not a runtime condition. Fastify would only notice\n // it inside deferred route registration and fail `server.ready()` with an\n // opaque FST_ERR_DUPLICATED_ROUTE naming neither adapter.\n assertNoRouteConflicts(options.adapters);\n\n const runtimes: AdapterRuntime[] = [];\n\n for (const adapter of options.adapters) {\n // Pre-scope the logger so every adapter's own log calls carry\n // `adapter: <name>` automatically — the adapter never has to remember to\n // add it itself.\n const adapterLogger = options.logger.child({ adapter: adapter.name });\n const adapterContext: ProtocolAdapterContext = { ...options.context, logger: adapterLogger };\n\n try {\n await adapter.start(adapterContext);\n } catch (error) {\n const detail = describeError(error);\n adapterLogger.error(\n { err: detail },\n 'Protocol adapter failed to start; gateway continues without it',\n );\n runtimes.push({\n adapter,\n startFailure: { status: 'fail', detail, checkedAt: options.clock.nowIso() },\n });\n continue;\n }\n\n if (isHttpProtocolAdapter(adapter)) {\n mountHttpAdapter(options.server, adapter, adapterLogger);\n }\n runtimes.push({ adapter });\n }\n\n return runtimes;\n}\n\ninterface RouteClaim {\n readonly adapter: string;\n readonly path: string;\n /** A mount also owns everything below its path, through its `/*` wildcard. */\n readonly wildcard: boolean;\n readonly method: 'ALL' | 'GET' | 'POST';\n}\n\nfunction routeClaims(adapters: readonly ProtocolAdapter[]): RouteClaim[] {\n const claims: RouteClaim[] = [];\n for (const adapter of adapters) {\n if (!isHttpProtocolAdapter(adapter)) continue;\n claims.push({\n adapter: adapter.name,\n path: adapter.mountPath.replace(/\\/+$/, ''),\n wildcard: true,\n method: 'ALL',\n });\n for (const route of adapter.additionalHttpRoutes ?? []) {\n claims.push({\n adapter: adapter.name,\n path: route.path.replace(/\\/+$/, ''),\n wildcard: false,\n method: route.method,\n });\n }\n }\n return claims;\n}\n\nfunction claimsCollide(a: RouteClaim, b: RouteClaim): boolean {\n if (a.wildcard && (b.path === a.path || b.path.startsWith(`${a.path}/`))) return true;\n if (b.wildcard && a.path.startsWith(`${b.path}/`)) return true;\n return a.path === b.path && (a.method === b.method || a.method === 'ALL' || b.method === 'ALL');\n}\n\n/**\n * Only *cross-adapter* claims conflict. An adapter serving a fixed route under\n * its own mount is fine — Fastify prefers a static route over a wildcard — and\n * is how a protocol that pins a sub-path stays self-contained.\n */\nfunction assertNoRouteConflicts(adapters: readonly ProtocolAdapter[]): void {\n const claims = routeClaims(adapters);\n for (const [index, a] of claims.entries()) {\n for (const b of claims.slice(index + 1)) {\n if (a.adapter === b.adapter || !claimsCollide(a, b)) continue;\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Protocol adapters \"${a.adapter}\" and \"${b.adapter}\" both claim the HTTP path \"${b.path}\"; each adapter path must be served by exactly one adapter`,\n { details: { adapters: [a.adapter, b.adapter], path: b.path } },\n );\n }\n }\n}\n\n/**\n * The body limit and the per-tool-call semaphore\n * (`protocol-mcp`'s MAX_CONCURRENT_TOOL_CALLS) both bound *what happens\n * after* a request is parsed — neither sees the SDK's own JSON.parse of the\n * request body, which was measured spiking one 256 KB batch\n * request's heap by ~106 MB (26 -> 132 MB) before GC reclaims it. Not a\n * leak, but unbounded concurrency times an unbounded spike is unbounded\n * memory: a 20-concurrent-batches probe (262 KB each) is\n * the only concurrency level this has actually been measured safe at (peak\n * RSS 368 MB, fully reclaimed) — so 20 is the cap, not a rounder guess.\n * compose sets no memory limit, so this is the only thing standing between\n * \"~40 connections\" and a multi-gigabyte spike.\n */\nexport const MOUNT_MAX_CONCURRENT_REQUESTS = 20;\n/** Short and blunt on purpose: this is a parse-time spike that clears in\n * well under a second once GC runs, not an outage a client should back off\n * from for long. */\nconst MOUNT_BUSY_RETRY_AFTER_SECONDS = 1;\n\nfunction mountHttpAdapter(\n server: FastifyInstance,\n adapter: HttpProtocolAdapter,\n logger: Logger,\n): void {\n const mountPath = adapter.mountPath;\n const wildcard = mountPath.endsWith('/') ? `${mountPath}*` : `${mountPath}/*`;\n const additionalRoutes = adapter.additionalHttpRoutes ?? [];\n // One counter for the whole adapter, mount and fixed routes alike: the cap\n // bounds what this adapter can be made to parse concurrently, and a second\n // door into the same adapter would be a way around it.\n let inFlight = 0;\n\n void server.register(async (instance) => {\n // Fastify pre-registers exact-match parsers for application/json and\n // text/plain that run BEFORE the '*' fallback (checked in getParser()).\n // MCP clients send application/json, so without an exact no-op here\n // Fastify's built-in JSON parser drains request.raw before the adapter's\n // own transport ever reads it -> the adapter sees an empty stream.\n instance.addContentTypeParser(\n ['application/json', 'text/plain'],\n (_request, _payload, done) => {\n done(null);\n },\n );\n instance.addContentTypeParser('*', (_request, _payload, done) => {\n done(null);\n });\n\n const makeHandler =\n (handleHttp: (req: IncomingMessage, res: ServerResponse) => Promise<void>) =>\n async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n if (inFlight >= MOUNT_MAX_CONCURRENT_REQUESTS) {\n // Reject before the SDK ever sees the body — the whole point is to\n // never let a request past this line start the parse that spikes\n // memory. No body-limit enforcement needed either: nothing here has\n // read a byte of it yet.\n const error = new CommerceError(\n 'GATEWAY_BUSY',\n 'Too many requests already parsing on this mount; retry shortly.',\n );\n reply\n .status(error.httpStatus)\n .header('retry-after', String(MOUNT_BUSY_RETRY_AFTER_SECONDS))\n .send(toErrorEnvelope(error));\n return;\n }\n inFlight += 1;\n try {\n const stopEnforcing = enforceMountBodyLimit(\n request.raw,\n reply.raw,\n MOUNT_BODY_LIMIT_BYTES,\n logger,\n );\n try {\n await handleHttp(request.raw, reply.raw);\n } catch (error) {\n logger.error({ err: describeError(error) }, 'Protocol adapter request handler threw');\n if (!reply.raw.headersSent) {\n reply.raw.statusCode = 500;\n reply.raw.end();\n }\n }\n stopEnforcing();\n reply.hijack();\n } finally {\n // Always released, even on a throw above — a stranded count would\n // shrink the effective cap by one forever and eventually 503 every\n // request on this mount permanently, which is worse than the\n // problem this exists to solve.\n inFlight -= 1;\n }\n };\n\n const mountHandler = makeHandler((req, res) => adapter.handleHttp(req, res));\n instance.all(mountPath, mountHandler);\n instance.all(wildcard, mountHandler);\n\n for (const route of additionalRoutes) {\n instance.route({\n method: route.method,\n url: route.path,\n handler: makeHandler((req, res) => route.handleHttp(req, res)),\n });\n }\n });\n}\n\nfunction enforceMountBodyLimit(\n req: IncomingMessage,\n res: ServerResponse,\n maxBytes: number,\n logger: Logger,\n): () => void {\n const socket = req.socket;\n let total = 0;\n let stopped = false;\n const onData = (chunk: Buffer): void => {\n total += chunk.length;\n if (total > maxBytes) {\n stop();\n logger.warn({ maxBytes }, 'Request body exceeded the mount body limit; connection closed');\n // a bare socket.destroy() gives the client ECONNRESET\n // with nothing naming the cap — right for an attacker, wrong for a\n // legitimate client the first time a tool payload crosses the limit.\n // Attempt a 413 with a JSON-RPC error body first, then destroy once it\n // has actually flushed. If the adapter already started writing its own\n // response, headersSent is true and there is nothing left to say —\n // just destroy. Never read the rest of the oversized body to be polite\n // about it; that defeats the point of the cap.\n if (!res.headersSent) {\n const body = JSON.stringify({\n jsonrpc: '2.0',\n id: null,\n error: { code: -32600, message: `Request body exceeds the ${maxBytes}-byte mount limit` },\n });\n try {\n res.writeHead(413, {\n 'content-type': 'application/json',\n 'content-length': Buffer.byteLength(body),\n });\n // `.end()`'s callback fires once the write is handed to the OS,\n // not once the peer has actually received it, so even a\n // best-effort destroy afterward can occasionally race a\n // still-in-flight response and truncate it (the client sees a\n // bare ECONNRESET instead of the 413 body). That is an accepted\n // trade — see \"attempt\" in the comment above — over leaving the\n // read side open, which would undo the whole point of this cap\n // (an attacker's still-arriving bytes must not keep flowing to\n // whatever is reading `req`).\n res.end(body, () => socket.destroy());\n return;\n } catch {\n // Fall through to a bare destroy below — e.g. the socket was\n // already gone by the time we tried to write.\n }\n }\n socket.destroy();\n }\n };\n const stop = (): void => {\n if (stopped) return;\n stopped = true;\n // A keep-alive connection carries many requests, and this function adds\n // a 'close' listener per request. Removing only the 'data' listener here\n // would leave the 'close' one to pile up, one per request, until the\n // connection finally closed (MaxListenersExceeded at request 11). Remove\n // both.\n socket.removeListener('data', onData);\n socket.removeListener('close', stop);\n };\n socket.on('data', onData);\n socket.once('close', stop);\n return stop;\n}\n\nexport async function getAdapterHealth(\n runtime: AdapterRuntime,\n clock: Clock,\n): Promise<AdapterHealth> {\n if (runtime.startFailure) return runtime.startFailure;\n try {\n return await runtime.adapter.health();\n } catch (error) {\n return { status: 'fail', detail: describeError(error), checkedAt: clock.nowIso() };\n }\n}\n\nexport async function stopAdapters(\n runtimes: readonly AdapterRuntime[],\n logger: Logger,\n): Promise<void> {\n for (const runtime of runtimes) {\n try {\n await runtime.adapter.stop();\n } catch (error) {\n logger\n .child({ adapter: runtime.adapter.name })\n .error({ err: describeError(error) }, 'Protocol adapter failed to stop cleanly');\n }\n }\n}\n\nfunction describeError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * Public (secret-free) projection of a `CommerceResource`.\n *\n * `handler.headers` may carry resolved backend secrets (e.g. an\n * `Authorization` value built from `${API_KEY}`) — never expose it on a\n * public discovery surface (`GET /api/resources`, `.well-known`).\n */\nimport type { CommerceResource } from '../core/index.js';\n\nexport interface PublicResource {\n readonly id: string;\n readonly name: string;\n readonly description?: string;\n readonly inputSchema?: Record<string, unknown>;\n readonly outputSchema?: Record<string, unknown>;\n readonly method: string;\n readonly pricing: CommerceResource['pricing'];\n readonly exposedVia: readonly string[];\n readonly paymentMethods: readonly string[];\n}\n\nexport function toPublicResource(resource: CommerceResource): PublicResource {\n return {\n id: resource.id,\n name: resource.name,\n ...(resource.description !== undefined ? { description: resource.description } : {}),\n ...(resource.inputSchema !== undefined ? { inputSchema: resource.inputSchema } : {}),\n ...(resource.outputSchema !== undefined ? { outputSchema: resource.outputSchema } : {}),\n method: resource.handler.method,\n pricing: resource.pricing,\n exposedVia: resource.exposedVia,\n paymentMethods: resource.paymentMethods,\n };\n}\n","/**\n * `GET /ready` readiness computation: 503 unless the store, every configured\n * protocol adapter, AND every payment provider are healthy. `status: 'warn'`\n * is treated as still-serving (degraded); only `status: 'fail'` blocks\n * readiness — applied uniformly to all three kinds of dependency.\n *\n * Payment providers are consulted here alongside the store and protocol\n * adapters: without that, a gateway whose x402 RPC is unreachable reports\n * `ready: true` and goes on serving 402 challenges it cannot honour. `fail`, not `warn`, blocks readiness for a provider — same\n * threshold as the store and adapters, not a special case: a broken payment\n * provider is not \"degraded but serving\", it is a broken core promise for\n * every resource that requires payment, exactly like a store that cannot\n * record or a required adapter that cannot route.\n *\n * The raw `detail` a store/adapter/provider health() implementation\n * returns (or a raw thrown Error's message) is exactly the kind of internal\n * detail exists to keep off a client-visible field — and this is an\n * unauthenticated route. The client only ever sees one of a small fixed\n * vocabulary; the raw detail is logged for the operator.\n *\n * `/ready` is itself unauthenticated, with no cache and no rate\n * limit, and `checkReadiness` calls every dependency's `health()` fresh on\n * every request — on a commercial RPC provider that is a live, billed\n * upstream call an attacker spends for free (measured: 20 requests -> 60\n * upstream JSON-RPC calls). `createReadinessProbe` memoises the result for\n * READINESS_TTL_MS and collapses concurrent callers onto one in-flight\n * evaluation, so a burst of N requests produces at most one real check.\n */\nimport type { AdapterHealth, Clock, Logger, PaymentProvider, ReceiptStore } from '../core/index.js';\nimport { type AdapterRuntime, getAdapterHealth } from './adapters.js';\n\nexport interface ReadinessCheck {\n readonly name: string;\n readonly status: AdapterHealth['status'];\n readonly detail?: string;\n}\n\nexport interface ReadinessResult {\n readonly ready: boolean;\n readonly store: ReadinessCheck;\n readonly adapters: readonly ReadinessCheck[];\n readonly paymentProviders: readonly ReadinessCheck[];\n}\n\nexport interface CheckReadinessOptions {\n readonly store: ReceiptStore;\n readonly adapterRuntimes: readonly AdapterRuntime[];\n readonly paymentProviders: readonly PaymentProvider[];\n readonly clock: Clock;\n readonly logger: Logger;\n}\n\nconst STORE_DETAIL: Readonly<Record<AdapterHealth['status'], string | undefined>> = {\n pass: undefined,\n warn: 'store-degraded',\n fail: 'store-unwritable',\n};\n\nconst ADAPTER_DETAIL: Readonly<Record<AdapterHealth['status'], string | undefined>> = {\n pass: undefined,\n warn: 'adapter-degraded',\n fail: 'adapter-unreachable',\n};\n\nconst PAYMENT_PROVIDER_DETAIL: Readonly<Record<AdapterHealth['status'], string | undefined>> = {\n pass: undefined,\n warn: 'payment-provider-degraded',\n fail: 'payment-provider-unreachable',\n};\n\nexport async function checkReadiness(options: CheckReadinessOptions): Promise<ReadinessResult> {\n let storeHealth: AdapterHealth;\n let storeThrew = false;\n try {\n storeHealth = await options.store.health();\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n options.logger.error({ err: message }, 'store.health() threw');\n storeHealth = { status: 'fail', checkedAt: options.clock.nowIso() };\n storeThrew = true;\n }\n if (storeHealth.detail !== undefined) {\n options.logger.debug(\n { detail: storeHealth.detail },\n 'store health detail (not sent to the client)',\n );\n }\n\n const adapterChecks = await Promise.all(\n options.adapterRuntimes.map(async (runtime): Promise<ReadinessCheck> => {\n const health = await getAdapterHealth(runtime, options.clock);\n if (health.detail !== undefined) {\n options.logger.debug(\n { adapter: runtime.adapter.name, detail: health.detail },\n 'adapter health detail (not sent to the client)',\n );\n }\n const detail = ADAPTER_DETAIL[health.status];\n return {\n name: runtime.adapter.name,\n status: health.status,\n ...(detail !== undefined ? { detail } : {}),\n };\n }),\n );\n\n const paymentProviderChecks = await Promise.all(\n options.paymentProviders.map(async (provider): Promise<ReadinessCheck> => {\n let health: AdapterHealth;\n try {\n health = await provider.health();\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n options.logger.error(\n { err: message, provider: provider.name },\n 'payment provider health() threw',\n );\n health = { status: 'fail', checkedAt: options.clock.nowIso() };\n }\n if (health.detail !== undefined) {\n options.logger.debug(\n { provider: provider.name, detail: health.detail },\n 'payment provider health detail (not sent to the client)',\n );\n }\n const detail = PAYMENT_PROVIDER_DETAIL[health.status];\n return {\n name: provider.name,\n status: health.status,\n ...(detail !== undefined ? { detail } : {}),\n };\n }),\n );\n\n const storeReady = storeHealth.status !== 'fail';\n const adaptersReady = adapterChecks.every((check) => check.status !== 'fail');\n const paymentProvidersReady = paymentProviderChecks.every((check) => check.status !== 'fail');\n const storeDetail = storeThrew ? 'store-unreachable' : STORE_DETAIL[storeHealth.status];\n\n return {\n ready: storeReady && adaptersReady && paymentProvidersReady,\n store: {\n name: 'store',\n status: storeHealth.status,\n ...(storeDetail !== undefined ? { detail: storeDetail } : {}),\n },\n adapters: adapterChecks,\n paymentProviders: paymentProviderChecks,\n };\n}\n\n/** A readiness probe does not need sub-second freshness: a real outage is\n * still caught within one TTL window, and this is short enough that a burst\n * of requests during a genuine state change (e.g. right after startup) isn't\n * stuck looking at a stale answer for long. */\nexport const READINESS_TTL_MS = 2_000;\n\nexport interface ReadinessProbe {\n check(): Promise<ReadinessResult>;\n}\n\nexport function createReadinessProbe(\n options: CheckReadinessOptions,\n ttlMs: number = READINESS_TTL_MS,\n): ReadinessProbe {\n let cached: { readonly result: ReadinessResult; readonly at: number } | undefined;\n let inFlight: Promise<ReadinessResult> | undefined;\n\n return {\n async check(): Promise<ReadinessResult> {\n const now = options.clock.monotonicMs();\n if (cached && now - cached.at < ttlMs) return cached.result;\n if (inFlight) return inFlight;\n\n inFlight = checkReadiness(options)\n .then((result) => {\n cached = { result, at: options.clock.monotonicMs() };\n return result;\n })\n .finally(() => {\n inFlight = undefined;\n });\n return inFlight;\n },\n };\n}\n","/**\n * `GET /.well-known/agent-commerce` — merchant + every adapter/provider/store\n * `AdapterDescriptor`, protocol/spec versions. This route is unauthenticated\n * by design, so nothing here may be a credential.\n *\n * The x402 settlement destination (`payTo`), `network` and `asset` ARE\n * public information — a payer needs them (plus scheme/amount, which travel\n * in the challenge's `accepts` array) to construct a payment, and `payTo` is\n * visible on-chain the moment any transfer lands. `rpcUrl` is different and\n * is deliberately NOT published here: every commercial EVM RPC\n * provider embeds an API key in the URL itself (Alchemy's `/v2/<KEY>`,\n * Infura's `/v3/<KEY>`, QuickNode's per-endpoint token) — on any non-local\n * deployment, echoing it back on an open route hands out a live credential\n * to anyone who asks. The facilitator URL is withheld for the same reason,\n * and the facilitator private key never appears at all. `doctor`'s\n * live/local cross-check (src/cli) only reads `asset`/`network`/`payTo` from\n * this document, so dropping `rpcUrl` does not affect it.\n *\n * `WellKnownDocument` is also exported via the package's\n * `./well-known.js` subpath (non-frozen — see docs/contracts.md's change\n * log) so `demo/dashboard`'s hand-maintained mirror of this shape\n * (`types.ts`) can assert assignability against the real type instead of\n * silently drifting — which is exactly how it twice shipped `rpcUrl` as\n * non-optional after this file stopped sending it. Consuming this as\n * `import type` only is what keeps the dashboard's browser bundle free of\n * Fastify/pino/better-sqlite3: a type-only import is erased entirely by any\n * TypeScript-aware bundler (esbuild, swc, tsc), independent of whatever\n * runtime code this file also happens to export — the same property\n * `src/core`'s `./execution` subpath already relies on.\n */\n\nimport type { GatewayConfig } from '../config/index.js';\nimport type {\n AdapterDescriptor,\n AdapterHealth,\n Clock,\n PaymentProvider,\n ReceiptStore,\n} from '../core/index.js';\nimport {\n type DeploymentMode,\n requireNetworkProfile,\n resolveDeploymentMode,\n} from '../payments/x402/networks.js';\nimport { PACKAGE_VERSION } from '../version.js';\nimport { type AdapterRuntime, getAdapterHealth } from './adapters.js';\n\n/**\n * The spec version is deliberately NOT derived from `PACKAGE_VERSION`. It\n * names the wire contract a client negotiates against, which changes only\n * when that contract does — a patch release of this package speaks the same\n * spec, and announcing a new one on every version bump would tell every\n * client the protocol moved when it did not.\n */\nconst GATEWAY_SUPPORTED_SPEC = 'agent-commerce/v1.0.0';\n\nexport interface WellKnownDocument {\n readonly gateway: { readonly implementationVersion: string; readonly supportedSpec: string };\n readonly merchant: GatewayConfig['merchant'];\n readonly protocols: GatewayConfig['protocols'];\n readonly adapters: ReadonlyArray<AdapterDescriptor & { readonly health: AdapterHealth }>;\n readonly paymentProviders: readonly AdapterDescriptor[];\n readonly store: AdapterDescriptor;\n readonly payments: {\n readonly x402?: {\n readonly enabled: boolean;\n readonly network: string;\n readonly asset: string;\n readonly assetName: string;\n readonly assetVersion: string;\n readonly assetDecimals: number;\n readonly payTo: string;\n readonly maxTimeoutSeconds: number;\n readonly facilitator: { readonly mode: 'local' | 'remote' };\n /** What this deployment actually is. */\n readonly mode: DeploymentMode;\n };\n };\n}\n\nexport interface BuildWellKnownOptions {\n readonly config: GatewayConfig;\n readonly paymentProviders: readonly PaymentProvider[];\n readonly store: ReceiptStore;\n readonly adapterRuntimes: readonly AdapterRuntime[];\n readonly clock: Clock;\n}\n\n/**\n * Strips a health result down to what an anonymous caller may see.\n *\n * `/ready` already codifies this rule and maps `detail` to a fixed vocabulary,\n * because the raw string is exactly the internal detail an unauthenticated\n * route must not carry — `getAdapterHealth` puts `describeError()` there for a\n * thrown `health()`, and a start failure puts the raw throw message, routinely\n * a module path or an internal hostname. This route is the same trust level and\n * was returning it verbatim. `createGateway` is public API and accepts\n * arbitrary adapters, so \"our own adapters say nothing sensitive\" is not a\n * property this code can rely on.\n */\nfunction publicHealth(health: AdapterHealth): AdapterHealth {\n const { detail: _detail, ...rest } = health;\n return rest;\n}\n\nexport async function buildWellKnownDocument(\n options: BuildWellKnownOptions,\n): Promise<WellKnownDocument> {\n const adapters = await Promise.all(\n options.adapterRuntimes.map(async (runtime) => {\n const health = await getAdapterHealth(runtime, options.clock);\n return { ...runtime.adapter.descriptor, health: publicHealth(health) };\n }),\n );\n\n const x402 = options.config.payments.x402;\n\n return {\n gateway: {\n implementationVersion: PACKAGE_VERSION,\n supportedSpec: GATEWAY_SUPPORTED_SPEC,\n },\n merchant: options.config.merchant,\n protocols: options.config.protocols,\n adapters,\n paymentProviders: options.paymentProviders.map((provider) => provider.descriptor),\n store: options.store.descriptor,\n payments: {\n ...(x402 !== undefined\n ? {\n x402: {\n enabled: x402.enabled,\n network: x402.network,\n asset: x402.asset,\n assetName: x402.assetName,\n assetVersion: x402.assetVersion,\n assetDecimals: x402.assetDecimals,\n payTo: x402.payTo,\n maxTimeoutSeconds: x402.maxTimeoutSeconds,\n // Never the signerPrivateKey, and never the facilitator URL:\n // a facilitator endpoint is a per-deployment operational detail\n // that can carry a tenant path or an API key, exactly like\n // `rpcUrl` above. Only whether it is local or remote is public.\n facilitator: { mode: x402.facilitator.mode },\n // Chain id 84532 is shared between the local dev chain and\n // public Base Sepolia, so the network id alone cannot say which\n // one a client is talking to. This can.\n mode: resolveDeploymentMode(\n requireNetworkProfile(x402.network, 'payments.x402.network'),\n x402.facilitator.mode,\n ),\n },\n }\n : {}),\n },\n };\n}\n","/**\n * The gateway's own HTTP surface (docs/contracts.md \"Gateway HTTP surface\").\n * Adapter mounting (e.g. `/mcp`) is handled separately in adapters.ts.\n */\n\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';\nimport type { GatewayConfig } from '../config/index.js';\nimport type { EventBus } from '../core/execution/index.js';\nimport {\n type CanonicalRequest,\n type Clock,\n CommerceError,\n type ExecutionPipeline,\n type Logger,\n PAYMENT_HEADER,\n PAYMENT_REQUIRED_HEADER,\n PAYMENT_RESPONSE_HEADER,\n type PaymentProvider,\n type ReceiptStore,\n type ResourceRegistry,\n toCommerceError,\n toErrorEnvelope,\n toPaymentRequiredEnvelope,\n} from '../core/index.js';\nimport { buildOperatorTokenHook } from './access-control.js';\nimport type { AdapterRuntime } from './adapters.js';\nimport { toPublicResource } from './public-resource.js';\nimport { createReadinessProbe } from './readiness.js';\nimport { buildWellKnownDocument } from './well-known.js';\n\nconst SSE_HEARTBEAT_MS = 15_000;\nconst MAX_SSE_SUBSCRIBERS = 32;\n\nexport interface RegisterRoutesOptions {\n readonly server: FastifyInstance;\n readonly config: GatewayConfig;\n readonly pipeline: ExecutionPipeline;\n readonly resources: ResourceRegistry;\n readonly store: ReceiptStore;\n readonly paymentProviders: readonly PaymentProvider[];\n readonly eventBus: EventBus;\n readonly clock: Clock;\n readonly adapterRuntimes: readonly AdapterRuntime[];\n readonly logger: Logger;\n}\n\nexport function registerRoutes(options: RegisterRoutesOptions): void {\n const { server } = options;\n\n // memoised + single-flight — see readiness.ts's own doc comment.\n // `options.adapterRuntimes` is mutated in place (pushed into) after\n // adapters start, so capturing the reference here is fine — the probe\n // always reads whatever it currently holds.\n const readinessProbe = createReadinessProbe({\n store: options.store,\n adapterRuntimes: options.adapterRuntimes,\n paymentProviders: options.paymentProviders,\n clock: options.clock,\n logger: options.logger,\n });\n\n server.get('/health', async () => ({ status: 'ok' }));\n\n server.get('/ready', async (_request, reply) => {\n const readiness = await readinessProbe.check();\n reply.status(readiness.ready ? 200 : 503);\n return readiness;\n });\n\n server.get('/.well-known/agent-commerce', async () =>\n buildWellKnownDocument({\n config: options.config,\n paymentProviders: options.paymentProviders,\n store: options.store,\n adapterRuntimes: options.adapterRuntimes,\n clock: options.clock,\n }),\n );\n\n server.get('/api/resources', async () => ({\n resources: options.resources.list().map(toPublicResource),\n }));\n\n server.post('/api/resources/:id/invoke', async (request, reply) => {\n await handleInvoke(request, reply, options);\n });\n\n // The admin-token gate is a per-route hook on each of these three\n // route definitions (not the global onRequest hook) — see\n // access-control.ts's file header for why. Fastify only invokes it once\n // routing has matched this exact route, so there is no percent-encoded\n // path string left for an attacker to disagree with the router about.\n const receiptsTokenHook = buildOperatorTokenHook(options.config.server.adminToken);\n const eventsTokenHook = buildOperatorTokenHook(options.config.server.adminToken);\n const eventsStreamTokenHook = buildOperatorTokenHook(options.config.server.adminToken);\n\n server.get('/api/receipts', { onRequest: receiptsTokenHook }, async (request, reply) => {\n try {\n const limit = parseLimit((request.query as Record<string, unknown>)['limit']);\n return { receipts: await options.store.listReceipts(limit !== undefined ? { limit } : {}) };\n } catch (error) {\n const commerceError = toCommerceError(error);\n reply.status(commerceError.httpStatus).send(toErrorEnvelope(commerceError));\n return undefined;\n }\n });\n\n server.get('/api/events', { onRequest: eventsTokenHook }, async (request, reply) => {\n try {\n const limit = parseLimit((request.query as Record<string, unknown>)['limit']);\n return { events: await options.store.listEvents(limit !== undefined ? { limit } : {}) };\n } catch (error) {\n const commerceError = toCommerceError(error);\n reply.status(commerceError.httpStatus).send(toErrorEnvelope(commerceError));\n return undefined;\n }\n });\n\n let activeSseSubscribers = 0;\n\n server.get('/api/events/stream', { onRequest: eventsStreamTokenHook }, (request, reply) => {\n // cap concurrent subscribers — the token hook above already\n // rejects an unauthenticated client before this handler runs; this cap\n // is about an *authenticated* client that never reads, which would\n // otherwise let Node buffer indefinitely, N times over.\n if (activeSseSubscribers >= MAX_SSE_SUBSCRIBERS) {\n reply.status(503).send({\n status: 'error',\n code: 'UNAVAILABLE',\n message: 'Too many event-stream subscribers',\n });\n return;\n }\n reply.raw.writeHead(200, {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive',\n });\n // Increment only after writeHead succeeds: if it threw, cleanup() below\n // was never registered, and incrementing first would leak the slot\n // permanently (after MAX_SSE_SUBSCRIBERS such leaks, the route is dead).\n activeSseSubscribers += 1;\n reply.raw.write(': connected\\n\\n');\n\n // Backpressure: write() returning false means the socket buffer\n // is full. Drop frames — not queue them — until 'drain'; an SSE feed is\n // \"latest state\", not a guaranteed-delivery log, and queuing unboundedly\n // is the exact memory-growth problem this is meant to avoid.\n let writable = true;\n reply.raw.on('drain', () => {\n writable = true;\n });\n\n // no `event:` line — the dashboard's EventSource only listens for\n // the default `message` type, and a named event never reaches onmessage\n // (onopen still fires, so the client reports \"live\" over a frozen feed).\n // `data:` already carries `type` in the serialised payload.\n //\n // queueMicrotask decouples fan-out from the caller: EventBus#emit() is\n // awaited inside the execution pipeline, so writing synchronously here\n // would add a slow SSE reader's latency to the payment path.\n const unsubscribe = options.eventBus.subscribe((event) => {\n queueMicrotask(() => {\n if (!writable) return;\n writable = reply.raw.write(`data: ${JSON.stringify(event)}\\n\\n`);\n });\n });\n\n const heartbeat = setInterval(() => {\n if (!writable) return;\n writable = reply.raw.write(': heartbeat\\n\\n');\n }, SSE_HEARTBEAT_MS);\n heartbeat.unref();\n\n // Guards against a double-decrement if both 'close' and 'error' fire for\n // the same connection (never actually observed — 40 connect/destroy\n // cycles could not trigger it — but the guard is one line and removes\n // the question).\n let cleanedUp = false;\n const cleanup = (): void => {\n if (cleanedUp) return;\n cleanedUp = true;\n clearInterval(heartbeat);\n unsubscribe();\n activeSseSubscribers -= 1;\n };\n request.raw.on('close', cleanup);\n reply.raw.on('error', cleanup);\n\n reply.hijack();\n });\n}\n\nasync function handleInvoke(\n request: FastifyRequest,\n reply: FastifyReply,\n options: RegisterRoutesOptions,\n): Promise<void> {\n const resourceId = (request.params as { id: string }).id;\n\n try {\n const resource = options.resources.get(resourceId);\n if (!resource || !resource.exposedVia.includes('http')) {\n throw new CommerceError('RESOURCE_NOT_FOUND', `Resource \"${resourceId}\" was not found`, {\n requestId: request.id,\n resourceId,\n });\n }\n\n const paymentHeader = request.headers[PAYMENT_HEADER];\n const paymentValue = Array.isArray(paymentHeader) ? paymentHeader[0] : paymentHeader;\n\n // The gateway does not decide which rail a resource uses — that's the\n // canonical resource's job (mirrors the protocol-side fix in the MCP\n // adapter). Derive the method from resource.paymentMethods instead of\n // hard-coding 'x402'. If a proof arrives for a resource with no payment\n // method configured, drop it rather than inventing a rail: the pipeline\n // will treat the resource as free (or reject it) on its own terms.\n const paymentMethod = resource.paymentMethods[0];\n const payment =\n paymentValue !== undefined && paymentMethod !== undefined\n ? { method: paymentMethod, payload: paymentValue }\n : undefined;\n\n const canonicalRequest: CanonicalRequest = {\n requestId: request.id,\n resourceId,\n input: request.body ?? {},\n protocol: 'http',\n receivedAt: options.clock.nowIso(),\n ...(payment !== undefined ? { payment } : {}),\n };\n\n const outcome = await options.pipeline.execute(canonicalRequest);\n\n if (outcome.kind === 'payment-required') {\n const envelope = toPaymentRequiredEnvelope(outcome);\n if (envelope.payment.envelope !== undefined) {\n // x402 v2 clients read the challenge from this header and never look\n // at the body. The body is still sent — it is richer, and it is the\n // only channel the MCP surface has — but the header is what makes an\n // off-the-shelf client able to pay.\n reply.header(PAYMENT_REQUIRED_HEADER, encodeHeaderDocument(envelope.payment.envelope));\n }\n // A challenge is per-request (fresh nonce window, fresh expiry). Caching\n // one would hand a later buyer an expired offer.\n reply.header('cache-control', 'no-store');\n reply.status(402).send(envelope);\n return;\n }\n\n if (outcome.payment) {\n reply.header(PAYMENT_RESPONSE_HEADER, encodePaymentSummary(outcome.payment));\n }\n reply.status(outcome.backendStatus).send(outcome.body);\n } catch (error) {\n const commerceError = toCommerceError(error);\n // a backend failure after successful settlement carries the\n // settlement summary on details.payment (pipeline.ts) — set the same\n // header the success path sets, so the buyer isn't told strictly less\n // about their own payment on the error path than on the happy path.\n const settledPayment = errorPaymentSummary(commerceError);\n if (settledPayment !== undefined) {\n reply.header(PAYMENT_RESPONSE_HEADER, encodePaymentSummary(settledPayment));\n }\n reply.status(commerceError.httpStatus).send(toErrorEnvelope(commerceError));\n }\n}\n\ninterface PaymentSummary {\n readonly status: string;\n readonly provider: string;\n readonly amount: string;\n readonly currency: string;\n readonly network?: string;\n readonly externalReference?: string;\n}\n\nfunction errorPaymentSummary(\n error: ReturnType<typeof toCommerceError>,\n): PaymentSummary | undefined {\n const payment = error.details?.['payment'];\n if (typeof payment !== 'object' || payment === null) return undefined;\n const rec = payment as Record<string, unknown>;\n const { status, provider, amount, currency, network, externalReference } = rec;\n if (\n typeof status !== 'string' ||\n typeof provider !== 'string' ||\n typeof amount !== 'string' ||\n typeof currency !== 'string'\n ) {\n return undefined;\n }\n return {\n status,\n provider,\n amount,\n currency,\n ...(typeof network === 'string' ? { network } : {}),\n ...(typeof externalReference === 'string' ? { externalReference } : {}),\n };\n}\n\n/**\n * Base64 of a JSON document, the encoding every x402 v2 payment header uses.\n *\n * Hand-rolled rather than imported from the x402 SDK on purpose: this module\n * is reachable from the package's main entry point, which must import zero\n * optional peers, and it is two lines.\n */\nfunction encodeHeaderDocument(document: unknown): string {\n return Buffer.from(JSON.stringify(document), 'utf8').toString('base64');\n}\n\n/**\n * The settlement result, in the shape an x402 v2 client decodes from\n * `PAYMENT-RESPONSE` (`SettleResponse`), mapped from the canonical\n * {@link PaymentResult} the pipeline produced.\n *\n * `provider`, `amount` and `currency` are ours and are additive: a v2 client\n * reads the fields it knows and ignores the rest.\n */\nfunction encodePaymentSummary(payment: PaymentSummary): string {\n return encodeHeaderDocument({\n success: payment.status === 'settled',\n transaction: payment.externalReference ?? '',\n network: payment.network ?? '',\n status: payment.status,\n provider: payment.provider,\n amount: payment.amount,\n currency: payment.currency,\n ...(payment.externalReference !== undefined\n ? { externalReference: payment.externalReference }\n : {}),\n });\n}\n\n/** Undefined = no limit given / unparseable (caller applies its own default). A\n * parseable but non-positive value (SQLite treats a negative LIMIT as\n * unbounded) is a caller error, not silently \"no limit\". */\nfunction parseLimit(value: unknown): number | undefined {\n if (Array.isArray(value)) return parseLimit(value[0]);\n let n: number | undefined;\n if (typeof value === 'number' && Number.isFinite(value)) n = Math.trunc(value);\n else if (typeof value === 'string' && value.length > 0) {\n const parsed = Number(value);\n if (Number.isFinite(parsed)) n = Math.trunc(parsed);\n }\n if (n === undefined) return undefined;\n if (n <= 0) {\n throw new CommerceError(\n 'INPUT_INVALID',\n `Query parameter \"limit\" must be a positive integer (got ${n})`,\n {\n details: { field: 'limit' },\n },\n );\n }\n return n;\n}\n","/**\n * `createGateway()` — the Fastify server. Fully usable (and tested) with\n * fakes, without `main.ts` (docs/contracts.md \"Composition root\").\n */\n\nimport Fastify, { type FastifyInstance } from 'fastify';\nimport type { GatewayConfig } from '../config/index.js';\nimport {\n createEventBus,\n createExecutionPipeline,\n createResourceRegistry,\n HttpBackendExecutor,\n} from '../core/execution/index.js';\nimport {\n type BackendExecutor,\n type Clock,\n type ExecutionPipeline,\n type IdGenerator,\n type Logger,\n type PaymentProvider,\n type ProtocolAdapter,\n type ProtocolAdapterContext,\n type ReceiptStore,\n type ResourceRegistry,\n systemClock,\n} from '../core/index.js';\nimport { buildAccessControlHook } from './access-control.js';\nimport {\n type AdapterRuntime,\n MOUNT_BODY_LIMIT_BYTES,\n startAndMountAdapters,\n stopAdapters,\n} from './adapters.js';\nimport { createDefaultIdGenerator } from './ids.js';\nimport { buildNotFoundHandler, createGatewayLogger, fastifyLoggerOptions } from './logger.js';\nimport { registerRoutes } from './routes.js';\n\nconst REQUEST_ID_HEADER = 'x-request-id';\n// an unvalidated caller-supplied id becomes the audit trail's\n// correlation key — a caller could reuse a legitimate flow's id to conflate\n// records, or write an unbounded string into every row. A client id is only\n// accepted in this constrained form; anything else gets a gateway-minted one.\nconst CLIENT_REQUEST_ID_PATTERN = /^[A-Za-z0-9._:-]{1,64}$/;\n\nexport interface GatewayOptions {\n readonly config: GatewayConfig;\n readonly store: ReceiptStore;\n readonly paymentProviders: readonly PaymentProvider[];\n readonly protocolAdapters: readonly ProtocolAdapter[];\n readonly logger?: Logger;\n readonly clock?: Clock;\n readonly ids?: IdGenerator;\n /** Override for tests. */\n readonly backend?: BackendExecutor;\n}\n\nexport interface GatewayInstance {\n readonly pipeline: ExecutionPipeline;\n readonly resources: ResourceRegistry;\n listen(): Promise<{ url: string }>;\n close(): Promise<void>;\n /** Fastify instance, for `.inject()` in tests. */\n readonly server: FastifyInstance;\n}\n\nexport async function createGateway(options: GatewayOptions): Promise<GatewayInstance> {\n const clock = options.clock ?? systemClock;\n const ids = options.ids ?? createDefaultIdGenerator();\n const logger = options.logger ?? createGatewayLogger({ name: options.config.merchant.id }).core;\n const backend = options.backend ?? new HttpBackendExecutor({ logger });\n\n const resources = createResourceRegistry(options.config.resources);\n const eventBus = createEventBus({ store: options.store, logger });\n const pipeline = createExecutionPipeline({\n resources,\n paymentProviders: options.paymentProviders,\n store: options.store,\n backend,\n events: eventBus,\n logger,\n clock,\n ids,\n });\n\n const server = Fastify({\n // One number for both surfaces — see adapters.ts's doc comment\n // on MOUNT_BODY_LIMIT_BYTES for why they're enforced two different ways.\n bodyLimit: MOUNT_BODY_LIMIT_BYTES,\n genReqId: (rawReq) => {\n const header = rawReq.headers[REQUEST_ID_HEADER];\n const value = Array.isArray(header) ? header[0] : header;\n return value !== undefined && CLIENT_REQUEST_ID_PATTERN.test(value) ? value : ids.next('req');\n },\n logger: fastifyLoggerOptions({ name: `${options.config.merchant.id}-http` }),\n });\n\n // See buildNotFoundHandler's own doc comment (logger.ts) — this\n // is what leaked the SSE ?adminToken= query param at info level on any 404\n // (a typo'd route, even a trailing slash on a real one).\n server.setNotFoundHandler(buildNotFoundHandler());\n\n // Host/Origin/admin-token gate — see access-control.ts. Closed by default:\n // no allowedOrigins means no browser can read anything cross-origin, and no\n // adminToken means the ledger routes 404 rather than serving openly.\n server.addHook(\n 'onRequest',\n buildAccessControlHook({\n publicBaseUrl: options.config.merchant.publicBaseUrl,\n allowedOrigins: options.config.server.allowedOrigins,\n }),\n );\n\n const adapterRuntimes: AdapterRuntime[] = [];\n\n registerRoutes({\n server,\n config: options.config,\n pipeline,\n resources,\n store: options.store,\n paymentProviders: options.paymentProviders,\n eventBus,\n clock,\n adapterRuntimes,\n logger,\n });\n\n const context: ProtocolAdapterContext = {\n pipeline,\n resources,\n events: eventBus,\n logger,\n clock,\n ids,\n publicBaseUrl: options.config.merchant.publicBaseUrl,\n };\n\n const started = await startAndMountAdapters({\n server,\n adapters: options.protocolAdapters,\n context,\n logger,\n clock,\n });\n adapterRuntimes.push(...started);\n\n await server.ready();\n\n return {\n pipeline,\n resources,\n async listen(): Promise<{ url: string }> {\n const url = await server.listen({\n port: options.config.server.port,\n host: options.config.server.host,\n });\n return { url };\n },\n async close(): Promise<void> {\n await stopAdapters(adapterRuntimes, logger);\n await server.close();\n },\n server,\n };\n}\n","/**\n * Defence-in-depth against accidentally persisting secrets.\n *\n * The gateway and payment providers are expected to never place secrets into\n * `CommerceReceipt.metadata`, `CommerceEvent.data` or `PaymentResult.metadata`\n * (see docs/contracts.md, \"Store NO secrets\"). This module is a second line\n * of defence at the persistence boundary: any key that *looks* like it holds\n * a private key, an auth header or a raw payment proof is stripped — never\n * persisted — rather than rejecting the whole write, so a logging bug never\n * takes down an otherwise-successful commerce flow (appendEvent especially\n * must never throw into the caller's flow).\n */\n/**\n * The bearer-token family was missing — `token`, `bearerToken`,\n * `adminToken`, `authToken`, `credential`, `cookie`, `sessionId`, `jwt` all\n * returned false. Nothing writes such a key today, which is exactly the state\n * a second line of defence is for; and this data also lands in a\n * file that is now owner-only precisely because it is worth protecting.\n */\nconst SECRET_KEY_PATTERN =\n /private[-_ ]?key|secret|password|mnemonic|seed[-_ ]?phrase|api[-_ ]?key|authoriz(e|ation)|^auth$|auth[-_]?header|payment[-_ ]?proof|^proof$|x-payment|signature|signed[-_ ]?message|token|bearer|credential|cookie|session|jwt/i;\n\nconst REDACTED = '[REDACTED]';\n\n/** True if `key` looks like it names a secret value. */\nexport function isSecretKey(key: string): boolean {\n return SECRET_KEY_PATTERN.test(key);\n}\n\n/**\n * Recursively strip values whose key looks secret-shaped, returning a new\n * object. Safe to call on already-clean data (no-op in that case).\n */\nexport function redact<T>(value: T): T {\n return redactValue(value) as T;\n}\n\nfunction redactValue(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(redactValue);\n }\n if (value !== null && typeof value === 'object') {\n const out: Record<string, unknown> = {};\n for (const [key, inner] of Object.entries(value as Record<string, unknown>)) {\n out[key] = isSecretKey(key) ? REDACTED : redactValue(inner);\n }\n return out;\n }\n return value;\n}\n\n/** True if `value` (recursively) contains any key that looks secret-shaped. */\nexport function containsSecretKey(value: unknown): boolean {\n if (Array.isArray(value)) {\n return value.some(containsSecretKey);\n }\n if (value !== null && typeof value === 'object') {\n return Object.entries(value as Record<string, unknown>).some(\n ([key, inner]) => isSecretKey(key) || containsSecretKey(inner),\n );\n }\n return false;\n}\n","/**\n * SQLite row shapes and mapping to/from the canonical domain model.\n *\n * `exactOptionalPropertyTypes` is on: optional fields are only assigned when\n * present (see docs/contracts.md, assumption 8).\n */\nimport type {\n CommerceEvent,\n CommerceEventType,\n CommerceReceipt,\n PaymentAttempt,\n PaymentResult,\n} from '../../core/index.js';\nimport { redact } from './redact.js';\n\nexport interface ReceiptRow {\n readonly id: string;\n readonly request_id: string;\n readonly resource_id: string;\n readonly payment_json: string | null;\n readonly delivered_at: string;\n readonly backend_status: number;\n readonly duration_ms: number | null;\n readonly protocol: string | null;\n readonly metadata_json: string | null;\n}\n\nexport interface EventRow {\n readonly id: string;\n readonly type: string;\n readonly request_id: string;\n readonly resource_id: string | null;\n readonly at: string;\n readonly adapter: string | null;\n readonly payment_provider: string | null;\n readonly duration_ms: number | null;\n readonly status: string | null;\n readonly data_json: string | null;\n}\n\nexport interface PaymentAttemptRow {\n readonly id: string;\n readonly request_id: string;\n readonly resource_id: string;\n readonly provider: string;\n readonly replay_key: string;\n readonly status: string;\n readonly amount: string;\n readonly currency: string;\n readonly payer: string | null;\n readonly payee: string | null;\n readonly external_reference: string | null;\n readonly rejection_reason: string | null;\n readonly created_at: string;\n readonly updated_at: string;\n}\n\nexport function receiptToRow(receipt: CommerceReceipt): {\n id: string;\n request_id: string;\n resource_id: string;\n payment_json: string | null;\n delivered_at: string;\n backend_status: number;\n duration_ms: number | null;\n protocol: string | null;\n metadata_json: string | null;\n} {\n return {\n id: receipt.id,\n request_id: receipt.requestId,\n resource_id: receipt.resourceId,\n payment_json: receipt.payment !== undefined ? JSON.stringify(redact(receipt.payment)) : null,\n delivered_at: receipt.deliveredAt,\n backend_status: receipt.backendStatus,\n duration_ms: receipt.durationMs !== undefined ? receipt.durationMs : null,\n protocol: receipt.protocol !== undefined ? receipt.protocol : null,\n metadata_json: receipt.metadata !== undefined ? JSON.stringify(redact(receipt.metadata)) : null,\n };\n}\n\nexport function rowToReceipt(row: ReceiptRow): CommerceReceipt {\n const payment =\n row.payment_json !== null ? (JSON.parse(row.payment_json) as PaymentResult) : undefined;\n const metadata =\n row.metadata_json !== null\n ? (JSON.parse(row.metadata_json) as Record<string, unknown>)\n : undefined;\n return {\n id: row.id,\n requestId: row.request_id,\n resourceId: row.resource_id,\n deliveredAt: row.delivered_at,\n backendStatus: row.backend_status,\n ...(payment !== undefined ? { payment } : {}),\n ...(row.duration_ms !== null ? { durationMs: row.duration_ms } : {}),\n ...(row.protocol !== null ? { protocol: row.protocol } : {}),\n ...(metadata !== undefined ? { metadata } : {}),\n };\n}\n\nexport function eventToRow(event: CommerceEvent): {\n id: string;\n type: string;\n request_id: string;\n resource_id: string | null;\n at: string;\n adapter: string | null;\n payment_provider: string | null;\n duration_ms: number | null;\n status: string | null;\n data_json: string | null;\n} {\n return {\n id: event.id,\n type: event.type,\n request_id: event.requestId,\n resource_id: event.resourceId !== undefined ? event.resourceId : null,\n at: event.at,\n adapter: event.adapter !== undefined ? event.adapter : null,\n payment_provider: event.paymentProvider !== undefined ? event.paymentProvider : null,\n duration_ms: event.durationMs !== undefined ? event.durationMs : null,\n status: event.status !== undefined ? event.status : null,\n data_json: event.data !== undefined ? JSON.stringify(redact(event.data)) : null,\n };\n}\n\nexport function rowToEvent(row: EventRow): CommerceEvent {\n const data =\n row.data_json !== null ? (JSON.parse(row.data_json) as Record<string, unknown>) : undefined;\n return {\n id: row.id,\n type: row.type as CommerceEventType,\n requestId: row.request_id,\n at: row.at,\n ...(row.resource_id !== null ? { resourceId: row.resource_id } : {}),\n ...(row.adapter !== null ? { adapter: row.adapter } : {}),\n ...(row.payment_provider !== null ? { paymentProvider: row.payment_provider } : {}),\n ...(row.duration_ms !== null ? { durationMs: row.duration_ms } : {}),\n ...(row.status !== null ? { status: row.status as 'ok' | 'error' } : {}),\n ...(data !== undefined ? { data } : {}),\n };\n}\n\nexport function rowToPaymentAttempt(row: PaymentAttemptRow): PaymentAttempt {\n return {\n id: row.id,\n requestId: row.request_id,\n resourceId: row.resource_id,\n provider: row.provider,\n replayKey: row.replay_key,\n status: row.status as PaymentAttempt['status'],\n amount: row.amount,\n currency: row.currency,\n ...(row.payer !== null ? { payer: row.payer } : {}),\n ...(row.payee !== null ? { payee: row.payee } : {}),\n ...(row.external_reference !== null ? { externalReference: row.external_reference } : {}),\n ...(row.rejection_reason !== null ? { rejectionReason: row.rejection_reason } : {}),\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n}\n","/**\n * Explicit migration scheme for the receipt-store SQLite schema.\n *\n * Uses SQLite's built-in `PRAGMA user_version` as the migration marker so a\n * restart against an existing database file re-opens without re-creating or\n * losing data (required negative test: \"gateway restart with receipt storage\n * preserved\").\n */\nimport type Database from 'better-sqlite3';\n\ninterface Migration {\n readonly version: number;\n up(db: Database.Database): void;\n}\n\nconst MIGRATIONS: readonly Migration[] = [\n {\n version: 1,\n up(db) {\n db.exec(`\n CREATE TABLE IF NOT EXISTS receipts (\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n id TEXT NOT NULL UNIQUE,\n request_id TEXT NOT NULL,\n resource_id TEXT NOT NULL,\n payment_json TEXT,\n delivered_at TEXT NOT NULL,\n backend_status INTEGER NOT NULL,\n duration_ms INTEGER,\n protocol TEXT,\n metadata_json TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_receipts_request_id ON receipts(request_id);\n CREATE INDEX IF NOT EXISTS idx_receipts_delivered_at ON receipts(delivered_at);\n\n CREATE TABLE IF NOT EXISTS events (\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n id TEXT NOT NULL UNIQUE,\n type TEXT NOT NULL,\n request_id TEXT NOT NULL,\n resource_id TEXT,\n at TEXT NOT NULL,\n adapter TEXT,\n payment_provider TEXT,\n duration_ms INTEGER,\n status TEXT,\n data_json TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_events_request_id ON events(request_id);\n CREATE INDEX IF NOT EXISTS idx_events_at ON events(at);\n\n CREATE TABLE IF NOT EXISTS payment_attempts (\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n id TEXT NOT NULL UNIQUE,\n request_id TEXT NOT NULL,\n resource_id TEXT NOT NULL,\n provider TEXT NOT NULL,\n replay_key TEXT NOT NULL UNIQUE,\n status TEXT NOT NULL,\n amount TEXT NOT NULL,\n currency TEXT NOT NULL,\n payer TEXT,\n payee TEXT,\n external_reference TEXT,\n rejection_reason TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_payment_attempts_request_id ON payment_attempts(request_id);\n CREATE INDEX IF NOT EXISTS idx_payment_attempts_created_at ON payment_attempts(created_at);\n `);\n },\n },\n];\n\n/** Current target schema version — the version of the last migration. */\nexport const SCHEMA_VERSION = MIGRATIONS[MIGRATIONS.length - 1]?.version ?? 0;\n\n/**\n * Bring `db` up to {@link SCHEMA_VERSION}. Idempotent: re-opening an existing,\n * already-migrated file is a fast no-op check against `PRAGMA user_version`.\n */\nexport function migrate(db: Database.Database): void {\n const current = db.pragma('user_version', { simple: true }) as number;\n for (const migration of MIGRATIONS) {\n if (migration.version <= current) continue;\n const apply = db.transaction(() => {\n migration.up(db);\n db.pragma(`user_version = ${migration.version}`);\n });\n apply();\n }\n}\n","/**\n * SQLite implementation of the frozen ReceiptStore interface.\n *\n * Thin repository layer — no ORM. Every write goes through a prepared\n * statement; the only thing that varies between calls is parameters.\n */\nimport { randomUUID } from 'node:crypto';\nimport {\n accessSync,\n chmodSync,\n closeSync,\n existsSync,\n constants as fsConstants,\n mkdirSync,\n openSync,\n} from 'node:fs';\nimport { dirname } from 'node:path';\nimport Database from 'better-sqlite3';\nimport {\n type AdapterDescriptor,\n type AdapterHealth,\n type Clock,\n CommerceError,\n type CommerceEvent,\n type CommerceReceipt,\n type IdGenerator,\n type ListOptions,\n type Logger,\n NOOP_LOGGER,\n type PaymentAttempt,\n type PaymentAttemptReservation,\n type PaymentAttemptUpdate,\n type ReceiptStore,\n systemClock,\n toCommerceError,\n} from '../../core/index.js';\nimport { PACKAGE_VERSION } from '../../version.js';\nimport {\n type EventRow,\n eventToRow,\n type PaymentAttemptRow,\n type ReceiptRow,\n receiptToRow,\n rowToEvent,\n rowToPaymentAttempt,\n rowToReceipt,\n} from './rows.js';\nimport { migrate, SCHEMA_VERSION } from './schema.js';\n\nconst DEFAULT_LIST_LIMIT = 50;\n/**\n * Hard ceiling on every list query, applied here rather than only at the\n * gateway route, so every caller (HTTP, CLI, a future adapter) is covered.\n * SQLite treats a negative `LIMIT` as \"no limit\" —\n * confirmed `{ limit: -1 }` returns the entire table.\n */\nconst MAX_LIST_LIMIT = 500;\n\n/**\n * Clamps to a whole number in [1, MAX_LIST_LIMIT], defaulting when absent OR\n * non-finite (NaN/Infinity) — a store-level invariant that must hold\n * regardless of whether the current caller already filters those out.\n */\nfunction clampListLimit(limit: number | undefined): number {\n const base = limit !== undefined && Number.isFinite(limit) ? limit : DEFAULT_LIST_LIMIT;\n return Math.min(Math.max(Math.trunc(base), 1), MAX_LIST_LIMIT);\n}\n\nexport interface SqliteReceiptStoreOptions {\n /** File path, or ':memory:' for tests. Parent directory is created if missing. */\n readonly path: string;\n readonly logger?: Logger;\n readonly clock?: Clock;\n readonly ids?: IdGenerator;\n}\n\nconst defaultIds: IdGenerator = {\n next: (prefix) => (prefix !== undefined ? `${prefix}_${randomUUID()}` : randomUUID()),\n};\n\nfunction isUniqueConstraintOn(err: unknown, column: string): boolean {\n return (\n err instanceof Error &&\n 'code' in err &&\n (err as { code?: unknown }).code === 'SQLITE_CONSTRAINT_UNIQUE' &&\n err.message.includes(column)\n );\n}\n\n/**\n * Narrow the database and its WAL sidecars to owner-only.\n *\n * `new Database(path)` opens with `0666 & ~umask`, so on a\n * standard host the `.sqlite`, `-wal` and `-shm` files landed at 0644 — any\n * other local user could read the whole commerce ledger: payer and payee\n * addresses, amounts, settlement transaction hashes, replay keys and the\n * entire event stream. No key material (the gateway is non-custodial and\n * `redact.ts` is recursive), but business metadata all the same.\n *\n * Called *after* `journal_mode = WAL`, because the sidecars do not exist until\n * then. Belt-and-braces since the main file is now pre-created at 0600 (see\n * `createSqliteReceiptStore`): this still tightens a database that already\n * existed with a looser mode. Best-effort by design: a filesystem without\n * POSIX modes must not stop the gateway from starting, so a failure warns\n * rather than throws.\n */\nfunction restrictDatabasePermissions(path: string, logger: Logger): void {\n for (const file of [path, `${path}-wal`, `${path}-shm`]) {\n try {\n chmodSync(file, 0o600);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === 'ENOENT') continue;\n logger.warn(\n { file, error: code ?? 'unknown' },\n 'could not restrict receipt database permissions to owner-only',\n );\n }\n }\n}\n\nexport function createSqliteReceiptStore(options: SqliteReceiptStoreOptions): ReceiptStore {\n const logger = options.logger ?? NOOP_LOGGER;\n const clock = options.clock ?? systemClock;\n const ids = options.ids ?? defaultIds;\n const path = options.path;\n const isFileBacked = path !== ':memory:';\n\n if (isFileBacked) {\n const dir = dirname(path);\n if (dir !== '' && dir !== '.' && !existsSync(dir)) {\n // 0700 on directories we create ourselves. An existing directory is the\n // operator's to own and is deliberately left alone.\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n }\n }\n\n // Fail at startup, not on the first payment. `new Database(path)`\n // happily opens a file the process cannot write, and SQLite only says\n // \"attempt to write a readonly database\" once a write is attempted — which\n // on a paid resource is *after* the payment attempt reservation, surfacing\n // as an opaque STORAGE_ERROR per request. Readiness does catch it (503), but\n // the operator is left guessing. This is not hypothetical: switching the\n // demo containers to a non-root user left an existing named volume\n // root-owned, and that is exactly how it presented.\n if (isFileBacked && existsSync(path)) {\n try {\n accessSync(path, fsConstants.W_OK);\n } catch {\n throw new CommerceError(\n 'STORAGE_ERROR',\n `Receipt database \"${path}\" exists but is not writable by this process (uid ${typeof process.getuid === 'function' ? process.getuid() : 'unknown'}). If this is a container that recently changed user, an existing volume may still be owned by the previous one — recreate it (docker compose down -v) or fix its ownership.`,\n { details: { path } },\n );\n }\n }\n\n // Create the file ourselves, at 0600, *before* SQLite can create it at\n // `0666 & ~umask`. The chmod below only narrows the mode after the fact: a\n // local co-tenant who opens the file inside that window keeps a readable\n // descriptor across the chmod and reads every receipt written afterwards.\n // SQLite copies the main file's mode onto the -wal/-shm sidecars, so this\n // one call covers all three. `mode` applies on creation only, so an\n // existing file is untouched here and left to the chmod.\n if (isFileBacked) {\n try {\n closeSync(openSync(path, 'a', 0o600));\n } catch {\n // Deliberately silent: whatever stopped us (unwritable directory,\n // exotic filesystem) is about to be reported by `new Database` with a\n // better message, or is harmless and covered by the chmod below.\n }\n }\n\n const db = new Database(path);\n db.pragma('journal_mode = WAL');\n db.pragma('foreign_keys = ON');\n migrate(db);\n if (isFileBacked) restrictDatabasePermissions(path, logger);\n\n const insertReceiptStmt = db.prepare(\n `INSERT INTO receipts (id, request_id, resource_id, payment_json, delivered_at, backend_status, duration_ms, protocol, metadata_json)\n VALUES (@id, @request_id, @resource_id, @payment_json, @delivered_at, @backend_status, @duration_ms, @protocol, @metadata_json)`,\n );\n const getReceiptStmt = db.prepare<[string], ReceiptRow>('SELECT * FROM receipts WHERE id = ?');\n const listReceiptsStmt = db.prepare<[number], ReceiptRow>(\n 'SELECT * FROM receipts ORDER BY delivered_at DESC, seq DESC LIMIT ?',\n );\n const listReceiptsByRequestStmt = db.prepare<[string, number], ReceiptRow>(\n 'SELECT * FROM receipts WHERE request_id = ? ORDER BY delivered_at DESC, seq DESC LIMIT ?',\n );\n const countReceiptsStmt = db.prepare<[], { count: number }>(\n 'SELECT COUNT(*) AS count FROM receipts',\n );\n // backend_status is INTEGER NOT NULL (schema.ts) so NOT BETWEEN never has\n // a NULL row to silently miss; 0 (backend never responded at all) and\n // every non-2xx status both count as undelivered, matching the dashboard's\n // deliveryResult() (ReceiptList.tsx) — the two views must not disagree\n // about what \"delivered\" means, which is the confusion.\n const countUndeliveredReceiptsStmt = db.prepare<[], { count: number }>(\n 'SELECT COUNT(*) AS count FROM receipts WHERE backend_status NOT BETWEEN 200 AND 299',\n );\n\n const insertEventStmt = db.prepare(\n `INSERT INTO events (id, type, request_id, resource_id, at, adapter, payment_provider, duration_ms, status, data_json)\n VALUES (@id, @type, @request_id, @resource_id, @at, @adapter, @payment_provider, @duration_ms, @status, @data_json)`,\n );\n const listEventsStmt = db.prepare<[number], EventRow>(\n 'SELECT * FROM events ORDER BY at DESC, seq DESC LIMIT ?',\n );\n const listEventsByRequestStmt = db.prepare<[string, number], EventRow>(\n 'SELECT * FROM events WHERE request_id = ? ORDER BY at DESC, seq DESC LIMIT ?',\n );\n\n const insertPaymentAttemptStmt = db.prepare(\n `INSERT INTO payment_attempts (id, request_id, resource_id, provider, replay_key, status, amount, currency, payer, payee, external_reference, rejection_reason, created_at, updated_at)\n VALUES (@id, @request_id, @resource_id, @provider, @replay_key, @status, @amount, @currency, @payer, @payee, @external_reference, @rejection_reason, @created_at, @updated_at)`,\n );\n const getPaymentAttemptByIdStmt = db.prepare<[string], PaymentAttemptRow>(\n 'SELECT * FROM payment_attempts WHERE id = ?',\n );\n // COALESCE: an omitted field (bound as NULL — see updatePaymentAttempt)\n // means \"leave the existing value alone\", not \"clear it\". Without this, a\n // second update that doesn't re-supply external_reference/rejection_reason\n // erases it — exactly the field that carries the on-chain tx hash for a\n // settlement-uncertain attempt, the one record proving the buyer's funds\n // may have moved. There is no current caller that needs to clear an\n // already-set value; if one appears, it needs an explicit sentinel rather\n // than overloading `undefined` to mean two different things again.\n const updatePaymentAttemptStmt = db.prepare(\n `UPDATE payment_attempts SET status = @status,\n external_reference = COALESCE(@external_reference, external_reference),\n rejection_reason = COALESCE(@rejection_reason, rejection_reason),\n updated_at = @updated_at\n WHERE replay_key = @replay_key`,\n );\n const listPaymentAttemptsStmt = db.prepare<[number], PaymentAttemptRow>(\n 'SELECT * FROM payment_attempts ORDER BY created_at DESC, seq DESC LIMIT ?',\n );\n const listPaymentAttemptsByRequestStmt = db.prepare<[string, number], PaymentAttemptRow>(\n 'SELECT * FROM payment_attempts WHERE request_id = ? ORDER BY created_at DESC, seq DESC LIMIT ?',\n );\n\n let closed = false;\n\n const descriptor: AdapterDescriptor = {\n name: 'sqlite-receipt-store',\n kind: 'storage',\n implementationVersion: PACKAGE_VERSION,\n supportedSpec: `sqlite-schema-v${SCHEMA_VERSION}`,\n capabilities: ['receipts', 'events', 'payment-attempts'],\n status: 'stable',\n };\n\n const store: ReceiptStore = {\n async init(): Promise<void> {\n // Schema setup already happened synchronously above (better-sqlite3 is\n // sync). This re-check makes init() a meaningful, idempotent gate for\n // callers that treat it as the lifecycle hook that must succeed before\n // any other method is used.\n const version = db.pragma('user_version', { simple: true }) as number;\n if (version !== SCHEMA_VERSION) {\n throw new CommerceError(\n 'STORAGE_ERROR',\n `Receipt store schema version mismatch (found ${version}, expected ${SCHEMA_VERSION})`,\n );\n }\n },\n\n async appendEvent(event: CommerceEvent): Promise<void> {\n try {\n insertEventStmt.run(eventToRow(event));\n } catch (err) {\n logger.warn(\n {\n err: err instanceof Error ? err.message : String(err),\n eventId: event.id,\n requestId: event.requestId,\n },\n 'receipt-store: failed to persist commerce event',\n );\n }\n },\n\n async reservePaymentAttempt(reservation: PaymentAttemptReservation): Promise<PaymentAttempt> {\n const now = clock.nowIso();\n const id = ids.next('attempt');\n try {\n insertPaymentAttemptStmt.run({\n id,\n request_id: reservation.requestId,\n resource_id: reservation.resourceId,\n provider: reservation.provider,\n replay_key: reservation.replayKey,\n status: 'reserved' satisfies PaymentAttempt['status'],\n amount: reservation.amount,\n currency: reservation.currency,\n payer: reservation.payer ?? null,\n payee: reservation.payee ?? null,\n external_reference: null,\n rejection_reason: null,\n created_at: now,\n updated_at: now,\n });\n } catch (err) {\n if (isUniqueConstraintOn(err, 'payment_attempts.replay_key')) {\n throw new CommerceError(\n 'PAYMENT_REPLAYED',\n `Payment authorisation has already been used (replayKey=${reservation.replayKey})`,\n { requestId: reservation.requestId, resourceId: reservation.resourceId },\n );\n }\n throw toCommerceError(err, 'STORAGE_ERROR', 'Failed to reserve payment attempt');\n }\n const row = getPaymentAttemptByIdStmt.get(id);\n if (row === undefined) {\n throw new CommerceError(\n 'STORAGE_ERROR',\n 'Payment attempt vanished immediately after insert',\n );\n }\n return rowToPaymentAttempt(row);\n },\n\n async updatePaymentAttempt(update: PaymentAttemptUpdate): Promise<void> {\n try {\n const result = updatePaymentAttemptStmt.run({\n replay_key: update.replayKey,\n status: update.status,\n external_reference: update.externalReference ?? null,\n rejection_reason: update.rejectionReason ?? null,\n updated_at: clock.nowIso(),\n });\n if (result.changes === 0) {\n throw new CommerceError(\n 'STORAGE_ERROR',\n `No payment attempt found for replayKey=${update.replayKey}`,\n );\n }\n } catch (err) {\n throw toCommerceError(err, 'STORAGE_ERROR', 'Failed to update payment attempt');\n }\n },\n\n async saveReceipt(receipt: CommerceReceipt): Promise<void> {\n try {\n insertReceiptStmt.run(receiptToRow(receipt));\n } catch (err) {\n throw toCommerceError(err, 'STORAGE_ERROR', 'Failed to save receipt');\n }\n },\n\n async getReceipt(id: string): Promise<CommerceReceipt | undefined> {\n const row = getReceiptStmt.get(id);\n return row !== undefined ? rowToReceipt(row) : undefined;\n },\n\n async listReceipts(listOptions: ListOptions = {}): Promise<readonly CommerceReceipt[]> {\n const limit = clampListLimit(listOptions.limit);\n const rows =\n listOptions.requestId !== undefined\n ? listReceiptsByRequestStmt.all(listOptions.requestId, limit)\n : listReceiptsStmt.all(limit);\n return rows.map(rowToReceipt);\n },\n\n /** Exact total, ignoring the listReceipts clamp — see the interface doc for why this exists. */\n async countReceipts(): Promise<number> {\n return countReceiptsStmt.get()?.count ?? 0;\n },\n\n /** Exact count of non-2xx receipts — see the interface doc for why this exists. */\n async countUndeliveredReceipts(): Promise<number> {\n return countUndeliveredReceiptsStmt.get()?.count ?? 0;\n },\n\n async listEvents(listOptions: ListOptions = {}): Promise<readonly CommerceEvent[]> {\n const limit = clampListLimit(listOptions.limit);\n const rows =\n listOptions.requestId !== undefined\n ? listEventsByRequestStmt.all(listOptions.requestId, limit)\n : listEventsStmt.all(limit);\n return rows.map(rowToEvent);\n },\n\n async listPaymentAttempts(listOptions: ListOptions = {}): Promise<readonly PaymentAttempt[]> {\n const limit = clampListLimit(listOptions.limit);\n const rows =\n listOptions.requestId !== undefined\n ? listPaymentAttemptsByRequestStmt.all(listOptions.requestId, limit)\n : listPaymentAttemptsStmt.all(limit);\n return rows.map(rowToPaymentAttempt);\n },\n\n descriptor,\n\n async health(): Promise<AdapterHealth> {\n // Same discipline: a client-visible field is authored from a\n // fixed vocabulary, never inherited from a caught error's `.message`.\n // `accessSync` on a real deployment throws e.g.\n // \"EACCES: permission denied, access '/workspace/data/receipts.sqlite'\"\n // — an absolute host path that must never reach the unauthenticated\n // `/ready` response). The raw message still goes\n // to the injected logger, so nothing is lost for diagnosis.\n const startedAt = clock.monotonicMs();\n if (closed) {\n return { status: 'fail', detail: 'store-unavailable', checkedAt: clock.nowIso() };\n }\n if (isFileBacked) {\n try {\n accessSync(path, fsConstants.W_OK);\n } catch (err) {\n logger.warn(\n { err: err instanceof Error ? err.message : String(err) },\n 'receipt-store: health check failed (store not writable)',\n );\n return {\n status: 'fail',\n detail: 'store-unwritable',\n checkedAt: clock.nowIso(),\n durationMs: clock.monotonicMs() - startedAt,\n };\n }\n }\n try {\n const version = db.pragma('user_version', { simple: true }) as number;\n if (version !== SCHEMA_VERSION) {\n logger.warn(\n { found: version, expected: SCHEMA_VERSION },\n 'receipt-store: health check failed (schema version mismatch)',\n );\n return {\n status: 'fail',\n detail: 'store-schema-mismatch',\n checkedAt: clock.nowIso(),\n durationMs: clock.monotonicMs() - startedAt,\n };\n }\n return {\n status: 'pass',\n detail: `sqlite schema v${SCHEMA_VERSION} writable`,\n checkedAt: clock.nowIso(),\n durationMs: clock.monotonicMs() - startedAt,\n };\n } catch (err) {\n logger.warn(\n { err: err instanceof Error ? err.message : String(err) },\n 'receipt-store: health check failed (store unavailable)',\n );\n return {\n status: 'fail',\n detail: 'store-unavailable',\n checkedAt: clock.nowIso(),\n durationMs: clock.monotonicMs() - startedAt,\n };\n }\n },\n\n async close(): Promise<void> {\n if (!closed) {\n closed = true;\n db.close();\n }\n },\n };\n\n return store;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/config/env.ts","../src/config/filename.ts","../src/core/execution/backend-http.ts","../src/core/execution/event-bus.ts","../src/core/execution/validation.ts","../src/core/execution/pipeline.ts","../src/core/execution/registry.ts","../src/protocols/acp/constants.ts","../src/config/schema.ts","../src/config/load.ts","../src/gateway/ids.ts","../src/gateway/logger.ts","../src/gateway/access-control.ts","../src/gateway/adapters.ts","../src/gateway/public-resource.ts","../src/gateway/readiness.ts","../src/gateway/well-known.ts","../src/gateway/routes.ts","../src/gateway/server.ts","../src/protocols/acp/checkout-mapping.ts","../src/protocols/acp/descriptor.ts","../src/protocols/acp/discovery.ts","../src/protocols/acp/errors.ts","../src/protocols/acp/idempotency/fingerprint.ts","../src/storage/sqlite.ts","../src/protocols/acp/idempotency/store.ts","../src/protocols/acp/auth.ts","../src/protocols/acp/router.ts","../src/protocols/acp/spec/2026-04-17/schema.agentic_checkout.json","../src/protocols/acp/validation.ts","../src/protocols/acp/request-guards.ts","../src/protocols/acp/response-mapping.ts","../src/protocols/acp/adapter.ts","../src/storage/receipts/redact.ts","../src/storage/receipts/rows.ts","../src/storage/receipts/schema.ts","../src/storage/receipts/store.ts"],"names":["path","isPlainObject","durationMs","url","validators","describeError","fs","parseYaml","header","createHash","fsConstants","timingSafeEqual","sha256","migrate","randomUUID","accessSync"],"mappings":";;;;;;;;;;;;;;;;;AAoCA,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;AACxB,IAAA,OAAO,KAAA,CAAM,GAAA,CAAI,CAAC,KAAA,EAAO,KAAA,KAAU,aAAA,CAAc,KAAA,EAAO,GAAA,EAAK,CAAA,EAAGA,KAAI,CAAA,CAAA,EAAI,KAAK,GAAG,CAAC,CAAA;AAAA,EACnF;AACA,EAAA,IAAI,aAAA,CAAc,KAAK,CAAA,EAAG;AACxB,IAAA,MAAM,SAAkC,EAAC;AACzC,IAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,KAAK,CAAA,EAAG;AAChD,MAAA,MAAA,CAAO,GAAG,IAAI,aAAA,CAAc,KAAA,EAAO,KAAK,CAAA,EAAGA,KAAI,CAAA,CAAA,EAAI,GAAG,CAAA,CAAE,CAAA;AAAA,IAC1D;AACA,IAAA,OAAO,MAAA;AAAA,EACT;AACA,EAAA,OAAO,KAAA;AACT;AAEA,SAAS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AAC,MAAA,EAAQ;AACX,QAAA,MAAA,GAAS,IAAA;AACT,QAAA,EAAA,CAAG,KAAA,EAAM;AAAA,MACX;AAAA,IACF;AAAA,GACF;AAEA,EAAA,OAAO,KAAA;AACT","file":"index.js","sourcesContent":["/**\n * `${VAR}` / `${VAR:-default}` substitution over an arbitrary parsed-YAML value.\n *\n * Only string leaves are touched; numbers/booleans/null pass through untouched\n * (the caller coerces the *resulting* string back into a number/boolean where\n * the schema expects one). An unresolved placeholder fails config loading\n * immediately — startup must never proceed with an unresolved secret. That\n * includes one left behind by a *nested* placeholder such as `${A:-${B}}`,\n * which is rejected rather than silently passed through. There is no\n * escape syntax for a literal `${NAME}`; nothing in this config format needs\n * one, and adding it would mean two ways to write every value.\n *\n * `${VAR}` (no default) requires `VAR` to be present in `env` (any value,\n * including an empty string, counts as present).\n * `${VAR:-default}` falls back to `default` when `VAR` is absent OR empty,\n * matching common shell semantics.\n *\n * Anything else brace-shaped is refused: `${VAR-x}`, `${VAR:=x}`, `${VAR:?x}`\n * are valid *shell* and would otherwise load as literal strings. That is\n * harmless where a downstream check rejects the literal, and quietly wrong for\n * a free-string field — `adminToken: ${ADMIN_TOKEN-fallback}` would run the\n * gateway with that literal as the ledger credential while the operator\n * believed an env secret gated it. A bare `$VAR` is deliberately left alone: it\n * is not brace-shaped, and refusing it would reject values that legitimately\n * contain a dollar sign.\n *\n * Every rule above is decided from the **template**, before substitution.\n * Deciding afterwards is how `${A:-${B}}` used to corrupt a value on the one\n * branch its guard did not cover, and how a resolved secret containing a\n * `${…}`-shaped fragment used to get quoted back in the error text.\n *\n * The resolved *value* of a variable is never included in any error message —\n * only the variable *name* and the config path are.\n */\nimport { CommerceError } from '../core/index.js';\n\nconst PLACEHOLDER_PATTERN = /\\$\\{([A-Za-z_][A-Za-z0-9_]*)(:-([^}]*))?\\}/g;\n\n/** An innermost brace token: `${` … `}` with no braces between. */\nconst BRACE_TOKEN = /\\$\\{[^{}]*\\}/g;\n\n/** The same grammar as PLACEHOLDER_PATTERN, 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 (isPlainObject(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 honour, before any substitution runs.\n *\n * `${A:-${B}}` is the case that motivated this. `[^}]*` cannot span the inner\n * `}`, so the match consumes `${A:-${B` and leaves a stray `}` behind. When `A`\n * is unset the leftover `${B}` was visible afterwards and got caught; when `A`\n * is *set* — the normal case, and the whole reason someone writes a default —\n * substitution succeeded and the stray `}` was appended to the resolved value\n * with nothing to notice it. For `adminToken` that means the gateway compares\n * against a credential the operator does not hold, with no diagnostic.\n *\n * Deciding from the template covers both branches with one rule, and means no\n * error message is ever derived from a resolved value.\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 BRACE_TOKEN.lastIndex = 0;\n for (const [token] of value.matchAll(BRACE_TOKEN)) {\n if (SUPPORTED_TOKEN.test(token)) continue;\n // The token itself, never the surrounding value: this runs pre-substitution,\n // so it cannot contain a resolved 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 recognised; 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\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n","/**\n * The default configuration filename, in one place.\n *\n * Deliberately its own module with **no imports**: `src/cli` reaches the rest\n * of `src/config` only through a dynamic import (see\n * `src/cli/lib/config-client.ts`), so that a broken config module cannot take\n * down commands that never read configuration. A leaf file holding a single\n * string has no module graph to break, so the CLI can import it directly\n * without reopening that seam — and `init`'s default output path, `--config`'s\n * help text and the loader's own lookup cannot drift apart, which is what\n * three separate copies of this string invited.\n */\nexport const DEFAULT_CONFIG_FILENAME = 'config.yaml';\n","/**\n * The only outbound HTTP path to a merchant backend.\n *\n * - Uses global `fetch` and always applies a bound timeout via `AbortSignal.timeout`.\n * - `redirect: 'manual'` - a 3xx response is treated as a `BACKEND_ERROR`, never\n * followed (SSRF hardening).\n * - `{param}` segments in `handler.url` are filled from validated input and\n * URL-encoded; whatever remains goes to the query string (GET/DELETE) or a\n * JSON body (POST/PUT/PATCH). `handler.inputBindings` replaces that\n * leftover rule with one that names each group explicitly - see\n * `buildBackendRequestParts`.\n */\nimport {\n type BackendHandler,\n type BackendMethod,\n DEFAULT_BACKEND_TIMEOUT_MS,\n} from '../domain/resource.js';\nimport { CommerceError } from '../errors/index.js';\nimport type { BackendExecutor, BackendRequest, BackendResponse } from '../interfaces/backend.js';\nimport { type Logger, NOOP_LOGGER } from '../interfaces/logger.js';\n\nconst MAX_BODY_SNIPPET_LENGTH = 512;\n/**\n * The one canonical `{param}` grammar. Extraction, substitution, the config\n * gate and `doctor`'s probe all go through it.\n *\n * `-` and `.` are admitted: `/report/{report-id}` is ordinary\n * REST, and under the previous `[a-zA-Z0-9_]+` class it matched *nothing*. It\n * was therefore invisible to the config gate, survived substitution as a\n * literal, and a paid resource settled the buyer's payment before sending\n * `/report/%7Breport-id%7D` to a backend that 404s - the earlier money bug,\n * reachable again through the character class rather than through the check.\n */\nconst PATH_PARAM_PATTERN = /\\{([a-zA-Z0-9_.-]+)\\}/g;\n/** A hostile or broken backend can otherwise materialise an arbitrarily\n * large response in memory - AbortSignal.timeout bounds it by *time*, not\n * bytes. 1 MB is generous for a JSON API response. */\nconst MAX_RESPONSE_BODY_BYTES = 1024 * 1024;\n\nexport interface HttpBackendExecutorOptions {\n /** Override for `fetch`, used in tests. Defaults to the global implementation. */\n readonly fetchImpl?: typeof fetch;\n /** A non-2xx backend body is logged here (debug), never shipped to the client. */\n readonly logger?: Logger;\n}\n\nexport class HttpBackendExecutor implements BackendExecutor {\n private readonly fetchImpl: typeof fetch;\n private readonly logger: Logger;\n\n constructor(options: HttpBackendExecutorOptions = {}) {\n this.fetchImpl = options.fetchImpl ?? fetch;\n this.logger = options.logger ?? NOOP_LOGGER;\n }\n\n async call(handler: BackendHandler, request: BackendRequest): Promise<BackendResponse> {\n const timeoutMs = handler.timeoutMs ?? DEFAULT_BACKEND_TIMEOUT_MS;\n const inputRecord = isPlainObject(request.input) ? request.input : {};\n\n const context = { requestId: request.requestId, resourceId: request.resourceId };\n // Throws INPUT_INVALID for every shape problem. The pipeline already ran\n // the same call pre-payment through validateBackendRequestShape(); this is\n // defence in depth for a caller that bypasses it, not the normal path.\n const parts = buildBackendRequestParts(handler, inputRecord, context);\n\n let target: URL;\n try {\n target = new URL(parts.url);\n } catch (error) {\n throw new CommerceError('BACKEND_ERROR', 'Backend URL could not be constructed from input', {\n ...context,\n details: { reason: 'invalid-url' },\n cause: error,\n });\n }\n\n // Belt-and-braces beyond the per-parameter check above: whatever the\n // templated path resolved to must still live under the template's own\n // literal (pre-`{param}`) prefix. Templating something other than a path\n // segment (e.g. the host) is not a documented usage; if the literal\n // prefix does not even parse as a URL, skip this extra check rather than\n // fail a request the per-parameter check already covers.\n const literalPrefix = handler.url.split('{')[0] ?? handler.url;\n try {\n const literalPrefixPathname = new URL(literalPrefix).pathname;\n if (!target.pathname.startsWith(literalPrefixPathname)) {\n throw new CommerceError(\n 'INPUT_INVALID',\n 'Path parameters resolved outside the configured backend path',\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n },\n );\n }\n } catch (error) {\n if (error instanceof CommerceError) throw error;\n }\n\n const headers: Record<string, string> = { ...(handler.headers ?? {}) };\n let body: string | undefined;\n\n //.set() REPLACES an existing param, so without this check a caller\n // input key with the same name as an operator-baked-in query param\n // (?apikey=SECRET in handler.url) silently overwrites it.\n // Shared with validateBackendRequestShape() - that copy runs\n // *before* payment, this one is defence in depth.\n checkQueryCollision(target, parts.query, context);\n for (const [key, value] of Object.entries(parts.query)) {\n target.searchParams.set(key, stringifyPrimitive(value));\n }\n if (parts.body !== undefined) {\n body = JSON.stringify(parts.body.value);\n // A configured Content-Type stays authoritative: a backend wanting\n // `application/vnd.x+json` says so in config and we do not override it.\n if (!hasHeader(headers, 'content-type')) {\n headers['content-type'] = 'application/json';\n }\n }\n\n const started = performance.now();\n let response: Response;\n try {\n response = await this.fetchImpl(target, {\n method: handler.method,\n headers,\n ...(body !== undefined ? { body } : {}),\n redirect: 'manual',\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (error) {\n const durationMs = Math.round(performance.now() - started);\n if (isAbortError(error)) {\n throw new CommerceError(\n 'BACKEND_TIMEOUT',\n `Backend request timed out after ${timeoutMs}ms`,\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: { timeoutMs, durationMs },\n cause: error,\n },\n );\n }\n throw new CommerceError('BACKEND_ERROR', 'Backend request failed (transport error)', {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: { durationMs },\n cause: error,\n });\n }\n const durationMs = Math.round(performance.now() - started);\n\n const isRedirect =\n response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400);\n if (isRedirect) {\n throw new CommerceError(\n 'BACKEND_ERROR',\n 'Backend responded with a redirect, which is not followed',\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: { status: response.status, reason: 'redirect-not-followed' },\n },\n );\n }\n\n const responseHeaders = headersToRecord(response.headers);\n const contentType = response.headers.get('content-type') ?? '';\n let parsedBody: unknown;\n try {\n parsedBody = await parseBody(response, contentType);\n } catch (error) {\n const tooLarge =\n error instanceof Error && error.message.startsWith('response-body-too-large');\n throw new CommerceError(\n 'BACKEND_ERROR',\n tooLarge\n ? 'Backend response exceeded the maximum allowed size'\n : 'Backend response could not be read',\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: tooLarge\n ? { reason: 'response-too-large', maxBytes: MAX_RESPONSE_BODY_BYTES }\n : { reason: 'read-error' },\n cause: error,\n },\n );\n }\n\n if (response.status < 200 || response.status >= 300) {\n // The backend status is ours to state; the backend's own response body\n // is not - a merchant backend in verbose/dev-error mode routinely\n // emits stack traces, hostnames or SQL fragments, and this gateway is\n // not the one who gets to decide those are safe to forward to whoever\n // called the (possibly free, possibly unauthenticated) resource. Log\n // it for the operator; never put it in a client-visible field.\n this.logger.debug(\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n status: response.status,\n bodySnippet: truncateSnippet(parsedBody),\n },\n 'Backend responded with a non-2xx status',\n );\n throw new CommerceError('BACKEND_ERROR', `Backend responded with status ${response.status}`, {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: { status: response.status },\n });\n }\n\n return {\n status: response.status,\n headers: responseHeaders,\n body: parsedBody,\n durationMs,\n };\n }\n}\n\n/**\n * The traversal and query-collision checks below must run before payment,\n * not only inside `call()` - pipeline step 6, which is *after*\n * verify -> reserve -> settle.\n * Both throw INPUT_INVALID, which schema validation (step 2) cannot catch\n * (it validates against `resource.inputSchema`, which knows nothing about\n * the URL template a bad value would collide with). Concretely: a paid,\n * path-templated resource called with `{ city: \"\" }` would settle the buyer's\n * payment on-chain and then never call the backend - payment without\n * delivery, no refund, no release of the reserved authorisation. Both\n * checks are pure functions of `(handler.url, input)` with no I/O, so the\n * pipeline calls this immediately after schema validation, *before* price\n * resolution - before any payment provider is even selected. `call()` keeps\n * its own copy as defence in depth (it is a public class; the pipeline is\n * not the only possible caller).\n */\n/**\n * `{param}` names in a `backend.url` template, in declaration order.\n * Exported so `src/config`'s `normaliseResource` can\n * cross-check every template parameter against the resource's input schema\n * at config load - the same regex, not a second copy that could silently\n * drift out of sync with what this file actually treats as a path\n * parameter.\n */\nexport function extractPathParameterNames(url: string): string[] {\n return [...url.matchAll(PATH_PARAM_PATTERN)].map((match) => match[1] as string);\n}\n\n/**\n * A brace left over after every legal `{param}` is removed, or `undefined`.\n *\n * Widening the grammar fixes the *common* spelling; it cannot fix every one.\n * `{report id}`, `{a/b}`, `{}` and an unbalanced `{` still match nothing, and\n * \"matches nothing\" is precisely the silent-literal shape that costs a buyer\n * money on a paid resource. So the rule is inverted: rather than enumerating\n * what is illegal, anything brace-shaped that is *not* a recognised parameter\n * is refused at config load. Exported so `src/config` applies it - the\n * grammar and its residue must never live in two files.\n */\nexport function findUnparsedBraceToken(url: string): string | undefined {\n const residue = url.replace(PATH_PARAM_PATTERN, '');\n const index = residue.search(/[{}]/);\n if (index === -1) return undefined;\n // Report the offending run, not just the character, so the error is fixable.\n const token = /\\{[^{}]*\\}?|\\}/.exec(residue.slice(index));\n return token?.[0] ?? residue[index];\n}\n\nexport function validateBackendRequestShape(\n handler: BackendHandler,\n input: unknown,\n context: ShapeContext,\n): void {\n const inputRecord = isPlainObject(input) ? input : {};\n\n // Every shape error - missing or invalid path parameter, a bound group that\n // is not an object - throws INPUT_INVALID from here, before payment.\n const parts = buildBackendRequestParts(handler, inputRecord, context);\n\n let target: URL;\n try {\n target = new URL(parts.url);\n } catch {\n return; // call() surfaces the real BACKEND_ERROR for an unparseable URL.\n }\n checkQueryCollision(target, parts.query, context);\n}\n\ntype ShapeContext = { readonly requestId: string; readonly resourceId: string };\n\n/** The path-templated URL plus the query and body values a request carries. */\ninterface BackendRequestParts {\n readonly url: string;\n readonly query: Record<string, unknown>;\n /** Present when a JSON body should be sent; `value` is what gets encoded. */\n readonly body?: { readonly value: unknown };\n}\n\nfunction acceptsBody(method: BackendMethod): boolean {\n return method !== 'GET' && method !== 'DELETE';\n}\n\n/**\n * Split validated input into URL, query and body according to\n * `handler.inputBindings` - the single place either mode is decided, so\n * `call()` and the pre-payment `validateBackendRequestShape()` can never\n * disagree about what request the input describes.\n *\n * Throws only `CommerceError('INPUT_INVALID')`, which is what makes it safe to\n * run before pricing.\n */\nfunction buildBackendRequestParts(\n handler: BackendHandler,\n input: Record<string, unknown>,\n context: ShapeContext,\n): BackendRequestParts {\n const bindings = handler.inputBindings;\n if (bindings === undefined) {\n const { url, remaining } = applyPathTemplate(handler.url, input, context);\n return acceptsBody(handler.method)\n ? { url, query: {}, body: { value: remaining } }\n : { url, query: remaining };\n }\n\n const pathValues =\n bindings.path === undefined ? {} : resolveBoundGroup(input, bindings.path, 'path', context);\n const { url } = applyPathTemplate(handler.url, pathValues, context);\n const query =\n bindings.query === undefined ? {} : resolveBoundGroup(input, bindings.query, 'query', context);\n\n // An absent body value sends no body at all rather than `null`: a request\n // body the operation does not require is simply not there. A body the\n // operation *does* require is caught one step earlier, by `required` in the\n // resource's input schema - also before payment.\n const bodyValue = bindings.body === undefined ? undefined : input[bindings.body];\n if (bodyValue === undefined || !acceptsBody(handler.method)) return { url, query };\n return { url, query, body: { value: bodyValue } };\n}\n\nfunction resolveBoundGroup(\n input: Record<string, unknown>,\n key: string,\n kind: 'path' | 'query',\n context: ShapeContext,\n): Record<string, unknown> {\n const value = input[key];\n if (value === undefined) return {};\n if (!isPlainObject(value)) {\n throw new CommerceError(\n 'INPUT_INVALID',\n `Input \"${key}\" must be an object of ${kind} parameters`,\n { ...context, details: { field: key } },\n );\n }\n return value;\n}\n\nfunction checkQueryCollision(\n target: URL,\n remaining: Record<string, unknown>,\n context: { readonly requestId: string; readonly resourceId: string },\n): void {\n const templateKeys = new Set(target.searchParams.keys());\n for (const key of Object.keys(remaining)) {\n if (templateKeys.has(key)) {\n throw new CommerceError(\n 'INPUT_INVALID',\n `Input key \"${key}\" collides with a query parameter already set on backend.url`,\n { requestId: context.requestId, resourceId: context.resourceId, details: { field: key } },\n );\n }\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n// encodeURIComponent does not escape \".\" - a raw \"..\"/\".\" path-parameter\n// value survives it and new URL() then normalises the segment away, letting\n// a caller step outside the template's own directory (bounded traversal:\n// slashes ARE escaped, so only removing segments, never adding them). Reject\n// these exact values at substitution time instead of shipping them.\nconst TRAVERSAL_PATH_VALUES = new Set(['', '.', '..']);\n\nfunction applyPathTemplate(\n template: string,\n input: Record<string, unknown>,\n context: ShapeContext,\n): { url: string; remaining: Record<string, unknown> } {\n const remaining: Record<string, unknown> = { ...input };\n let missing: string | undefined;\n let invalid: string | undefined;\n const url = template.replace(PATH_PARAM_PATTERN, (_match, key: string) => {\n // Object.hasOwn, not `key in remaining`: `in` also matches inherited\n // Object.prototype names (\"constructor\", \"toString\", …), which a\n // config-authored template naming a path param after one of them would\n // otherwise silently resolve to the wrong (inherited) value.\n if (!Object.hasOwn(remaining, key)) {\n missing = key;\n return '';\n }\n const value = remaining[key];\n delete remaining[key];\n const raw = stringifyPrimitive(value);\n if (TRAVERSAL_PATH_VALUES.has(raw)) {\n invalid = key;\n return '';\n }\n return encodeURIComponent(raw);\n });\n if (missing !== undefined) {\n // Tempting to shrug this off as a config/schema mismatch rather than bad\n // caller input. But a paid, `{param}`-templated resource whose input can\n // never supply it would reach settle() on every call - the buyer pays, the\n // backend is never called, no refund. `normaliseResource` (src/config) is\n // the root-cause fix, rejecting the shape at config load; throwing here\n // stops a hand-built `CommerceResource` from reintroducing the money bug\n // by skipping config validation.\n throw new CommerceError('INPUT_INVALID', `Path parameter \"${missing}\" was not supplied`, {\n ...context,\n details: { field: missing },\n });\n }\n if (invalid !== undefined) {\n throw new CommerceError('INPUT_INVALID', `Path parameter \"${invalid}\" is not a valid value`, {\n ...context,\n details: { field: invalid },\n });\n }\n return { url, remaining };\n}\n\nfunction stringifyPrimitive(value: unknown): string {\n if (value === undefined || value === null) return '';\n if (typeof value === 'string') return value;\n if (typeof value === 'number' || typeof value === 'boolean') return String(value);\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nfunction hasHeader(headers: Record<string, string>, name: string): boolean {\n const target = name.toLowerCase();\n return Object.keys(headers).some((key) => key.toLowerCase() === target);\n}\n\nfunction headersToRecord(headers: Headers): Record<string, string> {\n const record: Record<string, string> = {};\n headers.forEach((value, key) => {\n record[key] = value;\n });\n return record;\n}\n\nasync function readBodyCapped(response: Response, maxBytes: number): Promise<string> {\n if (!response.body) return '';\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel();\n throw new Error(`response-body-too-large:${maxBytes}`);\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n return Buffer.concat(chunks).toString('utf8');\n}\n\nasync function parseBody(response: Response, contentType: string): Promise<unknown> {\n const text = await readBodyCapped(response, MAX_RESPONSE_BODY_BYTES);\n if (text.length === 0) return text;\n if (contentType.includes('json')) {\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n }\n return text;\n}\n\nfunction truncateSnippet(body: unknown): string {\n const text = typeof body === 'string' ? body : safeStringify(body);\n return text.length > MAX_BODY_SNIPPET_LENGTH\n ? `${text.slice(0, MAX_BODY_SNIPPET_LENGTH)}…`\n : text;\n}\n\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\nfunction isAbortError(error: unknown): boolean {\n return error instanceof Error && (error.name === 'TimeoutError' || error.name === 'AbortError');\n}\n","/**\n * Fan-out `EventSink`: persists every event to the receipt store and notifies\n * in-process subscribers (the gateway's SSE feed). Never throws to the caller —\n * a store or subscriber failure is caught and logged.\n */\nimport type { CommerceEvent, EventSink } from '../domain/event.js';\nimport type { Logger } from '../interfaces/logger.js';\nimport type { Clock, IdGenerator } from '../interfaces/runtime.js';\nimport type { ReceiptStore } from '../interfaces/store.js';\n\nexport interface CreateEventBusOptions {\n readonly store: ReceiptStore;\n readonly logger: Logger;\n /** Reserved for callers that want the bus to mint ids/timestamps itself. */\n readonly ids?: IdGenerator;\n readonly clock?: Clock;\n}\n\nexport interface EventBus extends EventSink {\n /** Subscribe to every emitted event. Returns an unsubscribe function. */\n subscribe(fn: (event: CommerceEvent) => void): () => void;\n}\n\nexport function createEventBus(options: CreateEventBusOptions): EventBus {\n const subscribers = new Set<(event: CommerceEvent) => void>();\n\n return {\n async emit(event: CommerceEvent): Promise<void> {\n try {\n await options.store.appendEvent(event);\n } catch (error) {\n options.logger.error(\n { err: describeError(error), eventType: event.type, requestId: event.requestId },\n 'Failed to persist commerce event',\n );\n }\n\n for (const subscriber of subscribers) {\n try {\n subscriber(event);\n } catch (error) {\n options.logger.error(\n { err: describeError(error), eventType: event.type, requestId: event.requestId },\n 'Event subscriber threw',\n );\n }\n }\n },\n\n subscribe(fn: (event: CommerceEvent) => void): () => void {\n subscribers.add(fn);\n return () => {\n subscribers.delete(fn);\n };\n },\n };\n}\n\nfunction describeError(error: unknown): { message: string; name?: string } {\n if (error instanceof Error) {\n return { message: error.message, name: error.name };\n }\n return { message: String(error) };\n}\n","/**\n * A small, honest JSON Schema validator for resource input.\n *\n * Supported subset (draft-2020-12 vocabulary, structural only):\n * - `type`: \"object\" | \"string\" | \"number\" | \"integer\" | \"boolean\" | \"array\" | \"null\",\n * or an array of any of those (draft-2020-12 union form, e.g. `[\"object\",\"null\"]`)\n * - `properties` (object schemas, validated recursively)\n * - `required` (string[])\n * - `additionalProperties` (boolean, or a schema applied to extra properties)\n * - `enum` (array of allowed literal values, deep-equality compared)\n * - `items` (single schema applied to every array element — no tuple form)\n *\n * Explicitly NOT supported and silently ignored (never enforced):\n * `minLength`, `maxLength`, `pattern`, `format`, `minimum`, `maximum`,\n * `exclusiveMinimum/Maximum`, `multipleOf`, `oneOf`, `anyOf`, `allOf`, `not`,\n * `$ref`, `const`, `patternProperties`, `minItems`, `maxItems`, `uniqueItems`,\n * tuple-style `items` arrays. An unrecognised `type` value is not enforced\n * either. This is a deliberate, documented limitation of this release — do\n * not assume any of the above is validated.\n */\nimport type { JsonSchema } from '../domain/common.js';\n\nexport interface FieldError {\n readonly path: string;\n readonly message: string;\n}\n\nexport type ValidationResult =\n | { readonly valid: true; readonly value: unknown }\n | { readonly valid: false; readonly errors: readonly FieldError[] };\n\nexport type Validator = (input: unknown) => ValidationResult;\n\nconst SUPPORTED_TYPES = new Set([\n 'object',\n 'string',\n 'number',\n 'integer',\n 'boolean',\n 'array',\n 'null',\n]);\n\n/** Compile a resource `inputSchema` into a reusable validator function. */\nexport function compileJsonSchema(schema: JsonSchema | undefined): Validator {\n return (input: unknown): ValidationResult => {\n if (schema === undefined) return { valid: true, value: input };\n const errors = validateNode(schema, input, '$');\n return errors.length === 0 ? { valid: true, value: input } : { valid: false, errors };\n };\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction matchesType(type: string, value: unknown): boolean {\n switch (type) {\n case 'object':\n return isPlainObject(value);\n case 'array':\n return Array.isArray(value);\n case 'string':\n return typeof value === 'string';\n case 'boolean':\n return typeof value === 'boolean';\n case 'number':\n return typeof value === 'number' && Number.isFinite(value);\n case 'integer':\n return typeof value === 'number' && Number.isInteger(value);\n case 'null':\n return value === null;\n default:\n return true;\n }\n}\n\nfunction describeType(value: unknown): string {\n if (value === null) return 'null';\n if (Array.isArray(value)) return 'array';\n return typeof value;\n}\n\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (typeof a !== typeof b) return false;\n if (a === null || b === null) return false;\n if (typeof a !== 'object') return false;\n try {\n return JSON.stringify(a) === JSON.stringify(b);\n } catch {\n return false;\n }\n}\n\nfunction own(obj: Record<string, unknown>, key: string): unknown {\n return Object.hasOwn(obj, key) ? obj[key] : undefined;\n}\n\n/**\n * `type` may be a single string or (draft-2020-12) an array of strings,\n * e.g. `[\"object\", \"null\"]`. Only recognised when every entry is a string —\n * same conservative \"skip rather than guess\" rule the single-string form\n * already followed for an unrecognised type name.\n */\nfunction typeList(raw: unknown): string[] | undefined {\n if (typeof raw === 'string') return [raw];\n if (Array.isArray(raw) && raw.every((entry): entry is string => typeof entry === 'string')) {\n return raw;\n }\n return undefined;\n}\n\n/**\n * A bare `type === 'object'` string comparison is not enough: `type:\n * [\"object\", \"null\"]` — valid JSON Schema — would never route into\n * `validateObject`, so neither `required` nor `additionalProperties` would be\n * enforced on it, while `defaultClosedObjectSchema` (src/config) stamps\n * `additionalProperties: false` on it believing it closed. Also treats a node\n * with `properties`/`required` and no `type`\n * at all as an object schema, the same shape config's own stamping already\n * recognises via a bare `properties` check — a schema author relying on\n * `type` being implied by `properties` should not be silently unenforced.\n *\n * **exported**, and now the only definition of \"this node is\n * an object schema\" in the codebase. `src/config`'s `defaultClosedObjectSchema`\n * carried its own — `declaresObjectType || properties` — one keyword short of\n * this one, so a schema declaring only `required` was stamped by neither:\n * config left it open and this validator then enforced nothing on it, quietly\n * forwarding every unknown caller key to the merchant's backend while\n * docs/security.md promised \"closed by default at every level\". These two\n * definitions have been aligned once already; keeping them as two definitions\n * is what let them drift again.\n */\nexport function isObjectSchemaNode(schema: Record<string, unknown>): boolean {\n const types = typeList(schema['type']);\n if (types !== undefined) return types.includes('object');\n return Object.hasOwn(schema, 'properties') || Object.hasOwn(schema, 'required');\n}\n\nfunction validateNode(schema: JsonSchema, value: unknown, path: string): FieldError[] {\n const errors: FieldError[] = [];\n const types = typeList(own(schema, 'type'));\n const recognisedTypes = types?.filter((entry) => SUPPORTED_TYPES.has(entry));\n\n if (\n types !== undefined &&\n recognisedTypes !== undefined &&\n recognisedTypes.length === types.length &&\n types.length > 0\n ) {\n if (!types.some((entry) => matchesType(entry, value))) {\n errors.push({\n path,\n message: `expected type \"${types.join(' | ')}\" but got ${describeType(value)}`,\n });\n return errors;\n }\n }\n\n const enumRaw = own(schema, 'enum');\n if (Array.isArray(enumRaw)) {\n const allowed = enumRaw as unknown[];\n if (!allowed.some((candidate) => deepEqual(candidate, value))) {\n errors.push({ path, message: `must be one of ${JSON.stringify(allowed)}` });\n }\n }\n\n if (isObjectSchemaNode(schema) && isPlainObject(value)) {\n errors.push(...validateObject(schema, value, path));\n } else if ((types?.includes('array') ?? false) && Array.isArray(value)) {\n errors.push(...validateArray(schema, value, path));\n }\n\n return errors;\n}\n\nfunction validateObject(\n schema: JsonSchema,\n value: Record<string, unknown>,\n path: string,\n): FieldError[] {\n const errors: FieldError[] = [];\n const propsRaw = own(schema, 'properties');\n const properties = isPlainObject(propsRaw) ? propsRaw : {};\n const requiredRaw = own(schema, 'required');\n const required = Array.isArray(requiredRaw)\n ? requiredRaw.filter((entry): entry is string => typeof entry === 'string')\n : [];\n\n for (const key of required) {\n // Object.hasOwn, not `in`: `in` walks the prototype chain, so a schema\n // requiring \"toString\"/\"constructor\"/\"valueOf\"/\"hasOwnProperty\"/\n // \"__proto__\" could never actually enforce it — those names are always\n // present via inheritance, so `!(key in value)` is always false. This is\n // the same bug class every other lookup in this file already\n // guards against by using own().\n if (!Object.hasOwn(value, key)) {\n errors.push({ path: `${path}.${key}`, message: 'is required' });\n }\n }\n\n const additional = own(schema, 'additionalProperties');\n\n for (const key of Object.keys(value)) {\n // Object.hasOwn, not `properties[key]`: a plain-object lookup for\n // \"__proto__\"/\"constructor\"/\"toString\"/\"valueOf\"/\"hasOwnProperty\" resolves\n // to an inherited Object.prototype member instead of undefined, so those\n // keys would otherwise silently skip the additionalProperties check below.\n const propSchemaRaw = own(properties, key);\n if (propSchemaRaw !== undefined) {\n if (isPlainObject(propSchemaRaw)) {\n errors.push(...validateNode(propSchemaRaw, value[key], `${path}.${key}`));\n }\n continue;\n }\n if (additional === false) {\n errors.push({ path: `${path}.${key}`, message: 'additional property not allowed' });\n } else if (isPlainObject(additional)) {\n errors.push(...validateNode(additional, value[key], `${path}.${key}`));\n }\n }\n\n return errors;\n}\n\nfunction validateArray(schema: JsonSchema, value: unknown[], path: string): FieldError[] {\n const errors: FieldError[] = [];\n const itemsRaw = own(schema, 'items');\n if (isPlainObject(itemsRaw)) {\n value.forEach((item, index) => {\n errors.push(...validateNode(itemsRaw, item, `${path}[${index}]`));\n });\n }\n return errors;\n}\n","/**\n * The single execution path every protocol adapter converges on.\n *\n * Order is a security boundary — do not reorder:\n * 1. resolve resource RESOURCE_NOT_FOUND\n * 2. strip `_payment`, validate input INPUT_INVALID\n * 3. resolve price\n * 4. free -> straight to backend\n * 5. paid -> pick provider -> createRequirement -> (challenge | verify ->\n * reserve replay key -> settle), fail closed at every step\n * 6. call backend BACKEND_TIMEOUT / BACKEND_ERROR\n * 7. persist receipt, emit events, return outcome\n */\n\nimport type { PaymentMethodName } from '../domain/common.js';\nimport type { CommerceEvent, EventSink } from '../domain/event.js';\nimport type { PaymentProvider, PaymentRequirement, PaymentResult } from '../domain/payment.js';\nimport type { CommerceReceipt } from '../domain/receipt.js';\nimport type { CanonicalRequest, ExecutionOutcome, ExecutionPipeline } from '../domain/request.js';\nimport type { CommerceResource, ResourceRegistry } from '../domain/resource.js';\nimport { PAYMENT_INPUT_FIELD } from '../domain/wire.js';\nimport { CommerceError, isCommerceError, toCommerceError } from '../errors/index.js';\nimport type { BackendExecutor, BackendResponse } from '../interfaces/backend.js';\nimport type { Logger } from '../interfaces/logger.js';\nimport type { Clock, IdGenerator } from '../interfaces/runtime.js';\nimport type { ReceiptStore } from '../interfaces/store.js';\nimport { validateBackendRequestShape } from './backend-http.js';\nimport { compileJsonSchema, type Validator } from './validation.js';\n\nexport interface CreateExecutionPipelineOptions {\n readonly resources: ResourceRegistry;\n readonly paymentProviders: readonly PaymentProvider[];\n readonly store: ReceiptStore;\n readonly backend: BackendExecutor;\n readonly events: EventSink;\n readonly logger: Logger;\n readonly clock: Clock;\n readonly ids: IdGenerator;\n}\n\nexport function createExecutionPipeline(\n options: CreateExecutionPipelineOptions,\n): ExecutionPipeline {\n const validators = new Map<string, Validator>();\n\n function getValidator(resource: CommerceResource): Validator {\n const cached = validators.get(resource.id);\n if (cached) return cached;\n const compiled = compileJsonSchema(resource.inputSchema);\n validators.set(resource.id, compiled);\n return compiled;\n }\n\n async function safeEmit(event: CommerceEvent): Promise<void> {\n try {\n await options.events.emit(event);\n } catch (error) {\n options.logger.error(\n { err: describeError(error), eventType: event.type, requestId: event.requestId },\n 'Event sink failed; commerce flow continues',\n );\n }\n }\n\n async function safePersist(\n op: () => Promise<void>,\n label: string,\n requestId: string,\n ): Promise<void> {\n try {\n await op();\n } catch (error) {\n options.logger.error(\n { err: describeError(error), requestId },\n `Persistence failed: ${label}`,\n );\n }\n }\n\n function buildEvent(partial: Omit<CommerceEvent, 'id' | 'at'>): CommerceEvent {\n return { id: options.ids.next('evt'), at: options.clock.nowIso(), ...partial };\n }\n\n async function execute(request: CanonicalRequest): Promise<ExecutionOutcome> {\n const pipelineStart = options.clock.monotonicMs();\n\n // 1. resolve resource\n const resource = options.resources.get(request.resourceId);\n // Same code, same message as a genuine miss: `expose` is an admin scoping\n // decision enforced on the one execution path every adapter shares — a\n // caller on a protocol the resource isn't exposed via must not be able to\n // distinguish \"doesn't exist\" from \"exists but not for you\".\n if (!resource || !resource.exposedVia.includes(request.protocol)) {\n throw new CommerceError(\n 'RESOURCE_NOT_FOUND',\n `Resource \"${request.resourceId}\" was not found`,\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n },\n );\n }\n\n await safeEmit(\n buildEvent({\n type: 'resource.requested',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n }),\n );\n\n // 2. strip reserved payment field, then validate input\n const strippedInput = stripPaymentField(request.input);\n const validation = getValidator(resource)(strippedInput);\n if (!validation.valid) {\n throw new CommerceError(\n 'INPUT_INVALID',\n `Input for resource \"${resource.id}\" failed validation`,\n {\n requestId: request.requestId,\n resourceId: resource.id,\n details: { errors: validation.errors },\n },\n );\n }\n const validInput = validation.value;\n\n // validate the backend request shape (path-traversal, query-param\n // collision) here — before price resolution, so a resource that fails\n // this check never reaches payment. Both checks are pure functions of\n // (handler.url, input); doing them at pipeline step 6 (inside the actual\n // backend call) meant a bad value like `{ city: \"\" }` against a paid,\n // path-templated resource settled the buyer's payment and then never\n // called the backend at all — payment without delivery. call() keeps its\n // own copy of these checks as defence in depth.\n validateBackendRequestShape(resource.handler, validInput, {\n requestId: request.requestId,\n resourceId: resource.id,\n });\n\n // 3. resolve price\n if (resource.pricing.type === 'dynamic') {\n // Config validation rejects this before the gateway starts; this is defence-in-depth.\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${resource.id}\" uses unsupported dynamic pricing`,\n {\n requestId: request.requestId,\n resourceId: resource.id,\n },\n );\n }\n\n let paymentResult: PaymentResult | undefined;\n\n if (resource.pricing.type === 'fixed') {\n const pricing = resource.pricing;\n const provider = pickProvider(options.paymentProviders, resource.paymentMethods);\n if (!provider) {\n throw new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n `No enabled payment provider for resource \"${resource.id}\"`,\n {\n requestId: request.requestId,\n resourceId: resource.id,\n details: { paymentMethods: resource.paymentMethods },\n },\n );\n }\n\n let requirement: PaymentRequirement;\n try {\n requirement = await provider.createRequirement({\n requestId: request.requestId,\n resource,\n amount: pricing.amount,\n currency: pricing.currency,\n requestedAt: options.clock.nowIso(),\n });\n } catch (error) {\n throw isCommerceError(error)\n ? error\n : new CommerceError('PAYMENT_PROVIDER_UNAVAILABLE', 'Payment provider is unavailable', {\n requestId: request.requestId,\n resourceId: resource.id,\n cause: error,\n });\n }\n\n if (!request.payment) {\n await safeEmit(\n buildEvent({\n type: 'payment.required',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n }),\n );\n return {\n kind: 'payment-required',\n requestId: request.requestId,\n resourceId: resource.id,\n requirement,\n };\n }\n\n const payment = request.payment;\n\n let verification: PaymentResult;\n try {\n verification = await provider.verify({\n requestId: request.requestId,\n resource,\n requirement,\n submission: payment,\n });\n } catch (error) {\n // Any typed CommerceError the provider throws is rethrown as-is (a\n // provider can legitimately fail with STORAGE_ERROR, etc. — flattening\n // every code to PAYMENT_INVALID would hide the real cause and the\n // real, possibly-retryable HTTP status). Only a genuinely untyped\n // throw is mapped, with a fixed client-facing message — never the\n // raw error's own message.\n const mapped = isCommerceError(error)\n ? error\n : new CommerceError('PAYMENT_INVALID', 'Payment verification failed', {\n requestId: request.requestId,\n resourceId: resource.id,\n cause: error,\n });\n await safeEmit(\n buildEvent({\n type: 'payment.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: { reason: mapped.code },\n }),\n );\n throw mapped;\n }\n\n if (verification.status !== 'verified') {\n await safeEmit(\n buildEvent({\n type: 'payment.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: verification.rejectionReason ? { reason: verification.rejectionReason } : {},\n }),\n );\n throw new CommerceError(\n 'PAYMENT_INVALID',\n verification.rejectionReason ?? 'Payment was rejected',\n {\n requestId: request.requestId,\n resourceId: resource.id,\n },\n );\n }\n\n if (!verification.replayKey) {\n await safeEmit(\n buildEvent({\n type: 'payment.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: { reason: 'missing-replay-key' },\n }),\n );\n throw new CommerceError('PAYMENT_INVALID', 'Payment provider did not return a replay key', {\n requestId: request.requestId,\n resourceId: resource.id,\n });\n }\n const replayKey = verification.replayKey;\n\n try {\n await options.store.reservePaymentAttempt({\n requestId: request.requestId,\n resourceId: resource.id,\n provider: provider.name,\n replayKey,\n amount: verification.amount,\n currency: verification.currency,\n ...(verification.payer !== undefined ? { payer: verification.payer } : {}),\n ...(verification.payee !== undefined ? { payee: verification.payee } : {}),\n });\n } catch (error) {\n // The store contract only promises PAYMENT_REPLAYED for an actual\n // duplicate replayKey (already a CommerceError with that code, so\n // isCommerceError below preserves it as-is). Anything else — a disk-\n // full error, a dropped connection — is a storage failure, not a\n // replay, and must not be mislabelled as one: telling a buyer\n // \"duplicate payment\" for a transient outage is actively false, and\n // poisons any alerting keyed on replay counts.\n const mapped = toCommerceError(\n error,\n 'STORAGE_ERROR',\n 'Payment attempt could not be recorded',\n );\n await safeEmit(\n buildEvent({\n type: 'payment.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: { reason: mapped.code },\n }),\n );\n throw mapped;\n }\n\n await safeEmit(\n buildEvent({\n type: 'payment.verified',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'ok',\n }),\n );\n\n let settlement: PaymentResult;\n try {\n settlement = await provider.settle({\n requestId: request.requestId,\n resource,\n requirement,\n submission: payment,\n verification,\n });\n } catch (error) {\n // / \"the RPC did not answer\" and \"the transfer did not\n // happen\" are different facts. A provider that broadcast a settlement\n // transaction and then failed to confirm it throws\n // PAYMENT_PROVIDER_UNAVAILABLE with details.transactionHash attached\n // (the hash is known before confirmation). Recording that as plain\n // `failed` would tell the merchant's reconciliation artefact a\n // falsehood — the buyer's funds may already have moved. The resource\n // is still not delivered either way: only what gets *recorded*\n // changes, never the fail-closed outcome.\n const uncertainTxHash = uncertainSettlementTxHash(error);\n await safePersist(\n () =>\n options.store.updatePaymentAttempt(\n uncertainTxHash !== undefined\n ? { replayKey, status: 'settlement-uncertain', externalReference: uncertainTxHash }\n : {\n replayKey,\n status: 'failed',\n ...(error instanceof Error ? { rejectionReason: error.message } : {}),\n },\n ),\n uncertainTxHash !== undefined\n ? 'updatePaymentAttempt(settlement-uncertain)'\n : 'updatePaymentAttempt(failed)',\n request.requestId,\n );\n await safeEmit(\n buildEvent({\n type: 'payment.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data:\n uncertainTxHash !== undefined\n ? { reason: 'settlement-uncertain', transactionHash: uncertainTxHash }\n : { reason: 'settlement-threw' },\n }),\n );\n // The merchant's record now tells the truth (above); the buyer must\n // too — they are the party whose funds may have moved, and the\n // client-visible error is their only way to find out. Code stays\n // PAYMENT_SETTLEMENT_FAILED (not PAYMENT_PROVIDER_UNAVAILABLE, which\n // is retryable) — a retry would reuse the already-reserved replay\n // key. The transaction hash is safe to disclose: it's the buyer's\n // own payment, public on-chain the moment it lands. Nothing else\n // from the underlying error travels — only this flag and the hash.\n throw new CommerceError(\n 'PAYMENT_SETTLEMENT_FAILED',\n uncertainTxHash !== undefined\n ? 'Settlement could not be confirmed'\n : 'Payment settlement failed',\n {\n requestId: request.requestId,\n resourceId: resource.id,\n cause: error,\n ...(uncertainTxHash !== undefined\n ? { details: { settlementUncertain: true, transactionHash: uncertainTxHash } }\n : {}),\n },\n );\n }\n\n if (settlement.status !== 'settled') {\n await safePersist(\n () =>\n options.store.updatePaymentAttempt({\n replayKey,\n status: 'rejected',\n ...(settlement.rejectionReason !== undefined\n ? { rejectionReason: settlement.rejectionReason }\n : {}),\n }),\n 'updatePaymentAttempt(rejected)',\n request.requestId,\n );\n await safeEmit(\n buildEvent({\n type: 'payment.rejected',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: settlement.rejectionReason ? { reason: settlement.rejectionReason } : {},\n }),\n );\n throw new CommerceError(\n 'PAYMENT_SETTLEMENT_FAILED',\n settlement.rejectionReason ?? 'Settlement was rejected',\n {\n requestId: request.requestId,\n resourceId: resource.id,\n },\n );\n }\n\n await safePersist(\n () =>\n options.store.updatePaymentAttempt({\n replayKey,\n status: 'settled',\n ...(settlement.externalReference !== undefined\n ? { externalReference: settlement.externalReference }\n : {}),\n }),\n 'updatePaymentAttempt(settled)',\n request.requestId,\n );\n await safeEmit(\n buildEvent({\n type: 'payment.settled',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'ok',\n }),\n );\n\n paymentResult = settlement;\n }\n\n // 6. call backend\n const backendStart = options.clock.monotonicMs();\n let backendResponse: BackendResponse;\n try {\n backendResponse = await options.backend.call(resource.handler, {\n requestId: request.requestId,\n resourceId: resource.id,\n input: validInput,\n });\n } catch (error) {\n const commerceError = toCommerceError(error, 'BACKEND_ERROR', 'Backend call failed');\n await safeEmit(\n buildEvent({\n type: 'backend.failed',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n status: 'error',\n durationMs: Math.round(options.clock.monotonicMs() - backendStart),\n data: { code: commerceError.code },\n }),\n );\n\n if (paymentResult !== undefined) {\n // Settlement already succeeded (verify -> reserve -> settle all\n // completed) before the backend call failed, so the\n // uncertain-settlement rule (\"the merchant's record now tells the\n // truth; the buyer must too\") applies to this far more common\n // *certain*-loss branch as well, not only to the uncertain-RPC-timeout\n // one 100 lines above. A backend 500 is more likely than an RPC\n // confirmation timeout, so disclosing strictly *less* here than there\n // would be backwards. The tx hash is\n // safe to disclose: it is the buyer's own payment, public\n // on-chain the moment it lands.\n const failedReceipt: CommerceReceipt = {\n id: options.ids.next('receipt'),\n requestId: request.requestId,\n resourceId: resource.id,\n deliveredAt: options.clock.nowIso(),\n backendStatus: backendErrorStatus(commerceError),\n protocol: request.protocol,\n payment: paymentResult,\n metadata: { delivered: false, backendErrorCode: commerceError.code },\n };\n await safePersist(\n () => options.store.saveReceipt(failedReceipt),\n 'saveReceipt(backend-failed-after-settlement)',\n request.requestId,\n );\n\n throw new CommerceError(\n 'BACKEND_ERROR',\n 'Payment settled but the backend call failed; the payment was not refunded automatically',\n {\n requestId: request.requestId,\n resourceId: resource.id,\n cause: commerceError,\n details: {\n payment: {\n status: paymentResult.status,\n provider: paymentResult.provider,\n amount: paymentResult.amount,\n currency: paymentResult.currency,\n ...(paymentResult.network !== undefined ? { network: paymentResult.network } : {}),\n ...(paymentResult.externalReference !== undefined\n ? { externalReference: paymentResult.externalReference }\n : {}),\n },\n },\n },\n );\n }\n\n throw commerceError;\n }\n\n await safeEmit(\n buildEvent({\n type: 'backend.called',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n status: 'ok',\n durationMs: backendResponse.durationMs,\n data: { status: backendResponse.status },\n }),\n );\n\n // 7. persist receipt, emit final event, return outcome\n const receipt: CommerceReceipt = {\n id: options.ids.next('receipt'),\n requestId: request.requestId,\n resourceId: resource.id,\n deliveredAt: options.clock.nowIso(),\n backendStatus: backendResponse.status,\n durationMs: backendResponse.durationMs,\n protocol: request.protocol,\n ...(paymentResult !== undefined ? { payment: paymentResult } : {}),\n };\n\n await safePersist(() => options.store.saveReceipt(receipt), 'saveReceipt', request.requestId);\n\n const totalDurationMs = Math.round(options.clock.monotonicMs() - pipelineStart);\n\n await safeEmit(\n buildEvent({\n type: 'resource.delivered',\n requestId: request.requestId,\n resourceId: resource.id,\n adapter: request.protocol,\n status: 'ok',\n durationMs: totalDurationMs,\n }),\n );\n\n return {\n kind: 'delivered',\n requestId: request.requestId,\n resourceId: resource.id,\n backendStatus: backendResponse.status,\n body: backendResponse.body,\n headers: backendResponse.headers,\n ...(paymentResult !== undefined ? { payment: paymentResult } : {}),\n receipt,\n durationMs: totalDurationMs,\n };\n }\n\n return { execute };\n}\n\n/** The HTTP status the backend actually returned, when known (backend-http.ts\n * attaches it as `details.status` for a non-2xx response). 0 means \"no\n * response was received at all\" (timeout/transport failure) — distinct from\n * any real HTTP status. */\nfunction backendErrorStatus(error: CommerceError): number {\n const status = error.details?.['status'];\n return typeof status === 'number' ? status : 0;\n}\n\nfunction uncertainSettlementTxHash(error: unknown): string | undefined {\n if (!isCommerceError(error) || error.code !== 'PAYMENT_PROVIDER_UNAVAILABLE') return undefined;\n const hash = error.details?.['transactionHash'];\n return typeof hash === 'string' ? hash : undefined;\n}\n\nfunction pickProvider(\n providers: readonly PaymentProvider[],\n methods: readonly PaymentMethodName[],\n): PaymentProvider | undefined {\n for (const method of methods) {\n const found = providers.find((provider) => provider.name === method);\n if (found) return found;\n }\n return undefined;\n}\n\nconst RESERVED_INPUT_KEYS = new Set([PAYMENT_INPUT_FIELD, '__proto__']);\n\nfunction stripPaymentField(input: unknown): unknown {\n if (typeof input !== 'object' || input === null || Array.isArray(input)) return input;\n const record = input as Record<string, unknown>;\n // Object.hasOwn: `in` would also match inherited names and strip things\n // that were never actually present on this input.\n const hasReserved = [...RESERVED_INPUT_KEYS].some((key) => Object.hasOwn(record, key));\n if (!hasReserved) return input;\n const rest: Record<string, unknown> = {};\n for (const key of Object.keys(record)) {\n // \"__proto__\" is dropped, not just excluded from the reserved-field\n // check: `rest[key] = record[key]` for key === \"__proto__\" would invoke\n // the inherited setter and reassign rest's own prototype instead of\n // creating a data property (belt-and-braces — validation.ts's\n // Object.hasOwn fix is the primary control).\n if (!RESERVED_INPUT_KEYS.has(key)) rest[key] = record[key];\n }\n return rest;\n}\n\nfunction describeError(error: unknown): { message: string; name?: string } {\n if (error instanceof Error) return { message: error.message, name: error.name };\n return { message: String(error) };\n}\n","/**\n * In-memory implementation of the frozen `ResourceRegistry` interface.\n */\nimport type { ProtocolName } from '../domain/common.js';\nimport type { CommerceResource, ResourceRegistry } from '../domain/resource.js';\nimport { CommerceError } from '../errors/index.js';\n\nexport class ResourceRegistryImpl implements ResourceRegistry {\n private readonly byId = new Map<string, CommerceResource>();\n private readonly ordered: readonly CommerceResource[];\n\n constructor(resources: readonly CommerceResource[]) {\n for (const resource of resources) {\n if (this.byId.has(resource.id)) {\n throw new CommerceError('CONFIG_INVALID', `Duplicate resource id \"${resource.id}\"`, {\n details: { resourceId: resource.id },\n });\n }\n this.byId.set(resource.id, resource);\n }\n this.ordered = [...resources];\n }\n\n get(id: string): CommerceResource | undefined {\n return this.byId.get(id);\n }\n\n list(): readonly CommerceResource[] {\n return this.ordered;\n }\n\n listExposedVia(protocol: ProtocolName): readonly CommerceResource[] {\n return this.ordered.filter((resource) => resource.exposedVia.includes(protocol));\n }\n\n has(id: string): boolean {\n return this.byId.has(id);\n }\n}\n\n/** Build a `ResourceRegistry` from a validated list of canonical resources. */\nexport function createResourceRegistry(resources: readonly CommerceResource[]): ResourceRegistry {\n return new ResourceRegistryImpl(resources);\n}\n","/**\n * ACP protocol constants shared by the config layer and the adapter.\n *\n * Kept dependency-free: `src/config` reads the operation set at load time, so\n * anything imported here would become a config-load dependency too.\n */\n\n/**\n * The ACP stable snapshot this adapter implements, and the only value accepted\n * in the `API-Version` request header. Both name the same released snapshot;\n * they are separate constants because ACP versions the wire contract and the\n * header independently, and a future snapshot may accept more than one.\n *\n * Changing either means vendoring a new schema directory beside\n * `spec/2026-04-17/` - never editing the vendored one in place.\n */\nexport const ACP_SPEC_VERSION = '2026-04-17';\nexport const ACP_API_VERSION = '2026-04-17';\n\n/** Discovery path fixed by the ACP specification - never a configurable mount. */\nexport const ACP_WELL_KNOWN_PATH = '/.well-known/acp.json';\n\n/**\n * The stable checkout operations, by ACP operation id. All five are required\n * when ACP is enabled: a partially configured checkout lifecycle would be\n * advertised as a whole service the seller cannot actually serve.\n */\nexport const ACP_CHECKOUT_OPERATIONS = [\n 'createCheckoutSession',\n 'updateCheckoutSession',\n 'getCheckoutSession',\n 'completeCheckoutSession',\n 'cancelCheckoutSession',\n] as const;\n\nexport type AcpCheckoutOperation = (typeof ACP_CHECKOUT_OPERATIONS)[number];\n\n/**\n * Top-level canonical-input properties each operation always supplies.\n *\n * `path` carries `{ checkout_session_id }`, `body` the ACP request document.\n * Cancel is deliberately absent a body: the pinned schema does not require\n * one, and inventing one would make every cancel resource declare a property\n * ACP may never fill.\n */\nexport const ACP_OPERATION_INPUT_KEYS: Readonly<\n Record<AcpCheckoutOperation, readonly ('path' | 'body')[]>\n> = {\n createCheckoutSession: ['body'],\n updateCheckoutSession: ['path', 'body'],\n getCheckoutSession: ['path'],\n completeCheckoutSession: ['path', 'body'],\n cancelCheckoutSession: ['path'],\n};\n\n/** Media type for every ACP request and response body. */\nexport const ACP_JSON_MEDIA_TYPE = 'application/json';\n\n/**\n * Protocol headers, lowercased as Node delivers them.\n *\n * `API-Version` is mandatory on checkout requests and is never defaulted:\n * answering an unversioned request as if it named the pinned snapshot would be\n * guessing on the caller's behalf about a contract that changes.\n */\nexport const ACP_API_VERSION_HEADER = 'api-version';\nexport const ACP_REQUEST_ID_HEADER = 'request-id';\nexport const ACP_IDEMPOTENCY_KEY_HEADER = 'idempotency-key';\nexport const ACP_IDEMPOTENT_REPLAYED_HEADER = 'idempotent-replayed';\n\n/**\n * Seconds a client is told to wait before retrying a key whose first request is\n * still running. Short: the original is a live HTTP call, not a queue.\n */\nexport const ACP_IN_FLIGHT_RETRY_AFTER_SECONDS = 1;\n\n/**\n * Longest `Request-Id` echoed back. The value is the caller's, so it is\n * bounded and filtered before it is ever written into a response header.\n */\nexport const ACP_MAX_REQUEST_ID_LENGTH = 128;\n","/**\n * `config.yaml` schema, validation and normalisation into the\n * canonical `GatewayConfig` (docs/contracts.md).\n *\n * Two-phase validation:\n * 1. Zod validates *shape* (types, required fields, unknown-key rejection).\n * Numeric/boolean leaves accept either their native type or a string\n * (env substitution always produces a string), and are left as-is here -\n * Zod's typed transforms have surprising inference interactions with\n * `.strict()` objects, so numeric/boolean coercion is done explicitly,\n * in plain TypeScript, in the normalisation pass below.\n * 2. A manual business-rule pass validates cross-references that need a\n * specific, actionable message (duplicate ids, disabled protocols/payment\n * methods, dynamic pricing, destination-address plausibility) and\n * performs the numeric/boolean coercion.\n *\n * Env substitution (`${VAR}` / `${VAR:-default}`) runs over the raw parsed\n * value *before* either phase, so numeric/boolean fields can be templated too.\n * One exception, deliberate: `checkVersion` runs **before** substitution, so\n * `version:` cannot itself be templated. It is the compatibility gate that\n * decides whether this parser understands the document at all; resolving\n * environment variables to find out which schema version to expect would be\n * backwards. The order is intended; `version:` is the one exception to the\n * substitution rule, which this sentence exists to record.\n */\n\nimport { type ZodError, type ZodIssue, type ZodTypeAny, z } from 'zod';\nimport {\n extractPathParameterNames,\n findUnparsedBraceToken,\n isObjectSchemaNode,\n} from '../core/execution/index.js';\nimport {\n CommerceError,\n type CommerceResource,\n PAYMENT_INPUT_FIELD,\n PROTOCOL_NAMES,\n type Pricing,\n} from '../core/index.js';\nimport { resolveX402Deployment, type X402FacilitatorConfig } from '../payments/x402/guardrails.js';\nimport {\n ACP_CHECKOUT_OPERATIONS,\n ACP_OPERATION_INPUT_KEYS,\n ACP_WELL_KNOWN_PATH,\n type AcpCheckoutOperation,\n} from '../protocols/acp/constants.js';\nimport { substituteEnv } from './env.js';\n\nconst SUPPORTED_CONFIG_VERSION = 1;\n\n/** `0x` + 40 hex chars. Checksum-insensitive: casing is not enforced. */\nconst ADDRESS_PATTERN = /^0x[0-9a-fA-F]{40}$/;\nconst ZERO_ADDRESS_PATTERN = /^0x0{40}$/i;\n\n/**\n * A resource `id` doubles as its MCP tool name (protocol-mcp registers one\n * tool per resource, named by id). Value verified against the regex actually\n * shipped in the installed `@modelcontextprotocol/sdk@1.30.0`\n * (`shared/toolNameValidation.js`, SEP-986 \"Specify Format for Tool Names\") -\n * not duplicated as an SDK dependency, since config stays protocol-agnostic.\n */\nconst MCP_TOOL_NAME_PATTERN = /^[A-Za-z0-9._-]{1,128}$/;\n\n// ---------------------------------------------------------------------------\n// Zod schema for the *shape* of the raw (post-substitution) document.\n// ---------------------------------------------------------------------------\n\n/** Accepts a real number or a (post env-substitution) numeric string. */\nconst NumberOrString = z.union([z.number(), z.string()]);\n/** Accepts a real boolean or a (post env-substitution) \"true\"/\"false\" string. */\nconst BooleanOrString = z.union([z.boolean(), z.string()]);\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 /** Shared secret gating /api/receipts, /api/events, /api/events/stream. No token -> those routes 404. */\n adminToken: z.string().min(1).optional(),\n /** Browser origins allowed to read the dashboard-facing routes. Empty by default: closed. */\n // Entries are matched literally against the browser's\n // `Origin` header, so `\"*\"` and a trailing slash match nothing at all -\n // fail-closed (a lockout, not a bypass), but silently, and a lockout with\n // no explanation is the kind of thing an operator \"fixes\" by disabling the\n // check. Reject those two shapes with a pointer instead.\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/**\n * Every path the gateway registers itself (`src/gateway/routes.ts`), plus the\n * fixed discovery paths adapters own. An adapter mount that equals one of\n * these makes Fastify's `.all()` a duplicate of the registered route; one that\n * is a path-prefix of them swallows their 404s through the mount's\n * `${mountPath}/*` wildcard.\n */\nconst RESERVED_GATEWAY_PATHS = [\n '/health',\n '/ready',\n '/.well-known/agent-commerce',\n // Fixed by the A2A specification, so it is the adapter's to serve and never\n // a configurable mount's to claim.\n '/.well-known/agent-card.json',\n // Likewise 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/events/stream',\n] as const;\n\n/**\n * `mountPath` reaches Fastify as a route pattern, and a bad one throws inside\n * route registration - deferred to `server.ready()`, so `createGateway` fails\n * wholesale with an opaque `FST_ERR_*` instead of the adapter alone degrading.\n * Catching the shape here turns that into a CONFIG_INVALID naming the value.\n * Fastify pattern syntax (`:param`, `*`) is rejected rather than supported:\n * the mount registers its own wildcard, so a pattern here has no meaning.\n */\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 in this release - `none` is not offered. */\nconst AcpAuthSchema = z.object({ type: z.literal('bearer'), token: z.string().min(1) }).strict();\n\nconst AcpIdempotencySchema = z\n .object({ path: z.string().min(1), retentionHours: NumberOrString.optional() })\n .strict();\n\n/**\n * Operation ids are validated against `ACP_CHECKOUT_OPERATIONS` in the business\n * pass rather than spelled out again here: one list of the five names, and a\n * missing or misspelled key gets a message naming the operation.\n */\nconst AcpCheckoutSchema = z.object({ operations: z.record(z.string().min(1)) }).strict();\n\n/** Optional discovery metadata. Omitted when not configured - never guessed. */\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 block: A2A is off unless an operator asks for it, and an\n // existing config predating the adapter stays valid.\n a2a: z\n .object({\n enabled: BooleanOrString,\n mountPath: MountPathSchema.optional(),\n })\n .strict()\n .optional(),\n // Likewise optional and off by default. The sub-blocks are optional here\n // and required by the business pass only when ACP is enabled, so a\n // disabled placeholder block stays writable and an enabled one gets a\n // message naming the piece it is missing.\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\n/** Applied when `protocols.a2a` is absent or names no mount. */\nconst DEFAULT_A2A_MOUNT_PATH = '/a2a';\n\n/** Applied when `protocols.acp` is absent or names no mount. */\nconst DEFAULT_ACP_MOUNT_PATH = '/acp';\n\n/**\n * Idempotency records must outlive the window in which a client may retry, and\n * ACP fixes that window at 24 hours. A shorter retention would let a replayed\n * key past an expired record and run a checkout side effect twice, so it is\n * both the default and the floor.\n */\nconst ACP_RETENTION_HOURS = 24;\n\nconst BackendMethodSchema = z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']);\n\n/**\n * Names the top-level input properties carrying each part of the backend\n * request. Strict: a typo like `bodyy` must fail at load, not silently mean\n * \"no body binding\" and ship a request missing its payload.\n */\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\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 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 })\n .strict();\n\nconst ResourcesMapSchema = z.record(z.string().min(1), ResourceEntrySchema);\n\n/**\n * Facilitator credentials, kept generic on purpose: x402 facilitators are not\n * a single-vendor category, and an auth block shaped around one provider's\n * credentials would make the abstraction a fiction. A facilitator needing\n * per-request signed credentials is refused rather than sent nothing.\n */\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; a static header cannot express it.\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\nconst 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 means \"this facilitator takes no credential\" - an explicit\n // statement, normalised to `{ type: 'none' }` below. On a mainnet that\n // combination is refused outright, so the default can never quietly\n // become an unauthenticated production facilitator.\n auth: FacilitatorAuthSchema.optional(),\n })\n .strict(),\n]);\n\nconst X402Schema = z\n .object({\n enabled: BooleanOrString,\n network: z.string().min(1),\n rpcUrl: z.string().min(1),\n asset: z.string().min(1),\n assetName: z.string().min(1),\n assetVersion: z.string().min(1),\n assetDecimals: NumberOrString,\n payTo: z.string().min(1),\n maxTimeoutSeconds: NumberOrString,\n facilitator: FacilitatorSchema,\n /** Real funds. Never defaulted - see src/payments/x402/guardrails.ts. */\n allowMainnet: BooleanOrString.optional(),\n /** Accepts a mainnet facilitator that takes no credential. Never defaulted. */\n allowUnauthenticatedFacilitator: BooleanOrString.optional(),\n })\n .strict();\n\nconst PaymentsSchema = z\n .object({\n x402: X402Schema.optional(),\n })\n .strict();\n\nconst 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 })\n .strict();\n\ntype RawConfig = z.infer<typeof RawConfigSchema>;\ntype RawResourceEntry = z.infer<typeof ResourceEntrySchema>;\n\n// ---------------------------------------------------------------------------\n// Public shape (docs/contracts.md - exact).\n// ---------------------------------------------------------------------------\n\n/** Optional ACP discovery metadata. Absent fields are omitted from the document. */\nexport interface AcpDiscoveryConfig {\n readonly documentationUrl?: string;\n readonly supportedCurrencies?: readonly string[];\n readonly supportedLocales?: readonly string[];\n readonly interventionTypes?: readonly string[];\n}\n\n/**\n * Discriminated on `enabled` so an enabled ACP config carries everything the\n * adapter needs, with no optional-field assertions at the mount point: a\n * half-configured checkout lifecycle is rejected at load instead.\n */\nexport type AcpProtocolConfig =\n | { readonly enabled: false; readonly mountPath: string }\n | {\n readonly enabled: true;\n readonly mountPath: string;\n readonly auth: { readonly type: 'bearer'; readonly token: string };\n readonly idempotency: { readonly path: string; readonly retentionHours: number };\n readonly checkout: {\n readonly operations: Readonly<Record<AcpCheckoutOperation, string>>;\n };\n readonly discovery?: AcpDiscoveryConfig;\n };\n\nexport interface GatewayConfig {\n readonly version: 1;\n readonly merchant: { readonly id: string; readonly name: string; readonly publicBaseUrl: string };\n readonly server: {\n readonly port: number;\n readonly host: string;\n readonly adminToken?: string;\n readonly allowedOrigins: readonly string[];\n };\n readonly storage: { readonly receipts: { readonly driver: 'sqlite'; readonly path: string } };\n readonly protocols: {\n readonly http: { readonly enabled: boolean };\n readonly mcp: { readonly enabled: boolean; readonly mountPath: string };\n readonly a2a: { readonly enabled: boolean; readonly mountPath: string };\n readonly acp: AcpProtocolConfig;\n };\n /** Canonical resources, already normalised. */\n readonly resources: readonly CommerceResource[];\n readonly payments: {\n readonly x402?: {\n readonly enabled: boolean;\n readonly network: string;\n readonly rpcUrl: string;\n readonly asset: string;\n readonly assetName: string;\n readonly assetVersion: string;\n readonly assetDecimals: number;\n readonly payTo: string;\n readonly maxTimeoutSeconds: number;\n readonly facilitator: X402FacilitatorConfig;\n readonly allowMainnet?: boolean;\n readonly allowUnauthenticatedFacilitator?: boolean;\n };\n };\n}\n\n// ---------------------------------------------------------------------------\n// Entry point\n// ---------------------------------------------------------------------------\n\nexport function parseConfig(raw: unknown, env: NodeJS.ProcessEnv): GatewayConfig {\n if (typeof raw !== 'object' || raw === null || Array.isArray(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 as Record<string, unknown>);\n\n const substituted = substituteEnv(raw, env);\n const parsed = parseWithZod(RawConfigSchema, substituted);\n return normalise(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 rawVersion = raw['version'];\n const version = typeof rawVersion === 'string' ? Number(rawVersion) : rawVersion;\n if (version !== SUPPORTED_CONFIG_VERSION) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Unsupported config version \"${String(rawVersion)}\": this gateway only supports version ${SUPPORTED_CONFIG_VERSION}`,\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\n// ---------------------------------------------------------------------------\n// Numeric / boolean coercion (explicit, not via Zod - see file header).\n// ---------------------------------------------------------------------------\n\nfunction toNumber(\n value: number | string,\n path: string,\n bounds: { min?: number; max?: number } = {},\n): number {\n // `Number('')` is 0 - finite, integral, and inside\n // `server.port`'s deliberate `min: 0` (\"let the OS pick\"). So `port: ${PORT:-}`\n // or an exported-but-empty PORT validated PASS and the gateway bound a random\n // port, after which `doctor` derived `http://127.0.0.1:0`, failed to connect,\n // and reported the gateway unreachable while it was serving. `Number` also\n // accepts `\"0x50\"` (80) and `\"1e3\"` (1000) for fields that are decimal\n // integers everywhere they are documented. Require plain digits instead.\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\nfunction 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\n// ---------------------------------------------------------------------------\n// Business-rule validation + normalisation into the canonical shape.\n// ---------------------------------------------------------------------------\n\nconst SUPPORTED_PROTOCOLS: ReadonlySet<string> = new Set(PROTOCOL_NAMES);\nconst SUPPORTED_PAYMENT_METHODS = new Set(['x402']);\n\nfunction normalise(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: normaliseAcp(raw.protocols.acp),\n };\n validateMountPaths(protocols);\n\n const x402Raw = raw.payments.x402;\n const facilitator: X402FacilitatorConfig | undefined =\n x402Raw === undefined\n ? undefined\n : x402Raw.facilitator.mode === 'local'\n ? { mode: 'local', signerPrivateKey: x402Raw.facilitator.signerPrivateKey }\n : {\n mode: 'remote',\n url: x402Raw.facilitator.url,\n auth: x402Raw.facilitator.auth ?? { type: 'none' },\n };\n const x402 =\n x402Raw && facilitator\n ? {\n enabled: toBoolean(x402Raw.enabled, 'payments.x402.enabled'),\n network: x402Raw.network,\n rpcUrl: x402Raw.rpcUrl,\n asset: x402Raw.asset,\n assetName: x402Raw.assetName,\n assetVersion: x402Raw.assetVersion,\n assetDecimals: toNumber(x402Raw.assetDecimals, 'payments.x402.assetDecimals', {\n min: 0,\n max: 36,\n }),\n payTo: x402Raw.payTo,\n maxTimeoutSeconds: toNumber(\n x402Raw.maxTimeoutSeconds,\n 'payments.x402.maxTimeoutSeconds',\n {\n min: 1,\n },\n ),\n facilitator,\n ...(x402Raw.allowMainnet !== undefined\n ? { allowMainnet: toBoolean(x402Raw.allowMainnet, 'payments.x402.allowMainnet') }\n : {}),\n ...(x402Raw.allowUnauthenticatedFacilitator !== undefined\n ? {\n allowUnauthenticatedFacilitator: toBoolean(\n x402Raw.allowUnauthenticatedFacilitator,\n 'payments.x402.allowUnauthenticatedFacilitator',\n ),\n }\n : {}),\n }\n : undefined;\n\n if (x402) {\n validateAddress('payments.x402.payTo', x402.payTo);\n validateAddress('payments.x402.asset', x402.asset);\n // The same call the provider makes at construction, run here so\n // `agent-commerce validate` reports an unsafe deployment where an operator\n // expects to hear about it, rather than at first boot.\n resolveX402Deployment({\n network: x402.network,\n payTo: x402.payTo,\n asset: x402.asset,\n assetName: x402.assetName,\n assetVersion: x402.assetVersion,\n facilitator: x402.facilitator,\n ...(x402.allowMainnet !== undefined ? { allowMainnet: x402.allowMainnet } : {}),\n ...(x402.allowUnauthenticatedFacilitator !== undefined\n ? { allowUnauthenticatedFacilitator: x402.allowUnauthenticatedFacilitator }\n : {}),\n });\n }\n\n const resources = Object.entries(raw.resources).map(([id, entry]) =>\n normaliseResource(id, entry, protocols, x402),\n );\n if (protocols.acp.enabled) validateAcpCheckoutMapping(protocols.acp, resources);\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 // min 0, not 1: port 0 is the standard \"let the OS pick a free port\"\n // convention, useful for tests and ephemeral dev/demo 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 ...(x402 !== undefined ? { x402 } : {}),\n },\n };\n}\n\ninterface NormalisedProtocols {\n readonly http: { readonly enabled: boolean };\n readonly mcp: { readonly enabled: boolean; readonly mountPath: string };\n readonly a2a: { readonly enabled: boolean; readonly mountPath: string };\n readonly acp: AcpProtocolConfig;\n}\n\n/**\n * Two enabled mounts may not overlap: each registers a `${mountPath}/*`\n * wildcard, so a shared prefix means one adapter silently answers for the\n * other. Disabled protocols mount nothing and are not compared.\n */\nfunction validateMountPaths(protocols: NormalisedProtocols): 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// ---------------------------------------------------------------------------\n// ACP (experimental)\n// ---------------------------------------------------------------------------\n\ntype RawAcp = NonNullable<RawConfig['protocols']['acp']>;\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\nfunction normaliseAcp(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 if (raw.idempotency === undefined) {\n throw acpInvalid(\n 'protocols.acp.idempotency',\n 'protocols.acp.idempotency is required when ACP is enabled - it names the SQLite file holding checkout idempotency records, and ACP makes the Idempotency-Key mandatory on every checkout POST',\n );\n }\n\n const discovery = raw.discovery;\n\n return {\n enabled: true,\n mountPath,\n auth: raw.auth,\n idempotency: {\n path: raw.idempotency.path,\n retentionHours: toNumber(\n raw.idempotency.retentionHours ?? ACP_RETENTION_HOURS,\n 'protocols.acp.idempotency.retentionHours',\n { min: ACP_RETENTION_HOURS },\n ),\n },\n checkout: { operations: normaliseAcpOperations(raw.checkout) },\n // Built key by key rather than passed through: absent metadata must stay\n // absent from the discovery document, not appear there as `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/**\n * All five operations, each on its own resource.\n *\n * Partial mappings are refused because ACP discovery advertises `checkout` as\n * one service: a seller announcing it must be able to serve the whole\n * lifecycle. One resource serving two operations is refused because the\n * operations differ in method, canonical input and success status - a resource\n * that satisfies both is a resource that implements neither faithfully.\n */\nfunction normaliseAcpOperations(\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\nfunction 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 its own purchase payment (`payment_data` on\n // completion). Charging an Agent Commerce payment to *invoke* the operation\n // would stack a second, unrelated payment layer on one call, and ACP has no\n // wire representation for our payment-required outcome to negotiate it.\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/**\n * The adapter sends a fixed canonical envelope per operation, so a resource\n * whose input schema forbids a key ACP always sends - or demands one ACP never\n * sends - can only ever fail at request time with INPUT_INVALID. Cheaper to\n * say so at load.\n */\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 properties = schema['properties'];\n\n if (schema['additionalProperties'] === false && isPlainObject(properties)) {\n for (const key of keys) {\n if (!Object.hasOwn(properties, key)) {\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 always sends for this operation`,\n { resourceId: resource.id },\n );\n }\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 never supplies (it sends: ${keys.join(', ')})`,\n { resourceId: resource.id },\n );\n }\n }\n }\n}\n\ninterface NormalisedX402 {\n readonly enabled: boolean;\n readonly assetDecimals: number;\n}\n\nfunction normaliseResource(\n id: string,\n entry: RawResourceEntry,\n protocols: NormalisedProtocols,\n x402: NormalisedX402 | undefined,\n): CommerceResource {\n if (entry.input !== undefined) validateResourceSchemaKeywords(id, 'input', entry.input);\n\n const inputProperties = entry.input?.['properties'];\n if (\n inputProperties &&\n typeof inputProperties === 'object' &&\n PAYMENT_INPUT_FIELD in inputProperties\n ) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" declares an input property \"${PAYMENT_INPUT_FIELD}\", which is reserved for payment proofs`,\n {\n details: {\n path: `resources.${id}.input.properties.${PAYMENT_INPUT_FIELD}`,\n resourceId: id,\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 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 if (entry.pricing.type === 'fixed') {\n validatePricingAmount(id, entry.pricing.amount, x402);\n }\n\n const paymentMethods = entry.payments ?? [];\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: x402.`,\n { details: { path: `resources.${id}.payments`, resourceId: id, method } },\n );\n }\n if (method === 'x402' && (!x402 || !x402.enabled)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" names payment method \"x402\" which is not configured or not enabled under payments.x402`,\n { details: { path: `resources.${id}.payments`, resourceId: id, method } },\n );\n }\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 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 };\n}\n\n/**\n * `{param}` templates (e.g. `.../weather/{city}`) parse fine as a URL - the\n * WHATWG parser just percent-encodes the braces - so this only rejects\n * genuinely malformed strings and non-http(s) schemes, not templating.\n */\n/**\n * Permissive-by-default is the wrong default for a value forwarded to\n * someone else's API: an object schema that\n * omits `additionalProperties` defaults, per JSON Schema itself, to\n * \"anything goes\" - so default it to `false` here instead, unless the\n * operator set it explicitly (including explicitly to `true`, which is\n * respected).\n *\n * An earlier fix only stamped the ROOT schema, so\n * `filter: { type: object }` *looked* closed (the top level really was)\n * while every key one level down under `properties.filter` still passed\n * verbatim - `core`'s validator (execution/validation.ts) only enforces\n * `additionalProperties` where the schema states it explicitly, at every\n * level independently. Recurse into `properties` and `items` the same way\n * `validateResourceSchemaKeywords` below already does, so \"closed\" actually\n * means closed at every depth, not just the one an operator happened to\n * write `additionalProperties: false` on.\n *\n * `type` can be an array (`[\"object\",\"null\"]`, valid JSON\n * Schema) - a bare `=== 'object'` string comparison missed it, so a schema\n * in that shape got stamped as open. `declaresObjectType` below is the same\n * check `core`'s validator now makes (`execution/validation.ts`'s\n * `isObjectSchemaNode`) so the two stay in agreement.\n */\nfunction defaultClosedObjectSchema(schema: Record<string, unknown>): Record<string, unknown> {\n // imported, never re-implemented. The local predicate this\n // replaces recognised `type`/`properties` but not `required`, while core's\n // validator recognised `properties`/`required` - so `input: { required: [q] }`\n // was an object to the validator and not to the stamper, and every unknown\n // key sailed through to the merchant backend. One definition, one drift.\n const isObjectSchema = isObjectSchemaNode(schema);\n const result: Record<string, unknown> = { ...schema };\n\n if (isObjectSchema) {\n const properties = schema['properties'];\n if (isPlainObject(properties)) {\n result['properties'] = Object.fromEntries(\n Object.entries(properties).map(([key, sub]) => [\n key,\n isPlainObject(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 (isPlainObject(items)) {\n result['items'] = defaultClosedObjectSchema(items);\n }\n\n // The third place this stamper drifted from the validator, after `required`\n // and tuple `items`. `additionalProperties: {schema}` is the idiomatic\n // \"map of typed objects\" shape, and core's validator applies that subschema\n // recursively at unbounded depth - so without this branch, every node under\n // it stayed open and unknown keys reached the merchant backend. Recursion\n // here is not conditional on `isObjectSchema`: the validator applies the\n // subschema wherever it finds one.\n const additional = schema['additionalProperties'];\n if (isPlainObject(additional)) {\n result['additionalProperties'] = defaultClosedObjectSchema(additional);\n }\n\n return result;\n}\n\n/**\n * A resource that declares no `input:` at all got\n * `inputSchema: undefined`, and `compileJsonSchema(undefined)` is an\n * always-valid validator - every caller key was forwarded to the merchant\n * backend verbatim. The decision: default \"declared nothing\" to \"accepts\n * nothing\" (an empty closed object) rather than rejecting the config at load\n * time - a no-argument resource that omits `input:` is a legitimate shape,\n * and rejecting it would break every existing config that uses it.\n */\nconst EMPTY_CLOSED_OBJECT_SCHEMA: Record<string, unknown> = {\n type: 'object',\n properties: {},\n additionalProperties: false,\n};\n\n/**\n * `src/core`'s validator only enforces the subset documented in\n * `execution/validation.ts` (type/properties/required/additionalProperties/\n * enum/items) - everything else (`pattern`, `minLength`, `format`, `oneOf`,\n * …) is silently ignored at runtime. An operator who writes `pattern` and\n * never sees it enforced has no way to know that from the config alone, so\n * warn at load time instead of letting them find out the hard way.\n */\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\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** `type` explicitly set to something that rules out \"object\" (a bare\n * value, or an array not containing \"object\"). `undefined` - no `type` at\n * all - is deliberately NOT treated as excluding: core's validator treats\n * `properties`/`required` with no `type` as an object schema, so that shape\n * is fine, not another instance of this bug. */\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, both warning (existing, unenforced\n * keywords) and rejecting (a node whose declared `type`\n * cannot structurally be an object, yet which still carries `properties` or\n * `required`). The `properties`/`required`-with-no-`type` shape is not\n * this function's problem any more, since the\n * validator now treats that shape as an object; what's still a trap is a\n * `type` that actively rules \"object\" out while `properties`/`required`\n * imply it was meant to be one, e.g. a copy-pasted sibling schema whose\n * `type` was never updated. Rejecting (not just warning) here is the\n * decision - a warning is exactly what let this bug class ship silently in\n * the first place (`validate`/`doctor` both said PASS).\n */\nfunction 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 // eslint-disable-next-line no-console\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 // the other half. Closing a `required`-only node is\n // correct JSON Schema and quietly unsatisfiable: `required: [\"q\"]` demands a\n // property that `properties` never declares, so the stamped\n // `additionalProperties: false` rejects `q` as an unknown key - the schema\n // can never be satisfied by any input at all. Fail-closed, so no money is at\n // risk, but every call would 400 with a config that loaded cleanly. Say so\n // at load instead. Only when the node really will be closed: an explicit\n // `additionalProperties` 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 = isPlainObject(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 (isPlainObject(properties)) {\n for (const [key, sub] of Object.entries(properties)) {\n if (isPlainObject(sub)) validateResourceSchemaKeywords(id, `${path}.properties.${key}`, sub);\n }\n }\n const additional = schema['additionalProperties'];\n if (isPlainObject(additional)) {\n validateResourceSchemaKeywords(id, `${path}.additionalProperties`, additional);\n }\n const items = schema['items'];\n if (isPlainObject(items)) {\n validateResourceSchemaKeywords(id, `${path}.items`, items);\n } else if (Array.isArray(items)) {\n // tuple-form `items` (an array of per-position\n // schemas) is valid JSON Schema, but `core`'s validator only supports\n // the single-schema form applied to every element - a tuple silently\n // enforces nothing, invisibly rather than wrongly, so warn the same way\n // an unsupported keyword does.\n // eslint-disable-next-line no-console\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\n/**\n * `amount: z.string().min(1)` alone let \"0,01\", \"$0.01\", \"1e-2\", \"-1\" and an\n * over-precise \"0.0000001\" all pass config + `doctor`, then throw on every\n * purchase. A plain\n * positive decimal only - no currency symbol, no thousands separator, no\n * exponent notation.\n */\nconst PRICING_AMOUNT_PATTERN = /^\\d+(?:\\.\\d+)?$/;\nconst ZERO_AMOUNT_PATTERN = /^0(?:\\.0+)?$/;\n\nfunction validatePricingAmount(id: string, amount: string, x402: NormalisedX402 | 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 settles a zero-value transfer, which is\n // nonsense - if something is free, it should say so.\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 (x402 !== undefined) {\n const fractionalDigits = amount.includes('.') ? (amount.split('.')[1]?.length ?? 0) : 0;\n if (fractionalDigits > x402.assetDecimals) {\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 (${x402.assetDecimals} decimals)`,\n { details: { path, resourceId: id } },\n );\n }\n }\n}\n\n/**\n * `backend.inputBindings` names top-level input properties; this is the gate\n * that makes those names mean something at load time rather than at the first\n * paid call. Input schemas are closed by default at every depth\n * (`defaultClosedObjectSchema`), so a binding naming a property the schema\n * never declares can never be satisfied - the group would be silently empty\n * on every request, which on a paid resource is payment for a request the\n * backend receives incomplete.\n *\n * Returns the schema node `{param}` declarations must be found in: the path\n * group in explicit mode, the whole input in legacy mode.\n */\nfunction 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 = isPlainObject(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 (property === PAYMENT_INPUT_FIELD) {\n fail(\n `binds \"${location}\" to \"${PAYMENT_INPUT_FIELD}\", which is reserved for payment proofs`,\n { location },\n );\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 legitimately be any JSON value; only the two groups the\n // executor iterates as key/value pairs have to be objects.\n const declared = properties[property];\n if (location !== 'body' && isPlainObject(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: isPlainObject(group) ? group : undefined,\n where: `input.properties.${bindings.path}`,\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\n/**\n * The root-cause half. `validateBackendRequestShape`\n * (src/core) rejects a missing path parameter at request time - after\n * schema validation but, without this check, on every single call, because\n * a schema that never declares `{city}` can never satisfy it. A paid\n * resource in that shape settles the buyer's payment and then always fails\n * to reach the backend: no refund, replay key burned, on every call, not an\n * unlucky one. Every `{param}` in `backend.url` must be BOTH declared in\n * `properties` AND listed in `required` - an optional value hits the exact\n * same \"caller structurally cannot supply it on every call that omits it\"\n * problem as an undeclared one, just less often. This is the config-load\n * gate `agent-commerce validate`/`doctor` catch it at; the runtime\n * `INPUT_INVALID` in `validateBackendRequestShape` is defence in depth for\n * a hand-built `CommerceResource` this check never saw.\n */\nfunction validatePathParametersDeclared(\n id: string,\n url: string,\n input: Record<string, unknown> | undefined,\n where: string,\n): void {\n // Before anything else: a brace token the canonical grammar does not\n // recognise is neither extracted here nor substituted at request time, so it\n // would travel to the backend as a percent-encoded literal. On a paid\n // resource that is payment-without-delivery on every single call. Refuse it\n // at load rather than letting \"matches nothing\" mean \"nothing to check\".\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 be sent to the backend literally, so a paid resource would settle payment and then never reach the backend`,\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 // Every defence around `{param}` guards the *path* position, and in the host\n // position all of them fail open at once: `new URL('http://{host}/api')`\n // parses (the hostname is literally `{host}`) so the URL check passes; the\n // runtime containment check is skipped because its literal prefix\n // (`http://`) does not itself parse as a URL; and `encodeURIComponent` does\n // not escape dots, so a hostname survives it whole. Caller input then chooses\n // which host the gateway calls - the metadata service, an internal address,\n // anything. `http://{region}.api.internal/...` is an ordinary-looking\n // multi-tenant template, so this is refused here rather than warned about.\n //\n // The rule: everything before the first `{` must already be a complete\n // authority - a parseable origin followed by the path's leading `/`.\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 at all - the parameter starts before the authority is done.\n }\n if (origin === undefined || !prefix.startsWith(`${origin}/`)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has a backend.url parameter before the end of the host (\"${url}\"). 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 = isPlainObject(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 settle payment (if priced) and then fail to reach the backend`,\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 caller that omits it hits the same unservable-request problem as an undeclared parameter`,\n { details: { path, resourceId: id, param } },\n );\n }\n }\n}\n\nfunction validateBackendUrl(id: string, url: string): void {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" has an invalid backend.url \"${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\nfunction validateAddress(path: string, value: string): void {\n if (!ADDRESS_PATTERN.test(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 (ZERO_ADDRESS_PATTERN.test(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","/**\n * Locates and parses `config.yaml`, then hands the raw value to\n * `parseConfig`. Never trusts raw YAML before Zod 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/index.js';\nimport { DEFAULT_CONFIG_FILENAME } from './filename.js';\nimport { type GatewayConfig, parseConfig } from './schema.js';\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 // Retained for programmatic callers. Nothing in the CLI prints a\n // `cause`, and nothing should start: this is the object whose\n // `.message` carries the source excerpt (see below).\n cause: error,\n },\n );\n }\n\n return parseConfig(raw, env);\n}\n\n/**\n * A YAML failure described from the error's *structured* fields only.\n *\n * Deliberately not `error.message`: the `yaml` package builds that message\n * with a **code frame excerpt of the source line**, so a syntax error next to\n * an inline secret would reproduce it verbatim into `validate`/`doctor` output — including `doctor --json`, the output most\n * likely to be pasted into an issue or captured by CI:\n *\n * … is not valid YAML: Nested mappings are not allowed … at line 2, column 15:\n *\n * adminToken: super-secret-token-value\n * ^\n *\n * `server.adminToken` and `payments.x402.facilitator.signerPrivateKey` are\n * both legal as inline literals, so this was a real sink rather than a\n * hypothetical one — and it contradicted `validate`'s own promise never to\n * print a resolved value: it never printed a resolved `${ENV}`, only an\n * inlined one. `code` and `linePos` locate the fault exactly as well and\n * cannot contain file content.\n */\n/**\n * Plain-English phrasing for the codes an operator actually hits, so replacing\n * the excerpt does not also cost the diagnostic its readability. These are\n * fixed strings chosen here — they can never contain file content, which is\n * the entire property that matters. Anything unlisted degrades to the bare\n * code, which is still precise.\n */\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\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","/** Default `IdGenerator` used when the caller does not inject one. */\nimport { randomUUID } from 'node:crypto';\nimport type { IdGenerator } from '../core/index.js';\n\nexport function createDefaultIdGenerator(): IdGenerator {\n return {\n next(prefix?: string): string {\n const id = randomUUID();\n return prefix ? `${prefix}_${id}` : id;\n },\n };\n}\n","/**\n * Pino logger factory with redaction. Never log secrets: Authorization\n * headers, the payment-signature header, private keys, seeds, mnemonics,\n * signatures.\n *\n * Two independent things are built here, deliberately not the same pino\n * instance (Fastify's `loggerInstance` option forces its generic `Logger`\n * type into `FastifyInstance`, which then conflicts with our own `Logger`\n * shape under `exactOptionalPropertyTypes`):\n * - `fastifyLoggerOptions()` — a plain options object handed to Fastify's\n * `logger` option, so Fastify builds its own internally-typed pino\n * instance (still redacted, still pino-pretty in development) for HTTP\n * access logs.\n * - `createGatewayLogger()` — a standalone pino instance wrapped to the\n * `src/core` `Logger` shape, injected into the\n * execution pipeline and protocol adapters.\n * Both share the same redaction paths and level/pretty-print policy.\n */\n\nimport { createRequire } from 'node:module';\nimport type { FastifyReply, FastifyRequest } from 'fastify';\nimport pino, { type LoggerOptions, type Logger as PinoLogger } from 'pino';\nimport type { Logger } from '../core/index.js';\n\n/**\n * Absolute path to pino-pretty, or `undefined` when it is not installed.\n *\n * pino-pretty is a **devDependency**: it is a developer-experience nicety and\n * making every consumer of the published package install it (and its\n * transitive tree) to get log lines would be the wrong trade. But the pretty\n * default keys off `NODE_ENV`, which is unset in a normal consumer process —\n * so \"development\" was inferred and `pino()` threw\n * `unable to determine transport target for \"pino-pretty\"`, taking down\n * `createGateway()` for anyone importing the library. The clean-consumer test\n * caught it; nothing in the repo could, because here it is always installed.\n *\n * Resolving it ourselves answers the only question that matters — *is it\n * actually there* — and passing the resolved absolute path (rather than the\n * bare name) removes the second failure mode, where pino resolves transport\n * targets from a different directory than we do.\n */\nconst PINO_PRETTY_PATH: string | undefined = (() => {\n try {\n return createRequire(import.meta.url).resolve('pino-pretty');\n } catch {\n return undefined;\n }\n})();\n\n// pino/fast-redact paths below are single-level wildcards: '*.privateKey'\n// matches privateKey one level deep (e.g. `wallet.privateKey`), not at\n// arbitrary nesting (`a.b.privateKey` is not covered). Nothing leaks today\n// because every call site funnels through describeError(), which extracts\n// only {message, name} before logging — never a raw caught object — but that\n// is a property of current call sites, not of this redact config. Do not log\n// a raw object that might carry a secret at depth > 1 without either\n// extending these paths or hand-picking safe fields first.\nconst SECRET_FIELD_NAMES = [\n 'privateKey',\n 'signerPrivateKey',\n 'signature',\n 'seed',\n 'mnemonic',\n 'secret',\n 'apiKey',\n 'adminToken',\n 'token',\n] as const;\n\n/**\n * The bare top-level form was missing — `'*.privateKey'`\n * matches `{ wallet: { privateKey } }` but not `{ privateKey }`, so a\n * `logger.error({ privateKey })` would have printed it. Both forms are\n * generated now. The depth limit is real and unchanged: fast-redact wildcards\n * are single-level, so a secret at depth ≥ 2 is still not covered, and the\n * documentation says so rather than promising \"any field\".\n */\nexport const REDACT_PATHS: readonly string[] = [\n 'req.headers.authorization',\n 'req.headers[\"payment-signature\"]',\n ...SECRET_FIELD_NAMES,\n ...SECRET_FIELD_NAMES.map((name) => `*.${name}`),\n];\n\nexport interface CreateGatewayLoggerOptions {\n readonly level?: string;\n readonly name?: string;\n readonly nodeEnv?: string;\n readonly prettyPrint?: boolean;\n}\n\nexport interface CreatedGatewayLogger {\n /** Raw pino instance, not shared with Fastify — see file header. */\n readonly pino: PinoLogger;\n /** `src/core` `Logger`-shaped wrapper. */\n readonly core: Logger;\n}\n\nfunction baseLoggerOptions(options: CreateGatewayLoggerOptions): LoggerOptions {\n const nodeEnv = options.nodeEnv ?? process.env['NODE_ENV'] ?? 'development';\n // Never spawn a pino-pretty worker thread in tests: many short-lived\n // Fastify/pino instances are created per test run, and pretty-printing is a\n // pure developer-experience nicety, not a functional requirement there.\n const wantPretty = options.prettyPrint ?? (nodeEnv !== 'production' && nodeEnv !== 'test');\n // Asked for *and* available. An explicit `prettyPrint: true` cannot conjure\n // an uninstalled module, so it degrades to JSON rather than throwing —\n // pretty-printing is cosmetic, and losing colour beats losing the gateway.\n const usePretty = wantPretty && PINO_PRETTY_PATH !== undefined;\n\n return {\n level: options.level ?? process.env['LOG_LEVEL'] ?? (nodeEnv === 'test' ? 'silent' : 'info'),\n ...(options.name !== undefined ? { name: options.name } : {}),\n redact: { paths: [...REDACT_PATHS], censor: '[REDACTED]' },\n ...(usePretty ? { transport: { target: PINO_PRETTY_PATH as string } } : {}),\n };\n}\n\n/**\n * Strips the query string from a request URL before it reaches a log line\n * or an echoed-back response body. The admin token is header-only, with no\n * `?adminToken=` exception for the SSE route (see access-control.ts's doc\n * comment), so this is not the only thing keeping it out of logs — but any\n * query parameter, on any route, could carry something sensitive, and a\n * blanket redaction costs nothing to keep. Single source of truth: every place that puts a\n * request URL in front of a log or a client must call this, not re-derive\n * its own redaction — two redactors drift (Fastify's\n * default 404 handler built its own message string from the raw URL,\n * bypassing the `req` serializer below entirely; see server.ts's\n * `setNotFoundHandler`, which uses this same function).\n */\nexport function sanitizeUrl(url: string | undefined): string | undefined {\n if (url === undefined) return undefined;\n const queryIndex = url.indexOf('?');\n return queryIndex === -1 ? url : `${url.slice(0, queryIndex)}?[REDACTED]`;\n}\n\n/** Overrides (not extends) Fastify's default `req` serializer — see sanitizeUrl. */\nfunction redactedReqSerializer(req: {\n method?: string;\n url?: string;\n host?: string;\n ip?: string;\n socket?: { remotePort?: number };\n}): Record<string, unknown> {\n return {\n method: req.method,\n url: sanitizeUrl(req.url),\n host: req.host,\n remoteAddress: req.ip,\n remotePort: req.socket?.remotePort,\n };\n}\n\n/** Plain options object for Fastify's own `logger` option (see file header). */\nexport function fastifyLoggerOptions(options: CreateGatewayLoggerOptions = {}): LoggerOptions {\n return {\n ...baseLoggerOptions(options),\n serializers: { req: redactedReqSerializer },\n };\n}\n\n/**\n * Fastify's own default 404 handler (four-oh-four.js's `basic404` ->\n * log-controller.js's `routeNotFound`) builds its log line by interpolating\n * `request.raw.url` into a template string — bypassing the `req` serializer\n * above entirely, since it's a plain string, not a structured log call.\n * Registering a `setNotFoundHandler` replaces Fastify's internal one outright\n * (it is only ever invoked when none is set), so this is the only fix point.\n * Exported (not inlined in server.ts) so production and tests share the exact\n * same handler — a second, test-only reimplementation is exactly the kind of\n * thing that quietly drifts from what actually ships.\n */\nexport function buildNotFoundHandler(): (request: FastifyRequest, reply: FastifyReply) => void {\n return (request, reply) => {\n const safeUrl = sanitizeUrl(request.raw.url) ?? '';\n const message = `Route ${request.method}:${safeUrl} not found`;\n request.log.info(message);\n reply.code(404).send({ message, error: 'Not Found', statusCode: 404 });\n };\n}\n\nexport function createGatewayLogger(\n options: CreateGatewayLoggerOptions = {},\n): CreatedGatewayLogger {\n const instance = pino(baseLoggerOptions(options));\n return { pino: instance, core: wrapPino(instance) };\n}\n\nfunction wrapPino(instance: PinoLogger): Logger {\n const logger: Logger = {\n debug: (obj, msg) => instance.debug(obj, msg),\n info: (obj, msg) => instance.info(obj, msg),\n warn: (obj, msg) => instance.warn(obj, msg),\n error: (obj, msg) => instance.error(obj, msg),\n child: (bindings) => wrapPino(instance.child(bindings)),\n };\n return logger;\n}\n","/**\n * `onRequest` hooks doing two separate jobs:\n * - `buildAccessControlHook` (global, registered once): DNS-rebinding Host\n * defence + allowlisted CORS for browser traffic. Neither is path-keyed,\n * so this stays a single hook on the whole server.\n * - `buildOperatorTokenHook` (per-route, registered on each of the three\n * ledger routes individually): the `server.adminToken` gate.\n *\n * Why per-route and not the global hook: a global gate has only\n * `request.url`'s path to match against a literal string set. Fastify's\n * router (find-my-way) percent-*decodes* before matching, so such a gate\n * compares the *raw, still-encoded* string. `/api/%72eceipts` is \"not an\n * operator path\" to the gate and *is* `/api/receipts` to the router — a full\n * bypass with no precondition beyond network reach. A per-route hook removes\n * the whole bug class rather than guarding one instance of it: Fastify only invokes it\n * once routing has already matched this exact route, so there is no path\n * string left to attack — nothing here compares against `request.url` at\n * all.\n */\nimport { createHash, timingSafeEqual } from 'node:crypto';\nimport type { FastifyReply, FastifyRequest } from 'fastify';\n\nconst CORS_METHODS = 'GET,POST,DELETE,OPTIONS';\nconst CORS_HEADERS = 'content-type,payment-signature,x-request-id,authorization';\n/**\n * Without this a browser client can read neither the challenge nor the\n * settlement result: cross-origin JS only sees the CORS-safelisted response\n * headers unless they are named here.\n */\nconst CORS_EXPOSED_HEADERS = 'payment-required,payment-response,x-request-id';\n\nexport interface AccessControlOptions {\n readonly publicBaseUrl: string;\n readonly allowedOrigins: readonly string[];\n}\n\nexport function buildAccessControlHook(\n options: AccessControlOptions,\n): (request: FastifyRequest, reply: FastifyReply) => Promise<void> {\n // Compare case-insensitively (matches the Host check below) — an\n // operator's mis-cased allowedOrigins entry should not lock out the real\n // dashboard behind a generic 403 with no hint why. The *response* header\n // still echoes the browser's own Origin verbatim (not the lowercased\n // form): CORS requires a byte-for-byte match against what the browser\n // sent, and browsers always send Origin already lowercased in practice, so\n // this loses nothing while fixing the config-typo case.\n const allowedOrigins = new Set(options.allowedOrigins.map((origin) => origin.toLowerCase()));\n const publicHostname = hostnameOf(options.publicBaseUrl);\n\n return async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n // 1. Host validation (DNS-rebinding defence) — every request, browser or not.\n const host = request.headers.host;\n if (!isAllowedHost(host, publicHostname)) {\n reply.status(403).send({ status: 'error', code: 'FORBIDDEN', message: 'Host not allowed' });\n return;\n }\n\n // 2. CORS, only for requests that carry an Origin (browser traffic). A\n // request with no Origin (the normal case for agents/MCP clients) gets no\n // CORS header at all.\n const origin = request.headers.origin;\n if (origin !== undefined) {\n if (!allowedOrigins.has(origin.toLowerCase())) {\n reply\n .status(403)\n .send({ status: 'error', code: 'FORBIDDEN', message: 'Origin not allowed' });\n return;\n }\n reply.header('access-control-allow-origin', origin);\n reply.header('access-control-allow-methods', CORS_METHODS);\n reply.header('access-control-allow-headers', CORS_HEADERS);\n reply.header('access-control-expose-headers', CORS_EXPOSED_HEADERS);\n reply.header('vary', 'Origin');\n if (request.method === 'OPTIONS') {\n // Preflight: never carries credentials, so it must not hit a\n // downstream per-route token gate — the browser only sends the real\n // request afterward.\n reply.status(204).send();\n }\n }\n };\n}\n\n/**\n * Per-route token gate — register via `{ onRequest: buildOperatorTokenHook(...) }`\n * on each ledger route's own definition, not the global hook. Closed by\n * default: no token configured => 404 (fail closed, indistinguishable from\n * \"route doesn't exist\"). Token configured but missing/wrong => 401.\n *\n * Header-only, with no exception for the SSE route. `EventSource` cannot send\n * headers, which makes a `?adminToken=` query parameter tempting; the\n * dashboard uses its authenticated polling fallback instead — see\n * SECURITY.md. A token in a query string leaks through Referer, browser\n * history and proxy logs.\n */\nexport function buildOperatorTokenHook(\n adminToken: string | undefined,\n): (request: FastifyRequest, reply: FastifyReply) => Promise<void> {\n // async, matching buildAccessControlHook's convention: a plain 2-arg\n // function that returns `void` (not a Promise) is ambiguous to Fastify's\n // hook runner, which otherwise waits on a 3rd `done` callback that never\n // comes.\n return async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n if (!adminToken) {\n reply.status(404).send();\n return;\n }\n if (!isValidAdminToken(request.headers.authorization, adminToken)) {\n reply\n .status(401)\n .send({ status: 'error', code: 'UNAUTHORIZED', message: 'Admin token required' });\n }\n };\n}\n\n/** `new URL()` handles port-stripping and IPv6 bracket notation; no need to hand-roll it. */\nfunction hostnameOf(value: string): string {\n try {\n const hostname = new URL(\n value.includes('://') ? value : `http://${value}`,\n ).hostname.toLowerCase();\n // URL#hostname keeps the brackets on an IPv6 literal (\"[::1]\"); strip them\n // so it compares equal to the plain \"::1\" form.\n return hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;\n } catch {\n return '';\n }\n}\n\n// Loopback aliases are always trusted regardless of configured publicBaseUrl:\n// a DNS-rebinding attacker's page sends its OWN hostname as Host, never the\n// literal string \"localhost\"/\"127.0.0.1\"/\"::1\" — so allowing these can never\n// reintroduce the attack this check exists to stop, and it keeps local\n// dev/test setups (where the bind host and the configured publicBaseUrl\n// legitimately differ, e.g. 127.0.0.1 vs. localhost) working without\n// requiring them to match exactly.\nconst LOOPBACK_HOSTNAMES = new Set(['localhost', '127.0.0.1', '::1']);\n\nfunction isAllowedHost(hostHeader: string | undefined, publicHostname: string): boolean {\n if (!hostHeader) return false;\n const hostname = hostnameOf(hostHeader);\n return hostname !== '' && (hostname === publicHostname || LOOPBACK_HOSTNAMES.has(hostname));\n}\n\nfunction isValidAdminToken(authHeader: string | undefined, adminToken: string): boolean {\n const provided = authHeader?.startsWith('Bearer ')\n ? authHeader.slice('Bearer '.length)\n : undefined;\n if (provided === undefined) return false;\n // Hash both sides first: timingSafeEqual throws on unequal-length buffers,\n // and a thrown-vs-not branch is itself a timing/type oracle on the token's\n // length. SHA-256 digests are always 32 bytes, so the comparison is\n // constant-shape regardless of what the caller sent.\n return timingSafeEqual(hashToken(provided), hashToken(adminToken));\n}\n\nfunction hashToken(value: string): Buffer {\n return createHash('sha256').update(value, 'utf8').digest();\n}\n","/**\n * Adapter isolation: a failing adapter must not\n * prevent the server from starting or other adapters from working.\n *\n * `HttpProtocolAdapter`s are mounted at `adapter.mountPath` inside an\n * encapsulated Fastify plugin that never lets Fastify consume the request\n * body — the adapter's own transport (MCP's Streamable HTTP) reads\n * `request.raw` itself, so we register a wildcard content-type parser that\n * is a deliberate no-op, then hand the adapter the raw Node req/res and\n * `reply.hijack()` so Fastify does not also try to send a response.\n *\n * Fastify enforces `bodyLimit` *inside* the content-type parser — a\n * parser that never touches the payload never enforces it, so this mount had\n * no body cap at all, and the SDK's Streamable HTTP transport buffers the\n * whole request into memory with no cap of its own (unauthenticated, no\n * handshake needed). MOUNT_BODY_LIMIT_BYTES is enforced by tallying bytes on\n * the underlying *socket* (not the request stream) as they arrive and\n * destroying the connection past the cap: `Content-Length` alone is\n * insufficient (chunked encoding has none), and observing the socket's own\n * 'data' event doesn't compete with however the adapter reads the body —\n * Node's HTTP module already keeps the socket flowing internally to feed its\n * parser, so an extra listener is pure fan-out, never a second consumer. It\n * can only ever say \"stop\", never corrupt or steal a byte the adapter needs.\n */\n\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';\nimport {\n type AdapterHealth,\n type Clock,\n CommerceError,\n type HttpProtocolAdapter,\n isHttpProtocolAdapter,\n type Logger,\n type ProtocolAdapter,\n type ProtocolAdapterContext,\n toErrorEnvelope,\n} from '../core/index.js';\n\n/**\n * A separate, larger (1 MB) cap for this mount is tempting — MCP tool\n * payloads can legitimately carry more data than a REST-style invoke body.\n * It matches `server.ts`'s route `bodyLimit` (256 KB) anyway: the adapter\n * closes the batch-fan-out half (bounded concurrency, stop-on-disconnect),\n * but the SDK transport still parses the whole array before adapter code\n * ever runs, so\n * this cap is the only lever left on the first-request parse-time memory\n * spike, and a smaller cap admits proportionally fewer batch entries. One\n * documented number is also simpler to state correctly than \"two caps,\n * enforced two different ways\" — which is how `/mcp` ended up with no cap\n * at all in the first place (see docs/security.md). `server.ts` imports\n * this rather than defining its own, so there is exactly one number, not\n * two that happen to currently agree.\n */\nexport const MOUNT_BODY_LIMIT_BYTES = 256 * 1024;\n\nexport interface AdapterRuntime {\n readonly adapter: ProtocolAdapter;\n /** Set only when `start()` threw; a failed adapter is never re-queried live. */\n readonly startFailure?: AdapterHealth;\n}\n\nexport interface StartAndMountOptions {\n readonly server: FastifyInstance;\n readonly adapters: readonly ProtocolAdapter[];\n readonly context: ProtocolAdapterContext;\n readonly logger: Logger;\n readonly clock: Clock;\n}\n\nexport async function startAndMountAdapters(\n options: StartAndMountOptions,\n): Promise<AdapterRuntime[]> {\n // Before anything starts: two adapters claiming the same path is a\n // composition-root bug, not a runtime condition. Fastify would only notice\n // it inside deferred route registration and fail `server.ready()` with an\n // opaque FST_ERR_DUPLICATED_ROUTE naming neither adapter.\n assertNoRouteConflicts(options.adapters);\n\n const runtimes: AdapterRuntime[] = [];\n\n for (const adapter of options.adapters) {\n // Pre-scope the logger so every adapter's own log calls carry\n // `adapter: <name>` automatically — the adapter never has to remember to\n // add it itself.\n const adapterLogger = options.logger.child({ adapter: adapter.name });\n const adapterContext: ProtocolAdapterContext = { ...options.context, logger: adapterLogger };\n\n try {\n await adapter.start(adapterContext);\n } catch (error) {\n const detail = describeError(error);\n adapterLogger.error(\n { err: detail },\n 'Protocol adapter failed to start; gateway continues without it',\n );\n runtimes.push({\n adapter,\n startFailure: { status: 'fail', detail, checkedAt: options.clock.nowIso() },\n });\n continue;\n }\n\n if (isHttpProtocolAdapter(adapter)) {\n mountHttpAdapter(options.server, adapter, adapterLogger);\n }\n runtimes.push({ adapter });\n }\n\n return runtimes;\n}\n\ninterface RouteClaim {\n readonly adapter: string;\n readonly path: string;\n /** A mount also owns everything below its path, through its `/*` wildcard. */\n readonly wildcard: boolean;\n readonly method: 'ALL' | 'GET' | 'POST';\n}\n\nfunction routeClaims(adapters: readonly ProtocolAdapter[]): RouteClaim[] {\n const claims: RouteClaim[] = [];\n for (const adapter of adapters) {\n if (!isHttpProtocolAdapter(adapter)) continue;\n claims.push({\n adapter: adapter.name,\n path: adapter.mountPath.replace(/\\/+$/, ''),\n wildcard: true,\n method: 'ALL',\n });\n for (const route of adapter.additionalHttpRoutes ?? []) {\n claims.push({\n adapter: adapter.name,\n path: route.path.replace(/\\/+$/, ''),\n wildcard: false,\n method: route.method,\n });\n }\n }\n return claims;\n}\n\nfunction claimsCollide(a: RouteClaim, b: RouteClaim): boolean {\n if (a.wildcard && (b.path === a.path || b.path.startsWith(`${a.path}/`))) return true;\n if (b.wildcard && a.path.startsWith(`${b.path}/`)) return true;\n return a.path === b.path && (a.method === b.method || a.method === 'ALL' || b.method === 'ALL');\n}\n\n/**\n * Only *cross-adapter* claims conflict. An adapter serving a fixed route under\n * its own mount is fine — Fastify prefers a static route over a wildcard — and\n * is how a protocol that pins a sub-path stays self-contained.\n */\nfunction assertNoRouteConflicts(adapters: readonly ProtocolAdapter[]): void {\n const claims = routeClaims(adapters);\n for (const [index, a] of claims.entries()) {\n for (const b of claims.slice(index + 1)) {\n if (a.adapter === b.adapter || !claimsCollide(a, b)) continue;\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Protocol adapters \"${a.adapter}\" and \"${b.adapter}\" both claim the HTTP path \"${b.path}\"; each adapter path must be served by exactly one adapter`,\n { details: { adapters: [a.adapter, b.adapter], path: b.path } },\n );\n }\n }\n}\n\n/**\n * The body limit and the per-tool-call semaphore\n * (`protocol-mcp`'s MAX_CONCURRENT_TOOL_CALLS) both bound *what happens\n * after* a request is parsed — neither sees the SDK's own JSON.parse of the\n * request body, which was measured spiking one 256 KB batch\n * request's heap by ~106 MB (26 -> 132 MB) before GC reclaims it. Not a\n * leak, but unbounded concurrency times an unbounded spike is unbounded\n * memory: a 20-concurrent-batches probe (262 KB each) is\n * the only concurrency level this has actually been measured safe at (peak\n * RSS 368 MB, fully reclaimed) — so 20 is the cap, not a rounder guess.\n * compose sets no memory limit, so this is the only thing standing between\n * \"~40 connections\" and a multi-gigabyte spike.\n */\nexport const MOUNT_MAX_CONCURRENT_REQUESTS = 20;\n/** Short and blunt on purpose: this is a parse-time spike that clears in\n * well under a second once GC runs, not an outage a client should back off\n * from for long. */\nconst MOUNT_BUSY_RETRY_AFTER_SECONDS = 1;\n\nfunction mountHttpAdapter(\n server: FastifyInstance,\n adapter: HttpProtocolAdapter,\n logger: Logger,\n): void {\n const mountPath = adapter.mountPath;\n const wildcard = mountPath.endsWith('/') ? `${mountPath}*` : `${mountPath}/*`;\n const additionalRoutes = adapter.additionalHttpRoutes ?? [];\n // One counter for the whole adapter, mount and fixed routes alike: the cap\n // bounds what this adapter can be made to parse concurrently, and a second\n // door into the same adapter would be a way around it.\n let inFlight = 0;\n\n void server.register(async (instance) => {\n // Fastify pre-registers exact-match parsers for application/json and\n // text/plain that run BEFORE the '*' fallback (checked in getParser()).\n // MCP clients send application/json, so without an exact no-op here\n // Fastify's built-in JSON parser drains request.raw before the adapter's\n // own transport ever reads it -> the adapter sees an empty stream.\n instance.addContentTypeParser(\n ['application/json', 'text/plain'],\n (_request, _payload, done) => {\n done(null);\n },\n );\n instance.addContentTypeParser('*', (_request, _payload, done) => {\n done(null);\n });\n\n const makeHandler =\n (handleHttp: (req: IncomingMessage, res: ServerResponse) => Promise<void>) =>\n async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n if (inFlight >= MOUNT_MAX_CONCURRENT_REQUESTS) {\n // Reject before the SDK ever sees the body — the whole point is to\n // never let a request past this line start the parse that spikes\n // memory. No body-limit enforcement needed either: nothing here has\n // read a byte of it yet.\n const error = new CommerceError(\n 'GATEWAY_BUSY',\n 'Too many requests already parsing on this mount; retry shortly.',\n );\n reply\n .status(error.httpStatus)\n .header('retry-after', String(MOUNT_BUSY_RETRY_AFTER_SECONDS))\n .send(toErrorEnvelope(error));\n return;\n }\n inFlight += 1;\n try {\n const stopEnforcing = enforceMountBodyLimit(\n request.raw,\n reply.raw,\n MOUNT_BODY_LIMIT_BYTES,\n logger,\n );\n try {\n await handleHttp(request.raw, reply.raw);\n } catch (error) {\n logger.error({ err: describeError(error) }, 'Protocol adapter request handler threw');\n if (!reply.raw.headersSent) {\n reply.raw.statusCode = 500;\n reply.raw.end();\n }\n }\n stopEnforcing();\n reply.hijack();\n } finally {\n // Always released, even on a throw above — a stranded count would\n // shrink the effective cap by one forever and eventually 503 every\n // request on this mount permanently, which is worse than the\n // problem this exists to solve.\n inFlight -= 1;\n }\n };\n\n const mountHandler = makeHandler((req, res) => adapter.handleHttp(req, res));\n instance.all(mountPath, mountHandler);\n instance.all(wildcard, mountHandler);\n\n for (const route of additionalRoutes) {\n instance.route({\n method: route.method,\n url: route.path,\n handler: makeHandler((req, res) => route.handleHttp(req, res)),\n });\n }\n });\n}\n\nfunction enforceMountBodyLimit(\n req: IncomingMessage,\n res: ServerResponse,\n maxBytes: number,\n logger: Logger,\n): () => void {\n const socket = req.socket;\n let total = 0;\n let stopped = false;\n const onData = (chunk: Buffer): void => {\n total += chunk.length;\n if (total > maxBytes) {\n stop();\n logger.warn({ maxBytes }, 'Request body exceeded the mount body limit; connection closed');\n // a bare socket.destroy() gives the client ECONNRESET\n // with nothing naming the cap — right for an attacker, wrong for a\n // legitimate client the first time a tool payload crosses the limit.\n // Attempt a 413 with a JSON-RPC error body first, then destroy once it\n // has actually flushed. If the adapter already started writing its own\n // response, headersSent is true and there is nothing left to say —\n // just destroy. Never read the rest of the oversized body to be polite\n // about it; that defeats the point of the cap.\n if (!res.headersSent) {\n const body = JSON.stringify({\n jsonrpc: '2.0',\n id: null,\n error: { code: -32600, message: `Request body exceeds the ${maxBytes}-byte mount limit` },\n });\n try {\n res.writeHead(413, {\n 'content-type': 'application/json',\n 'content-length': Buffer.byteLength(body),\n });\n // `.end()`'s callback fires once the write is handed to the OS,\n // not once the peer has actually received it, so even a\n // best-effort destroy afterward can occasionally race a\n // still-in-flight response and truncate it (the client sees a\n // bare ECONNRESET instead of the 413 body). That is an accepted\n // trade — see \"attempt\" in the comment above — over leaving the\n // read side open, which would undo the whole point of this cap\n // (an attacker's still-arriving bytes must not keep flowing to\n // whatever is reading `req`).\n res.end(body, () => socket.destroy());\n return;\n } catch {\n // Fall through to a bare destroy below — e.g. the socket was\n // already gone by the time we tried to write.\n }\n }\n socket.destroy();\n }\n };\n const stop = (): void => {\n if (stopped) return;\n stopped = true;\n // A keep-alive connection carries many requests, and this function adds\n // a 'close' listener per request. Removing only the 'data' listener here\n // would leave the 'close' one to pile up, one per request, until the\n // connection finally closed (MaxListenersExceeded at request 11). Remove\n // both.\n socket.removeListener('data', onData);\n socket.removeListener('close', stop);\n };\n socket.on('data', onData);\n socket.once('close', stop);\n return stop;\n}\n\nexport async function getAdapterHealth(\n runtime: AdapterRuntime,\n clock: Clock,\n): Promise<AdapterHealth> {\n if (runtime.startFailure) return runtime.startFailure;\n try {\n return await runtime.adapter.health();\n } catch (error) {\n return { status: 'fail', detail: describeError(error), checkedAt: clock.nowIso() };\n }\n}\n\nexport async function stopAdapters(\n runtimes: readonly AdapterRuntime[],\n logger: Logger,\n): Promise<void> {\n for (const runtime of runtimes) {\n try {\n await runtime.adapter.stop();\n } catch (error) {\n logger\n .child({ adapter: runtime.adapter.name })\n .error({ err: describeError(error) }, 'Protocol adapter failed to stop cleanly');\n }\n }\n}\n\nfunction describeError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * Public (secret-free) projection of a `CommerceResource`.\n *\n * `handler.headers` may carry resolved backend secrets (e.g. an\n * `Authorization` value built from `${API_KEY}`) — never expose it on a\n * public discovery surface (`GET /api/resources`, `.well-known`).\n */\nimport type { CommerceResource } from '../core/index.js';\n\nexport interface PublicResource {\n readonly id: string;\n readonly name: string;\n readonly description?: string;\n readonly inputSchema?: Record<string, unknown>;\n readonly outputSchema?: Record<string, unknown>;\n readonly method: string;\n readonly pricing: CommerceResource['pricing'];\n readonly exposedVia: readonly string[];\n readonly paymentMethods: readonly string[];\n}\n\nexport function toPublicResource(resource: CommerceResource): PublicResource {\n return {\n id: resource.id,\n name: resource.name,\n ...(resource.description !== undefined ? { description: resource.description } : {}),\n ...(resource.inputSchema !== undefined ? { inputSchema: resource.inputSchema } : {}),\n ...(resource.outputSchema !== undefined ? { outputSchema: resource.outputSchema } : {}),\n method: resource.handler.method,\n pricing: resource.pricing,\n exposedVia: resource.exposedVia,\n paymentMethods: resource.paymentMethods,\n };\n}\n","/**\n * `GET /ready` readiness computation: 503 unless the store, every configured\n * protocol adapter, AND every payment provider are healthy. `status: 'warn'`\n * is treated as still-serving (degraded); only `status: 'fail'` blocks\n * readiness — applied uniformly to all three kinds of dependency.\n *\n * Payment providers are consulted here alongside the store and protocol\n * adapters: without that, a gateway whose x402 RPC is unreachable reports\n * `ready: true` and goes on serving 402 challenges it cannot honour. `fail`, not `warn`, blocks readiness for a provider — same\n * threshold as the store and adapters, not a special case: a broken payment\n * provider is not \"degraded but serving\", it is a broken core promise for\n * every resource that requires payment, exactly like a store that cannot\n * record or a required adapter that cannot route.\n *\n * The raw `detail` a store/adapter/provider health() implementation\n * returns (or a raw thrown Error's message) is exactly the kind of internal\n * detail exists to keep off a client-visible field — and this is an\n * unauthenticated route. The client only ever sees one of a small fixed\n * vocabulary; the raw detail is logged for the operator.\n *\n * `/ready` is itself unauthenticated, with no cache and no rate\n * limit, and `checkReadiness` calls every dependency's `health()` fresh on\n * every request — on a commercial RPC provider that is a live, billed\n * upstream call an attacker spends for free (measured: 20 requests -> 60\n * upstream JSON-RPC calls). `createReadinessProbe` memoises the result for\n * READINESS_TTL_MS and collapses concurrent callers onto one in-flight\n * evaluation, so a burst of N requests produces at most one real check.\n */\nimport type { AdapterHealth, Clock, Logger, PaymentProvider, ReceiptStore } from '../core/index.js';\nimport { type AdapterRuntime, getAdapterHealth } from './adapters.js';\n\nexport interface ReadinessCheck {\n readonly name: string;\n readonly status: AdapterHealth['status'];\n readonly detail?: string;\n}\n\nexport interface ReadinessResult {\n readonly ready: boolean;\n readonly store: ReadinessCheck;\n readonly adapters: readonly ReadinessCheck[];\n readonly paymentProviders: readonly ReadinessCheck[];\n}\n\nexport interface CheckReadinessOptions {\n readonly store: ReceiptStore;\n readonly adapterRuntimes: readonly AdapterRuntime[];\n readonly paymentProviders: readonly PaymentProvider[];\n readonly clock: Clock;\n readonly logger: Logger;\n}\n\nconst STORE_DETAIL: Readonly<Record<AdapterHealth['status'], string | undefined>> = {\n pass: undefined,\n warn: 'store-degraded',\n fail: 'store-unwritable',\n};\n\nconst ADAPTER_DETAIL: Readonly<Record<AdapterHealth['status'], string | undefined>> = {\n pass: undefined,\n warn: 'adapter-degraded',\n fail: 'adapter-unreachable',\n};\n\nconst PAYMENT_PROVIDER_DETAIL: Readonly<Record<AdapterHealth['status'], string | undefined>> = {\n pass: undefined,\n warn: 'payment-provider-degraded',\n fail: 'payment-provider-unreachable',\n};\n\nexport async function checkReadiness(options: CheckReadinessOptions): Promise<ReadinessResult> {\n let storeHealth: AdapterHealth;\n let storeThrew = false;\n try {\n storeHealth = await options.store.health();\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n options.logger.error({ err: message }, 'store.health() threw');\n storeHealth = { status: 'fail', checkedAt: options.clock.nowIso() };\n storeThrew = true;\n }\n if (storeHealth.detail !== undefined) {\n options.logger.debug(\n { detail: storeHealth.detail },\n 'store health detail (not sent to the client)',\n );\n }\n\n const adapterChecks = await Promise.all(\n options.adapterRuntimes.map(async (runtime): Promise<ReadinessCheck> => {\n const health = await getAdapterHealth(runtime, options.clock);\n if (health.detail !== undefined) {\n options.logger.debug(\n { adapter: runtime.adapter.name, detail: health.detail },\n 'adapter health detail (not sent to the client)',\n );\n }\n const detail = ADAPTER_DETAIL[health.status];\n return {\n name: runtime.adapter.name,\n status: health.status,\n ...(detail !== undefined ? { detail } : {}),\n };\n }),\n );\n\n const paymentProviderChecks = await Promise.all(\n options.paymentProviders.map(async (provider): Promise<ReadinessCheck> => {\n let health: AdapterHealth;\n try {\n health = await provider.health();\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n options.logger.error(\n { err: message, provider: provider.name },\n 'payment provider health() threw',\n );\n health = { status: 'fail', checkedAt: options.clock.nowIso() };\n }\n if (health.detail !== undefined) {\n options.logger.debug(\n { provider: provider.name, detail: health.detail },\n 'payment provider health detail (not sent to the client)',\n );\n }\n const detail = PAYMENT_PROVIDER_DETAIL[health.status];\n return {\n name: provider.name,\n status: health.status,\n ...(detail !== undefined ? { detail } : {}),\n };\n }),\n );\n\n const storeReady = storeHealth.status !== 'fail';\n const adaptersReady = adapterChecks.every((check) => check.status !== 'fail');\n const paymentProvidersReady = paymentProviderChecks.every((check) => check.status !== 'fail');\n const storeDetail = storeThrew ? 'store-unreachable' : STORE_DETAIL[storeHealth.status];\n\n return {\n ready: storeReady && adaptersReady && paymentProvidersReady,\n store: {\n name: 'store',\n status: storeHealth.status,\n ...(storeDetail !== undefined ? { detail: storeDetail } : {}),\n },\n adapters: adapterChecks,\n paymentProviders: paymentProviderChecks,\n };\n}\n\n/** A readiness probe does not need sub-second freshness: a real outage is\n * still caught within one TTL window, and this is short enough that a burst\n * of requests during a genuine state change (e.g. right after startup) isn't\n * stuck looking at a stale answer for long. */\nexport const READINESS_TTL_MS = 2_000;\n\nexport interface ReadinessProbe {\n check(): Promise<ReadinessResult>;\n}\n\nexport function createReadinessProbe(\n options: CheckReadinessOptions,\n ttlMs: number = READINESS_TTL_MS,\n): ReadinessProbe {\n let cached: { readonly result: ReadinessResult; readonly at: number } | undefined;\n let inFlight: Promise<ReadinessResult> | undefined;\n\n return {\n async check(): Promise<ReadinessResult> {\n const now = options.clock.monotonicMs();\n if (cached && now - cached.at < ttlMs) return cached.result;\n if (inFlight) return inFlight;\n\n inFlight = checkReadiness(options)\n .then((result) => {\n cached = { result, at: options.clock.monotonicMs() };\n return result;\n })\n .finally(() => {\n inFlight = undefined;\n });\n return inFlight;\n },\n };\n}\n","/**\n * `GET /.well-known/agent-commerce` — merchant + every adapter/provider/store\n * `AdapterDescriptor`, protocol/spec versions. This route is unauthenticated\n * by design, so nothing here may be a credential.\n *\n * The x402 settlement destination (`payTo`), `network` and `asset` ARE\n * public information — a payer needs them (plus scheme/amount, which travel\n * in the challenge's `accepts` array) to construct a payment, and `payTo` is\n * visible on-chain the moment any transfer lands. `rpcUrl` is different and\n * is deliberately NOT published here: every commercial EVM RPC\n * provider embeds an API key in the URL itself (Alchemy's `/v2/<KEY>`,\n * Infura's `/v3/<KEY>`, QuickNode's per-endpoint token) — on any non-local\n * deployment, echoing it back on an open route hands out a live credential\n * to anyone who asks. The facilitator URL is withheld for the same reason,\n * and the facilitator private key never appears at all. `doctor`'s\n * live/local cross-check (src/cli) only reads `asset`/`network`/`payTo` from\n * this document, so dropping `rpcUrl` does not affect it.\n *\n * `WellKnownDocument` is also exported via the package's\n * `./well-known.js` subpath (non-frozen — see docs/contracts.md's change\n * log) so `demo/dashboard`'s hand-maintained mirror of this shape\n * (`types.ts`) can assert assignability against the real type instead of\n * silently drifting — which is exactly how it twice shipped `rpcUrl` as\n * non-optional after this file stopped sending it. Consuming this as\n * `import type` only is what keeps the dashboard's browser bundle free of\n * Fastify/pino/better-sqlite3: a type-only import is erased entirely by any\n * TypeScript-aware bundler (esbuild, swc, tsc), independent of whatever\n * runtime code this file also happens to export — the same property\n * `src/core`'s `./execution` subpath already relies on.\n */\n\nimport type { GatewayConfig } from '../config/index.js';\nimport type {\n AdapterDescriptor,\n AdapterHealth,\n Clock,\n PaymentProvider,\n ReceiptStore,\n} from '../core/index.js';\nimport {\n type DeploymentMode,\n requireNetworkProfile,\n resolveDeploymentMode,\n} from '../payments/x402/networks.js';\nimport { PACKAGE_VERSION } from '../version.js';\nimport { type AdapterRuntime, getAdapterHealth } from './adapters.js';\n\n/**\n * The spec version is deliberately NOT derived from `PACKAGE_VERSION`. It\n * names the wire contract a client negotiates against, which changes only\n * when that contract does — a patch release of this package speaks the same\n * spec, and announcing a new one on every version bump would tell every\n * client the protocol moved when it did not.\n */\nconst GATEWAY_SUPPORTED_SPEC = 'agent-commerce/v1.0.0';\n\n/**\n * The protocol block as published, not as configured.\n *\n * Built field by field rather than spread from `config.protocols`, because that\n * object carries `protocols.acp.auth.token` - a live credential - plus the\n * idempotency database path and the operation-to-resource mapping. This route\n * is unauthenticated, so a future config field must be added here deliberately\n * to become public, never by inheriting a shape.\n */\nexport interface WellKnownProtocols {\n readonly http: { readonly enabled: boolean };\n readonly mcp: { readonly enabled: boolean; readonly mountPath: string };\n readonly a2a: { readonly enabled: boolean; readonly mountPath: string };\n readonly acp: { readonly enabled: boolean; readonly mountPath: string };\n}\n\nexport interface WellKnownDocument {\n readonly gateway: { readonly implementationVersion: string; readonly supportedSpec: string };\n readonly merchant: GatewayConfig['merchant'];\n readonly protocols: WellKnownProtocols;\n readonly adapters: ReadonlyArray<AdapterDescriptor & { readonly health: AdapterHealth }>;\n readonly paymentProviders: readonly AdapterDescriptor[];\n readonly store: AdapterDescriptor;\n readonly payments: {\n readonly x402?: {\n readonly enabled: boolean;\n readonly network: string;\n readonly asset: string;\n readonly assetName: string;\n readonly assetVersion: string;\n readonly assetDecimals: number;\n readonly payTo: string;\n readonly maxTimeoutSeconds: number;\n readonly facilitator: { readonly mode: 'local' | 'remote' };\n /** What this deployment actually is. */\n readonly mode: DeploymentMode;\n };\n };\n}\n\nexport interface BuildWellKnownOptions {\n readonly config: GatewayConfig;\n readonly paymentProviders: readonly PaymentProvider[];\n readonly store: ReceiptStore;\n readonly adapterRuntimes: readonly AdapterRuntime[];\n readonly clock: Clock;\n}\n\n/**\n * Strips a health result down to what an anonymous caller may see.\n *\n * `/ready` already codifies this rule and maps `detail` to a fixed vocabulary,\n * because the raw string is exactly the internal detail an unauthenticated\n * route must not carry — `getAdapterHealth` puts `describeError()` there for a\n * thrown `health()`, and a start failure puts the raw throw message, routinely\n * a module path or an internal hostname. This route is the same trust level and\n * was returning it verbatim. `createGateway` is public API and accepts\n * arbitrary adapters, so \"our own adapters say nothing sensitive\" is not a\n * property this code can rely on.\n */\nfunction publicHealth(health: AdapterHealth): AdapterHealth {\n const { detail: _detail, ...rest } = health;\n return rest;\n}\n\nfunction publicProtocols(protocols: GatewayConfig['protocols']): WellKnownProtocols {\n return {\n http: { enabled: protocols.http.enabled },\n mcp: { enabled: protocols.mcp.enabled, mountPath: protocols.mcp.mountPath },\n a2a: { enabled: protocols.a2a.enabled, mountPath: protocols.a2a.mountPath },\n acp: { enabled: protocols.acp.enabled, mountPath: protocols.acp.mountPath },\n };\n}\n\nexport async function buildWellKnownDocument(\n options: BuildWellKnownOptions,\n): Promise<WellKnownDocument> {\n const adapters = await Promise.all(\n options.adapterRuntimes.map(async (runtime) => {\n const health = await getAdapterHealth(runtime, options.clock);\n return { ...runtime.adapter.descriptor, health: publicHealth(health) };\n }),\n );\n\n const x402 = options.config.payments.x402;\n\n return {\n gateway: {\n implementationVersion: PACKAGE_VERSION,\n supportedSpec: GATEWAY_SUPPORTED_SPEC,\n },\n merchant: options.config.merchant,\n protocols: publicProtocols(options.config.protocols),\n adapters,\n paymentProviders: options.paymentProviders.map((provider) => provider.descriptor),\n store: options.store.descriptor,\n payments: {\n ...(x402 !== undefined\n ? {\n x402: {\n enabled: x402.enabled,\n network: x402.network,\n asset: x402.asset,\n assetName: x402.assetName,\n assetVersion: x402.assetVersion,\n assetDecimals: x402.assetDecimals,\n payTo: x402.payTo,\n maxTimeoutSeconds: x402.maxTimeoutSeconds,\n // Never the signerPrivateKey, and never the facilitator URL:\n // a facilitator endpoint is a per-deployment operational detail\n // that can carry a tenant path or an API key, exactly like\n // `rpcUrl` above. Only whether it is local or remote is public.\n facilitator: { mode: x402.facilitator.mode },\n // Chain id 84532 is shared between the local dev chain and\n // public Base Sepolia, so the network id alone cannot say which\n // one a client is talking to. This can.\n mode: resolveDeploymentMode(\n requireNetworkProfile(x402.network, 'payments.x402.network'),\n x402.facilitator.mode,\n ),\n },\n }\n : {}),\n },\n };\n}\n","/**\n * The gateway's own HTTP surface (docs/contracts.md \"Gateway HTTP surface\").\n * Adapter mounting (e.g. `/mcp`) is handled separately in adapters.ts.\n */\n\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';\nimport type { GatewayConfig } from '../config/index.js';\nimport type { EventBus } from '../core/execution/index.js';\nimport {\n type CanonicalRequest,\n type Clock,\n CommerceError,\n type ExecutionPipeline,\n type Logger,\n PAYMENT_HEADER,\n PAYMENT_REQUIRED_HEADER,\n PAYMENT_RESPONSE_HEADER,\n type PaymentProvider,\n type ReceiptStore,\n type ResourceRegistry,\n toCommerceError,\n toErrorEnvelope,\n toPaymentRequiredEnvelope,\n} from '../core/index.js';\nimport { buildOperatorTokenHook } from './access-control.js';\nimport type { AdapterRuntime } from './adapters.js';\nimport { toPublicResource } from './public-resource.js';\nimport { createReadinessProbe } from './readiness.js';\nimport { buildWellKnownDocument } from './well-known.js';\n\nconst SSE_HEARTBEAT_MS = 15_000;\nconst MAX_SSE_SUBSCRIBERS = 32;\n\nexport interface RegisterRoutesOptions {\n readonly server: FastifyInstance;\n readonly config: GatewayConfig;\n readonly pipeline: ExecutionPipeline;\n readonly resources: ResourceRegistry;\n readonly store: ReceiptStore;\n readonly paymentProviders: readonly PaymentProvider[];\n readonly eventBus: EventBus;\n readonly clock: Clock;\n readonly adapterRuntimes: readonly AdapterRuntime[];\n readonly logger: Logger;\n}\n\nexport function registerRoutes(options: RegisterRoutesOptions): void {\n const { server } = options;\n\n // memoised + single-flight — see readiness.ts's own doc comment.\n // `options.adapterRuntimes` is mutated in place (pushed into) after\n // adapters start, so capturing the reference here is fine — the probe\n // always reads whatever it currently holds.\n const readinessProbe = createReadinessProbe({\n store: options.store,\n adapterRuntimes: options.adapterRuntimes,\n paymentProviders: options.paymentProviders,\n clock: options.clock,\n logger: options.logger,\n });\n\n server.get('/health', async () => ({ status: 'ok' }));\n\n server.get('/ready', async (_request, reply) => {\n const readiness = await readinessProbe.check();\n reply.status(readiness.ready ? 200 : 503);\n return readiness;\n });\n\n server.get('/.well-known/agent-commerce', async () =>\n buildWellKnownDocument({\n config: options.config,\n paymentProviders: options.paymentProviders,\n store: options.store,\n adapterRuntimes: options.adapterRuntimes,\n clock: options.clock,\n }),\n );\n\n server.get('/api/resources', async () => ({\n resources: options.resources.list().map(toPublicResource),\n }));\n\n server.post('/api/resources/:id/invoke', async (request, reply) => {\n await handleInvoke(request, reply, options);\n });\n\n // The admin-token gate is a per-route hook on each of these three\n // route definitions (not the global onRequest hook) — see\n // access-control.ts's file header for why. Fastify only invokes it once\n // routing has matched this exact route, so there is no percent-encoded\n // path string left for an attacker to disagree with the router about.\n const receiptsTokenHook = buildOperatorTokenHook(options.config.server.adminToken);\n const eventsTokenHook = buildOperatorTokenHook(options.config.server.adminToken);\n const eventsStreamTokenHook = buildOperatorTokenHook(options.config.server.adminToken);\n\n server.get('/api/receipts', { onRequest: receiptsTokenHook }, async (request, reply) => {\n try {\n const limit = parseLimit((request.query as Record<string, unknown>)['limit']);\n return { receipts: await options.store.listReceipts(limit !== undefined ? { limit } : {}) };\n } catch (error) {\n const commerceError = toCommerceError(error);\n reply.status(commerceError.httpStatus).send(toErrorEnvelope(commerceError));\n return undefined;\n }\n });\n\n server.get('/api/events', { onRequest: eventsTokenHook }, async (request, reply) => {\n try {\n const limit = parseLimit((request.query as Record<string, unknown>)['limit']);\n return { events: await options.store.listEvents(limit !== undefined ? { limit } : {}) };\n } catch (error) {\n const commerceError = toCommerceError(error);\n reply.status(commerceError.httpStatus).send(toErrorEnvelope(commerceError));\n return undefined;\n }\n });\n\n let activeSseSubscribers = 0;\n\n server.get('/api/events/stream', { onRequest: eventsStreamTokenHook }, (request, reply) => {\n // cap concurrent subscribers — the token hook above already\n // rejects an unauthenticated client before this handler runs; this cap\n // is about an *authenticated* client that never reads, which would\n // otherwise let Node buffer indefinitely, N times over.\n if (activeSseSubscribers >= MAX_SSE_SUBSCRIBERS) {\n reply.status(503).send({\n status: 'error',\n code: 'UNAVAILABLE',\n message: 'Too many event-stream subscribers',\n });\n return;\n }\n reply.raw.writeHead(200, {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive',\n });\n // Increment only after writeHead succeeds: if it threw, cleanup() below\n // was never registered, and incrementing first would leak the slot\n // permanently (after MAX_SSE_SUBSCRIBERS such leaks, the route is dead).\n activeSseSubscribers += 1;\n reply.raw.write(': connected\\n\\n');\n\n // Backpressure: write() returning false means the socket buffer\n // is full. Drop frames — not queue them — until 'drain'; an SSE feed is\n // \"latest state\", not a guaranteed-delivery log, and queuing unboundedly\n // is the exact memory-growth problem this is meant to avoid.\n let writable = true;\n reply.raw.on('drain', () => {\n writable = true;\n });\n\n // no `event:` line — the dashboard's EventSource only listens for\n // the default `message` type, and a named event never reaches onmessage\n // (onopen still fires, so the client reports \"live\" over a frozen feed).\n // `data:` already carries `type` in the serialised payload.\n //\n // queueMicrotask decouples fan-out from the caller: EventBus#emit() is\n // awaited inside the execution pipeline, so writing synchronously here\n // would add a slow SSE reader's latency to the payment path.\n const unsubscribe = options.eventBus.subscribe((event) => {\n queueMicrotask(() => {\n if (!writable) return;\n writable = reply.raw.write(`data: ${JSON.stringify(event)}\\n\\n`);\n });\n });\n\n const heartbeat = setInterval(() => {\n if (!writable) return;\n writable = reply.raw.write(': heartbeat\\n\\n');\n }, SSE_HEARTBEAT_MS);\n heartbeat.unref();\n\n // Guards against a double-decrement if both 'close' and 'error' fire for\n // the same connection (never actually observed — 40 connect/destroy\n // cycles could not trigger it — but the guard is one line and removes\n // the question).\n let cleanedUp = false;\n const cleanup = (): void => {\n if (cleanedUp) return;\n cleanedUp = true;\n clearInterval(heartbeat);\n unsubscribe();\n activeSseSubscribers -= 1;\n };\n request.raw.on('close', cleanup);\n reply.raw.on('error', cleanup);\n\n reply.hijack();\n });\n}\n\nasync function handleInvoke(\n request: FastifyRequest,\n reply: FastifyReply,\n options: RegisterRoutesOptions,\n): Promise<void> {\n const resourceId = (request.params as { id: string }).id;\n\n try {\n const resource = options.resources.get(resourceId);\n if (!resource || !resource.exposedVia.includes('http')) {\n throw new CommerceError('RESOURCE_NOT_FOUND', `Resource \"${resourceId}\" was not found`, {\n requestId: request.id,\n resourceId,\n });\n }\n\n const paymentHeader = request.headers[PAYMENT_HEADER];\n const paymentValue = Array.isArray(paymentHeader) ? paymentHeader[0] : paymentHeader;\n\n // The gateway does not decide which rail a resource uses — that's the\n // canonical resource's job (mirrors the protocol-side fix in the MCP\n // adapter). Derive the method from resource.paymentMethods instead of\n // hard-coding 'x402'. If a proof arrives for a resource with no payment\n // method configured, drop it rather than inventing a rail: the pipeline\n // will treat the resource as free (or reject it) on its own terms.\n const paymentMethod = resource.paymentMethods[0];\n const payment =\n paymentValue !== undefined && paymentMethod !== undefined\n ? { method: paymentMethod, payload: paymentValue }\n : undefined;\n\n const canonicalRequest: CanonicalRequest = {\n requestId: request.id,\n resourceId,\n input: request.body ?? {},\n protocol: 'http',\n receivedAt: options.clock.nowIso(),\n ...(payment !== undefined ? { payment } : {}),\n };\n\n const outcome = await options.pipeline.execute(canonicalRequest);\n\n if (outcome.kind === 'payment-required') {\n const envelope = toPaymentRequiredEnvelope(outcome);\n if (envelope.payment.envelope !== undefined) {\n // x402 v2 clients read the challenge from this header and never look\n // at the body. The body is still sent — it is richer, and it is the\n // only channel the MCP surface has — but the header is what makes an\n // off-the-shelf client able to pay.\n reply.header(PAYMENT_REQUIRED_HEADER, encodeHeaderDocument(envelope.payment.envelope));\n }\n // A challenge is per-request (fresh nonce window, fresh expiry). Caching\n // one would hand a later buyer an expired offer.\n reply.header('cache-control', 'no-store');\n reply.status(402).send(envelope);\n return;\n }\n\n if (outcome.payment) {\n reply.header(PAYMENT_RESPONSE_HEADER, encodePaymentSummary(outcome.payment));\n }\n reply.status(outcome.backendStatus).send(outcome.body);\n } catch (error) {\n const commerceError = toCommerceError(error);\n // a backend failure after successful settlement carries the\n // settlement summary on details.payment (pipeline.ts) — set the same\n // header the success path sets, so the buyer isn't told strictly less\n // about their own payment on the error path than on the happy path.\n const settledPayment = errorPaymentSummary(commerceError);\n if (settledPayment !== undefined) {\n reply.header(PAYMENT_RESPONSE_HEADER, encodePaymentSummary(settledPayment));\n }\n reply.status(commerceError.httpStatus).send(toErrorEnvelope(commerceError));\n }\n}\n\ninterface PaymentSummary {\n readonly status: string;\n readonly provider: string;\n readonly amount: string;\n readonly currency: string;\n readonly network?: string;\n readonly externalReference?: string;\n}\n\nfunction errorPaymentSummary(\n error: ReturnType<typeof toCommerceError>,\n): PaymentSummary | undefined {\n const payment = error.details?.['payment'];\n if (typeof payment !== 'object' || payment === null) return undefined;\n const rec = payment as Record<string, unknown>;\n const { status, provider, amount, currency, network, externalReference } = rec;\n if (\n typeof status !== 'string' ||\n typeof provider !== 'string' ||\n typeof amount !== 'string' ||\n typeof currency !== 'string'\n ) {\n return undefined;\n }\n return {\n status,\n provider,\n amount,\n currency,\n ...(typeof network === 'string' ? { network } : {}),\n ...(typeof externalReference === 'string' ? { externalReference } : {}),\n };\n}\n\n/**\n * Base64 of a JSON document, the encoding every x402 v2 payment header uses.\n *\n * Hand-rolled rather than imported from the x402 SDK on purpose: this module\n * is reachable from the package's main entry point, which must import zero\n * optional peers, and it is two lines.\n */\nfunction encodeHeaderDocument(document: unknown): string {\n return Buffer.from(JSON.stringify(document), 'utf8').toString('base64');\n}\n\n/**\n * The settlement result, in the shape an x402 v2 client decodes from\n * `PAYMENT-RESPONSE` (`SettleResponse`), mapped from the canonical\n * {@link PaymentResult} the pipeline produced.\n *\n * `provider`, `amount` and `currency` are ours and are additive: a v2 client\n * reads the fields it knows and ignores the rest.\n */\nfunction encodePaymentSummary(payment: PaymentSummary): string {\n return encodeHeaderDocument({\n success: payment.status === 'settled',\n transaction: payment.externalReference ?? '',\n network: payment.network ?? '',\n status: payment.status,\n provider: payment.provider,\n amount: payment.amount,\n currency: payment.currency,\n ...(payment.externalReference !== undefined\n ? { externalReference: payment.externalReference }\n : {}),\n });\n}\n\n/** Undefined = no limit given / unparseable (caller applies its own default). A\n * parseable but non-positive value (SQLite treats a negative LIMIT as\n * unbounded) is a caller error, not silently \"no limit\". */\nfunction parseLimit(value: unknown): number | undefined {\n if (Array.isArray(value)) return parseLimit(value[0]);\n let n: number | undefined;\n if (typeof value === 'number' && Number.isFinite(value)) n = Math.trunc(value);\n else if (typeof value === 'string' && value.length > 0) {\n const parsed = Number(value);\n if (Number.isFinite(parsed)) n = Math.trunc(parsed);\n }\n if (n === undefined) return undefined;\n if (n <= 0) {\n throw new CommerceError(\n 'INPUT_INVALID',\n `Query parameter \"limit\" must be a positive integer (got ${n})`,\n {\n details: { field: 'limit' },\n },\n );\n }\n return n;\n}\n","/**\n * `createGateway()` — the Fastify server. Fully usable (and tested) with\n * fakes, without `main.ts` (docs/contracts.md \"Composition root\").\n */\n\nimport Fastify, { type FastifyInstance } from 'fastify';\nimport type { GatewayConfig } from '../config/index.js';\nimport {\n createEventBus,\n createExecutionPipeline,\n createResourceRegistry,\n HttpBackendExecutor,\n} from '../core/execution/index.js';\nimport {\n type BackendExecutor,\n type Clock,\n type ExecutionPipeline,\n type IdGenerator,\n type Logger,\n type PaymentProvider,\n type ProtocolAdapter,\n type ProtocolAdapterContext,\n type ReceiptStore,\n type ResourceRegistry,\n systemClock,\n} from '../core/index.js';\nimport { buildAccessControlHook } from './access-control.js';\nimport {\n type AdapterRuntime,\n MOUNT_BODY_LIMIT_BYTES,\n startAndMountAdapters,\n stopAdapters,\n} from './adapters.js';\nimport { createDefaultIdGenerator } from './ids.js';\nimport { buildNotFoundHandler, createGatewayLogger, fastifyLoggerOptions } from './logger.js';\nimport { registerRoutes } from './routes.js';\n\nconst REQUEST_ID_HEADER = 'x-request-id';\n// an unvalidated caller-supplied id becomes the audit trail's\n// correlation key — a caller could reuse a legitimate flow's id to conflate\n// records, or write an unbounded string into every row. A client id is only\n// accepted in this constrained form; anything else gets a gateway-minted one.\nconst CLIENT_REQUEST_ID_PATTERN = /^[A-Za-z0-9._:-]{1,64}$/;\n\nexport interface GatewayOptions {\n readonly config: GatewayConfig;\n readonly store: ReceiptStore;\n readonly paymentProviders: readonly PaymentProvider[];\n readonly protocolAdapters: readonly ProtocolAdapter[];\n readonly logger?: Logger;\n readonly clock?: Clock;\n readonly ids?: IdGenerator;\n /** Override for tests. */\n readonly backend?: BackendExecutor;\n}\n\nexport interface GatewayInstance {\n readonly pipeline: ExecutionPipeline;\n readonly resources: ResourceRegistry;\n listen(): Promise<{ url: string }>;\n close(): Promise<void>;\n /** Fastify instance, for `.inject()` in tests. */\n readonly server: FastifyInstance;\n}\n\nexport async function createGateway(options: GatewayOptions): Promise<GatewayInstance> {\n const clock = options.clock ?? systemClock;\n const ids = options.ids ?? createDefaultIdGenerator();\n const logger = options.logger ?? createGatewayLogger({ name: options.config.merchant.id }).core;\n const backend = options.backend ?? new HttpBackendExecutor({ logger });\n\n const resources = createResourceRegistry(options.config.resources);\n const eventBus = createEventBus({ store: options.store, logger });\n const pipeline = createExecutionPipeline({\n resources,\n paymentProviders: options.paymentProviders,\n store: options.store,\n backend,\n events: eventBus,\n logger,\n clock,\n ids,\n });\n\n const server = Fastify({\n // One number for both surfaces — see adapters.ts's doc comment\n // on MOUNT_BODY_LIMIT_BYTES for why they're enforced two different ways.\n bodyLimit: MOUNT_BODY_LIMIT_BYTES,\n genReqId: (rawReq) => {\n const header = rawReq.headers[REQUEST_ID_HEADER];\n const value = Array.isArray(header) ? header[0] : header;\n return value !== undefined && CLIENT_REQUEST_ID_PATTERN.test(value) ? value : ids.next('req');\n },\n logger: fastifyLoggerOptions({ name: `${options.config.merchant.id}-http` }),\n });\n\n // See buildNotFoundHandler's own doc comment (logger.ts) — this\n // is what leaked the SSE ?adminToken= query param at info level on any 404\n // (a typo'd route, even a trailing slash on a real one).\n server.setNotFoundHandler(buildNotFoundHandler());\n\n // Host/Origin/admin-token gate — see access-control.ts. Closed by default:\n // no allowedOrigins means no browser can read anything cross-origin, and no\n // adminToken means the ledger routes 404 rather than serving openly.\n server.addHook(\n 'onRequest',\n buildAccessControlHook({\n publicBaseUrl: options.config.merchant.publicBaseUrl,\n allowedOrigins: options.config.server.allowedOrigins,\n }),\n );\n\n const adapterRuntimes: AdapterRuntime[] = [];\n\n registerRoutes({\n server,\n config: options.config,\n pipeline,\n resources,\n store: options.store,\n paymentProviders: options.paymentProviders,\n eventBus,\n clock,\n adapterRuntimes,\n logger,\n });\n\n const context: ProtocolAdapterContext = {\n pipeline,\n resources,\n events: eventBus,\n logger,\n clock,\n ids,\n publicBaseUrl: options.config.merchant.publicBaseUrl,\n };\n\n const started = await startAndMountAdapters({\n server,\n adapters: options.protocolAdapters,\n context,\n logger,\n clock,\n });\n adapterRuntimes.push(...started);\n\n await server.ready();\n\n return {\n pipeline,\n resources,\n async listen(): Promise<{ url: string }> {\n const url = await server.listen({\n port: options.config.server.port,\n host: options.config.server.host,\n });\n return { url };\n },\n async close(): Promise<void> {\n await stopAdapters(adapterRuntimes, logger);\n await server.close();\n },\n server,\n };\n}\n","/**\n * ACP checkout operation -> canonical request.\n *\n * Each operation maps to exactly one configured resource and one deterministic\n * input envelope, matching `ACP_OPERATION_INPUT_KEYS`: `path` carries\n * `checkout_session_id`, `body` carries the validated ACP document.\n *\n * What is deliberately absent: any synthesis of a payment field. ACP\n * `payment_data` on completion is the merchant's own purchase payment and\n * stays inside `body` as ordinary business input. Turning it into a\n * `PaymentSubmission` would stack a gateway payment on top of the merchant's\n * one, for a single call.\n */\nimport type { CanonicalRequest } from '../../core/index.js';\nimport { ACP_OPERATION_INPUT_KEYS } from './constants.js';\nimport type { AcpGuardedRequest } from './request-guards.js';\n\nexport interface AcpCanonicalRequestOptions {\n readonly request: AcpGuardedRequest;\n readonly resourceId: string;\n readonly requestId: string;\n readonly receivedAt: string;\n}\n\nexport function toCanonicalRequest(options: AcpCanonicalRequestOptions): CanonicalRequest {\n const { request, resourceId, requestId, receivedAt } = options;\n return {\n requestId,\n resourceId,\n input: canonicalInput(request),\n protocol: 'acp',\n receivedAt,\n };\n}\n\nfunction canonicalInput(request: AcpGuardedRequest): Record<string, unknown> {\n const keys = ACP_OPERATION_INPUT_KEYS[request.route.operation];\n const input: Record<string, unknown> = {};\n\n if (keys.includes('path') && request.route.sessionId !== undefined) {\n input['path'] = { checkout_session_id: request.route.sessionId };\n }\n if (keys.includes('body')) {\n input['body'] = request.body;\n } else if (request.route.acceptsBody && Object.keys(request.body).length > 0) {\n // Cancel: the pinned schema requires no body, so resources are not asked to\n // declare one - but a caller that did send `intent_trace` meant it, and\n // silently dropping it would lose the only thing the request carried.\n input['body'] = request.body;\n }\n return input;\n}\n","/**\n * Adapter self-description.\n *\n * `supportedSpec` is the pinned ACP snapshot, never this package's version.\n * Status is `experimental` and stays that way until the unsupported list below\n * shrinks on purpose rather than by omission.\n */\nimport type { AdapterDescriptor } from '../../core/index.js';\nimport { ACP_CHECKOUT_OPERATIONS, ACP_SPEC_VERSION } from './constants.js';\n\n/** What this adapter actually implements. */\nexport const ACP_CAPABILITIES: readonly string[] = [\n 'rest transport',\n 'well-known discovery',\n 'bearer authentication',\n 'API-Version negotiation',\n 'checkout service',\n ...ACP_CHECKOUT_OPERATIONS,\n];\n\n/**\n * Everything an ACP client may reasonably expect and will not get here.\n * Complete on purpose: a short list reads as \"mostly compatible\", which is\n * exactly the blanket claim alpha honesty forbids. `doctor` and\n * `/.well-known/agent-commerce` surface this verbatim.\n */\nexport const ACP_UNSUPPORTED: readonly string[] = [\n // Services this seller does not implement, named as ACP names them. The\n // discovery document advertises `checkout` alone, and these are the reason.\n 'carts service',\n 'feed service',\n 'standalone orders service',\n 'delegate_payment',\n 'delegate_authentication',\n // Bindings and delivery directions.\n 'ACP MCP transport binding',\n 'webhooks',\n 'outbound merchant-to-agent delivery',\n 'ACP client role',\n // Request authentication beyond the bearer token.\n 'Signature header verification',\n 'Timestamp replay-window verification',\n // Extensions and versioning.\n 'discount extension',\n 'general ACP extension framework',\n 'multiple ACP API versions',\n 'seller-backed payment handler integration',\n];\n\nexport function buildDescriptor(implementationVersion: string): AdapterDescriptor {\n return {\n name: 'acp',\n kind: 'protocol',\n implementationVersion,\n supportedSpec: ACP_SPEC_VERSION,\n capabilities: ACP_CAPABILITIES,\n status: 'experimental',\n unsupported: ACP_UNSUPPORTED,\n };\n}\n","/**\n * The `/.well-known/acp.json` seller discovery document.\n *\n * It advertises exactly what this adapter implements: one transport, one\n * service, one API version. Optional metadata appears only when an operator\n * configured it - in particular currencies are never inferred from the\n * gateway's x402 configuration, which is a different payment domain entirely.\n *\n * Nothing derived from a secret goes in here: the document is public and\n * unauthenticated, so bearer token, backend URLs, resource mapping ids and the\n * idempotency database location all stay out by construction - they are not\n * inputs to this function.\n */\nimport { ACP_SPEC_VERSION } from './constants.js';\n\n/** Discovery metadata an operator may configure. Absent fields are omitted, never guessed. */\nexport interface AcpDiscoveryMetadata {\n readonly documentationUrl?: string;\n readonly supportedCurrencies?: readonly string[];\n readonly supportedLocales?: readonly string[];\n readonly interventionTypes?: readonly string[];\n}\n\nexport interface AcpDiscoveryOptions {\n /** Externally reachable base URL of the gateway. */\n readonly publicBaseUrl: string;\n readonly mountPath: string;\n readonly metadata?: AcpDiscoveryMetadata;\n}\n\nexport function buildAcpDiscoveryDocument(options: AcpDiscoveryOptions): Record<string, unknown> {\n const metadata = options.metadata ?? {};\n return {\n protocol: {\n name: 'acp',\n version: ACP_SPEC_VERSION,\n supported_versions: [ACP_SPEC_VERSION],\n ...(metadata.documentationUrl !== undefined\n ? { documentation_url: metadata.documentationUrl }\n : {}),\n },\n api_base_url: joinUrl(options.publicBaseUrl, options.mountPath),\n // Only the REST binding. ACP's MCP transport is its own fixed checkout\n // binding and is not the generic MCP adapter this gateway also serves;\n // advertising it here because \"we do MCP\" would be a false claim.\n transports: ['rest'],\n capabilities: {\n services: ['checkout'],\n ...(metadata.interventionTypes !== undefined\n ? { intervention_types: metadata.interventionTypes }\n : {}),\n ...(metadata.supportedCurrencies !== undefined\n ? { supported_currencies: metadata.supportedCurrencies }\n : {}),\n ...(metadata.supportedLocales !== undefined\n ? { supported_locales: metadata.supportedLocales }\n : {}),\n },\n };\n}\n\nfunction joinUrl(baseUrl: string, mountPath: string): string {\n return `${baseUrl.replace(/\\/+$/, '')}/${mountPath.replace(/^\\/+|\\/+$/g, '')}`;\n}\n","/**\n * The ACP `Error` object, and the one writer every ACP response goes through.\n *\n * Centralised so no handler can invent its own error shape, and so the rule\n * that nothing internal reaches a client - no stack, no backend body, no Ajv\n * message, no token, no path - is enforced in one place instead of at a dozen\n * call sites.\n */\nimport type { ServerResponse } from 'node:http';\nimport { ACP_JSON_MEDIA_TYPE } from './constants.js';\n\n/** The three categories the pinned snapshot allows. */\nexport type AcpErrorType = 'invalid_request' | 'processing_error' | 'service_unavailable';\n\nexport interface AcpError {\n readonly type: AcpErrorType;\n readonly code: string;\n readonly message: string;\n /** RFC 9535 JSONPath into the *caller's* document, never into ours. */\n readonly param?: string;\n /** Only on version errors, per the snapshot. */\n readonly supported_versions?: readonly string[];\n}\n\n/** An ACP error plus the status it is served with. */\nexport interface AcpFailure {\n readonly status: number;\n readonly error: AcpError;\n}\n\nexport function acpFailure(\n status: number,\n type: AcpErrorType,\n code: string,\n message: string,\n extra: { readonly param?: string; readonly supportedVersions?: readonly string[] } = {},\n): AcpFailure {\n return {\n status,\n error: {\n type,\n code,\n message,\n ...(extra.param !== undefined ? { param: extra.param } : {}),\n ...(extra.supportedVersions !== undefined\n ? { supported_versions: extra.supportedVersions }\n : {}),\n },\n };\n}\n\n/**\n * Response headers the adapter is allowed to set. Merchant backend headers are\n * never proxied - a `Set-Cookie` or a tracing header from a backend belongs to\n * the merchant's own domain, not to the ACP client.\n */\nexport type AcpResponseHeaders = Readonly<Record<string, string>>;\n\nexport function writeAcpJson(\n res: ServerResponse,\n status: number,\n body: unknown,\n headers: AcpResponseHeaders = {},\n): void {\n if (res.headersSent) return;\n res.writeHead(status, { 'content-type': ACP_JSON_MEDIA_TYPE, ...headers });\n res.end(JSON.stringify(body));\n}\n\nexport function writeAcpFailure(\n res: ServerResponse,\n failure: AcpFailure,\n headers: AcpResponseHeaders = {},\n): void {\n writeAcpJson(res, failure.status, failure.error, headers);\n}\n","/**\n * Identity and request fingerprints for ACP idempotency.\n *\n * The fingerprint is taken over the *parsed* JSON value, not the raw bytes: a\n * client that retries the same request through a different JSON serializer\n * (different key order, `1.0` where it first sent `1`, whitespace) is retrying,\n * not conflicting, and answering it with a 422 would be wrong. The distinctions\n * that do matter are kept: array order, `null` versus an absent property, and\n * type - `1` and `\"1\"` are different requests.\n */\nimport { createHash } from 'node:crypto';\n\n/**\n * The authenticated caller, as a value safe to persist.\n *\n * The bearer token itself never reaches the database, the logs or a response;\n * only this digest of it does, and the digest is never returned to a client.\n */\nexport function identityHash(token: string): string {\n return sha256(`acp-auth:${token}`);\n}\n\n/** SHA-256 over the canonical form of a parsed JSON document. */\nexport function requestFingerprint(body: unknown): string {\n return sha256(canonicalize(body));\n}\n\n/**\n * Deterministic JSON canonicalization, in the spirit of RFC 8785 and limited to\n * what `JSON.parse` can produce - no dependency for what is twenty lines.\n *\n * Object keys are sorted by UTF-16 code unit, exactly as `Array.prototype.sort`\n * orders them, so two orderings of the same object canonicalize identically.\n * Numbers go through `JSON.stringify`, which already normalises `1.0`, `1e2`\n * and `100` to one shortest round-trip form.\n */\nfunction canonicalize(value: unknown): string {\n if (value === null) return 'null';\n if (Array.isArray(value)) return `[${value.map(canonicalize).join(',')}]`;\n if (typeof value === 'object') {\n const entries = Object.entries(value as Record<string, unknown>)\n // `undefined` cannot come from JSON.parse, but a caller could hand us an\n // object literal; dropping those keys keeps \"absent\" and \"absent\" equal.\n .filter(([, entry]) => entry !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalize(entry)}`).join(',')}}`;\n }\n // Strings, numbers and booleans. `JSON.stringify` never returns undefined\n // for these, and the types stay distinct because their encodings do.\n return JSON.stringify(value) ?? 'null';\n}\n\nfunction sha256(value: string): string {\n return createHash('sha256').update(value, 'utf8').digest('hex');\n}\n","/**\n * Opening a SQLite file safely.\n *\n * One definition, because every rule below was learned once and must not be\n * re-learned per store: the file is pre-created at 0600 before SQLite can\n * create it at `0666 & ~umask`, the WAL sidecars are narrowed after WAL is\n * enabled (they do not exist until then), and an existing but unwritable file\n * fails at startup instead of on the first write.\n *\n * Callers own their schema. This function opens and hardens; it migrates\n * nothing.\n */\nimport {\n accessSync,\n chmodSync,\n closeSync,\n existsSync,\n constants as fsConstants,\n mkdirSync,\n openSync,\n} from 'node:fs';\nimport { dirname } from 'node:path';\nimport Database from 'better-sqlite3';\nimport { CommerceError, type Logger } from '../core/index.js';\n\nexport interface OpenSqliteOptions {\n /** File path, or ':memory:' for tests. Parent directory is created if missing. */\n readonly path: string;\n /** Names the database in operator-facing errors, e.g. \"Receipt database\". */\n readonly label: string;\n readonly logger: Logger;\n}\n\nexport function openSqliteDatabase(options: OpenSqliteOptions): Database.Database {\n const { path, label, logger } = options;\n const isFileBacked = path !== ':memory:';\n\n if (isFileBacked) {\n const dir = dirname(path);\n if (dir !== '' && dir !== '.' && !existsSync(dir)) {\n // 0700 on directories we create ourselves. An existing directory is the\n // operator's to own and is deliberately left alone.\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n }\n }\n\n // Fail at startup, not on the first write. `new Database(path)` happily opens\n // a file the process cannot write, and SQLite only says \"attempt to write a\n // readonly database\" once a write is attempted - which on a paid resource is\n // *after* the payment attempt reservation, surfacing as an opaque\n // STORAGE_ERROR per request. Readiness does catch it (503), but the operator\n // is left guessing. This is not hypothetical: switching the demo containers\n // to a non-root user left an existing named volume root-owned, and that is\n // exactly how it presented.\n if (isFileBacked && existsSync(path)) {\n try {\n accessSync(path, fsConstants.W_OK);\n } catch {\n throw new CommerceError(\n 'STORAGE_ERROR',\n `${label} \"${path}\" exists but is not writable by this process (uid ${typeof process.getuid === 'function' ? process.getuid() : 'unknown'}). If this is a container that recently changed user, an existing volume may still be owned by the previous one - recreate it (docker compose down -v) or fix its ownership.`,\n { details: { path } },\n );\n }\n }\n\n // Create the file ourselves, at 0600, *before* SQLite can create it at\n // `0666 & ~umask`. The chmod below only narrows the mode after the fact: a\n // local co-tenant who opens the file inside that window keeps a readable\n // descriptor across the chmod and reads everything written afterwards.\n // SQLite copies the main file's mode onto the -wal/-shm sidecars, so this one\n // call covers all three. `mode` applies on creation only, so an existing file\n // is untouched here and left to the chmod.\n if (isFileBacked) {\n try {\n closeSync(openSync(path, 'a', 0o600));\n } catch {\n // Deliberately silent: whatever stopped us (unwritable directory, exotic\n // filesystem) is about to be reported by `new Database` with a better\n // message, or is harmless and covered by the chmod below.\n }\n }\n\n const db = new Database(path);\n db.pragma('journal_mode = WAL');\n db.pragma('foreign_keys = ON');\n if (isFileBacked) restrictDatabasePermissions(path, label, logger);\n return db;\n}\n\n/**\n * Narrow the database and its WAL sidecars to owner-only.\n *\n * `new Database(path)` opens with `0666 & ~umask`, so on a standard host the\n * `.sqlite`, `-wal` and `-shm` files landed at 0644 - any other local user\n * could read the whole commerce ledger: payer and payee addresses, amounts,\n * settlement transaction hashes, replay keys and the entire event stream. No\n * key material (the gateway is non-custodial and `redact.ts` is recursive), but\n * business metadata all the same.\n *\n * Called *after* `journal_mode = WAL`, because the sidecars do not exist until\n * then. Belt-and-braces since the main file is pre-created at 0600 above: this\n * still tightens a database that already existed with a looser mode.\n * Best-effort by design: a filesystem without POSIX modes must not stop the\n * gateway from starting, so a failure warns rather than throws.\n */\nfunction restrictDatabasePermissions(path: string, label: string, logger: Logger): void {\n for (const file of [path, `${path}-wal`, `${path}-shm`]) {\n try {\n chmodSync(file, 0o600);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === 'ENOENT') continue;\n logger.warn(\n { file, label, error: code ?? 'unknown' },\n 'could not restrict database permissions to owner-only',\n );\n }\n }\n}\n","/**\n * Durable ACP checkout idempotency.\n *\n * Its own table in its own database file: this is protocol replay semantics for\n * a merchant checkout, and it has nothing to do with the x402 payment replay\n * defence in the receipt store. Sharing a table would tie two unrelated\n * lifetimes and two unrelated retention policies together.\n *\n * The reservation is what makes it safe. A key is claimed atomically *before*\n * the side effect starts, so a second request carrying the same key finds the\n * claim rather than starting a second checkout.\n *\n * What this cannot do: a merchant side effect over HTTP and a local SQLite\n * commit are not one transaction. If the process dies after the merchant\n * completed an order but before the response was stored, the row stays\n * `in_flight` and every retry of that key is answered 409 until it expires -\n * deliberately, because re-running a completion whose remote state is unknown\n * risks charging a buyer twice. Merchant-side idempotency on destructive\n * operations is still strongly recommended; this store does not make the\n * merchant's API exactly-once.\n */\nimport type { Database } from 'better-sqlite3';\nimport { type Logger, NOOP_LOGGER } from '../../../core/index.js';\nimport { openSqliteDatabase } from '../../../storage/sqlite.js';\n\n/** Longest `Idempotency-Key` ACP allows. */\nexport const ACP_MAX_IDEMPOTENCY_KEY_LENGTH = 255;\n\n/** Scope of one claim: who asked, which endpoint, which key. */\nexport interface AcpIdempotencyScope {\n /** Digest of the authenticated bearer token - never the token itself. */\n readonly identityHash: string;\n /** The concrete endpoint path, so one key may be reused across operations. */\n readonly endpoint: string;\n readonly key: string;\n}\n\n/** A response worth replaying: status plus the ACP document that was sent. */\nexport interface AcpStoredResponse {\n readonly status: number;\n readonly body: unknown;\n}\n\nexport type AcpIdempotencyClaim =\n /** The caller owns the key and must now do the work. */\n | { readonly kind: 'reserved' }\n /** Same scope, same body, still running elsewhere. */\n | { readonly kind: 'in-flight' }\n /** Same scope, different body: the key was reused for another request. */\n | { readonly kind: 'conflict' }\n /** Same scope, same body, already answered. */\n | ({ readonly kind: 'replay' } & AcpStoredResponse);\n\nexport interface AcpIdempotencyStore {\n /** Atomically claim `scope`, or report what already holds it. */\n claim(scope: AcpIdempotencyScope, fingerprint: string): AcpIdempotencyClaim;\n /** Store the answer, making later retries a replay. */\n complete(scope: AcpIdempotencyScope, response: AcpStoredResponse): void;\n /** Drop the claim so a clean retry can run: the attempt produced no answer worth keeping. */\n release(scope: AcpIdempotencyScope): void;\n close(): void;\n}\n\nexport interface AcpIdempotencyStoreOptions {\n /** File path, or ':memory:' for tests. */\n readonly path: string;\n /** Never below 24 hours - config enforces the floor. */\n readonly retentionHours: number;\n readonly logger?: Logger;\n /** Injectable for tests that need to move time. */\n readonly now?: () => number;\n}\n\ninterface ClaimRow {\n state: string;\n fingerprint: string;\n status: number | null;\n body_json: string | null;\n}\n\nexport function createAcpIdempotencyStore(\n options: AcpIdempotencyStoreOptions,\n): AcpIdempotencyStore {\n const logger = options.logger ?? NOOP_LOGGER;\n const now = options.now ?? (() => Date.now());\n const retentionMs = options.retentionHours * 60 * 60 * 1000;\n\n const db: Database = openSqliteDatabase({\n path: options.path,\n label: 'ACP idempotency database',\n logger,\n });\n migrate(db);\n\n const selectStmt = db.prepare<[string, string, string], ClaimRow>(\n `SELECT state, fingerprint, status, body_json FROM acp_idempotency\n WHERE identity_hash = ? AND endpoint = ? AND idempotency_key = ?`,\n );\n const insertStmt = db.prepare(\n `INSERT INTO acp_idempotency\n (identity_hash, endpoint, idempotency_key, fingerprint, state, created_at, expires_at)\n VALUES (@identity_hash, @endpoint, @idempotency_key, @fingerprint, 'in_flight', @created_at, @expires_at)`,\n );\n const completeStmt = db.prepare(\n `UPDATE acp_idempotency SET state = 'completed', status = @status, body_json = @body_json\n WHERE identity_hash = @identity_hash AND endpoint = @endpoint AND idempotency_key = @idempotency_key`,\n );\n const deleteStmt = db.prepare(\n `DELETE FROM acp_idempotency\n WHERE identity_hash = ? AND endpoint = ? AND idempotency_key = ?`,\n );\n const expireStmt = db.prepare('DELETE FROM acp_idempotency WHERE expires_at <= ?');\n\n /**\n * Lazy cleanup, on the same connection and inside the claim transaction: a\n * background worker would be a second moving part for something a request\n * already has to touch.\n */\n const claimTx = db.transaction(\n (scope: AcpIdempotencyScope, fingerprint: string): AcpIdempotencyClaim => {\n const at = now();\n expireStmt.run(new Date(at).toISOString());\n\n const existing = selectStmt.get(scope.identityHash, scope.endpoint, scope.key);\n if (existing === undefined) {\n insertStmt.run({\n identity_hash: scope.identityHash,\n endpoint: scope.endpoint,\n idempotency_key: scope.key,\n fingerprint,\n created_at: new Date(at).toISOString(),\n expires_at: new Date(at + retentionMs).toISOString(),\n });\n return { kind: 'reserved' };\n }\n\n // Fingerprint first: a key reused for a different request is a conflict\n // whether or not the first one has finished. Reporting \"in flight\" there\n // would invite a retry that can only ever conflict.\n if (existing.fingerprint !== fingerprint) return { kind: 'conflict' };\n if (existing.state !== 'completed') return { kind: 'in-flight' };\n return {\n kind: 'replay',\n status: existing.status ?? 500,\n body: existing.body_json === null ? null : JSON.parse(existing.body_json),\n };\n },\n );\n\n let closed = false;\n return {\n claim(scope, fingerprint) {\n return claimTx(scope, fingerprint);\n },\n complete(scope, response) {\n completeStmt.run({\n identity_hash: scope.identityHash,\n endpoint: scope.endpoint,\n idempotency_key: scope.key,\n status: response.status,\n body_json: JSON.stringify(response.body ?? null),\n });\n },\n release(scope) {\n deleteStmt.run(scope.identityHash, scope.endpoint, scope.key);\n },\n close() {\n if (closed) return;\n closed = true;\n db.close();\n },\n };\n}\n\n/**\n * `PRAGMA user_version` as the migration marker, so reopening an existing file\n * is a fast no-op check rather than a re-create.\n */\nfunction migrate(db: Database): void {\n const current = db.pragma('user_version', { simple: true }) as number;\n if (current >= 1) return;\n const apply = db.transaction(() => {\n db.exec(`\n CREATE TABLE IF NOT EXISTS acp_idempotency (\n identity_hash TEXT NOT NULL,\n endpoint TEXT NOT NULL,\n idempotency_key TEXT NOT NULL,\n fingerprint TEXT NOT NULL,\n state TEXT NOT NULL,\n status INTEGER,\n body_json TEXT,\n created_at TEXT NOT NULL,\n expires_at TEXT NOT NULL,\n PRIMARY KEY (identity_hash, endpoint, idempotency_key)\n );\n CREATE INDEX IF NOT EXISTS idx_acp_idempotency_expires_at\n ON acp_idempotency(expires_at);\n `);\n db.pragma('user_version = 1');\n });\n apply();\n}\n","/**\n * Bearer authentication for the ACP checkout endpoints.\n *\n * Bearer is the only scheme this release accepts (config refuses any other),\n * discovery stays public, and a `Signature` header is never allowed to stand\n * in for the token - signature verification is not implemented and not\n * advertised, so treating one as authentication would be an unauthenticated\n * checkout endpoint dressed as a secure one.\n */\nimport { createHash, timingSafeEqual } from 'node:crypto';\n\nconst BEARER_PREFIX = /^Bearer +/i;\n\n/**\n * Constant-time comparison of the presented token against the configured one.\n *\n * Both sides are hashed first: `timingSafeEqual` throws on a length mismatch,\n * and comparing raw tokens would leak the configured length through that throw\n * (and through the early return that avoiding it invites). Digests are always\n * 32 bytes, so every wrong token costs exactly the same.\n */\nexport function isAuthorizedBearer(header: string | undefined, expectedToken: string): boolean {\n if (header === undefined) return false;\n if (!BEARER_PREFIX.test(header)) return false;\n const presented = header.replace(BEARER_PREFIX, '');\n if (presented.length === 0) return false;\n return timingSafeEqual(sha256(presented), sha256(expectedToken));\n}\n\nfunction sha256(value: string): Buffer {\n return createHash('sha256').update(value, 'utf8').digest();\n}\n","/**\n * The five stable checkout routes, matched against the adapter's mount.\n *\n * The route table is closed: anything else under the mount is a 404, so a\n * client cannot discover an unimplemented ACP service by probing paths.\n */\nimport type { AcpCheckoutOperation } from './constants.js';\n\n/** Longest accepted `checkout_session_id`. Merchant ids are short; this bounds what a caller can send. */\nconst MAX_SESSION_ID_LENGTH = 128;\n\n/** ACP session ids are opaque, but they are path segments and go into canonical input. */\nconst SESSION_ID_PATTERN = /^[A-Za-z0-9._~-]{1,128}$/;\n\nconst COLLECTION = 'checkout_sessions';\n\nexport interface AcpRouteMatch {\n readonly operation: AcpCheckoutOperation;\n /**\n * The concrete endpoint path, rebuilt from the matched segments rather than\n * taken from the raw URL: it scopes idempotency keys, so it must be one\n * canonical string per endpoint and never carry a query string or an\n * alternative encoding of the same path.\n */\n readonly path: string;\n /** Absent only for `createCheckoutSession`. */\n readonly sessionId?: string;\n /** POST routes carry an ACP request document; the GET route carries none. */\n readonly acceptsBody: boolean;\n}\n\nexport type AcpRouteResult =\n | { readonly kind: 'match'; readonly route: AcpRouteMatch }\n | { readonly kind: 'not-found' }\n | { readonly kind: 'method-not-allowed'; readonly allow: readonly string[] };\n\n/**\n * Matches `method` + `url` against the checkout routes below `mountPath`.\n *\n * The URL arrives raw from Node, so it still carries any query string and may\n * be percent-encoded; both are handled here rather than by every caller.\n */\nexport function matchAcpRoute(\n method: string | undefined,\n url: string | undefined,\n mountPath: string,\n): AcpRouteResult {\n const segments = routeSegments(url, mountPath);\n if (segments === undefined || segments[0] !== COLLECTION) return { kind: 'not-found' };\n\n const verb = (method ?? '').toUpperCase();\n\n // POST /checkout_sessions\n if (segments.length === 1) {\n if (verb !== 'POST') return { kind: 'method-not-allowed', allow: ['POST'] };\n return {\n kind: 'match',\n route: {\n operation: 'createCheckoutSession',\n path: endpointPath(mountPath, segments),\n acceptsBody: true,\n },\n };\n }\n\n const sessionId = segments[1];\n if (sessionId === undefined || !SESSION_ID_PATTERN.test(sessionId)) return { kind: 'not-found' };\n\n // GET|POST /checkout_sessions/{id}\n if (segments.length === 2) {\n if (verb === 'GET') {\n return {\n kind: 'match',\n route: {\n operation: 'getCheckoutSession',\n path: endpointPath(mountPath, segments),\n sessionId,\n acceptsBody: false,\n },\n };\n }\n if (verb === 'POST') {\n return {\n kind: 'match',\n route: {\n operation: 'updateCheckoutSession',\n path: endpointPath(mountPath, segments),\n sessionId,\n acceptsBody: true,\n },\n };\n }\n return { kind: 'method-not-allowed', allow: ['GET', 'POST'] };\n }\n\n // POST /checkout_sessions/{id}/{complete|cancel}\n if (segments.length === 3) {\n const operation =\n segments[2] === 'complete'\n ? 'completeCheckoutSession'\n : segments[2] === 'cancel'\n ? 'cancelCheckoutSession'\n : undefined;\n if (operation === undefined) return { kind: 'not-found' };\n if (verb !== 'POST') return { kind: 'method-not-allowed', allow: ['POST'] };\n return {\n kind: 'match',\n route: { operation, path: endpointPath(mountPath, segments), sessionId, acceptsBody: true },\n };\n }\n\n return { kind: 'not-found' };\n}\n\nfunction endpointPath(mountPath: string, segments: readonly string[]): string {\n return `${mountPath.replace(/\\/+$/, '')}/${segments.join('/')}`;\n}\n\n/**\n * Path segments below the mount, or `undefined` when the URL is not under it.\n *\n * A percent-encoded separator (`%2F`) is decoded per segment *after* the split,\n * so an id can never smuggle in an extra path segment.\n */\nfunction routeSegments(url: string | undefined, mountPath: string): readonly string[] | undefined {\n if (url === undefined) return undefined;\n const path = url.split('?')[0]?.split('#')[0] ?? '';\n const base = mountPath.replace(/\\/+$/, '');\n if (path !== base && !path.startsWith(`${base}/`)) return undefined;\n\n const rest = path.slice(base.length);\n const segments: string[] = [];\n for (const raw of rest.split('/')) {\n if (raw.length === 0) continue;\n if (raw.length > MAX_SESSION_ID_LENGTH) return undefined;\n try {\n segments.push(decodeURIComponent(raw));\n } catch {\n // A malformed escape is not a route this adapter serves.\n return undefined;\n }\n }\n return segments;\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://example.com/schemas/agentic-checkout/bundle.schema.json\",\n \"title\": \"Agentic Checkout — Schema Bundle\",\n \"$defs\": {\n \"VariantOption\": {\n \"description\": \"Represents a single variant option for a product (e.g., size, color, material)\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Variant attribute name (e.g., 'Size', 'Color')\"\n },\n \"value\": {\n \"type\": \"string\",\n \"description\": \"Variant attribute value (e.g., 'Large', 'Blue')\"\n }\n },\n \"required\": [\n \"name\",\n \"value\"\n ],\n \"example\": {\n \"name\": \"Color\",\n \"value\": \"Midnight Blue\"\n }\n },\n \"WeightInfo\": {\n \"description\": \"Product weight with unit of measurement\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"value\": {\n \"type\": \"number\",\n \"description\": \"Numeric weight value\"\n },\n \"unit\": {\n \"type\": \"string\",\n \"enum\": [\n \"g\",\n \"kg\",\n \"oz\",\n \"lb\"\n ],\n \"description\": \"Unit of measurement for weight\"\n }\n },\n \"required\": [\n \"value\",\n \"unit\"\n ],\n \"example\": {\n \"value\": 250,\n \"unit\": \"g\"\n }\n },\n \"DimensionsInfo\": {\n \"description\": \"Physical dimensions of a product with unit of measurement\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"length\": {\n \"type\": \"number\",\n \"description\": \"Length dimension\"\n },\n \"width\": {\n \"type\": \"number\",\n \"description\": \"Width dimension\"\n },\n \"height\": {\n \"type\": \"number\",\n \"description\": \"Height dimension\"\n },\n \"unit\": {\n \"type\": \"string\",\n \"enum\": [\n \"cm\",\n \"in\"\n ],\n \"description\": \"Unit of measurement for dimensions\"\n }\n },\n \"required\": [\n \"length\",\n \"width\",\n \"height\",\n \"unit\"\n ],\n \"example\": {\n \"length\": 15.5,\n \"width\": 10.2,\n \"height\": 5.8,\n \"unit\": \"cm\"\n }\n },\n \"DiscountDetail\": {\n \"description\": \"Information about a discount applied to the checkout or a specific item\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"code\": {\n \"type\": \"string\",\n \"description\": \"Discount code if applicable\"\n },\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"percentage\",\n \"fixed\",\n \"bogo\",\n \"volume\"\n ],\n \"description\": \"Type of discount\"\n },\n \"amount\": {\n \"type\": \"integer\",\n \"description\": \"Discount amount in minor currency units (e.g. 100 cents for $1.00 or 100 for ¥100)\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Human-readable discount description\"\n },\n \"source\": {\n \"type\": \"string\",\n \"enum\": [\n \"coupon\",\n \"automatic\",\n \"loyalty\"\n ],\n \"description\": \"Source of the discount\"\n }\n },\n \"required\": [\n \"type\",\n \"amount\"\n ],\n \"example\": {\n \"code\": \"SAVE20\",\n \"type\": \"percentage\",\n \"amount\": 1600,\n \"description\": \"20% off your order\",\n \"source\": \"coupon\"\n }\n },\n \"Address\": {\n \"description\": \"Physical address for shipping, billing, or pickup locations\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Recipient name for this address\"\n },\n \"line_one\": {\n \"type\": \"string\",\n \"description\": \"Primary street address line\"\n },\n \"line_two\": {\n \"type\": \"string\",\n \"description\": \"Secondary address line (apartment, suite, etc.)\"\n },\n \"city\": {\n \"type\": \"string\",\n \"description\": \"City name\"\n },\n \"state\": {\n \"type\": \"string\",\n \"description\": \"State or province code\"\n },\n \"country\": {\n \"type\": \"string\",\n \"description\": \"ISO 3166-1 alpha-2 country code\"\n },\n \"postal_code\": {\n \"type\": \"string\",\n \"description\": \"Postal or ZIP code\"\n },\n \"company\": {\n \"type\": \"string\",\n \"description\": \"Postal or ZIP code\"\n }\n },\n \"required\": [\n \"name\",\n \"line_one\",\n \"city\",\n \"state\",\n \"country\",\n \"postal_code\"\n ],\n \"example\": {\n \"name\": \"Jane Doe\",\n \"line_one\": \"123 Main Street\",\n \"line_two\": \"Apt 4B\",\n \"city\": \"New York\",\n \"state\": \"NY\",\n \"country\": \"US\",\n \"postal_code\": \"10001\"\n }\n },\n \"AffiliateAttributionSource\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Context about where the attribution originated.\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"url\",\n \"platform\",\n \"unknown\"\n ],\n \"description\": \"The type of attribution source.\"\n },\n \"url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"Canonical content URL when type is 'url'.\"\n }\n },\n \"required\": [\n \"type\"\n ],\n \"example\": {\n \"type\": \"url\",\n \"url\": \"https://example.com/product-review\"\n }\n },\n \"AffiliateAttributionMetadata\": {\n \"type\": \"object\",\n \"additionalProperties\": {\n \"oneOf\": [\n {\n \"type\": \"string\",\n \"description\": \"String metadata value\"\n },\n {\n \"type\": \"number\",\n \"description\": \"Numeric metadata value\"\n },\n {\n \"type\": \"boolean\",\n \"description\": \"Boolean metadata value\"\n }\n ]\n },\n \"description\": \"Flat key/value map for additional non-sensitive context. Keys must be strings; values must be strings, numbers, or booleans. Arrays and nested objects are NOT permitted.\",\n \"example\": {\n \"campaign_type\": \"influencer\",\n \"commission_rate\": 0.15,\n \"is_verified\": true\n }\n },\n \"AffiliateAttribution\": {\n \"type\": \"object\",\n \"description\": \"Optional affiliate attribution data for crediting third-party publishers. Write-only: not returned in responses. Forward compatibility: Servers SHOULD ignore unknown fields to support future extensions (per RFC §8.2).\",\n \"properties\": {\n \"provider\": {\n \"type\": \"string\",\n \"description\": \"Identifier for the attribution provider / affiliate network namespace (e.g., 'impact.com').\"\n },\n \"token\": {\n \"type\": \"string\",\n \"description\": \"Opaque provider-issued token for fraud-resistant validation. Treat as secret.\"\n },\n \"publisher_id\": {\n \"type\": \"string\",\n \"description\": \"Provider-scoped affiliate/publisher identifier. Required if token is omitted.\"\n },\n \"campaign_id\": {\n \"type\": \"string\",\n \"description\": \"Provider-scoped campaign identifier.\"\n },\n \"creative_id\": {\n \"type\": \"string\",\n \"description\": \"Provider-scoped creative identifier.\"\n },\n \"sub_id\": {\n \"type\": \"string\",\n \"description\": \"Provider-scoped sub-tracking identifier.\"\n },\n \"source\": {\n \"$ref\": \"#/$defs/AffiliateAttributionSource\"\n },\n \"issued_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC3339 timestamp when the attribution token was issued.\"\n },\n \"expires_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC3339 timestamp when the attribution token expires.\"\n },\n \"metadata\": {\n \"$ref\": \"#/$defs/AffiliateAttributionMetadata\"\n },\n \"touchpoint\": {\n \"type\": \"string\",\n \"enum\": [\n \"first\",\n \"last\"\n ],\n \"description\": \"Attribution touchpoint type. Use 'first' when capturing at session creation, 'last' when capturing at completion. Enables multi-touch attribution models.\"\n }\n },\n \"required\": [\n \"provider\"\n ],\n \"anyOf\": [\n {\n \"required\": [\n \"token\"\n ]\n },\n {\n \"required\": [\n \"publisher_id\"\n ]\n }\n ],\n \"example\": {\n \"provider\": \"impact.com\",\n \"token\": \"atp_01J8Z3WXYZ9ABC\",\n \"publisher_id\": \"pub_123\",\n \"campaign_id\": \"camp_summer2026\",\n \"touchpoint\": \"first\",\n \"source\": {\n \"type\": \"url\",\n \"url\": \"https://example.com/product-review\"\n },\n \"issued_at\": \"2026-02-11T10:00:00Z\",\n \"expires_at\": \"2026-02-11T11:00:00Z\"\n }\n },\n \"FulfillmentDetails\": {\n \"description\": \"Details about how items will be fulfilled (shipping, pickup, or delivery information)\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Full name for fulfillment contact\"\n },\n \"phone_number\": {\n \"type\": \"string\",\n \"description\": \"Contact phone number. E.164 format recommended (e.g., +15551234567) for global interoperability and SMS/delivery carrier systems.\"\n },\n \"email\": {\n \"type\": \"string\",\n \"format\": \"email\",\n \"description\": \"Contact email address\"\n },\n \"address\": {\n \"$ref\": \"#/$defs/Address\",\n \"description\": \"Fulfillment address\"\n }\n },\n \"example\": {\n \"name\": \"John Smith\",\n \"phone_number\": \"15551234567\",\n \"email\": \"john.smith@example.com\",\n \"address\": {\n \"name\": \"John Smith\",\n \"line_one\": \"555 Golden Gate Avenue\",\n \"line_two\": \"Apt 401\",\n \"city\": \"San Francisco\",\n \"state\": \"CA\",\n \"country\": \"US\",\n \"postal_code\": \"94102\"\n }\n }\n },\n \"CompanyInfo\": {\n \"description\": \"Information about a company or organization associated with the buyer\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Company or organization name\"\n },\n \"tax_id\": {\n \"type\": \"string\",\n \"description\": \"Business tax identification number\"\n },\n \"department\": {\n \"type\": \"string\",\n \"description\": \"Department within the organization\"\n },\n \"cost_center\": {\n \"type\": \"string\",\n \"description\": \"Cost center code for internal accounting\"\n }\n },\n \"required\": [\n \"name\"\n ],\n \"example\": {\n \"name\": \"Acme Corporation\",\n \"tax_id\": \"12-3456789\",\n \"department\": \"Marketing\",\n \"cost_center\": \"CC-2001\"\n }\n },\n \"LoyaltyInfo\": {\n \"description\": \"Loyalty program information including membership details and rewards balance\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"tier\": {\n \"type\": \"string\",\n \"description\": \"Loyalty program tier level\"\n },\n \"points_balance\": {\n \"type\": \"integer\",\n \"description\": \"Current loyalty points balance\"\n },\n \"member_since\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when the customer joined the loyalty program\"\n }\n },\n \"example\": {\n \"tier\": \"Gold\",\n \"points_balance\": 5000,\n \"member_since\": \"2024-01-15T09:00:00Z\"\n }\n },\n \"TaxExemption\": {\n \"description\": \"Tax exemption information including exemption type and applicable regions\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"certificate_id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for the tax exemption certificate\"\n },\n \"certificate_type\": {\n \"type\": \"string\",\n \"enum\": [\n \"resale\",\n \"exempt_organization\",\n \"government\"\n ],\n \"description\": \"Type of tax exemption certificate\"\n },\n \"exempt_regions\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Region code where tax exemption applies (e.g., state abbreviation)\"\n },\n \"description\": \"List of regions where the exemption applies (e.g., state codes)\"\n },\n \"expires_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when the exemption certificate expires\"\n }\n },\n \"required\": [\n \"certificate_id\",\n \"certificate_type\"\n ],\n \"example\": {\n \"certificate_id\": \"cert_12345\",\n \"certificate_type\": \"resale\",\n \"exempt_regions\": [\n \"CA\",\n \"NY\",\n \"TX\"\n ],\n \"expires_at\": \"2027-12-31T23:59:59Z\"\n }\n },\n \"Buyer\": {\n \"description\": \"Information about the buyer including contact details, company info, and loyalty status\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"first_name\": {\n \"type\": \"string\",\n \"description\": \"Buyer's first name\"\n },\n \"last_name\": {\n \"type\": \"string\",\n \"description\": \"Buyer's last name\"\n },\n \"full_name\": {\n \"type\": \"string\",\n \"description\": \"Buyer's full name\"\n },\n \"email\": {\n \"type\": \"string\",\n \"format\": \"email\",\n \"description\": \"Buyer's email address\"\n },\n \"phone_number\": {\n \"type\": \"string\",\n \"description\": \"Buyer's phone number\"\n },\n \"customer_id\": {\n \"type\": \"string\",\n \"description\": \"Merchant's internal customer identifier\"\n },\n \"account_type\": {\n \"type\": \"string\",\n \"enum\": [\n \"guest\",\n \"registered\",\n \"business\"\n ],\n \"description\": \"Type of buyer account\"\n },\n \"authentication_status\": {\n \"type\": \"string\",\n \"enum\": [\n \"authenticated\",\n \"guest\",\n \"requires_signin\"\n ],\n \"description\": \"Buyer's authentication status\"\n },\n \"company\": {\n \"$ref\": \"#/$defs/CompanyInfo\",\n \"description\": \"Company information for business buyers\"\n },\n \"loyalty\": {\n \"$ref\": \"#/$defs/LoyaltyInfo\",\n \"description\": \"Loyalty program information\"\n },\n \"tax_exemption\": {\n \"$ref\": \"#/$defs/TaxExemption\",\n \"description\": \"Tax exemption details\"\n }\n },\n \"required\": [\n \"email\"\n ],\n \"example\": {\n \"first_name\": \"Sarah\",\n \"last_name\": \"Johnson\",\n \"full_name\": \"Sarah Johnson\",\n \"email\": \"sarah.johnson@example.com\",\n \"phone_number\": \"+1-415-555-0123\",\n \"customer_id\": \"cust_abc123\",\n \"account_type\": \"registered\",\n \"authentication_status\": \"authenticated\"\n }\n },\n \"InterventionCapabilities\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Intervention capabilities. Context-specific fields: display_context, redirect_context, max_redirects, max_interaction_depth (requests only). required, enforcement (responses only). supported field contains intersection in responses.\",\n \"properties\": {\n \"supported\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"enum\": [\n \"3ds\",\n \"biometric\",\n \"address_verification\"\n ]\n },\n \"description\": \"Intervention types supported. Agent request: Interventions the agent can handle. Seller response: Intersection of supported interventions.\"\n },\n \"required\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"enum\": [\n \"3ds\",\n \"biometric\"\n ]\n },\n \"description\": \"Intervention methods required for this session (seller only).\"\n },\n \"enforcement\": {\n \"type\": \"string\",\n \"enum\": [\n \"always\",\n \"conditional\",\n \"optional\"\n ],\n \"description\": \"When required interventions are enforced (seller only).\"\n },\n \"display_context\": {\n \"type\": \"string\",\n \"enum\": [\n \"native\",\n \"webview\",\n \"modal\",\n \"redirect\"\n ],\n \"description\": \"How the Agent presents interventions (agent only).\"\n },\n \"redirect_context\": {\n \"type\": \"string\",\n \"enum\": [\n \"in_app\",\n \"external_browser\",\n \"none\"\n ],\n \"description\": \"How the Agent handles redirects (agent only).\"\n },\n \"max_redirects\": {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"description\": \"Maximum number of redirects the Agent can handle (agent only).\"\n },\n \"max_interaction_depth\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"description\": \"Maximum depth of nested interactions the Agent can handle (agent only).\"\n }\n },\n \"example\": {\n \"supported\": [\n \"3ds\",\n \"address_verification\"\n ],\n \"display_context\": \"native\",\n \"redirect_context\": \"in_app\",\n \"max_redirects\": 3,\n \"max_interaction_depth\": 2\n }\n },\n \"Capabilities\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Capabilities object used in requests and responses. Context determines the party: requests are from Agents, responses are from Sellers. Seller responses contain the intersection of supported interventions.\",\n \"properties\": {\n \"payment\": {\n \"$ref\": \"#/$defs/Payment\"\n },\n \"interventions\": {\n \"$ref\": \"#/$defs/InterventionCapabilities\"\n },\n \"extensions\": {\n \"oneOf\": [\n {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Extension identifier string\"\n },\n \"uniqueItems\": true,\n \"description\": \"Extensions the agent understands (request). Simple identifiers like 'discount'.\"\n },\n {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/ExtensionDeclaration\"\n },\n \"uniqueItems\": true,\n \"description\": \"Active extensions for this session (response). Objects with name, extends, schema, spec.\"\n }\n ],\n \"description\": \"Extensions supported by the party. Requests: array of extension identifiers. Responses: array of extension declaration objects.\"\n }\n },\n \"example\": {\n \"interventions\": {\n \"supported\": [\n \"3ds\"\n ],\n \"display_context\": \"native\"\n },\n \"extensions\": [\n \"discount\",\n \"affiliate_attribution\"\n ]\n }\n },\n \"ExtensionDeclaration\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Extension declaration in capabilities.extensions (response). Describes an active extension and which schema fields it adds.\",\n \"required\": [\n \"name\"\n ],\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"pattern\": \"^[a-z][a-z0-9_-]*(@\\\\d{4}-\\\\d{2}-\\\\d{2})?$|^[a-z][a-z0-9]*(?:\\\\.[a-z][a-z0-9_-]*)+(@\\\\d{4}-\\\\d{2}-\\\\d{2})?$\",\n \"description\": \"Unique identifier for the extension.\"\n },\n \"extends\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\$\\\\.[A-Za-z][A-Za-z0-9]*(\\\\.[A-Za-z][A-Za-z0-9_]*)*$\",\n \"description\": \"JSONPath expression identifying a schema field added by this extension\"\n },\n \"uniqueItems\": true,\n \"description\": \"JSONPath expressions identifying the schema fields added by this extension. Format: $.<SchemaName>.<fieldName> (e.g., $.CheckoutSession.discounts).\"\n },\n \"schema\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to the extension's JSON Schema definition.\"\n },\n \"spec\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to the extension's specification document.\"\n }\n },\n \"example\": {\n \"name\": \"discount\",\n \"extends\": [\n \"$.CheckoutSession.discounts\",\n \"$.CheckoutSessionCreateRequest.coupons\"\n ],\n \"schema\": \"https://example.com/schemas/extensions/discount.schema.json\",\n \"spec\": \"https://example.com/specs/extensions/discount\"\n }\n },\n \"PaymentMethodObject\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Payment method with additional constraints (e.g., card brands, PSP routing)\",\n \"properties\": {\n \"method\": {\n \"type\": \"string\",\n \"description\": \"The payment method identifier\"\n },\n \"brands\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"enum\": [\n \"visa\",\n \"mastercard\",\n \"amex\",\n \"discover\",\n \"diners\",\n \"jcb\",\n \"unionpay\",\n \"eftpos\",\n \"interac\"\n ]\n },\n \"description\": \"Specific card brands/networks accepted\"\n },\n \"funding_types\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"enum\": [\n \"credit\",\n \"debit\",\n \"prepaid\"\n ]\n },\n \"description\": \"For card methods, funding types accepted\"\n },\n \"providers\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Payment service provider identifier\"\n },\n \"description\": \"Optional PSP routing information\"\n }\n },\n \"required\": [\n \"method\"\n ],\n \"example\": {\n \"method\": \"card\",\n \"brands\": [\n \"visa\",\n \"mastercard\"\n ],\n \"providers\": [\n \"stripe\",\n \"adyen\"\n ]\n }\n },\n \"Item\": {\n \"description\": \"A purchasable item with variant options (e.g., size, color) and quantity\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for the item\"\n },\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Display name of the item\"\n },\n \"unit_amount\": {\n \"type\": \"integer\",\n \"description\": \"Price per unit in minor currency units (e.g. 100 cents for $1.00 or 100 for ¥100)\"\n }\n },\n \"required\": [\n \"id\"\n ],\n \"example\": {\n \"id\": \"item_123\",\n \"name\": \"Wireless Headphones\",\n \"unit_amount\": 7999\n }\n },\n \"Disclosure\": {\n \"description\": \"Legal disclosure or terms that must be acknowledged by the buyer\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"disclaimer\"\n ],\n \"description\": \"Type of disclosure\"\n },\n \"content_type\": {\n \"type\": \"string\",\n \"enum\": [\n \"plain\",\n \"markdown\"\n ],\n \"description\": \"Format of the disclosure content. When set to 'markdown', content MUST conform to CommonMark (https://spec.commonmark.org/0.31.2/). Raw HTML elements MUST NOT be included. When set to 'plain', content is plain text with no formatting.\"\n },\n \"content\": {\n \"type\": \"string\",\n \"description\": \"The disclosure text content. When content_type is 'markdown', this MUST be valid CommonMark with no raw HTML. Agents MUST render using a CommonMark-compliant parser with raw HTML output disabled or sanitized.\"\n }\n },\n \"required\": [\n \"type\",\n \"content_type\",\n \"content\"\n ],\n \"example\": {\n \"type\": \"disclaimer\",\n \"content_type\": \"plain\",\n \"content\": \"This product contains small parts and is not suitable for children under 3 years.\"\n }\n },\n \"CustomAttribute\": {\n \"description\": \"Custom key-value attribute for merchant-specific metadata on line items\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"display_name\": {\n \"type\": \"string\",\n \"description\": \"Human-readable label for the attribute\"\n },\n \"value\": {\n \"type\": \"string\",\n \"description\": \"Attribute value\"\n }\n },\n \"required\": [\n \"display_name\",\n \"value\"\n ],\n \"example\": {\n \"display_name\": \"Engraving\",\n \"value\": \"Happy Birthday!\"\n }\n },\n \"MarketplaceSellerDetails\": {\n \"description\": \"Information about a third-party seller in a marketplace model\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Name of the marketplace seller or vendor\"\n }\n },\n \"required\": [\n \"name\"\n ],\n \"example\": {\n \"name\": \"TechGear Store\"\n }\n },\n \"PaymentHandler\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Payment handler configuration and capabilities\",\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Seller-defined handler identifier\"\n },\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Handler name in reverse-DNS format (e.g., dev.acp.tokenized.card)\"\n },\n \"display_name\": {\n \"type\": \"string\",\n \"description\": \"Human-readable name for UI (e.g., Credit Card). Use when showing payment options to the buyer.\"\n },\n \"version\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{4}-\\\\d{2}-\\\\d{2}$\",\n \"description\": \"Handler version in YYYY-MM-DD format\"\n },\n \"spec\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to handler specification\"\n },\n \"requires_delegate_payment\": {\n \"type\": \"boolean\",\n \"description\": \"Whether this handler requires using delegate_payment API\"\n },\n \"requires_pci_compliance\": {\n \"type\": \"boolean\",\n \"description\": \"Whether this handler routes PCI DSS sensitive data\"\n },\n \"psp\": {\n \"type\": \"string\",\n \"description\": \"Payment Service Provider identifier\"\n },\n \"config_schema\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to JSON Schema for handler configuration\"\n },\n \"instrument_schemas\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to a JSON Schema defining accepted payment instrument format\"\n },\n \"description\": \"URLs to JSON Schemas for payment instruments\"\n },\n \"config\": {\n \"type\": \"object\",\n \"description\": \"Handler-specific configuration\"\n },\n \"display_order\": {\n \"type\": \"integer\",\n \"description\": \"Optional merchant-suggested display order (lower = higher preference). Suggestive only; platform/agent MAY reorder.\"\n }\n },\n \"required\": [\n \"id\",\n \"name\",\n \"version\",\n \"spec\",\n \"requires_delegate_payment\",\n \"requires_pci_compliance\",\n \"psp\",\n \"config_schema\",\n \"instrument_schemas\",\n \"config\"\n ],\n \"example\": {\n \"id\": \"handler_stripe_01\",\n \"name\": \"Stripe\",\n \"type\": \"direct\",\n \"instrument_schemas\": [\n \"https://example.com/schemas/payment/card.json\"\n ]\n }\n },\n \"Payment\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Payment configuration with handlers\",\n \"properties\": {\n \"handlers\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/PaymentHandler\"\n },\n \"description\": \"Available payment handlers\"\n }\n },\n \"required\": [\n \"handlers\"\n ],\n \"example\": {\n \"handlers\": []\n }\n },\n \"LineItem\": {\n \"description\": \"A line item in the checkout representing a product with pricing, discounts, and fulfillment details\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for the line item\"\n },\n \"item\": {\n \"$ref\": \"#/$defs/Item\",\n \"description\": \"Reference to the item being purchased\"\n },\n \"quantity\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"description\": \"Number of units for this line item\"\n },\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Display name of the line item\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Detailed description of the line item\"\n },\n \"images\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"Image URL for the product\"\n },\n \"description\": \"Array of image URLs for this line item\"\n },\n \"unit_amount\": {\n \"type\": \"integer\",\n \"description\": \"The unit price of the line item in the smallest currency unit (e.g., cents for USD)\"\n },\n \"disclosures\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Disclosure\"\n },\n \"description\": \"Legal disclosures or disclaimers for this item\"\n },\n \"custom_attributes\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/CustomAttribute\"\n },\n \"description\": \"Custom attributes specific to this line item\"\n },\n \"marketplace_seller_details\": {\n \"$ref\": \"#/$defs/MarketplaceSellerDetails\",\n \"description\": \"Seller details for marketplace items\"\n },\n \"product_id\": {\n \"type\": \"string\",\n \"description\": \"Merchant's product identifier\"\n },\n \"sku\": {\n \"type\": \"string\",\n \"description\": \"Stock keeping unit identifier\"\n },\n \"variant_id\": {\n \"type\": \"string\",\n \"description\": \"Product variant identifier\"\n },\n \"category\": {\n \"type\": \"string\",\n \"description\": \"Product category\"\n },\n \"tags\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Product tag or category\"\n },\n \"description\": \"Product tags or labels\"\n },\n \"weight\": {\n \"$ref\": \"#/$defs/WeightInfo\",\n \"description\": \"Weight information for the item\"\n },\n \"dimensions\": {\n \"$ref\": \"#/$defs/DimensionsInfo\",\n \"description\": \"Dimensions for the item\"\n },\n \"availability_status\": {\n \"type\": \"string\",\n \"enum\": [\n \"in_stock\",\n \"low_stock\",\n \"out_of_stock\",\n \"backorder\",\n \"pre_order\"\n ],\n \"description\": \"Current availability status of the item\"\n },\n \"available_quantity\": {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"description\": \"Quantity currently available for purchase\"\n },\n \"max_quantity_per_order\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"description\": \"Maximum quantity allowed per order\"\n },\n \"fulfillable_on\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when item becomes available for fulfillment\"\n },\n \"variant_options\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/VariantOption\"\n },\n \"description\": \"Selected product variant options (e.g., size, color)\"\n },\n \"discount_details\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/DiscountDetail\"\n },\n \"description\": \"Line-item level discount details\"\n },\n \"tax_exempt\": {\n \"type\": \"boolean\",\n \"description\": \"Whether this line item is tax exempt\"\n },\n \"tax_exemption_reason\": {\n \"type\": \"string\",\n \"description\": \"Reason for tax exemption if applicable\"\n },\n \"parent_id\": {\n \"type\": \"string\",\n \"description\": \"Reference to parent line item for bundled products\"\n },\n \"totals\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Total\"\n },\n \"description\": \"Line-item level totals breakdown including base_amount, discount, subtotal, tax, and total\"\n }\n },\n \"required\": [\n \"id\",\n \"item\",\n \"quantity\",\n \"totals\"\n ],\n \"example\": {\n \"id\": \"item_001\",\n \"product_id\": \"prod_tshirt_blue_m\",\n \"name\": \"Organic Cotton T-Shirt\",\n \"quantity\": 2,\n \"base_amount\": 2900,\n \"discount\": 0,\n \"subtotal\": 5800,\n \"tax\": 464,\n \"total\": 6264,\n \"currency\": \"usd\",\n \"image_url\": \"https://example.com/images/tshirt-blue.jpg\"\n }\n },\n \"TaxBreakdownItem\": {\n \"description\": \"Breakdown of tax amounts by type, jurisdiction, or rate\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"jurisdiction\": {\n \"type\": \"string\",\n \"description\": \"Tax jurisdiction name (e.g., 'California State Tax', 'City of San Francisco')\"\n },\n \"rate\": {\n \"type\": \"number\",\n \"description\": \"Tax rate as a decimal (e.g., 0.0875 for 8.75%)\"\n },\n \"amount\": {\n \"type\": \"integer\",\n \"description\": \"Tax amount in minor currency units (e.g. 100 cents for $1.00 or 100 for ¥100)\"\n }\n },\n \"required\": [\n \"jurisdiction\",\n \"rate\",\n \"amount\"\n ],\n \"example\": {\n \"name\": \"State Sales Tax\",\n \"amount\": 464,\n \"rate\": 0.08\n }\n },\n \"Total\": {\n \"description\": \"Total amounts for the checkout including subtotal, discounts, tax, shipping, and final total\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"items_base_amount\",\n \"items_discount\",\n \"subtotal\",\n \"discount\",\n \"fulfillment\",\n \"tax\",\n \"fee\",\n \"gift_wrap\",\n \"tip\",\n \"store_credit\",\n \"total\",\n \"amount_refunded\"\n ],\n \"description\": \"Type of total line item\"\n },\n \"display_text\": {\n \"type\": \"string\",\n \"description\": \"Localized display text for this total\"\n },\n \"amount\": {\n \"type\": \"integer\",\n \"description\": \"Amount in minor currency units (e.g. 100 cents for $1.00 or 100 for ¥100)\"\n },\n \"presentment_amount\": {\n \"type\": \"integer\",\n \"description\": \"Amount in presentment currency minor units if different from settlement currency\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Additional descriptive text for this total\"\n },\n \"breakdown\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/TaxBreakdownItem\"\n },\n \"description\": \"Detailed breakdown for tax totals\"\n }\n },\n \"required\": [\n \"type\",\n \"display_text\",\n \"amount\"\n ],\n \"example\": {\n \"currency\": \"usd\",\n \"subtotal\": 5800,\n \"discount\": 0,\n \"tax\": 464,\n \"shipping\": 500,\n \"total\": 6764\n }\n },\n \"FulfillmentOptionPickup\": {\n \"description\": \"In-store or curbside pickup fulfillment option with pickup location details\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"pickup\",\n \"description\": \"Fulfillment type discriminator\"\n },\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for this fulfillment option\"\n },\n \"title\": {\n \"type\": \"string\",\n \"description\": \"Display title for this pickup option\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Additional details about this pickup option\"\n },\n \"location\": {\n \"type\": \"object\",\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Location name\"\n },\n \"address\": {\n \"$ref\": \"#/$defs/Address\",\n \"description\": \"Pickup address\"\n },\n \"phone\": {\n \"type\": \"string\",\n \"description\": \"Location phone number\"\n },\n \"instructions\": {\n \"type\": \"string\",\n \"description\": \"Special pickup instructions\"\n }\n },\n \"required\": [\n \"name\",\n \"address\"\n ],\n \"description\": \"Pickup location details\"\n },\n \"pickup_type\": {\n \"type\": \"string\",\n \"enum\": [\n \"in_store\",\n \"curbside\",\n \"locker\"\n ],\n \"description\": \"Type of pickup method\"\n },\n \"ready_by\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when order will be ready for pickup\"\n },\n \"pickup_by\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp by which order must be picked up\"\n },\n \"totals\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Total\"\n },\n \"description\": \"Cost breakdown for this fulfillment option\"\n }\n },\n \"required\": [\n \"type\",\n \"id\",\n \"title\",\n \"location\",\n \"totals\"\n ],\n \"example\": {\n \"id\": \"pickup_01\",\n \"type\": \"pickup\",\n \"name\": \"Store Pickup\",\n \"cost\": 0,\n \"currency\": \"usd\",\n \"address\": {\n \"name\": \"Downtown Store\",\n \"line_one\": \"123 Main St\",\n \"city\": \"San Francisco\",\n \"state\": \"CA\",\n \"country\": \"US\",\n \"postal_code\": \"94102\"\n }\n }\n },\n \"FulfillmentOptionLocalDelivery\": {\n \"description\": \"Local delivery fulfillment option with delivery address and scheduling details\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"local_delivery\",\n \"description\": \"Fulfillment type discriminator\"\n },\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for this fulfillment option\"\n },\n \"title\": {\n \"type\": \"string\",\n \"description\": \"Display title for this local delivery option\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Additional details about this delivery option\"\n },\n \"delivery_window\": {\n \"type\": \"object\",\n \"properties\": {\n \"start\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp for delivery window start\"\n },\n \"end\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp for delivery window end\"\n }\n },\n \"required\": [\n \"start\",\n \"end\"\n ],\n \"description\": \"Expected delivery time window\"\n },\n \"service_area\": {\n \"type\": \"object\",\n \"properties\": {\n \"radius_miles\": {\n \"type\": \"number\",\n \"description\": \"Delivery radius in miles\"\n },\n \"center_postal_code\": {\n \"type\": \"string\",\n \"description\": \"Center point postal code for delivery radius\"\n }\n },\n \"description\": \"Geographic service area for local delivery\"\n },\n \"totals\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Total\"\n },\n \"description\": \"Cost breakdown for this fulfillment option\"\n }\n },\n \"required\": [\n \"type\",\n \"id\",\n \"title\",\n \"totals\"\n ],\n \"example\": {\n \"id\": \"delivery_01\",\n \"type\": \"local_delivery\",\n \"name\": \"Same Day Delivery\",\n \"cost\": 999,\n \"currency\": \"usd\",\n \"address\": {\n \"name\": \"Jane Doe\",\n \"line_one\": \"456 Oak Ave\",\n \"city\": \"San Francisco\",\n \"state\": \"CA\",\n \"country\": \"US\",\n \"postal_code\": \"94103\"\n }\n }\n },\n \"FulfillmentOptionShipping\": {\n \"description\": \"Shipping fulfillment option with carrier, service level, and delivery estimates\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"shipping\",\n \"description\": \"Fulfillment type discriminator\"\n },\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for this fulfillment option\"\n },\n \"title\": {\n \"type\": \"string\",\n \"description\": \"Display title for this shipping option (e.g., 'Standard Shipping', 'Express')\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Additional details about this shipping option\"\n },\n \"carrier\": {\n \"type\": \"string\",\n \"description\": \"Shipping carrier name (e.g., 'USPS', 'FedEx')\"\n },\n \"earliest_delivery_time\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp for earliest expected delivery\"\n },\n \"latest_delivery_time\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp for latest expected delivery\"\n },\n \"totals\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Total\"\n },\n \"description\": \"Cost breakdown for this fulfillment option\"\n }\n },\n \"required\": [\n \"type\",\n \"id\",\n \"title\",\n \"totals\"\n ],\n \"example\": {\n \"id\": \"ship_01\",\n \"type\": \"shipping\",\n \"name\": \"Standard Shipping\",\n \"cost\": 500,\n \"currency\": \"usd\",\n \"carrier\": \"USPS\",\n \"service_level\": \"ground\"\n }\n },\n \"FulfillmentOptionDigital\": {\n \"description\": \"Digital delivery fulfillment option for downloadable or streaming content\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"digital\",\n \"description\": \"Fulfillment type discriminator\"\n },\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for this fulfillment option\"\n },\n \"title\": {\n \"type\": \"string\",\n \"description\": \"Display title for this digital delivery option\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Additional details about digital delivery method\"\n },\n \"totals\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Total\"\n },\n \"description\": \"Cost breakdown for this fulfillment option\"\n }\n },\n \"required\": [\n \"type\",\n \"id\",\n \"title\",\n \"totals\"\n ],\n \"example\": {\n \"id\": \"digital_01\",\n \"type\": \"digital\",\n \"name\": \"Instant Download\",\n \"cost\": 0,\n \"currency\": \"usd\"\n }\n },\n \"SelectedFulfillmentOption\": {\n \"description\": \"Fulfillment option selected by the buyer for specific line items\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"shipping\",\n \"digital\",\n \"pickup\",\n \"local_delivery\"\n ],\n \"description\": \"Type of fulfillment option selected\"\n },\n \"option_id\": {\n \"type\": \"string\",\n \"description\": \"ID of the selected fulfillment option\"\n },\n \"item_ids\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Line item identifier\"\n },\n \"description\": \"List of line item IDs associated with this fulfillment option\"\n }\n },\n \"required\": [\n \"type\",\n \"option_id\",\n \"item_ids\"\n ],\n \"example\": {\n \"id\": \"ship_01\",\n \"type\": \"shipping\",\n \"item_ids\": [\n \"item_001\",\n \"item_002\"\n ]\n }\n },\n \"GiftWrap\": {\n \"description\": \"Gift wrapping option with associated cost and customization details\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"enabled\": {\n \"type\": \"boolean\",\n \"description\": \"Whether gift wrapping is enabled for this order\"\n },\n \"style\": {\n \"type\": \"string\",\n \"enum\": [\n \"birthday\",\n \"holiday\",\n \"elegant\"\n ],\n \"description\": \"Gift wrap style selected\"\n },\n \"charge\": {\n \"type\": \"integer\",\n \"description\": \"Additional charge for gift wrapping in minor currency units (e.g. 100 cents for $1.00 or 100 for ¥100)\"\n }\n },\n \"required\": [\n \"enabled\"\n ],\n \"example\": {\n \"available\": true,\n \"cost\": 500,\n \"currency\": \"usd\",\n \"message\": \"Happy Birthday!\"\n }\n },\n \"SplitPayment\": {\n \"description\": \"Split payment configuration allowing payment across multiple methods or parties\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"amount\": {\n \"type\": \"integer\",\n \"description\": \"Payment amount in minor currency units (e.g. 100 cents for $1.00 or 100 for ¥100) for this split\"\n }\n },\n \"required\": [\n \"amount\"\n ],\n \"example\": {\n \"enabled\": true,\n \"methods\": [\n \"card\",\n \"paypal\"\n ]\n }\n },\n \"FulfillmentGroup\": {\n \"description\": \"Group of line items that share the same fulfillment method and destination\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for this fulfillment group\"\n },\n \"item_ids\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Line item identifier in this fulfillment group\"\n },\n \"description\": \"List of line item IDs in this fulfillment group\"\n },\n \"destination_type\": {\n \"type\": \"string\",\n \"enum\": [\n \"shipping\",\n \"pickup\",\n \"local_delivery\",\n \"digital\"\n ],\n \"description\": \"Type of fulfillment for this group\"\n },\n \"fulfillment_details\": {\n \"$ref\": \"#/$defs/FulfillmentDetails\",\n \"description\": \"Fulfillment contact and address details\"\n },\n \"location_id\": {\n \"type\": \"string\",\n \"description\": \"Location identifier for pickup or local delivery\"\n },\n \"instructions\": {\n \"type\": \"string\",\n \"description\": \"Special fulfillment instructions\"\n }\n },\n \"required\": [\n \"id\",\n \"item_ids\",\n \"destination_type\"\n ],\n \"example\": {\n \"id\": \"fg_01\",\n \"fulfillment_option_id\": \"ship_01\",\n \"item_ids\": [\n \"item_001\",\n \"item_002\"\n ]\n }\n },\n \"EstimatedDelivery\": {\n \"description\": \"Estimated delivery date range for a fulfillment option\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"earliest\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp for earliest expected delivery\"\n },\n \"latest\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp for latest expected delivery\"\n }\n },\n \"required\": [\n \"earliest\",\n \"latest\"\n ],\n \"example\": {\n \"earliest\": \"2026-02-15\",\n \"latest\": \"2026-02-20\"\n }\n },\n \"OrderConfirmation\": {\n \"description\": \"Order confirmation details including order number and tracking information\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"confirmation_number\": {\n \"type\": \"string\",\n \"description\": \"Order confirmation number\"\n },\n \"confirmation_email_sent\": {\n \"type\": \"boolean\",\n \"description\": \"Whether a confirmation email has been sent\"\n },\n \"receipt_url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to the order receipt\"\n },\n \"invoice_number\": {\n \"type\": \"string\",\n \"description\": \"Invoice number if generated\"\n },\n \"order_notes\": {\n \"type\": \"string\",\n \"description\": \"Echo of order_notes attached to the order.\"\n }\n },\n \"example\": {\n \"order_id\": \"ord_abc123\",\n \"order_number\": \"12345\",\n \"confirmation_url\": \"https://example.com/orders/ord_abc123\"\n }\n },\n \"SupportInfo\": {\n \"description\": \"Customer support contact information including email, phone, and URL\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"email\": {\n \"type\": \"string\",\n \"format\": \"email\",\n \"description\": \"Support contact email\"\n },\n \"phone\": {\n \"type\": \"string\",\n \"description\": \"Support contact phone number\"\n },\n \"hours\": {\n \"type\": \"string\",\n \"description\": \"Support hours of operation\"\n },\n \"help_center_url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to merchant's help center\"\n }\n },\n \"example\": {\n \"email\": \"support@example.com\",\n \"phone\": \"+1-800-555-0123\",\n \"url\": \"https://example.com/support\"\n }\n },\n \"MessageInfo\": {\n \"description\": \"Informational message to display to the buyer during checkout\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"info\",\n \"description\": \"Message type discriminator\"\n },\n \"severity\": {\n \"type\": \"string\",\n \"enum\": [\n \"info\",\n \"low\",\n \"medium\",\n \"high\",\n \"critical\"\n ],\n \"description\": \"Severity level of this informational message\"\n },\n \"resolution\": {\n \"type\": \"string\",\n \"enum\": [\n \"recoverable\",\n \"requires_buyer_input\",\n \"requires_buyer_review\"\n ],\n \"description\": \"Who resolves this message. 'recoverable': agent can fix via API. 'requires_buyer_input': buyer must provide info. 'requires_buyer_review': buyer must authorize.\"\n },\n \"param\": {\n \"type\": \"string\",\n \"description\": \"RFC 9535 JSONPath\"\n },\n \"content_type\": {\n \"type\": \"string\",\n \"enum\": [\n \"plain\",\n \"markdown\"\n ],\n \"description\": \"Format of the message content. When set to 'markdown', content MUST conform to CommonMark (https://spec.commonmark.org/0.31.2/). Raw HTML elements MUST NOT be included. When set to 'plain', content is plain text with no formatting.\"\n },\n \"content\": {\n \"type\": \"string\",\n \"description\": \"Informational message text. When content_type is 'markdown', this MUST be valid CommonMark with no raw HTML. Agents MUST render using a CommonMark-compliant parser with raw HTML output disabled or sanitized.\"\n }\n },\n \"required\": [\n \"type\",\n \"content_type\",\n \"content\"\n ],\n \"example\": {\n \"id\": \"msg_info_01\",\n \"message\": \"Free shipping on orders over $50\",\n \"display_context\": \"banner\"\n }\n },\n \"MessageWarning\": {\n \"description\": \"Warning message to display to the buyer during checkout (non-blocking)\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"warning\",\n \"description\": \"Message type discriminator\"\n },\n \"code\": {\n \"type\": \"string\",\n \"enum\": [\n \"low_stock\",\n \"high_demand\",\n \"shipping_delay\",\n \"price_change\",\n \"expiring_promotion\",\n \"limited_availability\",\n \"discount_code_expired\",\n \"discount_code_invalid\",\n \"discount_code_already_applied\",\n \"discount_code_combination_disallowed\",\n \"discount_code_minimum_not_met\",\n \"discount_code_user_not_logged_in\",\n \"discount_code_user_ineligible\",\n \"discount_code_usage_limit_reached\"\n ],\n \"description\": \"Warning code indicating the type of warning\"\n },\n \"severity\": {\n \"type\": \"string\",\n \"enum\": [\n \"info\",\n \"low\",\n \"medium\",\n \"high\",\n \"critical\"\n ],\n \"description\": \"Severity level of this warning\"\n },\n \"resolution\": {\n \"type\": \"string\",\n \"enum\": [\n \"recoverable\",\n \"requires_buyer_input\",\n \"requires_buyer_review\"\n ],\n \"description\": \"Who resolves this message. 'recoverable': agent can fix via API. 'requires_buyer_input': buyer must provide info. 'requires_buyer_review': buyer must authorize.\"\n },\n \"param\": {\n \"type\": \"string\",\n \"description\": \"RFC 9535 JSONPath\"\n },\n \"content_type\": {\n \"type\": \"string\",\n \"enum\": [\n \"plain\",\n \"markdown\"\n ],\n \"description\": \"Format of the warning message content. When set to 'markdown', content MUST conform to CommonMark (https://spec.commonmark.org/0.31.2/). Raw HTML elements MUST NOT be included. When set to 'plain', content is plain text with no formatting.\"\n },\n \"content\": {\n \"type\": \"string\",\n \"description\": \"Warning message text. When content_type is 'markdown', this MUST be valid CommonMark with no raw HTML. Agents MUST render using a CommonMark-compliant parser with raw HTML output disabled or sanitized.\"\n }\n },\n \"required\": [\n \"type\",\n \"code\",\n \"content_type\",\n \"content\"\n ],\n \"example\": {\n \"id\": \"msg_warn_01\",\n \"message\": \"Only 2 items left in stock\",\n \"code\": \"low_stock\",\n \"param\": \"$.items[0]\"\n }\n },\n \"MessageError\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Business-logic error within a valid CheckoutSession response. Used in messages[] on 2xx responses when the session is valid but has actionable issues (e.g. status \\\"not_ready_for_payment\\\"). The agent can respond by asking the buyer for corrections or trying alternatives. Use MessageError—not Error—when you can return a valid CheckoutSession and the problem is conversational (e.g. invalid email → code \\\"invalid\\\" and param \\\"$.buyer.email\\\"; out of stock → code \\\"out_of_stock\\\" and param \\\"$.items[0]\\\").\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"error\",\n \"description\": \"Message type discriminator\"\n },\n \"code\": {\n \"type\": \"string\",\n \"enum\": [\n \"missing\",\n \"invalid\",\n \"out_of_stock\",\n \"payment_declined\",\n \"requires_sign_in\",\n \"requires_3ds\",\n \"low_stock\",\n \"quantity_exceeded\",\n \"coupon_invalid\",\n \"coupon_expired\",\n \"minimum_not_met\",\n \"maximum_exceeded\",\n \"region_restricted\",\n \"age_verification_required\",\n \"approval_required\",\n \"unsupported\",\n \"not_found\",\n \"conflict\",\n \"rate_limited\",\n \"expired\",\n \"intervention_required\"\n ],\n \"description\": \"Error code indicating the type of error\"\n },\n \"severity\": {\n \"type\": \"string\",\n \"enum\": [\n \"info\",\n \"low\",\n \"medium\",\n \"high\",\n \"critical\"\n ],\n \"description\": \"Severity level of this error\"\n },\n \"resolution\": {\n \"type\": \"string\",\n \"enum\": [\n \"recoverable\",\n \"requires_buyer_input\",\n \"requires_buyer_review\"\n ],\n \"description\": \"Who resolves this message. 'recoverable': agent can fix via API. 'requires_buyer_input': buyer must provide info. 'requires_buyer_review': buyer must authorize.\"\n },\n \"param\": {\n \"type\": \"string\",\n \"description\": \"RFC 9535 JSONPath\"\n },\n \"content_type\": {\n \"type\": \"string\",\n \"enum\": [\n \"plain\",\n \"markdown\"\n ],\n \"description\": \"Format of the error message content. When set to 'markdown', content MUST conform to CommonMark (https://spec.commonmark.org/0.31.2/). Raw HTML elements MUST NOT be included. When set to 'plain', content is plain text with no formatting.\"\n },\n \"content\": {\n \"type\": \"string\",\n \"description\": \"Error message text. When content_type is 'markdown', this MUST be valid CommonMark with no raw HTML. Agents MUST render using a CommonMark-compliant parser with raw HTML output disabled or sanitized.\"\n }\n },\n \"required\": [\n \"type\",\n \"code\",\n \"content_type\",\n \"content\"\n ],\n \"example\": {\n \"id\": \"msg_err_01\",\n \"message\": \"Invalid email address format\",\n \"code\": \"invalid\",\n \"param\": \"$.buyer.email\"\n }\n },\n \"Link\": {\n \"description\": \"Hyperlink with URL, display text, and optional action semantics\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"terms_of_use\",\n \"privacy_policy\",\n \"return_policy\",\n \"shipping_policy\",\n \"contact_us\",\n \"about_us\",\n \"faq\",\n \"support\"\n ],\n \"description\": \"Type of link\"\n },\n \"title\": {\n \"type\": \"string\",\n \"description\": \"Display text for the link\"\n },\n \"url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL destination\"\n }\n },\n \"required\": [\n \"type\",\n \"url\"\n ],\n \"example\": {\n \"url\": \"https://example.com/terms\",\n \"text\": \"Terms of Service\",\n \"action\": \"view\"\n }\n },\n \"PaymentData\": {\n \"description\": \"Payment instrument data collected from the buyer (e.g., card details, wallet tokens)\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"handler_id\": {\n \"type\": \"string\",\n \"description\": \"ID of the payment handler to use\"\n },\n \"instrument\": {\n \"type\": \"object\",\n \"description\": \"Payment instrument details\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"description\": \"Instrument type (e.g., card, wallet_token)\"\n },\n \"credential\": {\n \"type\": \"object\",\n \"description\": \"Payment credential\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"description\": \"Credential type (e.g., spt, wallet_token)\"\n },\n \"token\": {\n \"type\": \"string\",\n \"description\": \"Credential token value\"\n }\n },\n \"required\": [\n \"type\",\n \"token\"\n ]\n }\n },\n \"required\": [\n \"type\",\n \"credential\"\n ]\n },\n \"billing_address\": {\n \"$ref\": \"#/$defs/Address\",\n \"description\": \"Billing address for the payment\"\n },\n \"purchase_order_number\": {\n \"type\": \"string\",\n \"description\": \"Purchase order number\"\n },\n \"payment_terms\": {\n \"type\": \"string\",\n \"enum\": [\n \"immediate\",\n \"net_15\",\n \"net_30\",\n \"net_60\",\n \"net_90\"\n ],\n \"description\": \"Payment terms for B2B transactions\"\n },\n \"due_date\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when payment is due\"\n },\n \"approval_required\": {\n \"type\": \"boolean\",\n \"description\": \"Whether this payment requires approval\"\n }\n },\n \"anyOf\": [\n {\n \"required\": [\n \"handler_id\",\n \"instrument\"\n ]\n },\n {\n \"required\": [\n \"purchase_order_number\"\n ]\n }\n ],\n \"example\": {\n \"type\": \"vault_token\",\n \"token\": \"vt_01J8Z3WXYZ9ABC123\"\n }\n },\n \"ProtocolVersion\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Protocol metadata included in checkout responses. Indicates the ACP version.\",\n \"properties\": {\n \"version\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{4}-\\\\d{2}-\\\\d{2}$\",\n \"example\": \"2026-01-27\",\n \"description\": \"ACP protocol version in YYYY-MM-DD format.\"\n }\n },\n \"required\": [\n \"version\"\n ],\n \"example\": {\n \"version\": \"2026-04-17\"\n }\n },\n \"DiscountAllocation\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Breakdown of how a discount amount was allocated to a specific target.\",\n \"required\": [\n \"path\",\n \"amount\"\n ],\n \"properties\": {\n \"path\": {\n \"type\": \"string\",\n \"description\": \"JSONPath to the allocation target (e.g., '$.line_items[0]', '$.totals.shipping').\"\n },\n \"amount\": {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"description\": \"Amount allocated to this target in minor (cents) currency units.\"\n }\n },\n \"example\": {\n \"target\": \"line_item\",\n \"target_id\": \"item_001\",\n \"amount\": 500\n }\n },\n \"Coupon\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Coupon details describing the discount terms.\",\n \"required\": [\n \"id\",\n \"name\"\n ],\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for the coupon.\"\n },\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Human-readable coupon name (e.g., 'Summer Sale 20% Off').\"\n },\n \"percent_off\": {\n \"type\": \"number\",\n \"minimum\": 0,\n \"maximum\": 100,\n \"description\": \"Percentage discount (0-100). Mutually exclusive with amount_off.\"\n },\n \"amount_off\": {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"description\": \"Fixed discount amount in minor currency units. Mutually exclusive with percent_off.\"\n },\n \"currency\": {\n \"type\": \"string\",\n \"pattern\": \"^[a-z]{3}$\",\n \"description\": \"ISO 4217 currency code for amount_off. Required if amount_off is set.\"\n },\n \"duration\": {\n \"type\": \"string\",\n \"enum\": [\n \"once\",\n \"repeating\",\n \"forever\"\n ],\n \"description\": \"How long the discount applies. 'once' = single use, 'repeating' = multiple billing periods, 'forever' = indefinitely.\"\n },\n \"duration_in_months\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"description\": \"Number of months the coupon applies if duration is 'repeating'.\"\n },\n \"max_redemptions\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"description\": \"Maximum number of times this coupon can be redeemed across all customers.\"\n },\n \"times_redeemed\": {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"description\": \"Number of times this coupon has been redeemed.\"\n },\n \"metadata\": {\n \"type\": \"object\",\n \"additionalProperties\": {\n \"type\": \"string\",\n \"description\": \"Metadata value\"\n },\n \"description\": \"Arbitrary key-value metadata attached to the coupon.\"\n }\n },\n \"example\": {\n \"code\": \"SAVE20\",\n \"metadata\": {}\n }\n },\n \"AppliedDiscount\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"A discount that was successfully applied to the checkout session.\",\n \"required\": [\n \"id\",\n \"coupon\",\n \"amount\"\n ],\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for this applied discount instance.\"\n },\n \"code\": {\n \"type\": \"string\",\n \"description\": \"The discount code entered by the user. Omitted for automatic discounts.\"\n },\n \"coupon\": {\n \"$ref\": \"#/$defs/Coupon\",\n \"description\": \"Details about the underlying coupon/promotion.\"\n },\n \"amount\": {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"description\": \"Total discount amount in minor (cents) currency units.\"\n },\n \"automatic\": {\n \"type\": \"boolean\",\n \"default\": false,\n \"description\": \"True if applied automatically by merchant rules (no code required).\"\n },\n \"start\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when the discount became active.\"\n },\n \"end\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when the discount expires.\"\n },\n \"method\": {\n \"type\": \"string\",\n \"enum\": [\n \"each\",\n \"across\"\n ],\n \"description\": \"Allocation method. 'each' = applied independently per item. 'across' = split proportionally by value.\"\n },\n \"priority\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"description\": \"Stacking order for discount calculation. Lower numbers applied first (1 = first).\"\n },\n \"allocations\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/DiscountAllocation\"\n },\n \"description\": \"Breakdown of where this discount was allocated. Sum of allocation amounts equals total amount.\"\n }\n },\n \"example\": {\n \"code\": \"SAVE20\",\n \"amount\": 1000,\n \"allocations\": []\n }\n },\n \"DiscountsRequest\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Discount codes input for checkout create/update requests.\",\n \"properties\": {\n \"codes\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Discount code to apply\"\n },\n \"description\": \"Discount codes to apply. Case-insensitive. Replaces previously submitted codes. Send empty array to clear.\"\n }\n },\n \"example\": {\n \"codes\": [\n \"SAVE20\",\n \"FREESHIP\"\n ]\n }\n },\n \"DiscountsResponse\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Discount codes input and applied discounts output in checkout responses.\",\n \"properties\": {\n \"codes\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Discount code submitted\"\n },\n \"description\": \"Echo of submitted discount codes.\"\n },\n \"applied\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/AppliedDiscount\"\n },\n \"description\": \"Discounts successfully applied (code-based and automatic).\"\n },\n \"rejected\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/RejectedDiscount\"\n },\n \"description\": \"Discount codes that could not be applied, with reasons.\"\n }\n },\n \"example\": {\n \"codes\": [\n \"SAVE20\"\n ],\n \"applied\": [],\n \"rejected\": []\n }\n },\n \"RejectedDiscount\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"A discount code that could not be applied, with the reason.\",\n \"required\": [\n \"code\",\n \"reason\"\n ],\n \"properties\": {\n \"code\": {\n \"type\": \"string\",\n \"description\": \"The discount code that was rejected.\"\n },\n \"reason\": {\n \"$ref\": \"#/$defs/DiscountErrorCode\",\n \"description\": \"Error code indicating why the discount was rejected.\"\n },\n \"message\": {\n \"type\": \"string\",\n \"description\": \"Human-readable explanation of why the code was rejected.\"\n }\n },\n \"example\": {\n \"code\": \"EXPIRED10\",\n \"reason\": \"discount_code_expired\"\n }\n },\n \"DiscountErrorCode\": {\n \"type\": \"string\",\n \"enum\": [\n \"discount_code_expired\",\n \"discount_code_invalid\",\n \"discount_code_already_applied\",\n \"discount_code_combination_disallowed\",\n \"discount_code_minimum_not_met\",\n \"discount_code_user_not_logged_in\",\n \"discount_code_user_ineligible\",\n \"discount_code_usage_limit_reached\"\n ],\n \"description\": \"Error codes for rejected discount codes, used in messages[].code.\",\n \"example\": \"discount_code_expired\"\n },\n \"PaymentResponse\": {\n \"description\": \"Payment configuration returned by the seller including accepted methods and handlers\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"provider\": {\n \"type\": \"string\",\n \"description\": \"Payment provider identifier\"\n },\n \"instruments\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"additionalProperties\": true,\n \"description\": \"Payment instrument schema reference\"\n },\n \"description\": \"Available payment instruments\"\n },\n \"handlers\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"additionalProperties\": true,\n \"description\": \"Payment handler configuration\"\n },\n \"description\": \"Available payment handlers\"\n }\n },\n \"example\": {\n \"instruments\": [],\n \"handlers\": []\n }\n },\n \"RiskSignals\": {\n \"description\": \"Risk and fraud detection signals for the checkout session\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"ip_address\": {\n \"type\": \"string\",\n \"description\": \"IP address of the buyer\"\n },\n \"user_agent\": {\n \"type\": \"string\",\n \"description\": \"User agent string of the buyer's browser\"\n },\n \"accept_language\": {\n \"type\": \"string\",\n \"description\": \"Accept-Language header from the buyer's browser\"\n },\n \"session_id\": {\n \"type\": \"string\",\n \"description\": \"Session identifier for the buyer\"\n },\n \"device_fingerprint\": {\n \"type\": \"string\",\n \"description\": \"Device fingerprint for fraud detection\"\n }\n },\n \"example\": {\n \"ip_country\": \"US\",\n \"device_fingerprint\": \"fp_abc123\"\n }\n },\n \"Order\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Order returned after checkout completion. Contains order details and optional rich post-purchase tracking.\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"order\",\n \"description\": \"Discriminator field for webhook payloads. Always 'order' when present.\"\n },\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for the order\"\n },\n \"checkout_session_id\": {\n \"type\": \"string\",\n \"description\": \"ID of the checkout session that created this order\"\n },\n \"order_number\": {\n \"type\": \"string\",\n \"description\": \"Human-readable order number for customer reference\"\n },\n \"client_reference_id\": {\n \"type\": \"string\",\n \"description\": \"Reference from the client (agent/platform) stored on the order for reconciliation (e.g. platform transaction id, PO number, ERP id).\"\n },\n \"permalink_url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"Permanent URL where the customer can view order details\"\n },\n \"status\": {\n \"type\": \"string\",\n \"description\": \"Order-level status. Implementations MUST accept unrecognized values gracefully. Defined values: 'created', 'confirmed', 'manual_review', 'processing', 'shipped', 'completed', 'canceled'. 'completed' means all items have been delivered/received regardless of fulfillment method. Distinct from LineItem.status 'fulfilled', which indicates the seller has dispatched the item.\"\n },\n \"estimated_delivery\": {\n \"$ref\": \"#/$defs/EstimatedDelivery\",\n \"description\": \"Estimated delivery time range\"\n },\n \"confirmation\": {\n \"$ref\": \"#/$defs/OrderConfirmation\",\n \"description\": \"Order confirmation details\"\n },\n \"support\": {\n \"$ref\": \"#/$defs/SupportInfo\",\n \"description\": \"Customer support contact information\"\n },\n \"line_items\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/OrderLineItem\"\n },\n \"description\": \"What was ordered, with per-item fulfillment tracking\"\n },\n \"fulfillments\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Fulfillment\"\n },\n \"description\": \"How items are being delivered (shipping, pickup, digital)\"\n },\n \"adjustments\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Adjustment\"\n },\n \"description\": \"Post-order changes: refunds, credits, returns, disputes\"\n },\n \"totals\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Total\"\n },\n \"description\": \"Order-level totals using the same Total schema as checkout. The 'total' entry is always the original charged amount. 'amount_refunded' tracks cumulative refunds.\"\n }\n },\n \"required\": [\n \"id\",\n \"checkout_session_id\",\n \"permalink_url\"\n ],\n \"example\": {\n \"id\": \"ord_abc123\",\n \"order_number\": \"12345\",\n \"status\": \"confirmed\",\n \"currency\": \"usd\",\n \"total\": 6764,\n \"line_items\": [],\n \"created_at\": \"2026-02-13T10:30:00Z\"\n }\n },\n \"OrderLineItem\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Per-line-item tracking of what was ordered and fulfillment progress.\",\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Line item identifier, used for references in fulfillments and adjustments\"\n },\n \"title\": {\n \"type\": \"string\",\n \"description\": \"Product name\"\n },\n \"product_id\": {\n \"type\": \"string\",\n \"description\": \"Catalog product ID\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Product description\"\n },\n \"image_url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"Product image URL\"\n },\n \"url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"Product page URL\"\n },\n \"quantity\": {\n \"$ref\": \"#/$defs/OrderLineItemQuantity\"\n },\n \"unit_price\": {\n \"type\": \"integer\",\n \"description\": \"Price per unit in minor currency units (cents)\"\n },\n \"subtotal\": {\n \"type\": \"integer\",\n \"description\": \"Line total in minor currency units\"\n },\n \"totals\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Total\"\n },\n \"description\": \"Optional line-item level totals breakdown using the same Total schema as checkout. Merchants who can provide richer breakdowns MAY use this alongside or instead of unit_price/subtotal.\"\n },\n \"status\": {\n \"type\": \"string\",\n \"description\": \"Derived from quantity fields. Implementations MUST accept unrecognized values gracefully. Defined values: 'processing', 'partial', 'fulfilled', 'removed'. Rules: 'removed' if current==0, 'fulfilled' if fulfilled==current, 'partial' if 0<fulfilled<current, 'processing' otherwise.\"\n }\n },\n \"required\": [\n \"id\",\n \"title\",\n \"quantity\"\n ],\n \"example\": {\n \"id\": \"oli_001\",\n \"title\": \"Running Shoes\",\n \"status\": \"fulfilled\",\n \"quantity\": {\n \"ordered\": 2,\n \"current\": 2,\n \"fulfilled\": 2\n }\n }\n },\n \"OrderLineItemQuantity\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Quantity tracking for an order line item. Uses a 3-field model: ordered (original), current (active after cancellations/returns), fulfilled (completed).\",\n \"properties\": {\n \"ordered\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"description\": \"Quantity originally ordered by the customer\"\n },\n \"current\": {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"description\": \"Current active quantity on the order. May be less than ordered due to cancellations or returns. A value of 0 means the line item has been fully removed.\"\n },\n \"fulfilled\": {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"default\": 0,\n \"description\": \"Quantity that has been fulfilled (shipped, picked up, or digitally delivered). Applies to all fulfillment types, not just shipping.\"\n }\n },\n \"required\": [\n \"ordered\",\n \"current\"\n ],\n \"example\": {\n \"ordered\": 3,\n \"current\": 3,\n \"fulfilled\": 2\n }\n },\n \"LineItemReference\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Reference to a line item with quantity, used in fulfillments and adjustments\",\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Line item ID reference\"\n },\n \"quantity\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"description\": \"Quantity in this fulfillment or adjustment\"\n }\n },\n \"required\": [\n \"id\",\n \"quantity\"\n ],\n \"example\": {\n \"line_item_id\": \"item_001\",\n \"quantity\": 1\n }\n },\n \"Fulfillment\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"A fulfillment represents how items are delivered to the buyer (shipping, pickup, digital).\",\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Fulfillment identifier\"\n },\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"shipping\",\n \"pickup\",\n \"digital\"\n ],\n \"description\": \"Fulfillment method type\"\n },\n \"status\": {\n \"type\": \"string\",\n \"description\": \"Current fulfillment status. Implementations MUST accept unrecognized values gracefully. Defined values: 'pending', 'processing', 'shipped', 'in_transit', 'out_for_delivery', 'ready_for_pickup', 'delivered', 'failed', 'canceled'. Not all statuses apply to all types.\"\n },\n \"line_items\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/LineItemReference\"\n },\n \"description\": \"Which line items and quantities are in this fulfillment\"\n },\n \"carrier\": {\n \"type\": \"string\",\n \"description\": \"Carrier name (e.g., 'FedEx', 'UPS', 'USPS'). Applies to type: shipping.\"\n },\n \"tracking_number\": {\n \"type\": \"string\",\n \"description\": \"Carrier tracking number. Applies to type: shipping.\"\n },\n \"tracking_url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to track this shipment. Applies to type: shipping.\"\n },\n \"destination\": {\n \"$ref\": \"#/$defs/Address\"\n },\n \"estimated_delivery\": {\n \"$ref\": \"#/$defs/EstimatedDelivery\"\n },\n \"digital_delivery\": {\n \"type\": \"object\",\n \"description\": \"Digital delivery details. Applies to type: digital.\",\n \"properties\": {\n \"access_url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to access digital content (download link, streaming page, etc.)\"\n },\n \"license_key\": {\n \"type\": \"string\",\n \"description\": \"License or activation key\"\n },\n \"expires_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"When access expires (RFC 3339 timestamp)\"\n }\n }\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Human-readable description (e.g., 'Backordered - ships Feb 15')\"\n },\n \"events\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/FulfillmentEvent\"\n },\n \"description\": \"Append-only event log tracking fulfillment progress\"\n }\n },\n \"required\": [\n \"id\",\n \"type\"\n ],\n \"example\": {\n \"id\": \"ful_001\",\n \"type\": \"shipping\",\n \"status\": \"shipped\",\n \"line_items\": [],\n \"tracking_number\": \"1Z999AA10123456784\",\n \"carrier\": \"UPS\"\n }\n },\n \"FulfillmentEvent\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"A point-in-time event in the fulfillment lifecycle.\",\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Event identifier\"\n },\n \"type\": {\n \"type\": \"string\",\n \"description\": \"Event type. Implementations MUST accept unrecognized values gracefully. Defined values: 'processing', 'shipped', 'in_transit', 'out_for_delivery', 'ready_for_pickup', 'delivered', 'failed_attempt', 'returned_to_sender', 'canceled', 'undeliverable'. 'out_for_delivery' and 'ready_for_pickup' are ACP extensions for richer agent experiences.\"\n },\n \"occurred_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when this event occurred\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Human-readable description (e.g., 'Left at front door')\"\n },\n \"location\": {\n \"type\": \"string\",\n \"description\": \"Location where this event occurred (e.g., 'Memphis, TN')\"\n }\n },\n \"required\": [\n \"id\",\n \"type\",\n \"occurred_at\"\n ],\n \"example\": {\n \"status\": \"shipped\",\n \"timestamp\": \"2026-02-13T14:00:00Z\",\n \"location\": \"San Francisco, CA\"\n }\n },\n \"Adjustment\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"A post-order change such as refund, credit, return, or dispute.\",\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Adjustment identifier\"\n },\n \"type\": {\n \"type\": \"string\",\n \"description\": \"Type of adjustment. Implementations MUST accept unrecognized values gracefully. Defined values: 'refund', 'credit', 'return', 'exchange', 'price_adjustment', 'cancellation', 'dispute'. Use 'refund' for both full and partial refunds (distinguish by amount). 'credit' replaces 'store_credit'. 'dispute' covers chargebacks.\"\n },\n \"occurred_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when this adjustment occurred\"\n },\n \"status\": {\n \"type\": \"string\",\n \"description\": \"Adjustment status. Implementations MUST accept unrecognized values gracefully. Defined values: 'pending', 'completed', 'failed'.\"\n },\n \"line_items\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/LineItemReference\"\n },\n \"description\": \"Which line items and quantities are affected\"\n },\n \"amount\": {\n \"type\": \"integer\",\n \"description\": \"Total amount credited to the buyer in minor currency units, inclusive of any applicable tax\"\n },\n \"currency\": {\n \"type\": \"string\",\n \"pattern\": \"^[a-z]{3}$\",\n \"description\": \"ISO 4217 currency code\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Human-readable reason (e.g., 'Defective item')\"\n },\n \"reason\": {\n \"type\": \"string\",\n \"description\": \"Structured reason code\"\n }\n },\n \"required\": [\n \"id\",\n \"type\",\n \"occurred_at\",\n \"status\"\n ],\n \"example\": {\n \"id\": \"adj_001\",\n \"type\": \"refund\",\n \"amount\": 1000,\n \"currency\": \"usd\",\n \"reason\": \"Customer request\",\n \"created_at\": \"2026-02-14T10:00:00Z\"\n }\n },\n \"AuthenticationMetadata\": {\n \"type\": \"object\",\n \"additionalProperties\": true,\n \"description\": \"Seller-provided authentication metadata for 3DS flows.\",\n \"required\": [\n \"acquirer_details\",\n \"directory_server\"\n ],\n \"properties\": {\n \"acquirer_details\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Details about the acquirer used for this 3DS Authentication. This object MUST be present.\",\n \"properties\": {\n \"acquirer_bin\": {\n \"type\": \"string\",\n \"maxLength\": 11,\n \"description\": \"The Acquirer BIN (directory-server specific).\"\n },\n \"acquirer_country\": {\n \"type\": \"string\",\n \"minLength\": 2,\n \"maxLength\": 2,\n \"description\": \"Two-letter ISO 3166-1 alpha-2 country code.\"\n },\n \"acquirer_merchant_id\": {\n \"type\": \"string\",\n \"maxLength\": 35,\n \"description\": \"The Merchant ID assigned by the acquirer.\"\n },\n \"merchant_name\": {\n \"type\": \"string\",\n \"maxLength\": 40,\n \"description\": \"Merchant name assigned by the acquirer.\"\n },\n \"requestor_id\": {\n \"type\": \"string\",\n \"maxLength\": 35,\n \"description\": \"Requestor ID (if required by the directory server).\"\n }\n },\n \"required\": [\n \"acquirer_bin\",\n \"acquirer_country\",\n \"acquirer_merchant_id\",\n \"merchant_name\"\n ]\n },\n \"directory_server\": {\n \"type\": \"string\",\n \"enum\": [\n \"american_express\",\n \"mastercard\",\n \"visa\"\n ],\n \"description\": \"The 3DS directory server used for this Authentication.\"\n },\n \"flow_preference\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Contains additional details on the seller's preference for the 3DS authentication flow. Sellers MAY request a preference, but issuers ultimately decide the actual flow.\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"challenge\",\n \"frictionless\"\n ],\n \"description\": \"Type of flow requested for this 3DS Authentication. 'challenge' requests a challenge flow; 'frictionless' requests a frictionless flow.\"\n },\n \"challenge\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Details about the requested challenge flow.\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"mandated\",\n \"preferred\"\n ],\n \"description\": \"Subtype of challenge preference.\"\n }\n }\n },\n \"frictionless\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Details about the requested frictionless flow.\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"low_risk\"\n ],\n \"description\": \"Subtype of frictionless preference.\"\n }\n }\n }\n },\n \"required\": [\n \"type\"\n ]\n }\n },\n \"example\": {\n \"three_ds_version\": \"2.1.0\",\n \"merchant_name\": \"Example Store\"\n }\n },\n \"AuthenticationResult\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Agent-provided authentication results returned to the seller for card-based 3D Secure.\",\n \"properties\": {\n \"outcome\": {\n \"type\": \"string\",\n \"description\": \"The outcome of this 3DS Authentication.\",\n \"enum\": [\n \"abandoned\",\n \"attempt_acknowledged\",\n \"authenticated\",\n \"canceled\",\n \"denied\",\n \"informational\",\n \"internal_error\",\n \"not_supported\",\n \"processing_error\",\n \"rejected\"\n ],\n \"example\": \"authenticated\"\n },\n \"outcome_details\": {\n \"type\": \"object\",\n \"description\": \"Detailed authentication data. This field is required when the outcome is 'authenticated', 'informational', or 'attempt_acknowledged'.\",\n \"additionalProperties\": false,\n \"properties\": {\n \"three_ds_cryptogram\": {\n \"type\": \"string\",\n \"description\": \"The 3DS cryptogram (authentication value / AAV/CAVV/AEVV). This value is 20 bytes, base64-encoded into a 28-character string.\",\n \"example\": \"AbCdEfGhIjKlMnOpQrStUvWxY0=\"\n },\n \"electronic_commerce_indicator\": {\n \"type\": \"string\",\n \"description\": \"Electronic Commerce Indicator (ECI) returned by the 3D Secure provider. Indicates the degree/type of authentication performed.\",\n \"enum\": [\n \"01\",\n \"02\",\n \"05\",\n \"06\",\n \"07\"\n ],\n \"example\": \"05\"\n },\n \"transaction_id\": {\n \"type\": \"string\",\n \"description\": \"Transaction identifier returned by the 3DS system:\\n- For 3DS1: the XID\\n- For 3DS2: the Directory Server Transaction ID (dsTransID)\",\n \"example\": \"dsTransId_abc123\"\n },\n \"version\": {\n \"type\": \"string\",\n \"description\": \"The 3D Secure version used for this authentication (for example '1.0.2' or '2.2.0').\",\n \"example\": \"2.2.0\"\n }\n },\n \"required\": [\n \"three_ds_cryptogram\",\n \"electronic_commerce_indicator\",\n \"transaction_id\",\n \"version\"\n ]\n }\n },\n \"required\": [\n \"outcome\"\n ],\n \"allOf\": [\n {\n \"if\": {\n \"properties\": {\n \"outcome\": {\n \"enum\": [\n \"authenticated\",\n \"informational\",\n \"attempt_acknowledged\"\n ]\n }\n }\n },\n \"then\": {\n \"required\": [\n \"outcome_details\"\n ]\n }\n }\n ],\n \"example\": {\n \"status\": \"authenticated\",\n \"transaction_id\": \"3ds_abc123\",\n \"eci\": \"05\"\n }\n },\n \"MarketingConsentOption\": {\n \"description\": \"Seller-declared marketing consent option that specifies an available channel for which the seller must obtain the buyer's consent before sending marketing content\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"channel\": {\n \"type\": \"string\",\n \"description\": \"Channel for marketing consent.\",\n \"examples\": [\"email\", \"sms\", \"whatsapp\"]\n },\n \"display_text\": {\n \"type\": \"string\",\n \"description\": \"What the buyer is consenting to receive, e.g., 'promotional emails, product launches, and exclusive offers'. Agents MAY use this to compose their own consent prompt.\"\n },\n \"privacy_policy_url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to the seller's privacy policy governing use of the buyer's contact information for marketing.\"\n },\n \"is_subscribed\": {\n \"type\": \"boolean\",\n \"description\": \"Whether the buyer is currently subscribed to marketing via this channel. When true, agents SHOULD render the consent checkbox as pre-checked. Defaults to false if omitted.\"\n }\n },\n \"required\": [\n \"channel\",\n \"display_text\",\n \"privacy_policy_url\"\n ],\n \"example\": {\n \"channel\": \"email\",\n \"display_text\": \"Promotional emails, product launches, and exclusive offers\",\n \"privacy_policy_url\": \"https://www.example.com/privacy\",\n \"is_subscribed\": false\n }\n },\n \"MarketingConsent\": {\n \"description\": \"Buyer's marketing consent decision for a specific channel submitted at checkout completion\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"channel\": {\n \"type\": \"string\",\n \"description\": \"Channel matching the consent option channel.\",\n \"examples\": [\"email\", \"sms\", \"whatsapp\"]\n },\n \"opted_in\": {\n \"type\": \"boolean\",\n \"description\": \"Whether the buyer consented to receive marketing via this channel.\"\n }\n },\n \"required\": [\n \"channel\",\n \"opted_in\"\n ],\n \"example\": {\n \"channel\": \"email\",\n \"opted_in\": true\n }\n },\n \"CheckoutSessionBase\": {\n \"description\": \"Base checkout session model containing common fields for all checkout session states\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique identifier for the checkout session\"\n },\n \"protocol\": {\n \"$ref\": \"#/$defs/ProtocolVersion\",\n \"description\": \"Protocol version metadata\"\n },\n \"capabilities\": {\n \"$ref\": \"#/$defs/Capabilities\",\n \"description\": \"Negotiated capabilities between agent and seller\"\n },\n \"buyer\": {\n \"$ref\": \"#/$defs/Buyer\",\n \"description\": \"Buyer information\"\n },\n \"status\": {\n \"type\": \"string\",\n \"enum\": [\n \"incomplete\",\n \"not_ready_for_payment\",\n \"requires_escalation\",\n \"authentication_required\",\n \"ready_for_payment\",\n \"pending_approval\",\n \"complete_in_progress\",\n \"completed\",\n \"canceled\",\n \"in_progress\",\n \"expired\"\n ],\n \"description\": \"Current status of the checkout session\"\n },\n \"currency\": {\n \"type\": \"string\",\n \"description\": \"ISO 4217 settlement currency code\"\n },\n \"presentment_currency\": {\n \"type\": \"string\",\n \"description\": \"ISO 4217 presentment currency code if different from settlement currency\"\n },\n \"exchange_rate\": {\n \"type\": \"number\",\n \"description\": \"Exchange rate from presentment to settlement currency\"\n },\n \"exchange_rate_timestamp\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when exchange rate was determined\"\n },\n \"locale\": {\n \"type\": \"string\",\n \"description\": \"Locale code (e.g., 'en-US') for localizing content\"\n },\n \"timezone\": {\n \"type\": \"string\",\n \"description\": \"IANA timezone identifier (e.g., 'America/New_York')\"\n },\n \"line_items\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/LineItem\"\n },\n \"description\": \"Line items in the checkout session\"\n },\n \"fulfillment_details\": {\n \"$ref\": \"#/$defs/FulfillmentDetails\",\n \"description\": \"Fulfillment contact and address details\"\n },\n \"fulfillment_options\": {\n \"type\": \"array\",\n \"items\": {\n \"oneOf\": [\n {\n \"$ref\": \"#/$defs/FulfillmentOptionShipping\"\n },\n {\n \"$ref\": \"#/$defs/FulfillmentOptionDigital\"\n },\n {\n \"$ref\": \"#/$defs/FulfillmentOptionPickup\"\n },\n {\n \"$ref\": \"#/$defs/FulfillmentOptionLocalDelivery\"\n }\n ]\n },\n \"description\": \"Available fulfillment options\"\n },\n \"selected_fulfillment_options\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/SelectedFulfillmentOption\"\n },\n \"description\": \"Currently selected fulfillment options\"\n },\n \"fulfillment_groups\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/FulfillmentGroup\"\n },\n \"description\": \"Optional grouping of line items by fulfillment method\"\n },\n \"totals\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Total\"\n },\n \"description\": \"Cart-level totals breakdown\"\n },\n \"messages\": {\n \"type\": \"array\",\n \"items\": {\n \"oneOf\": [\n {\n \"$ref\": \"#/$defs/MessageInfo\"\n },\n {\n \"$ref\": \"#/$defs/MessageWarning\"\n },\n {\n \"$ref\": \"#/$defs/MessageError\"\n }\n ]\n },\n \"description\": \"Messages to communicate with the buyer (info, warnings, errors)\"\n },\n \"links\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Link\"\n },\n \"description\": \"Relevant links (terms, policies, support)\"\n },\n \"authentication_metadata\": {\n \"$ref\": \"#/$defs/AuthenticationMetadata\",\n \"description\": \"Authentication metadata for payment interventions (e.g., 3DS)\"\n },\n \"created_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when the session was created\"\n },\n \"updated_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp of last update\"\n },\n \"expires_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when the session expires\"\n },\n \"continue_url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to continue or resume the checkout session\"\n },\n \"metadata\": {\n \"type\": \"object\",\n \"additionalProperties\": true,\n \"description\": \"Arbitrary metadata for merchant use\"\n },\n \"quote_id\": {\n \"type\": \"string\",\n \"description\": \"Quote identifier if this session is based on a quote\"\n },\n \"quote_expires_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"description\": \"RFC 3339 timestamp when the quote expires\"\n },\n \"discounts\": {\n \"$ref\": \"#/$defs/DiscountsResponse\",\n \"description\": \"Discount extension: submitted codes and applied discounts. Present when the 'discount' extension is active.\"\n },\n \"marketing_consent_options\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/MarketingConsentOption\"\n },\n \"description\": \"Marketing consent options the seller offers. When present, the agent SHOULD display these to the buyer before checkout completion. Agents MAY selectively surface a subset of options; options not surfaced MUST be omitted from marketing_consents in the complete request. When absent, the agent MUST NOT surface any marketing consent UI. An empty array is equivalent to absent.\"\n },\n \"order\": {\n \"$ref\": \"#/$defs/Order\"\n }\n },\n \"required\": [\n \"id\",\n \"status\",\n \"currency\",\n \"line_items\",\n \"totals\",\n \"fulfillment_options\",\n \"messages\",\n \"links\",\n \"capabilities\"\n ],\n \"example\": {\n \"id\": \"cs_abc123\",\n \"status\": \"ready_for_payment\",\n \"currency\": \"usd\",\n \"line_items\": [],\n \"totals\": {\n \"currency\": \"usd\",\n \"subtotal\": 5800,\n \"total\": 6764\n },\n \"fulfillment_options\": [],\n \"messages\": [],\n \"links\": [],\n \"capabilities\": {}\n }\n },\n \"CheckoutSession\": {\n \"description\": \"Checkout session response model\",\n \"allOf\": [\n {\n \"$ref\": \"#/$defs/CheckoutSessionBase\"\n }\n ],\n \"example\": {\n \"id\": \"cs_abc123\",\n \"status\": \"ready_for_payment\",\n \"currency\": \"usd\",\n \"line_items\": [],\n \"totals\": {\n \"currency\": \"usd\",\n \"subtotal\": 5800,\n \"total\": 6764\n },\n \"fulfillment_options\": [],\n \"messages\": [],\n \"links\": [],\n \"capabilities\": {}\n }\n },\n \"CheckoutSessionWithOrder\": {\n \"description\": \"Checkout session response after completion, includes the created order\",\n \"allOf\": [\n {\n \"$ref\": \"#/$defs/CheckoutSessionBase\"\n },\n {\n \"description\": \"Order extension for completed checkout sessions\",\n \"type\": \"object\",\n \"properties\": {\n \"order\": {\n \"$ref\": \"#/$defs/Order\",\n \"description\": \"Order created when checkout is completed\"\n }\n },\n \"required\": [\n \"order\"\n ]\n }\n ],\n \"example\": {\n \"id\": \"cs_abc123\",\n \"status\": \"completed\",\n \"currency\": \"usd\",\n \"line_items\": [],\n \"totals\": {\n \"currency\": \"usd\",\n \"subtotal\": 5800,\n \"total\": 6764\n },\n \"fulfillment_options\": [],\n \"messages\": [],\n \"links\": [],\n \"capabilities\": {},\n \"order\": {\n \"id\": \"ord_abc123\",\n \"order_number\": \"12345\",\n \"status\": \"confirmed\",\n \"currency\": \"usd\",\n \"total\": 6764,\n \"line_items\": [],\n \"created_at\": \"2026-02-13T10:30:00Z\"\n }\n }\n },\n \"CheckoutSessionCreateRequest\": {\n \"description\": \"Request to create a new checkout session\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"buyer\": {\n \"$ref\": \"#/$defs/Buyer\",\n \"description\": \"Buyer information\"\n },\n \"line_items\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Item\"\n },\n \"minItems\": 1,\n \"description\": \"Items to add to the checkout session\"\n },\n \"currency\": {\n \"type\": \"string\",\n \"description\": \"ISO 4217 currency code\"\n },\n \"fulfillment_details\": {\n \"$ref\": \"#/$defs/FulfillmentDetails\",\n \"description\": \"Fulfillment contact and address details\"\n },\n \"capabilities\": {\n \"$ref\": \"#/$defs/Capabilities\",\n \"description\": \"Agent capabilities and supported features\"\n },\n \"fulfillment_groups\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/FulfillmentGroup\"\n },\n \"description\": \"Grouping of items by fulfillment method\"\n },\n \"affiliate_attribution\": {\n \"$ref\": \"#/$defs/AffiliateAttribution\",\n \"description\": \"Affiliate attribution data for first-touch tracking\"\n },\n \"coupons\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Coupon code to apply\"\n },\n \"description\": \"DEPRECATED: Use discounts.codes instead. Discount codes to apply.\"\n },\n \"discounts\": {\n \"$ref\": \"#/$defs/DiscountsRequest\",\n \"description\": \"Discount codes to apply to the checkout session.\"\n },\n \"locale\": {\n \"type\": \"string\",\n \"description\": \"Locale code for localizing content (e.g., 'en-US')\"\n },\n \"timezone\": {\n \"type\": \"string\",\n \"description\": \"IANA timezone identifier (e.g., 'America/New_York')\"\n },\n \"quote_id\": {\n \"type\": \"string\",\n \"description\": \"Quote identifier if this session is based on a quote\"\n },\n \"metadata\": {\n \"type\": \"object\",\n \"additionalProperties\": true,\n \"description\": \"Arbitrary metadata for merchant use\"\n },\n \"order_notes\": {\n \"type\": \"string\",\n \"maxLength\": 5000,\n \"description\": \"Optional customer/order notes (e.g., delivery instructions, gift message).\"\n }\n },\n \"required\": [\n \"line_items\",\n \"currency\",\n \"capabilities\"\n ],\n \"example\": {\n \"items\": [\n {\n \"product_id\": \"prod_tshirt_blue_m\",\n \"quantity\": 2\n }\n ],\n \"currency\": \"usd\",\n \"capabilities\": {}\n }\n },\n \"CheckoutSessionUpdateRequest\": {\n \"description\": \"Request to update an existing checkout session\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"buyer\": {\n \"$ref\": \"#/$defs/Buyer\",\n \"description\": \"Updated buyer information\"\n },\n \"line_items\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/Item\"\n },\n \"description\": \"Items to update in the checkout session\"\n },\n \"fulfillment_details\": {\n \"$ref\": \"#/$defs/FulfillmentDetails\",\n \"description\": \"Updated fulfillment contact and address\"\n },\n \"fulfillment_groups\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/FulfillmentGroup\"\n },\n \"description\": \"Updated fulfillment groupings\"\n },\n \"selected_fulfillment_options\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/SelectedFulfillmentOption\"\n },\n \"description\": \"Fulfillment option selected by the buyer\"\n },\n \"coupons\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Coupon code to apply\"\n },\n \"description\": \"DEPRECATED: Use discounts.codes instead. Discount codes to apply.\"\n },\n \"discounts\": {\n \"$ref\": \"#/$defs/DiscountsRequest\",\n \"description\": \"Discount codes to apply. Replaces previously submitted codes.\"\n },\n \"order_notes\": {\n \"type\": \"string\",\n \"maxLength\": 5000,\n \"description\": \"Optional customer/order notes.\"\n }\n },\n \"example\": {\n \"buyer\": {\n \"email\": \"customer@example.com\"\n }\n }\n },\n \"CheckoutSessionCompleteRequest\": {\n \"description\": \"Request to complete a checkout session and create an order\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"buyer\": {\n \"$ref\": \"#/$defs/Buyer\",\n \"description\": \"Final buyer information\"\n },\n \"payment_data\": {\n \"$ref\": \"#/$defs/PaymentData\",\n \"description\": \"Payment method and details\"\n },\n \"authentication_result\": {\n \"$ref\": \"#/$defs/AuthenticationResult\",\n \"description\": \"Authentication result for 3DS flows\"\n },\n \"affiliate_attribution\": {\n \"$ref\": \"#/$defs/AffiliateAttribution\",\n \"description\": \"Affiliate attribution data for last-touch tracking\"\n },\n \"risk_signals\": {\n \"$ref\": \"#/$defs/RiskSignals\",\n \"description\": \"Risk and fraud signals\"\n },\n \"marketing_consents\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/MarketingConsent\"\n },\n \"description\": \"Buyer's marketing consent decisions. Agents SHOULD include an entry for each consent option surfaced to the buyer. Options not surfaced MUST be omitted — omission preserves existing subscription state. Sellers SHOULD ignore entries in marketing_consents that do not correspond to a channel in marketing_consent_options.\"\n },\n \"order_notes\": {\n \"type\": \"string\",\n \"maxLength\": 5000,\n \"description\": \"Optional customer/order notes (delivery instructions, gift message).\"\n }\n },\n \"required\": [\n \"payment_data\"\n ],\n \"example\": {\n \"payment_data\": {\n \"type\": \"vault_token\",\n \"token\": \"vt_01J8Z3WXYZ9ABC123\"\n }\n }\n },\n \"IntentTrace\": {\n \"description\": \"Structured reason for why a buyer action was taken, used for analytics and debugging\",\n \"type\": \"object\",\n \"properties\": {\n \"reason_code\": {\n \"type\": \"string\",\n \"description\": \"Reason for abandonment. This enum is extensible: servers SHOULD accept unrecognized values and treat them as 'other' (see RFC Section 7.2). Validators SHOULD be configured for lenient enum handling.\",\n \"enum\": [\n \"price_sensitivity\",\n \"shipping_cost\",\n \"shipping_speed\",\n \"product_fit\",\n \"trust_security\",\n \"returns_policy\",\n \"payment_options\",\n \"comparison\",\n \"timing_deferred\",\n \"other\"\n ]\n },\n \"trace_summary\": {\n \"type\": \"string\",\n \"maxLength\": 500,\n \"description\": \"A generated summary of the specific objection or negotiation gap.\"\n },\n \"metadata\": {\n \"type\": \"object\",\n \"additionalProperties\": {\n \"type\": [\n \"string\",\n \"number\",\n \"boolean\"\n ],\n \"description\": \"Metadata value\"\n },\n \"description\": \"Additional structured metadata about the intent\"\n }\n },\n \"required\": [\n \"reason_code\"\n ],\n \"example\": {\n \"reason_code\": \"buyer_initiated\",\n \"description\": \"Customer requested to complete checkout\",\n \"metadata\": {}\n }\n },\n \"CancelSessionRequest\": {\n \"description\": \"Request to cancel a checkout session\",\n \"type\": \"object\",\n \"properties\": {\n \"intent_trace\": {\n \"$ref\": \"#/$defs/IntentTrace\"\n }\n },\n \"example\": {\n \"intent_trace\": {\n \"reason_code\": \"buyer_cancelled\",\n \"description\": \"Customer decided not to purchase\"\n }\n }\n },\n \"DiscoveryResponse\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Well-known discovery document served at /.well-known/acp.json. Describes the seller's capabilities. This is stable, deterministic information that does not vary per session. Session-specific capabilities (payment methods, payment handlers) are negotiated inline via the capabilities object on POST /checkout_sessions.\",\n \"properties\": {\n \"protocol\": {\n \"$ref\": \"#/$defs/DiscoveryProtocol\"\n },\n \"api_base_url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"Base URL for the ACP REST API. Agents append resource paths to this URL (e.g., {api_base_url}/checkout_sessions).\"\n },\n \"transports\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"enum\": [\"rest\", \"mcp\"]\n },\n \"uniqueItems\": true,\n \"description\": \"Transport bindings supported by this seller. \\\"rest\\\" indicates the REST API at api_base_url. \\\"mcp\\\" indicates a Model Context Protocol server is available (see SEP #135). New values are introduced in new API versions; agents MAY treat this enum as exhaustive for a given version.\"\n },\n \"capabilities\": {\n \"$ref\": \"#/$defs/DiscoveryCapabilities\"\n }\n },\n \"required\": [\"protocol\", \"api_base_url\", \"transports\", \"capabilities\"],\n \"example\": {\n \"protocol\": {\n \"name\": \"acp\",\n \"version\": \"2026-04-17\",\n \"supported_versions\": [\"2025-09-29\", \"2026-01-30\", \"2026-04-17\"]\n },\n \"api_base_url\": \"https://acp.stripe.com/api\",\n \"transports\": [\"rest\"],\n \"capabilities\": {\n \"services\": [\"checkout\"]\n }\n }\n },\n \"DiscoveryCapabilities\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Seller capabilities advertised in the well-known discovery document. Contains feature declarations that are stable across sessions.\",\n \"properties\": {\n \"services\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"enum\": [\"checkout\", \"orders\", \"delegate_payment\", \"carts\"]\n },\n \"uniqueItems\": true,\n \"description\": \"Services available from this seller. Indicates which ACP operations are implemented. This enum is closed per API version; new values are introduced in new API versions. Agents MAY treat the set as exhaustive for a given version.\"\n },\n \"extensions\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/DiscoveryExtension\"\n },\n \"description\": \"Extensions the seller supports. Whether a specific extension is active for a given session is determined during checkout session creation.\"\n },\n \"intervention_types\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"enum\": [\"3ds\", \"biometric\", \"address_verification\"]\n },\n \"uniqueItems\": true,\n \"description\": \"Intervention types the seller supports. Actual availability for a specific session is negotiated via the capabilities object on POST /checkout_sessions. This enum is closed per API version; new values are introduced in new API versions. Agents MAY treat the set as exhaustive for a given version.\"\n },\n \"supported_currencies\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^[a-z]{3}$\",\n \"description\": \"ISO 4217 currency code in lowercase (e.g., \\\"usd\\\", \\\"eur\\\")\"\n },\n \"uniqueItems\": true,\n \"description\": \"ISO 4217 currency codes supported by the seller.\"\n },\n \"supported_locales\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"BCP 47 locale tag (e.g., \\\"en-US\\\", \\\"fr-FR\\\")\"\n },\n \"uniqueItems\": true,\n \"description\": \"BCP 47 locale tags supported by the seller for localized responses.\"\n }\n },\n \"required\": [\"services\"],\n \"example\": {\n \"services\": [\"checkout\", \"orders\", \"delegate_payment\", \"carts\"],\n \"extensions\": [{ \"name\": \"discount\", \"spec\": \"https://agenticcommerce.dev/specs/discount\", \"schema\": \"https://agenticcommerce.dev/schemas/discount.json\" }],\n \"intervention_types\": [\"3ds\"],\n \"supported_currencies\": [\"usd\", \"eur\"],\n \"supported_locales\": [\"en-US\"]\n }\n },\n \"DiscoveryProtocol\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Protocol identification and version information.\",\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"const\": \"acp\",\n \"description\": \"Protocol identifier. Always \\\"acp\\\".\"\n },\n \"version\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{4}-\\\\d{2}-\\\\d{2}$\",\n \"description\": \"The current (latest) API version supported by the seller, in YYYY-MM-DD format.\"\n },\n \"supported_versions\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{4}-\\\\d{2}-\\\\d{2}$\",\n \"description\": \"API version in YYYY-MM-DD format\"\n },\n \"uniqueItems\": true,\n \"description\": \"All API versions the seller currently supports, in chronological order (oldest first). Agents SHOULD use the API-Version header to request a specific version. The last element is always the latest supported version.\"\n },\n \"documentation_url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to the seller's ACP documentation.\"\n }\n },\n \"required\": [\"name\", \"version\", \"supported_versions\"],\n \"example\": {\n \"name\": \"acp\",\n \"version\": \"2026-04-17\",\n \"supported_versions\": [\"2025-09-29\", \"2026-01-30\", \"2026-04-17\"],\n \"documentation_url\": \"https://agenticcommerce.dev\"\n }\n },\n \"DiscoveryExtension\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"High-level extension declaration in the discovery document. Identifies the extension and provides a spec URL, but does not include session-level details like schema or extends fields.\",\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Extension identifier (e.g., \\\"discount\\\", \\\"fulfillment\\\").\"\n },\n \"spec\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to the extension's specification document.\"\n },\n \"schema\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"URL to the extension's JSON Schema definition for programmatic validation.\"\n }\n },\n \"required\": [\"name\"],\n \"example\": {\n \"name\": \"discount\",\n \"spec\": \"https://agenticcommerce.dev/specs/discount\",\n \"schema\": \"https://agenticcommerce.dev/schemas/discount.json\"\n }\n },\n \"Error\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"description\": \"Protocol-level error returned in 4xx/5xx responses when the server cannot return a valid CheckoutSession at all (e.g. malformed request or unexpected failure). Use Error—not MessageError—when there is no valid session state to return. type semantics: invalid_request — malformed request, missing required fields, invalid JSON, or idempotency violations (codes: idempotency_key_required, idempotency_in_flight, idempotency_conflict); processing_error — unexpected server-side failure; service_unavailable — temporary unavailability.\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"invalid_request\",\n \"processing_error\",\n \"service_unavailable\"\n ],\n \"description\": \"Error type indicating the category of protocol-level error\"\n },\n \"code\": {\n \"type\": \"string\",\n \"description\": \"Implementation-defined error code\"\n },\n \"message\": {\n \"type\": \"string\",\n \"description\": \"Human-readable error message\"\n },\n \"param\": {\n \"type\": \"string\",\n \"description\": \"RFC 9535 JSONPath (optional)\"\n },\n \"supported_versions\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{4}-\\\\d{2}-\\\\d{2}$\",\n \"description\": \"Supported API version in YYYY-MM-DD format\"\n },\n \"description\": \"List of API versions supported by the server, ordered by preference (newest first). Only included in version-related errors.\"\n }\n },\n \"required\": [\n \"type\",\n \"code\",\n \"message\"\n ],\n \"example\": {\n \"type\": \"invalid_request\",\n \"code\": \"invalid_email\",\n \"message\": \"The email address format is invalid\",\n \"param\": \"$.buyer.email\"\n }\n }\n }\n}\n","/**\n * Wire validation against the vendored ACP checkout schema.\n *\n * ACP request and response bodies are far larger than the JSON-Schema subset\n * `src/core/execution` validates canonical input with, so the pinned official\n * schema is compiled with Ajv rather than restated by hand: a hand-written\n * copy is a second definition of the protocol, and it drifts.\n *\n * The schema is *imported*, not read from disk. `dist/` collapses `src/**`\n * into two bundled files, so a relative `readFileSync` resolves from the wrong\n * depth once built - a failure this repository has shipped twice.\n */\n\nimport type { ErrorObject, ValidateFunction } from 'ajv';\nimport Ajv2020 from 'ajv/dist/2020.js';\nimport addFormats from 'ajv-formats';\nimport { CommerceError } from '../../core/index.js';\n// The snapshot directory is part of the path on purpose: a new ACP version is\n// a new import beside this one, never an edit to the vendored file.\nimport schemaDocument from './spec/2026-04-17/schema.agentic_checkout.json' with { type: 'json' };\n\n/**\n * A validation failure, reduced to what may safely cross the adapter\n * boundary. Ajv messages and schema paths describe *our* compiled schema and\n * never reach a client; the adapter turns this into an ACP `Error`.\n */\nexport interface AcpValidationFailure {\n /** The JSON Schema keyword that failed - spec vocabulary, not an Ajv internal. */\n readonly code: string;\n /** `$.buyer.email`-style pointer to the offending value. Omitted at the document root. */\n readonly path?: string;\n}\n\n/**\n * The released `$defs` this adapter validates against, by the role it uses\n * them in. Keys are ours; values are the exact names in the released snapshot,\n * and a typo in one is caught at first use rather than at first request.\n */\nexport const ACP_DEFINITIONS = {\n createRequest: 'CheckoutSessionCreateRequest',\n updateRequest: 'CheckoutSessionUpdateRequest',\n completeRequest: 'CheckoutSessionCompleteRequest',\n cancelRequest: 'CancelSessionRequest',\n checkoutSession: 'CheckoutSession',\n checkoutSessionWithOrder: 'CheckoutSessionWithOrder',\n discoveryResponse: 'DiscoveryResponse',\n error: 'Error',\n} as const;\n\nexport type AcpDefinition = keyof typeof ACP_DEFINITIONS;\n\nlet validators: ReadonlyMap<AcpDefinition, ValidateFunction> | undefined;\n\n/**\n * Compiled once for the process, on first use rather than at import: a gateway\n * with ACP disabled never pays for it, and the cost is the same either way for\n * one that has it on.\n */\nfunction acpValidators(): ReadonlyMap<AcpDefinition, ValidateFunction> {\n if (validators !== undefined) return validators;\n\n const ajv = new Ajv2020({\n // The vendored document is the released spec: annotations we do not know\n // are the spec's business, not a reason to refuse to start.\n strict: false,\n // One failure is all that leaves the adapter, and collecting every error\n // in a deeply nested cart is work an unauthenticated caller could ask for\n // repeatedly.\n allErrors: false,\n });\n addFormats(ajv);\n\n const document = relaxExtensibleEnums(structuredClone(schemaDocument)) as Record<string, unknown>;\n const schemaId = typeof document['$id'] === 'string' ? document['$id'] : '';\n ajv.addSchema(document as Parameters<typeof ajv.addSchema>[0]);\n\n const compiled = new Map<AcpDefinition, ValidateFunction>();\n for (const [name, definition] of Object.entries(ACP_DEFINITIONS)) {\n const validate = ajv.getSchema(`${schemaId}#/$defs/${definition}`);\n if (validate === undefined) {\n throw new CommerceError(\n 'PROTOCOL_UNSUPPORTED',\n `The vendored ACP schema has no definition \"${definition}\" - the pinned snapshot and this adapter disagree`,\n { details: { definition } },\n );\n }\n compiled.set(name as AcpDefinition, validate);\n }\n\n validators = compiled;\n return compiled;\n}\n\n/**\n * Drops the `enum` constraint from the few fields the snapshot itself marks as\n * extensible (\"servers SHOULD accept unrecognized values and treat them as\n * 'other'\", and \"validators SHOULD be configured for lenient enum handling\").\n *\n * Only fields carrying that wording are relaxed. The enums ACP calls closed\n * per API version stay closed - the point is not to be permissive, it is to\n * avoid refusing, say, a cancel because of an analytics reason code the buyer's\n * agent knows about and this snapshot does not.\n */\nfunction relaxExtensibleEnums(node: unknown): unknown {\n if (Array.isArray(node)) {\n for (const entry of node) relaxExtensibleEnums(entry);\n return node;\n }\n if (node === null || typeof node !== 'object') return node;\n\n const record = node as Record<string, unknown>;\n const description = record['description'];\n if (\n Array.isArray(record['enum']) &&\n typeof description === 'string' &&\n /enum is extensible/i.test(description)\n ) {\n delete record['enum'];\n }\n for (const value of Object.values(record)) relaxExtensibleEnums(value);\n return node;\n}\n\n/**\n * Validates one ACP document against a released definition.\n *\n * Returns `undefined` when the value conforms, otherwise the first failure.\n * Inbound, that failure becomes a 400 and no pipeline call happens; outbound,\n * it means the merchant backend returned something that is not ACP, and the\n * body must not be forwarded.\n */\nexport function validateAcpDocument(\n definition: AcpDefinition,\n value: unknown,\n): AcpValidationFailure | undefined {\n const validate = acpValidators().get(definition);\n /* c8 ignore next -- unreachable: every AcpDefinition is compiled above. */\n if (validate === undefined) return { code: 'unknown_definition' };\n\n if (validate(value)) return undefined;\n const error = validate.errors?.[0];\n if (error === undefined) return { code: 'invalid' };\n\n const path = failurePath(error);\n return { code: error.keyword, ...(path !== undefined ? { path } : {}) };\n}\n\n/**\n * Ajv's JSON Pointer, rendered as the `$.a.b[0]` form ACP errors use in\n * `param`. `required` and `additionalProperties` failures report the parent\n * object, so the offending key is appended - the difference between telling a\n * client `$` and telling it `$.buyer.email`.\n */\nfunction failurePath(error: ErrorObject): string | undefined {\n const segments = error.instancePath\n .split('/')\n .filter((segment) => segment.length > 0)\n .map((segment) => segment.replaceAll('~1', '/').replaceAll('~0', '~'));\n\n const params = error.params as { missingProperty?: unknown; additionalProperty?: unknown };\n const key = params.missingProperty ?? params.additionalProperty;\n if (typeof key === 'string') segments.push(key);\n\n if (segments.length === 0) return undefined;\n return segments.reduce(\n (path, segment) => (/^\\d+$/.test(segment) ? `${path}[${segment}]` : `${path}.${segment}`),\n '$',\n );\n}\n","/**\n * Everything that must hold before an ACP request reaches the pipeline.\n *\n * The sequence is fixed and fails closed at the first step that does not hold:\n * route -> bearer auth -> API-Version -> content type -> body size -> JSON ->\n * ACP request schema. Nothing below this file runs for a request that fails\n * any of them, which is what makes \"no pipeline call on a guard failure\"\n * checkable rather than a claim.\n */\nimport type { IncomingMessage } from 'node:http';\nimport { isAuthorizedBearer } from './auth.js';\nimport {\n ACP_API_VERSION,\n ACP_API_VERSION_HEADER,\n ACP_IDEMPOTENCY_KEY_HEADER,\n ACP_MAX_REQUEST_ID_LENGTH,\n ACP_REQUEST_ID_HEADER,\n} from './constants.js';\nimport { type AcpFailure, acpFailure } from './errors.js';\nimport { ACP_MAX_IDEMPOTENCY_KEY_LENGTH } from './idempotency/store.js';\nimport { type AcpRouteMatch, matchAcpRoute } from './router.js';\nimport { type AcpDefinition, validateAcpDocument } from './validation.js';\n\n/**\n * A second line behind the gateway mount's own cap, so this adapter bounds\n * what it buffers even if it is ever mounted without that guard.\n */\nexport const ACP_MAX_REQUEST_BODY_BYTES = 256 * 1024;\n\n/** Which released request definition each operation's body is validated against. */\nconst REQUEST_DEFINITIONS: Readonly<Record<AcpRouteMatch['operation'], AcpDefinition | undefined>> =\n {\n createCheckoutSession: 'createRequest',\n updateCheckoutSession: 'updateRequest',\n completeCheckoutSession: 'completeRequest',\n cancelCheckoutSession: 'cancelRequest',\n getCheckoutSession: undefined,\n };\n\nexport interface AcpGuardedRequest {\n readonly route: AcpRouteMatch;\n /** Validated ACP request document. `{}` for a body-less route. */\n readonly body: Record<string, unknown>;\n /** The caller's `Request-Id`, bounded and filtered, when it sent a usable one. */\n readonly requestId?: string;\n /** Present on every body-bearing route: ACP makes it mandatory there. */\n readonly idempotencyKey?: string;\n}\n\nexport type AcpGuardResult =\n | { readonly ok: true; readonly value: AcpGuardedRequest }\n | ({ readonly ok: false } & AcpFailure);\n\nexport interface AcpGuardOptions {\n readonly mountPath: string;\n readonly token: string;\n readonly maxBodyBytes?: number;\n}\n\nexport async function guardAcpRequest(\n req: IncomingMessage,\n options: AcpGuardOptions,\n): Promise<AcpGuardResult> {\n const matched = matchAcpRoute(req.method, req.url, options.mountPath);\n if (matched.kind === 'not-found') {\n return failed(acpFailure(404, 'invalid_request', 'not_found', 'Unknown ACP route.'));\n }\n if (matched.kind === 'method-not-allowed') {\n return failed(\n acpFailure(\n 405,\n 'invalid_request',\n 'method_not_allowed',\n `This ACP route accepts ${matched.allow.join(', ')}.`,\n ),\n );\n }\n const route = matched.route;\n\n // Before anything reads a body: an unauthenticated caller must not be able\n // to make this adapter buffer or parse.\n if (!isAuthorizedBearer(header(req, 'authorization'), options.token)) {\n return failed(\n acpFailure(\n 401,\n 'invalid_request',\n 'unauthorized',\n 'A valid \"Authorization: Bearer <token>\" header is required.',\n ),\n );\n }\n\n const version = header(req, ACP_API_VERSION_HEADER);\n if (version === undefined || version.trim().length === 0) {\n return failed(\n acpFailure(\n 400,\n 'invalid_request',\n 'missing_api_version',\n `The ${ACP_API_VERSION_HEADER} header is required.`,\n { supportedVersions: [ACP_API_VERSION] },\n ),\n );\n }\n if (version.trim() !== ACP_API_VERSION) {\n // Never mapped to the pinned version. \"latest\", an older snapshot and a\n // typo are the same answer: this deployment serves one contract.\n return failed(\n acpFailure(\n 400,\n 'invalid_request',\n 'unsupported_api_version',\n 'The requested API version is not supported.',\n { supportedVersions: [ACP_API_VERSION] },\n ),\n );\n }\n\n // Header-level and cheap, so it runs before a byte of body is read: a POST\n // without a usable key can never be executed, and reading its body first\n // would be work an authenticated client could ask for at will.\n let idempotencyKey: string | undefined;\n if (route.acceptsBody) {\n const presented = header(req, ACP_IDEMPOTENCY_KEY_HEADER)?.trim();\n if (presented === undefined || presented.length === 0) {\n return failed(\n acpFailure(\n 400,\n 'invalid_request',\n 'idempotency_key_required',\n `The ${ACP_IDEMPOTENCY_KEY_HEADER} header is required on this ACP operation.`,\n ),\n );\n }\n // Bounded and visible-ASCII for the same reason as Request-Id: the key is\n // echoed back in a response header, so a CRLF in it is a response-splitting\n // attempt rather than a key.\n if (presented.length > ACP_MAX_IDEMPOTENCY_KEY_LENGTH || !isVisibleAscii(presented)) {\n return failed(\n acpFailure(\n 400,\n 'invalid_request',\n 'idempotency_key_invalid',\n `The ${ACP_IDEMPOTENCY_KEY_HEADER} header must be 1-${ACP_MAX_IDEMPOTENCY_KEY_LENGTH} printable ASCII characters.`,\n ),\n );\n }\n idempotencyKey = presented;\n }\n\n const read = await readBody(req, options.maxBodyBytes ?? ACP_MAX_REQUEST_BODY_BYTES);\n if (read.kind === 'too-large') {\n return failed(\n acpFailure(\n 413,\n 'invalid_request',\n 'request_body_too_large',\n 'The request body is too large.',\n ),\n );\n }\n if (read.kind === 'unreadable') {\n return failed(\n acpFailure(\n 400,\n 'invalid_request',\n 'invalid_request_body',\n 'Could not read the request body.',\n ),\n );\n }\n\n const raw = read.text;\n const contentTypeFailure = checkContentType(header(req, 'content-type'), raw, route);\n if (contentTypeFailure !== undefined) return failed(contentTypeFailure);\n\n const definition = REQUEST_DEFINITIONS[route.operation];\n if (definition === undefined) {\n // GET carries no document; a body on it is ignored rather than validated.\n return ok(route, {}, req, idempotencyKey);\n }\n\n let body: unknown;\n if (raw.trim().length === 0) {\n // An absent body is an empty document, which the pinned schema then\n // accepts (cancel) or rejects (create) on its own terms.\n body = {};\n } else {\n try {\n body = JSON.parse(raw);\n } catch {\n return failed(\n acpFailure(400, 'invalid_request', 'invalid_json', 'The request body is not valid JSON.'),\n );\n }\n }\n\n const failure = validateAcpDocument(definition, body);\n if (failure !== undefined) {\n // Only the caller's own pointer travels; the Ajv message stays here.\n return failed(\n acpFailure(400, 'invalid_request', 'invalid_request_body', 'The request body is invalid.', {\n ...(failure.path !== undefined ? { param: failure.path } : {}),\n }),\n );\n }\n\n return ok(route, body as Record<string, unknown>, req, idempotencyKey);\n}\n\nfunction checkContentType(\n contentType: string | undefined,\n raw: string,\n route: AcpRouteMatch,\n): AcpFailure | undefined {\n if (!route.acceptsBody) return undefined;\n if (contentType === undefined) {\n // A POST with no body at all (a bare cancel) needs no content type.\n return raw.trim().length === 0\n ? undefined\n : acpFailure(\n 415,\n 'invalid_request',\n 'unsupported_media_type',\n 'ACP request bodies must be sent as \"application/json\".',\n );\n }\n const mediaType = contentType.split(';')[0]?.trim().toLowerCase();\n if (mediaType === 'application/json' || mediaType?.endsWith('+json')) return undefined;\n return acpFailure(\n 415,\n 'invalid_request',\n 'unsupported_media_type',\n 'ACP request bodies must be sent as \"application/json\".',\n );\n}\n\nfunction ok(\n route: AcpRouteMatch,\n body: Record<string, unknown>,\n req: IncomingMessage,\n idempotencyKey: string | undefined,\n): AcpGuardResult {\n const requestId = normalizeRequestId(header(req, ACP_REQUEST_ID_HEADER));\n return {\n ok: true,\n value: {\n route,\n body,\n ...(requestId !== undefined ? { requestId } : {}),\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n },\n };\n}\n\nfunction failed(failure: AcpFailure): AcpGuardResult {\n return { ok: false, ...failure };\n}\n\n/**\n * The caller's correlation id, echoed back but never used as the gateway's own\n * request identity. It is attacker-controlled text on its way into a response\n * header, so it is bounded and reduced to visible ASCII - a newline in there is\n * a response-splitting attempt, not a correlation id.\n */\nexport function normalizeRequestId(value: string | undefined): string | undefined {\n if (value === undefined) return undefined;\n const trimmed = value.trim().slice(0, ACP_MAX_REQUEST_ID_LENGTH);\n if (trimmed.length === 0) return undefined;\n if (!isVisibleAscii(trimmed)) return undefined;\n return trimmed;\n}\n\nfunction isVisibleAscii(value: string): boolean {\n return !/[^\\x20-\\x7e]/.test(value);\n}\n\nfunction header(req: IncomingMessage, name: string): string | undefined {\n const value = req.headers[name];\n return Array.isArray(value) ? value[0] : value;\n}\n\n/**\n * Reads the unconsumed request stream the gateway hands over, stopping at the\n * cap rather than buffering whatever arrives.\n */\nasync function readBody(req: IncomingMessage, maxBytes: number): Promise<BodyRead> {\n const chunks: Buffer[] = [];\n let total = 0;\n try {\n for await (const chunk of req) {\n const buffer = chunk as Buffer;\n total += buffer.length;\n if (total > maxBytes) return { kind: 'too-large' };\n chunks.push(buffer);\n }\n } catch {\n return { kind: 'unreadable' };\n }\n return { kind: 'ok', text: Buffer.concat(chunks).toString('utf8') };\n}\n\n/** A result object, not a sentinel string: a body whose text *is* \"too-large\" is a body. */\ntype BodyRead =\n | { readonly kind: 'ok'; readonly text: string }\n | { readonly kind: 'too-large' }\n | { readonly kind: 'unreadable' };\n","/**\n * Execution outcome -> ACP response.\n *\n * Two rules run everything here. A successful checkout answer must be a\n * document the pinned snapshot accepts, on the status ACP fixes for that route\n * - a merchant backend is not automatically ACP-conformant, and forwarding\n * whatever it returned would publish its shape as ours. And a failure tells the\n * caller what went wrong in ACP's vocabulary and nothing else: no merchant\n * response body, no stack, no internal path, no database error.\n */\nimport type { CommerceError, DeliveredOutcome } from '../../core/index.js';\nimport type { AcpCheckoutOperation } from './constants.js';\nimport { type AcpFailure, acpFailure } from './errors.js';\nimport { type AcpDefinition, validateAcpDocument } from './validation.js';\n\n/** One ACP answer, as a value: it may have to be stored before it is written. */\nexport interface AcpResponse {\n readonly status: number;\n readonly body: unknown;\n /** True when this answer came from the idempotency store rather than work done now. */\n readonly replayed?: boolean;\n}\n\n/**\n * The status each route answers on success, fixed by ACP. A merchant backend\n * that succeeded with a different one has not implemented the operation ACP\n * describes, so its answer is refused rather than quietly renumbered.\n */\nexport const ACP_SUCCESS_STATUS: Readonly<Record<AcpCheckoutOperation, number>> = {\n createCheckoutSession: 201,\n updateCheckoutSession: 200,\n getCheckoutSession: 200,\n completeCheckoutSession: 200,\n cancelCheckoutSession: 200,\n};\n\n/**\n * A mapped response, plus whatever the operator needs in the log to understand\n * a refusal. `logDetail` never reaches the client - that is the whole point of\n * carrying it separately from `response`.\n */\nexport interface AcpMappedResponse {\n readonly response: AcpResponse;\n readonly logDetail?: Readonly<Record<string, unknown>>;\n}\n\nconst PROCESSING_ERROR = acpFailure(\n 500,\n 'processing_error',\n 'processing_error',\n 'The server could not process this checkout operation.',\n);\n\nexport function toAcpResponse(\n operation: AcpCheckoutOperation,\n outcome: DeliveredOutcome,\n): AcpMappedResponse {\n const expected = ACP_SUCCESS_STATUS[operation];\n if (outcome.backendStatus !== expected) {\n return {\n response: asResponse(PROCESSING_ERROR),\n logDetail: {\n reason: 'unexpected-backend-status',\n operation,\n backendStatus: outcome.backendStatus,\n expected,\n },\n };\n }\n\n const definition = responseDefinition(operation, outcome.body);\n const failure = validateAcpDocument(definition, outcome.body);\n if (failure !== undefined) {\n // The backend document is not ACP. It must not be forwarded, and the\n // caller learns nothing about its shape - the pointer is into the\n // *merchant's* document, which is ours to fix, not theirs.\n return {\n response: asResponse(PROCESSING_ERROR),\n logDetail: {\n reason: 'backend-response-not-acp',\n operation,\n definition,\n path: failure.path ?? '$',\n keyword: failure.code,\n },\n };\n }\n\n return { response: { status: expected, body: outcome.body } };\n}\n\n/**\n * Completion is the one route with two shapes.\n *\n * A completed session must carry its order - that is the `CheckoutSessionWithOrder`\n * definition, and `Order` requires an id. But a completion attempt that ends in\n * a declined payment or an out-of-stock line item legitimately answers 200 with\n * an ordinary session and no order (both are examples in the snapshot), so\n * demanding an order on every completion would refuse valid merchant answers.\n * The session's own `status` is what decides which contract applies.\n */\nfunction responseDefinition(operation: AcpCheckoutOperation, body: unknown): AcpDefinition {\n if (operation !== 'completeCheckoutSession') return 'checkoutSession';\n const status = (body as { status?: unknown } | null)?.status;\n return status === 'completed' ? 'checkoutSessionWithOrder' : 'checkoutSession';\n}\n\n/**\n * Every failure the pipeline can raise, in ACP's vocabulary.\n *\n * Only the error *code* and, for a backend failure, the backend's *status*\n * cross this boundary. Both are ours to state; the merchant's response body is\n * not, and the gateway already withholds it.\n */\nexport function mapCommerceErrorToAcp(\n error: CommerceError,\n operation: AcpCheckoutOperation,\n): AcpFailure {\n switch (error.code) {\n case 'INPUT_INVALID':\n // The ACP schema accepted the document, so this is the *resource's* input\n // contract rejecting it: a configuration mismatch the caller cannot fix,\n // reported without naming the resource's internal field names.\n return acpFailure(\n 400,\n 'invalid_request',\n 'invalid_request_body',\n 'The request could not be accepted for this checkout operation.',\n );\n case 'BACKEND_TIMEOUT':\n return acpFailure(\n 504,\n 'service_unavailable',\n 'service_unavailable',\n 'The merchant did not respond in time.',\n );\n case 'GATEWAY_BUSY':\n return acpFailure(\n 503,\n 'service_unavailable',\n 'service_unavailable',\n 'The gateway is busy; retry shortly.',\n );\n case 'BACKEND_ERROR':\n return fromBackendStatus(error, operation);\n default:\n // RESOURCE_NOT_FOUND means the mapping points at a resource that is gone;\n // a PAYMENT_* code means a checkout resource was configured as paid.\n // Both are broken deployments, not something the caller did.\n return PROCESSING_ERROR;\n }\n}\n\n/**\n * A merchant status worth relaying, or a 502.\n *\n * Only statuses that mean the same thing to an ACP client are passed through.\n * A merchant 401 or 403, in particular, is not: relaying it would tell the\n * agent its own bearer token failed, when what failed is the gateway's\n * credential with the backend.\n */\nfunction fromBackendStatus(error: CommerceError, operation: AcpCheckoutOperation): AcpFailure {\n const status = error.details?.['status'];\n switch (typeof status === 'number' ? status : 0) {\n case 404:\n return acpFailure(\n 404,\n 'invalid_request',\n 'checkout_session_not_found',\n 'No such checkout session.',\n );\n case 405:\n return operation === 'cancelCheckoutSession'\n ? acpFailure(\n 405,\n 'invalid_request',\n 'checkout_session_not_cancelable',\n 'This checkout session can no longer be canceled.',\n )\n : acpFailure(\n 405,\n 'invalid_request',\n 'method_not_allowed',\n 'The merchant does not allow this operation on this checkout session.',\n );\n case 400:\n case 422:\n return acpFailure(\n 422,\n 'invalid_request',\n 'invalid_request_body',\n 'The merchant rejected this checkout request.',\n );\n case 409:\n return acpFailure(\n 409,\n 'invalid_request',\n 'checkout_session_conflict',\n 'This checkout session is in a state that does not allow this operation.',\n );\n default:\n return acpFailure(\n 502,\n 'processing_error',\n 'processing_error',\n 'The merchant could not process this checkout operation.',\n );\n }\n}\n\nexport function asResponse(failure: AcpFailure): AcpResponse {\n return { status: failure.status, body: failure.error };\n}\n","/**\n * ACP (Agentic Commerce Protocol) adapter - experimental.\n *\n * Serves two paths: the configured mount (`/acp`), where the five stable\n * checkout routes live, and the specification-fixed `/.well-known/acp.json`,\n * declared through `additionalHttpRoutes` so the gateway needs no ACP-specific\n * routing.\n *\n * Discovery and every protocol guard that must hold before canonical execution\n * are implemented. A guarded request is not executed yet: until checkout\n * operations reach the pipeline, a fully-valid request is answered with an\n * honest \"not implemented\" rather than a fabricated session.\n *\n * This file never calls a merchant backend and never inspects a payment\n * object.\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport {\n type AdapterDescriptor,\n type AdapterHealth,\n type AdapterHttpRoute,\n CommerceError,\n type CommerceResource,\n type DeliveredOutcome,\n type HttpProtocolAdapter,\n type ProtocolAdapterContext,\n toCommerceError,\n} from '../../core/index.js';\nimport { PACKAGE_VERSION } from '../../version.js';\nimport { toCanonicalRequest } from './checkout-mapping.js';\nimport {\n ACP_CHECKOUT_OPERATIONS,\n ACP_IDEMPOTENCY_KEY_HEADER,\n ACP_IDEMPOTENT_REPLAYED_HEADER,\n ACP_IN_FLIGHT_RETRY_AFTER_SECONDS,\n ACP_REQUEST_ID_HEADER,\n ACP_WELL_KNOWN_PATH,\n type AcpCheckoutOperation,\n} from './constants.js';\nimport { buildDescriptor } from './descriptor.js';\nimport { type AcpDiscoveryMetadata, buildAcpDiscoveryDocument } from './discovery.js';\nimport { acpFailure, writeAcpFailure, writeAcpJson } from './errors.js';\nimport { identityHash, requestFingerprint } from './idempotency/fingerprint.js';\nimport {\n type AcpIdempotencyScope,\n type AcpIdempotencyStore,\n createAcpIdempotencyStore,\n} from './idempotency/store.js';\nimport { type AcpGuardedRequest, guardAcpRequest } from './request-guards.js';\nimport {\n type AcpResponse,\n asResponse,\n mapCommerceErrorToAcp,\n toAcpResponse,\n} from './response-mapping.js';\nimport { validateAcpDocument } from './validation.js';\n\n/** Discovery is stable for the life of the process, so it is safe to cache at the edge. */\nconst DISCOVERY_CACHE_CONTROL = 'public, max-age=3600';\n\nexport interface AcpAdapterOptions {\n readonly mountPath: string;\n /** The configured bearer token. Never logged, never echoed, never published. */\n readonly token: string;\n /** Which canonical resource implements each ACP checkout operation. */\n readonly operations: Readonly<Record<AcpCheckoutOperation, string>>;\n /** Where checkout idempotency records live, and how long they are kept. */\n readonly idempotency: { readonly path: string; readonly retentionHours: number };\n readonly discovery?: AcpDiscoveryMetadata;\n}\n\nexport class AcpProtocolAdapter implements HttpProtocolAdapter {\n readonly name = 'acp' as const;\n readonly mountPath: string;\n readonly descriptor: AdapterDescriptor;\n readonly additionalHttpRoutes: readonly AdapterHttpRoute[];\n\n private readonly token: string;\n private readonly operations: Readonly<Record<AcpCheckoutOperation, string>>;\n private readonly idempotencyOptions: AcpAdapterOptions['idempotency'];\n /** Derived once: the token is fixed, and only its digest may be persisted. */\n private readonly identityHash: string;\n private readonly discoveryMetadata: AcpDiscoveryMetadata | undefined;\n private idempotency: AcpIdempotencyStore | undefined;\n private resources: ReadonlyMap<AcpCheckoutOperation, CommerceResource> = new Map();\n\n private context: ProtocolAdapterContext | undefined;\n private started = false;\n // Built once at start: the document is fixed by config, and rebuilding it\n // per request would let an unauthenticated GET do work a caller controls the\n // cost of.\n private discovery: Record<string, unknown> | undefined;\n\n constructor(options: AcpAdapterOptions) {\n this.mountPath = options.mountPath;\n this.token = options.token;\n this.operations = options.operations;\n this.idempotencyOptions = options.idempotency;\n this.identityHash = identityHash(options.token);\n this.discoveryMetadata = options.discovery;\n this.descriptor = buildDescriptor(PACKAGE_VERSION);\n this.additionalHttpRoutes = [\n {\n method: 'GET',\n path: ACP_WELL_KNOWN_PATH,\n handleHttp: (req, res) => this.handleDiscovery(req, res),\n },\n ];\n }\n\n async start(context: ProtocolAdapterContext): Promise<void> {\n this.context = context;\n this.started = false;\n\n const document = buildAcpDiscoveryDocument({\n publicBaseUrl: context.publicBaseUrl,\n mountPath: this.mountPath,\n ...(this.discoveryMetadata !== undefined ? { metadata: this.discoveryMetadata } : {}),\n });\n // Validated against the pinned snapshot rather than trusted: configured\n // metadata is free text (a currency that is not ISO 4217, an intervention\n // type ACP does not define), and publishing a document that fails ACP's own\n // schema would be the blanket-compatibility claim this project refuses to\n // make. Failing here fails only this adapter - the gateway isolates it.\n const invalid = validateAcpDocument('discoveryResponse', document);\n if (invalid !== undefined) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `ACP discovery document does not conform to the ${this.descriptor.supportedSpec} snapshot at \"${invalid.path ?? '$'}\" (${invalid.code}) - check protocols.acp.discovery`,\n { details: { path: invalid.path ?? '$', code: invalid.code } },\n );\n }\n\n // The same defence in depth MCP and A2A apply: config already refuses a\n // mapping to a resource that is not acp-exposed, but the adapter must not\n // rely on that alone to keep a resource scoped to another protocol out of\n // an ACP checkout.\n const exposed = new Map(\n context.resources.listExposedVia('acp').map((resource) => [resource.id, resource]),\n );\n const resolved = new Map<AcpCheckoutOperation, CommerceResource>();\n for (const operation of ACP_CHECKOUT_OPERATIONS) {\n const resourceId = this.operations[operation];\n const resource = exposed.get(resourceId);\n if (resource === undefined) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `ACP operation \"${operation}\" is mapped to resource \"${resourceId}\", which is not exposed via acp`,\n { details: { operation, resourceId } },\n );\n }\n resolved.set(operation, resource);\n }\n this.resources = resolved;\n\n this.idempotency = createAcpIdempotencyStore({\n path: this.idempotencyOptions.path,\n retentionHours: this.idempotencyOptions.retentionHours,\n logger: context.logger,\n });\n\n this.discovery = document;\n this.started = true;\n context.logger.info(\n {\n mountPath: this.mountPath,\n discoveryPath: ACP_WELL_KNOWN_PATH,\n idempotencyRetentionHours: this.idempotencyOptions.retentionHours,\n },\n 'acp adapter started',\n );\n }\n\n /** `GET /.well-known/acp.json` - public, unauthenticated, cacheable. */\n async handleDiscovery(req: IncomingMessage, res: ServerResponse): Promise<void> {\n try {\n if (!this.started || this.discovery === undefined) {\n writeAcpFailure(\n res,\n acpFailure(\n 503,\n 'service_unavailable',\n 'service_unavailable',\n 'The ACP adapter is not running.',\n ),\n );\n return;\n }\n if (req.method !== 'GET') {\n writeAcpFailure(\n res,\n acpFailure(\n 405,\n 'invalid_request',\n 'method_not_allowed',\n 'The ACP discovery document is read-only.',\n ),\n );\n return;\n }\n writeAcpJson(res, 200, this.discovery, { 'cache-control': DISCOVERY_CACHE_CONTROL });\n } catch (err) {\n this.fail(res, err, 'acp adapter: discovery request failed');\n }\n }\n\n /** `<mountPath>/checkout_sessions...` - the five stable checkout routes. */\n async handleHttp(req: IncomingMessage, res: ServerResponse): Promise<void> {\n try {\n if (!this.started) {\n writeAcpFailure(\n res,\n acpFailure(\n 503,\n 'service_unavailable',\n 'service_unavailable',\n 'The ACP adapter is not running.',\n ),\n );\n return;\n }\n\n const guarded = await guardAcpRequest(req, {\n mountPath: this.mountPath,\n token: this.token,\n });\n if (!guarded.ok) {\n // A guard failure never carries a Request-Id echo: the header is only\n // normalised once the request is known to be well-formed.\n writeAcpFailure(res, guarded);\n return;\n }\n\n const request = guarded.value;\n const response = await this.dispatch(request);\n writeAcpJson(res, response.status, response.body, this.responseHeaders(request, response));\n } catch (err) {\n this.fail(res, err, 'acp adapter: request handling failed');\n }\n }\n\n /**\n * One request, at most one execution.\n *\n * A body-bearing route claims its idempotency key *before* the work starts,\n * so a retry that arrives while the first one is still running finds the\n * claim instead of starting a second checkout. A route with no key (the GET)\n * is read-only and needs none.\n */\n private async dispatch(request: AcpGuardedRequest): Promise<AcpResponse> {\n const store = this.idempotency;\n const key = request.idempotencyKey;\n if (store === undefined || key === undefined) return this.runCheckout(request);\n\n const scope: AcpIdempotencyScope = {\n identityHash: this.identityHash,\n endpoint: request.route.path,\n key,\n };\n const claim = store.claim(scope, requestFingerprint(request.body));\n\n switch (claim.kind) {\n case 'in-flight':\n return asResponse(\n acpFailure(\n 409,\n 'invalid_request',\n 'idempotency_in_flight',\n 'A request with this Idempotency-Key is still being processed.',\n ),\n );\n case 'conflict':\n return asResponse(\n acpFailure(\n 422,\n 'invalid_request',\n 'idempotency_conflict',\n 'This Idempotency-Key was already used for a different request body.',\n ),\n );\n case 'replay':\n return { status: claim.status, body: claim.body, replayed: true };\n default:\n break;\n }\n\n let response: AcpResponse;\n try {\n response = await this.runCheckout(request);\n } catch (err) {\n // The attempt produced no answer worth keeping, so the key is freed for a\n // clean retry rather than left claimed by a request that never completed.\n store.release(scope);\n throw err;\n }\n\n // 5xx is never cached: a transient failure must not poison the key for the\n // whole retention window. 2xx and 4xx are the answer to this request and\n // every retry of it.\n if (response.status >= 500) store.release(scope);\n else store.complete(scope, response);\n return response;\n }\n\n /**\n * One accepted request, one `pipeline.execute()`.\n *\n * Nothing here prices a resource, inspects a payment proof or calls a\n * merchant backend: the adapter builds a canonical request and reads back\n * what the pipeline decided.\n */\n private async runCheckout(request: AcpGuardedRequest): Promise<AcpResponse> {\n const context = this.context;\n const resource = this.resources.get(request.route.operation);\n if (context === undefined || resource === undefined) {\n return asResponse(\n acpFailure(\n 503,\n 'service_unavailable',\n 'service_unavailable',\n 'The ACP adapter is not running.',\n ),\n );\n }\n\n const canonical = toCanonicalRequest({\n request,\n resourceId: resource.id,\n requestId: context.ids.next('acp'),\n receivedAt: context.clock.nowIso(),\n });\n\n try {\n const outcome = await context.pipeline.execute(canonical);\n if (outcome.kind === 'payment-required') {\n // ACP has no wire representation for a gateway payment challenge, and\n // config refuses a paid checkout resource - so reaching this is a\n // broken deployment, not something the caller can act on. Nothing about\n // the challenge is disclosed.\n context.logger.error(\n { resourceId: resource.id, requestId: canonical.requestId },\n 'acp adapter: mapped checkout resource returned payment-required - it must be priced free',\n );\n return asResponse(\n acpFailure(\n 500,\n 'processing_error',\n 'processing_error',\n 'The server could not process this checkout operation.',\n ),\n );\n }\n const mapped = toAcpResponse(request.route.operation, outcome as DeliveredOutcome);\n if (mapped.logDetail !== undefined) {\n // The merchant answered, but not with ACP. Everything needed to fix it\n // goes to the log; the caller gets the safe refusal in `response`.\n context.logger.error(\n { resourceId: resource.id, requestId: canonical.requestId, ...mapped.logDetail },\n 'acp adapter: refusing to forward a non-conformant merchant response',\n );\n }\n return mapped.response;\n } catch (err) {\n const error = toCommerceError(err);\n context.logger.warn(\n { resourceId: resource.id, requestId: canonical.requestId, err: error.toInfo() },\n 'acp adapter: checkout execution failed',\n );\n return asResponse(mapCommerceErrorToAcp(error, request.route.operation));\n }\n }\n\n /**\n * Protocol-owned headers only. A merchant backend's own headers are never\n * proxied onto an ACP response.\n */\n private responseHeaders(\n request: AcpGuardedRequest,\n response?: AcpResponse,\n ): Readonly<Record<string, string>> {\n const replayed = response?.replayed === true;\n return {\n ...(request.requestId !== undefined ? { [ACP_REQUEST_ID_HEADER]: request.requestId } : {}),\n ...(request.idempotencyKey !== undefined\n ? { [ACP_IDEMPOTENCY_KEY_HEADER]: request.idempotencyKey }\n : {}),\n ...(replayed ? { [ACP_IDEMPOTENT_REPLAYED_HEADER]: 'true' } : {}),\n ...(response?.status === 409\n ? { 'retry-after': String(ACP_IN_FLIGHT_RETRY_AFTER_SECONDS) }\n : {}),\n };\n }\n\n private fail(res: ServerResponse, err: unknown, message: string): void {\n // Nothing from `err` reaches the client: stack, exception name and any\n // upstream detail stay in the log.\n this.context?.logger.error({ err: toCommerceError(err).toInfo() }, message);\n writeAcpFailure(\n res,\n acpFailure(500, 'processing_error', 'internal_error', 'Internal server error.'),\n );\n }\n\n async health(): Promise<AdapterHealth> {\n const checkedAt = this.context?.clock.nowIso() ?? new Date().toISOString();\n if (!this.started || this.discovery === undefined) {\n return { status: 'fail', detail: 'ACP adapter has not been started.', checkedAt };\n }\n return {\n status: 'pass',\n detail: `checkout service published at ${this.mountPath}.`,\n checkedAt,\n };\n }\n\n async stop(): Promise<void> {\n this.started = false;\n this.discovery = undefined;\n this.resources = new Map();\n this.idempotency?.close();\n this.idempotency = undefined;\n this.context = undefined;\n }\n}\n\nexport function createAcpAdapter(options: AcpAdapterOptions): AcpProtocolAdapter {\n return new AcpProtocolAdapter(options);\n}\n","/**\n * Defence-in-depth against accidentally persisting secrets.\n *\n * The gateway and payment providers are expected to never place secrets into\n * `CommerceReceipt.metadata`, `CommerceEvent.data` or `PaymentResult.metadata`\n * (see docs/contracts.md, \"Store NO secrets\"). This module is a second line\n * of defence at the persistence boundary: any key that *looks* like it holds\n * a private key, an auth header or a raw payment proof is stripped — never\n * persisted — rather than rejecting the whole write, so a logging bug never\n * takes down an otherwise-successful commerce flow (appendEvent especially\n * must never throw into the caller's flow).\n */\n/**\n * The bearer-token family was missing — `token`, `bearerToken`,\n * `adminToken`, `authToken`, `credential`, `cookie`, `sessionId`, `jwt` all\n * returned false. Nothing writes such a key today, which is exactly the state\n * a second line of defence is for; and this data also lands in a\n * file that is now owner-only precisely because it is worth protecting.\n */\nconst SECRET_KEY_PATTERN =\n /private[-_ ]?key|secret|password|mnemonic|seed[-_ ]?phrase|api[-_ ]?key|authoriz(e|ation)|^auth$|auth[-_]?header|payment[-_ ]?proof|^proof$|x-payment|signature|signed[-_ ]?message|token|bearer|credential|cookie|session|jwt/i;\n\nconst REDACTED = '[REDACTED]';\n\n/** True if `key` looks like it names a secret value. */\nexport function isSecretKey(key: string): boolean {\n return SECRET_KEY_PATTERN.test(key);\n}\n\n/**\n * Recursively strip values whose key looks secret-shaped, returning a new\n * object. Safe to call on already-clean data (no-op in that case).\n */\nexport function redact<T>(value: T): T {\n return redactValue(value) as T;\n}\n\nfunction redactValue(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(redactValue);\n }\n if (value !== null && typeof value === 'object') {\n const out: Record<string, unknown> = {};\n for (const [key, inner] of Object.entries(value as Record<string, unknown>)) {\n out[key] = isSecretKey(key) ? REDACTED : redactValue(inner);\n }\n return out;\n }\n return value;\n}\n\n/** True if `value` (recursively) contains any key that looks secret-shaped. */\nexport function containsSecretKey(value: unknown): boolean {\n if (Array.isArray(value)) {\n return value.some(containsSecretKey);\n }\n if (value !== null && typeof value === 'object') {\n return Object.entries(value as Record<string, unknown>).some(\n ([key, inner]) => isSecretKey(key) || containsSecretKey(inner),\n );\n }\n return false;\n}\n","/**\n * SQLite row shapes and mapping to/from the canonical domain model.\n *\n * `exactOptionalPropertyTypes` is on: optional fields are only assigned when\n * present (see docs/contracts.md, assumption 8).\n */\nimport type {\n CommerceEvent,\n CommerceEventType,\n CommerceReceipt,\n PaymentAttempt,\n PaymentResult,\n} from '../../core/index.js';\nimport { redact } from './redact.js';\n\nexport interface ReceiptRow {\n readonly id: string;\n readonly request_id: string;\n readonly resource_id: string;\n readonly payment_json: string | null;\n readonly delivered_at: string;\n readonly backend_status: number;\n readonly duration_ms: number | null;\n readonly protocol: string | null;\n readonly metadata_json: string | null;\n}\n\nexport interface EventRow {\n readonly id: string;\n readonly type: string;\n readonly request_id: string;\n readonly resource_id: string | null;\n readonly at: string;\n readonly adapter: string | null;\n readonly payment_provider: string | null;\n readonly duration_ms: number | null;\n readonly status: string | null;\n readonly data_json: string | null;\n}\n\nexport interface PaymentAttemptRow {\n readonly id: string;\n readonly request_id: string;\n readonly resource_id: string;\n readonly provider: string;\n readonly replay_key: string;\n readonly status: string;\n readonly amount: string;\n readonly currency: string;\n readonly payer: string | null;\n readonly payee: string | null;\n readonly external_reference: string | null;\n readonly rejection_reason: string | null;\n readonly created_at: string;\n readonly updated_at: string;\n}\n\nexport function receiptToRow(receipt: CommerceReceipt): {\n id: string;\n request_id: string;\n resource_id: string;\n payment_json: string | null;\n delivered_at: string;\n backend_status: number;\n duration_ms: number | null;\n protocol: string | null;\n metadata_json: string | null;\n} {\n return {\n id: receipt.id,\n request_id: receipt.requestId,\n resource_id: receipt.resourceId,\n payment_json: receipt.payment !== undefined ? JSON.stringify(redact(receipt.payment)) : null,\n delivered_at: receipt.deliveredAt,\n backend_status: receipt.backendStatus,\n duration_ms: receipt.durationMs !== undefined ? receipt.durationMs : null,\n protocol: receipt.protocol !== undefined ? receipt.protocol : null,\n metadata_json: receipt.metadata !== undefined ? JSON.stringify(redact(receipt.metadata)) : null,\n };\n}\n\nexport function rowToReceipt(row: ReceiptRow): CommerceReceipt {\n const payment =\n row.payment_json !== null ? (JSON.parse(row.payment_json) as PaymentResult) : undefined;\n const metadata =\n row.metadata_json !== null\n ? (JSON.parse(row.metadata_json) as Record<string, unknown>)\n : undefined;\n return {\n id: row.id,\n requestId: row.request_id,\n resourceId: row.resource_id,\n deliveredAt: row.delivered_at,\n backendStatus: row.backend_status,\n ...(payment !== undefined ? { payment } : {}),\n ...(row.duration_ms !== null ? { durationMs: row.duration_ms } : {}),\n ...(row.protocol !== null ? { protocol: row.protocol } : {}),\n ...(metadata !== undefined ? { metadata } : {}),\n };\n}\n\nexport function eventToRow(event: CommerceEvent): {\n id: string;\n type: string;\n request_id: string;\n resource_id: string | null;\n at: string;\n adapter: string | null;\n payment_provider: string | null;\n duration_ms: number | null;\n status: string | null;\n data_json: string | null;\n} {\n return {\n id: event.id,\n type: event.type,\n request_id: event.requestId,\n resource_id: event.resourceId !== undefined ? event.resourceId : null,\n at: event.at,\n adapter: event.adapter !== undefined ? event.adapter : null,\n payment_provider: event.paymentProvider !== undefined ? event.paymentProvider : null,\n duration_ms: event.durationMs !== undefined ? event.durationMs : null,\n status: event.status !== undefined ? event.status : null,\n data_json: event.data !== undefined ? JSON.stringify(redact(event.data)) : null,\n };\n}\n\nexport function rowToEvent(row: EventRow): CommerceEvent {\n const data =\n row.data_json !== null ? (JSON.parse(row.data_json) as Record<string, unknown>) : undefined;\n return {\n id: row.id,\n type: row.type as CommerceEventType,\n requestId: row.request_id,\n at: row.at,\n ...(row.resource_id !== null ? { resourceId: row.resource_id } : {}),\n ...(row.adapter !== null ? { adapter: row.adapter } : {}),\n ...(row.payment_provider !== null ? { paymentProvider: row.payment_provider } : {}),\n ...(row.duration_ms !== null ? { durationMs: row.duration_ms } : {}),\n ...(row.status !== null ? { status: row.status as 'ok' | 'error' } : {}),\n ...(data !== undefined ? { data } : {}),\n };\n}\n\nexport function rowToPaymentAttempt(row: PaymentAttemptRow): PaymentAttempt {\n return {\n id: row.id,\n requestId: row.request_id,\n resourceId: row.resource_id,\n provider: row.provider,\n replayKey: row.replay_key,\n status: row.status as PaymentAttempt['status'],\n amount: row.amount,\n currency: row.currency,\n ...(row.payer !== null ? { payer: row.payer } : {}),\n ...(row.payee !== null ? { payee: row.payee } : {}),\n ...(row.external_reference !== null ? { externalReference: row.external_reference } : {}),\n ...(row.rejection_reason !== null ? { rejectionReason: row.rejection_reason } : {}),\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n}\n","/**\n * Explicit migration scheme for the receipt-store SQLite schema.\n *\n * Uses SQLite's built-in `PRAGMA user_version` as the migration marker so a\n * restart against an existing database file re-opens without re-creating or\n * losing data (required negative test: \"gateway restart with receipt storage\n * preserved\").\n */\nimport type Database from 'better-sqlite3';\n\ninterface Migration {\n readonly version: number;\n up(db: Database.Database): void;\n}\n\nconst MIGRATIONS: readonly Migration[] = [\n {\n version: 1,\n up(db) {\n db.exec(`\n CREATE TABLE IF NOT EXISTS receipts (\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n id TEXT NOT NULL UNIQUE,\n request_id TEXT NOT NULL,\n resource_id TEXT NOT NULL,\n payment_json TEXT,\n delivered_at TEXT NOT NULL,\n backend_status INTEGER NOT NULL,\n duration_ms INTEGER,\n protocol TEXT,\n metadata_json TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_receipts_request_id ON receipts(request_id);\n CREATE INDEX IF NOT EXISTS idx_receipts_delivered_at ON receipts(delivered_at);\n\n CREATE TABLE IF NOT EXISTS events (\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n id TEXT NOT NULL UNIQUE,\n type TEXT NOT NULL,\n request_id TEXT NOT NULL,\n resource_id TEXT,\n at TEXT NOT NULL,\n adapter TEXT,\n payment_provider TEXT,\n duration_ms INTEGER,\n status TEXT,\n data_json TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_events_request_id ON events(request_id);\n CREATE INDEX IF NOT EXISTS idx_events_at ON events(at);\n\n CREATE TABLE IF NOT EXISTS payment_attempts (\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n id TEXT NOT NULL UNIQUE,\n request_id TEXT NOT NULL,\n resource_id TEXT NOT NULL,\n provider TEXT NOT NULL,\n replay_key TEXT NOT NULL UNIQUE,\n status TEXT NOT NULL,\n amount TEXT NOT NULL,\n currency TEXT NOT NULL,\n payer TEXT,\n payee TEXT,\n external_reference TEXT,\n rejection_reason TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_payment_attempts_request_id ON payment_attempts(request_id);\n CREATE INDEX IF NOT EXISTS idx_payment_attempts_created_at ON payment_attempts(created_at);\n `);\n },\n },\n];\n\n/** Current target schema version — the version of the last migration. */\nexport const SCHEMA_VERSION = MIGRATIONS[MIGRATIONS.length - 1]?.version ?? 0;\n\n/**\n * Bring `db` up to {@link SCHEMA_VERSION}. Idempotent: re-opening an existing,\n * already-migrated file is a fast no-op check against `PRAGMA user_version`.\n */\nexport function migrate(db: Database.Database): void {\n const current = db.pragma('user_version', { simple: true }) as number;\n for (const migration of MIGRATIONS) {\n if (migration.version <= current) continue;\n const apply = db.transaction(() => {\n migration.up(db);\n db.pragma(`user_version = ${migration.version}`);\n });\n apply();\n }\n}\n","/**\n * SQLite implementation of the frozen ReceiptStore interface.\n *\n * Thin repository layer — no ORM. Every write goes through a prepared\n * statement; the only thing that varies between calls is parameters.\n */\nimport { randomUUID } from 'node:crypto';\nimport { accessSync, constants as fsConstants } from 'node:fs';\nimport {\n type AdapterDescriptor,\n type AdapterHealth,\n type Clock,\n CommerceError,\n type CommerceEvent,\n type CommerceReceipt,\n type IdGenerator,\n type ListOptions,\n type Logger,\n NOOP_LOGGER,\n type PaymentAttempt,\n type PaymentAttemptReservation,\n type PaymentAttemptUpdate,\n type ReceiptStore,\n systemClock,\n toCommerceError,\n} from '../../core/index.js';\nimport { PACKAGE_VERSION } from '../../version.js';\nimport { openSqliteDatabase } from '../sqlite.js';\nimport {\n type EventRow,\n eventToRow,\n type PaymentAttemptRow,\n type ReceiptRow,\n receiptToRow,\n rowToEvent,\n rowToPaymentAttempt,\n rowToReceipt,\n} from './rows.js';\nimport { migrate, SCHEMA_VERSION } from './schema.js';\n\nconst DEFAULT_LIST_LIMIT = 50;\n/**\n * Hard ceiling on every list query, applied here rather than only at the\n * gateway route, so every caller (HTTP, CLI, a future adapter) is covered.\n * SQLite treats a negative `LIMIT` as \"no limit\" —\n * confirmed `{ limit: -1 }` returns the entire table.\n */\nconst MAX_LIST_LIMIT = 500;\n\n/**\n * Clamps to a whole number in [1, MAX_LIST_LIMIT], defaulting when absent OR\n * non-finite (NaN/Infinity) — a store-level invariant that must hold\n * regardless of whether the current caller already filters those out.\n */\nfunction clampListLimit(limit: number | undefined): number {\n const base = limit !== undefined && Number.isFinite(limit) ? limit : DEFAULT_LIST_LIMIT;\n return Math.min(Math.max(Math.trunc(base), 1), MAX_LIST_LIMIT);\n}\n\nexport interface SqliteReceiptStoreOptions {\n /** File path, or ':memory:' for tests. Parent directory is created if missing. */\n readonly path: string;\n readonly logger?: Logger;\n readonly clock?: Clock;\n readonly ids?: IdGenerator;\n}\n\nconst defaultIds: IdGenerator = {\n next: (prefix) => (prefix !== undefined ? `${prefix}_${randomUUID()}` : randomUUID()),\n};\n\nfunction isUniqueConstraintOn(err: unknown, column: string): boolean {\n return (\n err instanceof Error &&\n 'code' in err &&\n (err as { code?: unknown }).code === 'SQLITE_CONSTRAINT_UNIQUE' &&\n err.message.includes(column)\n );\n}\n\nexport function createSqliteReceiptStore(options: SqliteReceiptStoreOptions): ReceiptStore {\n const logger = options.logger ?? NOOP_LOGGER;\n const clock = options.clock ?? systemClock;\n const ids = options.ids ?? defaultIds;\n const path = options.path;\n const isFileBacked = path !== ':memory:';\n\n // Opening and hardening the file is shared with the ACP idempotency store -\n // see src/storage/sqlite.ts. Two copies of that logic is how one of them\n // ends up shipping a world-readable database.\n const db = openSqliteDatabase({ path, label: 'Receipt database', logger });\n migrate(db);\n\n const insertReceiptStmt = db.prepare(\n `INSERT INTO receipts (id, request_id, resource_id, payment_json, delivered_at, backend_status, duration_ms, protocol, metadata_json)\n VALUES (@id, @request_id, @resource_id, @payment_json, @delivered_at, @backend_status, @duration_ms, @protocol, @metadata_json)`,\n );\n const getReceiptStmt = db.prepare<[string], ReceiptRow>('SELECT * FROM receipts WHERE id = ?');\n const listReceiptsStmt = db.prepare<[number], ReceiptRow>(\n 'SELECT * FROM receipts ORDER BY delivered_at DESC, seq DESC LIMIT ?',\n );\n const listReceiptsByRequestStmt = db.prepare<[string, number], ReceiptRow>(\n 'SELECT * FROM receipts WHERE request_id = ? ORDER BY delivered_at DESC, seq DESC LIMIT ?',\n );\n const countReceiptsStmt = db.prepare<[], { count: number }>(\n 'SELECT COUNT(*) AS count FROM receipts',\n );\n // backend_status is INTEGER NOT NULL (schema.ts) so NOT BETWEEN never has\n // a NULL row to silently miss; 0 (backend never responded at all) and\n // every non-2xx status both count as undelivered, matching the dashboard's\n // deliveryResult() (ReceiptList.tsx) — the two views must not disagree\n // about what \"delivered\" means, which is the confusion.\n const countUndeliveredReceiptsStmt = db.prepare<[], { count: number }>(\n 'SELECT COUNT(*) AS count FROM receipts WHERE backend_status NOT BETWEEN 200 AND 299',\n );\n\n const insertEventStmt = db.prepare(\n `INSERT INTO events (id, type, request_id, resource_id, at, adapter, payment_provider, duration_ms, status, data_json)\n VALUES (@id, @type, @request_id, @resource_id, @at, @adapter, @payment_provider, @duration_ms, @status, @data_json)`,\n );\n const listEventsStmt = db.prepare<[number], EventRow>(\n 'SELECT * FROM events ORDER BY at DESC, seq DESC LIMIT ?',\n );\n const listEventsByRequestStmt = db.prepare<[string, number], EventRow>(\n 'SELECT * FROM events WHERE request_id = ? ORDER BY at DESC, seq DESC LIMIT ?',\n );\n\n const insertPaymentAttemptStmt = db.prepare(\n `INSERT INTO payment_attempts (id, request_id, resource_id, provider, replay_key, status, amount, currency, payer, payee, external_reference, rejection_reason, created_at, updated_at)\n VALUES (@id, @request_id, @resource_id, @provider, @replay_key, @status, @amount, @currency, @payer, @payee, @external_reference, @rejection_reason, @created_at, @updated_at)`,\n );\n const getPaymentAttemptByIdStmt = db.prepare<[string], PaymentAttemptRow>(\n 'SELECT * FROM payment_attempts WHERE id = ?',\n );\n // COALESCE: an omitted field (bound as NULL — see updatePaymentAttempt)\n // means \"leave the existing value alone\", not \"clear it\". Without this, a\n // second update that doesn't re-supply external_reference/rejection_reason\n // erases it — exactly the field that carries the on-chain tx hash for a\n // settlement-uncertain attempt, the one record proving the buyer's funds\n // may have moved. There is no current caller that needs to clear an\n // already-set value; if one appears, it needs an explicit sentinel rather\n // than overloading `undefined` to mean two different things again.\n const updatePaymentAttemptStmt = db.prepare(\n `UPDATE payment_attempts SET status = @status,\n external_reference = COALESCE(@external_reference, external_reference),\n rejection_reason = COALESCE(@rejection_reason, rejection_reason),\n updated_at = @updated_at\n WHERE replay_key = @replay_key`,\n );\n const listPaymentAttemptsStmt = db.prepare<[number], PaymentAttemptRow>(\n 'SELECT * FROM payment_attempts ORDER BY created_at DESC, seq DESC LIMIT ?',\n );\n const listPaymentAttemptsByRequestStmt = db.prepare<[string, number], PaymentAttemptRow>(\n 'SELECT * FROM payment_attempts WHERE request_id = ? ORDER BY created_at DESC, seq DESC LIMIT ?',\n );\n\n let closed = false;\n\n const descriptor: AdapterDescriptor = {\n name: 'sqlite-receipt-store',\n kind: 'storage',\n implementationVersion: PACKAGE_VERSION,\n supportedSpec: `sqlite-schema-v${SCHEMA_VERSION}`,\n capabilities: ['receipts', 'events', 'payment-attempts'],\n status: 'stable',\n };\n\n const store: ReceiptStore = {\n async init(): Promise<void> {\n // Schema setup already happened synchronously above (better-sqlite3 is\n // sync). This re-check makes init() a meaningful, idempotent gate for\n // callers that treat it as the lifecycle hook that must succeed before\n // any other method is used.\n const version = db.pragma('user_version', { simple: true }) as number;\n if (version !== SCHEMA_VERSION) {\n throw new CommerceError(\n 'STORAGE_ERROR',\n `Receipt store schema version mismatch (found ${version}, expected ${SCHEMA_VERSION})`,\n );\n }\n },\n\n async appendEvent(event: CommerceEvent): Promise<void> {\n try {\n insertEventStmt.run(eventToRow(event));\n } catch (err) {\n logger.warn(\n {\n err: err instanceof Error ? err.message : String(err),\n eventId: event.id,\n requestId: event.requestId,\n },\n 'receipt-store: failed to persist commerce event',\n );\n }\n },\n\n async reservePaymentAttempt(reservation: PaymentAttemptReservation): Promise<PaymentAttempt> {\n const now = clock.nowIso();\n const id = ids.next('attempt');\n try {\n insertPaymentAttemptStmt.run({\n id,\n request_id: reservation.requestId,\n resource_id: reservation.resourceId,\n provider: reservation.provider,\n replay_key: reservation.replayKey,\n status: 'reserved' satisfies PaymentAttempt['status'],\n amount: reservation.amount,\n currency: reservation.currency,\n payer: reservation.payer ?? null,\n payee: reservation.payee ?? null,\n external_reference: null,\n rejection_reason: null,\n created_at: now,\n updated_at: now,\n });\n } catch (err) {\n if (isUniqueConstraintOn(err, 'payment_attempts.replay_key')) {\n throw new CommerceError(\n 'PAYMENT_REPLAYED',\n `Payment authorisation has already been used (replayKey=${reservation.replayKey})`,\n { requestId: reservation.requestId, resourceId: reservation.resourceId },\n );\n }\n throw toCommerceError(err, 'STORAGE_ERROR', 'Failed to reserve payment attempt');\n }\n const row = getPaymentAttemptByIdStmt.get(id);\n if (row === undefined) {\n throw new CommerceError(\n 'STORAGE_ERROR',\n 'Payment attempt vanished immediately after insert',\n );\n }\n return rowToPaymentAttempt(row);\n },\n\n async updatePaymentAttempt(update: PaymentAttemptUpdate): Promise<void> {\n try {\n const result = updatePaymentAttemptStmt.run({\n replay_key: update.replayKey,\n status: update.status,\n external_reference: update.externalReference ?? null,\n rejection_reason: update.rejectionReason ?? null,\n updated_at: clock.nowIso(),\n });\n if (result.changes === 0) {\n throw new CommerceError(\n 'STORAGE_ERROR',\n `No payment attempt found for replayKey=${update.replayKey}`,\n );\n }\n } catch (err) {\n throw toCommerceError(err, 'STORAGE_ERROR', 'Failed to update payment attempt');\n }\n },\n\n async saveReceipt(receipt: CommerceReceipt): Promise<void> {\n try {\n insertReceiptStmt.run(receiptToRow(receipt));\n } catch (err) {\n throw toCommerceError(err, 'STORAGE_ERROR', 'Failed to save receipt');\n }\n },\n\n async getReceipt(id: string): Promise<CommerceReceipt | undefined> {\n const row = getReceiptStmt.get(id);\n return row !== undefined ? rowToReceipt(row) : undefined;\n },\n\n async listReceipts(listOptions: ListOptions = {}): Promise<readonly CommerceReceipt[]> {\n const limit = clampListLimit(listOptions.limit);\n const rows =\n listOptions.requestId !== undefined\n ? listReceiptsByRequestStmt.all(listOptions.requestId, limit)\n : listReceiptsStmt.all(limit);\n return rows.map(rowToReceipt);\n },\n\n /** Exact total, ignoring the listReceipts clamp — see the interface doc for why this exists. */\n async countReceipts(): Promise<number> {\n return countReceiptsStmt.get()?.count ?? 0;\n },\n\n /** Exact count of non-2xx receipts — see the interface doc for why this exists. */\n async countUndeliveredReceipts(): Promise<number> {\n return countUndeliveredReceiptsStmt.get()?.count ?? 0;\n },\n\n async listEvents(listOptions: ListOptions = {}): Promise<readonly CommerceEvent[]> {\n const limit = clampListLimit(listOptions.limit);\n const rows =\n listOptions.requestId !== undefined\n ? listEventsByRequestStmt.all(listOptions.requestId, limit)\n : listEventsStmt.all(limit);\n return rows.map(rowToEvent);\n },\n\n async listPaymentAttempts(listOptions: ListOptions = {}): Promise<readonly PaymentAttempt[]> {\n const limit = clampListLimit(listOptions.limit);\n const rows =\n listOptions.requestId !== undefined\n ? listPaymentAttemptsByRequestStmt.all(listOptions.requestId, limit)\n : listPaymentAttemptsStmt.all(limit);\n return rows.map(rowToPaymentAttempt);\n },\n\n descriptor,\n\n async health(): Promise<AdapterHealth> {\n // Same discipline: a client-visible field is authored from a\n // fixed vocabulary, never inherited from a caught error's `.message`.\n // `accessSync` on a real deployment throws e.g.\n // \"EACCES: permission denied, access '/workspace/data/receipts.sqlite'\"\n // — an absolute host path that must never reach the unauthenticated\n // `/ready` response). The raw message still goes\n // to the injected logger, so nothing is lost for diagnosis.\n const startedAt = clock.monotonicMs();\n if (closed) {\n return { status: 'fail', detail: 'store-unavailable', checkedAt: clock.nowIso() };\n }\n if (isFileBacked) {\n try {\n accessSync(path, fsConstants.W_OK);\n } catch (err) {\n logger.warn(\n { err: err instanceof Error ? err.message : String(err) },\n 'receipt-store: health check failed (store not writable)',\n );\n return {\n status: 'fail',\n detail: 'store-unwritable',\n checkedAt: clock.nowIso(),\n durationMs: clock.monotonicMs() - startedAt,\n };\n }\n }\n try {\n const version = db.pragma('user_version', { simple: true }) as number;\n if (version !== SCHEMA_VERSION) {\n logger.warn(\n { found: version, expected: SCHEMA_VERSION },\n 'receipt-store: health check failed (schema version mismatch)',\n );\n return {\n status: 'fail',\n detail: 'store-schema-mismatch',\n checkedAt: clock.nowIso(),\n durationMs: clock.monotonicMs() - startedAt,\n };\n }\n return {\n status: 'pass',\n detail: `sqlite schema v${SCHEMA_VERSION} writable`,\n checkedAt: clock.nowIso(),\n durationMs: clock.monotonicMs() - startedAt,\n };\n } catch (err) {\n logger.warn(\n { err: err instanceof Error ? err.message : String(err) },\n 'receipt-store: health check failed (store unavailable)',\n );\n return {\n status: 'fail',\n detail: 'store-unavailable',\n checkedAt: clock.nowIso(),\n durationMs: clock.monotonicMs() - startedAt,\n };\n }\n },\n\n async close(): Promise<void> {\n if (!closed) {\n closed = true;\n db.close();\n }\n },\n };\n\n return store;\n}\n"]}
|