@baukit/auth-web 0.10.32 → 0.11.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 +122 -1
- package/dist/index.d.ts +3 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -72
- package/dist/index.js.map +1 -1
- package/dist/oidc-helpers.d.ts +11 -0
- package/dist/oidc-helpers.d.ts.map +1 -0
- package/dist/oidc-helpers.js +73 -0
- package/dist/oidc-helpers.js.map +1 -0
- package/dist/silent-token-broker.d.ts +83 -0
- package/dist/silent-token-broker.d.ts.map +1 -0
- package/dist/silent-token-broker.js +386 -0
- package/dist/silent-token-broker.js.map +1 -0
- package/dist/silent-token-browser.d.ts +6 -0
- package/dist/silent-token-browser.d.ts.map +1 -0
- package/dist/silent-token-browser.js +84 -0
- package/dist/silent-token-browser.js.map +1 -0
- package/dist/silent-token-errors.d.ts +7 -0
- package/dist/silent-token-errors.d.ts.map +1 -0
- package/dist/silent-token-errors.js +10 -0
- package/dist/silent-token-errors.js.map +1 -0
- package/package.json +7 -3
- package/src/index.ts +14 -85
- package/src/oidc-helpers.ts +89 -0
- package/src/silent-token-broker.test.ts +900 -0
- package/src/silent-token-broker.ts +527 -0
- package/src/silent-token-browser.test.ts +161 -0
- package/src/silent-token-browser.ts +92 -0
- package/src/silent-token-errors.ts +29 -0
|
@@ -0,0 +1,527 @@
|
|
|
1
|
+
import { createLocalJWKSet, jwtVerify, type JSONWebKeySet } from 'jose';
|
|
2
|
+
import {
|
|
3
|
+
base64UrlEncode,
|
|
4
|
+
buildAuthorizationUrl,
|
|
5
|
+
normalizeIssuer,
|
|
6
|
+
normalizeScopes,
|
|
7
|
+
randomUrlSafe,
|
|
8
|
+
} from './oidc-helpers.js';
|
|
9
|
+
import { openSilentAuthorizationWindow } from './silent-token-browser.js';
|
|
10
|
+
import { SilentTokenError } from './silent-token-errors.js';
|
|
11
|
+
|
|
12
|
+
export { SilentTokenError, type SilentTokenErrorCode } from './silent-token-errors.js';
|
|
13
|
+
|
|
14
|
+
export interface SilentTokenProduct {
|
|
15
|
+
readonly id: string;
|
|
16
|
+
readonly issuer: string;
|
|
17
|
+
readonly clientId: string;
|
|
18
|
+
readonly audience: string;
|
|
19
|
+
readonly redirectUri: string;
|
|
20
|
+
/** Defaults to `openid`, which is always included. */
|
|
21
|
+
readonly scopes?: readonly string[];
|
|
22
|
+
/** Provider options, such as an identity provider hint. Cannot override OIDC parameters. */
|
|
23
|
+
readonly authorizationParams?: Readonly<Record<string, string>>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface SilentTokenBrokerOptions {
|
|
27
|
+
/** A signed access token claim that binds each product account to the active session. */
|
|
28
|
+
readonly accountBinding: { readonly claim: string; readonly value: string };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export type SilentLoginReason =
|
|
32
|
+
'login_required' | 'interaction_required' | 'interaction_cancelled' | 'timeout';
|
|
33
|
+
|
|
34
|
+
export type SilentTokenResult =
|
|
35
|
+
| {
|
|
36
|
+
readonly status: 'ok';
|
|
37
|
+
readonly productId: string;
|
|
38
|
+
readonly accessToken: string;
|
|
39
|
+
readonly expiresAt: number;
|
|
40
|
+
}
|
|
41
|
+
| {
|
|
42
|
+
readonly status: 'login_required';
|
|
43
|
+
readonly productId: string;
|
|
44
|
+
readonly reason: SilentLoginReason;
|
|
45
|
+
}
|
|
46
|
+
| { readonly status: 'consent_required'; readonly productId: string }
|
|
47
|
+
| { readonly status: 'account_mismatch'; readonly productId: string }
|
|
48
|
+
| { readonly status: 'error'; readonly productId: string; readonly error: SilentTokenError };
|
|
49
|
+
|
|
50
|
+
type AuthorizationFailure = SilentLoginReason | 'consent_required' | 'account_mismatch';
|
|
51
|
+
|
|
52
|
+
class AuthorizationError extends Error {
|
|
53
|
+
public constructor(public readonly code: AuthorizationFailure) {
|
|
54
|
+
super(code);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface SilentAuthorizationWindow {
|
|
59
|
+
/** True when the interactive popup has closed. Omit if closure cannot be observed. */
|
|
60
|
+
readonly closed?: boolean;
|
|
61
|
+
receive(url: URL, signal: AbortSignal): Promise<string>;
|
|
62
|
+
close(): void;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface SilentTokenEnvironment {
|
|
66
|
+
readonly fetch: typeof globalThis.fetch;
|
|
67
|
+
readonly crypto: Crypto;
|
|
68
|
+
readonly now: () => number;
|
|
69
|
+
/** Must open interactive windows synchronously, before returning. */
|
|
70
|
+
readonly open: (interactive: boolean) => SilentAuthorizationWindow;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
interface Metadata {
|
|
74
|
+
readonly authorizationEndpoint: string;
|
|
75
|
+
readonly tokenEndpoint: string;
|
|
76
|
+
readonly jwksUri: string;
|
|
77
|
+
}
|
|
78
|
+
interface CachedToken {
|
|
79
|
+
readonly result: Extract<SilentTokenResult, { status: 'ok' }>;
|
|
80
|
+
readonly renewAt: number;
|
|
81
|
+
}
|
|
82
|
+
interface TokenResponse {
|
|
83
|
+
readonly accessToken: string;
|
|
84
|
+
readonly idToken: string;
|
|
85
|
+
readonly responseExpiresAt: number;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const SILENT_TIMEOUT_MS = 15_000;
|
|
89
|
+
const INTERACTIVE_TIMEOUT_MS = 180_000;
|
|
90
|
+
const POPUP_POLL_INTERVAL_MS = 250;
|
|
91
|
+
const EXPIRY_LEEWAY_MS = 30_000;
|
|
92
|
+
const RESERVED_PARAMETERS = new Set([
|
|
93
|
+
'client_id',
|
|
94
|
+
'redirect_uri',
|
|
95
|
+
'response_type',
|
|
96
|
+
'response_mode',
|
|
97
|
+
'scope',
|
|
98
|
+
'state',
|
|
99
|
+
'nonce',
|
|
100
|
+
'code_challenge',
|
|
101
|
+
'code_challenge_method',
|
|
102
|
+
'prompt',
|
|
103
|
+
'audience',
|
|
104
|
+
'resource',
|
|
105
|
+
]);
|
|
106
|
+
|
|
107
|
+
/** One instance belongs to one active session. Dispose it before changing identity. */
|
|
108
|
+
export class SilentTokenBroker {
|
|
109
|
+
private readonly products = new Map<string, SilentTokenProduct>();
|
|
110
|
+
private readonly cache = new Map<string, CachedToken>();
|
|
111
|
+
private readonly pending = new Map<string, Promise<SilentTokenResult>>();
|
|
112
|
+
private readonly failures = new Map<string, SilentTokenResult>();
|
|
113
|
+
private readonly controllers = new Set<AbortController>();
|
|
114
|
+
private readonly accountBinding: SilentTokenBrokerOptions['accountBinding'];
|
|
115
|
+
private disposed = false;
|
|
116
|
+
|
|
117
|
+
public constructor(
|
|
118
|
+
products: readonly SilentTokenProduct[],
|
|
119
|
+
options: SilentTokenBrokerOptions,
|
|
120
|
+
private readonly environment: SilentTokenEnvironment = browserEnvironment(),
|
|
121
|
+
) {
|
|
122
|
+
if (!options.accountBinding.claim.trim() || !options.accountBinding.value.trim()) {
|
|
123
|
+
throw new SilentTokenError('invalid_account_binding');
|
|
124
|
+
}
|
|
125
|
+
this.accountBinding = { ...options.accountBinding };
|
|
126
|
+
for (const product of products) {
|
|
127
|
+
if (
|
|
128
|
+
this.products.has(product.id) ||
|
|
129
|
+
!product.id.trim() ||
|
|
130
|
+
!product.clientId.trim() ||
|
|
131
|
+
!product.audience.trim()
|
|
132
|
+
) {
|
|
133
|
+
throw new SilentTokenError('invalid_product');
|
|
134
|
+
}
|
|
135
|
+
trustedUrl(product.issuer);
|
|
136
|
+
const redirectUri = trustedUrl(product.redirectUri).toString();
|
|
137
|
+
const authorizationParams = { ...product.authorizationParams };
|
|
138
|
+
for (const [key, value] of Object.entries(authorizationParams)) {
|
|
139
|
+
if (!key.trim() || RESERVED_PARAMETERS.has(key) || !value.trim()) {
|
|
140
|
+
throw new SilentTokenError('invalid_product');
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
this.products.set(product.id, {
|
|
144
|
+
...product,
|
|
145
|
+
issuer: normalizeIssuer(product.issuer),
|
|
146
|
+
clientId: product.clientId.trim(),
|
|
147
|
+
audience: product.audience.trim(),
|
|
148
|
+
redirectUri,
|
|
149
|
+
scopes: normalizeScopes(product.scopes ?? ['openid']),
|
|
150
|
+
authorizationParams,
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
public getToken(productId: string, audience?: string): Promise<SilentTokenResult> {
|
|
156
|
+
const product = this.product(productId, audience);
|
|
157
|
+
const cached = this.cache.get(product.id);
|
|
158
|
+
if (cached && cached.renewAt > this.environment.now()) return Promise.resolve(cached.result);
|
|
159
|
+
this.cache.delete(product.id);
|
|
160
|
+
const pending = this.pending.get(product.id);
|
|
161
|
+
if (pending) return pending;
|
|
162
|
+
const failure = this.failures.get(product.id);
|
|
163
|
+
return failure ? Promise.resolve(failure) : this.start(product, false);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Call directly from a user gesture. Opens a popup before any asynchronous work. */
|
|
167
|
+
public login(productId: string): Promise<SilentTokenResult> {
|
|
168
|
+
const product = this.product(productId);
|
|
169
|
+
return this.pending.get(product.id) ?? this.start(product, true);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Discards a token after an API rejection. Remembered failures remain latched. */
|
|
173
|
+
public invalidate(productId: string): void {
|
|
174
|
+
this.cache.delete(this.product(productId).id);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Allows the next getToken() to retry a remembered failure. Does not start work. */
|
|
178
|
+
public resetFailure(productId: string): void {
|
|
179
|
+
this.failures.delete(this.product(productId).id);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
public dispose(): void {
|
|
183
|
+
this.disposed = true;
|
|
184
|
+
for (const controller of this.controllers) controller.abort(new SilentTokenError('disposed'));
|
|
185
|
+
this.controllers.clear();
|
|
186
|
+
this.cache.clear();
|
|
187
|
+
this.failures.clear();
|
|
188
|
+
this.pending.clear();
|
|
189
|
+
this.products.clear();
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
private product(id: string, audience?: string): SilentTokenProduct {
|
|
193
|
+
if (this.disposed) throw new SilentTokenError('disposed');
|
|
194
|
+
const product = this.products.get(id);
|
|
195
|
+
if (!product || (audience !== undefined && product.audience !== audience)) {
|
|
196
|
+
throw new SilentTokenError('unknown_product_or_audience');
|
|
197
|
+
}
|
|
198
|
+
return product;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
private start(product: SilentTokenProduct, interactive: boolean): Promise<SilentTokenResult> {
|
|
202
|
+
this.cache.delete(product.id);
|
|
203
|
+
const pending = this.authorize(product, interactive)
|
|
204
|
+
.then((result) => {
|
|
205
|
+
if (this.disposed) return failureResult(product.id, new SilentTokenError('disposed'));
|
|
206
|
+
if (result.status === 'ok') {
|
|
207
|
+
const lifetime = result.expiresAt - this.environment.now();
|
|
208
|
+
this.cache.set(product.id, {
|
|
209
|
+
result,
|
|
210
|
+
renewAt: result.expiresAt - Math.min(EXPIRY_LEEWAY_MS, lifetime / 2),
|
|
211
|
+
});
|
|
212
|
+
this.failures.delete(product.id);
|
|
213
|
+
} else {
|
|
214
|
+
const previous = this.failures.get(product.id);
|
|
215
|
+
if (!previous || result.status !== 'error' || result.error.code !== 'popup_blocked')
|
|
216
|
+
this.failures.set(product.id, result);
|
|
217
|
+
}
|
|
218
|
+
return result;
|
|
219
|
+
})
|
|
220
|
+
.finally(() => {
|
|
221
|
+
this.pending.delete(product.id);
|
|
222
|
+
});
|
|
223
|
+
this.pending.set(product.id, pending);
|
|
224
|
+
return pending;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
private async authorize(
|
|
228
|
+
product: SilentTokenProduct,
|
|
229
|
+
interactive: boolean,
|
|
230
|
+
): Promise<SilentTokenResult> {
|
|
231
|
+
const controller = new AbortController();
|
|
232
|
+
this.controllers.add(controller);
|
|
233
|
+
const timer = setTimeout(
|
|
234
|
+
() => {
|
|
235
|
+
controller.abort(new AuthorizationError('timeout'));
|
|
236
|
+
},
|
|
237
|
+
interactive ? INTERACTIVE_TIMEOUT_MS : SILENT_TIMEOUT_MS,
|
|
238
|
+
);
|
|
239
|
+
let target: SilentAuthorizationWindow | undefined;
|
|
240
|
+
let popupPoll: ReturnType<typeof setInterval> | undefined;
|
|
241
|
+
try {
|
|
242
|
+
target = this.environment.open(interactive);
|
|
243
|
+
if (interactive) {
|
|
244
|
+
popupPoll = setInterval(() => {
|
|
245
|
+
if (target?.closed) controller.abort(new AuthorizationError('interaction_cancelled'));
|
|
246
|
+
}, POPUP_POLL_INTERVAL_MS);
|
|
247
|
+
}
|
|
248
|
+
return await abortable(
|
|
249
|
+
this.request(product, interactive, target, controller.signal),
|
|
250
|
+
controller.signal,
|
|
251
|
+
);
|
|
252
|
+
} catch (cause) {
|
|
253
|
+
return failureResult(
|
|
254
|
+
product.id,
|
|
255
|
+
controller.signal.aborted ? controller.signal.reason : cause,
|
|
256
|
+
);
|
|
257
|
+
} finally {
|
|
258
|
+
clearTimeout(timer);
|
|
259
|
+
clearInterval(popupPoll);
|
|
260
|
+
this.controllers.delete(controller);
|
|
261
|
+
target?.close();
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
private async request(
|
|
266
|
+
product: SilentTokenProduct,
|
|
267
|
+
interactive: boolean,
|
|
268
|
+
target: SilentAuthorizationWindow,
|
|
269
|
+
signal: AbortSignal,
|
|
270
|
+
): Promise<SilentTokenResult> {
|
|
271
|
+
const metadata = await this.metadata(product, signal);
|
|
272
|
+
const state = randomUrlSafe(this.environment.crypto, 32);
|
|
273
|
+
const nonce = randomUrlSafe(this.environment.crypto, 32);
|
|
274
|
+
const verifier = randomUrlSafe(this.environment.crypto, 64);
|
|
275
|
+
const digest = await this.environment.crypto.subtle.digest(
|
|
276
|
+
'SHA-256',
|
|
277
|
+
new TextEncoder().encode(verifier),
|
|
278
|
+
);
|
|
279
|
+
signal.throwIfAborted();
|
|
280
|
+
const url = buildAuthorizationUrl(product, metadata.authorizationEndpoint, {
|
|
281
|
+
state,
|
|
282
|
+
challenge: base64UrlEncode(new Uint8Array(digest)),
|
|
283
|
+
});
|
|
284
|
+
url.searchParams.set('response_mode', 'query');
|
|
285
|
+
url.searchParams.set('nonce', nonce);
|
|
286
|
+
if (!interactive) url.searchParams.set('prompt', 'none');
|
|
287
|
+
for (const [key, value] of Object.entries(product.authorizationParams ?? {}))
|
|
288
|
+
url.searchParams.set(key, value);
|
|
289
|
+
const callback = await target.receive(url, signal);
|
|
290
|
+
signal.throwIfAborted();
|
|
291
|
+
const code = callbackCode(callback, product, state);
|
|
292
|
+
return this.exchange(product, metadata, { code, verifier, nonce }, signal);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
private async exchange(
|
|
296
|
+
product: SilentTokenProduct,
|
|
297
|
+
metadata: Metadata,
|
|
298
|
+
transaction: { code: string; verifier: string; nonce: string },
|
|
299
|
+
signal: AbortSignal,
|
|
300
|
+
): Promise<Extract<SilentTokenResult, { status: 'ok' }>> {
|
|
301
|
+
const { value, receivedAt } = await this.json(metadata.tokenEndpoint, signal, {
|
|
302
|
+
method: 'POST',
|
|
303
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
304
|
+
body: new URLSearchParams({
|
|
305
|
+
grant_type: 'authorization_code',
|
|
306
|
+
client_id: product.clientId,
|
|
307
|
+
redirect_uri: product.redirectUri,
|
|
308
|
+
code: transaction.code,
|
|
309
|
+
code_verifier: transaction.verifier,
|
|
310
|
+
}),
|
|
311
|
+
});
|
|
312
|
+
const tokens = validateTokenResponse(value, receivedAt);
|
|
313
|
+
const signedExpiresAt = await this.verifyTokenClaims(
|
|
314
|
+
product,
|
|
315
|
+
metadata.jwksUri,
|
|
316
|
+
tokens,
|
|
317
|
+
transaction.nonce,
|
|
318
|
+
signal,
|
|
319
|
+
);
|
|
320
|
+
signal.throwIfAborted();
|
|
321
|
+
const expiresAt = Math.min(tokens.responseExpiresAt, signedExpiresAt);
|
|
322
|
+
if (expiresAt <= this.environment.now()) throw new SilentTokenError('invalid_tokens');
|
|
323
|
+
return { status: 'ok', productId: product.id, accessToken: tokens.accessToken, expiresAt };
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
private async verifyTokenClaims(
|
|
327
|
+
product: SilentTokenProduct,
|
|
328
|
+
jwksUri: string,
|
|
329
|
+
tokens: TokenResponse,
|
|
330
|
+
nonce: string,
|
|
331
|
+
signal: AbortSignal,
|
|
332
|
+
): Promise<number> {
|
|
333
|
+
const { value: jwks } = await this.json(jwksUri, signal);
|
|
334
|
+
const keys = createLocalJWKSet(jwks as unknown as JSONWebKeySet);
|
|
335
|
+
const options = {
|
|
336
|
+
issuer: product.issuer,
|
|
337
|
+
algorithms: ['RS256'],
|
|
338
|
+
currentDate: new Date(this.environment.now()),
|
|
339
|
+
requiredClaims: ['exp', 'iat', 'sub'],
|
|
340
|
+
};
|
|
341
|
+
const { payload: id } = await jwtVerify(tokens.idToken, keys, {
|
|
342
|
+
...options,
|
|
343
|
+
audience: product.clientId,
|
|
344
|
+
});
|
|
345
|
+
if (id['nonce'] !== nonce) throw new SilentTokenError('invalid_nonce');
|
|
346
|
+
if (
|
|
347
|
+
(Array.isArray(id.aud) && id.aud.length > 1 && id['azp'] !== product.clientId) ||
|
|
348
|
+
(id['azp'] !== undefined && id['azp'] !== product.clientId)
|
|
349
|
+
)
|
|
350
|
+
throw new SilentTokenError('invalid_client');
|
|
351
|
+
const { payload: access } = await jwtVerify(tokens.accessToken, keys, {
|
|
352
|
+
...options,
|
|
353
|
+
audience: product.audience,
|
|
354
|
+
});
|
|
355
|
+
if (
|
|
356
|
+
!id.sub ||
|
|
357
|
+
access.sub !== id.sub ||
|
|
358
|
+
access['azp'] !== product.clientId ||
|
|
359
|
+
access[this.accountBinding.claim] !== this.accountBinding.value
|
|
360
|
+
)
|
|
361
|
+
throw new AuthorizationError('account_mismatch');
|
|
362
|
+
return (access.exp ?? 0) * 1000;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
private async metadata(product: SilentTokenProduct, signal: AbortSignal): Promise<Metadata> {
|
|
366
|
+
const { value: raw } = await this.json(
|
|
367
|
+
`${product.issuer}/.well-known/openid-configuration`,
|
|
368
|
+
signal,
|
|
369
|
+
);
|
|
370
|
+
if (raw['issuer'] !== product.issuer) throw new SilentTokenError('invalid_issuer');
|
|
371
|
+
const endpoint = (field: string): string => {
|
|
372
|
+
const value = raw[field];
|
|
373
|
+
if (
|
|
374
|
+
typeof value !== 'string' ||
|
|
375
|
+
trustedUrl(value).origin !== new URL(product.issuer).origin
|
|
376
|
+
) {
|
|
377
|
+
throw new SilentTokenError('invalid_metadata');
|
|
378
|
+
}
|
|
379
|
+
return value;
|
|
380
|
+
};
|
|
381
|
+
return {
|
|
382
|
+
authorizationEndpoint: endpoint('authorization_endpoint'),
|
|
383
|
+
tokenEndpoint: endpoint('token_endpoint'),
|
|
384
|
+
jwksUri: endpoint('jwks_uri'),
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
private async json(
|
|
389
|
+
url: string,
|
|
390
|
+
signal: AbortSignal,
|
|
391
|
+
init: RequestInit = {},
|
|
392
|
+
): Promise<{ value: Record<string, unknown>; receivedAt: number }> {
|
|
393
|
+
signal.throwIfAborted();
|
|
394
|
+
const response = await this.environment.fetch(url, {
|
|
395
|
+
...init,
|
|
396
|
+
signal,
|
|
397
|
+
credentials: 'omit',
|
|
398
|
+
cache: 'no-store',
|
|
399
|
+
redirect: 'error',
|
|
400
|
+
});
|
|
401
|
+
const receivedAt = this.environment.now();
|
|
402
|
+
signal.throwIfAborted();
|
|
403
|
+
if (!response.ok) throw new SilentTokenError('http_error');
|
|
404
|
+
const value: unknown = await response.json();
|
|
405
|
+
signal.throwIfAborted();
|
|
406
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value))
|
|
407
|
+
throw new SilentTokenError('invalid_response');
|
|
408
|
+
return { value: value as Record<string, unknown>, receivedAt };
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
function validateTokenResponse(tokens: Record<string, unknown>, receivedAt: number): TokenResponse {
|
|
413
|
+
if (
|
|
414
|
+
typeof tokens['access_token'] !== 'string' ||
|
|
415
|
+
!tokens['access_token'] ||
|
|
416
|
+
typeof tokens['id_token'] !== 'string' ||
|
|
417
|
+
!tokens['id_token'] ||
|
|
418
|
+
typeof tokens['expires_in'] !== 'number' ||
|
|
419
|
+
!Number.isFinite(tokens['expires_in']) ||
|
|
420
|
+
tokens['expires_in'] <= 0 ||
|
|
421
|
+
!Number.isFinite(receivedAt + tokens['expires_in'] * 1000) ||
|
|
422
|
+
tokens['token_type'] !== 'Bearer'
|
|
423
|
+
) {
|
|
424
|
+
throw new SilentTokenError('invalid_tokens');
|
|
425
|
+
}
|
|
426
|
+
return {
|
|
427
|
+
accessToken: tokens['access_token'],
|
|
428
|
+
idToken: tokens['id_token'],
|
|
429
|
+
responseExpiresAt: receivedAt + tokens['expires_in'] * 1000,
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
function callbackCode(callback: string, product: SilentTokenProduct, state: string): string {
|
|
434
|
+
const returned = new URL(callback);
|
|
435
|
+
const expected = new URL(product.redirectUri);
|
|
436
|
+
if (
|
|
437
|
+
returned.origin !== expected.origin ||
|
|
438
|
+
returned.pathname !== expected.pathname ||
|
|
439
|
+
returned.hash ||
|
|
440
|
+
returned.username ||
|
|
441
|
+
returned.password
|
|
442
|
+
) {
|
|
443
|
+
throw new SilentTokenError('invalid_callback');
|
|
444
|
+
}
|
|
445
|
+
for (const field of ['state', 'iss', 'code', 'error']) {
|
|
446
|
+
if (returned.searchParams.getAll(field).length > 1)
|
|
447
|
+
throw new SilentTokenError('invalid_callback');
|
|
448
|
+
}
|
|
449
|
+
if (returned.searchParams.get('state') !== state) throw new SilentTokenError('invalid_state');
|
|
450
|
+
if (returned.searchParams.get('iss') !== product.issuer)
|
|
451
|
+
throw new SilentTokenError('invalid_issuer');
|
|
452
|
+
const error = returned.searchParams.get('error');
|
|
453
|
+
if (error !== null) {
|
|
454
|
+
if (returned.searchParams.has('code')) throw new SilentTokenError('invalid_callback');
|
|
455
|
+
if (
|
|
456
|
+
error === 'login_required' ||
|
|
457
|
+
error === 'interaction_required' ||
|
|
458
|
+
error === 'consent_required'
|
|
459
|
+
)
|
|
460
|
+
throw new AuthorizationError(error);
|
|
461
|
+
throw new SilentTokenError('authorization_rejected');
|
|
462
|
+
}
|
|
463
|
+
const code = returned.searchParams.get('code');
|
|
464
|
+
if (!code) throw new SilentTokenError('missing_code');
|
|
465
|
+
return code;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
function failureResult(
|
|
469
|
+
productId: string,
|
|
470
|
+
cause: unknown,
|
|
471
|
+
): Exclude<SilentTokenResult, { status: 'ok' }> {
|
|
472
|
+
if (cause instanceof AuthorizationError) {
|
|
473
|
+
if (cause.code === 'consent_required' || cause.code === 'account_mismatch')
|
|
474
|
+
return { status: cause.code, productId };
|
|
475
|
+
return { status: 'login_required', productId, reason: cause.code };
|
|
476
|
+
}
|
|
477
|
+
return {
|
|
478
|
+
status: 'error',
|
|
479
|
+
productId,
|
|
480
|
+
error:
|
|
481
|
+
cause instanceof SilentTokenError
|
|
482
|
+
? cause
|
|
483
|
+
: new SilentTokenError('unavailable_or_invalid_response'),
|
|
484
|
+
};
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
function trustedUrl(value: string): URL {
|
|
488
|
+
let url: URL;
|
|
489
|
+
try {
|
|
490
|
+
url = new URL(value);
|
|
491
|
+
} catch {
|
|
492
|
+
throw new SilentTokenError('invalid_url');
|
|
493
|
+
}
|
|
494
|
+
if (
|
|
495
|
+
(url.protocol !== 'https:' &&
|
|
496
|
+
!(url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))) ||
|
|
497
|
+
url.username ||
|
|
498
|
+
url.password ||
|
|
499
|
+
url.hash ||
|
|
500
|
+
url.search
|
|
501
|
+
)
|
|
502
|
+
throw new SilentTokenError('invalid_url');
|
|
503
|
+
return url;
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
function abortable<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {
|
|
507
|
+
return new Promise((resolve, reject) => {
|
|
508
|
+
const abort = () => {
|
|
509
|
+
reject(signal.reason instanceof Error ? signal.reason : new SilentTokenError('aborted'));
|
|
510
|
+
};
|
|
511
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
512
|
+
if (signal.aborted) abort();
|
|
513
|
+
work.then(resolve, reject).finally(() => {
|
|
514
|
+
signal.removeEventListener('abort', abort);
|
|
515
|
+
});
|
|
516
|
+
});
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
function browserEnvironment(): SilentTokenEnvironment {
|
|
520
|
+
if (typeof window === 'undefined') throw new SilentTokenError('unsupported_environment');
|
|
521
|
+
return {
|
|
522
|
+
fetch: globalThis.fetch.bind(globalThis),
|
|
523
|
+
crypto: globalThis.crypto,
|
|
524
|
+
now: () => Date.now(),
|
|
525
|
+
open: (interactive) => openSilentAuthorizationWindow(window, interactive),
|
|
526
|
+
};
|
|
527
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import { afterEach, expect, it, vi } from 'vitest';
|
|
3
|
+
import { CALLBACK_MESSAGE, completeSilentTokenCallback } from './index.js';
|
|
4
|
+
import { openSilentAuthorizationWindow } from './silent-token-browser.js';
|
|
5
|
+
|
|
6
|
+
afterEach(() => {
|
|
7
|
+
vi.restoreAllMocks();
|
|
8
|
+
document.body.replaceChildren();
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
it.each([false, true])(
|
|
12
|
+
'checks origin and source for interactive=%s and cleans up listeners',
|
|
13
|
+
async (interactive) => {
|
|
14
|
+
const target = { location: { replace: vi.fn() }, close: vi.fn() };
|
|
15
|
+
const targetWindow = target as unknown as Window;
|
|
16
|
+
vi.spyOn(HTMLIFrameElement.prototype, 'contentWindow', 'get').mockReturnValue(targetWindow);
|
|
17
|
+
const open = vi.spyOn(window, 'open').mockReturnValue(targetWindow);
|
|
18
|
+
const remove = vi.spyOn(window, 'removeEventListener');
|
|
19
|
+
const storage = vi.spyOn(Storage.prototype, 'setItem');
|
|
20
|
+
const authorization = openSilentAuthorizationWindow(window, interactive);
|
|
21
|
+
expect(open).toHaveBeenCalledTimes(interactive ? 1 : 0);
|
|
22
|
+
if (!interactive) expect(document.querySelector('iframe')?.hidden).toBe(true);
|
|
23
|
+
const url = new URL('https://identity.example/auth');
|
|
24
|
+
const controller = new AbortController();
|
|
25
|
+
let resolved = false;
|
|
26
|
+
const pending = authorization.receive(url, controller.signal).then((value) => {
|
|
27
|
+
resolved = true;
|
|
28
|
+
return value;
|
|
29
|
+
});
|
|
30
|
+
const valid = {
|
|
31
|
+
type: 'baukit-silent-token-callback',
|
|
32
|
+
url: `${window.location.origin}/callback?code=one`,
|
|
33
|
+
};
|
|
34
|
+
for (const data of [
|
|
35
|
+
null,
|
|
36
|
+
'bad',
|
|
37
|
+
{},
|
|
38
|
+
{ type: 'wrong', url: 'x' },
|
|
39
|
+
{ type: valid.type, url: 42 },
|
|
40
|
+
]) {
|
|
41
|
+
window.dispatchEvent(
|
|
42
|
+
new MessageEvent('message', { origin: window.location.origin, source: targetWindow, data }),
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
window.dispatchEvent(
|
|
46
|
+
new MessageEvent('message', {
|
|
47
|
+
origin: 'https://evil.example',
|
|
48
|
+
source: targetWindow,
|
|
49
|
+
data: valid,
|
|
50
|
+
}),
|
|
51
|
+
);
|
|
52
|
+
window.dispatchEvent(
|
|
53
|
+
new MessageEvent('message', { origin: window.location.origin, source: window, data: valid }),
|
|
54
|
+
);
|
|
55
|
+
await Promise.resolve();
|
|
56
|
+
expect(resolved).toBe(false);
|
|
57
|
+
window.dispatchEvent(
|
|
58
|
+
new MessageEvent('message', {
|
|
59
|
+
origin: window.location.origin,
|
|
60
|
+
source: targetWindow,
|
|
61
|
+
data: valid,
|
|
62
|
+
}),
|
|
63
|
+
);
|
|
64
|
+
expect(await pending).toBe(valid.url);
|
|
65
|
+
expect(target.location.replace).toHaveBeenCalledWith(url.toString());
|
|
66
|
+
expect(remove).toHaveBeenCalledWith('message', expect.any(Function));
|
|
67
|
+
authorization.close();
|
|
68
|
+
expect(document.querySelector('iframe')).toBeNull();
|
|
69
|
+
expect(target.close).toHaveBeenCalledTimes(interactive ? 1 : 0);
|
|
70
|
+
expect(storage).not.toHaveBeenCalled();
|
|
71
|
+
},
|
|
72
|
+
);
|
|
73
|
+
|
|
74
|
+
it('opens an explicit window synchronously and aborts its message listener', async () => {
|
|
75
|
+
const popup = { location: { replace: vi.fn() }, close: vi.fn() };
|
|
76
|
+
const open = vi.spyOn(window, 'open').mockReturnValue(popup as unknown as Window);
|
|
77
|
+
const target = openSilentAuthorizationWindow(window, true);
|
|
78
|
+
expect(open).toHaveBeenCalledTimes(1);
|
|
79
|
+
const controller = new AbortController();
|
|
80
|
+
const pending = target.receive(new URL('https://identity.example/auth'), controller.signal);
|
|
81
|
+
controller.abort(new Error('cancelled'));
|
|
82
|
+
await expect(pending).rejects.toThrow('cancelled');
|
|
83
|
+
target.close();
|
|
84
|
+
expect(popup.close).toHaveBeenCalled();
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
it('exposes the live popup closed state', () => {
|
|
88
|
+
const popup = { closed: false, close: vi.fn() };
|
|
89
|
+
vi.spyOn(window, 'open').mockReturnValue(popup as unknown as Window);
|
|
90
|
+
const target = openSilentAuthorizationWindow(window, true);
|
|
91
|
+
expect(target.closed).toBe(false);
|
|
92
|
+
popup.closed = true;
|
|
93
|
+
expect(target.closed).toBe(true);
|
|
94
|
+
target.close();
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it('reports blocked popups and handles pre-aborted authorization without navigating', async () => {
|
|
98
|
+
vi.spyOn(window, 'open').mockReturnValue(null);
|
|
99
|
+
expect(() => openSilentAuthorizationWindow(window, true)).toThrow('popup_blocked');
|
|
100
|
+
const replace = vi.fn();
|
|
101
|
+
vi.spyOn(HTMLIFrameElement.prototype, 'contentWindow', 'get').mockReturnValue({
|
|
102
|
+
location: { replace },
|
|
103
|
+
} as unknown as Window);
|
|
104
|
+
const target = openSilentAuthorizationWindow(window, false);
|
|
105
|
+
const controller = new AbortController();
|
|
106
|
+
controller.abort(new Error('disposed'));
|
|
107
|
+
await expect(
|
|
108
|
+
target.receive(new URL('https://identity.example/auth'), controller.signal),
|
|
109
|
+
).rejects.toThrow('disposed');
|
|
110
|
+
expect(replace).not.toHaveBeenCalled();
|
|
111
|
+
target.close();
|
|
112
|
+
expect(document.querySelector('iframe')).toBeNull();
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it('closing a frame rejects a pending receive and removes it', async () => {
|
|
116
|
+
const target = openSilentAuthorizationWindow(window, false);
|
|
117
|
+
const pending = target.receive(new URL('about:blank'), new AbortController().signal);
|
|
118
|
+
target.close();
|
|
119
|
+
await expect(pending).rejects.toMatchObject({ code: 'aborted' });
|
|
120
|
+
expect(document.querySelector('iframe')).toBeNull();
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
it.each(['opener', 'parent'] as const)(
|
|
124
|
+
'posts the callback only to the same-origin %s and strips the query first',
|
|
125
|
+
(recipient) => {
|
|
126
|
+
const postMessage = vi.fn();
|
|
127
|
+
const replaceState = vi.fn();
|
|
128
|
+
const browser = {
|
|
129
|
+
location: {
|
|
130
|
+
href: 'https://app.example/callback?code=secret&state=state',
|
|
131
|
+
pathname: '/callback',
|
|
132
|
+
origin: 'https://app.example',
|
|
133
|
+
},
|
|
134
|
+
history: { replaceState },
|
|
135
|
+
opener: recipient === 'opener' ? { postMessage } : null,
|
|
136
|
+
parent: { postMessage },
|
|
137
|
+
};
|
|
138
|
+
expect(completeSilentTokenCallback(browser as unknown as Window)).toBe(true);
|
|
139
|
+
expect(CALLBACK_MESSAGE).toBe('baukit-silent-token-callback');
|
|
140
|
+
expect(replaceState).toHaveBeenCalledWith(null, '', '/callback');
|
|
141
|
+
expect(postMessage).toHaveBeenCalledWith(
|
|
142
|
+
{ type: CALLBACK_MESSAGE, url: browser.location.href },
|
|
143
|
+
'https://app.example',
|
|
144
|
+
);
|
|
145
|
+
expect(replaceState.mock.invocationCallOrder[0]).toBeLessThan(
|
|
146
|
+
postMessage.mock.invocationCallOrder[0] ?? 0,
|
|
147
|
+
);
|
|
148
|
+
},
|
|
149
|
+
);
|
|
150
|
+
|
|
151
|
+
it('cleans a standalone callback without posting a message', () => {
|
|
152
|
+
const browser = {
|
|
153
|
+
location: window.location,
|
|
154
|
+
history: { replaceState: vi.fn() },
|
|
155
|
+
opener: null,
|
|
156
|
+
parent: {},
|
|
157
|
+
};
|
|
158
|
+
browser.parent = browser;
|
|
159
|
+
expect(completeSilentTokenCallback(browser as unknown as Window)).toBe(false);
|
|
160
|
+
expect(browser.history.replaceState).toHaveBeenCalled();
|
|
161
|
+
});
|