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.
Files changed (97) hide show
  1. package/CHANGELOG.md +31 -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 +148 -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/Issuer.d.ts +91 -0
  30. package/dist/extensions/identity/attestation/Issuer.js +159 -0
  31. package/dist/extensions/identity/attestation/Jwks.js +3 -3
  32. package/dist/extensions/identity/attestation/Token.js +7 -0
  33. package/dist/extensions/identity/attestation/Types.d.ts +31 -3
  34. package/dist/extensions/identity/attestation/index.d.ts +3 -1
  35. package/dist/extensions/identity/attestation/index.js +3 -1
  36. package/dist/extensions/identity/link/server/index.js +4 -4
  37. package/dist/extensions/identity/persona/server/index.js +3 -3
  38. package/dist/extensions/identity/tempo/Constants.d.ts +4 -0
  39. package/dist/extensions/identity/tempo/Constants.js +4 -0
  40. package/dist/extensions/identity/tempo/client/index.d.ts +63 -0
  41. package/dist/extensions/identity/tempo/client/index.js +151 -0
  42. package/dist/extensions/identity/tempo/index.d.ts +1 -0
  43. package/dist/extensions/identity/tempo/index.js +1 -0
  44. package/dist/extensions/identity/tempo/issuer/index.d.ts +83 -0
  45. package/dist/extensions/identity/tempo/issuer/index.js +183 -0
  46. package/dist/internal/CredentialExpiry.d.ts +30 -0
  47. package/dist/internal/CredentialExpiry.js +51 -0
  48. package/dist/internal/version.d.ts +2 -2
  49. package/dist/internal/version.js +1 -1
  50. package/dist/mcp/client/McpClient.js +29 -10
  51. package/dist/middlewares/express.d.ts +7 -2
  52. package/dist/middlewares/express.js +20 -23
  53. package/dist/middlewares/internal/express.d.ts +9 -1
  54. package/dist/middlewares/internal/express.js +348 -2
  55. package/dist/proxy/Proxy.js +15 -3
  56. package/dist/proxy/internal/Headers.js +1 -0
  57. package/dist/proxy/internal/Replay.d.ts +10 -0
  58. package/dist/proxy/internal/Replay.js +5 -0
  59. package/dist/server/Mppx.d.ts +1 -1
  60. package/dist/server/Mppx.js +47 -15
  61. package/dist/server/NodeListener.js +7 -0
  62. package/dist/server/Request.d.ts +6 -0
  63. package/dist/server/Request.js +43 -22
  64. package/dist/server/internal/challengeMeta.d.ts +10 -0
  65. package/dist/server/internal/challengeMeta.js +31 -1
  66. package/dist/server/internal/host.d.ts +4 -0
  67. package/dist/server/internal/host.js +41 -0
  68. package/dist/tempo/client/Charge.d.ts +5 -4
  69. package/dist/tempo/client/Charge.js +210 -38
  70. package/dist/tempo/client/Subscription.js +3 -0
  71. package/dist/tempo/internal/zone.d.ts +8 -0
  72. package/dist/tempo/internal/zone.js +15 -0
  73. package/dist/tempo/server/Charge.d.ts +19 -0
  74. package/dist/tempo/server/Charge.js +60 -15
  75. package/dist/tempo/server/internal/html.gen.js +1 -1
  76. package/dist/tempo/server/internal/transport.js +10 -54
  77. package/dist/tempo/session/client/ChannelOps.js +1 -1
  78. package/dist/tempo/session/client/SessionManager.d.ts +4 -1
  79. package/dist/tempo/session/client/SessionManager.js +8 -2
  80. package/dist/tempo/session/server/CredentialVerification.js +2 -3
  81. package/dist/viem/Client.d.ts +2 -0
  82. package/dist/viem/Client.js +4 -1
  83. package/dist/x402/Assets.d.ts +6 -0
  84. package/dist/x402/Assets.js +10 -0
  85. package/dist/x402/Siwx.d.ts +270 -0
  86. package/dist/x402/Siwx.js +458 -0
  87. package/dist/x402/Types.d.ts +72 -12
  88. package/dist/x402/Types.js +18 -3
  89. package/dist/x402/client/Exact.js +4 -1
  90. package/dist/x402/index.d.ts +1 -0
  91. package/dist/x402/index.js +1 -0
  92. package/dist/x402/middlewares/express.js +10 -1
  93. package/dist/x402/server/EvmCharge.d.ts +27 -3
  94. package/dist/x402/server/EvmCharge.js +27 -2
  95. package/dist/x402/server/Facilitator.d.ts +42 -3
  96. package/dist/x402/server/Facilitator.js +126 -16
  97. package/package.json +1 -1
@@ -0,0 +1,458 @@
1
+ import { Base64, Bytes, Hex } from 'ox';
2
+ import { getAddress, recoverMessageAddress } from 'viem';
3
+ import { getChainId, verifyMessage } from 'viem/actions';
4
+ import { createSiweMessage } from 'viem/siwe';
5
+ import * as Store from '../Store.js';
6
+ import * as z from '../zod.js';
7
+ import * as Types from './Types.js';
8
+ /** Key of the x402 `sign-in-with-x` (SIWX) extension in a 402's `extensions`. */
9
+ export const extensionKey = 'sign-in-with-x';
10
+ /** Request header that carries a signed SIWX proof as base64-encoded JSON. */
11
+ export const header = 'SIGN-IN-WITH-X';
12
+ /** How long a SIWX challenge stays valid, in milliseconds. */
13
+ export const ttl = 5 * 60 * 1000;
14
+ /** A signing method a server accepts. */
15
+ export const ChainSchema = z.object({
16
+ chainId: z.string(),
17
+ signatureScheme: z.optional(z.string()),
18
+ type: z.string(),
19
+ });
20
+ /** Message fields a server declares in its 402. */
21
+ export const InfoSchema = z.object({
22
+ domain: z.string(),
23
+ expirationTime: z.optional(z.string()),
24
+ issuedAt: z.string(),
25
+ nonce: z.string(),
26
+ notBefore: z.optional(z.string()),
27
+ requestId: z.optional(z.string()),
28
+ resources: z.optional(z.array(z.string())),
29
+ statement: z.optional(z.string()),
30
+ uri: z.string(),
31
+ version: z.string(),
32
+ });
33
+ /** The extension's value in a 402's `extensions`. */
34
+ export const ExtensionSchema = z.object({
35
+ info: InfoSchema,
36
+ schema: z.record(z.string(), z.unknown()),
37
+ supportedChains: z.array(ChainSchema),
38
+ });
39
+ /** The signed proof a client sends in the {@link header}. */
40
+ export const PayloadSchema = z.object({
41
+ ...InfoSchema.shape,
42
+ address: z.string(),
43
+ chainId: z.string(),
44
+ signature: z.string(),
45
+ signatureScheme: z.optional(z.string()),
46
+ type: z.string(),
47
+ });
48
+ /** JSON Schema of a {@link Payload}, advertised in the 402 as the spec requires. */
49
+ export const payloadJsonSchema = {
50
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
51
+ properties: {
52
+ address: { type: 'string' },
53
+ chainId: { type: 'string' },
54
+ domain: { type: 'string' },
55
+ expirationTime: { format: 'date-time', type: 'string' },
56
+ issuedAt: { format: 'date-time', type: 'string' },
57
+ nonce: { type: 'string' },
58
+ notBefore: { format: 'date-time', type: 'string' },
59
+ requestId: { type: 'string' },
60
+ resources: { items: { format: 'uri', type: 'string' }, type: 'array' },
61
+ signature: { type: 'string' },
62
+ statement: { type: 'string' },
63
+ type: { type: 'string' },
64
+ uri: { format: 'uri', type: 'string' },
65
+ version: { type: 'string' },
66
+ },
67
+ required: [
68
+ 'domain',
69
+ 'address',
70
+ 'uri',
71
+ 'version',
72
+ 'chainId',
73
+ 'type',
74
+ 'nonce',
75
+ 'issuedAt',
76
+ 'signature',
77
+ ],
78
+ type: 'object',
79
+ };
80
+ /** Error for a proof the server rejects. Its message is the spec's {@link ErrorCode}. */
81
+ export class InvalidProofError extends Error {
82
+ name = 'Siwx.InvalidProofError';
83
+ /** The spec's machine-readable code for the failed check. */
84
+ code;
85
+ constructor(code) {
86
+ super(code);
87
+ this.code = code;
88
+ }
89
+ }
90
+ /**
91
+ * Builds the EIP-4361 (SIWE) message a payload signs.
92
+ *
93
+ * The layout is viem's `createSiweMessage`, which also validates the fields, but timestamps
94
+ * are signed exactly as the payload carries them, as the x402 reference does, so a proof
95
+ * with any RFC 3339 timestamp verifies across implementations.
96
+ */
97
+ export function toMessage(payload) {
98
+ const issuedAt = timestamp(payload.issuedAt, 'issuedAt');
99
+ const expirationTime = payload.expirationTime
100
+ ? timestamp(payload.expirationTime, 'expirationTime')
101
+ : undefined;
102
+ const notBefore = payload.notBefore ? timestamp(payload.notBefore, 'notBefore') : undefined;
103
+ const address = getAddress(payload.address);
104
+ const chainId = chainIdOf(payload.chainId);
105
+ // Throws for a field the SIWE format rejects.
106
+ createSiweMessage({
107
+ address,
108
+ chainId,
109
+ domain: payload.domain,
110
+ ...(expirationTime ? { expirationTime: new Date(expirationTime) } : {}),
111
+ issuedAt: new Date(issuedAt),
112
+ nonce: payload.nonce,
113
+ ...(notBefore ? { notBefore: new Date(notBefore) } : {}),
114
+ ...(payload.requestId ? { requestId: payload.requestId } : {}),
115
+ ...(payload.resources ? { resources: payload.resources } : {}),
116
+ ...(payload.statement ? { statement: payload.statement } : {}),
117
+ uri: payload.uri,
118
+ version: '1',
119
+ });
120
+ if (payload.requestId?.includes('\n'))
121
+ throw new Error('Invalid SIWE message field requestId');
122
+ let prefix = `${payload.domain} wants you to sign in with your Ethereum account:\n${address}\n\n`;
123
+ if (payload.statement)
124
+ prefix += `${payload.statement}\n`;
125
+ const lines = [
126
+ `URI: ${payload.uri}`,
127
+ 'Version: 1',
128
+ `Chain ID: ${chainId}`,
129
+ `Nonce: ${payload.nonce}`,
130
+ `Issued At: ${issuedAt}`,
131
+ ];
132
+ if (expirationTime)
133
+ lines.push(`Expiration Time: ${expirationTime}`);
134
+ if (notBefore)
135
+ lines.push(`Not Before: ${notBefore}`);
136
+ if (payload.requestId)
137
+ lines.push(`Request ID: ${payload.requestId}`);
138
+ if (payload.resources) {
139
+ lines.push('Resources:');
140
+ for (const resource of payload.resources)
141
+ lines.push(`- ${resource}`);
142
+ }
143
+ return `${prefix}\n${lines.join('\n')}`;
144
+ }
145
+ /** An RFC 3339 date-time, as SIWE timestamps are. */
146
+ const timestampPattern = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;
147
+ function timestamp(value, field) {
148
+ if (!timestampPattern.test(value) || Number.isNaN(Date.parse(value)))
149
+ throw new Error(`Invalid SIWE message field ${field}`);
150
+ return value;
151
+ }
152
+ /** Encodes a payload as a {@link header} value. */
153
+ export function encode(payload) {
154
+ return Base64.fromString(JSON.stringify(payload));
155
+ }
156
+ /** Decodes a {@link header} value. Throws {@link InvalidProofError} when it is malformed. */
157
+ export function decode(value) {
158
+ try {
159
+ return PayloadSchema.parse(JSON.parse(Base64.toString(value)));
160
+ }
161
+ catch {
162
+ throw new InvalidProofError('invalid_siwx_payload');
163
+ }
164
+ }
165
+ /** Reads the SIWX extension from a decoded x402 402 body, if it offers one. */
166
+ export function fromPaymentRequired(paymentRequired) {
167
+ const result = ExtensionSchema.safeParse(paymentRequired.extensions?.[extensionKey]);
168
+ return result.success ? result.data : undefined;
169
+ }
170
+ /** Builds the extension a server adds to a 402, with a fresh nonce. */
171
+ export function createExtension(parameters) {
172
+ const { chainId, url } = parameters;
173
+ const origin = new URL(parameters.origin);
174
+ const now = Date.now();
175
+ return {
176
+ info: {
177
+ domain: origin.host,
178
+ expirationTime: new Date(now + ttl).toISOString(),
179
+ issuedAt: new Date(now).toISOString(),
180
+ nonce: Hex.fromBytes(Bytes.random(16)).slice(2),
181
+ uri: origin.origin + siweSafe(new URL(url).pathname + new URL(url).search),
182
+ version: '1',
183
+ },
184
+ schema: payloadJsonSchema,
185
+ supportedChains: [{ chainId: `eip155:${chainId}`, type: 'eip191' }],
186
+ };
187
+ }
188
+ /**
189
+ * Percent-encodes the characters a URL's path and query may keep (such as `|`, `{` or
190
+ * `^`) that an RFC 3986 URI, and so a SIWE message's `URI`, can't hold, including a `%`
191
+ * that doesn't start a valid percent escape.
192
+ */
193
+ function siweSafe(pathAndQuery) {
194
+ return pathAndQuery.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@/?%]|%(?![0-9A-Fa-f]{2})/g, (char) => Array.from(new TextEncoder().encode(char), (byte) => `%${byte.toString(16).toUpperCase().padStart(2, '0')}`).join(''));
195
+ }
196
+ /**
197
+ * Verifies a SIWX proof against the server's origin and chain. It does not record the
198
+ * nonce: call {@link claim} once the proof is used, so a check that declines the wallet
199
+ * leaves the proof for another.
200
+ * Throws {@link InvalidProofError} with the spec's code when the proof is rejected.
201
+ */
202
+ export async function verify(parameters) {
203
+ const { options, payload } = parameters;
204
+ const origin = new URL(options.origin);
205
+ const now = Date.now();
206
+ if (payload.domain !== origin.host)
207
+ throw new InvalidProofError('invalid_siwx_domain_mismatch');
208
+ if (originOf(payload.uri) !== origin.origin)
209
+ throw new InvalidProofError('invalid_siwx_uri_mismatch');
210
+ const issuedAt = Date.parse(payload.issuedAt);
211
+ if (Number.isNaN(issuedAt))
212
+ throw new InvalidProofError('invalid_siwx_issued_at');
213
+ if (issuedAt > now + clockSkew)
214
+ throw new InvalidProofError('invalid_siwx_issued_at_in_future');
215
+ if (now - issuedAt > ttl)
216
+ throw new InvalidProofError('invalid_siwx_issued_at_too_old');
217
+ if (payload.expirationTime !== undefined) {
218
+ const expires = Date.parse(payload.expirationTime);
219
+ if (Number.isNaN(expires))
220
+ throw new InvalidProofError('invalid_siwx_expiration_time');
221
+ if (expires <= now)
222
+ throw new InvalidProofError('invalid_siwx_expired');
223
+ }
224
+ if (payload.notBefore !== undefined) {
225
+ const notBefore = Date.parse(payload.notBefore);
226
+ if (Number.isNaN(notBefore))
227
+ throw new InvalidProofError('invalid_siwx_not_before');
228
+ if (notBefore > now)
229
+ throw new InvalidProofError('invalid_siwx_not_yet_valid');
230
+ }
231
+ if (!payload.chainId.startsWith('eip155:'))
232
+ throw new InvalidProofError('invalid_siwx_unsupported_chain');
233
+ const chainId = chainIdOf(payload.chainId);
234
+ if (chainId !== parameters.chainId)
235
+ throw new InvalidProofError('invalid_siwx_unsupported_chain');
236
+ // EIP-4361 nonces are at least 8 alphanumeric characters.
237
+ if (!/^[a-zA-Z0-9]{8,}$/.test(payload.nonce))
238
+ throw new InvalidProofError('invalid_siwx_nonce');
239
+ let address;
240
+ try {
241
+ address = getAddress(payload.address);
242
+ }
243
+ catch {
244
+ throw new InvalidProofError('invalid_siwx_payload');
245
+ }
246
+ if (!/^0x[0-9a-fA-F]+$/.test(payload.signature))
247
+ throw new InvalidProofError('invalid_siwx_signature');
248
+ const signature = payload.signature;
249
+ let message;
250
+ try {
251
+ message = toMessage(payload);
252
+ }
253
+ catch {
254
+ // A field the SIWE format rejects, such as a statement with a newline or an invalid URI.
255
+ throw new InvalidProofError('invalid_siwx_payload');
256
+ }
257
+ // A smart-wallet signature is checked against contract state, so it must be the state of
258
+ // the chain the proof names.
259
+ if (options.client) {
260
+ let clientChainId;
261
+ try {
262
+ clientChainId = options.client.chain?.id ?? (await getChainId(options.client));
263
+ }
264
+ catch {
265
+ throw new InvalidProofError('invalid_siwx_verifier_error');
266
+ }
267
+ if (clientChainId !== chainId)
268
+ throw new InvalidProofError('invalid_siwx_verifier_error');
269
+ }
270
+ let valid;
271
+ try {
272
+ valid = options.client
273
+ ? await verifyMessage(options.client, { address, message, signature })
274
+ : getAddress(await recoverMessageAddress({ message, signature })) === address;
275
+ }
276
+ catch {
277
+ if (options.client)
278
+ throw new InvalidProofError('invalid_siwx_verifier_error');
279
+ valid = false;
280
+ }
281
+ if (!valid)
282
+ throw new InvalidProofError('invalid_siwx_signature');
283
+ return { address, chainId };
284
+ }
285
+ /**
286
+ * Records a verified proof's nonce so it is accepted once.
287
+ * Throws {@link InvalidProofError} with `invalid_siwx_nonce` when it was already used.
288
+ */
289
+ export async function claim(parameters) {
290
+ const { payload, store } = parameters;
291
+ const claimed = await Store.tryClaim(store, nonceKey(payload), claimExpires(payload));
292
+ if (!claimed)
293
+ throw new InvalidProofError('invalid_siwx_nonce');
294
+ }
295
+ /**
296
+ * Releases a nonce {@link claim} recorded, so the proof can be accepted again. Call it
297
+ * only for a claim this request made, such as when `grant` declines the wallet.
298
+ * Does nothing once that claim has expired, since another request may hold the nonce by then.
299
+ */
300
+ export async function release(parameters) {
301
+ const { payload, store } = parameters;
302
+ // Until this request's claim expires nobody else can claim the nonce, so the stored marker
303
+ // is still this request's own. Close to expiry the claim is left to lapse instead. `delete`
304
+ // (not `update`) is what frees a native claim, such as one in a Durable Object replay shard.
305
+ if (Date.now() + releaseMargin >= claimExpires(payload))
306
+ return;
307
+ await store.delete(nonceKey(payload));
308
+ }
309
+ /** How long before a claim expires {@link release} stops deleting it. */
310
+ const releaseMargin = 5_000;
311
+ function nonceKey(payload) {
312
+ return `mppx:x402:siwx:${payload.nonce}`;
313
+ }
314
+ function claimExpires(payload) {
315
+ return Date.parse(payload.issuedAt) + ttl + clockSkew;
316
+ }
317
+ /**
318
+ * Wraps `fetch` so a 402 that offers SIWX is answered once with a proof signed by
319
+ * `account`, before any payment. Pass the result as the `fetch` of an mppx client:
320
+ * when the server still answers 402 because it doesn't grant this wallet, mppx pays
321
+ * from that response as usual.
322
+ *
323
+ * It signs only when the challenge's `domain` and `uri` origin match the URL that
324
+ * returned the 402, and only for `eip155` chains.
325
+ *
326
+ * @example
327
+ * ```ts
328
+ * import { Fetch, evm } from 'mppx/client'
329
+ * import { Siwx } from 'mppx/x402'
330
+ *
331
+ * const fetch = Fetch.from({
332
+ * fetch: Siwx.wrapFetch(globalThis.fetch, { account }),
333
+ * methods: [evm({ account })],
334
+ * })
335
+ * ```
336
+ */
337
+ export function wrapFetch(fetch, parameters) {
338
+ const { account } = parameters;
339
+ return async (input, init) => {
340
+ // A streamed upload can't be sent again without holding all of it in memory, so it
341
+ // passes through untouched and a 402 for it is paid as usual.
342
+ if (isStreamed(input, init))
343
+ return fetch(input, init);
344
+ const request = new Request(input, init);
345
+ // Keep a copy so a request body can be sent again with the proof.
346
+ const retry = request.clone();
347
+ // A Request drops init's symbol-keyed controls, such as mppx's payment opt-out, so
348
+ // they are passed along beside it on every call.
349
+ const controls = symbolControls(init);
350
+ const response = await fetch(request, controls);
351
+ if (response.status !== 402 ||
352
+ request.headers.has(header) ||
353
+ carriesPayment(request.headers) ||
354
+ carriesSingleUseProof(request.headers) ||
355
+ // A 402 reached through a redirect is left to payment: the retry goes to the requested
356
+ // URL without following redirects, and would send a redirected POST's body again.
357
+ response.redirected ||
358
+ !account.signMessage)
359
+ return response;
360
+ const value = response.headers.get(Types.paymentRequiredHeader);
361
+ if (!value)
362
+ return response;
363
+ let extension;
364
+ try {
365
+ extension = fromPaymentRequired(JSON.parse(Base64.toString(value)));
366
+ }
367
+ catch {
368
+ return response;
369
+ }
370
+ if (!extension)
371
+ return response;
372
+ const chain = extension.supportedChains.find((entry) => entry.chainId.startsWith('eip155:') && entry.type === 'eip191');
373
+ if (!chain)
374
+ return response;
375
+ // A challenge naming another site must never get this wallet's signature. The retry
376
+ // goes to the requested URL, so a challenge reached through a cross-origin redirect
377
+ // is refused too: signing it would hand the redirecting site the proof.
378
+ const target = new URL(request.url);
379
+ if (response.url && new URL(response.url).origin !== target.origin)
380
+ return response;
381
+ if (extension.info.domain !== target.host || originOf(extension.info.uri) !== target.origin)
382
+ return response;
383
+ const unsigned = {
384
+ ...extension.info,
385
+ address: account.address,
386
+ chainId: chain.chainId,
387
+ type: chain.type,
388
+ ...(chain.signatureScheme ? { signatureScheme: chain.signatureScheme } : {}),
389
+ };
390
+ let message;
391
+ try {
392
+ message = toMessage(unsigned);
393
+ }
394
+ catch {
395
+ // A challenge the SIWE format can't encode can't be signed: leave the 402 to payment.
396
+ return response;
397
+ }
398
+ const signature = await account.signMessage({ message });
399
+ // Not awaited: a fetch that kept a clone of the response would hold the cancel open.
400
+ response.body?.cancel().catch(() => { });
401
+ const headers = new Headers(retry.headers);
402
+ headers.set(header, encode({ ...unsigned, signature }));
403
+ // Redirects aren't followed, so no redirect can carry the proof to another site.
404
+ return fetch(new Request(retry, { headers, redirect: 'manual' }), controls);
405
+ };
406
+ }
407
+ /** The symbol-keyed entries of a fetch `init`, which a `Request` doesn't keep. */
408
+ function symbolControls(init) {
409
+ if (!init)
410
+ return undefined;
411
+ const symbols = Object.getOwnPropertySymbols(init);
412
+ if (symbols.length === 0)
413
+ return undefined;
414
+ const controls = {};
415
+ for (const symbol of symbols)
416
+ controls[symbol] = init[symbol];
417
+ return controls;
418
+ }
419
+ /**
420
+ * Whether a request already carries a payment credential. Its 402 means the payment was
421
+ * refused, so it is returned as is rather than sending the same credential again with a proof.
422
+ */
423
+ function carriesPayment(headers) {
424
+ if (headers.has(Types.paymentSignatureHeader) || headers.has(Types.legacyPaymentSignatureHeader))
425
+ return true;
426
+ return /^payment\s/i.test(headers.get('authorization') ?? '');
427
+ }
428
+ /**
429
+ * Whether a request carries an identity proof bound to a single send, such as an HTTP message
430
+ * signature (Web Bot Auth, TAP) or a DPoP proof. Resending it with a SIWX proof would be
431
+ * refused as a replay, so its 402 is returned as is and the caller's own retry signs afresh.
432
+ */
433
+ function carriesSingleUseProof(headers) {
434
+ return headers.has('signature-input') || headers.has('dpop');
435
+ }
436
+ /** Tolerance for client clocks that run slightly ahead of the server. */
437
+ const clockSkew = 60 * 1000;
438
+ function chainIdOf(value) {
439
+ const match = /^eip155:(\d+)$/.exec(value);
440
+ if (!match)
441
+ throw new InvalidProofError('invalid_siwx_chain_id');
442
+ return Number(match[1]);
443
+ }
444
+ /** Whether a request's body is a stream, rather than a value that can be sent again. */
445
+ function isStreamed(input, init) {
446
+ if (init?.body !== undefined && init.body !== null)
447
+ return init.body instanceof ReadableStream;
448
+ return input instanceof Request && input.body !== null;
449
+ }
450
+ function originOf(value) {
451
+ try {
452
+ return new URL(value).origin;
453
+ }
454
+ catch {
455
+ return undefined;
456
+ }
457
+ }
458
+ //# sourceMappingURL=Siwx.js.map
@@ -85,14 +85,14 @@ export type PaymentRequirements = z.infer<typeof PaymentRequirementsSchema>;
85
85
  export declare const ExtensionSchema: z.ZodMiniObject<{
86
86
  info: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>;
87
87
  schema: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>;
88
- }, z.core.$strip>;
88
+ }, z.core.$loose>;
89
89
  /** x402 v2 protocol extension value. */
90
90
  export type Extension = z.infer<typeof ExtensionSchema>;
91
91
  /** x402 v2 protocol extensions map. */
92
92
  export declare const ExtensionsSchema: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniObject<{
93
93
  info: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>;
94
94
  schema: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>;
95
- }, z.core.$strip>>;
95
+ }, z.core.$loose>>;
96
96
  /** x402 v2 protocol extensions map. */
97
97
  export type Extensions = z.infer<typeof ExtensionsSchema>;
98
98
  /** Public exact EVM route request accepted by `mppx` handlers. */
@@ -117,7 +117,7 @@ export declare const PaymentRequiredSchema: z.ZodMiniObject<{
117
117
  extensions: z.ZodMiniOptional<z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniObject<{
118
118
  info: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>;
119
119
  schema: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>;
120
- }, z.core.$strip>>>;
120
+ }, z.core.$loose>>>;
121
121
  resource: z.ZodMiniObject<{
122
122
  description: z.ZodMiniOptional<z.ZodMiniString<string>>;
123
123
  iconUrl: z.ZodMiniOptional<z.ZodMiniString<string>>;
@@ -210,7 +210,7 @@ export declare const PaymentPayloadSchema: z.ZodMiniObject<{
210
210
  extensions: z.ZodMiniOptional<z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniObject<{
211
211
  info: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>;
212
212
  schema: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>;
213
- }, z.core.$strip>>>;
213
+ }, z.core.$loose>>>;
214
214
  payload: z.ZodMiniUnion<readonly [z.ZodMiniObject<{
215
215
  authorization: z.ZodMiniObject<{
216
216
  from: z.ZodMiniString<string>;
@@ -252,10 +252,7 @@ export declare const PaymentPayloadSchema: z.ZodMiniObject<{
252
252
  export type PaymentPayload = z.infer<typeof PaymentPayloadSchema>;
253
253
  /** Facilitator verification response. */
254
254
  export declare const VerifyResponseSchema: z.ZodMiniObject<{
255
- extensions: z.ZodMiniOptional<z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniObject<{
256
- info: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>;
257
- schema: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>;
258
- }, z.core.$strip>>>;
255
+ extensions: z.ZodMiniOptional<z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>>;
259
256
  extra: z.ZodMiniOptional<z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>>;
260
257
  invalidMessage: z.ZodMiniOptional<z.ZodMiniString<string>>;
261
258
  invalidReason: z.ZodMiniOptional<z.ZodMiniString<string>>;
@@ -269,10 +266,7 @@ export declare const SettleResponseSchema: z.ZodMiniObject<{
269
266
  amount: z.ZodMiniOptional<z.ZodMiniString<string>>;
270
267
  errorMessage: z.ZodMiniOptional<z.ZodMiniString<string>>;
271
268
  errorReason: z.ZodMiniOptional<z.ZodMiniString<string>>;
272
- extensions: z.ZodMiniOptional<z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniObject<{
273
- info: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>;
274
- schema: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>;
275
- }, z.core.$strip>>>;
269
+ extensions: z.ZodMiniOptional<z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>>;
276
270
  extra: z.ZodMiniOptional<z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>>;
277
271
  network: z.ZodMiniString<string>;
278
272
  payer: z.ZodMiniOptional<z.ZodMiniString<string>>;
@@ -281,10 +275,76 @@ export declare const SettleResponseSchema: z.ZodMiniObject<{
281
275
  }, z.core.$strip>;
282
276
  /** Facilitator settlement response and x402 `PAYMENT-RESPONSE` body. */
283
277
  export type SettleResponse = z.infer<typeof SettleResponseSchema>;
278
+ /** One payment kind a facilitator supports, from `GET /supported`. */
279
+ export declare const SupportedKindSchema: z.ZodMiniObject<{
280
+ extra: z.ZodMiniOptional<z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>>;
281
+ network: z.ZodMiniString<string>;
282
+ scheme: z.ZodMiniString<string>;
283
+ x402Version: z.ZodMiniNumber<number>;
284
+ }, z.core.$strip>;
285
+ /** One payment kind a facilitator supports, from `GET /supported`. */
286
+ export type SupportedKind = z.infer<typeof SupportedKindSchema>;
287
+ /** Facilitator `GET /supported` response. */
288
+ export declare const SupportedResponseSchema: z.ZodMiniObject<{
289
+ extensions: z.ZodMiniOptional<z.ZodMiniArray<z.ZodMiniString<string>>>;
290
+ kinds: z.ZodMiniArray<z.ZodMiniObject<{
291
+ extra: z.ZodMiniOptional<z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>>;
292
+ network: z.ZodMiniString<string>;
293
+ scheme: z.ZodMiniString<string>;
294
+ x402Version: z.ZodMiniNumber<number>;
295
+ }, z.core.$strip>>;
296
+ signers: z.ZodMiniOptional<z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniArray<z.ZodMiniString<string>>>>;
297
+ }, z.core.$strip>;
298
+ /** Facilitator `GET /supported` response. */
299
+ export type SupportedResponse = z.infer<typeof SupportedResponseSchema>;
284
300
  /** x402 facilitator client interface used by server exact config. */
285
301
  export type Facilitator = {
286
302
  settle: (paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements) => Promise<SettleResponse>;
287
303
  verify: (paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements) => Promise<VerifyResponse>;
304
+ /**
305
+ * Lists the payment kinds the facilitator supports (`GET /supported`). Optional: needed only to
306
+ * read a `payTo` the facilitator publishes in `kinds[].extra.payTo`.
307
+ */
308
+ supported?: (() => Promise<SupportedResponse>) | undefined;
309
+ };
310
+ /**
311
+ * Headers an HTTP facilitator client sends with each request, keyed by facilitator path, the
312
+ * shape `createAuthHeaders` returns in `@x402/core`'s `FacilitatorConfig`. A path left out
313
+ * sends no extra headers.
314
+ */
315
+ export type FacilitatorPathHeaders = {
316
+ settle?: Record<string, string> | undefined;
317
+ supported?: Record<string, string> | undefined;
318
+ verify?: Record<string, string> | undefined;
319
+ };
320
+ /**
321
+ * Headers an HTTP facilitator client sends: either a flat record sent on every request, or a
322
+ * {@link FacilitatorPathHeaders} object keyed by path. A value counts as per-path only when it has
323
+ * at least one key, every key is `verify`, `settle` or `supported`, and every value is an object;
324
+ * anything else is a flat record.
325
+ */
326
+ export type FacilitatorHeaders = Record<string, string> | FacilitatorPathHeaders;
327
+ /**
328
+ * An HTTP facilitator that needs authentication, in the shape `@x402/core`'s
329
+ * `HTTPFacilitatorClient` takes, so one config works with both SDKs.
330
+ *
331
+ * @example
332
+ * ```ts
333
+ * const facilitator = {
334
+ * url: 'https://facilitator.example',
335
+ * headers: async () => ({ Authorization: `Bearer ${process.env.FACILITATOR_API_KEY}` }),
336
+ * }
337
+ * ```
338
+ */
339
+ export type FacilitatorConfig = {
340
+ /** Base URL of the facilitator. */
341
+ url: string;
342
+ /**
343
+ * Headers to send, such as an API key: a flat record for every request, or an object keyed by
344
+ * `verify`, `settle` and `supported` (the shape `createAuthHeaders` returns in `@x402/core`). A
345
+ * function is called before every request, so it can refresh short-lived tokens.
346
+ */
347
+ headers?: FacilitatorHeaders | (() => FacilitatorHeaders | Promise<FacilitatorHeaders>) | undefined;
288
348
  };
289
349
  /** Extracts x402 `PaymentRequirements` from a canonical exact request. */
290
350
  export declare function toPaymentRequirements(request: ExactRequest): PaymentRequirements;
@@ -58,7 +58,7 @@ export const PaymentRequirementsSchema = z.object({
58
58
  scheme: z.enum(schemes),
59
59
  });
60
60
  /** x402 v2 protocol extension value. */
61
- export const ExtensionSchema = z.object({
61
+ export const ExtensionSchema = z.looseObject({
62
62
  info: z.record(z.string(), z.unknown()),
63
63
  schema: z.record(z.string(), z.unknown()),
64
64
  });
@@ -114,7 +114,8 @@ export const PaymentPayloadSchema = z.object({
114
114
  });
115
115
  /** Facilitator verification response. */
116
116
  export const VerifyResponseSchema = z.object({
117
- extensions: z.optional(ExtensionsSchema),
117
+ // Response extension data is shaped by each extension, unlike PAYMENT-REQUIRED's { info, schema }.
118
+ extensions: z.optional(z.record(z.string(), z.unknown())),
118
119
  extra: z.optional(z.record(z.string(), z.unknown())),
119
120
  invalidMessage: z.optional(z.string()),
120
121
  invalidReason: z.optional(z.string()),
@@ -126,13 +127,27 @@ export const SettleResponseSchema = z.object({
126
127
  amount: z.optional(atomicAmount),
127
128
  errorMessage: z.optional(z.string()),
128
129
  errorReason: z.optional(z.string()),
129
- extensions: z.optional(ExtensionsSchema),
130
+ // Response extension data is shaped by each extension, unlike PAYMENT-REQUIRED's { info, schema }.
131
+ extensions: z.optional(z.record(z.string(), z.unknown())),
130
132
  extra: z.optional(z.record(z.string(), z.unknown())),
131
133
  network: nonEmptyString,
132
134
  payer: z.optional(z.string()),
133
135
  success: z.boolean(),
134
136
  transaction: z.string(),
135
137
  });
138
+ /** One payment kind a facilitator supports, from `GET /supported`. */
139
+ export const SupportedKindSchema = z.object({
140
+ extra: z.optional(z.record(z.string(), z.unknown())),
141
+ network: nonEmptyString,
142
+ scheme: nonEmptyString,
143
+ x402Version: z.number(),
144
+ });
145
+ /** Facilitator `GET /supported` response. */
146
+ export const SupportedResponseSchema = z.object({
147
+ extensions: z.optional(z.array(z.string())),
148
+ kinds: z.array(SupportedKindSchema),
149
+ signers: z.optional(z.record(z.string(), z.array(z.string()))),
150
+ });
136
151
  /** Extracts x402 `PaymentRequirements` from a canonical exact request. */
137
152
  export function toPaymentRequirements(request) {
138
153
  const { extensions: _extensions, resource: _resource, ...paymentRequirements } = request;
@@ -131,7 +131,10 @@ function decimalsOfAcceptedCurrency(parameters, accepted) {
131
131
  const resolved = currency ? Assets.resolve(currency, accepted.network) : undefined;
132
132
  if (resolved?.decimals !== undefined)
133
133
  return resolved.decimals;
134
- return parameters.decimals;
134
+ if (parameters.decimals !== undefined)
135
+ return parameters.decimals;
136
+ // Never the challenge's own metadata: a server could inflate decimals to raise the cap.
137
+ return Assets.lookup(acceptedCurrency, accepted.network)?.decimals;
135
138
  }
136
139
  function withNonceSalt(extensions) {
137
140
  const mppx = extensions.mppx;
@@ -1,6 +1,7 @@
1
1
  /** @deprecated Use `assets` instead. */
2
2
  export * as Assets from './Assets.js';
3
3
  export * as Header from './Header.js';
4
+ export * as Siwx from './Siwx.js';
4
5
  export * as Types from './Types.js';
5
6
  export * as assets from './Assets.js';
6
7
  export * from './Types.js';
@@ -1,6 +1,7 @@
1
1
  /** @deprecated Use `assets` instead. */
2
2
  export * as Assets from './Assets.js';
3
3
  export * as Header from './Header.js';
4
+ export * as Siwx from './Siwx.js';
4
5
  export * as Types from './Types.js';
5
6
  export * as assets from './Assets.js';
6
7
  export * from './Types.js';