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.
- package/CHANGELOG.md +39 -0
- package/dist/Currency.d.ts +59 -0
- package/dist/Currency.js +60 -0
- package/dist/Errors.d.ts +24 -4
- package/dist/Errors.js +28 -10
- package/dist/cli/cli.js +135 -135
- package/dist/cli/plugins/index.js +12 -12
- package/dist/cli/plugins/tempo.js +13 -1
- package/dist/client/internal/Fetch.d.ts +5 -0
- package/dist/client/internal/Fetch.js +7 -0
- package/dist/cloudflare/ChannelStore.d.ts +1 -2
- package/dist/cloudflare/ChannelStore.js +14 -20
- package/dist/cloudflare/Channels.d.ts +20 -2
- package/dist/cloudflare/Channels.js +47 -4
- package/dist/cloudflare/index.d.ts +1 -1
- package/dist/cloudflare/index.js +1 -1
- package/dist/discovery/Discovery.d.ts +116 -9
- package/dist/discovery/Discovery.js +169 -0
- package/dist/evm/server/Charge.js +2 -3
- package/dist/evm/server/Methods.d.ts +1 -1
- package/dist/evm/server/Methods.js +3 -2
- package/dist/extensions/identity/Types.d.ts +26 -0
- package/dist/extensions/identity/attestation/Token.d.ts +6 -4
- package/dist/extensions/identity/attestation/Token.js +11 -5
- package/dist/extensions/identity/email-otp/client/index.js +4 -4
- package/dist/extensions/identity/index.d.ts +6 -0
- package/dist/extensions/identity/index.js +6 -0
- package/dist/extensions/identity/internal/HttpMessageSignature.d.ts +2 -2
- package/dist/extensions/identity/internal/HttpMessageSignature.js +13 -10
- package/dist/extensions/identity/{web-bot-auth/internal → internal}/JwkThumbprint.js +1 -1
- package/dist/extensions/identity/internal/Signer.d.ts +20 -0
- package/dist/extensions/identity/internal/Signer.js +94 -0
- package/dist/extensions/identity/link/Constants.d.ts +102 -0
- package/dist/extensions/identity/link/Constants.js +16 -0
- package/dist/extensions/identity/link/client/index.d.ts +80 -0
- package/dist/extensions/identity/link/client/index.js +211 -0
- package/dist/extensions/identity/link/index.d.ts +12 -0
- package/dist/extensions/identity/link/index.js +12 -0
- package/dist/extensions/identity/link/server/index.d.ts +124 -0
- package/dist/extensions/identity/link/server/index.js +518 -0
- package/dist/extensions/identity/persona/Constants.d.ts +24 -0
- package/dist/extensions/identity/persona/Constants.js +24 -0
- package/dist/extensions/identity/persona/Did.d.ts +24 -0
- package/dist/extensions/identity/persona/Did.js +24 -0
- package/dist/extensions/identity/persona/Types.d.ts +21 -0
- package/dist/extensions/identity/persona/Types.js +2 -0
- package/dist/extensions/identity/persona/index.d.ts +10 -0
- package/dist/extensions/identity/persona/index.js +9 -0
- package/dist/extensions/identity/persona/server/index.d.ts +152 -0
- package/dist/extensions/identity/persona/server/index.js +263 -0
- package/dist/extensions/identity/tap/client/index.d.ts +6 -2
- package/dist/extensions/identity/tap/client/index.js +2 -0
- package/dist/extensions/identity/tempo/Constants.d.ts +14 -0
- package/dist/extensions/identity/tempo/Constants.js +14 -0
- package/dist/extensions/identity/tempo/Types.d.ts +31 -0
- package/dist/extensions/identity/tempo/Types.js +2 -0
- package/dist/extensions/identity/tempo/client/index.d.ts +34 -0
- package/dist/extensions/identity/tempo/client/index.js +60 -0
- package/dist/extensions/identity/tempo/index.d.ts +5 -0
- package/dist/extensions/identity/tempo/index.js +4 -0
- package/dist/extensions/identity/tempo/internal/Jwt.d.ts +36 -0
- package/dist/extensions/identity/tempo/internal/Jwt.js +114 -0
- package/dist/extensions/identity/tempo/server/index.d.ts +65 -0
- package/dist/extensions/identity/tempo/server/index.js +247 -0
- package/dist/extensions/identity/web-bot-auth/client/index.d.ts +6 -4
- package/dist/extensions/identity/web-bot-auth/client/index.js +7 -5
- package/dist/extensions/identity/web-bot-auth/server/index.js +1 -1
- package/dist/extensions/identity/world/Constants.d.ts +50 -0
- package/dist/extensions/identity/world/Constants.js +50 -0
- package/dist/extensions/identity/world/Types.d.ts +52 -0
- package/dist/extensions/identity/world/Types.js +2 -0
- package/dist/extensions/identity/world/client/index.d.ts +103 -0
- package/dist/extensions/identity/world/client/index.js +208 -0
- package/dist/extensions/identity/world/index.d.ts +6 -0
- package/dist/extensions/identity/world/index.js +5 -0
- package/dist/extensions/identity/world/internal/Idp.d.ts +50 -0
- package/dist/extensions/identity/world/internal/Idp.js +265 -0
- package/dist/extensions/identity/world/issuer/index.d.ts +120 -0
- package/dist/extensions/identity/world/issuer/index.js +520 -0
- package/dist/extensions/identity/world/server/index.d.ts +49 -0
- package/dist/extensions/identity/world/server/index.js +63 -0
- package/dist/identity/Headers.d.ts +6 -1
- package/dist/identity/Headers.js +11 -1
- package/dist/identity/Server.js +2 -0
- package/dist/identity/Types.d.ts +10 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/internal/version.d.ts +2 -2
- package/dist/internal/version.js +1 -1
- package/dist/proxy/internal/Headers.js +4 -4
- package/dist/server/Mppx.js +6 -2
- package/dist/stripe/server/internal/html.gen.js +1 -1
- package/dist/tempo/client/Charge.d.ts +11 -8
- package/dist/tempo/client/Charge.js +85 -18
- package/dist/tempo/index.d.ts +4 -0
- package/dist/tempo/index.js +4 -0
- package/dist/tempo/internal/auto-swap.d.ts +6 -5
- package/dist/tempo/internal/auto-swap.js +17 -2
- package/dist/tempo/internal/currencies.d.ts +5 -4
- package/dist/tempo/internal/currencies.js +13 -9
- package/dist/tempo/internal/defaults.d.ts +7 -0
- package/dist/tempo/internal/defaults.js +7 -0
- package/dist/tempo/internal/fee-payer.js +8 -2
- package/dist/tempo/internal/machine-token-charge.d.ts +52 -0
- package/dist/tempo/internal/machine-token-charge.js +82 -1
- package/dist/tempo/internal/zone.d.ts +27 -0
- package/dist/tempo/internal/zone.js +54 -7
- package/dist/tempo/server/Charge.js +59 -2
- package/dist/tempo/server/Methods.d.ts +1 -1
- package/dist/tempo/server/internal/html.gen.js +1 -1
- package/dist/tempo/server/internal/transport.d.ts +1 -1
- package/dist/tempo/server/internal/transport.js +9 -16
- package/dist/tempo/session/client/CredentialState.js +31 -0
- package/dist/tempo/session/client/Session.d.ts +12 -6
- package/dist/tempo/session/client/Session.js +64 -18
- package/dist/tempo/session/server/ChannelStore.d.ts +22 -1
- package/dist/tempo/session/server/ChannelStore.js +58 -8
- package/dist/tempo/session/server/CloseSupervisor.d.ts +5 -1
- package/dist/tempo/session/server/CloseSupervisor.js +110 -12
- package/dist/tempo/session/server/CredentialVerification.d.ts +2 -0
- package/dist/tempo/session/server/CredentialVerification.js +6 -32
- package/dist/tempo/session/server/Session.js +6 -3
- package/dist/tempo/session/server/Settlement.d.ts +7 -0
- package/dist/tempo/session/server/Settlement.js +36 -6
- package/dist/tempo/session/server/Sse.d.ts +2 -0
- package/dist/tempo/session/server/Sse.js +12 -12
- package/dist/tempo/subscription/KeyAuthorization.d.ts +1 -1
- package/dist/tempo/subscription/KeyAuthorization.js +1 -1
- package/dist/x402/Assets.d.ts +14 -5
- package/dist/x402/Assets.js +11 -16
- package/package.json +23 -3
- /package/dist/extensions/identity/{web-bot-auth/internal → internal}/JwkThumbprint.d.ts +0 -0
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import type { MaybePromise } from '../../../../internal/types.js';
|
|
2
|
+
import type * as Store from '../../../../Store.js';
|
|
3
|
+
import type * as AttestationTypes from '../../attestation/Types.js';
|
|
4
|
+
import type { SigningKey } from '../../Types.js';
|
|
5
|
+
/**
|
|
6
|
+
* Creates a World ID issuer: a World IdP confidential client that runs the device flow for agents'
|
|
7
|
+
* humans and signs `Identity-Attestation` tokens of type `world-id` for the servers they call.
|
|
8
|
+
*
|
|
9
|
+
* Run it as a shared service that many servers name as their `issuer`, or inside a server's own
|
|
10
|
+
* app (self-hosted), where `World.Server.verifier` resolves its key in process through
|
|
11
|
+
* `keyResolver`. Either way `handle` answers its three routes, relative to `url`:
|
|
12
|
+
*
|
|
13
|
+
* - `POST /world/device` starts an attempt for an audience (`Constants.devicePath`).
|
|
14
|
+
* - `POST /world/token` polls it; the poll interval is enforced per attempt in `store`.
|
|
15
|
+
* - `GET /.well-known/jwks.json` publishes the attestation key.
|
|
16
|
+
*
|
|
17
|
+
* Records expire on their own: each attempt start deletes attempts and limit windows that ended
|
|
18
|
+
* over a minute ago, so abandoned ones don't accumulate in `store`.
|
|
19
|
+
*
|
|
20
|
+
* Device codes, ID tokens and World's subject never leave the issuer. An approval's ID token is
|
|
21
|
+
* kept with the attempt until it verifies, so a World IdP key outage answers 503 and the next poll
|
|
22
|
+
* retries verification instead of asking the human again.
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* ```ts
|
|
26
|
+
* const issuer = World.Issuer.create({
|
|
27
|
+
* authorize: (request) => isSignedIn(request),
|
|
28
|
+
* clientId: process.env.WORLD_CLIENT_ID,
|
|
29
|
+
* clientSecret: process.env.WORLD_CLIENT_SECRET,
|
|
30
|
+
* secretKey: process.env.MPP_SECRET_KEY,
|
|
31
|
+
* signingKey,
|
|
32
|
+
* store,
|
|
33
|
+
* url: 'https://api.example',
|
|
34
|
+
* })
|
|
35
|
+
* // In the app's fetch handler, before its routes:
|
|
36
|
+
* const answered = await issuer.handle(request)
|
|
37
|
+
* if (answered) return answered
|
|
38
|
+
* ```
|
|
39
|
+
*/
|
|
40
|
+
export declare function create(config: create.Config): Issuer;
|
|
41
|
+
export declare namespace create {
|
|
42
|
+
type Config = {
|
|
43
|
+
/** This issuer's URL, the attestations' `iss`, such as `https://api.example` when self-hosted. */
|
|
44
|
+
readonly url: string;
|
|
45
|
+
/** Client ID registered at World IdP's portal. */
|
|
46
|
+
readonly clientId: string;
|
|
47
|
+
/** Client secret registered at World IdP's portal. Keep it on the server. */
|
|
48
|
+
readonly clientSecret: string;
|
|
49
|
+
/** How the client authenticates to World IdP, as registered. @default 'client_secret_basic' */
|
|
50
|
+
readonly clientAuthentication?: 'client_secret_basic' | 'client_secret_post' | undefined;
|
|
51
|
+
/** World IdP issuer. @default Constants.worldIssuer */
|
|
52
|
+
readonly worldIssuer?: string | undefined;
|
|
53
|
+
/**
|
|
54
|
+
* Accepted World IdP authentication classes, requested as essential and checked in the ID token.
|
|
55
|
+
* @default [Constants.acr.orb, Constants.acr.orbFace]
|
|
56
|
+
*/
|
|
57
|
+
readonly acr?: readonly string[] | undefined;
|
|
58
|
+
/**
|
|
59
|
+
* Ed25519 key pair, or a {@link SigningKey | Signer} for a key in a KMS or HSM, that signs
|
|
60
|
+
* attestations. Its public key is published at the JWKS route.
|
|
61
|
+
*/
|
|
62
|
+
readonly signingKey: SigningKey;
|
|
63
|
+
/**
|
|
64
|
+
* Holds attempts, their poll schedules and the start limit. Share one atomic store across
|
|
65
|
+
* instances, such as `Store.redis()` or `Store.postgres()`.
|
|
66
|
+
*/
|
|
67
|
+
readonly store: Store.AtomicStore;
|
|
68
|
+
/**
|
|
69
|
+
* Secret that derives pairwise subjects, such as `MPP_SECRET_KEY`. Required unless
|
|
70
|
+
* `subject` is `'world'`; changing it changes every subject.
|
|
71
|
+
*/
|
|
72
|
+
readonly secretKey?: string | undefined;
|
|
73
|
+
/**
|
|
74
|
+
* The attested `sub`: `'pairwise'` derives one per audience from World's subject, so servers
|
|
75
|
+
* can't link a human across them; `'world'` passes World's subject through.
|
|
76
|
+
* @default 'pairwise'
|
|
77
|
+
*/
|
|
78
|
+
readonly subject?: 'pairwise' | 'world' | undefined;
|
|
79
|
+
/**
|
|
80
|
+
* Audiences (server origins) this issuer attests for. Self-hosted, pass the app's own origin.
|
|
81
|
+
* Defaults to any https origin.
|
|
82
|
+
*/
|
|
83
|
+
readonly audiences?: readonly string[] | ((audience: string, request: Request) => MaybePromise<boolean>) | undefined;
|
|
84
|
+
/**
|
|
85
|
+
* Decides who may start an attempt, such as the app's signed-in users when self-hosted.
|
|
86
|
+
* Defaults to anyone: then set `limit`.
|
|
87
|
+
*/
|
|
88
|
+
readonly authorize?: ((request: Request) => MaybePromise<boolean>) | undefined;
|
|
89
|
+
/**
|
|
90
|
+
* Limits attempt starts per caller: World IdP limits starts per client, so one caller could
|
|
91
|
+
* otherwise use up every caller's budget.
|
|
92
|
+
*/
|
|
93
|
+
readonly limit?: {
|
|
94
|
+
/** Identifies the caller, such as an API key or a trusted client IP; `undefined` skips the limit. */
|
|
95
|
+
readonly key: (request: Request) => MaybePromise<string | undefined>;
|
|
96
|
+
/** Starts allowed per caller per window. */
|
|
97
|
+
readonly max: number;
|
|
98
|
+
/** Window length in seconds. */
|
|
99
|
+
readonly window: number;
|
|
100
|
+
} | undefined;
|
|
101
|
+
/** Attestation lifetime in seconds. @default 3600 */
|
|
102
|
+
readonly ttl?: number | undefined;
|
|
103
|
+
/** Fetch used to call World IdP. @default globalThis.fetch */
|
|
104
|
+
readonly fetch?: typeof globalThis.fetch | undefined;
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
/** A World ID issuer. */
|
|
108
|
+
export type Issuer = {
|
|
109
|
+
/** The issuer URL, which servers name as their `issuer` and clients list in `issuers`. */
|
|
110
|
+
readonly url: string;
|
|
111
|
+
/** Answers the issuer's routes, or returns `undefined` for any other request. */
|
|
112
|
+
handle(request: Request): Promise<Response | undefined>;
|
|
113
|
+
/** Resolves the attestation key in process, for a self-hosted `World.Server.verifier`. */
|
|
114
|
+
keyResolver: AttestationTypes.KeyResolver;
|
|
115
|
+
/** The JSON Web Key Set the JWKS route serves. */
|
|
116
|
+
jwks(): Promise<{
|
|
117
|
+
keys: readonly Record<string, string>[];
|
|
118
|
+
}>;
|
|
119
|
+
};
|
|
120
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,520 @@
|
|
|
1
|
+
import { Base64 } from 'ox';
|
|
2
|
+
import { Constants as AttestationConstants } from '../../attestation/Constants.js';
|
|
3
|
+
import { sign, isIssuer } from '../../attestation/Token.js';
|
|
4
|
+
import * as Signer from '../../internal/Signer.js';
|
|
5
|
+
import { Constants } from '../Constants.js';
|
|
6
|
+
import * as Idp from '../internal/Idp.js';
|
|
7
|
+
/**
|
|
8
|
+
* Creates a World ID issuer: a World IdP confidential client that runs the device flow for agents'
|
|
9
|
+
* humans and signs `Identity-Attestation` tokens of type `world-id` for the servers they call.
|
|
10
|
+
*
|
|
11
|
+
* Run it as a shared service that many servers name as their `issuer`, or inside a server's own
|
|
12
|
+
* app (self-hosted), where `World.Server.verifier` resolves its key in process through
|
|
13
|
+
* `keyResolver`. Either way `handle` answers its three routes, relative to `url`:
|
|
14
|
+
*
|
|
15
|
+
* - `POST /world/device` starts an attempt for an audience (`Constants.devicePath`).
|
|
16
|
+
* - `POST /world/token` polls it; the poll interval is enforced per attempt in `store`.
|
|
17
|
+
* - `GET /.well-known/jwks.json` publishes the attestation key.
|
|
18
|
+
*
|
|
19
|
+
* Records expire on their own: each attempt start deletes attempts and limit windows that ended
|
|
20
|
+
* over a minute ago, so abandoned ones don't accumulate in `store`.
|
|
21
|
+
*
|
|
22
|
+
* Device codes, ID tokens and World's subject never leave the issuer. An approval's ID token is
|
|
23
|
+
* kept with the attempt until it verifies, so a World IdP key outage answers 503 and the next poll
|
|
24
|
+
* retries verification instead of asking the human again.
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* ```ts
|
|
28
|
+
* const issuer = World.Issuer.create({
|
|
29
|
+
* authorize: (request) => isSignedIn(request),
|
|
30
|
+
* clientId: process.env.WORLD_CLIENT_ID,
|
|
31
|
+
* clientSecret: process.env.WORLD_CLIENT_SECRET,
|
|
32
|
+
* secretKey: process.env.MPP_SECRET_KEY,
|
|
33
|
+
* signingKey,
|
|
34
|
+
* store,
|
|
35
|
+
* url: 'https://api.example',
|
|
36
|
+
* })
|
|
37
|
+
* // In the app's fetch handler, before its routes:
|
|
38
|
+
* const answered = await issuer.handle(request)
|
|
39
|
+
* if (answered) return answered
|
|
40
|
+
* ```
|
|
41
|
+
*/
|
|
42
|
+
export function create(config) {
|
|
43
|
+
const url = config.url.replace(/\/+$/, '');
|
|
44
|
+
if (!isIssuer(url))
|
|
45
|
+
throw new TypeError('World ID issuer url must be an https URL.');
|
|
46
|
+
if (!config.clientId || !config.clientSecret)
|
|
47
|
+
throw new TypeError('World ID issuer requires clientId and clientSecret.');
|
|
48
|
+
const subject = config.subject ?? 'pairwise';
|
|
49
|
+
if (subject === 'pairwise' && !config.secretKey)
|
|
50
|
+
throw new TypeError('World ID issuer requires secretKey for pairwise subjects.');
|
|
51
|
+
const acr = config.acr ?? [Constants.acr.orb, Constants.acr.orbFace];
|
|
52
|
+
if (acr.length === 0)
|
|
53
|
+
throw new TypeError('World ID issuer requires at least one acr.');
|
|
54
|
+
const ttl = config.ttl ?? Constants.attestationTtl;
|
|
55
|
+
if (!Number.isSafeInteger(ttl) || ttl <= 0)
|
|
56
|
+
throw new TypeError('World ID issuer ttl must be a positive integer of seconds.');
|
|
57
|
+
const { limit, store } = config;
|
|
58
|
+
const base = new URL(url).pathname.replace(/\/+$/, '');
|
|
59
|
+
// Keys are scoped to this issuer, so issuers sharing a store never redeem each other's attempts.
|
|
60
|
+
const prefix = `mppx:world-id:${url}:`;
|
|
61
|
+
const idp = Idp.create({
|
|
62
|
+
acr,
|
|
63
|
+
clientAuthentication: config.clientAuthentication,
|
|
64
|
+
clientId: config.clientId,
|
|
65
|
+
clientSecret: config.clientSecret,
|
|
66
|
+
fetch: config.fetch,
|
|
67
|
+
issuer: (config.worldIssuer ?? Constants.worldIssuer).replace(/\/+$/, ''),
|
|
68
|
+
});
|
|
69
|
+
Signer.resolve(config.signingKey, ['ed25519']);
|
|
70
|
+
const key = (async () => {
|
|
71
|
+
const jwk = await crypto.subtle.exportKey('jwk', config.signingKey.publicKey);
|
|
72
|
+
if (jwk.kty !== 'OKP' || jwk.crv !== 'Ed25519' || !jwk.x)
|
|
73
|
+
throw new TypeError('World ID issuer signingKey must be an Ed25519 key pair.');
|
|
74
|
+
// RFC 7638 thumbprint, as `Attestation.sign` expects.
|
|
75
|
+
const canonical = JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x });
|
|
76
|
+
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(canonical));
|
|
77
|
+
const keyId = Base64.fromBytes(new Uint8Array(digest), { pad: false, url: true });
|
|
78
|
+
return {
|
|
79
|
+
jwk: { alg: 'EdDSA', crv: jwk.crv, kid: keyId, kty: jwk.kty, use: 'sig', x: jwk.x },
|
|
80
|
+
keyId,
|
|
81
|
+
};
|
|
82
|
+
})();
|
|
83
|
+
const hmac = config.secretKey
|
|
84
|
+
? crypto.subtle.importKey('raw', new TextEncoder().encode(config.secretKey), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])
|
|
85
|
+
: undefined;
|
|
86
|
+
/** Indexes a record under the minute it expires, so {@link sweep} can delete it. */
|
|
87
|
+
async function track(key, expires) {
|
|
88
|
+
const minute = Math.ceil(expires / bucketMs);
|
|
89
|
+
// The minute is registered before its shard gets the key, so a failure between the two writes
|
|
90
|
+
// leaves at most an empty minute, which a sweep drops, never a key no sweep can find. Once the
|
|
91
|
+
// minute is listed this writes nothing.
|
|
92
|
+
await store.update(`${prefix}expiry:minutes`, (current) => {
|
|
93
|
+
const minutes = current ?? [];
|
|
94
|
+
if (minutes.includes(minute))
|
|
95
|
+
return { op: 'noop', result: undefined };
|
|
96
|
+
return { op: 'set', value: [...minutes, minute].sort((a, b) => a - b), result: undefined };
|
|
97
|
+
});
|
|
98
|
+
// Sharded, so concurrent starts rarely contend on one index key.
|
|
99
|
+
await store.update(`${prefix}expiry:${minute}:${shardOf(key)}`, (current) => {
|
|
100
|
+
const keys = current ?? [];
|
|
101
|
+
if (keys.includes(key))
|
|
102
|
+
return { op: 'noop', result: undefined };
|
|
103
|
+
return { op: 'set', value: [...keys, key], result: undefined };
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Deletes up to `sweepLimit` records whose minute has passed: stores enforce no expiry, so
|
|
108
|
+
* abandoned attempts and limit windows would otherwise stay forever. Each call does a bounded
|
|
109
|
+
* amount of work, oldest minute first. A record renewed since it was indexed (a limit window that
|
|
110
|
+
* started again) is kept.
|
|
111
|
+
*/
|
|
112
|
+
async function sweep() {
|
|
113
|
+
const now = Math.floor(Date.now() / bucketMs);
|
|
114
|
+
const minutes = (await store.get(`${prefix}expiry:minutes`)) ?? [];
|
|
115
|
+
const minute = minutes.find((value) => value < now);
|
|
116
|
+
if (minute === undefined)
|
|
117
|
+
return;
|
|
118
|
+
const time = Date.now();
|
|
119
|
+
let budget = sweepLimit;
|
|
120
|
+
let empty = true;
|
|
121
|
+
for (let shard = 0; shard < shards; shard++) {
|
|
122
|
+
const bucketKey = `${prefix}expiry:${minute}:${shard}`;
|
|
123
|
+
const keys = (await store.get(bucketKey)) ?? [];
|
|
124
|
+
if (keys.length === 0)
|
|
125
|
+
continue;
|
|
126
|
+
const batch = keys.slice(0, budget);
|
|
127
|
+
budget -= batch.length;
|
|
128
|
+
for (const key of batch)
|
|
129
|
+
await store.update(key, (current) => {
|
|
130
|
+
const record = current;
|
|
131
|
+
if (!record)
|
|
132
|
+
return { op: 'noop', result: undefined };
|
|
133
|
+
if ((record.expires ?? record.reset ?? 0) > time)
|
|
134
|
+
return { op: 'noop', result: undefined };
|
|
135
|
+
return { op: 'delete', result: undefined };
|
|
136
|
+
});
|
|
137
|
+
const left = await store.update(bucketKey, (current) => {
|
|
138
|
+
const rest = (current ?? []).filter((key) => !batch.includes(key));
|
|
139
|
+
return rest.length === 0
|
|
140
|
+
? { op: 'delete', result: 0 }
|
|
141
|
+
: { op: 'set', value: rest, result: rest.length };
|
|
142
|
+
});
|
|
143
|
+
if (left > 0)
|
|
144
|
+
empty = false;
|
|
145
|
+
if (budget === 0) {
|
|
146
|
+
if (shard < shards - 1)
|
|
147
|
+
empty = false;
|
|
148
|
+
break;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
if (empty)
|
|
152
|
+
await store.update(`${prefix}expiry:minutes`, (current) => {
|
|
153
|
+
const list = current ?? [];
|
|
154
|
+
if (!list.includes(minute))
|
|
155
|
+
return { op: 'noop', result: undefined };
|
|
156
|
+
return { op: 'set', value: list.filter((value) => value !== minute), result: undefined };
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
async function device(request) {
|
|
160
|
+
// Cleanup never fails a start.
|
|
161
|
+
await sweep().catch(() => { });
|
|
162
|
+
const body = await read(request);
|
|
163
|
+
const audience = body?.audience;
|
|
164
|
+
if (typeof audience !== 'string' || !isOrigin(audience))
|
|
165
|
+
return error(400, 'invalid_request', 'audience must be an origin.');
|
|
166
|
+
if (config.audiences) {
|
|
167
|
+
const allowed = typeof config.audiences === 'function'
|
|
168
|
+
? await config.audiences(audience, request)
|
|
169
|
+
: config.audiences.includes(audience);
|
|
170
|
+
if (!allowed)
|
|
171
|
+
return error(403, 'access_denied', 'This audience is not served.');
|
|
172
|
+
}
|
|
173
|
+
if (config.authorize && !(await config.authorize(request)))
|
|
174
|
+
return error(403, 'access_denied', 'Not allowed to start a World ID attempt.');
|
|
175
|
+
if (limit) {
|
|
176
|
+
const caller = await limit.key(request);
|
|
177
|
+
if (caller !== undefined) {
|
|
178
|
+
const now = Date.now();
|
|
179
|
+
const limitKey = `${prefix}limit:${caller}`;
|
|
180
|
+
const reset = now + limit.window * 1_000;
|
|
181
|
+
// A new window opens only once indexed for cleanup, so a failed index never leaves a
|
|
182
|
+
// counter to undo: the start fails before any window exists. Indexed once per window.
|
|
183
|
+
let indexed = false;
|
|
184
|
+
let retryAfter;
|
|
185
|
+
while (true) {
|
|
186
|
+
// 'index': a new window must be indexed first; 0: within the limit; above: seconds to wait.
|
|
187
|
+
retryAfter = await store.update(limitKey, (current) => {
|
|
188
|
+
const window = current;
|
|
189
|
+
if (!window || window.reset <= now) {
|
|
190
|
+
if (!indexed)
|
|
191
|
+
return { op: 'noop', result: 'index' };
|
|
192
|
+
return { op: 'set', value: { count: 1, reset }, result: 0 };
|
|
193
|
+
}
|
|
194
|
+
if (window.count >= limit.max)
|
|
195
|
+
return { op: 'noop', result: Math.ceil((window.reset - now) / 1_000) };
|
|
196
|
+
return { op: 'set', value: { ...window, count: window.count + 1 }, result: 0 };
|
|
197
|
+
});
|
|
198
|
+
if (retryAfter !== 'index')
|
|
199
|
+
break;
|
|
200
|
+
try {
|
|
201
|
+
await track(limitKey, reset);
|
|
202
|
+
}
|
|
203
|
+
catch {
|
|
204
|
+
return error(503, 'temporarily_unavailable', 'World ID is unavailable.');
|
|
205
|
+
}
|
|
206
|
+
indexed = true;
|
|
207
|
+
}
|
|
208
|
+
if (retryAfter > 0)
|
|
209
|
+
return error(429, 'slow_down', 'Too many World ID attempts.', {
|
|
210
|
+
'retry-after': String(retryAfter),
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
let started;
|
|
215
|
+
try {
|
|
216
|
+
started = await idp.start();
|
|
217
|
+
}
|
|
218
|
+
catch {
|
|
219
|
+
return error(503, 'temporarily_unavailable', 'World ID is unavailable.');
|
|
220
|
+
}
|
|
221
|
+
const id = Base64.fromBytes(crypto.getRandomValues(new Uint8Array(24)), {
|
|
222
|
+
pad: false,
|
|
223
|
+
url: true,
|
|
224
|
+
});
|
|
225
|
+
const now = Date.now();
|
|
226
|
+
const attempt = {
|
|
227
|
+
audience,
|
|
228
|
+
created: Math.floor(now / 1_000),
|
|
229
|
+
deviceCode: started.device_code,
|
|
230
|
+
expires: now + started.expires_in * 1_000,
|
|
231
|
+
interval: started.interval,
|
|
232
|
+
// The first poll waits an interval too (RFC 8628).
|
|
233
|
+
next: now + started.interval * 1_000,
|
|
234
|
+
};
|
|
235
|
+
// An attempt is saved only once indexed, so a sweep can always delete it. A start that can't be
|
|
236
|
+
// indexed fails; the unused device authorization simply expires at World IdP.
|
|
237
|
+
try {
|
|
238
|
+
await track(`${prefix}attempt:${id}`, attempt.expires);
|
|
239
|
+
}
|
|
240
|
+
catch {
|
|
241
|
+
return error(503, 'temporarily_unavailable', 'World ID is unavailable.');
|
|
242
|
+
}
|
|
243
|
+
await store.put(`${prefix}attempt:${id}`, attempt);
|
|
244
|
+
return Response.json({
|
|
245
|
+
expires_in: started.expires_in,
|
|
246
|
+
id,
|
|
247
|
+
interval: started.interval,
|
|
248
|
+
user_code: started.user_code,
|
|
249
|
+
verification_uri: started.verification_uri,
|
|
250
|
+
...(started.verification_uri_complete && {
|
|
251
|
+
verification_uri_complete: started.verification_uri_complete,
|
|
252
|
+
}),
|
|
253
|
+
}, { headers: { 'cache-control': 'no-store' } });
|
|
254
|
+
}
|
|
255
|
+
async function token(request) {
|
|
256
|
+
const body = await read(request);
|
|
257
|
+
const id = body?.id;
|
|
258
|
+
if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{1,64}$/.test(id))
|
|
259
|
+
return error(400, 'invalid_request', 'id is required.');
|
|
260
|
+
const storeKey = `${prefix}attempt:${id}`;
|
|
261
|
+
const now = Date.now();
|
|
262
|
+
// Claims this poll's slot atomically, so replays and concurrent polls reach World IdP at most
|
|
263
|
+
// once per interval, on every instance sharing the store. A completed attempt answers with its
|
|
264
|
+
// attestation again, so a lost response never loses the approval.
|
|
265
|
+
const claimed = await store.update(storeKey, (current) => {
|
|
266
|
+
const attempt = current;
|
|
267
|
+
if (!attempt)
|
|
268
|
+
return { op: 'noop', result: 'missing' };
|
|
269
|
+
if (attempt.expires <= now)
|
|
270
|
+
return { op: 'delete', result: 'missing' };
|
|
271
|
+
if (attempt.done)
|
|
272
|
+
return { op: 'noop', result: attempt };
|
|
273
|
+
if (attempt.next > now)
|
|
274
|
+
return { op: 'noop', result: 'early' };
|
|
275
|
+
// A poll of World IdP still in flight holds the attempt, so an overlapping poll never
|
|
276
|
+
// redeems the spent code and takes its refusal for the human's answer.
|
|
277
|
+
if (!attempt.idToken && attempt.polling && attempt.polling > now)
|
|
278
|
+
return { op: 'noop', result: 'busy' };
|
|
279
|
+
const next = {
|
|
280
|
+
...attempt,
|
|
281
|
+
next: now + attempt.interval * 1_000,
|
|
282
|
+
...(!attempt.idToken && { polling: now + pollLease }),
|
|
283
|
+
};
|
|
284
|
+
return { op: 'set', value: next, result: next };
|
|
285
|
+
});
|
|
286
|
+
if (claimed === 'missing')
|
|
287
|
+
return error(400, 'expired_token', 'The attempt expired.');
|
|
288
|
+
if (claimed === 'early')
|
|
289
|
+
return error(400, 'slow_down', 'Polled too soon.');
|
|
290
|
+
if (claimed === 'busy')
|
|
291
|
+
return error(400, 'authorization_pending', 'Waiting for approval.');
|
|
292
|
+
const attempt = claimed;
|
|
293
|
+
if (attempt.done)
|
|
294
|
+
return issued(attempt.done);
|
|
295
|
+
let idToken = attempt.idToken;
|
|
296
|
+
if (!idToken) {
|
|
297
|
+
const lease = attempt.polling;
|
|
298
|
+
// Lets the next poll go ahead once this one ends without an approval.
|
|
299
|
+
const release = () => store
|
|
300
|
+
.update(storeKey, (current) => {
|
|
301
|
+
const value = current;
|
|
302
|
+
if (!value || value.polling !== lease)
|
|
303
|
+
return { op: 'noop', result: undefined };
|
|
304
|
+
const { polling: _, ...rest } = value;
|
|
305
|
+
return { op: 'set', value: rest, result: undefined };
|
|
306
|
+
})
|
|
307
|
+
.catch(() => { });
|
|
308
|
+
let result;
|
|
309
|
+
try {
|
|
310
|
+
result = await idp.poll(attempt.deviceCode);
|
|
311
|
+
}
|
|
312
|
+
catch {
|
|
313
|
+
await release();
|
|
314
|
+
return error(503, 'temporarily_unavailable', 'World ID is unavailable.');
|
|
315
|
+
}
|
|
316
|
+
if (result.status === 'pending') {
|
|
317
|
+
await release();
|
|
318
|
+
return error(400, 'authorization_pending', 'Waiting for approval.');
|
|
319
|
+
}
|
|
320
|
+
if (result.status === 'slow_down') {
|
|
321
|
+
await store.update(storeKey, (current) => {
|
|
322
|
+
const value = current;
|
|
323
|
+
if (!value)
|
|
324
|
+
return { op: 'noop', result: undefined };
|
|
325
|
+
const interval = value.interval + Constants.slowDown;
|
|
326
|
+
const { polling: _, ...rest } = value;
|
|
327
|
+
return {
|
|
328
|
+
op: 'set',
|
|
329
|
+
value: {
|
|
330
|
+
...(value.polling === lease ? rest : value),
|
|
331
|
+
interval,
|
|
332
|
+
next: now + interval * 1_000,
|
|
333
|
+
},
|
|
334
|
+
result: undefined,
|
|
335
|
+
};
|
|
336
|
+
});
|
|
337
|
+
return error(400, 'slow_down', 'Polled too soon.');
|
|
338
|
+
}
|
|
339
|
+
if (result.status !== 'approved') {
|
|
340
|
+
// An overlapping poll may have redeemed the device code and saved its approval meanwhile:
|
|
341
|
+
// that approval stands, and this poll's refusal of the spent code is not the human's answer.
|
|
342
|
+
const saved = await store.update(storeKey, (current) => {
|
|
343
|
+
const value = current;
|
|
344
|
+
if (value?.idToken || value?.done)
|
|
345
|
+
return { op: 'noop', result: true };
|
|
346
|
+
return { op: 'delete', result: false };
|
|
347
|
+
});
|
|
348
|
+
if (saved)
|
|
349
|
+
return error(400, 'authorization_pending', 'Waiting for approval.');
|
|
350
|
+
return result.status === 'expired'
|
|
351
|
+
? error(400, 'expired_token', 'The attempt expired.')
|
|
352
|
+
: error(400, 'access_denied', 'World ID was not approved.');
|
|
353
|
+
}
|
|
354
|
+
idToken = result.idToken;
|
|
355
|
+
// World IdP redeems a device code once: keep its ID token until it verifies.
|
|
356
|
+
await store.update(storeKey, (current) => {
|
|
357
|
+
const value = current;
|
|
358
|
+
if (!value || value.idToken || value.done)
|
|
359
|
+
return { op: 'noop', result: undefined };
|
|
360
|
+
const { polling: _, ...rest } = value;
|
|
361
|
+
return { op: 'set', value: { ...rest, idToken }, result: undefined };
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
let claims;
|
|
365
|
+
try {
|
|
366
|
+
claims = await idp.verify(idToken, attempt.created);
|
|
367
|
+
}
|
|
368
|
+
catch {
|
|
369
|
+
return error(503, 'temporarily_unavailable', 'World ID keys are unavailable.');
|
|
370
|
+
}
|
|
371
|
+
if (typeof claims === 'string') {
|
|
372
|
+
await store.delete(storeKey);
|
|
373
|
+
return error(400, 'access_denied', claims);
|
|
374
|
+
}
|
|
375
|
+
const { keyId } = await key;
|
|
376
|
+
const iat = Math.floor(Date.now() / 1_000);
|
|
377
|
+
const done = {
|
|
378
|
+
attestation: await sign({
|
|
379
|
+
acr: claims.acr,
|
|
380
|
+
aud: attempt.audience,
|
|
381
|
+
exp: iat + ttl,
|
|
382
|
+
iat,
|
|
383
|
+
iss: url,
|
|
384
|
+
jti: crypto.randomUUID(),
|
|
385
|
+
sub: await subjectOf(claims.sub, attempt.audience),
|
|
386
|
+
type: Constants.type,
|
|
387
|
+
}, { key: config.signingKey, keyId }),
|
|
388
|
+
expiresAt: (iat + ttl) * 1_000,
|
|
389
|
+
};
|
|
390
|
+
// The first completion wins, so overlapping polls all answer with one attestation; the record
|
|
391
|
+
// keeps it, without the ID token, until the attempt expires and the sweep deletes it.
|
|
392
|
+
const kept = await store.update(storeKey, (current) => {
|
|
393
|
+
const value = current;
|
|
394
|
+
if (!value)
|
|
395
|
+
return { op: 'noop', result: done };
|
|
396
|
+
if (value.done)
|
|
397
|
+
return { op: 'noop', result: value.done };
|
|
398
|
+
const { idToken: _, ...rest } = value;
|
|
399
|
+
return { op: 'set', value: { ...rest, done }, result: done };
|
|
400
|
+
});
|
|
401
|
+
return issued(kept);
|
|
402
|
+
}
|
|
403
|
+
function issued(done) {
|
|
404
|
+
return Response.json({ attestation: done.attestation, expires_at: new Date(done.expiresAt).toISOString() }, { headers: { 'cache-control': 'no-store' } });
|
|
405
|
+
}
|
|
406
|
+
async function subjectOf(sub, audience) {
|
|
407
|
+
if (subject === 'world')
|
|
408
|
+
return sub;
|
|
409
|
+
const mac = await crypto.subtle.sign('HMAC', await hmac, new TextEncoder().encode(`${audience}\n${sub}`));
|
|
410
|
+
return Base64.fromBytes(new Uint8Array(mac), { pad: false, url: true });
|
|
411
|
+
}
|
|
412
|
+
return {
|
|
413
|
+
url,
|
|
414
|
+
async handle(request) {
|
|
415
|
+
const { pathname } = new URL(request.url);
|
|
416
|
+
if (!pathname.startsWith(base))
|
|
417
|
+
return undefined;
|
|
418
|
+
const path = pathname.slice(base.length);
|
|
419
|
+
if (path === AttestationConstants.jwksPath) {
|
|
420
|
+
if (request.method !== 'GET' && request.method !== 'HEAD')
|
|
421
|
+
return methodNotAllowed('GET');
|
|
422
|
+
return Response.json({ keys: [(await key).jwk] }, { headers: { 'cache-control': 'public, max-age=300' } });
|
|
423
|
+
}
|
|
424
|
+
if (path !== Constants.devicePath && path !== Constants.tokenPath)
|
|
425
|
+
return undefined;
|
|
426
|
+
if (request.method !== 'POST')
|
|
427
|
+
return methodNotAllowed('POST');
|
|
428
|
+
return path === Constants.devicePath ? device(request) : token(request);
|
|
429
|
+
},
|
|
430
|
+
async keyResolver({ issuer, keyId }) {
|
|
431
|
+
if (issuer !== url || keyId !== (await key).keyId)
|
|
432
|
+
return undefined;
|
|
433
|
+
return config.signingKey.publicKey;
|
|
434
|
+
},
|
|
435
|
+
async jwks() {
|
|
436
|
+
return { keys: [(await key).jwk] };
|
|
437
|
+
},
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
/** Granularity of the expiry index: records are swept within a minute of expiring. */
|
|
441
|
+
const bucketMs = 60_000;
|
|
442
|
+
/** Shards of each expiry-index minute. */
|
|
443
|
+
const shards = 16;
|
|
444
|
+
/** Most records one sweep deletes, so each start does a bounded amount of cleanup. */
|
|
445
|
+
const sweepLimit = 50;
|
|
446
|
+
/** How long a poll of World IdP holds its attempt: past its request timeout, so it has ended. */
|
|
447
|
+
const pollLease = Constants.requestTimeout + 5_000;
|
|
448
|
+
/** The largest request body the issuer reads, in bytes. */
|
|
449
|
+
const maxBody = 4_096;
|
|
450
|
+
/** The index shard of a key. */
|
|
451
|
+
function shardOf(key) {
|
|
452
|
+
let hash = 0;
|
|
453
|
+
for (let i = 0; i < key.length; i++)
|
|
454
|
+
hash = (hash * 31 + key.charCodeAt(i)) >>> 0;
|
|
455
|
+
return hash % shards;
|
|
456
|
+
}
|
|
457
|
+
async function read(request) {
|
|
458
|
+
const length = Number(request.headers.get('content-length') ?? 0);
|
|
459
|
+
if (length > maxBody)
|
|
460
|
+
return undefined;
|
|
461
|
+
const text = await readText(request);
|
|
462
|
+
if (text === undefined)
|
|
463
|
+
return undefined;
|
|
464
|
+
try {
|
|
465
|
+
const value = JSON.parse(text);
|
|
466
|
+
return value && typeof value === 'object' && !Array.isArray(value)
|
|
467
|
+
? value
|
|
468
|
+
: undefined;
|
|
469
|
+
}
|
|
470
|
+
catch {
|
|
471
|
+
return undefined;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
/** Reads a body of at most {@link maxBody} bytes, cancelling the stream as soon as it is over. */
|
|
475
|
+
async function readText(request) {
|
|
476
|
+
if (!request.body)
|
|
477
|
+
return '';
|
|
478
|
+
const reader = request.body.getReader();
|
|
479
|
+
const chunks = [];
|
|
480
|
+
let size = 0;
|
|
481
|
+
try {
|
|
482
|
+
while (true) {
|
|
483
|
+
const { done, value } = await reader.read();
|
|
484
|
+
if (done)
|
|
485
|
+
break;
|
|
486
|
+
size += value.byteLength;
|
|
487
|
+
if (size > maxBody) {
|
|
488
|
+
// Not awaited: a cloned body's cancel waits for its unread sibling.
|
|
489
|
+
reader.cancel().catch(() => { });
|
|
490
|
+
return undefined;
|
|
491
|
+
}
|
|
492
|
+
chunks.push(value);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
catch {
|
|
496
|
+
return undefined;
|
|
497
|
+
}
|
|
498
|
+
const bytes = new Uint8Array(size);
|
|
499
|
+
let offset = 0;
|
|
500
|
+
for (const chunk of chunks) {
|
|
501
|
+
bytes.set(chunk, offset);
|
|
502
|
+
offset += chunk.byteLength;
|
|
503
|
+
}
|
|
504
|
+
try {
|
|
505
|
+
return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
506
|
+
}
|
|
507
|
+
catch {
|
|
508
|
+
return undefined;
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
function isOrigin(value) {
|
|
512
|
+
return isIssuer(value) && URL.canParse(value) && new URL(value).origin === value;
|
|
513
|
+
}
|
|
514
|
+
function error(status, code, description, headers = {}) {
|
|
515
|
+
return Response.json({ error: code, error_description: description }, { headers: { 'cache-control': 'no-store', ...headers }, status });
|
|
516
|
+
}
|
|
517
|
+
function methodNotAllowed(allow) {
|
|
518
|
+
return new Response(null, { headers: { allow }, status: 405 });
|
|
519
|
+
}
|
|
520
|
+
//# sourceMappingURL=index.js.map
|