@celo/buy-gateway 0.5.2 → 0.6.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
  }
@@ -155,40 +256,179 @@ async function readBody(req, res) {
155
256
  }
156
257
  export function createGateway(opts) {
157
258
  const { config, sponsor, events } = opts;
158
- const log = opts.log ?? (() => { });
259
+ // A log sink that throws is the operator's problem, never the payer's: it
260
+ // must not turn a settled request into a bare 500, or a settled-and-served
261
+ // one into anything else. Swallowed here, once, for every call site.
262
+ const log = (line) => {
263
+ try {
264
+ opts.log?.(line);
265
+ }
266
+ catch {
267
+ // nothing to do with it that would not be the same problem again
268
+ }
269
+ };
159
270
  const chain = chainFor(config.network);
160
271
  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;
272
+ // Instantiate Rate Limiters
273
+ const globalLimiter = config.rateLimit ? new RateLimiter(config.rateLimit) : undefined;
274
+ const serviceLimiters = new Map();
275
+ if (config.services) {
276
+ for (const [name, svc] of Object.entries(config.services)) {
277
+ if (svc.rateLimit)
278
+ serviceLimiters.set(name, new RateLimiter(svc.rateLimit));
168
279
  }
169
- if (pathname === '/__buy/usage') {
170
- json(res, 200, usage.snapshot());
171
- return;
280
+ }
281
+ // The legacy `routing` block is a service too, so its limit is honoured the
282
+ // same way; previously it parsed cleanly and was never consulted.
283
+ const routingLimiter = config.routing?.rateLimit
284
+ ? new RateLimiter(config.routing.rateLimit)
285
+ : undefined;
286
+ const endpointLimiters = new Map();
287
+ for (const ep of config.endpoints) {
288
+ if (ep.rateLimit)
289
+ endpointLimiters.set(ep.path, new RateLimiter(ep.rateLimit));
290
+ }
291
+ const handle = async (req, res) => {
292
+ const ip = clientIp(req, config.trustProxy);
293
+ // 1. Global unauthenticated rate limit (runs on all incoming requests)
294
+ if (globalLimiter) {
295
+ const check = globalLimiter.consume(ip);
296
+ if (!check.allowed) {
297
+ usage.recordRejection('*', 'rate_limited');
298
+ res.setHeader('Retry-After', String(check.retryAfterSeconds ?? 1));
299
+ json(res, 429, { error: 'rate_limited: too many requests' });
300
+ return;
301
+ }
172
302
  }
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.
303
+ const url = new URL(req.url ?? '/', 'http://placeholder');
304
+ const pathname = url.pathname;
177
305
  const endpoint = matchEndpoint(config, pathname);
178
306
  if (!endpoint) {
179
307
  json(res, 404, { error: 'not_found' });
180
308
  return;
181
309
  }
182
- const body = await readBody(req, res);
310
+ // 2. HTTP Method Restrictions
311
+ // Decided before the 402, like a path that would escape the upstream:
312
+ // Node's parser delivers TRACE and undici refuses to send it, so without
313
+ // this a paid TRACE was settled and then failed at fetch().
314
+ const method = (req.method ?? 'GET').toUpperCase();
315
+ const allowed = endpoint.restrictions?.methods ?? FORWARDABLE_METHODS;
316
+ if (!allowed.includes(method)) {
317
+ res.setHeader('Allow', allowed.join(', '));
318
+ json(res, 405, {
319
+ error: `method_not_allowed: method ${method} is not permitted for this endpoint`,
320
+ });
321
+ return;
322
+ }
323
+ // 3. Endpoint IP / Service Rate Limiting (pre-payment)
324
+ const epLimiter = endpointLimiters.get(endpoint.path);
325
+ if (epLimiter && epLimiter.scope === 'ip') {
326
+ const check = epLimiter.consume(ip);
327
+ if (!check.allowed) {
328
+ usage.recordRejection(endpoint.path, 'rate_limited');
329
+ res.setHeader('Retry-After', String(check.retryAfterSeconds ?? 1));
330
+ json(res, 429, { error: 'rate_limited: endpoint limit exceeded' });
331
+ return;
332
+ }
333
+ }
334
+ const serviceName = endpoint.service;
335
+ const serviceLimiter = serviceName ? serviceLimiters.get(serviceName) : routingLimiter;
336
+ if (serviceLimiter && serviceLimiter.scope === 'ip') {
337
+ const check = serviceLimiter.consume(ip);
338
+ if (!check.allowed) {
339
+ usage.recordRejection(endpoint.path, 'rate_limited');
340
+ res.setHeader('Retry-After', String(check.retryAfterSeconds ?? 1));
341
+ json(res, 429, { error: 'rate_limited: service limit exceeded' });
342
+ return;
343
+ }
344
+ }
345
+ // A `service` bucket protects the UPSTREAM's quota, so it is spent only by
346
+ // a request that will reach the upstream: a free one at the point of
347
+ // serving, a paid one after verification and before settlement. The unpaid
348
+ // 402 probe never reaches the upstream, and spending on it let anyone
349
+ // exhaust the bucket for every paying customer without paying for one.
350
+ // Header -> value for everything THIS service injects. A static source
351
+ // (env or resolvedHeaders) wins; a provider is asked only when nothing
352
+ // static names the variable, and its throw is caught by the callers below
353
+ // BEFORE settlement, so a credential that cannot be minted costs nothing.
354
+ const injectedFor = async (service) => {
355
+ const out = {};
356
+ if (service.mode !== 'proxy')
357
+ return out;
358
+ for (const [header, envVar] of Object.entries(service.injectHeaders)) {
359
+ // Empty is absent, not a value.
360
+ const fixed = process.env[envVar] || opts.resolvedHeaders?.[envVar];
361
+ const provider = opts.headerProviders?.[envVar];
362
+ if (fixed) {
363
+ out[header] = fixed;
364
+ }
365
+ else if (provider) {
366
+ const value = await withDeadline(provider(), opts.providerTimeoutMs ?? 10_000, envVar);
367
+ if (!value)
368
+ throw new Error(`provider for $${envVar} returned no credential`);
369
+ // Same guard resolveInjectedHeaders applies to a static value: a
370
+ // CR/LF in a minted token would pass the nonempty check, reach
371
+ // Headers.set() after settlement, and throw there — charged, 502.
372
+ if (!isHeaderValue(value)) {
373
+ throw new Error(`provider for $${envVar} returned an invalid header value`);
374
+ }
375
+ out[header] = value;
376
+ }
377
+ }
378
+ return out;
379
+ };
380
+ const credentialUnavailable = async (endpointPath, err, release, correlationId = randomBytes(6).toString('hex')) => {
381
+ if (release)
382
+ await release();
383
+ usage.recordRejection(endpointPath, 'upstream_credential_unavailable');
384
+ log(`credential provider failed cid=${correlationId}: ${err instanceof Error ? err.message : String(err)}`);
385
+ json(res, 503, {
386
+ error: `upstream_credential_unavailable: could not obtain the upstream credential (correlation id: ${correlationId})`,
387
+ });
388
+ };
389
+ const consumeServiceBucket = () => serviceLimiter && serviceLimiter.scope === 'service'
390
+ ? serviceLimiter.consume(serviceName ?? 'routing')
391
+ : { allowed: true };
392
+ const serviceLimited = (check) => {
393
+ usage.recordRejection(endpoint.path, 'rate_limited');
394
+ res.setHeader('Retry-After', String(check.retryAfterSeconds ?? 1));
395
+ json(res, 429, { error: 'rate_limited: service limit exceeded' });
396
+ };
397
+ const maxBodyBytes = endpoint.restrictions?.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
398
+ const body = await readBody(req, res, maxBodyBytes);
183
399
  if (body === undefined)
184
- return; // 413 already sent
400
+ return;
401
+ const service = resolveService(config, endpoint);
402
+ // Decided here, before the 402 and long before settlement: a path that
403
+ // would leave the upstream is refused while the request is still free,
404
+ // never after the payer has been charged for it.
405
+ const target = upstreamTarget(service, endpoint, pathname, url.search);
406
+ if (service.mode === 'proxy' && target === undefined) {
407
+ usage.recordRejection(endpoint.path, 'bad_request');
408
+ json(res, 400, { error: 'bad_request: path escapes the configured upstream' });
409
+ return;
410
+ }
411
+ // Free endpoints pass through without payment challenge
185
412
  if (endpoint.free) {
186
- await serve(req, res, pathname, body, null, undefined);
413
+ const check = consumeServiceBucket();
414
+ if (!check.allowed) {
415
+ serviceLimited(check);
416
+ return;
417
+ }
418
+ let injected;
419
+ try {
420
+ injected = await injectedFor(service);
421
+ }
422
+ catch (err) {
423
+ await credentialUnavailable(endpoint.path, err);
424
+ return;
425
+ }
426
+ await serve(req, res, target, service, body, null, undefined, injected);
187
427
  return;
188
428
  }
189
- const cid = randomBytes(6).toString('hex');
190
- const offers = offersFor(config, endpoint, resourceUrl(req, pathname));
191
- const challenge = { x402Version: 1, accepts: offers, error: '' };
429
+ const resource = resourceUrl(req, pathname);
430
+ const offers = offersFor(config, endpoint, resource);
431
+ const challenge = { x402Version: 1, accepts: offers, error: 'payment_required' };
192
432
  const paymentHeader = req.headers['x-payment'];
193
433
  if (!paymentHeader) {
194
434
  json(res, 402, challenge);
@@ -205,6 +445,7 @@ export function createGateway(opts) {
205
445
  });
206
446
  return;
207
447
  }
448
+ const cid = randomBytes(6).toString('hex');
208
449
  // The payer picked one offer and signed for its asset; verification runs
209
450
  // against that offer alone, and everything after — the Self gate, the
210
451
  // settlement, the revenue line — refers to it, never to the price currency.
@@ -221,6 +462,27 @@ export function createGateway(opts) {
221
462
  return;
222
463
  }
223
464
  const { requirements } = verified;
465
+ // 4. Payer Wallet Scoped Rate Limiting
466
+ if (epLimiter && epLimiter.scope === 'payer') {
467
+ const check = epLimiter.consume(verified.from.toLowerCase());
468
+ if (!check.allowed) {
469
+ await verified.releaseNonce();
470
+ usage.recordRejection(endpoint.path, 'rate_limited');
471
+ res.setHeader('Retry-After', String(check.retryAfterSeconds ?? 1));
472
+ json(res, 429, { error: 'rate_limited: wallet limit exceeded' });
473
+ return;
474
+ }
475
+ }
476
+ if (serviceLimiter && serviceLimiter.scope === 'payer') {
477
+ const check = serviceLimiter.consume(verified.from.toLowerCase());
478
+ if (!check.allowed) {
479
+ await verified.releaseNonce();
480
+ usage.recordRejection(endpoint.path, 'rate_limited');
481
+ res.setHeader('Retry-After', String(check.retryAfterSeconds ?? 1));
482
+ json(res, 429, { error: 'rate_limited: wallet service limit exceeded' });
483
+ return;
484
+ }
485
+ }
224
486
  if (endpoint.self) {
225
487
  const selfHeader = req.headers['x-self-attestation'];
226
488
  const selfResult = await verifySelfAttestation({
@@ -231,10 +493,6 @@ export function createGateway(opts) {
231
493
  ...(events ? { events } : {}),
232
494
  });
233
495
  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
496
  await verified.releaseNonce();
239
497
  usage.recordRejection(endpoint.path, selfResult.reason);
240
498
  json(res, 402, {
@@ -244,6 +502,24 @@ export function createGateway(opts) {
244
502
  return;
245
503
  }
246
504
  }
505
+ // Last check before money moves; a refusal here hands the nonce back.
506
+ const serviceCheck = consumeServiceBucket();
507
+ if (!serviceCheck.allowed) {
508
+ await verified.releaseNonce();
509
+ serviceLimited(serviceCheck);
510
+ return;
511
+ }
512
+ // The upstream credential, resolved before any money moves. A provider that
513
+ // cannot mint one now (metadata server down, key rotated away) must not be
514
+ // discovered after settlement, where the caller has paid for a 401.
515
+ let injected;
516
+ try {
517
+ injected = await injectedFor(service);
518
+ }
519
+ catch (err) {
520
+ await credentialUnavailable(endpoint.path, err, () => verified.releaseNonce(), cid);
521
+ return;
522
+ }
247
523
  let transaction = null;
248
524
  if (sponsor) {
249
525
  try {
@@ -256,13 +532,8 @@ export function createGateway(opts) {
256
532
  ...(events ? { events } : {}),
257
533
  });
258
534
  transaction = settled.tx;
259
- log(`settled cid=${cid} ${verified.from} → ${config.payTo} tx=${settled.tx}`);
260
535
  }
261
536
  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
537
  const message = err instanceof Error ? err.message : String(err);
267
538
  log(`SETTLE FAILED cid=${cid} payer=${verified.from} err=${message}`);
268
539
  usage.recordRejection(endpoint.path, 'settle_failed');
@@ -273,11 +544,40 @@ export function createGateway(opts) {
273
544
  return;
274
545
  }
275
546
  }
547
+ // Outside the try on purpose: the money has moved, and a log sink that
548
+ // throws must not be reported as a settlement that failed.
549
+ if (transaction)
550
+ log(`settled cid=${cid} ${verified.from} → ${config.payTo} tx=${transaction}`);
276
551
  usage.recordPayment(endpoint.path, endpoint.amount, tokenByAddress(config.network, requirements.asset)?.symbol ?? endpoint.currency);
277
- await serve(req, res, pathname, body, transaction, verified.from);
552
+ // Everything from here is a settled request. The upstream paths inside
553
+ // serve() carry the receipt on their own errors; this guard is for the
554
+ // rest — a header value the runtime rejects, a response the socket
555
+ // refuses — so that no throw after settlement reaches the bare 500.
556
+ try {
557
+ await serve(req, res, target, service, body, transaction, verified.from, injected);
558
+ }
559
+ catch (err) {
560
+ const message = err instanceof Error ? err.message : String(err);
561
+ log(`serve failed after settlement cid=${cid} tx=${transaction ?? 'none'} err=${message}`);
562
+ if (res.headersSent) {
563
+ res.destroy();
564
+ return;
565
+ }
566
+ const paymentResponse = encodeHeader({
567
+ success: true,
568
+ network: config.network,
569
+ payer: verified.from,
570
+ transaction,
571
+ });
572
+ res.setHeader('X-PAYMENT-RESPONSE', paymentResponse);
573
+ json(res, 502, {
574
+ error: `bad_gateway: could not serve the paid resource (correlation id: ${cid})`,
575
+ ...(transaction ? { transaction } : {}),
576
+ });
577
+ }
278
578
  };
279
- /** Deliver the paid resource: proxy upstream, or answer from config. */
280
- const serve = async (req, res, pathname, body, transaction, payer) => {
579
+ /** Deliver the paid resource: proxy upstream or respond from config. */
580
+ const serve = async (req, res, target, service, body, transaction, payer, injected) => {
281
581
  const paymentResponse = payer === undefined
282
582
  ? undefined
283
583
  : encodeHeader({
@@ -286,28 +586,19 @@ export function createGateway(opts) {
286
586
  payer,
287
587
  transaction,
288
588
  });
289
- if (config.routing.mode === 'respond') {
290
- const headers = { 'Content-Type': config.routing.contentType };
589
+ if (service.mode === 'respond') {
590
+ const headers = { 'Content-Type': service.contentType };
291
591
  if (paymentResponse)
292
592
  headers['X-PAYMENT-RESPONSE'] = paymentResponse;
293
593
  res.writeHead(200, headers);
294
- res.end(config.routing.body);
594
+ res.end(service.body);
295
595
  return;
296
596
  }
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.
597
+ // `upstreamTarget` returned undefined only for a non-proxy service, and
598
+ // that branch returned above; the handler refused escapes before charging.
599
+ if (target === undefined)
600
+ throw new Error('proxy service without a resolved target');
307
601
  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
602
  const hopByHop = new Set();
312
603
  const connection = req.headers.connection;
313
604
  if (typeof connection === 'string') {
@@ -319,12 +610,13 @@ export function createGateway(opts) {
319
610
  }
320
611
  for (const [key, value] of Object.entries(req.headers)) {
321
612
  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
613
  if (PROTECTED_HEADERS.has(lower) ||
326
614
  lower === 'x-payment' ||
327
615
  lower === 'x-self-attestation' ||
616
+ // undici decodes what IT negotiates; forwarding the caller's list
617
+ // (zstd, say) would fetch a coding it cannot decode. A coding that
618
+ // arrives anyway keeps its header on the way back — see the relay.
619
+ lower === 'accept-encoding' ||
328
620
  hopByHop.has(lower)) {
329
621
  continue;
330
622
  }
@@ -334,51 +626,127 @@ export function createGateway(opts) {
334
626
  for (const v of value)
335
627
  forwarded.append(key, v);
336
628
  }
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
- });
629
+ // Injected credentials configured for THIS service, resolved from the
630
+ // environment variable each one names. Last, and with `set`: a configured
631
+ // credential must win over anything the caller sent under any spelling of
632
+ // the same name (issue #41).
633
+ for (const [header, value] of Object.entries(injected))
634
+ forwarded.set(header, value);
635
+ const controller = new AbortController();
636
+ const timeoutMs = service.timeoutMs ?? 30_000;
637
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
638
+ let upstreamRes;
639
+ try {
640
+ upstreamRes = await fetch(target, {
641
+ method: req.method ?? 'GET',
642
+ headers: forwarded,
643
+ signal: controller.signal,
644
+ // `upstreamTarget` keeps the FIRST request on the configured origin;
645
+ // following a redirect would let the upstream send the injected
646
+ // credentials anywhere it names and pass that origin's body off as
647
+ // the paid resource. A 3xx is handled below as an upstream error.
648
+ redirect: 'manual',
649
+ ...(body.length > 0 && req.method !== 'GET' && req.method !== 'HEAD'
650
+ ? { body: new Uint8Array(body) }
651
+ : {}),
652
+ });
653
+ }
654
+ catch (err) {
655
+ clearTimeout(timer);
656
+ const isTimeout = controller.signal.aborted;
657
+ // Settlement already happened. The payer is out the money whether or not
658
+ // the upstream answered, so they get the receipt either way — without the
659
+ // transaction hash there is nothing to dispute or reconcile with.
660
+ if (paymentResponse)
661
+ res.setHeader('X-PAYMENT-RESPONSE', paymentResponse);
662
+ if (transaction) {
663
+ log(`upstream ${isTimeout ? 'timed out' : 'unreachable'} after settlement tx=${transaction}`);
664
+ }
665
+ json(res, isTimeout ? 504 : 502, {
666
+ error: isTimeout
667
+ ? 'gateway_timeout: upstream timed out'
668
+ : 'bad_gateway: upstream unreachable',
669
+ ...(transaction ? { transaction } : {}),
670
+ });
671
+ return;
672
+ }
673
+ // NOT cleared here: fetch() resolves when the HEADERS arrive, and the
674
+ // deadline has to cover the body too — an upstream that answers and then
675
+ // stalls is the same money situation as one that never answers.
676
+ // Never seen by the payer as a resource: it is the upstream declining to
677
+ // answer here, and the money has moved. Same shape as unreachable. Only
678
+ // the statuses that carry a Location — a 304 is the upstream honouring
679
+ // the caller's own conditional header, and is relayed like any answer.
680
+ if (REDIRECTS.has(upstreamRes.status)) {
681
+ clearTimeout(timer);
682
+ // Let go of the body (and the connection) we are not going to read.
683
+ controller.abort();
684
+ if (paymentResponse)
685
+ res.setHeader('X-PAYMENT-RESPONSE', paymentResponse);
686
+ if (transaction)
687
+ log(`upstream redirected after settlement tx=${transaction}`);
688
+ json(res, 502, {
689
+ error: `bad_gateway: upstream answered a redirect (${upstreamRes.status}), which is not followed`,
690
+ ...(transaction ? { transaction } : {}),
691
+ });
692
+ return;
693
+ }
694
+ const decodedByFetch = await codingsUndiciDecodes();
351
695
  const outHeaders = {};
352
696
  upstreamRes.headers.forEach((value, key) => {
353
697
  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') {
698
+ if (lower === 'transfer-encoding' || lower === 'content-length')
699
+ return;
700
+ if (lower === 'content-encoding' && decodedByFetch.has(value.trim().toLowerCase()))
364
701
  return;
365
- }
366
- // Hop-by-hop headers are per-connection and must not be relayed.
367
702
  if (lower === 'connection' || lower === 'keep-alive')
368
703
  return;
704
+ // Only the gateway speaks for payment. Relayed, an upstream's copy would
705
+ // be written beside the real receipt and corrupt it — or, on a free
706
+ // route, forge one.
707
+ if (lower === 'x-payment-response')
708
+ return;
709
+ // forEach yields each Set-Cookie separately under the same key; only
710
+ // the last would survive a plain assignment.
711
+ if (lower === 'set-cookie')
712
+ return;
369
713
  outHeaders[key] = value;
370
714
  });
715
+ const cookies = upstreamRes.headers.getSetCookie();
716
+ if (cookies.length > 0)
717
+ outHeaders['set-cookie'] = cookies;
371
718
  if (paymentResponse)
372
719
  outHeaders['X-PAYMENT-RESPONSE'] = paymentResponse;
373
- const buf = Buffer.from(await upstreamRes.arrayBuffer());
720
+ // The upstream can fail AFTER sending headers — a reset mid-body — and
721
+ // that is the same money situation as never answering: settled, unserved.
722
+ // Reading the body inside the same protection keeps the receipt on it.
723
+ let buf;
724
+ try {
725
+ buf = Buffer.from(await upstreamRes.arrayBuffer());
726
+ }
727
+ catch {
728
+ const isTimeout = controller.signal.aborted;
729
+ if (paymentResponse)
730
+ res.setHeader('X-PAYMENT-RESPONSE', paymentResponse);
731
+ if (transaction) {
732
+ log(`upstream body ${isTimeout ? 'timed out' : 'failed'} after settlement tx=${transaction}`);
733
+ }
734
+ json(res, isTimeout ? 504 : 502, {
735
+ error: isTimeout
736
+ ? 'gateway_timeout: upstream timed out'
737
+ : 'bad_gateway: upstream body failed',
738
+ ...(transaction ? { transaction } : {}),
739
+ });
740
+ return;
741
+ }
742
+ finally {
743
+ clearTimeout(timer);
744
+ }
374
745
  outHeaders['content-length'] = String(buf.length);
375
746
  res.writeHead(upstreamRes.status, outHeaders);
376
747
  res.end(buf);
377
748
  };
378
749
  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
750
  handle(req, res).catch((err) => {
383
751
  log(`request failed: ${err instanceof Error ? err.message : String(err)}`);
384
752
  if (res.headersSent) {
@@ -388,9 +756,8 @@ export function createGateway(opts) {
388
756
  json(res, 500, { error: 'internal_error' });
389
757
  });
390
758
  });
391
- // A trickled body would otherwise hold a handler slot for Node's 300s default.
392
759
  server.requestTimeout = 30_000;
393
760
  server.headersTimeout = 20_000;
394
- return { server, usage: () => usage.snapshot() };
761
+ return { server, handler: handle, usage: () => usage.snapshot() };
395
762
  }
396
763
  //# sourceMappingURL=server.js.map