mppx 0.18.1 → 0.19.1

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 (73) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/dist/Errors.d.ts +40 -4
  3. package/dist/Errors.js +40 -6
  4. package/dist/cli/cli.js +96 -96
  5. package/dist/cli/plugins/index.js +12 -12
  6. package/dist/extensions/identity/Types.d.ts +26 -0
  7. package/dist/extensions/identity/attestation/Token.d.ts +6 -4
  8. package/dist/extensions/identity/attestation/Token.js +11 -5
  9. package/dist/extensions/identity/index.d.ts +2 -0
  10. package/dist/extensions/identity/index.js +2 -0
  11. package/dist/extensions/identity/internal/HttpMessageSignature.d.ts +2 -2
  12. package/dist/extensions/identity/internal/HttpMessageSignature.js +13 -10
  13. package/dist/extensions/identity/{web-bot-auth/internal → internal}/JwkThumbprint.js +1 -1
  14. package/dist/extensions/identity/internal/Signer.d.ts +20 -0
  15. package/dist/extensions/identity/internal/Signer.js +94 -0
  16. package/dist/extensions/identity/poppy/Constants.d.ts +26 -0
  17. package/dist/extensions/identity/poppy/Constants.js +26 -0
  18. package/dist/extensions/identity/poppy/Types.d.ts +19 -0
  19. package/dist/extensions/identity/poppy/Types.js +2 -0
  20. package/dist/extensions/identity/poppy/client/index.d.ts +69 -0
  21. package/dist/extensions/identity/poppy/client/index.js +81 -0
  22. package/dist/extensions/identity/poppy/index.d.ts +7 -0
  23. package/dist/extensions/identity/poppy/index.js +7 -0
  24. package/dist/extensions/identity/poppy/internal/Jws.d.ts +12 -0
  25. package/dist/extensions/identity/poppy/internal/Jws.js +78 -0
  26. package/dist/extensions/identity/poppy/server/index.d.ts +40 -0
  27. package/dist/extensions/identity/poppy/server/index.js +181 -0
  28. package/dist/extensions/identity/tap/client/index.d.ts +6 -2
  29. package/dist/extensions/identity/tap/client/index.js +2 -0
  30. package/dist/extensions/identity/tempo/Constants.d.ts +14 -0
  31. package/dist/extensions/identity/tempo/Constants.js +14 -0
  32. package/dist/extensions/identity/tempo/Types.d.ts +31 -0
  33. package/dist/extensions/identity/tempo/Types.js +2 -0
  34. package/dist/extensions/identity/tempo/client/index.d.ts +34 -0
  35. package/dist/extensions/identity/tempo/client/index.js +60 -0
  36. package/dist/extensions/identity/tempo/index.d.ts +5 -0
  37. package/dist/extensions/identity/tempo/index.js +4 -0
  38. package/dist/extensions/identity/tempo/internal/Jwt.d.ts +36 -0
  39. package/dist/extensions/identity/tempo/internal/Jwt.js +114 -0
  40. package/dist/extensions/identity/tempo/server/index.d.ts +65 -0
  41. package/dist/extensions/identity/tempo/server/index.js +247 -0
  42. package/dist/extensions/identity/web-bot-auth/client/index.d.ts +6 -4
  43. package/dist/extensions/identity/web-bot-auth/client/index.js +7 -5
  44. package/dist/extensions/identity/web-bot-auth/server/index.js +1 -1
  45. package/dist/extensions/identity/world/Constants.d.ts +50 -0
  46. package/dist/extensions/identity/world/Constants.js +50 -0
  47. package/dist/extensions/identity/world/Types.d.ts +52 -0
  48. package/dist/extensions/identity/world/Types.js +2 -0
  49. package/dist/extensions/identity/world/client/index.d.ts +103 -0
  50. package/dist/extensions/identity/world/client/index.js +208 -0
  51. package/dist/extensions/identity/world/index.d.ts +6 -0
  52. package/dist/extensions/identity/world/index.js +5 -0
  53. package/dist/extensions/identity/world/internal/Idp.d.ts +50 -0
  54. package/dist/extensions/identity/world/internal/Idp.js +265 -0
  55. package/dist/extensions/identity/world/issuer/index.d.ts +120 -0
  56. package/dist/extensions/identity/world/issuer/index.js +520 -0
  57. package/dist/extensions/identity/world/server/index.d.ts +49 -0
  58. package/dist/extensions/identity/world/server/index.js +63 -0
  59. package/dist/identity/Headers.d.ts +1 -1
  60. package/dist/identity/Headers.js +7 -1
  61. package/dist/identity/Types.d.ts +5 -0
  62. package/dist/internal/version.d.ts +2 -2
  63. package/dist/internal/version.js +1 -1
  64. package/dist/server/Mppx.js +2 -1
  65. package/dist/tempo/client/Charge.js +39 -16
  66. package/dist/tempo/internal/simulation.d.ts +33 -0
  67. package/dist/tempo/internal/simulation.js +80 -0
  68. package/dist/tempo/internal/zone.d.ts +27 -0
  69. package/dist/tempo/internal/zone.js +54 -7
  70. package/dist/tempo/server/internal/html.gen.js +1 -1
  71. package/dist/tempo/session/client/ChannelOps.js +5 -2
  72. package/package.json +13 -1
  73. /package/dist/extensions/identity/{web-bot-auth/internal → internal}/JwkThumbprint.d.ts +0 -0
@@ -0,0 +1,40 @@
1
+ import type * as Identity from '../../../../identity/Types.js';
2
+ import type * as Types from '../Types.js';
3
+ /**
4
+ * Creates a verifier for Poppy's `Poppy-Session` header (Personal Agent Protocol 1.0, spec 5.3).
5
+ *
6
+ * It fetches the Personal Agent's client metadata from `client_id` and its keys from
7
+ * `jwks_uri`, verifies the delegation and the Session JWT, and checks the audience, method, URL,
8
+ * time and access-token binding. The verified value names the agent, the pseudonymous User and
9
+ * the Session, so a route can price or allow by them before any payment Challenge.
10
+ *
11
+ * A Session never grants account access. When the request also carries an access token, the
12
+ * verifier for that token must check it was issued to the Session's `clientId`.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * const poppy = Poppy.Server.verifier({
17
+ * audience: 'https://api.example.com',
18
+ * clients: ['https://agent.example/agent.json'],
19
+ * })
20
+ *
21
+ * mppx.charge({ amount: '0.01', identity: [poppy] })
22
+ * ```
23
+ */
24
+ export declare function verifier(config: verifier.Config): Identity.Verifier<Types.Session>;
25
+ export declare namespace verifier {
26
+ type Config = {
27
+ /** This Company's identifier, compared with `aud`: its OAuth issuer, or `https://{organization.domain}`. */
28
+ audience: string;
29
+ /**
30
+ * Personal Agent `client_id`s to accept. The verifier fetches metadata and keys only for
31
+ * these, so callers can't make it request other URLs, and its key cache stays this size.
32
+ */
33
+ clients: readonly string[];
34
+ /** Accepted seconds between a Session JWT's `iat` and now. @default 60 */
35
+ maxAge?: number | undefined;
36
+ /** Fetch for client metadata and keys. @default globalThis.fetch */
37
+ fetch?: typeof globalThis.fetch | undefined;
38
+ };
39
+ }
40
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,181 @@
1
+ import { unwrapFetch } from '../../../../client/internal/Fetch.js';
2
+ import * as Jwt from '../../tempo/internal/Jwt.js';
3
+ import { Constants } from '../Constants.js';
4
+ import * as Jws from '../internal/Jws.js';
5
+ /**
6
+ * Creates a verifier for Poppy's `Poppy-Session` header (Personal Agent Protocol 1.0, spec 5.3).
7
+ *
8
+ * It fetches the Personal Agent's client metadata from `client_id` and its keys from
9
+ * `jwks_uri`, verifies the delegation and the Session JWT, and checks the audience, method, URL,
10
+ * time and access-token binding. The verified value names the agent, the pseudonymous User and
11
+ * the Session, so a route can price or allow by them before any payment Challenge.
12
+ *
13
+ * A Session never grants account access. When the request also carries an access token, the
14
+ * verifier for that token must check it was issued to the Session's `clientId`.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * const poppy = Poppy.Server.verifier({
19
+ * audience: 'https://api.example.com',
20
+ * clients: ['https://agent.example/agent.json'],
21
+ * })
22
+ *
23
+ * mppx.charge({ amount: '0.01', identity: [poppy] })
24
+ * ```
25
+ */
26
+ export function verifier(config) {
27
+ const { audience, clients, maxAge = Constants.maxAge } = config;
28
+ if (!Array.isArray(clients) || !clients.every((client) => typeof client === 'string'))
29
+ throw new TypeError('Poppy clients must be an array of client_id URLs.');
30
+ if (!Number.isInteger(maxAge) || maxAge <= 0)
31
+ throw new RangeError('Poppy maxAge must be a positive integer.');
32
+ const fetch = unwrapFetch(config.fetch ?? globalThis.fetch);
33
+ const cache = new Map();
34
+ // The last key set that loaded for each client, which a failed reload keeps for a while.
35
+ const loaded = new Map();
36
+ // Spec 5.3: a failed Session check is HTTP 400 with `invalid_session`, not 401, so OAuth
37
+ // clients keep a valid access token.
38
+ const headers = { 'Content-Type': 'application/json' };
39
+ const body = (description) => JSON.stringify({ error: 'invalid_session', error_description: description });
40
+ const invalid = (reason) => ({ status: 'invalid', code: 400, headers, reason: body(reason) });
41
+ /** Fetches a client's metadata, without following redirects, then its keys (spec 4.1). */
42
+ async function load(clientId) {
43
+ const options = { redirect: 'manual', signal: AbortSignal.timeout(5_000) };
44
+ const response = await fetch(clientId, options);
45
+ if (!response.ok)
46
+ throw new Error(`Client metadata request failed with ${response.status}.`);
47
+ const metadata = (await response.json());
48
+ if (metadata.client_id !== clientId)
49
+ throw new Error('client_id does not match its URL.');
50
+ const jwksUri = typeof metadata.jwks_uri === 'string' ? new URL(metadata.jwks_uri) : undefined;
51
+ if (jwksUri?.protocol !== 'https:' || jwksUri.hostname !== new URL(clientId).hostname)
52
+ throw new Error('jwks_uri must be HTTPS on the client_id domain.');
53
+ const jwks = await fetch(jwksUri, options);
54
+ if (!jwks.ok)
55
+ throw new Error(`Key set request failed with ${jwks.status}.`);
56
+ const { keys } = (await jwks.json());
57
+ if (!Array.isArray(keys))
58
+ throw new Error('The key set has no keys array.');
59
+ return keys.filter(isObject);
60
+ }
61
+ /**
62
+ * Returns a client's keys, loaded at most `maxAge` seconds ago. A load is cached for 5
63
+ * minutes, and a failed one for 30 seconds, so a failing agent isn't refetched per request.
64
+ * A failed reload keeps the keys that last loaded, so a request that forces a reload can't
65
+ * replace them with the failure, but only for an hour after they loaded, so a removed key
66
+ * stops verifying within an hour even while the agent is unreachable.
67
+ */
68
+ function keys(clientId, maxAge = Constants.keyCacheTtl) {
69
+ const cached = cache.get(clientId);
70
+ if (cached && Date.now() - cached.at < Math.min(cached.ttl, maxAge) * 1_000)
71
+ return cached.keys;
72
+ const last = loaded.get(clientId);
73
+ const entry = { at: Date.now(), ttl: Constants.keyCacheTtl, keys: load(clientId) };
74
+ entry.keys = entry.keys.then((keys) => {
75
+ loaded.set(clientId, { at: Date.now(), keys });
76
+ return keys;
77
+ }, (error) => {
78
+ entry.ttl = Constants.keyRetryAfter;
79
+ const left = last ? Constants.keyStaleTtl - (Date.now() - last.at) / 1_000 : 0;
80
+ if (left <= 0)
81
+ throw error;
82
+ // Cache the fallback no longer than its hour lasts.
83
+ entry.ttl = Math.min(entry.ttl, left);
84
+ return last.keys;
85
+ });
86
+ cache.set(clientId, entry);
87
+ return entry.keys;
88
+ }
89
+ /** The published key with the delegation's `kid`, if it may verify the delegation's `alg`. */
90
+ function signer(jwks, header) {
91
+ if (typeof header.kid !== 'string')
92
+ return undefined;
93
+ return jwks.find((jwk) => {
94
+ const { alg, key_ops, kid, use } = jwk;
95
+ return (kid === header.kid &&
96
+ (use === undefined || use === 'sig') &&
97
+ (key_ops === undefined || (Array.isArray(key_ops) && key_ops.includes('verify'))) &&
98
+ (alg === undefined || alg === header.alg));
99
+ });
100
+ }
101
+ return {
102
+ async verify(request) {
103
+ const token = request.headers.get(Constants.sessionHeader);
104
+ if (!token)
105
+ return {
106
+ status: 'missing',
107
+ code: 400,
108
+ headers,
109
+ reason: body('Send a Poppy-Session header.'),
110
+ };
111
+ const session = Jwt.decode(token);
112
+ if (session?.header.typ !== Constants.sessionType || session.header.alg !== 'ES256')
113
+ return invalid('The Poppy-Session header is not a Session JWT.');
114
+ const { agent_id, ath, aud, htm, htu, iat, iss, jti, sid, sub } = session.claims;
115
+ const strings = [iss, sid, sub, jti];
116
+ if (strings.some((value) => typeof value !== 'string' || !value))
117
+ return invalid('The Session JWT is missing a claim.');
118
+ if (agent_id !== undefined && typeof agent_id !== 'string')
119
+ return invalid('The Session JWT agent_id is not a string.');
120
+ if (!URL.canParse(iss) || new URL(iss).protocol !== 'https:')
121
+ return invalid('The Session JWT iss is not an HTTPS client_id.');
122
+ // Checked before any fetch, so callers can't make the verifier request other URLs.
123
+ if (!clients.includes(iss))
124
+ return invalid('This Personal Agent is not accepted.');
125
+ if (aud !== audience)
126
+ return invalid('The Session JWT is for another Company.');
127
+ if (htm !== request.method || htu !== Jwt.htu(request.url))
128
+ return invalid('The Session JWT is for another request.');
129
+ const now = Math.floor(Date.now() / 1_000);
130
+ if (typeof iat !== 'number' || Math.abs(now - iat) > maxAge)
131
+ return invalid('The Session JWT is outside its time window.');
132
+ const accessToken = Jws.accessToken(request.headers);
133
+ if (accessToken === null)
134
+ return invalid('The Authorization header is malformed.');
135
+ if (accessToken ? ath !== (await Jwt.sha256(accessToken)) : ath !== undefined)
136
+ return invalid('The Session JWT ath does not match the access token.');
137
+ const delegation = typeof session.header.poppy_dlg === 'string'
138
+ ? Jwt.decode(session.header.poppy_dlg)
139
+ : undefined;
140
+ if (!delegation)
141
+ return invalid('The Session JWT has no delegation.');
142
+ const { cnf, exp, iat: issued, iss: delegator } = delegation.claims;
143
+ if (delegation.header.typ !== Constants.delegationType || delegator !== iss)
144
+ return invalid('The delegation is not for this Personal Agent.');
145
+ if (typeof exp !== 'number' ||
146
+ typeof issued !== 'number' ||
147
+ exp <= now ||
148
+ // A future `iat` would stretch the delegation past its 24-hour lifetime.
149
+ issued > now + maxAge ||
150
+ exp <= issued ||
151
+ exp - issued > Constants.maxDelegationLifetime)
152
+ return invalid('The delegation has expired.');
153
+ let key;
154
+ try {
155
+ key = signer(await keys(iss), delegation.header);
156
+ // An unknown key may be newly published: reload once the cache is 30 seconds old.
157
+ key ??= signer(await keys(iss, Constants.keyRetryAfter), delegation.header);
158
+ }
159
+ catch {
160
+ return { status: 'unavailable', reason: "The Personal Agent's keys are unavailable." };
161
+ }
162
+ if (!key || !(await Jws.verify(delegation, key, ['ES256', 'PS384'])))
163
+ return invalid('The delegation signature is invalid.');
164
+ const delegated = isObject(cnf) ? cnf.jwk : undefined;
165
+ if (!isObject(delegated) ||
166
+ 'd' in delegated ||
167
+ session.header.kid !== (await Jwt.thumbprint(delegated)))
168
+ return invalid('The Session JWT key does not match its delegation.');
169
+ if (!(await Jws.verify(session, delegated, ['ES256'])))
170
+ return invalid('The Session JWT signature is invalid.');
171
+ return {
172
+ status: 'valid',
173
+ value: { agentId: agent_id, clientId: iss, sessionId: sid, userId: sub },
174
+ };
175
+ },
176
+ };
177
+ }
178
+ function isObject(value) {
179
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
180
+ }
181
+ //# sourceMappingURL=index.js.map
@@ -1,4 +1,5 @@
1
1
  import type * as Identity from '../../../../identity/Types.js';
2
+ import type { SigningKey } from '../../Types.js';
2
3
  import { Constants } from '../Constants.js';
3
4
  /**
4
5
  * Creates a TAP identity prover.
@@ -17,8 +18,11 @@ export declare namespace prover {
17
18
  type Config = {
18
19
  /** TAP signature type for the request. */
19
20
  intent: (typeof Constants.intents)[keyof typeof Constants.intents];
20
- /** Ed25519 or RSA-PSS SHA-512 private key provisioned to the agent provider. */
21
- key: CryptoKey;
21
+ /**
22
+ * Ed25519 or RSA-PSS SHA-512 key pair, or a {@link SigningKey | Signer} for a remote key,
23
+ * provisioned to the agent provider.
24
+ */
25
+ key: SigningKey;
22
26
  /** Identifier the merchant uses to resolve the signing public key. */
23
27
  keyId: string;
24
28
  /** Origins that receive TAP signatures, or `'*'` for any origin. */
@@ -1,4 +1,5 @@
1
1
  import * as HttpMessageSignature from '../../internal/HttpMessageSignature.js';
2
+ import * as Signer from '../../internal/Signer.js';
2
3
  import { Constants } from '../Constants.js';
3
4
  /**
4
5
  * Creates a TAP identity prover.
@@ -15,6 +16,7 @@ import { Constants } from '../Constants.js';
15
16
  export function prover(config) {
16
17
  const tag = config.intent === Constants.intents.payment ? Constants.tags.payment : Constants.tags.browse;
17
18
  const expiresIn = config.expiresIn ?? Constants.defaultSignatureLifetime;
19
+ Signer.resolve(config.key);
18
20
  if (!Number.isInteger(expiresIn) ||
19
21
  expiresIn <= 0 ||
20
22
  expiresIn > Constants.maximumSignatureLifetime)
@@ -0,0 +1,14 @@
1
+ /** Tempo ID values. */
2
+ export declare const Constants: {
3
+ /** Identity type advertised in the 402's `Identity-Required` header. */
4
+ readonly type: 'tempo-id';
5
+ /** Tempo ID in production: the issuer of every access token. */
6
+ readonly issuer: 'https://id.tempo.xyz';
7
+ /** Header that carries the user's ID token, for their email address. */
8
+ readonly idTokenHeader: 'Tempo-Id-Token';
9
+ /** Seconds a DPoP proof is accepted after its `iat`. */
10
+ readonly proofMaxAge: 300;
11
+ /** Seconds of clock skew allowed on token and proof times. */
12
+ readonly clockTolerance: 60;
13
+ };
14
+ //# sourceMappingURL=Constants.d.ts.map
@@ -0,0 +1,14 @@
1
+ /** Tempo ID values. */
2
+ export const Constants = {
3
+ /** Identity type advertised in the 402's `Identity-Required` header. */
4
+ type: 'tempo-id',
5
+ /** Tempo ID in production: the issuer of every access token. */
6
+ issuer: 'https://id.tempo.xyz',
7
+ /** Header that carries the user's ID token, for their email address. */
8
+ idTokenHeader: 'Tempo-Id-Token',
9
+ /** Seconds a DPoP proof is accepted after its `iat`. */
10
+ proofMaxAge: 300,
11
+ /** Seconds of clock skew allowed on token and proof times. */
12
+ clockTolerance: 60,
13
+ };
14
+ //# sourceMappingURL=Constants.js.map
@@ -0,0 +1,31 @@
1
+ import type { Address } from 'ox';
2
+ /** The screening state of a Tempo Account: only `clear` may pay without limits. */
3
+ export type ComplianceState = 'clear' | 'exit_only' | 'blocked' | 'pending';
4
+ /** A Tempo ID user, as a verified access token (and, when sent, ID token) names them. */
5
+ export type Caller = {
6
+ /** The Tempo ID user ID: stable across every app on Tempo ID. */
7
+ readonly userId: string;
8
+ /** The app the user signed in to. */
9
+ readonly clientId: string;
10
+ /** The Tempo Accounts the token grants to the app on the configured chain, checksummed. */
11
+ readonly accounts: readonly Address.Address[];
12
+ /** The screening state of each account in the app's realms, by checksummed address. Empty for an unregistered app. */
13
+ readonly compliance: Readonly<Record<Address.Address, ComplianceState>>;
14
+ /** The user's email address, lowercased, from the ID token. Absent without one, or without the `email` scope. */
15
+ readonly email?: string | undefined;
16
+ /** Whether Tempo ID verified the email address. */
17
+ readonly emailVerified?: boolean | undefined;
18
+ };
19
+ /** A verified Tempo ID user and the Tempo Account that paid. */
20
+ export type Payer = Caller & {
21
+ /** The account that paid, checksummed. Absent when the check ran without a Credential. */
22
+ readonly account?: Address.Address | undefined;
23
+ };
24
+ /** An ES256 DPoP key (RFC 9449), such as the Tempo ID SDK's session key. */
25
+ export type DpopKey = {
26
+ /** The public key as a JWK. */
27
+ readonly jwk: JsonWebKey;
28
+ /** The private key that signs each proof. */
29
+ readonly privateKey: CryptoKey;
30
+ };
31
+ //# sourceMappingURL=Types.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=Types.js.map
@@ -0,0 +1,34 @@
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 sends a Tempo ID access token with each request: as `DPoP` with a new
6
+ * proof when `dpop` is set, else as `Bearer`.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * const mppx = Mppx.create({
11
+ * identity: [
12
+ * TempoId.Client.prover({
13
+ * accessToken: () => accounts.session.accessToken(),
14
+ * scope: ['https://api.example'],
15
+ * }),
16
+ * ],
17
+ * methods: [tempo({ account })],
18
+ * })
19
+ * ```
20
+ */
21
+ export declare function prover(config: prover.Config): Identity.Prover;
22
+ export declare namespace prover {
23
+ type Config = {
24
+ /** Returns a live Tempo ID access token, such as `accounts.session.accessToken`. */
25
+ readonly accessToken: () => MaybePromise<string>;
26
+ /** The DPoP key that binds the token. Absent, the token is sent as a Bearer token. */
27
+ readonly dpop?: Types.DpopKey | undefined;
28
+ /** Returns the user's ID token, such as `accounts.session.get()?.idToken`, so the API reads their email. */
29
+ readonly idToken?: (() => MaybePromise<string | undefined>) | undefined;
30
+ /** Origins that receive the token. Send it only to the API it was issued for. */
31
+ readonly scope: Identity.Prover['scope'];
32
+ };
33
+ }
34
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,60 @@
1
+ import { Base64 } from 'ox';
2
+ import * as Credential from '../../../../Credential.js';
3
+ import { Constants } from '../Constants.js';
4
+ import * as Jwt from '../internal/Jwt.js';
5
+ /**
6
+ * Creates a prover that sends a Tempo ID access token with each request: as `DPoP` with a new
7
+ * proof when `dpop` is set, else as `Bearer`.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * const mppx = Mppx.create({
12
+ * identity: [
13
+ * TempoId.Client.prover({
14
+ * accessToken: () => accounts.session.accessToken(),
15
+ * scope: ['https://api.example'],
16
+ * }),
17
+ * ],
18
+ * methods: [tempo({ account })],
19
+ * })
20
+ * ```
21
+ */
22
+ export function prover(config) {
23
+ const { dpop } = config;
24
+ return {
25
+ scope: config.scope,
26
+ headers: ['dpop', Constants.idTokenHeader.toLowerCase()],
27
+ async prove(request) {
28
+ const accessToken = await config.accessToken();
29
+ const headers = new Headers(request.headers);
30
+ // The access token would replace a Payment Credential in Authorization; a server created
31
+ // with `requiresAuth: true` takes the Credential in Payment-Authorization instead.
32
+ const authorization = headers.get('Authorization');
33
+ if (authorization && Credential.extractPaymentScheme(authorization) !== null)
34
+ throw new TypeError('The Tempo ID access token needs Authorization, which holds the Payment Credential: the server must set requiresAuth: true.');
35
+ headers.set('Authorization', `${dpop ? 'DPoP' : 'Bearer'} ${accessToken}`);
36
+ if (dpop)
37
+ headers.set('DPoP', await proof(dpop, accessToken, request));
38
+ const idToken = await config.idToken?.();
39
+ if (idToken)
40
+ headers.set(Constants.idTokenHeader, idToken);
41
+ return new Request(request, { headers });
42
+ },
43
+ };
44
+ }
45
+ /** Signs a DPoP proof (RFC 9449) of `accessToken` for one request. */
46
+ async function proof(dpop, accessToken, request) {
47
+ const { crv, kty, x, y } = dpop.jwk;
48
+ const header = Jwt.encode({ alg: 'ES256', jwk: { crv, kty, x, y }, typ: 'dpop+jwt' });
49
+ const claims = Jwt.encode({
50
+ ath: await Jwt.sha256(accessToken),
51
+ htm: request.method,
52
+ htu: Jwt.htu(request.url),
53
+ iat: Math.floor(Date.now() / 1_000),
54
+ jti: crypto.randomUUID(),
55
+ });
56
+ const input = `${header}.${claims}`;
57
+ const signature = await crypto.subtle.sign(Jwt.es256.sign, dpop.privateKey, new TextEncoder().encode(input));
58
+ return `${input}.${Base64.fromBytes(new Uint8Array(signature), { pad: false, url: true })}`;
59
+ }
60
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,5 @@
1
+ export * as Client from './client/index.js';
2
+ export { Constants } from './Constants.js';
3
+ export * as Server from './server/index.js';
4
+ export type * from './Types.js';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,4 @@
1
+ export * as Client from './client/index.js';
2
+ export { Constants } from './Constants.js';
3
+ export * as Server from './server/index.js';
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,36 @@
1
+ /** A decoded, unverified compact JWS. */
2
+ export type Decoded = {
3
+ readonly header: Record<string, any>;
4
+ readonly claims: Record<string, any>;
5
+ readonly signingInput: Uint8Array<ArrayBuffer>;
6
+ readonly signature: Uint8Array<ArrayBuffer>;
7
+ };
8
+ /** ES256 in Web Crypto: the only DPoP algorithm the Tempo ID SDK signs with. */
9
+ export declare const es256: {
10
+ readonly key: {
11
+ readonly name: 'ECDSA';
12
+ readonly namedCurve: 'P-256';
13
+ };
14
+ readonly sign: {
15
+ readonly name: 'ECDSA';
16
+ readonly hash: 'SHA-256';
17
+ };
18
+ };
19
+ /** Decodes a compact JWS without verifying it, or returns `undefined` if it is malformed. */
20
+ export declare function decode(token: string): Decoded | undefined;
21
+ /** Encodes a JSON value as unpadded base64url. */
22
+ export declare function encode(value: unknown): string;
23
+ /** Unpadded base64url SHA-256 of a string, as DPoP's `ath` uses. */
24
+ export declare function sha256(value: string): Promise<string>;
25
+ /** RFC 7638 thumbprint of a P-256 public JWK. */
26
+ export declare function thumbprint(jwk: JsonWebKey): Promise<string>;
27
+ /** A request URL without its query and fragment, as DPoP's `htu` names it. */
28
+ export declare function htu(url: string | URL): string;
29
+ /**
30
+ * Returns a lookup of an issuer's RS256 keys by key ID, from `<issuer>/oauth2/jwks`. The set is
31
+ * cached for five minutes, and an unknown key ID refetches it at most every 30 seconds. A failed
32
+ * fetch keeps the last set that loaded for up to one hour after it loaded, so a removed key stops
33
+ * verifying within an hour even while the issuer is unreachable.
34
+ */
35
+ export declare function keys(issuer: string, fetch: typeof globalThis.fetch): (kid: string) => Promise<CryptoKey | undefined>;
36
+ //# sourceMappingURL=Jwt.d.ts.map
@@ -0,0 +1,114 @@
1
+ import { Base64 } from 'ox';
2
+ /** ES256 in Web Crypto: the only DPoP algorithm the Tempo ID SDK signs with. */
3
+ export const es256 = {
4
+ key: { name: 'ECDSA', namedCurve: 'P-256' },
5
+ sign: { name: 'ECDSA', hash: 'SHA-256' },
6
+ };
7
+ /** Decodes a compact JWS without verifying it, or returns `undefined` if it is malformed. */
8
+ export function decode(token) {
9
+ if (token.length > 16_384)
10
+ return undefined;
11
+ const parts = token.split('.');
12
+ if (parts.length !== 3)
13
+ return undefined;
14
+ try {
15
+ const header = JSON.parse(Base64.toString(parts[0]));
16
+ const claims = JSON.parse(Base64.toString(parts[1]));
17
+ if (!isObject(header) || !isObject(claims))
18
+ return undefined;
19
+ return {
20
+ header,
21
+ claims,
22
+ signingInput: new TextEncoder().encode(`${parts[0]}.${parts[1]}`),
23
+ signature: new Uint8Array(Base64.toBytes(parts[2])),
24
+ };
25
+ }
26
+ catch {
27
+ return undefined;
28
+ }
29
+ }
30
+ /** Encodes a JSON value as unpadded base64url. */
31
+ export function encode(value) {
32
+ return Base64.fromString(JSON.stringify(value), { pad: false, url: true });
33
+ }
34
+ /** Unpadded base64url SHA-256 of a string, as DPoP's `ath` uses. */
35
+ export async function sha256(value) {
36
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value));
37
+ return Base64.fromBytes(new Uint8Array(digest), { pad: false, url: true });
38
+ }
39
+ /** RFC 7638 thumbprint of a P-256 public JWK. */
40
+ export function thumbprint(jwk) {
41
+ return sha256(JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y }));
42
+ }
43
+ /** A request URL without its query and fragment, as DPoP's `htu` names it. */
44
+ export function htu(url) {
45
+ const parsed = new URL(url);
46
+ return parsed.origin + parsed.pathname;
47
+ }
48
+ /**
49
+ * Returns a lookup of an issuer's RS256 keys by key ID, from `<issuer>/oauth2/jwks`. The set is
50
+ * cached for five minutes, and an unknown key ID refetches it at most every 30 seconds. A failed
51
+ * fetch keeps the last set that loaded for up to one hour after it loaded, so a removed key stops
52
+ * verifying within an hour even while the issuer is unreachable.
53
+ */
54
+ export function keys(issuer, fetch) {
55
+ // The last key set that loaded, which a failed refetch keeps.
56
+ let cached;
57
+ let pending;
58
+ let attempted = 0;
59
+ async function load() {
60
+ const response = await fetch(`${issuer}/oauth2/jwks`, { signal: AbortSignal.timeout(5_000) });
61
+ if (!response.ok)
62
+ throw new Error(`The key set request failed with ${response.status}.`);
63
+ const body = (await response.json());
64
+ const result = new Map();
65
+ for (const jwk of body.keys ?? []) {
66
+ const { e, kid, kty, n } = jwk;
67
+ if (kty !== 'RSA' || !kid || !e || !n)
68
+ continue;
69
+ const algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' };
70
+ result.set(kid, await crypto.subtle.importKey('jwk', { e, kty, n }, algorithm, false, ['verify']));
71
+ }
72
+ return result;
73
+ }
74
+ /** Returns the last loaded set while it is younger than one hour, else `undefined`. */
75
+ function stale() {
76
+ if (cached && Date.now() - cached.at < 3_600_000)
77
+ return cached.keys;
78
+ return undefined;
79
+ }
80
+ async function fresh(maxAge) {
81
+ if (cached && Date.now() - cached.at < maxAge)
82
+ return cached.keys;
83
+ // Within 30 seconds of the last attempt, the last loaded set serves, so unknown key IDs and an
84
+ // unreachable issuer cause at most one fetch each 30 seconds.
85
+ const last = stale();
86
+ if (last && !pending && Date.now() - attempted < 30_000)
87
+ return last;
88
+ if (!pending) {
89
+ attempted = Date.now();
90
+ pending = load()
91
+ .then((keys) => {
92
+ cached = { at: Date.now(), keys };
93
+ return keys;
94
+ })
95
+ .finally(() => {
96
+ pending = undefined;
97
+ });
98
+ }
99
+ try {
100
+ return await pending;
101
+ }
102
+ catch (error) {
103
+ const keys = stale();
104
+ if (keys)
105
+ return keys;
106
+ throw error;
107
+ }
108
+ }
109
+ return async (kid) => (await fresh(300_000)).get(kid) ?? (await fresh(30_000)).get(kid);
110
+ }
111
+ function isObject(value) {
112
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
113
+ }
114
+ //# sourceMappingURL=Jwt.js.map
@@ -0,0 +1,65 @@
1
+ import type * as Identity from '../../../../identity/Types.js';
2
+ import * as Store from '../../../../Store.js';
3
+ import type * as Types from '../Types.js';
4
+ /**
5
+ * Creates a Tempo ID verifier for one API.
6
+ *
7
+ * - `verifier` requires a valid Tempo ID access token from an allowed app.
8
+ * - `paymentCheck` also requires a `tempo` payment whose `source` is a Tempo Account the token
9
+ * grants to the app, so one user's token cannot pay with another user's wallet.
10
+ * It refuses an account that Tempo ID screened as anything but `clear`.
11
+ *
12
+ * Tokens verify offline against Tempo ID's keys. A DPoP-bound token also needs a proof of its key
13
+ * for the request, which `store` accepts once. The token uses `Authorization`, so create the
14
+ * server with `requiresAuth: true`.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * const tempoId = TempoId.Server.create({ clientId: 'app_…', store })
19
+ * const mppx = Mppx.create({ methods: [tempo({ … })], requiresAuth: true, secretKey })
20
+ *
21
+ * mppx.charge({ amount: '0.01', identity: { payment: tempoId.paymentCheck } })
22
+ * ```
23
+ *
24
+ * `allow` receives the user's ID, app, accounts with their compliance states, the email address
25
+ * from the ID token the client sends in `Tempo-Id-Token`, and, on the paid retry, the paying account:
26
+ *
27
+ * ```ts
28
+ * TempoId.Server.create({
29
+ * allow: (user) =>
30
+ * user.emailVerified === true &&
31
+ * user.email?.endsWith('@example.com') === true,
32
+ * clientId: 'app_…',
33
+ * })
34
+ * ```
35
+ */
36
+ export declare function create(config: create.Config): TempoId;
37
+ export declare namespace create {
38
+ type Config = {
39
+ /**
40
+ * Decides whether a verified user may call the API, such as by email or by the paying
41
+ * account's compliance state. On the paid retry it also receives the paying `account`.
42
+ */
43
+ readonly allow?: ((user: Types.Payer) => boolean | Promise<boolean>) | undefined;
44
+ /** The chain payments settle on. @default 4217 (Tempo mainnet) */
45
+ readonly chainId?: number | undefined;
46
+ /** The app or apps whose tokens the API accepts. @default any app */
47
+ readonly clientId?: string | readonly string[] | undefined;
48
+ /** Accepts each DPoP proof once. Without it, a proof can be replayed for five minutes. */
49
+ readonly store?: Store.AtomicStore | undefined;
50
+ /** The audience tokens must name. @default the issuer's origin */
51
+ readonly audience?: string | undefined;
52
+ /** Tempo ID's origin. @default 'https://id.tempo.xyz' */
53
+ readonly issuer?: string | undefined;
54
+ /** Fetch used for Tempo ID's keys. */
55
+ readonly fetch?: typeof globalThis.fetch | undefined;
56
+ };
57
+ }
58
+ /** A Tempo ID verifier from {@link create}. */
59
+ export type TempoId = {
60
+ /** A request-stage verifier: requires a Tempo ID access token before any 402. */
61
+ readonly verifier: Identity.Verifier<Types.Caller>;
62
+ /** A payment check: requires a Tempo ID access token, and that the payer is one of its accounts. */
63
+ readonly paymentCheck: Identity.PaymentCheck<Types.Payer>;
64
+ };
65
+ //# sourceMappingURL=index.d.ts.map