@baukit/auth-native 0.7.2 → 0.7.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +10 -3
- package/dist/index.js.map +1 -1
- package/package.json +2 -1
- package/src/authorization-state.test.ts +54 -0
- package/src/authorization-state.ts +69 -0
- package/src/expo.test.ts +110 -0
- package/src/expo.ts +133 -0
- package/src/index.test.ts +642 -0
- package/src/index.ts +816 -0
|
@@ -0,0 +1,642 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
NativeOidcClient,
|
|
5
|
+
OidcError,
|
|
6
|
+
safeAuthErrorMessage,
|
|
7
|
+
type AuthorizationRequest,
|
|
8
|
+
type AuthorizationResult,
|
|
9
|
+
type BrowserFlowPort,
|
|
10
|
+
type EndSessionRequest,
|
|
11
|
+
type FetchPort,
|
|
12
|
+
type NativeOidcEnvironment,
|
|
13
|
+
type NativeOidcConfig,
|
|
14
|
+
type SecureStoragePort,
|
|
15
|
+
} from './index.js';
|
|
16
|
+
|
|
17
|
+
class MemoryStorage implements SecureStoragePort {
|
|
18
|
+
public readonly values = new Map<string, string>();
|
|
19
|
+
public readonly deletes: string[] = [];
|
|
20
|
+
public readonly reads: string[] = [];
|
|
21
|
+
|
|
22
|
+
public get(key: string): Promise<string | null> {
|
|
23
|
+
this.validateKey(key);
|
|
24
|
+
this.reads.push(key);
|
|
25
|
+
return Promise.resolve(this.values.get(key) ?? null);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
public set(key: string, value: string): Promise<void> {
|
|
29
|
+
this.validateKey(key);
|
|
30
|
+
this.values.set(key, value);
|
|
31
|
+
return Promise.resolve();
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
public delete(key: string): Promise<void> {
|
|
35
|
+
this.validateKey(key);
|
|
36
|
+
this.deletes.push(key);
|
|
37
|
+
this.values.delete(key);
|
|
38
|
+
return Promise.resolve();
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
private validateKey(key: string): void {
|
|
42
|
+
if (!/^[A-Za-z0-9._-]+$/u.test(key)) throw new Error('Invalid SecureStore key');
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
class FakeBrowser implements BrowserFlowPort {
|
|
47
|
+
public readonly authorizationRequests: AuthorizationRequest[] = [];
|
|
48
|
+
public readonly endSessionRequests: EndSessionRequest[] = [];
|
|
49
|
+
public authorizationResults: AuthorizationResult[] = [successfulAuthorization()];
|
|
50
|
+
public endSessionResult = true;
|
|
51
|
+
public authorizationError: Error | undefined;
|
|
52
|
+
public endSessionError: Error | undefined;
|
|
53
|
+
public beforeEndSession: (() => void) | undefined;
|
|
54
|
+
|
|
55
|
+
public authorize(request: AuthorizationRequest): Promise<AuthorizationResult> {
|
|
56
|
+
this.authorizationRequests.push(request);
|
|
57
|
+
if (this.authorizationError !== undefined) {
|
|
58
|
+
return Promise.reject(this.authorizationError);
|
|
59
|
+
}
|
|
60
|
+
return Promise.resolve(this.authorizationResults.shift() ?? successfulAuthorization());
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
public endSession(request: EndSessionRequest): Promise<boolean> {
|
|
64
|
+
this.beforeEndSession?.();
|
|
65
|
+
this.endSessionRequests.push(request);
|
|
66
|
+
if (this.endSessionError !== undefined) {
|
|
67
|
+
return Promise.reject(this.endSessionError);
|
|
68
|
+
}
|
|
69
|
+
return Promise.resolve(this.endSessionResult);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
interface Harness {
|
|
74
|
+
readonly client: NativeOidcClient;
|
|
75
|
+
readonly storage: MemoryStorage;
|
|
76
|
+
readonly browser: FakeBrowser;
|
|
77
|
+
readonly requests: { readonly url: string; readonly init: RequestInit | undefined }[];
|
|
78
|
+
readonly tokenResponses: unknown[];
|
|
79
|
+
setNow(value: number): void;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
interface HarnessOptions {
|
|
83
|
+
readonly config?: NativeOidcConfig;
|
|
84
|
+
readonly endSessionEndpoint?: string | null;
|
|
85
|
+
readonly tokenResponses?: unknown[];
|
|
86
|
+
readonly userInfo?: unknown;
|
|
87
|
+
readonly fetchOverride?: FetchPort;
|
|
88
|
+
readonly userInfoNow?: number;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const issuer = 'https://identity.example.test/tenant';
|
|
92
|
+
const sessionKey = 'native-test.session';
|
|
93
|
+
const forceLoginKey = 'native-test.force-login';
|
|
94
|
+
|
|
95
|
+
function makeHarness(options: HarnessOptions = {}): Harness {
|
|
96
|
+
const storage = new MemoryStorage();
|
|
97
|
+
const browser = new FakeBrowser();
|
|
98
|
+
const requests: { readonly url: string; readonly init: RequestInit | undefined }[] = [];
|
|
99
|
+
const tokenResponses = options.tokenResponses ?? [defaultTokens()];
|
|
100
|
+
let now = 1_000;
|
|
101
|
+
const fetchImplementation: FetchPort =
|
|
102
|
+
options.fetchOverride ??
|
|
103
|
+
((url, init) => {
|
|
104
|
+
requests.push({ url, init });
|
|
105
|
+
if (url.endsWith('/.well-known/openid-configuration')) {
|
|
106
|
+
const configuredEndSession =
|
|
107
|
+
options.endSessionEndpoint === undefined
|
|
108
|
+
? 'https://login.example.test/session/end'
|
|
109
|
+
: options.endSessionEndpoint;
|
|
110
|
+
return Promise.resolve(
|
|
111
|
+
jsonResponse({
|
|
112
|
+
issuer,
|
|
113
|
+
authorization_endpoint: 'https://login.example.test/oauth/authorize',
|
|
114
|
+
token_endpoint: 'https://login.example.test/oauth/token',
|
|
115
|
+
userinfo_endpoint: 'https://login.example.test/oauth/userinfo',
|
|
116
|
+
...(configuredEndSession === null
|
|
117
|
+
? {}
|
|
118
|
+
: { end_session_endpoint: configuredEndSession }),
|
|
119
|
+
}),
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
if (url.endsWith('/userinfo')) {
|
|
123
|
+
if (options.userInfoNow !== undefined) {
|
|
124
|
+
now = options.userInfoNow;
|
|
125
|
+
}
|
|
126
|
+
return Promise.resolve(jsonResponse(options.userInfo ?? { sub: 'subject-123' }));
|
|
127
|
+
}
|
|
128
|
+
return Promise.resolve(jsonResponse(tokenResponses.shift() ?? defaultTokens()));
|
|
129
|
+
});
|
|
130
|
+
const environment: NativeOidcEnvironment = {
|
|
131
|
+
fetch: fetchImplementation,
|
|
132
|
+
storage,
|
|
133
|
+
browser,
|
|
134
|
+
now: () => now,
|
|
135
|
+
};
|
|
136
|
+
return {
|
|
137
|
+
client: new NativeOidcClient(
|
|
138
|
+
options.config ?? {
|
|
139
|
+
issuer: `${issuer}///`,
|
|
140
|
+
clientId: 'product-mobile',
|
|
141
|
+
redirectUri: 'product://oauth',
|
|
142
|
+
offlineAccess: true,
|
|
143
|
+
storageKeyPrefix: 'native-test',
|
|
144
|
+
},
|
|
145
|
+
environment,
|
|
146
|
+
),
|
|
147
|
+
storage,
|
|
148
|
+
browser,
|
|
149
|
+
requests,
|
|
150
|
+
tokenResponses,
|
|
151
|
+
setNow(value) {
|
|
152
|
+
now = value;
|
|
153
|
+
},
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function successfulAuthorization(
|
|
158
|
+
overrides: Partial<Extract<AuthorizationResult, { readonly type: 'success' }>> = {},
|
|
159
|
+
): Extract<AuthorizationResult, { readonly type: 'success' }> {
|
|
160
|
+
return {
|
|
161
|
+
type: 'success',
|
|
162
|
+
code: 'one-time-code',
|
|
163
|
+
state: 'state-123',
|
|
164
|
+
expectedState: 'state-123',
|
|
165
|
+
codeVerifier: 'pkce-verifier',
|
|
166
|
+
...overrides,
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function defaultTokens(overrides: Record<string, unknown> = {}): Record<string, unknown> {
|
|
171
|
+
return {
|
|
172
|
+
access_token: 'access-secret',
|
|
173
|
+
refresh_token: 'refresh-secret',
|
|
174
|
+
id_token: 'identity-secret',
|
|
175
|
+
expires_in: 60,
|
|
176
|
+
...overrides,
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function storedSession(overrides: Record<string, unknown> = {}): string {
|
|
181
|
+
return JSON.stringify({
|
|
182
|
+
subject: 'stored-subject',
|
|
183
|
+
accessToken: 'stored-access',
|
|
184
|
+
refreshToken: 'stored-refresh',
|
|
185
|
+
idToken: 'stored-id',
|
|
186
|
+
expiresAt: 61_000,
|
|
187
|
+
...overrides,
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function jsonResponse(body: unknown, status = 200): Response {
|
|
192
|
+
return new Response(JSON.stringify(body), {
|
|
193
|
+
status,
|
|
194
|
+
headers: { 'content-type': 'application/json' },
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
describe('NativeOidcClient', () => {
|
|
199
|
+
it.each([
|
|
200
|
+
'app:oidc',
|
|
201
|
+
'@baukit/auth',
|
|
202
|
+
'has space',
|
|
203
|
+
' app',
|
|
204
|
+
'app ',
|
|
205
|
+
'café',
|
|
206
|
+
'line\nbreak',
|
|
207
|
+
'slash/key',
|
|
208
|
+
])('rejects the invalid storage prefix %j before accessing storage', (storageKeyPrefix) => {
|
|
209
|
+
expect(() =>
|
|
210
|
+
makeHarness({
|
|
211
|
+
config: { issuer, clientId: 'mobile', redirectUri: 'product://oauth', storageKeyPrefix },
|
|
212
|
+
}),
|
|
213
|
+
).toThrow("OIDC storage key prefix must contain only ASCII letters, digits, '.', '-' and '_'.");
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
it('rejects an empty storage prefix', () => {
|
|
217
|
+
expect(() =>
|
|
218
|
+
makeHarness({
|
|
219
|
+
config: {
|
|
220
|
+
issuer,
|
|
221
|
+
clientId: 'mobile',
|
|
222
|
+
redirectUri: 'product://oauth',
|
|
223
|
+
storageKeyPrefix: '',
|
|
224
|
+
},
|
|
225
|
+
}),
|
|
226
|
+
).toThrow('OIDC storage key prefix must not be empty.');
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
it('persists both slots with a valid custom prefix and no key adapter', async () => {
|
|
230
|
+
const test = makeHarness({
|
|
231
|
+
config: {
|
|
232
|
+
issuer,
|
|
233
|
+
clientId: 'mobile',
|
|
234
|
+
redirectUri: 'product://oauth',
|
|
235
|
+
storageKeyPrefix: 'App_1.oidc-test',
|
|
236
|
+
},
|
|
237
|
+
});
|
|
238
|
+
await test.client.signIn();
|
|
239
|
+
expect(test.storage.values.has('App_1.oidc-test.session')).toBe(true);
|
|
240
|
+
test.browser.endSessionResult = false;
|
|
241
|
+
await test.client.signOut();
|
|
242
|
+
expect(test.storage.values.get('App_1.oidc-test.force-login')).toBe('1');
|
|
243
|
+
expect(test.storage.values.has('App_1.oidc-test.session')).toBe(false);
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
it('encodes default prefixes without collisions or invalid SecureStore characters', async () => {
|
|
247
|
+
const keys = new Set<string>();
|
|
248
|
+
for (const [configuredIssuer, clientId] of [
|
|
249
|
+
[issuer, 'mobile:é'],
|
|
250
|
+
[issuer, 'mobile_253Aé'],
|
|
251
|
+
[issuer + '.part', 'mobile'],
|
|
252
|
+
[issuer, 'part.mobile'],
|
|
253
|
+
] as const) {
|
|
254
|
+
const test = makeHarness({
|
|
255
|
+
config: { issuer: configuredIssuer, clientId, redirectUri: 'product://oauth' },
|
|
256
|
+
});
|
|
257
|
+
await test.client.initialize();
|
|
258
|
+
const key = test.storage.reads[0];
|
|
259
|
+
expect(key).toMatch(/^baukit\.auth-native\.[A-Za-z0-9._-]+\.session$/u);
|
|
260
|
+
expect(key).toBeDefined();
|
|
261
|
+
if (key === undefined) throw new Error('Missing session storage key');
|
|
262
|
+
keys.add(key);
|
|
263
|
+
}
|
|
264
|
+
expect(keys.size).toBe(4);
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
it('discovers standard endpoints, exchanges PKCE, and stores the UserInfo subject', async () => {
|
|
268
|
+
const test = makeHarness();
|
|
269
|
+
const updates: (string | undefined)[] = [];
|
|
270
|
+
test.client.subscribe((session) => updates.push(session?.subject));
|
|
271
|
+
|
|
272
|
+
await expect(test.client.signIn()).resolves.toEqual({
|
|
273
|
+
status: 'success',
|
|
274
|
+
subject: 'subject-123',
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
expect(test.requests[0]?.url).toBe(`${issuer}/.well-known/openid-configuration`);
|
|
278
|
+
expect(test.browser.authorizationRequests[0]).toEqual({
|
|
279
|
+
authorizationEndpoint: 'https://login.example.test/oauth/authorize',
|
|
280
|
+
clientId: 'product-mobile',
|
|
281
|
+
redirectUri: 'product://oauth',
|
|
282
|
+
scopes: ['openid', 'profile', 'email', 'offline_access'],
|
|
283
|
+
});
|
|
284
|
+
const exchange = test.requests.find(({ url }) => url.endsWith('/token'));
|
|
285
|
+
const exchangeBody = exchange?.init?.body as URLSearchParams;
|
|
286
|
+
expect(exchangeBody.get('code')).toBe('one-time-code');
|
|
287
|
+
expect(exchangeBody.get('code_verifier')).toBe('pkce-verifier');
|
|
288
|
+
const userInfo = test.requests.find(({ url }) => url.endsWith('/userinfo'));
|
|
289
|
+
expect(userInfo?.init?.headers).toEqual({ authorization: 'Bearer access-secret' });
|
|
290
|
+
expect(test.client.session()).toEqual({
|
|
291
|
+
subject: 'subject-123',
|
|
292
|
+
accessToken: 'access-secret',
|
|
293
|
+
refreshToken: 'refresh-secret',
|
|
294
|
+
idToken: 'identity-secret',
|
|
295
|
+
expiresAt: 61_000,
|
|
296
|
+
});
|
|
297
|
+
expect(Object.isFrozen(test.client.session())).toBe(true);
|
|
298
|
+
expect(updates).toEqual([undefined, 'subject-123']);
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
it.each(['cancel', 'dismiss'] as const)(
|
|
302
|
+
'returns %s as a non-error cancellation',
|
|
303
|
+
async (type) => {
|
|
304
|
+
const test = makeHarness();
|
|
305
|
+
test.browser.authorizationResults = [{ type }];
|
|
306
|
+
|
|
307
|
+
await expect(test.client.signIn()).resolves.toEqual({
|
|
308
|
+
status: 'cancelled',
|
|
309
|
+
reason: type,
|
|
310
|
+
});
|
|
311
|
+
expect(test.client.session()).toBeUndefined();
|
|
312
|
+
expect(test.requests.some(({ url }) => url.endsWith('/token'))).toBe(false);
|
|
313
|
+
},
|
|
314
|
+
);
|
|
315
|
+
|
|
316
|
+
it.each([
|
|
317
|
+
[successfulAuthorization({ state: 'attacker-state' }), 'callback_state_mismatch'],
|
|
318
|
+
[successfulAuthorization({ codeVerifier: '' }), 'pkce_verifier_missing'],
|
|
319
|
+
] as const)('rejects invalid state or PKCE transactions', async (result, code) => {
|
|
320
|
+
const test = makeHarness();
|
|
321
|
+
test.browser.authorizationResults = [result];
|
|
322
|
+
|
|
323
|
+
await expect(test.client.signIn()).rejects.toMatchObject({ code });
|
|
324
|
+
expect(test.client.session()).toBeUndefined();
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
it('retains the ID token while accepting a rotated refresh token', async () => {
|
|
328
|
+
const test = makeHarness({
|
|
329
|
+
tokenResponses: [
|
|
330
|
+
defaultTokens(),
|
|
331
|
+
defaultTokens({
|
|
332
|
+
access_token: 'refreshed-access',
|
|
333
|
+
refresh_token: 'rotated-refresh',
|
|
334
|
+
id_token: undefined,
|
|
335
|
+
expires_in: 120,
|
|
336
|
+
}),
|
|
337
|
+
],
|
|
338
|
+
});
|
|
339
|
+
await test.client.signIn();
|
|
340
|
+
test.setNow(40_000);
|
|
341
|
+
|
|
342
|
+
await expect(test.client.accessToken()).resolves.toBe('refreshed-access');
|
|
343
|
+
expect(test.client.session()).toMatchObject({
|
|
344
|
+
subject: 'subject-123',
|
|
345
|
+
refreshToken: 'rotated-refresh',
|
|
346
|
+
idToken: 'identity-secret',
|
|
347
|
+
});
|
|
348
|
+
const refresh = test.requests.filter(({ url }) => url.endsWith('/token')).at(-1);
|
|
349
|
+
expect((refresh?.init?.body as URLSearchParams).get('refresh_token')).toBe('refresh-secret');
|
|
350
|
+
});
|
|
351
|
+
|
|
352
|
+
it('retains the previous refresh token when refresh omits it', async () => {
|
|
353
|
+
const test = makeHarness({
|
|
354
|
+
tokenResponses: [
|
|
355
|
+
defaultTokens(),
|
|
356
|
+
defaultTokens({
|
|
357
|
+
access_token: 'refreshed-access',
|
|
358
|
+
refresh_token: undefined,
|
|
359
|
+
id_token: undefined,
|
|
360
|
+
}),
|
|
361
|
+
],
|
|
362
|
+
});
|
|
363
|
+
await test.client.signIn();
|
|
364
|
+
test.setNow(40_000);
|
|
365
|
+
|
|
366
|
+
await test.client.accessToken();
|
|
367
|
+
expect(test.client.session()).toMatchObject({
|
|
368
|
+
refreshToken: 'refresh-secret',
|
|
369
|
+
idToken: 'identity-secret',
|
|
370
|
+
});
|
|
371
|
+
});
|
|
372
|
+
|
|
373
|
+
it('anchors expiry to token receipt before later UserInfo work', async () => {
|
|
374
|
+
const test = makeHarness({ userInfoNow: 500_000 });
|
|
375
|
+
|
|
376
|
+
await test.client.signIn();
|
|
377
|
+
|
|
378
|
+
expect(test.client.session()?.expiresAt).toBe(61_000);
|
|
379
|
+
});
|
|
380
|
+
|
|
381
|
+
it('forwards the state decoration to the browser flow', async () => {
|
|
382
|
+
const test = makeHarness();
|
|
383
|
+
|
|
384
|
+
await test.client.signIn({ stateDecoration: ['ap1', 'd'] });
|
|
385
|
+
|
|
386
|
+
expect(test.browser.authorizationRequests[0]?.stateDecoration).toEqual(['ap1', 'd']);
|
|
387
|
+
});
|
|
388
|
+
|
|
389
|
+
it('shares one refresh across proactive and forced concurrent callers', async () => {
|
|
390
|
+
let resolveRefresh: ((response: Response) => void) | undefined;
|
|
391
|
+
let refreshCalls = 0;
|
|
392
|
+
const test = makeHarness({
|
|
393
|
+
fetchOverride: (url) => {
|
|
394
|
+
if (url.endsWith('/.well-known/openid-configuration')) {
|
|
395
|
+
return Promise.resolve(
|
|
396
|
+
jsonResponse({
|
|
397
|
+
issuer,
|
|
398
|
+
authorization_endpoint: 'https://login.example.test/oauth/authorize',
|
|
399
|
+
token_endpoint: 'https://login.example.test/oauth/token',
|
|
400
|
+
userinfo_endpoint: 'https://login.example.test/oauth/userinfo',
|
|
401
|
+
}),
|
|
402
|
+
);
|
|
403
|
+
}
|
|
404
|
+
refreshCalls += 1;
|
|
405
|
+
return new Promise((resolve) => {
|
|
406
|
+
resolveRefresh = resolve;
|
|
407
|
+
});
|
|
408
|
+
},
|
|
409
|
+
});
|
|
410
|
+
test.storage.values.set(sessionKey, storedSession({ expiresAt: 900 }));
|
|
411
|
+
|
|
412
|
+
const proactive = test.client.accessToken();
|
|
413
|
+
const forced = test.client.accessToken({ forceRefresh: true });
|
|
414
|
+
await vi.waitFor(() => {
|
|
415
|
+
expect(refreshCalls).toBe(1);
|
|
416
|
+
});
|
|
417
|
+
resolveRefresh?.(
|
|
418
|
+
jsonResponse(defaultTokens({ access_token: 'shared-access', refresh_token: undefined })),
|
|
419
|
+
);
|
|
420
|
+
|
|
421
|
+
await expect(Promise.all([proactive, forced])).resolves.toEqual([
|
|
422
|
+
'shared-access',
|
|
423
|
+
'shared-access',
|
|
424
|
+
]);
|
|
425
|
+
expect(refreshCalls).toBe(1);
|
|
426
|
+
});
|
|
427
|
+
|
|
428
|
+
it('does not report expiry after a session is cleared during a rejected refresh', async () => {
|
|
429
|
+
let resolveRefresh: ((response: Response) => void) | undefined;
|
|
430
|
+
const test = makeHarness({
|
|
431
|
+
fetchOverride: (url) => {
|
|
432
|
+
if (url.endsWith('/.well-known/openid-configuration')) {
|
|
433
|
+
return Promise.resolve(
|
|
434
|
+
jsonResponse({
|
|
435
|
+
issuer,
|
|
436
|
+
authorization_endpoint: 'https://login.example.test/oauth/authorize',
|
|
437
|
+
token_endpoint: 'https://login.example.test/oauth/token',
|
|
438
|
+
userinfo_endpoint: 'https://login.example.test/oauth/userinfo',
|
|
439
|
+
}),
|
|
440
|
+
);
|
|
441
|
+
}
|
|
442
|
+
return new Promise((resolve) => {
|
|
443
|
+
resolveRefresh = resolve;
|
|
444
|
+
});
|
|
445
|
+
},
|
|
446
|
+
});
|
|
447
|
+
test.storage.values.set(sessionKey, storedSession({ expiresAt: 900 }));
|
|
448
|
+
const expired: unknown[] = [];
|
|
449
|
+
test.client.subscribeSessionExpired((event) => expired.push(event));
|
|
450
|
+
|
|
451
|
+
const pending = test.client.accessToken();
|
|
452
|
+
await vi.waitFor(() => {
|
|
453
|
+
expect(resolveRefresh).toBeDefined();
|
|
454
|
+
});
|
|
455
|
+
await test.client.clearSession();
|
|
456
|
+
resolveRefresh?.(jsonResponse({ error: 'invalid_grant' }, 400));
|
|
457
|
+
|
|
458
|
+
await expect(pending).resolves.toBeUndefined();
|
|
459
|
+
expect(test.client.session()).toBeUndefined();
|
|
460
|
+
expect(expired).toEqual([]);
|
|
461
|
+
});
|
|
462
|
+
|
|
463
|
+
it('forces refresh outside the proactive expiry window', async () => {
|
|
464
|
+
const test = makeHarness({
|
|
465
|
+
tokenResponses: [defaultTokens(), defaultTokens({ access_token: 'forced-access' })],
|
|
466
|
+
});
|
|
467
|
+
await test.client.signIn();
|
|
468
|
+
|
|
469
|
+
await expect(test.client.accessToken({ forceRefresh: true })).resolves.toBe('forced-access');
|
|
470
|
+
expect(test.requests.filter(({ url }) => url.endsWith('/token'))).toHaveLength(2);
|
|
471
|
+
});
|
|
472
|
+
|
|
473
|
+
it('keeps a session retryable after a transient refresh failure', async () => {
|
|
474
|
+
const test = makeHarness({
|
|
475
|
+
fetchOverride: (url) => {
|
|
476
|
+
if (url.endsWith('/.well-known/openid-configuration')) {
|
|
477
|
+
return Promise.resolve(
|
|
478
|
+
jsonResponse({
|
|
479
|
+
issuer,
|
|
480
|
+
authorization_endpoint: 'https://login.example.test/oauth/authorize',
|
|
481
|
+
token_endpoint: 'https://login.example.test/oauth/token',
|
|
482
|
+
userinfo_endpoint: 'https://login.example.test/oauth/userinfo',
|
|
483
|
+
}),
|
|
484
|
+
);
|
|
485
|
+
}
|
|
486
|
+
return Promise.resolve(jsonResponse({ error: 'temporarily_unavailable' }, 503));
|
|
487
|
+
},
|
|
488
|
+
});
|
|
489
|
+
test.storage.values.set(sessionKey, storedSession({ expiresAt: 900 }));
|
|
490
|
+
|
|
491
|
+
await expect(test.client.accessToken()).rejects.toMatchObject({
|
|
492
|
+
code: 'refresh_failed',
|
|
493
|
+
retryable: true,
|
|
494
|
+
status: 503,
|
|
495
|
+
});
|
|
496
|
+
expect(test.client.session()?.refreshToken).toBe('stored-refresh');
|
|
497
|
+
expect(test.storage.values.has(sessionKey)).toBe(true);
|
|
498
|
+
});
|
|
499
|
+
|
|
500
|
+
it.each([
|
|
501
|
+
[400, { error: 'provider_error' }],
|
|
502
|
+
[403, { error: 'invalid_token' }],
|
|
503
|
+
] as const)('expires the session for terminal refresh rejection %#', async (status, body) => {
|
|
504
|
+
const test = makeHarness({
|
|
505
|
+
fetchOverride: (url) => {
|
|
506
|
+
if (url.endsWith('/.well-known/openid-configuration')) {
|
|
507
|
+
return Promise.resolve(
|
|
508
|
+
jsonResponse({
|
|
509
|
+
issuer,
|
|
510
|
+
authorization_endpoint: 'https://login.example.test/oauth/authorize',
|
|
511
|
+
token_endpoint: 'https://login.example.test/oauth/token',
|
|
512
|
+
userinfo_endpoint: 'https://login.example.test/oauth/userinfo',
|
|
513
|
+
}),
|
|
514
|
+
);
|
|
515
|
+
}
|
|
516
|
+
return Promise.resolve(jsonResponse(body, status));
|
|
517
|
+
},
|
|
518
|
+
});
|
|
519
|
+
test.storage.values.set(sessionKey, storedSession({ expiresAt: 900 }));
|
|
520
|
+
const expired: unknown[] = [];
|
|
521
|
+
test.client.subscribeSessionExpired((event) => expired.push(event));
|
|
522
|
+
|
|
523
|
+
await expect(test.client.accessToken()).resolves.toBeUndefined();
|
|
524
|
+
expect(test.client.session()).toBeUndefined();
|
|
525
|
+
expect(test.storage.values.has(sessionKey)).toBe(false);
|
|
526
|
+
expect(expired).toEqual([{ type: 'session-expired', reason: 'refresh_rejected' }]);
|
|
527
|
+
});
|
|
528
|
+
|
|
529
|
+
it('clears an expired session without a refresh token', async () => {
|
|
530
|
+
const test = makeHarness();
|
|
531
|
+
test.storage.values.set(sessionKey, storedSession({ refreshToken: undefined, expiresAt: 900 }));
|
|
532
|
+
const expired: unknown[] = [];
|
|
533
|
+
test.client.subscribeSessionExpired((event) => expired.push(event));
|
|
534
|
+
|
|
535
|
+
await expect(test.client.accessToken()).resolves.toBeUndefined();
|
|
536
|
+
expect(test.client.session()).toBeUndefined();
|
|
537
|
+
expect(test.storage.values.has(sessionKey)).toBe(false);
|
|
538
|
+
expect(expired).toEqual([{ type: 'session-expired', reason: 'refresh_unavailable' }]);
|
|
539
|
+
});
|
|
540
|
+
|
|
541
|
+
it('deletes corrupt secure storage and initializes signed out', async () => {
|
|
542
|
+
const test = makeHarness();
|
|
543
|
+
test.storage.values.set(sessionKey, '{private-token:broken');
|
|
544
|
+
|
|
545
|
+
await expect(test.client.initialize()).resolves.toBeUndefined();
|
|
546
|
+
expect(test.storage.deletes).toContain(sessionKey);
|
|
547
|
+
expect(test.storage.values.has(sessionKey)).toBe(false);
|
|
548
|
+
});
|
|
549
|
+
|
|
550
|
+
it('clears the local session before a working end-session flow', async () => {
|
|
551
|
+
const test = makeHarness();
|
|
552
|
+
await test.client.signIn();
|
|
553
|
+
test.browser.beforeEndSession = () => {
|
|
554
|
+
expect(test.client.session()).toBeUndefined();
|
|
555
|
+
expect(test.storage.values.has(sessionKey)).toBe(false);
|
|
556
|
+
};
|
|
557
|
+
|
|
558
|
+
await expect(test.client.signOut()).resolves.toEqual({ providerLogout: 'completed' });
|
|
559
|
+
const request = test.browser.endSessionRequests[0];
|
|
560
|
+
const logout = new URL(request?.url ?? 'https://invalid.example.test');
|
|
561
|
+
expect(logout.origin + logout.pathname).toBe('https://login.example.test/session/end');
|
|
562
|
+
expect(logout.searchParams.get('id_token_hint')).toBe('identity-secret');
|
|
563
|
+
expect(test.storage.values.has(forceLoginKey)).toBe(false);
|
|
564
|
+
});
|
|
565
|
+
|
|
566
|
+
it('forces the next login after a failed end-session flow and keeps it through cancellation', async () => {
|
|
567
|
+
const test = makeHarness();
|
|
568
|
+
await test.client.signIn();
|
|
569
|
+
test.browser.endSessionError = new Error('provider body access-secret');
|
|
570
|
+
|
|
571
|
+
await expect(test.client.signOut()).resolves.toEqual({ providerLogout: 'failed' });
|
|
572
|
+
expect(test.storage.values.get(forceLoginKey)).toBe('1');
|
|
573
|
+
|
|
574
|
+
test.browser.endSessionError = undefined;
|
|
575
|
+
test.browser.authorizationResults = [{ type: 'cancel' }];
|
|
576
|
+
await expect(test.client.signIn()).resolves.toEqual({
|
|
577
|
+
status: 'cancelled',
|
|
578
|
+
reason: 'cancel',
|
|
579
|
+
});
|
|
580
|
+
expect(test.browser.authorizationRequests.at(-1)?.prompt).toBe('login');
|
|
581
|
+
expect(test.storage.values.get(forceLoginKey)).toBe('1');
|
|
582
|
+
});
|
|
583
|
+
|
|
584
|
+
it('forces the next login when discovery has no end-session endpoint', async () => {
|
|
585
|
+
const test = makeHarness({ endSessionEndpoint: null });
|
|
586
|
+
await test.client.signIn();
|
|
587
|
+
|
|
588
|
+
await expect(test.client.signOut()).resolves.toEqual({ providerLogout: 'unavailable' });
|
|
589
|
+
test.browser.authorizationResults = [{ type: 'dismiss' }];
|
|
590
|
+
await test.client.signIn();
|
|
591
|
+
expect(test.browser.authorizationRequests.at(-1)?.prompt).toBe('login');
|
|
592
|
+
});
|
|
593
|
+
|
|
594
|
+
it('removes forced login only after a later successful sign-in', async () => {
|
|
595
|
+
const test = makeHarness();
|
|
596
|
+
test.storage.values.set(forceLoginKey, '1');
|
|
597
|
+
|
|
598
|
+
await test.client.signIn();
|
|
599
|
+
|
|
600
|
+
expect(test.browser.authorizationRequests[0]?.prompt).toBe('login');
|
|
601
|
+
expect(test.storage.values.has(forceLoginKey)).toBe(false);
|
|
602
|
+
});
|
|
603
|
+
|
|
604
|
+
it('redacts provider bodies, tokens, codes, and adapter exceptions', async () => {
|
|
605
|
+
const leaked = 'provider-private access-secret one-time-code';
|
|
606
|
+
const requests: string[] = [];
|
|
607
|
+
const fetchImplementation: FetchPort = (url) => {
|
|
608
|
+
requests.push(url);
|
|
609
|
+
if (url.endsWith('/.well-known/openid-configuration')) {
|
|
610
|
+
return Promise.resolve(
|
|
611
|
+
jsonResponse({
|
|
612
|
+
issuer,
|
|
613
|
+
authorization_endpoint: 'https://login.example.test/oauth/authorize',
|
|
614
|
+
token_endpoint: 'https://login.example.test/oauth/token',
|
|
615
|
+
userinfo_endpoint: 'https://login.example.test/oauth/userinfo',
|
|
616
|
+
}),
|
|
617
|
+
);
|
|
618
|
+
}
|
|
619
|
+
return Promise.resolve(new Response(leaked, { status: 400 }));
|
|
620
|
+
};
|
|
621
|
+
const tokenFailure = makeHarness({ fetchOverride: fetchImplementation });
|
|
622
|
+
let caught: unknown;
|
|
623
|
+
try {
|
|
624
|
+
await tokenFailure.client.signIn();
|
|
625
|
+
} catch (cause) {
|
|
626
|
+
caught = cause;
|
|
627
|
+
}
|
|
628
|
+
expect(caught).toBeInstanceOf(OidcError);
|
|
629
|
+
expect(caught).toMatchObject({ code: 'token_exchange_failed', status: 400 });
|
|
630
|
+
expect(String(caught)).not.toContain(leaked);
|
|
631
|
+
expect(safeAuthErrorMessage(caught)).toBe('OIDC token exchange failed.');
|
|
632
|
+
expect(safeAuthErrorMessage(new Error(leaked))).toBe('OIDC login failed.');
|
|
633
|
+
expect(requests).toHaveLength(2);
|
|
634
|
+
|
|
635
|
+
const browserFailure = makeHarness();
|
|
636
|
+
browserFailure.browser.authorizationError = new Error(leaked);
|
|
637
|
+
await browserFailure.client.signIn().catch((cause: unknown) => {
|
|
638
|
+
expect(String(cause)).not.toContain(leaked);
|
|
639
|
+
expect(cause).toMatchObject({ code: 'authorization_failed' });
|
|
640
|
+
});
|
|
641
|
+
});
|
|
642
|
+
});
|