@celo/buy-gateway 0.6.0 → 0.8.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 CHANGED
@@ -50,6 +50,10 @@ services:
50
50
  dune:
51
51
  mode: proxy
52
52
  upstream: https://api.dune.com
53
+ # Covers the whole upstream answer, body included (default 30000). The
54
+ # body is also capped at 10 MiB decoded; past either limit the caller gets
55
+ # a 504 or 502 that still carries the payment receipt. A caller who
56
+ # disconnects aborts the upstream request.
53
57
  timeoutMs: 30000
54
58
  injectHeaders:
55
59
  X-DUNE-API-KEY: DUNE_API_KEY
package/dist/index.d.ts CHANGED
@@ -3,3 +3,4 @@ export * from './credentials.js';
3
3
  export * from './server.js';
4
4
  export * from './usage.js';
5
5
  export { resolveInjectedHeaders, verifyUpstreamCredentials } from './credentials.js';
6
+ export * from './upstream.js';
package/dist/index.js CHANGED
@@ -3,4 +3,5 @@ export * from './credentials.js';
3
3
  export * from './server.js';
4
4
  export * from './usage.js';
5
5
  export { resolveInjectedHeaders, verifyUpstreamCredentials } from './credentials.js';
6
+ export * from './upstream.js';
6
7
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,kBAAkB,CAAC;AACjC,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,OAAO,EAAE,sBAAsB,EAAE,yBAAyB,EAAE,MAAM,kBAAkB,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,kBAAkB,CAAC;AACjC,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,OAAO,EAAE,sBAAsB,EAAE,yBAAyB,EAAE,MAAM,kBAAkB,CAAC;AACrF,cAAc,eAAe,CAAC"}
package/dist/server.d.ts CHANGED
@@ -4,21 +4,52 @@
4
4
  */
5
5
  import http from 'node:http';
6
6
  import type { PaymentRequirements } from '@celo/buy-core';
7
- import { type FacilitatorEvents } from '@celo/buy-facilitator';
7
+ import { type FacilitatorEvents, type RemoteFacilitator } from '@celo/buy-facilitator';
8
8
  import type { LocalAccount } from 'viem';
9
9
  import { type EndpointConfig, type PaywallConfig, type ServiceConfig } from './config.js';
10
+ import type { UpstreamAdmission } from './upstream.js';
10
11
  import { type UsageStats } from './usage.js';
11
12
  export type GatewayOptions = {
12
13
  config: PaywallConfig;
13
14
  /**
14
- * Gas sponsor. Omit for MOCK MODE: payments are verified but never settled.
15
+ * Gas sponsor. Omit for MOCK MODE (unless a remote facilitator is configured):
16
+ * payments are verified but never settled, which is how the demo servers let
17
+ * someone try the flow with no funds. A mock-mode response carries `transaction: null`.
15
18
  */
16
19
  sponsor?: LocalAccount;
17
20
  /**
18
- * Re-run the Self proof server-side and ignore client's claimed attributes.
21
+ * Optional remote facilitator client (e.g. api.x402.celo.org or
22
+ * api.x402.sepolia.celo.org). When provided, verification and settlement are
23
+ * delegated to that service instead of a local sponsor wallet.
19
24
  */
20
- reverify?: boolean;
25
+ facilitator?: RemoteFacilitator;
26
+ /**
27
+ * Re-run the Self proof server-side and ignore the client's claimed
28
+ * attributes. Off by default to match `verifySelfAttestation`, but a
29
+ * deployment taking real money wants it on, without it the attestation
30
+ * header is unauthenticated JSON the caller writes.
31
+ *
32
+ * `true` re-verifies against REAL passports (the production default). Pass
33
+ * `{ mockPassport: true }` for development-only mock passports, or
34
+ * `{ mockPassport: 'either' }` to accept both. Mock-only on `celo` mainnet is
35
+ * refused at construction: a mock identity must not satisfy a real-money gate.
36
+ */
37
+ reverify?: boolean | {
38
+ mockPassport: boolean | 'either';
39
+ };
40
+ upstreamAdmission?: UpstreamAdmission;
21
41
  events?: FacilitatorEvents;
42
+ settlementJournal?: {
43
+ prepare(input: {
44
+ requirements: PaymentRequirements;
45
+ payment: unknown;
46
+ endpoint: string;
47
+ correlationId: string;
48
+ }): Promise<{
49
+ events: FacilitatorEvents;
50
+ flush(): Promise<void>;
51
+ }>;
52
+ };
22
53
  /**
23
54
  * Credential values keyed by the ENV VAR NAME an `injectHeaders` entry
24
55
  * points at, for callers that resolve them out of band (tests, embedders).
@@ -71,4 +102,26 @@ export declare function offersFor(config: PaywallConfig, endpoint: EndpointConfi
71
102
  /** Build the x402 requirements for one endpoint in one token (default: its price currency). */
72
103
  export declare function requirementsFor(config: PaywallConfig, endpoint: EndpointConfig, resource: string, symbol?: string): PaymentRequirements;
73
104
  export declare function validateTokens(config: PaywallConfig): void;
105
+ export type ReverifyMode = {
106
+ mockPassport: boolean | 'either';
107
+ };
108
+ /**
109
+ * Resolve the `reverify` option to a concrete mode, and refuse the one
110
+ * combination that would let a mock identity satisfy a real-money gate:
111
+ * mock-ONLY passports on `celo` mainnet. `true` means real passports (the
112
+ * production default); `'either'` accepts both, which is allowed on mainnet
113
+ * because it still admits real ones. Undefined means re-verification is off.
114
+ */
115
+ export declare function resolveReverify(reverify: GatewayOptions['reverify'], network: PaywallConfig['network']): ReverifyMode | undefined;
116
+ /**
117
+ * Real-passport re-verification is only actually ENFORCED when every Self
118
+ * endpoint pins a production `endpointType`. The Self hub a proof verifies
119
+ * against is taken from the attestation (a proof only validates against the hub
120
+ * that minted it), so `verifySelfAttestation` relies on the `endpoint_mismatch`
121
+ * check to reject a staging (mock) proof — and that check can only fire when
122
+ * the requirements pin a non-staging `endpointType`. Without a pin, a mock
123
+ * identity would satisfy a gate configured for real passports. Refuse at boot
124
+ * rather than advertise a guarantee the config cannot keep (celo-org/cpay#43).
125
+ */
126
+ export declare function assertReverifyEnforceable(mode: ReverifyMode | undefined, config: PaywallConfig): void;
74
127
  export declare function createGateway(opts: GatewayOptions): Gateway;
package/dist/server.js CHANGED
@@ -6,12 +6,18 @@ import { randomBytes } from 'node:crypto';
6
6
  import http from 'node:http';
7
7
  import net from 'node:net';
8
8
  import { chainFor, tokenByAddress, tokenBySymbol } from '@celo/buy-core';
9
- import { settleX402Payment, verifyOfferedPayment, verifySelfAttestation, } from '@celo/buy-facilitator';
9
+ import { safeEmit, settleX402Payment, verifyOfferedPayment, verifySelfAttestation, } from '@celo/buy-facilitator';
10
10
  import { DECIMALS, FORWARDABLE_METHODS, PROTECTED_HEADERS, isHeaderValue, matchEndpoint, } from './config.js';
11
11
  import { RateLimiter } from './rate-limit.js';
12
12
  import { createUsageRecorder } from './usage.js';
13
13
  /** Anonymous callers can reach the body reader, so default cap is 64KB. */
14
14
  const DEFAULT_MAX_BODY_BYTES = 64 * 1024;
15
+ /**
16
+ * The most upstream body (decoded bytes) the proxy buffers for one response.
17
+ * Far above any JSON answer the configured APIs give; low enough that a few
18
+ * oversized or endless upstream bodies cannot take the process's memory (#42).
19
+ */
20
+ const MAX_UPSTREAM_RESPONSE_BYTES = 10 * 1024 * 1024;
15
21
  /** A credential provider that never settles must not hold a request open. */
16
22
  function withDeadline(promise, ms, what) {
17
23
  let timer;
@@ -254,8 +260,52 @@ async function readBody(req, res, maxBytes) {
254
260
  }
255
261
  return Buffer.concat(chunks);
256
262
  }
263
+ /**
264
+ * Resolve the `reverify` option to a concrete mode, and refuse the one
265
+ * combination that would let a mock identity satisfy a real-money gate:
266
+ * mock-ONLY passports on `celo` mainnet. `true` means real passports (the
267
+ * production default); `'either'` accepts both, which is allowed on mainnet
268
+ * because it still admits real ones. Undefined means re-verification is off.
269
+ */
270
+ export function resolveReverify(reverify, network) {
271
+ if (!reverify)
272
+ return undefined;
273
+ const mode = reverify === true ? { mockPassport: false } : reverify;
274
+ if (mode.mockPassport === true && network === 'celo') {
275
+ 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.');
276
+ }
277
+ return mode;
278
+ }
279
+ /**
280
+ * Real-passport re-verification is only actually ENFORCED when every Self
281
+ * endpoint pins a production `endpointType`. The Self hub a proof verifies
282
+ * against is taken from the attestation (a proof only validates against the hub
283
+ * that minted it), so `verifySelfAttestation` relies on the `endpoint_mismatch`
284
+ * check to reject a staging (mock) proof — and that check can only fire when
285
+ * the requirements pin a non-staging `endpointType`. Without a pin, a mock
286
+ * identity would satisfy a gate configured for real passports. Refuse at boot
287
+ * rather than advertise a guarantee the config cannot keep (celo-org/cpay#43).
288
+ */
289
+ export function assertReverifyEnforceable(mode, config) {
290
+ if (mode?.mockPassport !== false)
291
+ return; // only real-only needs a pinned hub
292
+ for (const ep of config.endpoints) {
293
+ if (!ep.self)
294
+ continue;
295
+ const et = ep.self.endpointType;
296
+ if (et === undefined || et.startsWith('staging_')) {
297
+ throw new Error(`reverify requires real passports, but the self endpoint "${ep.path}" ${et === undefined
298
+ ? 'does not pin an endpointType'
299
+ : `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.`);
300
+ }
301
+ }
302
+ }
257
303
  export function createGateway(opts) {
258
304
  const { config, sponsor, events } = opts;
305
+ // Resolved once, at construction, so an invalid network/passport-mode combo
306
+ // fails the boot rather than the first KYC request.
307
+ const reverify = resolveReverify(opts.reverify, config.network);
308
+ assertReverifyEnforceable(reverify, config);
259
309
  // A log sink that throws is the operator's problem, never the payer's: it
260
310
  // must not turn a settled request into a bare 500, or a settled-and-served
261
311
  // one into anything else. Swallowed here, once, for every call site.
@@ -269,6 +319,9 @@ export function createGateway(opts) {
269
319
  };
270
320
  const chain = chainFor(config.network);
271
321
  const usage = createUsageRecorder();
322
+ opts.upstreamAdmission?.assertCoverage(config.endpoints
323
+ .filter((endpoint) => resolveService(config, endpoint).mode === 'proxy')
324
+ .map((endpoint) => `gateway:${endpoint.service ?? 'routing'}:${endpoint.path}`));
272
325
  // Instantiate Rate Limiters
273
326
  const globalLimiter = config.rateLimit ? new RateLimiter(config.rateLimit) : undefined;
274
327
  const serviceLimiters = new Map();
@@ -410,6 +463,7 @@ export function createGateway(opts) {
410
463
  }
411
464
  // Free endpoints pass through without payment challenge
412
465
  if (endpoint.free) {
466
+ usage.recordFreeRequest(endpoint.path);
413
467
  const check = consumeServiceBucket();
414
468
  if (!check.allowed) {
415
469
  serviceLimited(check);
@@ -423,6 +477,28 @@ export function createGateway(opts) {
423
477
  await credentialUnavailable(endpoint.path, err);
424
478
  return;
425
479
  }
480
+ if (service.mode === 'proxy' && opts.upstreamAdmission) {
481
+ const admission = await opts.upstreamAdmission.admit({
482
+ route: `gateway:${endpoint.service ?? 'routing'}:${endpoint.path}`,
483
+ upstream: endpoint.service ?? 'routing',
484
+ correlationId: randomBytes(12).toString('hex'),
485
+ });
486
+ if (!admission.ok) {
487
+ json(res, 503, {
488
+ error: admission.reason,
489
+ upstream: admission.upstream,
490
+ budgetId: admission.budgetId,
491
+ paymentSettled: false,
492
+ });
493
+ return;
494
+ }
495
+ // Nothing was paid, so a request whose attempt cannot be recorded is refused.
496
+ if (!(await admission.attempt())) {
497
+ await admission.release('attempt_unrecorded');
498
+ json(res, 503, { error: 'upstream_budget_unavailable', paymentSettled: false });
499
+ return;
500
+ }
501
+ }
426
502
  await serve(req, res, target, service, body, null, undefined, injected);
427
503
  return;
428
504
  }
@@ -446,22 +522,56 @@ export function createGateway(opts) {
446
522
  return;
447
523
  }
448
524
  const cid = randomBytes(6).toString('hex');
525
+ const requestEvents = events
526
+ ? {
527
+ emit: (event) => events.emit({ ...event, endpoint: endpoint.path, correlationId: cid }),
528
+ }
529
+ : undefined;
449
530
  // The payer picked one offer and signed for its asset; verification runs
450
- // against that offer alone, and everything after — the Self gate, the
451
- // settlement, the revenue line — refers to it, never to the price currency.
531
+ // against that offer alone, and everything after (the Self gate, the
532
+ // settlement, the revenue line) refers to it, never to the price currency.
533
+ // Local verification always runs: with multi-token offers only it can tell
534
+ // which offer the payer signed, and it owns the nonce. A remote facilitator
535
+ // adds its hosted checks against that selected offer just below.
452
536
  const verified = await verifyOfferedPayment({
453
537
  requirements: offers,
454
538
  // biome-ignore lint/suspicious/noExplicitAny: verified inside; anything may arrive on the wire
455
539
  payment: payment,
456
540
  chainId: chain.id,
457
- ...(events ? { events } : {}),
541
+ ...(requestEvents ? { events: requestEvents } : {}),
458
542
  });
459
543
  if (!verified.ok) {
460
544
  usage.recordRejection(endpoint.path, verified.reason);
461
- json(res, 402, { ...challenge, error: `verify_payment_failed: ${verified.reason}` });
545
+ const detail = 'detail' in verified && verified.detail ? ` (${verified.detail})` : '';
546
+ json(res, 402, {
547
+ ...challenge,
548
+ error: `verify_payment_failed: ${verified.reason}${detail}`,
549
+ });
462
550
  return;
463
551
  }
464
552
  const { requirements } = verified;
553
+ // A remote facilitator runs its own hosted verification (balance and
554
+ // authorization) against the offer the payer signed, before any money
555
+ // moves. A rejection here hands the nonce back, exactly like a local one.
556
+ if (opts.facilitator) {
557
+ const remote = await opts.facilitator.verify({
558
+ requirements,
559
+ // biome-ignore lint/suspicious/noExplicitAny: already shape-verified above
560
+ payment: payment,
561
+ correlationId: cid,
562
+ ...(requestEvents ? { events: requestEvents } : {}),
563
+ });
564
+ if (!remote.ok) {
565
+ await verified.releaseNonce();
566
+ usage.recordRejection(endpoint.path, remote.reason);
567
+ const detail = 'detail' in remote && remote.detail ? ` (${remote.detail})` : '';
568
+ json(res, 402, {
569
+ ...challenge,
570
+ error: `verify_payment_failed: ${remote.reason}${detail}`,
571
+ });
572
+ return;
573
+ }
574
+ }
465
575
  // 4. Payer Wallet Scoped Rate Limiting
466
576
  if (epLimiter && epLimiter.scope === 'payer') {
467
577
  const check = epLimiter.consume(verified.from.toLowerCase());
@@ -489,8 +599,8 @@ export function createGateway(opts) {
489
599
  requirements: requirements.extra?.selfRequirements,
490
600
  attestationHeader: selfHeader ? String(selfHeader) : undefined,
491
601
  expectedAddress: verified.from,
492
- ...(opts.reverify ? { reverify: { mockPassport: true, appName: config.name } } : {}),
493
- ...(events ? { events } : {}),
602
+ ...(reverify ? { reverify: { ...reverify, appName: config.name } } : {}),
603
+ ...(requestEvents ? { events: requestEvents } : {}),
494
604
  });
495
605
  if (!selfResult.ok) {
496
606
  await verified.releaseNonce();
@@ -520,8 +630,95 @@ export function createGateway(opts) {
520
630
  await credentialUnavailable(endpoint.path, err, () => verified.releaseNonce(), cid);
521
631
  return;
522
632
  }
633
+ let journalRequest;
634
+ if (sponsor || opts.facilitator) {
635
+ try {
636
+ journalRequest = await opts.settlementJournal?.prepare({
637
+ requirements,
638
+ payment,
639
+ endpoint: endpoint.path,
640
+ correlationId: cid,
641
+ });
642
+ }
643
+ catch {
644
+ await verified.releaseNonce();
645
+ json(res, 503, { error: 'settlement_store_unavailable', paymentSettled: false });
646
+ return;
647
+ }
648
+ }
649
+ // Admission reserves before settlement; the reservation is released if
650
+ // settlement fails and committed right before the upstream call otherwise.
651
+ let upstreamReservation;
652
+ if (service.mode === 'proxy' && opts.upstreamAdmission) {
653
+ const admission = await opts.upstreamAdmission.admit({
654
+ route: `gateway:${endpoint.service ?? 'routing'}:${endpoint.path}`,
655
+ upstream: endpoint.service ?? 'routing',
656
+ correlationId: cid,
657
+ payment,
658
+ requirements,
659
+ });
660
+ if (admission.ok)
661
+ upstreamReservation = admission;
662
+ if (!admission.ok) {
663
+ await verified.releaseNonce();
664
+ usage.recordRejection(endpoint.path, admission.reason);
665
+ json(res, 503, {
666
+ error: admission.reason,
667
+ upstream: admission.upstream,
668
+ budgetId: admission.budgetId,
669
+ paymentSettled: false,
670
+ });
671
+ return;
672
+ }
673
+ }
674
+ const settlementSink = {
675
+ emit(event) {
676
+ safeEmit(requestEvents, event);
677
+ safeEmit(journalRequest?.events, event);
678
+ },
679
+ };
680
+ const flushSettlement = async () => {
681
+ try {
682
+ await journalRequest?.flush();
683
+ }
684
+ catch {
685
+ log(`settlement event flush failed cid=${cid}`);
686
+ }
687
+ };
523
688
  let transaction = null;
524
- if (sponsor) {
689
+ if (opts.facilitator) {
690
+ try {
691
+ const settled = await opts.facilitator
692
+ .settle({
693
+ requirements,
694
+ // biome-ignore lint/suspicious/noExplicitAny: already verified above
695
+ payment: payment,
696
+ correlationId: cid,
697
+ ...(settlementSink
698
+ ? {
699
+ events: {
700
+ emit: (event) => settlementSink.emit({ ...event, endpoint: endpoint.path }),
701
+ },
702
+ }
703
+ : {}),
704
+ })
705
+ .finally(flushSettlement);
706
+ transaction = settled.tx;
707
+ log(`settled (remote) cid=${cid} ${verified.from} → ${config.payTo} tx=${settled.tx}`);
708
+ }
709
+ catch (err) {
710
+ const message = err instanceof Error ? err.message : String(err);
711
+ log(`REMOTE SETTLE FAILED cid=${cid} payer=${verified.from} err=${message}`);
712
+ await upstreamReservation?.release('settlement_failed');
713
+ usage.recordRejection(endpoint.path, 'settle_failed');
714
+ json(res, 402, {
715
+ ...challenge,
716
+ error: `settle_failed: ${message} (correlation id: ${cid})`,
717
+ });
718
+ return;
719
+ }
720
+ }
721
+ else if (sponsor) {
525
722
  try {
526
723
  const settled = await settleX402Payment({
527
724
  requirements,
@@ -529,13 +726,21 @@ export function createGateway(opts) {
529
726
  payment: payment,
530
727
  chain,
531
728
  sponsor,
532
- ...(events ? { events } : {}),
533
- });
729
+ correlationId: cid,
730
+ ...(settlementSink
731
+ ? {
732
+ events: {
733
+ emit: (event) => settlementSink.emit({ ...event, endpoint: endpoint.path }),
734
+ },
735
+ }
736
+ : {}),
737
+ }).finally(flushSettlement);
534
738
  transaction = settled.tx;
535
739
  }
536
740
  catch (err) {
537
741
  const message = err instanceof Error ? err.message : String(err);
538
742
  log(`SETTLE FAILED cid=${cid} payer=${verified.from} err=${message}`);
743
+ await upstreamReservation?.release('settlement_failed');
539
744
  usage.recordRejection(endpoint.path, 'settle_failed');
540
745
  json(res, 402, {
541
746
  ...challenge,
@@ -548,15 +753,47 @@ export function createGateway(opts) {
548
753
  // throws must not be reported as a settlement that failed.
549
754
  if (transaction)
550
755
  log(`settled cid=${cid} ${verified.from} → ${config.payTo} tx=${transaction}`);
551
- usage.recordPayment(endpoint.path, endpoint.amount, tokenByAddress(config.network, requirements.asset)?.symbol ?? endpoint.currency);
756
+ const recordPayment = () => usage.recordPayment(endpoint.path, endpoint.amount, tokenByAddress(config.network, requirements.asset)?.symbol ?? endpoint.currency, verified.from);
757
+ // Real money moved at settlement, so it is revenue whether or not delivery
758
+ // works, and the nonce stays spent. Mock mode moved none: it counts only a
759
+ // delivered request, and a failed one hands the nonce back, before the
760
+ // error is written, so the same authorization can be retried (#44).
761
+ const mock = !opts.facilitator && !sponsor;
762
+ if (!mock)
763
+ recordPayment();
764
+ let delivered = true;
765
+ const undelivered = mock
766
+ ? async () => {
767
+ delivered = false;
768
+ await verified.releaseNonce();
769
+ }
770
+ : undefined;
771
+ // The money has moved (or, in mock mode, nothing will), so the upstream is
772
+ // called whatever happens here. An attempt that cannot be recorded leaves
773
+ // the reservation counted against headroom; say so, so it is never released.
774
+ if (upstreamReservation && !(await upstreamReservation.attempt())) {
775
+ // Mock mode never settles: nothing is paid, so refuse like any unpaid refusal.
776
+ if (mock) {
777
+ await upstreamReservation.release('attempt_unrecorded');
778
+ await verified.releaseNonce();
779
+ usage.recordRejection(endpoint.path, 'upstream_budget_unavailable');
780
+ json(res, 503, { error: 'upstream_budget_unavailable', paymentSettled: false });
781
+ return;
782
+ }
783
+ log(`upstream attempt unrecorded cid=${cid}: the reservation stays counted; do not release it`);
784
+ }
552
785
  // Everything from here is a settled request. The upstream paths inside
553
786
  // 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.
787
+ // rest: a header value the runtime rejects, a response the socket
788
+ // refuses. No throw after settlement reaches the bare 500.
556
789
  try {
557
- await serve(req, res, target, service, body, transaction, verified.from, injected);
790
+ await serve(req, res, target, service, body, transaction, verified.from, injected, undelivered);
791
+ if (mock && delivered)
792
+ recordPayment();
558
793
  }
559
794
  catch (err) {
795
+ if (delivered)
796
+ await undelivered?.();
560
797
  const message = err instanceof Error ? err.message : String(err);
561
798
  log(`serve failed after settlement cid=${cid} tx=${transaction ?? 'none'} err=${message}`);
562
799
  if (res.headersSent) {
@@ -577,7 +814,9 @@ export function createGateway(opts) {
577
814
  }
578
815
  };
579
816
  /** Deliver the paid resource: proxy upstream or respond from config. */
580
- const serve = async (req, res, target, service, body, transaction, payer, injected) => {
817
+ const serve = async (req, res, target, service, body, transaction, payer, injected,
818
+ /** Mock mode only: called before any error is written, when nothing was delivered. */
819
+ undelivered) => {
581
820
  const paymentResponse = payer === undefined
582
821
  ? undefined
583
822
  : encodeHeader({
@@ -635,6 +874,28 @@ export function createGateway(opts) {
635
874
  const controller = new AbortController();
636
875
  const timeoutMs = service.timeoutMs ?? 30_000;
637
876
  const timer = setTimeout(() => controller.abort(), timeoutMs);
877
+ // A caller who hangs up has nobody left to deliver to: stop the upstream
878
+ // work now instead of holding its socket until the deadline (#42).
879
+ let callerGone = false;
880
+ res.once('close', () => {
881
+ if (res.writableEnded)
882
+ return;
883
+ callerGone = true;
884
+ controller.abort();
885
+ });
886
+ // Every way the resource is not delivered once the request was paid for.
887
+ // Settlement already happened, so the payer is out the money whether or
888
+ // not the upstream answered: they get the receipt either way, because
889
+ // without the transaction hash there is nothing to dispute or reconcile.
890
+ const fail = async (status, error, what) => {
891
+ await undelivered?.();
892
+ if (paymentResponse)
893
+ res.setHeader('X-PAYMENT-RESPONSE', paymentResponse);
894
+ if (transaction) {
895
+ log(`${callerGone ? 'caller disconnected' : what} after settlement tx=${transaction}`);
896
+ }
897
+ json(res, status, { error, ...(transaction ? { transaction } : {}) });
898
+ };
638
899
  let upstreamRes;
639
900
  try {
640
901
  upstreamRes = await fetch(target, {
@@ -651,23 +912,14 @@ export function createGateway(opts) {
651
912
  : {}),
652
913
  });
653
914
  }
654
- catch (err) {
915
+ catch {
655
916
  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}`);
917
+ if (controller.signal.aborted) {
918
+ await fail(504, 'gateway_timeout: upstream timed out', 'upstream timed out');
919
+ }
920
+ else {
921
+ await fail(502, 'bad_gateway: upstream unreachable', 'upstream unreachable');
664
922
  }
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
923
  return;
672
924
  }
673
925
  // NOT cleared here: fetch() resolves when the HEADERS arrive, and the
@@ -681,14 +933,7 @@ export function createGateway(opts) {
681
933
  clearTimeout(timer);
682
934
  // Let go of the body (and the connection) we are not going to read.
683
935
  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
- });
936
+ await fail(502, `bad_gateway: upstream answered a redirect (${upstreamRes.status}), which is not followed`, 'upstream redirected');
692
937
  return;
693
938
  }
694
939
  const decodedByFetch = await codingsUndiciDecodes();
@@ -720,28 +965,49 @@ export function createGateway(opts) {
720
965
  // The upstream can fail AFTER sending headers — a reset mid-body — and
721
966
  // that is the same money situation as never answering: settled, unserved.
722
967
  // Reading the body inside the same protection keeps the receipt on it.
723
- let buf;
968
+ // Read incrementally so the cap holds while reading, not after buffering.
969
+ const chunks = [];
970
+ let size = 0;
724
971
  try {
725
- buf = Buffer.from(await upstreamRes.arrayBuffer());
972
+ const reader = upstreamRes.body?.getReader();
973
+ while (reader) {
974
+ const { done, value } = await reader.read();
975
+ if (done)
976
+ break;
977
+ size += value.byteLength;
978
+ if (size > MAX_UPSTREAM_RESPONSE_BYTES) {
979
+ // Lets go of the connection instead of draining the rest.
980
+ controller.abort();
981
+ break;
982
+ }
983
+ chunks.push(value);
984
+ }
726
985
  }
727
986
  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}`);
987
+ if (controller.signal.aborted) {
988
+ await fail(504, 'gateway_timeout: upstream timed out', 'upstream body timed out');
989
+ }
990
+ else {
991
+ await fail(502, 'bad_gateway: upstream body failed', 'upstream body failed');
733
992
  }
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
993
  return;
741
994
  }
742
995
  finally {
743
996
  clearTimeout(timer);
744
997
  }
998
+ if (size > MAX_UPSTREAM_RESPONSE_BYTES) {
999
+ await fail(502, `bad_gateway: upstream response exceeds ${MAX_UPSTREAM_RESPONSE_BYTES} bytes`, 'upstream response too large');
1000
+ return;
1001
+ }
1002
+ // The socket can be gone before the response's 'close' event is emitted,
1003
+ // and end() on a destroyed response still marks it ended, which would
1004
+ // silence the close handler above. Nothing reaches the caller, so in mock
1005
+ // mode it is not a delivery. ponytail: no test, the window is a single tick.
1006
+ if (callerGone || res.destroyed) {
1007
+ await undelivered?.();
1008
+ return;
1009
+ }
1010
+ const buf = Buffer.concat(chunks);
745
1011
  outHeaders['content-length'] = String(buf.length);
746
1012
  res.writeHead(upstreamRes.status, outHeaders);
747
1013
  res.end(buf);