mppx 0.17.6 → 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 (72) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/cli/cli.js +139 -139
  3. package/dist/cli/plugins/index.js +6 -6
  4. package/dist/client/Mppx.js +13 -4
  5. package/dist/client/internal/Fetch.js +9 -5
  6. package/dist/extensions/identity/{email-otp/internal → attestation}/Constants.d.ts +4 -1
  7. package/dist/extensions/identity/{email-otp/internal → attestation}/Constants.js +4 -1
  8. package/dist/extensions/identity/{email-otp/internal → attestation}/Jwks.d.ts +5 -5
  9. package/dist/extensions/identity/{email-otp/internal → attestation}/Jwks.js +1 -1
  10. package/dist/extensions/identity/{email-otp/internal/Attestation.d.ts → attestation/Token.d.ts} +40 -26
  11. package/dist/extensions/identity/{email-otp/internal/Attestation.js → attestation/Token.js} +18 -3
  12. package/dist/extensions/identity/{email-otp/internal → attestation}/Types.d.ts +14 -14
  13. package/dist/extensions/identity/attestation/client/index.d.ts +66 -0
  14. package/dist/extensions/identity/attestation/client/index.js +273 -0
  15. package/dist/extensions/identity/attestation/index.d.ts +20 -0
  16. package/dist/extensions/identity/attestation/index.js +18 -0
  17. package/dist/extensions/identity/attestation/internal/Cache.d.ts +120 -0
  18. package/dist/extensions/identity/attestation/internal/Cache.js +90 -0
  19. package/dist/extensions/identity/attestation/server/index.d.ts +66 -0
  20. package/dist/extensions/identity/attestation/server/index.js +119 -0
  21. package/dist/extensions/identity/email-otp/Constants.d.ts +5 -5
  22. package/dist/extensions/identity/email-otp/Constants.js +6 -5
  23. package/dist/extensions/identity/email-otp/Types.d.ts +4 -4
  24. package/dist/extensions/identity/email-otp/client/index.d.ts +22 -15
  25. package/dist/extensions/identity/email-otp/client/index.js +17 -5
  26. package/dist/extensions/identity/email-otp/index.d.ts +3 -8
  27. package/dist/extensions/identity/email-otp/index.js +3 -8
  28. package/dist/extensions/identity/email-otp/server/index.d.ts +16 -16
  29. package/dist/extensions/identity/email-otp/server/index.js +17 -14
  30. package/dist/extensions/identity/index.d.ts +2 -0
  31. package/dist/extensions/identity/index.js +2 -0
  32. package/dist/extensions/identity/internal/Verification.js +9 -5
  33. package/dist/identity/Callback.d.ts +24 -5
  34. package/dist/identity/Callback.js +35 -11
  35. package/dist/identity/Client.d.ts +78 -5
  36. package/dist/identity/Client.js +165 -48
  37. package/dist/identity/Headers.d.ts +16 -0
  38. package/dist/identity/Headers.js +19 -0
  39. package/dist/identity/Server.d.ts +159 -37
  40. package/dist/identity/Server.js +307 -138
  41. package/dist/identity/Status.d.ts +14 -0
  42. package/dist/identity/Status.js +19 -0
  43. package/dist/identity/Types.d.ts +161 -65
  44. package/dist/identity/index.d.ts +2 -0
  45. package/dist/identity/index.js +2 -0
  46. package/dist/identity/internal/Requirements.d.ts +28 -0
  47. package/dist/identity/internal/Requirements.js +78 -0
  48. package/dist/integrations/x402/Evm.d.ts +1 -0
  49. package/dist/internal/env.d.ts +14 -0
  50. package/dist/internal/env.js +38 -0
  51. package/dist/internal/version.d.ts +2 -2
  52. package/dist/internal/version.js +1 -1
  53. package/dist/proxy/internal/Headers.d.ts +1 -1
  54. package/dist/proxy/internal/Headers.js +7 -3
  55. package/dist/server/Mppx.d.ts +14 -6
  56. package/dist/server/Mppx.js +252 -148
  57. package/dist/server/internal/challengeMeta.d.ts +0 -6
  58. package/dist/server/internal/challengeMeta.js +3 -17
  59. package/dist/tempo/server/Charge.d.ts +14 -9
  60. package/dist/tempo/server/Charge.js +5 -1
  61. package/dist/tempo/server/Methods.js +4 -1
  62. package/dist/tempo/server/Subscription.d.ts +8 -0
  63. package/dist/tempo/server/internal/fallback-store.d.ts +7 -2
  64. package/dist/tempo/server/internal/fallback-store.js +12 -3
  65. package/dist/tempo/server/internal/html.gen.js +1 -1
  66. package/dist/tempo/session/server/Session.d.ts +5 -1
  67. package/package.json +5 -1
  68. package/dist/extensions/identity/email-otp/internal/Prover.d.ts +0 -46
  69. package/dist/extensions/identity/email-otp/internal/Prover.js +0 -168
  70. package/dist/extensions/identity/email-otp/internal/Verifier.d.ts +0 -56
  71. package/dist/extensions/identity/email-otp/internal/Verifier.js +0 -116
  72. /package/dist/extensions/identity/{email-otp/internal → attestation}/Types.js +0 -0
@@ -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
@@ -1,59 +1,181 @@
1
+ import type * as Challenge from '../Challenge.js';
2
+ import type * as Credential from '../Credential.js';
1
3
  import type * as Types from './Types.js';
4
+ /** The value of an `anyOf` verifier: the index of the first valid member and its value. */
5
+ type AnyOfValue = {
6
+ readonly index: number;
7
+ readonly value: unknown;
8
+ };
9
+ type Rejected = Exclude<Types.Verification, {
10
+ status: 'valid';
11
+ }>;
2
12
  /**
3
13
  * Accepts the first of several identity protocols that verifies.
4
14
  *
5
- * Every member runs. The result is `valid` if any member verifies, `invalid` if none verifies and
6
- * any member was presented but failed, and `missing` otherwise, with every
7
- * member's challenge headers. All members must run at the same stage.
15
+ * Every member runs. The result is `valid` if any member verifies (the first valid member
16
+ * wins). Otherwise the rejected member whose status has the highest precedence
17
+ * (`Identity.Status.precedence`) decides the status and reason, with every member's headers.
18
+ * Members' `Identity-Attestation-Required` values become one inner list of alternatives, such
19
+ * as `(email;issuer="https://a.example" email;issuer="https://b.example")`, so a client
20
+ * obtains one of them rather than all.
8
21
  *
9
22
  * @example
10
23
  * ```ts
11
24
  * mppx.charge({ amount: '1', identity: [Identity.anyOf(tap, webBotAuth)] })
12
25
  * ```
13
26
  */
14
- export declare function anyOf(...verifiers: readonly [Types.Verifier, Types.Verifier, ...Types.Verifier[]]): Types.Verifier<{
15
- index: number;
16
- value: unknown;
17
- }>;
18
- /** The combined outcome of a route's verifiers at one stage. @internal */
19
- export type Outcome = {
20
- status: 'valid';
21
- values: ReadonlyMap<Types.Verifier, unknown>;
22
- } | {
23
- status: 'missing' | 'invalid';
24
- code: number;
25
- headers: Headers;
26
- reason: string;
27
+ export declare function anyOf(...verifiers: readonly [Types.Verifier, Types.Verifier, ...Types.Verifier[]]): Types.Verifier<AnyOfValue>;
28
+ /** A rejected outcome reduced to its fixed status, the HTTP code it is sent with, headers and reason. */
29
+ export type Decision = {
30
+ readonly status: Types.RejectionStatus;
31
+ /** HTTP status code: `Identity.Status.codes[status]`, unless a deprecated `code` overrides it. */
32
+ readonly code: number;
33
+ readonly headers: readonly (readonly [name: string, value: string])[];
34
+ readonly reason: string;
27
35
  };
36
+ /** Verified values, keyed by the verifier (every `anyOf` level included) or payment check. */
37
+ export type Values = ReadonlyMap<Types.Verifier | Types.PaymentCheck, unknown>;
38
+ /** The combined outcome of verifiers or a payment check. @internal */
39
+ export type Outcome = {
40
+ readonly status: 'valid';
41
+ readonly values: Values;
42
+ } | Decision;
43
+ /** The outcome of no verifiers: valid, with no values. @internal */
44
+ export declare const none: Outcome;
28
45
  /**
29
- * Runs every verifier at one stage and combines their outcomes.
46
+ * Decides one rejection from rejected outcomes: the outcome whose fixed status has the highest
47
+ * precedence decides status, code and reason (the first such outcome on ties), and the headers
48
+ * of every outcome are merged. @internal
49
+ */
50
+ export declare function decide(outcomes: readonly Rejected[]): Decision;
51
+ /**
52
+ * The identity state of one request. Every verifier runs at most once per context, so
53
+ * replay-protected nonces are consumed once even when `compose` calls several offers with
54
+ * the same request. `compose` creates one and passes it to every offer it calls; a route
55
+ * called directly creates its own. @internal
56
+ */
57
+ export declare class Context {
58
+ /** Verification promises by verifier. Internal and mutable; outcomes are frozen. */
59
+ readonly verifications: Map<Types.Verifier<unknown>, Promise<Types.Verification<unknown>>>;
60
+ /**
61
+ * Payment check promises by check, then by Challenge id and attempt (`paid` or `unpaid`), so
62
+ * a check runs once per attempt even when `compose` calls the matched offer again.
63
+ */
64
+ readonly checks: Map<Types.PaymentCheck<unknown>, Map<string, Promise<Outcome>>>;
65
+ }
66
+ /** Creates the identity context of one request. @internal */
67
+ export declare function createContext(): Context;
68
+ /** Returns `value` if it is an identity context, otherwise a new one. @internal */
69
+ export declare function contextOf(value: unknown): Context;
70
+ /**
71
+ * Runs request-stage verifiers and combines their outcomes.
30
72
  *
31
- * Every verifier must be valid. Any `invalid` outcome rejects with 401 unless
32
- * it sets its own code; otherwise any `missing` outcome rejects with 403. The
33
- * headers of every rejected outcome are merged. Each verifier runs at most once
34
- * per request and context, so replay-protected nonces are consumed once even
35
- * when several handlers evaluate the same request.
73
+ * Valid only if every verifier is valid, with each value recorded at every `anyOf` level, so
74
+ * `results.get(leaf)` works when nested. Otherwise the precedence rule of {@link decide}.
75
+ * @internal
36
76
  */
37
- export declare function verify(request: Request, verifiers: readonly Types.Verifier[], context?: Types.Context): Promise<Outcome>;
77
+ export declare function verify(context: Context, request: Request, verifiers: readonly Types.Verifier[]): Promise<Outcome>;
38
78
  /**
39
- * Collects the challenge headers of payment-stage verifiers for one 402.
79
+ * Runs a payment check at most once per context, Challenge and attempt, and returns its
80
+ * outcome. @internal
81
+ */
82
+ export declare function check(context: Context, paymentCheck: Types.PaymentCheck, parameters: Parameters<Types.PaymentCheck['verify']>[0]): Promise<Outcome>;
83
+ /**
84
+ * The identity state of one route call, as a state machine:
85
+ *
86
+ * - `request`: nothing checked yet.
87
+ * - `identified`: request-stage verifiers passed; no payment decision yet.
88
+ * - `payment`: the payment check runs for a Challenge, with the Credential on a paid retry
89
+ * or without one before `authorize`.
90
+ * - `accepted`: the payment check passed (or the route has none): paid work may run.
91
+ * - `challenged`: the route issued a 402 carrying `requirements`.
92
+ * - `rejected`: identity was rejected; the response is sent as is, never a fresh 402.
40
93
  *
41
- * Each verifier's hook runs at most once per request and nonce, so every offer
42
- * in a composed 402 carries the same challenge. @internal
94
+ * @internal
43
95
  */
44
- export declare function challenge(request: Request, verifiers: readonly Types.Verifier[], nonce: string): Promise<Headers>;
96
+ export type State = {
97
+ readonly phase: 'request';
98
+ } | {
99
+ readonly phase: 'identified';
100
+ readonly values: Values;
101
+ } | {
102
+ readonly phase: 'payment';
103
+ readonly values: Values;
104
+ readonly challenge: Challenge.Challenge;
105
+ readonly credential: Credential.Credential | undefined;
106
+ } | {
107
+ readonly phase: 'accepted';
108
+ readonly values: Values;
109
+ } | {
110
+ readonly phase: 'challenged';
111
+ readonly values: Values;
112
+ readonly requirements: readonly Types.Requirement[];
113
+ } | {
114
+ readonly phase: 'rejected';
115
+ readonly rejection: Types.Rejection;
116
+ readonly code: number;
117
+ readonly headers: Decision['headers'];
118
+ };
119
+ /**
120
+ * An input to {@link transition}. The caller runs verifiers and checks (the only I/O) and feeds
121
+ * their outcomes in. @internal
122
+ */
123
+ export type Event =
124
+ /** Request-stage verifiers ran (`none` when the route has none). */
125
+ {
126
+ readonly type: 'verified';
127
+ readonly outcome: Outcome;
128
+ }
129
+ /** The payment check is about to run for `challenge`, with the paid retry's Credential if any. */
130
+ | {
131
+ readonly type: 'pay';
132
+ readonly challenge: Challenge.Challenge;
133
+ readonly credential: Credential.Credential | undefined;
134
+ }
135
+ /** The payment check ran (`none` when the route has none). */
136
+ | {
137
+ readonly type: 'checked';
138
+ readonly outcome: Outcome;
139
+ }
140
+ /** The route issues a 402 carrying `requirements`. */
141
+ | {
142
+ readonly type: 'challenge';
143
+ readonly requirements: readonly Types.Requirement[];
144
+ };
145
+ /** The state of a route call before identity runs. @internal */
146
+ export declare const initial: State;
45
147
  /**
46
- * Returns the identity nonce for every 402 issued on one request.
148
+ * Returns the next identity state. Pure: it never runs verifiers, and it throws a `TypeError`
149
+ * for an event the current phase does not accept.
47
150
  *
48
- * Composed routes call each offer with the same request, so all offers share it. @internal
151
+ * | Phase | Event | Next |
152
+ * | ------------------------ | ---------------------- | --------------------------------- |
153
+ * | `request` | `verified` (valid) | `identified` |
154
+ * | `request` | `verified` (rejected) | `rejected` (stage `request`) |
155
+ * | `identified` | `pay` | `payment` |
156
+ * | `payment` | `checked` (valid) | `accepted` |
157
+ * | `payment` + Credential | `checked` (rejected) | `rejected` (stage `payment`) |
158
+ * | `payment`, no Credential | `checked` (rejected) | `identified` (not authorized) |
159
+ * | `identified`, `accepted` | `challenge` | `challenged` |
160
+ *
161
+ * @internal
49
162
  */
50
- export declare function nonceFor(request: Request, create: () => string): string;
51
- /** Builds the rejection response for a failed request-stage outcome. @internal */
52
- export declare function toResponse(outcome: Exclude<Outcome, {
53
- status: 'valid';
163
+ export declare function transition(state: State, event: Event): State;
164
+ /** Builds the rejection response of a rejected state. @internal */
165
+ export declare function toResponse(state: Extract<State, {
166
+ phase: 'rejected';
54
167
  }>): Response;
55
- /** Creates a results lookup from verified values. @internal */
56
- export declare function results(values?: ReadonlyMap<Types.Verifier, unknown>): Types.Results;
57
- /** Returns the stage a verifier runs at. @internal */
58
- export declare function stageOf(verifier: Types.Verifier): Types.Stage;
168
+ /** Returns the frozen results lookup of a state's verified values. @internal */
169
+ export declare function results(state: State): Types.Results;
170
+ /** A route's parsed `identity` option. @internal */
171
+ export type RouteConfig = {
172
+ readonly request: readonly Types.Verifier[];
173
+ readonly payment: Types.PaymentCheck | undefined;
174
+ };
175
+ /**
176
+ * Parses a route's `identity` option. Throws a `TypeError` for a payment-stage or unknown-stage
177
+ * verifier, and for payment requirements that cannot be serialized. @internal
178
+ */
179
+ export declare function route(identity: Types.Route | undefined): RouteConfig;
180
+ export {};
59
181
  //# sourceMappingURL=Server.d.ts.map