mppx 0.19.1 → 0.20.1

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 (54) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/cli/cli.js +3 -3
  3. package/dist/cli/plugins/index.js +1 -1
  4. package/dist/evm/server/Charge.js +104 -0
  5. package/dist/extensions/identity/attestation/Issuer.d.ts +91 -0
  6. package/dist/extensions/identity/attestation/Issuer.js +159 -0
  7. package/dist/extensions/identity/attestation/Token.js +7 -0
  8. package/dist/extensions/identity/attestation/Types.d.ts +31 -3
  9. package/dist/extensions/identity/attestation/index.d.ts +3 -1
  10. package/dist/extensions/identity/attestation/index.js +3 -1
  11. package/dist/extensions/identity/erc8004/Constants.d.ts +20 -0
  12. package/dist/extensions/identity/erc8004/Constants.js +20 -0
  13. package/dist/extensions/identity/erc8004/Types.d.ts +11 -0
  14. package/dist/extensions/identity/erc8004/Types.js +2 -0
  15. package/dist/extensions/identity/erc8004/client/index.d.ts +33 -0
  16. package/dist/extensions/identity/erc8004/client/index.js +33 -0
  17. package/dist/extensions/identity/erc8004/index.d.ts +5 -0
  18. package/dist/extensions/identity/erc8004/index.js +4 -0
  19. package/dist/extensions/identity/erc8004/internal/Agent.d.ts +21 -0
  20. package/dist/extensions/identity/erc8004/internal/Agent.js +24 -0
  21. package/dist/extensions/identity/erc8004/server/index.d.ts +44 -0
  22. package/dist/extensions/identity/erc8004/server/index.js +178 -0
  23. package/dist/extensions/identity/index.d.ts +2 -0
  24. package/dist/extensions/identity/index.js +2 -0
  25. package/dist/extensions/identity/tempo/Constants.d.ts +4 -0
  26. package/dist/extensions/identity/tempo/Constants.js +4 -0
  27. package/dist/extensions/identity/tempo/client/index.d.ts +63 -0
  28. package/dist/extensions/identity/tempo/client/index.js +151 -0
  29. package/dist/extensions/identity/tempo/index.d.ts +1 -0
  30. package/dist/extensions/identity/tempo/index.js +1 -0
  31. package/dist/extensions/identity/tempo/issuer/index.d.ts +83 -0
  32. package/dist/extensions/identity/tempo/issuer/index.js +183 -0
  33. package/dist/identity/Headers.d.ts +1 -1
  34. package/dist/identity/Headers.js +2 -0
  35. package/dist/internal/version.d.ts +2 -2
  36. package/dist/internal/version.js +1 -1
  37. package/dist/proxy/Proxy.js +47 -9
  38. package/dist/proxy/internal/Headers.js +1 -0
  39. package/dist/server/Mppx.js +28 -1
  40. package/dist/tempo/server/internal/html.gen.js +1 -1
  41. package/dist/tempo/session/server/CredentialVerification.d.ts +2 -0
  42. package/dist/tempo/session/server/CredentialVerification.js +44 -0
  43. package/dist/tempo/session/server/MeteredStream.d.ts +2 -0
  44. package/dist/tempo/session/server/MeteredStream.js +11 -0
  45. package/dist/tempo/session/server/Sse.js +9 -4
  46. package/dist/x402/Siwx.d.ts +270 -0
  47. package/dist/x402/Siwx.js +458 -0
  48. package/dist/x402/Types.d.ts +6 -6
  49. package/dist/x402/Types.js +1 -1
  50. package/dist/x402/index.d.ts +1 -0
  51. package/dist/x402/index.js +1 -0
  52. package/dist/x402/server/EvmCharge.d.ts +7 -0
  53. package/dist/x402/server/EvmCharge.js +14 -1
  54. package/package.json +5 -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>;
@@ -255,7 +255,7 @@ export declare const VerifyResponseSchema: z.ZodMiniObject<{
255
255
  extensions: z.ZodMiniOptional<z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniObject<{
256
256
  info: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>;
257
257
  schema: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>;
258
- }, z.core.$strip>>>;
258
+ }, z.core.$loose>>>;
259
259
  extra: z.ZodMiniOptional<z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>>;
260
260
  invalidMessage: z.ZodMiniOptional<z.ZodMiniString<string>>;
261
261
  invalidReason: z.ZodMiniOptional<z.ZodMiniString<string>>;
@@ -272,7 +272,7 @@ export declare const SettleResponseSchema: z.ZodMiniObject<{
272
272
  extensions: z.ZodMiniOptional<z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniObject<{
273
273
  info: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>;
274
274
  schema: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>;
275
- }, z.core.$strip>>>;
275
+ }, z.core.$loose>>>;
276
276
  extra: z.ZodMiniOptional<z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>>;
277
277
  network: z.ZodMiniString<string>;
278
278
  payer: z.ZodMiniOptional<z.ZodMiniString<string>>;
@@ -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
  });
@@ -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';
@@ -1,6 +1,7 @@
1
1
  import type * as Credential from '../../Credential.js';
2
2
  import * as Types from '../../evm/Types.js';
3
3
  import * as ServerTransport from '../../server/Transport.js';
4
+ import * as Siwx from '../Siwx.js';
4
5
  import * as x402_Types from '../Types.js';
5
6
  export type Options = {
6
7
  /** Facilitator client or base URL used for x402-compatible settlement. */
@@ -28,6 +29,11 @@ export type Options = {
28
29
  * @default 'required'
29
30
  */
30
31
  routeBinding?: RouteBindingMode | undefined;
32
+ /**
33
+ * Accepts x402 `sign-in-with-x` (SIWX) proofs: a wallet that signs the 402's
34
+ * challenge, and that `grant` approves, gets the resource without paying.
35
+ */
36
+ siwx?: Siwx.ServerOptions | undefined;
31
37
  };
32
38
  /** How a route-scoped charge binds an x402 credential to its route. */
33
39
  export type RouteBindingMode = 'required' | 'resource';
@@ -36,6 +42,7 @@ export type ResolvedOptions = {
36
42
  facilitator?: x402_Types.Facilitator | undefined;
37
43
  maxTimeoutSeconds: number;
38
44
  routeBinding: RouteBindingMode;
45
+ siwx?: Siwx.ServerOptions | undefined;
39
46
  };
40
47
  export type Path = {
41
48
  credentialHeaders: readonly string[];
@@ -11,6 +11,7 @@ import * as ChallengeMeta from '../../server/internal/challengeMeta.js';
11
11
  import * as Scope from '../../server/internal/scope.js';
12
12
  import * as x402_Header from '../Header.js';
13
13
  import * as x402_RouteBinding from '../internal/RouteBinding.js';
14
+ import * as Siwx from '../Siwx.js';
14
15
  import * as x402_Types from '../Types.js';
15
16
  import * as x402_Facilitator from './Facilitator.js';
16
17
  const pendingX402Credential = Symbol('mppx.evm.pendingX402Credential');
@@ -39,6 +40,7 @@ export function resolveOptions(parameters) {
39
40
  : {}),
40
41
  maxTimeoutSeconds: parameters.options?.maxTimeoutSeconds ?? 300,
41
42
  routeBinding: parameters.options?.routeBinding ?? 'required',
43
+ ...(parameters.options?.siwx ? { siwx: parameters.options.siwx } : {}),
42
44
  };
43
45
  }
44
46
  /** Creates the x402 wire path for an EVM charge method. */
@@ -157,7 +159,18 @@ export function createPath(config) {
157
159
  headers.set(x402_Types.paymentRequiredHeader, x402_Header.encodePaymentRequired({
158
160
  accepts: [toPaymentRequirements(request, config)],
159
161
  error: options.error?.message ?? `${x402_Types.paymentSignatureHeader} header is required`,
160
- extensions: routeExtensions(options.challenge, options.input),
162
+ extensions: {
163
+ ...routeExtensions(options.challenge, options.input),
164
+ ...(config.siwx
165
+ ? {
166
+ [Siwx.extensionKey]: Siwx.createExtension({
167
+ chainId: request.methodDetails.chainId,
168
+ origin: config.siwx.origin,
169
+ url: options.input.url,
170
+ }),
171
+ }
172
+ : {}),
173
+ },
161
174
  resource: { url: options.input.url },
162
175
  x402Version: 2,
163
176
  }));
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mppx",
3
3
  "type": "module",
4
- "version": "0.19.1",
4
+ "version": "0.20.1",
5
5
  "main": "./dist/index.js",
6
6
  "license": "MIT",
7
7
  "homepage": "https://github.com/wevm/mppx#readme",
@@ -143,6 +143,10 @@
143
143
  "types": "./dist/extensions/identity/tap/index.d.ts",
144
144
  "default": "./dist/extensions/identity/tap/index.js"
145
145
  },
146
+ "./extensions/identity/erc8004": {
147
+ "types": "./dist/extensions/identity/erc8004/index.d.ts",
148
+ "default": "./dist/extensions/identity/erc8004/index.js"
149
+ },
146
150
  "./extensions/identity/email-otp": {
147
151
  "types": "./dist/extensions/identity/email-otp/index.d.ts",
148
152
  "default": "./dist/extensions/identity/email-otp/index.js"