ark-oauth-client-js 0.0.0-stage → 2.1.8
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/CHANGELOG.md +56 -0
- package/LICENSE +21 -0
- package/README.md +578 -2
- package/dist/ark-oauth-client.esm.min.js +3 -0
- package/dist/ark-oauth-client.esm.min.js.map +7 -0
- package/dist/ark-oauth-client.global.js +2510 -0
- package/dist/ark-oauth-client.global.min.js +3 -0
- package/dist/ark-oauth-client.global.min.js.map +7 -0
- package/package.json +122 -4
- package/src/access.js +141 -0
- package/src/angular.js +175 -0
- package/src/client.js +1426 -0
- package/src/config.js +196 -0
- package/src/crypto.js +121 -0
- package/src/denied.js +119 -0
- package/src/discovery.js +84 -0
- package/src/errors.js +110 -0
- package/src/http.js +190 -0
- package/src/index.js +44 -0
- package/src/jwks.js +124 -0
- package/src/jwt.js +223 -0
- package/src/lock.js +19 -0
- package/src/next.js +28 -0
- package/src/pkce.js +35 -0
- package/src/popup.js +162 -0
- package/src/react.js +225 -0
- package/src/storage.js +127 -0
- package/src/store.js +57 -0
- package/src/tokens.js +97 -0
- package/src/version.js +5 -0
- package/src/vue.js +110 -0
- package/types/angular.d.ts +61 -0
- package/types/index.d.ts +431 -0
- package/types/next.d.ts +19 -0
- package/types/react.d.ts +71 -0
- package/types/vue.d.ts +67 -0
package/src/client.js
ADDED
|
@@ -0,0 +1,1426 @@
|
|
|
1
|
+
import { DEFAULT_POST_LOGOUT_PATH, normalizeConfig } from './config.js';
|
|
2
|
+
import { MetadataResolver } from './discovery.js';
|
|
3
|
+
import { JwksCache } from './jwks.js';
|
|
4
|
+
import { TokenSet } from './tokens.js';
|
|
5
|
+
import { getJson, postForm, postFormNoCors } from './http.js';
|
|
6
|
+
import { createNonce, createPkcePair, createState } from './pkce.js';
|
|
7
|
+
import { base64UrlEncode, constantTimeEqual, sha256 } from './crypto.js';
|
|
8
|
+
import { verifyJwt } from './jwt.js';
|
|
9
|
+
import { ArkStore, INITIAL_SNAPSHOT } from './store.js';
|
|
10
|
+
import { keysWithPrefix, readJson, remove, resolveStorage, writeJson } from './storage.js';
|
|
11
|
+
import { withLock } from './lock.js';
|
|
12
|
+
import { openPopupWindow, popupChannelName, relayToOpener, waitForPopupCallback } from './popup.js';
|
|
13
|
+
import { ArkAccessDeniedReasons, describeDenial, evaluateAccess, localOrDefault } from './access.js';
|
|
14
|
+
import {
|
|
15
|
+
ArkCallbackError,
|
|
16
|
+
ArkConfigError,
|
|
17
|
+
ArkError,
|
|
18
|
+
ArkLoginRequiredError,
|
|
19
|
+
ArkNetworkError,
|
|
20
|
+
ArkOAuthError,
|
|
21
|
+
ArkTokenError
|
|
22
|
+
} from './errors.js';
|
|
23
|
+
|
|
24
|
+
/** Parameters of an authorization response, stripped from the URL once read. */
|
|
25
|
+
const RESPONSE_PARAMS = ['code', 'state', 'iss', 'error', 'error_description', 'error_uri', 'session_state'];
|
|
26
|
+
const DENIAL_TTL_SECONDS = 300;
|
|
27
|
+
const RETRY_AFTER_NETWORK_FAILURE_MS = 15_000;
|
|
28
|
+
const SPENT_TOKENS_REMEMBERED = 50;
|
|
29
|
+
const MAX_TIMER_MS = 2_147_483_647;
|
|
30
|
+
const EVENTS = ['signedIn', 'signedOut', 'tokensRefreshed', 'refreshFailed', 'sessionExpired', 'accessDenied', 'error'];
|
|
31
|
+
|
|
32
|
+
const now = () => Math.floor(Date.now() / 1000);
|
|
33
|
+
let instanceCounter = 0;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Lets a long-lived timer or channel not hold a Node process open (unit tests of an app, SSR).
|
|
37
|
+
* Browsers return a number from setTimeout and have no unref, so this is a no-op there.
|
|
38
|
+
*/
|
|
39
|
+
function unref(handle) {
|
|
40
|
+
if (handle && typeof handle.unref === 'function') handle.unref();
|
|
41
|
+
return handle;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The Ark OpenID Connect client for browser apps: React, Next.js, Vue, Angular, Svelte, or none.
|
|
46
|
+
*
|
|
47
|
+
* One instance per app. It runs the authorization code flow with PKCE as a public client, validates
|
|
48
|
+
* the ID token (signature, issuer, audience, nonce, at_hash, c_hash) in the browser, keeps the
|
|
49
|
+
* session renewed with rotating refresh tokens, and exposes the result as a small observable state
|
|
50
|
+
* that any framework can bind to. The framework adapters (`ark-oauth-client-js/react`, `/vue`,
|
|
51
|
+
* `/angular`, `/next`) are thin wrappers over exactly this object.
|
|
52
|
+
*
|
|
53
|
+
* const ark = new ArkBrowserClient({ authority: 'https://idp.example.com/my_idp', clientId: 'my-spa' });
|
|
54
|
+
* await ark.init(); // handles /signin-oidc, restores the session
|
|
55
|
+
* if (!ark.getSnapshot().isAuthenticated) await ark.signinRedirect();
|
|
56
|
+
* const res = await ark.fetch('/api/orders'); // bearer attached, refreshed when needed
|
|
57
|
+
*
|
|
58
|
+
* Nothing touches `window` until `init()` or a sign-in method is called, so creating the client
|
|
59
|
+
* during server-side rendering is safe; on the server it simply stays in the `loading` state.
|
|
60
|
+
*/
|
|
61
|
+
export class ArkBrowserClient {
|
|
62
|
+
#config;
|
|
63
|
+
#win;
|
|
64
|
+
#metadata;
|
|
65
|
+
#jwks = null;
|
|
66
|
+
#store = new ArkStore();
|
|
67
|
+
#events = new Map(EVENTS.map((name) => [name, new Set()]));
|
|
68
|
+
#id = `ark-${++instanceCounter}-${Math.random().toString(36).slice(2, 8)}`;
|
|
69
|
+
|
|
70
|
+
#ready = false;
|
|
71
|
+
#storage = null;
|
|
72
|
+
#storageKind = 'memory';
|
|
73
|
+
#txStorage = null;
|
|
74
|
+
#spentStorage = null;
|
|
75
|
+
#prefix;
|
|
76
|
+
|
|
77
|
+
#tokens = null;
|
|
78
|
+
#derived = { claims: null, arkClaims: Object.freeze([]), scopes: Object.freeze([]) };
|
|
79
|
+
#denial = null;
|
|
80
|
+
|
|
81
|
+
#initPromise = null;
|
|
82
|
+
#refreshPromise = null;
|
|
83
|
+
#timer = null;
|
|
84
|
+
#channel = null;
|
|
85
|
+
#detach = [];
|
|
86
|
+
#destroyed = false;
|
|
87
|
+
|
|
88
|
+
constructor(options = {}) {
|
|
89
|
+
this.#config = normalizeConfig(options);
|
|
90
|
+
this.#win = options.window !== undefined ? options.window : typeof window !== 'undefined' ? window : null;
|
|
91
|
+
this.#prefix = `ark.oidc:${this.#config.clientId}@${this.#config.authority}:`;
|
|
92
|
+
this.#metadata = new MetadataResolver(this.#config.authority, {
|
|
93
|
+
ttlMs: this.#config.metadataTtlMs,
|
|
94
|
+
timeoutMs: this.#config.timeoutMs,
|
|
95
|
+
fetch: this.#config.fetch
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
// Stable references: React's useSyncExternalStore and Svelte's `$store` call these detached.
|
|
99
|
+
this.subscribe = this.subscribe.bind(this);
|
|
100
|
+
this.getSnapshot = this.getSnapshot.bind(this);
|
|
101
|
+
this.getServerSnapshot = this.getServerSnapshot.bind(this);
|
|
102
|
+
this.fetch = this.fetch.bind(this);
|
|
103
|
+
this.getAccessToken = this.getAccessToken.bind(this);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
get config() {
|
|
107
|
+
return this.#config;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
get authority() {
|
|
111
|
+
return this.#config.authority;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
get clientId() {
|
|
115
|
+
return this.#config.clientId;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* False during server-side rendering (no window): the client stays `loading` and every action
|
|
120
|
+
* that needs a browser waits for one. Route guards use it to cancel quietly on the server and
|
|
121
|
+
* decide in the browser, after hydration.
|
|
122
|
+
*/
|
|
123
|
+
get isBrowser() {
|
|
124
|
+
return Boolean(this.#win);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// =================================================================
|
|
128
|
+
// State: the framework-agnostic surface
|
|
129
|
+
// =================================================================
|
|
130
|
+
|
|
131
|
+
/** The current state. The same frozen object until something changes. */
|
|
132
|
+
getSnapshot() {
|
|
133
|
+
return this.#store.get();
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** The state during server-side rendering and hydration: always `loading`. */
|
|
137
|
+
getServerSnapshot() {
|
|
138
|
+
return INITIAL_SNAPSHOT;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Calls `listener(snapshot)` on every change. Returns the unsubscribe function. */
|
|
142
|
+
subscribe(listener) {
|
|
143
|
+
return this.#store.subscribe(listener);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* The state as a Svelte-compatible store (`$ark.state` in a component): `subscribe` calls the
|
|
148
|
+
* listener straight away with the current value, then on every change.
|
|
149
|
+
*/
|
|
150
|
+
get state() {
|
|
151
|
+
return {
|
|
152
|
+
subscribe: (run) => {
|
|
153
|
+
run(this.#store.get());
|
|
154
|
+
return this.#store.subscribe(run);
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** The signed-in user's ID token claims, or null. */
|
|
160
|
+
getUser() {
|
|
161
|
+
return this.#store.get().user;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Listens for one event: `signedIn`, `signedOut`, `tokensRefreshed`, `refreshFailed`,
|
|
166
|
+
* `sessionExpired`, `accessDenied` or `error`. Returns the unsubscribe function.
|
|
167
|
+
*/
|
|
168
|
+
on(event, handler) {
|
|
169
|
+
const set = this.#events.get(event);
|
|
170
|
+
if (!set) throw new ArkConfigError(`ark_oauth_client: unknown event '${event}'. Known events: ${EVENTS.join(', ')}.`);
|
|
171
|
+
set.add(handler);
|
|
172
|
+
return () => set.delete(handler);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** True when the user holds every one of these Ark authorization claims. */
|
|
176
|
+
hasArkClaims(...claims) {
|
|
177
|
+
const held = this.#store.get().arkClaims;
|
|
178
|
+
return claims.flat().every((c) => held.includes(c));
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** True when the user holds at least one of these Ark authorization claims. */
|
|
182
|
+
hasAnyArkClaim(...claims) {
|
|
183
|
+
const held = this.#store.get().arkClaims;
|
|
184
|
+
return claims.flat().some((c) => held.includes(c));
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** True when every one of these scopes was granted. */
|
|
188
|
+
hasScopes(...scopes) {
|
|
189
|
+
const granted = this.#store.get().scopes;
|
|
190
|
+
return scopes.flat().every((s) => granted.includes(s));
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// =================================================================
|
|
194
|
+
// Start-up
|
|
195
|
+
// =================================================================
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Starts the client: completes a sign-in when the page is the redirect URI, completes a sign-out
|
|
199
|
+
* when it is the post-logout URI, otherwise restores the stored session (refreshing it if the
|
|
200
|
+
* access token expired while the page was closed). Resolves with the snapshot; never rejects: a
|
|
201
|
+
* failure lands in `snapshot.error` and the `error` event.
|
|
202
|
+
*
|
|
203
|
+
* Idempotent: every call after the first returns the first call's promise, so React StrictMode's
|
|
204
|
+
* double effects and several components calling it at once all share one start-up.
|
|
205
|
+
*
|
|
206
|
+
* After a completed sign-in the browser is sent to the page the user started from, through
|
|
207
|
+
* `onRedirectCallback(returnTo)` when given (pass your router's navigate here), otherwise through
|
|
208
|
+
* `history.replaceState` plus a `popstate` event, which React Router and the Angular router follow.
|
|
209
|
+
*
|
|
210
|
+
* @param {{ handleCallback?: boolean, onRedirectCallback?: (returnTo: string, result: object) => unknown }} [options]
|
|
211
|
+
*/
|
|
212
|
+
init(options = {}) {
|
|
213
|
+
if (!this.#win) return Promise.resolve(this.#store.get());
|
|
214
|
+
this.#initPromise ??= this.#runInit(options);
|
|
215
|
+
return this.#initPromise;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
async #runInit({ handleCallback = true, onRedirectCallback } = {}) {
|
|
219
|
+
this.#ensureReady();
|
|
220
|
+
this.#attachListeners();
|
|
221
|
+
this.#sweepTransactions();
|
|
222
|
+
|
|
223
|
+
const href = this.#win.location.href;
|
|
224
|
+
// Not awaited: a router navigation runs the app's guards, and a guard that awaits init() would
|
|
225
|
+
// otherwise wait on the very promise that is waiting on it.
|
|
226
|
+
const navigate = (to, result) => {
|
|
227
|
+
const handler = onRedirectCallback ?? this.#config.onRedirectCallback;
|
|
228
|
+
if (!handler) return this.#navigate(to);
|
|
229
|
+
try {
|
|
230
|
+
Promise.resolve(handler(to, result)).catch((error) => this.#emit('error', error));
|
|
231
|
+
} catch (error) {
|
|
232
|
+
this.#emit('error', error);
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
try {
|
|
237
|
+
const kind = handleCallback ? this.#classify(href) : null;
|
|
238
|
+
|
|
239
|
+
if (kind === 'signin') {
|
|
240
|
+
let result;
|
|
241
|
+
try {
|
|
242
|
+
result = await this.handleRedirectCallback(href);
|
|
243
|
+
} catch (error) {
|
|
244
|
+
// The page stays on the (now cleaned) callback URL with the error in the state: sending
|
|
245
|
+
// the user back to a guarded page would start the same failing sign-in again, in a loop.
|
|
246
|
+
this.#restore();
|
|
247
|
+
await this.#renewIfNeeded();
|
|
248
|
+
return this.#fail(error);
|
|
249
|
+
}
|
|
250
|
+
if (result.relayed) return this.#store.get(); // a popup, about to close
|
|
251
|
+
navigate(result.returnTo, result);
|
|
252
|
+
return this.#store.get();
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
if (kind === 'signout') {
|
|
256
|
+
const next = this.#takeLogoutTransaction(href);
|
|
257
|
+
if (next?.then === 'signin') {
|
|
258
|
+
// The second half of an account switch. The state stays `loading` until the browser has
|
|
259
|
+
// left: published as `unauthenticated`, a route guard would start a sign-in of its own,
|
|
260
|
+
// without the prompt=login this one carries.
|
|
261
|
+
await this.signinRedirect({ prompt: next.prompt ?? this.#config.accountSwitch.prompt, returnTo: next.returnTo, loginHint: next.loginHint });
|
|
262
|
+
return this.#store.get();
|
|
263
|
+
}
|
|
264
|
+
this.#publish({ error: null });
|
|
265
|
+
navigate(next?.returnTo ?? localOrDefault(this.#config.accountSwitch.homePath), { signedOut: true });
|
|
266
|
+
return this.#store.get();
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
this.#restore();
|
|
270
|
+
await this.#renewIfNeeded();
|
|
271
|
+
this.#publish();
|
|
272
|
+
this.#schedule();
|
|
273
|
+
} catch (error) {
|
|
274
|
+
return this.#fail(error);
|
|
275
|
+
}
|
|
276
|
+
return this.#store.get();
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// =================================================================
|
|
280
|
+
// Signing in
|
|
281
|
+
// =================================================================
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* Builds the authorization request and the transaction that must survive until the user comes
|
|
285
|
+
* back. For custom flows; `signinRedirect()` and `signinPopup()` use it.
|
|
286
|
+
*
|
|
287
|
+
* @returns {Promise<{ url: string, transaction: object }>}
|
|
288
|
+
*/
|
|
289
|
+
async createAuthorizationUrl(options = {}) {
|
|
290
|
+
const win = this.#requireWindow();
|
|
291
|
+
const config = this.#config;
|
|
292
|
+
const metadata = await this.metadata();
|
|
293
|
+
|
|
294
|
+
if (metadata.require_pushed_authorization_requests === true) {
|
|
295
|
+
throw new ArkConfigError(
|
|
296
|
+
'the tenant requires pushed authorization requests, which a browser app cannot make (/oauth2/par needs client ' +
|
|
297
|
+
'authentication and serves no CORS). Turn RequirePushedAuthorizationRequests off for this tenant, or the client\'s ' +
|
|
298
|
+
'require_par flag, or sign in through a server-side client.'
|
|
299
|
+
);
|
|
300
|
+
}
|
|
301
|
+
if (!metadata.authorization_endpoint) {
|
|
302
|
+
throw new ArkOAuthError('server_error', "the provider's metadata has no 'authorization_endpoint'.", { endpoint: config.authority });
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
const redirectUri = this.#resolve(options.redirectUri ?? config.redirectUri);
|
|
306
|
+
const scopes = options.scopes?.length ? [...options.scopes] : [...config.scopes];
|
|
307
|
+
const { codeVerifier, codeChallenge, codeChallengeMethod } = await createPkcePair();
|
|
308
|
+
const state = createState();
|
|
309
|
+
const nonce = scopes.includes('openid') ? createNonce() : null;
|
|
310
|
+
const prompt = options.prompt ?? config.prompt;
|
|
311
|
+
const acrValues = options.acrValues ?? config.acrValues;
|
|
312
|
+
const responseMode = options.responseMode ?? config.responseMode;
|
|
313
|
+
|
|
314
|
+
// Extra parameters go first so they can add to the request but never replace what its security
|
|
315
|
+
// rests on: an `extra` carrying its own state or code_challenge would detach the response from
|
|
316
|
+
// the transaction returned here.
|
|
317
|
+
const params = {
|
|
318
|
+
...config.extraAuthorizationParams,
|
|
319
|
+
...options.extra,
|
|
320
|
+
response_type: 'code',
|
|
321
|
+
client_id: config.clientId,
|
|
322
|
+
redirect_uri: redirectUri,
|
|
323
|
+
scope: scopes.join(' '),
|
|
324
|
+
state,
|
|
325
|
+
code_challenge: codeChallenge,
|
|
326
|
+
code_challenge_method: codeChallengeMethod,
|
|
327
|
+
response_mode: responseMode,
|
|
328
|
+
...(nonce ? { nonce } : {}),
|
|
329
|
+
...(prompt ? { prompt } : {}),
|
|
330
|
+
...(options.loginHint ? { login_hint: options.loginHint } : {}),
|
|
331
|
+
...(options.maxAge !== undefined && options.maxAge !== null ? { max_age: String(options.maxAge) } : {}),
|
|
332
|
+
...(acrValues ? { acr_values: acrValues } : {})
|
|
333
|
+
};
|
|
334
|
+
const query = new URLSearchParams(Object.entries(params).filter(([, v]) => v !== undefined && v !== null && v !== ''));
|
|
335
|
+
|
|
336
|
+
const here = `${win.location.pathname}${win.location.search}${win.location.hash}`;
|
|
337
|
+
const returnTo = localOrDefault(options.returnTo ?? (this.#classify(win.location.href) ? '/' : here), '/');
|
|
338
|
+
|
|
339
|
+
return {
|
|
340
|
+
url: `${metadata.authorization_endpoint}${metadata.authorization_endpoint.includes('?') ? '&' : '?'}${query}`,
|
|
341
|
+
transaction: {
|
|
342
|
+
state,
|
|
343
|
+
nonce,
|
|
344
|
+
codeVerifier,
|
|
345
|
+
redirectUri,
|
|
346
|
+
responseMode,
|
|
347
|
+
scope: scopes.join(' '),
|
|
348
|
+
maxAge: options.maxAge ?? null,
|
|
349
|
+
returnTo,
|
|
350
|
+
createdAt: now()
|
|
351
|
+
}
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* Sends the browser to the provider's sign-in page. The promise resolves as the page unloads.
|
|
357
|
+
*
|
|
358
|
+
* @param {{ returnTo?: string, prompt?: string, loginHint?: string, scopes?: string[], maxAge?: number,
|
|
359
|
+
* acrValues?: string, extra?: Record<string, string> }} [options]
|
|
360
|
+
*/
|
|
361
|
+
async signinRedirect(options = {}) {
|
|
362
|
+
this.#ensureReady();
|
|
363
|
+
const { url, transaction } = await this.createAuthorizationUrl(options);
|
|
364
|
+
this.#saveTransaction(transaction);
|
|
365
|
+
await this.#redirect(url);
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* Signs in through a popup window; the page never navigates. Call it straight from a click
|
|
370
|
+
* handler, before any `await`, or the browser blocks the popup. The popup lands on the redirect
|
|
371
|
+
* URI, whose page (this same app, calling `init()`) passes the result back here and closes.
|
|
372
|
+
*
|
|
373
|
+
* @returns {Promise<{ user: object|null, denied: boolean, returnTo: string }>}
|
|
374
|
+
*/
|
|
375
|
+
async signinPopup(options = {}) {
|
|
376
|
+
const win = this.#requireWindow();
|
|
377
|
+
// Synchronously, before anything is awaited: see popup.js.
|
|
378
|
+
const popup = options.popupWindow ?? openPopupWindow(win, this.#config.popup);
|
|
379
|
+
let waiter = null;
|
|
380
|
+
try {
|
|
381
|
+
this.#ensureReady();
|
|
382
|
+
const { url, transaction } = await this.createAuthorizationUrl(options);
|
|
383
|
+
waiter = waitForPopupCallback(win, popup, {
|
|
384
|
+
state: transaction.state,
|
|
385
|
+
channelName: popupChannelName(this.#config.authority, this.#config.clientId),
|
|
386
|
+
timeoutMs: this.#config.popup.timeoutMs
|
|
387
|
+
});
|
|
388
|
+
popup.location.href = url;
|
|
389
|
+
const responseUrl = await waiter.promise;
|
|
390
|
+
const params = this.#responseParams(new URL(responseUrl), transaction.responseMode);
|
|
391
|
+
if (params.error) throw this.#authorizationError(params);
|
|
392
|
+
return await this.#completeSignin(params, transaction);
|
|
393
|
+
} catch (error) {
|
|
394
|
+
waiter?.cancel(error);
|
|
395
|
+
this.#publish({ error: error instanceof ArkError ? error : new ArkError(String(error?.message ?? error)) });
|
|
396
|
+
this.#emit('error', error);
|
|
397
|
+
throw error;
|
|
398
|
+
} finally {
|
|
399
|
+
try {
|
|
400
|
+
if (!popup.closed) popup.close();
|
|
401
|
+
} catch {
|
|
402
|
+
/* already gone */
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/** Whether a URL is this client's sign-in callback: the redirect URI carrying a code or an error. */
|
|
408
|
+
isSigninCallback(url) {
|
|
409
|
+
return this.#classify(String(url ?? this.#requireWindow().location.href)) === 'signin';
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* Completes a sign-in from the authorization response in `url` (default: the current URL).
|
|
414
|
+
* `init()` calls this for you; call it yourself only with `init({ handleCallback: false })`.
|
|
415
|
+
*
|
|
416
|
+
* The checks, in order: an `error` response surfaces as an error; `state` must match a sign-in this
|
|
417
|
+
* tab started (constant-time, single use); `iss` must be the provider (RFC 9207); the code is
|
|
418
|
+
* redeemed with the PKCE verifier only this tab holds; the ID token is verified against the
|
|
419
|
+
* provider's keys, the `nonce`, `at_hash` and `c_hash`; then the access check, when configured.
|
|
420
|
+
* The response parameters are removed from the address bar either way, so a reload cannot replay them.
|
|
421
|
+
*
|
|
422
|
+
* @returns {Promise<{ returnTo: string, user: object|null, denied: boolean, relayed?: boolean }>}
|
|
423
|
+
*/
|
|
424
|
+
async handleRedirectCallback(url) {
|
|
425
|
+
const win = this.#requireWindow();
|
|
426
|
+
this.#ensureReady();
|
|
427
|
+
const href = String(url ?? win.location.href);
|
|
428
|
+
const parsed = new URL(href, win.location.href);
|
|
429
|
+
const params = this.#responseParams(parsed);
|
|
430
|
+
const transaction = params.state ? this.#takeTransaction(params.state) : null;
|
|
431
|
+
|
|
432
|
+
if (!transaction && params.state) {
|
|
433
|
+
// No sign-in with this state started in this tab: if this window is a sign-in popup, the
|
|
434
|
+
// opener holds the transaction. Hand the response over and close.
|
|
435
|
+
if (relayToOpener(win, href, params.state, popupChannelName(this.#config.authority, this.#config.clientId))) {
|
|
436
|
+
setTimeout(() => {
|
|
437
|
+
try {
|
|
438
|
+
win.close();
|
|
439
|
+
} catch {
|
|
440
|
+
/* not closable */
|
|
441
|
+
}
|
|
442
|
+
}, 50);
|
|
443
|
+
return { relayed: true, returnTo: null, user: null, denied: false };
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
this.#cleanResponseFromUrl(parsed);
|
|
448
|
+
|
|
449
|
+
if (params.error) throw this.#authorizationError(params);
|
|
450
|
+
if (!params.state) throw new ArkCallbackError('the authorization response carried no `state`.');
|
|
451
|
+
if (!transaction) {
|
|
452
|
+
throw new ArkCallbackError(
|
|
453
|
+
'the authorization response does not belong to a sign-in started in this tab (unknown or expired `state`). ' +
|
|
454
|
+
'Start the sign-in again. If this keeps happening, check that the redirect URI is served by this same origin, ' +
|
|
455
|
+
'and that storage is not being cleared between the two pages.'
|
|
456
|
+
);
|
|
457
|
+
}
|
|
458
|
+
if (!constantTimeEqual(String(params.state), String(transaction.state))) {
|
|
459
|
+
throw new ArkCallbackError('the authorization response `state` does not match the request. Treat this as a CSRF attempt.');
|
|
460
|
+
}
|
|
461
|
+
return this.#completeSignin(params, transaction);
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
async #completeSignin(params, transaction) {
|
|
465
|
+
const metadata = await this.metadata();
|
|
466
|
+
|
|
467
|
+
// RFC 9207. Ark always sends `iss`; when the provider advertises it, a response without one is
|
|
468
|
+
// as suspect as a wrong one, because stripping the parameter is how a mix-up attack hides.
|
|
469
|
+
if (params.iss || metadata.authorization_response_iss_parameter_supported) {
|
|
470
|
+
if (!params.iss) throw new ArkCallbackError('the provider advertises `iss` in authorization responses but this one has none.');
|
|
471
|
+
if (params.iss !== metadata.issuer) throw new ArkCallbackError(`the authorization response came from '${params.iss}', not from '${metadata.issuer}'.`);
|
|
472
|
+
}
|
|
473
|
+
if (!params.code) throw new ArkCallbackError('the authorization response carried no `code`.');
|
|
474
|
+
|
|
475
|
+
const tokens = await this.#exchangeCode({
|
|
476
|
+
code: params.code,
|
|
477
|
+
codeVerifier: transaction.codeVerifier,
|
|
478
|
+
redirectUri: transaction.redirectUri,
|
|
479
|
+
nonce: transaction.nonce ?? null,
|
|
480
|
+
maxAge: transaction.maxAge ?? null
|
|
481
|
+
});
|
|
482
|
+
|
|
483
|
+
const returnTo = localOrDefault(transaction.returnTo, '/');
|
|
484
|
+
const arkClaims = tokens.arkClaims();
|
|
485
|
+
const allowed = await evaluateAccess(this.#config.accountSwitch, this.#config.onEvaluateAccess, {
|
|
486
|
+
claims: tokens.claims ?? {},
|
|
487
|
+
arkClaims,
|
|
488
|
+
tokens
|
|
489
|
+
});
|
|
490
|
+
|
|
491
|
+
if (!allowed) {
|
|
492
|
+
// No token is stored for an account that cannot use the app. The refused identity is kept
|
|
493
|
+
// briefly, tab-local, so the dead end can say whose session it is and offer the way out.
|
|
494
|
+
const denial = describeDenial(ArkAccessDeniedReasons.NO_APP_ACCESS, tokens.claims, arkClaims, returnTo);
|
|
495
|
+
this.#setDenial({ ...denial, idTokenHint: tokens.idToken, createdAt: now() });
|
|
496
|
+
this.#setTokens(null);
|
|
497
|
+
if (tokens.refreshToken) this.#revokeQuietly(tokens.refreshToken);
|
|
498
|
+
this.#publish({ error: null });
|
|
499
|
+
this.#emit('accessDenied', this.#store.get().denial);
|
|
500
|
+
return { returnTo: this.#config.accountSwitch.accessDeniedPath ?? returnTo, user: tokens.claims, denied: true };
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
this.#setDenial(null);
|
|
504
|
+
this.#setTokens(tokens);
|
|
505
|
+
this.#publish({ error: null });
|
|
506
|
+
this.#schedule();
|
|
507
|
+
this.#emit('signedIn', { user: tokens.claims, returnTo });
|
|
508
|
+
this.#broadcast('signed-in');
|
|
509
|
+
return { returnTo, user: tokens.claims, denied: false };
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
// =================================================================
|
|
513
|
+
// Using the session
|
|
514
|
+
// =================================================================
|
|
515
|
+
|
|
516
|
+
/**
|
|
517
|
+
* The access token for an API call, refreshed first when it is about to expire; null when nobody
|
|
518
|
+
* is signed in or the session can no longer be renewed.
|
|
519
|
+
*
|
|
520
|
+
* Read it per call and never keep it: the client replaces it underneath you on every refresh.
|
|
521
|
+
*/
|
|
522
|
+
async getAccessToken({ forceRefresh = false } = {}) {
|
|
523
|
+
if (!this.#win) return null;
|
|
524
|
+
this.#ensureReady();
|
|
525
|
+
if (this.#initPromise) await this.#initPromise;
|
|
526
|
+
else this.#restore();
|
|
527
|
+
|
|
528
|
+
if (!this.#tokens) return null;
|
|
529
|
+
if (forceRefresh || this.#tokens.expired(this.#leeway(this.#tokens))) {
|
|
530
|
+
if (!this.#tokens.refreshToken) {
|
|
531
|
+
if (this.#tokens.expired(0)) {
|
|
532
|
+
this.#endLocalSession('expired', { broadcast: false });
|
|
533
|
+
this.#emit('sessionExpired', { reason: 'expired' });
|
|
534
|
+
return null;
|
|
535
|
+
}
|
|
536
|
+
return this.#tokens.accessToken;
|
|
537
|
+
}
|
|
538
|
+
try {
|
|
539
|
+
await this.refresh();
|
|
540
|
+
} catch (error) {
|
|
541
|
+
if (!this.#tokens) return null; // the session ended (refresh token refused)
|
|
542
|
+
if (this.#tokens.expired(0)) throw error; // offline with a dead token: say so
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
return this.#tokens?.accessToken ?? null;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/**
|
|
549
|
+
* Redeems the refresh token now. Concurrent calls, in this tab and (with Web Locks) across tabs,
|
|
550
|
+
* share one request: Ark rotates refresh tokens and revokes the whole family if a retired one is
|
|
551
|
+
* presented again, so two refreshes racing with the same token would sign the user out.
|
|
552
|
+
*/
|
|
553
|
+
refresh() {
|
|
554
|
+
this.#refreshPromise ??= this.#refreshUnderLock().finally(() => {
|
|
555
|
+
this.#refreshPromise = null;
|
|
556
|
+
});
|
|
557
|
+
return this.#refreshPromise;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
async #refreshUnderLock() {
|
|
561
|
+
this.#ensureReady();
|
|
562
|
+
if (!this.#tokens?.refreshToken) throw new ArkLoginRequiredError('there is no refresh token to renew the session with.');
|
|
563
|
+
|
|
564
|
+
return withLock(`${this.#prefix}refresh`, async () => {
|
|
565
|
+
if (this.#destroyed) throw new ArkError('the client was destroyed.');
|
|
566
|
+
let current = this.#tokens;
|
|
567
|
+
if (!current?.refreshToken) throw new ArkLoginRequiredError();
|
|
568
|
+
|
|
569
|
+
if (this.#storageKind !== 'memory') {
|
|
570
|
+
// Another tab (localStorage), or another instance on this page (a hot-module reload, a
|
|
571
|
+
// micro-frontend; sessionStorage too), may have refreshed or signed out while this one
|
|
572
|
+
// waited for the lock. Redeeming the token it already spent would revoke the family.
|
|
573
|
+
const stored = this.#readStoredTokens();
|
|
574
|
+
if (!stored) {
|
|
575
|
+
this.#endLocalSession('signout', { broadcast: false });
|
|
576
|
+
throw new ArkLoginRequiredError();
|
|
577
|
+
}
|
|
578
|
+
if (stored.refreshToken !== current.refreshToken) {
|
|
579
|
+
if (!stored.expired(this.#leeway(stored))) {
|
|
580
|
+
this.#setTokens(stored, { persist: false });
|
|
581
|
+
this.#publish({ error: null });
|
|
582
|
+
this.#schedule();
|
|
583
|
+
return stored;
|
|
584
|
+
}
|
|
585
|
+
current = stored;
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
if (await this.#isSpent(current.refreshToken)) {
|
|
590
|
+
// Redeemed already, from a copy of this tab's storage ("Duplicate tab" copies
|
|
591
|
+
// sessionStorage). Presenting it again would look like theft to the server and revoke the
|
|
592
|
+
// family for both tabs; this tab signs in afresh instead (silently, while SSO lasts).
|
|
593
|
+
this.#endLocalSession('expired', { broadcast: false });
|
|
594
|
+
this.#emit('sessionExpired', { reason: 'refresh_token_spent' });
|
|
595
|
+
throw new ArkLoginRequiredError('this tab\'s refresh token was already redeemed by a copy of it (a duplicated tab). Sign in again.');
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
let tokens;
|
|
599
|
+
try {
|
|
600
|
+
const metadata = await this.metadata();
|
|
601
|
+
const response = await this.#tokenRequest(metadata.token_endpoint, {
|
|
602
|
+
grant_type: 'refresh_token',
|
|
603
|
+
refresh_token: current.refreshToken
|
|
604
|
+
});
|
|
605
|
+
if (response.refresh_token && response.refresh_token !== current.refreshToken) {
|
|
606
|
+
// The server has rotated: the token just presented is spent, whatever happens next. Keep
|
|
607
|
+
// the new one before anything else can fail (the ID token check below may fetch JWKS),
|
|
608
|
+
// or a retry would present the spent token and the whole family would be revoked.
|
|
609
|
+
await this.#markSpent(current.refreshToken);
|
|
610
|
+
current = TokenSet.fromJSON({ ...current.toJSON(), refresh_token: response.refresh_token });
|
|
611
|
+
this.#setTokens(current);
|
|
612
|
+
}
|
|
613
|
+
tokens = await this.#toTokenSet(response, { nonce: null, subject: current.claims?.sub ?? null, previous: current });
|
|
614
|
+
} catch (error) {
|
|
615
|
+
this.#onRefreshFailure(error);
|
|
616
|
+
throw error;
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
// Stored even by a client destroyed mid-request: the server has already rotated, so the old
|
|
620
|
+
// refresh token in storage is spent, and the next instance must find the new one there.
|
|
621
|
+
this.#setTokens(tokens);
|
|
622
|
+
if (this.#destroyed) return tokens;
|
|
623
|
+
this.#publish({ error: null });
|
|
624
|
+
this.#schedule();
|
|
625
|
+
this.#emit('tokensRefreshed', { expiresAt: tokens.expiresAt });
|
|
626
|
+
this.#broadcast('tokens');
|
|
627
|
+
return tokens;
|
|
628
|
+
}, this.#win);
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
#onRefreshFailure(error) {
|
|
632
|
+
const fatal =
|
|
633
|
+
error instanceof ArkTokenError ||
|
|
634
|
+
(error instanceof ArkOAuthError && ['invalid_grant', 'invalid_client', 'unauthorized_client'].includes(error.error));
|
|
635
|
+
if (fatal) {
|
|
636
|
+
// The refresh token was refused (expired, revoked, its session ended, the account or the
|
|
637
|
+
// client deactivated) or what came back cannot be trusted. Either way the session is over.
|
|
638
|
+
// Other tabs hear about it only when they share these tokens; with per-tab storage each tab
|
|
639
|
+
// holds its own refresh token and finds out for itself.
|
|
640
|
+
const untrusted = error instanceof ArkTokenError ? this.#tokens?.refreshToken : null;
|
|
641
|
+
this.#endLocalSession('expired', { broadcast: this.#sharedStorage() });
|
|
642
|
+
// A response that failed validation may still have rotated: withdraw the token it brought.
|
|
643
|
+
if (untrusted) this.#revokeQuietly(untrusted);
|
|
644
|
+
this.#emit('sessionExpired', { reason: 'refresh_refused', error });
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
647
|
+
this.#emit('refreshFailed', { error });
|
|
648
|
+
if (this.#config.automaticRefresh && this.#tokens && !this.#destroyed) {
|
|
649
|
+
clearTimeout(this.#timer);
|
|
650
|
+
this.#timer = unref(setTimeout(() => this.refresh().catch(() => {}), RETRY_AFTER_NETWORK_FAILURE_MS));
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
/** Whether `ark.fetch()` may attach the access token to this URL: the app's own origin or one in `apiOrigins`. */
|
|
655
|
+
isApiUrl(url) {
|
|
656
|
+
const win = this.#win;
|
|
657
|
+
let target;
|
|
658
|
+
try {
|
|
659
|
+
target = new URL(String(url), win?.location?.href);
|
|
660
|
+
} catch {
|
|
661
|
+
return false;
|
|
662
|
+
}
|
|
663
|
+
const own = win?.location?.origin;
|
|
664
|
+
return target.origin === own || this.#config.apiOrigins.includes(target.origin);
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
/**
|
|
668
|
+
* `fetch` with the access token attached, for the app's own API.
|
|
669
|
+
*
|
|
670
|
+
* The token is sent only to the page's own origin and the origins in `apiOrigins`; anything else
|
|
671
|
+
* is refused rather than quietly handed a bearer token. A 401 that says the token is invalid is
|
|
672
|
+
* retried once after a refresh. Throws ArkLoginRequiredError when nobody is signed in.
|
|
673
|
+
*/
|
|
674
|
+
async fetch(input, init = {}) {
|
|
675
|
+
const win = this.#requireWindow();
|
|
676
|
+
const rawUrl = typeof input === 'string' || input instanceof URL ? String(input) : input?.url;
|
|
677
|
+
if (!this.isApiUrl(rawUrl)) {
|
|
678
|
+
const origin = (() => {
|
|
679
|
+
try {
|
|
680
|
+
return new URL(rawUrl, win.location.href).origin;
|
|
681
|
+
} catch {
|
|
682
|
+
return rawUrl;
|
|
683
|
+
}
|
|
684
|
+
})();
|
|
685
|
+
throw new ArkConfigError(
|
|
686
|
+
`ark_oauth_client: refusing to send the access token to ${origin}. Add that origin to 'apiOrigins' if it is your API, ` +
|
|
687
|
+
'or call it with plain fetch().'
|
|
688
|
+
);
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
const fetchImpl = this.#config.fetch ?? globalThis.fetch;
|
|
692
|
+
const send = (token) => {
|
|
693
|
+
const headers = new Headers(init.headers ?? (typeof Request !== 'undefined' && input instanceof Request ? input.headers : undefined));
|
|
694
|
+
headers.set('Authorization', `Bearer ${token}`);
|
|
695
|
+
return fetchImpl(input, { ...init, headers });
|
|
696
|
+
};
|
|
697
|
+
|
|
698
|
+
const token = await this.getAccessToken();
|
|
699
|
+
if (!token) throw new ArkLoginRequiredError();
|
|
700
|
+
let response = await send(token);
|
|
701
|
+
|
|
702
|
+
const replayable = !(typeof Request !== 'undefined' && input instanceof Request) && !(init.body && typeof init.body.getReader === 'function');
|
|
703
|
+
if (response.status === 401 && replayable && this.#tokens?.refreshToken) {
|
|
704
|
+
const challenge = response.headers.get('WWW-Authenticate') ?? '';
|
|
705
|
+
if (!challenge || /invalid_token/i.test(challenge)) {
|
|
706
|
+
const renewed = await this.getAccessToken({ forceRefresh: true }).catch(() => null);
|
|
707
|
+
if (renewed) response = await send(renewed);
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
return response;
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
/** The UserInfo endpoint (OIDC Core §5.3), with the current access token. */
|
|
714
|
+
async userInfo() {
|
|
715
|
+
const token = await this.getAccessToken();
|
|
716
|
+
if (!token) throw new ArkLoginRequiredError();
|
|
717
|
+
const metadata = await this.metadata();
|
|
718
|
+
return getJson(metadata.userinfo_endpoint, {
|
|
719
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
720
|
+
timeoutMs: this.#config.timeoutMs,
|
|
721
|
+
fetch: this.#config.fetch
|
|
722
|
+
});
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
// =================================================================
|
|
726
|
+
// Signing out and switching account
|
|
727
|
+
// =================================================================
|
|
728
|
+
|
|
729
|
+
/**
|
|
730
|
+
* Signs out of this app and the provider: drops the tokens here, revokes the refresh token, then
|
|
731
|
+
* sends the browser to the provider's end-session endpoint with `id_token_hint`, so the provider
|
|
732
|
+
* ends its session without asking and returns to `postLogoutRedirectUri`.
|
|
733
|
+
*
|
|
734
|
+
* Both halves matter. Dropping only the local tokens leaves the provider's session alive, and the
|
|
735
|
+
* next sign-in is silent, as the same person.
|
|
736
|
+
*
|
|
737
|
+
* @param {{ returnTo?: string, postLogoutRedirectUri?: string, revoke?: boolean }} [options]
|
|
738
|
+
*/
|
|
739
|
+
async signoutRedirect({ returnTo, postLogoutRedirectUri, revoke = true, ...internal } = {}) {
|
|
740
|
+
this.#requireWindow();
|
|
741
|
+
this.#ensureReady();
|
|
742
|
+
const idTokenHint = this.#tokens?.idToken ?? this.#denial?.idTokenHint ?? null;
|
|
743
|
+
const refreshToken = this.#tokens?.refreshToken ?? null;
|
|
744
|
+
let metadata = null;
|
|
745
|
+
try {
|
|
746
|
+
metadata = await this.metadata();
|
|
747
|
+
} catch {
|
|
748
|
+
metadata = null; // provider unreachable: still sign out locally
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
this.#endLocalSession('signout', { broadcast: true });
|
|
752
|
+
if (revoke && refreshToken && metadata?.revocation_endpoint) await this.#revokeQuietly(refreshToken, metadata);
|
|
753
|
+
|
|
754
|
+
const home = localOrDefault(returnTo ?? this.#config.accountSwitch.homePath, '/');
|
|
755
|
+
if (!metadata?.end_session_endpoint) {
|
|
756
|
+
this.#navigate(home);
|
|
757
|
+
return;
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
const params = new URLSearchParams({ client_id: this.#config.clientId });
|
|
761
|
+
if (idTokenHint) params.set('id_token_hint', idTokenHint);
|
|
762
|
+
const target = postLogoutRedirectUri ?? this.#config.postLogoutRedirectUri;
|
|
763
|
+
if (target) {
|
|
764
|
+
const state = createState();
|
|
765
|
+
params.set('post_logout_redirect_uri', this.#resolve(target));
|
|
766
|
+
params.set('state', state);
|
|
767
|
+
writeJson(this.#txStorage, `${this.#prefix}logout:${state}`, {
|
|
768
|
+
returnTo: home,
|
|
769
|
+
then: internal.then ?? null,
|
|
770
|
+
prompt: internal.prompt ?? null,
|
|
771
|
+
loginHint: internal.loginHint ?? null,
|
|
772
|
+
createdAt: now()
|
|
773
|
+
});
|
|
774
|
+
}
|
|
775
|
+
const endpoint = metadata.end_session_endpoint;
|
|
776
|
+
await this.#redirect(`${endpoint}${endpoint.includes('?') ? '&' : '?'}${params}`);
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
/**
|
|
780
|
+
* Signs out of this app only: tokens dropped and the refresh token revoked, the provider's session
|
|
781
|
+
* left alone (the user's other apps stay signed in, and the next sign-in here is silent).
|
|
782
|
+
*/
|
|
783
|
+
async signoutLocal({ revoke = true } = {}) {
|
|
784
|
+
this.#ensureReady();
|
|
785
|
+
const refreshToken = this.#tokens?.refreshToken ?? null;
|
|
786
|
+
this.#endLocalSession('signout', { broadcast: true });
|
|
787
|
+
if (revoke && refreshToken) await this.#revokeQuietly(refreshToken);
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
/**
|
|
791
|
+
* "Sign in as a different user": drops this app's session and signs in again with
|
|
792
|
+
* `prompt=login`, so the provider draws its sign-in form instead of answering from the session
|
|
793
|
+
* already in this browser. With `accountSwitch.endProviderSessionOnSwitch`, the provider session
|
|
794
|
+
* is ended first and the sign-in follows when the browser comes back.
|
|
795
|
+
*/
|
|
796
|
+
async switchUser({ returnTo, loginHint } = {}) {
|
|
797
|
+
const options = this.#config.accountSwitch;
|
|
798
|
+
const target = localOrDefault(returnTo ?? this.#denial?.returnTo ?? null, options.homePath);
|
|
799
|
+
if (options.endProviderSessionOnSwitch) {
|
|
800
|
+
await this.signoutRedirect({ returnTo: target, then: 'signin', prompt: options.prompt, loginHint });
|
|
801
|
+
return;
|
|
802
|
+
}
|
|
803
|
+
await this.signoutLocal();
|
|
804
|
+
await this.signinRedirect({ prompt: options.prompt || 'login', returnTo: target, loginHint });
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
/** Clears a refused sign-in's state without signing in again. */
|
|
808
|
+
clearDenial() {
|
|
809
|
+
this.#ensureReady();
|
|
810
|
+
this.#setDenial(null);
|
|
811
|
+
this.#publish();
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
// =================================================================
|
|
815
|
+
// Provider metadata and token checks
|
|
816
|
+
// =================================================================
|
|
817
|
+
|
|
818
|
+
/** The provider's discovery document, cached. */
|
|
819
|
+
metadata({ force = false } = {}) {
|
|
820
|
+
return this.#metadata.get(force);
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
async jwks() {
|
|
824
|
+
const { jwks_uri: uri } = await this.metadata();
|
|
825
|
+
if (!uri) throw new ArkOAuthError('server_error', "the provider's metadata has no 'jwks_uri'.", { endpoint: this.#config.authority });
|
|
826
|
+
if (!this.#jwks || this.#jwks.uri !== uri) {
|
|
827
|
+
this.#jwks = new JwksCache(uri, {
|
|
828
|
+
ttlMs: this.#config.jwksTtlMs,
|
|
829
|
+
minRefreshIntervalMs: this.#config.jwksMinRefreshIntervalMs,
|
|
830
|
+
timeoutMs: this.#config.timeoutMs,
|
|
831
|
+
fetch: this.#config.fetch
|
|
832
|
+
});
|
|
833
|
+
}
|
|
834
|
+
return this.#jwks;
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
/** Verifies an ID token against the provider's keys and the values of the sign-in it belongs to. */
|
|
838
|
+
async verifyIdToken(idToken, { nonce = null, accessToken = null, code = null, maxAge = null, subject = null } = {}) {
|
|
839
|
+
const metadata = await this.metadata();
|
|
840
|
+
return verifyJwt(idToken, await this.jwks(), {
|
|
841
|
+
issuer: metadata.issuer,
|
|
842
|
+
audience: this.#config.clientId,
|
|
843
|
+
subject: subject ?? undefined,
|
|
844
|
+
nonce,
|
|
845
|
+
accessToken,
|
|
846
|
+
code,
|
|
847
|
+
maxAgeSeconds: maxAge,
|
|
848
|
+
requireTokenHashes: this.#config.requireTokenHashes,
|
|
849
|
+
requireIat: true,
|
|
850
|
+
clockToleranceSeconds: this.#config.clockToleranceSeconds,
|
|
851
|
+
algorithms: this.#config.idTokenSigningAlgorithms ?? metadata.id_token_signing_alg_values_supported ?? undefined
|
|
852
|
+
});
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
// =================================================================
|
|
856
|
+
// Diagnostics
|
|
857
|
+
// =================================================================
|
|
858
|
+
|
|
859
|
+
/**
|
|
860
|
+
* Pairs this app's configuration with the provider's live metadata and reports what does not
|
|
861
|
+
* line up: the browser counterpart of `checkSetup()` in the Node client and `ArkSetupProbe` in
|
|
862
|
+
* .NET. In a browser it also proves CORS, which is the usual first failure of a new SPA and
|
|
863
|
+
* otherwise surfaces as a bare "Failed to fetch". Render it on a setup or health page.
|
|
864
|
+
*/
|
|
865
|
+
async checkSetup() {
|
|
866
|
+
const win = this.#win;
|
|
867
|
+
const config = this.#config;
|
|
868
|
+
const cut = config.authority.lastIndexOf('/');
|
|
869
|
+
const tenantId = config.authority.slice(cut + 1);
|
|
870
|
+
const report = {
|
|
871
|
+
authority: config.authority,
|
|
872
|
+
clientId: config.clientId,
|
|
873
|
+
tenantId,
|
|
874
|
+
origin: win?.location?.origin ?? null,
|
|
875
|
+
secureContext: Boolean(win?.isSecureContext ?? globalThis.isSecureContext),
|
|
876
|
+
webCrypto: Boolean(globalThis.crypto?.subtle),
|
|
877
|
+
storage: (this.#ensureReady(), this.#storageKind),
|
|
878
|
+
scopes: [...config.scopes],
|
|
879
|
+
responseMode: config.responseMode,
|
|
880
|
+
redirectUri: win ? this.#resolve(config.redirectUri) : config.redirectUri,
|
|
881
|
+
postLogoutRedirectUri: config.postLogoutRedirectUri && win ? this.#resolve(config.postLogoutRedirectUri) : config.postLogoutRedirectUri,
|
|
882
|
+
adminConsoleUrl: `${config.authority}/admin`,
|
|
883
|
+
integrationPageUrl: `${config.authority}/oauth2/integrate/${encodeURIComponent(config.clientId)}`,
|
|
884
|
+
discoveryUrl: `${config.authority}/.well-known/openid-configuration`,
|
|
885
|
+
discoveryOk: false,
|
|
886
|
+
jwksOk: false,
|
|
887
|
+
tokenEndpointCorsOk: null,
|
|
888
|
+
provider: null,
|
|
889
|
+
signingKeys: [],
|
|
890
|
+
problems: []
|
|
891
|
+
};
|
|
892
|
+
|
|
893
|
+
if (!report.secureContext || !report.webCrypto) {
|
|
894
|
+
report.problems.push('This page is not a secure context, so crypto.subtle is unavailable. Serve it over https, or over http on localhost only.');
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
let metadata;
|
|
898
|
+
try {
|
|
899
|
+
metadata = await this.metadata({ force: true });
|
|
900
|
+
report.discoveryOk = true;
|
|
901
|
+
} catch (error) {
|
|
902
|
+
report.problems.push(`The provider's discovery document could not be read: ${error.message}`);
|
|
903
|
+
return report;
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
report.provider = {
|
|
907
|
+
issuer: metadata.issuer,
|
|
908
|
+
authorizationEndpoint: metadata.authorization_endpoint,
|
|
909
|
+
tokenEndpoint: metadata.token_endpoint,
|
|
910
|
+
userInfoEndpoint: metadata.userinfo_endpoint,
|
|
911
|
+
jwksUri: metadata.jwks_uri,
|
|
912
|
+
endSessionEndpoint: metadata.end_session_endpoint ?? null,
|
|
913
|
+
revocationEndpoint: metadata.revocation_endpoint ?? null,
|
|
914
|
+
scopesSupported: metadata.scopes_supported ?? [],
|
|
915
|
+
grantTypesSupported: metadata.grant_types_supported ?? [],
|
|
916
|
+
responseModesSupported: metadata.response_modes_supported ?? [],
|
|
917
|
+
codeChallengeMethodsSupported: metadata.code_challenge_methods_supported ?? [],
|
|
918
|
+
tokenEndpointAuthMethodsSupported: metadata.token_endpoint_auth_methods_supported ?? [],
|
|
919
|
+
requirePushedAuthorizationRequests: metadata.require_pushed_authorization_requests === true
|
|
920
|
+
};
|
|
921
|
+
|
|
922
|
+
try {
|
|
923
|
+
const keys = await (await this.jwks()).keys({ force: true });
|
|
924
|
+
report.jwksOk = true;
|
|
925
|
+
report.signingKeys = keys.map((k) => ({ kid: k.kid ?? null, kty: k.kty, alg: k.alg ?? null, use: k.use ?? null }));
|
|
926
|
+
} catch (error) {
|
|
927
|
+
report.problems.push(`The provider's signing keys could not be read: ${error.message}`);
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
// A refresh with a token that cannot exist. Any OAuth error back proves the token endpoint is
|
|
931
|
+
// reachable *and* answers this origin; a network error means CORS (or the endpoint) is missing.
|
|
932
|
+
// Nothing is created or changed on the server.
|
|
933
|
+
try {
|
|
934
|
+
await postForm(
|
|
935
|
+
metadata.token_endpoint,
|
|
936
|
+
{ grant_type: 'refresh_token', refresh_token: 'ark-setup-probe', client_id: config.clientId },
|
|
937
|
+
{ timeoutMs: config.timeoutMs, fetch: config.fetch }
|
|
938
|
+
);
|
|
939
|
+
report.tokenEndpointCorsOk = true;
|
|
940
|
+
} catch (error) {
|
|
941
|
+
report.tokenEndpointCorsOk = !(error instanceof ArkNetworkError);
|
|
942
|
+
if (!report.tokenEndpointCorsOk) report.problems.push(`The token endpoint is not reachable from this page: ${error.message}`);
|
|
943
|
+
else if (error instanceof ArkOAuthError && ['invalid_client', 'unauthorized_client'].includes(error.error)) {
|
|
944
|
+
report.problems.push(
|
|
945
|
+
`The token endpoint refused client '${config.clientId}' (${error.error}${error.errorDescription ? `: ${error.errorDescription}` : ''}). ` +
|
|
946
|
+
"Check the client id, that the client is active, and that it is registered as a public client ('none') for authorization_code and refresh_token."
|
|
947
|
+
);
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
const supportedScopes = new Set(metadata.scopes_supported ?? []);
|
|
952
|
+
const unknown = supportedScopes.size ? config.scopes.filter((s) => !supportedScopes.has(s)) : [];
|
|
953
|
+
if (unknown.length) {
|
|
954
|
+
report.problems.push(`The tenant does not publish the scope(s) ${unknown.join(', ')}. A scope the client is not registered for is rejected outright, not dropped.`);
|
|
955
|
+
}
|
|
956
|
+
if (!(metadata.code_challenge_methods_supported ?? []).includes('S256')) {
|
|
957
|
+
report.problems.push('The tenant does not advertise the S256 PKCE method, which this client always sends.');
|
|
958
|
+
}
|
|
959
|
+
const methods = metadata.token_endpoint_auth_methods_supported ?? [];
|
|
960
|
+
if (methods.length && !methods.includes('none')) {
|
|
961
|
+
report.problems.push("The tenant does not list the 'none' token endpoint auth method, which a browser (public) client needs.");
|
|
962
|
+
}
|
|
963
|
+
const modes = metadata.response_modes_supported ?? [];
|
|
964
|
+
if (modes.length && !modes.includes(config.responseMode)) {
|
|
965
|
+
report.problems.push(`The tenant does not support response_mode '${config.responseMode}' (it lists ${modes.join(', ')}).`);
|
|
966
|
+
}
|
|
967
|
+
if (config.scopes.includes('offline_access') && !(metadata.grant_types_supported ?? ['refresh_token']).includes('refresh_token')) {
|
|
968
|
+
report.problems.push('offline_access is requested but the tenant does not serve the refresh_token grant.');
|
|
969
|
+
}
|
|
970
|
+
if (!config.scopes.includes('offline_access')) {
|
|
971
|
+
report.problems.push('offline_access is not requested, so there is no refresh token: the session ends when the access token expires.');
|
|
972
|
+
}
|
|
973
|
+
if (metadata.require_pushed_authorization_requests === true) {
|
|
974
|
+
report.problems.push('The tenant requires pushed authorization requests, which a browser app cannot make.');
|
|
975
|
+
}
|
|
976
|
+
if (!metadata.end_session_endpoint) {
|
|
977
|
+
report.problems.push('The provider has no end_session_endpoint, so sign-out can only end the local session.');
|
|
978
|
+
}
|
|
979
|
+
return report;
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
/** Stops timers and listeners. For tests, hot-module reloading, and micro-frontends that unmount. */
|
|
983
|
+
destroy() {
|
|
984
|
+
this.#destroyed = true;
|
|
985
|
+
clearTimeout(this.#timer);
|
|
986
|
+
this.#timer = null;
|
|
987
|
+
for (const off of this.#detach.splice(0)) off();
|
|
988
|
+
if (this.#channel) {
|
|
989
|
+
this.#channel.onmessage = null;
|
|
990
|
+
this.#channel.close();
|
|
991
|
+
this.#channel = null;
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
// =================================================================
|
|
996
|
+
// internals: tokens
|
|
997
|
+
// =================================================================
|
|
998
|
+
|
|
999
|
+
async #exchangeCode({ code, codeVerifier, redirectUri, nonce, maxAge }) {
|
|
1000
|
+
const metadata = await this.metadata();
|
|
1001
|
+
const response = await this.#tokenRequest(metadata.token_endpoint, {
|
|
1002
|
+
grant_type: 'authorization_code',
|
|
1003
|
+
code,
|
|
1004
|
+
redirect_uri: redirectUri,
|
|
1005
|
+
code_verifier: codeVerifier
|
|
1006
|
+
});
|
|
1007
|
+
return this.#toTokenSet(response, { nonce, code, maxAge });
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
/** A public client authenticates with nothing but its id, which goes in the body. */
|
|
1011
|
+
#tokenRequest(endpoint, form) {
|
|
1012
|
+
if (!endpoint) throw new ArkOAuthError('server_error', "the provider's metadata has no 'token_endpoint'.", { endpoint: this.#config.authority });
|
|
1013
|
+
return postForm(endpoint, { ...form, client_id: this.#config.clientId }, { timeoutMs: this.#config.timeoutMs, fetch: this.#config.fetch });
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
async #toTokenSet(response, { nonce, code = null, maxAge = null, subject = null, previous = null }) {
|
|
1017
|
+
if (!response.access_token) throw new ArkTokenError('the token response contains no access_token.');
|
|
1018
|
+
let claims = null;
|
|
1019
|
+
if (response.id_token) {
|
|
1020
|
+
// On refresh, OIDC Core §12.2: the new ID token must be about the same user.
|
|
1021
|
+
claims = await this.verifyIdToken(response.id_token, { nonce, accessToken: response.access_token, code, maxAge, subject });
|
|
1022
|
+
} else if (nonce !== null && String(response.scope ?? '').split(' ').includes('openid')) {
|
|
1023
|
+
throw new ArkTokenError('the token response contains no id_token, although the openid scope was granted.');
|
|
1024
|
+
}
|
|
1025
|
+
const merged = { ...response };
|
|
1026
|
+
if (previous) {
|
|
1027
|
+
// Rotation off: the server sends no new refresh token and the old one stays valid. A refresh
|
|
1028
|
+
// response may also omit the ID token; the last one still serves as id_token_hint at sign-out.
|
|
1029
|
+
merged.refresh_token ??= previous.refreshToken;
|
|
1030
|
+
merged.id_token ??= previous.idToken;
|
|
1031
|
+
}
|
|
1032
|
+
return new TokenSet(merged, { claims: claims ?? previous?.claims ?? null });
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
#setTokens(tokens, { persist = true } = {}) {
|
|
1036
|
+
this.#tokens = tokens;
|
|
1037
|
+
this.#derived = tokens
|
|
1038
|
+
? { claims: tokens.claims ? Object.freeze({ ...tokens.claims }) : null, arkClaims: Object.freeze(tokens.arkClaims()), scopes: Object.freeze(tokens.scopes()) }
|
|
1039
|
+
: { claims: null, arkClaims: Object.freeze([]), scopes: Object.freeze([]) };
|
|
1040
|
+
if (!persist) return;
|
|
1041
|
+
if (tokens) writeJson(this.#storage, `${this.#prefix}tokens`, tokens.toJSON());
|
|
1042
|
+
else remove(this.#storage, `${this.#prefix}tokens`);
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
#readStoredTokens() {
|
|
1046
|
+
const data = readJson(this.#storage, `${this.#prefix}tokens`);
|
|
1047
|
+
return data?.access_token ? TokenSet.fromJSON(data) : null;
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
#restore() {
|
|
1051
|
+
if (!this.#tokens) {
|
|
1052
|
+
const stored = this.#readStoredTokens();
|
|
1053
|
+
if (stored) this.#setTokens(stored, { persist: false });
|
|
1054
|
+
}
|
|
1055
|
+
if (!this.#denial) {
|
|
1056
|
+
const denial = readJson(this.#txStorage, `${this.#prefix}denied`);
|
|
1057
|
+
if (denial && now() - (denial.createdAt ?? 0) <= DENIAL_TTL_SECONDS) this.#denial = denial;
|
|
1058
|
+
else if (denial) remove(this.#txStorage, `${this.#prefix}denied`);
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
async #renewIfNeeded() {
|
|
1063
|
+
if (!this.#tokens || !this.#tokens.expired(this.#leeway(this.#tokens))) return;
|
|
1064
|
+
if (!this.#tokens.refreshToken) {
|
|
1065
|
+
if (this.#tokens.expired(0)) this.#endLocalSession('expired', { broadcast: false });
|
|
1066
|
+
return;
|
|
1067
|
+
}
|
|
1068
|
+
try {
|
|
1069
|
+
await this.refresh();
|
|
1070
|
+
} catch {
|
|
1071
|
+
/* already reflected in the state: session ended, or a retry is scheduled */
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
#endLocalSession(reason, { broadcast }) {
|
|
1076
|
+
const hadSession = Boolean(this.#tokens || this.#denial);
|
|
1077
|
+
clearTimeout(this.#timer);
|
|
1078
|
+
this.#timer = null;
|
|
1079
|
+
this.#setTokens(null);
|
|
1080
|
+
this.#setDenial(null);
|
|
1081
|
+
this.#publish();
|
|
1082
|
+
if (hadSession) this.#emit('signedOut', { reason });
|
|
1083
|
+
if (broadcast) this.#broadcast('signed-out');
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
async #revokeQuietly(token, metadata = null) {
|
|
1087
|
+
try {
|
|
1088
|
+
const md = metadata ?? (await this.metadata());
|
|
1089
|
+
if (!md.revocation_endpoint) return;
|
|
1090
|
+
await postFormNoCors(
|
|
1091
|
+
md.revocation_endpoint,
|
|
1092
|
+
{ token, token_type_hint: 'refresh_token', client_id: this.#config.clientId },
|
|
1093
|
+
{ timeoutMs: Math.min(this.#config.timeoutMs, 5000), fetch: this.#config.fetch }
|
|
1094
|
+
);
|
|
1095
|
+
} catch {
|
|
1096
|
+
// Best effort. The provider-side logout ends the session behind the token anyway, and a
|
|
1097
|
+
// refresh token whose session has ended is refused.
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
#schedule() {
|
|
1102
|
+
clearTimeout(this.#timer);
|
|
1103
|
+
this.#timer = null;
|
|
1104
|
+
const tokens = this.#tokens;
|
|
1105
|
+
if (this.#destroyed || !tokens || tokens.expiresAt === null || !this.#win) return;
|
|
1106
|
+
const renew = Boolean(this.#config.automaticRefresh && tokens.refreshToken);
|
|
1107
|
+
// automaticRefresh off with a refresh token in hand: nothing to time; getAccessToken() renews on demand.
|
|
1108
|
+
if (!renew && tokens.refreshToken) return;
|
|
1109
|
+
const at = renew ? tokens.expiresAt - this.#lead(tokens) : tokens.expiresAt;
|
|
1110
|
+
const delay = Math.min(MAX_TIMER_MS, Math.max(0, (at - now()) * 1000));
|
|
1111
|
+
this.#timer = unref(setTimeout(() => {
|
|
1112
|
+
if (renew) {
|
|
1113
|
+
this.refresh().catch(() => {});
|
|
1114
|
+
} else if (this.#tokens === tokens) {
|
|
1115
|
+
this.#endLocalSession('expired', { broadcast: false });
|
|
1116
|
+
this.#emit('sessionExpired', { reason: 'expired' });
|
|
1117
|
+
}
|
|
1118
|
+
}, delay));
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
#sharedStorage() {
|
|
1122
|
+
return this.#storageKind === 'local' || this.#storageKind === 'custom';
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
/**
|
|
1126
|
+
* How early to renew: `refreshBeforeSeconds`, but never more than half the token's lifetime. A
|
|
1127
|
+
* client record with 30- or 60-second access tokens would otherwise be due for renewal the moment
|
|
1128
|
+
* each one arrived, and refresh in a tight loop.
|
|
1129
|
+
*/
|
|
1130
|
+
#lead(tokens, max = this.#config.refreshBeforeSeconds) {
|
|
1131
|
+
if (!tokens || tokens.expiresAt === null) return max;
|
|
1132
|
+
const lifetime = tokens.expiresAt - tokens.issuedAt;
|
|
1133
|
+
return lifetime > 0 ? Math.min(max, lifetime / 2) : max;
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
/** The margin within which a token is renewed on use rather than handed out. */
|
|
1137
|
+
#leeway(tokens) {
|
|
1138
|
+
return this.#lead(tokens, Math.min(30, this.#config.refreshBeforeSeconds));
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
async #spentHash(token) {
|
|
1142
|
+
return base64UrlEncode(await sha256(`${this.#config.clientId}|${token}`)).slice(0, 24);
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
async #isSpent(token) {
|
|
1146
|
+
const hash = await this.#spentHash(token);
|
|
1147
|
+
return (readJson(this.#spentStorage, `${this.#prefix}spent`) ?? []).some((entry) => entry?.h === hash);
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1150
|
+
async #markSpent(token) {
|
|
1151
|
+
const hash = await this.#spentHash(token);
|
|
1152
|
+
const list = (readJson(this.#spentStorage, `${this.#prefix}spent`) ?? []).filter((entry) => entry && entry.h !== hash);
|
|
1153
|
+
list.push({ h: hash, at: now() });
|
|
1154
|
+
writeJson(this.#spentStorage, `${this.#prefix}spent`, list.slice(-SPENT_TOKENS_REMEMBERED));
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
// =================================================================
|
|
1158
|
+
// internals: state, storage, transactions
|
|
1159
|
+
// =================================================================
|
|
1160
|
+
|
|
1161
|
+
#ensureReady() {
|
|
1162
|
+
if (this.#ready) return;
|
|
1163
|
+
this.#ready = true;
|
|
1164
|
+
const { storage, kind } = resolveStorage(this.#config.storage, this.#win);
|
|
1165
|
+
this.#storage = storage;
|
|
1166
|
+
this.#storageKind = kind;
|
|
1167
|
+
// The sign-in transaction has to survive one navigation to the provider and back, in this tab
|
|
1168
|
+
// only. sessionStorage is exactly that, whatever the token storage is.
|
|
1169
|
+
this.#txStorage = kind === 'session' ? storage : resolveStorage('session', this.#win).storage;
|
|
1170
|
+
// Shared by every tab of the origin, so a duplicated tab can see that a refresh token it copied
|
|
1171
|
+
// has been redeemed already. Holds hashes, never tokens.
|
|
1172
|
+
this.#spentStorage = kind === 'local' ? storage : resolveStorage('local', this.#win).storage;
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
#publish(extra = {}) {
|
|
1176
|
+
const tokens = this.#tokens;
|
|
1177
|
+
const denial = this.#denial;
|
|
1178
|
+
this.#store.set({
|
|
1179
|
+
status: tokens ? 'authenticated' : denial ? 'denied' : 'unauthenticated',
|
|
1180
|
+
user: this.#derived.claims,
|
|
1181
|
+
arkClaims: this.#derived.arkClaims,
|
|
1182
|
+
scopes: this.#derived.scopes,
|
|
1183
|
+
expiresAt: tokens?.expiresAt ?? null,
|
|
1184
|
+
denial: denial ? this.#publicDenial(denial) : null,
|
|
1185
|
+
...extra
|
|
1186
|
+
});
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
#publicDenial(denial) {
|
|
1190
|
+
if (this.#publicDenialCache?.source === denial) return this.#publicDenialCache.value;
|
|
1191
|
+
// The ID token kept for the sign-out hint stays internal.
|
|
1192
|
+
const { idTokenHint: _hint, createdAt: _created, ...visible } = denial;
|
|
1193
|
+
const value = Object.freeze({ ...visible, arkClaims: Object.freeze([...(visible.arkClaims ?? [])]) });
|
|
1194
|
+
this.#publicDenialCache = { source: denial, value };
|
|
1195
|
+
return value;
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
#publicDenialCache = null;
|
|
1199
|
+
|
|
1200
|
+
#setDenial(denial) {
|
|
1201
|
+
this.#denial = denial;
|
|
1202
|
+
if (denial) writeJson(this.#txStorage, `${this.#prefix}denied`, denial);
|
|
1203
|
+
else remove(this.#txStorage, `${this.#prefix}denied`);
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
#fail(error) {
|
|
1207
|
+
const wrapped = error instanceof ArkError ? error : new ArkError(String(error?.message ?? error), { cause: error });
|
|
1208
|
+
this.#publish({ error: wrapped });
|
|
1209
|
+
this.#schedule();
|
|
1210
|
+
this.#emit('error', wrapped);
|
|
1211
|
+
return this.#store.get();
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
#saveTransaction(transaction) {
|
|
1215
|
+
writeJson(this.#txStorage, `${this.#prefix}tx:${transaction.state}`, transaction);
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
/** Reads and deletes a transaction: each one completes at most one sign-in. */
|
|
1219
|
+
#takeTransaction(state) {
|
|
1220
|
+
const key = `${this.#prefix}tx:${state}`;
|
|
1221
|
+
const transaction = readJson(this.#txStorage, key);
|
|
1222
|
+
remove(this.#txStorage, key);
|
|
1223
|
+
if (!transaction) return null;
|
|
1224
|
+
if (now() - (transaction.createdAt ?? 0) > this.#config.transactionTtlSeconds) return null;
|
|
1225
|
+
return transaction;
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1228
|
+
#takeLogoutTransaction(href) {
|
|
1229
|
+
const state = this.#responseParams(new URL(href)).state;
|
|
1230
|
+
if (!state) return null;
|
|
1231
|
+
const key = `${this.#prefix}logout:${state}`;
|
|
1232
|
+
const transaction = readJson(this.#txStorage, key);
|
|
1233
|
+
remove(this.#txStorage, key);
|
|
1234
|
+
this.#cleanResponseFromUrl(new URL(href));
|
|
1235
|
+
return transaction;
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
#sweepTransactions() {
|
|
1239
|
+
const limit = this.#config.transactionTtlSeconds;
|
|
1240
|
+
for (const key of keysWithPrefix(this.#txStorage, this.#prefix)) {
|
|
1241
|
+
if (!key.includes(':tx:') && !key.includes(':logout:')) continue;
|
|
1242
|
+
const entry = readJson(this.#txStorage, key);
|
|
1243
|
+
if (!entry || now() - (entry.createdAt ?? 0) > limit) remove(this.#txStorage, key);
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
// =================================================================
|
|
1248
|
+
// internals: URLs and navigation
|
|
1249
|
+
// =================================================================
|
|
1250
|
+
|
|
1251
|
+
#requireWindow() {
|
|
1252
|
+
if (!this.#win) {
|
|
1253
|
+
throw new ArkConfigError(
|
|
1254
|
+
'ark_oauth_client: this needs a browser window. On the server (SSR), create the client but call its methods from the browser only, e.g. in an effect.'
|
|
1255
|
+
);
|
|
1256
|
+
}
|
|
1257
|
+
return this.#win;
|
|
1258
|
+
}
|
|
1259
|
+
|
|
1260
|
+
/** A path becomes an absolute URL on the page's origin; an absolute URL is used as it is. */
|
|
1261
|
+
#resolve(value) {
|
|
1262
|
+
if (!value) return value;
|
|
1263
|
+
if (/^https?:\/\//i.test(value)) return value;
|
|
1264
|
+
return new URL(value, this.#requireWindow().location.origin).toString();
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
/** The response parameters, from the query or the fragment depending on the response mode. */
|
|
1268
|
+
#responseParams(url, responseMode = this.#config.responseMode) {
|
|
1269
|
+
const fromQuery = url.searchParams;
|
|
1270
|
+
const fromHash = new URLSearchParams(url.hash.startsWith('#') ? url.hash.slice(1) : url.hash);
|
|
1271
|
+
const pick = responseMode === 'fragment' ? [fromHash, fromQuery] : [fromQuery, fromHash];
|
|
1272
|
+
const source = pick.find((p) => p.has('state') || p.has('code') || p.has('error')) ?? pick[0];
|
|
1273
|
+
const result = {};
|
|
1274
|
+
for (const name of RESPONSE_PARAMS) {
|
|
1275
|
+
const value = source.get(name);
|
|
1276
|
+
if (value !== null) result[name] = value;
|
|
1277
|
+
}
|
|
1278
|
+
return result;
|
|
1279
|
+
}
|
|
1280
|
+
|
|
1281
|
+
#classify(href) {
|
|
1282
|
+
if (!this.#win) return null;
|
|
1283
|
+
let url;
|
|
1284
|
+
try {
|
|
1285
|
+
url = new URL(href, this.#win.location.href);
|
|
1286
|
+
} catch {
|
|
1287
|
+
return null;
|
|
1288
|
+
}
|
|
1289
|
+
const same = (target) => {
|
|
1290
|
+
if (!target) return false;
|
|
1291
|
+
const t = new URL(this.#resolve(target));
|
|
1292
|
+
return t.origin === url.origin && t.pathname === url.pathname;
|
|
1293
|
+
};
|
|
1294
|
+
const params = this.#responseParams(url);
|
|
1295
|
+
if (same(this.#config.redirectUri) && (params.code || params.error)) return 'signin';
|
|
1296
|
+
if (same(this.#config.postLogoutRedirectUri ?? DEFAULT_POST_LOGOUT_PATH) && params.state) {
|
|
1297
|
+
this.#ensureReady();
|
|
1298
|
+
if (readJson(this.#txStorage, `${this.#prefix}logout:${params.state}`)) return 'signout';
|
|
1299
|
+
}
|
|
1300
|
+
return null;
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
#cleanResponseFromUrl(url) {
|
|
1304
|
+
const win = this.#win;
|
|
1305
|
+
if (!win?.history?.replaceState) return;
|
|
1306
|
+
const clean = new URL(url.toString());
|
|
1307
|
+
for (const name of RESPONSE_PARAMS) clean.searchParams.delete(name);
|
|
1308
|
+
if (clean.hash) {
|
|
1309
|
+
const hash = new URLSearchParams(clean.hash.slice(1));
|
|
1310
|
+
if (RESPONSE_PARAMS.some((name) => hash.has(name))) {
|
|
1311
|
+
for (const name of RESPONSE_PARAMS) hash.delete(name);
|
|
1312
|
+
const rest = hash.toString();
|
|
1313
|
+
clean.hash = rest ? `#${rest}` : '';
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
const relative = `${clean.pathname}${clean.search}${clean.hash}`;
|
|
1317
|
+
try {
|
|
1318
|
+
win.history.replaceState(win.history.state, '', relative);
|
|
1319
|
+
} catch {
|
|
1320
|
+
/* sandboxed: nothing to clean */
|
|
1321
|
+
}
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1324
|
+
#authorizationError(params) {
|
|
1325
|
+
return new ArkOAuthError(params.error, params.error_description, {
|
|
1326
|
+
endpoint: `${this.#config.authority}/oauth2/authorize`,
|
|
1327
|
+
errorUri: params.error_uri ?? null,
|
|
1328
|
+
body: params
|
|
1329
|
+
});
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
async #redirect(url) {
|
|
1333
|
+
if (this.#config.redirect) return this.#config.redirect(url);
|
|
1334
|
+
this.#requireWindow().location.assign(url);
|
|
1335
|
+
}
|
|
1336
|
+
|
|
1337
|
+
/** In-app navigation to a local path without reloading. See init(). */
|
|
1338
|
+
#navigate(to) {
|
|
1339
|
+
if (this.#config.navigate) return this.#config.navigate(to);
|
|
1340
|
+
const win = this.#win;
|
|
1341
|
+
if (!win) return;
|
|
1342
|
+
try {
|
|
1343
|
+
win.history.replaceState(null, '', to);
|
|
1344
|
+
const PopState = win.PopStateEvent ?? globalThis.PopStateEvent;
|
|
1345
|
+
if (typeof PopState === 'function') win.dispatchEvent(new PopState('popstate', { state: null }));
|
|
1346
|
+
} catch {
|
|
1347
|
+
win.location.replace(to);
|
|
1348
|
+
}
|
|
1349
|
+
}
|
|
1350
|
+
|
|
1351
|
+
// =================================================================
|
|
1352
|
+
// internals: events and cross-tab sync
|
|
1353
|
+
// =================================================================
|
|
1354
|
+
|
|
1355
|
+
#emit(event, detail) {
|
|
1356
|
+
for (const handler of [...(this.#events.get(event) ?? [])]) {
|
|
1357
|
+
try {
|
|
1358
|
+
handler(detail);
|
|
1359
|
+
} catch (error) {
|
|
1360
|
+
queueMicrotask(() => {
|
|
1361
|
+
throw error;
|
|
1362
|
+
});
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
|
|
1367
|
+
#broadcast(type) {
|
|
1368
|
+
try {
|
|
1369
|
+
this.#channel?.postMessage({ type, from: this.#id });
|
|
1370
|
+
} catch {
|
|
1371
|
+
/* channel closed */
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
#attachListeners() {
|
|
1376
|
+
const win = this.#win;
|
|
1377
|
+
if (!win || this.#detach.length) return;
|
|
1378
|
+
|
|
1379
|
+
if (this.#config.syncTabs) {
|
|
1380
|
+
const Channel = win.BroadcastChannel ?? globalThis.BroadcastChannel;
|
|
1381
|
+
if (typeof Channel === 'function') {
|
|
1382
|
+
this.#channel = unref(new Channel(`ark-oidc:${this.#config.authority}|${this.#config.clientId}`));
|
|
1383
|
+
this.#channel.onmessage = (event) => this.#onTabMessage(event.data);
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
|
|
1387
|
+
// Timers in a background tab are throttled or frozen; coming back is the moment to catch up.
|
|
1388
|
+
const doc = win.document;
|
|
1389
|
+
if (doc?.addEventListener) {
|
|
1390
|
+
const onVisible = () => {
|
|
1391
|
+
if (doc.visibilityState !== 'visible' || !this.#tokens) return;
|
|
1392
|
+
if (this.#sharedStorage()) this.#adoptStoredTokens();
|
|
1393
|
+
if (this.#tokens?.expired(this.#lead(this.#tokens))) this.#renewIfNeeded();
|
|
1394
|
+
};
|
|
1395
|
+
doc.addEventListener('visibilitychange', onVisible);
|
|
1396
|
+
this.#detach.push(() => doc.removeEventListener('visibilitychange', onVisible));
|
|
1397
|
+
}
|
|
1398
|
+
}
|
|
1399
|
+
|
|
1400
|
+
#onTabMessage(message) {
|
|
1401
|
+
if (!message || message.from === this.#id) return;
|
|
1402
|
+
if (message.type === 'signed-out') {
|
|
1403
|
+
if (this.#tokens || this.#denial) this.#endLocalSession('signout', { broadcast: false });
|
|
1404
|
+
return;
|
|
1405
|
+
}
|
|
1406
|
+
if ((message.type === 'tokens' || message.type === 'signed-in') && this.#sharedStorage()) this.#adoptStoredTokens();
|
|
1407
|
+
}
|
|
1408
|
+
|
|
1409
|
+
#adoptStoredTokens() {
|
|
1410
|
+
const stored = this.#readStoredTokens();
|
|
1411
|
+
if (!stored) {
|
|
1412
|
+
if (this.#tokens) this.#endLocalSession('signout', { broadcast: false });
|
|
1413
|
+
return;
|
|
1414
|
+
}
|
|
1415
|
+
if (stored.accessToken === this.#tokens?.accessToken) return;
|
|
1416
|
+
this.#setTokens(stored, { persist: false });
|
|
1417
|
+
this.#setDenial(null);
|
|
1418
|
+
this.#publish({ error: null });
|
|
1419
|
+
this.#schedule();
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
|
|
1423
|
+
/** Convenience factory, for callers who prefer not to write `new`. */
|
|
1424
|
+
export function createArkClient(options) {
|
|
1425
|
+
return new ArkBrowserClient(options);
|
|
1426
|
+
}
|