mppx 0.20.1 → 0.21.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.
Files changed (78) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/Challenge.d.ts +59 -3
  3. package/dist/Challenge.js +162 -21
  4. package/dist/Errors.d.ts +35 -1
  5. package/dist/Errors.js +41 -3
  6. package/dist/Method.js +2 -2
  7. package/dist/Receipt.d.ts +2 -0
  8. package/dist/Receipt.js +5 -0
  9. package/dist/Store.d.ts +39 -10
  10. package/dist/Store.js +136 -29
  11. package/dist/cli/cli.d.ts +5 -0
  12. package/dist/cli/cli.js +135 -135
  13. package/dist/cli/plugins/index.js +12 -12
  14. package/dist/cli/sessions/commands.js +9 -0
  15. package/dist/cli/sessions/store.js +3 -2
  16. package/dist/cli/validate/challenge.js +15 -1
  17. package/dist/client/Mppx.d.ts +1 -1
  18. package/dist/client/Mppx.js +2 -1
  19. package/dist/client/internal/Fetch.d.ts +2 -1
  20. package/dist/client/internal/Fetch.js +43 -5
  21. package/dist/client/internal/PendingSettlement.d.ts +11 -0
  22. package/dist/client/internal/PendingSettlement.js +22 -0
  23. package/dist/client/internal/protocols/Mcp.js +8 -0
  24. package/dist/evm/client/Charge.js +7 -1
  25. package/dist/evm/server/Charge.d.ts +5 -0
  26. package/dist/evm/server/Charge.js +44 -0
  27. package/dist/evm/server/Methods.d.ts +8 -0
  28. package/dist/evm/server/Methods.js +8 -0
  29. package/dist/extensions/identity/attestation/Jwks.js +3 -3
  30. package/dist/extensions/identity/link/server/index.js +4 -4
  31. package/dist/extensions/identity/persona/server/index.js +3 -3
  32. package/dist/internal/CredentialExpiry.d.ts +30 -0
  33. package/dist/internal/CredentialExpiry.js +51 -0
  34. package/dist/internal/version.d.ts +2 -2
  35. package/dist/internal/version.js +1 -1
  36. package/dist/mcp/client/McpClient.js +29 -10
  37. package/dist/middlewares/express.d.ts +7 -2
  38. package/dist/middlewares/express.js +20 -23
  39. package/dist/middlewares/internal/express.d.ts +9 -1
  40. package/dist/middlewares/internal/express.js +348 -2
  41. package/dist/proxy/Proxy.js +15 -3
  42. package/dist/proxy/internal/Replay.d.ts +10 -0
  43. package/dist/proxy/internal/Replay.js +5 -0
  44. package/dist/server/Mppx.d.ts +1 -1
  45. package/dist/server/Mppx.js +19 -14
  46. package/dist/server/NodeListener.js +7 -0
  47. package/dist/server/Request.d.ts +6 -0
  48. package/dist/server/Request.js +43 -22
  49. package/dist/server/internal/challengeMeta.d.ts +10 -0
  50. package/dist/server/internal/challengeMeta.js +31 -1
  51. package/dist/server/internal/host.d.ts +4 -0
  52. package/dist/server/internal/host.js +41 -0
  53. package/dist/tempo/client/Charge.d.ts +5 -4
  54. package/dist/tempo/client/Charge.js +210 -38
  55. package/dist/tempo/client/Subscription.js +3 -0
  56. package/dist/tempo/internal/zone.d.ts +8 -0
  57. package/dist/tempo/internal/zone.js +15 -0
  58. package/dist/tempo/server/Charge.d.ts +19 -0
  59. package/dist/tempo/server/Charge.js +60 -15
  60. package/dist/tempo/server/internal/html.gen.js +1 -1
  61. package/dist/tempo/server/internal/transport.js +10 -54
  62. package/dist/tempo/session/client/ChannelOps.js +1 -1
  63. package/dist/tempo/session/client/SessionManager.d.ts +4 -1
  64. package/dist/tempo/session/client/SessionManager.js +8 -2
  65. package/dist/tempo/session/server/CredentialVerification.js +2 -3
  66. package/dist/viem/Client.d.ts +2 -0
  67. package/dist/viem/Client.js +4 -1
  68. package/dist/x402/Assets.d.ts +6 -0
  69. package/dist/x402/Assets.js +10 -0
  70. package/dist/x402/Types.d.ts +68 -8
  71. package/dist/x402/Types.js +17 -2
  72. package/dist/x402/client/Exact.js +4 -1
  73. package/dist/x402/middlewares/express.js +10 -1
  74. package/dist/x402/server/EvmCharge.d.ts +20 -3
  75. package/dist/x402/server/EvmCharge.js +13 -1
  76. package/dist/x402/server/Facilitator.d.ts +42 -3
  77. package/dist/x402/server/Facilitator.js +126 -16
  78. package/package.json +1 -1
@@ -1,11 +1,11 @@
1
1
  import * as Challenge from '../../Challenge.js';
2
+ import * as PendingSettlement from '../../client/internal/PendingSettlement.js';
2
3
  import * as ProofRealm from '../../client/internal/ProofRealm.js';
3
4
  import { adapterPaymentMetaKey } from '../../client/internal/protocols/Mcp.js';
4
5
  import * as Credential from '../../Credential.js';
5
6
  import * as Expires from '../../Expires.js';
6
7
  import * as AcceptPayment from '../../internal/AcceptPayment.js';
7
8
  import * as core_Mcp from '../../Mcp.js';
8
- import * as z from '../../zod.js';
9
9
  const MPPX_MCP_CLIENT_WRAPPER = Symbol.for('mppx.mcp.client.wrapper');
10
10
  const maxPaymentAttempts = 3;
11
11
  /**
@@ -73,10 +73,6 @@ export function wrap(client, config) {
73
73
  });
74
74
  return target;
75
75
  }
76
- /** Minimal wire shape of payment-required data; challenges are validated, extra fields pass through. */
77
- const PaymentRequiredSchema = z.object({
78
- challenges: z.array(Challenge.Schema).check(z.minLength(1)),
79
- });
80
76
  /**
81
77
  * Checks if an error is a payment required error.
82
78
  */
@@ -92,17 +88,20 @@ export function isPaymentRequiredError(error) {
92
88
  }
93
89
  /** @internal */
94
90
  async function createCredential(challenge, config) {
95
- const { context, method } = config;
91
+ const { context, method, signal } = config;
96
92
  if (challenge.expires)
97
93
  Expires.assert(challenge.expires, challenge.id);
98
94
  const parsedContext = method.context && context !== undefined ? method.context.parse(context) : undefined;
99
- return method.createCredential(parsedContext !== undefined ? { challenge, context: parsedContext } : { challenge });
95
+ // A Zone withdrawal still settling is resumed for this challenge, not paid again.
96
+ return PendingSettlement.resume(() => method.createCredential(parsedContext !== undefined
97
+ ? { challenge, context: parsedContext }
98
+ : { challenge }), { attempts: maxPaymentAttempts, signal });
100
99
  }
101
100
  function createPaymentAwareCallTool(callTool, config) {
102
101
  const methods = config.methods.flat();
103
102
  const paymentPreferences = AcceptPayment.resolve(methods, config.paymentPreferences);
104
103
  const retryWithPayment = async (params, call, paymentRequired, cause, attemptsRemaining = maxPaymentAttempts) => {
105
- const challenges = paymentRequired.challenges;
104
+ const challenges = usableChallenges(paymentRequired.challenges);
106
105
  const candidates = AcceptPayment.selectChallengeCandidates(challenges, methods, paymentPreferences.entries, call.context);
107
106
  const orderedCandidates = config.orderChallenges
108
107
  ? await config.orderChallenges(candidates)
@@ -111,7 +110,7 @@ function createPaymentAwareCallTool(callTool, config) {
111
110
  if (!selected) {
112
111
  const available = challenges.map((challenge) => `${challenge.method}.${challenge.intent}`);
113
112
  const installed = methods.map((method) => `${method.name}.${method.intent}`);
114
- throw new Error(`No compatible payment method. Server offers: ${available.join(', ')}. Client has: ${installed.join(', ')}`, { cause });
113
+ throw new Error(Challenge.withSkippedChallenges(`No compatible payment method. Server offers: ${available.join(', ')}. Client has: ${installed.join(', ')}`, paymentRequired.challenges.length - challenges.length), { cause });
115
114
  }
116
115
  if (selected.challenge.expires)
117
116
  Expires.assert(selected.challenge.expires, selected.challenge.id);
@@ -124,6 +123,7 @@ function createPaymentAwareCallTool(callTool, config) {
124
123
  const credential = await createCredential(selected.challenge, {
125
124
  context: call.context,
126
125
  method: selected.method,
126
+ signal: call.requestOptions?.signal,
127
127
  });
128
128
  const parsed = Credential.deserialize(credential);
129
129
  try {
@@ -164,8 +164,27 @@ function getPaymentRequiredMeta(result) {
164
164
  const data = result._meta?.[core_Mcp.paymentRequiredMetaKey];
165
165
  return isPaymentRequiredData(data) ? data : undefined;
166
166
  }
167
+ /**
168
+ * Validates payment-required data: challenges are validated, extra fields pass through. A
169
+ * well-formed challenge that selects an unsupported credential header is allowed here and skipped
170
+ * when paying.
171
+ */
167
172
  function isPaymentRequiredData(value) {
168
- return PaymentRequiredSchema.safeParse(value).success;
173
+ if (typeof value !== 'object' || value === null)
174
+ return false;
175
+ const { challenges } = value;
176
+ if (!Array.isArray(challenges) || challenges.length === 0)
177
+ return false;
178
+ return challenges.every((challenge) => Challenge.LenientSchema.safeParse(challenge).success);
179
+ }
180
+ /**
181
+ * Returns the challenges a client may pay: a challenge that selects an unsupported credential
182
+ * header gets no credential, but does not stop the client from paying another challenge.
183
+ */
184
+ function usableChallenges(challenges) {
185
+ return challenges.flatMap((challenge) => Challenge.hasUnsupportedCredentialHeader(challenge)
186
+ ? []
187
+ : [Challenge.Schema.parse(challenge)]);
169
188
  }
170
189
  function withReceipt(result) {
171
190
  return {
@@ -21,8 +21,13 @@ export declare namespace Mppx {
21
21
  * })
22
22
  * ```
23
23
  */
24
- function create<const methods extends Mppx_core.Methods>(config: Mppx_core.create.Config<methods>): Mppx_internal.Wrap<Mppx_core.Mppx<methods>, RequestHandler>;
24
+ function create<const methods extends Mppx_core.Methods>(config: Mppx_core.create.Config<methods> & AdapterOptions): Mppx_internal.Wrap<Mppx_core.Mppx<methods>, RequestHandler>;
25
25
  }
26
+ /** Optional ingress validation shared by Express payment handlers. */
27
+ export type AdapterOptions = {
28
+ /** Exact incoming hosts, including ports. Treat the list as immutable; replace the array to change it. Omitted preserves existing behavior; an empty list rejects all hosts. Configure trusted ingress to enforce the same list. */
29
+ allowedHosts?: readonly string[] | undefined;
30
+ };
26
31
  /**
27
32
  * Express middleware that gates a route behind a payment intent.
28
33
  *
@@ -43,7 +48,7 @@ export declare namespace Mppx {
43
48
  * })
44
49
  * ```
45
50
  */
46
- export declare function payment<const intent extends Mppx_internal.AnyMethodFn>(intent: intent, options: intent extends (options: infer options) => any ? options : never): RequestHandler;
51
+ export declare function payment<const intent extends Mppx_internal.AnyMethodFn>(intent: intent, options: intent extends (options: infer options) => any ? options : never, adapterOptions?: AdapterOptions): RequestHandler;
47
52
  export type DiscoveryConfig = Omit<GenerateConfig, 'routes'> & {
48
53
  path?: string;
49
54
  routes?: RouteConfig[];
@@ -1,4 +1,5 @@
1
1
  import { generate } from '../discovery/OpenApi.js';
2
+ import * as Host from '../server/internal/host.js';
2
3
  import * as Scope from '../server/internal/scope.js';
3
4
  import * as Mppx_core from '../server/Mppx.js';
4
5
  import * as ExpressAdapter from './internal/express.js';
@@ -24,7 +25,7 @@ export var Mppx;
24
25
  * ```
25
26
  */
26
27
  function create(config) {
27
- return Mppx_internal.wrap(Mppx_core.create(config), payment);
28
+ return Mppx_internal.wrap(Mppx_core.create(config), (method, options) => payment(method, options, config));
28
29
  }
29
30
  Mppx.create = create;
30
31
  })(Mppx || (Mppx = {}));
@@ -48,9 +49,24 @@ export var Mppx;
48
49
  * })
49
50
  * ```
50
51
  */
51
- export function payment(intent, options) {
52
+ export function payment(intent, options, adapterOptions = {}) {
52
53
  return async (req, res, next) => {
53
- const rawRequest = ExpressAdapter.toRequest(req);
54
+ const protocol = req.protocol.toLowerCase();
55
+ if (!Host.isAllowed(req, adapterOptions.allowedHosts, req.get('host')) ||
56
+ (adapterOptions.allowedHosts !== undefined && protocol !== 'http' && protocol !== 'https')) {
57
+ res.status(421).send('Misdirected Request');
58
+ return;
59
+ }
60
+ let rawRequest;
61
+ try {
62
+ rawRequest = ExpressAdapter.toRequest(req, protocol);
63
+ }
64
+ catch (error) {
65
+ if (!(error instanceof ExpressAdapter.InvalidRequestTargetError))
66
+ throw error;
67
+ res.status(400).send('Bad Request');
68
+ return;
69
+ }
54
70
  const routePath = typeof req.route?.path === 'string' ? req.route.path : req.path;
55
71
  const request = options.scope === undefined && Scope.read(options.meta) === undefined
56
72
  ? Scope.attach(rawRequest, `${req.method.toUpperCase()} ${req.baseUrl}${routePath}`)
@@ -81,26 +97,7 @@ export function payment(intent, options) {
81
97
  res.send(Buffer.from(await managementResponse.arrayBuffer()));
82
98
  return;
83
99
  }
84
- const originalJson = res.json;
85
- res.json = (body) => {
86
- const originalSend = res.send;
87
- // Let Express serialize with the application's replacer, spacing, and
88
- // escaping settings, but defer sending until the payment transport wraps it.
89
- res.send = (serialized) => {
90
- const response = new Response([204, 205, 304].includes(res.statusCode) ? null : serialized, { status: res.statusCode, headers: { 'Content-Type': res.get('Content-Type') } });
91
- void Promise.resolve()
92
- .then(() => result.withReceipt(response))
93
- .then((wrapped) => ExpressAdapter.sendResponse(res, wrapped))
94
- .catch(next);
95
- return res;
96
- };
97
- try {
98
- return originalJson.call(res, body);
99
- }
100
- finally {
101
- res.send = originalSend;
102
- }
103
- };
100
+ ExpressAdapter.wrapResponse(res, (response) => result.withReceipt(response), next);
104
101
  next();
105
102
  };
106
103
  }
@@ -3,6 +3,14 @@ import type { Request as ExpressRequest, Response as ExpressResponse } from 'exp
3
3
  export declare function copyHeaders(response: ExpressResponse, headers: Headers): void;
4
4
  /** Sends a Fetch response through Express without changing its status, headers, or bytes. */
5
5
  export declare function sendResponse(response: ExpressResponse, fetchResponse: Response): Promise<ExpressResponse<any, Record<string, any>>>;
6
+ export declare class InvalidRequestTargetError extends Error {
7
+ }
6
8
  /** Converts an Express parsed request into the Fetch request consumed by mppx core. */
7
- export declare function toRequest(request: ExpressRequest): Request;
9
+ export declare function toRequest(request: ExpressRequest, protocol?: string): Request;
10
+ /**
11
+ * Gates every Express output path through the payment transport before sending
12
+ * headers or bytes. The bounded stream preserves pipe backpressure while the
13
+ * transport validates and meters the response.
14
+ */
15
+ export declare function wrapResponse(response: ExpressResponse, withReceipt: (response: Response) => Response | Promise<Response>, onError: (error: unknown) => void): void;
8
16
  //# sourceMappingURL=express.d.ts.map
@@ -1,3 +1,7 @@
1
+ import { OutgoingMessage } from 'node:http';
2
+ import { PassThrough } from 'node:stream';
3
+ import { finished } from 'node:stream/promises';
4
+ import * as NodeListener from '../../server/NodeListener.js';
1
5
  import * as NodeRequest from './node.js';
2
6
  /** Copies Fetch response headers to an Express response. */
3
7
  export function copyHeaders(response, headers) {
@@ -12,13 +16,355 @@ export async function sendResponse(response, fetchResponse) {
12
16
  return response.end();
13
17
  return response.send(Buffer.from(await fetchResponse.arrayBuffer()));
14
18
  }
19
+ export class InvalidRequestTargetError extends Error {
20
+ }
15
21
  /** Converts an Express parsed request into the Fetch request consumed by mppx core. */
16
- export function toRequest(request) {
22
+ export function toRequest(request, protocol = request.protocol) {
23
+ const url = new URL(`${protocol}://${request.get('host')}`);
24
+ let target;
25
+ try {
26
+ target = new URL(request.originalUrl.startsWith('/')
27
+ ? `http://mppx.invalid${request.originalUrl}`
28
+ : request.originalUrl, 'http://mppx.invalid');
29
+ }
30
+ catch {
31
+ throw new InvalidRequestTargetError('Invalid request target');
32
+ }
33
+ if (target.protocol !== 'http:' && target.protocol !== 'https:')
34
+ throw new InvalidRequestTargetError('Unsupported request target protocol');
35
+ url.pathname = target.pathname;
36
+ url.search = target.search;
17
37
  return NodeRequest.toRequest({
18
38
  body: request.body,
19
39
  headers: request.headers,
20
40
  method: request.method,
21
- url: `${request.protocol}://${request.get('host')}${request.originalUrl}`,
41
+ url: url.href,
42
+ });
43
+ }
44
+ /**
45
+ * Gates every Express output path through the payment transport before sending
46
+ * headers or bytes. The bounded stream preserves pipe backpressure while the
47
+ * transport validates and meters the response.
48
+ */
49
+ export function wrapResponse(response, withReceipt, onError) {
50
+ const body = new PassThrough();
51
+ const original = {
52
+ write: response.write.bind(response),
53
+ end: response.end.bind(response),
54
+ writeHead: response.writeHead.bind(response),
55
+ flushHeaders: response.flushHeaders.bind(response),
56
+ addTrailers: response.addTrailers.bind(response),
57
+ };
58
+ const callbacks = new Set();
59
+ const endCallbacks = [];
60
+ const readyCallbacks = [];
61
+ let trailers;
62
+ let emitting = false;
63
+ let failed;
64
+ let started = false;
65
+ let ready = false;
66
+ let consumed = false;
67
+ let hasBody = true;
68
+ let preserveTrailers = false;
69
+ let preparingHeaders = false;
70
+ let headersPrepared = false;
71
+ let outputHeadersWritten = false;
72
+ let flushRequested = false;
73
+ let completed = false;
74
+ const nativeHeadersSent = Object.getOwnPropertyDescriptor(OutgoingMessage.prototype, 'headersSent').get;
75
+ Object.defineProperty(response, 'headersSent', {
76
+ configurable: true,
77
+ get: () => (started && !preparingHeaders) || nativeHeadersSent.call(response),
78
+ });
79
+ function acknowledgeWrites() {
80
+ if (!ready || !consumed || failed)
81
+ return;
82
+ for (const callback of readyCallbacks.splice(0)) {
83
+ if (callbacks.delete(callback))
84
+ queueMicrotask(() => callback());
85
+ }
86
+ }
87
+ function complete(pending, error) {
88
+ const entries = [...pending];
89
+ if (pending instanceof Set)
90
+ pending.clear();
91
+ else
92
+ pending.length = 0;
93
+ for (const callback of entries)
94
+ queueMicrotask(() => callback(error));
95
+ }
96
+ // Handler bytes already passed through downstream body wrappers. Emit them natively
97
+ // once; header hooks run separately before selecting the payment transport.
98
+ function emit(run) {
99
+ emitting = true;
100
+ try {
101
+ return run();
102
+ }
103
+ finally {
104
+ emitting = false;
105
+ }
106
+ }
107
+ const output = new Proxy(response, {
108
+ get(target, property) {
109
+ if (property === 'write')
110
+ return (chunk) => emit(() => original.write(chunk));
111
+ if (property === 'end')
112
+ return () => emit(() => {
113
+ if (!consumed)
114
+ failed = new Error('Payment transport replaced the content response.');
115
+ if (preserveTrailers && trailers)
116
+ original.addTrailers(trailers);
117
+ return original.end(() => {
118
+ completed = true;
119
+ complete(callbacks, failed);
120
+ complete(endCallbacks, failed);
121
+ });
122
+ });
123
+ if (property === 'writeHead')
124
+ return (...args) => emit(() => {
125
+ if (outputHeadersWritten)
126
+ return response;
127
+ // Apply the paid headers to the response instead of passing them to
128
+ // writeHead, so a hook installed before payment() edits the final header
129
+ // state and its forwarded arguments cannot replay a stale snapshot.
130
+ const values = args.find((arg) => typeof arg === 'object' && arg !== null);
131
+ for (const [name, value] of Object.entries(values ?? {}))
132
+ response.setHeader(name, value);
133
+ const message = args.find((arg) => typeof arg === 'string');
134
+ const result = message === undefined
135
+ ? original.writeHead(args[0])
136
+ : original.writeHead(args[0], message);
137
+ outputHeadersWritten = true;
138
+ if (flushRequested)
139
+ original.flushHeaders();
140
+ return result;
141
+ });
142
+ const value = Reflect.get(target, property, target);
143
+ return typeof value === 'function' ? value.bind(target) : value;
144
+ },
145
+ });
146
+ body.on('drain', () => {
147
+ if (!response.writableNeedDrain)
148
+ response.emit('drain');
149
+ });
150
+ body.on('error', () => { });
151
+ let closed = false;
152
+ response.once('close', () => {
153
+ closed = true;
154
+ body.destroy();
155
+ if (!response.writableFinished) {
156
+ const error = failed ?? new Error('Response closed before paid delivery completed.');
157
+ complete(callbacks, error);
158
+ complete(endCallbacks, error);
159
+ }
160
+ });
161
+ function start() {
162
+ if (started)
163
+ return;
164
+ started = true;
165
+ // Run downstream implicit-header hooks before the transport selects metering.
166
+ preparingHeaders = true;
167
+ try {
168
+ if (!headersPrepared)
169
+ response.writeHead(response.statusCode);
170
+ }
171
+ finally {
172
+ preparingHeaders = false;
173
+ }
174
+ const headers = new Headers();
175
+ for (const [name, value] of Object.entries(response.getHeaders())) {
176
+ if (Array.isArray(value))
177
+ for (const item of value)
178
+ headers.append(name, item);
179
+ else if (value !== undefined)
180
+ headers.set(name, String(value));
181
+ }
182
+ const status = response.statusCode;
183
+ hasBody = ![204, 205, 304].includes(status);
184
+ const iterator = body[Symbol.asyncIterator]();
185
+ let canceled = false;
186
+ const stream = new ReadableStream({
187
+ async pull(controller) {
188
+ consumed = true;
189
+ acknowledgeWrites();
190
+ try {
191
+ const next = await iterator.next();
192
+ if (canceled)
193
+ return;
194
+ if (next.done)
195
+ controller.close();
196
+ else
197
+ controller.enqueue(next.value);
198
+ }
199
+ catch (error) {
200
+ if (!canceled)
201
+ controller.error(error);
202
+ }
203
+ },
204
+ cancel() {
205
+ canceled = true;
206
+ body.destroy();
207
+ },
208
+ }, { highWaterMark: 0 });
209
+ if (!hasBody)
210
+ body.resume();
211
+ void Promise.resolve()
212
+ .then(() => withReceipt(new Response(hasBody ? stream : null, {
213
+ headers,
214
+ status,
215
+ statusText: response.statusMessage,
216
+ })))
217
+ .then(async (wrapped) => {
218
+ // Trailers describe the original body, not a replacement or transformed response.
219
+ preserveTrailers = hasBody && wrapped.body === stream;
220
+ // HEAD deliberately omits an unchanged body without making delivery a failure.
221
+ const head = response.req.method === 'HEAD' && preserveTrailers;
222
+ const bodyless = !hasBody && wrapped.body === null && wrapped.status === status;
223
+ if (head || bodyless) {
224
+ consumed = true;
225
+ body.resume();
226
+ }
227
+ ready = true;
228
+ acknowledgeWrites();
229
+ for (const name of response.getHeaderNames())
230
+ response.removeHeader(name);
231
+ try {
232
+ if (head || bodyless) {
233
+ output.writeHead(wrapped.status, wrapped.statusText, {
234
+ ...Object.fromEntries(wrapped.headers),
235
+ ...(wrapped.headers.getSetCookie().length
236
+ ? { 'set-cookie': wrapped.headers.getSetCookie() }
237
+ : {}),
238
+ });
239
+ try {
240
+ await finished(body, { cleanup: true });
241
+ }
242
+ catch (error) {
243
+ // The client left before the handler ended. The close listener already
244
+ // completed pending callbacks, so this is not a handler error.
245
+ if (closed)
246
+ return;
247
+ throw error;
248
+ }
249
+ }
250
+ await NodeListener.sendResponse(output, wrapped);
251
+ }
252
+ finally {
253
+ // A replacement response may finish without consuming the handler's body.
254
+ body.destroy();
255
+ }
256
+ })
257
+ .catch((error) => {
258
+ failed = error instanceof Error ? error : new Error(String(error));
259
+ body.destroy();
260
+ complete(callbacks, failed);
261
+ complete(endCallbacks, failed);
262
+ // Never reopen raw output while an asynchronous handler is still running.
263
+ response.destroy();
264
+ onError(error);
265
+ });
266
+ }
267
+ const write = ((chunk, encoding, callback) => {
268
+ if (emitting)
269
+ return original.write(chunk, encoding, callback);
270
+ const handler = typeof encoding === 'function' ? encoding : callback;
271
+ // Each write owns a completion, even when a producer reuses its callback.
272
+ const done = handler ? (error) => handler(error) : undefined;
273
+ if (failed || response.destroyed || response.writableEnded || body.destroyed) {
274
+ if (done)
275
+ queueMicrotask(() => done(failed ?? new Error('Response closed.')));
276
+ return false;
277
+ }
278
+ if (done)
279
+ callbacks.add(done);
280
+ start();
281
+ // A transport may retain the chunk after the producer's callback runs.
282
+ const copy = typeof chunk === 'string'
283
+ ? Buffer.from(chunk, typeof encoding === 'string' ? encoding : undefined)
284
+ : Buffer.from(chunk);
285
+ return body.write(copy, (error) => {
286
+ if (!done || !callbacks.has(done))
287
+ return;
288
+ if (error) {
289
+ callbacks.delete(done);
290
+ queueMicrotask(() => done(error));
291
+ }
292
+ else {
293
+ // The copied input has entered a bounded stream. Waiting for a complete
294
+ // output event here deadlocks producers that write that event in pieces.
295
+ readyCallbacks.push(done);
296
+ acknowledgeWrites();
297
+ }
298
+ });
299
+ });
300
+ response.write = write;
301
+ response.end = ((chunk, encoding, callback) => {
302
+ if (emitting)
303
+ return original.end(chunk, encoding, callback);
304
+ const done = typeof chunk === 'function' ? chunk : typeof encoding === 'function' ? encoding : callback;
305
+ if (done) {
306
+ if (completed || failed || response.destroyed)
307
+ queueMicrotask(() => done(failed ?? (completed ? undefined : new Error('Response closed.'))));
308
+ else
309
+ endCallbacks.push(done);
310
+ }
311
+ if (typeof chunk === 'string' || chunk instanceof Uint8Array)
312
+ write(chunk, typeof encoding === 'string' ? encoding : 'utf8');
313
+ start();
314
+ body.end();
315
+ // Native end uncorks implicitly, but paid delivery must drain before it can run.
316
+ while (response.writableCorked > 0)
317
+ response.uncork();
318
+ if (failed)
319
+ complete(endCallbacks, failed);
320
+ return response;
321
+ });
322
+ response.writeHead = ((status, messageOrHeaders, headers) => {
323
+ if (emitting)
324
+ return original.writeHead(status, messageOrHeaders, headers);
325
+ if (failed || response.destroyed)
326
+ return response;
327
+ response.statusCode = status;
328
+ if (typeof messageOrHeaders === 'string')
329
+ response.statusMessage = messageOrHeaders;
330
+ const values = headers ?? (typeof messageOrHeaders === 'string' ? undefined : messageOrHeaders);
331
+ if (Array.isArray(values)) {
332
+ const seen = new Set();
333
+ for (let i = 0; i < values.length; i += 2) {
334
+ const name = String(values[i]);
335
+ if (!seen.has(name.toLowerCase()))
336
+ response.removeHeader(name);
337
+ response.appendHeader(name, values[i + 1]);
338
+ seen.add(name.toLowerCase());
339
+ }
340
+ }
341
+ else if (values) {
342
+ for (const [name, value] of Object.entries(values))
343
+ response.setHeader(name, value);
344
+ }
345
+ headersPrepared = true;
346
+ start();
347
+ return response;
22
348
  });
349
+ // Node exposes writeHeader as a separate alias, so override it too.
350
+ Object.assign(response, { writeHeader: response.writeHead });
351
+ response.flushHeaders = () => {
352
+ if (emitting || outputHeadersWritten)
353
+ original.flushHeaders();
354
+ else {
355
+ flushRequested = true;
356
+ start();
357
+ }
358
+ };
359
+ response.addTrailers = (values) => {
360
+ if (emitting)
361
+ original.addTrailers(values);
362
+ else
363
+ trailers = values;
364
+ };
365
+ // Hints are optional and must not reveal protected metadata before accounting.
366
+ response.writeEarlyHints = (_hints, callback) => {
367
+ callback?.();
368
+ };
23
369
  }
24
370
  //# sourceMappingURL=express.js.map
@@ -163,6 +163,14 @@ export function create(config) {
163
163
  replayBody = body;
164
164
  paidRequest = Replay.withBody(request, body);
165
165
  replayKey = Replay.key({
166
+ authority: replay.authority,
167
+ scope: JSON.stringify([
168
+ (config.basePath ?? '').replace(/\/+$/, ''),
169
+ serviceId,
170
+ normalizeBaseUrl(service.baseUrl).href,
171
+ Route.parseRouteKey(matched.key),
172
+ getConfiguredScope(handler),
173
+ ]),
166
174
  body,
167
175
  credential,
168
176
  method: request.method,
@@ -499,9 +507,7 @@ function matchesPaymentBinding(endpoint, binding) {
499
507
  }
500
508
  function createFetchProxy(target, options) {
501
509
  const localFetch = options?.fetch ?? globalThis.fetch;
502
- const targetUrl = new URL(target);
503
- if (targetUrl.pathname.endsWith('/'))
504
- targetUrl.pathname = targetUrl.pathname.replace(/\/+$/, '');
510
+ const targetUrl = normalizeBaseUrl(target);
505
511
  return async (input, init) => {
506
512
  const request = new globalThis.Request(input, init);
507
513
  const url = new URL(request.url);
@@ -523,4 +529,10 @@ function createFetchProxy(target, options) {
523
529
  return localFetch(proxyUrl, proxyInit);
524
530
  };
525
531
  }
532
+ /** Uses the same canonical upstream base for delivery and replay scope. */
533
+ function normalizeBaseUrl(target) {
534
+ const url = new URL(target);
535
+ url.pathname = url.pathname.replace(/\/+$/, '');
536
+ return url;
537
+ }
526
538
  //# sourceMappingURL=Proxy.js.map
@@ -1,6 +1,13 @@
1
1
  import type * as Store from '../../Store.js';
2
2
  /** Options for replaying paid proxy deliveries. */
3
3
  export type Options = {
4
+ /**
5
+ * Trusted payment-authority identifier. Use the same value only for replicas
6
+ * with identical payment policies and upstream permissions. Never derive it
7
+ * from request headers. Required when replay is enabled; missing values fail at startup.
8
+ * Changing it invalidates outstanding replay records.
9
+ */
10
+ authority?: string | undefined;
4
11
  /**
5
12
  * Upstream attempts per credential, including the first, before a retry gets `502`.
6
13
  * A retry after a failed delivery (an upstream error, a 5xx or a body that broke
@@ -29,6 +36,7 @@ export type Options = {
29
36
  };
30
37
  /** Replay options with defaults applied. */
31
38
  export type Resolved = {
39
+ authority: string;
32
40
  maxAttempts: number;
33
41
  maxBodySize: number;
34
42
  maxRequestBodySize: number;
@@ -69,6 +77,8 @@ export declare function credentialOf(request: Request, headerNames?: readonly st
69
77
  export declare function readBody(request: Request, maxRequestBodySize: number): Promise<Uint8Array<ArrayBuffer> | null>;
70
78
  /** Derives the replay key from the credential and the exact request (origin, path, query, method, body) it paid for. */
71
79
  export declare function key(parameters: {
80
+ authority: string;
81
+ scope: string;
72
82
  body: Uint8Array;
73
83
  credential: string;
74
84
  method: string;
@@ -7,7 +7,10 @@ export function resolve(options) {
7
7
  // AbortSignal.timeout needs a positive integer that fits a 32-bit timer.
8
8
  if (!Number.isSafeInteger(ttl) || ttl <= 0 || ttl > 2_147_483_647)
9
9
  throw new RangeError('replay.ttl must be a positive integer number of milliseconds up to 2147483647.');
10
+ if (!options.authority?.trim())
11
+ throw new TypeError('replay.authority must be a stable, explicitly configured payment authority.');
10
12
  return {
13
+ authority: options.authority,
11
14
  maxAttempts: options.maxAttempts ?? 3,
12
15
  maxBodySize: options.maxBodySize ?? 1_048_576,
13
16
  maxRequestBodySize: options.maxRequestBodySize ?? 1_048_576,
@@ -41,6 +44,8 @@ export async function readBody(request, maxRequestBodySize) {
41
44
  export function key(parameters) {
42
45
  const bodyHash = Hash.sha256(parameters.body, { as: 'Hex' });
43
46
  const input = JSON.stringify([
47
+ parameters.authority,
48
+ parameters.scope,
44
49
  parameters.credential,
45
50
  parameters.method.toUpperCase(),
46
51
  parameters.target,
@@ -383,7 +383,7 @@ declare namespace MethodFn {
383
383
  description?: string | undefined;
384
384
  /** Optional challenge expiration timestamp (ISO 8601) or Date. */
385
385
  expires?: z.DatetimeInput | undefined;
386
- /** Optional server-defined correlation data serialized as `opaque`. `_mppx_nonce` is reserved for a fresh server-generated issuance nonce; clients MUST echo opaque unchanged. */
386
+ /** Optional server-defined correlation data serialized as `opaque`. `_mppx_nonce` is reserved for a fresh server-generated issuance nonce, and `_mppx_expiry_grace` marks a challenge whose method accepts some credentials after it expires; clients MUST echo opaque unchanged. */
387
387
  meta?: Record<string, string> | undefined;
388
388
  /** Optional route/resource scope bound via reserved challenge metadata. */
389
389
  scope?: string | undefined;