mppx 0.20.1 → 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 (78) hide show
  1. package/CHANGELOG.md +24 -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 +44 -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/Jwks.js +3 -3
  30. package/dist/extensions/identity/link/server/index.js +4 -4
  31. package/dist/extensions/identity/persona/server/index.js +3 -3
  32. package/dist/internal/CredentialExpiry.d.ts +30 -0
  33. package/dist/internal/CredentialExpiry.js +51 -0
  34. package/dist/internal/version.d.ts +2 -2
  35. package/dist/internal/version.js +1 -1
  36. package/dist/mcp/client/McpClient.js +29 -10
  37. package/dist/middlewares/express.d.ts +7 -2
  38. package/dist/middlewares/express.js +20 -23
  39. package/dist/middlewares/internal/express.d.ts +9 -1
  40. package/dist/middlewares/internal/express.js +348 -2
  41. package/dist/proxy/Proxy.js +15 -3
  42. package/dist/proxy/internal/Replay.d.ts +10 -0
  43. package/dist/proxy/internal/Replay.js +5 -0
  44. package/dist/server/Mppx.d.ts +1 -1
  45. package/dist/server/Mppx.js +19 -14
  46. package/dist/server/NodeListener.js +7 -0
  47. package/dist/server/Request.d.ts +6 -0
  48. package/dist/server/Request.js +43 -22
  49. package/dist/server/internal/challengeMeta.d.ts +10 -0
  50. package/dist/server/internal/challengeMeta.js +31 -1
  51. package/dist/server/internal/host.d.ts +4 -0
  52. package/dist/server/internal/host.js +41 -0
  53. package/dist/tempo/client/Charge.d.ts +5 -4
  54. package/dist/tempo/client/Charge.js +210 -38
  55. package/dist/tempo/client/Subscription.js +3 -0
  56. package/dist/tempo/internal/zone.d.ts +8 -0
  57. package/dist/tempo/internal/zone.js +15 -0
  58. package/dist/tempo/server/Charge.d.ts +19 -0
  59. package/dist/tempo/server/Charge.js +60 -15
  60. package/dist/tempo/server/internal/html.gen.js +1 -1
  61. package/dist/tempo/server/internal/transport.js +10 -54
  62. package/dist/tempo/session/client/ChannelOps.js +1 -1
  63. package/dist/tempo/session/client/SessionManager.d.ts +4 -1
  64. package/dist/tempo/session/client/SessionManager.js +8 -2
  65. package/dist/tempo/session/server/CredentialVerification.js +2 -3
  66. package/dist/viem/Client.d.ts +2 -0
  67. package/dist/viem/Client.js +4 -1
  68. package/dist/x402/Assets.d.ts +6 -0
  69. package/dist/x402/Assets.js +10 -0
  70. package/dist/x402/Types.d.ts +68 -8
  71. package/dist/x402/Types.js +17 -2
  72. package/dist/x402/client/Exact.js +4 -1
  73. package/dist/x402/middlewares/express.js +10 -1
  74. package/dist/x402/server/EvmCharge.d.ts +20 -3
  75. package/dist/x402/server/EvmCharge.js +13 -1
  76. package/dist/x402/server/Facilitator.d.ts +42 -3
  77. package/dist/x402/server/Facilitator.js +126 -16
  78. package/package.json +1 -1
@@ -7,6 +7,7 @@ import * as Expires from '../Expires.js';
7
7
  import * as IdentityRequirements from '../identity/internal/Requirements.js';
8
8
  import * as IdentityServer from '../identity/Server.js';
9
9
  import * as AcceptPayment from '../internal/AcceptPayment.js';
10
+ import * as CredentialExpiry from '../internal/CredentialExpiry.js';
10
11
  import * as Env from '../internal/env.js';
11
12
  import { warnOnce } from '../internal/warnOnce.js';
12
13
  import * as Mcp from '../Mcp.js';
@@ -209,14 +210,6 @@ export function create(config) {
209
210
  reason: 'challenge was not issued by this server',
210
211
  }));
211
212
  }
212
- try {
213
- Expires.assert(credential.challenge.expires, credential.challenge.id);
214
- }
215
- catch (e) {
216
- if (e instanceof Errors.PaymentError)
217
- await fail(e);
218
- throw e;
219
- }
220
213
  if (methodCandidates.length > 1) {
221
214
  const matches = [
222
215
  ...new Set(methodCandidates.filter((candidate) => matchesStandaloneMethod(candidate, credential.challenge.request, options?.request))),
@@ -230,6 +223,16 @@ export function create(config) {
230
223
  }));
231
224
  mi = matches[0];
232
225
  }
226
+ // Checked against the method that matched: only it knows how long after expiry it accepts
227
+ // the credential.
228
+ try {
229
+ CredentialExpiry.assertFor(mi, credential);
230
+ }
231
+ catch (e) {
232
+ if (e instanceof Errors.PaymentError)
233
+ await fail(e);
234
+ throw e;
235
+ }
233
236
  if (parameters.requireValidate && !mi.validate)
234
237
  await fail(new Errors.VerificationFailedError({
235
238
  details: { intent: credIntent, method: credMethod },
@@ -872,7 +875,7 @@ function createMethodFn(parameters) {
872
875
  }
873
876
  // Reject credentials without expires (fail-closed) or with expired timestamp
874
877
  try {
875
- Expires.assert(credential.challenge.expires, credential.challenge.id);
878
+ CredentialExpiry.assertFor(method, credential);
876
879
  }
877
880
  catch (error) {
878
881
  await emitPaymentFailed({
@@ -1380,7 +1383,7 @@ async function resolveRouteChallenge(parameters) {
1380
1383
  description: parameters.description,
1381
1384
  expires: parameters.expires,
1382
1385
  header: parameters.header,
1383
- meta: ChallengeMeta.withNonce(parameters.meta),
1386
+ meta: ChallengeMeta.withNonce(CredentialExpiry.issuanceMeta(parameters.method, parameters.meta)),
1384
1387
  realm: effectiveRealm,
1385
1388
  request: request,
1386
1389
  secretKey: parameters.secretKey,
@@ -1396,7 +1399,7 @@ function createFallbackChallenge(parameters) {
1396
1399
  description: parameters.description,
1397
1400
  expires: parameters.expires,
1398
1401
  header: parameters.header,
1399
- meta: ChallengeMeta.withNonce(parameters.meta),
1402
+ meta: ChallengeMeta.withNonce(CredentialExpiry.issuanceMeta(parameters.method, parameters.meta)),
1400
1403
  realm: parameters.realm ??
1401
1404
  (parameters.capturedRequest
1402
1405
  ? resolveRealmFromCapturedRequest(parameters.capturedRequest)
@@ -2257,10 +2260,12 @@ export function toNodeListener(handler, options) {
2257
2260
  result = await handler(request);
2258
2261
  }
2259
2262
  catch (error) {
2260
- if (!(error instanceof Request.RequestBodyTooLargeError))
2263
+ if (!(error instanceof Request.RequestBodyTooLargeError) &&
2264
+ !(error instanceof Request.UntrustedHostError))
2261
2265
  throw error;
2262
- const response = new globalThis.Response('Payload Too Large', {
2263
- status: 413,
2266
+ const untrusted = error instanceof Request.UntrustedHostError;
2267
+ const response = new globalThis.Response(untrusted ? 'Misdirected Request' : 'Payload Too Large', {
2268
+ status: untrusted ? 421 : 413,
2264
2269
  headers: { 'Content-Type': 'text/plain' },
2265
2270
  });
2266
2271
  await NodeListener.sendResponse(res, response);
@@ -58,6 +58,11 @@ export async function sendResponse(res, response) {
58
58
  }
59
59
  }
60
60
  }
61
+ catch (error) {
62
+ await reader.cancel(error).catch(() => { });
63
+ if (!connectionClosed && !isResponseClosed(res))
64
+ throw error;
65
+ }
61
66
  finally {
62
67
  res.removeListener('close', onClose);
63
68
  reader.releaseLock();
@@ -87,6 +92,8 @@ function waitForDrain(res) {
87
92
  res.removeListener('error', onError);
88
93
  };
89
94
  const onDrain = () => {
95
+ if (res.writableNeedDrain)
96
+ return;
90
97
  cleanup();
91
98
  resolve(true);
92
99
  };
@@ -1,6 +1,8 @@
1
1
  import type { IncomingMessage, RequestListener, ServerResponse } from 'node:http';
2
2
  export type FetchHandler = (request: Request) => Promise<Response> | Response;
3
3
  export type RequestListenerOptions = {
4
+ /** Exact incoming hosts, including ports. Treat the list as immutable; replace the array to change it. Omitted preserves existing behavior; an empty list rejects all hosts. Validate at trusted ingress too; forwarded hosts are not trusted. */
5
+ allowedHosts?: readonly string[] | undefined;
4
6
  host?: string | undefined;
5
7
  /** Maximum accepted request body size in bytes. @default 10485760 (10 MiB) */
6
8
  maxBodySize?: number | undefined;
@@ -9,6 +11,10 @@ export type RequestListenerOptions = {
9
11
  };
10
12
  /** Options used only while converting a Node request to a Fetch request. */
11
13
  export type NodeConversionOptions = Omit<RequestListenerOptions, 'onError'>;
14
+ /** Raised when the incoming Host is outside the configured allowlist. */
15
+ export declare class UntrustedHostError extends Error {
16
+ readonly name = "UntrustedHostError";
17
+ }
12
18
  /** Raised when a Node request body exceeds the configured byte limit. */
13
19
  export declare class RequestBodyTooLargeError extends Error {
14
20
  readonly name = "RequestBodyTooLargeError";
@@ -1,4 +1,9 @@
1
+ import * as Host from './internal/host.js';
1
2
  import * as NodeListener from './NodeListener.js';
3
+ /** Raised when the incoming Host is outside the configured allowlist. */
4
+ export class UntrustedHostError extends Error {
5
+ name = 'UntrustedHostError';
6
+ }
2
7
  const defaultMaxBodySize = 10 * 1024 * 1024;
3
8
  const bodyCompletions = new WeakMap();
4
9
  /** Raised when a Node request body exceeds the configured byte limit. */
@@ -13,19 +18,23 @@ export class RequestBodyTooLargeError extends Error {
13
18
  * @returns A Node.js `(req, res)` listener.
14
19
  */
15
20
  export function toNodeListener(handler, options) {
16
- const onError = options?.onError ??
17
- ((error) => {
18
- if (error instanceof RequestBodyTooLargeError)
19
- return new Response('Payload Too Large', {
20
- status: 413,
21
- headers: { 'Content-Type': 'text/plain' },
22
- });
23
- console.error(error);
24
- return new Response('Internal Server Error', {
25
- status: 500,
21
+ const customOnError = options?.onError;
22
+ const defaultError = (error) => {
23
+ if (error instanceof UntrustedHostError)
24
+ return new Response('Misdirected Request', { status: 421 });
25
+ if (error instanceof RequestBodyTooLargeError)
26
+ return new Response('Payload Too Large', {
27
+ status: 413,
26
28
  headers: { 'Content-Type': 'text/plain' },
27
29
  });
30
+ if (!customOnError)
31
+ console.error(error);
32
+ return new Response('Internal Server Error', {
33
+ status: 500,
34
+ headers: { 'Content-Type': 'text/plain' },
28
35
  });
36
+ };
37
+ const onError = customOnError ?? defaultError;
29
38
  return (async (req, res) => {
30
39
  let response;
31
40
  try {
@@ -35,12 +44,7 @@ export function toNodeListener(handler, options) {
35
44
  }
36
45
  catch (error) {
37
46
  try {
38
- response =
39
- (await onError(error)) ??
40
- new Response('Internal Server Error', {
41
- status: 500,
42
- headers: { 'Content-Type': 'text/plain' },
43
- });
47
+ response = (await onError(error)) ?? defaultError(error);
44
48
  }
45
49
  catch (innerError) {
46
50
  console.error(`There was an error in the error handler: ${innerError}`);
@@ -50,7 +54,22 @@ export function toNodeListener(handler, options) {
50
54
  });
51
55
  }
52
56
  }
53
- await NodeListener.sendResponse(res, response);
57
+ try {
58
+ await NodeListener.sendResponse(res, response);
59
+ }
60
+ catch (error) {
61
+ try {
62
+ await onError(error);
63
+ }
64
+ catch (innerError) {
65
+ console.error(`There was an error in the error handler: ${innerError}`);
66
+ }
67
+ finally {
68
+ // Transmission may already have sent headers; never send a second response.
69
+ if (!res.destroyed)
70
+ res.destroy();
71
+ }
72
+ }
54
73
  });
55
74
  }
56
75
  /**
@@ -61,21 +80,23 @@ export function toNodeListener(handler, options) {
61
80
  * @returns A Fetch API Request.
62
81
  */
63
82
  export function fromNodeListener(req, res, options) {
83
+ const headers = createHeaders(req);
84
+ const incomingHost = headers.get('Host') ?? req.headers[':authority'] ?? 'localhost';
85
+ const fixedHost = options?.host !== undefined;
86
+ const checkedHost = fixedHost ? (req.headers.host ?? incomingHost) : incomingHost;
87
+ if (!Host.isAllowed(req, options?.allowedHosts, checkedHost, fixedHost))
88
+ throw new UntrustedHostError('Incoming host is not allowed.');
64
89
  let controller = new AbortController();
65
90
  res.once('close', () => controller?.abort());
66
91
  res.once('finish', () => {
67
92
  controller = null;
68
93
  });
69
94
  const method = req.method ?? 'GET';
70
- const headers = createHeaders(req);
71
95
  const protocol = options?.protocol ??
72
96
  ('encrypted' in req.socket && req.socket.encrypted
73
97
  ? 'https:'
74
98
  : 'http:');
75
- const host = options?.host ??
76
- headers.get('Host') ??
77
- req.headers[':authority'] ??
78
- 'localhost';
99
+ const host = options?.host ?? incomingHost;
79
100
  const url = createRequestUrl(req.url, `${protocol}//${host}`);
80
101
  const init = {
81
102
  method,
@@ -1,5 +1,15 @@
1
1
  /** Adds fresh issuance randomness while preserving application and route metadata. */
2
2
  export declare function withNonce(meta: Record<string, string> | undefined): Record<string, string>;
3
+ /** Sets the expiry grace marker when `grace` is true and removes any copy of it otherwise. */
4
+ export declare function withExpiryGrace(meta: Record<string, string> | undefined, grace: boolean): Record<string, string> | undefined;
5
+ /**
6
+ * Whether the challenge carries the expiry grace marker. Reads `opaque` when present, the
7
+ * value the challenge HMAC covers, and `meta` only otherwise.
8
+ */
9
+ export declare function hasExpiryGrace(challenge: {
10
+ meta?: Record<string, string> | undefined;
11
+ opaque?: string | undefined;
12
+ }): boolean;
3
13
  /** Removes issuance-only metadata when comparing stable route requirements. */
4
14
  export declare function routeMeta(meta: Record<string, string> | undefined): Record<string, string> | undefined;
5
15
  //# sourceMappingURL=challengeMeta.d.ts.map
@@ -1,4 +1,5 @@
1
1
  import { Secp256k1 } from 'ox';
2
+ import * as PaymentRequest from '../../PaymentRequest.js';
2
3
  /** Reserved metadata key for HMAC-bound, per-issuance challenge randomness. */
3
4
  const nonceKey = '_mppx_nonce';
4
5
  /** Adds fresh issuance randomness while preserving application and route metadata. */
@@ -6,11 +7,40 @@ export function withNonce(meta) {
6
7
  // Ox uses runtime-specific secure randomness, including Node without global Web Crypto.
7
8
  return { ...meta, [nonceKey]: Secp256k1.randomPrivateKey() };
8
9
  }
10
+ /**
11
+ * Reserved metadata key marking a challenge whose method accepts some of its credentials for a
12
+ * while after it expires. Bound by the challenge HMAC, so a challenge issued without it, by an
13
+ * earlier release or with no grace configured, never gets that grace.
14
+ */
15
+ const expiryGraceKey = '_mppx_expiry_grace';
16
+ /** Sets the expiry grace marker when `grace` is true and removes any copy of it otherwise. */
17
+ export function withExpiryGrace(meta, grace) {
18
+ const { [expiryGraceKey]: _, ...rest } = meta ?? {};
19
+ if (grace)
20
+ return { ...rest, [expiryGraceKey]: '1' };
21
+ return meta === undefined || !(expiryGraceKey in meta) ? meta : rest;
22
+ }
23
+ /**
24
+ * Whether the challenge carries the expiry grace marker. Reads `opaque` when present, the
25
+ * value the challenge HMAC covers, and `meta` only otherwise.
26
+ */
27
+ export function hasExpiryGrace(challenge) {
28
+ const { meta, opaque } = challenge;
29
+ if (opaque === undefined)
30
+ return meta?.[expiryGraceKey] === '1';
31
+ try {
32
+ const decoded = PaymentRequest.deserialize(opaque);
33
+ return decoded?.[expiryGraceKey] === '1';
34
+ }
35
+ catch {
36
+ return false;
37
+ }
38
+ }
9
39
  /** Issuance-only identity nonce of earlier mppx releases with payment-stage verifiers; still ignored. */
10
40
  const legacyIdentityKey = '_mppx_identity';
11
41
  /** Removes issuance-only metadata when comparing stable route requirements. */
12
42
  export function routeMeta(meta) {
13
- const { [nonceKey]: _, [legacyIdentityKey]: __, ...rest } = meta ?? {};
43
+ const { [nonceKey]: _, [legacyIdentityKey]: __, [expiryGraceKey]: ___, ...rest } = meta ?? {};
14
44
  return Object.keys(rest).length ? rest : undefined;
15
45
  }
16
46
  //# sourceMappingURL=challengeMeta.js.map
@@ -0,0 +1,4 @@
1
+ import type { IncomingMessage } from 'node:http';
2
+ /** Validates every incoming authority before Node or Express normalizes duplicate headers. */
3
+ export declare function isAllowed(request: Pick<IncomingMessage, 'headers' | 'rawHeaders'>, allowedHosts: readonly string[] | undefined, urlAuthority: string | undefined, allowNormalizedOnly?: boolean): boolean;
4
+ //# sourceMappingURL=host.d.ts.map
@@ -0,0 +1,41 @@
1
+ const normalizedHosts = new WeakMap();
2
+ /** Validates every incoming authority before Node or Express normalizes duplicate headers. */
3
+ export function isAllowed(request, allowedHosts, urlAuthority, allowNormalizedOnly = false) {
4
+ if (allowedHosts === undefined)
5
+ return true;
6
+ if (typeof urlAuthority !== 'string' || urlAuthority.length === 0)
7
+ return false;
8
+ const authorities = [urlAuthority];
9
+ const names = new Set();
10
+ for (let i = 0; i < request.rawHeaders.length; i += 2) {
11
+ const name = request.rawHeaders[i]?.toLowerCase();
12
+ if (name !== 'host' && name !== ':authority')
13
+ continue;
14
+ if (names.has(name))
15
+ return false;
16
+ names.add(name);
17
+ authorities.push(request.rawHeaders[i + 1] ?? '');
18
+ }
19
+ const host = request.headers.host;
20
+ const authority = request.headers[':authority'];
21
+ if (host !== undefined)
22
+ authorities.push(host);
23
+ if (authority !== undefined) {
24
+ if (typeof authority !== 'string')
25
+ return false;
26
+ authorities.push(authority);
27
+ }
28
+ if (names.size === 0 &&
29
+ (!allowNormalizedOnly || (typeof host !== 'string' && typeof authority !== 'string')))
30
+ return false;
31
+ const expected = authorities[0]?.toLowerCase();
32
+ if (expected === undefined || !authorities.every((value) => value.toLowerCase() === expected))
33
+ return false;
34
+ let allowed = normalizedHosts.get(allowedHosts);
35
+ if (!allowed) {
36
+ allowed = new Set(allowedHosts.map((value) => value.toLowerCase()));
37
+ normalizedHosts.set(allowedHosts, allowed);
38
+ }
39
+ return allowed.has(expected);
40
+ }
41
+ //# sourceMappingURL=host.js.map
@@ -281,14 +281,15 @@ export declare namespace charge {
281
281
  * charge, parsed with the matched currency's decimals. Values with more fractional digits than
282
282
  * `decimals` are rejected rather than rounded. Compared against the challenge
283
283
  * amount, which includes splits; larger offers are skipped during selection and
284
- * rejected before signing. Applies per credential, not cumulatively across
285
- * payment retries. Requires `currencies`.
284
+ * rejected before signing. A payment from a Zone balance also pays the Zone's
285
+ * withdrawal fee, so the amount plus that fee must fit, checked before withdrawing.
286
+ * Applies per credential, not cumulatively across payment retries. Requires `currencies`.
286
287
  */
287
288
  maxAmount?: string | undefined;
288
289
  /**
289
290
  * Maximum amount the client is willing to pay per charge, in raw base units of
290
- * the challenge currency (compared directly with the challenge `amount`).
291
- * Checked like `maxAmount`. Requires `currencies`.
291
+ * the challenge currency (compared directly with the challenge `amount`, plus the
292
+ * withdrawal fee for a Zone payment). Checked like `maxAmount`. Requires `currencies`.
292
293
  */
293
294
  maxAtomicAmount?: string | undefined;
294
295
  /**