mppx 0.17.5 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/dist/cli/cli.js +141 -139
  3. package/dist/cli/plugins/index.js +6 -6
  4. package/dist/cli/stripe.d.ts +6 -1
  5. package/dist/cli/stripe.js +89 -5
  6. package/dist/client/Mppx.js +13 -3
  7. package/dist/client/internal/Fetch.js +9 -5
  8. package/dist/extensions/identity/attestation/Constants.d.ts +23 -0
  9. package/dist/extensions/identity/attestation/Constants.js +23 -0
  10. package/dist/extensions/identity/attestation/Jwks.d.ts +30 -0
  11. package/dist/extensions/identity/attestation/Jwks.js +114 -0
  12. package/dist/extensions/identity/attestation/Token.d.ts +80 -0
  13. package/dist/extensions/identity/attestation/Token.js +143 -0
  14. package/dist/extensions/identity/attestation/Types.d.ts +48 -0
  15. package/dist/extensions/identity/attestation/Types.js +2 -0
  16. package/dist/extensions/identity/attestation/client/index.d.ts +66 -0
  17. package/dist/extensions/identity/attestation/client/index.js +273 -0
  18. package/dist/extensions/identity/attestation/index.d.ts +20 -0
  19. package/dist/extensions/identity/attestation/index.js +18 -0
  20. package/dist/extensions/identity/attestation/internal/Cache.d.ts +120 -0
  21. package/dist/extensions/identity/attestation/internal/Cache.js +90 -0
  22. package/dist/extensions/identity/attestation/server/index.d.ts +66 -0
  23. package/dist/extensions/identity/attestation/server/index.js +119 -0
  24. package/dist/extensions/identity/email-otp/Constants.d.ts +16 -0
  25. package/dist/extensions/identity/email-otp/Constants.js +17 -0
  26. package/dist/extensions/identity/email-otp/Types.d.ts +12 -0
  27. package/dist/extensions/identity/email-otp/Types.js +2 -0
  28. package/dist/extensions/identity/email-otp/client/index.d.ts +123 -0
  29. package/dist/extensions/identity/email-otp/client/index.js +131 -0
  30. package/dist/extensions/identity/email-otp/index.d.ts +12 -0
  31. package/dist/extensions/identity/email-otp/index.js +11 -0
  32. package/dist/extensions/identity/email-otp/server/index.d.ts +48 -0
  33. package/dist/extensions/identity/email-otp/server/index.js +59 -0
  34. package/dist/extensions/identity/index.d.ts +4 -0
  35. package/dist/extensions/identity/index.js +4 -0
  36. package/dist/extensions/identity/internal/Verification.js +9 -5
  37. package/dist/identity/Callback.d.ts +66 -0
  38. package/dist/identity/Callback.js +88 -0
  39. package/dist/identity/Client.d.ts +78 -5
  40. package/dist/identity/Client.js +165 -48
  41. package/dist/identity/Headers.d.ts +16 -0
  42. package/dist/identity/Headers.js +19 -0
  43. package/dist/identity/Server.d.ts +159 -37
  44. package/dist/identity/Server.js +307 -138
  45. package/dist/identity/Status.d.ts +14 -0
  46. package/dist/identity/Status.js +19 -0
  47. package/dist/identity/Types.d.ts +161 -65
  48. package/dist/identity/index.d.ts +3 -0
  49. package/dist/identity/index.js +3 -0
  50. package/dist/identity/internal/Requirements.d.ts +28 -0
  51. package/dist/identity/internal/Requirements.js +78 -0
  52. package/dist/integrations/x402/Evm.d.ts +1 -0
  53. package/dist/internal/env.d.ts +14 -0
  54. package/dist/internal/env.js +38 -0
  55. package/dist/internal/version.d.ts +2 -2
  56. package/dist/internal/version.js +1 -1
  57. package/dist/proxy/internal/Headers.d.ts +1 -1
  58. package/dist/proxy/internal/Headers.js +7 -1
  59. package/dist/server/Mppx.d.ts +14 -6
  60. package/dist/server/Mppx.js +252 -148
  61. package/dist/server/internal/challengeMeta.d.ts +0 -6
  62. package/dist/server/internal/challengeMeta.js +3 -17
  63. package/dist/tempo/server/Charge.d.ts +14 -9
  64. package/dist/tempo/server/Charge.js +5 -1
  65. package/dist/tempo/server/Methods.js +4 -1
  66. package/dist/tempo/server/Subscription.d.ts +8 -0
  67. package/dist/tempo/server/internal/fallback-store.d.ts +7 -2
  68. package/dist/tempo/server/internal/fallback-store.js +12 -3
  69. package/dist/tempo/server/internal/html.gen.js +1 -1
  70. package/dist/tempo/session/server/Session.d.ts +5 -1
  71. package/package.json +9 -1
@@ -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
+ readonly iss: string;
12
+ /** Origin of the server the attestation is for, such as `https://api.example`. */
13
+ readonly aud: string;
14
+ /** Attested subject, such as an email address. */
15
+ readonly sub: string;
16
+ /** Attestation type, such as `email`. */
17
+ readonly type: string;
18
+ /** Issued-at time, in Unix seconds. */
19
+ readonly iat: number;
20
+ /** Expiry time, in Unix seconds. */
21
+ readonly exp: number;
22
+ /** Unique attestation identifier. */
23
+ readonly 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 (`unavailable`).
29
+ */
30
+ export type KeyResolver = (parameters: {
31
+ /** Issuer URL the attestation claims. */
32
+ readonly issuer: string;
33
+ /** Key identifier from the JWS header. */
34
+ readonly 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
+ readonly 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
+ readonly issuer?: string | undefined;
42
+ };
43
+ /** A verified attestation. */
44
+ export type Verified = {
45
+ /** Verified claims. */
46
+ readonly claims: Claims;
47
+ };
48
+ //# sourceMappingURL=Types.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=Types.js.map
@@ -0,0 +1,66 @@
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, and obtains them when a server asks.
6
+ *
7
+ * Each in-scope request carries, in `Identity-Attestation`, the cached attestations whose
8
+ * audience is the request's origin: on a paid attempt every one not expired beyond the clock
9
+ * tolerance, on an unpaid one only those outside the refresh margin, so one close to expiry is
10
+ * replaced before paying. When a server answers 401 or 403 with `Identity-Attestation-Required`,
11
+ * the prover meets each listed group (see {@link requirements}) with one attestation from a
12
+ * trusted issuer, and resends the request with them, keeping the attestations it already carried.
13
+ * Within a group of alternatives it prefers one it holds, and otherwise acquires them in listed
14
+ * order until one succeeds, so a route accepting any of several issuers costs one acquisition.
15
+ *
16
+ * Trust is set by two options together:
17
+ * - `scope`: the origins that may receive attestations and ask for new ones. The audience is
18
+ * always the request's own origin, never one a server names, so a server cannot obtain an
19
+ * attestation it could replay elsewhere.
20
+ * - `issuers`: the issuers `acquire` may be asked for. A server only names an issuer; an
21
+ * untrusted one could relay a code and obtain an attestation for another origin.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * Attestation.Client.prover({
26
+ * scope: ['https://api.example'],
27
+ * issuers: ['https://issuer.example'],
28
+ * types: ['phone'],
29
+ * acquire: ({ audience, issuer }) => obtainPhoneAttestation({ audience, issuer }),
30
+ * })
31
+ * ```
32
+ */
33
+ export declare function prover(config: prover.Config): Identity.Prover;
34
+ export declare namespace prover {
35
+ type Config = {
36
+ /** Origins that receive attestations and may ask for new ones, or `'*'` for any origin. */
37
+ readonly scope: Identity.Prover['scope'];
38
+ /** Attestations obtained beforehand, such as from an issuer with curl. */
39
+ readonly attestations?: readonly string[] | undefined;
40
+ /** Obtains an attestation a server requires, or returns `undefined` to decline. */
41
+ readonly acquire?: ((requirement: {
42
+ /** Origin the attestation must be bound to. */
43
+ readonly audience: string;
44
+ /** Issuer to obtain it from. */
45
+ readonly issuer: string;
46
+ /** Attestation type. */
47
+ readonly type: string;
48
+ }) => MaybePromise<string | undefined>) | undefined;
49
+ /** Issuers `acquire` may be asked for. Required with `acquire`. */
50
+ readonly issuers?: readonly string[] | undefined;
51
+ /** Attestation types `acquire` may be asked for. Defaults to any. */
52
+ readonly types?: readonly string[] | undefined;
53
+ };
54
+ }
55
+ /**
56
+ * Parses the attestation requirements of a rejected response as groups, every one of which a
57
+ * request must meet with any one of its requirements:
58
+ *
59
+ * - An item, such as `phone;issuer="https://a.example"`, is a group of one.
60
+ * - An inner list, such as `(email;issuer="https://a.example" email;issuer="https://b.example")`,
61
+ * is a group of alternatives, as `Identity.anyOf` sends them.
62
+ *
63
+ * Malformed members are skipped, and a group left with none is dropped.
64
+ */
65
+ export declare function requirements(headers: Headers): readonly (readonly Types.Requirement[])[];
66
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,273 @@
1
+ import { isInnerList, parseList, Token as SfToken } from 'structured-headers';
2
+ import { Constants } from '../Constants.js';
3
+ import * as Cache from '../internal/Cache.js';
4
+ import * as Token from '../Token.js';
5
+ /**
6
+ * Creates a prover that presents identity attestations, and obtains them when a server asks.
7
+ *
8
+ * Each in-scope request carries, in `Identity-Attestation`, the cached attestations whose
9
+ * audience is the request's origin: on a paid attempt every one not expired beyond the clock
10
+ * tolerance, on an unpaid one only those outside the refresh margin, so one close to expiry is
11
+ * replaced before paying. When a server answers 401 or 403 with `Identity-Attestation-Required`,
12
+ * the prover meets each listed group (see {@link requirements}) with one attestation from a
13
+ * trusted issuer, and resends the request with them, keeping the attestations it already carried.
14
+ * Within a group of alternatives it prefers one it holds, and otherwise acquires them in listed
15
+ * order until one succeeds, so a route accepting any of several issuers costs one acquisition.
16
+ *
17
+ * Trust is set by two options together:
18
+ * - `scope`: the origins that may receive attestations and ask for new ones. The audience is
19
+ * always the request's own origin, never one a server names, so a server cannot obtain an
20
+ * attestation it could replay elsewhere.
21
+ * - `issuers`: the issuers `acquire` may be asked for. A server only names an issuer; an
22
+ * untrusted one could relay a code and obtain an attestation for another origin.
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * Attestation.Client.prover({
27
+ * scope: ['https://api.example'],
28
+ * issuers: ['https://issuer.example'],
29
+ * types: ['phone'],
30
+ * acquire: ({ audience, issuer }) => obtainPhoneAttestation({ audience, issuer }),
31
+ * })
32
+ * ```
33
+ */
34
+ export function prover(config) {
35
+ if (config.acquire && !config.issuers)
36
+ throw new TypeError('An attestation prover that acquires attestations must list its issuers.');
37
+ // Compared as the verifier names them, without a trailing slash.
38
+ const issuers = config.issuers?.map((issuer) => issuer.replace(/\/+$/, ''));
39
+ const slots = new Map();
40
+ // Tokens a retry replaced because the server rejected them. Several provers' resend headers
41
+ // are combined, so another prover may carry one back; `prove` drops them.
42
+ const replaced = new Set();
43
+ const update = (key, event) => {
44
+ const next = Cache.transition(slots.get(key), event);
45
+ if (next)
46
+ slots.set(key, next);
47
+ else
48
+ slots.delete(key);
49
+ };
50
+ for (const token of config.attestations ?? []) {
51
+ const entry = toEntry(token);
52
+ slots.set(Cache.keyOf(entry.claims), Object.freeze({ phase: 'held', entry }));
53
+ }
54
+ /** Starts acquiring one requirement, so concurrent retries join it. */
55
+ function acquire(key, requirement, audience, rejected) {
56
+ const task = (async () => {
57
+ const token = await config.acquire({ audience, ...requirement });
58
+ if (!token)
59
+ return undefined;
60
+ const entry = toEntry(token, now());
61
+ // Only an attestation for this requirement is kept, so an issuer cannot plant one.
62
+ return Cache.keyOf(entry.claims) === key ? entry : undefined;
63
+ })();
64
+ const pending = task.then((entry) => {
65
+ update(key, { type: 'settle', entry });
66
+ return entry;
67
+ }, (error) => {
68
+ update(key, { type: 'settle', entry: undefined });
69
+ throw error;
70
+ });
71
+ update(key, { type: 'acquire', pending, rejected });
72
+ return pending;
73
+ }
74
+ return {
75
+ scope: config.scope,
76
+ prove(request, context) {
77
+ const origin = new URL(request.url).origin;
78
+ // A bearer attestation never goes over plaintext HTTP, except to localhost.
79
+ if (!Token.isIssuer(origin))
80
+ return request;
81
+ const attempt = context.challenge !== undefined ? 'paid' : 'unpaid';
82
+ const time = now();
83
+ // An attestation already on the request (such as one a retry carried on to the paid
84
+ // attempt) is dropped once it has expired beyond the clock tolerance: the server would
85
+ // reject it, so a fresher cached one goes in its place.
86
+ const carried = Token.parseHeader(request.headers.get(Constants.header));
87
+ for (const token of replaced)
88
+ if (expired(token, origin, time))
89
+ replaced.delete(token);
90
+ const kept = [...new Set(carried)].filter((token) => !replaced.has(token) && !expired(token, origin, time));
91
+ const present = new Set(kept);
92
+ const tokens = [...slots.values()]
93
+ .map(Cache.entryOf)
94
+ .filter((entry) => entry?.claims.aud === origin &&
95
+ Cache.usable(entry, time, attempt) &&
96
+ !present.has(entry.token))
97
+ .map(({ token }) => token);
98
+ if (tokens.length === 0 && kept.length === carried.length)
99
+ return request;
100
+ const headers = new Headers(request.headers);
101
+ const value = [...kept, ...tokens].join(', ');
102
+ if (value)
103
+ headers.set(Constants.header, value);
104
+ else
105
+ headers.delete(Constants.header);
106
+ return new Request(request, { headers });
107
+ },
108
+ async retry(response, context) {
109
+ if (response.status !== 401 && response.status !== 403)
110
+ return undefined;
111
+ // The resend goes to the request's URL, so attestations are bound to its origin, and a
112
+ // response from any other origin (a followed redirect) is never answered.
113
+ const target = context?.request.url ?? response.url;
114
+ if (!URL.canParse(target))
115
+ return undefined;
116
+ const audience = new URL(target).origin;
117
+ if (URL.canParse(response.url) && new URL(response.url).origin !== audience)
118
+ return undefined;
119
+ if (!Token.isIssuer(audience))
120
+ return undefined;
121
+ const sent = sentTokens(context?.request);
122
+ const obtained = new Map();
123
+ // Requirements tried in this retry, so one listed in several groups is acquired once.
124
+ const tried = new Set();
125
+ let failure;
126
+ // Every group must be met; one alternative meets it.
127
+ for (const group of requirements(response.headers)) {
128
+ const alternatives = trusted(group, audience);
129
+ if (alternatives.some(({ key }) => obtained.has(key)))
130
+ continue;
131
+ const decided = alternatives
132
+ .filter(({ key }) => !tried.has(key))
133
+ .map((alternative) => ({
134
+ ...alternative,
135
+ decision: Cache.decide({
136
+ now: now(),
137
+ sent: sent.get(alternative.key) ?? [],
138
+ slot: slots.get(alternative.key),
139
+ }),
140
+ }));
141
+ for (const { decision, key, requirement } of Cache.order(decided)) {
142
+ tried.add(key);
143
+ try {
144
+ const entry = decision.action === 'reuse'
145
+ ? decision.entry
146
+ : decision.action === 'join'
147
+ ? await decision.pending
148
+ : decision.action === 'acquire' && config.acquire
149
+ ? await acquire(key, requirement, audience, decision.rejected)
150
+ : undefined;
151
+ if (entry) {
152
+ obtained.set(key, entry.token);
153
+ break;
154
+ }
155
+ }
156
+ catch (error) {
157
+ // One issuer failing does not stop the next alternative or the other groups.
158
+ failure ??= { error };
159
+ }
160
+ }
161
+ }
162
+ // A failure surfaces only when nothing was obtained, so another attestation still resends.
163
+ if (obtained.size === 0) {
164
+ if (failure)
165
+ throw failure.error;
166
+ return undefined;
167
+ }
168
+ // The resend header replaces the request's, so the attestations the request already
169
+ // carried stay, except those this retry replaced.
170
+ for (const [key, tokens] of sent)
171
+ if (obtained.has(key))
172
+ for (const token of tokens)
173
+ replaced.add(token);
174
+ const kept = [...sent].filter(([key]) => !obtained.has(key)).flatMap(([, tokens]) => tokens);
175
+ return { [Constants.header]: [...kept, ...obtained.values()].join(', ') };
176
+ },
177
+ };
178
+ /** The trusted requirements, each once, in listed order. */
179
+ function trusted(list, audience) {
180
+ const result = new Map();
181
+ for (const { issuer, type } of list) {
182
+ if (!issuer || !issuers?.includes(issuer))
183
+ continue;
184
+ if (config.types && !config.types.includes(type))
185
+ continue;
186
+ const key = Cache.keyOf({ aud: audience, iss: issuer, type });
187
+ if (!result.has(key))
188
+ result.set(key, { key, requirement: { issuer, type } });
189
+ }
190
+ return [...result.values()];
191
+ }
192
+ }
193
+ /**
194
+ * Parses the attestation requirements of a rejected response as groups, every one of which a
195
+ * request must meet with any one of its requirements:
196
+ *
197
+ * - An item, such as `phone;issuer="https://a.example"`, is a group of one.
198
+ * - An inner list, such as `(email;issuer="https://a.example" email;issuer="https://b.example")`,
199
+ * is a group of alternatives, as `Identity.anyOf` sends them.
200
+ *
201
+ * Malformed members are skipped, and a group left with none is dropped.
202
+ */
203
+ export function requirements(headers) {
204
+ const value = headers.get(Constants.requiredHeader);
205
+ if (!value)
206
+ return [];
207
+ let list;
208
+ try {
209
+ list = parseList(value);
210
+ }
211
+ catch {
212
+ return [];
213
+ }
214
+ const groups = list
215
+ .map((member) => (isInnerList(member) ? member[0] : [member]).flatMap((item) => toRequirement(item) ?? []))
216
+ .filter((group) => group.length > 0)
217
+ .map((group) => Object.freeze(group));
218
+ return Object.freeze(groups);
219
+ }
220
+ /** Parses one requirement item, or returns `undefined` when it is malformed. */
221
+ function toRequirement([value, parameters]) {
222
+ if (!(value instanceof SfToken))
223
+ return undefined;
224
+ const type = value.toString();
225
+ const issuer = parameters.get('issuer');
226
+ if (issuer === undefined)
227
+ return Object.freeze({ type });
228
+ if (typeof issuer === 'string' && Token.isIssuer(issuer))
229
+ return Object.freeze({ type, issuer });
230
+ return undefined;
231
+ }
232
+ /** The current Unix time, in seconds. */
233
+ function now() {
234
+ return Math.floor(Date.now() / 1_000);
235
+ }
236
+ /** Decodes a token into a frozen cache entry, or throws a `TypeError` if it is malformed. */
237
+ function toEntry(token, received) {
238
+ const claims = Token.decode(token)?.claims;
239
+ if (!claims ||
240
+ typeof claims.aud !== 'string' ||
241
+ typeof claims.iss !== 'string' ||
242
+ typeof claims.type !== 'string' ||
243
+ typeof claims.exp !== 'number' ||
244
+ typeof claims.iat !== 'number')
245
+ throw new TypeError('Identity attestation is malformed.');
246
+ return Object.freeze({
247
+ token,
248
+ claims: Object.freeze({ ...claims }),
249
+ ...(received !== undefined && { received }),
250
+ });
251
+ }
252
+ /** Whether a token for `origin` has expired beyond the clock tolerance at `now`. */
253
+ function expired(token, origin, now) {
254
+ const claims = Token.decode(token)?.claims;
255
+ return (claims?.aud === origin &&
256
+ typeof claims.exp === 'number' &&
257
+ claims.exp <= now - Constants.clockTolerance);
258
+ }
259
+ /** The attestation tokens a request sent, by cache key. */
260
+ function sentTokens(request) {
261
+ const sent = new Map();
262
+ for (const token of Token.parseHeader(request?.headers.get(Constants.header) ?? null)) {
263
+ const claims = Token.decode(token)?.claims;
264
+ if (typeof claims?.aud !== 'string' ||
265
+ typeof claims.iss !== 'string' ||
266
+ typeof claims.type !== 'string')
267
+ continue;
268
+ const key = Cache.keyOf({ aud: claims.aud, iss: claims.iss, type: claims.type });
269
+ sent.set(key, [...(sent.get(key) ?? []), token]);
270
+ }
271
+ return sent;
272
+ }
273
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,20 @@
1
+ /**
2
+ * MPP identity attestations: a compact EdDSA JWS an issuer signs after checking one fact about
3
+ * the subject (such as an email address or phone number), bound to the origin it is presented
4
+ * to and sent in `Identity-Attestation`.
5
+ *
6
+ * Servers require one with `Server.verifier`, clients present and obtain them with
7
+ * `Client.prover`, and issuers sign them with `sign` and publish their keys as a JSON Web Key
8
+ * Set that `Jwks.resolver` reads.
9
+ */
10
+ /** Client prover that presents and obtains attestations. */
11
+ export * as Client from './client/index.js';
12
+ /** Issuer JSON Web Key Set resolver. */
13
+ export * as Jwks from './Jwks.js';
14
+ /** Server verifier that requires an attestation. */
15
+ export * as Server from './server/index.js';
16
+ export { decode, sign, verify } from './Token.js';
17
+ export type { Decoded, VerifyResult } from './Token.js';
18
+ export * from './Constants.js';
19
+ export type * from './Types.js';
20
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,18 @@
1
+ /**
2
+ * MPP identity attestations: a compact EdDSA JWS an issuer signs after checking one fact about
3
+ * the subject (such as an email address or phone number), bound to the origin it is presented
4
+ * to and sent in `Identity-Attestation`.
5
+ *
6
+ * Servers require one with `Server.verifier`, clients present and obtain them with
7
+ * `Client.prover`, and issuers sign them with `sign` and publish their keys as a JSON Web Key
8
+ * Set that `Jwks.resolver` reads.
9
+ */
10
+ /** Client prover that presents and obtains attestations. */
11
+ export * as Client from './client/index.js';
12
+ /** Issuer JSON Web Key Set resolver. */
13
+ export * as Jwks from './Jwks.js';
14
+ /** Server verifier that requires an attestation. */
15
+ export * as Server from './server/index.js';
16
+ export { decode, sign, verify } from './Token.js';
17
+ export * from './Constants.js';
18
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,120 @@
1
+ import type * as Types from '../Types.js';
2
+ /**
3
+ * The client's attestation cache as data: slots keyed by audience, issuer and type, with pure
4
+ * functions for what a prover sends and how a retry answers a rejection.
5
+ */
6
+ /**
7
+ * A cached attestation: the token and its decoded claims, frozen. `received` is the client's
8
+ * time when it acquired the attestation; one given beforehand has none.
9
+ */
10
+ export type Entry = {
11
+ readonly token: string;
12
+ readonly claims: Types.Claims;
13
+ readonly received?: number | undefined;
14
+ };
15
+ /**
16
+ * One cache slot, as a state machine. A missing slot (`undefined`) holds nothing.
17
+ *
18
+ * - `held`: an attestation is cached.
19
+ * - `acquiring`: an acquisition is pending, which concurrent retries join. `previous`, the
20
+ * attestation it replaces, is still sent until it settles, unless the server rejected it.
21
+ */
22
+ export type Slot = {
23
+ readonly phase: 'held';
24
+ readonly entry: Entry;
25
+ } | {
26
+ readonly phase: 'acquiring';
27
+ readonly pending: Promise<Entry | undefined>;
28
+ readonly previous?: Entry | undefined;
29
+ };
30
+ /** An input to {@link transition}. */
31
+ export type Event =
32
+ /** An acquisition starts; `rejected` is the token the server rejected, if any. */
33
+ {
34
+ readonly type: 'acquire';
35
+ readonly pending: Promise<Entry | undefined>;
36
+ readonly rejected?: string | undefined;
37
+ }
38
+ /** The acquisition settled, with the attestation it obtained or `undefined`. */
39
+ | {
40
+ readonly type: 'settle';
41
+ readonly entry: Entry | undefined;
42
+ };
43
+ /** Whether an attempt pays: a paid attempt is never resent. */
44
+ export type Attempt = 'paid' | 'unpaid';
45
+ /** How a retry answers one requirement, or one type's alternatives. */
46
+ export type Decision =
47
+ /** Resend with an attestation the cache already holds. */
48
+ {
49
+ readonly action: 'reuse';
50
+ readonly entry: Entry;
51
+ }
52
+ /** Wait for a pending acquisition of the same attestation. */
53
+ | {
54
+ readonly action: 'join';
55
+ readonly pending: Promise<Entry | undefined>;
56
+ }
57
+ /** Obtain a new attestation, replacing `rejected` if the request sent it. */
58
+ | {
59
+ readonly action: 'acquire';
60
+ readonly rejected?: string | undefined;
61
+ }
62
+ /** Do nothing: a new attestation would not change the outcome. */
63
+ | {
64
+ readonly action: 'skip';
65
+ };
66
+ /**
67
+ * Orders the alternatives of one requirement group for a retry, as data: one the cache holds
68
+ * first, then one being acquired, then those to acquire, each in listed order. Skipped ones are
69
+ * dropped. Pure.
70
+ */
71
+ export declare function order<alternative extends {
72
+ readonly decision: Decision;
73
+ }>(alternatives: readonly alternative[]): readonly alternative[];
74
+ /** Returns the cache key of an attestation. */
75
+ export declare function keyOf(claims: Pick<Types.Claims, 'aud' | 'iss' | 'type'>): string;
76
+ /**
77
+ * Returns the next slot. Pure; throws a `TypeError` for an event the slot does not accept.
78
+ *
79
+ * | Slot | Event | Next |
80
+ * | ----------------- | --------------------- | ------------------------------------------- |
81
+ * | none, `held` | `acquire` | `acquiring`, keeping the entry unless rejected |
82
+ * | `acquiring` | `settle` with entry | `held` with the new entry |
83
+ * | `acquiring` | `settle` without | `held` with `previous`, or none |
84
+ */
85
+ export declare function transition(slot: Slot | undefined, event: Event): Slot | undefined;
86
+ /** Returns the attestation a slot sends: the held one, or the one being replaced. */
87
+ export declare function entryOf(slot: Slot): Entry | undefined;
88
+ /**
89
+ * Seconds before expiry at which an unpaid attempt stops sending an attestation: the refresh
90
+ * margin, capped at half its lifetime so a short-lived attestation is still sent. The lifetime
91
+ * of an acquired attestation runs from when the client received it, not the issuer's `iat`,
92
+ * so an issuer whose clock trails the client's cannot make every fresh one look expiring and
93
+ * force a new acquisition on each request.
94
+ */
95
+ export declare function margin(entry: Pick<Entry, 'claims' | 'received'>): number;
96
+ /**
97
+ * Whether an attestation may be sent at `now`: on a paid attempt until it expires beyond the
98
+ * clock tolerance, since dropping it could reject a payment already pushed; on an unpaid one only
99
+ * outside the refresh {@link margin}, so it is replaced before paying.
100
+ */
101
+ export declare function usable(entry: Entry, now: number, attempt: Attempt): boolean;
102
+ /**
103
+ * Decides how a retry answers one requirement, from its slot and the tokens for it that the
104
+ * rejected request sent. Pure.
105
+ *
106
+ * - A pending acquisition is joined.
107
+ * - A listed requirement is answered whatever the response's status: a verifier lists its
108
+ * requirement only when a fresh attestation could pass, even when another verifier made the
109
+ * combined status 403.
110
+ * - A cached attestation the request sent is replaced: the server rejected it.
111
+ * - A different, unexpired one is reused: it is newer than what the request sent, or the request
112
+ * sent none and it is outside the refresh margin.
113
+ * - Otherwise a new one is acquired.
114
+ */
115
+ export declare function decide(parameters: {
116
+ readonly slot: Slot | undefined;
117
+ readonly sent: readonly string[];
118
+ readonly now: number;
119
+ }): Decision;
120
+ //# sourceMappingURL=Cache.d.ts.map
@@ -0,0 +1,90 @@
1
+ import { Constants } from '../Constants.js';
2
+ /** Order in which a retry tries a group's alternatives: no new attestation first. */
3
+ const rank = { reuse: 0, join: 1, acquire: 2, skip: 3 };
4
+ /**
5
+ * Orders the alternatives of one requirement group for a retry, as data: one the cache holds
6
+ * first, then one being acquired, then those to acquire, each in listed order. Skipped ones are
7
+ * dropped. Pure.
8
+ */
9
+ export function order(alternatives) {
10
+ return alternatives
11
+ .filter(({ decision }) => decision.action !== 'skip')
12
+ .sort((a, b) => rank[a.decision.action] - rank[b.decision.action]);
13
+ }
14
+ /** Returns the cache key of an attestation. */
15
+ export function keyOf(claims) {
16
+ return JSON.stringify([claims.aud, claims.iss, claims.type]);
17
+ }
18
+ /**
19
+ * Returns the next slot. Pure; throws a `TypeError` for an event the slot does not accept.
20
+ *
21
+ * | Slot | Event | Next |
22
+ * | ----------------- | --------------------- | ------------------------------------------- |
23
+ * | none, `held` | `acquire` | `acquiring`, keeping the entry unless rejected |
24
+ * | `acquiring` | `settle` with entry | `held` with the new entry |
25
+ * | `acquiring` | `settle` without | `held` with `previous`, or none |
26
+ */
27
+ export function transition(slot, event) {
28
+ if (event.type === 'acquire' && slot?.phase !== 'acquiring') {
29
+ const previous = slot?.entry.token === event.rejected ? undefined : slot?.entry;
30
+ return Object.freeze({ phase: 'acquiring', pending: event.pending, previous });
31
+ }
32
+ if (event.type === 'settle' && slot?.phase === 'acquiring') {
33
+ const entry = event.entry ?? slot.previous;
34
+ return entry ? Object.freeze({ phase: 'held', entry }) : undefined;
35
+ }
36
+ throw new TypeError(`Illegal attestation cache transition "${event.type}" from "${slot?.phase ?? 'none'}".`);
37
+ }
38
+ /** Returns the attestation a slot sends: the held one, or the one being replaced. */
39
+ export function entryOf(slot) {
40
+ return slot.phase === 'held' ? slot.entry : slot.previous;
41
+ }
42
+ /**
43
+ * Seconds before expiry at which an unpaid attempt stops sending an attestation: the refresh
44
+ * margin, capped at half its lifetime so a short-lived attestation is still sent. The lifetime
45
+ * of an acquired attestation runs from when the client received it, not the issuer's `iat`,
46
+ * so an issuer whose clock trails the client's cannot make every fresh one look expiring and
47
+ * force a new acquisition on each request.
48
+ */
49
+ export function margin(entry) {
50
+ const { exp, iat } = entry.claims;
51
+ return Math.min(Constants.refreshMargin, Math.floor((exp - (entry.received ?? iat)) / 2));
52
+ }
53
+ /**
54
+ * Whether an attestation may be sent at `now`: on a paid attempt until it expires beyond the
55
+ * clock tolerance, since dropping it could reject a payment already pushed; on an unpaid one only
56
+ * outside the refresh {@link margin}, so it is replaced before paying.
57
+ */
58
+ export function usable(entry, now, attempt) {
59
+ const { exp } = entry.claims;
60
+ if (exp <= now - Constants.clockTolerance)
61
+ return false;
62
+ return attempt === 'paid' || exp - now > margin(entry);
63
+ }
64
+ /**
65
+ * Decides how a retry answers one requirement, from its slot and the tokens for it that the
66
+ * rejected request sent. Pure.
67
+ *
68
+ * - A pending acquisition is joined.
69
+ * - A listed requirement is answered whatever the response's status: a verifier lists its
70
+ * requirement only when a fresh attestation could pass, even when another verifier made the
71
+ * combined status 403.
72
+ * - A cached attestation the request sent is replaced: the server rejected it.
73
+ * - A different, unexpired one is reused: it is newer than what the request sent, or the request
74
+ * sent none and it is outside the refresh margin.
75
+ * - Otherwise a new one is acquired.
76
+ */
77
+ export function decide(parameters) {
78
+ const { now, sent, slot } = parameters;
79
+ if (slot?.phase === 'acquiring')
80
+ return { action: 'join', pending: slot.pending };
81
+ const entry = slot?.entry;
82
+ if (!entry || !usable(entry, now, 'paid'))
83
+ return { action: 'acquire', rejected: entry?.token };
84
+ if (sent.includes(entry.token))
85
+ return { action: 'acquire', rejected: entry.token };
86
+ if (sent.length > 0 || usable(entry, now, 'unpaid'))
87
+ return { action: 'reuse', entry };
88
+ return { action: 'acquire' };
89
+ }
90
+ //# sourceMappingURL=Cache.js.map