mppx 0.17.5 → 0.18.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 (71) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/dist/cli/cli.js +141 -139
  3. package/dist/cli/plugins/index.js +6 -6
  4. package/dist/cli/stripe.d.ts +6 -1
  5. package/dist/cli/stripe.js +89 -5
  6. package/dist/client/Mppx.js +13 -3
  7. package/dist/client/internal/Fetch.js +9 -5
  8. package/dist/extensions/identity/attestation/Constants.d.ts +23 -0
  9. package/dist/extensions/identity/attestation/Constants.js +23 -0
  10. package/dist/extensions/identity/attestation/Jwks.d.ts +30 -0
  11. package/dist/extensions/identity/attestation/Jwks.js +114 -0
  12. package/dist/extensions/identity/attestation/Token.d.ts +80 -0
  13. package/dist/extensions/identity/attestation/Token.js +143 -0
  14. package/dist/extensions/identity/attestation/Types.d.ts +48 -0
  15. package/dist/extensions/identity/attestation/Types.js +2 -0
  16. package/dist/extensions/identity/attestation/client/index.d.ts +66 -0
  17. package/dist/extensions/identity/attestation/client/index.js +273 -0
  18. package/dist/extensions/identity/attestation/index.d.ts +20 -0
  19. package/dist/extensions/identity/attestation/index.js +18 -0
  20. package/dist/extensions/identity/attestation/internal/Cache.d.ts +120 -0
  21. package/dist/extensions/identity/attestation/internal/Cache.js +90 -0
  22. package/dist/extensions/identity/attestation/server/index.d.ts +66 -0
  23. package/dist/extensions/identity/attestation/server/index.js +119 -0
  24. package/dist/extensions/identity/email-otp/Constants.d.ts +16 -0
  25. package/dist/extensions/identity/email-otp/Constants.js +17 -0
  26. package/dist/extensions/identity/email-otp/Types.d.ts +12 -0
  27. package/dist/extensions/identity/email-otp/Types.js +2 -0
  28. package/dist/extensions/identity/email-otp/client/index.d.ts +123 -0
  29. package/dist/extensions/identity/email-otp/client/index.js +131 -0
  30. package/dist/extensions/identity/email-otp/index.d.ts +12 -0
  31. package/dist/extensions/identity/email-otp/index.js +11 -0
  32. package/dist/extensions/identity/email-otp/server/index.d.ts +48 -0
  33. package/dist/extensions/identity/email-otp/server/index.js +59 -0
  34. package/dist/extensions/identity/index.d.ts +4 -0
  35. package/dist/extensions/identity/index.js +4 -0
  36. package/dist/extensions/identity/internal/Verification.js +9 -5
  37. package/dist/identity/Callback.d.ts +66 -0
  38. package/dist/identity/Callback.js +88 -0
  39. package/dist/identity/Client.d.ts +78 -5
  40. package/dist/identity/Client.js +165 -48
  41. package/dist/identity/Headers.d.ts +16 -0
  42. package/dist/identity/Headers.js +19 -0
  43. package/dist/identity/Server.d.ts +159 -37
  44. package/dist/identity/Server.js +307 -138
  45. package/dist/identity/Status.d.ts +14 -0
  46. package/dist/identity/Status.js +19 -0
  47. package/dist/identity/Types.d.ts +161 -65
  48. package/dist/identity/index.d.ts +3 -0
  49. package/dist/identity/index.js +3 -0
  50. package/dist/identity/internal/Requirements.d.ts +28 -0
  51. package/dist/identity/internal/Requirements.js +78 -0
  52. package/dist/integrations/x402/Evm.d.ts +1 -0
  53. package/dist/internal/env.d.ts +14 -0
  54. package/dist/internal/env.js +38 -0
  55. package/dist/internal/version.d.ts +2 -2
  56. package/dist/internal/version.js +1 -1
  57. package/dist/proxy/internal/Headers.d.ts +1 -1
  58. package/dist/proxy/internal/Headers.js +7 -1
  59. package/dist/server/Mppx.d.ts +14 -6
  60. package/dist/server/Mppx.js +252 -148
  61. package/dist/server/internal/challengeMeta.d.ts +0 -6
  62. package/dist/server/internal/challengeMeta.js +3 -17
  63. package/dist/tempo/server/Charge.d.ts +14 -9
  64. package/dist/tempo/server/Charge.js +5 -1
  65. package/dist/tempo/server/Methods.js +4 -1
  66. package/dist/tempo/server/Subscription.d.ts +8 -0
  67. package/dist/tempo/server/internal/fallback-store.d.ts +7 -2
  68. package/dist/tempo/server/internal/fallback-store.js +12 -3
  69. package/dist/tempo/server/internal/html.gen.js +1 -1
  70. package/dist/tempo/session/server/Session.d.ts +5 -1
  71. package/package.json +9 -1
@@ -1,10 +1,14 @@
1
+ /** The identity status of each non-verified HTTP message signature result. */
2
+ const statuses = {
3
+ absent: 'missing',
4
+ invalid: 'invalid',
5
+ // The signature was presented, but its key is not trusted or could not be resolved.
6
+ unverified: 'forbidden',
7
+ };
1
8
  /** Maps a non-verified HTTP message signature result to an identity verification. */
2
9
  export function fromSignature(result) {
3
10
  if (result.status === 'absent')
4
- return { status: 'missing' };
5
- if (result.status === 'invalid')
6
- return { status: 'invalid', reason: result.reason };
7
- // The signature was presented but its key is not trusted or available.
8
- return { status: 'invalid', code: 403, reason: result.reason };
11
+ return { status: statuses.absent };
12
+ return { status: statuses[result.status], reason: result.reason };
9
13
  }
10
14
  //# sourceMappingURL=Verification.js.map
@@ -0,0 +1,66 @@
1
+ import type { MaybePromise } from '../internal/types.js';
2
+ import type * as Types from './Types.js';
3
+ /**
4
+ * Creates a request-stage verifier from a function, such as a lookup in your
5
+ * own database, session store or KYC provider.
6
+ *
7
+ * `verify` returns the caller's identity, which the route handler reads with
8
+ * `result.identity.get(verifier)`; `undefined` or `null` when the request carries none
9
+ * (`missing`, 401, with `challenge` headers if set); or throws a {@link Rejection} to
10
+ * reject the identity it carries.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * const customer = Identity.from({
15
+ * async verify(request) {
16
+ * const key = request.headers.get('X-Api-Key')
17
+ * if (!key) return undefined
18
+ * const row = await db.customerByKey(key)
19
+ * if (!row) throw new Identity.Rejection('Unknown API key.', { status: 'forbidden' })
20
+ * return row
21
+ * },
22
+ * })
23
+ * mppx.charge({ amount: '1', identity: [customer] })
24
+ * ```
25
+ */
26
+ export declare function from<value>(config: from.Config<value>): Types.Verifier<value>;
27
+ export declare namespace from {
28
+ type Config<value> = {
29
+ /**
30
+ * Returns the request's verified identity, `undefined` or `null` when it carries none,
31
+ * or throws a {@link Rejection} to reject the one it carries.
32
+ */
33
+ verify: (request: Request) => MaybePromise<value | null | undefined>;
34
+ /** Headers sent with a rejection, telling the client what identity to present. */
35
+ challenge?: HeadersInit | undefined;
36
+ };
37
+ }
38
+ /** Rejects an identity a {@link from} verifier was given. */
39
+ export declare class Rejection extends Error {
40
+ readonly name = "Rejection";
41
+ /** Fixed status of the rejection. @default 'invalid' */
42
+ readonly status: Rejection.Status;
43
+ /**
44
+ * HTTP status of the rejection.
45
+ *
46
+ * @deprecated Read `status`. Defaults to the status's fixed code (`Identity.Status.codes`).
47
+ */
48
+ readonly code: number;
49
+ constructor(message: string, options?: Rejection.Options);
50
+ }
51
+ export declare namespace Rejection {
52
+ /** Fixed statuses a {@link Rejection} can carry. */
53
+ type Status = Exclude<Types.RejectionStatus, 'missing'>;
54
+ type Options = {
55
+ /** Fixed status of the rejection. @default 'invalid' */
56
+ status?: Status | undefined;
57
+ /**
58
+ * HTTP status of the rejection.
59
+ *
60
+ * @deprecated Use `status`. 403 maps to `forbidden`, 503 to `unavailable`, and any other
61
+ * code to `invalid`, sent with that code.
62
+ */
63
+ code?: number | undefined;
64
+ };
65
+ }
66
+ //# sourceMappingURL=Callback.d.ts.map
@@ -0,0 +1,88 @@
1
+ import * as Status from './Status.js';
2
+ /**
3
+ * Creates a request-stage verifier from a function, such as a lookup in your
4
+ * own database, session store or KYC provider.
5
+ *
6
+ * `verify` returns the caller's identity, which the route handler reads with
7
+ * `result.identity.get(verifier)`; `undefined` or `null` when the request carries none
8
+ * (`missing`, 401, with `challenge` headers if set); or throws a {@link Rejection} to
9
+ * reject the identity it carries.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * const customer = Identity.from({
14
+ * async verify(request) {
15
+ * const key = request.headers.get('X-Api-Key')
16
+ * if (!key) return undefined
17
+ * const row = await db.customerByKey(key)
18
+ * if (!row) throw new Identity.Rejection('Unknown API key.', { status: 'forbidden' })
19
+ * return row
20
+ * },
21
+ * })
22
+ * mppx.charge({ amount: '1', identity: [customer] })
23
+ * ```
24
+ */
25
+ export function from(config) {
26
+ return Object.freeze({
27
+ async verify(request) {
28
+ let value;
29
+ try {
30
+ value = await config.verify(request);
31
+ }
32
+ catch (error) {
33
+ if (!(error instanceof Rejection))
34
+ throw error;
35
+ const { code, message: reason } = error;
36
+ // Fails closed: a status set at runtime outside the fixed rejections is `invalid`.
37
+ const status = isRejectionStatus(error.status) ? error.status : 'invalid';
38
+ if (status !== 'invalid')
39
+ return { status, headers: config.challenge, reason };
40
+ return {
41
+ status,
42
+ // A deprecated non-standard code is still sent as is.
43
+ ...(code !== Status.codes.invalid && { code }),
44
+ headers: config.challenge,
45
+ reason,
46
+ };
47
+ }
48
+ // A lookup that found nothing often returns null: treat it as no identity.
49
+ if (value === undefined || value === null)
50
+ return {
51
+ status: 'missing',
52
+ headers: config.challenge,
53
+ reason: 'Identity verification is required.',
54
+ };
55
+ return { status: 'valid', value };
56
+ },
57
+ });
58
+ }
59
+ const rejectionStatuses = ['invalid', 'forbidden', 'unavailable'];
60
+ function isRejectionStatus(status) {
61
+ return rejectionStatuses.includes(status);
62
+ }
63
+ /** Rejects an identity a {@link from} verifier was given. */
64
+ export class Rejection extends Error {
65
+ name = 'Rejection';
66
+ /** Fixed status of the rejection. @default 'invalid' */
67
+ status;
68
+ /**
69
+ * HTTP status of the rejection.
70
+ *
71
+ * @deprecated Read `status`. Defaults to the status's fixed code (`Identity.Status.codes`).
72
+ */
73
+ code;
74
+ constructor(message, options = {}) {
75
+ super(message);
76
+ if (options.status !== undefined && !isRejectionStatus(options.status))
77
+ throw new TypeError(`Identity rejection status must be one of ${rejectionStatuses.join(', ')}.`);
78
+ this.status =
79
+ options.status ??
80
+ (options.code === Status.codes.forbidden
81
+ ? 'forbidden'
82
+ : options.code === Status.codes.unavailable
83
+ ? 'unavailable'
84
+ : 'invalid');
85
+ this.code = options.code ?? Status.codes[this.status];
86
+ }
87
+ }
88
+ //# sourceMappingURL=Callback.js.map
@@ -1,4 +1,17 @@
1
+ import * as Challenge from '../Challenge.js';
1
2
  import type * as Types from './Types.js';
3
+ /** Headers a prover's `retry` returned, as name and value pairs. */
4
+ export type ResendHeaders = readonly (readonly [name: string, value: string])[];
5
+ /** Payment state of one send. */
6
+ export type SendContext = {
7
+ /** The Challenge a paid attempt answers. Its presence makes the attempt paid. */
8
+ readonly challenge?: Challenge.Challenge | undefined;
9
+ /**
10
+ * Headers a `retry` returned earlier in the same logical request, such as on the unpaid
11
+ * attempt before a 402. They are set before the provers run, so the paid attempt carries them.
12
+ */
13
+ readonly headers?: ResendHeaders | undefined;
14
+ };
2
15
  /** Sends HTTP attempts with every in-scope prover applied. */
3
16
  export type Client = {
4
17
  /**
@@ -10,13 +23,73 @@ export type Client = {
10
23
  * (non-402) response, the request is proved again and resent once, except for
11
24
  * paid attempts, which are never resent.
12
25
  */
13
- send: (fetch: typeof globalThis.fetch, request: Request, context?: Types.Context) => Promise<{
26
+ readonly send: (fetch: typeof globalThis.fetch, request: Request, context?: SendContext) => Promise<{
14
27
  request: Request;
15
28
  response: Response;
29
+ /** The retry headers the last attempt carried, to pass on to the paid attempt. */
30
+ headers: ResendHeaders;
16
31
  }>;
17
- /** Lets in-scope provers prepare proofs for a 402 challenge from `url` before the payment retry. */
18
- challenge: (response: Response, context: Types.Context, url: string) => Promise<void>;
32
+ /**
33
+ * Lets in-scope provers prepare proofs for a 402 from `url` before the payment retry,
34
+ * with the selected Challenge and the requirements of the 402's `Identity-Required` header.
35
+ */
36
+ readonly challenge: (response: Response, context: {
37
+ readonly challenge: Challenge.Challenge;
38
+ }, url: string) => Promise<void>;
39
+ /** Extra sensitive request headers the provers declare (`Prover.headers`), lowercased. */
40
+ readonly headers: readonly string[];
19
41
  };
42
+ /**
43
+ * The state of one `send`, as a state machine:
44
+ *
45
+ * - `unproved`: nothing sent yet.
46
+ * - `sent`: an unpaid attempt was sent; it may be resent once.
47
+ * - `paid`: a paid attempt was sent; it is never resent, since its payment may have settled.
48
+ * - `resent`: the request is proved again and resent once, with `headers` set.
49
+ * - `done`: the last response is final.
50
+ *
51
+ * @internal
52
+ */
53
+ export type Attempt = {
54
+ readonly phase: 'unproved';
55
+ } | {
56
+ readonly phase: 'sent';
57
+ } | {
58
+ readonly phase: 'paid';
59
+ } | {
60
+ readonly phase: 'resent';
61
+ readonly headers: ResendHeaders;
62
+ } | {
63
+ readonly phase: 'done';
64
+ };
65
+ /** An input to {@link transition}. @internal */
66
+ export type AttemptEvent =
67
+ /** The first attempt is sent, paid (a Challenge or payment credential) or not. */
68
+ {
69
+ readonly type: 'send';
70
+ readonly payment: 'paid' | 'unpaid';
71
+ }
72
+ /** A response arrived; `resend` holds the headers provers asked to resend with, if any. */
73
+ | {
74
+ readonly type: 'response';
75
+ readonly resend: ResendHeaders | undefined;
76
+ };
77
+ /** The state of a `send` before anything is sent. @internal */
78
+ export declare const initial: Attempt;
79
+ /**
80
+ * Returns the next attempt state. Pure; throws a `TypeError` for an event the current phase
81
+ * does not accept, such as resending a paid attempt or resending twice.
82
+ *
83
+ * | Phase | Event | Next |
84
+ * | ------------------ | ---------------------- | ---------- |
85
+ * | `unproved` | `send` (paid) | `paid` |
86
+ * | `unproved` | `send` (unpaid) | `sent` |
87
+ * | `sent` | `response` with resend | `resent` |
88
+ * | `sent`, `paid`, `resent` | `response` without | `done` |
89
+ *
90
+ * @internal
91
+ */
92
+ export declare function transition(attempt: Attempt, event: AttemptEvent): Attempt;
20
93
  /**
21
94
  * Creates the client runner for a list of provers.
22
95
  *
@@ -28,7 +101,7 @@ export declare function from(provers: readonly Types.Prover[]): Client;
28
101
  /**
29
102
  * Wraps a fetch implementation so every request is proved.
30
103
  *
31
- * Prefer `Mppx.create({ identity })`, which also passes the payment challenge to provers.
104
+ * Prefer `Mppx.create({ identity })`, which also passes the payment Challenge to provers.
32
105
  */
33
- export declare function wrapFetch(fetch: typeof globalThis.fetch, client: Client, context?: Types.Context): typeof globalThis.fetch;
106
+ export declare function wrapFetch(fetch: typeof globalThis.fetch, client: Client, context?: SendContext): typeof globalThis.fetch;
34
107
  //# sourceMappingURL=Client.d.ts.map
@@ -1,9 +1,50 @@
1
1
  import * as Challenge from '../Challenge.js';
2
2
  import * as Credential from '../Credential.js';
3
+ import * as Requirements from './internal/Requirements.js';
3
4
  import * as SigningContext from './internal/SigningContext.js';
4
5
  const skipPayment = Symbol.for('mppx.fetch.skipPayment');
5
6
  /** x402 credential headers (v2 and v1); a request carrying one is a paid attempt. */
6
7
  const x402CredentialHeaders = ['payment-signature', 'x-payment'];
8
+ /** Payment credential headers a prover's retry headers may never set, lowercased. */
9
+ const credentialHeaders = new Set([
10
+ 'authorization',
11
+ 'payment-authorization',
12
+ ...x402CredentialHeaders,
13
+ ]);
14
+ /** The state of a `send` before anything is sent. @internal */
15
+ export const initial = Object.freeze({ phase: 'unproved' });
16
+ /**
17
+ * Returns the next attempt state. Pure; throws a `TypeError` for an event the current phase
18
+ * does not accept, such as resending a paid attempt or resending twice.
19
+ *
20
+ * | Phase | Event | Next |
21
+ * | ------------------ | ---------------------- | ---------- |
22
+ * | `unproved` | `send` (paid) | `paid` |
23
+ * | `unproved` | `send` (unpaid) | `sent` |
24
+ * | `sent` | `response` with resend | `resent` |
25
+ * | `sent`, `paid`, `resent` | `response` without | `done` |
26
+ *
27
+ * @internal
28
+ */
29
+ export function transition(attempt, event) {
30
+ switch (event.type) {
31
+ case 'send':
32
+ if (attempt.phase !== 'unproved')
33
+ break;
34
+ return Object.freeze({ phase: event.payment === 'paid' ? 'paid' : 'sent' });
35
+ case 'response':
36
+ if (event.resend === undefined) {
37
+ if (attempt.phase === 'unproved' || attempt.phase === 'done')
38
+ break;
39
+ return Object.freeze({ phase: 'done' });
40
+ }
41
+ if (attempt.phase !== 'sent')
42
+ break;
43
+ return Object.freeze({ phase: 'resent', headers: event.resend });
44
+ }
45
+ const resend = event.type === 'response' && event.resend !== undefined ? ' with resend' : '';
46
+ throw new TypeError(`Illegal identity attempt transition "${event.type}${resend}" from phase "${attempt.phase}".`);
47
+ }
7
48
  /**
8
49
  * Creates the client runner for a list of provers.
9
50
  *
@@ -18,19 +59,44 @@ export function from(provers) {
18
59
  for (const prover of provers)
19
60
  if (prover.scope !== '*' && !Array.isArray(prover.scope))
20
61
  throw new TypeError('Identity prover scope must be "*" or an array of origins.');
62
+ const headers = Object.freeze([
63
+ ...new Set(provers.flatMap((prover) => {
64
+ if (prover.headers !== undefined && !Array.isArray(prover.headers))
65
+ throw new TypeError('Identity prover headers must be an array of header names.');
66
+ return (prover.headers ?? []).map((name) => name.toLowerCase());
67
+ })),
68
+ ]);
21
69
  const inScope = (url) => {
22
70
  const origin = new URL(url).origin;
23
71
  return provers.filter((prover) => prover.scope === '*' || prover.scope.includes(origin));
24
72
  };
25
- async function sendOnce(fetch, request, context, resendable) {
73
+ async function sendOnce(parameters) {
74
+ const { context, fetch, headers, keepReadable, request } = parameters;
26
75
  // Keep the original readable only when it may be resent; otherwise a clone would tee
27
76
  // (and buffer) a streamed body that is never read again.
28
- const source = resendable ? request.clone() : request;
77
+ const source = keepReadable ? request.clone() : request;
29
78
  const scoped = inScope(request.url);
30
79
  if (scoped.length === 0)
31
80
  return { request: source, response: await fetch(source) };
32
- const attempt = Object.freeze({ ...context, ...SigningContext.create() });
81
+ const attempt = Object.freeze({
82
+ ...SigningContext.create(),
83
+ ...(context.challenge && { challenge: context.challenge }),
84
+ });
85
+ // Resend headers are set before the provers run, so signing provers cover them.
86
+ const merged = new Headers(source.headers);
87
+ // Retry headers never replace a payment credential: the fixed credential headers, the one the
88
+ // Challenge names, or any header that already holds a Payment credential.
89
+ const protectedHeaders = new Set(credentialHeaders);
90
+ if (context.challenge)
91
+ protectedHeaders.add(Challenge.credentialHeader(context.challenge).toLowerCase());
92
+ for (const [name, value] of source.headers)
93
+ if (Credential.extractPaymentScheme(value) !== null)
94
+ protectedHeaders.add(name.toLowerCase());
95
+ for (const [name, value] of headers)
96
+ if (!protectedHeaders.has(name.toLowerCase()))
97
+ merged.set(name, value);
33
98
  let sent = new Request(source, {
99
+ headers: merged,
34
100
  redirect: request.redirect === 'follow' ? 'error' : request.redirect,
35
101
  });
36
102
  for (const prover of scoped)
@@ -38,37 +104,34 @@ export function from(provers) {
38
104
  return { request: sent, response: await fetch(sent) };
39
105
  }
40
106
  return {
107
+ headers,
41
108
  async send(fetch, request, context = {}) {
42
- // A paid attempt (a challenge in context, or a Payment or x402 credential the caller
43
- // attached) is never resent: its credential may already have settled, and replaying it
44
- // could pay again.
45
- const paid = context.challenge !== undefined ||
46
- x402CredentialHeaders.some((name) => request.headers.has(name)) ||
47
- [...request.headers.values()].some((value) => Credential.extractPaymentScheme(value) !== null);
48
- const resendable = !paid && inScope(request.url).some((prover) => prover.retry);
49
- const result = await sendOnce(fetch, request, context, resendable);
109
+ let attempt = transition(initial, {
110
+ type: 'send',
111
+ payment: isPaid(request, context) ? 'paid' : 'unpaid',
112
+ });
113
+ const retriers = inScope(request.url).filter((prover) => prover.retry);
114
+ const keepReadable = attempt.phase === 'sent' && retriers.length > 0;
115
+ const carried = context.headers ?? [];
116
+ const result = await sendOnce({ context, fetch, headers: carried, keepReadable, request });
50
117
  const { response } = result;
51
- if (!resendable || response.status < 400 || response.status === 402)
52
- return result;
53
- // Each callback reads its own copy, so the returned response stays readable.
54
- const copies = [];
55
- let retry = false;
56
- for (const prover of inScope(request.url)) {
57
- if (!prover.retry)
58
- continue;
59
- const copy = response.clone();
60
- copies.push(copy);
61
- if (await prover.retry(copy))
62
- retry = true;
63
- }
64
- if (!retry) {
65
- release(copies);
66
- return result;
67
- }
68
- release([response, ...copies]);
69
- return sendOnce(fetch, request, context, false);
118
+ const resend = keepReadable && response.status >= 400 && response.status !== 402
119
+ ? await resendHeaders(retriers, response, result.request)
120
+ : undefined;
121
+ attempt = transition(attempt, { type: 'response', resend });
122
+ if (attempt.phase !== 'resent')
123
+ return { ...result, headers: carried };
124
+ release([response]);
125
+ const headers = mergeHeaders(carried, attempt.headers);
126
+ const resent = await sendOnce({ context, fetch, headers, keepReadable: false, request });
127
+ transition(attempt, { type: 'response', resend: undefined });
128
+ return { ...resent, headers };
70
129
  },
71
- async challenge(response, context, url) {
130
+ async challenge(response, { challenge }, url) {
131
+ const context = Object.freeze({
132
+ challenge,
133
+ requirements: Requirements.parse(response.headers.get(Requirements.header)),
134
+ });
72
135
  for (const prover of inScope(url)) {
73
136
  if (!prover.prepare)
74
137
  continue;
@@ -83,6 +146,50 @@ export function from(provers) {
83
146
  },
84
147
  };
85
148
  }
149
+ /**
150
+ * Whether a send is a paid attempt: a Challenge in context, or a Payment or x402 credential the
151
+ * caller attached. Its credential may already have settled, so replaying it could pay again.
152
+ */
153
+ function isPaid(request, context) {
154
+ return (context.challenge !== undefined ||
155
+ x402CredentialHeaders.some((name) => request.headers.has(name)) ||
156
+ [...request.headers.values()].some((value) => Credential.extractPaymentScheme(value) !== null));
157
+ }
158
+ /**
159
+ * Asks each prover whether to resend a rejected response, each on its own copy so the response
160
+ * stays readable, with the request that got it. Returns the headers to resend with (same-named
161
+ * headers from several provers are combined, comma-separated, in prover order), or `undefined`
162
+ * when no prover asks to resend.
163
+ */
164
+ async function resendHeaders(provers, response, request) {
165
+ const context = Object.freeze({ request });
166
+ const copies = [];
167
+ let resend = false;
168
+ const headers = new Headers();
169
+ try {
170
+ for (const prover of provers) {
171
+ const copy = response.clone();
172
+ copies.push(copy);
173
+ const decision = await prover.retry(copy, context);
174
+ if (decision === true)
175
+ resend = true;
176
+ else if (typeof decision === 'object' && decision !== null) {
177
+ resend = true;
178
+ // Same-named headers from several provers are combined, so each one's values resend.
179
+ // Payment credential headers are never set from a retry.
180
+ for (const [name, value] of new Headers(decision))
181
+ if (!credentialHeaders.has(name))
182
+ headers.append(name, value);
183
+ }
184
+ }
185
+ }
186
+ finally {
187
+ release(copies);
188
+ }
189
+ if (!resend)
190
+ return undefined;
191
+ return Object.freeze([...headers].map(([name, value]) => Object.freeze([name, value])));
192
+ }
86
193
  /** Releases unread response copies without waiting, so they neither buffer the body nor block a resend. */
87
194
  function release(responses) {
88
195
  for (const unread of responses)
@@ -92,14 +199,14 @@ function release(responses) {
92
199
  /**
93
200
  * Wraps a fetch implementation so every request is proved.
94
201
  *
95
- * Prefer `Mppx.create({ identity })`, which also passes the payment challenge to provers.
202
+ * Prefer `Mppx.create({ identity })`, which also passes the payment Challenge to provers.
96
203
  */
97
- export function wrapFetch(fetch, client, context) {
204
+ export function wrapFetch(fetch, client, context = {}) {
98
205
  return async (input, init) => {
99
206
  const request = new Request(input, init);
100
- // A retry may answer a refreshed challenge: bind proofs to the challenge its credential
101
- // carries, and let provers prepare for a refreshed 402 of the same method and intent.
102
- const challenge = credentialChallenge(request.headers) ?? context?.challenge;
207
+ // A request carrying a Payment Credential is a paid attempt for that Credential's Challenge,
208
+ // which provers bind their proofs to; otherwise the wrapper's context applies.
209
+ const challenge = credentialChallenge(request.headers) ?? context.challenge;
103
210
  const { response } = await client.send((input, options) => fetch(input, {
104
211
  ...options,
105
212
  ...(init?.[skipPayment]
@@ -107,23 +214,15 @@ export function wrapFetch(fetch, client, context) {
107
214
  : {}),
108
215
  }), request, { ...context, challenge });
109
216
  if (response.status === 402 && challenge)
110
- // A 402 without a parseable Payment challenge is returned as is: the caller decides.
217
+ // Provers prepare for a refreshed 402 of the same method and intent. A 402 without a
218
+ // parseable Payment challenge is returned as is: the caller decides.
111
219
  for (const next of challengesOf(response))
112
220
  if (next.method === challenge.method && next.intent === challenge.intent)
113
- await client.challenge(response, { ...context, challenge: next }, request.url);
221
+ await client.challenge(response, { challenge: next }, request.url);
114
222
  return response;
115
223
  };
116
224
  }
117
- /** Returns the Payment challenges of a 402, or none when it carries none that parse. */
118
- function challengesOf(response) {
119
- try {
120
- return Challenge.fromResponseList(response);
121
- }
122
- catch {
123
- return [];
124
- }
125
- }
126
- /** Returns the challenge of a Payment credential in `headers`, if any. */
225
+ /** Returns the Challenge of a Payment Credential in `headers`, if any. */
127
226
  function credentialChallenge(headers) {
128
227
  for (const [, value] of headers) {
129
228
  const payment = Credential.extractPaymentScheme(value);
@@ -136,4 +235,22 @@ function credentialChallenge(headers) {
136
235
  }
137
236
  return undefined;
138
237
  }
238
+ /** Returns the Payment challenges of a 402, or none when it carries none that parse. */
239
+ function challengesOf(response) {
240
+ try {
241
+ return Challenge.fromResponseList(response);
242
+ }
243
+ catch {
244
+ return [];
245
+ }
246
+ }
247
+ /** Merges two lists of retry headers; `next` replaces same-named headers of `previous`. */
248
+ function mergeHeaders(previous, next) {
249
+ const merged = new Headers();
250
+ for (const [name, value] of previous)
251
+ merged.set(name, value);
252
+ for (const [name, value] of next)
253
+ merged.set(name, value);
254
+ return Object.freeze([...merged].map((entry) => Object.freeze(entry)));
255
+ }
139
256
  //# sourceMappingURL=Client.js.map
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Identity headers as data, lowercased, for code that must handle them without knowing each
3
+ * protocol: the client's redirect stripping and the proxy's header scrubbing.
4
+ */
5
+ /**
6
+ * Bearer identity request headers. Anyone holding one can replay it until it expires, so it is
7
+ * never sent across origins on a redirect or forwarded upstream by a proxy. Provers declare
8
+ * their own extra sensitive headers in `Prover.headers`.
9
+ */
10
+ export declare const request: readonly ["identity-attestation"];
11
+ /**
12
+ * Identity response headers a proxy must not pass on from upstream: they ask the client for an
13
+ * identity the proxy, not the upstream, decides on.
14
+ */
15
+ export declare const response: readonly ["identity-attestation-required", "identity-required"];
16
+ //# sourceMappingURL=Headers.d.ts.map
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Identity headers as data, lowercased, for code that must handle them without knowing each
3
+ * protocol: the client's redirect stripping and the proxy's header scrubbing.
4
+ */
5
+ /**
6
+ * Bearer identity request headers. Anyone holding one can replay it until it expires, so it is
7
+ * never sent across origins on a redirect or forwarded upstream by a proxy. Provers declare
8
+ * their own extra sensitive headers in `Prover.headers`.
9
+ */
10
+ export const request = Object.freeze(['identity-attestation']);
11
+ /**
12
+ * Identity response headers a proxy must not pass on from upstream: they ask the client for an
13
+ * identity the proxy, not the upstream, decides on.
14
+ */
15
+ export const response = Object.freeze([
16
+ 'identity-attestation-required',
17
+ 'identity-required',
18
+ ]);
19
+ //# sourceMappingURL=Headers.js.map