mppx 0.17.6 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/cli/cli.js +139 -139
  3. package/dist/cli/plugins/index.js +6 -6
  4. package/dist/client/Mppx.js +13 -4
  5. package/dist/client/internal/Fetch.js +9 -5
  6. package/dist/extensions/identity/{email-otp/internal → attestation}/Constants.d.ts +4 -1
  7. package/dist/extensions/identity/{email-otp/internal → attestation}/Constants.js +4 -1
  8. package/dist/extensions/identity/{email-otp/internal → attestation}/Jwks.d.ts +5 -5
  9. package/dist/extensions/identity/{email-otp/internal → attestation}/Jwks.js +1 -1
  10. package/dist/extensions/identity/{email-otp/internal/Attestation.d.ts → attestation/Token.d.ts} +40 -26
  11. package/dist/extensions/identity/{email-otp/internal/Attestation.js → attestation/Token.js} +18 -3
  12. package/dist/extensions/identity/{email-otp/internal → attestation}/Types.d.ts +14 -14
  13. package/dist/extensions/identity/attestation/client/index.d.ts +66 -0
  14. package/dist/extensions/identity/attestation/client/index.js +273 -0
  15. package/dist/extensions/identity/attestation/index.d.ts +20 -0
  16. package/dist/extensions/identity/attestation/index.js +18 -0
  17. package/dist/extensions/identity/attestation/internal/Cache.d.ts +120 -0
  18. package/dist/extensions/identity/attestation/internal/Cache.js +90 -0
  19. package/dist/extensions/identity/attestation/server/index.d.ts +66 -0
  20. package/dist/extensions/identity/attestation/server/index.js +119 -0
  21. package/dist/extensions/identity/email-otp/Constants.d.ts +5 -5
  22. package/dist/extensions/identity/email-otp/Constants.js +6 -5
  23. package/dist/extensions/identity/email-otp/Types.d.ts +4 -4
  24. package/dist/extensions/identity/email-otp/client/index.d.ts +22 -15
  25. package/dist/extensions/identity/email-otp/client/index.js +17 -5
  26. package/dist/extensions/identity/email-otp/index.d.ts +3 -8
  27. package/dist/extensions/identity/email-otp/index.js +3 -8
  28. package/dist/extensions/identity/email-otp/server/index.d.ts +16 -16
  29. package/dist/extensions/identity/email-otp/server/index.js +17 -14
  30. package/dist/extensions/identity/index.d.ts +2 -0
  31. package/dist/extensions/identity/index.js +2 -0
  32. package/dist/extensions/identity/internal/Verification.js +9 -5
  33. package/dist/identity/Callback.d.ts +24 -5
  34. package/dist/identity/Callback.js +35 -11
  35. package/dist/identity/Client.d.ts +78 -5
  36. package/dist/identity/Client.js +165 -48
  37. package/dist/identity/Headers.d.ts +16 -0
  38. package/dist/identity/Headers.js +19 -0
  39. package/dist/identity/Server.d.ts +159 -37
  40. package/dist/identity/Server.js +307 -138
  41. package/dist/identity/Status.d.ts +14 -0
  42. package/dist/identity/Status.js +19 -0
  43. package/dist/identity/Types.d.ts +161 -65
  44. package/dist/identity/index.d.ts +2 -0
  45. package/dist/identity/index.js +2 -0
  46. package/dist/identity/internal/Requirements.d.ts +28 -0
  47. package/dist/identity/internal/Requirements.js +78 -0
  48. package/dist/integrations/x402/Evm.d.ts +1 -0
  49. package/dist/internal/env.d.ts +14 -0
  50. package/dist/internal/env.js +38 -0
  51. package/dist/internal/version.d.ts +2 -2
  52. package/dist/internal/version.js +1 -1
  53. package/dist/proxy/internal/Headers.d.ts +1 -1
  54. package/dist/proxy/internal/Headers.js +7 -3
  55. package/dist/server/Mppx.d.ts +14 -6
  56. package/dist/server/Mppx.js +252 -148
  57. package/dist/server/internal/challengeMeta.d.ts +0 -6
  58. package/dist/server/internal/challengeMeta.js +3 -17
  59. package/dist/tempo/server/Charge.d.ts +14 -9
  60. package/dist/tempo/server/Charge.js +5 -1
  61. package/dist/tempo/server/Methods.js +4 -1
  62. package/dist/tempo/server/Subscription.d.ts +8 -0
  63. package/dist/tempo/server/internal/fallback-store.d.ts +7 -2
  64. package/dist/tempo/server/internal/fallback-store.js +12 -3
  65. package/dist/tempo/server/internal/html.gen.js +1 -1
  66. package/dist/tempo/session/server/Session.d.ts +5 -1
  67. package/package.json +5 -1
  68. package/dist/extensions/identity/email-otp/internal/Prover.d.ts +0 -46
  69. package/dist/extensions/identity/email-otp/internal/Prover.js +0 -168
  70. package/dist/extensions/identity/email-otp/internal/Verifier.d.ts +0 -56
  71. package/dist/extensions/identity/email-otp/internal/Verifier.js +0 -116
  72. /package/dist/extensions/identity/{email-otp/internal → attestation}/Types.js +0 -0
@@ -193,7 +193,11 @@ export declare namespace session {
193
193
  *
194
194
  * Session mutations must be linearizable across instances so spent,
195
195
  * highest-voucher, top-up, and close/finalization updates cannot race.
196
- * Use `Store.memory()` for tests or local single-process usage.
196
+ *
197
+ * If omitted, this throws in production (`NODE_ENV=production`), on
198
+ * multi-instance platforms and on Cloudflare Workers, and otherwise warns
199
+ * and falls back to an in-memory store. Pass `Store.memory()` explicitly
200
+ * for tests or local single-process usage.
197
201
  */
198
202
  store?: Store.AtomicStore | undefined;
199
203
  /** Enable SSE streaming. Pass `true` for defaults or an options object to configure SSE. */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mppx",
3
3
  "type": "module",
4
- "version": "0.17.6",
4
+ "version": "0.18.0",
5
5
  "main": "./dist/index.js",
6
6
  "license": "MIT",
7
7
  "homepage": "https://github.com/wevm/mppx#readme",
@@ -131,6 +131,10 @@
131
131
  "types": "./dist/extensions/identity/index.d.ts",
132
132
  "default": "./dist/extensions/identity/index.js"
133
133
  },
134
+ "./extensions/identity/attestation": {
135
+ "types": "./dist/extensions/identity/attestation/index.d.ts",
136
+ "default": "./dist/extensions/identity/attestation/index.js"
137
+ },
134
138
  "./extensions/identity/tap": {
135
139
  "types": "./dist/extensions/identity/tap/index.d.ts",
136
140
  "default": "./dist/extensions/identity/tap/index.js"
@@ -1,46 +0,0 @@
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
@@ -1,168 +0,0 @@
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
@@ -1,56 +0,0 @@
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
@@ -1,116 +0,0 @@
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