@axa-fr/oidc-client 7.29.7 → 7.30.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 (72) hide show
  1. package/README.md +226 -0
  2. package/dist/events.d.ts +3 -0
  3. package/dist/events.d.ts.map +1 -1
  4. package/dist/fetch.d.ts +2 -2
  5. package/dist/fetch.d.ts.map +1 -1
  6. package/dist/index.d.ts +1 -1
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +1353 -873
  9. package/dist/index.umd.cjs +2 -2
  10. package/dist/initSession.d.ts +2 -0
  11. package/dist/initSession.d.ts.map +1 -1
  12. package/dist/initWorker.d.ts +1 -25
  13. package/dist/initWorker.d.ts.map +1 -1
  14. package/dist/jwt.d.ts.map +1 -1
  15. package/dist/legacyCompatibility.spec.d.ts +2 -0
  16. package/dist/legacyCompatibility.spec.d.ts.map +1 -0
  17. package/dist/login.d.ts +2 -1
  18. package/dist/login.d.ts.map +1 -1
  19. package/dist/logout.d.ts.map +1 -1
  20. package/dist/node_modules/@axa-fr/oidc-client-service-worker/dist/OidcServiceWorker.js +1049 -0
  21. package/dist/node_modules/@axa-fr/oidc-client-service-worker/dist/OidcTrustedDomains.js +31 -0
  22. package/dist/oidc.d.ts +6 -1
  23. package/dist/oidc.d.ts.map +1 -1
  24. package/dist/oidcClient.d.ts +13 -2
  25. package/dist/oidcClient.d.ts.map +1 -1
  26. package/dist/oidcError.d.ts +5 -0
  27. package/dist/oidcError.d.ts.map +1 -1
  28. package/dist/parseTokens.d.ts +10 -0
  29. package/dist/parseTokens.d.ts.map +1 -1
  30. package/dist/protocol.d.ts +7 -1
  31. package/dist/protocol.d.ts.map +1 -1
  32. package/dist/renewTokens.d.ts +0 -6
  33. package/dist/renewTokens.d.ts.map +1 -1
  34. package/dist/requests.d.ts +3 -3
  35. package/dist/requests.d.ts.map +1 -1
  36. package/dist/resourceParameters.d.ts +9 -0
  37. package/dist/resourceParameters.d.ts.map +1 -0
  38. package/dist/resourceTokens.d.ts +34 -0
  39. package/dist/resourceTokens.d.ts.map +1 -0
  40. package/dist/resourceTokens.spec.d.ts +2 -0
  41. package/dist/resourceTokens.spec.d.ts.map +1 -0
  42. package/dist/silentLogin.d.ts +2 -1
  43. package/dist/silentLogin.d.ts.map +1 -1
  44. package/dist/types.d.ts +28 -0
  45. package/dist/types.d.ts.map +1 -1
  46. package/dist/version.d.ts +1 -1
  47. package/package.json +3 -3
  48. package/src/events.ts +3 -0
  49. package/src/fetch.ts +115 -15
  50. package/src/index.ts +4 -0
  51. package/src/initSession.ts +9 -0
  52. package/src/initWorker.ts +65 -13
  53. package/src/jwt.spec.ts +17 -0
  54. package/src/jwt.ts +4 -1
  55. package/src/legacyCompatibility.spec.ts +142 -0
  56. package/src/login.ts +91 -29
  57. package/src/logout.ts +36 -0
  58. package/src/oidc.ts +71 -20
  59. package/src/oidcClient.ts +48 -3
  60. package/src/oidcError.ts +7 -0
  61. package/src/parseTokens.ts +14 -1
  62. package/src/protocol.ts +16 -1
  63. package/src/renewTokens.ts +32 -16
  64. package/src/renewTokensError.spec.ts +111 -0
  65. package/src/requests.ts +13 -11
  66. package/src/resourceParameters.ts +85 -0
  67. package/src/resourceTokens.spec.ts +1271 -0
  68. package/src/resourceTokens.ts +708 -0
  69. package/src/silentLogin.spec.ts +87 -1
  70. package/src/silentLogin.ts +24 -22
  71. package/src/types.ts +34 -0
  72. package/src/version.ts +1 -1
package/src/fetch.ts CHANGED
@@ -2,8 +2,13 @@
2
2
  import Oidc from './oidc';
3
3
  import { createNetworkError, OidcError, OidcErrorCode, OidcErrorPhase } from './oidcError';
4
4
  import { getValidTokenAsync, OidcToken } from './parseTokens';
5
+ import {
6
+ getResourceConfiguration,
7
+ isResourceOriginManaged,
8
+ isResourceUrlAllowed,
9
+ } from './protocol';
5
10
  import { syncTokensInfoAsync } from './renewTokens';
6
- import { Fetch } from './types';
11
+ import { Fetch, ResourceFetchOptions } from './types';
7
12
 
8
13
  // @ts-ignore
9
14
  export const fetchWithTokens =
@@ -11,16 +16,83 @@ export const fetchWithTokens =
11
16
  fetch: Fetch,
12
17
  oidc: Oidc,
13
18
  demonstrating_proof_of_possession: boolean = false,
14
- phase: OidcErrorPhase = 'api_request',
19
+ selection: OidcErrorPhase | ResourceFetchOptions = 'api_request',
15
20
  ): Fetch =>
16
21
  async (...params: Parameters<Fetch>): Promise<Response> => {
17
22
  const [url, options, ...rest] = params;
18
- const optionTmp = options ? { ...options } : { method: 'GET' };
23
+ const phase = typeof selection === 'string' ? selection : 'api_request';
24
+ const resource = typeof selection === 'string' ? undefined : selection.resource;
25
+ let destination: string | undefined;
26
+ if (resource === undefined && phase === 'api_request' && oidc.configuration.resources?.length) {
27
+ try {
28
+ const candidate = new URL(
29
+ url instanceof Request ? url.url : url.toString(),
30
+ window.location.href,
31
+ ).toString();
32
+ if (isResourceOriginManaged(oidc.configuration.resources, candidate)) {
33
+ throw new Error('Select a resource explicitly when fetching a resource-managed API.');
34
+ }
35
+ } catch (cause) {
36
+ const error = new OidcError(
37
+ OidcErrorCode.INVALID_RESOURCE,
38
+ cause instanceof Error ? cause.message : 'Invalid resource destination.',
39
+ { phase, retryable: false, cause },
40
+ );
41
+ oidc.publishEvent(eventNames.apiRequest_error, error);
42
+ throw error;
43
+ }
44
+ }
45
+ if (
46
+ typeof selection !== 'string' &&
47
+ Object.prototype.hasOwnProperty.call(selection, 'resource')
48
+ ) {
49
+ try {
50
+ if (typeof resource !== 'string')
51
+ throw new Error('An explicit resource identifier is required.');
52
+ destination = new URL(
53
+ url instanceof Request ? url.url : url.toString(),
54
+ window.location.href,
55
+ ).toString();
56
+ if (
57
+ !isResourceUrlAllowed(
58
+ getResourceConfiguration(oidc.configuration.resources, resource),
59
+ destination,
60
+ )
61
+ ) {
62
+ throw new Error('The destination does not belong to the selected resource.');
63
+ }
64
+ if (options?.redirect === 'follow')
65
+ throw new Error('Resource fetch cannot automatically follow redirects.');
66
+ } catch (cause) {
67
+ const error = new OidcError(
68
+ OidcErrorCode.INVALID_RESOURCE,
69
+ cause instanceof Error ? cause.message : 'Invalid resource destination.',
70
+ { phase, retryable: false, cause },
71
+ );
72
+ oidc.publishEvent(eventNames.apiRequest_error, error);
73
+ throw error;
74
+ }
75
+ }
76
+ const optionTmp: RequestInit =
77
+ resource !== undefined
78
+ ? {
79
+ ...(url instanceof Request
80
+ ? { method: url.method, headers: url.headers, credentials: url.credentials }
81
+ : { method: 'GET' }),
82
+ ...options,
83
+ redirect: options?.redirect ?? 'error',
84
+ }
85
+ : options
86
+ ? { ...options }
87
+ : { method: 'GET' };
19
88
  let headers = new Headers();
20
89
  if (optionTmp.headers) {
21
- headers = !(optionTmp.headers instanceof Headers)
22
- ? new Headers(optionTmp.headers)
23
- : optionTmp.headers;
90
+ headers =
91
+ resource !== undefined
92
+ ? new Headers(optionTmp.headers)
93
+ : !(optionTmp.headers instanceof Headers)
94
+ ? new Headers(optionTmp.headers)
95
+ : optionTmp.headers;
24
96
  }
25
97
  const oidcToken: OidcToken = {
26
98
  getTokens: () => oidc.tokens,
@@ -43,22 +115,31 @@ export const fetchWithTokens =
43
115
  };
44
116
 
45
117
  // @ts-ignore
46
- const getValidToken = await getValidTokenAsync(oidcToken);
47
- const accessToken = getValidToken?.tokens?.accessToken;
118
+ const resourceToken =
119
+ resource === undefined ? undefined : await oidc.resourceTokens.getAccessTokenAsync(resource);
120
+ const getValidToken = resource === undefined ? await getValidTokenAsync(oidcToken) : undefined;
121
+ const accessToken = resourceToken?.accessToken ?? getValidToken?.tokens?.accessToken;
48
122
  if (!headers.has('Accept')) {
49
123
  headers.set('Accept', 'application/json');
50
124
  }
51
125
  if (accessToken) {
52
126
  if (
53
- oidc.configuration.demonstrating_proof_of_possession &&
54
- demonstrating_proof_of_possession
127
+ (oidc.configuration.demonstrating_proof_of_possession &&
128
+ demonstrating_proof_of_possession) ||
129
+ resourceToken?.tokenType?.toLowerCase() === 'dpop'
55
130
  ) {
56
131
  const demonstrationOdProofOfPossession =
57
- await oidc.generateDemonstrationOfProofOfPossessionAsync(
58
- accessToken,
59
- url.toString(),
60
- optionTmp.method,
61
- );
132
+ resource === undefined
133
+ ? await oidc.generateDemonstrationOfProofOfPossessionAsync(
134
+ accessToken,
135
+ url.toString(),
136
+ optionTmp.method,
137
+ )
138
+ : await oidc.resourceTokens.generateProofAsync(resource, {
139
+ accessToken,
140
+ url: destination,
141
+ method: optionTmp.method ?? 'GET',
142
+ });
62
143
  headers.set('Authorization', `DPoP ${accessToken}`);
63
144
  headers.set('DPoP', demonstrationOdProofOfPossession);
64
145
  } else {
@@ -69,6 +150,22 @@ export const fetchWithTokens =
69
150
  }
70
151
  }
71
152
  const newOptions = { ...optionTmp, headers };
153
+ const recordApiNonce =
154
+ resourceToken && headers.has('DPoP')
155
+ ? oidc.resourceTokens.createApiNonceRecorder(resource)
156
+ : undefined;
157
+ if (
158
+ resourceToken &&
159
+ oidc.resourceTokens.peek(resource)?.accessToken !== resourceToken.accessToken
160
+ ) {
161
+ const error = new OidcError(
162
+ OidcErrorCode.RESOURCE_TOKEN_UNAVAILABLE,
163
+ 'The selected resource token was cleared or changed before dispatch.',
164
+ { phase, retryable: false },
165
+ );
166
+ oidc.publishEvent(eventNames.apiRequest_error, error);
167
+ throw error;
168
+ }
72
169
  let response: Response;
73
170
  try {
74
171
  response = await fetch(url, newOptions, ...rest);
@@ -80,6 +177,9 @@ export const fetchWithTokens =
80
177
  throw error;
81
178
  }
82
179
 
180
+ const apiNonce = response.headers?.get('DPoP-Nonce');
181
+ if (recordApiNonce && apiNonce) await recordApiNonce(apiNonce);
182
+
83
183
  if (
84
184
  !response.ok &&
85
185
  response.headers?.has('DPoP-Nonce') &&
package/src/index.ts CHANGED
@@ -38,7 +38,11 @@ export type {
38
38
  AuthorityConfiguration,
39
39
  Fetch,
40
40
  OidcConfiguration,
41
+ OidcResourceConfiguration,
41
42
  PushedAuthorizationRequestMode,
43
+ ResourceAccessToken,
44
+ ResourceFetchOptions,
45
+ ResourceTokenOptions,
42
46
  StringMap,
43
47
  } from './types.js';
44
48
  export { TokenAutomaticRenewMode } from './types.js';
@@ -102,6 +102,13 @@ export const initSession = (
102
102
  return storage[`oidc.dpop_nonce.${configurationName}`];
103
103
  };
104
104
 
105
+ const setDemonstratingProofOfPossessionApiNonce = async (nonce: string): Promise<void> => {
106
+ writeRaw(storage, `oidc.dpop_api_nonce.${configurationName}`, nonce);
107
+ };
108
+
109
+ const getDemonstratingProofOfPossessionApiNonce = (): string | undefined =>
110
+ storage[`oidc.dpop_api_nonce.${configurationName}`];
111
+
105
112
  const getTokens = () => {
106
113
  const parsed = parseJsonOrNull(storage[`oidc.${configurationName}`]) as {
107
114
  tokens: any;
@@ -170,6 +177,8 @@ export const initSession = (
170
177
  setCodeVerifierAsync,
171
178
  setDemonstratingProofOfPossessionNonce,
172
179
  getDemonstratingProofOfPossessionNonce,
180
+ setDemonstratingProofOfPossessionApiNonce,
181
+ getDemonstratingProofOfPossessionApiNonce,
173
182
  setDemonstratingProofOfPossessionJwkAsync,
174
183
  getDemonstratingProofOfPossessionJwkAsync,
175
184
  };
package/src/initWorker.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { ILOidcLocation } from './location';
2
+ import { OidcError, OidcErrorCode } from './oidcError';
2
3
  import { parseOriginalTokens } from './parseTokens.js';
4
+ import { getContextResource } from './protocol';
3
5
  import timer from './timer.js';
4
6
  import { OidcConfiguration } from './types.js';
5
7
  import codeVersion from './version.js';
@@ -62,6 +64,9 @@ export const defaultServiceWorkerUpdateRequireCallback =
62
64
  };
63
65
 
64
66
  export const getTabId = (configurationName: string) => {
67
+ if (getContextResource(configurationName) !== undefined) {
68
+ configurationName = configurationName.split('#resource=')[0];
69
+ }
65
70
  const key = `oidc.tabId.${configurationName}`;
66
71
  const tabId = sessionStorage.getItem(key);
67
72
  if (tabId) return tabId;
@@ -224,6 +229,21 @@ export const initWorkerAsync = async (
224
229
  configurationName: string,
225
230
  ) => {
226
231
  const serviceWorkerRelativeUrl = configuration.service_worker_relative_url;
232
+ const resource = getContextResource(configurationName);
233
+ const baseConfigurationName = configurationName.split('#resource=')[0];
234
+ const unavailable = () => {
235
+ if (resource !== undefined && serviceWorkerRelativeUrl) {
236
+ throw new OidcError(
237
+ OidcErrorCode.RESOURCE_WORKER_UNSUPPORTED,
238
+ 'Resource token isolation requires an available, compatible Service Worker.',
239
+ {
240
+ phase: 'refresh',
241
+ retryable: false,
242
+ },
243
+ );
244
+ }
245
+ return null;
246
+ };
227
247
 
228
248
  if (
229
249
  typeof window === 'undefined' ||
@@ -231,14 +251,15 @@ export const initWorkerAsync = async (
231
251
  !navigator.serviceWorker ||
232
252
  !serviceWorkerRelativeUrl
233
253
  ) {
234
- return null;
254
+ return unavailable();
235
255
  }
236
256
 
237
257
  if (configuration.service_worker_activate() === false) {
238
- return null;
258
+ return unavailable();
239
259
  }
240
260
 
241
- const swUrl = `${serviceWorkerRelativeUrl}?v=${codeVersion}`;
261
+ const separator = serviceWorkerRelativeUrl.includes('?') ? '&' : '?';
262
+ const swUrl = `${serviceWorkerRelativeUrl}${separator}v=${codeVersion}`;
242
263
 
243
264
  const cacheKey = configuration.service_worker_register ? serviceWorkerRelativeUrl : swUrl;
244
265
 
@@ -265,7 +286,7 @@ export const initWorkerAsync = async (
265
286
  'oidc-client: service worker registration was aborted (likely tab shutdown or backgrounding); falling back to non–service-worker mode.',
266
287
  error,
267
288
  );
268
- return null;
289
+ return unavailable();
269
290
  }
270
291
  throw error;
271
292
  }
@@ -399,7 +420,7 @@ export const initWorkerAsync = async (
399
420
  }
400
421
  } catch (err: any) {
401
422
  console.warn(`Failed init ServiceWorker ${err?.toString?.() ?? String(err)}`);
402
- return null;
423
+ return unavailable();
403
424
  }
404
425
 
405
426
  // 3) Register the controllerchange listener AFTER claim, and only once per page lifetime.
@@ -442,16 +463,42 @@ export const initWorkerAsync = async (
442
463
  where,
443
464
  oidcConfiguration: OidcConfiguration,
444
465
  ) => {
466
+ const workerConfiguration = {
467
+ token_renew_mode: oidcConfiguration.token_renew_mode,
468
+ client_id: oidcConfiguration.client_id,
469
+ scope: oidcConfiguration.scope,
470
+ resource: oidcConfiguration.resource,
471
+ resources: oidcConfiguration.resources,
472
+ service_worker_convert_all_requests_to_cors:
473
+ oidcConfiguration.service_worker_convert_all_requests_to_cors,
474
+ };
475
+ if (resource !== undefined) {
476
+ const capability = await sendMessageAsync(registration)({
477
+ type: 'init',
478
+ configurationName: baseConfigurationName,
479
+ data: {
480
+ oidcServerConfiguration,
481
+ where: 'resource-capability',
482
+ oidcConfiguration: workerConfiguration,
483
+ },
484
+ });
485
+ if (capability.resourceTokenManagement !== true) {
486
+ throw new OidcError(
487
+ OidcErrorCode.RESOURCE_WORKER_UNSUPPORTED,
488
+ 'Update OidcServiceWorker.js before using resource tokens.',
489
+ {
490
+ phase: 'refresh',
491
+ retryable: false,
492
+ },
493
+ );
494
+ }
495
+ }
445
496
  const result = await sendMessageAsync(registration)({
446
497
  type: 'init',
447
498
  data: {
448
499
  oidcServerConfiguration,
449
500
  where,
450
- oidcConfiguration: {
451
- token_renew_mode: oidcConfiguration.token_renew_mode,
452
- service_worker_convert_all_requests_to_cors:
453
- oidcConfiguration.service_worker_convert_all_requests_to_cors,
454
- },
501
+ oidcConfiguration: workerConfiguration,
455
502
  },
456
503
  configurationName,
457
504
  });
@@ -512,6 +559,7 @@ export const initWorkerAsync = async (
512
559
  return {
513
560
  tokens: parseOriginalTokens(result.tokens, null, oidcConfiguration.token_renew_mode),
514
561
  status: result.status,
562
+ resourceContexts: result.resourceContexts,
515
563
  };
516
564
  };
517
565
 
@@ -541,7 +589,7 @@ export const initWorkerAsync = async (
541
589
  };
542
590
 
543
591
  const setNonceAsync = nonce => {
544
- sessionStorage[`oidc.nonce.${configurationName}`] = nonce.nonce;
592
+ if (resource === undefined) sessionStorage[`oidc.nonce.${configurationName}`] = nonce.nonce;
545
593
  return sendMessageAsync(registration)({
546
594
  type: 'setNonce',
547
595
  data: { nonce },
@@ -558,6 +606,7 @@ export const initWorkerAsync = async (
558
606
 
559
607
  // @ts-ignore
560
608
  let nonce = result.nonce;
609
+ if (resource !== undefined) return { nonce };
561
610
  if (!nonce) {
562
611
  nonce = sessionStorage[`oidc.nonce.${configurationName}`];
563
612
  console.warn('nonce not found in service worker, using sessionStorage');
@@ -656,6 +705,7 @@ export const initWorkerAsync = async (
656
705
 
657
706
  // @ts-ignore
658
707
  let state = result.state;
708
+ if (resource !== undefined) return state;
659
709
  if (!state) {
660
710
  state = sessionStorage[`oidc.state.${configurationName}`];
661
711
  console.warn('state not found in service worker, using sessionStorage');
@@ -668,7 +718,7 @@ export const initWorkerAsync = async (
668
718
  };
669
719
 
670
720
  const setStateAsync = async (state: string) => {
671
- sessionStorage[`oidc.state.${configurationName}`] = state;
721
+ if (resource === undefined) sessionStorage[`oidc.state.${configurationName}`] = state;
672
722
  return sendMessageAsync(registration)({
673
723
  type: 'setState',
674
724
  data: { state },
@@ -685,6 +735,7 @@ export const initWorkerAsync = async (
685
735
 
686
736
  // @ts-ignore
687
737
  let codeVerifier = result.codeVerifier;
738
+ if (resource !== undefined) return codeVerifier;
688
739
  if (!codeVerifier) {
689
740
  codeVerifier = sessionStorage[`oidc.code_verifier.${configurationName}`];
690
741
  console.warn('codeVerifier not found in service worker, using sessionStorage');
@@ -697,7 +748,8 @@ export const initWorkerAsync = async (
697
748
  };
698
749
 
699
750
  const setCodeVerifierAsync = async (codeVerifier: string) => {
700
- sessionStorage[`oidc.code_verifier.${configurationName}`] = codeVerifier;
751
+ if (resource === undefined)
752
+ sessionStorage[`oidc.code_verifier.${configurationName}`] = codeVerifier;
701
753
  return sendMessageAsync(registration)({
702
754
  type: 'setCodeVerifier',
703
755
  data: { codeVerifier },
package/src/jwt.spec.ts CHANGED
@@ -12,6 +12,23 @@ const decodePayload = (jwt: string) => {
12
12
  };
13
13
 
14
14
  describe('generateJwtDemonstratingProofOfPossessionAsync', () => {
15
+ it.each([
16
+ ['https://api.example.com/resource?limit=2#section', 'https://api.example.com/resource'],
17
+ ['/resource?limit=2#section', 'https://api.example.com/resource'],
18
+ ])('excludes query and fragment from the DPoP target %s', async (url, expected) => {
19
+ const environment = {
20
+ crypto: globalThis.crypto,
21
+ location: { href: 'https://api.example.com/' },
22
+ };
23
+ const jwk = await generateJwkAsync(environment)(
24
+ defaultDemonstratingProofOfPossessionConfiguration.generateKeyAlgorithm,
25
+ );
26
+ const jwt = await generateJwtDemonstratingProofOfPossessionAsync(environment)(
27
+ defaultDemonstratingProofOfPossessionConfiguration,
28
+ )(jwk, 'GET', url);
29
+ expect(decodePayload(jwt).htu).toBe(expected);
30
+ });
31
+
15
32
  it('uses a cryptographically secure UUID for the DPoP jti', async () => {
16
33
  const uuid = '123e4567-e89b-42d3-a456-426614174000';
17
34
  const randomUUID = vi.fn(() => uuid);
package/src/jwt.ts CHANGED
@@ -207,11 +207,14 @@ export const generateJwtDemonstratingProofOfPossessionAsync =
207
207
  (w: any) =>
208
208
  (demonstratingProofOfPossessionConfiguration: DemonstratingProofOfPossessionConfiguration) =>
209
209
  async (jwk, method = 'POST', url: string, extrasClaims = {}) => {
210
+ const target = new URL(url, w.location?.href);
211
+ target.search = '';
212
+ target.hash = '';
210
213
  const claims = {
211
214
  // https://www.rfc-editor.org/rfc/rfc9449.html#name-concept
212
215
  jti: btoa(w.crypto.randomUUID()),
213
216
  htm: method,
214
- htu: url,
217
+ htu: target.href,
215
218
  iat: Math.round(Date.now() / 1000),
216
219
  ...extrasClaims,
217
220
  };
@@ -0,0 +1,142 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
+
3
+ import { initSession } from './initSession';
4
+ import { Oidc } from './oidc';
5
+ import { OidcClient } from './oidcClient';
6
+ import { TokenAutomaticRenewMode } from './types';
7
+
8
+ const issuer = 'https://issuer.example.com';
9
+ const href = 'https://app.example.com/callback?code=code&state=state';
10
+ const idToken = (): string =>
11
+ `e30.${btoa(JSON.stringify({ iss: issuer, sub: 'alice', nonce: 'nonce', exp: Date.now() / 1000 + 3600, iat: Date.now() / 1000 }))}.signature`;
12
+ let storage: Storage;
13
+ let client: OidcClient;
14
+ let oidc: Oidc;
15
+ let postMessage: ReturnType<typeof vi.fn>;
16
+
17
+ beforeEach(() => {
18
+ vi.useFakeTimers();
19
+ storage = Object.create(null) as Storage;
20
+ const blockedStorage = new Proxy({} as Storage, {
21
+ get: () => {
22
+ throw new DOMException('Native session storage is blocked.', 'SecurityError');
23
+ },
24
+ ownKeys: () => {
25
+ throw new DOMException('Native session storage is blocked.', 'SecurityError');
26
+ },
27
+ });
28
+ postMessage = vi.fn();
29
+ vi.stubGlobal('sessionStorage', blockedStorage);
30
+ vi.stubGlobal('navigator', {});
31
+ vi.stubGlobal('window', {
32
+ sessionStorage: blockedStorage,
33
+ location: { href },
34
+ parent: { postMessage },
35
+ });
36
+ vi.stubGlobal(
37
+ 'fetch',
38
+ vi.fn(
39
+ async () =>
40
+ new Response(
41
+ JSON.stringify({
42
+ access_token: 'access',
43
+ refresh_token: 'refresh',
44
+ id_token: idToken(),
45
+ expires_in: 3600,
46
+ }),
47
+ ),
48
+ ),
49
+ );
50
+ oidc = new Oidc(
51
+ {
52
+ authority: issuer,
53
+ authority_configuration: {
54
+ issuer,
55
+ authorization_endpoint: `${issuer}/authorize`,
56
+ token_endpoint: `${issuer}/token`,
57
+ revocation_endpoint: `${issuer}/revoke`,
58
+ },
59
+ client_id: 'client',
60
+ scope: 'openid',
61
+ redirect_uri: 'https://app.example.com/callback',
62
+ silent_redirect_uri: 'https://app.example.com/silent-callback',
63
+ storage,
64
+ login_state_storage: storage,
65
+ token_automatic_renew_mode: TokenAutomaticRenewMode.AutomaticOnlyWhenFetchExecuted,
66
+ },
67
+ 'legacy',
68
+ () => fetch,
69
+ {
70
+ getCurrentHref: () => href,
71
+ getOrigin: () => 'https://app.example.com',
72
+ getPath: () => '/callback',
73
+ open: vi.fn(),
74
+ reload: vi.fn(),
75
+ },
76
+ );
77
+ client = new OidcClient(oidc);
78
+ const session = initSession('legacy', storage, storage);
79
+ session.setStateAsync('state');
80
+ session.setNonceAsync({ nonce: 'nonce' });
81
+ session.setCodeVerifierAsync('verifier');
82
+ session.setLoginParams({ callbackPath: '/after', extras: null, scope: 'openid' });
83
+ });
84
+
85
+ afterEach(() => {
86
+ vi.clearAllTimers();
87
+ vi.useRealTimers();
88
+ vi.restoreAllMocks();
89
+ vi.unstubAllGlobals();
90
+ });
91
+
92
+ describe('legacy clients with custom storage and no resource registry', () => {
93
+ it('completes interactive callbacks without accessing native sessionStorage', async () => {
94
+ await expect(client.loginCallbackAsync()).resolves.toEqual({ callbackPath: '/after' });
95
+ expect(client.tokens.accessToken).toBe('access');
96
+ expect(JSON.parse(storage['oidc.legacy']).tokens.accessToken).toBe('access');
97
+ });
98
+
99
+ it('posts successful silent callbacks without accessing native sessionStorage', async () => {
100
+ await client.silentLoginCallbackAsync();
101
+ expect(postMessage).toHaveBeenCalledWith(
102
+ expect.stringContaining('legacy_oidc_tokens:'),
103
+ 'https://app.example.com',
104
+ );
105
+ });
106
+
107
+ it('clears the local session without accessing native sessionStorage', async () => {
108
+ oidc.tokens = { accessToken: 'access' } as Oidc['tokens'];
109
+ initSession('legacy', storage).setTokens(oidc.tokens);
110
+ await expect(client.clearSessionAsync()).resolves.toBeUndefined();
111
+ expect(client.tokens).toBeNull();
112
+ expect(JSON.parse(storage['oidc.legacy']).tokens).toBeNull();
113
+ });
114
+ });
115
+
116
+ describe('legacy explicit silent-login results', () => {
117
+ it('resolves with an error value on timeout rather than rejecting', async () => {
118
+ oidc.configuration.silent_login_timeout = 25;
119
+ vi.stubGlobal('document', {
120
+ createElement: () => ({ setAttribute: vi.fn(), style: {}, remove: vi.fn() }),
121
+ body: { appendChild: vi.fn() },
122
+ });
123
+ vi.stubGlobal('window', {
124
+ ...window,
125
+ addEventListener: vi.fn(),
126
+ removeEventListener: vi.fn(),
127
+ });
128
+ const result = client.loginAsync(undefined, undefined, false, undefined, true);
129
+ const assertion = expect(result).resolves.toBeInstanceOf(Error);
130
+ await vi.advanceTimersByTimeAsync(25);
131
+ await assertion;
132
+ });
133
+
134
+ it('resolves without starting authorization when silent callbacks are disabled', async () => {
135
+ oidc.configuration.silent_redirect_uri = undefined;
136
+ oidc.configuration.silent_login_uri = undefined;
137
+ await expect(
138
+ client.loginAsync(undefined, undefined, false, undefined, true),
139
+ ).resolves.toBeUndefined();
140
+ expect(fetch).not.toHaveBeenCalled();
141
+ });
142
+ });