@axa-fr/oidc-client 7.30.1 → 7.30.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.
@@ -0,0 +1,136 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
+
3
+ import { initWorkerAsync, registrationCache } from './initWorker';
4
+ import type { OidcConfiguration } from './types';
5
+
6
+ const configuration = {
7
+ service_worker_relative_url: '/OidcServiceWorker.js',
8
+ service_worker_activate: () => true,
9
+ } as OidcConfiguration;
10
+
11
+ const createRegistration = () => ({
12
+ update: vi.fn().mockResolvedValue(undefined),
13
+ addEventListener: vi.fn(),
14
+ installing: null as ServiceWorker | null,
15
+ waiting: null,
16
+ });
17
+
18
+ describe('service worker update checks', () => {
19
+ let registration: ReturnType<typeof createRegistration>;
20
+ let register: ReturnType<typeof vi.fn>;
21
+
22
+ beforeEach(() => {
23
+ registrationCache.clear();
24
+ registration = createRegistration();
25
+ register = vi.fn().mockResolvedValue(registration);
26
+ vi.stubGlobal('window', {});
27
+ vi.stubGlobal('navigator', {
28
+ serviceWorker: {
29
+ register,
30
+ controller: {},
31
+ ready: Promise.resolve(registration),
32
+ addEventListener: vi.fn(),
33
+ },
34
+ });
35
+ vi.spyOn(Date, 'now').mockReturnValue(0);
36
+ });
37
+
38
+ afterEach(() => {
39
+ registrationCache.clear();
40
+ vi.restoreAllMocks();
41
+ vi.unstubAllGlobals();
42
+ });
43
+
44
+ it('bounds checks and listeners across repeated token synchronization and configurations', async () => {
45
+ for (let tick = 0; tick < 30; tick++) {
46
+ await initWorkerAsync(configuration, tick % 2 ? 'default' : 'another');
47
+ vi.mocked(Date.now).mockReturnValue((tick + 1) * 1000);
48
+ }
49
+ expect(register).toHaveBeenCalledOnce();
50
+ expect(registration.update).toHaveBeenCalledOnce();
51
+ expect(registration.addEventListener).toHaveBeenCalledOnce();
52
+ expect(registration.addEventListener).toHaveBeenCalledWith('updatefound', expect.any(Function));
53
+ });
54
+
55
+ it('bounds concurrent initialization while an update is pending', async () => {
56
+ registration.update.mockReturnValue(new Promise(() => {}));
57
+ const workers = await Promise.all(
58
+ Array.from({ length: 10 }, () => initWorkerAsync(configuration, 'default')),
59
+ );
60
+ expect(workers.every(Boolean)).toBe(true);
61
+ expect(registration.update).toHaveBeenCalledOnce();
62
+ });
63
+
64
+ it('checks again after an hour', async () => {
65
+ await initWorkerAsync(configuration, 'default');
66
+ vi.mocked(Date.now).mockReturnValue(60 * 60 * 1000 - 1);
67
+ await initWorkerAsync(configuration, 'default');
68
+ expect(registration.update).toHaveBeenCalledOnce();
69
+ vi.mocked(Date.now).mockReturnValue(60 * 60 * 1000);
70
+ await initWorkerAsync(configuration, 'default');
71
+ expect(registration.update).toHaveBeenCalledTimes(2);
72
+ });
73
+
74
+ it('bounds failed checks and retries after the interval without blocking initialization', async () => {
75
+ vi.spyOn(console, 'error').mockImplementation(() => {});
76
+ registration.update.mockRejectedValue(new Error('offline'));
77
+ await expect(initWorkerAsync(configuration, 'default')).resolves.toBeTruthy();
78
+ await initWorkerAsync(configuration, 'default');
79
+ expect(registration.update).toHaveBeenCalledOnce();
80
+ vi.mocked(Date.now).mockReturnValue(60 * 60 * 1000);
81
+ await initWorkerAsync(configuration, 'default');
82
+ expect(registration.update).toHaveBeenCalledTimes(2);
83
+ });
84
+
85
+ it('checks and observes a replacement registration immediately', async () => {
86
+ await initWorkerAsync(configuration, 'default');
87
+ const replacement = createRegistration();
88
+ registrationCache.clear();
89
+ register.mockResolvedValue(replacement);
90
+ await initWorkerAsync(configuration, 'default');
91
+ expect(replacement.update).toHaveBeenCalledOnce();
92
+ expect(replacement.addEventListener).toHaveBeenCalledOnce();
93
+ });
94
+
95
+ it('still claims a callback page without a controller', async () => {
96
+ const values = new Map<string, string>();
97
+ vi.stubGlobal('sessionStorage', {
98
+ getItem: (key: string) => values.get(key) ?? null,
99
+ setItem: (key: string, value: string) => values.set(key, value),
100
+ });
101
+ const postMessage = vi.fn((_data, ports) => {
102
+ Object.defineProperty(navigator.serviceWorker, 'controller', {
103
+ value: {},
104
+ configurable: true,
105
+ });
106
+ ports[0].postMessage({});
107
+ });
108
+ Object.assign(registration, { active: { postMessage } });
109
+ Object.defineProperty(navigator.serviceWorker, 'controller', {
110
+ value: null,
111
+ configurable: true,
112
+ });
113
+
114
+ await expect(initWorkerAsync(configuration, 'default')).resolves.toBeTruthy();
115
+
116
+ expect(postMessage).toHaveBeenCalledWith(
117
+ expect.objectContaining({ type: 'claim' }),
118
+ expect.any(Array),
119
+ );
120
+ expect(registration.update).toHaveBeenCalledOnce();
121
+ });
122
+
123
+ it('observes installing workers once and still discovers replacements during the interval', async () => {
124
+ const installing = { addEventListener: vi.fn() };
125
+ registration.installing = installing as unknown as ServiceWorker;
126
+ await initWorkerAsync(configuration, 'default');
127
+ await initWorkerAsync(configuration, 'default');
128
+ expect(installing.addEventListener).toHaveBeenCalledOnce();
129
+ const replacement = { addEventListener: vi.fn() };
130
+ registration.installing = replacement as unknown as ServiceWorker;
131
+ const onUpdateFound = registration.addEventListener.mock.calls[0][1];
132
+ onUpdateFound();
133
+ expect(replacement.addEventListener).toHaveBeenCalledWith('statechange', expect.any(Function));
134
+ expect(registration.update).toHaveBeenCalledOnce();
135
+ });
136
+ });
@@ -156,6 +156,104 @@ describe.each(['service worker', 'browser storage'])('session restoration with %
156
156
  expect(clearWorker).not.toHaveBeenCalled();
157
157
  });
158
158
 
159
+ it('does not renew unexpired stored tokens during restoration', async () => {
160
+ const renew = vi.spyOn(renewal, 'renewTokensAndStartTimerAsync');
161
+ await expect(restore()).resolves.toBe(true);
162
+ expect(renew).not.toHaveBeenCalled();
163
+ });
164
+
165
+ it.each([false, true])(
166
+ 'awaits expired-token renewal before readiness (saved metadata: %s)',
167
+ async saved => {
168
+ vi.setSystemTime((tokens.expiresAt + 1) * 1000);
169
+ if (saved) loginStateStorage['oidc.login.default'] = JSON.stringify(loginParams);
170
+ const renewed = {
171
+ ...tokens,
172
+ accessToken: 'renewed-access-token',
173
+ expiresAt: tokens.expiresAt + 3600,
174
+ };
175
+ let finishRenewal: () => void;
176
+ const renew = vi.spyOn(renewal, 'renewTokensAndStartTimerAsync').mockImplementation(
177
+ () =>
178
+ new Promise(resolve => {
179
+ finishRenewal = () => {
180
+ oidc.tokens = renewed;
181
+ resolve(renewed);
182
+ };
183
+ }),
184
+ );
185
+
186
+ const restoring = restore();
187
+ await vi.waitFor(() => expect(renew).toHaveBeenCalledOnce());
188
+ expect(renew).toHaveBeenCalledWith(
189
+ oidc,
190
+ true,
191
+ saved ? loginParams.extras : undefined,
192
+ saved ? loginParams.scope : undefined,
193
+ );
194
+ expect(renewal.autoRenewTokens).not.toHaveBeenCalled();
195
+ expect(getSessionState).not.toHaveBeenCalled();
196
+ expect(oidc.userInfoAsync).not.toHaveBeenCalled();
197
+ expect(oidc.publishEvent).not.toHaveBeenCalledWith(
198
+ eventNames.tryKeepExistingSessionAsync_end,
199
+ expect.objectContaining({ success: true }),
200
+ );
201
+
202
+ finishRenewal();
203
+ await expect(restoring).resolves.toBe(true);
204
+ expect(oidc.tokens).toEqual(renewed);
205
+ expect(renewal.autoRenewTokens).toHaveBeenCalledWith(
206
+ oidc,
207
+ renewed.expiresAt,
208
+ saved ? loginParams.extras : undefined,
209
+ saved ? loginParams.scope : undefined,
210
+ );
211
+ expect(oidc.userInfoAsync).toHaveBeenCalledOnce();
212
+ expect(vi.getTimerCount()).toBe(1);
213
+ },
214
+ );
215
+
216
+ it.each([null, { ...tokens, expiresAt: 1 }])(
217
+ 'returns false when renewal produces no valid tokens: %j',
218
+ async result => {
219
+ vi.setSystemTime((tokens.expiresAt + 1) * 1000);
220
+ vi.spyOn(renewal, 'renewTokensAndStartTimerAsync').mockResolvedValue(result);
221
+
222
+ await expect(restore()).resolves.toBe(false);
223
+
224
+ expect(oidc.tokens).toBeNull();
225
+ expect(oidc.userInfo).toBeNull();
226
+ expect(renewal.autoRenewTokens).not.toHaveBeenCalled();
227
+ expect(getSessionState).not.toHaveBeenCalled();
228
+ expect(oidc.userInfoAsync).not.toHaveBeenCalled();
229
+ expect(vi.getTimerCount()).toBe(0);
230
+ expect(oidc.publishEvent).toHaveBeenCalledWith(
231
+ eventNames.tryKeepExistingSessionAsync_end,
232
+ expect.objectContaining({ success: false }),
233
+ );
234
+ },
235
+ );
236
+
237
+ it('cleans up a rejected initial renewal and allows restoration to be retried', async () => {
238
+ vi.setSystemTime((tokens.expiresAt + 1) * 1000);
239
+ const renew = vi
240
+ .spyOn(renewal, 'renewTokensAndStartTimerAsync')
241
+ .mockRejectedValueOnce(new Error('renewal failed'));
242
+ await expect(restore()).resolves.toBe(false);
243
+ expect(oidc.tokens).toBeNull();
244
+ expect(oidc.timeoutId).toBeNull();
245
+ expect(oidc.userInfoAsync).not.toHaveBeenCalled();
246
+ expect(vi.getTimerCount()).toBe(0);
247
+
248
+ renew.mockImplementationOnce(async () => {
249
+ const renewed = { ...tokens, expiresAt: tokens.expiresAt + 3600 };
250
+ oidc.tokens = renewed;
251
+ return renewed;
252
+ });
253
+ await expect(restore()).resolves.toBe(true);
254
+ expect(renew).toHaveBeenCalledTimes(2);
255
+ });
256
+
159
257
  it.each(['session state', 'session monitoring', 'user info'])(
160
258
  'clears page state on a %s failure and allows a successful retry',
161
259
  async stage => {
@@ -2,10 +2,30 @@ import { eventNames } from './events';
2
2
  import { initSession } from './initSession';
3
3
  import { initWorkerAsync } from './initWorker';
4
4
  import Oidc from './oidc';
5
- import { setTokens } from './parseTokens';
6
- import { autoRenewTokens } from './renewTokens';
5
+ import { isTokensValid, setTokens } from './parseTokens';
6
+ import { autoRenewTokens, renewTokensAndStartTimerAsync } from './renewTokens';
7
7
  import timer from './timer';
8
8
 
9
+ const renewExpiredSessionAsync = async (oidc: Oidc, loginParams) => {
10
+ if (isTokensValid(oidc.tokens)) return true;
11
+
12
+ const tokens = await renewTokensAndStartTimerAsync(
13
+ oidc,
14
+ true,
15
+ loginParams?.extras,
16
+ loginParams?.scope,
17
+ );
18
+ if (isTokensValid(tokens)) return true;
19
+
20
+ oidc.tokens = null;
21
+ oidc.userInfo = null;
22
+ oidc.publishEvent(eventNames.tryKeepExistingSessionAsync_end, {
23
+ success: false,
24
+ message: 'stored tokens could not be renewed',
25
+ });
26
+ return false;
27
+ };
28
+
9
29
  export const tryKeepSessionAsync = async (oidc: Oidc) => {
10
30
  let serviceWorker;
11
31
  if (oidc.tokens != null) {
@@ -30,6 +50,7 @@ export const tryKeepSessionAsync = async (oidc: Oidc) => {
30
50
  // @ts-ignore
31
51
  oidc.tokens = tokens;
32
52
  const getLoginParams = serviceWorker.getLoginParams(oidc.configurationName);
53
+ if (!(await renewExpiredSessionAsync(oidc, getLoginParams))) return false;
33
54
  // @ts-ignore
34
55
  oidc.timeoutId = autoRenewTokens(
35
56
  oidc,
@@ -73,6 +94,7 @@ export const tryKeepSessionAsync = async (oidc: Oidc) => {
73
94
  // @ts-ignore
74
95
  oidc.tokens = setTokens(tokens, null, configuration.token_renew_mode);
75
96
  const getLoginParams = session.getLoginParams();
97
+ if (!(await renewExpiredSessionAsync(oidc, getLoginParams))) return false;
76
98
  // @ts-ignore
77
99
  oidc.timeoutId = autoRenewTokens(
78
100
  oidc,
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export default '7.30.1';
1
+ export default '7.30.3';