@baukit/auth-web 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/package.json +2 -1
- package/src/index.test.ts +463 -0
- package/src/index.ts +695 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@baukit/auth-web",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.3",
|
|
4
4
|
"description": "Framework-neutral browser OIDC authorization-code client with S256 PKCE, provider discovery, and callback deduplication.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Patrick Koss",
|
|
@@ -30,6 +30,7 @@
|
|
|
30
30
|
},
|
|
31
31
|
"files": [
|
|
32
32
|
"dist",
|
|
33
|
+
"src",
|
|
33
34
|
"README.md",
|
|
34
35
|
"LICENSE"
|
|
35
36
|
],
|
|
@@ -0,0 +1,463 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
OidcClient,
|
|
5
|
+
OidcError,
|
|
6
|
+
buildAuthorizationUrl,
|
|
7
|
+
normalizeIssuer,
|
|
8
|
+
safeAuthErrorMessage,
|
|
9
|
+
type OidcClientEnvironment,
|
|
10
|
+
} from './index.js';
|
|
11
|
+
|
|
12
|
+
class MemoryStorage implements Storage {
|
|
13
|
+
private readonly values = new Map<string, string>();
|
|
14
|
+
|
|
15
|
+
public get length(): number {
|
|
16
|
+
return this.values.size;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
public clear(): void {
|
|
20
|
+
this.values.clear();
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
public getItem(key: string): string | null {
|
|
24
|
+
return this.values.get(key) ?? null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
public key(index: number): string | null {
|
|
28
|
+
return [...this.values.keys()][index] ?? null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
public removeItem(key: string): void {
|
|
32
|
+
this.values.delete(key);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
public setItem(key: string, value: string): void {
|
|
36
|
+
this.values.set(key, value);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface TestEnvironment {
|
|
41
|
+
readonly environment: OidcClientEnvironment;
|
|
42
|
+
readonly localStorage: MemoryStorage;
|
|
43
|
+
readonly sessionStorage: MemoryStorage;
|
|
44
|
+
readonly navigations: string[];
|
|
45
|
+
readonly replacements: string[];
|
|
46
|
+
setCurrentUrl(url: string): void;
|
|
47
|
+
setNow(value: number): void;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function makeEnvironment(fetchImplementation: typeof globalThis.fetch): TestEnvironment {
|
|
51
|
+
const localStorage = new MemoryStorage();
|
|
52
|
+
const sessionStorage = new MemoryStorage();
|
|
53
|
+
const navigations: string[] = [];
|
|
54
|
+
const replacements: string[] = [];
|
|
55
|
+
let currentUrl = 'https://app.example.test/';
|
|
56
|
+
let now = 1_000_000;
|
|
57
|
+
return {
|
|
58
|
+
environment: {
|
|
59
|
+
fetch: fetchImplementation,
|
|
60
|
+
crypto: globalThis.crypto,
|
|
61
|
+
localStorage,
|
|
62
|
+
sessionStorage,
|
|
63
|
+
currentUrl: () => currentUrl,
|
|
64
|
+
navigate: (url) => navigations.push(url),
|
|
65
|
+
replaceUrl: (url) => replacements.push(url),
|
|
66
|
+
now: () => now,
|
|
67
|
+
},
|
|
68
|
+
localStorage,
|
|
69
|
+
sessionStorage,
|
|
70
|
+
navigations,
|
|
71
|
+
replacements,
|
|
72
|
+
setCurrentUrl: (url) => {
|
|
73
|
+
currentUrl = url;
|
|
74
|
+
},
|
|
75
|
+
setNow: (value) => {
|
|
76
|
+
now = value;
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function jsonResponse(body: unknown, status = 200): Response {
|
|
82
|
+
return new Response(JSON.stringify(body), {
|
|
83
|
+
status,
|
|
84
|
+
headers: { 'content-type': 'application/json' },
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function required<T>(value: T | null | undefined): T {
|
|
89
|
+
if (value === undefined || value === null) {
|
|
90
|
+
throw new Error('Expected test value to be present.');
|
|
91
|
+
}
|
|
92
|
+
return value;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function discoveryResponse(): Response {
|
|
96
|
+
return jsonResponse({
|
|
97
|
+
issuer: 'https://identity.example.test/tenant',
|
|
98
|
+
authorization_endpoint: 'https://login.example.test/oauth/authorize',
|
|
99
|
+
token_endpoint: 'https://login.example.test/oauth/token',
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function storedTokens(overrides: Record<string, unknown> = {}): string {
|
|
104
|
+
return JSON.stringify({
|
|
105
|
+
accessToken: 'stored-access',
|
|
106
|
+
refreshToken: 'stored-refresh',
|
|
107
|
+
idToken: 'stored-id',
|
|
108
|
+
expiresAt: 900,
|
|
109
|
+
...overrides,
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function makeClient(test: TestEnvironment): OidcClient {
|
|
114
|
+
return new OidcClient(
|
|
115
|
+
{
|
|
116
|
+
issuer: 'https://identity.example.test/tenant',
|
|
117
|
+
clientId: 'product-web',
|
|
118
|
+
redirectUri: 'https://app.example.test/callback',
|
|
119
|
+
storageKeyPrefix: 'lifecycle',
|
|
120
|
+
},
|
|
121
|
+
test.environment,
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
describe('OidcClient', () => {
|
|
126
|
+
it('discovers endpoints and completes login, deduplicated callback, refresh, and logout', async () => {
|
|
127
|
+
const requests: { readonly url: string; readonly init: RequestInit | undefined }[] = [];
|
|
128
|
+
let tokenCalls = 0;
|
|
129
|
+
const mockedFetch: typeof globalThis.fetch = (input, init) => {
|
|
130
|
+
const url = input instanceof Request ? input.url : input.toString();
|
|
131
|
+
requests.push({ url, init });
|
|
132
|
+
if (url.endsWith('/.well-known/openid-configuration')) {
|
|
133
|
+
return Promise.resolve(
|
|
134
|
+
jsonResponse({
|
|
135
|
+
issuer: 'https://identity.example.test/tenant',
|
|
136
|
+
authorization_endpoint: 'https://login.example.test/oauth/authorize',
|
|
137
|
+
token_endpoint: 'https://login.example.test/oauth/token',
|
|
138
|
+
end_session_endpoint: 'https://login.example.test/session/end',
|
|
139
|
+
}),
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
tokenCalls += 1;
|
|
143
|
+
return Promise.resolve(
|
|
144
|
+
tokenCalls === 1
|
|
145
|
+
? jsonResponse({
|
|
146
|
+
access_token: 'access-secret',
|
|
147
|
+
refresh_token: 'refresh-secret',
|
|
148
|
+
id_token: 'identity-secret',
|
|
149
|
+
expires_in: 60,
|
|
150
|
+
})
|
|
151
|
+
: jsonResponse({ access_token: 'refreshed-secret', expires_in: 120 }),
|
|
152
|
+
);
|
|
153
|
+
};
|
|
154
|
+
const test = makeEnvironment(mockedFetch);
|
|
155
|
+
const client = new OidcClient(
|
|
156
|
+
{
|
|
157
|
+
issuer: 'https://identity.example.test/tenant///',
|
|
158
|
+
clientId: 'product-web',
|
|
159
|
+
redirectUri: 'https://app.example.test/callback',
|
|
160
|
+
scopes: ['profile', 'email', 'profile'],
|
|
161
|
+
offlineAccess: true,
|
|
162
|
+
storageKeyPrefix: 'test-auth',
|
|
163
|
+
},
|
|
164
|
+
test.environment,
|
|
165
|
+
);
|
|
166
|
+
|
|
167
|
+
await client.login();
|
|
168
|
+
const authorization = new URL(required(test.navigations[0]));
|
|
169
|
+
expect(authorization.origin + authorization.pathname).toBe(
|
|
170
|
+
'https://login.example.test/oauth/authorize',
|
|
171
|
+
);
|
|
172
|
+
expect(authorization.searchParams.get('scope')).toBe('openid profile email offline_access');
|
|
173
|
+
expect(authorization.searchParams.get('code_challenge_method')).toBe('S256');
|
|
174
|
+
expect(authorization.searchParams.get('code_challenge')).toMatch(/^[\w-]{43}$/u);
|
|
175
|
+
|
|
176
|
+
const transaction = JSON.parse(
|
|
177
|
+
required(test.sessionStorage.getItem('test-auth:transaction')),
|
|
178
|
+
) as {
|
|
179
|
+
readonly state: string;
|
|
180
|
+
};
|
|
181
|
+
test.setCurrentUrl(
|
|
182
|
+
`https://app.example.test/callback?code=one-time-code&state=${transaction.state}&session_state=private&iss=https%3A%2F%2Fidentity.example.test%2Ftenant&kept=yes`,
|
|
183
|
+
);
|
|
184
|
+
const firstCallback = client.handleCallback();
|
|
185
|
+
const repeatedCallback = client.handleCallback();
|
|
186
|
+
expect(firstCallback).toBe(repeatedCallback);
|
|
187
|
+
await expect(Promise.all([firstCallback, repeatedCallback])).resolves.toEqual([true, true]);
|
|
188
|
+
expect(tokenCalls).toBe(1);
|
|
189
|
+
expect(test.replacements).toEqual(['https://app.example.test/callback?kept=yes']);
|
|
190
|
+
expect(await client.accessToken()).toBe('access-secret');
|
|
191
|
+
|
|
192
|
+
test.setNow(1_031_000);
|
|
193
|
+
await expect(Promise.all([client.accessToken(), client.accessToken()])).resolves.toEqual([
|
|
194
|
+
'refreshed-secret',
|
|
195
|
+
'refreshed-secret',
|
|
196
|
+
]);
|
|
197
|
+
expect(tokenCalls).toBe(2);
|
|
198
|
+
const refreshBody = requests.at(-1)?.init?.body as URLSearchParams;
|
|
199
|
+
expect(refreshBody.get('grant_type')).toBe('refresh_token');
|
|
200
|
+
expect(refreshBody.get('refresh_token')).toBe('refresh-secret');
|
|
201
|
+
|
|
202
|
+
await expect(client.logout()).resolves.toBe(true);
|
|
203
|
+
const logout = new URL(required(test.navigations.at(-1)));
|
|
204
|
+
expect(logout.origin + logout.pathname).toBe('https://login.example.test/session/end');
|
|
205
|
+
expect(logout.searchParams.get('id_token_hint')).toBe('identity-secret');
|
|
206
|
+
expect(client.hasSession()).toBe(false);
|
|
207
|
+
expect(requests.filter(({ url }) => url.includes('.well-known')).length).toBe(1);
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
it('uses only discovered endpoints and makes offline access opt-in', () => {
|
|
211
|
+
const url = buildAuthorizationUrl(
|
|
212
|
+
{
|
|
213
|
+
clientId: 'client',
|
|
214
|
+
redirectUri: 'https://app.example.test/callback',
|
|
215
|
+
scopes: ['custom'],
|
|
216
|
+
},
|
|
217
|
+
'https://provider.example.test/non-keycloak/authorize',
|
|
218
|
+
{ state: 'state', challenge: 'challenge' },
|
|
219
|
+
);
|
|
220
|
+
expect(url.pathname).toBe('/non-keycloak/authorize');
|
|
221
|
+
expect(url.searchParams.get('scope')).toBe('openid custom');
|
|
222
|
+
expect(url.searchParams.has('offline_access')).toBe(false);
|
|
223
|
+
expect(normalizeIssuer('https://provider.example.test/path///')).toBe(
|
|
224
|
+
'https://provider.example.test/path',
|
|
225
|
+
);
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
it('shares one refresh across proactive and forced callers', async () => {
|
|
229
|
+
let resolveRefresh: ((response: Response) => void) | undefined;
|
|
230
|
+
let refreshCalls = 0;
|
|
231
|
+
const test = makeEnvironment((input) => {
|
|
232
|
+
const url = input instanceof Request ? input.url : input.toString();
|
|
233
|
+
if (url.includes('.well-known')) {
|
|
234
|
+
return Promise.resolve(discoveryResponse());
|
|
235
|
+
}
|
|
236
|
+
refreshCalls += 1;
|
|
237
|
+
return new Promise((resolve) => {
|
|
238
|
+
resolveRefresh = resolve;
|
|
239
|
+
});
|
|
240
|
+
});
|
|
241
|
+
test.localStorage.setItem('lifecycle:tokens', storedTokens());
|
|
242
|
+
const client = makeClient(test);
|
|
243
|
+
|
|
244
|
+
const proactive = client.accessToken();
|
|
245
|
+
const forced = client.accessToken({ forceRefresh: true });
|
|
246
|
+
await vi.waitFor(() => {
|
|
247
|
+
expect(refreshCalls).toBe(1);
|
|
248
|
+
});
|
|
249
|
+
resolveRefresh?.(
|
|
250
|
+
jsonResponse({
|
|
251
|
+
access_token: 'shared-access',
|
|
252
|
+
expires_in: 120,
|
|
253
|
+
}),
|
|
254
|
+
);
|
|
255
|
+
|
|
256
|
+
await expect(Promise.all([proactive, forced])).resolves.toEqual([
|
|
257
|
+
'shared-access',
|
|
258
|
+
'shared-access',
|
|
259
|
+
]);
|
|
260
|
+
expect(refreshCalls).toBe(1);
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
it('does not restore a session cleared while refresh is pending', async () => {
|
|
264
|
+
let resolveRefresh: ((response: Response) => void) | undefined;
|
|
265
|
+
const test = makeEnvironment((input) => {
|
|
266
|
+
const url = input instanceof Request ? input.url : input.toString();
|
|
267
|
+
if (url.includes('.well-known')) {
|
|
268
|
+
return Promise.resolve(discoveryResponse());
|
|
269
|
+
}
|
|
270
|
+
return new Promise((resolve) => {
|
|
271
|
+
resolveRefresh = resolve;
|
|
272
|
+
});
|
|
273
|
+
});
|
|
274
|
+
test.localStorage.setItem('lifecycle:tokens', storedTokens());
|
|
275
|
+
const client = makeClient(test);
|
|
276
|
+
|
|
277
|
+
const pending = client.accessToken();
|
|
278
|
+
await vi.waitFor(() => {
|
|
279
|
+
expect(resolveRefresh).toBeDefined();
|
|
280
|
+
});
|
|
281
|
+
client.clearSession();
|
|
282
|
+
resolveRefresh?.(jsonResponse({ access_token: 'stale-access', expires_in: 120 }));
|
|
283
|
+
|
|
284
|
+
await expect(pending).resolves.toBeUndefined();
|
|
285
|
+
expect(client.hasSession()).toBe(false);
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
it('forces refresh outside the proactive window and retains token rotation state', async () => {
|
|
289
|
+
let tokenCalls = 0;
|
|
290
|
+
const test = makeEnvironment((input) => {
|
|
291
|
+
const url = input instanceof Request ? input.url : input.toString();
|
|
292
|
+
if (url.includes('.well-known')) {
|
|
293
|
+
return Promise.resolve(discoveryResponse());
|
|
294
|
+
}
|
|
295
|
+
tokenCalls += 1;
|
|
296
|
+
return Promise.resolve(
|
|
297
|
+
jsonResponse({
|
|
298
|
+
access_token: 'forced-access',
|
|
299
|
+
expires_in: 120,
|
|
300
|
+
}),
|
|
301
|
+
);
|
|
302
|
+
});
|
|
303
|
+
test.localStorage.setItem('lifecycle:tokens', storedTokens({ expiresAt: 2_000_000 }));
|
|
304
|
+
const client = makeClient(test);
|
|
305
|
+
|
|
306
|
+
await expect(client.accessToken({ forceRefresh: true })).resolves.toBe('forced-access');
|
|
307
|
+
expect(tokenCalls).toBe(1);
|
|
308
|
+
expect(JSON.parse(required(test.localStorage.getItem('lifecycle:tokens')))).toMatchObject({
|
|
309
|
+
refreshToken: 'stored-refresh',
|
|
310
|
+
idToken: 'stored-id',
|
|
311
|
+
});
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
it('preserves the session and exposes a retryable transient refresh failure', async () => {
|
|
315
|
+
const test = makeEnvironment((input) => {
|
|
316
|
+
const url = input instanceof Request ? input.url : input.toString();
|
|
317
|
+
return Promise.resolve(
|
|
318
|
+
url.includes('.well-known')
|
|
319
|
+
? discoveryResponse()
|
|
320
|
+
: jsonResponse({ error: 'temporarily_unavailable' }, 503),
|
|
321
|
+
);
|
|
322
|
+
});
|
|
323
|
+
test.localStorage.setItem('lifecycle:tokens', storedTokens());
|
|
324
|
+
const client = makeClient(test);
|
|
325
|
+
|
|
326
|
+
await expect(client.accessToken()).rejects.toMatchObject({
|
|
327
|
+
code: 'refresh_failed',
|
|
328
|
+
retryable: true,
|
|
329
|
+
status: 503,
|
|
330
|
+
});
|
|
331
|
+
expect(client.hasSession()).toBe(true);
|
|
332
|
+
expect(test.localStorage.getItem('lifecycle:tokens')).not.toBeNull();
|
|
333
|
+
});
|
|
334
|
+
|
|
335
|
+
it.each([
|
|
336
|
+
[401, { error: 'provider_error' }],
|
|
337
|
+
[403, { error: 'invalid_grant' }],
|
|
338
|
+
] as const)('expires the session for terminal refresh rejection %#', async (status, body) => {
|
|
339
|
+
const test = makeEnvironment((input) => {
|
|
340
|
+
const url = input instanceof Request ? input.url : input.toString();
|
|
341
|
+
return Promise.resolve(
|
|
342
|
+
url.includes('.well-known') ? discoveryResponse() : jsonResponse(body, status),
|
|
343
|
+
);
|
|
344
|
+
});
|
|
345
|
+
test.localStorage.setItem('lifecycle:tokens', storedTokens());
|
|
346
|
+
const client = makeClient(test);
|
|
347
|
+
const expired: unknown[] = [];
|
|
348
|
+
client.subscribeSessionExpired((event) => expired.push(event));
|
|
349
|
+
|
|
350
|
+
await expect(client.accessToken()).resolves.toBeUndefined();
|
|
351
|
+
expect(client.hasSession()).toBe(false);
|
|
352
|
+
expect(expired).toEqual([{ type: 'session-expired', reason: 'refresh_rejected' }]);
|
|
353
|
+
});
|
|
354
|
+
|
|
355
|
+
it('sanitizes provider errors, response content, and unknown errors', async () => {
|
|
356
|
+
const leakedDescription = 'private content access-token-secret';
|
|
357
|
+
const fetchImplementation: typeof globalThis.fetch = () =>
|
|
358
|
+
Promise.resolve(
|
|
359
|
+
jsonResponse({
|
|
360
|
+
issuer: 'https://identity.example.test',
|
|
361
|
+
authorization_endpoint: 'https://identity.example.test/authorize',
|
|
362
|
+
token_endpoint: 'https://identity.example.test/token',
|
|
363
|
+
}),
|
|
364
|
+
);
|
|
365
|
+
const test = makeEnvironment(fetchImplementation);
|
|
366
|
+
test.sessionStorage.setItem(
|
|
367
|
+
'safe:transaction',
|
|
368
|
+
JSON.stringify({ state: 'expected', verifier: 'verifier' }),
|
|
369
|
+
);
|
|
370
|
+
test.setCurrentUrl(
|
|
371
|
+
`https://app.example.test/callback?error=access_denied&error_description=${encodeURIComponent(leakedDescription)}&state=expected`,
|
|
372
|
+
);
|
|
373
|
+
const client = new OidcClient(
|
|
374
|
+
{
|
|
375
|
+
issuer: 'https://identity.example.test',
|
|
376
|
+
clientId: 'client',
|
|
377
|
+
redirectUri: 'https://app.example.test/callback',
|
|
378
|
+
storageKeyPrefix: 'safe',
|
|
379
|
+
},
|
|
380
|
+
test.environment,
|
|
381
|
+
);
|
|
382
|
+
|
|
383
|
+
let caught: unknown;
|
|
384
|
+
try {
|
|
385
|
+
await client.handleCallback();
|
|
386
|
+
} catch (cause) {
|
|
387
|
+
caught = cause;
|
|
388
|
+
}
|
|
389
|
+
expect(caught).toBeInstanceOf(OidcError);
|
|
390
|
+
expect(safeAuthErrorMessage(caught)).toBe('OIDC authorization failed.');
|
|
391
|
+
expect(safeAuthErrorMessage(caught)).not.toContain(leakedDescription);
|
|
392
|
+
expect(safeAuthErrorMessage(new Error(leakedDescription))).toBe('OIDC login failed.');
|
|
393
|
+
expect(test.replacements[0]).not.toContain('error_description');
|
|
394
|
+
});
|
|
395
|
+
|
|
396
|
+
it('does not expose a token endpoint error body or authorization code', async () => {
|
|
397
|
+
const fetchImplementation: typeof globalThis.fetch = (input) => {
|
|
398
|
+
const url = input instanceof Request ? input.url : input.toString();
|
|
399
|
+
return Promise.resolve(
|
|
400
|
+
url.includes('.well-known')
|
|
401
|
+
? jsonResponse({
|
|
402
|
+
issuer: 'https://identity.example.test',
|
|
403
|
+
authorization_endpoint: 'https://identity.example.test/authorize',
|
|
404
|
+
token_endpoint: 'https://identity.example.test/token',
|
|
405
|
+
})
|
|
406
|
+
: new Response('private-content access-token-secret one-time-code', { status: 400 }),
|
|
407
|
+
);
|
|
408
|
+
};
|
|
409
|
+
const test = makeEnvironment(fetchImplementation);
|
|
410
|
+
test.sessionStorage.setItem(
|
|
411
|
+
'http-error:transaction',
|
|
412
|
+
JSON.stringify({ state: 'expected', verifier: 'verifier' }),
|
|
413
|
+
);
|
|
414
|
+
test.setCurrentUrl('https://app.example.test/callback?code=one-time-code&state=expected');
|
|
415
|
+
const client = new OidcClient(
|
|
416
|
+
{
|
|
417
|
+
issuer: 'https://identity.example.test',
|
|
418
|
+
clientId: 'client',
|
|
419
|
+
redirectUri: 'https://app.example.test/callback',
|
|
420
|
+
storageKeyPrefix: 'http-error',
|
|
421
|
+
},
|
|
422
|
+
test.environment,
|
|
423
|
+
);
|
|
424
|
+
|
|
425
|
+
let caught: unknown;
|
|
426
|
+
try {
|
|
427
|
+
await client.handleCallback();
|
|
428
|
+
} catch (cause) {
|
|
429
|
+
caught = cause;
|
|
430
|
+
}
|
|
431
|
+
expect(caught).toMatchObject({ code: 'token_exchange_failed', status: 400 });
|
|
432
|
+
expect(safeAuthErrorMessage(caught)).toBe('OIDC token exchange failed.');
|
|
433
|
+
expect(String(caught)).not.toContain('private-content');
|
|
434
|
+
expect(String(caught)).not.toContain('one-time-code');
|
|
435
|
+
});
|
|
436
|
+
|
|
437
|
+
it('rejects mismatched discovery issuers without exposing metadata content', async () => {
|
|
438
|
+
const fetchImplementation: typeof globalThis.fetch = () =>
|
|
439
|
+
Promise.resolve(
|
|
440
|
+
jsonResponse({
|
|
441
|
+
issuer: 'https://attacker.example.test/token-secret',
|
|
442
|
+
authorization_endpoint: 'https://attacker.example.test/authorize',
|
|
443
|
+
token_endpoint: 'https://attacker.example.test/token',
|
|
444
|
+
}),
|
|
445
|
+
);
|
|
446
|
+
const test = makeEnvironment(fetchImplementation);
|
|
447
|
+
const client = new OidcClient(
|
|
448
|
+
{
|
|
449
|
+
issuer: 'https://identity.example.test',
|
|
450
|
+
clientId: 'client',
|
|
451
|
+
redirectUri: 'https://app.example.test/callback',
|
|
452
|
+
},
|
|
453
|
+
test.environment,
|
|
454
|
+
);
|
|
455
|
+
await expect(client.discover()).rejects.toMatchObject({ code: 'issuer_mismatch' });
|
|
456
|
+
await client.discover().catch((error: unknown) => {
|
|
457
|
+
expect(safeAuthErrorMessage(error)).toBe(
|
|
458
|
+
'OIDC provider issuer did not match the configured issuer.',
|
|
459
|
+
);
|
|
460
|
+
expect(safeAuthErrorMessage(error)).not.toContain('token-secret');
|
|
461
|
+
});
|
|
462
|
+
});
|
|
463
|
+
});
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,695 @@
|
|
|
1
|
+
export type OidcErrorCode =
|
|
2
|
+
| 'authorization_failed'
|
|
3
|
+
| 'callback_state_mismatch'
|
|
4
|
+
| 'discovery_failed'
|
|
5
|
+
| 'invalid_discovery_document'
|
|
6
|
+
| 'invalid_token_response'
|
|
7
|
+
| 'issuer_mismatch'
|
|
8
|
+
| 'refresh_failed'
|
|
9
|
+
| 'token_exchange_failed';
|
|
10
|
+
|
|
11
|
+
const SAFE_ERROR_MESSAGES = {
|
|
12
|
+
authorization_failed: 'OIDC authorization failed.',
|
|
13
|
+
callback_state_mismatch: 'OIDC callback state did not match the login transaction.',
|
|
14
|
+
discovery_failed: 'OIDC provider discovery failed.',
|
|
15
|
+
invalid_discovery_document: 'OIDC provider returned invalid discovery metadata.',
|
|
16
|
+
invalid_token_response: 'OIDC token endpoint returned an invalid response.',
|
|
17
|
+
issuer_mismatch: 'OIDC provider issuer did not match the configured issuer.',
|
|
18
|
+
refresh_failed: 'OIDC token refresh failed.',
|
|
19
|
+
token_exchange_failed: 'OIDC token exchange failed.',
|
|
20
|
+
} as const satisfies Record<OidcErrorCode, string>;
|
|
21
|
+
|
|
22
|
+
/** An authentication failure whose message is safe to display or log. */
|
|
23
|
+
export class OidcError extends Error {
|
|
24
|
+
public readonly code: OidcErrorCode;
|
|
25
|
+
public readonly status: number | undefined;
|
|
26
|
+
/** True only when retrying the failed operation may succeed without signing in again. */
|
|
27
|
+
public readonly retryable: boolean;
|
|
28
|
+
|
|
29
|
+
public constructor(
|
|
30
|
+
code: OidcErrorCode,
|
|
31
|
+
options: { readonly retryable?: boolean; readonly status?: number } = {},
|
|
32
|
+
) {
|
|
33
|
+
super(SAFE_ERROR_MESSAGES[code]);
|
|
34
|
+
this.name = 'OidcError';
|
|
35
|
+
this.code = code;
|
|
36
|
+
this.status = options.status;
|
|
37
|
+
this.retryable = options.retryable ?? false;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface OidcClientConfig {
|
|
42
|
+
readonly issuer: string;
|
|
43
|
+
readonly clientId: string;
|
|
44
|
+
readonly redirectUri: string;
|
|
45
|
+
/** `openid` is prepended when omitted. Defaults to `openid profile email`. */
|
|
46
|
+
readonly scopes?: readonly string[];
|
|
47
|
+
/** Adds `offline_access` to the requested scopes. Defaults to false. */
|
|
48
|
+
readonly offlineAccess?: boolean;
|
|
49
|
+
/** Defaults to `redirectUri`. */
|
|
50
|
+
readonly postLogoutRedirectUri?: string;
|
|
51
|
+
/** Defaults to 30 seconds. */
|
|
52
|
+
readonly refreshLeewaySeconds?: number;
|
|
53
|
+
/** Overrides the deterministic, issuer/client-specific storage prefix. */
|
|
54
|
+
readonly storageKeyPrefix?: string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface OidcProviderMetadata {
|
|
58
|
+
readonly issuer: string;
|
|
59
|
+
readonly authorizationEndpoint: string;
|
|
60
|
+
readonly tokenEndpoint: string;
|
|
61
|
+
readonly endSessionEndpoint?: string;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface OidcClientEnvironment {
|
|
65
|
+
readonly fetch: typeof globalThis.fetch;
|
|
66
|
+
readonly crypto: Crypto;
|
|
67
|
+
readonly localStorage: Storage;
|
|
68
|
+
readonly sessionStorage: Storage;
|
|
69
|
+
readonly currentUrl: () => string;
|
|
70
|
+
readonly navigate: (url: string) => void;
|
|
71
|
+
readonly replaceUrl: (url: string) => void;
|
|
72
|
+
readonly now: () => number;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
interface NormalizedConfig {
|
|
76
|
+
readonly issuer: string;
|
|
77
|
+
readonly clientId: string;
|
|
78
|
+
readonly redirectUri: string;
|
|
79
|
+
readonly scopes: readonly string[];
|
|
80
|
+
readonly postLogoutRedirectUri: string;
|
|
81
|
+
readonly refreshLeewayMs: number;
|
|
82
|
+
readonly storageKeyPrefix: string;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
interface StoredTokens {
|
|
86
|
+
readonly accessToken: string;
|
|
87
|
+
readonly refreshToken?: string;
|
|
88
|
+
readonly idToken?: string;
|
|
89
|
+
readonly expiresAt: number;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
interface LoginTransaction {
|
|
93
|
+
readonly state: string;
|
|
94
|
+
readonly verifier: string;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
interface TokenResponse {
|
|
98
|
+
readonly access_token: string;
|
|
99
|
+
readonly expires_in: number;
|
|
100
|
+
readonly refresh_token?: string;
|
|
101
|
+
readonly id_token?: string;
|
|
102
|
+
}
|
|
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
|
+
type SessionExpiredListener = (event: SessionExpiredEvent) => void;
|
|
112
|
+
|
|
113
|
+
interface RawProviderMetadata {
|
|
114
|
+
readonly issuer: string;
|
|
115
|
+
readonly authorization_endpoint: string;
|
|
116
|
+
readonly token_endpoint: string;
|
|
117
|
+
readonly end_session_endpoint?: string;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export interface PkceAuthorizationRequest {
|
|
121
|
+
readonly state: string;
|
|
122
|
+
readonly challenge: string;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Removes trailing issuer slashes while rejecting query strings and fragments. */
|
|
126
|
+
export function normalizeIssuer(issuer: string): string {
|
|
127
|
+
const trimmed = issuer.trim();
|
|
128
|
+
if (trimmed.length === 0) {
|
|
129
|
+
throw new TypeError('OIDC issuer must not be empty.');
|
|
130
|
+
}
|
|
131
|
+
const url = new URL(trimmed);
|
|
132
|
+
if (url.search.length !== 0 || url.hash.length !== 0) {
|
|
133
|
+
throw new TypeError('OIDC issuer must not include a query string or fragment.');
|
|
134
|
+
}
|
|
135
|
+
return url.toString().replace(/\/+$/u, '');
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Builds an authorization request from the endpoint supplied by discovery. */
|
|
139
|
+
export function buildAuthorizationUrl(
|
|
140
|
+
config: Pick<OidcClientConfig, 'clientId' | 'redirectUri' | 'scopes' | 'offlineAccess'>,
|
|
141
|
+
authorizationEndpoint: string,
|
|
142
|
+
pkce: PkceAuthorizationRequest,
|
|
143
|
+
): URL {
|
|
144
|
+
const endpoint = new URL(authorizationEndpoint);
|
|
145
|
+
endpoint.search = new URLSearchParams({
|
|
146
|
+
client_id: requiredText(config.clientId, 'OIDC client ID'),
|
|
147
|
+
redirect_uri: requiredUrl(config.redirectUri, 'OIDC redirect URI'),
|
|
148
|
+
response_type: 'code',
|
|
149
|
+
scope: normalizeScopes(config.scopes, config.offlineAccess).join(' '),
|
|
150
|
+
state: pkce.state,
|
|
151
|
+
code_challenge: pkce.challenge,
|
|
152
|
+
code_challenge_method: 'S256',
|
|
153
|
+
}).toString();
|
|
154
|
+
return endpoint;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Returns an allowlisted message without reflecting untrusted error content. */
|
|
158
|
+
export function safeAuthErrorMessage(cause: unknown): string {
|
|
159
|
+
return cause instanceof OidcError ? SAFE_ERROR_MESSAGES[cause.code] : 'OIDC login failed.';
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Browser OIDC authorization-code client. It has no React dependency. */
|
|
163
|
+
export class OidcClient {
|
|
164
|
+
private readonly config: NormalizedConfig;
|
|
165
|
+
private readonly environment: OidcClientEnvironment;
|
|
166
|
+
private readonly tokenStorageKey: string;
|
|
167
|
+
private readonly transactionStorageKey: string;
|
|
168
|
+
private readonly sessionExpiredListeners = new Set<SessionExpiredListener>();
|
|
169
|
+
private metadataPromise: Promise<OidcProviderMetadata> | undefined;
|
|
170
|
+
private callbackPromise: Promise<boolean> | undefined;
|
|
171
|
+
private refreshPromise: Promise<string | undefined> | undefined;
|
|
172
|
+
private sessionRevision = 0;
|
|
173
|
+
|
|
174
|
+
public constructor(
|
|
175
|
+
config: OidcClientConfig,
|
|
176
|
+
environment: OidcClientEnvironment = browserEnvironment(),
|
|
177
|
+
) {
|
|
178
|
+
this.config = normalizeConfig(config);
|
|
179
|
+
this.environment = environment;
|
|
180
|
+
this.tokenStorageKey = `${this.config.storageKeyPrefix}:tokens`;
|
|
181
|
+
this.transactionStorageKey = `${this.config.storageKeyPrefix}:transaction`;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
public hasSession(): boolean {
|
|
185
|
+
return this.readTokens() !== undefined;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
public discover(): Promise<OidcProviderMetadata> {
|
|
189
|
+
this.metadataPromise ??= discoverProvider(this.config.issuer, this.environment.fetch);
|
|
190
|
+
return this.metadataPromise;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Observes terminal expiry separately from explicit logout or manual clearing. */
|
|
194
|
+
public subscribeSessionExpired(listener: SessionExpiredListener): () => void {
|
|
195
|
+
this.sessionExpiredListeners.add(listener);
|
|
196
|
+
return () => {
|
|
197
|
+
this.sessionExpiredListeners.delete(listener);
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
public async login(): Promise<void> {
|
|
202
|
+
const metadata = await this.discover();
|
|
203
|
+
const state = randomUrlSafe(this.environment.crypto, 32);
|
|
204
|
+
const verifier = randomUrlSafe(this.environment.crypto, 64);
|
|
205
|
+
const challenge = base64UrlEncode(
|
|
206
|
+
new Uint8Array(
|
|
207
|
+
await this.environment.crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier)),
|
|
208
|
+
),
|
|
209
|
+
);
|
|
210
|
+
this.environment.sessionStorage.setItem(
|
|
211
|
+
this.transactionStorageKey,
|
|
212
|
+
JSON.stringify({ state, verifier }),
|
|
213
|
+
);
|
|
214
|
+
const authorizationUrl = buildAuthorizationUrl(
|
|
215
|
+
{
|
|
216
|
+
clientId: this.config.clientId,
|
|
217
|
+
redirectUri: this.config.redirectUri,
|
|
218
|
+
scopes: this.config.scopes,
|
|
219
|
+
},
|
|
220
|
+
metadata.authorizationEndpoint,
|
|
221
|
+
{ state, challenge },
|
|
222
|
+
);
|
|
223
|
+
this.environment.navigate(authorizationUrl.toString());
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Returns one shared promise so repeated effects cannot exchange a code twice. */
|
|
227
|
+
public handleCallback(): Promise<boolean> {
|
|
228
|
+
this.callbackPromise ??= this.handleCallbackOnce();
|
|
229
|
+
return this.callbackPromise;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
public async accessToken(
|
|
233
|
+
options: { readonly forceRefresh?: boolean } = {},
|
|
234
|
+
): Promise<string | undefined> {
|
|
235
|
+
const tokens = this.readTokens();
|
|
236
|
+
if (tokens === undefined) {
|
|
237
|
+
return undefined;
|
|
238
|
+
}
|
|
239
|
+
if (
|
|
240
|
+
options.forceRefresh !== true &&
|
|
241
|
+
tokens.expiresAt > this.environment.now() + this.config.refreshLeewayMs
|
|
242
|
+
) {
|
|
243
|
+
return tokens.accessToken;
|
|
244
|
+
}
|
|
245
|
+
if (tokens.refreshToken === undefined) {
|
|
246
|
+
this.expireSession('refresh_unavailable');
|
|
247
|
+
return undefined;
|
|
248
|
+
}
|
|
249
|
+
if (this.refreshPromise !== undefined) {
|
|
250
|
+
return this.refreshPromise;
|
|
251
|
+
}
|
|
252
|
+
const pending = this.refresh(tokens, tokens.refreshToken);
|
|
253
|
+
this.refreshPromise = pending;
|
|
254
|
+
try {
|
|
255
|
+
return await pending;
|
|
256
|
+
} finally {
|
|
257
|
+
if (this.refreshPromise === pending) {
|
|
258
|
+
this.refreshPromise = undefined;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Clears local tokens and redirects through the discovered logout endpoint when available. */
|
|
264
|
+
public async logout(): Promise<boolean> {
|
|
265
|
+
const idToken = this.readTokens()?.idToken;
|
|
266
|
+
this.clearSession();
|
|
267
|
+
const metadata = await this.discover();
|
|
268
|
+
if (metadata.endSessionEndpoint === undefined) {
|
|
269
|
+
return false;
|
|
270
|
+
}
|
|
271
|
+
const endpoint = new URL(metadata.endSessionEndpoint);
|
|
272
|
+
endpoint.searchParams.set('client_id', this.config.clientId);
|
|
273
|
+
endpoint.searchParams.set('post_logout_redirect_uri', this.config.postLogoutRedirectUri);
|
|
274
|
+
if (idToken !== undefined) {
|
|
275
|
+
endpoint.searchParams.set('id_token_hint', idToken);
|
|
276
|
+
}
|
|
277
|
+
this.environment.navigate(endpoint.toString());
|
|
278
|
+
return true;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** Clears local authentication state without contacting the provider. */
|
|
282
|
+
public clearSession(): void {
|
|
283
|
+
this.sessionRevision += 1;
|
|
284
|
+
this.environment.localStorage.removeItem(this.tokenStorageKey);
|
|
285
|
+
this.environment.sessionStorage.removeItem(this.transactionStorageKey);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
private async handleCallbackOnce(): Promise<boolean> {
|
|
289
|
+
const callback = new URL(this.environment.currentUrl());
|
|
290
|
+
if (!hasCallbackParameters(callback)) {
|
|
291
|
+
return false;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
const code = callback.searchParams.get('code');
|
|
295
|
+
const returnedState = callback.searchParams.get('state');
|
|
296
|
+
const returnedIssuer = callback.searchParams.get('iss');
|
|
297
|
+
const providerError = callback.searchParams.has('error');
|
|
298
|
+
this.removeCallbackParameters(callback);
|
|
299
|
+
|
|
300
|
+
const transaction = readTransaction(
|
|
301
|
+
this.environment.sessionStorage.getItem(this.transactionStorageKey),
|
|
302
|
+
);
|
|
303
|
+
this.environment.sessionStorage.removeItem(this.transactionStorageKey);
|
|
304
|
+
if (returnedState === null || transaction?.state !== returnedState) {
|
|
305
|
+
throw new OidcError('callback_state_mismatch');
|
|
306
|
+
}
|
|
307
|
+
if (returnedIssuer !== null && normalizeIssuer(returnedIssuer) !== this.config.issuer) {
|
|
308
|
+
throw new OidcError('issuer_mismatch');
|
|
309
|
+
}
|
|
310
|
+
if (providerError) {
|
|
311
|
+
throw new OidcError('authorization_failed');
|
|
312
|
+
}
|
|
313
|
+
if (code === null) {
|
|
314
|
+
throw new OidcError('callback_state_mismatch');
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
const sessionRevision = this.sessionRevision;
|
|
318
|
+
const tokens = await this.exchange(
|
|
319
|
+
new URLSearchParams({
|
|
320
|
+
grant_type: 'authorization_code',
|
|
321
|
+
client_id: this.config.clientId,
|
|
322
|
+
redirect_uri: this.config.redirectUri,
|
|
323
|
+
code,
|
|
324
|
+
code_verifier: transaction.verifier,
|
|
325
|
+
}),
|
|
326
|
+
undefined,
|
|
327
|
+
'token_exchange_failed',
|
|
328
|
+
);
|
|
329
|
+
if (this.sessionRevision === sessionRevision) {
|
|
330
|
+
this.writeTokens(tokens);
|
|
331
|
+
}
|
|
332
|
+
return true;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
private removeCallbackParameters(callback: URL): void {
|
|
336
|
+
for (const parameter of [
|
|
337
|
+
'code',
|
|
338
|
+
'state',
|
|
339
|
+
'session_state',
|
|
340
|
+
'iss',
|
|
341
|
+
'error',
|
|
342
|
+
'error_description',
|
|
343
|
+
'error_uri',
|
|
344
|
+
]) {
|
|
345
|
+
callback.searchParams.delete(parameter);
|
|
346
|
+
}
|
|
347
|
+
this.environment.replaceUrl(callback.toString());
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
private async refresh(tokens: StoredTokens, refreshToken: string): Promise<string | undefined> {
|
|
351
|
+
const sessionRevision = this.sessionRevision;
|
|
352
|
+
try {
|
|
353
|
+
const refreshed = await this.exchange(
|
|
354
|
+
new URLSearchParams({
|
|
355
|
+
grant_type: 'refresh_token',
|
|
356
|
+
client_id: this.config.clientId,
|
|
357
|
+
refresh_token: refreshToken,
|
|
358
|
+
}),
|
|
359
|
+
tokens,
|
|
360
|
+
'refresh_failed',
|
|
361
|
+
);
|
|
362
|
+
if (this.sessionRevision !== sessionRevision) {
|
|
363
|
+
return this.readTokens()?.accessToken;
|
|
364
|
+
}
|
|
365
|
+
this.writeTokens(refreshed);
|
|
366
|
+
return refreshed.accessToken;
|
|
367
|
+
} catch (cause) {
|
|
368
|
+
if (isTerminalRefreshError(cause)) {
|
|
369
|
+
if (this.sessionRevision !== sessionRevision) {
|
|
370
|
+
return this.readTokens()?.accessToken;
|
|
371
|
+
}
|
|
372
|
+
this.expireSession('refresh_rejected');
|
|
373
|
+
return undefined;
|
|
374
|
+
}
|
|
375
|
+
throw transientRefreshError(cause);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
private async exchange(
|
|
380
|
+
body: URLSearchParams,
|
|
381
|
+
existingTokens: StoredTokens | undefined,
|
|
382
|
+
failureCode: 'refresh_failed' | 'token_exchange_failed',
|
|
383
|
+
): Promise<StoredTokens> {
|
|
384
|
+
const metadata = await this.discover();
|
|
385
|
+
let response: Response;
|
|
386
|
+
try {
|
|
387
|
+
response = await this.environment.fetch(metadata.tokenEndpoint, {
|
|
388
|
+
method: 'POST',
|
|
389
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
|
390
|
+
body,
|
|
391
|
+
});
|
|
392
|
+
} catch {
|
|
393
|
+
throw new OidcError(failureCode, { retryable: failureCode === 'refresh_failed' });
|
|
394
|
+
}
|
|
395
|
+
const receivedAt = this.environment.now();
|
|
396
|
+
if (!response.ok) {
|
|
397
|
+
const providerError = await readProviderError(response);
|
|
398
|
+
throw new OidcError(failureCode, {
|
|
399
|
+
status: response.status,
|
|
400
|
+
retryable:
|
|
401
|
+
failureCode === 'refresh_failed' &&
|
|
402
|
+
!isTerminalRefreshRejection(response.status, providerError),
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
let payload: unknown;
|
|
407
|
+
try {
|
|
408
|
+
payload = await response.json();
|
|
409
|
+
} catch {
|
|
410
|
+
throw new OidcError('invalid_token_response');
|
|
411
|
+
}
|
|
412
|
+
if (!isTokenResponse(payload)) {
|
|
413
|
+
throw new OidcError('invalid_token_response');
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
const refreshToken = payload.refresh_token ?? existingTokens?.refreshToken;
|
|
417
|
+
const idToken = payload.id_token ?? existingTokens?.idToken;
|
|
418
|
+
const tokens: StoredTokens = {
|
|
419
|
+
accessToken: payload.access_token,
|
|
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
|
+
const event: SessionExpiredEvent = { type: 'session-expired', reason };
|
|
435
|
+
for (const listener of this.sessionExpiredListeners) {
|
|
436
|
+
try {
|
|
437
|
+
listener(event);
|
|
438
|
+
} catch {
|
|
439
|
+
// Observers cannot change the terminal unauthenticated result.
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
private readTokens(): StoredTokens | undefined {
|
|
445
|
+
const raw = this.environment.localStorage.getItem(this.tokenStorageKey);
|
|
446
|
+
if (raw === null) {
|
|
447
|
+
return undefined;
|
|
448
|
+
}
|
|
449
|
+
try {
|
|
450
|
+
const value: unknown = JSON.parse(raw);
|
|
451
|
+
if (isStoredTokens(value)) {
|
|
452
|
+
return value;
|
|
453
|
+
}
|
|
454
|
+
} catch {
|
|
455
|
+
// Invalid state is discarded below without reflecting its content.
|
|
456
|
+
}
|
|
457
|
+
this.environment.localStorage.removeItem(this.tokenStorageKey);
|
|
458
|
+
this.sessionRevision += 1;
|
|
459
|
+
return undefined;
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
async function readProviderError(response: Response): Promise<string | undefined> {
|
|
464
|
+
try {
|
|
465
|
+
const value: unknown = await response.json();
|
|
466
|
+
return isObject(value) && typeof value['error'] === 'string' ? value['error'] : undefined;
|
|
467
|
+
} catch {
|
|
468
|
+
return undefined;
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
function isTerminalRefreshRejection(status: number, providerError: string | undefined): boolean {
|
|
473
|
+
return (
|
|
474
|
+
status === 400 ||
|
|
475
|
+
status === 401 ||
|
|
476
|
+
providerError === 'invalid_grant' ||
|
|
477
|
+
providerError === 'invalid_token'
|
|
478
|
+
);
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
function isTerminalRefreshError(cause: unknown): boolean {
|
|
482
|
+
return cause instanceof OidcError && cause.code === 'refresh_failed' && !cause.retryable;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
function transientRefreshError(cause: unknown): OidcError {
|
|
486
|
+
if (cause instanceof OidcError && cause.code === 'refresh_failed' && cause.retryable) {
|
|
487
|
+
return cause;
|
|
488
|
+
}
|
|
489
|
+
return new OidcError('refresh_failed', {
|
|
490
|
+
retryable: true,
|
|
491
|
+
...(cause instanceof OidcError && cause.status !== undefined ? { status: cause.status } : {}),
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
async function discoverProvider(
|
|
496
|
+
issuer: string,
|
|
497
|
+
fetchImplementation: typeof globalThis.fetch,
|
|
498
|
+
): Promise<OidcProviderMetadata> {
|
|
499
|
+
let response: Response;
|
|
500
|
+
try {
|
|
501
|
+
response = await fetchImplementation(`${issuer}/.well-known/openid-configuration`);
|
|
502
|
+
} catch {
|
|
503
|
+
throw new OidcError('discovery_failed');
|
|
504
|
+
}
|
|
505
|
+
if (!response.ok) {
|
|
506
|
+
throw new OidcError('discovery_failed', { status: response.status });
|
|
507
|
+
}
|
|
508
|
+
let value: unknown;
|
|
509
|
+
try {
|
|
510
|
+
value = await response.json();
|
|
511
|
+
} catch {
|
|
512
|
+
throw new OidcError('invalid_discovery_document');
|
|
513
|
+
}
|
|
514
|
+
if (!isProviderMetadata(value)) {
|
|
515
|
+
throw new OidcError('invalid_discovery_document');
|
|
516
|
+
}
|
|
517
|
+
if (normalizeIssuer(value.issuer) !== issuer) {
|
|
518
|
+
throw new OidcError('issuer_mismatch');
|
|
519
|
+
}
|
|
520
|
+
return {
|
|
521
|
+
issuer,
|
|
522
|
+
authorizationEndpoint: value.authorization_endpoint,
|
|
523
|
+
tokenEndpoint: value.token_endpoint,
|
|
524
|
+
...(value.end_session_endpoint === undefined
|
|
525
|
+
? {}
|
|
526
|
+
: { endSessionEndpoint: value.end_session_endpoint }),
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
function normalizeConfig(config: OidcClientConfig): NormalizedConfig {
|
|
531
|
+
const issuer = normalizeIssuer(config.issuer);
|
|
532
|
+
const clientId = requiredText(config.clientId, 'OIDC client ID');
|
|
533
|
+
const redirectUri = requiredUrl(config.redirectUri, 'OIDC redirect URI');
|
|
534
|
+
const refreshLeewaySeconds = config.refreshLeewaySeconds ?? 30;
|
|
535
|
+
if (!Number.isFinite(refreshLeewaySeconds) || refreshLeewaySeconds < 0) {
|
|
536
|
+
throw new RangeError('OIDC refresh leeway must be a non-negative number.');
|
|
537
|
+
}
|
|
538
|
+
const storageKeyPrefix =
|
|
539
|
+
config.storageKeyPrefix ?? `@baukit/auth-web:${encodeURIComponent(issuer)}:${clientId}`;
|
|
540
|
+
if (storageKeyPrefix.length === 0) {
|
|
541
|
+
throw new TypeError('OIDC storage key prefix must not be empty.');
|
|
542
|
+
}
|
|
543
|
+
return {
|
|
544
|
+
issuer,
|
|
545
|
+
clientId,
|
|
546
|
+
redirectUri,
|
|
547
|
+
scopes: normalizeScopes(config.scopes, config.offlineAccess),
|
|
548
|
+
postLogoutRedirectUri: requiredUrl(
|
|
549
|
+
config.postLogoutRedirectUri ?? redirectUri,
|
|
550
|
+
'OIDC post-logout redirect URI',
|
|
551
|
+
),
|
|
552
|
+
refreshLeewayMs: refreshLeewaySeconds * 1000,
|
|
553
|
+
storageKeyPrefix,
|
|
554
|
+
};
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
function normalizeScopes(scopes: readonly string[] | undefined, offlineAccess = false): string[] {
|
|
558
|
+
const requested = scopes ?? ['openid', 'profile', 'email'];
|
|
559
|
+
const normalized: string[] = [];
|
|
560
|
+
for (const scope of ['openid', ...requested, ...(offlineAccess ? ['offline_access'] : [])]) {
|
|
561
|
+
const trimmed = scope.trim();
|
|
562
|
+
if (trimmed.length === 0 || /\s/u.test(trimmed)) {
|
|
563
|
+
throw new TypeError('OIDC scopes must be non-empty and contain no whitespace.');
|
|
564
|
+
}
|
|
565
|
+
if (!normalized.includes(trimmed)) {
|
|
566
|
+
normalized.push(trimmed);
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
return normalized;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
function requiredText(value: string, label: string): string {
|
|
573
|
+
const trimmed = value.trim();
|
|
574
|
+
if (trimmed.length === 0) {
|
|
575
|
+
throw new TypeError(`${label} must not be empty.`);
|
|
576
|
+
}
|
|
577
|
+
return trimmed;
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
function requiredUrl(value: string, label: string): string {
|
|
581
|
+
const trimmed = requiredText(value, label);
|
|
582
|
+
try {
|
|
583
|
+
return new URL(trimmed).toString();
|
|
584
|
+
} catch {
|
|
585
|
+
throw new TypeError(`${label} must be an absolute URL.`);
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
function hasCallbackParameters(url: URL): boolean {
|
|
590
|
+
return ['code', 'state', 'error', 'iss', 'session_state'].some((name) =>
|
|
591
|
+
url.searchParams.has(name),
|
|
592
|
+
);
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
function randomUrlSafe(cryptoImplementation: Crypto, byteLength: number): string {
|
|
596
|
+
return base64UrlEncode(cryptoImplementation.getRandomValues(new Uint8Array(byteLength)));
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
function base64UrlEncode(bytes: Uint8Array): string {
|
|
600
|
+
let binary = '';
|
|
601
|
+
for (const byte of bytes) {
|
|
602
|
+
binary += String.fromCharCode(byte);
|
|
603
|
+
}
|
|
604
|
+
return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/u, '');
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
function readTransaction(raw: string | null): LoginTransaction | undefined {
|
|
608
|
+
if (raw === null) {
|
|
609
|
+
return undefined;
|
|
610
|
+
}
|
|
611
|
+
try {
|
|
612
|
+
const value: unknown = JSON.parse(raw);
|
|
613
|
+
return isObject(value) &&
|
|
614
|
+
typeof value['state'] === 'string' &&
|
|
615
|
+
value['state'].length > 0 &&
|
|
616
|
+
typeof value['verifier'] === 'string' &&
|
|
617
|
+
value['verifier'].length > 0
|
|
618
|
+
? { state: value['state'], verifier: value['verifier'] }
|
|
619
|
+
: undefined;
|
|
620
|
+
} catch {
|
|
621
|
+
return undefined;
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
function isStoredTokens(value: unknown): value is StoredTokens {
|
|
626
|
+
return (
|
|
627
|
+
isObject(value) &&
|
|
628
|
+
typeof value['accessToken'] === 'string' &&
|
|
629
|
+
value['accessToken'].length > 0 &&
|
|
630
|
+
typeof value['expiresAt'] === 'number' &&
|
|
631
|
+
Number.isFinite(value['expiresAt']) &&
|
|
632
|
+
(value['refreshToken'] === undefined || typeof value['refreshToken'] === 'string') &&
|
|
633
|
+
(value['idToken'] === undefined || typeof value['idToken'] === 'string')
|
|
634
|
+
);
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
function isTokenResponse(value: unknown): value is TokenResponse {
|
|
638
|
+
return (
|
|
639
|
+
isObject(value) &&
|
|
640
|
+
typeof value['access_token'] === 'string' &&
|
|
641
|
+
value['access_token'].length > 0 &&
|
|
642
|
+
typeof value['expires_in'] === 'number' &&
|
|
643
|
+
Number.isFinite(value['expires_in']) &&
|
|
644
|
+
value['expires_in'] > 0 &&
|
|
645
|
+
(value['refresh_token'] === undefined || typeof value['refresh_token'] === 'string') &&
|
|
646
|
+
(value['id_token'] === undefined || typeof value['id_token'] === 'string')
|
|
647
|
+
);
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
function isProviderMetadata(value: unknown): value is RawProviderMetadata {
|
|
651
|
+
if (
|
|
652
|
+
!isObject(value) ||
|
|
653
|
+
typeof value['issuer'] !== 'string' ||
|
|
654
|
+
typeof value['authorization_endpoint'] !== 'string' ||
|
|
655
|
+
typeof value['token_endpoint'] !== 'string' ||
|
|
656
|
+
(value['end_session_endpoint'] !== undefined &&
|
|
657
|
+
typeof value['end_session_endpoint'] !== 'string')
|
|
658
|
+
) {
|
|
659
|
+
return false;
|
|
660
|
+
}
|
|
661
|
+
try {
|
|
662
|
+
requiredUrl(value['authorization_endpoint'], 'OIDC authorization endpoint');
|
|
663
|
+
requiredUrl(value['token_endpoint'], 'OIDC token endpoint');
|
|
664
|
+
if (value['end_session_endpoint'] !== undefined) {
|
|
665
|
+
requiredUrl(value['end_session_endpoint'], 'OIDC end-session endpoint');
|
|
666
|
+
}
|
|
667
|
+
return true;
|
|
668
|
+
} catch {
|
|
669
|
+
return false;
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
function isObject(value: unknown): value is Record<string, unknown> {
|
|
674
|
+
return typeof value === 'object' && value !== null;
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
function browserEnvironment(): OidcClientEnvironment {
|
|
678
|
+
if (typeof window === 'undefined') {
|
|
679
|
+
throw new Error('OidcClient requires a browser environment or an explicit environment.');
|
|
680
|
+
}
|
|
681
|
+
return {
|
|
682
|
+
fetch: globalThis.fetch.bind(globalThis),
|
|
683
|
+
crypto: globalThis.crypto,
|
|
684
|
+
localStorage: window.localStorage,
|
|
685
|
+
sessionStorage: window.sessionStorage,
|
|
686
|
+
currentUrl: () => window.location.href,
|
|
687
|
+
navigate: (url) => {
|
|
688
|
+
window.location.assign(url);
|
|
689
|
+
},
|
|
690
|
+
replaceUrl: (url) => {
|
|
691
|
+
window.history.replaceState({}, '', url);
|
|
692
|
+
},
|
|
693
|
+
now: () => Date.now(),
|
|
694
|
+
};
|
|
695
|
+
}
|