@baukit/auth-web 0.18.2 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +78 -33
  2. package/dist/browser-session-client.d.ts +85 -0
  3. package/dist/browser-session-client.d.ts.map +1 -0
  4. package/dist/browser-session-client.js +339 -0
  5. package/dist/browser-session-client.js.map +1 -0
  6. package/dist/browser-session-support.d.ts +44 -0
  7. package/dist/browser-session-support.d.ts.map +1 -0
  8. package/dist/browser-session-support.js +102 -0
  9. package/dist/browser-session-support.js.map +1 -0
  10. package/dist/clerk.d.ts +1 -1
  11. package/dist/clerk.d.ts.map +1 -1
  12. package/dist/clerk.js.map +1 -1
  13. package/dist/index.d.ts +5 -95
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +3 -466
  16. package/dist/index.js.map +1 -1
  17. package/dist/oidc-client.d.ts +67 -0
  18. package/dist/oidc-client.d.ts.map +1 -0
  19. package/dist/oidc-client.js +135 -0
  20. package/dist/oidc-client.js.map +1 -0
  21. package/dist/oidc-errors.d.ts +15 -0
  22. package/dist/oidc-errors.d.ts.map +1 -0
  23. package/dist/oidc-errors.js +30 -0
  24. package/dist/oidc-errors.js.map +1 -0
  25. package/dist/oidc-helpers.d.ts +1 -1
  26. package/dist/oidc-helpers.d.ts.map +1 -1
  27. package/dist/oidc-validation.d.ts +15 -0
  28. package/dist/oidc-validation.d.ts.map +1 -0
  29. package/dist/oidc-validation.js +76 -0
  30. package/dist/oidc-validation.js.map +1 -0
  31. package/dist/session-events.d.ts +10 -0
  32. package/dist/session-events.d.ts.map +1 -0
  33. package/dist/session-events.js +2 -0
  34. package/dist/session-events.js.map +1 -0
  35. package/dist/silent-token-broker.d.ts.map +1 -1
  36. package/dist/silent-token-broker.js +39 -28
  37. package/dist/silent-token-broker.js.map +1 -1
  38. package/dist/workos.d.ts +1 -1
  39. package/dist/workos.d.ts.map +1 -1
  40. package/dist/workos.js +1 -1
  41. package/dist/workos.js.map +1 -1
  42. package/package.json +5 -3
  43. package/src/browser-session-client.test.ts +426 -0
  44. package/src/browser-session-client.ts +414 -0
  45. package/src/browser-session-refresh.test.ts +58 -0
  46. package/src/browser-session-storage.test.ts +113 -0
  47. package/src/browser-session-support.ts +153 -0
  48. package/src/clerk.ts +5 -1
  49. package/src/index.test.ts +98 -594
  50. package/src/index.ts +28 -663
  51. package/src/oidc-client.ts +229 -0
  52. package/src/oidc-errors.ts +46 -0
  53. package/src/oidc-helpers.ts +1 -1
  54. package/src/oidc-validation.ts +93 -0
  55. package/src/session-events.ts +12 -0
  56. package/src/silent-token-broker.ts +49 -33
  57. package/src/test-support/browser-session.ts +203 -0
  58. package/src/test-support/session-backend.ts +104 -0
  59. package/src/workos.ts +6 -6
@@ -0,0 +1,414 @@
1
+ import {
2
+ browserSessionEnvironment,
3
+ isIssuedSession,
4
+ readAccountHint,
5
+ readEndSessionUrl,
6
+ readSessionMessage,
7
+ type AccountHint,
8
+ type BrowserSessionEnvironment,
9
+ type IssuedSession,
10
+ type SessionChannel,
11
+ type SessionMessage,
12
+ type SignedOutCause,
13
+ } from './browser-session-support.js';
14
+ import { OidcClient, type OidcClientConfig } from './oidc-client.js';
15
+ import { OidcError } from './oidc-errors.js';
16
+ import { requiredUrl } from './oidc-helpers.js';
17
+ import type {
18
+ ClearSessionOptions,
19
+ SessionExpiredEvent,
20
+ SessionExpiredListener,
21
+ SessionExpiredReason,
22
+ } from './session-events.js';
23
+
24
+ export interface BrowserSessionClientConfig extends OidcClientConfig {
25
+ /** Origin (and optional base path) of the backend that mounts `/auth/session`. */
26
+ readonly apiBaseUrl: string;
27
+ /** Defaults to 30 seconds. */
28
+ readonly refreshLeewaySeconds?: number;
29
+ }
30
+
31
+ export const BROWSER_SESSION_PATH = '/auth/session';
32
+ export const BROWSER_SESSION_HEADER = 'X-Baukit-Session';
33
+
34
+ const DEFAULT_REFRESH_LEEWAY_SECONDS = 30;
35
+ const MS_PER_SECOND = 1000;
36
+ const HTTP_NO_CONTENT = 204;
37
+ const HTTP_UNAUTHORIZED = 401;
38
+ const HTTP_TOO_MANY_REQUESTS = 429;
39
+ const HTTP_SERVER_ERROR = 500;
40
+ /** How long a tab that waited for the refresh lock waits for the winner's token. */
41
+ export const SESSION_HANDOFF_TIMEOUT_MS = 2000;
42
+
43
+ type SessionEndpoint = 'exchange' | 'refresh' | 'logout';
44
+
45
+ interface MemoryToken extends IssuedSession {
46
+ readonly receivedAt: number;
47
+ }
48
+
49
+ /**
50
+ * Browser sign-in against the product backend's `/auth/session` routes. The
51
+ * backend holds the refresh token behind an HttpOnly cookie; the access token
52
+ * lives only in this object's memory.
53
+ */
54
+ export class BrowserSessionClient {
55
+ private readonly oidc: OidcClient;
56
+ private readonly environment: BrowserSessionEnvironment;
57
+ private readonly sessionBaseUrl: string;
58
+ private readonly refreshLeewayMs: number;
59
+ private readonly accountStorageKey: string;
60
+ private readonly lockName: string;
61
+ private readonly generationStorageKey: string;
62
+ private readonly sessionWaiters = new Set<() => void>();
63
+ private readonly channel: SessionChannel | undefined;
64
+ private readonly listeners = new Set<SessionExpiredListener>();
65
+ private token: MemoryToken | undefined;
66
+ private callbackPromise: Promise<boolean> | undefined;
67
+ private refreshPromise: Promise<string | undefined> | undefined;
68
+ private revision = 0;
69
+
70
+ public constructor(
71
+ config: BrowserSessionClientConfig,
72
+ environment: BrowserSessionEnvironment = browserSessionEnvironment(),
73
+ ) {
74
+ this.oidc = new OidcClient(config, environment);
75
+ this.environment = environment;
76
+ this.sessionBaseUrl = `${requiredUrl(config.apiBaseUrl, 'API base URL').replace(/\/+$/u, '')}${BROWSER_SESSION_PATH}`;
77
+ this.refreshLeewayMs = refreshLeewayMs(config.refreshLeewaySeconds);
78
+ const prefix = this.oidc.storageKeyPrefix;
79
+ this.accountStorageKey = `${prefix}:account`;
80
+ this.lockName = `${prefix}:refresh`;
81
+ this.generationStorageKey = `${prefix}:session-generation`;
82
+ this.channel = environment.openChannel?.(`${prefix}:session`);
83
+ this.channel?.subscribe((message) => {
84
+ this.receive(readSessionMessage(message));
85
+ });
86
+ }
87
+
88
+ /** True while a token is in memory or the account hint says this browser signed in. */
89
+ public hasSession(): boolean {
90
+ return this.token !== undefined || this.account() !== undefined;
91
+ }
92
+
93
+ /** The signed-in account, readable offline. */
94
+ public account(): AccountHint | undefined {
95
+ return readAccountHint(this.environment.localStorage.getItem(this.accountStorageKey));
96
+ }
97
+
98
+ public login(): Promise<void> {
99
+ return this.oidc.login();
100
+ }
101
+
102
+ /** Returns one shared promise so repeated effects cannot redeem a code twice. */
103
+ public handleCallback(): Promise<boolean> {
104
+ this.callbackPromise ??= this.handleCallbackOnce();
105
+ return this.callbackPromise;
106
+ }
107
+
108
+ /** Refreshes once when an account hint exists, as on page load. */
109
+ public async restore(): Promise<boolean> {
110
+ return (await this.getAccessToken()) !== undefined;
111
+ }
112
+
113
+ /**
114
+ * Resolves the in-memory access token, refreshing it near expiry or when
115
+ * forced. A network failure rejects with a retryable `OidcError` and keeps
116
+ * the account hint; only a 401 signs out.
117
+ */
118
+ public getAccessToken(
119
+ options: { readonly forceRefresh?: boolean } = {},
120
+ ): Promise<string | undefined> {
121
+ const token = this.token;
122
+ if (token !== undefined && options.forceRefresh !== true && this.isFresh(token)) {
123
+ return Promise.resolve(token.accessToken);
124
+ }
125
+ if (token === undefined && this.account() === undefined) {
126
+ return Promise.resolve(undefined);
127
+ }
128
+ this.refreshPromise ??= this.coordinatedRefresh(this.revision).finally(() => {
129
+ this.refreshPromise = undefined;
130
+ });
131
+ return this.refreshPromise;
132
+ }
133
+
134
+ public accessToken(
135
+ options: { readonly forceRefresh?: boolean } = {},
136
+ ): Promise<string | undefined> {
137
+ return this.getAccessToken(options);
138
+ }
139
+
140
+ /** Observes sign-out by expiry, erasure or another tab, not this tab's own `clearSession()`. */
141
+ public onSessionExpired(listener: SessionExpiredListener): () => void {
142
+ this.listeners.add(listener);
143
+ return () => {
144
+ this.listeners.delete(listener);
145
+ };
146
+ }
147
+
148
+ public subscribeSessionExpired(listener: SessionExpiredListener): () => void {
149
+ return this.onSessionExpired(listener);
150
+ }
151
+
152
+ /**
153
+ * Signs out every tab, ends the backend session and navigates to the IdP
154
+ * end-session URL when the backend returns one.
155
+ */
156
+ public async logout(): Promise<boolean> {
157
+ this.clearSession();
158
+ let response: Response;
159
+ try {
160
+ response = await this.post('logout');
161
+ } catch {
162
+ throw new OidcError('logout_failed', { retryable: true });
163
+ }
164
+ if (response.status === HTTP_NO_CONTENT) {
165
+ return false;
166
+ }
167
+ if (!response.ok) {
168
+ throw new OidcError('logout_failed', { status: response.status });
169
+ }
170
+ const endSessionUrl = readEndSessionUrl(await readJson(response));
171
+ if (endSessionUrl === undefined) {
172
+ return false;
173
+ }
174
+ this.environment.navigate(endSessionUrl);
175
+ return true;
176
+ }
177
+
178
+ /** Clears local state in every tab without contacting the backend. */
179
+ public clearSession(options: ClearSessionOptions = {}): void {
180
+ if (options.reason !== undefined) {
181
+ this.expire(options.reason);
182
+ return;
183
+ }
184
+ this.clearLocal();
185
+ this.broadcast({ type: 'signed-out', cause: 'cleared' });
186
+ }
187
+
188
+ public dispose(): void {
189
+ this.channel?.close();
190
+ }
191
+
192
+ private async handleCallbackOnce(): Promise<boolean> {
193
+ const callback = this.oidc.completeCallback();
194
+ if (callback === undefined) {
195
+ return false;
196
+ }
197
+ const revision = this.revision;
198
+ let response: Response;
199
+ try {
200
+ response = await this.post('exchange', callback);
201
+ } catch {
202
+ throw new OidcError('token_exchange_failed');
203
+ }
204
+ if (!response.ok) {
205
+ throw new OidcError('token_exchange_failed', { status: response.status });
206
+ }
207
+ const session = await readIssuedSession(response);
208
+ if (this.revision === revision) {
209
+ this.accept(session, { newSignIn: true });
210
+ this.oidc.confirmFreshLogin();
211
+ }
212
+ return true;
213
+ }
214
+
215
+ private coordinatedRefresh(requestedAt: number): Promise<string | undefined> {
216
+ const generation = this.sessionGeneration();
217
+ const run = () => this.refreshUnlessSettled(requestedAt, generation);
218
+ const locks = this.environment.locks;
219
+ return locks === undefined ? run() : locks.request(this.lockName, run);
220
+ }
221
+
222
+ /** Skips the request when another tab refreshed or signed out while this one waited. */
223
+ private async refreshUnlessSettled(
224
+ requestedAt: number,
225
+ generation: number,
226
+ ): Promise<string | undefined> {
227
+ if (this.revision === requestedAt && this.sessionGeneration() !== generation) {
228
+ await this.nextSession();
229
+ }
230
+ const current = this.token;
231
+ if (this.revision !== requestedAt) {
232
+ if (current === undefined) {
233
+ return undefined;
234
+ }
235
+ if (this.isFresh(current)) {
236
+ return current.accessToken;
237
+ }
238
+ }
239
+ const revision = this.revision;
240
+ let response: Response;
241
+ try {
242
+ response = await this.post('refresh');
243
+ } catch {
244
+ throw new OidcError('refresh_failed', { retryable: true });
245
+ }
246
+ if (response.status === HTTP_UNAUTHORIZED) {
247
+ if (this.revision === revision) {
248
+ this.expire('refresh_rejected');
249
+ }
250
+ return this.token?.accessToken;
251
+ }
252
+ if (!response.ok) {
253
+ throw new OidcError('refresh_failed', {
254
+ status: response.status,
255
+ retryable: isRetryableStatus(response.status),
256
+ });
257
+ }
258
+ const session = await readIssuedSession(response);
259
+ if (this.revision !== revision) {
260
+ return this.token?.accessToken;
261
+ }
262
+ this.accept(session, { newSignIn: false });
263
+ return session.accessToken;
264
+ }
265
+
266
+ private accept(session: IssuedSession, options: { readonly newSignIn: boolean }): void {
267
+ this.remember(session);
268
+ this.environment.localStorage.setItem(
269
+ this.generationStorageKey,
270
+ String(this.sessionGeneration() + 1),
271
+ );
272
+ const hint = this.account();
273
+ if (options.newSignIn || hint?.subject !== session.subject) {
274
+ const next: AccountHint = { subject: session.subject, signedInAt: this.environment.now() };
275
+ this.environment.localStorage.setItem(this.accountStorageKey, JSON.stringify(next));
276
+ }
277
+ this.broadcast({
278
+ type: 'session',
279
+ accessToken: session.accessToken,
280
+ expiresAt: session.expiresAt,
281
+ subject: session.subject,
282
+ });
283
+ }
284
+
285
+ private remember(session: IssuedSession): void {
286
+ this.revision += 1;
287
+ this.token = {
288
+ accessToken: session.accessToken,
289
+ expiresAt: session.expiresAt,
290
+ subject: session.subject,
291
+ receivedAt: this.environment.now(),
292
+ };
293
+ }
294
+
295
+ private receive(message: SessionMessage | undefined): void {
296
+ if (message === undefined) {
297
+ return;
298
+ }
299
+ if (message.type === 'session') {
300
+ this.remember(message);
301
+ this.releaseSessionWaiters();
302
+ return;
303
+ }
304
+ this.revision += 1;
305
+ this.token = undefined;
306
+ this.releaseSessionWaiters();
307
+ this.notify(expiredReason(message.cause));
308
+ }
309
+
310
+ /** Counts sessions issued in any tab; it holds no token or expiry. */
311
+ private sessionGeneration(): number {
312
+ const value = Number(this.environment.localStorage.getItem(this.generationStorageKey));
313
+ return Number.isSafeInteger(value) ? value : 0;
314
+ }
315
+
316
+ /** Resolves when another tab's session message arrives or the handoff times out. */
317
+ private nextSession(): Promise<void> {
318
+ return new Promise((resolve) => {
319
+ const done = () => {
320
+ clearTimeout(timer);
321
+ this.sessionWaiters.delete(done);
322
+ resolve();
323
+ };
324
+ const timer = setTimeout(done, SESSION_HANDOFF_TIMEOUT_MS);
325
+ this.sessionWaiters.add(done);
326
+ });
327
+ }
328
+
329
+ private releaseSessionWaiters(): void {
330
+ for (const done of [...this.sessionWaiters]) {
331
+ done();
332
+ }
333
+ }
334
+
335
+ private expire(reason: SessionExpiredReason): void {
336
+ this.clearLocal();
337
+ if (reason === 'profile_erased') {
338
+ this.oidc.requireFreshLogin();
339
+ }
340
+ this.broadcast({ type: 'signed-out', cause: reason });
341
+ this.notify(reason);
342
+ }
343
+
344
+ private clearLocal(): void {
345
+ this.revision += 1;
346
+ this.token = undefined;
347
+ this.environment.localStorage.removeItem(this.accountStorageKey);
348
+ this.oidc.clearTransaction();
349
+ }
350
+
351
+ private notify(reason: SessionExpiredReason): void {
352
+ const event: SessionExpiredEvent = { type: 'session-expired', reason };
353
+ for (const listener of this.listeners) {
354
+ try {
355
+ listener(event);
356
+ } catch {
357
+ // Observers cannot change the terminal unauthenticated result.
358
+ }
359
+ }
360
+ }
361
+
362
+ private broadcast(message: SessionMessage): void {
363
+ this.channel?.postMessage(message);
364
+ }
365
+
366
+ private isFresh(token: MemoryToken): boolean {
367
+ const window = Math.min(this.refreshLeewayMs, (token.expiresAt - token.receivedAt) / 2);
368
+ return token.expiresAt > this.environment.now() + window;
369
+ }
370
+
371
+ private post(endpoint: SessionEndpoint, body?: object): Promise<Response> {
372
+ return this.environment.fetch(`${this.sessionBaseUrl}/${endpoint}`, {
373
+ method: 'POST',
374
+ credentials: 'include',
375
+ cache: 'no-store',
376
+ headers:
377
+ body === undefined
378
+ ? { [BROWSER_SESSION_HEADER]: '1' }
379
+ : { [BROWSER_SESSION_HEADER]: '1', 'content-type': 'application/json' },
380
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
381
+ });
382
+ }
383
+ }
384
+
385
+ function refreshLeewayMs(seconds = DEFAULT_REFRESH_LEEWAY_SECONDS): number {
386
+ if (!Number.isFinite(seconds) || seconds < 0) {
387
+ throw new RangeError('OIDC refresh leeway must be a non-negative number.');
388
+ }
389
+ return seconds * MS_PER_SECOND;
390
+ }
391
+
392
+ function isRetryableStatus(status: number): boolean {
393
+ return status === HTTP_TOO_MANY_REQUESTS || status >= HTTP_SERVER_ERROR;
394
+ }
395
+
396
+ function expiredReason(cause: SignedOutCause): SessionExpiredReason {
397
+ return cause === 'cleared' ? 'signed_out' : cause;
398
+ }
399
+
400
+ async function readJson(response: Response): Promise<unknown> {
401
+ try {
402
+ return (await response.json()) as unknown;
403
+ } catch {
404
+ return undefined;
405
+ }
406
+ }
407
+
408
+ async function readIssuedSession(response: Response): Promise<IssuedSession> {
409
+ const value = await readJson(response);
410
+ if (!isIssuedSession(value)) {
411
+ throw new OidcError('invalid_token_response');
412
+ }
413
+ return value;
414
+ }
@@ -0,0 +1,58 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+
3
+ import { BrowserSessionClient, SESSION_HANDOFF_TIMEOUT_MS } from './browser-session-client.js';
4
+ import { ChannelHub } from './test-support/browser-session.js';
5
+ import {
6
+ CONFIG,
7
+ ROTATED_TOKEN,
8
+ sessionCalls,
9
+ setup,
10
+ signIn,
11
+ storageEntries,
12
+ } from './test-support/session-backend.js';
13
+
14
+ describe('BrowserSessionClient refresh handoff', () => {
15
+ it("refreshes once when the winning tab's session message arrives after the lock is released", async () => {
16
+ const { browser, server } = setup();
17
+ await signIn(browser.tab());
18
+ const lateChannel = new ChannelHub('task');
19
+ const tabs = [browser.tab(), browser.tab()].map(
20
+ (tab) =>
21
+ new BrowserSessionClient(CONFIG, { ...tab.environment, openChannel: lateChannel.open }),
22
+ );
23
+
24
+ await expect(Promise.all(tabs.map((client) => client.getAccessToken()))).resolves.toEqual([
25
+ ROTATED_TOKEN,
26
+ ROTATED_TOKEN,
27
+ ]);
28
+ expect(sessionCalls(server, 'refresh')).toHaveLength(1);
29
+ expect(JSON.stringify(Object.fromEntries(storageEntries(browser.localStorage)))).not.toMatch(
30
+ /eyJ|expiresAt/u,
31
+ );
32
+ });
33
+
34
+ it("refreshes after the handoff timeout when the winning tab's message never arrives", async () => {
35
+ vi.useFakeTimers();
36
+ try {
37
+ const { browser, server } = setup();
38
+ await signIn(browser.tab());
39
+ const silent = {
40
+ postMessage: () => undefined,
41
+ subscribe: () => undefined,
42
+ close: () => undefined,
43
+ };
44
+ const tabs = [browser.tab(), browser.tab()].map(
45
+ (tab) =>
46
+ new BrowserSessionClient(CONFIG, { ...tab.environment, openChannel: () => silent }),
47
+ );
48
+
49
+ const pending = Promise.all(tabs.map((client) => client.getAccessToken()));
50
+ await vi.advanceTimersByTimeAsync(SESSION_HANDOFF_TIMEOUT_MS);
51
+
52
+ await expect(pending).resolves.toEqual([ROTATED_TOKEN, ROTATED_TOKEN]);
53
+ expect(sessionCalls(server, 'refresh')).toHaveLength(2);
54
+ } finally {
55
+ vi.useRealTimers();
56
+ }
57
+ });
58
+ });
@@ -0,0 +1,113 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+
3
+ import { BrowserSessionClient } from './index.js';
4
+ import {
5
+ MemoryStorage,
6
+ discoveryResponse,
7
+ fakeBrowser,
8
+ jsonResponse,
9
+ requestUrl,
10
+ required,
11
+ } from './test-support/browser-session.js';
12
+
13
+ const ACCESS_TOKEN = 'eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ1c2VyLTEifQ.access-signature';
14
+ const FORBIDDEN = [ACCESS_TOKEN, 'refresh_token', 'eyJ'];
15
+
16
+ /** A stand-in for IndexedDB or the Cache API that records every call's arguments. */
17
+ function recordingApi(writes: string[], path: string): unknown {
18
+ const call = (...args: unknown[]): unknown => {
19
+ writes.push(`${path}(${args.map((arg) => safeText(arg)).join(',')})`);
20
+ return recordingApi(writes, `${path}()`);
21
+ };
22
+ return new Proxy(call, {
23
+ get: (_target, property) =>
24
+ property === 'then' ? undefined : recordingApi(writes, `${path}.${String(property)}`),
25
+ });
26
+ }
27
+
28
+ function safeText(value: unknown): string {
29
+ try {
30
+ return typeof value === 'string' ? value : JSON.stringify(value);
31
+ } catch {
32
+ return String(value);
33
+ }
34
+ }
35
+
36
+ afterEach(() => {
37
+ vi.unstubAllGlobals();
38
+ vi.restoreAllMocks();
39
+ });
40
+
41
+ describe('BrowserSessionClient storage', () => {
42
+ it('never writes a token to localStorage, sessionStorage, IndexedDB or the Cache API', async () => {
43
+ const writes: string[] = [];
44
+ vi.stubGlobal('indexedDB', recordingApi(writes, 'indexedDB'));
45
+ vi.stubGlobal('caches', recordingApi(writes, 'caches'));
46
+ const setItem = vi.spyOn(MemoryStorage.prototype, 'setItem');
47
+ let refreshStatus = 200;
48
+ const browser = fakeBrowser((input) => {
49
+ const url = requestUrl(input);
50
+ if (url.includes('.well-known')) return Promise.resolve(discoveryResponse());
51
+ if (url.endsWith('/logout')) return Promise.resolve(new Response(null, { status: 204 }));
52
+ if (url.endsWith('/refresh') && refreshStatus === 401) {
53
+ return Promise.resolve(jsonResponse({ code: 'session_expired' }, 401));
54
+ }
55
+ return Promise.resolve(
56
+ jsonResponse({
57
+ accessToken: ACCESS_TOKEN,
58
+ expiresAt: 9_000_000,
59
+ subject: 'user-1',
60
+ refresh_token: 'leaked-by-a-broken-backend',
61
+ }),
62
+ );
63
+ });
64
+
65
+ const tab = browser.tab();
66
+ const client = new BrowserSessionClient(clientConfig(), tab.environment);
67
+ const others = [browser.tab(), browser.tab()].map(
68
+ (other) => new BrowserSessionClient(clientConfig(), other.environment),
69
+ );
70
+ await client.login();
71
+ const state = required(new URL(required(tab.navigations.at(-1))).searchParams.get('state'));
72
+ tab.setCurrentUrl(`https://app.example.test/?code=code&state=${state}`);
73
+ await client.handleCallback();
74
+ await Promise.all(
75
+ [client, ...others].map((each) => each.getAccessToken({ forceRefresh: true })),
76
+ );
77
+ refreshStatus = 401;
78
+ await client.getAccessToken({ forceRefresh: true });
79
+ await client.login();
80
+ await client.logout();
81
+
82
+ expect(setItem).toHaveBeenCalled();
83
+ const stored = [
84
+ ...setItem.mock.calls.map(([key, value]) => `${key}=${value}`),
85
+ ...writes,
86
+ ...dump(browser.localStorage),
87
+ ...dump(tab.sessionStorage),
88
+ ];
89
+ for (const entry of stored) {
90
+ for (const forbidden of FORBIDDEN) {
91
+ expect(entry, entry).not.toContain(forbidden);
92
+ }
93
+ }
94
+ expect(browser.hub.posted.length).toBeGreaterThan(0);
95
+ });
96
+ });
97
+
98
+ function clientConfig() {
99
+ return {
100
+ issuer: 'https://identity.example.test/realm',
101
+ clientId: 'product-web',
102
+ redirectUri: 'https://app.example.test/',
103
+ storageKeyPrefix: 'product',
104
+ apiBaseUrl: 'https://api.example.test',
105
+ };
106
+ }
107
+
108
+ function dump(storage: Storage): string[] {
109
+ return Array.from({ length: storage.length }, (_, index) => {
110
+ const key = required(storage.key(index));
111
+ return `${key}=${storage.getItem(key) ?? ''}`;
112
+ });
113
+ }