mppx 0.17.4 → 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 (39) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +15 -0
  3. package/dist/cli/cli.js +141 -137
  4. package/dist/cli/stripe.d.ts +53 -0
  5. package/dist/cli/stripe.js +241 -0
  6. package/dist/client/Mppx.js +1 -0
  7. package/dist/extensions/identity/email-otp/Constants.d.ts +16 -0
  8. package/dist/extensions/identity/email-otp/Constants.js +16 -0
  9. package/dist/extensions/identity/email-otp/Types.d.ts +12 -0
  10. package/dist/extensions/identity/email-otp/Types.js +2 -0
  11. package/dist/extensions/identity/email-otp/client/index.d.ts +116 -0
  12. package/dist/extensions/identity/email-otp/client/index.js +119 -0
  13. package/dist/extensions/identity/email-otp/index.d.ts +17 -0
  14. package/dist/extensions/identity/email-otp/index.js +16 -0
  15. package/dist/extensions/identity/email-otp/internal/Attestation.d.ts +66 -0
  16. package/dist/extensions/identity/email-otp/internal/Attestation.js +128 -0
  17. package/dist/extensions/identity/email-otp/internal/Constants.d.ts +20 -0
  18. package/dist/extensions/identity/email-otp/internal/Constants.js +20 -0
  19. package/dist/extensions/identity/email-otp/internal/Jwks.d.ts +30 -0
  20. package/dist/extensions/identity/email-otp/internal/Jwks.js +114 -0
  21. package/dist/extensions/identity/email-otp/internal/Prover.d.ts +46 -0
  22. package/dist/extensions/identity/email-otp/internal/Prover.js +168 -0
  23. package/dist/extensions/identity/email-otp/internal/Types.d.ts +48 -0
  24. package/dist/extensions/identity/email-otp/internal/Types.js +2 -0
  25. package/dist/extensions/identity/email-otp/internal/Verifier.d.ts +56 -0
  26. package/dist/extensions/identity/email-otp/internal/Verifier.js +116 -0
  27. package/dist/extensions/identity/email-otp/server/index.d.ts +48 -0
  28. package/dist/extensions/identity/email-otp/server/index.js +56 -0
  29. package/dist/extensions/identity/index.d.ts +2 -0
  30. package/dist/extensions/identity/index.js +2 -0
  31. package/dist/identity/Callback.d.ts +47 -0
  32. package/dist/identity/Callback.js +64 -0
  33. package/dist/identity/index.d.ts +1 -0
  34. package/dist/identity/index.js +1 -0
  35. package/dist/internal/version.d.ts +2 -2
  36. package/dist/internal/version.js +1 -1
  37. package/dist/proxy/internal/Headers.js +2 -0
  38. package/dist/tempo/server/internal/html.gen.js +1 -1
  39. package/package.json +5 -1
@@ -0,0 +1,66 @@
1
+ import type * as Types from './Types.js';
2
+ /** A decoded, unverified attestation. */
3
+ export type Decoded = {
4
+ /** JWS protected header. */
5
+ header: {
6
+ alg?: unknown;
7
+ kid?: unknown;
8
+ typ?: unknown;
9
+ };
10
+ /** Unverified claims. */
11
+ claims: Partial<Types.Claims> & Record<string, unknown>;
12
+ /** The signed bytes: `base64url(header) + '.' + base64url(claims)`. */
13
+ signingInput: Uint8Array;
14
+ /** Signature bytes. */
15
+ signature: Uint8Array;
16
+ };
17
+ /**
18
+ * Signs attestation claims as a compact JWS (EdDSA over Ed25519).
19
+ *
20
+ * For issuers. `keyId` should be the RFC 7638 thumbprint of the public key
21
+ * published in the issuer's JSON Web Key Set.
22
+ */
23
+ export declare function sign(claims: Types.Claims, options: {
24
+ key: CryptoKey;
25
+ keyId: string;
26
+ }): Promise<string>;
27
+ /** Decodes an attestation without verifying it, or returns `undefined` if it is malformed. */
28
+ export declare function decode(token: string): Decoded | undefined;
29
+ /**
30
+ * Verifies an attestation's signature and claims.
31
+ *
32
+ * Checks the EdDSA algorithm and `typ`, the issuer, audience and type, and the
33
+ * `iat` and `exp` times (with `clockTolerance`), then the signature with the
34
+ * key `keyResolver` returns for the header's `kid`.
35
+ */
36
+ export declare function verify(token: string, options: verify.Options): Promise<{
37
+ status: 'valid';
38
+ claims: Types.Claims;
39
+ } | {
40
+ status: 'invalid';
41
+ reason: string;
42
+ unavailable?: true;
43
+ }>;
44
+ export declare namespace verify {
45
+ type Options = {
46
+ /** Accepted attestation type, such as `email`. */
47
+ type: string;
48
+ /** Trusted issuer URL. */
49
+ issuer: string;
50
+ /** Origin the attestation must be bound to. */
51
+ audience: string;
52
+ /** Resolves the issuer's public key by key ID. */
53
+ keyResolver: Types.KeyResolver;
54
+ /** Oldest accepted `iat`, in seconds before now. Defaults to the attestation's own `exp`. */
55
+ maxAge?: number | undefined;
56
+ /** Clock tolerance in seconds. @default 60 */
57
+ clockTolerance?: number | undefined;
58
+ /** Current Unix time in seconds, for tests. */
59
+ now?: number | undefined;
60
+ };
61
+ }
62
+ /** Splits an `Identity-Attestation` header value into its attestations. */
63
+ export declare function parseHeader(value: string | null): string[];
64
+ /** Accepts https issuers, and http only on localhost for development. */
65
+ export declare function isIssuer(value: string): boolean;
66
+ //# sourceMappingURL=Attestation.d.ts.map
@@ -0,0 +1,128 @@
1
+ import { Base64 } from 'ox';
2
+ import { Constants } from './Constants.js';
3
+ /**
4
+ * Signs attestation claims as a compact JWS (EdDSA over Ed25519).
5
+ *
6
+ * For issuers. `keyId` should be the RFC 7638 thumbprint of the public key
7
+ * published in the issuer's JSON Web Key Set.
8
+ */
9
+ export async function sign(claims, options) {
10
+ const header = { alg: Constants.algorithm, kid: options.keyId, typ: Constants.tokenType };
11
+ const input = `${encode(header)}.${encode(claims)}`;
12
+ const signature = await crypto.subtle.sign({ name: 'Ed25519' }, options.key, new TextEncoder().encode(input));
13
+ return `${input}.${Base64.fromBytes(new Uint8Array(signature), { pad: false, url: true })}`;
14
+ }
15
+ /** Decodes an attestation without verifying it, or returns `undefined` if it is malformed. */
16
+ export function decode(token) {
17
+ if (token.length > Constants.maxLength)
18
+ return undefined;
19
+ const parts = token.split('.');
20
+ if (parts.length !== 3 || parts.some((part) => !/^[A-Za-z0-9_-]+$/.test(part)))
21
+ return undefined;
22
+ try {
23
+ const header = JSON.parse(Base64.toString(parts[0]));
24
+ const claims = JSON.parse(Base64.toString(parts[1]));
25
+ if (!isObject(header) || !isObject(claims))
26
+ return undefined;
27
+ return {
28
+ header,
29
+ claims,
30
+ signingInput: new TextEncoder().encode(`${parts[0]}.${parts[1]}`),
31
+ signature: Base64.toBytes(parts[2]),
32
+ };
33
+ }
34
+ catch {
35
+ return undefined;
36
+ }
37
+ }
38
+ /**
39
+ * Verifies an attestation's signature and claims.
40
+ *
41
+ * Checks the EdDSA algorithm and `typ`, the issuer, audience and type, and the
42
+ * `iat` and `exp` times (with `clockTolerance`), then the signature with the
43
+ * key `keyResolver` returns for the header's `kid`.
44
+ */
45
+ export async function verify(token, options) {
46
+ const decoded = decode(token);
47
+ if (!decoded)
48
+ return invalid('The attestation is malformed.');
49
+ const { header, claims } = decoded;
50
+ if (header.alg !== Constants.algorithm)
51
+ return invalid('The attestation algorithm is not EdDSA.');
52
+ if (header.typ !== Constants.tokenType)
53
+ return invalid('The attestation type header is wrong.');
54
+ if (typeof header.kid !== 'string' || header.kid === '')
55
+ return invalid('The attestation has no key ID.');
56
+ if (claims.iss !== options.issuer)
57
+ return invalid('The attestation issuer is not trusted.');
58
+ if (claims.type !== options.type)
59
+ return invalid('The attestation type is not accepted.');
60
+ if (claims.aud !== options.audience)
61
+ return invalid('The attestation is for another audience.');
62
+ if (typeof claims.sub !== 'string' || claims.sub === '')
63
+ return invalid('The attestation has no subject.');
64
+ if (claims.jti !== undefined && typeof claims.jti !== 'string')
65
+ return invalid('The attestation ID is malformed.');
66
+ if (!isTime(claims.iat) || !isTime(claims.exp))
67
+ return invalid('The attestation times are malformed.');
68
+ const now = options.now ?? Math.floor(Date.now() / 1_000);
69
+ const tolerance = options.clockTolerance ?? Constants.clockTolerance;
70
+ if (claims.exp <= now - tolerance)
71
+ return invalid('The attestation has expired.');
72
+ if (claims.iat > now + tolerance)
73
+ return invalid('The attestation was issued in the future.');
74
+ if (options.maxAge !== undefined && now - claims.iat > options.maxAge + tolerance)
75
+ return invalid('The attestation is too old.');
76
+ let key;
77
+ try {
78
+ key = await options.keyResolver({ issuer: options.issuer, keyId: header.kid });
79
+ }
80
+ catch {
81
+ // The issuer's keys are unreachable, which says nothing about the token.
82
+ return { ...invalid('The attestation key could not be resolved.'), unavailable: true };
83
+ }
84
+ if (!key)
85
+ return invalid('No public key is available for the attestation key ID.');
86
+ let valid = false;
87
+ try {
88
+ valid = await crypto.subtle.verify({ name: 'Ed25519' }, key, decoded.signature, decoded.signingInput);
89
+ }
90
+ catch { }
91
+ if (!valid)
92
+ return invalid('The attestation signature is invalid.');
93
+ return { status: 'valid', claims: claims };
94
+ }
95
+ /** Splits an `Identity-Attestation` header value into its attestations. */
96
+ export function parseHeader(value) {
97
+ if (!value)
98
+ return [];
99
+ return value
100
+ .split(',')
101
+ .map((token) => token.trim())
102
+ .filter(Boolean);
103
+ }
104
+ function encode(value) {
105
+ return Base64.fromString(JSON.stringify(value), { pad: false, url: true });
106
+ }
107
+ function invalid(reason) {
108
+ return { status: 'invalid', reason };
109
+ }
110
+ function isObject(value) {
111
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
112
+ }
113
+ function isTime(value) {
114
+ // Bounded by the largest time a Date holds, so every accepted time converts to a valid Date.
115
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 && value <= maxTime;
116
+ }
117
+ /** Latest time, in Unix seconds, that a JavaScript Date can represent. */
118
+ const maxTime = 8_640_000_000_000;
119
+ /** Accepts https issuers, and http only on localhost for development. */
120
+ export function isIssuer(value) {
121
+ if (!URL.canParse(value))
122
+ return false;
123
+ const url = new URL(value);
124
+ if (url.protocol === 'https:')
125
+ return true;
126
+ return url.protocol === 'http:' && (url.hostname === 'localhost' || url.hostname === '127.0.0.1');
127
+ }
128
+ //# sourceMappingURL=Attestation.js.map
@@ -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