mppx 0.20.0 → 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 (32) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/cli/cli.js +2 -2
  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/tempo/Constants.d.ts +4 -0
  12. package/dist/extensions/identity/tempo/Constants.js +4 -0
  13. package/dist/extensions/identity/tempo/client/index.d.ts +63 -0
  14. package/dist/extensions/identity/tempo/client/index.js +151 -0
  15. package/dist/extensions/identity/tempo/index.d.ts +1 -0
  16. package/dist/extensions/identity/tempo/index.js +1 -0
  17. package/dist/extensions/identity/tempo/issuer/index.d.ts +83 -0
  18. package/dist/extensions/identity/tempo/issuer/index.js +183 -0
  19. package/dist/internal/version.d.ts +2 -2
  20. package/dist/internal/version.js +1 -1
  21. package/dist/proxy/internal/Headers.js +1 -0
  22. package/dist/server/Mppx.js +28 -1
  23. package/dist/tempo/server/internal/html.gen.js +1 -1
  24. package/dist/x402/Siwx.d.ts +270 -0
  25. package/dist/x402/Siwx.js +458 -0
  26. package/dist/x402/Types.d.ts +6 -6
  27. package/dist/x402/Types.js +1 -1
  28. package/dist/x402/index.d.ts +1 -0
  29. package/dist/x402/index.js +1 -0
  30. package/dist/x402/server/EvmCharge.d.ts +7 -0
  31. package/dist/x402/server/EvmCharge.js +14 -1
  32. package/package.json +1 -1
@@ -1,5 +1,9 @@
1
1
  import { Base64 } from 'ox';
2
+ import { unwrapFetch, withoutPayment } from '../../../../client/internal/Fetch.js';
2
3
  import * as Credential from '../../../../Credential.js';
4
+ import * as Attestation from '../../attestation/client/index.js';
5
+ import { Constants as AttestationConstants } from '../../attestation/Constants.js';
6
+ import { decode as decodeAttestation, isIssuer, parseHeader } from '../../attestation/Token.js';
3
7
  import { Constants } from '../Constants.js';
4
8
  import * as Jwt from '../internal/Jwt.js';
5
9
  /**
@@ -42,6 +46,153 @@ export function prover(config) {
42
46
  },
43
47
  };
44
48
  }
49
+ /**
50
+ * Creates a prover that presents Tempo ID attestations, obtaining them from a Tempo ID
51
+ * attestation issuer (`TempoId.Issuer`) when a server asks: an `Attestation.Client.prover` whose
52
+ * `acquire` exchanges the user's access token (and ID token, for `email`) at the issuer.
53
+ *
54
+ * Unlike {@link prover}, the access token goes only to the issuer: servers get short-lived
55
+ * attestations bound to their origin, and verify them like any other issuer's.
56
+ *
57
+ * @example
58
+ * ```ts
59
+ * const mppx = Mppx.create({
60
+ * identity: [
61
+ * TempoId.Client.attestations({
62
+ * accessToken: () => accounts.session.accessToken(),
63
+ * idToken: () => accounts.session.get()?.idToken,
64
+ * issuer: 'https://attest.example',
65
+ * scope: ['https://api.example'],
66
+ * }),
67
+ * ],
68
+ * methods: [tempo({ account })],
69
+ * })
70
+ * ```
71
+ */
72
+ export function attestations(config) {
73
+ assertIssuer(config.issuer);
74
+ const issuer = config.issuer.replace(/\/+$/, '');
75
+ const types = config.types ?? Constants.attestationTypes;
76
+ let current;
77
+ // Only the latest lookup may replace `current`, so a slow lookup cannot roll it back.
78
+ let latest = 0;
79
+ // Used while the access token cannot be read: presents nothing, keeps the cache.
80
+ const unavailable = { user: undefined, prover: create(undefined, undefined) };
81
+ function create(user, held) {
82
+ return Attestation.prover({
83
+ attestations: held,
84
+ issuers: [config.issuer],
85
+ scope: config.scope,
86
+ types,
87
+ async acquire({ audience, issuer, type }) {
88
+ const result = await attest({ ...config, audience, issuer, type });
89
+ if (!result)
90
+ return undefined;
91
+ // Only keep an attestation for the user this cache belongs to.
92
+ const uid = decodeAttestation(result.attestation)?.claims.uid;
93
+ return user !== undefined && uid === user ? result.attestation : undefined;
94
+ },
95
+ });
96
+ }
97
+ async function resolve() {
98
+ const lookup = ++latest;
99
+ let user;
100
+ try {
101
+ const sub = Jwt.decode(await config.accessToken())?.claims.sub;
102
+ user = typeof sub === 'string' && sub ? sub : undefined;
103
+ }
104
+ catch {
105
+ // The token could not be read this time: present nothing, but keep the user's cache.
106
+ return unavailable;
107
+ }
108
+ if (current && current.user === user)
109
+ return current;
110
+ // Stored attestations are restored only for this issuer and the user they name.
111
+ const held = current
112
+ ? undefined
113
+ : config.attestations?.filter((token) => {
114
+ const claims = decodeAttestation(token)?.claims;
115
+ return user !== undefined && claims?.iss === issuer && claims.uid === user;
116
+ });
117
+ const entry = { user, prover: create(user, held) };
118
+ if (lookup === latest)
119
+ current = entry;
120
+ return entry;
121
+ }
122
+ return {
123
+ scope: config.scope,
124
+ async prove(request, context) {
125
+ const { prover, user } = await resolve();
126
+ // A request already in flight (such as a payment retry) may still carry the previous
127
+ // user's attestations from this prover: drop those, and only those, naming another user.
128
+ const sent = parseHeader(request.headers.get(AttestationConstants.header));
129
+ const kept = sent.filter((token) => {
130
+ const claims = decodeAttestation(token)?.claims;
131
+ const ours = claims?.iss === issuer && types.includes(claims.type) && claims.uid !== undefined;
132
+ return !ours || (user !== undefined && claims.uid === user);
133
+ });
134
+ if (kept.length !== sent.length) {
135
+ const headers = new Headers(request.headers);
136
+ if (kept.length > 0)
137
+ headers.set(AttestationConstants.header, kept.join(', '));
138
+ else
139
+ headers.delete(AttestationConstants.header);
140
+ request = new Request(request, { headers });
141
+ }
142
+ return prover.prove(request, context);
143
+ },
144
+ async prepare(response, context) {
145
+ return (await resolve()).prover.prepare?.(response, context);
146
+ },
147
+ async retry(response, context) {
148
+ return (await resolve()).prover.retry?.(response, context);
149
+ },
150
+ };
151
+ }
152
+ /**
153
+ * Exchanges a Tempo ID access token for one attestation at a Tempo ID attestation issuer.
154
+ * Resolves with `undefined` when the issuer refuses this user that type (403, such as `email`
155
+ * without a verified address), and throws on any other failure.
156
+ */
157
+ export async function attest(parameters) {
158
+ const { audience, dpop, type } = parameters;
159
+ assertIssuer(parameters.issuer);
160
+ const issuer = parameters.issuer.replace(/\/+$/, '');
161
+ const fetch = unwrapFetch(parameters.fetch ?? globalThis.fetch);
162
+ const accessToken = await parameters.accessToken();
163
+ const url = issuer + Constants.attestPath;
164
+ const headers = new Headers({
165
+ Authorization: `${dpop ? 'DPoP' : 'Bearer'} ${accessToken}`,
166
+ 'Content-Type': 'application/json',
167
+ });
168
+ if (dpop)
169
+ headers.set('DPoP', await proof(dpop, accessToken, new Request(url, { method: 'POST' })));
170
+ // Sent on every exchange: an issuer's `allow` may read the verified email for any type.
171
+ const idToken = await parameters.idToken?.();
172
+ if (idToken)
173
+ headers.set(Constants.idTokenHeader, idToken);
174
+ // Never pays: an issuer that answers 402 fails the exchange.
175
+ const response = await fetch(url, withoutPayment({
176
+ body: JSON.stringify({ audience, type }),
177
+ headers,
178
+ method: 'POST',
179
+ redirect: 'manual',
180
+ signal: AbortSignal.timeout((parameters.timeout ?? 10) * 1_000),
181
+ }));
182
+ const body = (await response.json().catch(() => ({})));
183
+ if (response.status === 403)
184
+ return undefined;
185
+ if (!response.ok)
186
+ throw new Error(typeof body.error === 'string' ? body.error : `The issuer answered ${response.status}.`);
187
+ if (typeof body.attestation !== 'string' || typeof body.expires_at !== 'string')
188
+ throw new Error('The issuer returned a malformed attestation.');
189
+ return { attestation: body.attestation, expiresAt: new Date(body.expires_at) };
190
+ }
191
+ /** Throws unless `issuer` is https (http only on localhost), since it receives the user's tokens. */
192
+ function assertIssuer(issuer) {
193
+ if (!isIssuer(issuer.replace(/\/+$/, '')) || /[?#]/.test(issuer))
194
+ throw new TypeError('The Tempo ID attestation issuer must be an https URL (http only on localhost) without a query or fragment.');
195
+ }
45
196
  /** Signs a DPoP proof (RFC 9449) of `accessToken` for one request. */
46
197
  async function proof(dpop, accessToken, request) {
47
198
  const { crv, kty, x, y } = dpop.jwk;
@@ -1,5 +1,6 @@
1
1
  export * as Client from './client/index.js';
2
2
  export { Constants } from './Constants.js';
3
+ export * as Issuer from './issuer/index.js';
3
4
  export * as Server from './server/index.js';
4
5
  export type * from './Types.js';
5
6
  //# sourceMappingURL=index.d.ts.map
@@ -1,4 +1,5 @@
1
1
  export * as Client from './client/index.js';
2
2
  export { Constants } from './Constants.js';
3
+ export * as Issuer from './issuer/index.js';
3
4
  export * as Server from './server/index.js';
4
5
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,83 @@
1
+ import type { MaybePromise } from '../../../../internal/types.js';
2
+ import type * as Store from '../../../../Store.js';
3
+ import * as Attestation from '../../attestation/Issuer.js';
4
+ import type { SigningKey } from '../../Types.js';
5
+ import { Constants } from '../Constants.js';
6
+ import type * as Types from '../Types.js';
7
+ /**
8
+ * Creates a Tempo ID attestation issuer: exchanges a signed-in user's Tempo ID access token for
9
+ * `Identity-Attestation` tokens that any MPP server verifies with `Attestation.Server.verifier`,
10
+ * like those of any other issuer.
11
+ *
12
+ * - `tempo-id`: `sub` is the user's Tempo ID user ID.
13
+ * - `email`: `sub` is the user's email address, only when the client sends an ID token
14
+ * (`Tempo-Id-Token`) and Tempo ID verified the address.
15
+ *
16
+ * Every attestation carries the user ID as `uid`, so a server can tell that attestations of
17
+ * several types name one user, and the app that exchanged the token as `azp`. The access token is checked as `TempoId.Server` checks it,
18
+ * including its DPoP proof, which the client signs for this endpoint.
19
+ *
20
+ * `handle` answers, relative to `url`:
21
+ * - `POST /tempo-id/attest` (`Constants.attestPath`) with `{ audience, type }`: `200`
22
+ * `{ attestation, expires_at }`; `400`, `401`, `403` or `503` `{ error }`.
23
+ * - `GET /.well-known/jwks.json`: the attestation key.
24
+ *
25
+ * Run it as a shared service many servers trust, or inside an app's own backend.
26
+ *
27
+ * @example
28
+ * ```ts
29
+ * const issuer = TempoId.Issuer.create({
30
+ * clientId: 'app_…',
31
+ * signingKey,
32
+ * store,
33
+ * url: 'https://attest.example',
34
+ * })
35
+ * // In the fetch handler, before its routes:
36
+ * const answered = await issuer.handle(request)
37
+ * if (answered) return answered
38
+ * ```
39
+ */
40
+ export declare function create(config: create.Config): Issuer;
41
+ export declare namespace create {
42
+ type Config = {
43
+ /** This issuer's URL, which attestations carry as `iss`. */
44
+ readonly url: string;
45
+ /** Ed25519 key pair, or a remote Signer, that signs attestations. */
46
+ readonly signingKey: SigningKey;
47
+ /** Attestation types this issuer signs. @default ['tempo-id', 'email'] */
48
+ readonly types?: readonly Type[] | undefined;
49
+ /** Seconds each attestation is valid. @default 3600 */
50
+ readonly ttl?: number | undefined;
51
+ /** The app or apps whose access tokens may be exchanged. Required. */
52
+ readonly clientId: string | readonly string[];
53
+ /** Decides whether a verified user may get attestations. */
54
+ readonly allow?: ((user: Types.Payer) => MaybePromise<boolean>) | undefined;
55
+ /** Accepts each DPoP proof once. Required, so a captured proof cannot be exchanged again. */
56
+ readonly store: Store.AtomicStore;
57
+ /**
58
+ * The audience access tokens must name. Defaults to this issuer's `url`, so a token Tempo ID
59
+ * issued for another API cannot be exchanged here.
60
+ */
61
+ readonly tokenAudience?: string | undefined;
62
+ /** Tempo ID's origin. @default 'https://id.tempo.xyz' */
63
+ readonly issuer?: string | undefined;
64
+ /** Fetch used for Tempo ID's keys. */
65
+ readonly fetch?: typeof globalThis.fetch | undefined;
66
+ /** Chain whose accounts `allow` sees, such as Moderato `42431`. @default 4217 */
67
+ readonly chainId?: number | undefined;
68
+ };
69
+ }
70
+ /** An attestation type a Tempo ID attestation issuer signs. */
71
+ export type Type = (typeof Constants.attestationTypes)[number];
72
+ /** A Tempo ID attestation issuer from {@link create}. */
73
+ export type Issuer = {
74
+ /** This issuer's URL, without a trailing slash. */
75
+ readonly issuer: string;
76
+ /** Resolves this issuer's key in process, for a server that runs beside it. */
77
+ readonly keyResolver: Attestation.Issuer['keyResolver'];
78
+ /** This issuer's JSON Web Key Set. */
79
+ readonly jwks: Attestation.Issuer['jwks'];
80
+ /** Answers the issuer's routes, and returns `undefined` for any other request. */
81
+ readonly handle: (request: Request) => Promise<Response | undefined>;
82
+ };
83
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,183 @@
1
+ import * as Attestation from '../../attestation/Issuer.js';
2
+ import { decode, isIssuer } from '../../attestation/Token.js';
3
+ import { Constants } from '../Constants.js';
4
+ import * as Server from '../server/index.js';
5
+ /**
6
+ * Creates a Tempo ID attestation issuer: exchanges a signed-in user's Tempo ID access token for
7
+ * `Identity-Attestation` tokens that any MPP server verifies with `Attestation.Server.verifier`,
8
+ * like those of any other issuer.
9
+ *
10
+ * - `tempo-id`: `sub` is the user's Tempo ID user ID.
11
+ * - `email`: `sub` is the user's email address, only when the client sends an ID token
12
+ * (`Tempo-Id-Token`) and Tempo ID verified the address.
13
+ *
14
+ * Every attestation carries the user ID as `uid`, so a server can tell that attestations of
15
+ * several types name one user, and the app that exchanged the token as `azp`. The access token is checked as `TempoId.Server` checks it,
16
+ * including its DPoP proof, which the client signs for this endpoint.
17
+ *
18
+ * `handle` answers, relative to `url`:
19
+ * - `POST /tempo-id/attest` (`Constants.attestPath`) with `{ audience, type }`: `200`
20
+ * `{ attestation, expires_at }`; `400`, `401`, `403` or `503` `{ error }`.
21
+ * - `GET /.well-known/jwks.json`: the attestation key.
22
+ *
23
+ * Run it as a shared service many servers trust, or inside an app's own backend.
24
+ *
25
+ * @example
26
+ * ```ts
27
+ * const issuer = TempoId.Issuer.create({
28
+ * clientId: 'app_…',
29
+ * signingKey,
30
+ * store,
31
+ * url: 'https://attest.example',
32
+ * })
33
+ * // In the fetch handler, before its routes:
34
+ * const answered = await issuer.handle(request)
35
+ * if (answered) return answered
36
+ * ```
37
+ */
38
+ export function create(config) {
39
+ const url = config.url.replace(/\/+$/, '');
40
+ if (!isIssuer(url) || /[?#]/.test(url))
41
+ throw new TypeError('Tempo ID attestation issuer url must be an https URL without a query or fragment.');
42
+ const types = config.types ?? Constants.attestationTypes;
43
+ for (const type of types)
44
+ if (!Constants.attestationTypes.includes(type))
45
+ throw new TypeError(`Tempo ID attestation issuer cannot sign type "${type}".`);
46
+ const attestation = Attestation.create({
47
+ issuer: url,
48
+ signingKey: config.signingKey,
49
+ ttl: config.ttl,
50
+ });
51
+ if (!config.store)
52
+ throw new TypeError('Tempo ID attestation issuer requires store, so each DPoP proof is accepted once.');
53
+ if (!config.clientId || (Array.isArray(config.clientId) && config.clientId.length === 0))
54
+ throw new TypeError('Tempo ID attestation issuer requires clientId: the apps that may exchange tokens.');
55
+ const tempoId = Server.create({
56
+ allow: config.allow,
57
+ chainId: config.chainId,
58
+ // Only tokens issued for this issuer: a token another API received cannot be exchanged here.
59
+ audience: config.tokenAudience ?? url,
60
+ clientId: config.clientId,
61
+ fetch: config.fetch,
62
+ issuer: config.issuer,
63
+ store: config.store,
64
+ });
65
+ const attestPath = new URL(url).pathname.replace(/\/+$/, '') + Constants.attestPath;
66
+ // DPoP proofs must name this issuer's configured endpoint, never one built from the Host header.
67
+ const attestUrl = new URL(url).origin + attestPath;
68
+ async function attest(request) {
69
+ const body = await readJson(request);
70
+ if (body === undefined)
71
+ return error(400, `The body must be JSON of at most ${maxBody} bytes.`);
72
+ const { audience, type } = (typeof body === 'object' && body !== null ? body : {});
73
+ if (typeof audience !== 'string' || audience.length > 2_048 || !isIssuer(audience))
74
+ return error(400, 'audience must be an https origin.');
75
+ if (typeof type !== 'string' || !types.includes(type))
76
+ return error(400, `type must be one of ${types.join(', ')}.`);
77
+ const verified = await tempoId.verifier.verify(new Request(attestUrl, { headers: request.headers, method: request.method }));
78
+ if (verified.status !== 'valid')
79
+ return error(statusCodes[verified.status], verified.reason ?? 'Sign in with Tempo ID.', {
80
+ ...(verified.status === 'missing' || verified.status === 'invalid'
81
+ ? Object.fromEntries(new Headers(verified.headers))
82
+ : {}),
83
+ });
84
+ const user = verified.value;
85
+ let sub;
86
+ if (type === 'email') {
87
+ if (!user.email || user.emailVerified !== true)
88
+ return error(403, 'Send an ID token naming an email address Tempo ID verified.');
89
+ sub = user.email;
90
+ }
91
+ else
92
+ sub = user.userId;
93
+ let token;
94
+ try {
95
+ token = await attestation.sign({
96
+ audience,
97
+ // The app that exchanged the token, so a server can restrict which apps it accepts.
98
+ claims: { azp: user.clientId },
99
+ sub,
100
+ type,
101
+ uid: user.userId,
102
+ });
103
+ }
104
+ catch (cause) {
105
+ // Bad input is the caller's to fix; anything else is the signer's outage, worth a retry.
106
+ if (cause instanceof Attestation.InvalidParametersError)
107
+ return error(400, 'The attestation cannot be signed for this request.');
108
+ return error(503, 'The attestation signer is unavailable.', { 'Retry-After': '5' });
109
+ }
110
+ const exp = decode(token)?.claims.exp;
111
+ if (typeof exp !== 'number')
112
+ return error(400, 'The attestation cannot be signed for this request.');
113
+ return Response.json({ attestation: token, expires_at: new Date(exp * 1_000).toISOString() }, { headers: { ...cors, 'Cache-Control': 'no-store' } });
114
+ }
115
+ return {
116
+ issuer: url,
117
+ keyResolver: attestation.keyResolver,
118
+ jwks: attestation.jwks,
119
+ async handle(request) {
120
+ const { pathname } = new URL(request.url);
121
+ if (pathname === attestPath) {
122
+ if (request.method === 'OPTIONS')
123
+ return new Response(null, {
124
+ status: 204,
125
+ headers: {
126
+ ...cors,
127
+ 'Access-Control-Allow-Headers': 'authorization, content-type, dpop, tempo-id-token',
128
+ 'Access-Control-Allow-Methods': 'POST',
129
+ 'Access-Control-Max-Age': '600',
130
+ },
131
+ });
132
+ if (request.method !== 'POST')
133
+ return error(405, 'Use POST.', { Allow: 'POST' });
134
+ return attest(request);
135
+ }
136
+ return attestation.handle(request);
137
+ },
138
+ };
139
+ }
140
+ const cors = { 'Access-Control-Allow-Origin': '*' };
141
+ /** The largest request body the issuer reads, in bytes. */
142
+ const maxBody = 4_096;
143
+ /**
144
+ * Reads a JSON body of at most {@link maxBody} bytes before anything else runs, cancelling the
145
+ * stream once it is over, or returns `undefined`.
146
+ */
147
+ async function readJson(request) {
148
+ if (Number(request.headers.get('content-length') ?? 0) > maxBody)
149
+ return undefined;
150
+ if (!request.body)
151
+ return undefined;
152
+ const reader = request.body.getReader();
153
+ const chunks = [];
154
+ let size = 0;
155
+ try {
156
+ while (true) {
157
+ const { done, value } = await reader.read();
158
+ if (done)
159
+ break;
160
+ size += value.byteLength;
161
+ if (size > maxBody) {
162
+ reader.cancel().catch(() => { });
163
+ return undefined;
164
+ }
165
+ chunks.push(value);
166
+ }
167
+ const bytes = new Uint8Array(size);
168
+ let offset = 0;
169
+ for (const chunk of chunks) {
170
+ bytes.set(chunk, offset);
171
+ offset += chunk.byteLength;
172
+ }
173
+ return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
174
+ }
175
+ catch {
176
+ return undefined;
177
+ }
178
+ }
179
+ const statusCodes = { missing: 401, invalid: 401, forbidden: 403, unavailable: 503 };
180
+ function error(status, message, headers = {}) {
181
+ return Response.json({ error: message }, { status, headers: { ...cors, ...headers } });
182
+ }
183
+ //# sourceMappingURL=index.js.map
@@ -1,5 +1,5 @@
1
1
  /** Current mppx package version. */
2
- export declare const version = "0.20.0";
2
+ export declare const version = "0.20.1";
3
3
  /** Canonical SDK identifier for this mppx release. */
4
- export declare const sdkIdentifier = "mppx/0.20.0";
4
+ export declare const sdkIdentifier = "mppx/0.20.1";
5
5
  //# sourceMappingURL=version.d.ts.map
@@ -1,6 +1,6 @@
1
1
  // Generated by scripts/sync-version.ts.
2
2
  /** Current mppx package version. */
3
- export const version = '0.20.0';
3
+ export const version = '0.20.1';
4
4
  /** Canonical SDK identifier for this mppx release. */
5
5
  export const sdkIdentifier = `mppx/${version}`;
6
6
  //# sourceMappingURL=version.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. */
@@ -12,6 +12,7 @@ import { warnOnce } from '../internal/warnOnce.js';
12
12
  import * as Mcp from '../Mcp.js';
13
13
  import * as PaymentRequest from '../PaymentRequest.js';
14
14
  import * as x402_Header from '../x402/Header.js';
15
+ import * as x402_Siwx from '../x402/Siwx.js';
15
16
  import * as x402_Types from '../x402/Types.js';
16
17
  import * as z from '../zod.js';
17
18
  import * as ChallengeMeta from './internal/challengeMeta.js';
@@ -2200,7 +2201,7 @@ function mergeX402PaymentRequiredHeaders(values) {
2200
2201
  if (!first)
2201
2202
  throw new Error('Expected at least one x402 payment-required header.');
2202
2203
  const incompatible = rest.some((value) => !isDeepStrictEqual(value.resource, first.resource) ||
2203
- !isDeepStrictEqual(value.extensions, first.extensions));
2204
+ !isDeepStrictEqual(withoutSiwx(value.extensions), withoutSiwx(first.extensions)));
2204
2205
  if (incompatible)
2205
2206
  return [
2206
2207
  x402_Header.encodePaymentRequired({
@@ -2213,14 +2214,40 @@ function mergeX402PaymentRequiredHeaders(values) {
2213
2214
  const error = [first.error, ...rest.map((value) => value.error)]
2214
2215
  .filter((value) => value !== undefined && value.length > 0)
2215
2216
  .join('; ');
2217
+ const siwx = mergeSiwx([first, ...rest]);
2216
2218
  return [
2217
2219
  x402_Header.encodePaymentRequired({
2218
2220
  ...first,
2219
2221
  accepts: [first.accepts, ...rest.map((value) => value.accepts)].flat(),
2222
+ ...(siwx ? { extensions: { ...first.extensions, [x402_Siwx.extensionKey]: siwx } } : {}),
2220
2223
  ...(error ? { error } : {}),
2221
2224
  }),
2222
2225
  ];
2223
2226
  }
2227
+ /**
2228
+ * Each SIWX offer carries its own nonce, so offers differ only in that and their chains.
2229
+ * Nonces aren't tied to the offer that issued them, so one challenge listing every
2230
+ * offer's chains serves all of them.
2231
+ */
2232
+ function mergeSiwx(values) {
2233
+ const extensions = values
2234
+ .map((value) => x402_Siwx.fromPaymentRequired(value))
2235
+ .filter((value) => value !== undefined);
2236
+ const [first] = extensions;
2237
+ if (!first)
2238
+ return undefined;
2239
+ const chains = new Map();
2240
+ for (const extension of extensions)
2241
+ for (const chain of extension.supportedChains)
2242
+ chains.set(`${chain.chainId}:${chain.type}`, chain);
2243
+ return { ...first, supportedChains: [...chains.values()] };
2244
+ }
2245
+ function withoutSiwx(extensions) {
2246
+ if (!extensions)
2247
+ return extensions;
2248
+ const { [x402_Siwx.extensionKey]: _, ...rest } = extensions;
2249
+ return rest;
2250
+ }
2224
2251
  export function toNodeListener(handler, options) {
2225
2252
  return async (req, res) => {
2226
2253
  let result;