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
@@ -1,6 +1,7 @@
1
1
  import { Cli, Errors, z } from 'incur';
2
2
  import { createClient, http } from 'viem';
3
3
  import { tempo as tempoMainnet, tempoModerato } from 'viem/tempo/chains';
4
+ import * as Challenge from '../../Challenge.js';
4
5
  import { normalizeHeaders } from '../../client/internal/Fetch.js';
5
6
  import { canSignDescriptor } from '../../tempo/session/client/CredentialState.js';
6
7
  import * as Chain from '../../tempo/session/precompile/Chain.js';
@@ -257,6 +258,14 @@ const sessions = Cli.create('sessions', {
257
258
  message: `Session ${channelId} was not found.`,
258
259
  exitCode: 2,
259
260
  });
261
+ // A session stored by an earlier version may hold a challenge that selects another
262
+ // credential header. It still lists, but no credential is sent in that header.
263
+ if (Challenge.hasUnsupportedCredentialHeader(record.challenge))
264
+ throw new Errors.IncurError({
265
+ code: 'SESSION_STATE_INVALID',
266
+ message: 'Stored session challenge selects a credential header other than Payment-Authorization.',
267
+ exitCode: 65,
268
+ });
260
269
  const resolvedAccount = await resolveCloseAccount(record, options.account);
261
270
  const client = await resolveCloseClient(record.channel.chainId, options);
262
271
  const expectedId = Channel.computeId({
@@ -75,7 +75,8 @@ const storedSessionSchema = z.object({
75
75
  channel: storedChannelSchema,
76
76
  account: accountSchema,
77
77
  endpoint: z.string(),
78
- challenge: Challenge.Schema,
78
+ // Sessions stored before `header` was limited to Payment-Authorization must still load.
79
+ challenge: Challenge.LenientSchema,
79
80
  receipt: z.optional(receiptSchema),
80
81
  spent: z.string(),
81
82
  units: z.number(),
@@ -458,7 +459,7 @@ function sanitizeStoredChannel(value, file) {
458
459
  return parseStored(storedChannelSchema, value, file, 'Stored session channel is invalid.');
459
460
  }
460
461
  function parseSessionChallenge(value, file) {
461
- const parsed = Challenge.Schema.safeParse(value);
462
+ const parsed = Challenge.LenientSchema.safeParse(value);
462
463
  if (!parsed.success || !isTempoSessionChallenge(parsed.data))
463
464
  throw stateError(file, 'Stored session challenge is invalid.');
464
465
  return parsed.data;
@@ -117,11 +117,25 @@ export async function validateChallenge(baseUrl, endpoint, verbose, options) {
117
117
  return { results };
118
118
  }
119
119
  if (challenges.length === 0) {
120
- results.push(fail('Challenge parseable', 'No Payment challenges found in header'));
120
+ // List parsing skips challenges it may not pay (such as an unsupported credential header);
121
+ // report why the first one was skipped.
122
+ let reason = 'No Payment challenges found in header';
123
+ try {
124
+ Challenge.fromResponse(response);
125
+ }
126
+ catch (error) {
127
+ reason = error.message;
128
+ }
129
+ results.push(fail('Challenge parseable', reason));
121
130
  return { results };
122
131
  }
123
132
  const methodList = challenges.map((c) => `${c.method}/${c.intent}`).join(', ');
124
133
  results.push(check('Challenge parseable', challenges.length === 1 ? methodList : `${challenges.length} methods: ${methodList}`));
134
+ // List parsing skips a challenge that selects another credential header; report it even when
135
+ // another challenge is usable.
136
+ const skipped = Challenge.countUnsupportedCredentialHeaders(wwwAuth);
137
+ if (skipped > 0)
138
+ results.push(fail('Challenge credential header', `${skipped} of ${challenges.length + skipped} challenges select a credential header other than Payment-Authorization`, 'A challenge may only set header="Payment-Authorization"; omit header to use Authorization.'));
125
139
  // Validate common fields across all challenges
126
140
  const serverHost = new URL(baseUrl).hostname;
127
141
  validateIds(challenges, results);
@@ -1,4 +1,4 @@
1
- import type * as Challenge from '../Challenge.js';
1
+ import * as Challenge from '../Challenge.js';
2
2
  import type * as Identity from '../identity/Types.js';
3
3
  import * as AcceptPayment from '../internal/AcceptPayment.js';
4
4
  import type * as Method from '../Method.js';
@@ -1,3 +1,4 @@
1
+ import * as Challenge from '../Challenge.js';
1
2
  import * as Constants from '../Constants.js';
2
3
  import * as Expires from '../Expires.js';
3
4
  import * as IdentityClient from '../identity/Client.js';
@@ -93,7 +94,7 @@ export function create(config) {
93
94
  const orderedCandidates = await resolveChallengeOrder(candidates, options?.orderChallenges ?? orderChallenges);
94
95
  const selected = orderedCandidates[0];
95
96
  if (!selected)
96
- throw new Error(`No method found for challenges: ${challenges.map((challenge) => `${challenge.method}.${challenge.intent}`).join(', ')}. Available: ${methods.map((m) => `${m.name}.${m.intent}`).join(', ')}`);
97
+ throw new Error(Challenge.withSkippedChallenges(`No method found for challenges: ${challenges.map((challenge) => `${challenge.method}.${challenge.intent}`).join(', ')}. Available: ${methods.map((m) => `${m.name}.${m.intent}`).join(', ')}`, Fetch.skippedChallengeCount(response)));
97
98
  // Signing must use what the caller inspects, while attachment needs the adapter's original
98
99
  // object identity to retain protocol provenance.
99
100
  const transportChallenge = selected.challenge;
@@ -190,10 +190,11 @@ export declare function identityOf(fetch: typeof globalThis.fetch): IdentityClie
190
190
  export declare function unwrapFetch(fetch: typeof globalThis.fetch): typeof globalThis.fetch;
191
191
  /** @internal */
192
192
  export declare function resolveRequestSignal(input: RequestInfo | URL, init: RequestInit | undefined): AbortSignal | undefined;
193
- /** @internal */
194
193
  export declare function validateCredentialHeaderValue(credential: string): void;
195
194
  /** @internal */
196
195
  /** @internal */
197
196
  export declare function shouldInjectForPolicy(input: RequestInfo | URL, policy: NonNullable<from.Config['acceptPaymentPolicy']>): boolean;
197
+ /** Counts the challenges in a 402's `WWW-Authenticate` header that list parsing skipped. */
198
+ export declare function skippedChallengeCount(response: unknown): number;
198
199
  export {};
199
200
  //# sourceMappingURL=Fetch.d.ts.map
@@ -1,5 +1,6 @@
1
1
  import * as Challenge from '../../Challenge.js';
2
2
  import * as Constants from '../../Constants.js';
3
+ import * as Credential from '../../Credential.js';
3
4
  import { PaymentOutcomeUnknownError } from '../../Errors.js';
4
5
  import * as Expires from '../../Expires.js';
5
6
  import * as IdentityClient from '../../identity/Client.js';
@@ -7,6 +8,7 @@ import * as AcceptPayment from '../../internal/AcceptPayment.js';
7
8
  import * as Transport from '../Transport.js';
8
9
  import * as MethodChallenge from './MethodChallenge.js';
9
10
  import * as MethodResponse from './MethodResponse.js';
11
+ import * as PendingSettlement from './PendingSettlement.js';
10
12
  import * as ProofRealm from './ProofRealm.js';
11
13
  import { adapterOwnsPayment } from './protocols/Mcp.js';
12
14
  // We tag wrappers with a global symbol so we can recognize wrappers created by mppx,
@@ -125,7 +127,9 @@ export function from(config) {
125
127
  // which can duplicate retries and make restore semantics fragile.
126
128
  const baseFetch = unwrapFetch(fetch);
127
129
  const send = async (input, init, context) => identity
128
- ? identity.send(baseFetch, new Request(input, init), context)
130
+ ? identity.send((request, nextInit) => baseFetch(request, init?.[skipPayment]
131
+ ? withoutPayment(nextInit)
132
+ : nextInit), new Request(input, init), context)
129
133
  : { response: await baseFetch(input, init), headers: [] };
130
134
  const request = async (input, init, canRefetch) => {
131
135
  const callerHeaders = getCallerHeaders(input, init?.headers);
@@ -170,7 +174,7 @@ export function from(config) {
170
174
  // is the server's final answer, not a new challenge round.
171
175
  if (retry > 0)
172
176
  return response;
173
- throw new Error(`No method found for challenges: ${challenges.map((c) => `${c.method}.${c.intent}`).join(', ')}. Available: ${methods.map((m) => `${m.name}.${m.intent}`).join(', ')}`);
177
+ throw new Error(Challenge.withSkippedChallenges(`No method found for challenges: ${challenges.map((c) => `${c.method}.${c.intent}`).join(', ')}. Available: ${methods.map((m) => `${m.name}.${m.intent}`).join(', ')}`, skippedChallengeCount(response)));
174
178
  }
175
179
  const selectedChallenge = selected.challenge;
176
180
  challenge = selectedChallenge;
@@ -205,7 +209,8 @@ export function from(config) {
205
209
  resolveRequestSignal(input, init)?.throwIfAborted();
206
210
  const credentialContext = overrideContext ?? context;
207
211
  if (!MethodChallenge.has(selected.method))
208
- return resolveCredential(selectedChallenge, selected.method, credentialContext);
212
+ // A Zone withdrawal still settling is resumed for this challenge, not paid again.
213
+ return PendingSettlement.resume(() => resolveCredential(selectedChallenge, selected.method, credentialContext, requestOrigin(paymentInput)), { attempts: maxPaymentRetries, signal: resolveRequestSignal(input, init) });
209
214
  const attempt = {
210
215
  origin: resolveRequestUrl(paymentInput).origin,
211
216
  prepare: () => MethodChallenge.handle(selected.method, {
@@ -256,6 +261,9 @@ export function from(config) {
256
261
  }
257
262
  const effectiveContext = preparedCredential ? preparedCredential.context : context;
258
263
  validateCredentialHeaderValue(credential);
264
+ // Identity proofs bind to the Challenge the credential pays, which can be an earlier one
265
+ // (a resumed Zone withdrawal) rather than the one just selected.
266
+ const paidChallenge = credentialChallenge(credential, selectedChallenge);
259
267
  await events.emit('credential.created', createCredentialCreatedPayload({
260
268
  challenge: selectedChallenge,
261
269
  credential,
@@ -279,7 +287,7 @@ export function from(config) {
279
287
  }, credential, { challenge: selectedChallenge }),
280
288
  // Runtimes do not strip custom payment headers on cross-origin redirects.
281
289
  redirect: 'manual',
282
- }, { challenge: selectedChallenge, headers: identityHeaders }));
290
+ }, { challenge: paidChallenge, headers: identityHeaders }));
283
291
  }
284
292
  catch (cause) {
285
293
  outcomeUnknown = unknownOutcome(cause);
@@ -760,6 +768,21 @@ function isWrappedFetch(fetch) {
760
768
  return Boolean(fetch[MPPX_FETCH_WRAPPER]);
761
769
  }
762
770
  /** @internal */
771
+ /**
772
+ * Returns the Challenge a serialized credential pays: the selected one, or the earlier
773
+ * Challenge a method resumed a payment for (keeping the selected one's credential header).
774
+ */
775
+ function credentialChallenge(credential, selected) {
776
+ try {
777
+ const { challenge } = Credential.deserialize(credential);
778
+ if (challenge.id === selected.id)
779
+ return selected;
780
+ return { ...challenge, ...(selected.header !== undefined && { header: selected.header }) };
781
+ }
782
+ catch {
783
+ return selected;
784
+ }
785
+ }
763
786
  export function validateCredentialHeaderValue(credential) {
764
787
  if (!credential.trim())
765
788
  throw new Error('Credential header value must be non-empty');
@@ -773,7 +796,7 @@ async function resolveCredential(challenge, mi, context, attempt) {
773
796
  const parameters = parsedContext !== undefined ? { challenge, context: parsedContext } : { challenge };
774
797
  if (attempt?.origin)
775
798
  MethodResponse.attachOrigin(parameters, attempt.origin);
776
- if (attempt)
799
+ if (attempt && 'prepare' in attempt)
777
800
  MethodResponse.attachAttempt(mi, parameters, attempt);
778
801
  return mi.createCredential(parameters);
779
802
  }
@@ -833,6 +856,15 @@ function resolveRequestUrl(input) {
833
856
  return new URL(input.url);
834
857
  return new URL(input, isBrowser() ? globalThis.location.href : undefined);
835
858
  }
859
+ /** The request's origin, or `undefined` for a relative URL outside a browser. */
860
+ function requestOrigin(input) {
861
+ try {
862
+ return { origin: resolveRequestUrl(input).origin };
863
+ }
864
+ catch {
865
+ return undefined;
866
+ }
867
+ }
836
868
  /** Rejects Request modes whose paid retry cannot carry a credential to the server. */
837
869
  function assertPayableRequest(input, init) {
838
870
  const request = input instanceof Request ? input : undefined;
@@ -893,4 +925,10 @@ async function resolvePaymentRetryInput(response, fallback, initialInput, init)
893
925
  }
894
926
  return response.url;
895
927
  }
928
+ /** Counts the challenges in a 402's `WWW-Authenticate` header that list parsing skipped. */
929
+ export function skippedChallengeCount(response) {
930
+ if (!(response instanceof Response) || response.status !== 402)
931
+ return 0;
932
+ return Challenge.countUnsupportedCredentialHeaders(response.headers.get(Constants.Headers.wwwAuthenticate));
933
+ }
896
934
  //# sourceMappingURL=Fetch.js.map
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Creates a credential and, while the Zone withdrawal that pays its challenge is still
3
+ * settling, creates it again for the same challenge, up to `attempts` times in all. Each
4
+ * attempt resumes waiting for that withdrawal; requesting a new challenge instead would not
5
+ * settle it sooner.
6
+ */
7
+ export declare function resume(create: () => Promise<string>, options: {
8
+ attempts: number;
9
+ signal?: AbortSignal | undefined;
10
+ }): Promise<string>;
11
+ //# sourceMappingURL=PendingSettlement.d.ts.map
@@ -0,0 +1,22 @@
1
+ import { ZoneSettlementPendingError } from '../../Errors.js';
2
+ /**
3
+ * Creates a credential and, while the Zone withdrawal that pays its challenge is still
4
+ * settling, creates it again for the same challenge, up to `attempts` times in all. Each
5
+ * attempt resumes waiting for that withdrawal; requesting a new challenge instead would not
6
+ * settle it sooner.
7
+ */
8
+ export async function resume(create, options) {
9
+ const { attempts, signal } = options;
10
+ for (let attempt = 1;; attempt++) {
11
+ signal?.throwIfAborted();
12
+ try {
13
+ return await create();
14
+ }
15
+ catch (error) {
16
+ if (!(error instanceof ZoneSettlementPendingError) || attempt >= attempts)
17
+ throw error;
18
+ signal?.throwIfAborted();
19
+ }
20
+ }
21
+ }
22
+ //# sourceMappingURL=PendingSettlement.js.map
@@ -78,11 +78,19 @@ function paymentRequiredDataFromValue(data) {
78
78
  return undefined;
79
79
  const parsed = [];
80
80
  for (const challenge of challenges) {
81
+ if (!Challenge.LenientSchema.safeParse(challenge).success)
82
+ return undefined;
83
+ // A well-formed challenge that selects an unsupported credential header gets no credential, but
84
+ // must not stop the client from paying another challenge.
85
+ if (Challenge.hasUnsupportedCredentialHeader(challenge))
86
+ continue;
81
87
  const result = Challenge.Schema.safeParse(challenge);
82
88
  if (!result.success)
83
89
  return undefined;
84
90
  parsed.push(result.data);
85
91
  }
92
+ if (parsed.length === 0)
93
+ return undefined;
86
94
  const { httpStatus, problem } = data;
87
95
  return {
88
96
  challenges: parsed,
@@ -128,6 +128,9 @@ function resolveAuthorization(parameters, request) {
128
128
  };
129
129
  if (parameters.authorization)
130
130
  return parameters.authorization;
131
+ const known = Assets.lookup(acceptedCurrency, network)?.transfer;
132
+ if (known?.type === Types.eip3009)
133
+ return { name: known.name, version: known.version };
131
134
  throw new Error('EVM authorization requires token name and version.');
132
135
  }
133
136
  function decimalsOfAcceptedCurrency(parameters, request) {
@@ -138,6 +141,9 @@ function decimalsOfAcceptedCurrency(parameters, request) {
138
141
  const resolved = currency ? Assets.resolve(currency, network) : undefined;
139
142
  if (resolved?.decimals !== undefined)
140
143
  return resolved.decimals;
141
- return parameters.decimals;
144
+ if (parameters.decimals !== undefined)
145
+ return parameters.decimals;
146
+ // Never `methodDetails.decimals`: a server could inflate decimals to raise the cap.
147
+ return Assets.lookup(acceptedCurrency, network)?.decimals;
142
148
  }
143
149
  //# sourceMappingURL=Charge.js.map
@@ -53,6 +53,11 @@ export declare namespace charge {
53
53
  request: Types.ChargeRequest;
54
54
  source: ReturnType<typeof Types.toSource>;
55
55
  }) => Promise<{
56
+ /**
57
+ * Settlement data to pass through on the Receipt and the x402 `PAYMENT-RESPONSE`, such as
58
+ * an x402 facilitator's `SettleResponse.extensions`.
59
+ */
60
+ extensions?: Record<string, unknown> | undefined;
56
61
  reference: string;
57
62
  timestamp?: string | undefined;
58
63
  }>;
@@ -5,6 +5,7 @@ import * as Method from '../../Method.js';
5
5
  import * as Receipt from '../../Receipt.js';
6
6
  import * as ServerTransport from '../../server/Transport.js';
7
7
  import * as X402 from '../../x402/server/EvmCharge.js';
8
+ import * as Siwx from '../../x402/Siwx.js';
8
9
  import * as Assets from '../Assets.js';
9
10
  import * as Methods from '../Methods.js';
10
11
  import * as Types from '../Types.js';
@@ -13,6 +14,7 @@ export function charge(parameters) {
13
14
  const paths = createPaths(config);
14
15
  const transport = httpTransport(paths);
15
16
  return Method.toServer(Methods.charge, {
17
+ ...(config.x402.siwx ? { authorize: siwxAuthorize(config.x402.siwx) } : {}),
16
18
  canOffer: parameters.canOffer,
17
19
  onPaymentSuccess: parameters.onPaymentSuccess,
18
20
  defaults: {
@@ -102,7 +104,9 @@ export function charge(parameters) {
102
104
  chainId: request.methodDetails.chainId,
103
105
  }),
104
106
  });
107
+ const extensions = toJsonExtensions(settled.extensions);
105
108
  return Receipt.from({
109
+ ...(extensions ? { extensions } : {}),
106
110
  method: Types.paymentMethod,
107
111
  reference: settled.reference,
108
112
  status: 'success',
@@ -206,9 +210,153 @@ function httpTransport(paths) {
206
210
  },
207
211
  });
208
212
  }
213
+ /**
214
+ * SIWX nonces each request has claimed, per replay store, shared by the offers of a
215
+ * composed route. Offers with their own stores each record the nonce in theirs.
216
+ */
217
+ const siwxClaims = new WeakMap();
218
+ /**
219
+ * SIWX nonces an offer of each request found already used. Later offers of a composed
220
+ * route refuse them too, so an offer whose store never saw the nonce can't accept a replay.
221
+ */
222
+ const siwxReplays = new WeakMap();
223
+ /**
224
+ * Grants a request that carries a valid x402 SIWX proof without payment, when the
225
+ * server's `grant` approves the wallet. A request without a proof, or one `grant`
226
+ * refuses, gets the route's 402; an invalid proof gets it with the spec's error code.
227
+ */
228
+ function siwxAuthorize(siwx) {
229
+ return async ({ input, request }) => {
230
+ const value = input.headers.get(Siwx.header);
231
+ if (!value)
232
+ return undefined;
233
+ try {
234
+ const payload = Siwx.decode(value);
235
+ const proof = await Siwx.verify({
236
+ chainId: request.methodDetails.chainId,
237
+ options: siwx,
238
+ payload,
239
+ });
240
+ // A copy, as canOffer and selectOffers get, so a grant that reads the body leaves it
241
+ // for the route handler. Taken before the claim, so a body already read can't spend the
242
+ // nonce: grant then gets the request without its body.
243
+ const copy = cloneGrantInput(input);
244
+ // The copy's body tees the request's, so it is cancelled once grant returns: an unread
245
+ // copy would otherwise buffer everything the route handler later streams from the request.
246
+ let granted;
247
+ try {
248
+ // Reserve the nonce before grant, so a replayed proof never reaches grant. A claim this
249
+ // request already made (a composed offer before this one declined) is shared, so a later
250
+ // offer can still grant the wallet; a proof every offer declined stays spent, so it can't
251
+ // be replayed once grant would approve the wallet. Clients sign a fresh proof each time.
252
+ const stores = siwxClaims.get(input) ?? new WeakMap();
253
+ siwxClaims.set(input, stores);
254
+ const claimed = stores.get(siwx.store) ?? new Set();
255
+ stores.set(siwx.store, claimed);
256
+ const key = `${payload.nonce}:${payload.issuedAt}`;
257
+ const replays = siwxReplays.get(input) ?? new Set();
258
+ siwxReplays.set(input, replays);
259
+ if (replays.has(key))
260
+ throw new Siwx.InvalidProofError('invalid_siwx_nonce');
261
+ if (!claimed.has(key)) {
262
+ try {
263
+ await Siwx.claim({ payload, store: siwx.store });
264
+ }
265
+ catch (error) {
266
+ if (error instanceof Siwx.InvalidProofError)
267
+ replays.add(key);
268
+ throw error;
269
+ }
270
+ claimed.add(key);
271
+ }
272
+ granted = Boolean(await siwx.grant({ ...proof, request: copy }));
273
+ }
274
+ finally {
275
+ releaseGrantInput(copy);
276
+ }
277
+ if (!granted)
278
+ return undefined;
279
+ return {
280
+ receipt: {
281
+ method: Methods.charge.name,
282
+ reference: Types.toSource({ address: proof.address, chainId: proof.chainId }),
283
+ status: 'success',
284
+ timestamp: new Date().toISOString(),
285
+ },
286
+ };
287
+ }
288
+ catch (error) {
289
+ if (error instanceof Siwx.InvalidProofError)
290
+ throw new VerificationFailedError({ reason: error.code });
291
+ throw error;
292
+ }
293
+ };
294
+ }
295
+ /** Clones a request for `grant`, falling back to a bodyless copy when its body was read. */
296
+ function cloneGrantInput(input) {
297
+ try {
298
+ return input.clone();
299
+ }
300
+ catch {
301
+ return new globalThis.Request(input.url, {
302
+ headers: new Headers(input.headers),
303
+ method: input.method,
304
+ signal: input.signal,
305
+ });
306
+ }
307
+ }
308
+ /** Cancels a grant copy's body, so its tee branch stops buffering the request's body. */
309
+ function releaseGrantInput(copy) {
310
+ if (!copy.body || copy.bodyUsed)
311
+ return;
312
+ // Not awaited: a tee branch's cancel settles only once the other branch is done too.
313
+ void copy.body.cancel().catch(() => { });
314
+ }
209
315
  function assertAddressEqual(actual, expected, reason) {
210
316
  if (getAddress(actual) === getAddress(expected))
211
317
  return;
212
318
  throw new VerificationFailedError({ reason });
213
319
  }
320
+ /** Largest serialized settle extensions a receipt carries; larger ones are dropped. */
321
+ const maxExtensionsBytes = 4096;
322
+ /** Deepest nesting settle extensions may have; deeper ones are dropped. */
323
+ const maxExtensionsDepth = 8;
324
+ /**
325
+ * Normalizes settler extensions to the JSON the receipt header carries. A value that isn't a
326
+ * plain JSON object, nests deeper than 8 levels or serializes past 4 KiB is dropped, so a settled
327
+ * payment never fails on its receipt or overflows a client's header limit.
328
+ */
329
+ function toJsonExtensions(extensions) {
330
+ if (!extensions || typeof extensions !== 'object' || Array.isArray(extensions))
331
+ return undefined;
332
+ if (!withinDepth(extensions, maxExtensionsDepth))
333
+ return undefined;
334
+ try {
335
+ const serialized = JSON.stringify(extensions);
336
+ if (new TextEncoder().encode(serialized).byteLength > maxExtensionsBytes)
337
+ return undefined;
338
+ const json = JSON.parse(serialized);
339
+ if (!json || typeof json !== 'object' || Array.isArray(json))
340
+ return undefined;
341
+ return Object.keys(json).length ? json : undefined;
342
+ }
343
+ catch {
344
+ return undefined;
345
+ }
346
+ }
347
+ /** Checks nesting without recursion, so hostile depth can't overflow the stack. */
348
+ function withinDepth(value, limit) {
349
+ const stack = [[value, 1]];
350
+ let visited = 0;
351
+ while (stack.length) {
352
+ const [node, depth] = stack.pop();
353
+ if (!node || typeof node !== 'object')
354
+ continue;
355
+ if (depth > limit || ++visited > 10_000)
356
+ return false;
357
+ for (const child of Object.values(node))
358
+ stack.push([child, depth + 1]);
359
+ }
360
+ return true;
361
+ }
214
362
  //# sourceMappingURL=Charge.js.map
@@ -1,4 +1,5 @@
1
1
  import type { NoExtraKeys } from '../../internal/types.js';
2
+ import * as Facilitator from '../../x402/server/Facilitator.js';
2
3
  import * as Assets from '../Assets.js';
3
4
  import * as Chains from '../Chains.js';
4
5
  import { charge as charge_ } from './Charge.js';
@@ -237,5 +238,12 @@ export declare namespace evm {
237
238
  const assets: typeof Assets;
238
239
  /** Common EVM chain IDs for public config. */
239
240
  const chains: typeof Chains;
241
+ /**
242
+ * Reads the `payTo` an x402 facilitator publishes in `GET /supported` (`kinds[].extra.payTo`),
243
+ * for facilitators that settle into an address of their own. Use it once at startup as `recipient`.
244
+ * Takes a URL, a `{ url, headers }` config or a client; pass `headers` in
245
+ * the parameters to authenticate a URL facilitator.
246
+ */
247
+ const facilitatorPayTo: typeof Facilitator.payTo;
240
248
  }
241
249
  //# sourceMappingURL=Methods.d.ts.map
@@ -1,4 +1,5 @@
1
1
  import * as Currency from '../../Currency.js';
2
+ import * as Facilitator from '../../x402/server/Facilitator.js';
2
3
  import * as Assets from '../Assets.js';
3
4
  import * as Chains from '../Chains.js';
4
5
  import { charge as charge_ } from './Charge.js';
@@ -61,5 +62,12 @@ export function evm(parameters) {
61
62
  evm.assets = Assets;
62
63
  /** Common EVM chain IDs for public config. */
63
64
  evm.chains = Chains;
65
+ /**
66
+ * Reads the `payTo` an x402 facilitator publishes in `GET /supported` (`kinds[].extra.payTo`),
67
+ * for facilitators that settle into an address of their own. Use it once at startup as `recipient`.
68
+ * Takes a URL, a `{ url, headers }` config or a client; pass `headers` in
69
+ * the parameters to authenticate a URL facilitator.
70
+ */
71
+ evm.facilitatorPayTo = Facilitator.payTo;
64
72
  })(evm || (evm = {}));
65
73
  //# sourceMappingURL=Methods.js.map
@@ -0,0 +1,91 @@
1
+ import type { SigningKey } from '../Types.js';
2
+ import type * as Types from './Types.js';
3
+ /**
4
+ * Creates an attestation issuer: signs audience-bound `Identity-Attestation` tokens with one
5
+ * Ed25519 key and publishes that key as a JSON Web Key Set.
6
+ *
7
+ * It is the building block for any identity provider that already knows who its user is (an
8
+ * OpenID Connect sign-in, a wallet service, Tempo ID): after its own check, it calls `sign` with
9
+ * the fact it verified, one attestation per type, and serves `handle` so servers can fetch its
10
+ * key. `signingKey` may be a {@link SigningKey | Signer} whose private key stays in a KMS, HSM or
11
+ * wallet service.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * const issuer = Attestation.Issuer.create({ issuer: 'https://issuer.example', signingKey })
16
+ *
17
+ * // After the user signed in with GitHub:
18
+ * const attestation = await issuer.sign({
19
+ * audience: 'https://api.example',
20
+ * type: 'github',
21
+ * sub: String(user.id),
22
+ * uid: user.accountId,
23
+ * })
24
+ *
25
+ * // In the issuer's fetch handler, before its routes:
26
+ * const answered = await issuer.handle(request)
27
+ * if (answered) return answered
28
+ * ```
29
+ */
30
+ export declare function create(config: create.Config): Issuer;
31
+ export declare namespace create {
32
+ type Config = {
33
+ /** This issuer's URL, which attestations carry as `iss` and servers trust by name. */
34
+ readonly issuer: string;
35
+ /** Ed25519 key pair, or a remote {@link SigningKey | Signer}, that signs attestations. */
36
+ readonly signingKey: SigningKey;
37
+ /** Key identifier. @default the RFC 7638 thumbprint of the public key */
38
+ readonly keyId?: string | undefined;
39
+ /** Seconds each attestation is valid. @default 3600 */
40
+ readonly ttl?: number | undefined;
41
+ };
42
+ }
43
+ /** An attestation issuer from {@link create}. */
44
+ export type Issuer = {
45
+ /** This issuer's URL, without a trailing slash. */
46
+ readonly issuer: string;
47
+ /**
48
+ * Signs one attestation for `audience`. Call it only after checking the fact it states:
49
+ * servers trust it because they trust this issuer.
50
+ */
51
+ readonly sign: (parameters: SignParameters) => Promise<string>;
52
+ /** This issuer's JSON Web Key Set. */
53
+ readonly jwks: () => Promise<{
54
+ readonly keys: readonly JsonWebKey[];
55
+ }>;
56
+ /** Resolves this issuer's key in process, for a server that runs beside it. */
57
+ readonly keyResolver: Types.KeyResolver;
58
+ /**
59
+ * Answers `GET <issuer path>/.well-known/jwks.json` with the key set, and returns `undefined`
60
+ * for every other request.
61
+ */
62
+ readonly handle: (request: Request) => Promise<Response | undefined>;
63
+ };
64
+ /** What {@link Issuer.sign} attests. */
65
+ export type SignParameters = {
66
+ /** Origin of the server the attestation is for, such as `https://api.example`. */
67
+ readonly audience: string;
68
+ /** Attestation type, such as `email` or `github`. */
69
+ readonly type: string;
70
+ /** The attested subject: an address, or the provider's stable account identifier. */
71
+ readonly sub: string;
72
+ /** The issuer's identifier for the user, shared by all of their attestations. */
73
+ readonly uid?: string | undefined;
74
+ /** What the attestation is bound to (RFC 7800). */
75
+ readonly cnf?: Types.Confirmation | undefined;
76
+ /** Other claims to include. Registered claims (`iss`, `aud`, `sub`, `type`, times) win. */
77
+ readonly claims?: Readonly<Record<string, unknown>> | undefined;
78
+ /** Seconds this attestation is valid, instead of the issuer's `ttl`. */
79
+ readonly ttl?: number | undefined;
80
+ };
81
+ /**
82
+ * Thrown by {@link Issuer.sign} for parameters it cannot sign, such as a malformed claim or a token
83
+ * longer than servers accept. Any other error comes from the signing key, such as a remote signer
84
+ * that is unavailable.
85
+ */
86
+ export declare class InvalidParametersError extends TypeError {
87
+ readonly name = "Attestation.Issuer.InvalidParametersError";
88
+ }
89
+ /** Whether a value is a `cnf` object whose `jkt` and `addr`, when present, are strings. */
90
+ export declare function isConfirmation(value: unknown): value is Types.Confirmation;
91
+ //# sourceMappingURL=Issuer.d.ts.map