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,208 @@
|
|
|
1
|
+
import { unwrapFetch } from '../../../../client/internal/Fetch.js';
|
|
2
|
+
import * as Attestation from '../../attestation/client/index.js';
|
|
3
|
+
import { isIssuer } from '../../attestation/Token.js';
|
|
4
|
+
import { Constants } from '../Constants.js';
|
|
5
|
+
/** Asks a World ID issuer to start a device attempt for `audience`. */
|
|
6
|
+
export async function startDevice(parameters) {
|
|
7
|
+
const { body, response } = await post(parameters.issuer, Constants.devicePath, parameters.fetch, {
|
|
8
|
+
audience: parameters.audience,
|
|
9
|
+
});
|
|
10
|
+
if (!response.ok)
|
|
11
|
+
throw new WorldIdError(errorOf(body) ?? `The issuer answered ${response.status}.`, {
|
|
12
|
+
status: response.status,
|
|
13
|
+
});
|
|
14
|
+
const { expires_in, id, interval, user_code, verification_uri, verification_uri_complete } = body;
|
|
15
|
+
if (!isText(id) ||
|
|
16
|
+
!isText(user_code) ||
|
|
17
|
+
!isHttps(verification_uri) ||
|
|
18
|
+
(verification_uri_complete !== undefined && !isHttps(verification_uri_complete)) ||
|
|
19
|
+
!isSeconds(expires_in) ||
|
|
20
|
+
(interval !== undefined && !(isSeconds(interval) || interval === 0)))
|
|
21
|
+
throw new WorldIdError('The issuer returned a malformed device attempt.');
|
|
22
|
+
return Object.freeze({
|
|
23
|
+
expiresAt: new Date(Date.now() + expires_in * 1_000),
|
|
24
|
+
id,
|
|
25
|
+
interval: interval ?? Constants.interval,
|
|
26
|
+
userCode: user_code,
|
|
27
|
+
verificationUri: verification_uri,
|
|
28
|
+
...(verification_uri_complete !== undefined && {
|
|
29
|
+
verificationUriComplete: verification_uri_complete,
|
|
30
|
+
}),
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Polls a device attempt once. Throws a `WorldIdError` when the attempt ended without approval
|
|
35
|
+
* (`access_denied`, `expired_token` or another error); a 429, 5xx, timeout or network error is
|
|
36
|
+
* `unavailable`, never an approval or a failure.
|
|
37
|
+
*/
|
|
38
|
+
export async function pollDevice(parameters) {
|
|
39
|
+
let result;
|
|
40
|
+
try {
|
|
41
|
+
result = await post(parameters.issuer, Constants.tokenPath, parameters.fetch, {
|
|
42
|
+
id: parameters.id,
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
if (error instanceof WorldIdError)
|
|
47
|
+
throw error;
|
|
48
|
+
return { status: 'unavailable' };
|
|
49
|
+
}
|
|
50
|
+
const { body, response } = result;
|
|
51
|
+
if (response.status === 429 || response.status >= 500)
|
|
52
|
+
return { status: 'unavailable' };
|
|
53
|
+
if (response.ok) {
|
|
54
|
+
const expiresAt = isText(body.expires_at) ? new Date(body.expires_at) : undefined;
|
|
55
|
+
if (!isText(body.attestation) || !expiresAt || !Number.isFinite(expiresAt.getTime()))
|
|
56
|
+
throw new WorldIdError('The issuer returned a malformed attestation.');
|
|
57
|
+
return { status: 'approved', attestation: body.attestation, expiresAt };
|
|
58
|
+
}
|
|
59
|
+
const error = errorOf(body);
|
|
60
|
+
if (error === 'authorization_pending')
|
|
61
|
+
return { status: 'pending' };
|
|
62
|
+
if (error === 'slow_down')
|
|
63
|
+
return { status: 'slow_down' };
|
|
64
|
+
throw new WorldIdError(error === 'access_denied'
|
|
65
|
+
? 'World ID was not approved.'
|
|
66
|
+
: error === 'expired_token'
|
|
67
|
+
? 'The World ID attempt expired.'
|
|
68
|
+
: (error ?? `The issuer answered ${response.status}.`), { code: error, status: response.status });
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Creates a prover that gets a human's World ID approval when a server asks for one: an
|
|
72
|
+
* `Attestation.Client.prover` of type `world-id` whose `acquire` runs the issuer's device flow.
|
|
73
|
+
*
|
|
74
|
+
* When a server answers with `Identity-Attestation-Required: world-id;issuer="…"`, the prover
|
|
75
|
+
* asks the issuer to start a device attempt for the server's origin, shows the human the approval
|
|
76
|
+
* link through `verification`, and polls the issuer at its interval until the human approves in
|
|
77
|
+
* World App. It then sends the request again with the attestation, and reuses it for that origin
|
|
78
|
+
* until it expires.
|
|
79
|
+
*
|
|
80
|
+
* - Concurrent requests to one origin share one attempt, so the human sees one link.
|
|
81
|
+
* - After an attempt fails or is declined, requests to that origin get the failure for
|
|
82
|
+
* `Constants.retryDelay` seconds instead of starting another attempt.
|
|
83
|
+
* - An unavailable issuer (429, 5xx, timeout) is polled again at the interval until the attempt
|
|
84
|
+
* expires.
|
|
85
|
+
*
|
|
86
|
+
* @example
|
|
87
|
+
* ```ts
|
|
88
|
+
* const mppx = Mppx.create({
|
|
89
|
+
* identity: [
|
|
90
|
+
* World.Client.prover({
|
|
91
|
+
* issuers: ['https://world-id.issuer.example'],
|
|
92
|
+
* scope: ['https://api.example'],
|
|
93
|
+
* verification: ({ url, userCode }) => console.log(`Approve: ${url} (code ${userCode})`),
|
|
94
|
+
* }),
|
|
95
|
+
* ],
|
|
96
|
+
* methods: [tempo({ account })],
|
|
97
|
+
* })
|
|
98
|
+
* ```
|
|
99
|
+
*/
|
|
100
|
+
export function prover(config) {
|
|
101
|
+
// Failed or declined attempts by issuer and audience, so a failure is not retried in a loop.
|
|
102
|
+
const failures = new Map();
|
|
103
|
+
return Attestation.prover({
|
|
104
|
+
attestations: config.attestations,
|
|
105
|
+
issuers: config.issuers,
|
|
106
|
+
scope: config.scope,
|
|
107
|
+
types: [Constants.type],
|
|
108
|
+
async acquire({ audience, issuer }) {
|
|
109
|
+
const key = JSON.stringify([issuer, audience]);
|
|
110
|
+
const failure = failures.get(key);
|
|
111
|
+
if (failure && failure.until > Date.now()) {
|
|
112
|
+
if (failure.error)
|
|
113
|
+
throw failure.error;
|
|
114
|
+
return undefined;
|
|
115
|
+
}
|
|
116
|
+
failures.delete(key);
|
|
117
|
+
try {
|
|
118
|
+
const token = await authenticate({ audience, issuer });
|
|
119
|
+
if (!token)
|
|
120
|
+
failures.set(key, { until: Date.now() + Constants.retryDelay * 1_000 });
|
|
121
|
+
return token;
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
failures.set(key, { error, until: Date.now() + Constants.retryDelay * 1_000 });
|
|
125
|
+
throw error;
|
|
126
|
+
}
|
|
127
|
+
},
|
|
128
|
+
});
|
|
129
|
+
async function authenticate({ audience, issuer }) {
|
|
130
|
+
const device = await startDevice({ audience, fetch: config.fetch, issuer });
|
|
131
|
+
const shown = await config.verification({
|
|
132
|
+
expiresAt: device.expiresAt,
|
|
133
|
+
issuer,
|
|
134
|
+
origin: audience,
|
|
135
|
+
url: device.verificationUriComplete ?? device.verificationUri,
|
|
136
|
+
userCode: device.userCode,
|
|
137
|
+
});
|
|
138
|
+
if (shown === false)
|
|
139
|
+
return undefined;
|
|
140
|
+
let interval = device.interval;
|
|
141
|
+
while (true) {
|
|
142
|
+
// The first poll waits an interval too (RFC 8628).
|
|
143
|
+
if (Date.now() + interval * 1_000 >= device.expiresAt.getTime())
|
|
144
|
+
throw new WorldIdError('The World ID attempt expired.', { code: 'expired_token' });
|
|
145
|
+
await sleep(interval * 1_000);
|
|
146
|
+
const result = await pollDevice({ fetch: config.fetch, id: device.id, issuer });
|
|
147
|
+
if (result.status === 'approved')
|
|
148
|
+
return result.attestation;
|
|
149
|
+
if (result.status === 'slow_down')
|
|
150
|
+
interval += Constants.slowDown;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
/** A World ID issuer refused a request, or an attempt ended without approval. */
|
|
155
|
+
export class WorldIdError extends Error {
|
|
156
|
+
name = 'WorldIdError';
|
|
157
|
+
/** OAuth error code the issuer answered with, such as `access_denied`, if any. */
|
|
158
|
+
code;
|
|
159
|
+
/** HTTP status the issuer answered with, if any. */
|
|
160
|
+
status;
|
|
161
|
+
constructor(message, options = {}) {
|
|
162
|
+
super(message);
|
|
163
|
+
this.code = options.code;
|
|
164
|
+
this.status = options.status;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
async function post(issuer, path, fetch, body) {
|
|
168
|
+
// Attempt IDs and attestations never go over plaintext HTTP, except to localhost.
|
|
169
|
+
if (!isIssuer(issuer))
|
|
170
|
+
throw new WorldIdError('The issuer must be an https URL (http only on localhost).');
|
|
171
|
+
// The unwrapped fetch, so an issuer's 402 is never paid automatically.
|
|
172
|
+
const response = await unwrapFetch(fetch ?? globalThis.fetch)(`${issuer.replace(/\/+$/, '')}${path}`, {
|
|
173
|
+
body: JSON.stringify(body),
|
|
174
|
+
headers: { 'content-type': 'application/json' },
|
|
175
|
+
method: 'POST',
|
|
176
|
+
// Workers reject 'error'; a redirect is not ok, so it fails as a refusal.
|
|
177
|
+
redirect: 'manual',
|
|
178
|
+
signal: AbortSignal.timeout(Constants.requestTimeout),
|
|
179
|
+
});
|
|
180
|
+
// A body that fails to arrive (reset, timeout) throws, so a poll counts it as unavailable;
|
|
181
|
+
// only a body that arrived but isn't a JSON object reads as empty.
|
|
182
|
+
const text = await response.text();
|
|
183
|
+
let json;
|
|
184
|
+
try {
|
|
185
|
+
json = JSON.parse(text);
|
|
186
|
+
}
|
|
187
|
+
catch { }
|
|
188
|
+
return {
|
|
189
|
+
body: json && typeof json === 'object' ? json : {},
|
|
190
|
+
response,
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
function errorOf(body) {
|
|
194
|
+
return isText(body.error) ? body.error : undefined;
|
|
195
|
+
}
|
|
196
|
+
function sleep(ms) {
|
|
197
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
198
|
+
}
|
|
199
|
+
function isText(value) {
|
|
200
|
+
return typeof value === 'string' && value !== '';
|
|
201
|
+
}
|
|
202
|
+
function isHttps(value) {
|
|
203
|
+
return isText(value) && URL.canParse(value) && new URL(value).protocol === 'https:';
|
|
204
|
+
}
|
|
205
|
+
function isSeconds(value) {
|
|
206
|
+
return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
|
|
207
|
+
}
|
|
208
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/** Claims of a verified World IdP ID token. */
|
|
2
|
+
export type IdTokenClaims = {
|
|
3
|
+
readonly sub: string;
|
|
4
|
+
readonly acr: string;
|
|
5
|
+
readonly amr: readonly string[];
|
|
6
|
+
readonly auth_time: number;
|
|
7
|
+
};
|
|
8
|
+
/** A device authorization from World IdP. */
|
|
9
|
+
export type Authorization = {
|
|
10
|
+
readonly device_code: string;
|
|
11
|
+
readonly user_code: string;
|
|
12
|
+
readonly verification_uri: string;
|
|
13
|
+
readonly verification_uri_complete?: string | undefined;
|
|
14
|
+
readonly expires_in: number;
|
|
15
|
+
readonly interval: number;
|
|
16
|
+
};
|
|
17
|
+
/** One poll of World IdP's token endpoint. */
|
|
18
|
+
export type Poll = {
|
|
19
|
+
readonly status: 'approved';
|
|
20
|
+
readonly idToken: string;
|
|
21
|
+
} | {
|
|
22
|
+
readonly status: 'pending' | 'slow_down' | 'denied' | 'expired';
|
|
23
|
+
};
|
|
24
|
+
/** Settings of a World IdP confidential client. */
|
|
25
|
+
export type Config = {
|
|
26
|
+
readonly issuer: string;
|
|
27
|
+
readonly clientId: string;
|
|
28
|
+
readonly clientSecret: string;
|
|
29
|
+
readonly clientAuthentication?: 'client_secret_basic' | 'client_secret_post' | undefined;
|
|
30
|
+
readonly acr: readonly string[];
|
|
31
|
+
readonly fetch?: typeof globalThis.fetch | undefined;
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* Calls World IdP as a confidential client: discovery, the device flow (RFC 8628) and ID token
|
|
35
|
+
* validation. Every call times out, and a timeout or outage throws, so callers treat it as
|
|
36
|
+
* unavailable rather than as an answer.
|
|
37
|
+
*/
|
|
38
|
+
export declare function create(config: Config): {
|
|
39
|
+
/** Starts a device attempt. Throws when World IdP is unreachable or refuses it. */
|
|
40
|
+
start(): Promise<Authorization>;
|
|
41
|
+
/** Polls a device attempt once. Throws when World IdP is unavailable or misconfigured. */
|
|
42
|
+
poll(deviceCode: string): Promise<Poll>;
|
|
43
|
+
/**
|
|
44
|
+
* Validates an ID token from the device grant: RS256 signature with World IdP's keys, issuer,
|
|
45
|
+
* audience, times, an authentication at or after the attempt started, and an accepted `acr`.
|
|
46
|
+
* Returns the reason when it is invalid; throws when the keys can't be fetched.
|
|
47
|
+
*/
|
|
48
|
+
verify(token: string, created: number): Promise<IdTokenClaims | string>;
|
|
49
|
+
};
|
|
50
|
+
//# sourceMappingURL=Idp.d.ts.map
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
import { Base64 } from 'ox';
|
|
2
|
+
import { unwrapFetch } from '../../../../client/internal/Fetch.js';
|
|
3
|
+
import { isIssuer } from '../../attestation/Token.js';
|
|
4
|
+
import { Constants } from '../Constants.js';
|
|
5
|
+
/**
|
|
6
|
+
* Calls World IdP as a confidential client: discovery, the device flow (RFC 8628) and ID token
|
|
7
|
+
* validation. Every call times out, and a timeout or outage throws, so callers treat it as
|
|
8
|
+
* unavailable rather than as an answer.
|
|
9
|
+
*/
|
|
10
|
+
export function create(config) {
|
|
11
|
+
const { acr, clientId, clientSecret, issuer } = config;
|
|
12
|
+
// Unwrapped, so a 402 is never paid in a process that also runs the client.
|
|
13
|
+
const fetch = unwrapFetch(config.fetch ?? globalThis.fetch);
|
|
14
|
+
let metadata;
|
|
15
|
+
const keys = jwks(fetch);
|
|
16
|
+
function discover() {
|
|
17
|
+
metadata ??= (async () => {
|
|
18
|
+
const body = await json(await get(`${issuer}/.well-known/openid-configuration`));
|
|
19
|
+
const endpoints = [
|
|
20
|
+
body.device_authorization_endpoint,
|
|
21
|
+
body.token_endpoint,
|
|
22
|
+
body.jwks_uri,
|
|
23
|
+
];
|
|
24
|
+
if (body.issuer !== issuer ||
|
|
25
|
+
!endpoints.every((url) => typeof url === 'string' && isIssuer(url)))
|
|
26
|
+
throw new Error('World IdP discovery is malformed.');
|
|
27
|
+
return body;
|
|
28
|
+
})().catch((error) => {
|
|
29
|
+
metadata = undefined;
|
|
30
|
+
throw error;
|
|
31
|
+
});
|
|
32
|
+
return metadata;
|
|
33
|
+
}
|
|
34
|
+
function get(url) {
|
|
35
|
+
return fetch(url, {
|
|
36
|
+
headers: { accept: 'application/json' },
|
|
37
|
+
redirect: 'manual',
|
|
38
|
+
signal: AbortSignal.timeout(Constants.requestTimeout),
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
function post(url, fields) {
|
|
42
|
+
const body = new URLSearchParams(fields);
|
|
43
|
+
const headers = {
|
|
44
|
+
accept: 'application/json',
|
|
45
|
+
'content-type': 'application/x-www-form-urlencoded',
|
|
46
|
+
};
|
|
47
|
+
if (config.clientAuthentication === 'client_secret_post') {
|
|
48
|
+
body.set('client_id', clientId);
|
|
49
|
+
body.set('client_secret', clientSecret);
|
|
50
|
+
}
|
|
51
|
+
else
|
|
52
|
+
headers.authorization = `Basic ${Base64.fromString(`${formEncode(clientId)}:${formEncode(clientSecret)}`)}`;
|
|
53
|
+
return fetch(url, {
|
|
54
|
+
body,
|
|
55
|
+
headers,
|
|
56
|
+
method: 'POST',
|
|
57
|
+
redirect: 'manual',
|
|
58
|
+
signal: AbortSignal.timeout(Constants.requestTimeout),
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
return {
|
|
62
|
+
/** Starts a device attempt. Throws when World IdP is unreachable or refuses it. */
|
|
63
|
+
async start() {
|
|
64
|
+
const { device_authorization_endpoint } = await discover();
|
|
65
|
+
const response = await post(device_authorization_endpoint, {
|
|
66
|
+
scope: 'openid',
|
|
67
|
+
claims: JSON.stringify({ id_token: { acr: { essential: true, values: acr } } }),
|
|
68
|
+
});
|
|
69
|
+
if (!response.ok)
|
|
70
|
+
throw new Error(`World IdP answered ${response.status}.`);
|
|
71
|
+
const body = await json(response);
|
|
72
|
+
const { device_code, expires_in, interval, user_code, verification_uri } = body;
|
|
73
|
+
const complete = body.verification_uri_complete;
|
|
74
|
+
if (!isText(device_code) ||
|
|
75
|
+
!isText(user_code) ||
|
|
76
|
+
!isText(verification_uri) ||
|
|
77
|
+
!isIssuer(verification_uri) ||
|
|
78
|
+
(complete !== undefined && !(isText(complete) && isIssuer(complete))) ||
|
|
79
|
+
!isSeconds(expires_in) ||
|
|
80
|
+
(interval !== undefined && !isSeconds(interval)))
|
|
81
|
+
throw new Error('World IdP returned a malformed device authorization.');
|
|
82
|
+
return {
|
|
83
|
+
device_code,
|
|
84
|
+
expires_in,
|
|
85
|
+
interval: interval ?? Constants.interval,
|
|
86
|
+
user_code,
|
|
87
|
+
verification_uri,
|
|
88
|
+
...(complete !== undefined && { verification_uri_complete: complete }),
|
|
89
|
+
};
|
|
90
|
+
},
|
|
91
|
+
/** Polls a device attempt once. Throws when World IdP is unavailable or misconfigured. */
|
|
92
|
+
async poll(deviceCode) {
|
|
93
|
+
const { token_endpoint } = await discover();
|
|
94
|
+
const response = await post(token_endpoint, {
|
|
95
|
+
grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
|
|
96
|
+
device_code: deviceCode,
|
|
97
|
+
});
|
|
98
|
+
const body = await json(response).catch(() => ({}));
|
|
99
|
+
if (response.ok) {
|
|
100
|
+
if (!isText(body.id_token))
|
|
101
|
+
throw new Error('World IdP returned no ID token.');
|
|
102
|
+
return { status: 'approved', idToken: body.id_token };
|
|
103
|
+
}
|
|
104
|
+
// Only an OAuth error ends or continues the attempt; anything else is an outage.
|
|
105
|
+
if (response.status !== 400 && response.status !== 401)
|
|
106
|
+
throw new Error('World IdP is unavailable.');
|
|
107
|
+
if (body.error === 'authorization_pending')
|
|
108
|
+
return { status: 'pending' };
|
|
109
|
+
if (body.error === 'slow_down')
|
|
110
|
+
return { status: 'slow_down' };
|
|
111
|
+
if (body.error === 'expired_token')
|
|
112
|
+
return { status: 'expired' };
|
|
113
|
+
if (body.error === 'access_denied' || body.error === 'invalid_grant')
|
|
114
|
+
return { status: 'denied' };
|
|
115
|
+
// invalid_client and other errors are the issuer's misconfiguration, not the person's answer.
|
|
116
|
+
throw new Error('World IdP rejected the request.');
|
|
117
|
+
},
|
|
118
|
+
/**
|
|
119
|
+
* Validates an ID token from the device grant: RS256 signature with World IdP's keys, issuer,
|
|
120
|
+
* audience, times, an authentication at or after the attempt started, and an accepted `acr`.
|
|
121
|
+
* Returns the reason when it is invalid; throws when the keys can't be fetched.
|
|
122
|
+
*/
|
|
123
|
+
async verify(token, created) {
|
|
124
|
+
const parts = token.split('.');
|
|
125
|
+
if (parts.length !== 3 || parts.some((part) => !/^[A-Za-z0-9_-]+$/.test(part)))
|
|
126
|
+
return 'The ID token is malformed.';
|
|
127
|
+
let header;
|
|
128
|
+
let claims;
|
|
129
|
+
try {
|
|
130
|
+
header = JSON.parse(Base64.toString(parts[0]));
|
|
131
|
+
claims = JSON.parse(Base64.toString(parts[1]));
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
return 'The ID token is malformed.';
|
|
135
|
+
}
|
|
136
|
+
if (header?.alg !== 'RS256' || !isText(header.kid))
|
|
137
|
+
return 'The ID token algorithm is not RS256.';
|
|
138
|
+
const now = Math.floor(Date.now() / 1_000);
|
|
139
|
+
const tolerance = Constants.clockTolerance;
|
|
140
|
+
if (claims?.iss !== issuer)
|
|
141
|
+
return 'The ID token issuer is not World IdP.';
|
|
142
|
+
const aud = claims.aud;
|
|
143
|
+
const audiences = Array.isArray(aud) ? aud : [aud];
|
|
144
|
+
if (!audiences.includes(clientId) || (audiences.length > 1 && claims.azp !== clientId))
|
|
145
|
+
return 'The ID token is for another client.';
|
|
146
|
+
if (!isText(claims.sub))
|
|
147
|
+
return 'The ID token has no subject.';
|
|
148
|
+
if (!isTime(claims.exp) || claims.exp <= now - tolerance)
|
|
149
|
+
return 'The ID token has expired.';
|
|
150
|
+
if (!isTime(claims.iat) || claims.iat > now + tolerance)
|
|
151
|
+
return 'The ID token was issued in the future.';
|
|
152
|
+
if (!isTime(claims.auth_time) || claims.auth_time > now + tolerance)
|
|
153
|
+
return 'The ID token has no valid auth_time.';
|
|
154
|
+
// The device grant always authenticates afresh: an older authentication is not this attempt's.
|
|
155
|
+
if (claims.auth_time < created - tolerance)
|
|
156
|
+
return 'The World ID authentication predates the attempt.';
|
|
157
|
+
if (!isText(claims.acr) || !acr.includes(claims.acr))
|
|
158
|
+
return 'The World ID authentication class is not accepted.';
|
|
159
|
+
if (!Array.isArray(claims.amr) || !claims.amr.every(isText))
|
|
160
|
+
return 'The ID token has no valid amr.';
|
|
161
|
+
const { jwks_uri } = await discover();
|
|
162
|
+
const key = await keys(jwks_uri, header.kid);
|
|
163
|
+
if (!key)
|
|
164
|
+
return 'No World IdP key matches the ID token.';
|
|
165
|
+
let valid = false;
|
|
166
|
+
try {
|
|
167
|
+
valid = await crypto.subtle.verify('RSASSA-PKCS1-v1_5', key, Base64.toBytes(parts[2]), new TextEncoder().encode(`${parts[0]}.${parts[1]}`));
|
|
168
|
+
}
|
|
169
|
+
catch { }
|
|
170
|
+
if (!valid)
|
|
171
|
+
return 'The ID token signature is invalid.';
|
|
172
|
+
return { sub: claims.sub, acr: claims.acr, amr: claims.amr, auth_time: claims.auth_time };
|
|
173
|
+
},
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Resolves World IdP's RS256 keys by key ID from its JSON Web Key Set, cached for five minutes.
|
|
178
|
+
* An unknown key ID refetches the set at most every 30 seconds, and concurrent lookups share one
|
|
179
|
+
* fetch. While a refetch fails, the last set fetched successfully keeps resolving for an hour, so
|
|
180
|
+
* a brief outage never wastes an approval; a key it lacks then throws (unavailable), since World
|
|
181
|
+
* IdP may have rotated, and only a fresh set proves a key unknown.
|
|
182
|
+
*/
|
|
183
|
+
function jwks(fetch) {
|
|
184
|
+
let cache;
|
|
185
|
+
let good;
|
|
186
|
+
function load(url) {
|
|
187
|
+
const fetchedAt = Date.now();
|
|
188
|
+
const keys = (async () => {
|
|
189
|
+
const response = await fetch(url, {
|
|
190
|
+
headers: { accept: 'application/json' },
|
|
191
|
+
redirect: 'manual',
|
|
192
|
+
signal: AbortSignal.timeout(Constants.requestTimeout),
|
|
193
|
+
});
|
|
194
|
+
if (!response.ok)
|
|
195
|
+
throw new Error(`World IdP JWKS answered ${response.status}.`);
|
|
196
|
+
const body = await json(response);
|
|
197
|
+
if (!Array.isArray(body.keys))
|
|
198
|
+
throw new Error('World IdP JWKS has no keys.');
|
|
199
|
+
const result = new Map();
|
|
200
|
+
for (const jwk of body.keys) {
|
|
201
|
+
const { alg, e, kid, kty, n, use } = (jwk ?? {});
|
|
202
|
+
if (kty !== 'RSA' || !isText(kid) || !isText(n) || !isText(e))
|
|
203
|
+
continue;
|
|
204
|
+
if ((use !== undefined && use !== 'sig') || (alg !== undefined && alg !== 'RS256'))
|
|
205
|
+
continue;
|
|
206
|
+
try {
|
|
207
|
+
result.set(kid, await crypto.subtle.importKey('jwk', { kty, n, e }, { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, false, ['verify']));
|
|
208
|
+
}
|
|
209
|
+
catch { }
|
|
210
|
+
}
|
|
211
|
+
good = { url, fetchedAt, keys: result };
|
|
212
|
+
return result;
|
|
213
|
+
})();
|
|
214
|
+
const entry = { url, fetchedAt, keys };
|
|
215
|
+
cache = entry;
|
|
216
|
+
keys.catch(() => {
|
|
217
|
+
if (cache === entry)
|
|
218
|
+
cache = undefined;
|
|
219
|
+
});
|
|
220
|
+
return keys.then((result) => ({ keys: result, fresh: true }), (error) => {
|
|
221
|
+
if (good?.url === url && Date.now() - good.fetchedAt < 3_600_000)
|
|
222
|
+
return { keys: good.keys, fresh: false };
|
|
223
|
+
throw error;
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
return async (url, kid) => {
|
|
227
|
+
const age = cache && cache.url === url ? Date.now() - cache.fetchedAt : Infinity;
|
|
228
|
+
const first = age < 300_000 ? { keys: await cache.keys, fresh: true } : await load(url);
|
|
229
|
+
if (first.keys.has(kid))
|
|
230
|
+
return first.keys.get(kid);
|
|
231
|
+
// A stale set can't prove a key unknown: World IdP may have rotated while its JWKS is down.
|
|
232
|
+
if (!first.fresh)
|
|
233
|
+
throw new Error('World IdP keys are unavailable.');
|
|
234
|
+
if (age < 30_000 || age >= 300_000)
|
|
235
|
+
return undefined;
|
|
236
|
+
const second = await load(url);
|
|
237
|
+
if (second.keys.has(kid))
|
|
238
|
+
return second.keys.get(kid);
|
|
239
|
+
if (!second.fresh)
|
|
240
|
+
throw new Error('World IdP keys are unavailable.');
|
|
241
|
+
return undefined;
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
async function json(response) {
|
|
245
|
+
if (!(response.headers.get('content-type') ?? '').includes('json') && response.ok)
|
|
246
|
+
throw new Error('World IdP did not answer with JSON.');
|
|
247
|
+
const body = (await response.json());
|
|
248
|
+
if (typeof body !== 'object' || body === null || Array.isArray(body))
|
|
249
|
+
throw new Error('World IdP answered with a malformed body.');
|
|
250
|
+
return body;
|
|
251
|
+
}
|
|
252
|
+
/** Form-encodes a client credential for HTTP Basic authentication (RFC 6749, section 2.3.1). */
|
|
253
|
+
function formEncode(value) {
|
|
254
|
+
return new URLSearchParams({ v: value }).toString().slice(2);
|
|
255
|
+
}
|
|
256
|
+
function isText(value) {
|
|
257
|
+
return typeof value === 'string' && value !== '' && value.length <= 4_096;
|
|
258
|
+
}
|
|
259
|
+
function isSeconds(value) {
|
|
260
|
+
return typeof value === 'number' && Number.isSafeInteger(value) && value > 0 && value <= 86_400;
|
|
261
|
+
}
|
|
262
|
+
function isTime(value) {
|
|
263
|
+
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
|
|
264
|
+
}
|
|
265
|
+
//# sourceMappingURL=Idp.js.map
|
|
@@ -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
|