mppx 0.17.5 → 0.17.6

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 (38) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/cli/cli.js +14 -12
  3. package/dist/cli/stripe.d.ts +6 -1
  4. package/dist/cli/stripe.js +89 -5
  5. package/dist/client/Mppx.js +1 -0
  6. package/dist/extensions/identity/email-otp/Constants.d.ts +16 -0
  7. package/dist/extensions/identity/email-otp/Constants.js +16 -0
  8. package/dist/extensions/identity/email-otp/Types.d.ts +12 -0
  9. package/dist/extensions/identity/email-otp/Types.js +2 -0
  10. package/dist/extensions/identity/email-otp/client/index.d.ts +116 -0
  11. package/dist/extensions/identity/email-otp/client/index.js +119 -0
  12. package/dist/extensions/identity/email-otp/index.d.ts +17 -0
  13. package/dist/extensions/identity/email-otp/index.js +16 -0
  14. package/dist/extensions/identity/email-otp/internal/Attestation.d.ts +66 -0
  15. package/dist/extensions/identity/email-otp/internal/Attestation.js +128 -0
  16. package/dist/extensions/identity/email-otp/internal/Constants.d.ts +20 -0
  17. package/dist/extensions/identity/email-otp/internal/Constants.js +20 -0
  18. package/dist/extensions/identity/email-otp/internal/Jwks.d.ts +30 -0
  19. package/dist/extensions/identity/email-otp/internal/Jwks.js +114 -0
  20. package/dist/extensions/identity/email-otp/internal/Prover.d.ts +46 -0
  21. package/dist/extensions/identity/email-otp/internal/Prover.js +168 -0
  22. package/dist/extensions/identity/email-otp/internal/Types.d.ts +48 -0
  23. package/dist/extensions/identity/email-otp/internal/Types.js +2 -0
  24. package/dist/extensions/identity/email-otp/internal/Verifier.d.ts +56 -0
  25. package/dist/extensions/identity/email-otp/internal/Verifier.js +116 -0
  26. package/dist/extensions/identity/email-otp/server/index.d.ts +48 -0
  27. package/dist/extensions/identity/email-otp/server/index.js +56 -0
  28. package/dist/extensions/identity/index.d.ts +2 -0
  29. package/dist/extensions/identity/index.js +2 -0
  30. package/dist/identity/Callback.d.ts +47 -0
  31. package/dist/identity/Callback.js +64 -0
  32. package/dist/identity/index.d.ts +1 -0
  33. package/dist/identity/index.js +1 -0
  34. package/dist/internal/version.d.ts +2 -2
  35. package/dist/internal/version.js +1 -1
  36. package/dist/proxy/internal/Headers.js +2 -0
  37. package/dist/tempo/server/internal/html.gen.js +1 -1
  38. package/package.json +5 -1
@@ -0,0 +1,20 @@
1
+ /** Values shared by every MPP identity attestation. */
2
+ export declare const Constants: {
3
+ /** Request header carrying one or more attestations, separated by commas. */
4
+ readonly header: 'Identity-Attestation';
5
+ /** Response header listing the attestations a route requires, as a structured list. */
6
+ readonly requiredHeader: 'Identity-Attestation-Required';
7
+ /** JWS `typ` header of an attestation. */
8
+ readonly tokenType: 'mpp-attestation+jwt';
9
+ /** JWS algorithm of an attestation: EdDSA over Ed25519. */
10
+ readonly algorithm: 'EdDSA';
11
+ /** Path of the issuer's JSON Web Key Set, relative to the issuer URL. */
12
+ readonly jwksPath: '/.well-known/jwks.json';
13
+ /** Clock tolerance, in seconds, applied to `iat` and `exp`. */
14
+ readonly clockTolerance: 60;
15
+ /** Seconds before expiry at which a client replaces an attestation instead of sending it unpaid. */
16
+ readonly refreshMargin: 300;
17
+ /** Longest attestation accepted, in characters. */
18
+ readonly maxLength: 8192;
19
+ };
20
+ //# sourceMappingURL=Constants.d.ts.map
@@ -0,0 +1,20 @@
1
+ /** Values shared by every MPP identity attestation. */
2
+ export const Constants = {
3
+ /** Request header carrying one or more attestations, separated by commas. */
4
+ header: 'Identity-Attestation',
5
+ /** Response header listing the attestations a route requires, as a structured list. */
6
+ requiredHeader: 'Identity-Attestation-Required',
7
+ /** JWS `typ` header of an attestation. */
8
+ tokenType: 'mpp-attestation+jwt',
9
+ /** JWS algorithm of an attestation: EdDSA over Ed25519. */
10
+ algorithm: 'EdDSA',
11
+ /** Path of the issuer's JSON Web Key Set, relative to the issuer URL. */
12
+ jwksPath: '/.well-known/jwks.json',
13
+ /** Clock tolerance, in seconds, applied to `iat` and `exp`. */
14
+ clockTolerance: 60,
15
+ /** Seconds before expiry at which a client replaces an attestation instead of sending it unpaid. */
16
+ refreshMargin: 300,
17
+ /** Longest attestation accepted, in characters. */
18
+ maxLength: 8_192,
19
+ };
20
+ //# sourceMappingURL=Constants.js.map
@@ -0,0 +1,30 @@
1
+ import type * as Types from './Types.js';
2
+ /**
3
+ * Creates a key resolver that reads an issuer's JSON Web Key Set.
4
+ *
5
+ * Fetches `<issuer>/.well-known/jwks.json` and caches its Ed25519 keys for
6
+ * `ttl` seconds. An unknown key ID refetches the set at most once every
7
+ * `refreshInterval` seconds per issuer, and concurrent lookups share one fetch,
8
+ * so callers cannot trigger a fetch per request. While the issuer is
9
+ * unreachable, the last key set fetched successfully keeps verifying for up to
10
+ * `maxStale` seconds after it was fetched; after that, verification fails closed.
11
+ */
12
+ export declare function resolver(options?: resolver.Options): Types.KeyResolver;
13
+ export declare namespace resolver {
14
+ type Options = {
15
+ /** Fetch implementation. @default globalThis.fetch */
16
+ fetch?: typeof globalThis.fetch | undefined;
17
+ /** Seconds a fetched key set is cached. @default 300 */
18
+ ttl?: number | undefined;
19
+ /** Seconds before a key set fetch is abandoned. @default 5 */
20
+ timeout?: number | undefined;
21
+ /** Minimum seconds between refetches for an unknown key ID, per issuer. @default 30 */
22
+ refreshInterval?: number | undefined;
23
+ /**
24
+ * Seconds after its fetch that the last good key set keeps verifying while
25
+ * the issuer is unreachable, so a rotated-out key stops working. @default 3600
26
+ */
27
+ maxStale?: number | undefined;
28
+ };
29
+ }
30
+ //# sourceMappingURL=Jwks.d.ts.map
@@ -0,0 +1,114 @@
1
+ import { unwrapFetch } from '../../../../client/internal/Fetch.js';
2
+ import { Constants } from './Constants.js';
3
+ /**
4
+ * Creates a key resolver that reads an issuer's JSON Web Key Set.
5
+ *
6
+ * Fetches `<issuer>/.well-known/jwks.json` and caches its Ed25519 keys for
7
+ * `ttl` seconds. An unknown key ID refetches the set at most once every
8
+ * `refreshInterval` seconds per issuer, and concurrent lookups share one fetch,
9
+ * so callers cannot trigger a fetch per request. While the issuer is
10
+ * unreachable, the last key set fetched successfully keeps verifying for up to
11
+ * `maxStale` seconds after it was fetched; after that, verification fails closed.
12
+ */
13
+ export function resolver(options = {}) {
14
+ const ttl = (options.ttl ?? 300) * 1_000;
15
+ const refreshInterval = (options.refreshInterval ?? 30) * 1_000;
16
+ const maxStale = (options.maxStale ?? 3_600) * 1_000;
17
+ const timeout = (options.timeout ?? 5) * 1_000;
18
+ // Unwrapped, so an issuer's 402 is never paid in a process that also runs the client.
19
+ const fetch = unwrapFetch(options.fetch ?? globalThis.fetch);
20
+ // The newest fetch per issuer, started at `startedAt`; shared by concurrent lookups.
21
+ const sets = new Map();
22
+ // The last set fetched successfully per issuer, served while a refetch fails.
23
+ const good = new Map();
24
+ function load(issuer) {
25
+ const startedAt = Date.now();
26
+ const keys = (async () => {
27
+ const response = await fetch(`${issuer.replace(/\/+$/, '')}${Constants.jwksPath}`, {
28
+ headers: { accept: 'application/json' },
29
+ signal: AbortSignal.timeout(timeout),
30
+ // Workers reject 'error'; a redirect is not ok, so it fails below.
31
+ redirect: 'manual',
32
+ });
33
+ if (!response.ok)
34
+ throw new Error(`JWKS request failed with ${response.status}.`);
35
+ const body = (await response.json());
36
+ // A body without a key list is a failed fetch, so it never replaces the last good set.
37
+ if (!body || !Array.isArray(body.keys))
38
+ throw new Error('JWKS response has no keys list.');
39
+ const result = new Map();
40
+ for (const jwk of body.keys) {
41
+ if (!jwk || typeof jwk !== 'object')
42
+ continue;
43
+ const { alg, crv, key_ops, kid, kty, use, x } = jwk;
44
+ if (kty !== 'OKP' || crv !== 'Ed25519' || typeof x !== 'string' || typeof kid !== 'string')
45
+ continue;
46
+ // Honor the issuer's restrictions on what the key may do.
47
+ if (use !== undefined && use !== 'sig')
48
+ continue;
49
+ if (alg !== undefined && alg !== 'EdDSA' && alg !== 'Ed25519')
50
+ continue;
51
+ if (key_ops !== undefined && !(Array.isArray(key_ops) && key_ops.includes('verify')))
52
+ continue;
53
+ // A malformed key is skipped, so it cannot take the issuer's other keys down.
54
+ try {
55
+ result.set(kid, await crypto.subtle.importKey('jwk', { crv, kty, x }, { name: 'Ed25519' }, true, [
56
+ 'verify',
57
+ ]));
58
+ }
59
+ catch { }
60
+ }
61
+ good.set(issuer, { fetchedAt: startedAt, keys: result });
62
+ return result;
63
+ })();
64
+ const entry = { failed: false, startedAt, keys };
65
+ // A failed fetch is retried after `refreshInterval` rather than cached for `ttl`.
66
+ keys.catch(() => {
67
+ entry.failed = true;
68
+ });
69
+ sets.set(issuer, entry);
70
+ return entry;
71
+ }
72
+ /** The newest fetch, or one started now if the newest is older than `age`. */
73
+ function current(issuer, age) {
74
+ const entry = sets.get(issuer);
75
+ const limit = entry?.failed ? Math.min(age, refreshInterval) : age;
76
+ return entry && Date.now() - entry.startedAt <= limit ? entry : load(issuer);
77
+ }
78
+ /** Awaits a fetch, falling back to the last good set while it is within `maxStale`. */
79
+ async function keysOf(issuer, entry) {
80
+ try {
81
+ return await entry.keys;
82
+ }
83
+ catch (error) {
84
+ const last = good.get(issuer);
85
+ if (last && Date.now() - last.fetchedAt <= maxStale)
86
+ return last.keys;
87
+ throw error;
88
+ }
89
+ }
90
+ return async ({ issuer, keyId }) => {
91
+ // A known key in a set fetched within `ttl` is served at once, so a refetch
92
+ // an unknown key ID started does not hold up other lookups.
93
+ const last = good.get(issuer);
94
+ if (last && Date.now() - last.fetchedAt <= ttl && last.keys.has(keyId))
95
+ return last.keys.get(keyId);
96
+ const keys = await keysOf(issuer, current(issuer, ttl));
97
+ if (keys.has(keyId))
98
+ return keys.get(keyId);
99
+ // An unknown key ID: join the newest fetch, or start one if it is old enough.
100
+ // If that fetch fails, a stale set cannot say the key is unknown (it may be
101
+ // newly rotated in), so the outage is thrown and answered with 503.
102
+ const entry = current(issuer, refreshInterval);
103
+ try {
104
+ return (await entry.keys).get(keyId);
105
+ }
106
+ catch (error) {
107
+ const stale = good.get(issuer);
108
+ if (stale && Date.now() - stale.fetchedAt <= maxStale && stale.keys.has(keyId))
109
+ return stale.keys.get(keyId);
110
+ throw error;
111
+ }
112
+ };
113
+ }
114
+ //# sourceMappingURL=Jwks.js.map
@@ -0,0 +1,46 @@
1
+ import type * as Identity from '../../../../identity/Types.js';
2
+ import type { MaybePromise } from '../../../../internal/types.js';
3
+ import type * as Types from './Types.js';
4
+ /**
5
+ * Creates a prover that presents identity attestations.
6
+ *
7
+ * On each in-scope request it sends, in `Identity-Attestation`, every unexpired
8
+ * attestation whose audience is the request's origin. When a server answers
9
+ * 401 or 403 with `Identity-Attestation-Required`, it calls `acquire` for each
10
+ * listed type and issuer it accepts, keeps the result, and the request is sent
11
+ * once more.
12
+ *
13
+ * The audience is always the request's own origin, never one a server names,
14
+ * so a server cannot obtain an attestation it could replay elsewhere. `acquire`
15
+ * runs only for the listed `issuers`.
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * Mppx.create({ identity: [Attestation.Client.prover({ scope: '*', attestations: [token] })], methods })
20
+ * ```
21
+ */
22
+ export declare function prover(config: prover.Config): Identity.Prover;
23
+ export declare namespace prover {
24
+ type Config = {
25
+ /** Origins that receive attestations, or `'*'` for any origin. */
26
+ scope: Identity.Prover['scope'];
27
+ /** Attestations obtained beforehand, such as from an issuer with curl. */
28
+ attestations?: readonly string[] | undefined;
29
+ /** Obtains an attestation a server requires, or returns `undefined` to decline. */
30
+ acquire?: ((requirement: {
31
+ /** Origin the attestation must be bound to. */
32
+ audience: string;
33
+ /** Issuer to obtain it from. */
34
+ issuer: string;
35
+ /** Attestation type. */
36
+ type: string;
37
+ }) => MaybePromise<string | undefined>) | undefined;
38
+ /** Issuers `acquire` may be asked for. Required with `acquire`. */
39
+ issuers?: readonly string[] | undefined;
40
+ /** Attestation types `acquire` may be asked for. Defaults to any. */
41
+ types?: readonly string[] | undefined;
42
+ };
43
+ }
44
+ /** Parses the attestation requirements of a rejected response. */
45
+ export declare function requirements(headers: Headers): Types.Requirement[];
46
+ //# sourceMappingURL=Prover.d.ts.map
@@ -0,0 +1,168 @@
1
+ import { isInnerList, parseList, Token } from 'structured-headers';
2
+ import * as Attestation from './Attestation.js';
3
+ import { Constants } from './Constants.js';
4
+ /**
5
+ * Creates a prover that presents identity attestations.
6
+ *
7
+ * On each in-scope request it sends, in `Identity-Attestation`, every unexpired
8
+ * attestation whose audience is the request's origin. When a server answers
9
+ * 401 or 403 with `Identity-Attestation-Required`, it calls `acquire` for each
10
+ * listed type and issuer it accepts, keeps the result, and the request is sent
11
+ * once more.
12
+ *
13
+ * The audience is always the request's own origin, never one a server names,
14
+ * so a server cannot obtain an attestation it could replay elsewhere. `acquire`
15
+ * runs only for the listed `issuers`.
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * Mppx.create({ identity: [Attestation.Client.prover({ scope: '*', attestations: [token] })], methods })
20
+ * ```
21
+ */
22
+ export function prover(config) {
23
+ const stored = new Map();
24
+ const pending = new Map();
25
+ const keyOf = (claims) => JSON.stringify([claims.aud, claims.iss, claims.type]);
26
+ function decode(token) {
27
+ const claims = Attestation.decode(token)?.claims;
28
+ if (!claims ||
29
+ typeof claims.aud !== 'string' ||
30
+ typeof claims.iss !== 'string' ||
31
+ typeof claims.type !== 'string' ||
32
+ typeof claims.exp !== 'number')
33
+ throw new TypeError('Identity attestation is malformed.');
34
+ return claims;
35
+ }
36
+ function add(token, claims = decode(token), fresh = false) {
37
+ const added = Math.floor(Date.now() / 1_000);
38
+ const freshUntil = fresh ? added + Constants.clockTolerance : 0;
39
+ stored.set(keyOf(claims), { added, claims, freshUntil, token });
40
+ }
41
+ for (const token of config.attestations ?? [])
42
+ add(token);
43
+ const now = () => Math.floor(Date.now() / 1_000);
44
+ if (config.acquire && !config.issuers)
45
+ throw new TypeError('An attestation prover that acquires attestations must list its issuers.');
46
+ // Compared as the verifier names them, without a trailing slash.
47
+ const issuers = config.issuers?.map((issuer) => issuer.replace(/\/+$/, ''));
48
+ return {
49
+ scope: config.scope,
50
+ prove(request, context) {
51
+ const origin = new URL(request.url).origin;
52
+ // A bearer attestation never goes over plaintext HTTP, except to localhost.
53
+ if (!Attestation.isIssuer(origin))
54
+ return request;
55
+ // An unpaid attempt sends only an attestation with time to spare, so one close to expiry
56
+ // is replaced before paying. The paid retry keeps sending it within the server's clock
57
+ // tolerance: dropping it there would reject a payment that may already be broadcast.
58
+ const paid = context.challenge !== undefined;
59
+ // The margin is at most half the attestation's lifetime, so a short-lived one is still sent,
60
+ // less the verifier's clock tolerance, so an issuer clock behind the client's does not
61
+ // withhold it.
62
+ const margin = ({ claims, added }) => Math.min(Constants.refreshMargin, Math.floor((claims.exp - (typeof claims.iat === 'number' ? claims.iat : added)) / 2)) - Constants.clockTolerance;
63
+ const usable = (entry) => {
64
+ if (entry.claims.aud !== origin)
65
+ return false;
66
+ if (entry.claims.exp <= now() - Constants.clockTolerance)
67
+ return false;
68
+ // An attestation acquired moments ago is always sent, so every request resent after
69
+ // acquiring it carries it; the window is time-based, so concurrent requests cannot use it up.
70
+ return (paid || now() <= entry.freshUntil || entry.claims.exp > now() + Math.max(0, margin(entry)));
71
+ };
72
+ const tokens = [...stored.values()].filter(usable).map(({ token }) => token);
73
+ if (tokens.length === 0)
74
+ return request;
75
+ const headers = new Headers(request.headers);
76
+ const existing = headers.get(Constants.header);
77
+ headers.set(Constants.header, [existing, ...tokens].filter(Boolean).join(', '));
78
+ return new Request(request, { headers });
79
+ },
80
+ async retry(response) {
81
+ if (response.status !== 401 && response.status !== 403)
82
+ return false;
83
+ if (!config.acquire || !URL.canParse(response.url))
84
+ return false;
85
+ const audience = new URL(response.url).origin;
86
+ let acquired = false;
87
+ let failure;
88
+ // A requirement listed twice is acquired once, so it sends one code.
89
+ const seen = new Set();
90
+ for (const { type, issuer } of requirements(response.headers)) {
91
+ // Only trusted issuers: a server-named one could relay a code and obtain an
92
+ // attestation for another origin.
93
+ if (!issuer || !issuers?.includes(issuer))
94
+ continue;
95
+ if (config.types && !config.types.includes(type))
96
+ continue;
97
+ const key = keyOf({ aud: audience, iss: issuer, type });
98
+ if (seen.has(key))
99
+ continue;
100
+ seen.add(key);
101
+ let task = pending.get(key);
102
+ if (!task) {
103
+ // A stored attestation the server rejected is replaced.
104
+ stored.delete(key);
105
+ task = (async () => {
106
+ const token = await config.acquire({ audience, issuer, type });
107
+ if (!token)
108
+ return false;
109
+ const claims = decode(token);
110
+ // Store only an attestation for this requirement, so an issuer cannot plant one.
111
+ if (claims.aud !== audience || claims.iss !== issuer || claims.type !== type)
112
+ return false;
113
+ add(token, claims, true);
114
+ return true;
115
+ })().finally(() => pending.delete(key));
116
+ pending.set(key, task);
117
+ }
118
+ // A route may accept any one of the listed issuers, so one that fails does not stop
119
+ // the others; the failure surfaces only when none succeeded.
120
+ try {
121
+ if (await task)
122
+ acquired = true;
123
+ }
124
+ catch (error) {
125
+ failure ??= { error };
126
+ }
127
+ }
128
+ if (!acquired && failure)
129
+ throw failure.error;
130
+ // Every attestation this retry acquired stays fresh for the resend, even when a later
131
+ // code took the user longer than the window to enter.
132
+ for (const key of seen) {
133
+ const entry = stored.get(key);
134
+ if (entry?.freshUntil)
135
+ entry.freshUntil = now() + Constants.clockTolerance;
136
+ }
137
+ return acquired;
138
+ },
139
+ };
140
+ }
141
+ /** Parses the attestation requirements of a rejected response. */
142
+ export function requirements(headers) {
143
+ const value = headers.get(Constants.requiredHeader);
144
+ if (!value)
145
+ return [];
146
+ let list;
147
+ try {
148
+ list = parseList(value);
149
+ }
150
+ catch {
151
+ return [];
152
+ }
153
+ const result = [];
154
+ for (const member of list) {
155
+ if (isInnerList(member) || !(member[0] instanceof Token))
156
+ continue;
157
+ const issuer = member[1].get('issuer');
158
+ if (issuer === undefined) {
159
+ result.push({ type: member[0].toString() });
160
+ continue;
161
+ }
162
+ if (typeof issuer !== 'string' || !Attestation.isIssuer(issuer))
163
+ continue;
164
+ result.push({ type: member[0].toString(), issuer });
165
+ }
166
+ return result;
167
+ }
168
+ //# sourceMappingURL=Prover.js.map
@@ -0,0 +1,48 @@
1
+ import type { MaybePromise } from '../../../../internal/types.js';
2
+ /**
3
+ * Claims of an MPP identity attestation.
4
+ *
5
+ * An issuer signs these after checking one fact about the subject, such as
6
+ * control of an email address. `aud` binds the attestation to the origin of
7
+ * the server it is presented to, so that server cannot replay it elsewhere.
8
+ */
9
+ export type Claims = {
10
+ /** Issuer URL. */
11
+ iss: string;
12
+ /** Origin of the server the attestation is for, such as `https://api.example`. */
13
+ aud: string;
14
+ /** Attested subject, such as an email address. */
15
+ sub: string;
16
+ /** Attestation type, such as `email`. */
17
+ type: string;
18
+ /** Issued-at time, in Unix seconds. */
19
+ iat: number;
20
+ /** Expiry time, in Unix seconds. */
21
+ exp: number;
22
+ /** Unique attestation identifier. */
23
+ jti?: string | undefined;
24
+ };
25
+ /**
26
+ * Resolves the issuer's public key for an attestation's `kid`. Returns
27
+ * `undefined` for an unknown or malformed `kid`, and throws only when the keys
28
+ * cannot be fetched: a throw answers the request with 503.
29
+ */
30
+ export type KeyResolver = (parameters: {
31
+ /** Issuer URL the attestation claims. */
32
+ issuer: string;
33
+ /** Key identifier from the JWS header. */
34
+ keyId: string;
35
+ }) => MaybePromise<CryptoKey | undefined>;
36
+ /** An attestation a route requires, as listed in `Identity-Attestation-Required`. */
37
+ export type Requirement = {
38
+ /** Attestation type, such as `email`. */
39
+ type: string;
40
+ /** Issuer URL the route trusts, or where to obtain the identity. Absent for a server's own identity system without one. */
41
+ issuer?: string | undefined;
42
+ };
43
+ /** A verified attestation. */
44
+ export type Verified = {
45
+ /** Verified claims. */
46
+ claims: Claims;
47
+ };
48
+ //# sourceMappingURL=Types.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=Types.js.map
@@ -0,0 +1,56 @@
1
+ import type * as Identity from '../../../../identity/Types.js';
2
+ import type { MaybePromise } from '../../../../internal/types.js';
3
+ import type * as Types from './Types.js';
4
+ /**
5
+ * Creates a request-stage verifier for one type of identity attestation from one issuer.
6
+ *
7
+ * A request without a matching `Identity-Attestation` is rejected with 401 and an
8
+ * `Identity-Attestation-Required` header naming the type and issuer, which a
9
+ * client prover answers by obtaining an attestation and retrying. Attestations of
10
+ * other types or issuers in the same header are left to their own verifiers.
11
+ *
12
+ * An attestation is a bearer proof bound to this server's origin until it
13
+ * expires; it says what the issuer checked, not what the subject may do.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * const email = Attestation.Server.verifier({
18
+ * audience: 'https://api.example',
19
+ * issuer: 'https://issuer.example',
20
+ * type: 'email',
21
+ * })
22
+ * mppx.charge({ amount: '1', identity: [email] })
23
+ * ```
24
+ */
25
+ export declare function verifier(config: verifier.Config): Identity.Verifier<Types.Verified>;
26
+ export declare namespace verifier {
27
+ type Config = {
28
+ /** Accepted attestation type, such as `email`. */
29
+ type: string;
30
+ /** Trusted issuer URL. */
31
+ issuer: string;
32
+ /**
33
+ * This server's public origin, such as `https://api.example`, which attestations must be bound to.
34
+ *
35
+ * A function may derive it from the request, but only where the platform
36
+ * guarantees the request's host (such as a Cloudflare Worker route): many
37
+ * Node servers build the URL from the client's `Host` header, which would let
38
+ * another server's attestation through.
39
+ */
40
+ audience: string | ((request: Request) => string);
41
+ /** Resolves issuer keys. Defaults to the issuer's JSON Web Key Set. */
42
+ keyResolver?: Types.KeyResolver | undefined;
43
+ /** Fetch used for the default JSON Web Key Set resolver. */
44
+ fetch?: typeof globalThis.fetch | undefined;
45
+ /** Oldest accepted `iat`, in seconds before now. Defaults to the attestation's own `exp`. */
46
+ maxAge?: number | undefined;
47
+ /** Clock tolerance in seconds. @default 60 */
48
+ clockTolerance?: number | undefined;
49
+ /**
50
+ * Applies the route's policy to verified claims. Return a reason to reject
51
+ * the request with 403, or `undefined` to accept it.
52
+ */
53
+ validate?: ((claims: Types.Claims, request: Request) => MaybePromise<string | undefined>) | undefined;
54
+ };
55
+ }
56
+ //# sourceMappingURL=Verifier.d.ts.map
@@ -0,0 +1,116 @@
1
+ import { serializeList, Token } from 'structured-headers';
2
+ import * as Attestation from './Attestation.js';
3
+ import { Constants } from './Constants.js';
4
+ import * as Jwks from './Jwks.js';
5
+ /**
6
+ * Creates a request-stage verifier for one type of identity attestation from one issuer.
7
+ *
8
+ * A request without a matching `Identity-Attestation` is rejected with 401 and an
9
+ * `Identity-Attestation-Required` header naming the type and issuer, which a
10
+ * client prover answers by obtaining an attestation and retrying. Attestations of
11
+ * other types or issuers in the same header are left to their own verifiers.
12
+ *
13
+ * An attestation is a bearer proof bound to this server's origin until it
14
+ * expires; it says what the issuer checked, not what the subject may do.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * const email = Attestation.Server.verifier({
19
+ * audience: 'https://api.example',
20
+ * issuer: 'https://issuer.example',
21
+ * type: 'email',
22
+ * })
23
+ * mppx.charge({ amount: '1', identity: [email] })
24
+ * ```
25
+ */
26
+ export function verifier(config) {
27
+ const issuer = config.issuer.replace(/\/+$/, '');
28
+ if (!Attestation.isIssuer(issuer))
29
+ throw new TypeError('Attestation issuer must be an https URL (http only on localhost).');
30
+ for (const [name, value] of [
31
+ ['clockTolerance', config.clockTolerance],
32
+ ['maxAge', config.maxAge],
33
+ ])
34
+ if (value !== undefined && !(Number.isSafeInteger(value) && value >= 0))
35
+ throw new TypeError(`Attestation ${name} must be a non-negative integer of seconds.`);
36
+ const keyResolver = config.keyResolver ?? Jwks.resolver({ fetch: config.fetch });
37
+ const required = {
38
+ [Constants.requiredHeader]: serializeList([
39
+ [new Token(config.type), new Map([['issuer', issuer]])],
40
+ ]),
41
+ };
42
+ return {
43
+ stage: 'request',
44
+ async verify(request) {
45
+ const audience = origin(typeof config.audience === 'function' ? config.audience(request) : config.audience);
46
+ // At most `maxCandidates` distinct tokens are verified, latest expiry first,
47
+ // so repeated or forged tokens cost a bounded number of signature checks.
48
+ // A stray forged token does not hide a valid one, but whoever controls the
49
+ // header can always withhold a valid token, so the bound is not a guarantee
50
+ // against that sender. Without a usable one, the first is verified so its
51
+ // rejection says why.
52
+ const now = Math.floor(Date.now() / 1_000);
53
+ const tolerance = config.clockTolerance ?? Constants.clockTolerance;
54
+ const candidates = Attestation.parseHeader(request.headers.get(Constants.header))
55
+ .map((token) => ({ token, claims: Attestation.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
+ code: 401,
67
+ headers: required,
68
+ reason: `An identity attestation of type "${config.type}" is required.`,
69
+ };
70
+ let reason = 'The identity attestation is invalid.';
71
+ let unavailable;
72
+ let forbidden;
73
+ for (const token of tokens) {
74
+ const result = await Attestation.verify(token, {
75
+ audience,
76
+ clockTolerance: config.clockTolerance,
77
+ issuer,
78
+ keyResolver,
79
+ maxAge: config.maxAge,
80
+ type: config.type,
81
+ });
82
+ // 503 rather than 401, so a client keeps its attestation instead of
83
+ // discarding it and asking for a new code while the issuer is down.
84
+ // A later token may still verify, so an outage is answered only if none does.
85
+ if (result.status === 'invalid' && result.unavailable) {
86
+ unavailable ??= result.reason;
87
+ continue;
88
+ }
89
+ if (result.status === 'invalid') {
90
+ reason = result.reason;
91
+ continue;
92
+ }
93
+ const rejected = await config.validate?.(result.claims, request);
94
+ // A later attestation, such as another address, may still be allowed.
95
+ if (rejected) {
96
+ forbidden ??= rejected;
97
+ continue;
98
+ }
99
+ return { status: 'valid', value: { claims: result.claims } };
100
+ }
101
+ if (forbidden)
102
+ return { status: 'invalid', code: 403, reason: forbidden };
103
+ if (unavailable)
104
+ return { status: 'invalid', code: 503, reason: unavailable };
105
+ // The client may obtain a fresh attestation and retry.
106
+ return { status: 'invalid', code: 401, headers: required, reason };
107
+ },
108
+ };
109
+ }
110
+ /** Most distinct attestations of one type and issuer verified per request. */
111
+ const maxCandidates = 3;
112
+ /** An audience as the origin attestations carry, so `https://api.example/` matches. */
113
+ function origin(audience) {
114
+ return URL.canParse(audience) ? new URL(audience).origin : audience;
115
+ }
116
+ //# sourceMappingURL=Verifier.js.map