@baukit/auth-native 0.7.2 → 0.7.3

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/index.ts ADDED
@@ -0,0 +1,816 @@
1
+ export {
2
+ AUTHORIZATION_STATE_ENTROPY_BYTES,
3
+ appearanceStateDecoration,
4
+ decoratedAuthorizationState,
5
+ type AppearanceMode,
6
+ type AppearanceState,
7
+ } from './authorization-state.js';
8
+
9
+ export type OidcErrorCode =
10
+ | 'authorization_failed'
11
+ | 'callback_state_mismatch'
12
+ | 'discovery_failed'
13
+ | 'invalid_discovery_document'
14
+ | 'invalid_token_response'
15
+ | 'invalid_userinfo_response'
16
+ | 'issuer_mismatch'
17
+ | 'pkce_verifier_missing'
18
+ | 'refresh_failed'
19
+ | 'storage_failed'
20
+ | 'token_exchange_failed'
21
+ | 'userinfo_failed';
22
+
23
+ const SAFE_ERROR_MESSAGES = {
24
+ authorization_failed: 'OIDC authorization failed.',
25
+ callback_state_mismatch: 'OIDC callback state did not match the login transaction.',
26
+ discovery_failed: 'OIDC provider discovery failed.',
27
+ invalid_discovery_document: 'OIDC provider returned invalid discovery metadata.',
28
+ invalid_token_response: 'OIDC token endpoint returned an invalid response.',
29
+ invalid_userinfo_response: 'OIDC UserInfo endpoint returned an invalid response.',
30
+ issuer_mismatch: 'OIDC provider issuer did not match the configured issuer.',
31
+ pkce_verifier_missing: 'OIDC login did not produce a PKCE verifier.',
32
+ refresh_failed: 'OIDC token refresh failed.',
33
+ storage_failed: 'Secure authentication storage failed.',
34
+ token_exchange_failed: 'OIDC token exchange failed.',
35
+ userinfo_failed: 'OIDC UserInfo request failed.',
36
+ } as const satisfies Record<OidcErrorCode, string>;
37
+
38
+ /** An authentication failure whose message is safe to display or log. */
39
+ export class OidcError extends Error {
40
+ public readonly code: OidcErrorCode;
41
+ public readonly status: number | undefined;
42
+ /** True only when retrying the failed operation may succeed without signing in again. */
43
+ public readonly retryable: boolean;
44
+
45
+ public constructor(
46
+ code: OidcErrorCode,
47
+ options: { readonly retryable?: boolean; readonly status?: number } = {},
48
+ ) {
49
+ super(SAFE_ERROR_MESSAGES[code]);
50
+ this.name = 'OidcError';
51
+ this.code = code;
52
+ this.status = options.status;
53
+ this.retryable = options.retryable ?? false;
54
+ }
55
+ }
56
+
57
+ export interface NativeOidcConfig {
58
+ readonly issuer: string;
59
+ readonly clientId: string;
60
+ readonly redirectUri: string;
61
+ /** `openid` is prepended when omitted. Defaults to `openid profile email`. */
62
+ readonly scopes?: readonly string[];
63
+ /** Adds `offline_access` to the requested scopes. Defaults to false. */
64
+ readonly offlineAccess?: boolean;
65
+ /** Defaults to `redirectUri`. */
66
+ readonly postLogoutRedirectUri?: string;
67
+ /** Defaults to 30 seconds. */
68
+ readonly refreshLeewaySeconds?: number;
69
+ /** Overrides the issuer/client-specific prefix. Only ASCII letters, digits, '.', '-' and '_' are allowed. */
70
+ readonly storageKeyPrefix?: string;
71
+ }
72
+
73
+ export interface OidcProviderMetadata {
74
+ readonly issuer: string;
75
+ readonly authorizationEndpoint: string;
76
+ readonly tokenEndpoint: string;
77
+ readonly userInfoEndpoint: string;
78
+ readonly endSessionEndpoint?: string;
79
+ }
80
+
81
+ export interface OidcSession {
82
+ /** Immutable OIDC subject obtained from the authenticated UserInfo response. */
83
+ readonly subject: string;
84
+ readonly accessToken: string;
85
+ readonly refreshToken?: string;
86
+ readonly idToken?: string;
87
+ readonly expiresAt: number;
88
+ }
89
+
90
+ export interface SignInOptions {
91
+ /** Forwarded to the browser flow, for example `appearanceStateDecoration({ mode: 'dark' })`. */
92
+ readonly stateDecoration?: readonly string[];
93
+ }
94
+
95
+ export type SignInResult =
96
+ | { readonly status: 'success'; readonly subject: string }
97
+ | { readonly status: 'cancelled'; readonly reason: 'cancel' | 'dismiss' };
98
+
99
+ export type SignOutResult =
100
+ | { readonly providerLogout: 'completed' }
101
+ | { readonly providerLogout: 'unavailable' }
102
+ | { readonly providerLogout: 'failed' };
103
+
104
+ export type SessionExpiredReason = 'refresh_rejected' | 'refresh_unavailable';
105
+
106
+ export interface SessionExpiredEvent {
107
+ readonly type: 'session-expired';
108
+ readonly reason: SessionExpiredReason;
109
+ }
110
+
111
+ export interface SecureStoragePort {
112
+ get(key: string): Promise<string | null>;
113
+ set(key: string, value: string): Promise<void>;
114
+ delete(key: string): Promise<void>;
115
+ }
116
+
117
+ export interface AuthorizationRequest {
118
+ readonly authorizationEndpoint: string;
119
+ readonly clientId: string;
120
+ readonly redirectUri: string;
121
+ readonly scopes: readonly string[];
122
+ readonly prompt?: 'login';
123
+ /** Segments a decorating browser flow puts in front of its random state. Other flows ignore them. */
124
+ readonly stateDecoration?: readonly string[];
125
+ }
126
+
127
+ export type AuthorizationResult =
128
+ | { readonly type: 'cancel' }
129
+ | { readonly type: 'dismiss' }
130
+ | { readonly type: 'error' }
131
+ | {
132
+ readonly type: 'success';
133
+ readonly code: string;
134
+ readonly state: string;
135
+ readonly expectedState: string;
136
+ readonly codeVerifier: string;
137
+ };
138
+
139
+ export interface EndSessionRequest {
140
+ readonly url: string;
141
+ readonly redirectUri: string;
142
+ }
143
+
144
+ /** AuthSession-like browser seam. Implementations own S256 PKCE and transaction state creation. */
145
+ export interface BrowserFlowPort {
146
+ authorize(request: AuthorizationRequest): Promise<AuthorizationResult>;
147
+ endSession(request: EndSessionRequest): Promise<boolean>;
148
+ }
149
+
150
+ export type FetchPort = (input: string, init?: RequestInit) => Promise<Response>;
151
+
152
+ export interface NativeOidcEnvironment {
153
+ readonly fetch: FetchPort;
154
+ readonly storage: SecureStoragePort;
155
+ readonly browser: BrowserFlowPort;
156
+ readonly now: () => number;
157
+ }
158
+
159
+ interface NormalizedConfig {
160
+ readonly issuer: string;
161
+ readonly clientId: string;
162
+ readonly redirectUri: string;
163
+ readonly scopes: readonly string[];
164
+ readonly postLogoutRedirectUri: string;
165
+ readonly refreshLeewayMs: number;
166
+ readonly storageKeyPrefix: string;
167
+ }
168
+
169
+ interface RawProviderMetadata {
170
+ readonly issuer: string;
171
+ readonly authorization_endpoint: string;
172
+ readonly token_endpoint: string;
173
+ readonly userinfo_endpoint: string;
174
+ readonly end_session_endpoint?: string;
175
+ }
176
+
177
+ interface TokenResponse {
178
+ readonly access_token: string;
179
+ readonly expires_in: number;
180
+ readonly refresh_token?: string;
181
+ readonly id_token?: string;
182
+ }
183
+
184
+ interface ReceivedTokenResponse extends TokenResponse {
185
+ readonly receivedAt: number;
186
+ }
187
+
188
+ type SessionListener = (session: OidcSession | undefined) => void;
189
+ type SessionExpiredListener = (event: SessionExpiredEvent) => void;
190
+
191
+ /** Provider-neutral native OIDC client. It has no React or router dependency. */
192
+ export class NativeOidcClient {
193
+ private readonly config: NormalizedConfig;
194
+ private readonly environment: NativeOidcEnvironment;
195
+ private readonly sessionStorageKey: string;
196
+ private readonly forceLoginStorageKey: string;
197
+ private readonly listeners = new Set<SessionListener>();
198
+ private readonly sessionExpiredListeners = new Set<SessionExpiredListener>();
199
+ private currentSession: OidcSession | undefined;
200
+ private initialized = false;
201
+ private initializePromise: Promise<OidcSession | undefined> | undefined;
202
+ private metadataPromise: Promise<OidcProviderMetadata> | undefined;
203
+ private refreshPromise: Promise<string | undefined> | undefined;
204
+
205
+ public constructor(config: NativeOidcConfig, environment: NativeOidcEnvironment) {
206
+ this.config = normalizeConfig(config);
207
+ this.environment = environment;
208
+ this.sessionStorageKey = `${this.config.storageKeyPrefix}.session`;
209
+ this.forceLoginStorageKey = `${this.config.storageKeyPrefix}.force-login`;
210
+ }
211
+
212
+ /** Loads secure storage once. Corrupt values are removed and treated as signed out. */
213
+ public initialize(): Promise<OidcSession | undefined> {
214
+ if (this.initialized) {
215
+ return Promise.resolve(this.currentSession);
216
+ }
217
+ this.initializePromise ??= this.initializeOnce();
218
+ return this.initializePromise;
219
+ }
220
+
221
+ /** Returns the last initialized session without performing I/O. */
222
+ public session(): OidcSession | undefined {
223
+ return this.currentSession;
224
+ }
225
+
226
+ public subscribe(listener: SessionListener): () => void {
227
+ this.listeners.add(listener);
228
+ return () => {
229
+ this.listeners.delete(listener);
230
+ };
231
+ }
232
+
233
+ /** Observes terminal expiry separately from explicit sign-out or manual clearing. */
234
+ public subscribeSessionExpired(listener: SessionExpiredListener): () => void {
235
+ this.sessionExpiredListeners.add(listener);
236
+ return () => {
237
+ this.sessionExpiredListeners.delete(listener);
238
+ };
239
+ }
240
+
241
+ public discover(): Promise<OidcProviderMetadata> {
242
+ this.metadataPromise ??= discoverProvider(this.config.issuer, this.environment.fetch);
243
+ return this.metadataPromise;
244
+ }
245
+
246
+ public async signIn(options: SignInOptions = {}): Promise<SignInResult> {
247
+ await this.initialize();
248
+ const metadata = await this.discover();
249
+ const forceLogin = await this.readForceLogin();
250
+ let result: AuthorizationResult;
251
+ try {
252
+ result = await this.environment.browser.authorize({
253
+ authorizationEndpoint: metadata.authorizationEndpoint,
254
+ clientId: this.config.clientId,
255
+ redirectUri: this.config.redirectUri,
256
+ scopes: this.config.scopes,
257
+ ...(forceLogin ? { prompt: 'login' as const } : {}),
258
+ ...(options.stateDecoration === undefined
259
+ ? {}
260
+ : { stateDecoration: options.stateDecoration }),
261
+ });
262
+ } catch {
263
+ throw new OidcError('authorization_failed');
264
+ }
265
+
266
+ if (result.type === 'cancel' || result.type === 'dismiss') {
267
+ return { status: 'cancelled', reason: result.type };
268
+ }
269
+ if (result.type === 'error' || result.code.length === 0) {
270
+ throw new OidcError('authorization_failed');
271
+ }
272
+ if (result.state.length === 0 || result.state !== result.expectedState) {
273
+ throw new OidcError('callback_state_mismatch');
274
+ }
275
+ if (result.codeVerifier.length === 0) {
276
+ throw new OidcError('pkce_verifier_missing');
277
+ }
278
+
279
+ const tokens = await this.exchange(
280
+ metadata.tokenEndpoint,
281
+ new URLSearchParams({
282
+ grant_type: 'authorization_code',
283
+ client_id: this.config.clientId,
284
+ redirect_uri: this.config.redirectUri,
285
+ code: result.code,
286
+ code_verifier: result.codeVerifier,
287
+ }),
288
+ 'token_exchange_failed',
289
+ );
290
+ const subject = await fetchSubject(
291
+ metadata.userInfoEndpoint,
292
+ tokens.access_token,
293
+ this.environment.fetch,
294
+ );
295
+ const session = makeSession(tokens, subject);
296
+ await this.writeSession(session);
297
+ await this.deleteForceLoginBestEffort();
298
+ return { status: 'success', subject };
299
+ }
300
+
301
+ /** Returns a current token, refreshing once when needed. */
302
+ public async accessToken(
303
+ options: { readonly forceRefresh?: boolean } = {},
304
+ ): Promise<string | undefined> {
305
+ await this.initialize();
306
+ const session = this.currentSession;
307
+ if (session === undefined) {
308
+ return undefined;
309
+ }
310
+ const expiresSoon = session.expiresAt <= this.environment.now() + this.config.refreshLeewayMs;
311
+ if (options.forceRefresh !== true && !expiresSoon) {
312
+ return session.accessToken;
313
+ }
314
+ if (session.refreshToken === undefined) {
315
+ await this.expireSession('refresh_unavailable');
316
+ return undefined;
317
+ }
318
+ if (this.refreshPromise !== undefined) {
319
+ return this.refreshPromise;
320
+ }
321
+ const pending = this.refresh(session);
322
+ this.refreshPromise = pending;
323
+ try {
324
+ return await pending;
325
+ } finally {
326
+ if (this.refreshPromise === pending) {
327
+ this.refreshPromise = undefined;
328
+ }
329
+ }
330
+ }
331
+
332
+ /** Clears local state first, then makes a best-effort provider logout attempt. */
333
+ public async signOut(): Promise<SignOutResult> {
334
+ await this.initialize();
335
+ const idToken = this.currentSession?.idToken;
336
+ await this.clearSession();
337
+ await this.setForceLogin();
338
+
339
+ let metadata: OidcProviderMetadata;
340
+ try {
341
+ metadata = await this.discover();
342
+ } catch {
343
+ return { providerLogout: 'failed' };
344
+ }
345
+ if (metadata.endSessionEndpoint === undefined) {
346
+ return { providerLogout: 'unavailable' };
347
+ }
348
+
349
+ const endpoint = new URL(metadata.endSessionEndpoint);
350
+ endpoint.searchParams.set('client_id', this.config.clientId);
351
+ endpoint.searchParams.set('post_logout_redirect_uri', this.config.postLogoutRedirectUri);
352
+ if (idToken !== undefined) {
353
+ endpoint.searchParams.set('id_token_hint', idToken);
354
+ }
355
+ try {
356
+ const completed = await this.environment.browser.endSession({
357
+ url: endpoint.toString(),
358
+ redirectUri: this.config.postLogoutRedirectUri,
359
+ });
360
+ if (!completed) {
361
+ return { providerLogout: 'failed' };
362
+ }
363
+ await this.deleteForceLoginBestEffort();
364
+ return { providerLogout: 'completed' };
365
+ } catch {
366
+ return { providerLogout: 'failed' };
367
+ }
368
+ }
369
+
370
+ /** Clears local authentication state without contacting the provider. */
371
+ public async clearSession(): Promise<void> {
372
+ this.setCurrentSession(undefined);
373
+ try {
374
+ await this.environment.storage.delete(this.sessionStorageKey);
375
+ } catch {
376
+ throw new OidcError('storage_failed');
377
+ }
378
+ }
379
+
380
+ private async initializeOnce(): Promise<OidcSession | undefined> {
381
+ let raw: string | null;
382
+ try {
383
+ raw = await this.environment.storage.get(this.sessionStorageKey);
384
+ } catch {
385
+ throw new OidcError('storage_failed');
386
+ }
387
+ const session = parseSession(raw);
388
+ if (raw !== null && session === undefined) {
389
+ this.setCurrentSession(undefined);
390
+ try {
391
+ await this.environment.storage.delete(this.sessionStorageKey);
392
+ } catch {
393
+ throw new OidcError('storage_failed');
394
+ }
395
+ } else {
396
+ this.setCurrentSession(session);
397
+ }
398
+ this.initialized = true;
399
+ return this.currentSession;
400
+ }
401
+
402
+ private async refresh(previous: OidcSession): Promise<string | undefined> {
403
+ const refreshToken = previous.refreshToken;
404
+ if (refreshToken === undefined) {
405
+ return undefined;
406
+ }
407
+ let tokens: ReceivedTokenResponse;
408
+ try {
409
+ const metadata = await this.discover();
410
+ tokens = await this.exchange(
411
+ metadata.tokenEndpoint,
412
+ new URLSearchParams({
413
+ grant_type: 'refresh_token',
414
+ client_id: this.config.clientId,
415
+ refresh_token: refreshToken,
416
+ scope: this.config.scopes.join(' '),
417
+ }),
418
+ 'refresh_failed',
419
+ );
420
+ } catch (cause) {
421
+ if (isTerminalRefreshError(cause)) {
422
+ if (this.currentSession !== previous) {
423
+ return this.currentSession?.accessToken;
424
+ }
425
+ await this.expireSession('refresh_rejected');
426
+ return undefined;
427
+ }
428
+ throw transientRefreshError(cause);
429
+ }
430
+ if (this.currentSession !== previous) {
431
+ return this.currentSession?.accessToken;
432
+ }
433
+ const session = makeSession(tokens, previous.subject, previous);
434
+ await this.writeSession(session);
435
+ return session.accessToken;
436
+ }
437
+
438
+ private async exchange(
439
+ endpoint: string,
440
+ body: URLSearchParams,
441
+ failureCode: 'refresh_failed' | 'token_exchange_failed',
442
+ ): Promise<ReceivedTokenResponse> {
443
+ let response: Response;
444
+ try {
445
+ response = await this.environment.fetch(endpoint, {
446
+ method: 'POST',
447
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
448
+ body,
449
+ });
450
+ } catch {
451
+ throw new OidcError(failureCode, { retryable: failureCode === 'refresh_failed' });
452
+ }
453
+ const receivedAt = this.environment.now();
454
+ if (!response.ok) {
455
+ const providerError = await readProviderError(response);
456
+ throw new OidcError(failureCode, {
457
+ status: response.status,
458
+ retryable:
459
+ failureCode === 'refresh_failed' &&
460
+ !isTerminalRefreshRejection(response.status, providerError),
461
+ });
462
+ }
463
+ let value: unknown;
464
+ try {
465
+ value = await response.json();
466
+ } catch {
467
+ throw new OidcError('invalid_token_response');
468
+ }
469
+ if (!isTokenResponse(value)) {
470
+ throw new OidcError('invalid_token_response');
471
+ }
472
+ return { ...value, receivedAt };
473
+ }
474
+
475
+ private async writeSession(session: OidcSession): Promise<void> {
476
+ try {
477
+ await this.environment.storage.set(this.sessionStorageKey, JSON.stringify(session));
478
+ } catch {
479
+ throw new OidcError('storage_failed');
480
+ }
481
+ this.setCurrentSession(session);
482
+ }
483
+
484
+ private async readForceLogin(): Promise<boolean> {
485
+ let stored: string | null;
486
+ try {
487
+ stored = await this.environment.storage.get(this.forceLoginStorageKey);
488
+ } catch {
489
+ throw new OidcError('storage_failed');
490
+ }
491
+ if (stored === null || stored === '0') {
492
+ return false;
493
+ }
494
+ if (stored !== '1') {
495
+ await this.setForceLogin();
496
+ }
497
+ return true;
498
+ }
499
+
500
+ private async setForceLogin(): Promise<void> {
501
+ try {
502
+ await this.environment.storage.set(this.forceLoginStorageKey, '1');
503
+ } catch {
504
+ throw new OidcError('storage_failed');
505
+ }
506
+ }
507
+
508
+ private async deleteForceLoginBestEffort(): Promise<void> {
509
+ try {
510
+ await this.environment.storage.delete(this.forceLoginStorageKey);
511
+ } catch {
512
+ // Retaining prompt=login is the fail-safe outcome when storage deletion fails.
513
+ }
514
+ }
515
+
516
+ private setCurrentSession(session: OidcSession | undefined): void {
517
+ this.currentSession = session;
518
+ for (const listener of this.listeners) {
519
+ try {
520
+ listener(session);
521
+ } catch {
522
+ // Observers cannot interrupt persistence or authentication transitions.
523
+ }
524
+ }
525
+ }
526
+
527
+ private async expireSession(reason: SessionExpiredReason): Promise<void> {
528
+ await this.clearSession();
529
+ const event: SessionExpiredEvent = { type: 'session-expired', reason };
530
+ for (const listener of this.sessionExpiredListeners) {
531
+ try {
532
+ listener(event);
533
+ } catch {
534
+ // Observers cannot change the terminal unauthenticated result.
535
+ }
536
+ }
537
+ }
538
+ }
539
+
540
+ /** Removes trailing issuer slashes while rejecting query strings and fragments. */
541
+ export function normalizeIssuer(issuer: string): string {
542
+ const trimmed = issuer.trim();
543
+ if (trimmed.length === 0) {
544
+ throw new TypeError('OIDC issuer must not be empty.');
545
+ }
546
+ const url = new URL(trimmed);
547
+ if (url.search.length !== 0 || url.hash.length !== 0) {
548
+ throw new TypeError('OIDC issuer must not include a query string or fragment.');
549
+ }
550
+ return url.toString().replace(/\/+$/u, '');
551
+ }
552
+
553
+ /** Returns an allowlisted message without reflecting untrusted error content. */
554
+ export function safeAuthErrorMessage(cause: unknown): string {
555
+ return cause instanceof OidcError ? SAFE_ERROR_MESSAGES[cause.code] : 'OIDC login failed.';
556
+ }
557
+
558
+ async function discoverProvider(
559
+ issuer: string,
560
+ fetchImplementation: FetchPort,
561
+ ): Promise<OidcProviderMetadata> {
562
+ let response: Response;
563
+ try {
564
+ response = await fetchImplementation(`${issuer}/.well-known/openid-configuration`);
565
+ } catch {
566
+ throw new OidcError('discovery_failed');
567
+ }
568
+ if (!response.ok) {
569
+ throw new OidcError('discovery_failed', { status: response.status });
570
+ }
571
+ let value: unknown;
572
+ try {
573
+ value = await response.json();
574
+ } catch {
575
+ throw new OidcError('invalid_discovery_document');
576
+ }
577
+ if (!isProviderMetadata(value)) {
578
+ throw new OidcError('invalid_discovery_document');
579
+ }
580
+ if (normalizeIssuer(value.issuer) !== issuer) {
581
+ throw new OidcError('issuer_mismatch');
582
+ }
583
+ return Object.freeze({
584
+ issuer,
585
+ authorizationEndpoint: value.authorization_endpoint,
586
+ tokenEndpoint: value.token_endpoint,
587
+ userInfoEndpoint: value.userinfo_endpoint,
588
+ ...(value.end_session_endpoint === undefined
589
+ ? {}
590
+ : { endSessionEndpoint: value.end_session_endpoint }),
591
+ });
592
+ }
593
+
594
+ async function fetchSubject(
595
+ endpoint: string,
596
+ accessToken: string,
597
+ fetchImplementation: FetchPort,
598
+ ): Promise<string> {
599
+ let response: Response;
600
+ try {
601
+ response = await fetchImplementation(endpoint, {
602
+ headers: { authorization: `Bearer ${accessToken}` },
603
+ });
604
+ } catch {
605
+ throw new OidcError('userinfo_failed');
606
+ }
607
+ if (!response.ok) {
608
+ throw new OidcError('userinfo_failed', { status: response.status });
609
+ }
610
+ let value: unknown;
611
+ try {
612
+ value = await response.json();
613
+ } catch {
614
+ throw new OidcError('invalid_userinfo_response');
615
+ }
616
+ if (!isObject(value) || typeof value['sub'] !== 'string' || value['sub'].length === 0) {
617
+ throw new OidcError('invalid_userinfo_response');
618
+ }
619
+ return value['sub'];
620
+ }
621
+
622
+ function normalizeConfig(config: NativeOidcConfig): NormalizedConfig {
623
+ const issuer = normalizeIssuer(config.issuer);
624
+ const clientId = requiredText(config.clientId, 'OIDC client ID');
625
+ const redirectUri = requiredUrl(config.redirectUri, 'OIDC redirect URI');
626
+ const refreshLeewaySeconds = config.refreshLeewaySeconds ?? 30;
627
+ if (!Number.isFinite(refreshLeewaySeconds) || refreshLeewaySeconds < 0) {
628
+ throw new RangeError('OIDC refresh leeway must be a non-negative number.');
629
+ }
630
+ const storageKeyPrefix =
631
+ config.storageKeyPrefix ??
632
+ `baukit.auth-native.${storageKeyPart(issuer)}.${storageKeyPart(clientId)}`;
633
+ if (storageKeyPrefix.length === 0) {
634
+ throw new TypeError('OIDC storage key prefix must not be empty.');
635
+ }
636
+ if (!/^[A-Za-z0-9._-]+$/u.test(storageKeyPrefix)) {
637
+ throw new TypeError(
638
+ "OIDC storage key prefix must contain only ASCII letters, digits, '.', '-' and '_'.",
639
+ );
640
+ }
641
+ return {
642
+ issuer,
643
+ clientId,
644
+ redirectUri,
645
+ scopes: normalizeScopes(config.scopes, config.offlineAccess),
646
+ postLogoutRedirectUri: requiredUrl(
647
+ config.postLogoutRedirectUri ?? redirectUri,
648
+ 'OIDC post-logout redirect URI',
649
+ ),
650
+ refreshLeewayMs: refreshLeewaySeconds * 1000,
651
+ storageKeyPrefix,
652
+ };
653
+ }
654
+
655
+ function storageKeyPart(value: string): string {
656
+ return encodeURIComponent(value).replace(
657
+ /[!'()*_.~%]/gu,
658
+ (character) => `_${character.charCodeAt(0).toString(16)}`,
659
+ );
660
+ }
661
+
662
+ function normalizeScopes(scopes: readonly string[] | undefined, offlineAccess = false): string[] {
663
+ const requested = scopes ?? ['openid', 'profile', 'email'];
664
+ const normalized: string[] = [];
665
+ for (const scope of ['openid', ...requested, ...(offlineAccess ? ['offline_access'] : [])]) {
666
+ const trimmed = scope.trim();
667
+ if (trimmed.length === 0 || /\s/u.test(trimmed)) {
668
+ throw new TypeError('OIDC scopes must be non-empty and contain no whitespace.');
669
+ }
670
+ if (!normalized.includes(trimmed)) {
671
+ normalized.push(trimmed);
672
+ }
673
+ }
674
+ return normalized;
675
+ }
676
+
677
+ function requiredText(value: string, label: string): string {
678
+ const trimmed = value.trim();
679
+ if (trimmed.length === 0) {
680
+ throw new TypeError(`${label} must not be empty.`);
681
+ }
682
+ return trimmed;
683
+ }
684
+
685
+ function requiredUrl(value: string, label: string): string {
686
+ const trimmed = requiredText(value, label);
687
+ try {
688
+ return new URL(trimmed).toString();
689
+ } catch {
690
+ throw new TypeError(`${label} must be an absolute URL.`);
691
+ }
692
+ }
693
+
694
+ function makeSession(
695
+ tokens: ReceivedTokenResponse,
696
+ subject: string,
697
+ previous?: OidcSession,
698
+ ): OidcSession {
699
+ const refreshToken = tokens.refresh_token ?? previous?.refreshToken;
700
+ const idToken = tokens.id_token ?? previous?.idToken;
701
+ return Object.freeze({
702
+ subject,
703
+ accessToken: tokens.access_token,
704
+ expiresAt: tokens.receivedAt + tokens.expires_in * 1000,
705
+ ...(refreshToken === undefined ? {} : { refreshToken }),
706
+ ...(idToken === undefined ? {} : { idToken }),
707
+ });
708
+ }
709
+
710
+ async function readProviderError(response: Response): Promise<string | undefined> {
711
+ try {
712
+ const value: unknown = await response.json();
713
+ return isObject(value) && typeof value['error'] === 'string' ? value['error'] : undefined;
714
+ } catch {
715
+ return undefined;
716
+ }
717
+ }
718
+
719
+ function isTerminalRefreshRejection(status: number, providerError: string | undefined): boolean {
720
+ return (
721
+ status === 400 ||
722
+ status === 401 ||
723
+ providerError === 'invalid_grant' ||
724
+ providerError === 'invalid_token'
725
+ );
726
+ }
727
+
728
+ function isTerminalRefreshError(cause: unknown): boolean {
729
+ return cause instanceof OidcError && cause.code === 'refresh_failed' && !cause.retryable;
730
+ }
731
+
732
+ function transientRefreshError(cause: unknown): OidcError {
733
+ if (cause instanceof OidcError && cause.code === 'refresh_failed' && cause.retryable) {
734
+ return cause;
735
+ }
736
+ return new OidcError('refresh_failed', {
737
+ retryable: true,
738
+ ...(cause instanceof OidcError && cause.status !== undefined ? { status: cause.status } : {}),
739
+ });
740
+ }
741
+
742
+ function parseSession(raw: string | null): OidcSession | undefined {
743
+ if (raw === null) {
744
+ return undefined;
745
+ }
746
+ try {
747
+ const value: unknown = JSON.parse(raw);
748
+ if (isSession(value)) {
749
+ return Object.freeze({ ...value });
750
+ }
751
+ } catch {
752
+ // Corrupt state is discarded by the caller without reflecting its content.
753
+ }
754
+ return undefined;
755
+ }
756
+
757
+ function isSession(value: unknown): value is OidcSession {
758
+ return (
759
+ isObject(value) &&
760
+ typeof value['subject'] === 'string' &&
761
+ value['subject'].length > 0 &&
762
+ typeof value['accessToken'] === 'string' &&
763
+ value['accessToken'].length > 0 &&
764
+ typeof value['expiresAt'] === 'number' &&
765
+ Number.isFinite(value['expiresAt']) &&
766
+ (value['refreshToken'] === undefined ||
767
+ (typeof value['refreshToken'] === 'string' && value['refreshToken'].length > 0)) &&
768
+ (value['idToken'] === undefined ||
769
+ (typeof value['idToken'] === 'string' && value['idToken'].length > 0))
770
+ );
771
+ }
772
+
773
+ function isTokenResponse(value: unknown): value is TokenResponse {
774
+ return (
775
+ isObject(value) &&
776
+ typeof value['access_token'] === 'string' &&
777
+ value['access_token'].length > 0 &&
778
+ typeof value['expires_in'] === 'number' &&
779
+ Number.isFinite(value['expires_in']) &&
780
+ value['expires_in'] > 0 &&
781
+ (value['refresh_token'] === undefined ||
782
+ (typeof value['refresh_token'] === 'string' && value['refresh_token'].length > 0)) &&
783
+ (value['id_token'] === undefined ||
784
+ (typeof value['id_token'] === 'string' && value['id_token'].length > 0))
785
+ );
786
+ }
787
+
788
+ function isProviderMetadata(value: unknown): value is RawProviderMetadata {
789
+ if (
790
+ !isObject(value) ||
791
+ typeof value['issuer'] !== 'string' ||
792
+ typeof value['authorization_endpoint'] !== 'string' ||
793
+ typeof value['token_endpoint'] !== 'string' ||
794
+ typeof value['userinfo_endpoint'] !== 'string' ||
795
+ (value['end_session_endpoint'] !== undefined &&
796
+ typeof value['end_session_endpoint'] !== 'string')
797
+ ) {
798
+ return false;
799
+ }
800
+ try {
801
+ normalizeIssuer(value['issuer']);
802
+ requiredUrl(value['authorization_endpoint'], 'OIDC authorization endpoint');
803
+ requiredUrl(value['token_endpoint'], 'OIDC token endpoint');
804
+ requiredUrl(value['userinfo_endpoint'], 'OIDC UserInfo endpoint');
805
+ if (value['end_session_endpoint'] !== undefined) {
806
+ requiredUrl(value['end_session_endpoint'], 'OIDC end-session endpoint');
807
+ }
808
+ return true;
809
+ } catch {
810
+ return false;
811
+ }
812
+ }
813
+
814
+ function isObject(value: unknown): value is Record<string, unknown> {
815
+ return typeof value === 'object' && value !== null;
816
+ }