mppx 0.20.0 → 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.
- package/CHANGELOG.md +31 -0
- package/dist/Challenge.d.ts +59 -3
- package/dist/Challenge.js +162 -21
- package/dist/Errors.d.ts +35 -1
- package/dist/Errors.js +41 -3
- package/dist/Method.js +2 -2
- package/dist/Receipt.d.ts +2 -0
- package/dist/Receipt.js +5 -0
- package/dist/Store.d.ts +39 -10
- package/dist/Store.js +136 -29
- package/dist/cli/cli.d.ts +5 -0
- package/dist/cli/cli.js +135 -135
- package/dist/cli/plugins/index.js +12 -12
- package/dist/cli/sessions/commands.js +9 -0
- package/dist/cli/sessions/store.js +3 -2
- package/dist/cli/validate/challenge.js +15 -1
- package/dist/client/Mppx.d.ts +1 -1
- package/dist/client/Mppx.js +2 -1
- package/dist/client/internal/Fetch.d.ts +2 -1
- package/dist/client/internal/Fetch.js +43 -5
- package/dist/client/internal/PendingSettlement.d.ts +11 -0
- package/dist/client/internal/PendingSettlement.js +22 -0
- package/dist/client/internal/protocols/Mcp.js +8 -0
- package/dist/evm/client/Charge.js +7 -1
- package/dist/evm/server/Charge.d.ts +5 -0
- package/dist/evm/server/Charge.js +148 -0
- package/dist/evm/server/Methods.d.ts +8 -0
- package/dist/evm/server/Methods.js +8 -0
- package/dist/extensions/identity/attestation/Issuer.d.ts +91 -0
- package/dist/extensions/identity/attestation/Issuer.js +159 -0
- package/dist/extensions/identity/attestation/Jwks.js +3 -3
- package/dist/extensions/identity/attestation/Token.js +7 -0
- package/dist/extensions/identity/attestation/Types.d.ts +31 -3
- package/dist/extensions/identity/attestation/index.d.ts +3 -1
- package/dist/extensions/identity/attestation/index.js +3 -1
- package/dist/extensions/identity/link/server/index.js +4 -4
- package/dist/extensions/identity/persona/server/index.js +3 -3
- package/dist/extensions/identity/tempo/Constants.d.ts +4 -0
- package/dist/extensions/identity/tempo/Constants.js +4 -0
- package/dist/extensions/identity/tempo/client/index.d.ts +63 -0
- package/dist/extensions/identity/tempo/client/index.js +151 -0
- package/dist/extensions/identity/tempo/index.d.ts +1 -0
- package/dist/extensions/identity/tempo/index.js +1 -0
- package/dist/extensions/identity/tempo/issuer/index.d.ts +83 -0
- package/dist/extensions/identity/tempo/issuer/index.js +183 -0
- package/dist/internal/CredentialExpiry.d.ts +30 -0
- package/dist/internal/CredentialExpiry.js +51 -0
- package/dist/internal/version.d.ts +2 -2
- package/dist/internal/version.js +1 -1
- package/dist/mcp/client/McpClient.js +29 -10
- package/dist/middlewares/express.d.ts +7 -2
- package/dist/middlewares/express.js +20 -23
- package/dist/middlewares/internal/express.d.ts +9 -1
- package/dist/middlewares/internal/express.js +348 -2
- package/dist/proxy/Proxy.js +15 -3
- package/dist/proxy/internal/Headers.js +1 -0
- package/dist/proxy/internal/Replay.d.ts +10 -0
- package/dist/proxy/internal/Replay.js +5 -0
- package/dist/server/Mppx.d.ts +1 -1
- package/dist/server/Mppx.js +47 -15
- package/dist/server/NodeListener.js +7 -0
- package/dist/server/Request.d.ts +6 -0
- package/dist/server/Request.js +43 -22
- package/dist/server/internal/challengeMeta.d.ts +10 -0
- package/dist/server/internal/challengeMeta.js +31 -1
- package/dist/server/internal/host.d.ts +4 -0
- package/dist/server/internal/host.js +41 -0
- package/dist/tempo/client/Charge.d.ts +5 -4
- package/dist/tempo/client/Charge.js +210 -38
- package/dist/tempo/client/Subscription.js +3 -0
- package/dist/tempo/internal/zone.d.ts +8 -0
- package/dist/tempo/internal/zone.js +15 -0
- package/dist/tempo/server/Charge.d.ts +19 -0
- package/dist/tempo/server/Charge.js +60 -15
- package/dist/tempo/server/internal/html.gen.js +1 -1
- package/dist/tempo/server/internal/transport.js +10 -54
- package/dist/tempo/session/client/ChannelOps.js +1 -1
- package/dist/tempo/session/client/SessionManager.d.ts +4 -1
- package/dist/tempo/session/client/SessionManager.js +8 -2
- package/dist/tempo/session/server/CredentialVerification.js +2 -3
- package/dist/viem/Client.d.ts +2 -0
- package/dist/viem/Client.js +4 -1
- package/dist/x402/Assets.d.ts +6 -0
- package/dist/x402/Assets.js +10 -0
- package/dist/x402/Siwx.d.ts +270 -0
- package/dist/x402/Siwx.js +458 -0
- package/dist/x402/Types.d.ts +72 -12
- package/dist/x402/Types.js +18 -3
- package/dist/x402/client/Exact.js +4 -1
- package/dist/x402/index.d.ts +1 -0
- package/dist/x402/index.js +1 -0
- package/dist/x402/middlewares/express.js +10 -1
- package/dist/x402/server/EvmCharge.d.ts +27 -3
- package/dist/x402/server/EvmCharge.js +27 -2
- package/dist/x402/server/Facilitator.d.ts +42 -3
- package/dist/x402/server/Facilitator.js +126 -16
- package/package.json +1 -1
|
@@ -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:
|
|
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
|
package/dist/proxy/Proxy.js
CHANGED
|
@@ -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 =
|
|
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
|
|
@@ -20,6 +20,7 @@ const paymentHeaders = new Set([
|
|
|
20
20
|
'payment-session',
|
|
21
21
|
'payment-session-snapshot',
|
|
22
22
|
'payment-signature',
|
|
23
|
+
'sign-in-with-x',
|
|
23
24
|
'www-authenticate',
|
|
24
25
|
]);
|
|
25
26
|
/** Strips hop-by-hop, auth, identity, encoding, cookie, and forwarding headers from a request before proxying upstream. */
|
|
@@ -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,
|
package/dist/server/Mppx.d.ts
CHANGED
|
@@ -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;
|
package/dist/server/Mppx.js
CHANGED
|
@@ -7,11 +7,13 @@ import * as Expires from '../Expires.js';
|
|
|
7
7
|
import * as IdentityRequirements from '../identity/internal/Requirements.js';
|
|
8
8
|
import * as IdentityServer from '../identity/Server.js';
|
|
9
9
|
import * as AcceptPayment from '../internal/AcceptPayment.js';
|
|
10
|
+
import * as CredentialExpiry from '../internal/CredentialExpiry.js';
|
|
10
11
|
import * as Env from '../internal/env.js';
|
|
11
12
|
import { warnOnce } from '../internal/warnOnce.js';
|
|
12
13
|
import * as Mcp from '../Mcp.js';
|
|
13
14
|
import * as PaymentRequest from '../PaymentRequest.js';
|
|
14
15
|
import * as x402_Header from '../x402/Header.js';
|
|
16
|
+
import * as x402_Siwx from '../x402/Siwx.js';
|
|
15
17
|
import * as x402_Types from '../x402/Types.js';
|
|
16
18
|
import * as z from '../zod.js';
|
|
17
19
|
import * as ChallengeMeta from './internal/challengeMeta.js';
|
|
@@ -208,14 +210,6 @@ export function create(config) {
|
|
|
208
210
|
reason: 'challenge was not issued by this server',
|
|
209
211
|
}));
|
|
210
212
|
}
|
|
211
|
-
try {
|
|
212
|
-
Expires.assert(credential.challenge.expires, credential.challenge.id);
|
|
213
|
-
}
|
|
214
|
-
catch (e) {
|
|
215
|
-
if (e instanceof Errors.PaymentError)
|
|
216
|
-
await fail(e);
|
|
217
|
-
throw e;
|
|
218
|
-
}
|
|
219
213
|
if (methodCandidates.length > 1) {
|
|
220
214
|
const matches = [
|
|
221
215
|
...new Set(methodCandidates.filter((candidate) => matchesStandaloneMethod(candidate, credential.challenge.request, options?.request))),
|
|
@@ -229,6 +223,16 @@ export function create(config) {
|
|
|
229
223
|
}));
|
|
230
224
|
mi = matches[0];
|
|
231
225
|
}
|
|
226
|
+
// Checked against the method that matched: only it knows how long after expiry it accepts
|
|
227
|
+
// the credential.
|
|
228
|
+
try {
|
|
229
|
+
CredentialExpiry.assertFor(mi, credential);
|
|
230
|
+
}
|
|
231
|
+
catch (e) {
|
|
232
|
+
if (e instanceof Errors.PaymentError)
|
|
233
|
+
await fail(e);
|
|
234
|
+
throw e;
|
|
235
|
+
}
|
|
232
236
|
if (parameters.requireValidate && !mi.validate)
|
|
233
237
|
await fail(new Errors.VerificationFailedError({
|
|
234
238
|
details: { intent: credIntent, method: credMethod },
|
|
@@ -871,7 +875,7 @@ function createMethodFn(parameters) {
|
|
|
871
875
|
}
|
|
872
876
|
// Reject credentials without expires (fail-closed) or with expired timestamp
|
|
873
877
|
try {
|
|
874
|
-
|
|
878
|
+
CredentialExpiry.assertFor(method, credential);
|
|
875
879
|
}
|
|
876
880
|
catch (error) {
|
|
877
881
|
await emitPaymentFailed({
|
|
@@ -1379,7 +1383,7 @@ async function resolveRouteChallenge(parameters) {
|
|
|
1379
1383
|
description: parameters.description,
|
|
1380
1384
|
expires: parameters.expires,
|
|
1381
1385
|
header: parameters.header,
|
|
1382
|
-
meta: ChallengeMeta.withNonce(parameters.meta),
|
|
1386
|
+
meta: ChallengeMeta.withNonce(CredentialExpiry.issuanceMeta(parameters.method, parameters.meta)),
|
|
1383
1387
|
realm: effectiveRealm,
|
|
1384
1388
|
request: request,
|
|
1385
1389
|
secretKey: parameters.secretKey,
|
|
@@ -1395,7 +1399,7 @@ function createFallbackChallenge(parameters) {
|
|
|
1395
1399
|
description: parameters.description,
|
|
1396
1400
|
expires: parameters.expires,
|
|
1397
1401
|
header: parameters.header,
|
|
1398
|
-
meta: ChallengeMeta.withNonce(parameters.meta),
|
|
1402
|
+
meta: ChallengeMeta.withNonce(CredentialExpiry.issuanceMeta(parameters.method, parameters.meta)),
|
|
1399
1403
|
realm: parameters.realm ??
|
|
1400
1404
|
(parameters.capturedRequest
|
|
1401
1405
|
? resolveRealmFromCapturedRequest(parameters.capturedRequest)
|
|
@@ -2200,7 +2204,7 @@ function mergeX402PaymentRequiredHeaders(values) {
|
|
|
2200
2204
|
if (!first)
|
|
2201
2205
|
throw new Error('Expected at least one x402 payment-required header.');
|
|
2202
2206
|
const incompatible = rest.some((value) => !isDeepStrictEqual(value.resource, first.resource) ||
|
|
2203
|
-
!isDeepStrictEqual(value.extensions, first.extensions));
|
|
2207
|
+
!isDeepStrictEqual(withoutSiwx(value.extensions), withoutSiwx(first.extensions)));
|
|
2204
2208
|
if (incompatible)
|
|
2205
2209
|
return [
|
|
2206
2210
|
x402_Header.encodePaymentRequired({
|
|
@@ -2213,14 +2217,40 @@ function mergeX402PaymentRequiredHeaders(values) {
|
|
|
2213
2217
|
const error = [first.error, ...rest.map((value) => value.error)]
|
|
2214
2218
|
.filter((value) => value !== undefined && value.length > 0)
|
|
2215
2219
|
.join('; ');
|
|
2220
|
+
const siwx = mergeSiwx([first, ...rest]);
|
|
2216
2221
|
return [
|
|
2217
2222
|
x402_Header.encodePaymentRequired({
|
|
2218
2223
|
...first,
|
|
2219
2224
|
accepts: [first.accepts, ...rest.map((value) => value.accepts)].flat(),
|
|
2225
|
+
...(siwx ? { extensions: { ...first.extensions, [x402_Siwx.extensionKey]: siwx } } : {}),
|
|
2220
2226
|
...(error ? { error } : {}),
|
|
2221
2227
|
}),
|
|
2222
2228
|
];
|
|
2223
2229
|
}
|
|
2230
|
+
/**
|
|
2231
|
+
* Each SIWX offer carries its own nonce, so offers differ only in that and their chains.
|
|
2232
|
+
* Nonces aren't tied to the offer that issued them, so one challenge listing every
|
|
2233
|
+
* offer's chains serves all of them.
|
|
2234
|
+
*/
|
|
2235
|
+
function mergeSiwx(values) {
|
|
2236
|
+
const extensions = values
|
|
2237
|
+
.map((value) => x402_Siwx.fromPaymentRequired(value))
|
|
2238
|
+
.filter((value) => value !== undefined);
|
|
2239
|
+
const [first] = extensions;
|
|
2240
|
+
if (!first)
|
|
2241
|
+
return undefined;
|
|
2242
|
+
const chains = new Map();
|
|
2243
|
+
for (const extension of extensions)
|
|
2244
|
+
for (const chain of extension.supportedChains)
|
|
2245
|
+
chains.set(`${chain.chainId}:${chain.type}`, chain);
|
|
2246
|
+
return { ...first, supportedChains: [...chains.values()] };
|
|
2247
|
+
}
|
|
2248
|
+
function withoutSiwx(extensions) {
|
|
2249
|
+
if (!extensions)
|
|
2250
|
+
return extensions;
|
|
2251
|
+
const { [x402_Siwx.extensionKey]: _, ...rest } = extensions;
|
|
2252
|
+
return rest;
|
|
2253
|
+
}
|
|
2224
2254
|
export function toNodeListener(handler, options) {
|
|
2225
2255
|
return async (req, res) => {
|
|
2226
2256
|
let result;
|
|
@@ -2230,10 +2260,12 @@ export function toNodeListener(handler, options) {
|
|
|
2230
2260
|
result = await handler(request);
|
|
2231
2261
|
}
|
|
2232
2262
|
catch (error) {
|
|
2233
|
-
if (!(error instanceof Request.RequestBodyTooLargeError)
|
|
2263
|
+
if (!(error instanceof Request.RequestBodyTooLargeError) &&
|
|
2264
|
+
!(error instanceof Request.UntrustedHostError))
|
|
2234
2265
|
throw error;
|
|
2235
|
-
const
|
|
2236
|
-
|
|
2266
|
+
const untrusted = error instanceof Request.UntrustedHostError;
|
|
2267
|
+
const response = new globalThis.Response(untrusted ? 'Misdirected Request' : 'Payload Too Large', {
|
|
2268
|
+
status: untrusted ? 421 : 413,
|
|
2237
2269
|
headers: { 'Content-Type': 'text/plain' },
|
|
2238
2270
|
});
|
|
2239
2271
|
await NodeListener.sendResponse(res, response);
|
|
@@ -58,6 +58,11 @@ export async function sendResponse(res, response) {
|
|
|
58
58
|
}
|
|
59
59
|
}
|
|
60
60
|
}
|
|
61
|
+
catch (error) {
|
|
62
|
+
await reader.cancel(error).catch(() => { });
|
|
63
|
+
if (!connectionClosed && !isResponseClosed(res))
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
61
66
|
finally {
|
|
62
67
|
res.removeListener('close', onClose);
|
|
63
68
|
reader.releaseLock();
|
|
@@ -87,6 +92,8 @@ function waitForDrain(res) {
|
|
|
87
92
|
res.removeListener('error', onError);
|
|
88
93
|
};
|
|
89
94
|
const onDrain = () => {
|
|
95
|
+
if (res.writableNeedDrain)
|
|
96
|
+
return;
|
|
90
97
|
cleanup();
|
|
91
98
|
resolve(true);
|
|
92
99
|
};
|
package/dist/server/Request.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { IncomingMessage, RequestListener, ServerResponse } from 'node:http';
|
|
2
2
|
export type FetchHandler = (request: Request) => Promise<Response> | Response;
|
|
3
3
|
export type RequestListenerOptions = {
|
|
4
|
+
/** 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. Validate at trusted ingress too; forwarded hosts are not trusted. */
|
|
5
|
+
allowedHosts?: readonly string[] | undefined;
|
|
4
6
|
host?: string | undefined;
|
|
5
7
|
/** Maximum accepted request body size in bytes. @default 10485760 (10 MiB) */
|
|
6
8
|
maxBodySize?: number | undefined;
|
|
@@ -9,6 +11,10 @@ export type RequestListenerOptions = {
|
|
|
9
11
|
};
|
|
10
12
|
/** Options used only while converting a Node request to a Fetch request. */
|
|
11
13
|
export type NodeConversionOptions = Omit<RequestListenerOptions, 'onError'>;
|
|
14
|
+
/** Raised when the incoming Host is outside the configured allowlist. */
|
|
15
|
+
export declare class UntrustedHostError extends Error {
|
|
16
|
+
readonly name = "UntrustedHostError";
|
|
17
|
+
}
|
|
12
18
|
/** Raised when a Node request body exceeds the configured byte limit. */
|
|
13
19
|
export declare class RequestBodyTooLargeError extends Error {
|
|
14
20
|
readonly name = "RequestBodyTooLargeError";
|