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
@@ -0,0 +1,119 @@
1
+ import { serializeList, Token as SfToken } from 'structured-headers';
2
+ import * as Status from '../../../../identity/Status.js';
3
+ import { Constants } from '../Constants.js';
4
+ import * as Jwks from '../Jwks.js';
5
+ import * as Token from '../Token.js';
6
+ /**
7
+ * Creates a request-stage verifier for one type of identity attestation from one issuer.
8
+ *
9
+ * Outcomes:
10
+ * - `missing` (401): no attestation of this type and issuer, with an
11
+ * `Identity-Attestation-Required` header naming them, which a client prover answers by
12
+ * obtaining one and retrying.
13
+ * - `invalid` (401): none verified, with the same header so the client can obtain a fresh one.
14
+ * - `forbidden` (403): one verified, but `validate` rejected it.
15
+ * - `unavailable` (503): the issuer's keys could not be fetched, so the client keeps its
16
+ * attestation instead of asking for a new one.
17
+ *
18
+ * Attestations of other types or issuers in the same header are left to their own verifiers.
19
+ * An attestation is a bearer proof bound to this server's origin until it expires; it says what
20
+ * the issuer checked, not what the subject may do.
21
+ *
22
+ * @example
23
+ * ```ts
24
+ * const phone = Attestation.Server.verifier({
25
+ * audience: 'https://api.example',
26
+ * issuer: 'https://issuer.example',
27
+ * type: 'phone',
28
+ * })
29
+ * mppx.charge({ amount: '1', identity: [phone] })
30
+ * ```
31
+ */
32
+ export function verifier(config) {
33
+ const issuer = config.issuer.replace(/\/+$/, '');
34
+ if (!Token.isIssuer(issuer))
35
+ throw new TypeError('Attestation issuer must be an https URL (http only on localhost).');
36
+ Token.assertTimes({ clockTolerance: config.clockTolerance, maxAge: config.maxAge });
37
+ const keyResolver = config.keyResolver ?? Jwks.resolver({ fetch: config.fetch });
38
+ const tolerance = config.clockTolerance ?? Constants.clockTolerance;
39
+ const required = Object.freeze({
40
+ [Constants.requiredHeader]: serializeList([
41
+ [new SfToken(config.type), new Map([['issuer', issuer]])],
42
+ ]),
43
+ });
44
+ return {
45
+ async verify(request) {
46
+ const audience = origin(typeof config.audience === 'function' ? config.audience(request) : config.audience);
47
+ // At most `maxCandidates` distinct tokens are verified, latest expiry first,
48
+ // so repeated or forged tokens cost a bounded number of signature checks.
49
+ // A stray forged token does not hide a valid one, but whoever controls the
50
+ // header can always withhold a valid token, so the bound is not a guarantee
51
+ // against that sender. Without a usable one, the first is verified so its
52
+ // rejection says why.
53
+ const now = Math.floor(Date.now() / 1_000);
54
+ const candidates = Token.parseHeader(request.headers.get(Constants.header))
55
+ .map((token) => ({ token, claims: Token.decode(token)?.claims }))
56
+ .filter(({ claims }) => claims?.iss === issuer && claims.type === config.type);
57
+ const usable = candidates
58
+ .filter(({ claims }) => claims?.aud === audience && (claims.exp ?? 0) > now - tolerance)
59
+ .sort((a, b) => (b.claims?.exp ?? 0) - (a.claims?.exp ?? 0));
60
+ const tokens = [
61
+ ...new Set((usable.length > 0 ? usable : candidates).map(({ token }) => token)),
62
+ ].slice(0, usable.length > 0 ? maxCandidates : 1);
63
+ if (tokens.length === 0)
64
+ return {
65
+ status: 'missing',
66
+ headers: required,
67
+ reason: `An identity attestation of type "${config.type}" is required.`,
68
+ };
69
+ // Every token's outcome, so the most decisive one answers when none is valid.
70
+ const rejections = [];
71
+ for (const token of tokens) {
72
+ const result = await Token.verify(token, {
73
+ audience,
74
+ clockTolerance: config.clockTolerance,
75
+ issuer,
76
+ keyResolver,
77
+ maxAge: config.maxAge,
78
+ type: config.type,
79
+ });
80
+ if (result.status !== 'valid') {
81
+ rejections.push(result);
82
+ continue;
83
+ }
84
+ // A later attestation, such as another address, may still be allowed.
85
+ // Only `undefined` accepts, so an empty or otherwise falsy reason still rejects.
86
+ const reason = config.validate ? await config.validate(result.claims, request) : undefined;
87
+ if (reason !== undefined) {
88
+ rejections.push({
89
+ status: 'forbidden',
90
+ reason: typeof reason === 'string' && reason ? reason : defaultForbiddenReason,
91
+ });
92
+ continue;
93
+ }
94
+ return { status: 'valid', value: Object.freeze({ claims: result.claims }) };
95
+ }
96
+ const rejection = decisive(rejections);
97
+ // Only an invalid attestation is worth replacing: the client may obtain a fresh one.
98
+ return rejection.status === 'invalid' ? { ...rejection, headers: required } : rejection;
99
+ },
100
+ };
101
+ }
102
+ /** The reason sent when `validate` rejects without a usable one. */
103
+ const defaultForbiddenReason = 'This identity attestation is not allowed.';
104
+ /** Returns the first rejection of the status with the highest precedence. `rejections` is never empty. */
105
+ function decisive(rejections) {
106
+ for (const status of Status.precedence) {
107
+ const rejection = rejections.find((candidate) => candidate.status === status);
108
+ if (rejection)
109
+ return rejection;
110
+ }
111
+ return rejections[0];
112
+ }
113
+ /** Most distinct attestations of one type and issuer verified per request. */
114
+ const maxCandidates = 3;
115
+ /** An audience as the origin attestations carry, so `https://api.example/` matches. */
116
+ function origin(audience) {
117
+ return URL.canParse(audience) ? new URL(audience).origin : audience;
118
+ }
119
+ //# sourceMappingURL=index.js.map
@@ -1,9 +1,9 @@
1
- /** Email OTP attestation values. */
1
+ /** Email OTP attestation values. Values every attestation shares are in `Attestation.Constants`. */
2
2
  export declare const Constants: {
3
- /** Request header carrying the email attestation. */
4
- readonly header: 'Identity-Attestation';
5
- /** Response header naming the issuer to get an attestation from. */
6
- readonly requiredHeader: 'Identity-Attestation-Required';
3
+ /** @deprecated Use `Attestation.Constants.header`. */
4
+ readonly header: "Identity-Attestation";
5
+ /** @deprecated Use `Attestation.Constants.requiredHeader`. */
6
+ readonly requiredHeader: "Identity-Attestation-Required";
7
7
  /** Attestation type for a verified email address. */
8
8
  readonly type: 'email';
9
9
  /** Issuer path that emails a one-time code. */
@@ -1,9 +1,10 @@
1
- /** Email OTP attestation values. */
1
+ import { Constants as AttestationConstants } from '../attestation/Constants.js';
2
+ /** Email OTP attestation values. Values every attestation shares are in `Attestation.Constants`. */
2
3
  export const Constants = {
3
- /** Request header carrying the email attestation. */
4
- header: 'Identity-Attestation',
5
- /** Response header naming the issuer to get an attestation from. */
6
- requiredHeader: 'Identity-Attestation-Required',
4
+ /** @deprecated Use `Attestation.Constants.header`. */
5
+ header: AttestationConstants.header,
6
+ /** @deprecated Use `Attestation.Constants.requiredHeader`. */
7
+ requiredHeader: AttestationConstants.requiredHeader,
7
8
  /** Attestation type for a verified email address. */
8
9
  type: 'email',
9
10
  /** Issuer path that emails a one-time code. */
@@ -1,12 +1,12 @@
1
1
  /** A verified email address. */
2
2
  export type VerifiedEmail = {
3
3
  /** The email address the issuer sent a one-time code to, lowercased. */
4
- email: string;
4
+ readonly email: string;
5
5
  /** Issuer URL. */
6
- issuer: string;
6
+ readonly issuer: string;
7
7
  /** When the attestation expires. */
8
- expiresAt: Date;
8
+ readonly expiresAt: Date;
9
9
  /** Attestation identifier (`jti`), if the issuer set one. */
10
- id?: string | undefined;
10
+ readonly id?: string | undefined;
11
11
  };
12
12
  //# sourceMappingURL=Types.d.ts.map
@@ -41,13 +41,24 @@ export declare namespace verifyCode {
41
41
  };
42
42
  }
43
43
  /**
44
- * Creates a prover that verifies an email address when a server asks for one.
44
+ * Creates a prover that verifies an email address when a server asks for one: an
45
+ * `Attestation.Client.prover` of type `email` whose `acquire` sends the code, prompts and verifies.
45
46
  *
46
47
  * When a server answers with `Identity-Attestation-Required: email;issuer="…"`,
47
48
  * the prover asks the issuer to email a code to `email`, gets the code from
48
49
  * `code` (such as a terminal prompt or a form), exchanges it for an
49
50
  * attestation bound to the server's origin and sends the request again with it.
50
- * Later requests to that origin reuse it until it expires.
51
+ * Later requests to that origin reuse it until it expires. A route that accepts any of several
52
+ * issuers (`Identity.anyOf`) lists them as alternatives: the prover asks the first trusted one,
53
+ * and the next only if that one fails or is declined. A route that requires several issuers gets
54
+ * a code from, and a prompt for, each of them.
55
+ *
56
+ * Trust is set by two options together:
57
+ * - `scope`: the origins that may ask for and receive the attestation. It is always
58
+ * bound to the request's own origin, never one a server names.
59
+ * - `issuers`: the issuers the email address may be sent to. A server only names the
60
+ * issuer it wants; an untrusted one could relay a code and obtain an attestation
61
+ * for another server.
51
62
  *
52
63
  * @example
53
64
  * ```ts
@@ -56,8 +67,9 @@ export declare namespace verifyCode {
56
67
  * EmailOtp.Client.prover({
57
68
  * code: () => prompt('Code:'),
58
69
  * email: 'me@example.com',
70
+ * // Only this issuer receives the address, and only this origin the attestation.
59
71
  * issuers: ['https://issuer.example'],
60
- * scope: '*',
72
+ * scope: ['https://api.example'],
61
73
  * }),
62
74
  * ],
63
75
  * methods: [tempo({ account })],
@@ -68,14 +80,14 @@ export declare function prover(config: prover.Config): Identity.Prover;
68
80
  export declare namespace prover {
69
81
  type Config = {
70
82
  /** Origins that may ask for and receive the attestation, or `'*'` for any origin. */
71
- scope: Identity.Prover['scope'];
83
+ readonly scope: Identity.Prover['scope'];
72
84
  /** Email address to verify, or a function that returns it (or `undefined` to decline). */
73
- email: string | ((parameters: {
85
+ readonly email: string | ((parameters: {
74
86
  audience: string;
75
87
  issuer: string;
76
88
  }) => MaybePromise<string | undefined>);
77
89
  /** Returns the code the user received, or `undefined` to give up. */
78
- code: (parameters: {
90
+ readonly code: (parameters: {
79
91
  /** Origin the attestation is for. */
80
92
  audience: string;
81
93
  /** Email address the code was sent to. */
@@ -92,16 +104,11 @@ export declare namespace prover {
92
104
  error?: Error | undefined;
93
105
  }) => MaybePromise<string | undefined>;
94
106
  /** Attestations obtained beforehand, such as from the issuer with curl. */
95
- attestations?: readonly string[] | undefined;
96
- /**
97
- * Issuers the prover may send the email address to, such as `['https://identity.mpp.tempo.xyz']`.
98
- *
99
- * A server only names the issuer it wants; an untrusted one could relay a code
100
- * and obtain an attestation for another server.
101
- */
102
- issuers: readonly string[];
107
+ readonly attestations?: readonly string[] | undefined;
108
+ /** Issuers the prover may send the email address to, such as `['https://identity.mpp.tempo.xyz']`. */
109
+ readonly issuers: readonly string[];
103
110
  /** Fetch used to call the issuer. @default globalThis.fetch */
104
- fetch?: typeof globalThis.fetch | undefined;
111
+ readonly fetch?: typeof globalThis.fetch | undefined;
105
112
  };
106
113
  }
107
114
  /** An issuer rejected an email OTP request. */
@@ -1,7 +1,7 @@
1
1
  import { unwrapFetch } from '../../../../client/internal/Fetch.js';
2
+ import * as Attestation from '../../attestation/client/index.js';
3
+ import { isIssuer } from '../../attestation/Token.js';
2
4
  import { Constants } from '../Constants.js';
3
- import { isIssuer } from '../internal/Attestation.js';
4
- import * as Attestation from '../internal/Prover.js';
5
5
  /**
6
6
  * Asks an issuer to email a one-time code for `audience`.
7
7
  *
@@ -36,13 +36,24 @@ function date(value) {
36
36
  return Number.isFinite(result.getTime()) ? result : undefined;
37
37
  }
38
38
  /**
39
- * Creates a prover that verifies an email address when a server asks for one.
39
+ * Creates a prover that verifies an email address when a server asks for one: an
40
+ * `Attestation.Client.prover` of type `email` whose `acquire` sends the code, prompts and verifies.
40
41
  *
41
42
  * When a server answers with `Identity-Attestation-Required: email;issuer="…"`,
42
43
  * the prover asks the issuer to email a code to `email`, gets the code from
43
44
  * `code` (such as a terminal prompt or a form), exchanges it for an
44
45
  * attestation bound to the server's origin and sends the request again with it.
45
- * Later requests to that origin reuse it until it expires.
46
+ * Later requests to that origin reuse it until it expires. A route that accepts any of several
47
+ * issuers (`Identity.anyOf`) lists them as alternatives: the prover asks the first trusted one,
48
+ * and the next only if that one fails or is declined. A route that requires several issuers gets
49
+ * a code from, and a prompt for, each of them.
50
+ *
51
+ * Trust is set by two options together:
52
+ * - `scope`: the origins that may ask for and receive the attestation. It is always
53
+ * bound to the request's own origin, never one a server names.
54
+ * - `issuers`: the issuers the email address may be sent to. A server only names the
55
+ * issuer it wants; an untrusted one could relay a code and obtain an attestation
56
+ * for another server.
46
57
  *
47
58
  * @example
48
59
  * ```ts
@@ -51,8 +62,9 @@ function date(value) {
51
62
  * EmailOtp.Client.prover({
52
63
  * code: () => prompt('Code:'),
53
64
  * email: 'me@example.com',
65
+ * // Only this issuer receives the address, and only this origin the attestation.
54
66
  * issuers: ['https://issuer.example'],
55
- * scope: '*',
67
+ * scope: ['https://api.example'],
56
68
  * }),
57
69
  * ],
58
70
  * methods: [tempo({ account })],
@@ -1,12 +1,7 @@
1
1
  /**
2
- * Email OTP identity: an issuer emails a one-time code and signs an attestation
3
- * the client sends in `Identity-Attestation`.
4
- *
5
- * Limitation: the attestation format, its key lookup and the
6
- * `Identity-Attestation` headers are internal to this extension. Another
7
- * attestation type (phone, KYC) needs its own extension, or this one made
8
- * generic, once a second issuer exists. For your own identity system, use
9
- * `Identity.from` from `mppx/identity`.
2
+ * Email OTP identity: an issuer emails a one-time code and signs an `email` attestation
3
+ * (`mppx/extensions/identity/attestation`) the client sends in `Identity-Attestation`.
4
+ * For your own identity system, use `Identity.from` from `mppx/identity`.
10
5
  */
11
6
  /** Client helpers that verify an email address with a one-time code. */
12
7
  export * as Client from './client/index.js';
@@ -1,12 +1,7 @@
1
1
  /**
2
- * Email OTP identity: an issuer emails a one-time code and signs an attestation
3
- * the client sends in `Identity-Attestation`.
4
- *
5
- * Limitation: the attestation format, its key lookup and the
6
- * `Identity-Attestation` headers are internal to this extension. Another
7
- * attestation type (phone, KYC) needs its own extension, or this one made
8
- * generic, once a second issuer exists. For your own identity system, use
9
- * `Identity.from` from `mppx/identity`.
2
+ * Email OTP identity: an issuer emails a one-time code and signs an `email` attestation
3
+ * (`mppx/extensions/identity/attestation`) the client sends in `Identity-Attestation`.
4
+ * For your own identity system, use `Identity.from` from `mppx/identity`.
10
5
  */
11
6
  /** Client helpers that verify an email address with a one-time code. */
12
7
  export * as Client from './client/index.js';
@@ -1,14 +1,16 @@
1
1
  import type * as Identity from '../../../../identity/Types.js';
2
2
  import type { MaybePromise } from '../../../../internal/types.js';
3
- import type * as AttestationTypes from '../internal/Types.js';
3
+ import * as Attestation from '../../attestation/server/index.js';
4
+ import type * as AttestationTypes from '../../attestation/Types.js';
4
5
  import type * as Types from '../Types.js';
5
6
  /**
6
- * Creates a request-stage verifier that requires a verified email address.
7
+ * Creates a request-stage verifier that requires a verified email address: an
8
+ * `Attestation.Server.verifier` of type `email` whose `validate` is `allow`.
7
9
  *
8
10
  * A request without one gets 401 with `Identity-Attestation-Required: email;issuer="…"`.
9
11
  * The client obtains an attestation from the issuer with a one-time code sent to
10
- * the address and sends it in `Identity-Attestation`. `allow` applies the
11
- * route's policy, such as a domain allowlist.
12
+ * the address and sends it in `Identity-Attestation`. An address `allow` rejects is
13
+ * `forbidden` (403).
12
14
  *
13
15
  * @example
14
16
  * ```ts
@@ -25,24 +27,22 @@ export declare function verifier(config: verifier.Config): Identity.Verifier<Typ
25
27
  export declare namespace verifier {
26
28
  type Config = {
27
29
  /** Trusted issuer URL. */
28
- issuer: string;
29
- /** Accepts or rejects (403) a verified, lowercased email address. Defaults to any. */
30
- allow?: ((email: string, request: Request) => MaybePromise<boolean>) | undefined;
30
+ readonly issuer: string;
31
+ /** Accepts or rejects (`forbidden`, 403) a verified, lowercased email address. Defaults to any. */
32
+ readonly allow?: ((email: string, request: Request) => MaybePromise<boolean>) | undefined;
31
33
  /**
32
- * This server's public origin, such as `https://api.example`, which attestations must be bound to.
33
- *
34
- * A function may derive it from the request only where the platform
35
- * guarantees the request's host (such as a Cloudflare Worker route).
34
+ * This server's public origin, such as `https://api.example`, which attestations must be
35
+ * bound to. The function form is deprecated: see `Attestation.Server.verifier.AudienceFunction`.
36
36
  */
37
- audience: string | ((request: Request) => string);
37
+ readonly audience: string | Attestation.verifier.AudienceFunction;
38
38
  /** Resolves issuer keys. Defaults to the issuer's JSON Web Key Set. */
39
- keyResolver?: AttestationTypes.KeyResolver | undefined;
39
+ readonly keyResolver?: AttestationTypes.KeyResolver | undefined;
40
40
  /** Fetch used for the default JSON Web Key Set resolver. */
41
- fetch?: typeof globalThis.fetch | undefined;
41
+ readonly fetch?: typeof globalThis.fetch | undefined;
42
42
  /** Oldest accepted attestation, in seconds since it was issued. Defaults to its own expiry. */
43
- maxAge?: number | undefined;
43
+ readonly maxAge?: number | undefined;
44
44
  /** Clock tolerance in seconds. @default 60 */
45
- clockTolerance?: number | undefined;
45
+ readonly clockTolerance?: number | undefined;
46
46
  };
47
47
  }
48
48
  //# sourceMappingURL=index.d.ts.map
@@ -1,12 +1,13 @@
1
+ import * as Attestation from '../../attestation/server/index.js';
1
2
  import { Constants } from '../Constants.js';
2
- import * as Attestation from '../internal/Verifier.js';
3
3
  /**
4
- * Creates a request-stage verifier that requires a verified email address.
4
+ * Creates a request-stage verifier that requires a verified email address: an
5
+ * `Attestation.Server.verifier` of type `email` whose `validate` is `allow`.
5
6
  *
6
7
  * A request without one gets 401 with `Identity-Attestation-Required: email;issuer="…"`.
7
8
  * The client obtains an attestation from the issuer with a one-time code sent to
8
- * the address and sends it in `Identity-Attestation`. `allow` applies the
9
- * route's policy, such as a domain allowlist.
9
+ * the address and sends it in `Identity-Attestation`. An address `allow` rejects is
10
+ * `forbidden` (403).
10
11
  *
11
12
  * @example
12
13
  * ```ts
@@ -20,6 +21,7 @@ import * as Attestation from '../internal/Verifier.js';
20
21
  * ```
21
22
  */
22
23
  export function verifier(config) {
24
+ const { allow } = config;
23
25
  const inner = Attestation.verifier({
24
26
  audience: config.audience,
25
27
  clockTolerance: config.clockTolerance,
@@ -28,27 +30,28 @@ export function verifier(config) {
28
30
  keyResolver: config.keyResolver,
29
31
  maxAge: config.maxAge,
30
32
  type: Constants.type,
31
- async validate(claims, request) {
32
- if (!config.allow || (await config.allow(claims.sub.toLowerCase(), request)))
33
- return undefined;
34
- return 'This email address is not allowed.';
35
- },
33
+ ...(allow && {
34
+ async validate(claims, request) {
35
+ if (await allow(claims.sub.toLowerCase(), request))
36
+ return undefined;
37
+ return 'This email address is not allowed.';
38
+ },
39
+ }),
36
40
  });
37
41
  return {
38
- stage: 'request',
39
- async verify(request, context) {
40
- const result = await inner.verify(request, context);
42
+ async verify(request) {
43
+ const result = await inner.verify(request);
41
44
  if (result.status !== 'valid')
42
45
  return result;
43
46
  const { claims } = result.value;
44
47
  return {
45
48
  status: 'valid',
46
- value: {
49
+ value: Object.freeze({
47
50
  email: claims.sub.toLowerCase(),
48
51
  expiresAt: new Date(claims.exp * 1_000),
49
52
  id: claims.jti,
50
53
  issuer: claims.iss,
51
- },
54
+ }),
52
55
  };
53
56
  },
54
57
  };
@@ -1,3 +1,5 @@
1
+ /** Identity attestations: issuer-signed tokens a server requires and a client presents. */
2
+ export * as Attestation from './attestation/index.js';
1
3
  /** Email address verification with a one-time code. */
2
4
  export * as EmailOtp from './email-otp/index.js';
3
5
  /** Client and server adapters for the TAP agent-recognition signature profile. */
@@ -1,3 +1,5 @@
1
+ /** Identity attestations: issuer-signed tokens a server requires and a client presents. */
2
+ export * as Attestation from './attestation/index.js';
1
3
  /** Email address verification with a one-time code. */
2
4
  export * as EmailOtp from './email-otp/index.js';
3
5
  /** Client and server adapters for the TAP agent-recognition signature profile. */
@@ -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
@@ -6,7 +6,7 @@ import type * as Types from './Types.js';
6
6
  *
7
7
  * `verify` returns the caller's identity, which the route handler reads with
8
8
  * `result.identity.get(verifier)`; `undefined` or `null` when the request carries none
9
- * (401, with `challenge` headers if set); or throws a {@link Rejection} to
9
+ * (`missing`, 401, with `challenge` headers if set); or throws a {@link Rejection} to
10
10
  * reject the identity it carries.
11
11
  *
12
12
  * @example
@@ -16,7 +16,7 @@ import type * as Types from './Types.js';
16
16
  * const key = request.headers.get('X-Api-Key')
17
17
  * if (!key) return undefined
18
18
  * const row = await db.customerByKey(key)
19
- * if (!row) throw new Identity.Rejection('Unknown API key.', { code: 403 })
19
+ * if (!row) throw new Identity.Rejection('Unknown API key.', { status: 'forbidden' })
20
20
  * return row
21
21
  * },
22
22
  * })
@@ -38,10 +38,29 @@ export declare namespace from {
38
38
  /** Rejects an identity a {@link from} verifier was given. */
39
39
  export declare class Rejection extends Error {
40
40
  readonly name = "Rejection";
41
- /** HTTP status of the rejection. @default 401 */
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
+ */
42
48
  readonly code: number;
43
- constructor(message: string, options?: {
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
+ */
44
63
  code?: number | undefined;
45
- });
64
+ };
46
65
  }
47
66
  //# sourceMappingURL=Callback.d.ts.map
@@ -1,10 +1,11 @@
1
+ import * as Status from './Status.js';
1
2
  /**
2
3
  * Creates a request-stage verifier from a function, such as a lookup in your
3
4
  * own database, session store or KYC provider.
4
5
  *
5
6
  * `verify` returns the caller's identity, which the route handler reads with
6
7
  * `result.identity.get(verifier)`; `undefined` or `null` when the request carries none
7
- * (401, with `challenge` headers if set); or throws a {@link Rejection} to
8
+ * (`missing`, 401, with `challenge` headers if set); or throws a {@link Rejection} to
8
9
  * reject the identity it carries.
9
10
  *
10
11
  * @example
@@ -14,7 +15,7 @@
14
15
  * const key = request.headers.get('X-Api-Key')
15
16
  * if (!key) return undefined
16
17
  * const row = await db.customerByKey(key)
17
- * if (!row) throw new Identity.Rejection('Unknown API key.', { code: 403 })
18
+ * if (!row) throw new Identity.Rejection('Unknown API key.', { status: 'forbidden' })
18
19
  * return row
19
20
  * },
20
21
  * })
@@ -22,8 +23,7 @@
22
23
  * ```
23
24
  */
24
25
  export function from(config) {
25
- return {
26
- stage: 'request',
26
+ return Object.freeze({
27
27
  async verify(request) {
28
28
  let value;
29
29
  try {
@@ -32,33 +32,57 @@ export function from(config) {
32
32
  catch (error) {
33
33
  if (!(error instanceof Rejection))
34
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 };
35
40
  return {
36
- status: 'invalid',
37
- code: error.code,
41
+ status,
42
+ // A deprecated non-standard code is still sent as is.
43
+ ...(code !== Status.codes.invalid && { code }),
38
44
  headers: config.challenge,
39
- reason: error.message,
45
+ reason,
40
46
  };
41
47
  }
42
48
  // A lookup that found nothing often returns null: treat it as no identity.
43
49
  if (value === undefined || value === null)
44
50
  return {
45
51
  status: 'missing',
46
- code: 401,
47
52
  headers: config.challenge,
48
53
  reason: 'Identity verification is required.',
49
54
  };
50
55
  return { status: 'valid', value };
51
56
  },
52
- };
57
+ });
58
+ }
59
+ const rejectionStatuses = ['invalid', 'forbidden', 'unavailable'];
60
+ function isRejectionStatus(status) {
61
+ return rejectionStatuses.includes(status);
53
62
  }
54
63
  /** Rejects an identity a {@link from} verifier was given. */
55
64
  export class Rejection extends Error {
56
65
  name = 'Rejection';
57
- /** HTTP status of the rejection. @default 401 */
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
+ */
58
73
  code;
59
74
  constructor(message, options = {}) {
60
75
  super(message);
61
- this.code = options.code ?? 401;
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];
62
86
  }
63
87
  }
64
88
  //# sourceMappingURL=Callback.js.map