@celo/buy-gateway 0.8.4 → 0.8.6

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
@@ -6,8 +6,9 @@ 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 { safeEmit, settleX402Payment, verifyOfferedPayment, verifySelfAttestation, } from '@celo/buy-facilitator';
9
+ import { carriesPayment, challengeHeaders, isPaymentHeader, readPayment, receiptHeaders, safeEmit, settleX402Payment, validateProtocols, verifyOfferedPayment, verifySelfAttestation, } from '@celo/buy-facilitator';
10
10
  import { DECIMALS, FORWARDABLE_METHODS, PROTECTED_HEADERS, isHeaderValue, matchEndpoint, } from './config.js';
11
+ import { judgeRequest } from './judged.js';
11
12
  import { RateLimiter } from './rate-limit.js';
12
13
  import { createUsageRecorder } from './usage.js';
13
14
  /** Anonymous callers can reach the body reader, so default cap is 64KB. */
@@ -35,9 +36,6 @@ function json(res, status, body) {
35
36
  function decodeHeader(raw) {
36
37
  return JSON.parse(Buffer.from(raw, 'base64').toString('utf8'));
37
38
  }
38
- function encodeHeader(value) {
39
- return Buffer.from(JSON.stringify(value)).toString('base64');
40
- }
41
39
  /** Upstream statuses that mean "go elsewhere", which the gateway will not. */
42
40
  const REDIRECTS = new Set([301, 302, 303, 307, 308]);
43
41
  /**
@@ -151,8 +149,13 @@ export function upstreamTarget(service, endpoint, pathname, search) {
151
149
  return undefined;
152
150
  return target;
153
151
  }
154
- /** The tokens a priced endpoint is offered in: `config.tokens`, else its price currency. */
155
- function offeredTokens(config, endpoint) {
152
+ /**
153
+ * The tokens a priced endpoint is offered in: `config.tokens`, else its price
154
+ * currency. The 402 challenge quotes exactly these, so anything that
155
+ * advertises the route (a catalogue, a discovery feed) should call this rather
156
+ * than restate it.
157
+ */
158
+ export function offeredTokens(config, endpoint) {
156
159
  return config.tokens ?? [endpoint.currency];
157
160
  }
158
161
  /**
@@ -177,6 +180,13 @@ function settleableToken(network, symbol) {
177
180
  }
178
181
  return token;
179
182
  }
183
+ /**
184
+ * The protocols one endpoint speaks. The identity requirement travels inside
185
+ * the x402 offer and MPP has no place for it, so a `self` route is x402 only.
186
+ */
187
+ export function endpointProtocols(protocols, endpoint) {
188
+ return endpoint.self ? { ...protocols, mpp: undefined } : protocols;
189
+ }
180
190
  /** One x402 offer per token the endpoint accepts, at the same price, in config order. */
181
191
  export function offersFor(config, endpoint, resource) {
182
192
  return offeredTokens(config, endpoint).map((symbol) => requirementsFor(config, endpoint, resource, symbol));
@@ -264,16 +274,18 @@ async function readBody(req, res, maxBytes) {
264
274
  }
265
275
  /**
266
276
  * Apply an endpoint's JSON restrictions to a request body.
267
- * With `jsonFields` or `jsonOnlyFields` the body handed back is re-serialized
277
+ * With `jsonFields`, `jsonOnlyFields` or `textOnlyMessages` the body handed back is re-serialized
268
278
  * from the parsed value: JSON.parse keeps the LAST of two duplicate keys and
269
279
  * an upstream may keep the first, so forwarding the original bytes could let
270
- * the upstream act on a value this check never saw.
280
+ * the upstream act on a value this check never saw. `value` is what was
281
+ * parsed, when anything was, for the judged envelope to read.
271
282
  */
272
283
  export function checkJsonBody(body, restrictions) {
273
284
  const fields = restrictions?.jsonFields;
274
285
  const only = restrictions?.jsonOnlyFields;
275
286
  const maxArrayLength = restrictions?.maxJsonArrayLength;
276
- if (!restrictions?.json && !fields && !only && maxArrayLength === undefined) {
287
+ const textOnly = restrictions?.textOnlyMessages === true;
288
+ if (!restrictions?.json && !fields && !only && maxArrayLength === undefined && !textOnly) {
277
289
  return { ok: true, body };
278
290
  }
279
291
  let parsed;
@@ -288,9 +300,9 @@ export function checkJsonBody(body, restrictions) {
288
300
  }
289
301
  // Read as JSON and found sound, but forwarded as it came: the bytes of a
290
302
  // JSON-RPC id or a large integer are the caller's to choose.
291
- if (!fields && !only)
292
- return { ok: true, body, json: true };
293
- if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
303
+ if (!fields && !only && !textOnly)
304
+ return { ok: true, body, json: true, value: parsed };
305
+ if (!isJsonObject(parsed)) {
294
306
  return { ok: false, reason: 'the body must be a JSON object' };
295
307
  }
296
308
  const record = parsed;
@@ -314,7 +326,58 @@ export function checkJsonBody(body, restrictions) {
314
326
  };
315
327
  }
316
328
  }
317
- return { ok: true, body: Buffer.from(JSON.stringify(parsed)), json: true };
329
+ if (textOnly && Object.hasOwn(record, 'messages')) {
330
+ const refusal = nonTextMessage(record.messages);
331
+ if (refusal !== undefined)
332
+ return { ok: false, reason: refusal };
333
+ }
334
+ return { ok: true, body: Buffer.from(JSON.stringify(parsed)), json: true, value: parsed };
335
+ }
336
+ function isJsonObject(value) {
337
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
338
+ }
339
+ const TEXT_MESSAGE_KEYS = ['role', 'content', 'name'];
340
+ const TEXT_PART_KEYS = ['type', 'text'];
341
+ /**
342
+ * Why `messages` is not text only, or undefined when it is. A key outside the
343
+ * lists is refused rather than ignored: a provider may read it (an `audio`
344
+ * reference, an `image_url` beside a text part's `text`), and the point is that
345
+ * nothing reaches the provider except text the byte cap has already counted.
346
+ */
347
+ function nonTextMessage(messages) {
348
+ if (!Array.isArray(messages))
349
+ return 'messages must be an array';
350
+ for (const [i, message] of messages.entries()) {
351
+ const at = `messages[${i}]`;
352
+ if (!isJsonObject(message))
353
+ return `${at} must be an object`;
354
+ const extra = Object.keys(message).find((key) => !TEXT_MESSAGE_KEYS.includes(key));
355
+ if (extra !== undefined) {
356
+ return `${at} may carry only ${TEXT_MESSAGE_KEYS.join(', ')} (got ${JSON.stringify(extra.slice(0, 64))})`;
357
+ }
358
+ const content = message.content;
359
+ if (typeof content === 'string')
360
+ continue;
361
+ if (!Array.isArray(content)) {
362
+ return `${at}.content must be a string or an array of text parts`;
363
+ }
364
+ for (const [j, part] of content.entries()) {
365
+ const partAt = `${at}.content[${j}]`;
366
+ if (!isJsonObject(part))
367
+ return `${partAt} must be a text part`;
368
+ if (part.type !== 'text') {
369
+ const type = typeof part.type === 'string' ? JSON.stringify(part.type.slice(0, 64)) : 'none';
370
+ return `${partAt} must be a text part; this endpoint accepts text only (got type ${type})`;
371
+ }
372
+ if (typeof part.text !== 'string')
373
+ return `${partAt}.text must be a string`;
374
+ const partExtra = Object.keys(part).find((key) => !TEXT_PART_KEYS.includes(key));
375
+ if (partExtra !== undefined) {
376
+ return `${partAt} may carry only ${TEXT_PART_KEYS.join(', ')} (got ${JSON.stringify(partExtra.slice(0, 64))})`;
377
+ }
378
+ }
379
+ }
380
+ return undefined;
318
381
  }
319
382
  /**
320
383
  * How long a payer may take to sign and send the authorization a 402 quotes.
@@ -368,6 +431,7 @@ export function createGateway(opts) {
368
431
  // fails the boot rather than the first KYC request.
369
432
  const reverify = resolveReverify(opts.reverify, config.network);
370
433
  assertReverifyEnforceable(reverify, config);
434
+ validateProtocols(opts.protocols);
371
435
  // A log sink that throws is the operator's problem, never the payer's: it
372
436
  // must not turn a settled request into a bare 500, or a settled-and-served
373
437
  // one into anything else. Swallowed here, once, for every call site.
@@ -466,7 +530,18 @@ export function createGateway(opts) {
466
530
  // this a paid TRACE was settled and then failed at fetch().
467
531
  const method = (req.method ?? 'GET').toUpperCase();
468
532
  const allowed = endpoint.restrictions?.methods ?? FORWARDABLE_METHODS;
469
- if (!allowed.includes(method)) {
533
+ const paymentHeader = req.headers['x-payment'];
534
+ const protocols = endpointProtocols(opts.protocols, endpoint);
535
+ // Any payment, in any protocol this route speaks. Only the unpaid get the
536
+ // probe's answers below.
537
+ const paid = Boolean(paymentHeader) || carriesPayment({ protocols, headers: req.headers });
538
+ // Index crawlers probe a paid route with a bare, unpaid GET or POST and
539
+ // read the price from the 402 (#389). An unpaid GET or HEAD on a route
540
+ // that does not take it is let through to that probe answer below and
541
+ // refused there if it carries a body; with a payment it is a 405 here,
542
+ // so nothing is ever settled for a method the endpoint does not take.
543
+ const probeOnly = !endpoint.free && !paid && (method === 'GET' || method === 'HEAD');
544
+ if (!allowed.includes(method) && !probeOnly) {
470
545
  refuse(endpoint.path, 405, 'method_not_allowed');
471
546
  res.setHeader('Allow', allowed.join(', '));
472
547
  json(res, 405, {
@@ -555,6 +630,46 @@ export function createGateway(opts) {
555
630
  refuse(endpoint.path, 413, 'payload_too_large');
556
631
  return;
557
632
  }
633
+ const service = resolveService(config, endpoint);
634
+ // Decided here, before the 402 and long before settlement: a path that
635
+ // would leave the upstream is refused while the request is still free,
636
+ // never after the payer has been charged for it.
637
+ const target = upstreamTarget(service, endpoint, pathname, url.search);
638
+ if (service.mode === 'proxy' && target === undefined) {
639
+ refuse(endpoint.path, 400, 'bad_request');
640
+ json(res, 400, { error: 'bad_request: path escapes the configured upstream' });
641
+ return;
642
+ }
643
+ const resource = resourceUrl(req, pathname);
644
+ // A free endpoint names no token, so it has no offers to build.
645
+ const offers = endpoint.free ? [] : offersFor(config, endpoint, resource);
646
+ const challenge = { x402Version: 1, accepts: offers, error: 'payment_required' };
647
+ /** The 402: the v1 body, and the same offers in every other protocol that is on. */
648
+ const challenge402 = (error = challenge.error) => {
649
+ const headers = challengeHeaders({ protocols, offers, chainId: chain.id, error });
650
+ for (const [name, value] of Object.entries(headers))
651
+ res.setHeader(name, value);
652
+ json(res, 402, { ...challenge, error });
653
+ };
654
+ // The bare probe: no payment and no body. Its 402 comes before the body
655
+ // checks below, because a crawler that cannot read a price lists the
656
+ // route as unpriced (#389). Anything that carries a body, or a payment,
657
+ // is checked exactly as before.
658
+ if (!endpoint.free && !paid && raw.length === 0) {
659
+ // A GET or HEAD the endpoint does not take is priced (#319), and says so.
660
+ if (!allowed.includes(method))
661
+ res.setHeader('Allow', allowed.join(', '));
662
+ challenge402();
663
+ return;
664
+ }
665
+ if (probeOnly && !allowed.includes(method)) {
666
+ refuse(endpoint.path, 405, 'method_not_allowed');
667
+ res.setHeader('Allow', allowed.join(', '));
668
+ json(res, 405, {
669
+ error: `method_not_allowed: method ${method} is not permitted for this endpoint`,
670
+ });
671
+ return;
672
+ }
558
673
  // Before the 402, like the method and the size: a body the upstream would
559
674
  // refuse, or one asking for something this endpoint does not sell, is
560
675
  // turned away while it is still free instead of settled and then failed.
@@ -566,6 +681,8 @@ export function createGateway(opts) {
566
681
  }
567
682
  const body = checked.body;
568
683
  const checkedJson = checked.json === true;
684
+ // Reported on the completion only; it refuses and prices nothing.
685
+ const judgment = judgeRequest(endpoint.judged, checked.value);
569
686
  // `jsonOnlyFields` lists everything a request may ask for. The query
570
687
  // string is forwarded as well, and an upstream that reads a parameter
571
688
  // from it would be asked for something that list never saw.
@@ -576,16 +693,6 @@ export function createGateway(opts) {
576
693
  });
577
694
  return;
578
695
  }
579
- const service = resolveService(config, endpoint);
580
- // Decided here, before the 402 and long before settlement: a path that
581
- // would leave the upstream is refused while the request is still free,
582
- // never after the payer has been charged for it.
583
- const target = upstreamTarget(service, endpoint, pathname, url.search);
584
- if (service.mode === 'proxy' && target === undefined) {
585
- refuse(endpoint.path, 400, 'bad_request');
586
- json(res, 400, { error: 'bad_request: path escapes the configured upstream' });
587
- return;
588
- }
589
696
  // Free endpoints pass through without payment challenge
590
697
  if (endpoint.free) {
591
698
  usage.recordFreeRequest(endpoint.path);
@@ -626,29 +733,40 @@ export function createGateway(opts) {
626
733
  return;
627
734
  }
628
735
  }
629
- await serve(req, res, target, service, body, checkedJson, null, undefined, injected);
736
+ await serve(req, res, target, service, body, checkedJson, null, {}, injected);
630
737
  return;
631
738
  }
632
- const resource = resourceUrl(req, pathname);
633
- const offers = offersFor(config, endpoint, resource);
634
- const challenge = { x402Version: 1, accepts: offers, error: 'payment_required' };
635
- const paymentHeader = req.headers['x-payment'];
636
- if (!paymentHeader) {
637
- json(res, 402, challenge);
739
+ // X-PAYMENT first, and alone: a request that carries it never reaches the
740
+ // other formats, so it is handled as it always was.
741
+ const other = paymentHeader
742
+ ? undefined
743
+ : readPayment({ protocols, headers: req.headers, offers, chainId: chain.id });
744
+ if (!paymentHeader && !other) {
745
+ challenge402();
746
+ return;
747
+ }
748
+ if (other && !other.ok) {
749
+ // Not always malformed: a well-formed payment for an offer this route does
750
+ // not make lands here too.
751
+ refuse(endpoint.path, 402, 'invalid_payment');
752
+ challenge402(other.error);
638
753
  return;
639
754
  }
640
755
  let payment;
641
- try {
642
- payment = decodeHeader(String(paymentHeader));
756
+ if (other) {
757
+ payment = other.payment;
643
758
  }
644
- catch (err) {
645
- refuse(endpoint.path, 402, 'malformed_payment_header');
646
- json(res, 402, {
647
- ...challenge,
648
- error: `malformed X-PAYMENT: ${err instanceof Error ? err.message : String(err)}`,
649
- });
650
- return;
759
+ else {
760
+ try {
761
+ payment = decodeHeader(String(paymentHeader));
762
+ }
763
+ catch (err) {
764
+ refuse(endpoint.path, 402, 'malformed_payment_header');
765
+ challenge402(`malformed X-PAYMENT: ${err instanceof Error ? err.message : String(err)}`);
766
+ return;
767
+ }
651
768
  }
769
+ const protocol = other?.protocol ?? 'x402-v1';
652
770
  const cid = randomBytes(6).toString('hex');
653
771
  const requestEvents = events
654
772
  ? {
@@ -662,7 +780,8 @@ export function createGateway(opts) {
662
780
  // which offer the payer signed, and it owns the nonce. A remote facilitator
663
781
  // adds its hosted checks against that selected offer just below.
664
782
  const verified = await verifyOfferedPayment({
665
- requirements: offers,
783
+ // A v2 or an MPP payment names its offer, so only that one is tried.
784
+ requirements: other?.offers ?? offers,
666
785
  // biome-ignore lint/suspicious/noExplicitAny: verified inside; anything may arrive on the wire
667
786
  payment: payment,
668
787
  chainId: chain.id,
@@ -671,10 +790,7 @@ export function createGateway(opts) {
671
790
  if (!verified.ok) {
672
791
  refuse(endpoint.path, 402, verified.reason);
673
792
  const detail = 'detail' in verified && verified.detail ? ` (${verified.detail})` : '';
674
- json(res, 402, {
675
- ...challenge,
676
- error: `verify_payment_failed: ${verified.reason}${detail}`,
677
- });
793
+ challenge402(`verify_payment_failed: ${verified.reason}${detail}`);
678
794
  return;
679
795
  }
680
796
  const { requirements } = verified;
@@ -693,10 +809,7 @@ export function createGateway(opts) {
693
809
  await verified.releaseNonce();
694
810
  refuse(endpoint.path, 402, remote.reason);
695
811
  const detail = 'detail' in remote && remote.detail ? ` (${remote.detail})` : '';
696
- json(res, 402, {
697
- ...challenge,
698
- error: `verify_payment_failed: ${remote.reason}${detail}`,
699
- });
812
+ challenge402(`verify_payment_failed: ${remote.reason}${detail}`);
700
813
  return;
701
814
  }
702
815
  }
@@ -733,10 +846,7 @@ export function createGateway(opts) {
733
846
  if (!selfResult.ok) {
734
847
  await verified.releaseNonce();
735
848
  refuse(endpoint.path, 402, selfResult.reason);
736
- json(res, 402, {
737
- ...challenge,
738
- error: `verify_self_failed: ${selfResult.reason}${selfResult.detail ? ` (${selfResult.detail})` : ''}`,
739
- });
849
+ challenge402(`verify_self_failed: ${selfResult.reason}${selfResult.detail ? ` (${selfResult.detail})` : ''}`);
740
850
  return;
741
851
  }
742
852
  }
@@ -840,10 +950,7 @@ export function createGateway(opts) {
840
950
  log(`REMOTE SETTLE FAILED cid=${cid} payer=${verified.from} err=${message}`);
841
951
  await upstreamReservation?.release('settlement_failed');
842
952
  refuse(endpoint.path, 402, 'settle_failed');
843
- json(res, 402, {
844
- ...challenge,
845
- error: `settle_failed: ${message} (correlation id: ${cid})`,
846
- });
953
+ challenge402(`settle_failed: ${message} (correlation id: ${cid})`);
847
954
  return;
848
955
  }
849
956
  }
@@ -871,10 +978,7 @@ export function createGateway(opts) {
871
978
  log(`SETTLE FAILED cid=${cid} payer=${verified.from} err=${message}`);
872
979
  await upstreamReservation?.release('settlement_failed');
873
980
  refuse(endpoint.path, 402, 'settle_failed');
874
- json(res, 402, {
875
- ...challenge,
876
- error: `settle_failed: ${message} (correlation id: ${cid})`,
877
- });
981
+ challenge402(`settle_failed: ${message} (correlation id: ${cid})`);
878
982
  return;
879
983
  }
880
984
  }
@@ -882,6 +986,13 @@ export function createGateway(opts) {
882
986
  // throws must not be reported as a settlement that failed.
883
987
  if (transaction)
884
988
  log(`settled cid=${cid} ${verified.from} → ${config.payTo} tx=${transaction}`);
989
+ const receipt = receiptHeaders({
990
+ protocol,
991
+ network: config.network,
992
+ chainId: chain.id,
993
+ payer: verified.from,
994
+ transaction,
995
+ });
885
996
  const recordPayment = () => usage.recordPayment(endpoint.path, endpoint.amount, tokenByAddress(config.network, requirements.asset)?.symbol ?? endpoint.currency, verified.from);
886
997
  // Real money moved at settlement, so it is revenue whether or not delivery
887
998
  // works, and the nonce stays spent. Mock mode moved none: it counts only a
@@ -911,6 +1022,7 @@ export function createGateway(opts) {
911
1022
  }
912
1023
  log(`upstream attempt unrecorded cid=${cid}: the reservation stays counted; do not release it`);
913
1024
  }
1025
+ const servingFrom = performance.now();
914
1026
  const completion = (outcome) => ({
915
1027
  ...outcome,
916
1028
  correlationId: cid,
@@ -928,13 +1040,16 @@ export function createGateway(opts) {
928
1040
  chainId: chain.id,
929
1041
  transaction,
930
1042
  mock,
1043
+ judged: judgment.judged,
1044
+ ...(judgment.judged ? {} : { unjudgedReason: judgment.reason }),
1045
+ elapsedMs: Math.max(0, Math.round(performance.now() - servingFrom)),
931
1046
  });
932
1047
  // Everything from here is a settled request. The upstream paths inside
933
1048
  // serve() carry the receipt on their own errors; this guard is for the
934
1049
  // rest: a header value the runtime rejects, a response the socket
935
1050
  // refuses. No throw after settlement reaches the bare 500.
936
1051
  try {
937
- const outcome = await serve(req, res, target, service, body, checkedJson, transaction, verified.from, injected, undelivered);
1052
+ const outcome = await serve(req, res, target, service, body, checkedJson, transaction, receipt, injected, undelivered);
938
1053
  if (mock && delivered && outcome.delivered)
939
1054
  recordPayment();
940
1055
  complete(completion(outcome));
@@ -949,13 +1064,8 @@ export function createGateway(opts) {
949
1064
  complete(completion({ status: null, delivered: false, reason: 'serve_failed' }));
950
1065
  return;
951
1066
  }
952
- const paymentResponse = encodeHeader({
953
- success: true,
954
- network: config.network,
955
- payer: verified.from,
956
- transaction,
957
- });
958
- res.setHeader('X-PAYMENT-RESPONSE', paymentResponse);
1067
+ for (const [name, value] of Object.entries(receipt))
1068
+ res.setHeader(name, value);
959
1069
  json(res, 502, {
960
1070
  error: `bad_gateway: could not serve the paid resource (correlation id: ${cid})`,
961
1071
  ...(transaction ? { transaction } : {}),
@@ -966,22 +1076,13 @@ export function createGateway(opts) {
966
1076
  /** Deliver the paid resource: proxy upstream or respond from config. */
967
1077
  const serve = async (req, res, target, service, body,
968
1078
  /** The JSON checks read this body, as UTF-8, before it was priced. */
969
- checkedJson, transaction, payer, injected,
1079
+ checkedJson, transaction,
1080
+ /** The receipt header of the payer's protocol; empty on a free route. */
1081
+ receipt, injected,
970
1082
  /** Mock mode only: called before any error is written, when nothing was delivered. */
971
1083
  undelivered) => {
972
- const paymentResponse = payer === undefined
973
- ? undefined
974
- : encodeHeader({
975
- success: true,
976
- network: config.network,
977
- payer,
978
- transaction,
979
- });
980
1084
  if (service.mode === 'respond') {
981
- const headers = { 'Content-Type': service.contentType };
982
- if (paymentResponse)
983
- headers['X-PAYMENT-RESPONSE'] = paymentResponse;
984
- res.writeHead(200, headers);
1085
+ res.writeHead(200, { 'Content-Type': service.contentType, ...receipt });
985
1086
  res.end(service.body);
986
1087
  return { status: 200, delivered: true };
987
1088
  }
@@ -1009,7 +1110,9 @@ export function createGateway(opts) {
1009
1110
  // underscore spellings too, which some servers fold into the real ones.
1010
1111
  (checkedJson && BODY_DESCRIPTORS.has(lower.replaceAll('_', '-'))) ||
1011
1112
  PROTECTED_HEADERS.has(lower) ||
1012
- lower === 'x-payment' ||
1113
+ // A payment in any protocol, read or not: `Authorization: Payment`
1114
+ // carries a signed authorization, and the upstream is a third party.
1115
+ isPaymentHeader(lower, String(value)) ||
1013
1116
  lower === 'x-self-attestation' ||
1014
1117
  // undici decodes what IT negotiates; forwarding the caller's list
1015
1118
  // (zstd, say) would fetch a coding it cannot decode. A coding that
@@ -1055,8 +1158,8 @@ export function createGateway(opts) {
1055
1158
  // without the transaction hash there is nothing to dispute or reconcile.
1056
1159
  const fail = async (status, error, what, reason) => {
1057
1160
  await undelivered?.();
1058
- if (paymentResponse)
1059
- res.setHeader('X-PAYMENT-RESPONSE', paymentResponse);
1161
+ for (const [name, value] of Object.entries(receipt))
1162
+ res.setHeader(name, value);
1060
1163
  if (transaction) {
1061
1164
  log(`${callerGone ? 'caller disconnected' : what} after settlement tx=${transaction}`);
1062
1165
  }
@@ -1111,10 +1214,12 @@ export function createGateway(opts) {
1111
1214
  return;
1112
1215
  if (lower === 'connection' || lower === 'keep-alive')
1113
1216
  return;
1114
- // Only the gateway speaks for payment. Relayed, an upstream's copy would
1115
- // be written beside the real receipt and corrupt it — or, on a free
1116
- // route, forge one.
1117
- if (lower === 'x-payment-response')
1217
+ // Only the gateway speaks for payment, in every protocol and whether or
1218
+ // not that protocol is on here. Relayed, an upstream's receipt would be
1219
+ // written beside the real one and corrupt it, or forge one on a free
1220
+ // route; its challenge on a 402 would have a paying client send its
1221
+ // money to the upstream.
1222
+ if (isPaymentHeader(lower, value))
1118
1223
  return;
1119
1224
  // forEach yields each Set-Cookie separately under the same key; only
1120
1225
  // the last would survive a plain assignment.
@@ -1125,8 +1230,7 @@ export function createGateway(opts) {
1125
1230
  const cookies = upstreamRes.headers.getSetCookie();
1126
1231
  if (cookies.length > 0)
1127
1232
  outHeaders['set-cookie'] = cookies;
1128
- if (paymentResponse)
1129
- outHeaders['X-PAYMENT-RESPONSE'] = paymentResponse;
1233
+ Object.assign(outHeaders, receipt);
1130
1234
  // The upstream can fail AFTER sending headers — a reset mid-body — and
1131
1235
  // that is the same money situation as never answering: settled, unserved.
1132
1236
  // Reading the body inside the same protection keeps the receipt on it.