@axa-fr/oidc-client 7.29.8 → 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 (71) hide show
  1. package/README.md +174 -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/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 +19 -8
  64. package/src/requests.ts +13 -11
  65. package/src/resourceParameters.ts +85 -0
  66. package/src/resourceTokens.spec.ts +1271 -0
  67. package/src/resourceTokens.ts +708 -0
  68. package/src/silentLogin.spec.ts +87 -1
  69. package/src/silentLogin.ts +24 -22
  70. package/src/types.ts +34 -0
  71. package/src/version.ts +1 -1
package/src/login.ts CHANGED
@@ -21,6 +21,12 @@ import {
21
21
  PushedAuthorizationRequestErrorCode,
22
22
  } from './pushedAuthorizationRequestError.js';
23
23
  import { performAuthorizationRequestAsync, performFirstTokenRequestAsync } from './requests.js';
24
+ import {
25
+ applyResourceParameters,
26
+ rememberResourceTransaction,
27
+ RESOURCE_LOGIN_PARAMETER,
28
+ resourceContextName,
29
+ } from './resourceParameters';
24
30
  import { getParseQueryStringFromLocation } from './route-utils.js';
25
31
  import { Fetch, OidcConfiguration, StringMap } from './types.js';
26
32
 
@@ -43,12 +49,17 @@ export const defaultLoginAsync =
43
49
  ): Promise<unknown> => {
44
50
  const originExtras = extras;
45
51
  extras = { ...extras };
52
+ const resource = extras[RESOURCE_LOGIN_PARAMETER];
53
+ delete extras[RESOURCE_LOGIN_PARAMETER];
54
+ const contextName = resourceContextName(configurationName, resource);
46
55
  const loginLocalAsync = async () => {
47
56
  const url = callbackPath || oidcLocation.getPath();
48
57
 
49
58
  if (!('state' in extras)) {
50
59
  extras.state = generateRandom(16);
51
60
  }
61
+ if (resource !== undefined)
62
+ rememberResourceTransaction(configurationName, extras.state, resource);
52
63
 
53
64
  publishEvent(eventNames.loginAsync_begin, {});
54
65
  if (extras) {
@@ -66,30 +77,43 @@ export const defaultLoginAsync =
66
77
  scope = configuration.scope;
67
78
  }
68
79
 
69
- const extraFinal = !configuration.extras ? extras : { ...configuration.extras, ...extras };
80
+ const extraFinal = applyResourceParameters(
81
+ !configuration.extras ? extras : { ...configuration.extras, ...extras },
82
+ configuration,
83
+ resource,
84
+ );
85
+ if (typeof extraFinal.scope === 'string') scope = extraFinal.scope;
70
86
  if (!extraFinal.nonce) {
71
87
  extraFinal.nonce = generateRandom(12);
72
88
  }
73
89
  const nonce = { nonce: extraFinal.nonce };
74
- const serviceWorker = await initWorkerAsync(configuration, configurationName);
90
+ const serviceWorker = await initWorkerAsync(configuration, contextName);
75
91
  const oidcServerConfiguration = await initAsync(
76
92
  configuration.authority,
77
93
  configuration.authority_configuration,
78
94
  );
79
95
  let storage;
80
96
  if (serviceWorker) {
81
- serviceWorker.setLoginParams({ callbackPath: url, extras: originExtras, scope: scope });
82
- await serviceWorker.initAsync(oidcServerConfiguration, 'loginAsync', configuration);
97
+ serviceWorker.setLoginParams({
98
+ callbackPath: url,
99
+ extras: originExtras,
100
+ scope,
101
+ resource,
102
+ });
103
+ await serviceWorker.initAsync(oidcServerConfiguration, 'loginAsync', {
104
+ ...configuration,
105
+ scope,
106
+ });
83
107
  await serviceWorker.setNonceAsync(nonce);
84
108
  serviceWorker.startKeepAliveServiceWorker();
85
109
  storage = serviceWorker;
86
110
  } else {
87
111
  const session = initSession(
88
- configurationName,
112
+ contextName,
89
113
  configuration.storage ?? sessionStorage,
90
114
  configuration.login_state_storage ?? configuration.storage ?? sessionStorage,
91
115
  );
92
- session.setLoginParams({ callbackPath: url, extras: originExtras, scope: scope });
116
+ session.setLoginParams({ callbackPath: url, extras: originExtras, scope, resource });
93
117
  await session.setNonceAsync(nonce);
94
118
  storage = session;
95
119
  }
@@ -144,10 +168,11 @@ export const defaultLoginAsync =
144
168
 
145
169
  export const loginCallbackAsync =
146
170
  (oidc: Oidc) =>
147
- async (isSilentSignin = false) => {
171
+ async (isSilentSignin = false, resource?: string) => {
148
172
  try {
149
173
  oidc.publishEvent(eventNames.loginCallbackAsync_begin, {});
150
174
  const configuration = oidc.configuration;
175
+ const contextName = resourceContextName(oidc.configurationName, resource);
151
176
  const clientId = configuration.client_id;
152
177
  const redirectUri = isSilentSignin
153
178
  ? configuration.silent_redirect_uri
@@ -161,7 +186,7 @@ export const loginCallbackAsync =
161
186
  const href = oidc.location.getCurrentHref();
162
187
  const queryParams = getParseQueryStringFromLocation(href);
163
188
  const sessionState = queryParams.session_state;
164
- const serviceWorker = await initWorkerAsync(configuration, oidc.configurationName);
189
+ const serviceWorker = await initWorkerAsync(configuration, contextName);
165
190
  let storage;
166
191
  let nonceData;
167
192
  let getLoginParams;
@@ -176,7 +201,7 @@ export const loginCallbackAsync =
176
201
  storage = serviceWorker;
177
202
  } else {
178
203
  const session = initSession(
179
- oidc.configurationName,
204
+ contextName,
180
205
  configuration.storage ?? sessionStorage,
181
206
  configuration.login_state_storage ?? configuration.storage ?? sessionStorage,
182
207
  );
@@ -229,12 +254,16 @@ export const loginCallbackAsync =
229
254
  );
230
255
  }
231
256
 
232
- const data = {
233
- code: queryParams.code,
234
- grant_type: 'authorization_code',
235
- client_id: configuration.client_id,
236
- redirect_uri: redirectUri,
237
- };
257
+ const data = applyResourceParameters(
258
+ {
259
+ code: queryParams.code,
260
+ grant_type: 'authorization_code',
261
+ client_id: configuration.client_id,
262
+ redirect_uri: redirectUri,
263
+ },
264
+ configuration,
265
+ resource,
266
+ );
238
267
 
239
268
  const extras = {};
240
269
  // @ts-ignore
@@ -256,13 +285,27 @@ export const loginCallbackAsync =
256
285
  let demonstratingProofOfPossessionJwk;
257
286
  if (configuration.demonstrating_proof_of_possession) {
258
287
  if (serviceWorker) {
259
- headersExtras['DPoP'] = `DPOP_SECURED_BY_OIDC_SERVICE_WORKER_${oidc.configurationName}`;
288
+ headersExtras['DPoP'] = `DPOP_SECURED_BY_OIDC_SERVICE_WORKER_${contextName}`;
260
289
  } else {
261
- demonstratingProofOfPossessionJwk = await generateJwkAsync(window)(
262
- configuration.demonstrating_proof_of_possession_configuration.generateKeyAlgorithm,
263
- );
290
+ demonstratingProofOfPossessionJwk =
291
+ resource === undefined
292
+ ? await generateJwkAsync(window)(
293
+ configuration.demonstrating_proof_of_possession_configuration
294
+ .generateKeyAlgorithm,
295
+ )
296
+ : await initSession(
297
+ oidc.configurationName,
298
+ configuration.storage,
299
+ ).getDemonstratingProofOfPossessionJwkAsync();
300
+ if (!demonstratingProofOfPossessionJwk) {
301
+ throw new OidcError(
302
+ OidcErrorCode.RESOURCE_TOKEN_UNAVAILABLE,
303
+ 'The original OIDC DPoP key is unavailable.',
304
+ { phase: 'callback', retryable: false },
305
+ );
306
+ }
264
307
  const session = initSession(
265
- oidc.configurationName,
308
+ contextName,
266
309
  configuration.storage,
267
310
  configuration.login_state_storage ?? configuration.storage,
268
311
  );
@@ -275,9 +318,14 @@ export const loginCallbackAsync =
275
318
  }
276
319
  }
277
320
 
321
+ const tokenParameters = applyResourceParameters(
322
+ { ...data, ...extras },
323
+ configuration,
324
+ resource,
325
+ );
278
326
  let tokenResponse = await performFirstTokenRequestAsync(storage)(
279
327
  url,
280
- { ...data, ...extras },
328
+ tokenParameters,
281
329
  headersExtras,
282
330
  oidc.configuration.token_renew_mode,
283
331
  tokenRequestTimeout,
@@ -302,7 +350,7 @@ export const loginCallbackAsync =
302
350
  }
303
351
  tokenResponse = await performFirstTokenRequestAsync(storage)(
304
352
  url,
305
- { ...data, ...extras },
353
+ tokenParameters,
306
354
  headersExtras,
307
355
  oidc.configuration.token_renew_mode,
308
356
  tokenRequestTimeout,
@@ -329,6 +377,8 @@ export const loginCallbackAsync =
329
377
 
330
378
  let loginParams;
331
379
  const formattedTokens = tokenResponse.data.tokens;
380
+ if (configuration.resources?.length)
381
+ formattedTokens.scope ??= getLoginParams?.scope ?? configuration.scope;
332
382
  const demonstratingProofOfPossessionNonce =
333
383
  tokenResponse.data.demonstratingProofOfPossessionNonce;
334
384
 
@@ -339,6 +389,16 @@ export const loginCallbackAsync =
339
389
  retryable: false,
340
390
  });
341
391
  }
392
+ if (resource !== undefined && formattedTokens.idTokenPayload?.nonce !== nonceData.nonce) {
393
+ throw new OidcError(
394
+ OidcErrorCode.INVALID_NONCE,
395
+ 'Resource authorization requires the transaction nonce in a fresh ID token.',
396
+ {
397
+ phase: isSilentSignin ? 'refresh' : 'callback',
398
+ retryable: false,
399
+ },
400
+ );
401
+ }
342
402
  const { isValid, reason } = isTokensOidcValid(
343
403
  formattedTokens,
344
404
  nonceData.nonce,
@@ -383,7 +443,7 @@ export const loginCallbackAsync =
383
443
  }
384
444
  } else {
385
445
  const session = initSession(
386
- oidc.configurationName,
446
+ contextName,
387
447
  configuration.storage,
388
448
  configuration.login_state_storage ?? configuration.storage,
389
449
  );
@@ -393,14 +453,16 @@ export const loginCallbackAsync =
393
453
  }
394
454
  }
395
455
 
396
- await oidc.startCheckSessionAsync(
397
- oidcServerConfiguration.checkSessionIframe,
398
- clientId,
399
- sessionState,
400
- isSilentSignin,
401
- );
456
+ if (resource === undefined)
457
+ await oidc.startCheckSessionAsync(
458
+ oidcServerConfiguration.checkSessionIframe,
459
+ clientId,
460
+ sessionState,
461
+ isSilentSignin,
462
+ );
402
463
  oidc.publishEvent(eventNames.loginCallbackAsync_end, {});
403
464
  return {
465
+ resource,
404
466
  tokens: formattedTokens,
405
467
  state: 'request.state',
406
468
  callbackPath: loginParams.callbackPath,
package/src/logout.ts CHANGED
@@ -47,6 +47,7 @@ const keepExtras = (extras: StringMap): StringMap => {
47
47
  };
48
48
 
49
49
  export const destroyAsync = oidc => async status => {
50
+ if (oidc.resourceTokens) await oidc.resourceTokens.clearAllAsync();
50
51
  timer.clearTimeout(oidc.timeoutId);
51
52
  oidc.timeoutId = null;
52
53
  if (oidc.checkSessionIFrame) {
@@ -165,6 +166,9 @@ export const logoutAsync =
165
166
 
166
167
  try {
167
168
  try {
169
+ if (configuration.resources?.length && oidc.resourceTokens) {
170
+ await oidc.resourceTokens.withRefreshLockAsync(async (): Promise<void> => {});
171
+ }
168
172
  const revocationEndpoint = oidcServerConfiguration.revocationEndpoint;
169
173
  if (revocationEndpoint) {
170
174
  const promises = [];
@@ -198,6 +202,38 @@ export const logoutAsync =
198
202
  );
199
203
  promises.push(revokeRefreshTokenPromise);
200
204
  }
205
+ if (oidc.resourceTokens) {
206
+ const resourceTokens = await oidc.resourceTokens.getTokensToRevokeAsync();
207
+ const seen = new Set<string>([accessToken, refreshToken].filter(Boolean));
208
+ for (const tokens of resourceTokens) {
209
+ for (const [tokenType, token] of [
210
+ [TOKEN_TYPE.access_token, tokens.accessToken],
211
+ [TOKEN_TYPE.refresh_token, tokens.refreshToken],
212
+ ]) {
213
+ if (
214
+ token &&
215
+ !seen.has(token) &&
216
+ configuration.logout_tokens_to_invalidate.includes(tokenType)
217
+ ) {
218
+ seen.add(token);
219
+ promises.push(
220
+ performRevocationRequestAsync(fetch)(
221
+ revocationEndpoint,
222
+ token,
223
+ tokenType,
224
+ configuration.client_id,
225
+ extractExtras(
226
+ extras,
227
+ tokenType === TOKEN_TYPE.access_token
228
+ ? ':revoke_access_token'
229
+ : ':revoke_refresh_token',
230
+ ),
231
+ ),
232
+ );
233
+ }
234
+ }
235
+ }
236
+ }
201
237
  if (promises.length > 0) {
202
238
  // Revocation must be awaited *before* navigation, so a cancelled
203
239
  // navigation can never leave valid tokens behind both in storage
package/src/oidc.ts CHANGED
@@ -27,6 +27,13 @@ import {
27
27
  RenewTokensResult,
28
28
  } from './renewTokens.js';
29
29
  import { fetchFromIssuer } from './requests.js';
30
+ import {
31
+ clearResourceTransaction,
32
+ getCallbackResource,
33
+ RESOURCE_LOGIN_PARAMETER,
34
+ resourceContextName,
35
+ } from './resourceParameters';
36
+ import { ResourceTokens } from './resourceTokens';
30
37
  import { getParseQueryStringFromLocation } from './route-utils.js';
31
38
  import defaultSilentLoginAsync from './silentLogin.js';
32
39
  import timer from './timer.js';
@@ -104,6 +111,7 @@ const loginCallbackWithAutoTokensRenewAsync = async (oidc): Promise<LoginCallbac
104
111
  };
105
112
 
106
113
  export class Oidc {
114
+ public resourceTokens: ResourceTokens;
107
115
  public configuration: OidcConfiguration;
108
116
  public userInfo: null;
109
117
  public tokens?: Tokens;
@@ -172,6 +180,7 @@ export class Oidc {
172
180
  this.userInfo = null;
173
181
  this.events = [];
174
182
  this.timeoutId = null;
183
+ this.resourceTokens = new ResourceTokens(this);
175
184
  this.loginCallbackWithAutoTokensRenewAsync.bind(this);
176
185
  this.initAsync.bind(this);
177
186
  this.loginCallbackAsync.bind(this);
@@ -244,12 +253,12 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
244
253
 
245
254
  static eventNames = eventNames;
246
255
 
247
- _silentLoginCallbackFromIFrame() {
256
+ _silentLoginCallbackFromIFrame(tokens: Tokens = this.tokens, resource?: string) {
248
257
  if (this.configuration.silent_redirect_uri && this.configuration.silent_login_uri) {
249
258
  const location = this.location;
250
259
  const queryParams = getParseQueryStringFromLocation(location.getCurrentHref());
251
260
  window.parent.postMessage(
252
- `${this.configurationName}_oidc_tokens:${JSON.stringify({ tokens: this.tokens, sessionState: queryParams.session_state })}`,
261
+ `${this.configurationName}_oidc_tokens:${JSON.stringify({ tokens, resource, sessionState: queryParams.session_state })}`,
253
262
  location.getOrigin(),
254
263
  );
255
264
  }
@@ -288,8 +297,11 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
288
297
 
289
298
  async silentLoginCallbackAsync() {
290
299
  try {
291
- await this.loginCallbackAsync(true);
292
- this._silentLoginCallbackFromIFrame();
300
+ const resource = this.configuration.resources?.length
301
+ ? getCallbackResource(this.configurationName, this.location.getCurrentHref())
302
+ : undefined;
303
+ const response = await this.loginCallbackAsync(true);
304
+ this._silentLoginCallbackFromIFrame(response.parsedTokens, resource);
293
305
  } catch (exception) {
294
306
  console.error(exception);
295
307
  this._silentLoginErrorCallbackFromIFrame(exception);
@@ -379,16 +391,23 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
379
391
  if (this.loginPromise !== null) {
380
392
  return this.loginPromise;
381
393
  }
382
- if (silentLoginOnly) {
383
- this.loginPromise = defaultSilentLoginAsync(
384
- window,
385
- this.configurationName,
386
- this.configuration,
387
- this.publishEvent.bind(this),
388
- this,
389
- )(extras, scope);
390
- } else {
391
- this.loginPromise = defaultLoginAsync(
394
+ this.loginPromise = (async () => {
395
+ if (
396
+ extras?.[RESOURCE_LOGIN_PARAMETER] === undefined &&
397
+ this.configuration.resources?.length
398
+ ) {
399
+ await this.resourceTokens.clearAllAsync();
400
+ }
401
+ if (silentLoginOnly) {
402
+ return defaultSilentLoginAsync(
403
+ window,
404
+ this.configurationName,
405
+ this.configuration,
406
+ this.publishEvent.bind(this),
407
+ this,
408
+ )(extras, scope);
409
+ }
410
+ return defaultLoginAsync(
392
411
  this.configurationName,
393
412
  this.configuration,
394
413
  this.publishEvent.bind(this),
@@ -396,10 +415,15 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
396
415
  this.location,
397
416
  this.getFetch,
398
417
  )(callbackPath, extras, isSilentSignin, scope);
399
- }
400
- return this.loginPromise.finally(() => {
401
- this.loginPromise = null;
402
- });
418
+ })();
419
+ return this.loginPromise
420
+ .catch(error => {
421
+ if (isSilentSignin) this._silentLoginErrorCallbackFromIFrame(error);
422
+ throw error;
423
+ })
424
+ .finally(() => {
425
+ this.loginPromise = null;
426
+ });
403
427
  }
404
428
 
405
429
  loginCallbackPromise: Promise<any> = null;
@@ -409,12 +433,39 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
409
433
  }
410
434
 
411
435
  const loginCallbackLocalAsync = async (): Promise<InternalLoginCallback> => {
412
- const response = await loginCallbackAsync(this)(isSilenSignin);
436
+ const resource = this.configuration.resources?.length
437
+ ? getCallbackResource(this.configurationName, this.location.getCurrentHref())
438
+ : undefined;
439
+ const response = await loginCallbackAsync(this)(isSilenSignin, resource);
413
440
  // @ts-ignore
414
441
  const parsedTokens = response.tokens;
415
442
  // @ts-ignore
443
+ if (resource !== undefined) {
444
+ if (
445
+ getCallbackResource(this.configurationName, this.location.getCurrentHref()) !== resource
446
+ ) {
447
+ throw new OidcError(
448
+ OidcErrorCode.RESOURCE_TOKEN_UNAVAILABLE,
449
+ 'The resource authorization was cleared.',
450
+ { phase: 'callback', retryable: false },
451
+ );
452
+ }
453
+ await this.resourceTokens.acceptAuthorizationAsync(resource, parsedTokens);
454
+ clearResourceTransaction(this.configurationName, this.location.getCurrentHref());
455
+ return {
456
+ parsedTokens,
457
+ state: response.state,
458
+ callbackPath: response.callbackPath,
459
+ scope: response.scope,
460
+ extras: response.extras,
461
+ };
462
+ }
463
+ await this.resourceTokens.clearAllAsync();
416
464
  this.tokens = parsedTokens;
417
- const serviceWorker = await initWorkerAsync(this.configuration, this.configurationName);
465
+ const serviceWorker = await initWorkerAsync(
466
+ this.configuration,
467
+ resourceContextName(this.configurationName, resource),
468
+ );
418
469
  if (!serviceWorker) {
419
470
  const session = initSession(
420
471
  this.configurationName,
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,