mppx 0.18.0 → 0.19.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 (132) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/dist/Currency.d.ts +59 -0
  3. package/dist/Currency.js +60 -0
  4. package/dist/Errors.d.ts +24 -4
  5. package/dist/Errors.js +28 -10
  6. package/dist/cli/cli.js +135 -135
  7. package/dist/cli/plugins/index.js +12 -12
  8. package/dist/cli/plugins/tempo.js +13 -1
  9. package/dist/client/internal/Fetch.d.ts +5 -0
  10. package/dist/client/internal/Fetch.js +7 -0
  11. package/dist/cloudflare/ChannelStore.d.ts +1 -2
  12. package/dist/cloudflare/ChannelStore.js +14 -20
  13. package/dist/cloudflare/Channels.d.ts +20 -2
  14. package/dist/cloudflare/Channels.js +47 -4
  15. package/dist/cloudflare/index.d.ts +1 -1
  16. package/dist/cloudflare/index.js +1 -1
  17. package/dist/discovery/Discovery.d.ts +116 -9
  18. package/dist/discovery/Discovery.js +169 -0
  19. package/dist/evm/server/Charge.js +2 -3
  20. package/dist/evm/server/Methods.d.ts +1 -1
  21. package/dist/evm/server/Methods.js +3 -2
  22. package/dist/extensions/identity/Types.d.ts +26 -0
  23. package/dist/extensions/identity/attestation/Token.d.ts +6 -4
  24. package/dist/extensions/identity/attestation/Token.js +11 -5
  25. package/dist/extensions/identity/email-otp/client/index.js +4 -4
  26. package/dist/extensions/identity/index.d.ts +6 -0
  27. package/dist/extensions/identity/index.js +6 -0
  28. package/dist/extensions/identity/internal/HttpMessageSignature.d.ts +2 -2
  29. package/dist/extensions/identity/internal/HttpMessageSignature.js +13 -10
  30. package/dist/extensions/identity/{web-bot-auth/internal → internal}/JwkThumbprint.js +1 -1
  31. package/dist/extensions/identity/internal/Signer.d.ts +20 -0
  32. package/dist/extensions/identity/internal/Signer.js +94 -0
  33. package/dist/extensions/identity/link/Constants.d.ts +102 -0
  34. package/dist/extensions/identity/link/Constants.js +16 -0
  35. package/dist/extensions/identity/link/client/index.d.ts +80 -0
  36. package/dist/extensions/identity/link/client/index.js +211 -0
  37. package/dist/extensions/identity/link/index.d.ts +12 -0
  38. package/dist/extensions/identity/link/index.js +12 -0
  39. package/dist/extensions/identity/link/server/index.d.ts +124 -0
  40. package/dist/extensions/identity/link/server/index.js +518 -0
  41. package/dist/extensions/identity/persona/Constants.d.ts +24 -0
  42. package/dist/extensions/identity/persona/Constants.js +24 -0
  43. package/dist/extensions/identity/persona/Did.d.ts +24 -0
  44. package/dist/extensions/identity/persona/Did.js +24 -0
  45. package/dist/extensions/identity/persona/Types.d.ts +21 -0
  46. package/dist/extensions/identity/persona/Types.js +2 -0
  47. package/dist/extensions/identity/persona/index.d.ts +10 -0
  48. package/dist/extensions/identity/persona/index.js +9 -0
  49. package/dist/extensions/identity/persona/server/index.d.ts +152 -0
  50. package/dist/extensions/identity/persona/server/index.js +263 -0
  51. package/dist/extensions/identity/tap/client/index.d.ts +6 -2
  52. package/dist/extensions/identity/tap/client/index.js +2 -0
  53. package/dist/extensions/identity/tempo/Constants.d.ts +14 -0
  54. package/dist/extensions/identity/tempo/Constants.js +14 -0
  55. package/dist/extensions/identity/tempo/Types.d.ts +31 -0
  56. package/dist/extensions/identity/tempo/Types.js +2 -0
  57. package/dist/extensions/identity/tempo/client/index.d.ts +34 -0
  58. package/dist/extensions/identity/tempo/client/index.js +60 -0
  59. package/dist/extensions/identity/tempo/index.d.ts +5 -0
  60. package/dist/extensions/identity/tempo/index.js +4 -0
  61. package/dist/extensions/identity/tempo/internal/Jwt.d.ts +36 -0
  62. package/dist/extensions/identity/tempo/internal/Jwt.js +114 -0
  63. package/dist/extensions/identity/tempo/server/index.d.ts +65 -0
  64. package/dist/extensions/identity/tempo/server/index.js +247 -0
  65. package/dist/extensions/identity/web-bot-auth/client/index.d.ts +6 -4
  66. package/dist/extensions/identity/web-bot-auth/client/index.js +7 -5
  67. package/dist/extensions/identity/web-bot-auth/server/index.js +1 -1
  68. package/dist/extensions/identity/world/Constants.d.ts +50 -0
  69. package/dist/extensions/identity/world/Constants.js +50 -0
  70. package/dist/extensions/identity/world/Types.d.ts +52 -0
  71. package/dist/extensions/identity/world/Types.js +2 -0
  72. package/dist/extensions/identity/world/client/index.d.ts +103 -0
  73. package/dist/extensions/identity/world/client/index.js +208 -0
  74. package/dist/extensions/identity/world/index.d.ts +6 -0
  75. package/dist/extensions/identity/world/index.js +5 -0
  76. package/dist/extensions/identity/world/internal/Idp.d.ts +50 -0
  77. package/dist/extensions/identity/world/internal/Idp.js +265 -0
  78. package/dist/extensions/identity/world/issuer/index.d.ts +120 -0
  79. package/dist/extensions/identity/world/issuer/index.js +520 -0
  80. package/dist/extensions/identity/world/server/index.d.ts +49 -0
  81. package/dist/extensions/identity/world/server/index.js +63 -0
  82. package/dist/identity/Headers.d.ts +6 -1
  83. package/dist/identity/Headers.js +11 -1
  84. package/dist/identity/Server.js +2 -0
  85. package/dist/identity/Types.d.ts +10 -0
  86. package/dist/index.d.ts +1 -0
  87. package/dist/index.js +1 -0
  88. package/dist/internal/version.d.ts +2 -2
  89. package/dist/internal/version.js +1 -1
  90. package/dist/proxy/internal/Headers.js +4 -4
  91. package/dist/server/Mppx.js +6 -2
  92. package/dist/stripe/server/internal/html.gen.js +1 -1
  93. package/dist/tempo/client/Charge.d.ts +11 -8
  94. package/dist/tempo/client/Charge.js +85 -18
  95. package/dist/tempo/index.d.ts +4 -0
  96. package/dist/tempo/index.js +4 -0
  97. package/dist/tempo/internal/auto-swap.d.ts +6 -5
  98. package/dist/tempo/internal/auto-swap.js +17 -2
  99. package/dist/tempo/internal/currencies.d.ts +5 -4
  100. package/dist/tempo/internal/currencies.js +13 -9
  101. package/dist/tempo/internal/defaults.d.ts +7 -0
  102. package/dist/tempo/internal/defaults.js +7 -0
  103. package/dist/tempo/internal/fee-payer.js +8 -2
  104. package/dist/tempo/internal/machine-token-charge.d.ts +52 -0
  105. package/dist/tempo/internal/machine-token-charge.js +82 -1
  106. package/dist/tempo/internal/zone.d.ts +27 -0
  107. package/dist/tempo/internal/zone.js +54 -7
  108. package/dist/tempo/server/Charge.js +59 -2
  109. package/dist/tempo/server/Methods.d.ts +1 -1
  110. package/dist/tempo/server/internal/html.gen.js +1 -1
  111. package/dist/tempo/server/internal/transport.d.ts +1 -1
  112. package/dist/tempo/server/internal/transport.js +9 -16
  113. package/dist/tempo/session/client/CredentialState.js +31 -0
  114. package/dist/tempo/session/client/Session.d.ts +12 -6
  115. package/dist/tempo/session/client/Session.js +64 -18
  116. package/dist/tempo/session/server/ChannelStore.d.ts +22 -1
  117. package/dist/tempo/session/server/ChannelStore.js +58 -8
  118. package/dist/tempo/session/server/CloseSupervisor.d.ts +5 -1
  119. package/dist/tempo/session/server/CloseSupervisor.js +110 -12
  120. package/dist/tempo/session/server/CredentialVerification.d.ts +2 -0
  121. package/dist/tempo/session/server/CredentialVerification.js +6 -32
  122. package/dist/tempo/session/server/Session.js +6 -3
  123. package/dist/tempo/session/server/Settlement.d.ts +7 -0
  124. package/dist/tempo/session/server/Settlement.js +36 -6
  125. package/dist/tempo/session/server/Sse.d.ts +2 -0
  126. package/dist/tempo/session/server/Sse.js +12 -12
  127. package/dist/tempo/subscription/KeyAuthorization.d.ts +1 -1
  128. package/dist/tempo/subscription/KeyAuthorization.js +1 -1
  129. package/dist/x402/Assets.d.ts +14 -5
  130. package/dist/x402/Assets.js +11 -16
  131. package/package.json +23 -3
  132. /package/dist/extensions/identity/{web-bot-auth/internal → internal}/JwkThumbprint.d.ts +0 -0
@@ -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
@@ -0,0 +1,247 @@
1
+ import { Address } from 'ox';
2
+ import { unwrapFetch } from '../../../../client/internal/Fetch.js';
3
+ import * as Store from '../../../../Store.js';
4
+ import { Constants } from '../Constants.js';
5
+ import * as Jwt from '../internal/Jwt.js';
6
+ /**
7
+ * Creates a Tempo ID verifier for one API.
8
+ *
9
+ * - `verifier` requires a valid Tempo ID access token from an allowed app.
10
+ * - `paymentCheck` also requires a `tempo` payment whose `source` is a Tempo Account the token
11
+ * grants to the app, so one user's token cannot pay with another user's wallet.
12
+ * It refuses an account that Tempo ID screened as anything but `clear`.
13
+ *
14
+ * Tokens verify offline against Tempo ID's keys. A DPoP-bound token also needs a proof of its key
15
+ * for the request, which `store` accepts once. The token uses `Authorization`, so create the
16
+ * server with `requiresAuth: true`.
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * const tempoId = TempoId.Server.create({ clientId: 'app_…', store })
21
+ * const mppx = Mppx.create({ methods: [tempo({ … })], requiresAuth: true, secretKey })
22
+ *
23
+ * mppx.charge({ amount: '0.01', identity: { payment: tempoId.paymentCheck } })
24
+ * ```
25
+ *
26
+ * `allow` receives the user's ID, app, accounts with their compliance states, the email address
27
+ * from the ID token the client sends in `Tempo-Id-Token`, and, on the paid retry, the paying account:
28
+ *
29
+ * ```ts
30
+ * TempoId.Server.create({
31
+ * allow: (user) =>
32
+ * user.emailVerified === true &&
33
+ * user.email?.endsWith('@example.com') === true,
34
+ * clientId: 'app_…',
35
+ * })
36
+ * ```
37
+ */
38
+ export function create(config) {
39
+ const { chainId = 4217, store } = config;
40
+ const issuer = new URL(config.issuer ?? Constants.issuer).origin;
41
+ const audience = config.audience ?? issuer;
42
+ // Absent, any app's token passes; `allow` can still decide by `clientId`.
43
+ const clientIds = config.clientId === undefined ? undefined : [config.clientId].flat();
44
+ const keys = Jwt.keys(issuer, unwrapFetch(config.fetch ?? globalThis.fetch));
45
+ // One verification per request, so a DPoP proof is spent once across both checks.
46
+ const verified = new WeakMap();
47
+ const headers = { 'WWW-Authenticate': 'DPoP algs="ES256", Bearer' };
48
+ const invalid = (reason) => ({ status: 'invalid', headers, reason });
49
+ async function check(request) {
50
+ // RFC 9110: one or more spaces separate the scheme and the token.
51
+ const [, scheme = '', token = ''] = /^(\S+) +(\S+) *$/.exec(request.headers.get('Authorization') ?? '') ?? [];
52
+ const dpop = scheme.toLowerCase() === 'dpop';
53
+ if (!token || (!dpop && scheme.toLowerCase() !== 'bearer'))
54
+ return { status: 'missing', headers, reason: 'Sign in with Tempo ID.' };
55
+ const jwt = Jwt.decode(token);
56
+ if (!jwt || jwt.header.typ !== 'at+jwt')
57
+ return invalid('The token is not a Tempo ID access token.');
58
+ const signed = await signedByTempoId(jwt);
59
+ if (signed === 'unavailable')
60
+ return { status: 'unavailable', reason: "Tempo ID's signing keys are unavailable." };
61
+ if (!signed)
62
+ return invalid('The access token signature is invalid.');
63
+ const { aud, client_id, cnf, exp, iss, nbf, sub } = jwt.claims;
64
+ const now = Math.floor(Date.now() / 1_000);
65
+ // A token that also names another API is that API's too, so only our audience (and Tempo ID's userinfo) passes.
66
+ const audiences = [aud].flat();
67
+ if (iss !== issuer || typeof sub !== 'string')
68
+ return invalid('The access token is not from Tempo ID.');
69
+ if (!audiences.includes(audience) ||
70
+ audiences.some((a) => a !== audience && a !== `${issuer}/oauth2/userinfo`))
71
+ return invalid('The access token is for another API.');
72
+ if (typeof exp !== 'number' || exp + Constants.clockTolerance <= now)
73
+ return invalid('The access token has expired.');
74
+ if (nbf !== undefined && (typeof nbf !== 'number' || nbf > now + Constants.clockTolerance))
75
+ return invalid('The access token is not valid yet.');
76
+ if (typeof client_id !== 'string' || (clientIds && !clientIds.includes(client_id)))
77
+ return { status: 'forbidden', reason: 'This app may not call this API.' };
78
+ // RFC 9449: a DPoP-bound token is useless without a proof from its key, and a Bearer token takes none.
79
+ if (dpop !== (cnf?.jkt !== undefined))
80
+ return invalid('The access token scheme does not match its binding.');
81
+ if (dpop) {
82
+ // A replay store failure rejects, so the proof cannot be spent once.
83
+ const reason = await checkProof(request, { jkt: cnf.jkt, now, token }).catch(() => null);
84
+ if (reason === null)
85
+ return { status: 'unavailable', reason: 'The DPoP replay store is unavailable.' };
86
+ if (reason)
87
+ return invalid(reason);
88
+ }
89
+ const accounts = [...(jwt.claims.access_keys ?? [])]
90
+ .filter((entry) => entry?.chain_id === chainId && isAddress(entry.account))
91
+ .map((entry) => entry.account)
92
+ .concat((jwt.claims.tempo_accounts ?? []).filter(isAddress))
93
+ .map((account) => Address.checksum(account));
94
+ const compliance = Object.fromEntries(Object.entries(jwt.claims.compliance ?? {}).map(([address, state]) => [
95
+ Address.checksum(address),
96
+ state,
97
+ ]));
98
+ const idToken = await checkIdToken(request, { clientId: client_id, now, sub });
99
+ if (typeof idToken === 'string')
100
+ return invalid(idToken);
101
+ if (idToken === null)
102
+ return { status: 'unavailable', reason: "Tempo ID's signing keys are unavailable." };
103
+ return {
104
+ status: 'valid',
105
+ value: {
106
+ accounts: [...new Set(accounts)],
107
+ clientId: client_id,
108
+ compliance,
109
+ ...idToken,
110
+ userId: sub,
111
+ },
112
+ };
113
+ }
114
+ /** Returns whether Tempo ID's RS256 keys signed a JWS, or `'unavailable'` when they cannot be read. */
115
+ async function signedByTempoId(jwt) {
116
+ if (jwt.header.alg !== 'RS256')
117
+ return false;
118
+ let key;
119
+ try {
120
+ key = await keys(String(jwt.header.kid));
121
+ }
122
+ catch {
123
+ return 'unavailable';
124
+ }
125
+ if (!key)
126
+ return false;
127
+ return crypto.subtle.verify('RSASSA-PKCS1-v1_5', key, jwt.signature, jwt.signingInput);
128
+ }
129
+ /**
130
+ * Reads the email of the request's ID token, which Tempo ID issues to the same app for the same
131
+ * user. Returns why it fails, `null` when the keys are unavailable, or no email without a token.
132
+ */
133
+ async function checkIdToken(request, options) {
134
+ const value = request.headers.get(Constants.idTokenHeader);
135
+ if (!value)
136
+ return {};
137
+ const jwt = Jwt.decode(value);
138
+ if (!jwt)
139
+ return 'The ID token is malformed.';
140
+ const signed = await signedByTempoId(jwt);
141
+ if (signed === 'unavailable')
142
+ return null;
143
+ if (!signed)
144
+ return 'The ID token signature is invalid.';
145
+ const { aud, email, email_verified, exp, iss, sub } = jwt.claims;
146
+ if (iss !== issuer || ![aud].flat().includes(options.clientId) || sub !== options.sub)
147
+ return 'The ID token is for another user or app.';
148
+ // An expired ID token names no email, so `allow` decides without it.
149
+ if (typeof exp !== 'number' || exp + Constants.clockTolerance <= options.now)
150
+ return {};
151
+ if (typeof email !== 'string')
152
+ return {};
153
+ return { email: email.toLowerCase(), emailVerified: email_verified === true };
154
+ }
155
+ /** Runs `allow` on a verified user or payer. */
156
+ async function allowed(result) {
157
+ if (result.status !== 'valid' || !config.allow || (await config.allow(result.value)))
158
+ return result;
159
+ return { status: 'forbidden', reason: 'This user may not call this API.' };
160
+ }
161
+ /** Returns why a request's DPoP proof fails, or `undefined`. */
162
+ async function checkProof(request, options) {
163
+ const proof = Jwt.decode(request.headers.get('DPoP') ?? '');
164
+ if (!proof || proof.header.alg !== 'ES256' || proof.header.typ !== 'dpop+jwt')
165
+ return 'The DPoP proof is malformed.';
166
+ const jwk = proof.header.jwk;
167
+ if (!jwk ||
168
+ typeof jwk !== 'object' ||
169
+ 'd' in jwk ||
170
+ (await Jwt.thumbprint(jwk)) !== options.jkt)
171
+ return 'The DPoP proof key does not bind the token.';
172
+ const valid = await crypto.subtle
173
+ .importKey('jwk', jwk, Jwt.es256.key, false, ['verify'])
174
+ .then((key) => crypto.subtle.verify(Jwt.es256.sign, key, proof.signature, proof.signingInput))
175
+ .catch(() => false);
176
+ if (!valid)
177
+ return 'The DPoP proof signature is invalid.';
178
+ const { ath, htm, htu, iat, jti } = proof.claims;
179
+ if (htm !== request.method || htu !== Jwt.htu(request.url))
180
+ return 'The DPoP proof is for another request.';
181
+ if (ath !== (await Jwt.sha256(options.token)))
182
+ return 'The DPoP proof is for another token.';
183
+ if (typeof iat !== 'number')
184
+ return 'The DPoP proof has expired.';
185
+ const expires = iat + Constants.proofMaxAge + Constants.clockTolerance;
186
+ if (iat > options.now + Constants.clockTolerance || expires < options.now)
187
+ return 'The DPoP proof has expired.';
188
+ if (typeof jti !== 'string' || !jti)
189
+ return 'The DPoP proof has no ID.';
190
+ if (store &&
191
+ !(await Store.tryClaim(store, `mppx:tempo-id:dpop:${await Jwt.sha256(`${options.jkt}:${jti}`)}`, expires * 1_000)))
192
+ return 'The DPoP proof was already used.';
193
+ return undefined;
194
+ }
195
+ function verify(request) {
196
+ let result = verified.get(request);
197
+ if (!result)
198
+ verified.set(request, (result = check(request)));
199
+ return result;
200
+ }
201
+ return {
202
+ verifier: { authorization: true, verify: async (request) => allowed(await verify(request)) },
203
+ paymentCheck: {
204
+ authorization: true,
205
+ requires: [{ type: Constants.type, issuer }],
206
+ async verify(parameters) {
207
+ const caller = await verify(parameters.request);
208
+ if (caller.status !== 'valid' || !parameters.credential)
209
+ return allowed(caller);
210
+ // Only the tempo method checks the source against the transaction's sender.
211
+ if (parameters.challenge.method !== 'tempo')
212
+ return { status: 'forbidden', reason: 'Pay with the tempo method.' };
213
+ // A Zone payment does not bind its source to the paying account.
214
+ if (parameters.credential.payload?.type === 'zone')
215
+ return { status: 'forbidden', reason: 'Pay from a Tempo account, not a Zone.' };
216
+ // The source is a did:pkh:eip155:<chainId>:<address>.
217
+ const parts = parameters.credential.source?.split(':') ?? [];
218
+ const [did, pkh, namespace, chain, address] = parts;
219
+ if (parts.length !== 5 ||
220
+ did !== 'did' ||
221
+ pkh !== 'pkh' ||
222
+ namespace !== 'eip155' ||
223
+ chain !== String(chainId) ||
224
+ !isAddress(address))
225
+ return {
226
+ status: 'invalid',
227
+ reason: `The payment must name its source account on chain ${chainId}.`,
228
+ };
229
+ const account = Address.checksum(address);
230
+ if (!caller.value.accounts.includes(account))
231
+ return {
232
+ status: 'forbidden',
233
+ reason: 'The paying account is not one this user granted to the app.',
234
+ };
235
+ const state = caller.value.compliance[account];
236
+ // Tempo ID screens the accounts in a registered app's realms; only a clear one pays.
237
+ if (state !== undefined && state !== 'clear')
238
+ return { status: 'forbidden', reason: 'The paying account is not cleared to pay.' };
239
+ return allowed({ status: 'valid', value: { ...caller.value, account } });
240
+ },
241
+ },
242
+ };
243
+ }
244
+ function isAddress(value) {
245
+ return typeof value === 'string' && /^0x[0-9a-fA-F]{40}$/.test(value);
246
+ }
247
+ //# 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
  /**
3
4
  * Creates a Web Bot Auth HTTPS-directory profile identity prover.
4
5
  *
@@ -11,10 +12,11 @@ import type * as Identity from '../../../../identity/Types.js';
11
12
  export declare function prover(config: prover.Config): Identity.Prover;
12
13
  export declare namespace prover {
13
14
  type Config = {
14
- /** Ed25519 or RSA-PSS SHA-512 private key registered for the bot. */
15
- key: CryptoKey;
16
- /** RFC 7638 JWK thumbprint for the registered public key. */
17
- keyId: string;
15
+ /**
16
+ * Ed25519 or RSA-PSS SHA-512 key pair, or a {@link SigningKey | Signer} for a remote key,
17
+ * registered for the bot. The `keyid` is the RFC 7638 thumbprint of its public key.
18
+ */
19
+ key: SigningKey;
18
20
  /** Origins that receive Web Bot Auth signatures, or `'*'` for any origin. */
19
21
  scope: Identity.Prover['scope'];
20
22
  /** Required HTTPS directory origin, sent with the default `directory` discovery type. */
@@ -1,7 +1,8 @@
1
1
  import { parseDictionary, serializeDictionary } from 'structured-headers';
2
2
  import * as HttpMessageSignature from '../../internal/HttpMessageSignature.js';
3
+ import * as JwkThumbprint from '../../internal/JwkThumbprint.js';
4
+ import * as Signer from '../../internal/Signer.js';
3
5
  import { Constants } from '../Constants.js';
4
- import * as JwkThumbprint from '../internal/JwkThumbprint.js';
5
6
  import * as SignatureAgent from '../internal/SignatureAgent.js';
6
7
  /**
7
8
  * Creates a Web Bot Auth HTTPS-directory profile identity prover.
@@ -17,15 +18,15 @@ export function prover(config) {
17
18
  const signatureAgentKey = config.signatureAgentKey ?? label;
18
19
  const expiresIn = config.expiresIn ?? Constants.defaultSignatureLifetime;
19
20
  const signatureAgent = SignatureAgent.directoryOrigin(config.signatureAgent);
20
- if (!JwkThumbprint.is(config.keyId))
21
- throw new TypeError('Web Bot Auth keyId must be an RFC 7638 SHA-256 JWK thumbprint.');
21
+ const { publicKey } = Signer.resolve(config.key);
22
+ let keyId;
22
23
  if (!signatureAgent)
23
24
  throw new TypeError('Signature-Agent must identify a valid HTTPS origin.');
24
25
  if (!Number.isInteger(expiresIn) || expiresIn <= 0)
25
26
  throw new RangeError('Web Bot Auth expiresIn must be a positive integer.');
26
27
  return {
27
28
  scope: config.scope,
28
- prove(request, context) {
29
+ async prove(request, context) {
29
30
  const headers = new Headers(request.headers);
30
31
  const signatureAgents = parseSignatureAgents(headers);
31
32
  if (signatureAgents.has(signatureAgentKey))
@@ -43,7 +44,8 @@ export function prover(config) {
43
44
  context,
44
45
  expiresIn,
45
46
  key: config.key,
46
- keyId: config.keyId,
47
+ // The keyid is the RFC 7638 thumbprint of the public key, so it can't disagree with it.
48
+ keyId: await (keyId ??= JwkThumbprint.fromKey(publicKey)),
47
49
  label,
48
50
  tag: Constants.tag,
49
51
  });
@@ -1,8 +1,8 @@
1
1
  import { isInnerList, parseDictionary, Token } from 'structured-headers';
2
2
  import * as HttpMessageSignature from '../../internal/HttpMessageSignature.js';
3
+ import * as JwkThumbprint from '../../internal/JwkThumbprint.js';
3
4
  import * as Verification from '../../internal/Verification.js';
4
5
  import { Constants } from '../Constants.js';
5
- import * as JwkThumbprint from '../internal/JwkThumbprint.js';
6
6
  import * as SignatureAgent from '../internal/SignatureAgent.js';
7
7
  /**
8
8
  * Creates a request-stage identity verifier for the Web Bot Auth HTTPS-directory profile.
@@ -0,0 +1,50 @@
1
+ /**
2
+ * World ID attestation values. Values every attestation shares are in `Attestation.Constants`.
3
+ *
4
+ * A World ID issuer (`World.Issuer`, shared or self-hosted) holds a confidential World IdP client. It runs World
5
+ * IdP's OpenID Connect device flow for the agent's human, verifies the ID token, and signs an
6
+ * `Identity-Attestation` of type `world-id` bound to the server's origin. Its API:
7
+ *
8
+ * - `POST {issuer}/world/device` with `{ "audience": "<origin>" }`: starts an attempt and answers
9
+ * `{ id, user_code, verification_uri, verification_uri_complete?, expires_in, interval }`.
10
+ * - `POST {issuer}/world/token` with `{ "id": "<attempt>" }`: answers `{ attestation, expires_at }`
11
+ * once approved, or 400 with `error` set to `authorization_pending`, `slow_down`,
12
+ * `access_denied` or `expired_token` (RFC 8628). 429 and 5xx mean try again later.
13
+ * - `GET {issuer}/.well-known/jwks.json`: its attestation keys.
14
+ */
15
+ export declare const Constants: {
16
+ /** World IdP issuer, which `World.Issuer` calls as a confidential client. */
17
+ readonly worldIssuer: 'https://auth.world.org';
18
+ /** World IdP sandbox issuer, for testing with sandbox client credentials. */
19
+ readonly worldSandboxIssuer: 'https://sandbox.auth.world.org';
20
+ /** Attestation type for a human verified with World ID. */
21
+ readonly type: 'world-id';
22
+ /** Issuer path that starts a device attempt. */
23
+ readonly devicePath: '/world/device';
24
+ /** Issuer path that polls a device attempt for its attestation. */
25
+ readonly tokenPath: '/world/token';
26
+ /** World IdP authentication classes, which an issuer puts in the attestation's `acr` claim. */
27
+ readonly acr: {
28
+ /** Orb-verified account. */
29
+ readonly orb: 'https://world.org/oidc/acr/orb';
30
+ /** Orb-verified account with a Face Auth check during this authentication. */
31
+ readonly orbFace: 'https://world.org/oidc/acr/orb-face';
32
+ /** Selfie Check-verified account. */
33
+ readonly selfie: 'https://world.org/oidc/acr/selfie';
34
+ /** Selfie Check-verified account with a Face Auth check during this authentication. */
35
+ readonly selfieFace: 'https://world.org/oidc/acr/selfie-face';
36
+ };
37
+ /** Polling interval, in seconds, when the issuer sets none (RFC 8628). */
38
+ readonly interval: 5;
39
+ /** Seconds `slow_down` adds to the polling interval (RFC 8628). */
40
+ readonly slowDown: 5;
41
+ /** Seconds a client waits after a failed or declined attempt before starting another for the same origin. */
42
+ readonly retryDelay: 60;
43
+ /** Default lifetime, in seconds, of an attestation `World.Issuer` signs. */
44
+ readonly attestationTtl: 3600;
45
+ /** Allowed clock skew, in seconds, for ID token times. */
46
+ readonly clockTolerance: 60;
47
+ /** Milliseconds a client waits for each issuer call, and an issuer for each World IdP call. */
48
+ readonly requestTimeout: 10000;
49
+ };
50
+ //# sourceMappingURL=Constants.d.ts.map
@@ -0,0 +1,50 @@
1
+ /**
2
+ * World ID attestation values. Values every attestation shares are in `Attestation.Constants`.
3
+ *
4
+ * A World ID issuer (`World.Issuer`, shared or self-hosted) holds a confidential World IdP client. It runs World
5
+ * IdP's OpenID Connect device flow for the agent's human, verifies the ID token, and signs an
6
+ * `Identity-Attestation` of type `world-id` bound to the server's origin. Its API:
7
+ *
8
+ * - `POST {issuer}/world/device` with `{ "audience": "<origin>" }`: starts an attempt and answers
9
+ * `{ id, user_code, verification_uri, verification_uri_complete?, expires_in, interval }`.
10
+ * - `POST {issuer}/world/token` with `{ "id": "<attempt>" }`: answers `{ attestation, expires_at }`
11
+ * once approved, or 400 with `error` set to `authorization_pending`, `slow_down`,
12
+ * `access_denied` or `expired_token` (RFC 8628). 429 and 5xx mean try again later.
13
+ * - `GET {issuer}/.well-known/jwks.json`: its attestation keys.
14
+ */
15
+ export const Constants = {
16
+ /** World IdP issuer, which `World.Issuer` calls as a confidential client. */
17
+ worldIssuer: 'https://auth.world.org',
18
+ /** World IdP sandbox issuer, for testing with sandbox client credentials. */
19
+ worldSandboxIssuer: 'https://sandbox.auth.world.org',
20
+ /** Attestation type for a human verified with World ID. */
21
+ type: 'world-id',
22
+ /** Issuer path that starts a device attempt. */
23
+ devicePath: '/world/device',
24
+ /** Issuer path that polls a device attempt for its attestation. */
25
+ tokenPath: '/world/token',
26
+ /** World IdP authentication classes, which an issuer puts in the attestation's `acr` claim. */
27
+ acr: {
28
+ /** Orb-verified account. */
29
+ orb: 'https://world.org/oidc/acr/orb',
30
+ /** Orb-verified account with a Face Auth check during this authentication. */
31
+ orbFace: 'https://world.org/oidc/acr/orb-face',
32
+ /** Selfie Check-verified account. */
33
+ selfie: 'https://world.org/oidc/acr/selfie',
34
+ /** Selfie Check-verified account with a Face Auth check during this authentication. */
35
+ selfieFace: 'https://world.org/oidc/acr/selfie-face',
36
+ },
37
+ /** Polling interval, in seconds, when the issuer sets none (RFC 8628). */
38
+ interval: 5,
39
+ /** Seconds `slow_down` adds to the polling interval (RFC 8628). */
40
+ slowDown: 5,
41
+ /** Seconds a client waits after a failed or declined attempt before starting another for the same origin. */
42
+ retryDelay: 60,
43
+ /** Default lifetime, in seconds, of an attestation `World.Issuer` signs. */
44
+ attestationTtl: 3_600,
45
+ /** Allowed clock skew, in seconds, for ID token times. */
46
+ clockTolerance: 60,
47
+ /** Milliseconds a client waits for each issuer call, and an issuer for each World IdP call. */
48
+ requestTimeout: 10_000,
49
+ };
50
+ //# sourceMappingURL=Constants.js.map
@@ -0,0 +1,52 @@
1
+ /** A human verified with World ID, as a World ID issuer attests. */
2
+ export type VerifiedHuman = {
3
+ /** Issuer URL. */
4
+ readonly issuer: string;
5
+ /**
6
+ * The issuer's identifier for the human. It is pseudonymous; whether it differs between
7
+ * servers depends on the issuer. Store it together with `issuer`.
8
+ */
9
+ readonly subject: string;
10
+ /** World IdP authentication class, such as `https://world.org/oidc/acr/orb`, if the issuer set one. */
11
+ readonly acr?: string | undefined;
12
+ /** When the attestation expires. */
13
+ readonly expiresAt: Date;
14
+ /** Attestation identifier (`jti`), if the issuer set one. */
15
+ readonly id?: string | undefined;
16
+ };
17
+ /** A device attempt the issuer started: what to show the human. */
18
+ export type Device = {
19
+ /** Attempt identifier to poll with. */
20
+ readonly id: string;
21
+ /** Code the human confirms on the approval page. */
22
+ readonly userCode: string;
23
+ /** Approval page. */
24
+ readonly verificationUri: string;
25
+ /** Approval page with the code filled in, if the issuer provides one. */
26
+ readonly verificationUriComplete?: string | undefined;
27
+ /** When the attempt expires. */
28
+ readonly expiresAt: Date;
29
+ /** Seconds to wait between polls. */
30
+ readonly interval: number;
31
+ };
32
+ /** One poll of a device attempt. */
33
+ export type Poll =
34
+ /** Approved: the attestation for the audience the attempt was started for. */
35
+ {
36
+ readonly status: 'approved';
37
+ readonly attestation: string;
38
+ readonly expiresAt: Date;
39
+ }
40
+ /** Not approved yet. */
41
+ | {
42
+ readonly status: 'pending';
43
+ }
44
+ /** Polling too fast: add `Constants.slowDown` seconds to the interval. */
45
+ | {
46
+ readonly status: 'slow_down';
47
+ }
48
+ /** The issuer could not answer (429, 5xx, timeout or network error): poll again later. */
49
+ | {
50
+ readonly status: 'unavailable';
51
+ };
52
+ //# sourceMappingURL=Types.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=Types.js.map