@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
@@ -13,6 +13,7 @@ import {
13
13
  import { OidcStateError, OidcStateErrorCode } from './oidcStateError.js';
14
14
  import { computeTimeLeft, isTokensOidcValid, setTokens, Tokens } from './parseTokens.js';
15
15
  import { performTokenRequestAsync } from './requests';
16
+ import { applyResourceParameters } from './resourceParameters';
16
17
  import { _silentLoginAsync } from './silentLogin';
17
18
  import timer from './timer.js';
18
19
  import { OidcConfiguration, StringMap, TokenAutomaticRenewMode } from './types.js';
@@ -54,15 +55,20 @@ async function syncTokens(
54
55
  const updateTokens = tokens => {
55
56
  oidc.tokens = tokens;
56
57
  };
57
- const result = await synchroniseTokensAsync(oidc)(
58
- updateTokens,
59
- 0,
60
- 0,
61
- forceRefresh,
62
- extras,
63
- scope,
64
- );
58
+ oidc.publishEvent(Oidc.eventNames.syncTokensAsync_begin, {});
59
+ let result;
60
+ try {
61
+ result = await synchroniseTokensAsync(oidc)(updateTokens, 0, 0, forceRefresh, extras, scope);
62
+ } catch (exception: any) {
63
+ oidc.publishEvent(Oidc.eventNames.syncTokensAsync_error, {
64
+ message: 'sync tokens error',
65
+ error: isOidcError(exception) ? exception : undefined,
66
+ exception,
67
+ });
68
+ throw exception;
69
+ }
65
70
  const { tokens, status } = result;
71
+ oidc.publishEvent(Oidc.eventNames.syncTokensAsync_end, { status });
66
72
 
67
73
  const serviceWorker = await initWorkerAsync(oidc.configuration, oidc.configurationName);
68
74
  if (!serviceWorker) {
@@ -92,7 +98,14 @@ export async function renewTokensAndStartTimerResultAsync(
92
98
 
93
99
  let result: RenewTokensResult;
94
100
  const serviceWorker = await initWorkerAsync(oidc.configuration, oidc.configurationName);
95
- if ((configuration?.storage === window?.sessionStorage && !serviceWorker) || !navigator.locks) {
101
+ if (configuration.resources?.length && oidc.resourceTokens) {
102
+ result = await oidc.resourceTokens.withRefreshLockAsync(() =>
103
+ syncTokens(oidc, forceRefresh, extras, scope),
104
+ );
105
+ } else if (
106
+ (configuration?.storage === window?.sessionStorage && !serviceWorker) ||
107
+ !navigator.locks
108
+ ) {
96
109
  result = await syncTokens(oidc, forceRefresh, extras, scope);
97
110
  } else {
98
111
  let lockResult: any = 'retry';
@@ -489,12 +502,15 @@ const synchroniseTokensAsync =
489
502
  }
490
503
  }
491
504
  const localFunctionAsync = async () => {
492
- const details = {
493
- client_id: clientId,
494
- redirect_uri: redirectUri,
495
- grant_type: 'refresh_token',
496
- refresh_token: tokens.refreshToken,
497
- };
505
+ const details = applyResourceParameters(
506
+ {
507
+ client_id: clientId,
508
+ redirect_uri: redirectUri,
509
+ grant_type: 'refresh_token',
510
+ refresh_token: tokens.refreshToken,
511
+ },
512
+ configuration,
513
+ );
498
514
  const oidcServerConfiguration = await oidc.initAsync(
499
515
  authority,
500
516
  configuration.authority_configuration,
@@ -512,7 +528,7 @@ const synchroniseTokensAsync =
512
528
  let tokenResponse = await performTokenRequestAsync(oidc.getFetch())(
513
529
  url,
514
530
  details,
515
- finalExtras,
531
+ applyResourceParameters(finalExtras, configuration),
516
532
  tokens,
517
533
  headersExtras,
518
534
  configuration.token_renew_mode,
@@ -114,3 +114,114 @@ describe('strict token renewal', () => {
114
114
  expect(oidc.tokens).toBeNull();
115
115
  });
116
116
  });
117
+
118
+ describe('syncTokensAsync events', () => {
119
+ const createOidc = (expiresAt: number) => {
120
+ const oidc = Object.create(Oidc.prototype) as Oidc;
121
+ oidc.configurationName = 'default';
122
+ oidc.configuration = {
123
+ authority: 'https://issuer.example.com',
124
+ client_id: 'client',
125
+ redirect_uri: 'https://client.example.com/callback',
126
+ refresh_time_before_tokens_expiration_in_second: 0,
127
+ scope: 'openid',
128
+ storage: {},
129
+ token_renew_mode: 'access_token_or_id_token_invalid',
130
+ } as never;
131
+ oidc.destroyAsync = vi.fn();
132
+ oidc.getFetch = vi.fn();
133
+ oidc.initAsync = vi.fn().mockResolvedValue({
134
+ tokenEndpoint: 'https://issuer.example.com/token',
135
+ });
136
+ oidc.publishEvent = vi.fn();
137
+ oidc.tokens = {
138
+ accessToken: 'access-token',
139
+ expiresAt,
140
+ issuedAt: 1,
141
+ refreshToken: 'refresh-token',
142
+ } as Tokens;
143
+ return oidc;
144
+ };
145
+
146
+ const mockSessionWithTokens = (expiresAt: number) => {
147
+ vi.spyOn(initSessionModule, 'initSession').mockReturnValue({
148
+ getNonceAsync: vi.fn().mockResolvedValue({ nonce: null }),
149
+ initAsync: vi.fn().mockResolvedValue({
150
+ status: null,
151
+ tokens: {
152
+ accessToken: 'access-token',
153
+ expiresAt,
154
+ issuedAt: 1,
155
+ refreshToken: 'refresh-token',
156
+ },
157
+ }),
158
+ setTokens: vi.fn(),
159
+ } as never);
160
+ };
161
+
162
+ const publishedEventNames = (oidc: Oidc) =>
163
+ (oidc.publishEvent as any).mock.calls.map(([name]) => name);
164
+
165
+ it('publishes syncTokensAsync_begin then syncTokensAsync_end once tokens are synchronized', async () => {
166
+ const expiresAt = Date.now() / 1000 + 3600;
167
+ vi.stubGlobal('navigator', { locks: undefined, onLine: true });
168
+ vi.stubGlobal('document', { hidden: false });
169
+ vi.stubGlobal('window', { sessionStorage: {} });
170
+ vi.spyOn(initWorkerModule, 'initWorkerAsync').mockResolvedValue(null);
171
+ mockSessionWithTokens(expiresAt);
172
+ const oidc = createOidc(expiresAt);
173
+
174
+ const result = await renewTokensAndStartTimerResultAsync(oidc);
175
+
176
+ expect(result.status).toBe('LOGGED_IN');
177
+ expect(publishedEventNames(oidc)).toEqual(['syncTokensAsync_begin', 'syncTokensAsync_end']);
178
+ expect(oidc.publishEvent).toHaveBeenNthCalledWith(2, 'syncTokensAsync_end', {
179
+ status: 'LOGGED_IN',
180
+ });
181
+ });
182
+
183
+ it('publishes a single begin/end pair when the lock is not available on the first attempt', async () => {
184
+ const expiresAt = Date.now() / 1000 + 3600;
185
+ let lockRequestCount = 0;
186
+ vi.stubGlobal('navigator', {
187
+ onLine: true,
188
+ locks: {
189
+ request: vi.fn(
190
+ (_resource: string, _options: unknown, callback: (lock: unknown) => unknown) =>
191
+ Promise.resolve(++lockRequestCount === 1 ? callback(null) : callback({ name: 'lock' })),
192
+ ),
193
+ },
194
+ });
195
+ vi.stubGlobal('document', { hidden: false });
196
+ vi.stubGlobal('window', { sessionStorage: {} });
197
+ vi.spyOn(initWorkerModule, 'initWorkerAsync').mockResolvedValue(null);
198
+ mockSessionWithTokens(expiresAt);
199
+ const oidc = createOidc(expiresAt);
200
+
201
+ const result = await renewTokensAndStartTimerResultAsync(oidc);
202
+
203
+ expect(result.status).toBe('LOGGED_IN');
204
+ expect(publishedEventNames(oidc)).toEqual([
205
+ 'syncTokensAsync_lock_not_available',
206
+ 'syncTokensAsync_begin',
207
+ 'syncTokensAsync_end',
208
+ ]);
209
+ });
210
+
211
+ it('publishes syncTokensAsync_error and rethrows when the synchronization throws', async () => {
212
+ vi.stubGlobal('navigator', { locks: undefined, onLine: false });
213
+ vi.stubGlobal('document', undefined);
214
+ vi.stubGlobal('window', { sessionStorage: {} });
215
+ vi.spyOn(initWorkerModule, 'initWorkerAsync').mockResolvedValue(null);
216
+ const oidc = createOidc(Date.now() / 1000 + 3600);
217
+
218
+ await expect(renewTokensAndStartTimerResultAsync(oidc)).rejects.toThrow();
219
+
220
+ expect(publishedEventNames(oidc)).toEqual(['syncTokensAsync_begin', 'syncTokensAsync_error']);
221
+ expect(oidc.publishEvent).toHaveBeenNthCalledWith(
222
+ 2,
223
+ 'syncTokensAsync_error',
224
+ expect.objectContaining({ message: 'sync tokens error' }),
225
+ );
226
+ });
227
+ });
package/src/requests.ts CHANGED
@@ -7,7 +7,7 @@ import {
7
7
  PushedAuthorizationRequestError,
8
8
  PushedAuthorizationRequestErrorCode,
9
9
  } from './pushedAuthorizationRequestError.js';
10
- import { Fetch, StringMap } from './types.js';
10
+ import { Fetch, OAuthParameters, StringMap } from './types.js';
11
11
 
12
12
  const oneHourSecond = 60 * 60;
13
13
  export const fetchFromIssuer =
@@ -69,10 +69,14 @@ export const TOKEN_TYPE = {
69
69
  access_token: 'access_token',
70
70
  };
71
71
 
72
- const encodeFormBody = (details: StringMap): string => {
72
+ const encodeFormBody = (details: OAuthParameters): string => {
73
73
  const formBody: string[] = [];
74
74
  for (const property in details) {
75
- formBody.push(`${encodeURIComponent(property)}=${encodeURIComponent(details[property])}`);
75
+ const value = details[property];
76
+ const values = Array.isArray(value) ? value : [String(value)];
77
+ for (const item of values) {
78
+ formBody.push(`${encodeURIComponent(property)}=${encodeURIComponent(item)}`);
79
+ }
76
80
  }
77
81
  return formBody.join('&');
78
82
  };
@@ -153,7 +157,7 @@ export const performPushedAuthorizationRequestAsync =
153
157
  (fetch: Fetch) =>
154
158
  async (
155
159
  url: string,
156
- details: StringMap,
160
+ details: OAuthParameters,
157
161
  timeoutMs = 10000,
158
162
  ): Promise<PushedAuthorizationRequestResponse> => {
159
163
  if (details.request_uri !== undefined) {
@@ -291,7 +295,7 @@ export const performAuthorizationRequestAsync =
291
295
  (storage: any, oidcLocation: ILOidcLocation) =>
292
296
  async (
293
297
  url,
294
- extras: StringMap,
298
+ extras: OAuthParameters,
295
299
  pushedAuthorizationRequest?: {
296
300
  endpoint: string;
297
301
  fetch: Fetch;
@@ -311,7 +315,7 @@ export const performAuthorizationRequestAsync =
311
315
  pushedAuthorizationRequest.fetch,
312
316
  )(pushedAuthorizationRequest.endpoint, extras, pushedAuthorizationRequest.timeoutMs);
313
317
  oidcLocation.open(
314
- `${url}?client_id=${encodeURIComponent(extras.client_id)}&request_uri=${encodeURIComponent(
318
+ `${url}?client_id=${encodeURIComponent(String(extras.client_id))}&request_uri=${encodeURIComponent(
315
319
  response.request_uri,
316
320
  )}`,
317
321
  );
@@ -321,12 +325,10 @@ export const performAuthorizationRequestAsync =
321
325
  let queryString = '';
322
326
  if (extras) {
323
327
  for (const [key, value] of Object.entries(extras)) {
324
- if (queryString === '') {
325
- queryString += '?';
326
- } else {
327
- queryString += '&';
328
+ for (const item of Array.isArray(value) ? value : [String(value)]) {
329
+ queryString += queryString === '' ? '?' : '&';
330
+ queryString += `${key}=${encodeURIComponent(item)}`;
328
331
  }
329
- queryString += `${key}=${encodeURIComponent(value)}`;
330
332
  }
331
333
  }
332
334
  oidcLocation.open(`${url}${queryString}`);
@@ -0,0 +1,85 @@
1
+ import { OidcError, OidcErrorCode } from './oidcError';
2
+ import {
3
+ getResourceConfiguration,
4
+ getResourceContextName,
5
+ validateResourceIdentifier,
6
+ } from './protocol';
7
+ import { getParseQueryStringFromLocation } from './route-utils';
8
+ import type { OAuthParameters, OidcConfiguration } from './types';
9
+
10
+ export const RESOURCE_LOGIN_PARAMETER = '_oidc_resource';
11
+ const transactionPrefix = 'oidc.resource_transaction.';
12
+
13
+ export const resourceContextName = (name: string, resource?: string): string =>
14
+ resource === undefined ? name : getResourceContextName(name, resource);
15
+
16
+ export const applyResourceParameters = (
17
+ parameters: OAuthParameters,
18
+ configuration: OidcConfiguration,
19
+ resource?: string,
20
+ ): OAuthParameters => {
21
+ const selected = resource ?? configuration.resource;
22
+ if (selected === undefined) return parameters;
23
+ const resources = typeof selected === 'string' ? [selected] : selected;
24
+ if (resources.length === 0) {
25
+ throw new OidcError(OidcErrorCode.INVALID_RESOURCE, 'At least one resource is required.', {
26
+ phase: 'login',
27
+ retryable: false,
28
+ });
29
+ }
30
+ for (const value of resources) {
31
+ validateResourceIdentifier(value);
32
+ if (configuration.resources) getResourceConfiguration(configuration.resources, value);
33
+ }
34
+ const supplied = parameters.resource;
35
+ if (
36
+ supplied !== undefined &&
37
+ JSON.stringify(typeof supplied === 'string' ? [supplied] : supplied) !==
38
+ JSON.stringify(resources)
39
+ ) {
40
+ throw new OidcError(
41
+ OidcErrorCode.INVALID_RESOURCE,
42
+ 'Resource extras conflict with the selected resource.',
43
+ {
44
+ phase: 'login',
45
+ retryable: false,
46
+ },
47
+ );
48
+ }
49
+ return { ...parameters, resource: selected };
50
+ };
51
+
52
+ export const rememberResourceTransaction = (
53
+ configurationName: string,
54
+ state: string,
55
+ resource: string,
56
+ ): void => {
57
+ sessionStorage.setItem(`${transactionPrefix}${configurationName}.${state}`, resource);
58
+ };
59
+
60
+ export const getCallbackResource = (
61
+ configurationName: string,
62
+ href: string,
63
+ ): string | undefined => {
64
+ const { state } = getParseQueryStringFromLocation(href);
65
+ return state
66
+ ? (sessionStorage.getItem(`${transactionPrefix}${configurationName}.${state}`) ?? undefined)
67
+ : undefined;
68
+ };
69
+
70
+ export const clearResourceTransaction = (configurationName: string, href: string): void => {
71
+ const { state } = getParseQueryStringFromLocation(href);
72
+ if (state) sessionStorage.removeItem(`${transactionPrefix}${configurationName}.${state}`);
73
+ };
74
+
75
+ export const cancelResourceTransactions = (configurationName: string, resource?: string): void => {
76
+ const prefix = `${transactionPrefix}${configurationName}.`;
77
+ for (const key of Object.keys(sessionStorage)) {
78
+ if (
79
+ key.startsWith(prefix) &&
80
+ (resource === undefined || sessionStorage.getItem(key) === resource)
81
+ ) {
82
+ sessionStorage.removeItem(key);
83
+ }
84
+ }
85
+ };