@odudu-io/oidc 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,891 @@
1
+ // src/adapter/discovery.ts
2
+ import * as oauth from "oauth4webapi";
3
+
4
+ // src/services/odudu-error.ts
5
+ var OAUTH_CODES = [
6
+ "invalid_request",
7
+ "invalid_client",
8
+ "invalid_grant",
9
+ "unauthorized_client",
10
+ "unsupported_grant_type",
11
+ "unsupported_response_type",
12
+ "invalid_scope",
13
+ "invalid_target",
14
+ "access_denied",
15
+ "server_error",
16
+ "temporarily_unavailable",
17
+ "login_required",
18
+ "consent_required",
19
+ "interaction_required",
20
+ "account_selection_required"
21
+ ];
22
+ var OduduError = class extends Error {
23
+ code;
24
+ error;
25
+ errorDescription;
26
+ constructor(code, message, detail2 = {}) {
27
+ super(message, detail2.cause === void 0 ? void 0 : { cause: detail2.cause });
28
+ this.name = "OduduError";
29
+ this.code = code;
30
+ this.error = detail2.error;
31
+ this.errorDescription = detail2.errorDescription;
32
+ }
33
+ };
34
+ function isOauthCode(value) {
35
+ return OAUTH_CODES.includes(value);
36
+ }
37
+ function fromServerError(error, errorDescription, message) {
38
+ const code = isOauthCode(error) ? error : "unrecognized_error";
39
+ return new OduduError(code, message, {
40
+ error,
41
+ ...errorDescription === void 0 ? {} : { errorDescription }
42
+ });
43
+ }
44
+
45
+ // src/adapter/discovery.ts
46
+ function throughFetch(fetcher) {
47
+ return (url, options) => fetcher(url, {
48
+ method: options.method,
49
+ headers: options.headers,
50
+ redirect: options.redirect,
51
+ ...options.body === void 0 ? {} : { body: options.body },
52
+ ...options.signal === void 0 ? {} : { signal: options.signal }
53
+ });
54
+ }
55
+ var REQUEST_TIMEOUT_MS = 3e4;
56
+ function requestOptions(deps) {
57
+ return {
58
+ signal: () => AbortSignal.timeout(REQUEST_TIMEOUT_MS),
59
+ ...deps.fetch === void 0 ? {} : { [oauth.customFetch]: throughFetch(deps.fetch) },
60
+ ...deps.allowInsecureRequests === true ? { [oauth.allowInsecureRequests]: true } : {}
61
+ };
62
+ }
63
+ async function fetchMetadata(issuer, deps) {
64
+ try {
65
+ const url = new URL(issuer);
66
+ const response = await oauth.discoveryRequest(url, {
67
+ algorithm: "oidc",
68
+ ...requestOptions(deps)
69
+ });
70
+ const metadata = await oauth.processDiscoveryResponse(url, response);
71
+ if (metadata.issuer !== issuer) throw new Error("the metadata spells the issuer differently");
72
+ return metadata;
73
+ } catch (cause) {
74
+ throw new OduduError("discovery_failed", `could not read the metadata of ${issuer}`, { cause });
75
+ }
76
+ }
77
+
78
+ // src/services/discovery-cache.ts
79
+ var MAX_ISSUERS = 256;
80
+ var TTL_MS = 60 * 60 * 1e3;
81
+ var DiscoveryCache = class {
82
+ entries = /* @__PURE__ */ new Map();
83
+ get(key, now) {
84
+ const entry = this.entries.get(key);
85
+ if (entry === void 0) return void 0;
86
+ if (entry.expiresAt <= now) {
87
+ this.entries.delete(key);
88
+ return void 0;
89
+ }
90
+ return entry.metadata;
91
+ }
92
+ set(key, metadata, now) {
93
+ this.entries.delete(key);
94
+ this.entries.set(key, { expiresAt: now + TTL_MS, metadata });
95
+ const oldest = this.entries.keys().next();
96
+ if (this.entries.size > MAX_ISSUERS && oldest.done !== true) this.entries.delete(oldest.value);
97
+ }
98
+ // Forget a request that failed, if it is still the one held.
99
+ drop(key, metadata) {
100
+ if (this.entries.get(key)?.metadata === metadata) this.entries.delete(key);
101
+ }
102
+ };
103
+
104
+ // src/repository/metadata.ts
105
+ var cache = new DiscoveryCache();
106
+ function readMetadata(issuer, deps) {
107
+ const key = `${deps.allowInsecureRequests === true ? "insecure:" : ""}${issuer}`;
108
+ const now = (deps.now ?? Date.now)();
109
+ const cached = cache.get(key, now);
110
+ if (cached !== void 0) return cached;
111
+ const request = fetchMetadata(issuer, deps);
112
+ cache.set(key, request, now);
113
+ request.catch(() => {
114
+ cache.drop(key, request);
115
+ });
116
+ return request;
117
+ }
118
+
119
+ // src/use-cases/discover.ts
120
+ function discover(issuer, deps = {}) {
121
+ return readMetadata(issuer, deps);
122
+ }
123
+
124
+ // src/adapter/authorize.ts
125
+ import * as oauth2 from "oauth4webapi";
126
+ function newSecrets() {
127
+ return {
128
+ state: oauth2.generateRandomState(),
129
+ nonce: oauth2.generateRandomNonce(),
130
+ codeVerifier: oauth2.generateRandomCodeVerifier()
131
+ };
132
+ }
133
+ async function authorizationUrl(metadata, options, secrets, scope, resources, silent) {
134
+ if (metadata.authorization_endpoint === void 0) {
135
+ throw new OduduError("discovery_failed", "the metadata names no authorization endpoint");
136
+ }
137
+ const url = new URL(metadata.authorization_endpoint);
138
+ const params = url.searchParams;
139
+ params.set("response_type", "code");
140
+ params.set("client_id", options.clientId);
141
+ params.set("redirect_uri", options.redirectUri);
142
+ params.set("scope", scope);
143
+ params.set("code_challenge", await oauth2.calculatePKCECodeChallenge(secrets.codeVerifier));
144
+ params.set("code_challenge_method", "S256");
145
+ params.set("state", secrets.state);
146
+ params.set("nonce", secrets.nonce);
147
+ for (const resource of resources) params.append("resource", resource);
148
+ if (options.prompt !== void 0) params.set("prompt", options.prompt);
149
+ if (silent) params.set("prompt", "none");
150
+ if (options.action !== void 0) params.set("action", options.action);
151
+ return url.href;
152
+ }
153
+
154
+ // src/services/sign-in-request.ts
155
+ var ME_READ = "me:read";
156
+ var ME_WRITE = "me:write";
157
+ function meResource(issuer) {
158
+ return `${issuer.replace(/\/+$/u, "")}/me`;
159
+ }
160
+ function refuseConflictingOptions(options) {
161
+ const { prompt, action } = options;
162
+ if (prompt !== void 0 && action !== void 0) {
163
+ throw new OduduError(
164
+ "invalid_options",
165
+ "prompt and action cannot be combined: a sign-in starts at one or the other"
166
+ );
167
+ }
168
+ }
169
+ function scopeOf(options) {
170
+ const scopes = /* @__PURE__ */ new Set(["openid", ...options.scope.split(/\s+/u).filter((s) => s !== "")]);
171
+ if (options.meAccess !== void 0) scopes.add(ME_READ);
172
+ if (options.meAccess === "write") scopes.add(ME_WRITE);
173
+ return [...scopes].join(" ");
174
+ }
175
+ function resourcesOf(options) {
176
+ const resources = new Set(options.resource ?? []);
177
+ if (options.meAccess !== void 0) resources.add(meResource(options.issuer));
178
+ return [...resources];
179
+ }
180
+ function idTokenAlgOf(options) {
181
+ return options.idTokenAlg ?? "RS256";
182
+ }
183
+ function audienceSignIn(request) {
184
+ const { issuer, clientId, redirectUri, scope, resource, idTokenAlg } = request;
185
+ return {
186
+ issuer,
187
+ clientId,
188
+ redirectUri,
189
+ scope,
190
+ ...idTokenAlg === void 0 ? {} : { idTokenAlg },
191
+ resource: [resource],
192
+ ...resource === meResource(request.issuer) ? { meAccess: "read" } : {}
193
+ };
194
+ }
195
+
196
+ // src/repository/authorization-request.ts
197
+ async function buildAuthorizationRequest(metadata, given, silent = false) {
198
+ const options = structuredClone(given);
199
+ const secrets = newSecrets();
200
+ const resources = resourcesOf(options);
201
+ const url = await authorizationUrl(
202
+ metadata,
203
+ options,
204
+ secrets,
205
+ scopeOf(options),
206
+ resources,
207
+ silent
208
+ );
209
+ return {
210
+ url,
211
+ pending: {
212
+ issuer: options.issuer,
213
+ clientId: options.clientId,
214
+ redirectUri: options.redirectUri,
215
+ ...secrets,
216
+ resources,
217
+ idTokenAlg: idTokenAlgOf(options)
218
+ }
219
+ };
220
+ }
221
+
222
+ // src/use-cases/begin-sign-in.ts
223
+ async function beginSignIn(options, deps = {}) {
224
+ refuseConflictingOptions(options);
225
+ return buildAuthorizationRequest(await discover(options.issuer, deps), options);
226
+ }
227
+
228
+ // src/adapter/token-exchange.ts
229
+ import * as oauth5 from "oauth4webapi";
230
+
231
+ // src/adapter/client-authentication.ts
232
+ import * as oauth3 from "oauth4webapi";
233
+
234
+ // src/adapter/client-assertion.ts
235
+ import { importJWK, SignJWT } from "jose";
236
+
237
+ // src/services/client-credentials-request.ts
238
+ var ASSERTION_LIFETIME_SECONDS = 120;
239
+ var DEFAULT_LIFETIME_SECONDS = 60;
240
+ function lifetimeSeconds(expiresIn) {
241
+ return expiresIn !== void 0 && Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : DEFAULT_LIFETIME_SECONDS;
242
+ }
243
+ function withUsableLifetime(body) {
244
+ if (typeof body !== "object" || body === null || !("expires_in" in body)) return body;
245
+ const { expires_in: expiresIn, ...rest } = body;
246
+ const parsed = typeof expiresIn === "number" ? expiresIn : parseFloat(String(expiresIn));
247
+ return Number.isFinite(parsed) && parsed >= 0 ? body : rest;
248
+ }
249
+ function checkedOptions(options) {
250
+ const auth = options.auth;
251
+ if (options.issuer === "" || options.clientId === "") {
252
+ throw new OduduError("invalid_options", "the issuer and the client ID are required");
253
+ }
254
+ if (auth.secret !== void 0 && auth.privateKey !== void 0) {
255
+ throw new OduduError("invalid_options", "auth takes a secret or a private key, not both");
256
+ }
257
+ if (typeof auth.secret === "string" && auth.secret !== "") return options;
258
+ if (typeof auth.privateKey?.kty === "string") return options;
259
+ throw new OduduError(
260
+ "invalid_options",
261
+ "auth needs a non-empty secret or a private key in JWK form"
262
+ );
263
+ }
264
+ function grantParameters(options) {
265
+ const parameters = new URLSearchParams();
266
+ if (options.scope !== void 0) parameters.set("scope", options.scope);
267
+ if (options.resource !== void 0) parameters.set("resource", options.resource);
268
+ return parameters;
269
+ }
270
+ function assertionAlgorithm(key, alg) {
271
+ if (alg !== void 0) return alg;
272
+ const byCurve = { "P-256": "ES256", "P-384": "ES384", "P-521": "ES512" };
273
+ if (key.kty === "RSA") return "RS256";
274
+ const fromCurve = key.kty === "EC" && key.crv !== void 0 ? byCurve[key.crv] : void 0;
275
+ if (fromCurve === void 0) {
276
+ throw new OduduError(
277
+ "invalid_options",
278
+ "cannot tell which algorithm this key signs with: pass auth.alg"
279
+ );
280
+ }
281
+ return fromCurve;
282
+ }
283
+ function assertionClaims(clientId, tokenEndpoint, jti, nowSeconds) {
284
+ return {
285
+ iss: clientId,
286
+ sub: clientId,
287
+ aud: tokenEndpoint,
288
+ jti,
289
+ iat: nowSeconds,
290
+ exp: nowSeconds + ASSERTION_LIFETIME_SECONDS
291
+ };
292
+ }
293
+ function privateKeyOf(auth) {
294
+ return auth.privateKey === void 0 ? void 0 : {
295
+ key: auth.privateKey,
296
+ ...auth.kid === void 0 ? {} : { kid: auth.kid },
297
+ ...auth.alg === void 0 ? {} : { alg: auth.alg }
298
+ };
299
+ }
300
+ function audienceTokenOf(response, requestedScope, now) {
301
+ return {
302
+ accessToken: response.access_token,
303
+ expiresAt: now + lifetimeSeconds(response.expires_in) * 1e3,
304
+ scope: response.scope ?? requestedScope ?? ""
305
+ };
306
+ }
307
+
308
+ // src/adapter/client-assertion.ts
309
+ async function signAssertion(signing, clientId, tokenEndpoint, nowSeconds) {
310
+ const alg = assertionAlgorithm(signing.key, signing.alg);
311
+ try {
312
+ const key = await importJWK({ ...signing.key }, alg);
313
+ return await new SignJWT(
314
+ assertionClaims(clientId, tokenEndpoint, crypto.randomUUID(), nowSeconds)
315
+ ).setProtectedHeader({ alg, ...signing.kid === void 0 ? {} : { kid: signing.kid } }).sign(key);
316
+ } catch (cause) {
317
+ throw new OduduError("invalid_options", "the private key cannot sign with that algorithm", {
318
+ cause
319
+ });
320
+ }
321
+ }
322
+
323
+ // src/adapter/client-authentication.ts
324
+ var ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
325
+ function clientAuthentication(auth, deps) {
326
+ if (auth === void 0) return oauth3.None();
327
+ const signing = privateKeyOf(auth);
328
+ if (signing === void 0) return oauth3.ClientSecretBasic(auth.secret ?? "");
329
+ return async (metadata, client, body) => {
330
+ const endpoint = metadata.token_endpoint;
331
+ if (endpoint === void 0) {
332
+ throw new OduduError("discovery_failed", "the metadata names no token endpoint");
333
+ }
334
+ const now = Math.floor((deps.now ?? Date.now)() / 1e3);
335
+ body.set("client_id", client.client_id);
336
+ body.set("client_assertion_type", ASSERTION_TYPE);
337
+ body.set("client_assertion", await signAssertion(signing, client.client_id, endpoint, now));
338
+ };
339
+ }
340
+
341
+ // src/adapter/token-failure.ts
342
+ import * as oauth4 from "oauth4webapi";
343
+
344
+ // src/adapter/bounded-body.ts
345
+ var ERROR_BODY_LIMIT = 8192;
346
+ async function readBoundedText(response, limit) {
347
+ try {
348
+ const declared = Number(response.headers.get("content-length"));
349
+ if (Number.isFinite(declared) && declared > limit) {
350
+ await response.body?.cancel();
351
+ return void 0;
352
+ }
353
+ if (response.bodyUsed) return void 0;
354
+ const reader = response.body?.getReader();
355
+ if (reader === void 0) return "";
356
+ const decoder = new TextDecoder("utf-8", { fatal: true });
357
+ let text = "";
358
+ let size = 0;
359
+ for (; ; ) {
360
+ const { done, value } = await reader.read();
361
+ if (done) return text + decoder.decode();
362
+ size += value.byteLength;
363
+ if (size > limit) {
364
+ await reader.cancel();
365
+ return void 0;
366
+ }
367
+ text += decoder.decode(value, { stream: true });
368
+ }
369
+ } catch {
370
+ return void 0;
371
+ }
372
+ }
373
+
374
+ // src/adapter/token-failure.ts
375
+ async function challengeRefusal(cause, refusal) {
376
+ const text = await readBoundedText(cause.response, ERROR_BODY_LIMIT);
377
+ if (text === void 0) return void 0;
378
+ let body;
379
+ try {
380
+ body = JSON.parse(text);
381
+ } catch {
382
+ return void 0;
383
+ }
384
+ if (typeof body !== "object" || body === null || !("error" in body)) return void 0;
385
+ if (typeof body.error !== "string") return void 0;
386
+ const description = "error_description" in body ? body.error_description : void 0;
387
+ return fromServerError(
388
+ body.error,
389
+ typeof description === "string" ? description : void 0,
390
+ refusal
391
+ );
392
+ }
393
+ function isUnusableResponse(cause) {
394
+ return cause.code === oauth4.RESPONSE_IS_NOT_CONFORM || cause.code === oauth4.RESPONSE_IS_NOT_JSON;
395
+ }
396
+ async function tokenFailure(cause, refusal) {
397
+ if (cause instanceof oauth4.ResponseBodyError) {
398
+ return fromServerError(cause.error, cause.error_description, refusal);
399
+ }
400
+ if (cause instanceof oauth4.WWWAuthenticateChallengeError) {
401
+ const named = await challengeRefusal(cause, refusal);
402
+ if (named !== void 0) return named;
403
+ }
404
+ if (cause instanceof oauth4.OperationProcessingError && !isUnusableResponse(cause)) {
405
+ return new OduduError("invalid_id_token", `the response was refused: ${cause.message}`, {
406
+ cause
407
+ });
408
+ }
409
+ return new OduduError("request_failed", "the token request did not complete", { cause });
410
+ }
411
+
412
+ // src/adapter/token-exchange.ts
413
+ async function exchangeCode(metadata, params, pending, deps, auth) {
414
+ const client = {
415
+ client_id: pending.clientId,
416
+ id_token_signed_response_alg: pending.idTokenAlg
417
+ };
418
+ const options = requestOptions(deps);
419
+ try {
420
+ const response = await oauth5.processAuthorizationCodeResponse(
421
+ metadata,
422
+ client,
423
+ await oauth5.authorizationCodeGrantRequest(
424
+ metadata,
425
+ client,
426
+ clientAuthentication(auth, deps),
427
+ // Only a value this library has validated is accepted for the exchange;
428
+ // readCallback has already refused everything it would.
429
+ oauth5.validateAuthResponse(metadata, client, params, pending.state),
430
+ pending.redirectUri,
431
+ pending.codeVerifier,
432
+ options
433
+ ),
434
+ { expectedNonce: pending.nonce, requireIdToken: true, ...options }
435
+ );
436
+ const claims = oauth5.getValidatedIdTokenClaims(response);
437
+ if (claims === void 0)
438
+ throw new OduduError("invalid_id_token", "the response has no ID token");
439
+ return { response, claims };
440
+ } catch (cause) {
441
+ throw cause instanceof OduduError ? cause : await tokenFailure(cause, "the token endpoint refused the code");
442
+ }
443
+ }
444
+
445
+ // src/services/token-set.ts
446
+ function expiresAtOf(response, now) {
447
+ if (response.expires_in === void 0) {
448
+ throw new OduduError("request_failed", "the token response carries no expires_in");
449
+ }
450
+ return now + response.expires_in * 1e3;
451
+ }
452
+ function refreshExpiresAtOf(response, now) {
453
+ return now + (response.expires_in ?? DEFAULT_LIFETIME_SECONDS) * 1e3;
454
+ }
455
+ function tokenSetOf(response, claims, pending, now) {
456
+ const audiences = pending.resources.length === 0 ? [pending.issuer] : pending.resources;
457
+ const entry = {
458
+ accessToken: response.access_token,
459
+ expiresAt: expiresAtOf(response, now),
460
+ scope: response.scope ?? ""
461
+ };
462
+ return {
463
+ byAudience: Object.fromEntries(audiences.map((audience) => [audience, { ...entry }])),
464
+ idToken: response.id_token ?? "",
465
+ ...response.refresh_token === void 0 ? {} : { refreshToken: response.refresh_token },
466
+ claims,
467
+ issuer: pending.issuer,
468
+ clientId: pending.clientId
469
+ };
470
+ }
471
+
472
+ // src/repository/code-exchange.ts
473
+ async function exchangeForTokens(metadata, params, pending, deps, auth) {
474
+ const requestedAt = (deps.now ?? Date.now)();
475
+ const { response, claims } = await exchangeCode(metadata, params, pending, deps, auth);
476
+ return tokenSetOf(response, claims, pending, requestedAt);
477
+ }
478
+
479
+ // src/services/callback.ts
480
+ function parsedUrl(value, message) {
481
+ try {
482
+ return new URL(value);
483
+ } catch (cause) {
484
+ throw new OduduError("invalid_callback", message, { cause });
485
+ }
486
+ }
487
+ function readCallback(callbackUrl, expected) {
488
+ const url = parsedUrl(callbackUrl, "the callback address is not a URL");
489
+ const redirect = parsedUrl(expected.redirectUri, "the redirect URI of this sign-in is not a URL");
490
+ if (url.origin !== redirect.origin || url.pathname !== redirect.pathname) {
491
+ throw new OduduError("invalid_callback", "the response did not arrive at the redirect URI");
492
+ }
493
+ const params = url.searchParams;
494
+ const state = params.get("state");
495
+ if (state === null) {
496
+ throw new OduduError("invalid_state", "the response carries no state");
497
+ }
498
+ if (state !== expected.state) {
499
+ throw new OduduError("invalid_state", "the response state is not the one this sign-in sent");
500
+ }
501
+ const issuer = params.get("iss");
502
+ if (issuer === null) {
503
+ throw new OduduError("invalid_issuer", "the response carries no iss parameter (RFC 9207)");
504
+ }
505
+ if (issuer !== expected.issuer) {
506
+ throw new OduduError("invalid_issuer", "the response iss is not the issuer this sign-in used");
507
+ }
508
+ const error = params.get("error");
509
+ if (error !== null) {
510
+ throw fromServerError(
511
+ error,
512
+ params.get("error_description") ?? void 0,
513
+ "the authorization server refused the request"
514
+ );
515
+ }
516
+ if (!params.has("code")) {
517
+ throw new OduduError("invalid_callback", "the response carries no code");
518
+ }
519
+ return params;
520
+ }
521
+
522
+ // src/use-cases/complete-sign-in.ts
523
+ async function completeSignIn(callbackUrl, pending, options = {}, deps = {}) {
524
+ const params = readCallback(callbackUrl, pending);
525
+ return exchangeForTokens(
526
+ await discover(pending.issuer, deps),
527
+ params,
528
+ pending,
529
+ deps,
530
+ options.auth
531
+ );
532
+ }
533
+
534
+ // src/adapter/refresh.ts
535
+ import * as oauth6 from "oauth4webapi";
536
+ async function refreshGrant(metadata, client, refreshToken, resource, deps, auth) {
537
+ const options = requestOptions(deps);
538
+ try {
539
+ const response = await oauth6.processRefreshTokenResponse(
540
+ metadata,
541
+ client,
542
+ await oauth6.refreshTokenGrantRequest(
543
+ metadata,
544
+ client,
545
+ clientAuthentication(auth, deps),
546
+ refreshToken,
547
+ {
548
+ ...resource === void 0 ? {} : { additionalParameters: { resource } },
549
+ ...options
550
+ }
551
+ )
552
+ );
553
+ return { response, claims: oauth6.getValidatedIdTokenClaims(response) };
554
+ } catch (cause) {
555
+ if (cause instanceof oauth6.ResponseBodyError && cause.error === "invalid_target") {
556
+ throw new OduduError(
557
+ "audience_not_granted",
558
+ "the grant does not carry this audience: use requestAudience to ask for it",
559
+ { error: cause.error, ...detail(cause.error_description) }
560
+ );
561
+ }
562
+ throw await tokenFailure(cause, "the token endpoint refused the refresh token");
563
+ }
564
+ }
565
+ function detail(description) {
566
+ return description === void 0 ? {} : { errorDescription: description };
567
+ }
568
+
569
+ // src/services/refresh-request.ts
570
+ function refreshTokenOf(tokens) {
571
+ if (tokens.refreshToken === void 0) {
572
+ throw new OduduError(
573
+ "invalid_options",
574
+ "these tokens carry no refresh token: Odudu issues one to a client that has the refresh_token grant, so sign in again with such a client"
575
+ );
576
+ }
577
+ return tokens.refreshToken;
578
+ }
579
+ var UNKNOWN_OUTCOME = " The outcome of that refresh is unknown, so this one was not sent: use the tokens the last successful refresh returned, or sign in again.";
580
+ function isRefusedBeforeSpending(error) {
581
+ return error instanceof OduduError && error.code === "audience_not_granted";
582
+ }
583
+ function abandoned(error) {
584
+ if (error instanceof OduduError) {
585
+ if (error.message.endsWith(UNKNOWN_OUTCOME)) return error;
586
+ return new OduduError(error.code, `${error.message}${UNKNOWN_OUTCOME}`, {
587
+ cause: error,
588
+ ...error.error === void 0 ? {} : { error: error.error },
589
+ ...error.errorDescription === void 0 ? {} : { errorDescription: error.errorDescription }
590
+ });
591
+ }
592
+ return new OduduError("request_failed", `The refresh before this one failed.${UNKNOWN_OUTCOME}`, {
593
+ cause: error
594
+ });
595
+ }
596
+ function checkResource(tokens, resource) {
597
+ if (resource !== void 0 && !Object.hasOwn(tokens.byAudience, resource)) {
598
+ throw new OduduError(
599
+ "audience_not_granted",
600
+ "the sign-in does not carry this audience: use requestAudience to ask for it"
601
+ );
602
+ }
603
+ }
604
+ function audiencesNamedBy(accessToken) {
605
+ const payload = accessToken.split(".")[1];
606
+ if (payload === void 0) return void 0;
607
+ try {
608
+ const bytes = Uint8Array.from(
609
+ atob(payload.replaceAll("-", "+").replaceAll("_", "/")),
610
+ (c) => c.charCodeAt(0)
611
+ );
612
+ const claims = JSON.parse(new TextDecoder().decode(bytes));
613
+ const aud = typeof claims === "object" && claims !== null && "aud" in claims ? claims.aud : void 0;
614
+ const named = (Array.isArray(aud) ? aud : [aud]).filter((a) => typeof a === "string");
615
+ return named.length === 0 ? void 0 : named;
616
+ } catch {
617
+ return void 0;
618
+ }
619
+ }
620
+ function renewedAudiences(previous, accessToken) {
621
+ const held = Object.keys(previous.byAudience);
622
+ const named = audiencesNamedBy(accessToken)?.filter((audience) => held.includes(audience));
623
+ return named === void 0 || named.length === 0 ? held : named;
624
+ }
625
+ function refreshedTokenSet(previous, response, claims, resource, now) {
626
+ if (claims !== void 0 && claims.sub !== previous.claims.sub) {
627
+ throw new OduduError("invalid_id_token", "the refreshed ID token names another subject");
628
+ }
629
+ const accessToken = response.access_token;
630
+ const expiresAt = refreshExpiresAtOf(response, now);
631
+ const audiences = resource === void 0 ? renewedAudiences(previous, accessToken) : [resource];
632
+ const refreshToken = response.refresh_token ?? previous.refreshToken;
633
+ return {
634
+ byAudience: {
635
+ ...resource === void 0 ? {} : previous.byAudience,
636
+ ...Object.fromEntries(
637
+ audiences.map((audience) => [
638
+ audience,
639
+ // A response without `scope` leaves the scope unchanged (RFC 6749 section 5.1).
640
+ {
641
+ accessToken,
642
+ expiresAt,
643
+ scope: response.scope ?? previous.byAudience[audience]?.scope ?? ""
644
+ }
645
+ ])
646
+ )
647
+ },
648
+ idToken: response.id_token ?? previous.idToken,
649
+ ...refreshToken === void 0 ? {} : { refreshToken },
650
+ claims: claims ?? previous.claims,
651
+ issuer: previous.issuer,
652
+ clientId: previous.clientId
653
+ };
654
+ }
655
+
656
+ // src/services/single-flight.ts
657
+ var SingleFlight = class {
658
+ chains = /* @__PURE__ */ new Map();
659
+ rules;
660
+ constructor(rules) {
661
+ this.rules = rules;
662
+ }
663
+ run(key, tag, start) {
664
+ const chain = this.chains.get(key) ?? this.open(key);
665
+ if (chain.tail?.tag === tag) return chain.tail.promise;
666
+ const turn = chain.tail?.promise.then(noop, (error) => {
667
+ if (!this.rules.retryable(error)) throw this.rules.abandoned(error);
668
+ }) ?? Promise.resolve();
669
+ chain.pending += 1;
670
+ const promise = turn.then(() => start(chain.latest)).then((value) => {
671
+ chain.latest = value;
672
+ for (const successor of this.rules.successorKeys(value)) {
673
+ chain.keys.add(successor);
674
+ this.chains.set(successor, chain);
675
+ }
676
+ return value;
677
+ }).finally(() => {
678
+ chain.pending -= 1;
679
+ if (chain.pending === 0) this.close(chain);
680
+ });
681
+ chain.tail = { tag, promise };
682
+ return promise;
683
+ }
684
+ open(key) {
685
+ const chain = {
686
+ keys: /* @__PURE__ */ new Set([key]),
687
+ tail: void 0,
688
+ latest: void 0,
689
+ pending: 0
690
+ };
691
+ this.chains.set(key, chain);
692
+ return chain;
693
+ }
694
+ close(chain) {
695
+ for (const key of chain.keys) {
696
+ if (this.chains.get(key) === chain) this.chains.delete(key);
697
+ }
698
+ }
699
+ };
700
+ function noop() {
701
+ }
702
+
703
+ // src/repository/refresh.ts
704
+ var flights = new SingleFlight({
705
+ successorKeys: (tokens) => tokens.refreshToken === void 0 ? [] : [tokens.refreshToken],
706
+ retryable: isRefusedBeforeSpending,
707
+ abandoned
708
+ });
709
+ function refreshTokens(metadata, tokens, options, deps) {
710
+ return flights.run(refreshTokenOf(tokens), options.resource ?? "", async (latest) => {
711
+ const previous = latest ?? tokens;
712
+ const requestedAt = (deps.now ?? Date.now)();
713
+ const { response, claims } = await refreshGrant(
714
+ metadata,
715
+ { client_id: previous.clientId, id_token_signed_response_alg: idTokenAlgOf(options) },
716
+ refreshTokenOf(previous),
717
+ options.resource,
718
+ deps,
719
+ options.auth
720
+ );
721
+ return refreshedTokenSet(previous, response, claims, options.resource, requestedAt);
722
+ });
723
+ }
724
+
725
+ // src/use-cases/refresh.ts
726
+ async function refresh(tokens, options = {}, deps = {}) {
727
+ checkResource(tokens, options.resource);
728
+ const metadata = await discover(tokens.issuer, deps);
729
+ return refreshTokens(metadata, tokens, options, deps);
730
+ }
731
+
732
+ // src/use-cases/request-audience.ts
733
+ async function requestAudience(request, deps = {}) {
734
+ return buildAuthorizationRequest(
735
+ await discover(request.issuer, deps),
736
+ audienceSignIn(request),
737
+ request.silent === true
738
+ );
739
+ }
740
+
741
+ // src/adapter/client-credentials.ts
742
+ import * as oauth7 from "oauth4webapi";
743
+ async function clientCredentialsGrant(metadata, clientId, auth, parameters, deps) {
744
+ const client = { client_id: clientId };
745
+ try {
746
+ const response = await oauth7.clientCredentialsGrantRequest(
747
+ metadata,
748
+ client,
749
+ clientAuthentication(auth, deps),
750
+ parameters,
751
+ requestOptions(deps)
752
+ );
753
+ return await oauth7.processClientCredentialsResponse(
754
+ metadata,
755
+ client,
756
+ await readableLifetime(response)
757
+ );
758
+ } catch (cause) {
759
+ if (cause instanceof OduduError) throw cause;
760
+ throw await clientTokenFailure(cause);
761
+ }
762
+ }
763
+ async function clientTokenFailure(cause) {
764
+ const failure = await tokenFailure(cause, "the token endpoint refused the client");
765
+ return failure.code === "invalid_id_token" ? new OduduError("request_failed", "the token request did not complete", { cause }) : failure;
766
+ }
767
+ async function readableLifetime(response) {
768
+ if (!response.ok) return response;
769
+ const body = await response.clone().json().catch(() => void 0);
770
+ const usable = withUsableLifetime(body);
771
+ return usable === body ? response : new Response(JSON.stringify(usable), { status: response.status, headers: response.headers });
772
+ }
773
+
774
+ // src/repository/client-credentials.ts
775
+ function checkOptions(options) {
776
+ return checkedOptions(options);
777
+ }
778
+ async function requestClientToken(metadata, options, deps) {
779
+ const requestedAt = (deps.now ?? Date.now)();
780
+ const response = await clientCredentialsGrant(
781
+ metadata,
782
+ options.clientId,
783
+ options.auth,
784
+ grantParameters(options),
785
+ deps
786
+ );
787
+ return audienceTokenOf(response, options.scope, requestedAt);
788
+ }
789
+
790
+ // src/use-cases/client-credentials.ts
791
+ async function clientCredentials(options, deps = {}) {
792
+ const checked = checkOptions(options);
793
+ return requestClientToken(await discover(checked.issuer, deps), checked, deps);
794
+ }
795
+
796
+ // src/repository/client-assertion.ts
797
+ function signClientAssertionFor(signing, clientId, tokenEndpoint, nowSeconds) {
798
+ return signAssertion(signing, clientId, tokenEndpoint, nowSeconds);
799
+ }
800
+
801
+ // src/use-cases/sign-client-assertion.ts
802
+ async function signClientAssertion(options) {
803
+ if (options.clientId === "" || options.audience === "") {
804
+ throw new OduduError("invalid_options", "the client ID and the audience are required");
805
+ }
806
+ return await signClientAssertionFor(
807
+ {
808
+ key: options.privateKey,
809
+ ...options.kid === void 0 ? {} : { kid: options.kid },
810
+ ...options.alg === void 0 ? {} : { alg: options.alg }
811
+ },
812
+ options.clientId,
813
+ options.audience,
814
+ Math.floor((options.now ?? Date.now()) / 1e3)
815
+ );
816
+ }
817
+
818
+ // src/services/token-renewer.ts
819
+ function checkSkew(skewMs) {
820
+ if (!Number.isFinite(skewMs) || skewMs < 0) {
821
+ throw new OduduError("invalid_options", "skewMs must be a finite number, zero or more");
822
+ }
823
+ return skewMs;
824
+ }
825
+ function tokenRenewer(fetchToken, now, skewMs) {
826
+ let held;
827
+ let renewal;
828
+ return () => {
829
+ if (held !== void 0 && now() < held.renewAt) {
830
+ return Promise.resolve(held.token.accessToken);
831
+ }
832
+ renewal ??= fetchToken().then((token) => {
833
+ const skew = Math.min(skewMs, Math.floor((token.expiresAt - now()) / 2));
834
+ held = { token, renewAt: token.expiresAt - skew };
835
+ return token.accessToken;
836
+ }).finally(() => {
837
+ renewal = void 0;
838
+ });
839
+ return renewal;
840
+ };
841
+ }
842
+
843
+ // src/use-cases/token-source.ts
844
+ var DEFAULT_SKEW_MS = 3e4;
845
+ function createTokenSource(options, deps = {}) {
846
+ const { skewMs = DEFAULT_SKEW_MS, ...grant } = options;
847
+ return tokenRenewer(
848
+ () => clientCredentials(grant, deps),
849
+ deps.now ?? Date.now,
850
+ checkSkew(skewMs)
851
+ );
852
+ }
853
+
854
+ // src/services/sign-out-request.ts
855
+ function signOutAddress(metadata, options, allowInsecure) {
856
+ if (metadata.end_session_endpoint === void 0) {
857
+ throw new OduduError("discovery_failed", "the metadata names no end_session_endpoint");
858
+ }
859
+ const url = new URL(metadata.end_session_endpoint);
860
+ if (url.protocol !== "https:" && !(allowInsecure && url.protocol === "http:")) {
861
+ throw new OduduError("discovery_failed", "the end_session_endpoint is not an https address");
862
+ }
863
+ url.searchParams.set("id_token_hint", options.idToken);
864
+ if (options.postLogoutRedirectUri !== void 0) {
865
+ url.searchParams.set("post_logout_redirect_uri", options.postLogoutRedirectUri);
866
+ }
867
+ if (options.state !== void 0) url.searchParams.set("state", options.state);
868
+ return url.href;
869
+ }
870
+
871
+ // src/use-cases/sign-out-url.ts
872
+ async function signOutUrl(options, deps = {}) {
873
+ return signOutAddress(
874
+ await discover(options.issuer, deps),
875
+ options,
876
+ deps.allowInsecureRequests === true
877
+ );
878
+ }
879
+ export {
880
+ OduduError,
881
+ beginSignIn,
882
+ clientCredentials,
883
+ completeSignIn,
884
+ createTokenSource,
885
+ discover,
886
+ refresh,
887
+ requestAudience,
888
+ signClientAssertion,
889
+ signOutUrl
890
+ };
891
+ //# sourceMappingURL=index.js.map