@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.
- package/README.md +187 -0
- package/dist/events.d.ts +3 -0
- package/dist/events.d.ts.map +1 -1
- package/dist/fetch.d.ts +2 -2
- package/dist/fetch.d.ts.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1339 -871
- package/dist/index.umd.cjs +2 -2
- package/dist/initSession.d.ts +2 -0
- package/dist/initSession.d.ts.map +1 -1
- package/dist/initWorker.d.ts +1 -25
- package/dist/initWorker.d.ts.map +1 -1
- package/dist/jwt.d.ts.map +1 -1
- package/dist/keepSession.d.ts.map +1 -1
- package/dist/keepSession.spec.d.ts +2 -0
- package/dist/keepSession.spec.d.ts.map +1 -0
- package/dist/legacyCompatibility.spec.d.ts +2 -0
- package/dist/legacyCompatibility.spec.d.ts.map +1 -0
- package/dist/login.d.ts +2 -1
- package/dist/login.d.ts.map +1 -1
- package/dist/logout.d.ts.map +1 -1
- package/dist/node_modules/@axa-fr/oidc-client-service-worker/dist/OidcServiceWorker.js +1049 -0
- package/dist/node_modules/@axa-fr/oidc-client-service-worker/dist/OidcTrustedDomains.js +31 -0
- package/dist/oidc.d.ts +6 -1
- package/dist/oidc.d.ts.map +1 -1
- package/dist/oidcClient.d.ts +13 -2
- package/dist/oidcClient.d.ts.map +1 -1
- package/dist/oidcError.d.ts +5 -0
- package/dist/oidcError.d.ts.map +1 -1
- package/dist/parseTokens.d.ts +10 -0
- package/dist/parseTokens.d.ts.map +1 -1
- package/dist/protocol.d.ts +7 -1
- package/dist/protocol.d.ts.map +1 -1
- package/dist/renewTokens.d.ts +0 -6
- package/dist/renewTokens.d.ts.map +1 -1
- package/dist/requests.d.ts +3 -3
- package/dist/requests.d.ts.map +1 -1
- package/dist/resourceParameters.d.ts +9 -0
- package/dist/resourceParameters.d.ts.map +1 -0
- package/dist/resourceTokens.d.ts +34 -0
- package/dist/resourceTokens.d.ts.map +1 -0
- package/dist/resourceTokens.spec.d.ts +2 -0
- package/dist/resourceTokens.spec.d.ts.map +1 -0
- package/dist/silentLogin.d.ts +2 -1
- package/dist/silentLogin.d.ts.map +1 -1
- package/dist/types.d.ts +28 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/version.d.ts +1 -1
- package/package.json +3 -3
- package/src/events.ts +3 -0
- package/src/fetch.ts +115 -15
- package/src/index.ts +4 -0
- package/src/initSession.ts +9 -0
- package/src/initWorker.ts +65 -13
- package/src/jwt.spec.ts +17 -0
- package/src/jwt.ts +4 -1
- package/src/keepSession.spec.ts +254 -0
- package/src/keepSession.ts +10 -4
- package/src/legacyCompatibility.spec.ts +142 -0
- package/src/login.ts +91 -29
- package/src/logout.ts +36 -0
- package/src/oidc.ts +71 -20
- package/src/oidcClient.ts +48 -3
- package/src/oidcError.ts +7 -0
- package/src/parseTokens.ts +14 -1
- package/src/protocol.ts +16 -1
- package/src/renewTokens.ts +19 -8
- package/src/requests.ts +13 -11
- package/src/resourceParameters.ts +85 -0
- package/src/resourceTokens.spec.ts +1271 -0
- package/src/resourceTokens.ts +708 -0
- package/src/silentLogin.spec.ts +87 -1
- package/src/silentLogin.ts +24 -22
- package/src/types.ts +34 -0
- 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
|
-
|
|
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
|
|
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 =
|
|
22
|
-
|
|
23
|
-
|
|
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
|
|
47
|
-
|
|
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
|
-
|
|
127
|
+
(oidc.configuration.demonstrating_proof_of_possession &&
|
|
128
|
+
demonstrating_proof_of_possession) ||
|
|
129
|
+
resourceToken?.tokenType?.toLowerCase() === 'dpop'
|
|
55
130
|
) {
|
|
56
131
|
const demonstrationOdProofOfPossession =
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
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';
|
package/src/initSession.ts
CHANGED
|
@@ -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
|
|
254
|
+
return unavailable();
|
|
235
255
|
}
|
|
236
256
|
|
|
237
257
|
if (configuration.service_worker_activate() === false) {
|
|
238
|
-
return
|
|
258
|
+
return unavailable();
|
|
239
259
|
}
|
|
240
260
|
|
|
241
|
-
const
|
|
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
|
|
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
|
|
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
|
-
|
|
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:
|
|
217
|
+
htu: target.href,
|
|
215
218
|
iat: Math.round(Date.now() / 1000),
|
|
216
219
|
...extrasClaims,
|
|
217
220
|
};
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import { eventNames } from './events';
|
|
4
|
+
import * as sessions from './initSession';
|
|
5
|
+
import * as workers from './initWorker';
|
|
6
|
+
import Oidc from './oidc';
|
|
7
|
+
import { type Tokens } from './parseTokens';
|
|
8
|
+
import * as renewal from './renewTokens';
|
|
9
|
+
import timer from './timer';
|
|
10
|
+
|
|
11
|
+
afterEach(() => {
|
|
12
|
+
vi.clearAllTimers();
|
|
13
|
+
vi.useRealTimers();
|
|
14
|
+
vi.restoreAllMocks();
|
|
15
|
+
vi.unstubAllGlobals();
|
|
16
|
+
workers.registrationCache.clear();
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
describe.each(['service worker', 'browser storage'])('session restoration with %s', mode => {
|
|
20
|
+
const tokens: Tokens = {
|
|
21
|
+
accessToken: 'access-token',
|
|
22
|
+
refreshToken: 'refresh-token',
|
|
23
|
+
idToken: 'id-token',
|
|
24
|
+
accessTokenPayload: null,
|
|
25
|
+
idTokenPayload: null,
|
|
26
|
+
expiresAt: 2000000000,
|
|
27
|
+
issuedAt: 1900000000,
|
|
28
|
+
};
|
|
29
|
+
const server = { checkSessionIframe: 'https://issuer.example.com/check-session' };
|
|
30
|
+
const loginParams = { extras: { audience: 'api' }, scope: 'openid profile' };
|
|
31
|
+
|
|
32
|
+
const createOidc = (storage: Storage, loginStateStorage: Storage) => ({
|
|
33
|
+
configuration: {
|
|
34
|
+
authority: 'https://issuer.example.com',
|
|
35
|
+
client_id: 'client',
|
|
36
|
+
redirect_uri: 'https://app.example.com/callback',
|
|
37
|
+
scope: 'openid',
|
|
38
|
+
storage,
|
|
39
|
+
login_state_storage: loginStateStorage,
|
|
40
|
+
preload_user_info: true,
|
|
41
|
+
service_worker_relative_url: mode === 'service worker' ? '/OidcServiceWorker.js' : null,
|
|
42
|
+
service_worker_activate: () => true,
|
|
43
|
+
},
|
|
44
|
+
configurationName: 'default',
|
|
45
|
+
tokens: null as Tokens | null,
|
|
46
|
+
userInfo: { sub: 'previous-user' },
|
|
47
|
+
timeoutId: null as ReturnType<typeof timer.setTimeout> | null,
|
|
48
|
+
checkSessionIFrame: { stop: vi.fn() },
|
|
49
|
+
tryKeepExistingSessionPromise: null,
|
|
50
|
+
initAsync: vi.fn().mockResolvedValue(server),
|
|
51
|
+
startCheckSessionAsync: vi.fn().mockResolvedValue(undefined),
|
|
52
|
+
userInfoAsync: vi.fn().mockResolvedValue({ sub: 'user' }),
|
|
53
|
+
publishEvent: vi.fn(),
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
let oidc: ReturnType<typeof createOidc>;
|
|
57
|
+
let loginStateStorage: Storage;
|
|
58
|
+
let getSessionState: ReturnType<typeof vi.fn<() => Promise<string>>>;
|
|
59
|
+
let clearWorker: ReturnType<typeof vi.fn<() => Promise<void>>>;
|
|
60
|
+
let restore: () => Promise<boolean>;
|
|
61
|
+
|
|
62
|
+
beforeEach(async () => {
|
|
63
|
+
vi.useFakeTimers();
|
|
64
|
+
vi.spyOn(timer, 'setTimeout').mockImplementation(setTimeout);
|
|
65
|
+
vi.spyOn(timer, 'clearTimeout').mockImplementation(clearTimeout);
|
|
66
|
+
vi.spyOn(renewal, 'autoRenewTokens');
|
|
67
|
+
vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
68
|
+
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
|
69
|
+
workers.registrationCache.clear();
|
|
70
|
+
|
|
71
|
+
const storage = {} as Storage;
|
|
72
|
+
loginStateStorage = {} as Storage;
|
|
73
|
+
oidc = createOidc(storage, loginStateStorage);
|
|
74
|
+
restore = () => Oidc.prototype.tryKeepExistingSessionAsync.call(oidc as unknown as Oidc);
|
|
75
|
+
getSessionState = vi.fn().mockResolvedValue('session-state');
|
|
76
|
+
clearWorker = vi.fn().mockResolvedValue(undefined);
|
|
77
|
+
|
|
78
|
+
const session = sessions.initSession('default', storage, loginStateStorage);
|
|
79
|
+
session.setTokens({ ...tokens });
|
|
80
|
+
|
|
81
|
+
if (mode === 'service worker') {
|
|
82
|
+
// Keep the real worker login-metadata reader; only worker messaging is mocked.
|
|
83
|
+
const registration = {
|
|
84
|
+
addEventListener: vi.fn(),
|
|
85
|
+
update: vi.fn().mockResolvedValue(undefined),
|
|
86
|
+
};
|
|
87
|
+
vi.stubGlobal('window', {});
|
|
88
|
+
vi.stubGlobal('localStorage', loginStateStorage);
|
|
89
|
+
vi.stubGlobal('navigator', {
|
|
90
|
+
serviceWorker: {
|
|
91
|
+
controller: {},
|
|
92
|
+
register: vi.fn().mockResolvedValue(registration),
|
|
93
|
+
ready: Promise.resolve(registration),
|
|
94
|
+
addEventListener: vi.fn(),
|
|
95
|
+
},
|
|
96
|
+
});
|
|
97
|
+
const worker = await workers.initWorkerAsync(oidc.configuration, 'default');
|
|
98
|
+
vi.spyOn(workers, 'initWorkerAsync').mockResolvedValue({
|
|
99
|
+
...worker,
|
|
100
|
+
initAsync: vi.fn().mockResolvedValue({ tokens: { ...tokens } }),
|
|
101
|
+
startKeepAliveServiceWorker: vi.fn(),
|
|
102
|
+
getSessionStateAsync: getSessionState,
|
|
103
|
+
clearAsync: clearWorker,
|
|
104
|
+
});
|
|
105
|
+
} else {
|
|
106
|
+
vi.spyOn(workers, 'initWorkerAsync').mockResolvedValue(null);
|
|
107
|
+
vi.spyOn(sessions, 'initSession').mockReturnValue({
|
|
108
|
+
...session,
|
|
109
|
+
getSessionStateAsync: getSessionState,
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
it.each([undefined, '', 'null', 'undefined', '{invalid-json'])(
|
|
115
|
+
'restores tokens when persisted login metadata is %s',
|
|
116
|
+
async metadata => {
|
|
117
|
+
if (metadata !== undefined) {
|
|
118
|
+
loginStateStorage['oidc.login.default'] = metadata;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
await expect(restore()).resolves.toBe(true);
|
|
122
|
+
|
|
123
|
+
expect(oidc.tokens).toEqual(tokens);
|
|
124
|
+
expect(renewal.autoRenewTokens).toHaveBeenCalledWith(
|
|
125
|
+
oidc,
|
|
126
|
+
tokens.expiresAt,
|
|
127
|
+
undefined,
|
|
128
|
+
undefined,
|
|
129
|
+
);
|
|
130
|
+
expect(vi.getTimerCount()).toBe(1);
|
|
131
|
+
expect(oidc.startCheckSessionAsync).toHaveBeenCalledWith(
|
|
132
|
+
server.checkSessionIframe,
|
|
133
|
+
'client',
|
|
134
|
+
'session-state',
|
|
135
|
+
);
|
|
136
|
+
expect(oidc.userInfoAsync).toHaveBeenCalledOnce();
|
|
137
|
+
expect(oidc.publishEvent).toHaveBeenCalledWith(
|
|
138
|
+
eventNames.tryKeepExistingSessionAsync_end,
|
|
139
|
+
expect.objectContaining({ success: true }),
|
|
140
|
+
);
|
|
141
|
+
expect(clearWorker).not.toHaveBeenCalled();
|
|
142
|
+
},
|
|
143
|
+
);
|
|
144
|
+
|
|
145
|
+
it('preserves stored extras and scope when starting renewal', async () => {
|
|
146
|
+
loginStateStorage['oidc.login.default'] = JSON.stringify(loginParams);
|
|
147
|
+
|
|
148
|
+
await expect(restore()).resolves.toBe(true);
|
|
149
|
+
|
|
150
|
+
expect(renewal.autoRenewTokens).toHaveBeenCalledWith(
|
|
151
|
+
oidc,
|
|
152
|
+
tokens.expiresAt,
|
|
153
|
+
loginParams.extras,
|
|
154
|
+
loginParams.scope,
|
|
155
|
+
);
|
|
156
|
+
expect(clearWorker).not.toHaveBeenCalled();
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
it.each(['session state', 'session monitoring', 'user info'])(
|
|
160
|
+
'clears page state on a %s failure and allows a successful retry',
|
|
161
|
+
async stage => {
|
|
162
|
+
loginStateStorage['oidc.login.default'] = JSON.stringify(loginParams);
|
|
163
|
+
const error = new Error(`${stage} failed`);
|
|
164
|
+
const failingStep =
|
|
165
|
+
stage === 'session state'
|
|
166
|
+
? getSessionState
|
|
167
|
+
: stage === 'session monitoring'
|
|
168
|
+
? oidc.startCheckSessionAsync
|
|
169
|
+
: oidc.userInfoAsync;
|
|
170
|
+
failingStep.mockRejectedValueOnce(error);
|
|
171
|
+
|
|
172
|
+
await expect(restore()).resolves.toBe(false);
|
|
173
|
+
|
|
174
|
+
expect(renewal.autoRenewTokens).toHaveBeenCalledOnce();
|
|
175
|
+
expect(oidc.tokens).toBeNull();
|
|
176
|
+
expect(oidc.userInfo).toBeNull();
|
|
177
|
+
expect(oidc.timeoutId).toBeNull();
|
|
178
|
+
expect(oidc.checkSessionIFrame.stop).toHaveBeenCalledOnce();
|
|
179
|
+
expect(vi.getTimerCount()).toBe(0);
|
|
180
|
+
expect(oidc.publishEvent).toHaveBeenCalledWith(
|
|
181
|
+
eventNames.tryKeepExistingSessionAsync_error,
|
|
182
|
+
expect.any(String),
|
|
183
|
+
);
|
|
184
|
+
|
|
185
|
+
await expect(restore()).resolves.toBe(true);
|
|
186
|
+
|
|
187
|
+
expect(workers.initWorkerAsync).toHaveBeenCalledTimes(2);
|
|
188
|
+
expect(oidc.tokens).toEqual(tokens);
|
|
189
|
+
expect(vi.getTimerCount()).toBe(1);
|
|
190
|
+
},
|
|
191
|
+
);
|
|
192
|
+
|
|
193
|
+
it('handles a restoration failure before a renewal timer or session monitor exists', async () => {
|
|
194
|
+
oidc.checkSessionIFrame = null;
|
|
195
|
+
oidc.initAsync.mockRejectedValueOnce(new Error('discovery failed'));
|
|
196
|
+
|
|
197
|
+
await expect(restore()).resolves.toBe(false);
|
|
198
|
+
|
|
199
|
+
expect(oidc.tokens).toBeNull();
|
|
200
|
+
expect(oidc.userInfo).toBeNull();
|
|
201
|
+
expect(oidc.timeoutId).toBeNull();
|
|
202
|
+
expect(vi.getTimerCount()).toBe(0);
|
|
203
|
+
expect(clearWorker).not.toHaveBeenCalled();
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
if (mode === 'service worker') {
|
|
207
|
+
it.each([false, true])(
|
|
208
|
+
'clears page state before worker cleanup completes (cleanup rejects: %s)',
|
|
209
|
+
async rejects => {
|
|
210
|
+
loginStateStorage['oidc.login.default'] = JSON.stringify(loginParams);
|
|
211
|
+
oidc.userInfoAsync.mockRejectedValueOnce(new Error('user info failed'));
|
|
212
|
+
let finishCleanup: () => void;
|
|
213
|
+
let pageStateBeforeCleanup: unknown;
|
|
214
|
+
const cleanupError = new Error('worker cleanup failed');
|
|
215
|
+
clearWorker.mockImplementationOnce(() => {
|
|
216
|
+
pageStateBeforeCleanup = {
|
|
217
|
+
tokens: oidc.tokens,
|
|
218
|
+
userInfo: oidc.userInfo,
|
|
219
|
+
timeoutId: oidc.timeoutId,
|
|
220
|
+
monitorStopCount: oidc.checkSessionIFrame.stop.mock.calls.length,
|
|
221
|
+
timerCount: vi.getTimerCount(),
|
|
222
|
+
};
|
|
223
|
+
return new Promise<void>((resolve, reject) => {
|
|
224
|
+
finishCleanup = () => (rejects ? reject(cleanupError) : resolve());
|
|
225
|
+
});
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
const restoring = restore();
|
|
229
|
+
const result = rejects
|
|
230
|
+
? expect(restoring).rejects.toBe(cleanupError)
|
|
231
|
+
: expect(restoring).resolves.toBe(false);
|
|
232
|
+
await vi.waitFor(() => expect(clearWorker).toHaveBeenCalledOnce());
|
|
233
|
+
finishCleanup();
|
|
234
|
+
await result;
|
|
235
|
+
|
|
236
|
+
expect(pageStateBeforeCleanup).toEqual({
|
|
237
|
+
tokens: null,
|
|
238
|
+
userInfo: null,
|
|
239
|
+
timeoutId: null,
|
|
240
|
+
monitorStopCount: 1,
|
|
241
|
+
timerCount: 0,
|
|
242
|
+
});
|
|
243
|
+
expect(oidc.tokens).toBeNull();
|
|
244
|
+
expect(oidc.userInfo).toBeNull();
|
|
245
|
+
expect(oidc.timeoutId).toBeNull();
|
|
246
|
+
expect(vi.getTimerCount()).toBe(0);
|
|
247
|
+
|
|
248
|
+
await expect(restore()).resolves.toBe(true);
|
|
249
|
+
expect(workers.initWorkerAsync).toHaveBeenCalledTimes(2);
|
|
250
|
+
expect(oidc.tokens).toEqual(tokens);
|
|
251
|
+
},
|
|
252
|
+
);
|
|
253
|
+
}
|
|
254
|
+
});
|