@baukit/auth-web 0.18.3 → 0.19.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +78 -33
- package/dist/browser-session-client.d.ts +85 -0
- package/dist/browser-session-client.d.ts.map +1 -0
- package/dist/browser-session-client.js +339 -0
- package/dist/browser-session-client.js.map +1 -0
- package/dist/browser-session-support.d.ts +44 -0
- package/dist/browser-session-support.d.ts.map +1 -0
- package/dist/browser-session-support.js +102 -0
- package/dist/browser-session-support.js.map +1 -0
- package/dist/clerk.d.ts +1 -1
- package/dist/clerk.d.ts.map +1 -1
- package/dist/clerk.js.map +1 -1
- package/dist/index.d.ts +5 -95
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -466
- package/dist/index.js.map +1 -1
- package/dist/oidc-client.d.ts +67 -0
- package/dist/oidc-client.d.ts.map +1 -0
- package/dist/oidc-client.js +135 -0
- package/dist/oidc-client.js.map +1 -0
- package/dist/oidc-errors.d.ts +15 -0
- package/dist/oidc-errors.d.ts.map +1 -0
- package/dist/oidc-errors.js +30 -0
- package/dist/oidc-errors.js.map +1 -0
- package/dist/oidc-helpers.d.ts +1 -1
- package/dist/oidc-helpers.d.ts.map +1 -1
- package/dist/oidc-validation.d.ts +15 -0
- package/dist/oidc-validation.d.ts.map +1 -0
- package/dist/oidc-validation.js +76 -0
- package/dist/oidc-validation.js.map +1 -0
- package/dist/session-events.d.ts +10 -0
- package/dist/session-events.d.ts.map +1 -0
- package/dist/session-events.js +2 -0
- package/dist/session-events.js.map +1 -0
- package/dist/silent-token-broker.d.ts.map +1 -1
- package/dist/silent-token-broker.js +39 -28
- package/dist/silent-token-broker.js.map +1 -1
- package/dist/workos.d.ts +1 -1
- package/dist/workos.d.ts.map +1 -1
- package/dist/workos.js +1 -1
- package/dist/workos.js.map +1 -1
- package/package.json +5 -3
- package/src/browser-session-client.test.ts +426 -0
- package/src/browser-session-client.ts +414 -0
- package/src/browser-session-refresh.test.ts +58 -0
- package/src/browser-session-storage.test.ts +113 -0
- package/src/browser-session-support.ts +153 -0
- package/src/clerk.ts +5 -1
- package/src/index.test.ts +98 -594
- package/src/index.ts +28 -663
- package/src/oidc-client.ts +229 -0
- package/src/oidc-errors.ts +46 -0
- package/src/oidc-helpers.ts +1 -1
- package/src/oidc-validation.ts +93 -0
- package/src/session-events.ts +12 -0
- package/src/silent-token-broker.ts +49 -33
- package/src/test-support/browser-session.ts +203 -0
- package/src/test-support/session-backend.ts +104 -0
- package/src/workos.ts +6 -6
package/src/index.ts
CHANGED
|
@@ -1,666 +1,31 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
1
|
+
export {
|
|
2
|
+
BROWSER_SESSION_HEADER,
|
|
3
|
+
BROWSER_SESSION_PATH,
|
|
4
|
+
BrowserSessionClient,
|
|
5
|
+
type BrowserSessionClientConfig,
|
|
6
|
+
} from './browser-session-client.js';
|
|
7
|
+
export type {
|
|
8
|
+
AccountHint,
|
|
9
|
+
BrowserSessionEnvironment,
|
|
10
|
+
IssuedSession,
|
|
11
|
+
SessionChannel,
|
|
12
|
+
SessionLocks,
|
|
13
|
+
} from './browser-session-support.js';
|
|
14
|
+
export {
|
|
15
|
+
OidcClient,
|
|
16
|
+
type AuthorizationCallback,
|
|
17
|
+
type OidcClientConfig,
|
|
18
|
+
type OidcClientEnvironment,
|
|
19
|
+
type OidcProviderMetadata,
|
|
20
|
+
type PkceAuthorizationRequest,
|
|
21
|
+
} from './oidc-client.js';
|
|
22
|
+
export { OidcError, safeAuthErrorMessage, type OidcErrorCode } from './oidc-errors.js';
|
|
11
23
|
export { buildAuthorizationUrl, normalizeIssuer } from './oidc-helpers.js';
|
|
24
|
+
export type {
|
|
25
|
+
ClearSessionOptions,
|
|
26
|
+
SessionExpiredEvent,
|
|
27
|
+
SessionExpiredListener,
|
|
28
|
+
SessionExpiredReason,
|
|
29
|
+
} from './session-events.js';
|
|
12
30
|
export * from './silent-token-broker.js';
|
|
13
31
|
export { CALLBACK_MESSAGE, completeSilentTokenCallback } from './silent-token-browser.js';
|
|
14
|
-
|
|
15
|
-
export type OidcErrorCode =
|
|
16
|
-
| 'authorization_failed'
|
|
17
|
-
| 'callback_state_mismatch'
|
|
18
|
-
| 'discovery_failed'
|
|
19
|
-
| 'invalid_discovery_document'
|
|
20
|
-
| 'invalid_token_response'
|
|
21
|
-
| 'issuer_mismatch'
|
|
22
|
-
| 'refresh_failed'
|
|
23
|
-
| 'token_exchange_failed';
|
|
24
|
-
|
|
25
|
-
const SAFE_ERROR_MESSAGES = {
|
|
26
|
-
authorization_failed: 'OIDC authorization failed.',
|
|
27
|
-
callback_state_mismatch: 'OIDC callback state did not match the login transaction.',
|
|
28
|
-
discovery_failed: 'OIDC provider discovery failed.',
|
|
29
|
-
invalid_discovery_document: 'OIDC provider returned invalid discovery metadata.',
|
|
30
|
-
invalid_token_response: 'OIDC token endpoint returned an invalid response.',
|
|
31
|
-
issuer_mismatch: 'OIDC provider issuer did not match the configured issuer.',
|
|
32
|
-
refresh_failed: 'OIDC token refresh failed.',
|
|
33
|
-
token_exchange_failed: 'OIDC token exchange failed.',
|
|
34
|
-
} as const satisfies Record<OidcErrorCode, string>;
|
|
35
|
-
|
|
36
|
-
/** An authentication failure whose message is safe to display or log. */
|
|
37
|
-
export class OidcError extends Error {
|
|
38
|
-
public readonly code: OidcErrorCode;
|
|
39
|
-
public readonly status: number | undefined;
|
|
40
|
-
/** True only when retrying the failed operation may succeed without signing in again. */
|
|
41
|
-
public readonly retryable: boolean;
|
|
42
|
-
|
|
43
|
-
public constructor(
|
|
44
|
-
code: OidcErrorCode,
|
|
45
|
-
options: { readonly retryable?: boolean; readonly status?: number } = {},
|
|
46
|
-
) {
|
|
47
|
-
super(SAFE_ERROR_MESSAGES[code]);
|
|
48
|
-
this.name = 'OidcError';
|
|
49
|
-
this.code = code;
|
|
50
|
-
this.status = options.status;
|
|
51
|
-
this.retryable = options.retryable ?? false;
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
export interface OidcClientConfig {
|
|
56
|
-
readonly issuer: string;
|
|
57
|
-
readonly clientId: string;
|
|
58
|
-
readonly redirectUri: string;
|
|
59
|
-
readonly audience?: string;
|
|
60
|
-
readonly resource?: 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 deterministic, issuer/client-specific storage prefix. */
|
|
70
|
-
readonly storageKeyPrefix?: string;
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
export interface OidcProviderMetadata {
|
|
74
|
-
readonly issuer: string;
|
|
75
|
-
readonly authorizationEndpoint: string;
|
|
76
|
-
readonly tokenEndpoint: string;
|
|
77
|
-
readonly endSessionEndpoint?: string;
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
export interface OidcClientEnvironment {
|
|
81
|
-
readonly fetch: typeof globalThis.fetch;
|
|
82
|
-
readonly crypto: Crypto;
|
|
83
|
-
readonly localStorage: Storage;
|
|
84
|
-
readonly sessionStorage: Storage;
|
|
85
|
-
readonly currentUrl: () => string;
|
|
86
|
-
readonly navigate: (url: string) => void;
|
|
87
|
-
readonly replaceUrl: (url: string) => void;
|
|
88
|
-
readonly now: () => number;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
interface NormalizedConfig {
|
|
92
|
-
readonly issuer: string;
|
|
93
|
-
readonly clientId: string;
|
|
94
|
-
readonly redirectUri: string;
|
|
95
|
-
readonly audience?: string;
|
|
96
|
-
readonly resource?: string;
|
|
97
|
-
readonly scopes: readonly string[];
|
|
98
|
-
readonly postLogoutRedirectUri: string;
|
|
99
|
-
readonly refreshLeewayMs: number;
|
|
100
|
-
readonly storageKeyPrefix: string;
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
interface StoredTokens {
|
|
104
|
-
readonly accessToken: string;
|
|
105
|
-
readonly refreshToken?: string;
|
|
106
|
-
readonly idToken?: string;
|
|
107
|
-
readonly issuedAt: number;
|
|
108
|
-
readonly expiresAt: number;
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
interface LoginTransaction {
|
|
112
|
-
readonly state: string;
|
|
113
|
-
readonly verifier: string;
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
interface TokenResponse {
|
|
117
|
-
readonly access_token: string;
|
|
118
|
-
readonly expires_in: number;
|
|
119
|
-
readonly refresh_token?: string;
|
|
120
|
-
readonly id_token?: string;
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
export type SessionExpiredReason = 'refresh_rejected' | 'refresh_unavailable' | 'profile_erased';
|
|
124
|
-
|
|
125
|
-
export interface ClearSessionOptions {
|
|
126
|
-
readonly reason?: 'profile_erased';
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
export interface SessionExpiredEvent {
|
|
130
|
-
readonly type: 'session-expired';
|
|
131
|
-
readonly reason: SessionExpiredReason;
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
type SessionExpiredListener = (event: SessionExpiredEvent) => void;
|
|
135
|
-
|
|
136
|
-
interface RawProviderMetadata {
|
|
137
|
-
readonly issuer: string;
|
|
138
|
-
readonly authorization_endpoint: string;
|
|
139
|
-
readonly token_endpoint: string;
|
|
140
|
-
readonly end_session_endpoint?: string;
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
export interface PkceAuthorizationRequest {
|
|
144
|
-
readonly state: string;
|
|
145
|
-
readonly challenge: string;
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
/** Returns an allowlisted message without reflecting untrusted error content. */
|
|
149
|
-
export function safeAuthErrorMessage(cause: unknown): string {
|
|
150
|
-
return cause instanceof OidcError ? SAFE_ERROR_MESSAGES[cause.code] : 'OIDC login failed.';
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
/** Browser OIDC authorization-code client. It has no React dependency. */
|
|
154
|
-
export class OidcClient {
|
|
155
|
-
private readonly config: NormalizedConfig;
|
|
156
|
-
private readonly environment: OidcClientEnvironment;
|
|
157
|
-
private readonly tokenStorageKey: string;
|
|
158
|
-
private readonly transactionStorageKey: string;
|
|
159
|
-
private readonly forceLoginStorageKey: string;
|
|
160
|
-
private readonly sessionExpiredListeners = new Set<SessionExpiredListener>();
|
|
161
|
-
private metadataPromise: Promise<OidcProviderMetadata> | undefined;
|
|
162
|
-
private callbackPromise: Promise<boolean> | undefined;
|
|
163
|
-
private refreshPromise: Promise<string | undefined> | undefined;
|
|
164
|
-
private sessionRevision = 0;
|
|
165
|
-
|
|
166
|
-
public constructor(
|
|
167
|
-
config: OidcClientConfig,
|
|
168
|
-
environment: OidcClientEnvironment = browserEnvironment(),
|
|
169
|
-
) {
|
|
170
|
-
this.config = normalizeConfig(config);
|
|
171
|
-
this.environment = environment;
|
|
172
|
-
this.tokenStorageKey = `${this.config.storageKeyPrefix}:tokens`;
|
|
173
|
-
this.transactionStorageKey = `${this.config.storageKeyPrefix}:transaction`;
|
|
174
|
-
this.forceLoginStorageKey = `${this.config.storageKeyPrefix}:force-login`;
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
public hasSession(): boolean {
|
|
178
|
-
return this.readTokens() !== undefined;
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
public discover(): Promise<OidcProviderMetadata> {
|
|
182
|
-
this.metadataPromise ??= discoverProvider(this.config.issuer, this.environment.fetch);
|
|
183
|
-
return this.metadataPromise;
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
/** Observes terminal expiry separately from explicit logout or manual clearing. */
|
|
187
|
-
public subscribeSessionExpired(listener: SessionExpiredListener): () => void {
|
|
188
|
-
this.sessionExpiredListeners.add(listener);
|
|
189
|
-
return () => {
|
|
190
|
-
this.sessionExpiredListeners.delete(listener);
|
|
191
|
-
};
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
public async login(): Promise<void> {
|
|
195
|
-
const metadata = await this.discover();
|
|
196
|
-
const state = randomUrlSafe(this.environment.crypto, 32);
|
|
197
|
-
const verifier = randomUrlSafe(this.environment.crypto, 64);
|
|
198
|
-
const challenge = base64UrlEncode(
|
|
199
|
-
new Uint8Array(
|
|
200
|
-
await this.environment.crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier)),
|
|
201
|
-
),
|
|
202
|
-
);
|
|
203
|
-
this.environment.sessionStorage.setItem(
|
|
204
|
-
this.transactionStorageKey,
|
|
205
|
-
JSON.stringify({ state, verifier }),
|
|
206
|
-
);
|
|
207
|
-
const authorizationUrl = buildAuthorizationUrl(
|
|
208
|
-
this.config,
|
|
209
|
-
metadata.authorizationEndpoint,
|
|
210
|
-
{ state, challenge },
|
|
211
|
-
this.environment.localStorage.getItem(this.forceLoginStorageKey) === null
|
|
212
|
-
? undefined
|
|
213
|
-
: 'login',
|
|
214
|
-
);
|
|
215
|
-
this.environment.navigate(authorizationUrl.toString());
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
/** Returns one shared promise so repeated effects cannot exchange a code twice. */
|
|
219
|
-
public handleCallback(): Promise<boolean> {
|
|
220
|
-
this.callbackPromise ??= this.handleCallbackOnce();
|
|
221
|
-
return this.callbackPromise;
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
public async accessToken(
|
|
225
|
-
options: { readonly forceRefresh?: boolean } = {},
|
|
226
|
-
): Promise<string | undefined> {
|
|
227
|
-
const tokens = this.readTokens();
|
|
228
|
-
if (tokens === undefined) {
|
|
229
|
-
return undefined;
|
|
230
|
-
}
|
|
231
|
-
const leewayMs = refreshWindowMs(
|
|
232
|
-
tokens.issuedAt,
|
|
233
|
-
tokens.expiresAt,
|
|
234
|
-
this.config.refreshLeewayMs,
|
|
235
|
-
);
|
|
236
|
-
if (options.forceRefresh !== true && tokens.expiresAt > this.environment.now() + leewayMs) {
|
|
237
|
-
return tokens.accessToken;
|
|
238
|
-
}
|
|
239
|
-
if (tokens.refreshToken === undefined) {
|
|
240
|
-
this.expireSession('refresh_unavailable');
|
|
241
|
-
return undefined;
|
|
242
|
-
}
|
|
243
|
-
if (this.refreshPromise !== undefined) {
|
|
244
|
-
return this.refreshPromise;
|
|
245
|
-
}
|
|
246
|
-
const pending = this.refresh(tokens, tokens.refreshToken);
|
|
247
|
-
this.refreshPromise = pending;
|
|
248
|
-
try {
|
|
249
|
-
return await pending;
|
|
250
|
-
} finally {
|
|
251
|
-
if (this.refreshPromise === pending) {
|
|
252
|
-
this.refreshPromise = undefined;
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
/** Clears local tokens and redirects through the discovered logout endpoint when available. */
|
|
258
|
-
public async logout(): Promise<boolean> {
|
|
259
|
-
const idToken = this.readTokens()?.idToken;
|
|
260
|
-
this.clearSession();
|
|
261
|
-
const metadata = await this.discover();
|
|
262
|
-
if (metadata.endSessionEndpoint === undefined) {
|
|
263
|
-
return false;
|
|
264
|
-
}
|
|
265
|
-
const endpoint = new URL(metadata.endSessionEndpoint);
|
|
266
|
-
endpoint.searchParams.set('client_id', this.config.clientId);
|
|
267
|
-
endpoint.searchParams.set('post_logout_redirect_uri', this.config.postLogoutRedirectUri);
|
|
268
|
-
if (idToken !== undefined) {
|
|
269
|
-
endpoint.searchParams.set('id_token_hint', idToken);
|
|
270
|
-
}
|
|
271
|
-
this.environment.navigate(endpoint.toString());
|
|
272
|
-
return true;
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
/** Clears local authentication state without contacting the provider. */
|
|
276
|
-
public clearSession(options: ClearSessionOptions = {}): void {
|
|
277
|
-
if (options.reason !== undefined) {
|
|
278
|
-
this.expireSession(options.reason);
|
|
279
|
-
return;
|
|
280
|
-
}
|
|
281
|
-
this.sessionRevision += 1;
|
|
282
|
-
this.environment.localStorage.removeItem(this.tokenStorageKey);
|
|
283
|
-
this.environment.sessionStorage.removeItem(this.transactionStorageKey);
|
|
284
|
-
}
|
|
285
|
-
|
|
286
|
-
private async handleCallbackOnce(): Promise<boolean> {
|
|
287
|
-
const callback = new URL(this.environment.currentUrl());
|
|
288
|
-
if (!hasCallbackParameters(callback)) {
|
|
289
|
-
return false;
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
const code = callback.searchParams.get('code');
|
|
293
|
-
const returnedState = callback.searchParams.get('state');
|
|
294
|
-
const returnedIssuer = callback.searchParams.get('iss');
|
|
295
|
-
const providerError = callback.searchParams.has('error');
|
|
296
|
-
this.removeCallbackParameters(callback);
|
|
297
|
-
|
|
298
|
-
const transaction = readTransaction(
|
|
299
|
-
this.environment.sessionStorage.getItem(this.transactionStorageKey),
|
|
300
|
-
);
|
|
301
|
-
this.environment.sessionStorage.removeItem(this.transactionStorageKey);
|
|
302
|
-
if (returnedState === null || transaction?.state !== returnedState) {
|
|
303
|
-
throw new OidcError('callback_state_mismatch');
|
|
304
|
-
}
|
|
305
|
-
if (returnedIssuer !== null && normalizeIssuer(returnedIssuer) !== this.config.issuer) {
|
|
306
|
-
throw new OidcError('issuer_mismatch');
|
|
307
|
-
}
|
|
308
|
-
if (providerError) {
|
|
309
|
-
throw new OidcError('authorization_failed');
|
|
310
|
-
}
|
|
311
|
-
if (code === null) {
|
|
312
|
-
throw new OidcError('callback_state_mismatch');
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
const sessionRevision = this.sessionRevision;
|
|
316
|
-
const tokens = await this.exchange(
|
|
317
|
-
new URLSearchParams({
|
|
318
|
-
grant_type: 'authorization_code',
|
|
319
|
-
client_id: this.config.clientId,
|
|
320
|
-
redirect_uri: this.config.redirectUri,
|
|
321
|
-
code,
|
|
322
|
-
code_verifier: transaction.verifier,
|
|
323
|
-
}),
|
|
324
|
-
undefined,
|
|
325
|
-
'token_exchange_failed',
|
|
326
|
-
);
|
|
327
|
-
if (this.sessionRevision === sessionRevision) {
|
|
328
|
-
this.writeTokens(tokens);
|
|
329
|
-
this.environment.localStorage.removeItem(this.forceLoginStorageKey);
|
|
330
|
-
}
|
|
331
|
-
return true;
|
|
332
|
-
}
|
|
333
|
-
|
|
334
|
-
private removeCallbackParameters(callback: URL): void {
|
|
335
|
-
for (const parameter of [
|
|
336
|
-
'code',
|
|
337
|
-
'state',
|
|
338
|
-
'session_state',
|
|
339
|
-
'iss',
|
|
340
|
-
'error',
|
|
341
|
-
'error_description',
|
|
342
|
-
'error_uri',
|
|
343
|
-
]) {
|
|
344
|
-
callback.searchParams.delete(parameter);
|
|
345
|
-
}
|
|
346
|
-
this.environment.replaceUrl(callback.toString());
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
private async refresh(tokens: StoredTokens, refreshToken: string): Promise<string | undefined> {
|
|
350
|
-
const sessionRevision = this.sessionRevision;
|
|
351
|
-
try {
|
|
352
|
-
const refreshed = await this.exchange(
|
|
353
|
-
new URLSearchParams({
|
|
354
|
-
grant_type: 'refresh_token',
|
|
355
|
-
client_id: this.config.clientId,
|
|
356
|
-
refresh_token: refreshToken,
|
|
357
|
-
}),
|
|
358
|
-
tokens,
|
|
359
|
-
'refresh_failed',
|
|
360
|
-
);
|
|
361
|
-
if (this.sessionRevision !== sessionRevision) {
|
|
362
|
-
return this.readTokens()?.accessToken;
|
|
363
|
-
}
|
|
364
|
-
this.writeTokens(refreshed);
|
|
365
|
-
return refreshed.accessToken;
|
|
366
|
-
} catch (cause) {
|
|
367
|
-
if (isTerminalRefreshError(cause)) {
|
|
368
|
-
if (this.sessionRevision !== sessionRevision) {
|
|
369
|
-
return this.readTokens()?.accessToken;
|
|
370
|
-
}
|
|
371
|
-
this.expireSession('refresh_rejected');
|
|
372
|
-
return undefined;
|
|
373
|
-
}
|
|
374
|
-
throw transientRefreshError(cause);
|
|
375
|
-
}
|
|
376
|
-
}
|
|
377
|
-
|
|
378
|
-
private async exchange(
|
|
379
|
-
body: URLSearchParams,
|
|
380
|
-
existingTokens: StoredTokens | undefined,
|
|
381
|
-
failureCode: 'refresh_failed' | 'token_exchange_failed',
|
|
382
|
-
): Promise<StoredTokens> {
|
|
383
|
-
const metadata = await this.discover();
|
|
384
|
-
let response: Response;
|
|
385
|
-
try {
|
|
386
|
-
response = await this.environment.fetch(metadata.tokenEndpoint, {
|
|
387
|
-
method: 'POST',
|
|
388
|
-
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
|
389
|
-
body,
|
|
390
|
-
});
|
|
391
|
-
} catch {
|
|
392
|
-
throw new OidcError(failureCode, { retryable: failureCode === 'refresh_failed' });
|
|
393
|
-
}
|
|
394
|
-
const receivedAt = this.environment.now();
|
|
395
|
-
if (!response.ok) {
|
|
396
|
-
const providerError = await readProviderError(response);
|
|
397
|
-
throw new OidcError(failureCode, {
|
|
398
|
-
status: response.status,
|
|
399
|
-
retryable:
|
|
400
|
-
failureCode === 'refresh_failed' &&
|
|
401
|
-
!isTerminalRefreshRejection(response.status, providerError),
|
|
402
|
-
});
|
|
403
|
-
}
|
|
404
|
-
|
|
405
|
-
let payload: unknown;
|
|
406
|
-
try {
|
|
407
|
-
payload = await response.json();
|
|
408
|
-
} catch {
|
|
409
|
-
throw new OidcError('invalid_token_response');
|
|
410
|
-
}
|
|
411
|
-
if (!isTokenResponse(payload)) {
|
|
412
|
-
throw new OidcError('invalid_token_response');
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
const refreshToken = payload.refresh_token ?? existingTokens?.refreshToken;
|
|
416
|
-
const idToken = payload.id_token ?? existingTokens?.idToken;
|
|
417
|
-
const tokens: StoredTokens = {
|
|
418
|
-
accessToken: payload.access_token,
|
|
419
|
-
issuedAt: receivedAt,
|
|
420
|
-
expiresAt: receivedAt + payload.expires_in * 1000,
|
|
421
|
-
...(refreshToken === undefined ? {} : { refreshToken }),
|
|
422
|
-
...(idToken === undefined ? {} : { idToken }),
|
|
423
|
-
};
|
|
424
|
-
return tokens;
|
|
425
|
-
}
|
|
426
|
-
|
|
427
|
-
private writeTokens(tokens: StoredTokens): void {
|
|
428
|
-
this.environment.localStorage.setItem(this.tokenStorageKey, JSON.stringify(tokens));
|
|
429
|
-
this.sessionRevision += 1;
|
|
430
|
-
}
|
|
431
|
-
|
|
432
|
-
private expireSession(reason: SessionExpiredReason): void {
|
|
433
|
-
this.clearSession();
|
|
434
|
-
if (reason === 'profile_erased') {
|
|
435
|
-
this.environment.localStorage.setItem(this.forceLoginStorageKey, '1');
|
|
436
|
-
}
|
|
437
|
-
const event: SessionExpiredEvent = { type: 'session-expired', reason };
|
|
438
|
-
for (const listener of this.sessionExpiredListeners) {
|
|
439
|
-
try {
|
|
440
|
-
listener(event);
|
|
441
|
-
} catch {
|
|
442
|
-
// Observers cannot change the terminal unauthenticated result.
|
|
443
|
-
}
|
|
444
|
-
}
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
private readTokens(): StoredTokens | undefined {
|
|
448
|
-
const raw = this.environment.localStorage.getItem(this.tokenStorageKey);
|
|
449
|
-
if (raw === null) {
|
|
450
|
-
return undefined;
|
|
451
|
-
}
|
|
452
|
-
try {
|
|
453
|
-
const value: unknown = JSON.parse(raw);
|
|
454
|
-
if (isStoredTokens(value)) {
|
|
455
|
-
return value;
|
|
456
|
-
}
|
|
457
|
-
} catch {
|
|
458
|
-
// Invalid state is discarded below without reflecting its content.
|
|
459
|
-
}
|
|
460
|
-
this.environment.localStorage.removeItem(this.tokenStorageKey);
|
|
461
|
-
this.sessionRevision += 1;
|
|
462
|
-
return undefined;
|
|
463
|
-
}
|
|
464
|
-
}
|
|
465
|
-
|
|
466
|
-
async function readProviderError(response: Response): Promise<string | undefined> {
|
|
467
|
-
try {
|
|
468
|
-
const value: unknown = await response.json();
|
|
469
|
-
return isObject(value) && typeof value['error'] === 'string' ? value['error'] : undefined;
|
|
470
|
-
} catch {
|
|
471
|
-
return undefined;
|
|
472
|
-
}
|
|
473
|
-
}
|
|
474
|
-
|
|
475
|
-
function isTerminalRefreshRejection(status: number, providerError: string | undefined): boolean {
|
|
476
|
-
return (
|
|
477
|
-
status === 400 ||
|
|
478
|
-
status === 401 ||
|
|
479
|
-
providerError === 'invalid_grant' ||
|
|
480
|
-
providerError === 'invalid_token'
|
|
481
|
-
);
|
|
482
|
-
}
|
|
483
|
-
|
|
484
|
-
function isTerminalRefreshError(cause: unknown): boolean {
|
|
485
|
-
return cause instanceof OidcError && cause.code === 'refresh_failed' && !cause.retryable;
|
|
486
|
-
}
|
|
487
|
-
|
|
488
|
-
function transientRefreshError(cause: unknown): OidcError {
|
|
489
|
-
if (cause instanceof OidcError && cause.code === 'refresh_failed' && cause.retryable) {
|
|
490
|
-
return cause;
|
|
491
|
-
}
|
|
492
|
-
return new OidcError('refresh_failed', {
|
|
493
|
-
retryable: true,
|
|
494
|
-
...(cause instanceof OidcError && cause.status !== undefined ? { status: cause.status } : {}),
|
|
495
|
-
});
|
|
496
|
-
}
|
|
497
|
-
|
|
498
|
-
async function discoverProvider(
|
|
499
|
-
issuer: string,
|
|
500
|
-
fetchImplementation: typeof globalThis.fetch,
|
|
501
|
-
): Promise<OidcProviderMetadata> {
|
|
502
|
-
let response: Response;
|
|
503
|
-
try {
|
|
504
|
-
response = await fetchImplementation(`${issuer}/.well-known/openid-configuration`);
|
|
505
|
-
} catch {
|
|
506
|
-
throw new OidcError('discovery_failed');
|
|
507
|
-
}
|
|
508
|
-
if (!response.ok) {
|
|
509
|
-
throw new OidcError('discovery_failed', { status: response.status });
|
|
510
|
-
}
|
|
511
|
-
let value: unknown;
|
|
512
|
-
try {
|
|
513
|
-
value = await response.json();
|
|
514
|
-
} catch {
|
|
515
|
-
throw new OidcError('invalid_discovery_document');
|
|
516
|
-
}
|
|
517
|
-
if (!isProviderMetadata(value)) {
|
|
518
|
-
throw new OidcError('invalid_discovery_document');
|
|
519
|
-
}
|
|
520
|
-
if (normalizeIssuer(value.issuer) !== issuer) {
|
|
521
|
-
throw new OidcError('issuer_mismatch');
|
|
522
|
-
}
|
|
523
|
-
return {
|
|
524
|
-
issuer,
|
|
525
|
-
authorizationEndpoint: value.authorization_endpoint,
|
|
526
|
-
tokenEndpoint: value.token_endpoint,
|
|
527
|
-
...(value.end_session_endpoint === undefined
|
|
528
|
-
? {}
|
|
529
|
-
: { endSessionEndpoint: value.end_session_endpoint }),
|
|
530
|
-
};
|
|
531
|
-
}
|
|
532
|
-
|
|
533
|
-
function normalizeConfig(config: OidcClientConfig): NormalizedConfig {
|
|
534
|
-
const issuer = normalizeIssuer(config.issuer);
|
|
535
|
-
const clientId = requiredText(config.clientId, 'OIDC client ID');
|
|
536
|
-
const redirectUri = requiredUrl(config.redirectUri, 'OIDC redirect URI');
|
|
537
|
-
const refreshLeewaySeconds = config.refreshLeewaySeconds ?? 30;
|
|
538
|
-
if (!Number.isFinite(refreshLeewaySeconds) || refreshLeewaySeconds < 0) {
|
|
539
|
-
throw new RangeError('OIDC refresh leeway must be a non-negative number.');
|
|
540
|
-
}
|
|
541
|
-
const storageKeyPrefix =
|
|
542
|
-
config.storageKeyPrefix ?? `@baukit/auth-web:${encodeURIComponent(issuer)}:${clientId}`;
|
|
543
|
-
if (storageKeyPrefix.length === 0) {
|
|
544
|
-
throw new TypeError('OIDC storage key prefix must not be empty.');
|
|
545
|
-
}
|
|
546
|
-
return {
|
|
547
|
-
issuer,
|
|
548
|
-
clientId,
|
|
549
|
-
redirectUri,
|
|
550
|
-
...(config.audience === undefined
|
|
551
|
-
? {}
|
|
552
|
-
: { audience: requiredText(config.audience, 'OIDC audience') }),
|
|
553
|
-
...(config.resource === undefined
|
|
554
|
-
? {}
|
|
555
|
-
: { resource: requiredText(config.resource, 'OIDC resource') }),
|
|
556
|
-
scopes: normalizeScopes(config.scopes, config.offlineAccess),
|
|
557
|
-
postLogoutRedirectUri: requiredUrl(
|
|
558
|
-
config.postLogoutRedirectUri ?? redirectUri,
|
|
559
|
-
'OIDC post-logout redirect URI',
|
|
560
|
-
),
|
|
561
|
-
refreshLeewayMs: refreshLeewaySeconds * 1000,
|
|
562
|
-
storageKeyPrefix,
|
|
563
|
-
};
|
|
564
|
-
}
|
|
565
|
-
|
|
566
|
-
function hasCallbackParameters(url: URL): boolean {
|
|
567
|
-
return ['code', 'state', 'error', 'iss', 'session_state'].some((name) =>
|
|
568
|
-
url.searchParams.has(name),
|
|
569
|
-
);
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
function readTransaction(raw: string | null): LoginTransaction | undefined {
|
|
573
|
-
if (raw === null) {
|
|
574
|
-
return undefined;
|
|
575
|
-
}
|
|
576
|
-
try {
|
|
577
|
-
const value: unknown = JSON.parse(raw);
|
|
578
|
-
return isObject(value) &&
|
|
579
|
-
typeof value['state'] === 'string' &&
|
|
580
|
-
value['state'].length > 0 &&
|
|
581
|
-
typeof value['verifier'] === 'string' &&
|
|
582
|
-
value['verifier'].length > 0
|
|
583
|
-
? { state: value['state'], verifier: value['verifier'] }
|
|
584
|
-
: undefined;
|
|
585
|
-
} catch {
|
|
586
|
-
return undefined;
|
|
587
|
-
}
|
|
588
|
-
}
|
|
589
|
-
|
|
590
|
-
function refreshWindowMs(issuedAt: number, expiresAt: number, configuredLeewayMs: number): number {
|
|
591
|
-
return Math.min(configuredLeewayMs, (expiresAt - issuedAt) / 2);
|
|
592
|
-
}
|
|
593
|
-
|
|
594
|
-
function isStoredTokens(value: unknown): value is StoredTokens {
|
|
595
|
-
return (
|
|
596
|
-
isObject(value) &&
|
|
597
|
-
typeof value['accessToken'] === 'string' &&
|
|
598
|
-
value['accessToken'].length > 0 &&
|
|
599
|
-
typeof value['issuedAt'] === 'number' &&
|
|
600
|
-
Number.isFinite(value['issuedAt']) &&
|
|
601
|
-
typeof value['expiresAt'] === 'number' &&
|
|
602
|
-
Number.isFinite(value['expiresAt']) &&
|
|
603
|
-
(value['refreshToken'] === undefined || typeof value['refreshToken'] === 'string') &&
|
|
604
|
-
(value['idToken'] === undefined || typeof value['idToken'] === 'string')
|
|
605
|
-
);
|
|
606
|
-
}
|
|
607
|
-
|
|
608
|
-
function isTokenResponse(value: unknown): value is TokenResponse {
|
|
609
|
-
return (
|
|
610
|
-
isObject(value) &&
|
|
611
|
-
typeof value['access_token'] === 'string' &&
|
|
612
|
-
value['access_token'].length > 0 &&
|
|
613
|
-
typeof value['expires_in'] === 'number' &&
|
|
614
|
-
Number.isFinite(value['expires_in']) &&
|
|
615
|
-
value['expires_in'] > 0 &&
|
|
616
|
-
(value['refresh_token'] === undefined || typeof value['refresh_token'] === 'string') &&
|
|
617
|
-
(value['id_token'] === undefined || typeof value['id_token'] === 'string')
|
|
618
|
-
);
|
|
619
|
-
}
|
|
620
|
-
|
|
621
|
-
function isProviderMetadata(value: unknown): value is RawProviderMetadata {
|
|
622
|
-
if (
|
|
623
|
-
!isObject(value) ||
|
|
624
|
-
typeof value['issuer'] !== 'string' ||
|
|
625
|
-
typeof value['authorization_endpoint'] !== 'string' ||
|
|
626
|
-
typeof value['token_endpoint'] !== 'string' ||
|
|
627
|
-
(value['end_session_endpoint'] !== undefined &&
|
|
628
|
-
typeof value['end_session_endpoint'] !== 'string')
|
|
629
|
-
) {
|
|
630
|
-
return false;
|
|
631
|
-
}
|
|
632
|
-
try {
|
|
633
|
-
requiredUrl(value['authorization_endpoint'], 'OIDC authorization endpoint');
|
|
634
|
-
requiredUrl(value['token_endpoint'], 'OIDC token endpoint');
|
|
635
|
-
if (value['end_session_endpoint'] !== undefined) {
|
|
636
|
-
requiredUrl(value['end_session_endpoint'], 'OIDC end-session endpoint');
|
|
637
|
-
}
|
|
638
|
-
return true;
|
|
639
|
-
} catch {
|
|
640
|
-
return false;
|
|
641
|
-
}
|
|
642
|
-
}
|
|
643
|
-
|
|
644
|
-
function isObject(value: unknown): value is Record<string, unknown> {
|
|
645
|
-
return typeof value === 'object' && value !== null;
|
|
646
|
-
}
|
|
647
|
-
|
|
648
|
-
function browserEnvironment(): OidcClientEnvironment {
|
|
649
|
-
if (typeof window === 'undefined') {
|
|
650
|
-
throw new Error('OidcClient requires a browser environment or an explicit environment.');
|
|
651
|
-
}
|
|
652
|
-
return {
|
|
653
|
-
fetch: globalThis.fetch.bind(globalThis),
|
|
654
|
-
crypto: globalThis.crypto,
|
|
655
|
-
localStorage: window.localStorage,
|
|
656
|
-
sessionStorage: window.sessionStorage,
|
|
657
|
-
currentUrl: () => window.location.href,
|
|
658
|
-
navigate: (url) => {
|
|
659
|
-
window.location.assign(url);
|
|
660
|
-
},
|
|
661
|
-
replaceUrl: (url) => {
|
|
662
|
-
window.history.replaceState({}, '', url);
|
|
663
|
-
},
|
|
664
|
-
now: () => Date.now(),
|
|
665
|
-
};
|
|
666
|
-
}
|