ark-oauth-client-node 0.0.0-stage → 2.2.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/src/client.js ADDED
@@ -0,0 +1,780 @@
1
+ import { normalizeConfig } from './config.js';
2
+ import { MetadataResolver } from './discovery.js';
3
+ import { JwksCache } from './jwks.js';
4
+ import { TokenSet } from './tokens.js';
5
+ import { basicAuthHeader, getJson, postForm, request } from './http.js';
6
+ import { createNonce, createPkcePair, createState } from './pkce.js';
7
+ import { fixedTimeEqual, randomToken, sha256 } from './crypto.js';
8
+ import { signJwt, verifyJwt } from './jwt.js';
9
+ import { ArkCallbackError, ArkConfigError, ArkOAuthError, ArkTokenError } from './errors.js';
10
+
11
+ /**
12
+ * The Ark OAuth 2.1 / OpenID Connect client.
13
+ *
14
+ * One object per application, holding the configuration, the cached discovery document and the
15
+ * cached JWKS. It is stateless with respect to users: a sign-in produces a *transaction* the
16
+ * caller stores (the `state`, `nonce` and PKCE verifier), and a token set the caller stores. That
17
+ * is what makes it safe to share one instance across every request in a process, and what lets
18
+ * the session live wherever the application already keeps sessions rather than in this library.
19
+ *
20
+ * For an Express or Connect application, `arkExpress()` in ./express.js drives all of this — the
21
+ * transaction, the session, the silent refresh — and is the thing to reach for first. Use this
22
+ * class directly for CLIs, workers, Fastify/Koa/Hapi, or any flow without a browser.
23
+ */
24
+ export class ArkOAuthClient {
25
+ #config;
26
+ #metadata;
27
+ #jwks = new Map();
28
+ #serviceTokens = new Map();
29
+
30
+ constructor(options = {}) {
31
+ this.#config = normalizeConfig(options);
32
+ const http = { timeoutMs: this.#config.timeoutMs, fetch: this.#config.fetch };
33
+ this.#metadata = options.metadataResolver ?? new MetadataResolver({ ttlMs: this.#config.metadataTtlMs, ...http });
34
+ }
35
+
36
+ get config() {
37
+ return this.#config;
38
+ }
39
+
40
+ get authority() {
41
+ return this.#config.authority;
42
+ }
43
+
44
+ /** The provider's discovery document, cached. Every endpoint below is read from it. */
45
+ async metadata({ force = false } = {}) {
46
+ return this.#metadata.get(this.#config.authority, { force });
47
+ }
48
+
49
+ /** The provider's published signing keys, cached and refreshed across key rotation. */
50
+ async jwks() {
51
+ const { jwks_uri: uri } = await this.metadata();
52
+ if (!uri) throw new ArkOAuthError('server_error', "the provider's metadata has no 'jwks_uri'.", { endpoint: this.#config.authority });
53
+ let cache = this.#jwks.get(uri);
54
+ if (!cache) {
55
+ cache = new JwksCache(uri, {
56
+ ttlMs: this.#config.jwksTtlMs,
57
+ minRefreshIntervalMs: this.#config.jwksMinRefreshIntervalMs,
58
+ timeoutMs: this.#config.timeoutMs,
59
+ fetch: this.#config.fetch
60
+ });
61
+ this.#jwks.set(uri, cache);
62
+ }
63
+ return cache;
64
+ }
65
+
66
+ // =================================================================
67
+ // Interactive sign-in: authorization code + PKCE
68
+ // =================================================================
69
+
70
+ /**
71
+ * Starts a sign-in: builds the URL to send the browser to, and returns the transaction that has
72
+ * to survive until the user comes back.
73
+ *
74
+ * The returned `state`, `nonce` and `codeVerifier` are the entire security of the flow — store
75
+ * them somewhere the user cannot read or edit (a server-side session, an encrypted cookie) and
76
+ * pass the same object to `handleCallback`. Putting them in a plain cookie or a hidden form
77
+ * field hands the attacker exactly the three values the checks are made of.
78
+ *
79
+ * @returns {Promise<{url: string, state: string, nonce: string, codeVerifier: string, redirectUri: string, createdAt: number, returnTo?: string}>}
80
+ */
81
+ async createAuthorizationUrl(options = {}) {
82
+ const config = this.#config;
83
+ const metadata = await this.metadata();
84
+
85
+ const redirectUri = options.redirectUri ?? config.redirectUri;
86
+ if (!redirectUri) {
87
+ throw new ArkConfigError("ark_oauth_client: no 'redirectUri' is configured, and none was passed to createAuthorizationUrl().");
88
+ }
89
+
90
+ const scopes = options.scopes ?? config.scopes;
91
+ const { codeVerifier, codeChallenge, codeChallengeMethod } = createPkcePair();
92
+ const state = options.state ?? createState();
93
+ const scopeValue = [...scopes].join(' ');
94
+ const wantsIdToken = scopes.includes('openid');
95
+ const nonce = options.nonce ?? (wantsIdToken ? createNonce() : null);
96
+
97
+ // Extra parameters go first so they can add to the request but never replace what the flow's
98
+ // security rests on: an `extra` carrying its own state or code_challenge would detach the
99
+ // response from the transaction this method returns.
100
+ const params = {
101
+ ...config.extraAuthorizationParams,
102
+ ...options.extra,
103
+ response_type: 'code',
104
+ client_id: config.clientId,
105
+ redirect_uri: redirectUri,
106
+ scope: scopeValue,
107
+ state,
108
+ code_challenge: codeChallenge,
109
+ code_challenge_method: codeChallengeMethod,
110
+ response_mode: options.responseMode ?? config.responseMode,
111
+ ...(nonce ? { nonce } : {}),
112
+ ...(options.prompt ?? config.prompt ? { prompt: options.prompt ?? config.prompt } : {}),
113
+ ...(options.loginHint ? { login_hint: options.loginHint } : {}),
114
+ ...(options.maxAge !== undefined && options.maxAge !== null ? { max_age: String(options.maxAge) } : {}),
115
+ ...(options.acrValues ?? config.acrValues ? { acr_values: options.acrValues ?? config.acrValues } : {})
116
+ };
117
+
118
+ const authorizationEndpoint = metadata.authorization_endpoint;
119
+ if (!authorizationEndpoint) {
120
+ throw new ArkOAuthError('server_error', "the provider's metadata has no 'authorization_endpoint'.", { endpoint: config.authority });
121
+ }
122
+
123
+ // Pushed authorization requests (RFC 9126): the parameters travel over the authenticated back
124
+ // channel and the browser only carries a one-time reference to them, so nothing in the URL can
125
+ // be logged, tampered with or replayed. Used when asked for, and when the tenant requires it.
126
+ const usePar = options.usePar ?? (config.usePar || metadata.require_pushed_authorization_requests === true);
127
+ let url;
128
+ if (usePar) {
129
+ const pushed = await this.pushAuthorizationRequest(params);
130
+ url = `${authorizationEndpoint}?${new URLSearchParams({ client_id: config.clientId, request_uri: pushed.request_uri })}`;
131
+ } else {
132
+ url = `${authorizationEndpoint}?${new URLSearchParams(Object.entries(params).filter(([, v]) => v !== undefined && v !== null))}`;
133
+ }
134
+
135
+ return {
136
+ url,
137
+ state,
138
+ nonce,
139
+ codeVerifier,
140
+ redirectUri,
141
+ scope: scopeValue,
142
+ maxAge: options.maxAge ?? null,
143
+ createdAt: Math.floor(Date.now() / 1000),
144
+ ...(options.returnTo ? { returnTo: options.returnTo } : {})
145
+ };
146
+ }
147
+
148
+ /**
149
+ * Reads the authorization response out of whatever the web framework handed you: a full URL, a
150
+ * query string, a URLSearchParams, or the parsed body of a `form_post` callback.
151
+ */
152
+ static readCallbackParams(input) {
153
+ if (!input) return {};
154
+ if (input instanceof URLSearchParams) return Object.fromEntries(input);
155
+ if (typeof input === 'string') {
156
+ const query = input.includes('?') ? input.slice(input.indexOf('?') + 1) : input.replace(/^[?#]/, '');
157
+ return Object.fromEntries(new URLSearchParams(query));
158
+ }
159
+ if (typeof input === 'object') return { ...input };
160
+ return {};
161
+ }
162
+
163
+ /**
164
+ * Completes a sign-in: checks the response against the transaction, redeems the code, and
165
+ * validates the ID token.
166
+ *
167
+ * Everything that makes the authorization code flow safe happens in this method, in this order:
168
+ * an error response is surfaced as an error rather than as a missing code; `state` is compared
169
+ * in constant time, so a response that belongs to no request of ours is refused before anything
170
+ * is redeemed; `iss` is checked (RFC 9207) so a response cannot be replayed from one provider to
171
+ * another; the code is exchanged with the PKCE verifier that only this process holds; and the ID
172
+ * token is verified against the provider's keys, its `nonce`, and its `at_hash`/`c_hash`.
173
+ *
174
+ * @param {string|URLSearchParams|object} responseParams
175
+ * @param {object} transaction the object returned by createAuthorizationUrl
176
+ */
177
+ async handleCallback(responseParams, transaction, options = {}) {
178
+ const params = ArkOAuthClient.readCallbackParams(responseParams);
179
+ const metadata = await this.metadata();
180
+
181
+ if (!transaction?.state || !transaction?.codeVerifier) {
182
+ throw new ArkCallbackError(
183
+ 'no login transaction was supplied. The state, nonce and PKCE verifier from createAuthorizationUrl() must be stored ' +
184
+ 'when the sign-in starts and passed back here.'
185
+ );
186
+ }
187
+
188
+ // The user denied consent, the client is disabled, the tenant rejected the request: all
189
+ // arrive here as a redirect carrying `error`, and all of them mean there is no code to redeem.
190
+ if (params.error) {
191
+ throw new ArkOAuthError(params.error, params.error_description, {
192
+ endpoint: metadata.authorization_endpoint,
193
+ errorUri: params.error_uri ?? null,
194
+ body: params
195
+ });
196
+ }
197
+
198
+ if (!params.state) throw new ArkCallbackError('the authorization response carried no `state`.');
199
+ if (!fixedTimeEqual(String(params.state), String(transaction.state))) {
200
+ throw new ArkCallbackError('the authorization response `state` does not match the request. Treat this as a CSRF attempt.');
201
+ }
202
+
203
+ // RFC 9207. Ark always sends `iss`; when the provider advertises it, a response without one is
204
+ // as suspect as a wrong one, because stripping the parameter is how a mix-up attack hides.
205
+ if (params.iss || metadata.authorization_response_iss_parameter_supported) {
206
+ if (!params.iss) throw new ArkCallbackError('the provider advertises `iss` in authorization responses but this one has none.');
207
+ if (params.iss !== metadata.issuer) {
208
+ throw new ArkCallbackError(`the authorization response came from '${params.iss}', not from '${metadata.issuer}'.`);
209
+ }
210
+ }
211
+
212
+ if (!params.code) throw new ArkCallbackError('the authorization response carried no `code`.');
213
+
214
+ return this.exchangeCode({
215
+ code: params.code,
216
+ codeVerifier: transaction.codeVerifier,
217
+ redirectUri: options.redirectUri ?? transaction.redirectUri ?? this.#config.redirectUri,
218
+ nonce: transaction.nonce ?? null,
219
+ maxAge: transaction.maxAge ?? null
220
+ });
221
+ }
222
+
223
+ /** The bare `authorization_code` exchange, for callers doing their own callback handling. */
224
+ async exchangeCode({ code, codeVerifier, redirectUri, nonce = null, maxAge = null }) {
225
+ const metadata = await this.metadata();
226
+ const endpoint = metadata.token_endpoint;
227
+
228
+ const response = await this.#tokenRequest(endpoint, {
229
+ grant_type: 'authorization_code',
230
+ code,
231
+ redirect_uri: redirectUri,
232
+ code_verifier: codeVerifier
233
+ });
234
+
235
+ return this.#toTokenSet(response, { nonce, code, maxAge });
236
+ }
237
+
238
+ /**
239
+ * Exchanges a refresh token for a new access token.
240
+ *
241
+ * Rotation is on by default on this server: the response carries a *new* refresh token and the
242
+ * one just presented is retired. Store what comes back. Presenting a retired token is treated as
243
+ * theft and revokes the entire family, which is the point of rotation, and also the reason a
244
+ * client that keeps re-sending its original token locks itself out on the second refresh.
245
+ */
246
+ async refresh(refreshToken, { scopes } = {}) {
247
+ if (!refreshToken) throw new ArkConfigError('refresh() needs a refresh token.');
248
+ const metadata = await this.metadata();
249
+
250
+ const response = await this.#tokenRequest(metadata.token_endpoint, {
251
+ grant_type: 'refresh_token',
252
+ refresh_token: refreshToken,
253
+ // RFC 6749 §6: scope may be narrowed here, never widened. The server rejects a widening.
254
+ ...(scopes?.length ? { scope: [...scopes].join(' ') } : {})
255
+ });
256
+
257
+ return this.#toTokenSet(response, { nonce: null });
258
+ }
259
+
260
+ /**
261
+ * The client credentials grant — the service authenticating as itself, with no user involved.
262
+ *
263
+ * Tokens are cached per client and scope set until shortly before they expire. A service that
264
+ * asks for a fresh token on every outbound call turns one request into two and rate-limits
265
+ * itself against its own identity provider.
266
+ */
267
+ async clientCredentials({ scopes = [], clientId, clientSecret, force = false, renewBeforeSeconds = 60 } = {}) {
268
+ if (this.#config.tokenEndpointAuthMethod === 'none' && !clientSecret) {
269
+ throw new ArkConfigError(
270
+ 'the client_credentials grant requires client authentication; a public client cannot use it. ' +
271
+ 'Register a confidential client (client_secret_basic or private_key_jwt) for service-to-service calls.'
272
+ );
273
+ }
274
+
275
+ const id = clientId ?? this.#config.clientId;
276
+ const scopeValue = [...scopes].join(' ');
277
+ // The credential is part of the key: a caller presenting a wrong secret must be refused by the
278
+ // provider, not handed the token another caller earned with the right one. Hashed, so the cache
279
+ // holds no secret.
280
+ const credential = sha256(String(clientSecret ?? this.#config.clientSecret ?? '')).toString('base64url');
281
+ const key = `${this.#config.authority}|${id}|${credential}|${scopeValue}`;
282
+
283
+ const cached = this.#serviceTokens.get(key);
284
+ if (!force && cached && !cached.expired(renewBeforeSeconds)) return cached;
285
+
286
+ const metadata = await this.metadata();
287
+ const response = await this.#tokenRequest(
288
+ metadata.token_endpoint,
289
+ { grant_type: 'client_credentials', ...(scopeValue ? { scope: scopeValue } : {}) },
290
+ { clientId: id, clientSecret }
291
+ );
292
+
293
+ const tokens = new TokenSet(response);
294
+ this.#serviceTokens.set(key, tokens);
295
+ return tokens;
296
+ }
297
+
298
+ // =================================================================
299
+ // Device authorization grant (RFC 8628)
300
+ // =================================================================
301
+
302
+ /** Step one of the device grant: ask for a code, then show the user `verification_uri_complete`. */
303
+ async deviceAuthorization({ scopes } = {}) {
304
+ const metadata = await this.metadata();
305
+ const endpoint = metadata.device_authorization_endpoint;
306
+ if (!endpoint) {
307
+ throw new ArkOAuthError('unsupported_grant_type', 'this tenant does not serve the device authorization grant.', {
308
+ endpoint: this.#config.authority
309
+ });
310
+ }
311
+
312
+ const scopeValue = [...(scopes ?? this.#config.scopes)].join(' ');
313
+ const { form, headers } = await this.#clientAuthentication({ scope: scopeValue }, endpoint);
314
+ return postForm(endpoint, form, { headers, timeoutMs: this.#config.timeoutMs, fetch: this.#config.fetch });
315
+ }
316
+
317
+ /**
318
+ * Step two: poll the token endpoint until the user approves on their other device.
319
+ *
320
+ * The two error codes that are not failures are handled here — `authorization_pending` means
321
+ * keep waiting, and `slow_down` means the server wants a longer interval and will keep saying so
322
+ * until it gets one (RFC 8628 §3.5). Everything else ends the wait.
323
+ */
324
+ async pollDeviceToken(deviceAuthorization, { signal, onPending, intervalSeconds, timeoutSeconds } = {}) {
325
+ const metadata = await this.metadata();
326
+ const deviceCode = deviceAuthorization.device_code ?? deviceAuthorization;
327
+ let interval = (intervalSeconds ?? deviceAuthorization.interval ?? 5) * 1000;
328
+ const deadline = Date.now() + (timeoutSeconds ?? deviceAuthorization.expires_in ?? 600) * 1000;
329
+
330
+ for (;;) {
331
+ if (signal?.aborted) throw new ArkOAuthError('access_denied', 'the device flow was cancelled.', { endpoint: metadata.token_endpoint });
332
+ if (Date.now() >= deadline) {
333
+ throw new ArkOAuthError('expired_token', 'the device code expired before the user approved it.', {
334
+ endpoint: metadata.token_endpoint
335
+ });
336
+ }
337
+
338
+ await new Promise((resolve) => {
339
+ const wake = () => {
340
+ clearTimeout(timer);
341
+ signal?.removeEventListener('abort', wake);
342
+ resolve();
343
+ };
344
+ // One listener per wait, removed again: left attached, a long approval piles up one per
345
+ // poll on the caller's signal.
346
+ const timer = setTimeout(wake, interval);
347
+ signal?.addEventListener('abort', wake, { once: true });
348
+ });
349
+
350
+ try {
351
+ const response = await this.#tokenRequest(metadata.token_endpoint, {
352
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
353
+ device_code: deviceCode
354
+ });
355
+ return await this.#toTokenSet(response, { nonce: null });
356
+ } catch (error) {
357
+ if (!(error instanceof ArkOAuthError)) throw error;
358
+ if (error.error === 'authorization_pending') {
359
+ onPending?.(error);
360
+ continue;
361
+ }
362
+ if (error.error === 'slow_down') {
363
+ interval += 5000; // §3.5: add five seconds and keep going
364
+ onPending?.(error);
365
+ continue;
366
+ }
367
+ throw error;
368
+ }
369
+ }
370
+ }
371
+
372
+ // =================================================================
373
+ // Pushed authorization requests (RFC 9126)
374
+ // =================================================================
375
+
376
+ async pushAuthorizationRequest(params) {
377
+ const metadata = await this.metadata();
378
+ const endpoint = metadata.pushed_authorization_request_endpoint;
379
+ if (!endpoint) {
380
+ throw new ArkOAuthError('invalid_request', 'this tenant does not serve pushed authorization requests.', {
381
+ endpoint: this.#config.authority
382
+ });
383
+ }
384
+
385
+ const body = Object.fromEntries(Object.entries(params).filter(([, v]) => v !== undefined && v !== null && v !== ''));
386
+ const { form, headers } = await this.#clientAuthentication(body, endpoint);
387
+ return postForm(endpoint, form, { headers, timeoutMs: this.#config.timeoutMs, fetch: this.#config.fetch });
388
+ }
389
+
390
+ // =================================================================
391
+ // Using and inspecting tokens
392
+ // =================================================================
393
+
394
+ /**
395
+ * The UserInfo endpoint (OIDC Core §5.3).
396
+ *
397
+ * Returns only the claims the presented token was granted scope for. Worth calling when a claim
398
+ * is needed that the ID token did not carry; not worth calling on every request, since the ID
399
+ * token already holds what the scopes unlocked at sign-in.
400
+ */
401
+ async userInfo(accessToken) {
402
+ const metadata = await this.metadata();
403
+ if (!accessToken) throw new ArkConfigError('userInfo() needs an access token.');
404
+ return getJson(metadata.userinfo_endpoint, {
405
+ headers: { Authorization: `Bearer ${accessToken}` },
406
+ timeoutMs: this.#config.timeoutMs,
407
+ fetch: this.#config.fetch
408
+ });
409
+ }
410
+
411
+ /**
412
+ * Token introspection (RFC 7662). Requires client authentication, so a public client cannot use
413
+ * it — which is deliberate on the server side: an unauthenticated introspection endpoint is an
414
+ * oracle for testing captured tokens.
415
+ *
416
+ * For a JWT access token from this server, `verifyAccessToken` answers the same question locally
417
+ * and without a network call; reach for introspection to learn whether a *refresh* token is
418
+ * still live, or when the token is opaque.
419
+ */
420
+ async introspect(token, { tokenTypeHint } = {}) {
421
+ const metadata = await this.metadata();
422
+ const endpoint = metadata.introspection_endpoint;
423
+ const { form, headers } = await this.#clientAuthentication(
424
+ { token, ...(tokenTypeHint ? { token_type_hint: tokenTypeHint } : {}) },
425
+ endpoint
426
+ );
427
+ return postForm(endpoint, form, { headers, timeoutMs: this.#config.timeoutMs, fetch: this.#config.fetch });
428
+ }
429
+
430
+ /**
431
+ * Token revocation (RFC 7009). Revoking a refresh token takes down its whole rotation family, so
432
+ * this is the call that really ends a session's access — sign-out should make it.
433
+ *
434
+ * An unknown token is a success (§2.2): the caller's goal is already met.
435
+ */
436
+ async revoke(token, { tokenTypeHint = 'refresh_token' } = {}) {
437
+ const metadata = await this.metadata();
438
+ const endpoint = metadata.revocation_endpoint;
439
+ const { form, headers } = await this.#clientAuthentication(
440
+ { token, ...(tokenTypeHint ? { token_type_hint: tokenTypeHint } : {}) },
441
+ endpoint
442
+ );
443
+ await postForm(endpoint, form, { headers, timeoutMs: this.#config.timeoutMs, fetch: this.#config.fetch });
444
+ return true;
445
+ }
446
+
447
+ /**
448
+ * The RP-initiated logout URL.
449
+ *
450
+ * `idTokenHint` is what lets the provider know which session to end and which client asked, and
451
+ * without it the `post_logout_redirect_uri` cannot be matched against a registration — so the
452
+ * user is left on the provider's "signed out" page instead of coming back to the application.
453
+ */
454
+ async endSessionUrl({ idTokenHint, postLogoutRedirectUri, state, clientId } = {}) {
455
+ const metadata = await this.metadata();
456
+ const endpoint = metadata.end_session_endpoint;
457
+ if (!endpoint) throw new ArkOAuthError('server_error', "the provider's metadata has no 'end_session_endpoint'.", { endpoint: this.#config.authority });
458
+
459
+ const params = new URLSearchParams({ client_id: clientId ?? this.#config.clientId });
460
+ if (idTokenHint) params.set('id_token_hint', idTokenHint);
461
+ const target = postLogoutRedirectUri ?? this.#config.postLogoutRedirectUri;
462
+ if (target) params.set('post_logout_redirect_uri', target);
463
+ if (state) params.set('state', state);
464
+ return `${endpoint}?${params}`;
465
+ }
466
+
467
+ /** Verifies an ID token against the provider's keys and the values from the sign-in transaction. */
468
+ async verifyIdToken(idToken, { nonce = null, accessToken = null, code = null, maxAge = null } = {}) {
469
+ const metadata = await this.metadata();
470
+ const jwks = await this.jwks();
471
+ return verifyJwt(idToken, jwks, {
472
+ issuer: metadata.issuer,
473
+ audience: this.#config.clientId,
474
+ nonce,
475
+ accessToken,
476
+ code,
477
+ maxAgeSeconds: maxAge,
478
+ requireTokenHashes: this.#config.requireTokenHashes,
479
+ requireIat: true,
480
+ clockToleranceSeconds: this.#config.clockToleranceSeconds,
481
+ algorithms: this.#config.idTokenSigningAlgorithms ?? undefined
482
+ });
483
+ }
484
+
485
+ /**
486
+ * Verifies an access token this server issued — the resource-server side of the library.
487
+ *
488
+ * Local verification against the cached JWKS, so protecting an API costs no network call per
489
+ * request. `scopes` and `arkClaims` are checked here rather than left to the caller, because
490
+ * "the token is valid" and "the token is allowed to do this" are different questions and only
491
+ * the second one is the authorization decision.
492
+ */
493
+ async verifyAccessToken(token, { audience, scopes = [], arkClaims = [], requireTypeHeader = true } = {}) {
494
+ const metadata = await this.metadata();
495
+ const jwks = await this.jwks();
496
+
497
+ const payload = await verifyJwt(token, jwks, {
498
+ issuer: metadata.issuer,
499
+ audience: audience ?? this.#config.audience ?? undefined,
500
+ typ: requireTypeHeader ? 'at+jwt' : undefined,
501
+ requireIat: true,
502
+ clockToleranceSeconds: this.#config.clockToleranceSeconds
503
+ });
504
+
505
+ const granted = new Set(String(payload.scope ?? '').split(' ').filter(Boolean));
506
+ const missingScopes = [...scopes].flat().filter((s) => !granted.has(s));
507
+ if (missingScopes.length > 0) {
508
+ throw new ArkOAuthError('insufficient_scope', `the token is missing the scope(s): ${missingScopes.join(', ')}.`, { status: 403 });
509
+ }
510
+
511
+ const held = new Set(Array.isArray(payload.ark_claims) ? payload.ark_claims : payload.ark_claims ? [payload.ark_claims] : []);
512
+ const missingClaims = [...arkClaims].flat().filter((c) => !held.has(c));
513
+ if (missingClaims.length > 0) {
514
+ throw new ArkOAuthError('insufficient_scope', `the token is missing the authorization claim(s): ${missingClaims.join(', ')}.`, { status: 403 });
515
+ }
516
+
517
+ return payload;
518
+ }
519
+
520
+ // =================================================================
521
+ // Dynamic client registration (RFC 7591 / 7592)
522
+ // =================================================================
523
+
524
+ /**
525
+ * Registers a client. Off by default on the server, and when on it wants an initial access token
526
+ * carrying the `client.register` scope — which itself comes from the client credentials grant,
527
+ * so registration is a two-step chain rather than an open endpoint.
528
+ *
529
+ * The response carries `client_secret` exactly once; it is stored only as a hash and cannot be
530
+ * read back afterwards.
531
+ */
532
+ async registerClient(clientMetadata, initialAccessToken) {
533
+ const metadata = await this.metadata();
534
+ const endpoint = metadata.registration_endpoint;
535
+ if (!endpoint) {
536
+ throw new ArkOAuthError('registration_not_supported', 'this tenant does not serve dynamic client registration.', {
537
+ endpoint: this.#config.authority
538
+ });
539
+ }
540
+ const { body } = await request(endpoint, {
541
+ method: 'POST',
542
+ json: clientMetadata,
543
+ headers: initialAccessToken ? { Authorization: `Bearer ${initialAccessToken}` } : {},
544
+ timeoutMs: this.#config.timeoutMs,
545
+ fetch: this.#config.fetch
546
+ });
547
+ return body;
548
+ }
549
+
550
+ /** Reads a registration back (RFC 7592 §2.1), using the registration access token from creation. */
551
+ async readRegistration(clientId, registrationAccessToken) {
552
+ const metadata = await this.metadata();
553
+ return getJson(`${metadata.registration_endpoint}/${encodeURIComponent(clientId)}`, {
554
+ headers: { Authorization: `Bearer ${registrationAccessToken}` },
555
+ timeoutMs: this.#config.timeoutMs,
556
+ fetch: this.#config.fetch
557
+ });
558
+ }
559
+
560
+ /** Deletes a registration (RFC 7592 §2.3). */
561
+ async deleteRegistration(clientId, registrationAccessToken) {
562
+ const metadata = await this.metadata();
563
+ await request(`${metadata.registration_endpoint}/${encodeURIComponent(clientId)}`, {
564
+ method: 'DELETE',
565
+ headers: { Authorization: `Bearer ${registrationAccessToken}` },
566
+ timeoutMs: this.#config.timeoutMs,
567
+ fetch: this.#config.fetch
568
+ });
569
+ return true;
570
+ }
571
+
572
+ // =================================================================
573
+ // Diagnostics
574
+ // =================================================================
575
+
576
+ /**
577
+ * Pairs this application's configuration with the provider's live metadata and reports what does
578
+ * not line up.
579
+ *
580
+ * The same idea as `ArkSetupProbe` in the .NET client, and it earns its place for the same
581
+ * reason: without it, the first symptom of a wrong port, a stopped provider, a missing tenant id
582
+ * or a scope the client was never registered for is `invalid_request` on a page the user is
583
+ * looking at. Render this on a health or setup page and the mistake reads as a sentence.
584
+ */
585
+ async checkSetup({ origin, callbackPath = '/signin-oidc' } = {}) {
586
+ const config = this.#config;
587
+ const base = config.authority.slice(0, config.authority.lastIndexOf('/'));
588
+ const tenantId = config.authority.slice(config.authority.lastIndexOf('/') + 1);
589
+ const report = {
590
+ authority: config.authority,
591
+ clientId: config.clientId,
592
+ isConfidential: config.tokenEndpointAuthMethod !== 'none',
593
+ tokenEndpointAuthMethod: config.tokenEndpointAuthMethod,
594
+ scopes: [...config.scopes],
595
+ redirectUri: config.redirectUri ?? (origin ? `${origin.replace(/\/+$/, '')}${callbackPath}` : null),
596
+ postLogoutRedirectUri: config.postLogoutRedirectUri,
597
+ origin: origin ?? null,
598
+ tenantId,
599
+ // Where the client is registered, and the provider's own page of what it expects from it.
600
+ adminConsoleUrl: `${base}/${tenantId}/admin`,
601
+ integrationPageUrl: `${config.authority}/oauth2/integrate/${encodeURIComponent(config.clientId)}`,
602
+ discoveryUrl: `${config.authority}/.well-known/openid-configuration`,
603
+ discoveryOk: false,
604
+ discoveryError: null,
605
+ supportsClientCredentials: false,
606
+ supportsDynamicRegistration: false,
607
+ provider: null,
608
+ problems: []
609
+ };
610
+
611
+ let metadata;
612
+ try {
613
+ metadata = await this.metadata({ force: true });
614
+ report.discoveryOk = true;
615
+ } catch (error) {
616
+ report.discoveryError = error.message;
617
+ report.problems.push(`The provider's discovery document could not be read: ${error.message}`);
618
+ return report;
619
+ }
620
+
621
+ report.provider = {
622
+ issuer: metadata.issuer,
623
+ authorizationEndpoint: metadata.authorization_endpoint,
624
+ tokenEndpoint: metadata.token_endpoint,
625
+ userInfoEndpoint: metadata.userinfo_endpoint,
626
+ jwksUri: metadata.jwks_uri,
627
+ endSessionEndpoint: metadata.end_session_endpoint,
628
+ deviceAuthorizationEndpoint: metadata.device_authorization_endpoint ?? null,
629
+ pushedAuthorizationRequestEndpoint: metadata.pushed_authorization_request_endpoint ?? null,
630
+ registrationEndpoint: metadata.registration_endpoint ?? null,
631
+ scopesSupported: metadata.scopes_supported ?? [],
632
+ grantTypesSupported: metadata.grant_types_supported ?? [],
633
+ codeChallengeMethodsSupported: metadata.code_challenge_methods_supported ?? [],
634
+ responseModesSupported: metadata.response_modes_supported ?? [],
635
+ tokenEndpointAuthMethodsSupported: metadata.token_endpoint_auth_methods_supported ?? [],
636
+ requirePushedAuthorizationRequests: metadata.require_pushed_authorization_requests === true
637
+ };
638
+ report.supportsClientCredentials = report.provider.grantTypesSupported.includes('client_credentials');
639
+ report.supportsDynamicRegistration = Boolean(metadata.registration_endpoint);
640
+
641
+ try {
642
+ const keys = await (await this.jwks()).keys({ force: true });
643
+ report.signingKeys = keys.map((k) => ({ kid: k.kid, kty: k.kty, alg: k.alg ?? null, use: k.use ?? null }));
644
+ } catch (error) {
645
+ report.problems.push(`The provider's signing keys could not be read: ${error.message}`);
646
+ }
647
+
648
+ const supported = new Set(metadata.scopes_supported ?? []);
649
+ const unknown = supported.size > 0 ? config.scopes.filter((s) => !supported.has(s)) : [];
650
+ if (unknown.length > 0) {
651
+ report.problems.push(
652
+ `The tenant does not publish the scope(s) ${unknown.join(', ')}. A scope this client is not registered for is rejected outright, not dropped.`
653
+ );
654
+ }
655
+
656
+ if (!(metadata.code_challenge_methods_supported ?? []).includes('S256')) {
657
+ report.problems.push('The tenant does not advertise the S256 PKCE method, which this client always sends.');
658
+ }
659
+
660
+ const methods = metadata.token_endpoint_auth_methods_supported ?? [];
661
+ if (methods.length > 0 && !methods.includes(config.tokenEndpointAuthMethod)) {
662
+ report.problems.push(
663
+ `This client authenticates with '${config.tokenEndpointAuthMethod}', which the tenant does not list (${methods.join(', ')}).`
664
+ );
665
+ }
666
+
667
+ if (config.usePar && !metadata.pushed_authorization_request_endpoint) {
668
+ report.problems.push('usePar is on, but the tenant does not serve /oauth2/par.');
669
+ }
670
+ if (metadata.require_pushed_authorization_requests === true && !config.usePar) {
671
+ report.problems.push('The tenant requires pushed authorization requests; set usePar:true or plain /authorize calls will be refused.');
672
+ }
673
+
674
+ if (!report.redirectUri) {
675
+ report.problems.push('No redirectUri is configured, so an interactive sign-in cannot be started.');
676
+ }
677
+
678
+ return report;
679
+ }
680
+
681
+ // =================================================================
682
+ // internals
683
+ // =================================================================
684
+
685
+ /** POSTs to the token endpoint with whatever client authentication this client is registered for. */
686
+ async #tokenRequest(endpoint, body, credentials) {
687
+ const { form, headers } = await this.#clientAuthentication(body, endpoint, credentials);
688
+ return postForm(endpoint, form, { headers, timeoutMs: this.#config.timeoutMs, fetch: this.#config.fetch });
689
+ }
690
+
691
+ /**
692
+ * Applies the client's registered authentication method.
693
+ *
694
+ * RFC 6749 §2.3 forbids presenting more than one set of credentials in a single request and the
695
+ * Ark server rejects rather than resolves that, so exactly one of these branches may contribute
696
+ * a credential. `client_id` in the body is not a credential and always goes along: the `none`
697
+ * method needs it, and with Basic the server reads the header regardless.
698
+ */
699
+ async #clientAuthentication(body, endpoint, credentials = {}) {
700
+ const config = this.#config;
701
+ const clientId = credentials.clientId ?? config.clientId;
702
+ const clientSecret = credentials.clientSecret ?? config.clientSecret;
703
+ const method = credentials.clientSecret && config.tokenEndpointAuthMethod === 'none' ? 'client_secret_basic' : config.tokenEndpointAuthMethod;
704
+
705
+ const form = { ...body, client_id: clientId };
706
+ const headers = {};
707
+
708
+ switch (method) {
709
+ case 'client_secret_basic':
710
+ headers.Authorization = basicAuthHeader(clientId, clientSecret);
711
+ break;
712
+ case 'client_secret_post':
713
+ form.client_secret = clientSecret;
714
+ break;
715
+ case 'private_key_jwt': {
716
+ form.client_assertion_type = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer';
717
+ form.client_assertion = this.#clientAssertion(clientId, endpoint);
718
+ break;
719
+ }
720
+ case 'none':
721
+ default:
722
+ break;
723
+ }
724
+
725
+ return { form, headers };
726
+ }
727
+
728
+ /**
729
+ * A `private_key_jwt` client assertion (OIDC Core §9).
730
+ *
731
+ * `jti` is random and the lifetime is short because the server refuses a `jti` it has already
732
+ * seen — a captured assertion is worth nothing on its second use.
733
+ */
734
+ #clientAssertion(clientId, endpoint) {
735
+ const { privateKey, kid, alg = 'RS256', lifetimeSeconds = 60 } = this.#config.privateKeyJwt ?? {};
736
+ const now = Math.floor(Date.now() / 1000);
737
+ return signJwt(
738
+ {
739
+ iss: clientId,
740
+ sub: clientId, // §9: both must be the client id
741
+ aud: endpoint,
742
+ jti: randomToken(16),
743
+ iat: now,
744
+ nbf: now,
745
+ exp: now + lifetimeSeconds
746
+ },
747
+ { key: privateKey, alg, kid }
748
+ );
749
+ }
750
+
751
+ /** Turns a token response into a TokenSet, validating the ID token when there is one. */
752
+ async #toTokenSet(response, { nonce, code = null, maxAge = null }) {
753
+ let claims = null;
754
+
755
+ if (response.id_token) {
756
+ claims = await this.verifyIdToken(response.id_token, {
757
+ nonce,
758
+ accessToken: response.access_token ?? null,
759
+ code,
760
+ maxAge
761
+ });
762
+ } else if (nonce !== null && this.#requestedOpenId(response)) {
763
+ // openid was granted but nothing came back to prove who signed in.
764
+ throw new ArkTokenError('the token response contains no id_token, although the openid scope was granted.');
765
+ }
766
+
767
+ return new TokenSet(response, { claims });
768
+ }
769
+
770
+ #requestedOpenId(response) {
771
+ return String(response.scope ?? '')
772
+ .split(' ')
773
+ .includes('openid');
774
+ }
775
+ }
776
+
777
+ /** Convenience factory, for callers who prefer not to write `new`. */
778
+ export function createArkClient(options) {
779
+ return new ArkOAuthClient(options);
780
+ }