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.
- package/CHANGELOG.md +33 -0
- package/dist/Errors.d.ts +40 -4
- package/dist/Errors.js +40 -6
- package/dist/cli/cli.js +96 -96
- package/dist/cli/plugins/index.js +12 -12
- 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/index.d.ts +2 -0
- package/dist/extensions/identity/index.js +2 -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/poppy/Constants.d.ts +26 -0
- package/dist/extensions/identity/poppy/Constants.js +26 -0
- package/dist/extensions/identity/poppy/Types.d.ts +19 -0
- package/dist/extensions/identity/poppy/Types.js +2 -0
- package/dist/extensions/identity/poppy/client/index.d.ts +69 -0
- package/dist/extensions/identity/poppy/client/index.js +81 -0
- package/dist/extensions/identity/poppy/index.d.ts +7 -0
- package/dist/extensions/identity/poppy/index.js +7 -0
- package/dist/extensions/identity/poppy/internal/Jws.d.ts +12 -0
- package/dist/extensions/identity/poppy/internal/Jws.js +78 -0
- package/dist/extensions/identity/poppy/server/index.d.ts +40 -0
- package/dist/extensions/identity/poppy/server/index.js +181 -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 +1 -1
- package/dist/identity/Headers.js +7 -1
- package/dist/identity/Types.d.ts +5 -0
- package/dist/internal/version.d.ts +2 -2
- package/dist/internal/version.js +1 -1
- package/dist/server/Mppx.js +2 -1
- package/dist/tempo/client/Charge.js +39 -16
- package/dist/tempo/internal/simulation.d.ts +33 -0
- package/dist/tempo/internal/simulation.js +80 -0
- package/dist/tempo/internal/zone.d.ts +27 -0
- package/dist/tempo/internal/zone.js +54 -7
- package/dist/tempo/server/internal/html.gen.js +1 -1
- package/dist/tempo/session/client/ChannelOps.js +5 -2
- package/package.json +13 -1
- /package/dist/extensions/identity/{web-bot-auth/internal → internal}/JwkThumbprint.d.ts +0 -0
|
@@ -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
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type * as Identity from '../../../../identity/Types.js';
|
|
2
|
+
import * as Attestation from '../../attestation/server/index.js';
|
|
3
|
+
import type * as AttestationTypes from '../../attestation/Types.js';
|
|
4
|
+
import type * as Types from '../Types.js';
|
|
5
|
+
/**
|
|
6
|
+
* Creates a request-stage verifier that requires a human verified with World ID: an
|
|
7
|
+
* `Attestation.Server.verifier` of type `world-id` from a shared World ID issuer.
|
|
8
|
+
*
|
|
9
|
+
* A request without one gets 401 with `Identity-Attestation-Required: world-id;issuer="…"`. The
|
|
10
|
+
* client runs World IdP's device flow through the issuer, which holds the World IdP client, and
|
|
11
|
+
* sends the attestation in `Identity-Attestation`. This server never calls World IdP and hosts no
|
|
12
|
+
* routes. An attestation whose `acr` is not in `acr` is `forbidden` (403).
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```ts
|
|
16
|
+
* const human = World.Server.verifier({
|
|
17
|
+
* audience: 'https://api.example',
|
|
18
|
+
* issuer: 'https://world-id.issuer.example',
|
|
19
|
+
* })
|
|
20
|
+
* const result = await mppx.charge({ amount: '1', identity: [human] })(request)
|
|
21
|
+
* if (result.status === 200) result.identity?.get(human)?.subject
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
export declare function verifier(config: verifier.Config): Identity.Verifier<Types.VerifiedHuman>;
|
|
25
|
+
export declare namespace verifier {
|
|
26
|
+
type Config = {
|
|
27
|
+
/** Trusted World ID issuer URL. */
|
|
28
|
+
readonly issuer: string;
|
|
29
|
+
/**
|
|
30
|
+
* This server's public origin, such as `https://api.example`, which attestations must be
|
|
31
|
+
* bound to. The function form is deprecated: see `Attestation.Server.verifier.AudienceFunction`.
|
|
32
|
+
*/
|
|
33
|
+
readonly audience: string | Attestation.verifier.AudienceFunction;
|
|
34
|
+
/**
|
|
35
|
+
* Accepted World IdP authentication classes (`Constants.acr`). Defaults to any the issuer
|
|
36
|
+
* attests.
|
|
37
|
+
*/
|
|
38
|
+
readonly acr?: readonly string[] | undefined;
|
|
39
|
+
/** Resolves issuer keys. Defaults to the issuer's JSON Web Key Set. */
|
|
40
|
+
readonly keyResolver?: AttestationTypes.KeyResolver | undefined;
|
|
41
|
+
/** Fetch used for the default JSON Web Key Set resolver. */
|
|
42
|
+
readonly fetch?: typeof globalThis.fetch | undefined;
|
|
43
|
+
/** Oldest accepted attestation, in seconds since it was issued. Defaults to its own expiry. */
|
|
44
|
+
readonly maxAge?: number | undefined;
|
|
45
|
+
/** Clock tolerance in seconds. @default 60 */
|
|
46
|
+
readonly clockTolerance?: number | undefined;
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import * as Attestation from '../../attestation/server/index.js';
|
|
2
|
+
import { Constants } from '../Constants.js';
|
|
3
|
+
/**
|
|
4
|
+
* Creates a request-stage verifier that requires a human verified with World ID: an
|
|
5
|
+
* `Attestation.Server.verifier` of type `world-id` from a shared World ID issuer.
|
|
6
|
+
*
|
|
7
|
+
* A request without one gets 401 with `Identity-Attestation-Required: world-id;issuer="…"`. The
|
|
8
|
+
* client runs World IdP's device flow through the issuer, which holds the World IdP client, and
|
|
9
|
+
* sends the attestation in `Identity-Attestation`. This server never calls World IdP and hosts no
|
|
10
|
+
* routes. An attestation whose `acr` is not in `acr` is `forbidden` (403).
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```ts
|
|
14
|
+
* const human = World.Server.verifier({
|
|
15
|
+
* audience: 'https://api.example',
|
|
16
|
+
* issuer: 'https://world-id.issuer.example',
|
|
17
|
+
* })
|
|
18
|
+
* const result = await mppx.charge({ amount: '1', identity: [human] })(request)
|
|
19
|
+
* if (result.status === 200) result.identity?.get(human)?.subject
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
export function verifier(config) {
|
|
23
|
+
const acr = config.acr;
|
|
24
|
+
if (acr && acr.length === 0)
|
|
25
|
+
throw new TypeError('World ID verifier requires at least one acr.');
|
|
26
|
+
const inner = Attestation.verifier({
|
|
27
|
+
audience: config.audience,
|
|
28
|
+
clockTolerance: config.clockTolerance,
|
|
29
|
+
fetch: config.fetch,
|
|
30
|
+
issuer: config.issuer,
|
|
31
|
+
keyResolver: config.keyResolver,
|
|
32
|
+
maxAge: config.maxAge,
|
|
33
|
+
type: Constants.type,
|
|
34
|
+
...(acr && {
|
|
35
|
+
validate(claims) {
|
|
36
|
+
const value = claims.acr;
|
|
37
|
+
if (typeof value === 'string' && acr.includes(value))
|
|
38
|
+
return undefined;
|
|
39
|
+
return 'This World ID verification level is not accepted.';
|
|
40
|
+
},
|
|
41
|
+
}),
|
|
42
|
+
});
|
|
43
|
+
return {
|
|
44
|
+
async verify(request) {
|
|
45
|
+
const result = await inner.verify(request);
|
|
46
|
+
if (result.status !== 'valid')
|
|
47
|
+
return result;
|
|
48
|
+
const { claims } = result.value;
|
|
49
|
+
const value = claims.acr;
|
|
50
|
+
return {
|
|
51
|
+
status: 'valid',
|
|
52
|
+
value: Object.freeze({
|
|
53
|
+
...(typeof value === 'string' && { acr: value }),
|
|
54
|
+
expiresAt: new Date(claims.exp * 1_000),
|
|
55
|
+
id: claims.jti,
|
|
56
|
+
issuer: claims.iss,
|
|
57
|
+
subject: claims.sub,
|
|
58
|
+
}),
|
|
59
|
+
};
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* never sent across origins on a redirect or forwarded upstream by a proxy. Provers declare
|
|
8
8
|
* their own extra sensitive headers in `Prover.headers`.
|
|
9
9
|
*/
|
|
10
|
-
export declare const request: readonly ["identity-attestation", "identity-presentation"];
|
|
10
|
+
export declare const request: readonly ["dpop", "identity-attestation", "identity-presentation", "poppy-session", "tempo-id-token"];
|
|
11
11
|
/**
|
|
12
12
|
* `WWW-Authenticate` schemes that ask for an identity, lowercased. A proxy removes them from
|
|
13
13
|
* upstream responses: the proxy, not the upstream, decides which identity the client presents.
|
package/dist/identity/Headers.js
CHANGED
|
@@ -7,7 +7,13 @@
|
|
|
7
7
|
* never sent across origins on a redirect or forwarded upstream by a proxy. Provers declare
|
|
8
8
|
* their own extra sensitive headers in `Prover.headers`.
|
|
9
9
|
*/
|
|
10
|
-
export const request = Object.freeze([
|
|
10
|
+
export const request = Object.freeze([
|
|
11
|
+
'dpop',
|
|
12
|
+
'identity-attestation',
|
|
13
|
+
'identity-presentation',
|
|
14
|
+
'poppy-session',
|
|
15
|
+
'tempo-id-token',
|
|
16
|
+
]);
|
|
11
17
|
/**
|
|
12
18
|
* `WWW-Authenticate` schemes that ask for an identity, lowercased. A proxy removes them from
|
|
13
19
|
* upstream responses: the proxy, not the upstream, decides which identity the client presents.
|
package/dist/identity/Types.d.ts
CHANGED
|
@@ -112,6 +112,11 @@ export type Requirement = {
|
|
|
112
112
|
* @experimental Unstable: may change or be removed in any release.
|
|
113
113
|
*/
|
|
114
114
|
export type PaymentCheck<value = unknown> = {
|
|
115
|
+
/**
|
|
116
|
+
* The check reads its credential from `Authorization`. A route that uses it needs a server
|
|
117
|
+
* created with `requiresAuth: true`, so Payment Credentials travel in `Payment-Authorization`.
|
|
118
|
+
*/
|
|
119
|
+
readonly authorization?: boolean | undefined;
|
|
115
120
|
/** Identities the check requires, advertised in every 402 of the route. */
|
|
116
121
|
readonly requires: readonly Requirement[];
|
|
117
122
|
/** Returns the check's outcome for the paid retry (or, without a Credential, for `authorize`). */
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Current mppx package version. */
|
|
2
|
-
export declare const version = "0.
|
|
2
|
+
export declare const version = "0.19.1";
|
|
3
3
|
/** Canonical SDK identifier for this mppx release. */
|
|
4
|
-
export declare const sdkIdentifier = "mppx/0.
|
|
4
|
+
export declare const sdkIdentifier = "mppx/0.19.1";
|
|
5
5
|
//# sourceMappingURL=version.d.ts.map
|