@celo/buy-gateway 0.5.2 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -1,34 +1,27 @@
1
1
  /**
2
2
  * The gateway: one HTTP server that turns a PaywallConfig into a working x402
3
- * paywall.
4
- *
5
- * The request flow is the one the four `examples/*.mjs` demo servers all
6
- * hand-wrote — match route → 402 challenge → verify → optional Self gate →
7
- * settle → serve — plus the hardening those servers accumulated the hard way
8
- * and which a generic replacement must not silently drop:
9
- *
10
- * - an `unhandledRejection` backstop, because a throw inside an async
11
- * handler is an unhandled rejection and Node exits on those by default:
12
- * one malformed request could take down the whole gateway;
13
- * - a PER-REQUEST boundary too, since the process-level handler cannot see
14
- * `res` and would otherwise trade a crash for a hung client and a leaked
15
- * socket — slow exhaustion instead of a fast death;
16
- * - request/header timeouts, so a trickled body cannot hold a handler slot
17
- * for Node's 300s default;
18
- * - a body cap, since an unbounded upload is free memory for an anonymous
19
- * caller;
20
- * - `releaseNonce` on every rejection BEFORE settlement, so a refused payer
21
- * is not locked out of their own signed authorization for the claim's TTL
22
- * and their corrected retry does not read as a replay.
3
+ * paywall with multi-service routing, scoped rate limiting, and request restrictions.
23
4
  */
24
5
  import { randomBytes } from 'node:crypto';
25
6
  import http from 'node:http';
7
+ import net from 'node:net';
26
8
  import { chainFor, tokenByAddress, tokenBySymbol } from '@celo/buy-core';
27
9
  import { settleX402Payment, verifyOfferedPayment, verifySelfAttestation, } from '@celo/buy-facilitator';
28
- import { DECIMALS, PROTECTED_HEADERS, matchEndpoint, } from './config.js';
10
+ import { DECIMALS, FORWARDABLE_METHODS, PROTECTED_HEADERS, isHeaderValue, matchEndpoint, } from './config.js';
11
+ import { RateLimiter } from './rate-limit.js';
29
12
  import { createUsageRecorder } from './usage.js';
30
- /** Anonymous callers can reach the body reader, so it must be bounded. */
31
- const MAX_BODY_BYTES = 64 * 1024;
13
+ /** Anonymous callers can reach the body reader, so default cap is 64KB. */
14
+ const DEFAULT_MAX_BODY_BYTES = 64 * 1024;
15
+ /** A credential provider that never settles must not hold a request open. */
16
+ function withDeadline(promise, ms, what) {
17
+ let timer;
18
+ return Promise.race([
19
+ promise,
20
+ new Promise((_, reject) => {
21
+ timer = setTimeout(() => reject(new Error(`provider for $${what} timed out after ${ms}ms`)), ms);
22
+ }),
23
+ ]).finally(() => clearTimeout(timer));
24
+ }
32
25
  function json(res, status, body) {
33
26
  res.writeHead(status, { 'Content-Type': 'application/json' });
34
27
  res.end(JSON.stringify(body));
@@ -39,12 +32,119 @@ function decodeHeader(raw) {
39
32
  function encodeHeader(value) {
40
33
  return Buffer.from(JSON.stringify(value)).toString('base64');
41
34
  }
35
+ /** Upstream statuses that mean "go elsewhere", which the gateway will not. */
36
+ const REDIRECTS = new Set([301, 302, 303, 307, 308]);
37
+ /**
38
+ * Codings undici decodes transparently, leaving the header in place while the
39
+ * body arrives plain. The gateway must drop content-encoding for exactly these,
40
+ * or the client double-decodes. Which codings undici decodes has grown across
41
+ * versions — gzip/deflate/br have always been decoded, zstd arrived later — so
42
+ * the set is not hard-coded: it is probed once, at first use, against the
43
+ * undici actually running, and cached. A fixed list was wrong on Node 24, whose
44
+ * newer undici decodes zstd, while Node 20's does not.
45
+ */
46
+ const ALWAYS_DECODED = ['gzip', 'x-gzip', 'deflate', 'br'];
47
+ let decodedCodingsCache;
48
+ export function codingsUndiciDecodes() {
49
+ decodedCodingsCache ??= (async () => {
50
+ const set = new Set(ALWAYS_DECODED);
51
+ // zstd is the one that varies. Serve a real zstd frame to ourselves and
52
+ // see whether fetch hands it back decoded; if so, its header must be
53
+ // stripped like the others.
54
+ try {
55
+ const { zstdCompressSync } = await import('node:zlib');
56
+ if (typeof zstdCompressSync !== 'function')
57
+ return set;
58
+ const frame = zstdCompressSync(Buffer.from('probe'));
59
+ const probe = http.createServer((_q, r) => {
60
+ r.writeHead(200, { 'content-encoding': 'zstd' });
61
+ r.end(frame);
62
+ });
63
+ await new Promise((resolve) => probe.listen(0, '127.0.0.1', resolve));
64
+ const { port } = probe.address();
65
+ try {
66
+ const res = await fetch(`http://127.0.0.1:${port}/`);
67
+ const body = Buffer.from(await res.arrayBuffer());
68
+ if (body.toString() === 'probe')
69
+ set.add('zstd');
70
+ }
71
+ finally {
72
+ probe.close();
73
+ }
74
+ }
75
+ catch {
76
+ // Probe failed (no zstd in zlib, a sandbox with no loopback): keep the
77
+ // conservative set. A zstd upstream on such a runtime is rare, and
78
+ // keeping its header is the safer of the two wrong answers.
79
+ }
80
+ return set;
81
+ })();
82
+ return decodedCodingsCache;
83
+ }
42
84
  /** Absolute URL of the resource being requested, for the 402 envelope. */
43
85
  function resourceUrl(req, pathname) {
44
86
  const proto = req.headers['x-forwarded-proto'] ?? 'http';
45
87
  const host = req.headers['x-forwarded-host'] ?? req.headers.host ?? 'localhost';
46
88
  return `${proto}://${host}${pathname}`;
47
89
  }
90
+ /**
91
+ * The address every IP-scoped limit keys on.
92
+ *
93
+ * With `trustProxy` the proxy in front of us APPENDS the peer it saw to
94
+ * X-Forwarded-For, so the entry it vouches for is the LAST one; everything to
95
+ * the left is whatever the client chose to send. Reading the first entry — the
96
+ * obvious choice — hands the caller their own bucket key: vary it to evade the
97
+ * limit, or send a victim's address to exhaust theirs. The value is also
98
+ * required to parse as an IP, so a 4 KB header cannot become a 4 KB map key.
99
+ *
100
+ * Without `trustProxy` the header is ignored entirely. Behind a proxy that
101
+ * means every caller shares the proxy's address; set `trustProxy: true` there.
102
+ */
103
+ function clientIp(req, trustProxy = false) {
104
+ if (trustProxy) {
105
+ const forwarded = req.headers['x-forwarded-for'];
106
+ if (typeof forwarded === 'string') {
107
+ const last = forwarded.split(',').pop()?.trim();
108
+ // net.isIP accepts an IPv6 zone suffix (`fe80::1%…`) of any length,
109
+ // which would reopen the unbounded-key hole the isIP check closes.
110
+ if (last && !last.includes('%') && net.isIP(last))
111
+ return last;
112
+ }
113
+ }
114
+ return req.socket.remoteAddress ?? 'unknown';
115
+ }
116
+ /**
117
+ * Where a proxied request goes, resolved BEFORE any payment is verified so a
118
+ * request that would escape the upstream is refused while it is still free.
119
+ *
120
+ * The prefix-stripped remainder is attacker-influenced. Handing it to
121
+ * `new URL()` as a reference — the natural thing — lets it re-parse the whole
122
+ * target: `http://evil.test/x` ignores the base entirely, `//evil.test/x` is
123
+ * protocol-relative and swaps the host, and a bare `/x` is root-relative and
124
+ * discards the upstream's own path. Each of those went out with the service's
125
+ * injected credentials attached. Assigning it to `pathname` percent-encodes
126
+ * rather than reparses, so a scheme or host inside it can only ever be path
127
+ * text; the origin and base-path checks after are tripwires that should now
128
+ * be unreachable, kept because "should" is not a security boundary.
129
+ */
130
+ export function upstreamTarget(service, endpoint, pathname, search) {
131
+ if (service.mode !== 'proxy')
132
+ return undefined;
133
+ let rest = pathname;
134
+ if (endpoint.stripPrefix && rest.startsWith(endpoint.stripPrefix)) {
135
+ rest = rest.slice(endpoint.stripPrefix.length);
136
+ }
137
+ const base = new URL(service.upstream);
138
+ const basePath = base.pathname.replace(/\/$/, '');
139
+ const target = new URL(base);
140
+ target.pathname = `${basePath}/${rest.replace(/^\/+/, '')}`;
141
+ target.search = search;
142
+ if (target.origin !== base.origin)
143
+ return undefined;
144
+ if (target.pathname !== basePath && !target.pathname.startsWith(`${basePath}/`))
145
+ return undefined;
146
+ return target;
147
+ }
48
148
  /** The tokens a priced endpoint is offered in: `config.tokens`, else its price currency. */
49
149
  function offeredTokens(config, endpoint) {
50
150
  return config.tokens ?? [endpoint.currency];
@@ -88,41 +188,28 @@ export function requirementsFor(config, endpoint, resource, symbol = endpoint.cu
88
188
  payTo: config.payTo,
89
189
  maxTimeoutSeconds: 60,
90
190
  asset: token.address,
91
- // The EIP-712 domain comes from the TOKEN, and the two differ between
92
- // networks — USDC is "USD Coin" on mainnet but "USDC" on sepolia. Getting
93
- // this wrong produces a signature the token rejects at settlement.
94
- extra: { name: token.eip712Name, version: token.eip712Version },
191
+ extra: {
192
+ name: token.eip712Name,
193
+ version: token.eip712Version,
194
+ },
95
195
  };
96
196
  if (endpoint.self) {
97
197
  requirements.extra = {
98
198
  ...requirements.extra,
99
199
  selfRequirements: {
100
200
  scope: endpoint.self.scope,
101
- ...(endpoint.self.endpoint ? { endpoint: endpoint.self.endpoint } : {}),
102
- ...(endpoint.self.endpointType ? { endpointType: endpoint.self.endpointType } : {}),
103
201
  disclosures: {
104
- ...(endpoint.self.minimumAge !== undefined
105
- ? { minimumAge: endpoint.self.minimumAge }
106
- : {}),
107
- ...(endpoint.self.ofac !== undefined ? { ofac: endpoint.self.ofac } : {}),
108
- ...(endpoint.self.excludedCountries
109
- ? { excludedCountries: endpoint.self.excludedCountries }
110
- : {}),
202
+ minimumAge: endpoint.self.minimumAge,
203
+ ofac: endpoint.self.ofac,
204
+ excludedCountries: endpoint.self.excludedCountries,
111
205
  },
206
+ endpoint: endpoint.self.endpoint,
207
+ endpointType: endpoint.self.endpointType,
112
208
  },
113
209
  };
114
210
  }
115
211
  return requirements;
116
212
  }
117
- /**
118
- * Refuse a config whose currencies cannot actually settle, at BOOT.
119
- *
120
- * Without this the failure surfaces on the first real payment: the payer signs
121
- * an authorization the token can never honour, and the operator learns their
122
- * paywall is broken from a customer. `tokenBySymbol` returns undefined for a
123
- * symbol that does not exist on the network (there is no USDT on sepolia), and
124
- * a token without EIP-712 domain metadata does not implement EIP-3009.
125
- */
126
213
  export function validateTokens(config) {
127
214
  for (const endpoint of config.endpoints) {
128
215
  if (endpoint.free)
@@ -138,14 +225,28 @@ export function validateTokens(config) {
138
225
  }
139
226
  }
140
227
  }
141
- /** Read a bounded request body, answering 413 and returning undefined if oversized. */
142
- async function readBody(req, res) {
228
+ /**
229
+ * Resolve which service configuration handles this endpoint.
230
+ */
231
+ function resolveService(config, endpoint) {
232
+ // hasOwn, not a truthy lookup: `service: toString` resolves through the
233
+ // prototype to a function, boots cleanly, and 500s on the first paid request.
234
+ if (endpoint.service && config.services && Object.hasOwn(config.services, endpoint.service)) {
235
+ return config.services[endpoint.service];
236
+ }
237
+ if (config.routing) {
238
+ return config.routing;
239
+ }
240
+ throw new Error(`Endpoint "${endpoint.path}" cannot be resolved to any service routing configuration`);
241
+ }
242
+ /** Read the request body up to a configured byte limit. */
243
+ async function readBody(req, res, maxBytes) {
143
244
  const chunks = [];
144
245
  let size = 0;
145
246
  for await (const chunk of req) {
146
247
  size += chunk.length;
147
- if (size > MAX_BODY_BYTES) {
148
- json(res, 413, { error: `request body too large (max ${MAX_BODY_BYTES} bytes)` });
248
+ if (size > maxBytes) {
249
+ json(res, 413, { error: `request body too large (max ${maxBytes} bytes)` });
149
250
  req.destroy();
150
251
  return undefined;
151
252
  }
@@ -153,42 +254,225 @@ async function readBody(req, res) {
153
254
  }
154
255
  return Buffer.concat(chunks);
155
256
  }
257
+ /**
258
+ * Resolve the `reverify` option to a concrete mode, and refuse the one
259
+ * combination that would let a mock identity satisfy a real-money gate:
260
+ * mock-ONLY passports on `celo` mainnet. `true` means real passports (the
261
+ * production default); `'either'` accepts both, which is allowed on mainnet
262
+ * because it still admits real ones. Undefined means re-verification is off.
263
+ */
264
+ export function resolveReverify(reverify, network) {
265
+ if (!reverify)
266
+ return undefined;
267
+ const mode = reverify === true ? { mockPassport: false } : reverify;
268
+ if (mode.mockPassport === true && network === 'celo') {
269
+ throw new Error('reverify is set to mock-only passports on celo mainnet: a mock identity would satisfy a real-money KYC gate. Use real passports (the default), "either" to accept both, or run on a testnet.');
270
+ }
271
+ return mode;
272
+ }
273
+ /**
274
+ * Real-passport re-verification is only actually ENFORCED when every Self
275
+ * endpoint pins a production `endpointType`. The Self hub a proof verifies
276
+ * against is taken from the attestation (a proof only validates against the hub
277
+ * that minted it), so `verifySelfAttestation` relies on the `endpoint_mismatch`
278
+ * check to reject a staging (mock) proof — and that check can only fire when
279
+ * the requirements pin a non-staging `endpointType`. Without a pin, a mock
280
+ * identity would satisfy a gate configured for real passports. Refuse at boot
281
+ * rather than advertise a guarantee the config cannot keep (celo-org/cpay#43).
282
+ */
283
+ export function assertReverifyEnforceable(mode, config) {
284
+ if (mode?.mockPassport !== false)
285
+ return; // only real-only needs a pinned hub
286
+ for (const ep of config.endpoints) {
287
+ if (!ep.self)
288
+ continue;
289
+ const et = ep.self.endpointType;
290
+ if (et === undefined || et.startsWith('staging_')) {
291
+ throw new Error(`reverify requires real passports, but the self endpoint "${ep.path}" ${et === undefined
292
+ ? 'does not pin an endpointType'
293
+ : `pins the staging endpointType "${et}"`}: the Self hub is taken from the attestation, so without a pinned production endpointType (https or celo) a mock proof would still be accepted. Pin "endpointType: https", or set BUY_SELF_MOCK_PASSPORT=both to accept mock passports too.`);
294
+ }
295
+ }
296
+ }
156
297
  export function createGateway(opts) {
157
298
  const { config, sponsor, events } = opts;
158
- const log = opts.log ?? (() => { });
299
+ // Resolved once, at construction, so an invalid network/passport-mode combo
300
+ // fails the boot rather than the first KYC request.
301
+ const reverify = resolveReverify(opts.reverify, config.network);
302
+ assertReverifyEnforceable(reverify, config);
303
+ // A log sink that throws is the operator's problem, never the payer's: it
304
+ // must not turn a settled request into a bare 500, or a settled-and-served
305
+ // one into anything else. Swallowed here, once, for every call site.
306
+ const log = (line) => {
307
+ try {
308
+ opts.log?.(line);
309
+ }
310
+ catch {
311
+ // nothing to do with it that would not be the same problem again
312
+ }
313
+ };
159
314
  const chain = chainFor(config.network);
160
315
  const usage = createUsageRecorder();
161
- const handle = async (req, res) => {
162
- const parsed = new URL(req.url ?? '/', 'http://placeholder');
163
- const pathname = parsed.pathname;
164
- if (pathname === '/healthz') {
165
- res.writeHead(200, { 'Content-Type': 'text/plain' });
166
- res.end('ok');
167
- return;
316
+ // Instantiate Rate Limiters
317
+ const globalLimiter = config.rateLimit ? new RateLimiter(config.rateLimit) : undefined;
318
+ const serviceLimiters = new Map();
319
+ if (config.services) {
320
+ for (const [name, svc] of Object.entries(config.services)) {
321
+ if (svc.rateLimit)
322
+ serviceLimiters.set(name, new RateLimiter(svc.rateLimit));
168
323
  }
169
- if (pathname === '/__buy/usage') {
170
- json(res, 200, usage.snapshot());
171
- return;
324
+ }
325
+ // The legacy `routing` block is a service too, so its limit is honoured the
326
+ // same way; previously it parsed cleanly and was never consulted.
327
+ const routingLimiter = config.routing?.rateLimit
328
+ ? new RateLimiter(config.routing.rateLimit)
329
+ : undefined;
330
+ const endpointLimiters = new Map();
331
+ for (const ep of config.endpoints) {
332
+ if (ep.rateLimit)
333
+ endpointLimiters.set(ep.path, new RateLimiter(ep.rateLimit));
334
+ }
335
+ const handle = async (req, res) => {
336
+ const ip = clientIp(req, config.trustProxy);
337
+ // 1. Global unauthenticated rate limit (runs on all incoming requests)
338
+ if (globalLimiter) {
339
+ const check = globalLimiter.consume(ip);
340
+ if (!check.allowed) {
341
+ usage.recordRejection('*', 'rate_limited');
342
+ res.setHeader('Retry-After', String(check.retryAfterSeconds ?? 1));
343
+ json(res, 429, { error: 'rate_limited: too many requests' });
344
+ return;
345
+ }
172
346
  }
173
- // THE ALLOWLIST. A path with no matching endpoint is not merely unpriced —
174
- // it does not exist as far as this gateway is concerned, and in proxy mode
175
- // it is never forwarded. That is what stops a paywall from accidentally
176
- // exposing everything behind it.
347
+ const url = new URL(req.url ?? '/', 'http://placeholder');
348
+ const pathname = url.pathname;
177
349
  const endpoint = matchEndpoint(config, pathname);
178
350
  if (!endpoint) {
179
351
  json(res, 404, { error: 'not_found' });
180
352
  return;
181
353
  }
182
- const body = await readBody(req, res);
354
+ // 2. HTTP Method Restrictions
355
+ // Decided before the 402, like a path that would escape the upstream:
356
+ // Node's parser delivers TRACE and undici refuses to send it, so without
357
+ // this a paid TRACE was settled and then failed at fetch().
358
+ const method = (req.method ?? 'GET').toUpperCase();
359
+ const allowed = endpoint.restrictions?.methods ?? FORWARDABLE_METHODS;
360
+ if (!allowed.includes(method)) {
361
+ res.setHeader('Allow', allowed.join(', '));
362
+ json(res, 405, {
363
+ error: `method_not_allowed: method ${method} is not permitted for this endpoint`,
364
+ });
365
+ return;
366
+ }
367
+ // 3. Endpoint IP / Service Rate Limiting (pre-payment)
368
+ const epLimiter = endpointLimiters.get(endpoint.path);
369
+ if (epLimiter && epLimiter.scope === 'ip') {
370
+ const check = epLimiter.consume(ip);
371
+ if (!check.allowed) {
372
+ usage.recordRejection(endpoint.path, 'rate_limited');
373
+ res.setHeader('Retry-After', String(check.retryAfterSeconds ?? 1));
374
+ json(res, 429, { error: 'rate_limited: endpoint limit exceeded' });
375
+ return;
376
+ }
377
+ }
378
+ const serviceName = endpoint.service;
379
+ const serviceLimiter = serviceName ? serviceLimiters.get(serviceName) : routingLimiter;
380
+ if (serviceLimiter && serviceLimiter.scope === 'ip') {
381
+ const check = serviceLimiter.consume(ip);
382
+ if (!check.allowed) {
383
+ usage.recordRejection(endpoint.path, 'rate_limited');
384
+ res.setHeader('Retry-After', String(check.retryAfterSeconds ?? 1));
385
+ json(res, 429, { error: 'rate_limited: service limit exceeded' });
386
+ return;
387
+ }
388
+ }
389
+ // A `service` bucket protects the UPSTREAM's quota, so it is spent only by
390
+ // a request that will reach the upstream: a free one at the point of
391
+ // serving, a paid one after verification and before settlement. The unpaid
392
+ // 402 probe never reaches the upstream, and spending on it let anyone
393
+ // exhaust the bucket for every paying customer without paying for one.
394
+ // Header -> value for everything THIS service injects. A static source
395
+ // (env or resolvedHeaders) wins; a provider is asked only when nothing
396
+ // static names the variable, and its throw is caught by the callers below
397
+ // BEFORE settlement, so a credential that cannot be minted costs nothing.
398
+ const injectedFor = async (service) => {
399
+ const out = {};
400
+ if (service.mode !== 'proxy')
401
+ return out;
402
+ for (const [header, envVar] of Object.entries(service.injectHeaders)) {
403
+ // Empty is absent, not a value.
404
+ const fixed = process.env[envVar] || opts.resolvedHeaders?.[envVar];
405
+ const provider = opts.headerProviders?.[envVar];
406
+ if (fixed) {
407
+ out[header] = fixed;
408
+ }
409
+ else if (provider) {
410
+ const value = await withDeadline(provider(), opts.providerTimeoutMs ?? 10_000, envVar);
411
+ if (!value)
412
+ throw new Error(`provider for $${envVar} returned no credential`);
413
+ // Same guard resolveInjectedHeaders applies to a static value: a
414
+ // CR/LF in a minted token would pass the nonempty check, reach
415
+ // Headers.set() after settlement, and throw there — charged, 502.
416
+ if (!isHeaderValue(value)) {
417
+ throw new Error(`provider for $${envVar} returned an invalid header value`);
418
+ }
419
+ out[header] = value;
420
+ }
421
+ }
422
+ return out;
423
+ };
424
+ const credentialUnavailable = async (endpointPath, err, release, correlationId = randomBytes(6).toString('hex')) => {
425
+ if (release)
426
+ await release();
427
+ usage.recordRejection(endpointPath, 'upstream_credential_unavailable');
428
+ log(`credential provider failed cid=${correlationId}: ${err instanceof Error ? err.message : String(err)}`);
429
+ json(res, 503, {
430
+ error: `upstream_credential_unavailable: could not obtain the upstream credential (correlation id: ${correlationId})`,
431
+ });
432
+ };
433
+ const consumeServiceBucket = () => serviceLimiter && serviceLimiter.scope === 'service'
434
+ ? serviceLimiter.consume(serviceName ?? 'routing')
435
+ : { allowed: true };
436
+ const serviceLimited = (check) => {
437
+ usage.recordRejection(endpoint.path, 'rate_limited');
438
+ res.setHeader('Retry-After', String(check.retryAfterSeconds ?? 1));
439
+ json(res, 429, { error: 'rate_limited: service limit exceeded' });
440
+ };
441
+ const maxBodyBytes = endpoint.restrictions?.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
442
+ const body = await readBody(req, res, maxBodyBytes);
183
443
  if (body === undefined)
184
- return; // 413 already sent
444
+ return;
445
+ const service = resolveService(config, endpoint);
446
+ // Decided here, before the 402 and long before settlement: a path that
447
+ // would leave the upstream is refused while the request is still free,
448
+ // never after the payer has been charged for it.
449
+ const target = upstreamTarget(service, endpoint, pathname, url.search);
450
+ if (service.mode === 'proxy' && target === undefined) {
451
+ usage.recordRejection(endpoint.path, 'bad_request');
452
+ json(res, 400, { error: 'bad_request: path escapes the configured upstream' });
453
+ return;
454
+ }
455
+ // Free endpoints pass through without payment challenge
185
456
  if (endpoint.free) {
186
- await serve(req, res, pathname, body, null, undefined);
457
+ const check = consumeServiceBucket();
458
+ if (!check.allowed) {
459
+ serviceLimited(check);
460
+ return;
461
+ }
462
+ let injected;
463
+ try {
464
+ injected = await injectedFor(service);
465
+ }
466
+ catch (err) {
467
+ await credentialUnavailable(endpoint.path, err);
468
+ return;
469
+ }
470
+ await serve(req, res, target, service, body, null, undefined, injected);
187
471
  return;
188
472
  }
189
- const cid = randomBytes(6).toString('hex');
190
- const offers = offersFor(config, endpoint, resourceUrl(req, pathname));
191
- const challenge = { x402Version: 1, accepts: offers, error: '' };
473
+ const resource = resourceUrl(req, pathname);
474
+ const offers = offersFor(config, endpoint, resource);
475
+ const challenge = { x402Version: 1, accepts: offers, error: 'payment_required' };
192
476
  const paymentHeader = req.headers['x-payment'];
193
477
  if (!paymentHeader) {
194
478
  json(res, 402, challenge);
@@ -205,9 +489,13 @@ export function createGateway(opts) {
205
489
  });
206
490
  return;
207
491
  }
492
+ const cid = randomBytes(6).toString('hex');
208
493
  // The payer picked one offer and signed for its asset; verification runs
209
- // against that offer alone, and everything after — the Self gate, the
210
- // settlement, the revenue line — refers to it, never to the price currency.
494
+ // against that offer alone, and everything after (the Self gate, the
495
+ // settlement, the revenue line) refers to it, never to the price currency.
496
+ // Local verification always runs: with multi-token offers only it can tell
497
+ // which offer the payer signed, and it owns the nonce. A remote facilitator
498
+ // adds its hosted checks against that selected offer just below.
211
499
  const verified = await verifyOfferedPayment({
212
500
  requirements: offers,
213
501
  // biome-ignore lint/suspicious/noExplicitAny: verified inside; anything may arrive on the wire
@@ -217,24 +505,67 @@ export function createGateway(opts) {
217
505
  });
218
506
  if (!verified.ok) {
219
507
  usage.recordRejection(endpoint.path, verified.reason);
220
- json(res, 402, { ...challenge, error: `verify_payment_failed: ${verified.reason}` });
508
+ const detail = 'detail' in verified && verified.detail ? ` (${verified.detail})` : '';
509
+ json(res, 402, {
510
+ ...challenge,
511
+ error: `verify_payment_failed: ${verified.reason}${detail}`,
512
+ });
221
513
  return;
222
514
  }
223
515
  const { requirements } = verified;
516
+ // A remote facilitator runs its own hosted verification (balance and
517
+ // authorization) against the offer the payer signed, before any money
518
+ // moves. A rejection here hands the nonce back, exactly like a local one.
519
+ if (opts.facilitator) {
520
+ const remote = await opts.facilitator.verify({
521
+ requirements,
522
+ // biome-ignore lint/suspicious/noExplicitAny: already shape-verified above
523
+ payment: payment,
524
+ correlationId: cid,
525
+ ...(events ? { events } : {}),
526
+ });
527
+ if (!remote.ok) {
528
+ await verified.releaseNonce();
529
+ usage.recordRejection(endpoint.path, remote.reason);
530
+ const detail = 'detail' in remote && remote.detail ? ` (${remote.detail})` : '';
531
+ json(res, 402, {
532
+ ...challenge,
533
+ error: `verify_payment_failed: ${remote.reason}${detail}`,
534
+ });
535
+ return;
536
+ }
537
+ }
538
+ // 4. Payer Wallet Scoped Rate Limiting
539
+ if (epLimiter && epLimiter.scope === 'payer') {
540
+ const check = epLimiter.consume(verified.from.toLowerCase());
541
+ if (!check.allowed) {
542
+ await verified.releaseNonce();
543
+ usage.recordRejection(endpoint.path, 'rate_limited');
544
+ res.setHeader('Retry-After', String(check.retryAfterSeconds ?? 1));
545
+ json(res, 429, { error: 'rate_limited: wallet limit exceeded' });
546
+ return;
547
+ }
548
+ }
549
+ if (serviceLimiter && serviceLimiter.scope === 'payer') {
550
+ const check = serviceLimiter.consume(verified.from.toLowerCase());
551
+ if (!check.allowed) {
552
+ await verified.releaseNonce();
553
+ usage.recordRejection(endpoint.path, 'rate_limited');
554
+ res.setHeader('Retry-After', String(check.retryAfterSeconds ?? 1));
555
+ json(res, 429, { error: 'rate_limited: wallet service limit exceeded' });
556
+ return;
557
+ }
558
+ }
224
559
  if (endpoint.self) {
225
560
  const selfHeader = req.headers['x-self-attestation'];
226
561
  const selfResult = await verifySelfAttestation({
227
562
  requirements: requirements.extra?.selfRequirements,
228
563
  attestationHeader: selfHeader ? String(selfHeader) : undefined,
229
564
  expectedAddress: verified.from,
230
- ...(opts.reverify ? { reverify: { mockPassport: true, appName: config.name } } : {}),
565
+ ...(reverify ? { reverify: { ...reverify, appName: config.name } } : {}),
231
566
  ...(events ? { events } : {}),
232
567
  });
233
568
  if (!selfResult.ok) {
234
- // Nothing settled, so hand the nonce back. Without this a KYC refusal
235
- // locks the payer out of their own authorization until the claim's TTL
236
- // expires, and their corrected retry comes back as `nonce_already_seen`
237
- // — a replay error for a payment that never paid.
238
569
  await verified.releaseNonce();
239
570
  usage.recordRejection(endpoint.path, selfResult.reason);
240
571
  json(res, 402, {
@@ -244,8 +575,49 @@ export function createGateway(opts) {
244
575
  return;
245
576
  }
246
577
  }
578
+ // Last check before money moves; a refusal here hands the nonce back.
579
+ const serviceCheck = consumeServiceBucket();
580
+ if (!serviceCheck.allowed) {
581
+ await verified.releaseNonce();
582
+ serviceLimited(serviceCheck);
583
+ return;
584
+ }
585
+ // The upstream credential, resolved before any money moves. A provider that
586
+ // cannot mint one now (metadata server down, key rotated away) must not be
587
+ // discovered after settlement, where the caller has paid for a 401.
588
+ let injected;
589
+ try {
590
+ injected = await injectedFor(service);
591
+ }
592
+ catch (err) {
593
+ await credentialUnavailable(endpoint.path, err, () => verified.releaseNonce(), cid);
594
+ return;
595
+ }
247
596
  let transaction = null;
248
- if (sponsor) {
597
+ if (opts.facilitator) {
598
+ try {
599
+ const settled = await opts.facilitator.settle({
600
+ requirements,
601
+ // biome-ignore lint/suspicious/noExplicitAny: already verified above
602
+ payment: payment,
603
+ correlationId: cid,
604
+ ...(events ? { events } : {}),
605
+ });
606
+ transaction = settled.tx;
607
+ log(`settled (remote) cid=${cid} ${verified.from} → ${config.payTo} tx=${settled.tx}`);
608
+ }
609
+ catch (err) {
610
+ const message = err instanceof Error ? err.message : String(err);
611
+ log(`REMOTE SETTLE FAILED cid=${cid} payer=${verified.from} err=${message}`);
612
+ usage.recordRejection(endpoint.path, 'settle_failed');
613
+ json(res, 402, {
614
+ ...challenge,
615
+ error: `settle_failed: ${message} (correlation id: ${cid})`,
616
+ });
617
+ return;
618
+ }
619
+ }
620
+ else if (sponsor) {
249
621
  try {
250
622
  const settled = await settleX402Payment({
251
623
  requirements,
@@ -256,13 +628,8 @@ export function createGateway(opts) {
256
628
  ...(events ? { events } : {}),
257
629
  });
258
630
  transaction = settled.tx;
259
- log(`settled cid=${cid} ${verified.from} → ${config.payTo} tx=${settled.tx}`);
260
631
  }
261
632
  catch (err) {
262
- // Deliberately NOT releasing the nonce: settle broadcasts before it
263
- // awaits the receipt, so a throw does not mean the transfer failed —
264
- // it may be mined moments later. Releasing would invite a retry of an
265
- // authorization that is already spending.
266
633
  const message = err instanceof Error ? err.message : String(err);
267
634
  log(`SETTLE FAILED cid=${cid} payer=${verified.from} err=${message}`);
268
635
  usage.recordRejection(endpoint.path, 'settle_failed');
@@ -273,11 +640,40 @@ export function createGateway(opts) {
273
640
  return;
274
641
  }
275
642
  }
643
+ // Outside the try on purpose: the money has moved, and a log sink that
644
+ // throws must not be reported as a settlement that failed.
645
+ if (transaction)
646
+ log(`settled cid=${cid} ${verified.from} → ${config.payTo} tx=${transaction}`);
276
647
  usage.recordPayment(endpoint.path, endpoint.amount, tokenByAddress(config.network, requirements.asset)?.symbol ?? endpoint.currency);
277
- await serve(req, res, pathname, body, transaction, verified.from);
648
+ // Everything from here is a settled request. The upstream paths inside
649
+ // serve() carry the receipt on their own errors; this guard is for the
650
+ // rest — a header value the runtime rejects, a response the socket
651
+ // refuses — so that no throw after settlement reaches the bare 500.
652
+ try {
653
+ await serve(req, res, target, service, body, transaction, verified.from, injected);
654
+ }
655
+ catch (err) {
656
+ const message = err instanceof Error ? err.message : String(err);
657
+ log(`serve failed after settlement cid=${cid} tx=${transaction ?? 'none'} err=${message}`);
658
+ if (res.headersSent) {
659
+ res.destroy();
660
+ return;
661
+ }
662
+ const paymentResponse = encodeHeader({
663
+ success: true,
664
+ network: config.network,
665
+ payer: verified.from,
666
+ transaction,
667
+ });
668
+ res.setHeader('X-PAYMENT-RESPONSE', paymentResponse);
669
+ json(res, 502, {
670
+ error: `bad_gateway: could not serve the paid resource (correlation id: ${cid})`,
671
+ ...(transaction ? { transaction } : {}),
672
+ });
673
+ }
278
674
  };
279
- /** Deliver the paid resource: proxy upstream, or answer from config. */
280
- const serve = async (req, res, pathname, body, transaction, payer) => {
675
+ /** Deliver the paid resource: proxy upstream or respond from config. */
676
+ const serve = async (req, res, target, service, body, transaction, payer, injected) => {
281
677
  const paymentResponse = payer === undefined
282
678
  ? undefined
283
679
  : encodeHeader({
@@ -286,28 +682,19 @@ export function createGateway(opts) {
286
682
  payer,
287
683
  transaction,
288
684
  });
289
- if (config.routing.mode === 'respond') {
290
- const headers = { 'Content-Type': config.routing.contentType };
685
+ if (service.mode === 'respond') {
686
+ const headers = { 'Content-Type': service.contentType };
291
687
  if (paymentResponse)
292
688
  headers['X-PAYMENT-RESPONSE'] = paymentResponse;
293
689
  res.writeHead(200, headers);
294
- res.end(config.routing.body);
690
+ res.end(service.body);
295
691
  return;
296
692
  }
297
- const target = new URL(pathname.replace(/^\//, ''), `${config.routing.upstream.replace(/\/$/, '')}/`);
298
- const search = new URL(req.url ?? '/', 'http://placeholder').search;
299
- if (search)
300
- target.search = search;
301
- // A plain object keyed by header name is the wrong shape here: HTTP header
302
- // names are case-insensitive, so a caller's `authorization` and a
303
- // configured `Authorization` are two keys in an object but one header on
304
- // the wire — and merging them concatenated the caller's value with the
305
- // trusted one ("Bearer caller, Bearer trusted"). `Headers` folds case for
306
- // us, so `set()` genuinely replaces whatever the caller sent.
693
+ // `upstreamTarget` returned undefined only for a non-proxy service, and
694
+ // that branch returned above; the handler refused escapes before charging.
695
+ if (target === undefined)
696
+ throw new Error('proxy service without a resolved target');
307
697
  const forwarded = new Headers();
308
- // `Connection` names further headers as hop-by-hop. Honouring that list is
309
- // not politeness: it is how a caller says "this header ends at the proxy",
310
- // and ignoring it forwards per-connection state to a different connection.
311
698
  const hopByHop = new Set();
312
699
  const connection = req.headers.connection;
313
700
  if (typeof connection === 'string') {
@@ -319,12 +706,13 @@ export function createGateway(opts) {
319
706
  }
320
707
  for (const [key, value] of Object.entries(req.headers)) {
321
708
  const lower = key.toLowerCase();
322
- // Framing headers stop here because we re-frame the request ourselves;
323
- // the payment headers stop here because the upstream neither needs the
324
- // payment proof nor should be able to see the caller's attestation.
325
709
  if (PROTECTED_HEADERS.has(lower) ||
326
710
  lower === 'x-payment' ||
327
711
  lower === 'x-self-attestation' ||
712
+ // undici decodes what IT negotiates; forwarding the caller's list
713
+ // (zstd, say) would fetch a coding it cannot decode. A coding that
714
+ // arrives anyway keeps its header on the way back — see the relay.
715
+ lower === 'accept-encoding' ||
328
716
  hopByHop.has(lower)) {
329
717
  continue;
330
718
  }
@@ -334,51 +722,127 @@ export function createGateway(opts) {
334
722
  for (const v of value)
335
723
  forwarded.append(key, v);
336
724
  }
337
- // Last, and with `set`: a configured credential must win over anything the
338
- // caller sent under any spelling of the same name.
339
- for (const [key, value] of Object.entries(opts.resolvedHeaders ?? {})) {
340
- forwarded.set(key, value);
341
- }
342
- const upstreamRes = await fetch(target, {
343
- method: req.method ?? 'GET',
344
- headers: forwarded,
345
- // Buffer -> Uint8Array: a Node Buffer is not a DOM BodyInit, and passing
346
- // one relies on undici's tolerance rather than the typed contract.
347
- ...(body.length > 0 && req.method !== 'GET' && req.method !== 'HEAD'
348
- ? { body: new Uint8Array(body) }
349
- : {}),
350
- });
725
+ // Injected credentials configured for THIS service, resolved from the
726
+ // environment variable each one names. Last, and with `set`: a configured
727
+ // credential must win over anything the caller sent under any spelling of
728
+ // the same name (issue #41).
729
+ for (const [header, value] of Object.entries(injected))
730
+ forwarded.set(header, value);
731
+ const controller = new AbortController();
732
+ const timeoutMs = service.timeoutMs ?? 30_000;
733
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
734
+ let upstreamRes;
735
+ try {
736
+ upstreamRes = await fetch(target, {
737
+ method: req.method ?? 'GET',
738
+ headers: forwarded,
739
+ signal: controller.signal,
740
+ // `upstreamTarget` keeps the FIRST request on the configured origin;
741
+ // following a redirect would let the upstream send the injected
742
+ // credentials anywhere it names and pass that origin's body off as
743
+ // the paid resource. A 3xx is handled below as an upstream error.
744
+ redirect: 'manual',
745
+ ...(body.length > 0 && req.method !== 'GET' && req.method !== 'HEAD'
746
+ ? { body: new Uint8Array(body) }
747
+ : {}),
748
+ });
749
+ }
750
+ catch (err) {
751
+ clearTimeout(timer);
752
+ const isTimeout = controller.signal.aborted;
753
+ // Settlement already happened. The payer is out the money whether or not
754
+ // the upstream answered, so they get the receipt either way — without the
755
+ // transaction hash there is nothing to dispute or reconcile with.
756
+ if (paymentResponse)
757
+ res.setHeader('X-PAYMENT-RESPONSE', paymentResponse);
758
+ if (transaction) {
759
+ log(`upstream ${isTimeout ? 'timed out' : 'unreachable'} after settlement tx=${transaction}`);
760
+ }
761
+ json(res, isTimeout ? 504 : 502, {
762
+ error: isTimeout
763
+ ? 'gateway_timeout: upstream timed out'
764
+ : 'bad_gateway: upstream unreachable',
765
+ ...(transaction ? { transaction } : {}),
766
+ });
767
+ return;
768
+ }
769
+ // NOT cleared here: fetch() resolves when the HEADERS arrive, and the
770
+ // deadline has to cover the body too — an upstream that answers and then
771
+ // stalls is the same money situation as one that never answers.
772
+ // Never seen by the payer as a resource: it is the upstream declining to
773
+ // answer here, and the money has moved. Same shape as unreachable. Only
774
+ // the statuses that carry a Location — a 304 is the upstream honouring
775
+ // the caller's own conditional header, and is relayed like any answer.
776
+ if (REDIRECTS.has(upstreamRes.status)) {
777
+ clearTimeout(timer);
778
+ // Let go of the body (and the connection) we are not going to read.
779
+ controller.abort();
780
+ if (paymentResponse)
781
+ res.setHeader('X-PAYMENT-RESPONSE', paymentResponse);
782
+ if (transaction)
783
+ log(`upstream redirected after settlement tx=${transaction}`);
784
+ json(res, 502, {
785
+ error: `bad_gateway: upstream answered a redirect (${upstreamRes.status}), which is not followed`,
786
+ ...(transaction ? { transaction } : {}),
787
+ });
788
+ return;
789
+ }
790
+ const decodedByFetch = await codingsUndiciDecodes();
351
791
  const outHeaders = {};
352
792
  upstreamRes.headers.forEach((value, key) => {
353
793
  const lower = key.toLowerCase();
354
- // Drop the upstream's framing and encoding headers. `fetch` has already
355
- // decoded the body and we re-frame it with our own content-length below,
356
- // so forwarding these describes a body that no longer exists: a
357
- // `transfer-encoding: chunked` alongside our content-length is illegal
358
- // per RFC 9112, and undici rejects the response outright with
359
- // "Content-Length can't be present with Transfer-Encoding" — the client
360
- // sees a failed fetch even though the payment settled.
361
- if (lower === 'content-encoding' ||
362
- lower === 'transfer-encoding' ||
363
- lower === 'content-length') {
794
+ if (lower === 'transfer-encoding' || lower === 'content-length')
795
+ return;
796
+ if (lower === 'content-encoding' && decodedByFetch.has(value.trim().toLowerCase()))
364
797
  return;
365
- }
366
- // Hop-by-hop headers are per-connection and must not be relayed.
367
798
  if (lower === 'connection' || lower === 'keep-alive')
368
799
  return;
800
+ // Only the gateway speaks for payment. Relayed, an upstream's copy would
801
+ // be written beside the real receipt and corrupt it — or, on a free
802
+ // route, forge one.
803
+ if (lower === 'x-payment-response')
804
+ return;
805
+ // forEach yields each Set-Cookie separately under the same key; only
806
+ // the last would survive a plain assignment.
807
+ if (lower === 'set-cookie')
808
+ return;
369
809
  outHeaders[key] = value;
370
810
  });
811
+ const cookies = upstreamRes.headers.getSetCookie();
812
+ if (cookies.length > 0)
813
+ outHeaders['set-cookie'] = cookies;
371
814
  if (paymentResponse)
372
815
  outHeaders['X-PAYMENT-RESPONSE'] = paymentResponse;
373
- const buf = Buffer.from(await upstreamRes.arrayBuffer());
816
+ // The upstream can fail AFTER sending headers — a reset mid-body — and
817
+ // that is the same money situation as never answering: settled, unserved.
818
+ // Reading the body inside the same protection keeps the receipt on it.
819
+ let buf;
820
+ try {
821
+ buf = Buffer.from(await upstreamRes.arrayBuffer());
822
+ }
823
+ catch {
824
+ const isTimeout = controller.signal.aborted;
825
+ if (paymentResponse)
826
+ res.setHeader('X-PAYMENT-RESPONSE', paymentResponse);
827
+ if (transaction) {
828
+ log(`upstream body ${isTimeout ? 'timed out' : 'failed'} after settlement tx=${transaction}`);
829
+ }
830
+ json(res, isTimeout ? 504 : 502, {
831
+ error: isTimeout
832
+ ? 'gateway_timeout: upstream timed out'
833
+ : 'bad_gateway: upstream body failed',
834
+ ...(transaction ? { transaction } : {}),
835
+ });
836
+ return;
837
+ }
838
+ finally {
839
+ clearTimeout(timer);
840
+ }
374
841
  outHeaders['content-length'] = String(buf.length);
375
842
  res.writeHead(upstreamRes.status, outHeaders);
376
843
  res.end(buf);
377
844
  };
378
845
  const server = http.createServer((req, res) => {
379
- // Per-request boundary: answer this request rather than letting the throw
380
- // reach the process handler, which cannot see `res` and would leave the
381
- // client hanging on a socket that is never released.
382
846
  handle(req, res).catch((err) => {
383
847
  log(`request failed: ${err instanceof Error ? err.message : String(err)}`);
384
848
  if (res.headersSent) {
@@ -388,9 +852,8 @@ export function createGateway(opts) {
388
852
  json(res, 500, { error: 'internal_error' });
389
853
  });
390
854
  });
391
- // A trickled body would otherwise hold a handler slot for Node's 300s default.
392
855
  server.requestTimeout = 30_000;
393
856
  server.headersTimeout = 20_000;
394
- return { server, usage: () => usage.snapshot() };
857
+ return { server, handler: handle, usage: () => usage.snapshot() };
395
858
  }
396
859
  //# sourceMappingURL=server.js.map