@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.test.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { describe, expect, it
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
2
|
|
|
3
3
|
import {
|
|
4
4
|
OidcClient,
|
|
@@ -6,405 +6,112 @@ import {
|
|
|
6
6
|
buildAuthorizationUrl,
|
|
7
7
|
normalizeIssuer,
|
|
8
8
|
safeAuthErrorMessage,
|
|
9
|
-
type OidcClientEnvironment,
|
|
10
9
|
} from './index.js';
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
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;
|
|
10
|
+
import {
|
|
11
|
+
discoveryResponse,
|
|
12
|
+
fakeBrowser,
|
|
13
|
+
jsonResponse,
|
|
14
|
+
readLoginTransaction,
|
|
15
|
+
required,
|
|
16
|
+
type Tab,
|
|
17
|
+
} from './test-support/browser-session.js';
|
|
18
|
+
|
|
19
|
+
const CONFIG = {
|
|
20
|
+
issuer: 'https://identity.example.test/realm',
|
|
21
|
+
clientId: 'product-web',
|
|
22
|
+
redirectUri: 'https://app.example.test/callback',
|
|
23
|
+
storageKeyPrefix: 'oidc',
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
function setup(fetch: typeof globalThis.fetch = () => Promise.resolve(discoveryResponse())) {
|
|
27
|
+
const browser = fakeBrowser(fetch);
|
|
28
|
+
const tab = browser.tab({ coordinated: false });
|
|
29
|
+
return { browser, tab, client: new OidcClient(CONFIG, tab.environment) };
|
|
48
30
|
}
|
|
49
31
|
|
|
50
|
-
function
|
|
51
|
-
|
|
52
|
-
|
|
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
|
-
};
|
|
32
|
+
async function loginState(client: OidcClient, tab: Tab): Promise<string> {
|
|
33
|
+
await client.login();
|
|
34
|
+
return required(new URL(required(tab.navigations.at(-1))).searchParams.get('state'));
|
|
79
35
|
}
|
|
80
36
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
37
|
+
describe('OidcClient', () => {
|
|
38
|
+
it('redirects with S256 PKCE and returns the verified code for the backend', async () => {
|
|
39
|
+
const { tab, client } = setup();
|
|
40
|
+
const state = await loginState(client, tab);
|
|
41
|
+
const authorization = new URL(required(tab.navigations.at(-1)));
|
|
42
|
+
expect(authorization.origin + authorization.pathname).toBe(
|
|
43
|
+
'https://identity.example.test/realm/authorize',
|
|
44
|
+
);
|
|
45
|
+
expect(authorization.searchParams.get('code_challenge_method')).toBe('S256');
|
|
46
|
+
expect(authorization.searchParams.has('prompt')).toBe(false);
|
|
47
|
+
const { verifier } = readLoginTransaction(tab.sessionStorage, 'oidc:transaction');
|
|
87
48
|
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
}
|
|
92
|
-
return value;
|
|
93
|
-
}
|
|
49
|
+
tab.setCurrentUrl(
|
|
50
|
+
`https://app.example.test/callback?code=one-time&state=${state}&iss=${encodeURIComponent(CONFIG.issuer)}`,
|
|
51
|
+
);
|
|
94
52
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
53
|
+
expect(client.completeCallback()).toEqual({
|
|
54
|
+
code: 'one-time',
|
|
55
|
+
codeVerifier: verifier,
|
|
56
|
+
redirectUri: CONFIG.redirectUri,
|
|
57
|
+
});
|
|
58
|
+
expect(tab.sessionStorage.length).toBe(0);
|
|
100
59
|
});
|
|
101
|
-
}
|
|
102
60
|
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
refreshToken: 'stored-refresh',
|
|
107
|
-
idToken: 'stored-id',
|
|
108
|
-
issuedAt: 0,
|
|
109
|
-
expiresAt: 900,
|
|
110
|
-
...overrides,
|
|
61
|
+
it('ignores a URL without callback parameters', () => {
|
|
62
|
+
const { client } = setup();
|
|
63
|
+
expect(client.completeCallback()).toBeUndefined();
|
|
111
64
|
});
|
|
112
|
-
}
|
|
113
65
|
|
|
114
|
-
|
|
115
|
-
return new OidcClient(
|
|
66
|
+
it.each([
|
|
116
67
|
{
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
storageKeyPrefix: 'lifecycle',
|
|
68
|
+
name: 'a wrong state',
|
|
69
|
+
query: (state: string) => `code=c&state=${state}x`,
|
|
70
|
+
code: 'callback_state_mismatch',
|
|
121
71
|
},
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
describe('OidcClient', () => {
|
|
127
|
-
it.each([
|
|
128
|
-
{ expiresIn: 10, leeway: undefined, refreshAt: 1_005_000 },
|
|
129
|
-
{ expiresIn: 3600, leeway: undefined, refreshAt: 4_570_000 },
|
|
130
|
-
{ expiresIn: 10, leeway: 0, refreshAt: 1_010_000 },
|
|
131
|
-
{ expiresIn: 10, leeway: 2, refreshAt: 1_008_000 },
|
|
132
|
-
])(
|
|
133
|
-
'refreshes a $expiresIn s token with leeway $leeway at $refreshAt',
|
|
134
|
-
async ({ expiresIn, leeway, refreshAt }) => {
|
|
135
|
-
let refreshCalls = 0;
|
|
136
|
-
const test = makeEnvironment((input, init) => {
|
|
137
|
-
const url = input instanceof Request ? input.url : input.toString();
|
|
138
|
-
if (url.includes('.well-known')) return Promise.resolve(discoveryResponse());
|
|
139
|
-
if (!(init?.body instanceof URLSearchParams)) throw new Error('Expected a token request.');
|
|
140
|
-
const refresh = init.body.get('grant_type') === 'refresh_token';
|
|
141
|
-
if (refresh) refreshCalls += 1;
|
|
142
|
-
return Promise.resolve(
|
|
143
|
-
jsonResponse({
|
|
144
|
-
access_token: refresh ? 'refreshed-access' : 'access-secret',
|
|
145
|
-
refresh_token: 'refresh-secret',
|
|
146
|
-
expires_in: expiresIn,
|
|
147
|
-
}),
|
|
148
|
-
);
|
|
149
|
-
});
|
|
150
|
-
const client = new OidcClient(
|
|
151
|
-
{
|
|
152
|
-
issuer: 'https://identity.example.test/tenant',
|
|
153
|
-
clientId: 'product-web',
|
|
154
|
-
redirectUri: 'https://app.example.test/callback',
|
|
155
|
-
storageKeyPrefix: 'lifecycle',
|
|
156
|
-
...(leeway === undefined ? {} : { refreshLeewaySeconds: leeway }),
|
|
157
|
-
},
|
|
158
|
-
test.environment,
|
|
159
|
-
);
|
|
160
|
-
await client.login();
|
|
161
|
-
const state = required(new URL(required(test.navigations.at(-1))).searchParams.get('state'));
|
|
162
|
-
test.setCurrentUrl(`https://app.example.test/callback?code=one-time-code&state=${state}`);
|
|
163
|
-
await expect(client.handleCallback()).resolves.toBe(true);
|
|
164
|
-
|
|
165
|
-
for (const now of [1_000_000, 1_001_000, 1_002_000, refreshAt - 1]) {
|
|
166
|
-
test.setNow(now);
|
|
167
|
-
await expect(client.accessToken()).resolves.toBe('access-secret');
|
|
168
|
-
}
|
|
169
|
-
expect(refreshCalls).toBe(0);
|
|
170
|
-
expect(JSON.parse(required(test.localStorage.getItem('lifecycle:tokens')))).toMatchObject({
|
|
171
|
-
issuedAt: 1_000_000,
|
|
172
|
-
expiresAt: 1_000_000 + expiresIn * 1000,
|
|
173
|
-
});
|
|
174
|
-
|
|
175
|
-
test.setNow(refreshAt);
|
|
176
|
-
await expect(Promise.all([client.accessToken(), client.accessToken()])).resolves.toEqual([
|
|
177
|
-
'refreshed-access',
|
|
178
|
-
'refreshed-access',
|
|
179
|
-
]);
|
|
180
|
-
await expect(client.accessToken()).resolves.toBe('refreshed-access');
|
|
181
|
-
expect(refreshCalls).toBe(1);
|
|
182
|
-
expect(JSON.parse(required(test.localStorage.getItem('lifecycle:tokens')))).toMatchObject({
|
|
183
|
-
issuedAt: refreshAt,
|
|
184
|
-
expiresAt: refreshAt + expiresIn * 1000,
|
|
185
|
-
});
|
|
72
|
+
{
|
|
73
|
+
name: 'a missing code',
|
|
74
|
+
query: (state: string) => `state=${state}`,
|
|
75
|
+
code: 'callback_state_mismatch',
|
|
186
76
|
},
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
const test = makeEnvironment(fetch);
|
|
192
|
-
test.localStorage.setItem(
|
|
193
|
-
'lifecycle:tokens',
|
|
194
|
-
storedTokens({ issuedAt: undefined, expiresAt: 2_000_000 }),
|
|
195
|
-
);
|
|
196
|
-
const client = makeClient(test);
|
|
197
|
-
|
|
198
|
-
expect(client.hasSession()).toBe(false);
|
|
199
|
-
await expect(client.accessToken()).resolves.toBeUndefined();
|
|
200
|
-
expect(test.localStorage.getItem('lifecycle:tokens')).toBeNull();
|
|
201
|
-
expect(fetch).not.toHaveBeenCalled();
|
|
202
|
-
});
|
|
203
|
-
|
|
204
|
-
it('clears silently without a reason and leaves normal login unchanged', async () => {
|
|
205
|
-
const test = makeEnvironment(() => Promise.resolve(discoveryResponse()));
|
|
206
|
-
const client = makeClient(test);
|
|
207
|
-
const expired = vi.fn();
|
|
208
|
-
client.subscribeSessionExpired(expired);
|
|
209
|
-
test.localStorage.setItem('lifecycle:tokens', storedTokens());
|
|
210
|
-
test.sessionStorage.setItem('lifecycle:transaction', '{}');
|
|
211
|
-
|
|
212
|
-
client.clearSession();
|
|
213
|
-
|
|
214
|
-
expect(client.hasSession()).toBe(false);
|
|
215
|
-
expect(test.localStorage.length).toBe(0);
|
|
216
|
-
expect(test.sessionStorage.length).toBe(0);
|
|
217
|
-
expect(expired).not.toHaveBeenCalled();
|
|
218
|
-
await client.login();
|
|
219
|
-
expect(new URL(required(test.navigations.at(-1))).searchParams.has('prompt')).toBe(false);
|
|
220
|
-
});
|
|
221
|
-
|
|
222
|
-
it('persists fresh authentication after erasure until a successful callback', async () => {
|
|
223
|
-
const fetch = vi.fn<typeof globalThis.fetch>().mockResolvedValue(discoveryResponse());
|
|
224
|
-
const test = makeEnvironment(fetch);
|
|
225
|
-
const client = makeClient(test);
|
|
226
|
-
test.localStorage.setItem('lifecycle:tokens', storedTokens());
|
|
227
|
-
test.sessionStorage.setItem('lifecycle:transaction', '{}');
|
|
228
|
-
const throwing = vi.fn(() => {
|
|
229
|
-
throw new Error('observer');
|
|
230
|
-
});
|
|
231
|
-
const observed: { hasSession: boolean; marker: string | null }[] = [];
|
|
232
|
-
const expired = vi.fn(() => {
|
|
233
|
-
observed.push({
|
|
234
|
-
hasSession: client.hasSession(),
|
|
235
|
-
marker: test.localStorage.getItem('lifecycle:force-login'),
|
|
236
|
-
});
|
|
237
|
-
});
|
|
238
|
-
client.subscribeSessionExpired(throwing);
|
|
239
|
-
client.subscribeSessionExpired(expired);
|
|
240
|
-
|
|
241
|
-
expect(() => {
|
|
242
|
-
client.clearSession({ reason: 'profile_erased' });
|
|
243
|
-
}).not.toThrow();
|
|
244
|
-
|
|
245
|
-
expect(throwing).toHaveBeenCalledTimes(1);
|
|
246
|
-
expect(expired).toHaveBeenCalledTimes(1);
|
|
247
|
-
expect(expired).toHaveBeenCalledWith({ type: 'session-expired', reason: 'profile_erased' });
|
|
248
|
-
expect(observed).toEqual([{ hasSession: false, marker: '1' }]);
|
|
249
|
-
expect(test.sessionStorage.length).toBe(0);
|
|
250
|
-
expect(test.localStorage.getItem('lifecycle:tokens')).toBeNull();
|
|
251
|
-
client.clearSession();
|
|
252
|
-
expect(expired).toHaveBeenCalledTimes(1);
|
|
253
|
-
|
|
254
|
-
const reloaded = makeClient(test);
|
|
255
|
-
await reloaded.login();
|
|
256
|
-
const authorization = new URL(required(test.navigations.at(-1)));
|
|
257
|
-
expect(authorization.searchParams.get('prompt')).toBe('login');
|
|
258
|
-
test.setCurrentUrl(
|
|
259
|
-
`https://app.example.test/callback?code=fresh&state=${required(authorization.searchParams.get('state'))}`,
|
|
260
|
-
);
|
|
261
|
-
fetch.mockResolvedValue(jsonResponse({ access_token: 'fresh-access', expires_in: 60 }));
|
|
262
|
-
await expect(reloaded.handleCallback()).resolves.toBe(true);
|
|
263
|
-
expect(test.localStorage.getItem('lifecycle:force-login')).toBeNull();
|
|
264
|
-
await expect(reloaded.accessToken()).resolves.toBe('fresh-access');
|
|
265
|
-
await reloaded.login();
|
|
266
|
-
expect(new URL(required(test.navigations.at(-1))).searchParams.has('prompt')).toBe(false);
|
|
267
|
-
});
|
|
268
|
-
|
|
269
|
-
it.each(['exchange', 'state', 'provider'] as const)(
|
|
270
|
-
'keeps fresh authentication after a failed %s callback',
|
|
271
|
-
async (failure) => {
|
|
272
|
-
const fetch = vi.fn<typeof globalThis.fetch>().mockResolvedValue(discoveryResponse());
|
|
273
|
-
const test = makeEnvironment(fetch);
|
|
274
|
-
const client = makeClient(test);
|
|
275
|
-
client.clearSession({ reason: 'profile_erased' });
|
|
276
|
-
await client.login();
|
|
277
|
-
const authorization = new URL(required(test.navigations.at(-1)));
|
|
278
|
-
const state =
|
|
279
|
-
failure === 'state' ? 'wrong' : required(authorization.searchParams.get('state'));
|
|
280
|
-
test.setCurrentUrl(
|
|
281
|
-
`https://app.example.test/callback?state=${state}&${failure === 'provider' ? 'error=access_denied' : 'code=fresh'}`,
|
|
282
|
-
);
|
|
283
|
-
fetch.mockResolvedValue(jsonResponse({ error: 'invalid_grant' }, 400));
|
|
284
|
-
|
|
285
|
-
await expect(client.handleCallback()).rejects.toBeInstanceOf(OidcError);
|
|
286
|
-
|
|
287
|
-
expect(test.localStorage.getItem('lifecycle:force-login')).toBe('1');
|
|
288
|
-
expect(client.hasSession()).toBe(false);
|
|
289
|
-
fetch.mockResolvedValue(discoveryResponse());
|
|
290
|
-
await makeClient(test).login();
|
|
291
|
-
expect(new URL(required(test.navigations.at(-1))).searchParams.get('prompt')).toBe('login');
|
|
77
|
+
{
|
|
78
|
+
name: 'a foreign issuer',
|
|
79
|
+
query: (state: string) => `code=c&state=${state}&iss=https://evil.example.test`,
|
|
80
|
+
code: 'issuer_mismatch',
|
|
292
81
|
},
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
const state =
|
|
301
|
-
|
|
302
|
-
let complete: ((response: Response) => void) | undefined;
|
|
303
|
-
fetch.mockImplementation(
|
|
304
|
-
() =>
|
|
305
|
-
new Promise((resolve) => {
|
|
306
|
-
complete = resolve;
|
|
307
|
-
}),
|
|
308
|
-
);
|
|
309
|
-
const callback = client.handleCallback();
|
|
310
|
-
await vi.waitFor(() => {
|
|
311
|
-
expect(complete).toBeDefined();
|
|
312
|
-
});
|
|
313
|
-
|
|
314
|
-
client.clearSession({ reason: 'profile_erased' });
|
|
315
|
-
required(complete)(jsonResponse({ access_token: 'late-access', expires_in: 60 }));
|
|
316
|
-
await callback;
|
|
82
|
+
{
|
|
83
|
+
name: 'a provider error',
|
|
84
|
+
query: (state: string) => `error=access_denied&state=${state}`,
|
|
85
|
+
code: 'authorization_failed',
|
|
86
|
+
},
|
|
87
|
+
])('rejects $name and consumes the transaction', async ({ query, code }) => {
|
|
88
|
+
const { tab, client } = setup();
|
|
89
|
+
const state = await loginState(client, tab);
|
|
90
|
+
tab.setCurrentUrl(`https://app.example.test/callback?${query(state)}`);
|
|
317
91
|
|
|
318
|
-
expect(client.
|
|
319
|
-
expect(
|
|
92
|
+
expect(() => client.completeCallback()).toThrow(expect.objectContaining({ code }));
|
|
93
|
+
expect(tab.sessionStorage.length).toBe(0);
|
|
320
94
|
});
|
|
321
95
|
|
|
322
|
-
it('
|
|
323
|
-
const
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
if (url.endsWith('/.well-known/openid-configuration')) {
|
|
329
|
-
return Promise.resolve(
|
|
330
|
-
jsonResponse({
|
|
331
|
-
issuer: 'https://identity.example.test/tenant',
|
|
332
|
-
authorization_endpoint: 'https://login.example.test/oauth/authorize',
|
|
333
|
-
token_endpoint: 'https://login.example.test/oauth/token',
|
|
334
|
-
end_session_endpoint: 'https://login.example.test/session/end',
|
|
335
|
-
}),
|
|
336
|
-
);
|
|
337
|
-
}
|
|
338
|
-
tokenCalls += 1;
|
|
339
|
-
return Promise.resolve(
|
|
340
|
-
tokenCalls === 1
|
|
341
|
-
? jsonResponse({
|
|
342
|
-
access_token: 'access-secret',
|
|
343
|
-
refresh_token: 'refresh-secret',
|
|
344
|
-
id_token: 'identity-secret',
|
|
345
|
-
expires_in: 60,
|
|
346
|
-
})
|
|
347
|
-
: jsonResponse({ access_token: 'refreshed-secret', expires_in: 120 }),
|
|
348
|
-
);
|
|
349
|
-
};
|
|
350
|
-
const test = makeEnvironment(mockedFetch);
|
|
351
|
-
const client = new OidcClient(
|
|
352
|
-
{
|
|
353
|
-
issuer: 'https://identity.example.test/tenant///',
|
|
354
|
-
clientId: 'product-web',
|
|
355
|
-
redirectUri: 'https://app.example.test/callback',
|
|
356
|
-
scopes: ['profile', 'email', 'profile'],
|
|
357
|
-
offlineAccess: true,
|
|
358
|
-
storageKeyPrefix: 'test-auth',
|
|
359
|
-
audience: 'https://api.example.test',
|
|
360
|
-
resource: 'https://api.example.test',
|
|
361
|
-
},
|
|
362
|
-
test.environment,
|
|
363
|
-
);
|
|
364
|
-
|
|
365
|
-
await client.login();
|
|
366
|
-
const authorization = new URL(required(test.navigations[0]));
|
|
367
|
-
expect(authorization.origin + authorization.pathname).toBe(
|
|
368
|
-
'https://login.example.test/oauth/authorize',
|
|
369
|
-
);
|
|
370
|
-
expect(authorization.searchParams.get('scope')).toBe('openid profile email offline_access');
|
|
371
|
-
expect(authorization.searchParams.get('audience')).toBe('https://api.example.test');
|
|
372
|
-
expect(authorization.searchParams.get('resource')).toBe('https://api.example.test');
|
|
373
|
-
expect(authorization.searchParams.get('code_challenge_method')).toBe('S256');
|
|
374
|
-
expect(authorization.searchParams.get('code_challenge')).toMatch(/^[\w-]{43}$/u);
|
|
375
|
-
|
|
376
|
-
const transaction = JSON.parse(
|
|
377
|
-
required(test.sessionStorage.getItem('test-auth:transaction')),
|
|
378
|
-
) as {
|
|
379
|
-
readonly state: string;
|
|
380
|
-
};
|
|
381
|
-
test.setCurrentUrl(
|
|
382
|
-
`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`,
|
|
383
|
-
);
|
|
384
|
-
const firstCallback = client.handleCallback();
|
|
385
|
-
const repeatedCallback = client.handleCallback();
|
|
386
|
-
expect(firstCallback).toBe(repeatedCallback);
|
|
387
|
-
await expect(Promise.all([firstCallback, repeatedCallback])).resolves.toEqual([true, true]);
|
|
388
|
-
expect(tokenCalls).toBe(1);
|
|
389
|
-
expect(test.replacements).toEqual(['https://app.example.test/callback?kept=yes']);
|
|
390
|
-
expect(await client.accessToken()).toBe('access-secret');
|
|
96
|
+
it('requests prompt=login until a fresh sign-in is confirmed', async () => {
|
|
97
|
+
const { browser, tab, client } = setup();
|
|
98
|
+
client.requireFreshLogin();
|
|
99
|
+
await loginState(client, tab);
|
|
100
|
+
expect(new URL(required(tab.navigations.at(-1))).searchParams.get('prompt')).toBe('login');
|
|
101
|
+
expect(browser.localStorage.getItem('oidc:force-login')).toBe('1');
|
|
391
102
|
|
|
392
|
-
|
|
393
|
-
await
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
]);
|
|
397
|
-
expect(tokenCalls).toBe(2);
|
|
398
|
-
const refreshBody = requests.at(-1)?.init?.body as URLSearchParams;
|
|
399
|
-
expect(refreshBody.get('grant_type')).toBe('refresh_token');
|
|
400
|
-
expect(refreshBody.get('refresh_token')).toBe('refresh-secret');
|
|
103
|
+
client.confirmFreshLogin();
|
|
104
|
+
await loginState(client, tab);
|
|
105
|
+
expect(new URL(required(tab.navigations.at(-1))).searchParams.has('prompt')).toBe(false);
|
|
106
|
+
});
|
|
401
107
|
|
|
402
|
-
|
|
403
|
-
const
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
expect(
|
|
108
|
+
it('never touches a token storage key', async () => {
|
|
109
|
+
const { browser, tab, client } = setup();
|
|
110
|
+
const state = await loginState(client, tab);
|
|
111
|
+
tab.setCurrentUrl(`https://app.example.test/callback?code=c&state=${state}`);
|
|
112
|
+
client.completeCallback();
|
|
113
|
+
expect(browser.localStorage.getItem('oidc:tokens')).toBeNull();
|
|
114
|
+
expect(browser.localStorage.length).toBe(0);
|
|
408
115
|
});
|
|
409
116
|
|
|
410
117
|
it('uses only discovered endpoints and makes offline access opt-in', () => {
|
|
@@ -419,245 +126,42 @@ describe('OidcClient', () => {
|
|
|
419
126
|
);
|
|
420
127
|
expect(url.pathname).toBe('/non-keycloak/authorize');
|
|
421
128
|
expect(url.searchParams.get('scope')).toBe('openid custom');
|
|
422
|
-
expect(url.searchParams.has('offline_access')).toBe(false);
|
|
423
129
|
expect(normalizeIssuer('https://provider.example.test/path///')).toBe(
|
|
424
130
|
'https://provider.example.test/path',
|
|
425
131
|
);
|
|
426
132
|
});
|
|
427
133
|
|
|
428
|
-
it('
|
|
429
|
-
let resolveRefresh: ((response: Response) => void) | undefined;
|
|
430
|
-
let refreshCalls = 0;
|
|
431
|
-
const test = makeEnvironment((input) => {
|
|
432
|
-
const url = input instanceof Request ? input.url : input.toString();
|
|
433
|
-
if (url.includes('.well-known')) {
|
|
434
|
-
return Promise.resolve(discoveryResponse());
|
|
435
|
-
}
|
|
436
|
-
refreshCalls += 1;
|
|
437
|
-
return new Promise((resolve) => {
|
|
438
|
-
resolveRefresh = resolve;
|
|
439
|
-
});
|
|
440
|
-
});
|
|
441
|
-
test.localStorage.setItem('lifecycle:tokens', storedTokens());
|
|
442
|
-
const client = makeClient(test);
|
|
443
|
-
|
|
444
|
-
const proactive = client.accessToken();
|
|
445
|
-
const forced = client.accessToken({ forceRefresh: true });
|
|
446
|
-
await vi.waitFor(() => {
|
|
447
|
-
expect(refreshCalls).toBe(1);
|
|
448
|
-
});
|
|
449
|
-
resolveRefresh?.(
|
|
450
|
-
jsonResponse({
|
|
451
|
-
access_token: 'shared-access',
|
|
452
|
-
expires_in: 120,
|
|
453
|
-
}),
|
|
454
|
-
);
|
|
455
|
-
|
|
456
|
-
await expect(Promise.all([proactive, forced])).resolves.toEqual([
|
|
457
|
-
'shared-access',
|
|
458
|
-
'shared-access',
|
|
459
|
-
]);
|
|
460
|
-
expect(refreshCalls).toBe(1);
|
|
461
|
-
});
|
|
462
|
-
|
|
463
|
-
it('does not restore a session cleared while refresh is pending', async () => {
|
|
464
|
-
let resolveRefresh: ((response: Response) => void) | undefined;
|
|
465
|
-
const test = makeEnvironment((input) => {
|
|
466
|
-
const url = input instanceof Request ? input.url : input.toString();
|
|
467
|
-
if (url.includes('.well-known')) {
|
|
468
|
-
return Promise.resolve(discoveryResponse());
|
|
469
|
-
}
|
|
470
|
-
return new Promise((resolve) => {
|
|
471
|
-
resolveRefresh = resolve;
|
|
472
|
-
});
|
|
473
|
-
});
|
|
474
|
-
test.localStorage.setItem('lifecycle:tokens', storedTokens());
|
|
475
|
-
const client = makeClient(test);
|
|
476
|
-
|
|
477
|
-
const pending = client.accessToken();
|
|
478
|
-
await vi.waitFor(() => {
|
|
479
|
-
expect(resolveRefresh).toBeDefined();
|
|
480
|
-
});
|
|
481
|
-
client.clearSession();
|
|
482
|
-
resolveRefresh?.(jsonResponse({ access_token: 'stale-access', expires_in: 120 }));
|
|
483
|
-
|
|
484
|
-
await expect(pending).resolves.toBeUndefined();
|
|
485
|
-
expect(client.hasSession()).toBe(false);
|
|
486
|
-
});
|
|
487
|
-
|
|
488
|
-
it('forces refresh outside the proactive window and retains token rotation state', async () => {
|
|
489
|
-
let tokenCalls = 0;
|
|
490
|
-
const test = makeEnvironment((input) => {
|
|
491
|
-
const url = input instanceof Request ? input.url : input.toString();
|
|
492
|
-
if (url.includes('.well-known')) {
|
|
493
|
-
return Promise.resolve(discoveryResponse());
|
|
494
|
-
}
|
|
495
|
-
tokenCalls += 1;
|
|
496
|
-
return Promise.resolve(
|
|
497
|
-
jsonResponse({
|
|
498
|
-
access_token: 'forced-access',
|
|
499
|
-
expires_in: 120,
|
|
500
|
-
}),
|
|
501
|
-
);
|
|
502
|
-
});
|
|
503
|
-
test.localStorage.setItem('lifecycle:tokens', storedTokens({ expiresAt: 2_000_000 }));
|
|
504
|
-
const client = makeClient(test);
|
|
505
|
-
|
|
506
|
-
await expect(client.accessToken({ forceRefresh: true })).resolves.toBe('forced-access');
|
|
507
|
-
expect(tokenCalls).toBe(1);
|
|
508
|
-
expect(JSON.parse(required(test.localStorage.getItem('lifecycle:tokens')))).toMatchObject({
|
|
509
|
-
refreshToken: 'stored-refresh',
|
|
510
|
-
idToken: 'stored-id',
|
|
511
|
-
});
|
|
512
|
-
});
|
|
513
|
-
|
|
514
|
-
it('preserves the session and exposes a retryable transient refresh failure', async () => {
|
|
515
|
-
const test = makeEnvironment((input) => {
|
|
516
|
-
const url = input instanceof Request ? input.url : input.toString();
|
|
517
|
-
return Promise.resolve(
|
|
518
|
-
url.includes('.well-known')
|
|
519
|
-
? discoveryResponse()
|
|
520
|
-
: jsonResponse({ error: 'temporarily_unavailable' }, 503),
|
|
521
|
-
);
|
|
522
|
-
});
|
|
523
|
-
test.localStorage.setItem('lifecycle:tokens', storedTokens());
|
|
524
|
-
const client = makeClient(test);
|
|
525
|
-
|
|
526
|
-
await expect(client.accessToken()).rejects.toMatchObject({
|
|
527
|
-
code: 'refresh_failed',
|
|
528
|
-
retryable: true,
|
|
529
|
-
status: 503,
|
|
530
|
-
});
|
|
531
|
-
expect(client.hasSession()).toBe(true);
|
|
532
|
-
expect(test.localStorage.getItem('lifecycle:tokens')).not.toBeNull();
|
|
533
|
-
});
|
|
534
|
-
|
|
535
|
-
it.each([
|
|
536
|
-
[401, { error: 'provider_error' }],
|
|
537
|
-
[403, { error: 'invalid_grant' }],
|
|
538
|
-
] as const)('expires the session for terminal refresh rejection %#', async (status, body) => {
|
|
539
|
-
const test = makeEnvironment((input) => {
|
|
540
|
-
const url = input instanceof Request ? input.url : input.toString();
|
|
541
|
-
return Promise.resolve(
|
|
542
|
-
url.includes('.well-known') ? discoveryResponse() : jsonResponse(body, status),
|
|
543
|
-
);
|
|
544
|
-
});
|
|
545
|
-
test.localStorage.setItem('lifecycle:tokens', storedTokens());
|
|
546
|
-
const client = makeClient(test);
|
|
547
|
-
const expired: unknown[] = [];
|
|
548
|
-
client.subscribeSessionExpired((event) => expired.push(event));
|
|
549
|
-
|
|
550
|
-
await expect(client.accessToken()).resolves.toBeUndefined();
|
|
551
|
-
expect(client.hasSession()).toBe(false);
|
|
552
|
-
expect(expired).toEqual([{ type: 'session-expired', reason: 'refresh_rejected' }]);
|
|
553
|
-
});
|
|
554
|
-
|
|
555
|
-
it('sanitizes provider errors, response content, and unknown errors', async () => {
|
|
134
|
+
it('sanitizes provider errors and unknown errors', async () => {
|
|
556
135
|
const leakedDescription = 'private content access-token-secret';
|
|
557
|
-
const
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
authorization_endpoint: 'https://identity.example.test/authorize',
|
|
562
|
-
token_endpoint: 'https://identity.example.test/token',
|
|
563
|
-
}),
|
|
564
|
-
);
|
|
565
|
-
const test = makeEnvironment(fetchImplementation);
|
|
566
|
-
test.sessionStorage.setItem(
|
|
567
|
-
'safe:transaction',
|
|
568
|
-
JSON.stringify({ state: 'expected', verifier: 'verifier' }),
|
|
569
|
-
);
|
|
570
|
-
test.setCurrentUrl(
|
|
571
|
-
`https://app.example.test/callback?error=access_denied&error_description=${encodeURIComponent(leakedDescription)}&state=expected`,
|
|
572
|
-
);
|
|
573
|
-
const client = new OidcClient(
|
|
574
|
-
{
|
|
575
|
-
issuer: 'https://identity.example.test',
|
|
576
|
-
clientId: 'client',
|
|
577
|
-
redirectUri: 'https://app.example.test/callback',
|
|
578
|
-
storageKeyPrefix: 'safe',
|
|
579
|
-
},
|
|
580
|
-
test.environment,
|
|
136
|
+
const { tab, client } = setup();
|
|
137
|
+
const state = await loginState(client, tab);
|
|
138
|
+
tab.setCurrentUrl(
|
|
139
|
+
`https://app.example.test/callback?error=access_denied&error_description=${encodeURIComponent(leakedDescription)}&state=${state}`,
|
|
581
140
|
);
|
|
582
141
|
|
|
583
142
|
let caught: unknown;
|
|
584
143
|
try {
|
|
585
|
-
|
|
144
|
+
client.completeCallback();
|
|
586
145
|
} catch (cause) {
|
|
587
146
|
caught = cause;
|
|
588
147
|
}
|
|
589
148
|
expect(caught).toBeInstanceOf(OidcError);
|
|
590
149
|
expect(safeAuthErrorMessage(caught)).toBe('OIDC authorization failed.');
|
|
591
|
-
expect(safeAuthErrorMessage(caught)).not.toContain(leakedDescription);
|
|
592
150
|
expect(safeAuthErrorMessage(new Error(leakedDescription))).toBe('OIDC login failed.');
|
|
593
|
-
expect(test.replacements[0]).not.toContain('error_description');
|
|
594
|
-
});
|
|
595
|
-
|
|
596
|
-
it('does not expose a token endpoint error body or authorization code', async () => {
|
|
597
|
-
const fetchImplementation: typeof globalThis.fetch = (input) => {
|
|
598
|
-
const url = input instanceof Request ? input.url : input.toString();
|
|
599
|
-
return Promise.resolve(
|
|
600
|
-
url.includes('.well-known')
|
|
601
|
-
? jsonResponse({
|
|
602
|
-
issuer: 'https://identity.example.test',
|
|
603
|
-
authorization_endpoint: 'https://identity.example.test/authorize',
|
|
604
|
-
token_endpoint: 'https://identity.example.test/token',
|
|
605
|
-
})
|
|
606
|
-
: new Response('private-content access-token-secret one-time-code', { status: 400 }),
|
|
607
|
-
);
|
|
608
|
-
};
|
|
609
|
-
const test = makeEnvironment(fetchImplementation);
|
|
610
|
-
test.sessionStorage.setItem(
|
|
611
|
-
'http-error:transaction',
|
|
612
|
-
JSON.stringify({ state: 'expected', verifier: 'verifier' }),
|
|
613
|
-
);
|
|
614
|
-
test.setCurrentUrl('https://app.example.test/callback?code=one-time-code&state=expected');
|
|
615
|
-
const client = new OidcClient(
|
|
616
|
-
{
|
|
617
|
-
issuer: 'https://identity.example.test',
|
|
618
|
-
clientId: 'client',
|
|
619
|
-
redirectUri: 'https://app.example.test/callback',
|
|
620
|
-
storageKeyPrefix: 'http-error',
|
|
621
|
-
},
|
|
622
|
-
test.environment,
|
|
623
|
-
);
|
|
624
|
-
|
|
625
|
-
let caught: unknown;
|
|
626
|
-
try {
|
|
627
|
-
await client.handleCallback();
|
|
628
|
-
} catch (cause) {
|
|
629
|
-
caught = cause;
|
|
630
|
-
}
|
|
631
|
-
expect(caught).toMatchObject({ code: 'token_exchange_failed', status: 400 });
|
|
632
|
-
expect(safeAuthErrorMessage(caught)).toBe('OIDC token exchange failed.');
|
|
633
|
-
expect(String(caught)).not.toContain('private-content');
|
|
634
|
-
expect(String(caught)).not.toContain('one-time-code');
|
|
635
151
|
});
|
|
636
152
|
|
|
637
153
|
it('rejects mismatched discovery issuers without exposing metadata content', async () => {
|
|
638
|
-
const
|
|
154
|
+
const { client } = setup(() =>
|
|
639
155
|
Promise.resolve(
|
|
640
156
|
jsonResponse({
|
|
641
157
|
issuer: 'https://attacker.example.test/token-secret',
|
|
642
158
|
authorization_endpoint: 'https://attacker.example.test/authorize',
|
|
643
159
|
token_endpoint: 'https://attacker.example.test/token',
|
|
644
160
|
}),
|
|
645
|
-
)
|
|
646
|
-
const test = makeEnvironment(fetchImplementation);
|
|
647
|
-
const client = new OidcClient(
|
|
648
|
-
{
|
|
649
|
-
issuer: 'https://identity.example.test',
|
|
650
|
-
clientId: 'client',
|
|
651
|
-
redirectUri: 'https://app.example.test/callback',
|
|
652
|
-
},
|
|
653
|
-
test.environment,
|
|
161
|
+
),
|
|
654
162
|
);
|
|
655
|
-
await
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
'OIDC provider issuer did not match the configured issuer.',
|
|
659
|
-
);
|
|
660
|
-
expect(safeAuthErrorMessage(error)).not.toContain('token-secret');
|
|
661
|
-
});
|
|
163
|
+
const failure = await client.discover().catch((error: unknown) => error);
|
|
164
|
+
expect(failure).toMatchObject({ code: 'issuer_mismatch' });
|
|
165
|
+
expect(safeAuthErrorMessage(failure)).not.toContain('token-secret');
|
|
662
166
|
});
|
|
663
167
|
});
|