@devlab.group/agent-commerce 0.1.0-alpha.0 → 1.0.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 +144 -46
- package/dist/{chunk-CZ6ZDAYD.js → chunk-BQNE3A5H.js} +9 -7
- package/dist/chunk-BQNE3A5H.js.map +1 -0
- package/dist/chunk-MEPETSP6.js +255 -0
- package/dist/chunk-MEPETSP6.js.map +1 -0
- package/dist/cli/index.d.ts +1 -0
- package/dist/cli/index.js +401 -61
- package/dist/cli/index.js.map +1 -1
- package/dist/guardrails-Dmwi63KB.d.ts +38 -0
- package/dist/index.d.ts +38 -19
- package/dist/index.js +177 -48
- package/dist/index.js.map +1 -1
- package/dist/mcp.d.ts +2 -2
- package/dist/mcp.js +2 -2
- package/dist/mcp.js.map +1 -1
- package/dist/{protocol-adapter-C0goMgLK.d.ts → protocol-adapter-CZPOb9uG.d.ts} +2 -3
- package/dist/{runtime-LCk2TzGN.d.ts → runtime-B-9IjMbO.d.ts} +17 -5
- package/dist/x402.d.ts +83 -17
- package/dist/x402.js +321 -216
- package/dist/x402.js.map +1 -1
- package/package.json +19 -7
- package/dist/chunk-CZ6ZDAYD.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","describeError","fs","parseYaml","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AAA;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 * 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\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 const substituted = substituteOnce(value, env, path);\n\n // `${A:-${B}}` with A unset produced the literal string\n // `${B}` — an unresolved placeholder that survived into the config, directly\n // contradicting this module's promise that one fails loading immediately.\n // (`[^}]*` cannot span the inner `}`, so the default captured is `${B`, and\n // the trailing `}` is ordinary text.) Refusing is the fail-closed reading of\n // that promise; resolving recursively would mean deciding what `${A:-${B:-c}}`\n // and a self-reference should do, which no config here needs. A `${` with no\n // closing brace is left alone — it is not a placeholder.\n PLACEHOLDER_PATTERN.lastIndex = 0;\n if (PLACEHOLDER_PATTERN.test(substituted)) {\n PLACEHOLDER_PATTERN.lastIndex = 0;\n const residual = PLACEHOLDER_PATTERN.exec(substituted)?.[0] ?? '${…}';\n PLACEHOLDER_PATTERN.lastIndex = 0;\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration value at \"${path}\" still contains the unresolved placeholder \"${residual}\" after substitution — nested placeholders (e.g. \"\\${A:-\\${B}}\") are not supported. Use a plain default, or set the variable.`,\n { details: { path, residual } },\n );\n }\n return substituted;\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).\n */\nimport { type BackendHandler, DEFAULT_BACKEND_TIMEOUT_MS } 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 let target: URL;\n let remaining: Record<string, unknown>;\n try {\n const templated = applyPathTemplate(handler.url, inputRecord);\n target = new URL(templated.url);\n remaining = templated.remaining;\n } catch (error) {\n if (error instanceof Error && error.message.startsWith('invalid-path-parameter:')) {\n const field = error.message.slice('invalid-path-parameter:'.length);\n throw new CommerceError('INPUT_INVALID', `Path parameter \"${field}\" is not a valid value`, {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: { field },\n });\n }\n // Mirrors validateBackendRequestShape()'s own copy\n // — the pipeline calls that one first, so this branch is defence in\n // depth for a caller that bypasses it, not the normal path.\n if (error instanceof Error && error.message.startsWith('missing-path-parameter:')) {\n const field = error.message.slice('missing-path-parameter:'.length);\n throw new CommerceError('INPUT_INVALID', `Path parameter \"${field}\" was not supplied`, {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: { field },\n });\n }\n throw new CommerceError('BACKEND_ERROR', 'Backend URL could not be constructed from input', {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: { reason: describeConstructionError(error) },\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 if (handler.method === 'GET' || handler.method === 'DELETE') {\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, remaining, {\n requestId: request.requestId,\n resourceId: request.resourceId,\n });\n for (const [key, value] of Object.entries(remaining)) {\n target.searchParams.set(key, stringifyPrimitive(value));\n }\n } else {\n body = JSON.stringify(remaining);\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: { readonly requestId: string; readonly resourceId: string },\n): void {\n const inputRecord = isPlainObject(input) ? input : {};\n\n let templated: { url: string; remaining: Record<string, unknown> };\n try {\n templated = applyPathTemplate(handler.url, inputRecord);\n } catch (error) {\n if (error instanceof Error && error.message.startsWith('invalid-path-parameter:')) {\n const field = error.message.slice('invalid-path-parameter:'.length);\n throw new CommerceError('INPUT_INVALID', `Path parameter \"${field}\" is not a valid value`, {\n requestId: context.requestId,\n resourceId: context.resourceId,\n details: { field },\n });\n }\n if (error instanceof Error && error.message.startsWith('missing-path-parameter:')) {\n // Returning here is tempting: a missing path parameter is a\n // config/schema mismatch, not caller input, and so arguably not this\n // function's job. But that lets a paid, `{param}`-templated resource\n // whose schema can never supply it reach settle() on every call — the buyer pays, the backend is never\n // called, and there is no refund. The request genuinely cannot be\n // served, so it throws here, before payment, the same as an invalid\n // value does two lines up. `normaliseResource` (src/config) is\n // the root-cause fix — it rejects this shape at config load — but a\n // hand-built `CommerceResource` or a future adapter must not be able\n // to reintroduce the money bug just by skipping config validation.\n const field = error.message.slice('missing-path-parameter:'.length);\n throw new CommerceError('INPUT_INVALID', `Path parameter \"${field}\" was not supplied`, {\n requestId: context.requestId,\n resourceId: context.resourceId,\n details: { field },\n });\n }\n return;\n }\n\n if (handler.method === 'GET' || handler.method === 'DELETE') {\n let target: URL;\n try {\n target = new URL(templated.url);\n } catch {\n return; // call() surfaces the real BACKEND_ERROR for an unparseable URL.\n }\n checkQueryCollision(target, templated.remaining, context);\n }\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): { 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 throw new Error(`missing-path-parameter:${missing}`);\n }\n if (invalid !== undefined) {\n throw new Error(`invalid-path-parameter:${invalid}`);\n }\n return { url, remaining };\n}\n\nfunction describeConstructionError(error: unknown): string {\n if (error instanceof Error && error.message.startsWith('missing-path-parameter:')) {\n return error.message;\n }\n return 'invalid-url';\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 for v0.1.0-alpha — 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 //.\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.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 type Pricing,\n} from '../core/index.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\nconst ProtocolsSchema = z\n .object({\n http: z.object({ enabled: BooleanOrString }).strict(),\n mcp: z\n .object({\n enabled: BooleanOrString,\n mountPath: z.string().min(1),\n })\n .strict(),\n })\n .strict();\n\nconst BackendMethodSchema = z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']);\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 })\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\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 })\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 })\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 };\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:\n | { readonly mode: 'local'; readonly signerPrivateKey: string }\n | { readonly mode: 'remote'; readonly url: string };\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 = new Set(['http', 'mcp']);\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 };\n\n const x402Raw = raw.payments.x402;\n // facilitator.mode \"remote\" is documented as unimplemented (three\n // places), but was accepted at config load — the provider constructed and\n // health() returned only \"warn\" (not consulted by /ready), so the failure\n // landed inside settle(), after the buyer's payment authorisation was\n // already burned. Every buyer who hit it lost that authorisation\n // permanently and had to sign a fresh one that failed identically. Reject\n // it here, next to the dynamic-pricing and UCP rejections, so\n // `agent-commerce validate` catches it where an operator expects it.\n if (x402Raw?.facilitator.mode === 'remote') {\n throw new CommerceError(\n 'CONFIG_INVALID',\n 'payments.x402.facilitator.mode \"remote\" is not supported in v0.1.0-alpha; use \"local\" (the deterministic dev-chain facilitator)',\n { details: { path: 'payments.x402.facilitator.mode' } },\n );\n }\n const x402 = x402Raw\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(x402Raw.maxTimeoutSeconds, 'payments.x402.maxTimeoutSeconds', {\n min: 1,\n }),\n // Only \"local\" can reach here — \"remote\" was rejected above.\n facilitator: {\n mode: 'local' as const,\n signerPrivateKey: x402Raw.facilitator.signerPrivateKey,\n },\n }\n : undefined;\n\n if (x402) {\n validateAddress('payments.x402.payTo', x402.payTo);\n validateAddress('payments.x402.asset', x402.asset);\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}\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 v0.1.0-alpha)' : '';\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${id}\" exposes unsupported protocol \"${protocol}\"${hint}. Supported: http, mcp.`,\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('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 validatePathParametersDeclared(id, entry.backend.url, entry.input);\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 v0.1.0-alpha`,\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 },\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 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 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 * 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): 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 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 its input schema — 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 its input schema but not listed in \"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 X-PAYMENT header, private keys, seeds, mnemonics, 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[\"x-payment\"]',\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,x-payment,x-request-id,authorization';\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('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 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\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 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 handler = 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 adapter.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 instance.all(mountPath, handler);\n instance.all(wildcard, handler);\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 private key never appears either\n *. `doctor`'s live/local cross-check\n * (src/cli) only reads `asset`/`network`/`payTo` from this document, so\n * 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 { 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/v0.1.0-alpha';\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:\n | { readonly mode: 'local' }\n | { readonly mode: 'remote'; readonly url: string };\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\nexport async function buildWellKnownDocument(\n options: BuildWellKnownOptions,\n): Promise<WellKnownDocument> {\n const adapters = await Promise.all(\n options.adapterRuntimes.map(async (runtime) => ({\n ...runtime.adapter.descriptor,\n health: await getAdapterHealth(runtime, options.clock),\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 — only whether the facilitator is\n // local (dev-chain only) or remote, plus its (non-secret) URL.\n facilitator:\n x402.facilitator.mode === 'local'\n ? { mode: 'local' as const }\n : { mode: 'remote' as const, url: x402.facilitator.url },\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_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 reply.status(402).send(toPaymentRequiredEnvelope(outcome));\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 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, 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 externalReference === 'string' ? { externalReference } : {}),\n };\n}\n\nfunction encodePaymentSummary(payment: PaymentSummary): string {\n const summary = {\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 return Buffer.from(JSON.stringify(summary), 'utf8').toString('base64');\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 { accessSync, chmodSync, existsSync, constants as fsConstants, mkdirSync } 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. Best-effort by design: a filesystem without POSIX modes must not stop\n * the gateway from starting, so a failure warns 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 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/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","describeError","fs","parseYaml","randomUUID","fsConstants"],"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,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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).\n */\nimport { type BackendHandler, DEFAULT_BACKEND_TIMEOUT_MS } 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 let target: URL;\n let remaining: Record<string, unknown>;\n try {\n const templated = applyPathTemplate(handler.url, inputRecord);\n target = new URL(templated.url);\n remaining = templated.remaining;\n } catch (error) {\n if (error instanceof Error && error.message.startsWith('invalid-path-parameter:')) {\n const field = error.message.slice('invalid-path-parameter:'.length);\n throw new CommerceError('INPUT_INVALID', `Path parameter \"${field}\" is not a valid value`, {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: { field },\n });\n }\n // Mirrors validateBackendRequestShape()'s own copy\n // — the pipeline calls that one first, so this branch is defence in\n // depth for a caller that bypasses it, not the normal path.\n if (error instanceof Error && error.message.startsWith('missing-path-parameter:')) {\n const field = error.message.slice('missing-path-parameter:'.length);\n throw new CommerceError('INPUT_INVALID', `Path parameter \"${field}\" was not supplied`, {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: { field },\n });\n }\n throw new CommerceError('BACKEND_ERROR', 'Backend URL could not be constructed from input', {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: { reason: describeConstructionError(error) },\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 if (handler.method === 'GET' || handler.method === 'DELETE') {\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, remaining, {\n requestId: request.requestId,\n resourceId: request.resourceId,\n });\n for (const [key, value] of Object.entries(remaining)) {\n target.searchParams.set(key, stringifyPrimitive(value));\n }\n } else {\n body = JSON.stringify(remaining);\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: { readonly requestId: string; readonly resourceId: string },\n): void {\n const inputRecord = isPlainObject(input) ? input : {};\n\n let templated: { url: string; remaining: Record<string, unknown> };\n try {\n templated = applyPathTemplate(handler.url, inputRecord);\n } catch (error) {\n if (error instanceof Error && error.message.startsWith('invalid-path-parameter:')) {\n const field = error.message.slice('invalid-path-parameter:'.length);\n throw new CommerceError('INPUT_INVALID', `Path parameter \"${field}\" is not a valid value`, {\n requestId: context.requestId,\n resourceId: context.resourceId,\n details: { field },\n });\n }\n if (error instanceof Error && error.message.startsWith('missing-path-parameter:')) {\n // Returning here is tempting: a missing path parameter is a\n // config/schema mismatch, not caller input, and so arguably not this\n // function's job. But that lets a paid, `{param}`-templated resource\n // whose schema can never supply it reach settle() on every call — the buyer pays, the backend is never\n // called, and there is no refund. The request genuinely cannot be\n // served, so it throws here, before payment, the same as an invalid\n // value does two lines up. `normaliseResource` (src/config) is\n // the root-cause fix — it rejects this shape at config load — but a\n // hand-built `CommerceResource` or a future adapter must not be able\n // to reintroduce the money bug just by skipping config validation.\n const field = error.message.slice('missing-path-parameter:'.length);\n throw new CommerceError('INPUT_INVALID', `Path parameter \"${field}\" was not supplied`, {\n requestId: context.requestId,\n resourceId: context.resourceId,\n details: { field },\n });\n }\n return;\n }\n\n if (handler.method === 'GET' || handler.method === 'DELETE') {\n let target: URL;\n try {\n target = new URL(templated.url);\n } catch {\n return; // call() surfaces the real BACKEND_ERROR for an unparseable URL.\n }\n checkQueryCollision(target, templated.remaining, context);\n }\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): { 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 throw new Error(`missing-path-parameter:${missing}`);\n }\n if (invalid !== undefined) {\n throw new Error(`invalid-path-parameter:${invalid}`);\n }\n return { url, remaining };\n}\n\nfunction describeConstructionError(error: unknown): string {\n if (error instanceof Error && error.message.startsWith('missing-path-parameter:')) {\n return error.message;\n }\n return 'invalid-url';\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 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`). An MCP\n * mount that equals one of these makes Fastify's `.all()` a duplicate of the\n * registered route; one that is a path-prefix of them swallows their 404s\n * through the mount's `${mountPath}/*` wildcard.\n */\nconst RESERVED_GATEWAY_PATHS = [\n '/health',\n '/ready',\n '/.well-known/agent-commerce',\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 McpMountPathSchema = 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: McpMountPathSchema,\n })\n .strict(),\n })\n .strict();\n\nconst BackendMethodSchema = z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']);\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 })\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 };\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 = new Set(['http', 'mcp']);\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 };\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}\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.`,\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('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 validatePathParametersDeclared(id, entry.backend.url, entry.input);\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 },\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 * 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): 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 its input schema — 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 its input schema but not listed in \"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 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\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 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 handler = 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 adapter.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 instance.all(mountPath, handler);\n instance.all(wildcard, handler);\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"]}
|