@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.
- package/README.md +226 -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 +1353 -873
- 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/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/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 +32 -16
- package/src/renewTokensError.spec.ts +111 -0
- 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
|
@@ -0,0 +1,708 @@
|
|
|
1
|
+
import { base64urlOfHashOfASCIIEncodingAsync } from './crypto';
|
|
2
|
+
import { eventNames } from './events';
|
|
3
|
+
import { initSession } from './initSession';
|
|
4
|
+
import { initWorkerAsync } from './initWorker';
|
|
5
|
+
import { generateJwtDemonstratingProofOfPossessionAsync } from './jwt';
|
|
6
|
+
import type { Oidc } from './oidc';
|
|
7
|
+
import {
|
|
8
|
+
createNetworkError,
|
|
9
|
+
createOAuthError,
|
|
10
|
+
isNetworkErrorCause,
|
|
11
|
+
isOidcError,
|
|
12
|
+
OidcError,
|
|
13
|
+
OidcErrorCode,
|
|
14
|
+
} from './oidcError';
|
|
15
|
+
import { isTokensOidcValid, isTokensValid, TokenRenewMode, Tokens } from './parseTokens';
|
|
16
|
+
import {
|
|
17
|
+
getContextResource,
|
|
18
|
+
getResourceConfiguration,
|
|
19
|
+
RESOURCE_TOKEN_REQUEST_HEADER,
|
|
20
|
+
} from './protocol';
|
|
21
|
+
import { performTokenRequestAsync } from './requests';
|
|
22
|
+
import {
|
|
23
|
+
cancelResourceTransactions,
|
|
24
|
+
RESOURCE_LOGIN_PARAMETER,
|
|
25
|
+
resourceContextName,
|
|
26
|
+
} from './resourceParameters';
|
|
27
|
+
import { _silentLoginAsync } from './silentLogin';
|
|
28
|
+
import timer from './timer';
|
|
29
|
+
import type { ResourceAccessToken, ResourceTokenOptions } from './types';
|
|
30
|
+
|
|
31
|
+
const unavailable = (message: string): OidcError =>
|
|
32
|
+
new OidcError(OidcErrorCode.RESOURCE_TOKEN_UNAVAILABLE, message, {
|
|
33
|
+
phase: 'refresh',
|
|
34
|
+
retryable: false,
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
interface ResourceTokenContext {
|
|
38
|
+
storage:
|
|
39
|
+
ReturnType<typeof initSession> | NonNullable<Awaited<ReturnType<typeof initWorkerAsync>>>;
|
|
40
|
+
tokens: Tokens | null;
|
|
41
|
+
server: Awaited<ReturnType<Oidc['initAsync']>>;
|
|
42
|
+
isWorker: boolean;
|
|
43
|
+
resourceContexts: string[];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export class ResourceTokens {
|
|
47
|
+
private readonly pending = new Map<string, Promise<ResourceAccessToken>>();
|
|
48
|
+
private readonly cached = new Map<string, Tokens>();
|
|
49
|
+
private readonly generations = new Map<string, number>();
|
|
50
|
+
private generation = 0;
|
|
51
|
+
private refreshQueue: Promise<unknown> = Promise.resolve();
|
|
52
|
+
private readonly renewalTimers = new Map<string, ReturnType<typeof timer.setTimeout>>();
|
|
53
|
+
|
|
54
|
+
constructor(private readonly oidc: Oidc) {}
|
|
55
|
+
|
|
56
|
+
private async contextAsync(resource?: string): Promise<ResourceTokenContext> {
|
|
57
|
+
const { oidc } = this;
|
|
58
|
+
const name = resourceContextName(oidc.configurationName, resource);
|
|
59
|
+
const server = await oidc.initAsync(
|
|
60
|
+
oidc.configuration.authority,
|
|
61
|
+
oidc.configuration.authority_configuration,
|
|
62
|
+
);
|
|
63
|
+
const worker = await initWorkerAsync(oidc.configuration, name);
|
|
64
|
+
const session = initSession(
|
|
65
|
+
name,
|
|
66
|
+
oidc.configuration.storage,
|
|
67
|
+
oidc.configuration.login_state_storage ?? oidc.configuration.storage,
|
|
68
|
+
);
|
|
69
|
+
const result = worker
|
|
70
|
+
? await worker.initAsync(server, 'resource-token', oidc.configuration)
|
|
71
|
+
: await session.initAsync();
|
|
72
|
+
const resourceContexts: string[] = [];
|
|
73
|
+
if ('resourceContexts' in result && result.resourceContexts !== undefined) {
|
|
74
|
+
if (
|
|
75
|
+
!Array.isArray(result.resourceContexts) ||
|
|
76
|
+
result.resourceContexts.some((value: unknown) => typeof value !== 'string')
|
|
77
|
+
) {
|
|
78
|
+
throw unavailable('The worker returned invalid resource context metadata.');
|
|
79
|
+
}
|
|
80
|
+
resourceContexts.push(...result.resourceContexts);
|
|
81
|
+
}
|
|
82
|
+
return {
|
|
83
|
+
storage: worker ?? session,
|
|
84
|
+
tokens: result.tokens as Tokens | null,
|
|
85
|
+
server,
|
|
86
|
+
isWorker: worker !== null,
|
|
87
|
+
resourceContexts,
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
private validate(
|
|
92
|
+
resource: string,
|
|
93
|
+
tokens: Tokens,
|
|
94
|
+
issuer: string,
|
|
95
|
+
subject: string | undefined = this.oidc.tokens?.idTokenPayload?.sub,
|
|
96
|
+
): void {
|
|
97
|
+
const { oidc } = this;
|
|
98
|
+
const configuration = getResourceConfiguration(oidc.configuration.resources, resource);
|
|
99
|
+
const context = tokens.resourceContext;
|
|
100
|
+
if (
|
|
101
|
+
!context ||
|
|
102
|
+
context.resource !== resource ||
|
|
103
|
+
context.issuer !== issuer ||
|
|
104
|
+
context.clientId !== oidc.configuration.client_id ||
|
|
105
|
+
context.configurationName !== oidc.configurationName ||
|
|
106
|
+
context.subject !== subject
|
|
107
|
+
) {
|
|
108
|
+
throw new OidcError(
|
|
109
|
+
OidcErrorCode.RESOURCE_CONTEXT_MISMATCH,
|
|
110
|
+
'The token does not belong to this resource and OIDC session.',
|
|
111
|
+
{ phase: 'refresh', retryable: false },
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
const payload = tokens.accessTokenPayload;
|
|
115
|
+
if (
|
|
116
|
+
(payload?.iss !== undefined && payload.iss !== issuer) ||
|
|
117
|
+
(payload &&
|
|
118
|
+
configuration.audiences &&
|
|
119
|
+
!configuration.audiences.some(audience =>
|
|
120
|
+
(typeof payload.aud === 'string'
|
|
121
|
+
? [payload.aud]
|
|
122
|
+
: Array.isArray(payload.aud)
|
|
123
|
+
? payload.aud
|
|
124
|
+
: []
|
|
125
|
+
).includes(audience),
|
|
126
|
+
))
|
|
127
|
+
) {
|
|
128
|
+
throw new OidcError(
|
|
129
|
+
OidcErrorCode.RESOURCE_CONTEXT_MISMATCH,
|
|
130
|
+
'Resource token issuer or configured audience does not match.',
|
|
131
|
+
{ phase: 'refresh', retryable: false },
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
if (
|
|
135
|
+
typeof tokens.accessToken !== 'string' ||
|
|
136
|
+
!tokens.accessToken ||
|
|
137
|
+
!Number.isFinite(tokens.expiresAt) ||
|
|
138
|
+
!Number.isFinite(tokens.issuedAt) ||
|
|
139
|
+
(tokens.refreshToken != null &&
|
|
140
|
+
(typeof tokens.refreshToken !== 'string' || !tokens.refreshToken))
|
|
141
|
+
) {
|
|
142
|
+
throw unavailable('The provider did not return a usable resource token response.');
|
|
143
|
+
}
|
|
144
|
+
if (
|
|
145
|
+
configuration.scope &&
|
|
146
|
+
!configuration.scope
|
|
147
|
+
.split(/\s+/)
|
|
148
|
+
.filter(Boolean)
|
|
149
|
+
.every(scope => (tokens.scope ?? '').split(/\s+/).includes(scope))
|
|
150
|
+
) {
|
|
151
|
+
throw unavailable('The provider did not grant the required resource scopes.');
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
private publicToken(resource: string, tokens: Tokens): ResourceAccessToken {
|
|
156
|
+
return {
|
|
157
|
+
resource,
|
|
158
|
+
issuer: tokens.resourceContext!.issuer,
|
|
159
|
+
clientId: this.oidc.configuration.client_id,
|
|
160
|
+
configurationName: this.oidc.configurationName,
|
|
161
|
+
accessToken: tokens.accessToken,
|
|
162
|
+
expiresAt: tokens.expiresAt,
|
|
163
|
+
scope: tokens.scope,
|
|
164
|
+
tokenType: tokens.tokenType,
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
private updateSharedRefreshToken(tokens: Tokens, isWorker: boolean): void {
|
|
169
|
+
if (typeof tokens.refreshToken !== 'string' || !tokens.refreshToken || !this.oidc.tokens)
|
|
170
|
+
return;
|
|
171
|
+
this.oidc.tokens = { ...this.oidc.tokens, refreshToken: tokens.refreshToken };
|
|
172
|
+
if (!isWorker)
|
|
173
|
+
initSession(this.oidc.configurationName, this.oidc.configuration.storage).setTokens(
|
|
174
|
+
this.oidc.tokens,
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
private scheduleRenewal(resource: string, tokens: Tokens): void {
|
|
179
|
+
const previous = this.renewalTimers.get(resource);
|
|
180
|
+
if (previous) timer.clearTimeout(previous);
|
|
181
|
+
if (this.oidc.configuration.token_automatic_renew_mode === 'AutomaticOnlyWhenFetchExecuted')
|
|
182
|
+
return;
|
|
183
|
+
const delay = Math.max(
|
|
184
|
+
1000,
|
|
185
|
+
Math.min(
|
|
186
|
+
2147483647,
|
|
187
|
+
(tokens.expiresAt - Date.now() / 1000 - this.renewalMargin(tokens)) * 1000,
|
|
188
|
+
),
|
|
189
|
+
);
|
|
190
|
+
const timeout = timer.setTimeout(async () => {
|
|
191
|
+
this.renewalTimers.delete(resource);
|
|
192
|
+
try {
|
|
193
|
+
await this.getAccessTokenAsync(resource, { forceRenew: true });
|
|
194
|
+
} catch (error) {
|
|
195
|
+
console.error(
|
|
196
|
+
'Resource renewal failed:',
|
|
197
|
+
isOidcError(error) ? error.code : 'unexpected error',
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
}, delay);
|
|
201
|
+
this.renewalTimers.set(resource, timeout);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
private renewalMargin(tokens: Tokens): number {
|
|
205
|
+
return Math.min(
|
|
206
|
+
this.oidc.configuration.refresh_time_before_tokens_expiration_in_second,
|
|
207
|
+
Math.max(0, (tokens.expiresAt - tokens.issuedAt) / 2),
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async withRefreshLockAsync<T>(operation: () => Promise<T>): Promise<T> {
|
|
212
|
+
const execute = async (): Promise<T> => {
|
|
213
|
+
if (navigator.locks) {
|
|
214
|
+
const configuration = this.oidc.configuration;
|
|
215
|
+
return navigator.locks.request(
|
|
216
|
+
`${configuration.client_id}_${this.oidc.configurationName}_${configuration.authority}`,
|
|
217
|
+
operation,
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
return operation();
|
|
221
|
+
};
|
|
222
|
+
const result = this.refreshQueue.then(execute, execute);
|
|
223
|
+
this.refreshQueue = result.then(
|
|
224
|
+
() => undefined,
|
|
225
|
+
() => undefined,
|
|
226
|
+
);
|
|
227
|
+
return result;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
async acceptAuthorizationAsync(resource: string, tokens: Tokens): Promise<void> {
|
|
231
|
+
const generation = this.generation;
|
|
232
|
+
const resourceGeneration = this.generations.get(resource) ?? 0;
|
|
233
|
+
const context = await this.contextAsync(resource);
|
|
234
|
+
const parent = await this.contextAsync();
|
|
235
|
+
if (
|
|
236
|
+
generation !== this.generation ||
|
|
237
|
+
resourceGeneration !== (this.generations.get(resource) ?? 0)
|
|
238
|
+
)
|
|
239
|
+
throw unavailable('The resource authorization was cleared.');
|
|
240
|
+
const subject = tokens.idTokenPayload?.sub;
|
|
241
|
+
if (
|
|
242
|
+
typeof subject !== 'string' ||
|
|
243
|
+
(this.oidc.tokens?.idTokenPayload?.sub ?? parent.tokens?.idTokenPayload?.sub) !== subject
|
|
244
|
+
) {
|
|
245
|
+
throw new OidcError(
|
|
246
|
+
OidcErrorCode.RESOURCE_CONTEXT_MISMATCH,
|
|
247
|
+
'Resource authorization must preserve the authenticated subject.',
|
|
248
|
+
{ phase: 'callback', retryable: false },
|
|
249
|
+
);
|
|
250
|
+
}
|
|
251
|
+
if (tokens.refreshToken && tokens.refreshToken === parent.tokens?.refreshToken) {
|
|
252
|
+
throw unavailable(
|
|
253
|
+
'The provider reused a refresh token across separate authorization transactions; use a multi-resource authorization grant instead.',
|
|
254
|
+
);
|
|
255
|
+
}
|
|
256
|
+
const entry: Tokens = {
|
|
257
|
+
...tokens,
|
|
258
|
+
scope:
|
|
259
|
+
tokens.scope ??
|
|
260
|
+
getResourceConfiguration(this.oidc.configuration.resources, resource).scope ??
|
|
261
|
+
this.oidc.configuration.scope,
|
|
262
|
+
resourceContext: {
|
|
263
|
+
resource,
|
|
264
|
+
issuer: context.server.issuer,
|
|
265
|
+
clientId: this.oidc.configuration.client_id,
|
|
266
|
+
configurationName: this.oidc.configurationName,
|
|
267
|
+
subject,
|
|
268
|
+
grantResource: resource,
|
|
269
|
+
},
|
|
270
|
+
};
|
|
271
|
+
this.validate(resource, entry, context.server.issuer, subject);
|
|
272
|
+
if (!context.isWorker)
|
|
273
|
+
initSession(
|
|
274
|
+
resourceContextName(this.oidc.configurationName, resource),
|
|
275
|
+
this.oidc.configuration.storage,
|
|
276
|
+
).setTokens(entry);
|
|
277
|
+
this.cached.set(resource, entry);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
getAccessTokenAsync(
|
|
281
|
+
resource: string,
|
|
282
|
+
options: ResourceTokenOptions = {},
|
|
283
|
+
): Promise<ResourceAccessToken> {
|
|
284
|
+
const existing = this.pending.get(resource);
|
|
285
|
+
if (existing) return existing;
|
|
286
|
+
const generation = this.generation;
|
|
287
|
+
const resourceGeneration = this.generations.get(resource) ?? 0;
|
|
288
|
+
const subject = this.oidc.tokens?.idTokenPayload?.sub;
|
|
289
|
+
const sessionNonce = this.oidc.tokens?.idTokenPayload?.nonce;
|
|
290
|
+
const isCurrent = (): boolean =>
|
|
291
|
+
this.generation === generation &&
|
|
292
|
+
(this.generations.get(resource) ?? 0) === resourceGeneration &&
|
|
293
|
+
!this.oidc.isLoggingOut &&
|
|
294
|
+
this.oidc.tokens?.idTokenPayload?.sub === subject &&
|
|
295
|
+
this.oidc.tokens?.idTokenPayload?.nonce === sessionNonce;
|
|
296
|
+
const operation = this.withRefreshLockAsync(async () => {
|
|
297
|
+
const { oidc } = this;
|
|
298
|
+
const configuration = getResourceConfiguration(oidc.configuration.resources, resource);
|
|
299
|
+
if (
|
|
300
|
+
!Number.isFinite(oidc.configuration.refresh_time_before_tokens_expiration_in_second) ||
|
|
301
|
+
oidc.configuration.refresh_time_before_tokens_expiration_in_second < 0
|
|
302
|
+
) {
|
|
303
|
+
throw unavailable('Configure a finite, non-negative renewal margin.');
|
|
304
|
+
}
|
|
305
|
+
if (!oidc.tokens || typeof oidc.tokens.idTokenPayload?.sub !== 'string' || !isCurrent()) {
|
|
306
|
+
throw unavailable('Sign in before requesting a resource token.');
|
|
307
|
+
}
|
|
308
|
+
if (
|
|
309
|
+
oidc.configuration.token_request_extras?.resource !== undefined &&
|
|
310
|
+
oidc.configuration.token_request_extras.resource !== resource
|
|
311
|
+
) {
|
|
312
|
+
throw new OidcError(
|
|
313
|
+
OidcErrorCode.INVALID_RESOURCE,
|
|
314
|
+
'Token extras conflict with the selected resource.',
|
|
315
|
+
{ phase: 'refresh', retryable: false },
|
|
316
|
+
);
|
|
317
|
+
}
|
|
318
|
+
let context = await this.contextAsync(resource);
|
|
319
|
+
const parent = await this.contextAsync();
|
|
320
|
+
if (!isCurrent()) throw unavailable('The resource transaction was cleared.');
|
|
321
|
+
const parentNonce = parent.tokens?.idTokenPayload?.nonce;
|
|
322
|
+
if (
|
|
323
|
+
!parent.tokens ||
|
|
324
|
+
parent.tokens.idTokenPayload?.sub !== subject ||
|
|
325
|
+
(!parent.isWorker && parentNonce !== oidc.tokens.idTokenPayload?.nonce)
|
|
326
|
+
) {
|
|
327
|
+
throw unavailable(
|
|
328
|
+
'The original OIDC session changed or is unavailable; restore it before requesting resource tokens.',
|
|
329
|
+
);
|
|
330
|
+
}
|
|
331
|
+
let tokens = context.tokens;
|
|
332
|
+
if (tokens) {
|
|
333
|
+
this.validate(resource, tokens, context.server.issuer);
|
|
334
|
+
if (!options.forceRenew && isTokensValid(tokens, this.renewalMargin(tokens))) {
|
|
335
|
+
const previous = this.cached.get(resource);
|
|
336
|
+
this.cached.set(resource, tokens);
|
|
337
|
+
this.scheduleRenewal(resource, tokens);
|
|
338
|
+
if (
|
|
339
|
+
previous?.accessToken !== tokens.accessToken ||
|
|
340
|
+
previous?.expiresAt !== tokens.expiresAt ||
|
|
341
|
+
previous?.scope !== tokens.scope ||
|
|
342
|
+
previous?.tokenType !== tokens.tokenType
|
|
343
|
+
) {
|
|
344
|
+
oidc.publishEvent(eventNames.resource_token_acquired, { resource });
|
|
345
|
+
}
|
|
346
|
+
return this.publicToken(resource, tokens);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
const configuredResources =
|
|
350
|
+
typeof oidc.configuration.resource === 'string'
|
|
351
|
+
? [oidc.configuration.resource]
|
|
352
|
+
: (oidc.configuration.resource ?? []);
|
|
353
|
+
const grantedScopes = (parent.tokens.scope ?? oidc.configuration.scope).split(/\s+/);
|
|
354
|
+
const scopeWithinGrant =
|
|
355
|
+
!configuration.scope ||
|
|
356
|
+
configuration.scope
|
|
357
|
+
.split(/\s+/)
|
|
358
|
+
.filter(Boolean)
|
|
359
|
+
.every(scope => grantedScopes.includes(scope));
|
|
360
|
+
const grantResource = tokens?.resourceContext
|
|
361
|
+
? tokens.resourceContext.grantResource
|
|
362
|
+
: configuredResources.includes(resource) && scopeWithinGrant
|
|
363
|
+
? null
|
|
364
|
+
: resource;
|
|
365
|
+
const source = grantResource === null ? await this.contextAsync() : context;
|
|
366
|
+
const refreshToken =
|
|
367
|
+
grantResource === null && !scopeWithinGrant ? undefined : source.tokens?.refreshToken;
|
|
368
|
+
const isDpop =
|
|
369
|
+
oidc.configuration.demonstrating_proof_of_possession ||
|
|
370
|
+
source.tokens?.tokenType?.toLowerCase() === 'dpop';
|
|
371
|
+
if (!isCurrent()) throw unavailable('The resource transaction was cleared.');
|
|
372
|
+
if (refreshToken) {
|
|
373
|
+
const nonce = await source.storage.getNonceAsync();
|
|
374
|
+
const headers: Record<string, string> = context.isWorker
|
|
375
|
+
? { [RESOURCE_TOKEN_REQUEST_HEADER]: encodeURIComponent(resource) }
|
|
376
|
+
: {};
|
|
377
|
+
if (isDpop) {
|
|
378
|
+
headers.DPoP = await this.generateProofAsync(resource, {
|
|
379
|
+
accessToken: source.tokens.accessToken,
|
|
380
|
+
url: context.server.tokenEndpoint,
|
|
381
|
+
method: 'POST',
|
|
382
|
+
grantResource,
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
const details = {
|
|
386
|
+
client_id: oidc.configuration.client_id,
|
|
387
|
+
grant_type: 'refresh_token',
|
|
388
|
+
refresh_token: refreshToken,
|
|
389
|
+
resource,
|
|
390
|
+
...(configuration.scope ? { scope: configuration.scope } : {}),
|
|
391
|
+
};
|
|
392
|
+
const request = () =>
|
|
393
|
+
performTokenRequestAsync(oidc.getFetch())(
|
|
394
|
+
context.server.tokenEndpoint,
|
|
395
|
+
details,
|
|
396
|
+
oidc.configuration.token_request_extras ?? {},
|
|
397
|
+
tokens,
|
|
398
|
+
headers,
|
|
399
|
+
TokenRenewMode.access_token_invalid,
|
|
400
|
+
oidc.configuration.token_request_timeout,
|
|
401
|
+
);
|
|
402
|
+
let response = await request();
|
|
403
|
+
if (
|
|
404
|
+
!response.success &&
|
|
405
|
+
response.oauthError === 'use_dpop_nonce' &&
|
|
406
|
+
response.demonstratingProofOfPossessionNonce &&
|
|
407
|
+
isDpop
|
|
408
|
+
) {
|
|
409
|
+
await source.storage.setDemonstratingProofOfPossessionNonce(
|
|
410
|
+
response.demonstratingProofOfPossessionNonce,
|
|
411
|
+
);
|
|
412
|
+
headers.DPoP = await this.generateProofAsync(resource, {
|
|
413
|
+
accessToken: source.tokens.accessToken,
|
|
414
|
+
url: context.server.tokenEndpoint,
|
|
415
|
+
method: 'POST',
|
|
416
|
+
grantResource,
|
|
417
|
+
});
|
|
418
|
+
response = await request();
|
|
419
|
+
}
|
|
420
|
+
if (response.success) {
|
|
421
|
+
const currentParent = await this.contextAsync();
|
|
422
|
+
if (
|
|
423
|
+
!currentParent.tokens ||
|
|
424
|
+
currentParent.tokens.idTokenPayload?.sub !== subject ||
|
|
425
|
+
(!currentParent.isWorker && currentParent.tokens.idTokenPayload?.nonce !== parentNonce)
|
|
426
|
+
) {
|
|
427
|
+
throw unavailable('The original OIDC session changed during resource renewal.');
|
|
428
|
+
}
|
|
429
|
+
tokens = response.data;
|
|
430
|
+
const isSameSession =
|
|
431
|
+
this.generation === generation &&
|
|
432
|
+
oidc.tokens?.idTokenPayload?.sub === subject &&
|
|
433
|
+
oidc.tokens?.idTokenPayload?.nonce === sessionNonce;
|
|
434
|
+
if (isSameSession && grantResource === null)
|
|
435
|
+
this.updateSharedRefreshToken(tokens, context.isWorker);
|
|
436
|
+
if (tokens.idTokenPayload?.sub !== undefined && tokens.idTokenPayload.sub !== subject) {
|
|
437
|
+
throw new OidcError(
|
|
438
|
+
OidcErrorCode.RESOURCE_CONTEXT_MISMATCH,
|
|
439
|
+
'Resource renewal changed the authenticated subject.',
|
|
440
|
+
{ phase: 'refresh', retryable: false },
|
|
441
|
+
);
|
|
442
|
+
}
|
|
443
|
+
const valid = isTokensOidcValid(tokens, nonce?.nonce, context.server);
|
|
444
|
+
if (!valid.isValid) throw unavailable(valid.reason);
|
|
445
|
+
tokens = {
|
|
446
|
+
...tokens,
|
|
447
|
+
scope:
|
|
448
|
+
tokens.scope ??
|
|
449
|
+
configuration.scope ??
|
|
450
|
+
source.tokens.scope ??
|
|
451
|
+
oidc.configuration.scope,
|
|
452
|
+
resourceContext: {
|
|
453
|
+
resource,
|
|
454
|
+
issuer: context.server.issuer,
|
|
455
|
+
clientId: oidc.configuration.client_id,
|
|
456
|
+
configurationName: oidc.configurationName,
|
|
457
|
+
subject,
|
|
458
|
+
grantResource,
|
|
459
|
+
},
|
|
460
|
+
};
|
|
461
|
+
this.validate(resource, tokens, context.server.issuer, subject);
|
|
462
|
+
if (!isCurrent()) {
|
|
463
|
+
if (isSameSession) {
|
|
464
|
+
if (
|
|
465
|
+
oidc.isLoggingOut &&
|
|
466
|
+
resourceGeneration === (this.generations.get(resource) ?? 0) &&
|
|
467
|
+
!context.isWorker
|
|
468
|
+
) {
|
|
469
|
+
initSession(
|
|
470
|
+
resourceContextName(oidc.configurationName, resource),
|
|
471
|
+
oidc.configuration.storage,
|
|
472
|
+
).setTokens(tokens);
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
throw unavailable('The resource transaction was cleared.');
|
|
476
|
+
}
|
|
477
|
+
if (response.demonstratingProofOfPossessionNonce)
|
|
478
|
+
await source.storage.setDemonstratingProofOfPossessionNonce(
|
|
479
|
+
response.demonstratingProofOfPossessionNonce,
|
|
480
|
+
);
|
|
481
|
+
if (!context.isWorker) {
|
|
482
|
+
initSession(
|
|
483
|
+
resourceContextName(oidc.configurationName, resource),
|
|
484
|
+
oidc.configuration.storage,
|
|
485
|
+
).setTokens(tokens);
|
|
486
|
+
}
|
|
487
|
+
if (grantResource === null) this.updateSharedRefreshToken(tokens, context.isWorker);
|
|
488
|
+
} else if (response.oauthError !== 'invalid_grant') {
|
|
489
|
+
throw createOAuthError(
|
|
490
|
+
response.oauthError,
|
|
491
|
+
response.oauthErrorDescription,
|
|
492
|
+
'Resource token request failed.',
|
|
493
|
+
'refresh',
|
|
494
|
+
response.status,
|
|
495
|
+
);
|
|
496
|
+
} else {
|
|
497
|
+
tokens = null;
|
|
498
|
+
}
|
|
499
|
+
} else {
|
|
500
|
+
tokens = null;
|
|
501
|
+
}
|
|
502
|
+
if (!tokens) {
|
|
503
|
+
if (!isCurrent()) throw unavailable('The resource transaction was cleared.');
|
|
504
|
+
const scope = configuration.scope
|
|
505
|
+
? [...new Set(['openid', ...configuration.scope.split(' ')])].join(' ')
|
|
506
|
+
: oidc.configuration.scope;
|
|
507
|
+
const response = await _silentLoginAsync(
|
|
508
|
+
oidc.configurationName,
|
|
509
|
+
oidc.configuration,
|
|
510
|
+
oidc.publishEvent.bind(oidc),
|
|
511
|
+
'refresh',
|
|
512
|
+
)(
|
|
513
|
+
{
|
|
514
|
+
...oidc.configuration.extras,
|
|
515
|
+
prompt: 'none',
|
|
516
|
+
resource,
|
|
517
|
+
[RESOURCE_LOGIN_PARAMETER]: resource,
|
|
518
|
+
},
|
|
519
|
+
null,
|
|
520
|
+
scope,
|
|
521
|
+
);
|
|
522
|
+
if (!response)
|
|
523
|
+
throw unavailable(
|
|
524
|
+
'Configure silent_redirect_uri and silent_login_uri for resource authorization.',
|
|
525
|
+
);
|
|
526
|
+
if (response.error)
|
|
527
|
+
throw (
|
|
528
|
+
response.oidcError ??
|
|
529
|
+
createOAuthError(
|
|
530
|
+
response.error,
|
|
531
|
+
undefined,
|
|
532
|
+
'Resource silent authorization failed.',
|
|
533
|
+
'refresh',
|
|
534
|
+
)
|
|
535
|
+
);
|
|
536
|
+
if (!isCurrent() || response.resource !== resource)
|
|
537
|
+
throw unavailable('The resource authorization transaction is no longer current.');
|
|
538
|
+
await this.acceptAuthorizationAsync(resource, response.tokens);
|
|
539
|
+
context = await this.contextAsync(resource);
|
|
540
|
+
tokens = context.tokens ?? this.cached.get(resource);
|
|
541
|
+
}
|
|
542
|
+
if (!isCurrent()) throw unavailable('The resource transaction was cleared.');
|
|
543
|
+
this.validate(resource, tokens, context.server.issuer);
|
|
544
|
+
if (!isTokensValid(tokens)) throw unavailable('The resource access token is expired.');
|
|
545
|
+
this.cached.set(resource, tokens);
|
|
546
|
+
this.scheduleRenewal(resource, tokens);
|
|
547
|
+
oidc.publishEvent(eventNames.resource_token_acquired, { resource });
|
|
548
|
+
return this.publicToken(resource, tokens);
|
|
549
|
+
});
|
|
550
|
+
const result = operation
|
|
551
|
+
.catch(cause => {
|
|
552
|
+
const error = isOidcError(cause)
|
|
553
|
+
? cause
|
|
554
|
+
: isNetworkErrorCause(cause)
|
|
555
|
+
? createNetworkError(cause, 'refresh')
|
|
556
|
+
: new OidcError(
|
|
557
|
+
OidcErrorCode.RESOURCE_TOKEN_UNAVAILABLE,
|
|
558
|
+
cause instanceof Error ? cause.message : 'Resource token acquisition failed.',
|
|
559
|
+
{ phase: 'refresh', retryable: false, cause },
|
|
560
|
+
);
|
|
561
|
+
this.oidc.publishEvent(eventNames.resource_token_error, { resource, error });
|
|
562
|
+
throw error;
|
|
563
|
+
})
|
|
564
|
+
.finally(() => {
|
|
565
|
+
if (this.pending.get(resource) === result) this.pending.delete(resource);
|
|
566
|
+
});
|
|
567
|
+
this.pending.set(resource, result);
|
|
568
|
+
return result;
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
async generateProofAsync(
|
|
572
|
+
resource: string,
|
|
573
|
+
input: { accessToken: string; url: string; method: string; grantResource?: string | null },
|
|
574
|
+
): Promise<string> {
|
|
575
|
+
const cachedContext = this.cached.get(resource)?.resourceContext;
|
|
576
|
+
const grantResource =
|
|
577
|
+
input.grantResource === undefined
|
|
578
|
+
? cachedContext
|
|
579
|
+
? cachedContext.grantResource
|
|
580
|
+
: resource
|
|
581
|
+
: input.grantResource;
|
|
582
|
+
const context = await this.contextAsync(grantResource ?? undefined);
|
|
583
|
+
if (context.isWorker)
|
|
584
|
+
return `DPOP_SECURED_BY_OIDC_SERVICE_WORKER_${resourceContextName(this.oidc.configurationName, resource)}`;
|
|
585
|
+
const key = await context.storage.getDemonstratingProofOfPossessionJwkAsync();
|
|
586
|
+
if (!key) throw unavailable('The resource DPoP grant key is unavailable.');
|
|
587
|
+
const nonce =
|
|
588
|
+
input.url === context.server.tokenEndpoint
|
|
589
|
+
? await context.storage.getDemonstratingProofOfPossessionNonce()
|
|
590
|
+
: initSession(
|
|
591
|
+
resourceContextName(this.oidc.configurationName, resource),
|
|
592
|
+
this.oidc.configuration.storage,
|
|
593
|
+
).getDemonstratingProofOfPossessionApiNonce();
|
|
594
|
+
return generateJwtDemonstratingProofOfPossessionAsync(window)(
|
|
595
|
+
this.oidc.configuration.demonstrating_proof_of_possession_configuration,
|
|
596
|
+
)(key, input.method, input.url, {
|
|
597
|
+
ath: await base64urlOfHashOfASCIIEncodingAsync(input.accessToken),
|
|
598
|
+
...(nonce ? { nonce } : {}),
|
|
599
|
+
});
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
peek(resource: string): ResourceAccessToken | null {
|
|
603
|
+
if (this.oidc.isLoggingOut) return null;
|
|
604
|
+
const tokens = this.cached.get(resource);
|
|
605
|
+
return tokens &&
|
|
606
|
+
tokens.resourceContext?.subject === this.oidc.tokens?.idTokenPayload?.sub &&
|
|
607
|
+
isTokensValid(tokens)
|
|
608
|
+
? this.publicToken(resource, tokens)
|
|
609
|
+
: null;
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
createApiNonceRecorder(resource: string): (nonce: string) => Promise<void> {
|
|
613
|
+
const generation = this.generation;
|
|
614
|
+
const resourceGeneration = this.generations.get(resource) ?? 0;
|
|
615
|
+
return async (nonce: string): Promise<void> => {
|
|
616
|
+
if (
|
|
617
|
+
generation !== this.generation ||
|
|
618
|
+
resourceGeneration !== (this.generations.get(resource) ?? 0) ||
|
|
619
|
+
!this.peek(resource)
|
|
620
|
+
) {
|
|
621
|
+
console.warn('Ignoring a resource API nonce response after its session was cleared.');
|
|
622
|
+
return;
|
|
623
|
+
}
|
|
624
|
+
if (!this.oidc.configuration.service_worker_relative_url) {
|
|
625
|
+
await initSession(
|
|
626
|
+
resourceContextName(this.oidc.configurationName, resource),
|
|
627
|
+
this.oidc.configuration.storage,
|
|
628
|
+
).setDemonstratingProofOfPossessionApiNonce(nonce);
|
|
629
|
+
}
|
|
630
|
+
};
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
async getTokensToRevokeAsync(): Promise<Tokens[]> {
|
|
634
|
+
if (!this.oidc.configuration.resources?.length) return [];
|
|
635
|
+
const base = await this.contextAsync();
|
|
636
|
+
const resources = base.isWorker
|
|
637
|
+
? base.resourceContexts
|
|
638
|
+
.map(getContextResource)
|
|
639
|
+
.filter((resource): resource is string => resource !== undefined)
|
|
640
|
+
: this.oidc.configuration.resources.map(configuration => configuration.resource);
|
|
641
|
+
const entries: Tokens[] = [];
|
|
642
|
+
for (const resource of resources) {
|
|
643
|
+
const context = await this.contextAsync(resource);
|
|
644
|
+
if (context.tokens) {
|
|
645
|
+
this.validate(resource, context.tokens, context.server.issuer);
|
|
646
|
+
entries.push(context.tokens);
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
return entries;
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
async clearAsync(resource: string): Promise<void> {
|
|
653
|
+
getResourceConfiguration(this.oidc.configuration.resources, resource);
|
|
654
|
+
this.generations.set(resource, (this.generations.get(resource) ?? 0) + 1);
|
|
655
|
+
cancelResourceTransactions(this.oidc.configurationName, resource);
|
|
656
|
+
this.pending.delete(resource);
|
|
657
|
+
this.cached.delete(resource);
|
|
658
|
+
const timeout = this.renewalTimers.get(resource);
|
|
659
|
+
if (timeout) timer.clearTimeout(timeout);
|
|
660
|
+
this.renewalTimers.delete(resource);
|
|
661
|
+
const context = await this.contextAsync(resource);
|
|
662
|
+
await context.storage.clearAsync('LOGGED_OUT');
|
|
663
|
+
context.storage.setLoginParams(null);
|
|
664
|
+
if (!context.isWorker) {
|
|
665
|
+
await initSession(
|
|
666
|
+
resourceContextName(this.oidc.configurationName, resource),
|
|
667
|
+
this.oidc.configuration.storage,
|
|
668
|
+
).setDemonstratingProofOfPossessionApiNonce(null);
|
|
669
|
+
await Promise.all([
|
|
670
|
+
context.storage.setStateAsync(null),
|
|
671
|
+
context.storage.setCodeVerifierAsync(null),
|
|
672
|
+
context.storage.setNonceAsync(null),
|
|
673
|
+
context.storage.setDemonstratingProofOfPossessionJwkAsync(null),
|
|
674
|
+
context.storage.setDemonstratingProofOfPossessionNonce(null),
|
|
675
|
+
]);
|
|
676
|
+
}
|
|
677
|
+
this.oidc.publishEvent(eventNames.resource_token_cleared, { resource });
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
async clearAllAsync(): Promise<void> {
|
|
681
|
+
if (!this.oidc.configuration.resources?.length) return;
|
|
682
|
+
this.generation++;
|
|
683
|
+
cancelResourceTransactions(this.oidc.configurationName);
|
|
684
|
+
this.pending.clear();
|
|
685
|
+
this.cached.clear();
|
|
686
|
+
for (const timeout of this.renewalTimers.values()) timer.clearTimeout(timeout);
|
|
687
|
+
this.renewalTimers.clear();
|
|
688
|
+
if (!this.oidc.configuration.service_worker_relative_url) {
|
|
689
|
+
for (const configuration of this.oidc.configuration.resources ?? []) {
|
|
690
|
+
const session = initSession(
|
|
691
|
+
resourceContextName(this.oidc.configurationName, configuration.resource),
|
|
692
|
+
this.oidc.configuration.storage,
|
|
693
|
+
this.oidc.configuration.login_state_storage ?? this.oidc.configuration.storage,
|
|
694
|
+
);
|
|
695
|
+
await session.clearAsync('LOGGED_OUT');
|
|
696
|
+
session.setLoginParams(null);
|
|
697
|
+
await Promise.all([
|
|
698
|
+
session.setStateAsync(null),
|
|
699
|
+
session.setCodeVerifierAsync(null),
|
|
700
|
+
session.setNonceAsync(null),
|
|
701
|
+
session.setDemonstratingProofOfPossessionJwkAsync(null),
|
|
702
|
+
session.setDemonstratingProofOfPossessionNonce(null),
|
|
703
|
+
session.setDemonstratingProofOfPossessionApiNonce(null),
|
|
704
|
+
]);
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
}
|