@axa-fr/oidc-client 7.29.8 → 7.30.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.
Files changed (76) hide show
  1. package/README.md +187 -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 +1339 -871
  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/keepSession.d.ts.map +1 -1
  16. package/dist/keepSession.spec.d.ts +2 -0
  17. package/dist/keepSession.spec.d.ts.map +1 -0
  18. package/dist/legacyCompatibility.spec.d.ts +2 -0
  19. package/dist/legacyCompatibility.spec.d.ts.map +1 -0
  20. package/dist/login.d.ts +2 -1
  21. package/dist/login.d.ts.map +1 -1
  22. package/dist/logout.d.ts.map +1 -1
  23. package/dist/node_modules/@axa-fr/oidc-client-service-worker/dist/OidcServiceWorker.js +1049 -0
  24. package/dist/node_modules/@axa-fr/oidc-client-service-worker/dist/OidcTrustedDomains.js +31 -0
  25. package/dist/oidc.d.ts +6 -1
  26. package/dist/oidc.d.ts.map +1 -1
  27. package/dist/oidcClient.d.ts +13 -2
  28. package/dist/oidcClient.d.ts.map +1 -1
  29. package/dist/oidcError.d.ts +5 -0
  30. package/dist/oidcError.d.ts.map +1 -1
  31. package/dist/parseTokens.d.ts +10 -0
  32. package/dist/parseTokens.d.ts.map +1 -1
  33. package/dist/protocol.d.ts +7 -1
  34. package/dist/protocol.d.ts.map +1 -1
  35. package/dist/renewTokens.d.ts +0 -6
  36. package/dist/renewTokens.d.ts.map +1 -1
  37. package/dist/requests.d.ts +3 -3
  38. package/dist/requests.d.ts.map +1 -1
  39. package/dist/resourceParameters.d.ts +9 -0
  40. package/dist/resourceParameters.d.ts.map +1 -0
  41. package/dist/resourceTokens.d.ts +34 -0
  42. package/dist/resourceTokens.d.ts.map +1 -0
  43. package/dist/resourceTokens.spec.d.ts +2 -0
  44. package/dist/resourceTokens.spec.d.ts.map +1 -0
  45. package/dist/silentLogin.d.ts +2 -1
  46. package/dist/silentLogin.d.ts.map +1 -1
  47. package/dist/types.d.ts +28 -0
  48. package/dist/types.d.ts.map +1 -1
  49. package/dist/version.d.ts +1 -1
  50. package/package.json +3 -3
  51. package/src/events.ts +3 -0
  52. package/src/fetch.ts +115 -15
  53. package/src/index.ts +4 -0
  54. package/src/initSession.ts +9 -0
  55. package/src/initWorker.ts +65 -13
  56. package/src/jwt.spec.ts +17 -0
  57. package/src/jwt.ts +4 -1
  58. package/src/keepSession.spec.ts +254 -0
  59. package/src/keepSession.ts +10 -4
  60. package/src/legacyCompatibility.spec.ts +142 -0
  61. package/src/login.ts +91 -29
  62. package/src/logout.ts +36 -0
  63. package/src/oidc.ts +71 -20
  64. package/src/oidcClient.ts +48 -3
  65. package/src/oidcError.ts +7 -0
  66. package/src/parseTokens.ts +14 -1
  67. package/src/protocol.ts +16 -1
  68. package/src/renewTokens.ts +19 -8
  69. package/src/requests.ts +13 -11
  70. package/src/resourceParameters.ts +85 -0
  71. package/src/resourceTokens.spec.ts +1271 -0
  72. package/src/resourceTokens.ts +708 -0
  73. package/src/silentLogin.spec.ts +87 -1
  74. package/src/silentLogin.ts +24 -22
  75. package/src/types.ts +34 -0
  76. package/src/version.ts +1 -1
package/src/oidcClient.ts CHANGED
@@ -8,7 +8,14 @@ import { ILOidcLocation, OidcLocation } from './location';
8
8
  import { LoginCallback, Oidc } from './oidc.js';
9
9
  import { getValidTokenAsync, OidcToken, Tokens, ValidToken } from './parseTokens.js';
10
10
  import { syncTokensInfoAsync } from './renewTokens';
11
- import { Fetch, OidcConfiguration, StringMap } from './types.js';
11
+ import {
12
+ Fetch,
13
+ OidcConfiguration,
14
+ ResourceAccessToken,
15
+ ResourceFetchOptions,
16
+ ResourceTokenOptions,
17
+ StringMap,
18
+ } from './types.js';
12
19
 
13
20
  export interface EventSubscriber {
14
21
  (name: string, data: any);
@@ -174,8 +181,46 @@ export class OidcClient {
174
181
  return getValidTokenAsync(oidcToken, waitMs, numberWait);
175
182
  }
176
183
 
177
- fetchWithTokens(fetch: Fetch, demonstratingProofOfPossession: boolean = false): Fetch {
178
- return fetchWithTokens(fetch, this._oidc, demonstratingProofOfPossession);
184
+ /** Acquires or renews an access token belonging to an explicitly configured resource. */
185
+ getAccessTokenForResourceAsync(
186
+ resource: string,
187
+ options?: ResourceTokenOptions,
188
+ ): Promise<ResourceAccessToken> {
189
+ return this._oidc.resourceTokens.getAccessTokenAsync(resource, options);
190
+ }
191
+
192
+ /** Reads an already acquired usable resource token without starting authorization. */
193
+ getAccessTokenForResource(resource: string): ResourceAccessToken | null {
194
+ return this._oidc.resourceTokens.peek(resource);
195
+ }
196
+
197
+ /** Clears only this resource locally, without revoking a shared refresh grant. */
198
+ clearResourceTokensAsync(resource: string): Promise<void> {
199
+ return this._oidc.resourceTokens.clearAsync(resource);
200
+ }
201
+
202
+ /** Wraps fetch with an explicit resource and validated API destinations; redirects are not followed. */
203
+ fetchForResource(
204
+ resource: string,
205
+ fetch: Fetch = window.fetch,
206
+ options: Omit<ResourceFetchOptions, 'resource'> = {},
207
+ ): Fetch {
208
+ return this.fetchWithTokens(fetch, options.demonstratingProofOfPossession ?? false, {
209
+ resource,
210
+ });
211
+ }
212
+
213
+ fetchWithTokens(
214
+ fetch: Fetch,
215
+ demonstratingProofOfPossession: boolean = false,
216
+ options: ResourceFetchOptions = {},
217
+ ): Fetch {
218
+ return fetchWithTokens(
219
+ fetch,
220
+ this._oidc,
221
+ options.demonstratingProofOfPossession ?? demonstratingProofOfPossession,
222
+ options,
223
+ );
179
224
  }
180
225
 
181
226
  async userInfoAsync<T extends OidcUserInfo = OidcUserInfo>(
package/src/oidcError.ts CHANGED
@@ -1,4 +1,9 @@
1
1
  export const OidcErrorCode = {
2
+ INVALID_RESOURCE: 'INVALID_RESOURCE',
3
+ INVALID_TARGET: 'INVALID_TARGET',
4
+ RESOURCE_TOKEN_UNAVAILABLE: 'RESOURCE_TOKEN_UNAVAILABLE',
5
+ RESOURCE_CONTEXT_MISMATCH: 'RESOURCE_CONTEXT_MISMATCH',
6
+ RESOURCE_WORKER_UNSUPPORTED: 'RESOURCE_WORKER_UNSUPPORTED',
2
7
  LOGIN_REQUIRED: 'LOGIN_REQUIRED',
3
8
  CONSENT_REQUIRED: 'CONSENT_REQUIRED',
4
9
  INTERACTION_REQUIRED: 'INTERACTION_REQUIRED',
@@ -85,6 +90,8 @@ export const isRetryableHttpStatus = (status?: number): boolean =>
85
90
 
86
91
  export const oidcErrorCodeFromOAuthError = (oauthError?: string): OidcErrorCode => {
87
92
  switch (oauthError) {
93
+ case 'invalid_target':
94
+ return OidcErrorCode.INVALID_TARGET;
88
95
  case 'login_required':
89
96
  return OidcErrorCode.LOGIN_REQUIRED;
90
97
  case 'consent_required':
@@ -32,6 +32,16 @@ export type Tokens = {
32
32
  accessToken: string;
33
33
  expiresAt: number;
34
34
  issuedAt: number;
35
+ scope?: string;
36
+ tokenType?: string;
37
+ resourceContext?: {
38
+ resource: string;
39
+ issuer: string;
40
+ clientId: string;
41
+ configurationName: string;
42
+ subject: string;
43
+ grantResource: string | null;
44
+ };
35
45
  };
36
46
 
37
47
  export type TokenRenewModeType = {
@@ -139,10 +149,13 @@ export const parseOriginalTokens = (tokens, oldTokens, tokenRenewMode: string) =
139
149
  accessToken: tokens.access_token,
140
150
  expiresIn: tokens.expires_in,
141
151
  idToken: tokens.id_token,
142
- scope: tokens.scope,
152
+ scope: tokens.scope ?? oldTokens?.scope,
143
153
  tokenType: tokens.token_type,
144
154
  issuedAt: tokens.issued_at,
145
155
  };
156
+ if (tokens.resourceContext !== undefined) {
157
+ Object.assign(data, { resourceContext: tokens.resourceContext });
158
+ }
146
159
 
147
160
  if ('refresh_token' in tokens) {
148
161
  // @ts-ignore
package/src/protocol.ts CHANGED
@@ -15,7 +15,18 @@
15
15
  /**
16
16
  * Semver-protected version of the service worker `postMessage` protocol.
17
17
  */
18
- export const PROTOCOL_VERSION = '1.0.0' as const;
18
+ export const PROTOCOL_VERSION = '1.1.0' as const;
19
+
20
+ export type { OidcResourceConfiguration } from '@axa-fr/oidc-client-service-worker/protocol';
21
+ export {
22
+ getContextResource,
23
+ getResourceConfiguration,
24
+ getResourceContextName,
25
+ isResourceOriginManaged,
26
+ isResourceUrlAllowed,
27
+ RESOURCE_TOKEN_REQUEST_HEADER,
28
+ validateResourceIdentifier,
29
+ } from '@axa-fr/oidc-client-service-worker/protocol';
19
30
 
20
31
  /**
21
32
  * Every supported service worker message type. The values are also the
@@ -53,6 +64,10 @@ export interface ServiceWorkerMessage<TData = unknown> {
53
64
  }
54
65
 
55
66
  export interface ServiceWorkerResponse {
67
+ /** Resource isolation capability provided by protocol 1.1 workers. */
68
+ resourceTokenManagement?: boolean;
69
+ /** Worker-owned context names, without token or key material. */
70
+ resourceContexts?: string[];
56
71
  configurationName?: string;
57
72
  error?: unknown;
58
73
  [key: string]: unknown;
@@ -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';
@@ -97,7 +98,14 @@ export async function renewTokensAndStartTimerResultAsync(
97
98
 
98
99
  let result: RenewTokensResult;
99
100
  const serviceWorker = await initWorkerAsync(oidc.configuration, oidc.configurationName);
100
- 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
+ ) {
101
109
  result = await syncTokens(oidc, forceRefresh, extras, scope);
102
110
  } else {
103
111
  let lockResult: any = 'retry';
@@ -494,12 +502,15 @@ const synchroniseTokensAsync =
494
502
  }
495
503
  }
496
504
  const localFunctionAsync = async () => {
497
- const details = {
498
- client_id: clientId,
499
- redirect_uri: redirectUri,
500
- grant_type: 'refresh_token',
501
- refresh_token: tokens.refreshToken,
502
- };
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
+ );
503
514
  const oidcServerConfiguration = await oidc.initAsync(
504
515
  authority,
505
516
  configuration.authority_configuration,
@@ -517,7 +528,7 @@ const synchroniseTokensAsync =
517
528
  let tokenResponse = await performTokenRequestAsync(oidc.getFetch())(
518
529
  url,
519
530
  details,
520
- finalExtras,
531
+ applyResourceParameters(finalExtras, configuration),
521
532
  tokens,
522
533
  headersExtras,
523
534
  configuration.token_renew_mode,
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
+ };