ark-oauth-client-js 0.0.0-stage → 2.1.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.
@@ -0,0 +1,2510 @@
1
+ /*! ark-oauth-client-js 2.1.1 | MIT | https://github.com/ir-dev/ark-oauth-oidc */
2
+ var ArkOAuth = (() => {
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/index.js
22
+ var index_exports = {};
23
+ __export(index_exports, {
24
+ ACCOUNT_SWITCH_DEFAULTS: () => ACCOUNT_SWITCH_DEFAULTS,
25
+ ArkAccessDeniedReasons: () => ArkAccessDeniedReasons,
26
+ ArkBrowserClient: () => ArkBrowserClient,
27
+ ArkCallbackError: () => ArkCallbackError,
28
+ ArkChallengeProperties: () => ArkChallengeProperties,
29
+ ArkConfigError: () => ArkConfigError,
30
+ ArkError: () => ArkError,
31
+ ArkLoginRequiredError: () => ArkLoginRequiredError,
32
+ ArkNetworkError: () => ArkNetworkError,
33
+ ArkOAuthError: () => ArkOAuthError,
34
+ ArkPopupError: () => ArkPopupError,
35
+ ArkTokenError: () => ArkTokenError,
36
+ DEFAULT_POST_LOGOUT_PATH: () => DEFAULT_POST_LOGOUT_PATH,
37
+ DEFAULT_REDIRECT_PATH: () => DEFAULT_REDIRECT_PATH,
38
+ DEFAULT_SCOPES: () => DEFAULT_SCOPES,
39
+ INITIAL_SNAPSHOT: () => INITIAL_SNAPSHOT,
40
+ JwksCache: () => JwksCache,
41
+ MemoryStorage: () => MemoryStorage,
42
+ MetadataResolver: () => MetadataResolver,
43
+ SUPPORTED_ALGORITHMS: () => SUPPORTED_ALGORITHMS,
44
+ TokenSet: () => TokenSet,
45
+ VERSION: () => VERSION,
46
+ base64UrlDecode: () => base64UrlDecode,
47
+ base64UrlEncode: () => base64UrlEncode,
48
+ codeChallengeFor: () => codeChallengeFor,
49
+ createArkClient: () => createArkClient,
50
+ createCodeVerifier: () => createCodeVerifier,
51
+ createNonce: () => createNonce,
52
+ createPkcePair: () => createPkcePair,
53
+ createState: () => createState,
54
+ decodeJwt: () => decodeJwt,
55
+ discoveryUrls: () => discoveryUrls,
56
+ localOrDefault: () => localOrDefault,
57
+ normalizeAccountSwitch: () => normalizeAccountSwitch,
58
+ normalizeConfig: () => normalizeConfig,
59
+ randomToken: () => randomToken,
60
+ renderAccessDenied: () => renderAccessDenied,
61
+ validateClaims: () => validateClaims,
62
+ validateTokenHashes: () => validateTokenHashes,
63
+ verifyJwt: () => verifyJwt,
64
+ verifySignature: () => verifySignature
65
+ });
66
+
67
+ // src/version.js
68
+ var VERSION = "2.1.1";
69
+
70
+ // src/errors.js
71
+ var ArkError = class extends Error {
72
+ constructor(message, options) {
73
+ super(message, options);
74
+ this.name = new.target.name;
75
+ }
76
+ };
77
+ var ArkConfigError = class extends ArkError {
78
+ };
79
+ var ArkOAuthError = class _ArkOAuthError extends ArkError {
80
+ constructor(error, description, { status = 0, endpoint = null, errorUri = null, body = null } = {}) {
81
+ super(description ? `${error}: ${description}` : error);
82
+ this.error = error;
83
+ this.errorDescription = description ?? null;
84
+ this.errorUri = errorUri;
85
+ this.status = status;
86
+ this.endpoint = endpoint;
87
+ this.body = body;
88
+ }
89
+ /** Builds the error from a parsed response body, falling back to the HTTP status. */
90
+ static fromResponse(status, body, endpoint) {
91
+ if (body && typeof body === "object" && typeof body.error === "string") {
92
+ return new _ArkOAuthError(body.error, body.error_description, {
93
+ status,
94
+ endpoint,
95
+ errorUri: body.error_uri ?? null,
96
+ body
97
+ });
98
+ }
99
+ return new _ArkOAuthError("server_error", `the endpoint returned HTTP ${status}.`, { status, endpoint, body });
100
+ }
101
+ };
102
+ var ArkTokenError = class extends ArkError {
103
+ constructor(message, { claim = null } = {}) {
104
+ super(message);
105
+ this.claim = claim;
106
+ }
107
+ };
108
+ var ArkCallbackError = class extends ArkError {
109
+ };
110
+ var ArkNetworkError = class extends ArkError {
111
+ };
112
+ var ArkLoginRequiredError = class extends ArkError {
113
+ constructor(message = "no user is signed in, or the session has ended. Call signinRedirect() to sign in.") {
114
+ super(message);
115
+ this.error = "login_required";
116
+ }
117
+ };
118
+ var ArkPopupError = class extends ArkError {
119
+ constructor(reason, message) {
120
+ super(message);
121
+ this.reason = reason;
122
+ }
123
+ };
124
+
125
+ // src/access.js
126
+ var ArkAccessDeniedReasons = Object.freeze({
127
+ /** The provider authenticated them, but they hold no authorization claims for this client. */
128
+ NO_APP_ACCESS: "no_app_access",
129
+ /** They are signed in, but a guard refused the page they asked for. */
130
+ FORBIDDEN: "forbidden"
131
+ });
132
+ var ACCOUNT_SWITCH_DEFAULTS = Object.freeze({
133
+ /**
134
+ * Refuse the sign-in when the access token carries no `ark_claims` for this client. Off, the wrong
135
+ * account is signed in and every guarded view says "forbidden". On, the callback stops before any
136
+ * token is stored and the state becomes `denied`, from where the user can switch.
137
+ *
138
+ * Ark issues the user's whole claim mapping as `ark_claims`, identity names like `email`
139
+ * included, so this check alone admits a user with an identity-only mapping. Name the claims
140
+ * that mean "may use this app" in `requiredClaims`.
141
+ */
142
+ requireArkClaims: false,
143
+ /** Narrow that check: at least one of these. Empty means any `ark_claims` will do. */
144
+ requiredClaims: Object.freeze([]),
145
+ /** Where to send the browser after a refused sign-in. Null stays on the page the user asked for. */
146
+ accessDeniedPath: null,
147
+ /** Sent as `prompt` when switching. `login` is the one every provider honours. */
148
+ prompt: "login",
149
+ /**
150
+ * Make switching a full RP-initiated logout first. Off, only this app's tokens are dropped and
151
+ * the previous user's other apps are left alone; on, they are signed out everywhere (right for a
152
+ * kiosk, heavy-handed for a laptop).
153
+ */
154
+ endProviderSessionOnSwitch: false,
155
+ /** The app's name on the built-in page. Defaults to the client id. */
156
+ appDisplayName: null,
157
+ /** Name the refused account on the page. On a shared browser it is somebody else's address. */
158
+ showSignedInAccount: true,
159
+ /** Offer "Sign out completely" beside "Sign in as a different user". */
160
+ allowFullSignOut: true,
161
+ /** Where "Sign out completely" lands, and the fallback for an absent or off-site return URL. */
162
+ homePath: "/",
163
+ supportUrl: null,
164
+ supportEmail: null
165
+ });
166
+ function localOrDefault(url, fallback = "/") {
167
+ const home = typeof fallback === "string" && fallback.trim() ? fallback : fallback === null ? null : "/";
168
+ if (typeof url !== "string" || !url.trim()) return home;
169
+ const candidate = url.trim();
170
+ if (!candidate.startsWith("/") || candidate.startsWith("//")) return home;
171
+ if (candidate.startsWith("/\\")) return home;
172
+ if (/[\u0000-\u001f\u007f]/.test(candidate)) return home;
173
+ return candidate;
174
+ }
175
+ function normalizeAccountSwitch(options = {}) {
176
+ const merged = { ...ACCOUNT_SWITCH_DEFAULTS };
177
+ for (const [key, value] of Object.entries(options ?? {})) {
178
+ if (Object.prototype.hasOwnProperty.call(ACCOUNT_SWITCH_DEFAULTS, key) && value !== void 0) merged[key] = value;
179
+ }
180
+ for (const key of ["accessDeniedPath", "homePath"]) {
181
+ if (merged[key] !== null && localOrDefault(merged[key], null) !== merged[key]) {
182
+ throw new ArkConfigError(`ark_oauth_client: accountSwitch.${key} must be a local path starting with '/', but is '${merged[key]}'.`);
183
+ }
184
+ }
185
+ if (merged.supportUrl && !/^https?:\/\//i.test(merged.supportUrl)) {
186
+ throw new ArkConfigError(`ark_oauth_client: accountSwitch.supportUrl must be an http(s) URL, but is '${merged.supportUrl}'.`);
187
+ }
188
+ merged.requiredClaims = Object.freeze([...merged.requiredClaims ?? []].map(String));
189
+ return Object.freeze(merged);
190
+ }
191
+ var ArkChallengeProperties = Object.freeze({
192
+ switchUser(returnTo = null, loginHint = null, prompt = "login") {
193
+ return { returnTo: returnTo || "/", prompt: prompt || "login", ...loginHint ? { loginHint } : {} };
194
+ },
195
+ /** The provider's account picker. A provider without one falls back to its sign-in form. */
196
+ selectAccount(returnTo = null) {
197
+ return ArkChallengeProperties.switchUser(returnTo, null, "select_account");
198
+ }
199
+ });
200
+ async function evaluateAccess(options, onEvaluateAccess, { claims = {}, arkClaims = [], tokens = null } = {}) {
201
+ const required = options.requiredClaims.map((c) => c.toLowerCase());
202
+ const allowedByConfiguration = !options.requireArkClaims || (required.length ? arkClaims.some((c) => required.includes(String(c).toLowerCase())) : arkClaims.length > 0);
203
+ if (typeof onEvaluateAccess !== "function") return allowedByConfiguration;
204
+ return Boolean(await onEvaluateAccess({ claims: { ...claims }, arkClaims: [...arkClaims], allowedByConfiguration, tokens }));
205
+ }
206
+ function describeDenial(reason, claims, arkClaims, returnTo) {
207
+ const first = (...names) => {
208
+ for (const name of names) if (claims?.[name]) return String(claims[name]);
209
+ return null;
210
+ };
211
+ return {
212
+ reason,
213
+ subject: first("sub"),
214
+ email: first("email", "preferred_username"),
215
+ name: first("name"),
216
+ arkClaims: [...arkClaims ?? []],
217
+ returnTo: returnTo ?? null
218
+ };
219
+ }
220
+
221
+ // src/config.js
222
+ var DEFAULT_SCOPES = Object.freeze(["openid", "profile", "email", "offline_access"]);
223
+ var DEFAULT_REDIRECT_PATH = "/signin-oidc";
224
+ var DEFAULT_POST_LOGOUT_PATH = "/signout-callback-oidc";
225
+ function isLoopback(url) {
226
+ return ["localhost", "127.0.0.1", "[::1]", "::1"].includes(url.hostname);
227
+ }
228
+ function parseAbsolute(value, setting) {
229
+ let url;
230
+ try {
231
+ url = new URL(value);
232
+ } catch {
233
+ throw new ArkConfigError(`ark_oauth_client: '${setting}' must be an absolute URL, but is '${value}'.`);
234
+ }
235
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
236
+ throw new ArkConfigError(`ark_oauth_client: '${setting}' must be an http or https URL, but is '${value}'.`);
237
+ }
238
+ return url;
239
+ }
240
+ function checkRedirect(value, setting) {
241
+ if (value === null || value === void 0 || value === "") return null;
242
+ const text = String(value);
243
+ if (text.startsWith("/") && !text.startsWith("//")) {
244
+ if (text.includes("#")) throw new ArkConfigError(`ark_oauth_client: '${setting}' must not contain a fragment: ${text}`);
245
+ return text;
246
+ }
247
+ const url = parseAbsolute(text, setting);
248
+ if (url.hash) throw new ArkConfigError(`ark_oauth_client: '${setting}' must not contain a fragment: ${text}`);
249
+ if (url.protocol !== "https:" && !isLoopback(url)) {
250
+ throw new ArkConfigError(`ark_oauth_client: '${setting}' is ${text}. The server accepts http only for loopback addresses (RFC 8252 \xA77.3).`);
251
+ }
252
+ return text;
253
+ }
254
+ function normalizeOrigins(list) {
255
+ return Object.freeze(
256
+ [...list ?? []].map((value) => {
257
+ if (value === "*") {
258
+ throw new ArkConfigError("ark_oauth_client: 'apiOrigins' cannot be '*'. List the exact origins the access token may be sent to.");
259
+ }
260
+ return parseAbsolute(String(value), "apiOrigins").origin;
261
+ })
262
+ );
263
+ }
264
+ function normalizeConfig(options = {}) {
265
+ const {
266
+ authority,
267
+ authServerUrl,
268
+ tenantId,
269
+ clientId,
270
+ clientSecret,
271
+ privateKeyJwt,
272
+ tokenEndpointAuthMethod,
273
+ usePar,
274
+ redirectUri = DEFAULT_REDIRECT_PATH,
275
+ postLogoutRedirectUri = DEFAULT_POST_LOGOUT_PATH,
276
+ scopes,
277
+ responseMode = "query",
278
+ prompt = null,
279
+ acrValues = null,
280
+ extraAuthorizationParams = null,
281
+ storage = "session",
282
+ automaticRefresh = true,
283
+ refreshBeforeSeconds = 60,
284
+ apiOrigins = [],
285
+ syncTabs = true,
286
+ accountSwitch,
287
+ onEvaluateAccess = null,
288
+ onRedirectCallback = null,
289
+ navigate = null,
290
+ redirect = null,
291
+ popup = {},
292
+ transactionTtlSeconds = 600,
293
+ clockToleranceSeconds = 60,
294
+ requireHttps = true,
295
+ requireTokenHashes = true,
296
+ idTokenSigningAlgorithms = null,
297
+ timeoutMs = 1e4,
298
+ metadataTtlMs = 5 * 6e4,
299
+ jwksTtlMs = 5 * 6e4,
300
+ jwksMinRefreshIntervalMs = 1e4,
301
+ fetch: fetchImpl = void 0
302
+ } = options;
303
+ let resolvedAuthority = String(authority ?? "").trim();
304
+ if (!resolvedAuthority && authServerUrl && tenantId) resolvedAuthority = `${String(authServerUrl).replace(/\/+$/, "")}/${tenantId}`;
305
+ if (!resolvedAuthority) {
306
+ throw new ArkConfigError(
307
+ "ark_oauth_client: set 'authority' to the issuer URL of your Ark tenant, {BaseUrl}/{TenantId}, e.g. https://idp.example.com/my_idp. (Or set authServerUrl + tenantId and they are joined for you.)"
308
+ );
309
+ }
310
+ resolvedAuthority = resolvedAuthority.replace(/\/+$/, "");
311
+ const authorityUrl = parseAbsolute(resolvedAuthority, "authority");
312
+ if (requireHttps && authorityUrl.protocol !== "https:" && !isLoopback(authorityUrl)) {
313
+ throw new ArkConfigError(
314
+ `ark_oauth_client: 'authority' is ${resolvedAuthority}, which is plain http. Tokens would cross the network in the clear. Use https, or set requireHttps:false, only ever for local development.`
315
+ );
316
+ }
317
+ if (!clientId || typeof clientId !== "string") {
318
+ throw new ArkConfigError("ark_oauth_client: 'clientId' is required: the client id registered with the tenant.");
319
+ }
320
+ if (clientSecret || privateKeyJwt || tokenEndpointAuthMethod && tokenEndpointAuthMethod !== "none") {
321
+ throw new ArkConfigError(
322
+ "ark_oauth_client: a browser app cannot keep a client secret or a private key: anything in the bundle is readable by every visitor. Register this app as a public client (token endpoint auth method 'none'; PKCE protects the code), or keep the confidential client on a server with ark-oauth-client (Node), ark-oauth-client (Python) or Ark.oAuth.Client (.NET)."
323
+ );
324
+ }
325
+ if (usePar) {
326
+ throw new ArkConfigError(
327
+ "ark_oauth_client: 'usePar' is not available in a browser app: /oauth2/par needs client authentication and serves no CORS. Leave PAR to a server-side client."
328
+ );
329
+ }
330
+ if (!["query", "fragment"].includes(responseMode)) {
331
+ throw new ArkConfigError(
332
+ `ark_oauth_client: 'responseMode' is '${responseMode}'. A browser app reads the response from its own URL, so use 'query' or 'fragment'` + (responseMode === "form_post" ? "; form_post POSTs to a server, which a single-page app does not have." : ".")
333
+ );
334
+ }
335
+ if (!Number.isFinite(refreshBeforeSeconds) || refreshBeforeSeconds < 0) {
336
+ throw new ArkConfigError(`ark_oauth_client: 'refreshBeforeSeconds' must be a number of seconds, not '${refreshBeforeSeconds}'.`);
337
+ }
338
+ return Object.freeze({
339
+ authority: resolvedAuthority,
340
+ clientId,
341
+ redirectUri: checkRedirect(redirectUri, "redirectUri") ?? DEFAULT_REDIRECT_PATH,
342
+ postLogoutRedirectUri: checkRedirect(postLogoutRedirectUri, "postLogoutRedirectUri"),
343
+ scopes: Object.freeze(scopes?.length ? [...scopes] : [...DEFAULT_SCOPES]),
344
+ responseMode,
345
+ prompt,
346
+ acrValues,
347
+ extraAuthorizationParams: extraAuthorizationParams ? Object.freeze({ ...extraAuthorizationParams }) : null,
348
+ storage,
349
+ automaticRefresh: Boolean(automaticRefresh),
350
+ refreshBeforeSeconds,
351
+ apiOrigins: normalizeOrigins(apiOrigins),
352
+ syncTabs: Boolean(syncTabs),
353
+ accountSwitch: normalizeAccountSwitch(accountSwitch),
354
+ onEvaluateAccess,
355
+ onRedirectCallback,
356
+ navigate,
357
+ redirect,
358
+ popup: Object.freeze({ width: 520, height: 680, timeoutMs: 5 * 6e4, ...popup }),
359
+ transactionTtlSeconds,
360
+ clockToleranceSeconds,
361
+ requireHttps,
362
+ requireTokenHashes,
363
+ idTokenSigningAlgorithms: idTokenSigningAlgorithms ? Object.freeze([...idTokenSigningAlgorithms]) : null,
364
+ timeoutMs,
365
+ metadataTtlMs,
366
+ jwksTtlMs,
367
+ jwksMinRefreshIntervalMs,
368
+ fetch: fetchImpl
369
+ });
370
+ }
371
+
372
+ // src/http.js
373
+ var DEFAULT_TIMEOUT_MS = 1e4;
374
+ function timeoutSignal(signal, timeoutMs) {
375
+ let timeout;
376
+ if (typeof AbortSignal.timeout === "function") {
377
+ timeout = AbortSignal.timeout(timeoutMs);
378
+ } else {
379
+ const controller2 = new AbortController();
380
+ setTimeout(() => controller2.abort(new DOMException("The operation timed out.", "TimeoutError")), timeoutMs);
381
+ timeout = controller2.signal;
382
+ }
383
+ if (!signal) return timeout;
384
+ if (typeof AbortSignal.any === "function") return AbortSignal.any([signal, timeout]);
385
+ const controller = new AbortController();
386
+ const forward = (source) => () => controller.abort(source.reason);
387
+ if (signal.aborted) controller.abort(signal.reason);
388
+ signal.addEventListener("abort", forward(signal), { once: true });
389
+ timeout.addEventListener("abort", forward(timeout), { once: true });
390
+ return controller.signal;
391
+ }
392
+ async function readBody(response) {
393
+ const text = await response.text();
394
+ if (!text) return null;
395
+ const type = response.headers.get("content-type") ?? "";
396
+ const trimmed = text.trimStart();
397
+ if (type.includes("json") || trimmed.startsWith("{") || trimmed.startsWith("[")) {
398
+ try {
399
+ return JSON.parse(text);
400
+ } catch {
401
+ return text;
402
+ }
403
+ }
404
+ return text;
405
+ }
406
+ function currentOrigin() {
407
+ try {
408
+ return globalThis.location?.origin ?? null;
409
+ } catch {
410
+ return null;
411
+ }
412
+ }
413
+ function describeFetchFailure(method, url, cause, timeoutMs) {
414
+ const timedOut = cause?.name === "TimeoutError" || cause?.cause?.name === "TimeoutError";
415
+ if (timedOut) return `${method} ${url} timed out after ${timeoutMs}ms.`;
416
+ if (cause?.name === "AbortError") return `${method} ${url} was aborted.`;
417
+ const origin = currentOrigin();
418
+ return `${method} ${url} failed: ${cause?.message ?? cause}. In a browser this is most often CORS: the provider must list this app's origin${origin && origin !== "null" ? ` (${origin})` : ""} in ark_oauth_server:Oidc:CorsOrigins (the Protocol step of the setup wizard). Otherwise the provider is unreachable from here: wrong host or port, offline, or stopped.`;
419
+ }
420
+ async function request(url, options = {}) {
421
+ const {
422
+ method = "GET",
423
+ form,
424
+ headers = {},
425
+ cache,
426
+ timeoutMs = DEFAULT_TIMEOUT_MS,
427
+ signal,
428
+ fetch: fetchImpl = globalThis.fetch
429
+ } = options;
430
+ if (typeof fetchImpl !== "function") {
431
+ throw new ArkNetworkError("no fetch implementation is available; pass `fetch` in the client options.");
432
+ }
433
+ const init = {
434
+ method,
435
+ headers: { Accept: "application/json", ...headers },
436
+ signal: timeoutSignal(signal, timeoutMs),
437
+ // Token and userinfo responses are never cached: a cached userinfo keyed on a bearer token is
438
+ // a different user's tomorrow. Discovery and JWKS pass `default` to reuse the server's max-age.
439
+ cache: cache ?? "no-store",
440
+ // The provider grants CORS without credentials, and nothing here should ever carry the
441
+ // provider's session cookie: a bearer token in a header is the whole of the authentication.
442
+ credentials: "omit",
443
+ // A GET of metadata or keys may follow a redirect (http to https is common), and the issuer
444
+ // check on the document is what establishes trust. A POST carries a code or a refresh token,
445
+ // and a redirect would forward it somewhere else.
446
+ redirect: method === "GET" ? "follow" : "manual"
447
+ };
448
+ if (form) {
449
+ const body2 = new URLSearchParams();
450
+ for (const [key, value] of Object.entries(form)) {
451
+ if (value === void 0 || value === null || value === "") continue;
452
+ body2.set(key, String(value));
453
+ }
454
+ init.body = body2;
455
+ init.headers["Content-Type"] = "application/x-www-form-urlencoded";
456
+ }
457
+ let response;
458
+ try {
459
+ response = await fetchImpl(url, init);
460
+ } catch (cause) {
461
+ throw new ArkNetworkError(describeFetchFailure(method, url, cause, timeoutMs), { cause });
462
+ }
463
+ if (response.type === "opaqueredirect" || response.status >= 300 && response.status < 400) {
464
+ throw new ArkOAuthError("server_error", `${method} ${url} answered with a redirect, which is not followed for a token request.`, {
465
+ status: response.status,
466
+ endpoint: url
467
+ });
468
+ }
469
+ const body = await readBody(response);
470
+ if (!response.ok) throw ArkOAuthError.fromResponse(response.status, body, url);
471
+ return { status: response.status, body, headers: response.headers };
472
+ }
473
+ async function getJson(url, options) {
474
+ const { body } = await request(url, { ...options, method: "GET" });
475
+ if (!body || typeof body !== "object") {
476
+ throw new ArkOAuthError("server_error", `${url} did not return a JSON object.`, { endpoint: url, body });
477
+ }
478
+ return body;
479
+ }
480
+ async function postForm(url, form, options) {
481
+ const { body, status } = await request(url, { ...options, method: "POST", form });
482
+ if (body === null) return {};
483
+ if (typeof body !== "object") {
484
+ throw new ArkOAuthError("server_error", `${url} returned HTTP ${status} with a non-JSON body.`, { endpoint: url, status, body });
485
+ }
486
+ return body;
487
+ }
488
+ async function postFormNoCors(url, form, { timeoutMs = DEFAULT_TIMEOUT_MS, fetch: fetchImpl = globalThis.fetch } = {}) {
489
+ const body = new URLSearchParams();
490
+ for (const [key, value] of Object.entries(form)) {
491
+ if (value !== void 0 && value !== null && value !== "") body.set(key, String(value));
492
+ }
493
+ try {
494
+ await fetchImpl(url, {
495
+ method: "POST",
496
+ mode: "no-cors",
497
+ credentials: "omit",
498
+ cache: "no-store",
499
+ // Survives the page navigating away, which is exactly what a sign-out does next.
500
+ keepalive: true,
501
+ body,
502
+ signal: timeoutSignal(void 0, timeoutMs)
503
+ });
504
+ } catch (cause) {
505
+ throw new ArkNetworkError(describeFetchFailure("POST", url, cause, timeoutMs), { cause });
506
+ }
507
+ }
508
+
509
+ // src/discovery.js
510
+ var DEFAULT_TTL_MS = 5 * 6e4;
511
+ function discoveryUrls(authority) {
512
+ const base = authority.replace(/\/+$/, "");
513
+ const url = new URL(base);
514
+ const path = url.pathname.replace(/\/+$/, "");
515
+ return [`${base}/.well-known/openid-configuration`, `${url.origin}/.well-known/oauth-authorization-server${path}`];
516
+ }
517
+ var MetadataResolver = class {
518
+ #authority;
519
+ #ttlMs;
520
+ #http;
521
+ #entry = null;
522
+ constructor(authority, { ttlMs = DEFAULT_TTL_MS, ...http } = {}) {
523
+ this.#authority = authority.replace(/\/+$/, "");
524
+ this.#ttlMs = ttlMs;
525
+ this.#http = http;
526
+ }
527
+ get(force = false) {
528
+ const hit = this.#entry;
529
+ if (hit && !force && (hit.pending || Date.now() - hit.fetchedAt <= this.#ttlMs)) return hit.promise;
530
+ const entry = { fetchedAt: Date.now(), pending: true };
531
+ entry.promise = this.#fetch(force).then(
532
+ (metadata) => {
533
+ entry.pending = false;
534
+ return metadata;
535
+ },
536
+ (error) => {
537
+ if (this.#entry === entry) this.#entry = null;
538
+ throw error;
539
+ }
540
+ );
541
+ this.#entry = entry;
542
+ return entry.promise;
543
+ }
544
+ clear() {
545
+ this.#entry = null;
546
+ }
547
+ async #fetch(force) {
548
+ const [primary, fallback] = discoveryUrls(this.#authority);
549
+ const options = { ...this.#http, cache: force ? "no-cache" : "default" };
550
+ let metadata;
551
+ try {
552
+ metadata = await getJson(primary, options);
553
+ } catch (error) {
554
+ if (error instanceof ArkOAuthError && error.status === 404) metadata = await getJson(fallback, options);
555
+ else throw error;
556
+ }
557
+ if (!metadata.issuer) {
558
+ throw new ArkOAuthError("server_error", `${primary} returned a document with no 'issuer'.`, { endpoint: primary });
559
+ }
560
+ if (metadata.issuer.replace(/\/+$/, "") !== this.#authority) {
561
+ throw new ArkConfigError(
562
+ `the provider at ${primary} identifies itself as '${metadata.issuer}', but this client is configured for '${this.#authority}'. Set 'authority' to exactly the issuer value: for Ark that is {BaseUrl}/{TenantId}.`
563
+ );
564
+ }
565
+ return Object.freeze(metadata);
566
+ }
567
+ };
568
+
569
+ // src/crypto.js
570
+ function webCrypto() {
571
+ const c = globalThis.crypto;
572
+ if (!c?.getRandomValues) {
573
+ throw new ArkConfigError("ark_oauth_client: this environment has no Web Crypto API (globalThis.crypto).");
574
+ }
575
+ return c;
576
+ }
577
+ function subtle() {
578
+ const s = webCrypto().subtle;
579
+ if (!s) {
580
+ throw new ArkConfigError(
581
+ "ark_oauth_client: crypto.subtle is unavailable because this page is not a secure context. Serve the app over https, or over http only on localhost / 127.0.0.1 during development."
582
+ );
583
+ }
584
+ return s;
585
+ }
586
+ var encoder = new TextEncoder();
587
+ var decoder = new TextDecoder();
588
+ function toBytes(input) {
589
+ if (input instanceof Uint8Array) return input;
590
+ if (input instanceof ArrayBuffer) return new Uint8Array(input);
591
+ if (ArrayBuffer.isView(input)) return new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
592
+ return encoder.encode(String(input));
593
+ }
594
+ function base64UrlEncode(input) {
595
+ const bytes = toBytes(input);
596
+ let binary = "";
597
+ for (let i = 0; i < bytes.length; i += 32768) {
598
+ binary += String.fromCharCode.apply(null, bytes.subarray(i, i + 32768));
599
+ }
600
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
601
+ }
602
+ function base64UrlDecode(value) {
603
+ const normalized = String(value).replace(/-/g, "+").replace(/_/g, "/");
604
+ const padded = normalized + "=".repeat((4 - normalized.length % 4) % 4);
605
+ let binary;
606
+ try {
607
+ binary = atob(padded);
608
+ } catch (cause) {
609
+ throw new ArkTokenError("a token segment is not valid base64url.", { cause });
610
+ }
611
+ const bytes = new Uint8Array(binary.length);
612
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
613
+ return bytes;
614
+ }
615
+ function base64UrlDecodeToString(value) {
616
+ return decoder.decode(base64UrlDecode(value));
617
+ }
618
+ function randomToken(bytes = 32) {
619
+ const buffer = new Uint8Array(bytes);
620
+ webCrypto().getRandomValues(buffer);
621
+ return base64UrlEncode(buffer);
622
+ }
623
+ async function digest(input, hash = "SHA-256") {
624
+ return new Uint8Array(await subtle().digest(hash, toBytes(input)));
625
+ }
626
+ function sha256(input) {
627
+ return digest(input, "SHA-256");
628
+ }
629
+ async function leftHalfHash(value, hash = "SHA-256") {
630
+ const full = await digest(value, hash);
631
+ return base64UrlEncode(full.subarray(0, full.length / 2));
632
+ }
633
+ function constantTimeEqual(a, b) {
634
+ if (typeof a !== "string" || typeof b !== "string") return false;
635
+ const x = encoder.encode(a);
636
+ const y = encoder.encode(b);
637
+ let diff = x.length ^ y.length;
638
+ for (let i = 0; i < Math.max(x.length, y.length); i++) diff |= (x[i] ?? 0) ^ (y[i] ?? 0);
639
+ return diff === 0;
640
+ }
641
+
642
+ // src/jwt.js
643
+ var ALGORITHMS = {
644
+ RS256: { kty: "RSA", hash: "SHA-256", importParams: { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, verifyParams: { name: "RSASSA-PKCS1-v1_5" } },
645
+ RS384: { kty: "RSA", hash: "SHA-384", importParams: { name: "RSASSA-PKCS1-v1_5", hash: "SHA-384" }, verifyParams: { name: "RSASSA-PKCS1-v1_5" } },
646
+ RS512: { kty: "RSA", hash: "SHA-512", importParams: { name: "RSASSA-PKCS1-v1_5", hash: "SHA-512" }, verifyParams: { name: "RSASSA-PKCS1-v1_5" } },
647
+ PS256: { kty: "RSA", hash: "SHA-256", importParams: { name: "RSA-PSS", hash: "SHA-256" }, verifyParams: { name: "RSA-PSS", saltLength: 32 } },
648
+ PS384: { kty: "RSA", hash: "SHA-384", importParams: { name: "RSA-PSS", hash: "SHA-384" }, verifyParams: { name: "RSA-PSS", saltLength: 48 } },
649
+ PS512: { kty: "RSA", hash: "SHA-512", importParams: { name: "RSA-PSS", hash: "SHA-512" }, verifyParams: { name: "RSA-PSS", saltLength: 64 } },
650
+ // JWS carries ECDSA signatures as raw r||s, which is also what Web Crypto expects.
651
+ ES256: { kty: "EC", hash: "SHA-256", crv: "P-256", importParams: { name: "ECDSA", namedCurve: "P-256" }, verifyParams: { name: "ECDSA", hash: "SHA-256" } },
652
+ ES384: { kty: "EC", hash: "SHA-384", crv: "P-384", importParams: { name: "ECDSA", namedCurve: "P-384" }, verifyParams: { name: "ECDSA", hash: "SHA-384" } },
653
+ ES512: { kty: "EC", hash: "SHA-512", crv: "P-521", importParams: { name: "ECDSA", namedCurve: "P-521" }, verifyParams: { name: "ECDSA", hash: "SHA-512" } }
654
+ };
655
+ var SUPPORTED_ALGORITHMS = Object.freeze(Object.keys(ALGORITHMS));
656
+ function hashForAlgorithm(alg) {
657
+ return ALGORITHMS[alg]?.hash ?? "SHA-256";
658
+ }
659
+ var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
660
+ function decodeJwt(token) {
661
+ if (typeof token !== "string") throw new ArkTokenError("the token is not a string.");
662
+ const parts = token.split(".");
663
+ if (parts.length !== 3) throw new ArkTokenError(`the token is not a compact JWS: expected 3 segments, found ${parts.length}.`);
664
+ let header;
665
+ let payload;
666
+ try {
667
+ header = JSON.parse(base64UrlDecodeToString(parts[0]));
668
+ payload = JSON.parse(base64UrlDecodeToString(parts[1]));
669
+ } catch (cause) {
670
+ throw new ArkTokenError("the token header or payload is not valid JSON.", { cause });
671
+ }
672
+ if (!isObject(header) || !isObject(payload)) throw new ArkTokenError("the token header and payload must both be JSON objects.");
673
+ return { header, payload, signature: base64UrlDecode(parts[2]), signingInput: `${parts[0]}.${parts[1]}` };
674
+ }
675
+ async function importVerifyKey(jwk, alg) {
676
+ const spec = ALGORITHMS[alg];
677
+ if (!spec) throw new ArkTokenError(`unsupported signing algorithm '${alg}'.`);
678
+ const material = spec.kty === "RSA" ? { kty: "RSA", n: jwk.n, e: jwk.e } : { kty: "EC", crv: jwk.crv, x: jwk.x, y: jwk.y };
679
+ try {
680
+ return await subtle().importKey("jwk", { ...material, ext: true }, spec.importParams, false, ["verify"]);
681
+ } catch (cause) {
682
+ throw new ArkTokenError(`the published key for kid '${jwk.kid}' could not be imported: ${cause?.message ?? cause}`, { cause });
683
+ }
684
+ }
685
+ async function verifySignature(decoded, jwk, { algorithms, key } = {}) {
686
+ const alg = decoded.header.alg;
687
+ if (!alg || alg === "none") throw new ArkTokenError(`the token declares alg '${alg ?? "missing"}'; unsigned tokens are never accepted.`);
688
+ const allowed = algorithms ?? SUPPORTED_ALGORITHMS;
689
+ if (!allowed.includes(alg)) throw new ArkTokenError(`the token is signed with ${alg}, which this client does not accept (allowed: ${allowed.join(", ")}).`);
690
+ const spec = ALGORITHMS[alg];
691
+ if (!spec) throw new ArkTokenError(`unsupported signing algorithm '${alg}'.`);
692
+ if (jwk.kty !== spec.kty) throw new ArkTokenError(`the signing key is a ${jwk.kty} key but the token declares ${alg}.`);
693
+ if (jwk.alg && jwk.alg !== alg) throw new ArkTokenError(`the key published for kid '${jwk.kid}' is registered for ${jwk.alg}, not ${alg}.`);
694
+ if (jwk.use && jwk.use !== "sig") throw new ArkTokenError(`the key published for kid '${jwk.kid}' is for '${jwk.use}', not signing.`);
695
+ if (spec.crv && jwk.crv !== spec.crv) throw new ArkTokenError(`the key for kid '${jwk.kid}' is on ${jwk.crv}, but ${alg} needs ${spec.crv}.`);
696
+ const cryptoKey = key ?? await importVerifyKey(jwk, alg);
697
+ const ok = await subtle().verify(spec.verifyParams, cryptoKey, decoded.signature, new TextEncoder().encode(decoded.signingInput));
698
+ if (!ok) throw new ArkTokenError("the token signature does not verify against the published key.");
699
+ return true;
700
+ }
701
+ function validateClaims(payload, options = {}) {
702
+ const {
703
+ issuer,
704
+ audience,
705
+ subject,
706
+ nonce,
707
+ maxAgeSeconds,
708
+ clockToleranceSeconds = 60,
709
+ requireExp = true,
710
+ requireIat = false,
711
+ now: now2 = Math.floor(Date.now() / 1e3)
712
+ } = options;
713
+ const fail = (message, claim) => {
714
+ throw new ArkTokenError(message, { claim });
715
+ };
716
+ if (issuer) {
717
+ if (!payload.iss) fail("the token has no `iss` claim.", "iss");
718
+ if (payload.iss !== issuer) fail(`the token was issued by '${payload.iss}', not by '${issuer}'.`, "iss");
719
+ }
720
+ if (audience) {
721
+ const auds = Array.isArray(payload.aud) ? payload.aud : payload.aud ? [payload.aud] : [];
722
+ if (auds.length === 0) fail("the token has no `aud` claim.", "aud");
723
+ if (!auds.includes(audience)) fail(`the token is addressed to ${auds.map((a) => `'${a}'`).join(", ")}, not to '${audience}'.`, "aud");
724
+ if (auds.length > 1 && payload.azp && payload.azp !== audience) fail(`the token names '${payload.azp}' as its authorized party, not '${audience}'.`, "azp");
725
+ }
726
+ if (subject && payload.sub !== subject) fail(`the token belongs to subject '${payload.sub}', not '${subject}'.`, "sub");
727
+ if (payload.exp === void 0) {
728
+ if (requireExp) fail("the token has no `exp` claim.", "exp");
729
+ } else if (typeof payload.exp !== "number" || now2 >= payload.exp + clockToleranceSeconds) {
730
+ fail(`the token expired at ${new Date((Number(payload.exp) || 0) * 1e3).toISOString()}.`, "exp");
731
+ }
732
+ for (const claim of ["nbf", "iat"]) {
733
+ if (payload[claim] !== void 0 && (typeof payload[claim] !== "number" || !Number.isFinite(payload[claim]))) {
734
+ fail(`the token's \`${claim}\` is not a NumericDate.`, claim);
735
+ }
736
+ }
737
+ if (payload.nbf !== void 0 && now2 + clockToleranceSeconds < payload.nbf) {
738
+ fail(`the token is not valid before ${new Date(payload.nbf * 1e3).toISOString()}.`, "nbf");
739
+ }
740
+ if (payload.iat === void 0) {
741
+ if (requireIat) fail("the token has no `iat` claim.", "iat");
742
+ } else if (now2 + clockToleranceSeconds < payload.iat) {
743
+ fail(`the token was issued in the future, at ${new Date(payload.iat * 1e3).toISOString()}.`, "iat");
744
+ }
745
+ if (nonce !== void 0 && nonce !== null) {
746
+ if (!payload.nonce) fail("the ID token has no `nonce`, so it cannot be tied to this sign-in.", "nonce");
747
+ if (payload.nonce !== nonce) fail("the ID token `nonce` does not match the one sent with the authorization request.", "nonce");
748
+ }
749
+ if (maxAgeSeconds !== void 0 && maxAgeSeconds !== null) {
750
+ if (typeof payload.auth_time !== "number") fail("`max_age` was requested but the ID token carries no `auth_time`.", "auth_time");
751
+ if (now2 - payload.auth_time > maxAgeSeconds + clockToleranceSeconds) {
752
+ fail(`the user authenticated ${now2 - payload.auth_time}s ago, beyond the requested max_age of ${maxAgeSeconds}s.`, "auth_time");
753
+ }
754
+ }
755
+ return payload;
756
+ }
757
+ async function validateTokenHashes(payload, { alg = "RS256", accessToken, code, require: required = true } = {}) {
758
+ const hash = hashForAlgorithm(alg);
759
+ for (const [claim, value] of [
760
+ ["at_hash", accessToken],
761
+ ["c_hash", code]
762
+ ]) {
763
+ if (!value) continue;
764
+ const present = payload[claim];
765
+ if (!present) {
766
+ if (required) {
767
+ throw new ArkTokenError(
768
+ `the ID token has no \`${claim}\`, so the ${claim === "at_hash" ? "access token" : "authorization code"} it arrived with cannot be tied to it.`,
769
+ { claim }
770
+ );
771
+ }
772
+ continue;
773
+ }
774
+ if (present !== await leftHalfHash(value, hash)) {
775
+ throw new ArkTokenError(`the ID token \`${claim}\` does not cover the value it arrived with; it may have been substituted.`, { claim });
776
+ }
777
+ }
778
+ return payload;
779
+ }
780
+ async function verifyJwt(token, jwks, options = {}) {
781
+ const decoded = decodeJwt(token);
782
+ const { jwk, key } = await jwks.getSigningKey(decoded.header.kid, decoded.header.alg);
783
+ await verifySignature(decoded, jwk, { algorithms: options.algorithms, key });
784
+ validateClaims(decoded.payload, options);
785
+ if (options.accessToken || options.code) {
786
+ await validateTokenHashes(decoded.payload, {
787
+ alg: decoded.header.alg,
788
+ accessToken: options.accessToken,
789
+ code: options.code,
790
+ require: options.requireTokenHashes !== false
791
+ });
792
+ }
793
+ return decoded.payload;
794
+ }
795
+
796
+ // src/jwks.js
797
+ var KTY_FOR_ALG = { RS: "RSA", PS: "RSA", ES: "EC" };
798
+ var MAX_REMEMBERED_MISSES = 64;
799
+ var JwksCache = class {
800
+ #uri;
801
+ #ttlMs;
802
+ #cooldownMs;
803
+ #http;
804
+ #keys = null;
805
+ #fetchedAt = 0;
806
+ #forcedAt = 0;
807
+ #inFlight = null;
808
+ #missing = /* @__PURE__ */ new Set();
809
+ #imported = /* @__PURE__ */ new Map();
810
+ constructor(jwksUri, { ttlMs = 5 * 6e4, minRefreshIntervalMs = 1e4, ...http } = {}) {
811
+ this.#uri = jwksUri;
812
+ this.#ttlMs = ttlMs;
813
+ this.#cooldownMs = minRefreshIntervalMs;
814
+ this.#http = http;
815
+ }
816
+ get uri() {
817
+ return this.#uri;
818
+ }
819
+ /** Every published key, fetching or refreshing as needed. */
820
+ async keys({ force = false } = {}) {
821
+ const stale = Date.now() - this.#fetchedAt > this.#ttlMs;
822
+ if (this.#keys && !force && !stale) return this.#keys;
823
+ return this.#load(force);
824
+ }
825
+ /**
826
+ * The key that signed a token, as `{ jwk, key }` where `key` is the imported CryptoKey.
827
+ *
828
+ * A token with no `kid` resolves only when exactly one usable key is published: guessing among
829
+ * several would mean trying each until one verifies.
830
+ */
831
+ async getSigningKey(kid, alg) {
832
+ let candidates = this.#select(await this.keys(), kid, alg);
833
+ if (candidates.length === 0) {
834
+ const marker = kid ?? "\0none";
835
+ if (!this.#missing.has(marker) && Date.now() - this.#forcedAt >= this.#cooldownMs) {
836
+ candidates = this.#select(await this.keys({ force: true }), kid, alg);
837
+ }
838
+ if (candidates.length === 0) {
839
+ if (this.#missing.size >= MAX_REMEMBERED_MISSES) this.#missing.clear();
840
+ this.#missing.add(marker);
841
+ }
842
+ }
843
+ if (candidates.length === 0) {
844
+ throw new ArkTokenError(
845
+ kid ? `no key with kid '${kid}' is published at ${this.#uri}; the token may have been signed by a different provider.` : `the token carries no 'kid' and ${this.#uri} publishes more than one key, so the signing key is ambiguous.`
846
+ );
847
+ }
848
+ const jwk = candidates[0];
849
+ const cacheKey = `${jwk.kid ?? ""}|${alg}|${jwk.n ?? jwk.x ?? ""}`;
850
+ let key = this.#imported.get(cacheKey);
851
+ if (!key) {
852
+ key = await importVerifyKey(jwk, alg);
853
+ this.#imported.set(cacheKey, key);
854
+ }
855
+ return { jwk, key };
856
+ }
857
+ clear() {
858
+ this.#keys = null;
859
+ this.#fetchedAt = 0;
860
+ this.#forcedAt = 0;
861
+ this.#missing.clear();
862
+ this.#imported.clear();
863
+ }
864
+ #select(keys, kid, alg) {
865
+ const wantedKty = KTY_FOR_ALG[String(alg ?? "").slice(0, 2)];
866
+ const usable = keys.filter((k) => (!k.use || k.use === "sig") && (!wantedKty || k.kty === wantedKty) && (!k.alg || !alg || k.alg === alg));
867
+ if (kid) return usable.filter((k) => k.kid === kid);
868
+ return usable.length === 1 ? usable : [];
869
+ }
870
+ async #load(force) {
871
+ if (force) this.#forcedAt = Date.now();
872
+ this.#inFlight ??= (async () => {
873
+ try {
874
+ const document = await getJson(this.#uri, { ...this.#http, cache: force ? "no-cache" : "default" });
875
+ const keys = Array.isArray(document.keys) ? document.keys : [];
876
+ if (keys.length === 0) throw new ArkTokenError(`${this.#uri} published no keys.`);
877
+ this.#keys = keys;
878
+ this.#fetchedAt = Date.now();
879
+ this.#missing.clear();
880
+ return keys;
881
+ } finally {
882
+ this.#inFlight = null;
883
+ }
884
+ })();
885
+ return this.#inFlight;
886
+ }
887
+ };
888
+
889
+ // src/tokens.js
890
+ var TokenSet = class _TokenSet {
891
+ /**
892
+ * @param {object} response the raw JSON from /oauth2/token
893
+ * @param {{ issuedAt?: number, claims?: object|null }} [options]
894
+ */
895
+ constructor(response = {}, { issuedAt = Math.floor(Date.now() / 1e3), claims = null } = {}) {
896
+ this.accessToken = response.access_token ?? null;
897
+ this.tokenType = response.token_type ?? "Bearer";
898
+ this.refreshToken = response.refresh_token ?? null;
899
+ this.idToken = response.id_token ?? null;
900
+ this.scope = response.scope ?? null;
901
+ this.issuedAt = issuedAt;
902
+ this.expiresAt = typeof response.expires_in === "number" ? issuedAt + response.expires_in : response.expires_at ?? null;
903
+ this.claims = claims;
904
+ }
905
+ /** Seconds until expiry; negative once passed; null when the server gave no lifetime. */
906
+ expiresIn(now2 = Math.floor(Date.now() / 1e3)) {
907
+ return this.expiresAt === null ? null : this.expiresAt - now2;
908
+ }
909
+ /** Whether the access token should be treated as spent, `leewaySeconds` early. */
910
+ expired(leewaySeconds = 0, now2 = Math.floor(Date.now() / 1e3)) {
911
+ if (this.expiresAt === null) return false;
912
+ return now2 >= this.expiresAt - leewaySeconds;
913
+ }
914
+ scopes() {
915
+ return this.scope ? this.scope.split(" ").filter(Boolean) : [];
916
+ }
917
+ hasScope(...wanted) {
918
+ const granted = new Set(this.scopes());
919
+ return wanted.flat().every((s) => granted.has(s));
920
+ }
921
+ /**
922
+ * The tenant's authorization claims from the access token: Ark's `ark_claims`.
923
+ *
924
+ * These, not scopes, are what an app authorises against. Scopes say what the client asked for;
925
+ * `ark_claims` say what this user may do in this client.
926
+ */
927
+ arkClaims() {
928
+ const claims = this.accessTokenClaims()?.ark_claims;
929
+ if (Array.isArray(claims)) return claims.map(String);
930
+ return typeof claims === "string" ? [claims] : [];
931
+ }
932
+ /** The access token's own claims, unverified: for display and `sub`, never for authorising. */
933
+ accessTokenClaims() {
934
+ if (!this.accessToken) return null;
935
+ try {
936
+ return decodeJwt(this.accessToken).payload;
937
+ } catch {
938
+ return null;
939
+ }
940
+ }
941
+ get subject() {
942
+ return this.claims?.sub ?? this.accessTokenClaims()?.sub ?? null;
943
+ }
944
+ authorizationHeader() {
945
+ return `${this.tokenType} ${this.accessToken}`;
946
+ }
947
+ toJSON() {
948
+ return {
949
+ access_token: this.accessToken,
950
+ token_type: this.tokenType,
951
+ refresh_token: this.refreshToken,
952
+ id_token: this.idToken,
953
+ scope: this.scope,
954
+ expires_at: this.expiresAt,
955
+ issued_at: this.issuedAt,
956
+ claims: this.claims
957
+ };
958
+ }
959
+ static fromJSON(data) {
960
+ if (!data) return null;
961
+ if (data instanceof _TokenSet) return data;
962
+ return new _TokenSet(data, { issuedAt: data.issued_at ?? Math.floor(Date.now() / 1e3), claims: data.claims ?? null });
963
+ }
964
+ };
965
+
966
+ // src/pkce.js
967
+ function createCodeVerifier() {
968
+ return randomToken(32);
969
+ }
970
+ async function codeChallengeFor(verifier) {
971
+ return base64UrlEncode(await sha256(verifier));
972
+ }
973
+ function createState() {
974
+ return randomToken(24);
975
+ }
976
+ function createNonce() {
977
+ return randomToken(24);
978
+ }
979
+ async function createPkcePair() {
980
+ const codeVerifier = createCodeVerifier();
981
+ return { codeVerifier, codeChallenge: await codeChallengeFor(codeVerifier), codeChallengeMethod: "S256" };
982
+ }
983
+
984
+ // src/store.js
985
+ var INITIAL_SNAPSHOT = Object.freeze({
986
+ status: "loading",
987
+ isLoading: true,
988
+ isAuthenticated: false,
989
+ user: null,
990
+ arkClaims: Object.freeze([]),
991
+ scopes: Object.freeze([]),
992
+ expiresAt: null,
993
+ error: null,
994
+ denial: null
995
+ });
996
+ var ArkStore = class {
997
+ #state = INITIAL_SNAPSHOT;
998
+ #listeners = /* @__PURE__ */ new Set();
999
+ get() {
1000
+ return this.#state;
1001
+ }
1002
+ /** Replaces the state with `patch` merged in, and notifies, unless nothing changed. */
1003
+ set(patch) {
1004
+ const next = { ...this.#state, ...patch };
1005
+ next.isLoading = next.status === "loading";
1006
+ next.isAuthenticated = next.status === "authenticated";
1007
+ if (Object.keys(next).every((key) => Object.is(next[key], this.#state[key]))) return this.#state;
1008
+ this.#state = Object.freeze(next);
1009
+ for (const listener of [...this.#listeners]) {
1010
+ try {
1011
+ listener(this.#state);
1012
+ } catch (error) {
1013
+ queueMicrotask(() => {
1014
+ throw error;
1015
+ });
1016
+ }
1017
+ }
1018
+ return this.#state;
1019
+ }
1020
+ subscribe(listener) {
1021
+ this.#listeners.add(listener);
1022
+ return () => this.#listeners.delete(listener);
1023
+ }
1024
+ };
1025
+
1026
+ // src/storage.js
1027
+ var MemoryStorage = class {
1028
+ #map = /* @__PURE__ */ new Map();
1029
+ getItem(key) {
1030
+ return this.#map.has(key) ? this.#map.get(key) : null;
1031
+ }
1032
+ setItem(key, value) {
1033
+ this.#map.set(key, String(value));
1034
+ }
1035
+ removeItem(key) {
1036
+ this.#map.delete(key);
1037
+ }
1038
+ key(index) {
1039
+ return [...this.#map.keys()][index] ?? null;
1040
+ }
1041
+ get length() {
1042
+ return this.#map.size;
1043
+ }
1044
+ clear() {
1045
+ this.#map.clear();
1046
+ }
1047
+ };
1048
+ function isStorageLike(value) {
1049
+ return value && typeof value.getItem === "function" && typeof value.setItem === "function" && typeof value.removeItem === "function";
1050
+ }
1051
+ function probe(storage) {
1052
+ try {
1053
+ const key = "__ark_probe__";
1054
+ storage.setItem(key, "1");
1055
+ storage.removeItem(key);
1056
+ return storage;
1057
+ } catch {
1058
+ return null;
1059
+ }
1060
+ }
1061
+ function resolveStorage(option, win) {
1062
+ if (isStorageLike(option)) return { storage: option, kind: "custom" };
1063
+ if (option === "memory" || !win) return { storage: new MemoryStorage(), kind: "memory" };
1064
+ if (option === "session" || option === "local") {
1065
+ let candidate = null;
1066
+ try {
1067
+ candidate = option === "session" ? win.sessionStorage : win.localStorage;
1068
+ } catch {
1069
+ candidate = null;
1070
+ }
1071
+ const usable = candidate ? probe(candidate) : null;
1072
+ return usable ? { storage: usable, kind: option } : { storage: new MemoryStorage(), kind: "memory" };
1073
+ }
1074
+ throw new ArkConfigError(`ark_oauth_client: 'storage' must be 'session', 'local', 'memory' or a Storage-like object, not '${option}'.`);
1075
+ }
1076
+ function readJson(storage, key) {
1077
+ try {
1078
+ const raw = storage.getItem(key);
1079
+ return raw ? JSON.parse(raw) : null;
1080
+ } catch {
1081
+ return null;
1082
+ }
1083
+ }
1084
+ function writeJson(storage, key, value) {
1085
+ try {
1086
+ storage.setItem(key, JSON.stringify(value));
1087
+ return true;
1088
+ } catch {
1089
+ return false;
1090
+ }
1091
+ }
1092
+ function remove(storage, key) {
1093
+ try {
1094
+ storage.removeItem(key);
1095
+ } catch {
1096
+ }
1097
+ }
1098
+ function keysWithPrefix(storage, prefix) {
1099
+ const found = [];
1100
+ try {
1101
+ const count = storage.length ?? 0;
1102
+ for (let i = 0; i < count; i++) {
1103
+ const key = storage.key(i);
1104
+ if (key && key.startsWith(prefix)) found.push(key);
1105
+ }
1106
+ } catch {
1107
+ }
1108
+ return found;
1109
+ }
1110
+
1111
+ // src/lock.js
1112
+ async function withLock(name, fn, win) {
1113
+ const locks = win?.navigator?.locks ?? globalThis.navigator?.locks;
1114
+ if (locks && typeof locks.request === "function") {
1115
+ return locks.request(name, { mode: "exclusive" }, () => fn());
1116
+ }
1117
+ return fn();
1118
+ }
1119
+
1120
+ // src/popup.js
1121
+ var POPUP_MESSAGE_TYPE = "ark-oidc:callback";
1122
+ function popupChannelName(authority, clientId) {
1123
+ return `ark-oidc:${authority}|${clientId}:popup`;
1124
+ }
1125
+ function openPopupWindow(win, { width = 520, height = 680 } = {}) {
1126
+ const screenLeft = win.screenX ?? win.screenLeft ?? 0;
1127
+ const screenTop = win.screenY ?? win.screenTop ?? 0;
1128
+ const outerWidth = win.outerWidth ?? width;
1129
+ const outerHeight = win.outerHeight ?? height;
1130
+ const left = Math.max(0, Math.round(screenLeft + (outerWidth - width) / 2));
1131
+ const top = Math.max(0, Math.round(screenTop + (outerHeight - height) / 2));
1132
+ const features = `popup=yes,width=${width},height=${height},left=${left},top=${top},resizable=yes,scrollbars=yes`;
1133
+ let popup = null;
1134
+ try {
1135
+ popup = win.open("", "ark-oidc-popup", features);
1136
+ } catch {
1137
+ popup = null;
1138
+ }
1139
+ if (!popup) {
1140
+ throw new ArkPopupError(
1141
+ "blocked",
1142
+ "the browser blocked the sign-in popup. Call signinPopup() directly from a click handler, before any await, or use signinRedirect()."
1143
+ );
1144
+ }
1145
+ return popup;
1146
+ }
1147
+ function waitForPopupCallback(win, popup, { state, channelName, timeoutMs }) {
1148
+ let settle;
1149
+ const promise = new Promise((resolve, reject) => {
1150
+ let done = false;
1151
+ let channel = null;
1152
+ let closedTimer = null;
1153
+ let closedGrace = null;
1154
+ let timeoutTimer = null;
1155
+ const cleanup = () => {
1156
+ done = true;
1157
+ win.removeEventListener("message", onMessage);
1158
+ if (channel) {
1159
+ channel.onmessage = null;
1160
+ channel.close();
1161
+ }
1162
+ clearInterval(closedTimer);
1163
+ clearTimeout(closedGrace);
1164
+ clearTimeout(timeoutTimer);
1165
+ };
1166
+ const accept = (data) => {
1167
+ if (done || !data || data.type !== POPUP_MESSAGE_TYPE || data.state !== state || typeof data.url !== "string") return;
1168
+ cleanup();
1169
+ resolve(data.url);
1170
+ };
1171
+ const onMessage = (event) => {
1172
+ if (event.origin !== win.location.origin) return;
1173
+ accept(event.data);
1174
+ };
1175
+ win.addEventListener("message", onMessage);
1176
+ const Channel = win.BroadcastChannel ?? globalThis.BroadcastChannel;
1177
+ if (typeof Channel === "function") {
1178
+ channel = new Channel(channelName);
1179
+ channel.onmessage = (event) => accept(event.data);
1180
+ }
1181
+ closedTimer = setInterval(() => {
1182
+ let closed = false;
1183
+ try {
1184
+ closed = popup.closed;
1185
+ } catch {
1186
+ closed = false;
1187
+ }
1188
+ if (closed && !done && !closedGrace) {
1189
+ closedGrace = setTimeout(() => {
1190
+ if (done) return;
1191
+ cleanup();
1192
+ reject(new ArkPopupError("closed", "the sign-in popup was closed before the sign-in finished."));
1193
+ }, 400);
1194
+ }
1195
+ }, 250);
1196
+ timeoutTimer = setTimeout(() => {
1197
+ if (done) return;
1198
+ cleanup();
1199
+ try {
1200
+ popup.close();
1201
+ } catch {
1202
+ }
1203
+ reject(new ArkPopupError("timeout", `the sign-in popup did not finish within ${Math.round(timeoutMs / 1e3)}s.`));
1204
+ }, timeoutMs);
1205
+ settle = (error) => {
1206
+ if (done) return;
1207
+ cleanup();
1208
+ reject(error);
1209
+ };
1210
+ });
1211
+ return { promise, cancel: (error) => settle(error ?? new ArkPopupError("closed", "the sign-in popup was cancelled.")) };
1212
+ }
1213
+ function relayToOpener(win, url, state, channelName) {
1214
+ let delivered = false;
1215
+ const message = { type: POPUP_MESSAGE_TYPE, url, state };
1216
+ try {
1217
+ const opener = win.opener;
1218
+ if (opener && opener !== win) {
1219
+ opener.postMessage(message, win.location.origin);
1220
+ delivered = true;
1221
+ }
1222
+ } catch {
1223
+ }
1224
+ const Channel = win.BroadcastChannel ?? globalThis.BroadcastChannel;
1225
+ if (typeof Channel === "function") {
1226
+ try {
1227
+ const channel = new Channel(channelName);
1228
+ channel.postMessage(message);
1229
+ channel.close();
1230
+ delivered = delivered || Boolean(win.opener) || win.name === "ark-oidc-popup";
1231
+ } catch {
1232
+ }
1233
+ }
1234
+ return delivered;
1235
+ }
1236
+
1237
+ // src/client.js
1238
+ var RESPONSE_PARAMS = ["code", "state", "iss", "error", "error_description", "error_uri", "session_state"];
1239
+ var DENIAL_TTL_SECONDS = 300;
1240
+ var RETRY_AFTER_NETWORK_FAILURE_MS = 15e3;
1241
+ var SPENT_TOKENS_REMEMBERED = 50;
1242
+ var MAX_TIMER_MS = 2147483647;
1243
+ var EVENTS = ["signedIn", "signedOut", "tokensRefreshed", "refreshFailed", "sessionExpired", "accessDenied", "error"];
1244
+ var now = () => Math.floor(Date.now() / 1e3);
1245
+ var instanceCounter = 0;
1246
+ function unref(handle) {
1247
+ if (handle && typeof handle.unref === "function") handle.unref();
1248
+ return handle;
1249
+ }
1250
+ var ArkBrowserClient = class {
1251
+ #config;
1252
+ #win;
1253
+ #metadata;
1254
+ #jwks = null;
1255
+ #store = new ArkStore();
1256
+ #events = new Map(EVENTS.map((name) => [name, /* @__PURE__ */ new Set()]));
1257
+ #id = `ark-${++instanceCounter}-${Math.random().toString(36).slice(2, 8)}`;
1258
+ #ready = false;
1259
+ #storage = null;
1260
+ #storageKind = "memory";
1261
+ #txStorage = null;
1262
+ #spentStorage = null;
1263
+ #prefix;
1264
+ #tokens = null;
1265
+ #derived = { claims: null, arkClaims: Object.freeze([]), scopes: Object.freeze([]) };
1266
+ #denial = null;
1267
+ #initPromise = null;
1268
+ #refreshPromise = null;
1269
+ #timer = null;
1270
+ #channel = null;
1271
+ #detach = [];
1272
+ #destroyed = false;
1273
+ constructor(options = {}) {
1274
+ this.#config = normalizeConfig(options);
1275
+ this.#win = options.window !== void 0 ? options.window : typeof window !== "undefined" ? window : null;
1276
+ this.#prefix = `ark.oidc:${this.#config.clientId}@${this.#config.authority}:`;
1277
+ this.#metadata = new MetadataResolver(this.#config.authority, {
1278
+ ttlMs: this.#config.metadataTtlMs,
1279
+ timeoutMs: this.#config.timeoutMs,
1280
+ fetch: this.#config.fetch
1281
+ });
1282
+ this.subscribe = this.subscribe.bind(this);
1283
+ this.getSnapshot = this.getSnapshot.bind(this);
1284
+ this.getServerSnapshot = this.getServerSnapshot.bind(this);
1285
+ this.fetch = this.fetch.bind(this);
1286
+ this.getAccessToken = this.getAccessToken.bind(this);
1287
+ }
1288
+ get config() {
1289
+ return this.#config;
1290
+ }
1291
+ get authority() {
1292
+ return this.#config.authority;
1293
+ }
1294
+ get clientId() {
1295
+ return this.#config.clientId;
1296
+ }
1297
+ /**
1298
+ * False during server-side rendering (no window): the client stays `loading` and every action
1299
+ * that needs a browser waits for one. Route guards use it to cancel quietly on the server and
1300
+ * decide in the browser, after hydration.
1301
+ */
1302
+ get isBrowser() {
1303
+ return Boolean(this.#win);
1304
+ }
1305
+ // =================================================================
1306
+ // State: the framework-agnostic surface
1307
+ // =================================================================
1308
+ /** The current state. The same frozen object until something changes. */
1309
+ getSnapshot() {
1310
+ return this.#store.get();
1311
+ }
1312
+ /** The state during server-side rendering and hydration: always `loading`. */
1313
+ getServerSnapshot() {
1314
+ return INITIAL_SNAPSHOT;
1315
+ }
1316
+ /** Calls `listener(snapshot)` on every change. Returns the unsubscribe function. */
1317
+ subscribe(listener) {
1318
+ return this.#store.subscribe(listener);
1319
+ }
1320
+ /**
1321
+ * The state as a Svelte-compatible store (`$ark.state` in a component): `subscribe` calls the
1322
+ * listener straight away with the current value, then on every change.
1323
+ */
1324
+ get state() {
1325
+ return {
1326
+ subscribe: (run) => {
1327
+ run(this.#store.get());
1328
+ return this.#store.subscribe(run);
1329
+ }
1330
+ };
1331
+ }
1332
+ /** The signed-in user's ID token claims, or null. */
1333
+ getUser() {
1334
+ return this.#store.get().user;
1335
+ }
1336
+ /**
1337
+ * Listens for one event: `signedIn`, `signedOut`, `tokensRefreshed`, `refreshFailed`,
1338
+ * `sessionExpired`, `accessDenied` or `error`. Returns the unsubscribe function.
1339
+ */
1340
+ on(event, handler) {
1341
+ const set = this.#events.get(event);
1342
+ if (!set) throw new ArkConfigError(`ark_oauth_client: unknown event '${event}'. Known events: ${EVENTS.join(", ")}.`);
1343
+ set.add(handler);
1344
+ return () => set.delete(handler);
1345
+ }
1346
+ /** True when the user holds every one of these Ark authorization claims. */
1347
+ hasArkClaims(...claims) {
1348
+ const held = this.#store.get().arkClaims;
1349
+ return claims.flat().every((c) => held.includes(c));
1350
+ }
1351
+ /** True when the user holds at least one of these Ark authorization claims. */
1352
+ hasAnyArkClaim(...claims) {
1353
+ const held = this.#store.get().arkClaims;
1354
+ return claims.flat().some((c) => held.includes(c));
1355
+ }
1356
+ /** True when every one of these scopes was granted. */
1357
+ hasScopes(...scopes) {
1358
+ const granted = this.#store.get().scopes;
1359
+ return scopes.flat().every((s) => granted.includes(s));
1360
+ }
1361
+ // =================================================================
1362
+ // Start-up
1363
+ // =================================================================
1364
+ /**
1365
+ * Starts the client: completes a sign-in when the page is the redirect URI, completes a sign-out
1366
+ * when it is the post-logout URI, otherwise restores the stored session (refreshing it if the
1367
+ * access token expired while the page was closed). Resolves with the snapshot; never rejects: a
1368
+ * failure lands in `snapshot.error` and the `error` event.
1369
+ *
1370
+ * Idempotent: every call after the first returns the first call's promise, so React StrictMode's
1371
+ * double effects and several components calling it at once all share one start-up.
1372
+ *
1373
+ * After a completed sign-in the browser is sent to the page the user started from, through
1374
+ * `onRedirectCallback(returnTo)` when given (pass your router's navigate here), otherwise through
1375
+ * `history.replaceState` plus a `popstate` event, which React Router and the Angular router follow.
1376
+ *
1377
+ * @param {{ handleCallback?: boolean, onRedirectCallback?: (returnTo: string, result: object) => unknown }} [options]
1378
+ */
1379
+ init(options = {}) {
1380
+ if (!this.#win) return Promise.resolve(this.#store.get());
1381
+ this.#initPromise ??= this.#runInit(options);
1382
+ return this.#initPromise;
1383
+ }
1384
+ async #runInit({ handleCallback = true, onRedirectCallback } = {}) {
1385
+ this.#ensureReady();
1386
+ this.#attachListeners();
1387
+ this.#sweepTransactions();
1388
+ const href = this.#win.location.href;
1389
+ const navigate = (to, result) => {
1390
+ const handler = onRedirectCallback ?? this.#config.onRedirectCallback;
1391
+ if (!handler) return this.#navigate(to);
1392
+ try {
1393
+ Promise.resolve(handler(to, result)).catch((error) => this.#emit("error", error));
1394
+ } catch (error) {
1395
+ this.#emit("error", error);
1396
+ }
1397
+ };
1398
+ try {
1399
+ const kind = handleCallback ? this.#classify(href) : null;
1400
+ if (kind === "signin") {
1401
+ let result;
1402
+ try {
1403
+ result = await this.handleRedirectCallback(href);
1404
+ } catch (error) {
1405
+ this.#restore();
1406
+ await this.#renewIfNeeded();
1407
+ return this.#fail(error);
1408
+ }
1409
+ if (result.relayed) return this.#store.get();
1410
+ navigate(result.returnTo, result);
1411
+ return this.#store.get();
1412
+ }
1413
+ if (kind === "signout") {
1414
+ const next = this.#takeLogoutTransaction(href);
1415
+ if (next?.then === "signin") {
1416
+ await this.signinRedirect({ prompt: next.prompt ?? this.#config.accountSwitch.prompt, returnTo: next.returnTo, loginHint: next.loginHint });
1417
+ return this.#store.get();
1418
+ }
1419
+ this.#publish({ error: null });
1420
+ navigate(next?.returnTo ?? localOrDefault(this.#config.accountSwitch.homePath), { signedOut: true });
1421
+ return this.#store.get();
1422
+ }
1423
+ this.#restore();
1424
+ await this.#renewIfNeeded();
1425
+ this.#publish();
1426
+ this.#schedule();
1427
+ } catch (error) {
1428
+ return this.#fail(error);
1429
+ }
1430
+ return this.#store.get();
1431
+ }
1432
+ // =================================================================
1433
+ // Signing in
1434
+ // =================================================================
1435
+ /**
1436
+ * Builds the authorization request and the transaction that must survive until the user comes
1437
+ * back. For custom flows; `signinRedirect()` and `signinPopup()` use it.
1438
+ *
1439
+ * @returns {Promise<{ url: string, transaction: object }>}
1440
+ */
1441
+ async createAuthorizationUrl(options = {}) {
1442
+ const win = this.#requireWindow();
1443
+ const config = this.#config;
1444
+ const metadata = await this.metadata();
1445
+ if (metadata.require_pushed_authorization_requests === true) {
1446
+ throw new ArkConfigError(
1447
+ "the tenant requires pushed authorization requests, which a browser app cannot make (/oauth2/par needs client authentication and serves no CORS). Turn RequirePushedAuthorizationRequests off for this tenant, or the client's require_par flag, or sign in through a server-side client."
1448
+ );
1449
+ }
1450
+ if (!metadata.authorization_endpoint) {
1451
+ throw new ArkOAuthError("server_error", "the provider's metadata has no 'authorization_endpoint'.", { endpoint: config.authority });
1452
+ }
1453
+ const redirectUri = this.#resolve(options.redirectUri ?? config.redirectUri);
1454
+ const scopes = options.scopes?.length ? [...options.scopes] : [...config.scopes];
1455
+ const { codeVerifier, codeChallenge, codeChallengeMethod } = await createPkcePair();
1456
+ const state = createState();
1457
+ const nonce = scopes.includes("openid") ? createNonce() : null;
1458
+ const prompt = options.prompt ?? config.prompt;
1459
+ const acrValues = options.acrValues ?? config.acrValues;
1460
+ const responseMode = options.responseMode ?? config.responseMode;
1461
+ const params = {
1462
+ ...config.extraAuthorizationParams,
1463
+ ...options.extra,
1464
+ response_type: "code",
1465
+ client_id: config.clientId,
1466
+ redirect_uri: redirectUri,
1467
+ scope: scopes.join(" "),
1468
+ state,
1469
+ code_challenge: codeChallenge,
1470
+ code_challenge_method: codeChallengeMethod,
1471
+ response_mode: responseMode,
1472
+ ...nonce ? { nonce } : {},
1473
+ ...prompt ? { prompt } : {},
1474
+ ...options.loginHint ? { login_hint: options.loginHint } : {},
1475
+ ...options.maxAge !== void 0 && options.maxAge !== null ? { max_age: String(options.maxAge) } : {},
1476
+ ...acrValues ? { acr_values: acrValues } : {}
1477
+ };
1478
+ const query = new URLSearchParams(Object.entries(params).filter(([, v]) => v !== void 0 && v !== null && v !== ""));
1479
+ const here = `${win.location.pathname}${win.location.search}${win.location.hash}`;
1480
+ const returnTo = localOrDefault(options.returnTo ?? (this.#classify(win.location.href) ? "/" : here), "/");
1481
+ return {
1482
+ url: `${metadata.authorization_endpoint}${metadata.authorization_endpoint.includes("?") ? "&" : "?"}${query}`,
1483
+ transaction: {
1484
+ state,
1485
+ nonce,
1486
+ codeVerifier,
1487
+ redirectUri,
1488
+ responseMode,
1489
+ scope: scopes.join(" "),
1490
+ maxAge: options.maxAge ?? null,
1491
+ returnTo,
1492
+ createdAt: now()
1493
+ }
1494
+ };
1495
+ }
1496
+ /**
1497
+ * Sends the browser to the provider's sign-in page. The promise resolves as the page unloads.
1498
+ *
1499
+ * @param {{ returnTo?: string, prompt?: string, loginHint?: string, scopes?: string[], maxAge?: number,
1500
+ * acrValues?: string, extra?: Record<string, string> }} [options]
1501
+ */
1502
+ async signinRedirect(options = {}) {
1503
+ this.#ensureReady();
1504
+ const { url, transaction } = await this.createAuthorizationUrl(options);
1505
+ this.#saveTransaction(transaction);
1506
+ await this.#redirect(url);
1507
+ }
1508
+ /**
1509
+ * Signs in through a popup window; the page never navigates. Call it straight from a click
1510
+ * handler, before any `await`, or the browser blocks the popup. The popup lands on the redirect
1511
+ * URI, whose page (this same app, calling `init()`) passes the result back here and closes.
1512
+ *
1513
+ * @returns {Promise<{ user: object|null, denied: boolean, returnTo: string }>}
1514
+ */
1515
+ async signinPopup(options = {}) {
1516
+ const win = this.#requireWindow();
1517
+ const popup = options.popupWindow ?? openPopupWindow(win, this.#config.popup);
1518
+ let waiter = null;
1519
+ try {
1520
+ this.#ensureReady();
1521
+ const { url, transaction } = await this.createAuthorizationUrl(options);
1522
+ waiter = waitForPopupCallback(win, popup, {
1523
+ state: transaction.state,
1524
+ channelName: popupChannelName(this.#config.authority, this.#config.clientId),
1525
+ timeoutMs: this.#config.popup.timeoutMs
1526
+ });
1527
+ popup.location.href = url;
1528
+ const responseUrl = await waiter.promise;
1529
+ const params = this.#responseParams(new URL(responseUrl), transaction.responseMode);
1530
+ if (params.error) throw this.#authorizationError(params);
1531
+ return await this.#completeSignin(params, transaction);
1532
+ } catch (error) {
1533
+ waiter?.cancel(error);
1534
+ this.#publish({ error: error instanceof ArkError ? error : new ArkError(String(error?.message ?? error)) });
1535
+ this.#emit("error", error);
1536
+ throw error;
1537
+ } finally {
1538
+ try {
1539
+ if (!popup.closed) popup.close();
1540
+ } catch {
1541
+ }
1542
+ }
1543
+ }
1544
+ /** Whether a URL is this client's sign-in callback: the redirect URI carrying a code or an error. */
1545
+ isSigninCallback(url) {
1546
+ return this.#classify(String(url ?? this.#requireWindow().location.href)) === "signin";
1547
+ }
1548
+ /**
1549
+ * Completes a sign-in from the authorization response in `url` (default: the current URL).
1550
+ * `init()` calls this for you; call it yourself only with `init({ handleCallback: false })`.
1551
+ *
1552
+ * The checks, in order: an `error` response surfaces as an error; `state` must match a sign-in this
1553
+ * tab started (constant-time, single use); `iss` must be the provider (RFC 9207); the code is
1554
+ * redeemed with the PKCE verifier only this tab holds; the ID token is verified against the
1555
+ * provider's keys, the `nonce`, `at_hash` and `c_hash`; then the access check, when configured.
1556
+ * The response parameters are removed from the address bar either way, so a reload cannot replay them.
1557
+ *
1558
+ * @returns {Promise<{ returnTo: string, user: object|null, denied: boolean, relayed?: boolean }>}
1559
+ */
1560
+ async handleRedirectCallback(url) {
1561
+ const win = this.#requireWindow();
1562
+ this.#ensureReady();
1563
+ const href = String(url ?? win.location.href);
1564
+ const parsed = new URL(href, win.location.href);
1565
+ const params = this.#responseParams(parsed);
1566
+ const transaction = params.state ? this.#takeTransaction(params.state) : null;
1567
+ if (!transaction && params.state) {
1568
+ if (relayToOpener(win, href, params.state, popupChannelName(this.#config.authority, this.#config.clientId))) {
1569
+ setTimeout(() => {
1570
+ try {
1571
+ win.close();
1572
+ } catch {
1573
+ }
1574
+ }, 50);
1575
+ return { relayed: true, returnTo: null, user: null, denied: false };
1576
+ }
1577
+ }
1578
+ this.#cleanResponseFromUrl(parsed);
1579
+ if (params.error) throw this.#authorizationError(params);
1580
+ if (!params.state) throw new ArkCallbackError("the authorization response carried no `state`.");
1581
+ if (!transaction) {
1582
+ throw new ArkCallbackError(
1583
+ "the authorization response does not belong to a sign-in started in this tab (unknown or expired `state`). Start the sign-in again. If this keeps happening, check that the redirect URI is served by this same origin, and that storage is not being cleared between the two pages."
1584
+ );
1585
+ }
1586
+ if (!constantTimeEqual(String(params.state), String(transaction.state))) {
1587
+ throw new ArkCallbackError("the authorization response `state` does not match the request. Treat this as a CSRF attempt.");
1588
+ }
1589
+ return this.#completeSignin(params, transaction);
1590
+ }
1591
+ async #completeSignin(params, transaction) {
1592
+ const metadata = await this.metadata();
1593
+ if (params.iss || metadata.authorization_response_iss_parameter_supported) {
1594
+ if (!params.iss) throw new ArkCallbackError("the provider advertises `iss` in authorization responses but this one has none.");
1595
+ if (params.iss !== metadata.issuer) throw new ArkCallbackError(`the authorization response came from '${params.iss}', not from '${metadata.issuer}'.`);
1596
+ }
1597
+ if (!params.code) throw new ArkCallbackError("the authorization response carried no `code`.");
1598
+ const tokens = await this.#exchangeCode({
1599
+ code: params.code,
1600
+ codeVerifier: transaction.codeVerifier,
1601
+ redirectUri: transaction.redirectUri,
1602
+ nonce: transaction.nonce ?? null,
1603
+ maxAge: transaction.maxAge ?? null
1604
+ });
1605
+ const returnTo = localOrDefault(transaction.returnTo, "/");
1606
+ const arkClaims = tokens.arkClaims();
1607
+ const allowed = await evaluateAccess(this.#config.accountSwitch, this.#config.onEvaluateAccess, {
1608
+ claims: tokens.claims ?? {},
1609
+ arkClaims,
1610
+ tokens
1611
+ });
1612
+ if (!allowed) {
1613
+ const denial = describeDenial(ArkAccessDeniedReasons.NO_APP_ACCESS, tokens.claims, arkClaims, returnTo);
1614
+ this.#setDenial({ ...denial, idTokenHint: tokens.idToken, createdAt: now() });
1615
+ this.#setTokens(null);
1616
+ if (tokens.refreshToken) this.#revokeQuietly(tokens.refreshToken);
1617
+ this.#publish({ error: null });
1618
+ this.#emit("accessDenied", this.#store.get().denial);
1619
+ return { returnTo: this.#config.accountSwitch.accessDeniedPath ?? returnTo, user: tokens.claims, denied: true };
1620
+ }
1621
+ this.#setDenial(null);
1622
+ this.#setTokens(tokens);
1623
+ this.#publish({ error: null });
1624
+ this.#schedule();
1625
+ this.#emit("signedIn", { user: tokens.claims, returnTo });
1626
+ this.#broadcast("signed-in");
1627
+ return { returnTo, user: tokens.claims, denied: false };
1628
+ }
1629
+ // =================================================================
1630
+ // Using the session
1631
+ // =================================================================
1632
+ /**
1633
+ * The access token for an API call, refreshed first when it is about to expire; null when nobody
1634
+ * is signed in or the session can no longer be renewed.
1635
+ *
1636
+ * Read it per call and never keep it: the client replaces it underneath you on every refresh.
1637
+ */
1638
+ async getAccessToken({ forceRefresh = false } = {}) {
1639
+ if (!this.#win) return null;
1640
+ this.#ensureReady();
1641
+ if (this.#initPromise) await this.#initPromise;
1642
+ else this.#restore();
1643
+ if (!this.#tokens) return null;
1644
+ if (forceRefresh || this.#tokens.expired(this.#leeway(this.#tokens))) {
1645
+ if (!this.#tokens.refreshToken) {
1646
+ if (this.#tokens.expired(0)) {
1647
+ this.#endLocalSession("expired", { broadcast: false });
1648
+ this.#emit("sessionExpired", { reason: "expired" });
1649
+ return null;
1650
+ }
1651
+ return this.#tokens.accessToken;
1652
+ }
1653
+ try {
1654
+ await this.refresh();
1655
+ } catch (error) {
1656
+ if (!this.#tokens) return null;
1657
+ if (this.#tokens.expired(0)) throw error;
1658
+ }
1659
+ }
1660
+ return this.#tokens?.accessToken ?? null;
1661
+ }
1662
+ /**
1663
+ * Redeems the refresh token now. Concurrent calls, in this tab and (with Web Locks) across tabs,
1664
+ * share one request: Ark rotates refresh tokens and revokes the whole family if a retired one is
1665
+ * presented again, so two refreshes racing with the same token would sign the user out.
1666
+ */
1667
+ refresh() {
1668
+ this.#refreshPromise ??= this.#refreshUnderLock().finally(() => {
1669
+ this.#refreshPromise = null;
1670
+ });
1671
+ return this.#refreshPromise;
1672
+ }
1673
+ async #refreshUnderLock() {
1674
+ this.#ensureReady();
1675
+ if (!this.#tokens?.refreshToken) throw new ArkLoginRequiredError("there is no refresh token to renew the session with.");
1676
+ return withLock(`${this.#prefix}refresh`, async () => {
1677
+ if (this.#destroyed) throw new ArkError("the client was destroyed.");
1678
+ let current = this.#tokens;
1679
+ if (!current?.refreshToken) throw new ArkLoginRequiredError();
1680
+ if (this.#storageKind !== "memory") {
1681
+ const stored = this.#readStoredTokens();
1682
+ if (!stored) {
1683
+ this.#endLocalSession("signout", { broadcast: false });
1684
+ throw new ArkLoginRequiredError();
1685
+ }
1686
+ if (stored.refreshToken !== current.refreshToken) {
1687
+ if (!stored.expired(this.#leeway(stored))) {
1688
+ this.#setTokens(stored, { persist: false });
1689
+ this.#publish({ error: null });
1690
+ this.#schedule();
1691
+ return stored;
1692
+ }
1693
+ current = stored;
1694
+ }
1695
+ }
1696
+ if (await this.#isSpent(current.refreshToken)) {
1697
+ this.#endLocalSession("expired", { broadcast: false });
1698
+ this.#emit("sessionExpired", { reason: "refresh_token_spent" });
1699
+ throw new ArkLoginRequiredError("this tab's refresh token was already redeemed by a copy of it (a duplicated tab). Sign in again.");
1700
+ }
1701
+ let tokens;
1702
+ try {
1703
+ const metadata = await this.metadata();
1704
+ const response = await this.#tokenRequest(metadata.token_endpoint, {
1705
+ grant_type: "refresh_token",
1706
+ refresh_token: current.refreshToken
1707
+ });
1708
+ if (response.refresh_token && response.refresh_token !== current.refreshToken) {
1709
+ await this.#markSpent(current.refreshToken);
1710
+ current = TokenSet.fromJSON({ ...current.toJSON(), refresh_token: response.refresh_token });
1711
+ this.#setTokens(current);
1712
+ }
1713
+ tokens = await this.#toTokenSet(response, { nonce: null, subject: current.claims?.sub ?? null, previous: current });
1714
+ } catch (error) {
1715
+ this.#onRefreshFailure(error);
1716
+ throw error;
1717
+ }
1718
+ this.#setTokens(tokens);
1719
+ if (this.#destroyed) return tokens;
1720
+ this.#publish({ error: null });
1721
+ this.#schedule();
1722
+ this.#emit("tokensRefreshed", { expiresAt: tokens.expiresAt });
1723
+ this.#broadcast("tokens");
1724
+ return tokens;
1725
+ }, this.#win);
1726
+ }
1727
+ #onRefreshFailure(error) {
1728
+ const fatal = error instanceof ArkTokenError || error instanceof ArkOAuthError && ["invalid_grant", "invalid_client", "unauthorized_client"].includes(error.error);
1729
+ if (fatal) {
1730
+ const untrusted = error instanceof ArkTokenError ? this.#tokens?.refreshToken : null;
1731
+ this.#endLocalSession("expired", { broadcast: this.#sharedStorage() });
1732
+ if (untrusted) this.#revokeQuietly(untrusted);
1733
+ this.#emit("sessionExpired", { reason: "refresh_refused", error });
1734
+ return;
1735
+ }
1736
+ this.#emit("refreshFailed", { error });
1737
+ if (this.#config.automaticRefresh && this.#tokens && !this.#destroyed) {
1738
+ clearTimeout(this.#timer);
1739
+ this.#timer = unref(setTimeout(() => this.refresh().catch(() => {
1740
+ }), RETRY_AFTER_NETWORK_FAILURE_MS));
1741
+ }
1742
+ }
1743
+ /** Whether `ark.fetch()` may attach the access token to this URL: the app's own origin or one in `apiOrigins`. */
1744
+ isApiUrl(url) {
1745
+ const win = this.#win;
1746
+ let target;
1747
+ try {
1748
+ target = new URL(String(url), win?.location?.href);
1749
+ } catch {
1750
+ return false;
1751
+ }
1752
+ const own = win?.location?.origin;
1753
+ return target.origin === own || this.#config.apiOrigins.includes(target.origin);
1754
+ }
1755
+ /**
1756
+ * `fetch` with the access token attached, for the app's own API.
1757
+ *
1758
+ * The token is sent only to the page's own origin and the origins in `apiOrigins`; anything else
1759
+ * is refused rather than quietly handed a bearer token. A 401 that says the token is invalid is
1760
+ * retried once after a refresh. Throws ArkLoginRequiredError when nobody is signed in.
1761
+ */
1762
+ async fetch(input, init = {}) {
1763
+ const win = this.#requireWindow();
1764
+ const rawUrl = typeof input === "string" || input instanceof URL ? String(input) : input?.url;
1765
+ if (!this.isApiUrl(rawUrl)) {
1766
+ const origin = (() => {
1767
+ try {
1768
+ return new URL(rawUrl, win.location.href).origin;
1769
+ } catch {
1770
+ return rawUrl;
1771
+ }
1772
+ })();
1773
+ throw new ArkConfigError(
1774
+ `ark_oauth_client: refusing to send the access token to ${origin}. Add that origin to 'apiOrigins' if it is your API, or call it with plain fetch().`
1775
+ );
1776
+ }
1777
+ const fetchImpl = this.#config.fetch ?? globalThis.fetch;
1778
+ const send = (token2) => {
1779
+ const headers = new Headers(init.headers ?? (typeof Request !== "undefined" && input instanceof Request ? input.headers : void 0));
1780
+ headers.set("Authorization", `Bearer ${token2}`);
1781
+ return fetchImpl(input, { ...init, headers });
1782
+ };
1783
+ const token = await this.getAccessToken();
1784
+ if (!token) throw new ArkLoginRequiredError();
1785
+ let response = await send(token);
1786
+ const replayable = !(typeof Request !== "undefined" && input instanceof Request) && !(init.body && typeof init.body.getReader === "function");
1787
+ if (response.status === 401 && replayable && this.#tokens?.refreshToken) {
1788
+ const challenge = response.headers.get("WWW-Authenticate") ?? "";
1789
+ if (!challenge || /invalid_token/i.test(challenge)) {
1790
+ const renewed = await this.getAccessToken({ forceRefresh: true }).catch(() => null);
1791
+ if (renewed) response = await send(renewed);
1792
+ }
1793
+ }
1794
+ return response;
1795
+ }
1796
+ /** The UserInfo endpoint (OIDC Core §5.3), with the current access token. */
1797
+ async userInfo() {
1798
+ const token = await this.getAccessToken();
1799
+ if (!token) throw new ArkLoginRequiredError();
1800
+ const metadata = await this.metadata();
1801
+ return getJson(metadata.userinfo_endpoint, {
1802
+ headers: { Authorization: `Bearer ${token}` },
1803
+ timeoutMs: this.#config.timeoutMs,
1804
+ fetch: this.#config.fetch
1805
+ });
1806
+ }
1807
+ // =================================================================
1808
+ // Signing out and switching account
1809
+ // =================================================================
1810
+ /**
1811
+ * Signs out of this app and the provider: drops the tokens here, revokes the refresh token, then
1812
+ * sends the browser to the provider's end-session endpoint with `id_token_hint`, so the provider
1813
+ * ends its session without asking and returns to `postLogoutRedirectUri`.
1814
+ *
1815
+ * Both halves matter. Dropping only the local tokens leaves the provider's session alive, and the
1816
+ * next sign-in is silent, as the same person.
1817
+ *
1818
+ * @param {{ returnTo?: string, postLogoutRedirectUri?: string, revoke?: boolean }} [options]
1819
+ */
1820
+ async signoutRedirect({ returnTo, postLogoutRedirectUri, revoke = true, ...internal } = {}) {
1821
+ this.#requireWindow();
1822
+ this.#ensureReady();
1823
+ const idTokenHint = this.#tokens?.idToken ?? this.#denial?.idTokenHint ?? null;
1824
+ const refreshToken = this.#tokens?.refreshToken ?? null;
1825
+ let metadata = null;
1826
+ try {
1827
+ metadata = await this.metadata();
1828
+ } catch {
1829
+ metadata = null;
1830
+ }
1831
+ this.#endLocalSession("signout", { broadcast: true });
1832
+ if (revoke && refreshToken && metadata?.revocation_endpoint) await this.#revokeQuietly(refreshToken, metadata);
1833
+ const home = localOrDefault(returnTo ?? this.#config.accountSwitch.homePath, "/");
1834
+ if (!metadata?.end_session_endpoint) {
1835
+ this.#navigate(home);
1836
+ return;
1837
+ }
1838
+ const params = new URLSearchParams({ client_id: this.#config.clientId });
1839
+ if (idTokenHint) params.set("id_token_hint", idTokenHint);
1840
+ const target = postLogoutRedirectUri ?? this.#config.postLogoutRedirectUri;
1841
+ if (target) {
1842
+ const state = createState();
1843
+ params.set("post_logout_redirect_uri", this.#resolve(target));
1844
+ params.set("state", state);
1845
+ writeJson(this.#txStorage, `${this.#prefix}logout:${state}`, {
1846
+ returnTo: home,
1847
+ then: internal.then ?? null,
1848
+ prompt: internal.prompt ?? null,
1849
+ loginHint: internal.loginHint ?? null,
1850
+ createdAt: now()
1851
+ });
1852
+ }
1853
+ const endpoint = metadata.end_session_endpoint;
1854
+ await this.#redirect(`${endpoint}${endpoint.includes("?") ? "&" : "?"}${params}`);
1855
+ }
1856
+ /**
1857
+ * Signs out of this app only: tokens dropped and the refresh token revoked, the provider's session
1858
+ * left alone (the user's other apps stay signed in, and the next sign-in here is silent).
1859
+ */
1860
+ async signoutLocal({ revoke = true } = {}) {
1861
+ this.#ensureReady();
1862
+ const refreshToken = this.#tokens?.refreshToken ?? null;
1863
+ this.#endLocalSession("signout", { broadcast: true });
1864
+ if (revoke && refreshToken) await this.#revokeQuietly(refreshToken);
1865
+ }
1866
+ /**
1867
+ * "Sign in as a different user": drops this app's session and signs in again with
1868
+ * `prompt=login`, so the provider draws its sign-in form instead of answering from the session
1869
+ * already in this browser. With `accountSwitch.endProviderSessionOnSwitch`, the provider session
1870
+ * is ended first and the sign-in follows when the browser comes back.
1871
+ */
1872
+ async switchUser({ returnTo, loginHint } = {}) {
1873
+ const options = this.#config.accountSwitch;
1874
+ const target = localOrDefault(returnTo ?? this.#denial?.returnTo ?? null, options.homePath);
1875
+ if (options.endProviderSessionOnSwitch) {
1876
+ await this.signoutRedirect({ returnTo: target, then: "signin", prompt: options.prompt, loginHint });
1877
+ return;
1878
+ }
1879
+ await this.signoutLocal();
1880
+ await this.signinRedirect({ prompt: options.prompt || "login", returnTo: target, loginHint });
1881
+ }
1882
+ /** Clears a refused sign-in's state without signing in again. */
1883
+ clearDenial() {
1884
+ this.#ensureReady();
1885
+ this.#setDenial(null);
1886
+ this.#publish();
1887
+ }
1888
+ // =================================================================
1889
+ // Provider metadata and token checks
1890
+ // =================================================================
1891
+ /** The provider's discovery document, cached. */
1892
+ metadata({ force = false } = {}) {
1893
+ return this.#metadata.get(force);
1894
+ }
1895
+ async jwks() {
1896
+ const { jwks_uri: uri } = await this.metadata();
1897
+ if (!uri) throw new ArkOAuthError("server_error", "the provider's metadata has no 'jwks_uri'.", { endpoint: this.#config.authority });
1898
+ if (!this.#jwks || this.#jwks.uri !== uri) {
1899
+ this.#jwks = new JwksCache(uri, {
1900
+ ttlMs: this.#config.jwksTtlMs,
1901
+ minRefreshIntervalMs: this.#config.jwksMinRefreshIntervalMs,
1902
+ timeoutMs: this.#config.timeoutMs,
1903
+ fetch: this.#config.fetch
1904
+ });
1905
+ }
1906
+ return this.#jwks;
1907
+ }
1908
+ /** Verifies an ID token against the provider's keys and the values of the sign-in it belongs to. */
1909
+ async verifyIdToken(idToken, { nonce = null, accessToken = null, code = null, maxAge = null, subject = null } = {}) {
1910
+ const metadata = await this.metadata();
1911
+ return verifyJwt(idToken, await this.jwks(), {
1912
+ issuer: metadata.issuer,
1913
+ audience: this.#config.clientId,
1914
+ subject: subject ?? void 0,
1915
+ nonce,
1916
+ accessToken,
1917
+ code,
1918
+ maxAgeSeconds: maxAge,
1919
+ requireTokenHashes: this.#config.requireTokenHashes,
1920
+ requireIat: true,
1921
+ clockToleranceSeconds: this.#config.clockToleranceSeconds,
1922
+ algorithms: this.#config.idTokenSigningAlgorithms ?? metadata.id_token_signing_alg_values_supported ?? void 0
1923
+ });
1924
+ }
1925
+ // =================================================================
1926
+ // Diagnostics
1927
+ // =================================================================
1928
+ /**
1929
+ * Pairs this app's configuration with the provider's live metadata and reports what does not
1930
+ * line up: the browser counterpart of `checkSetup()` in the Node client and `ArkSetupProbe` in
1931
+ * .NET. In a browser it also proves CORS, which is the usual first failure of a new SPA and
1932
+ * otherwise surfaces as a bare "Failed to fetch". Render it on a setup or health page.
1933
+ */
1934
+ async checkSetup() {
1935
+ const win = this.#win;
1936
+ const config = this.#config;
1937
+ const cut = config.authority.lastIndexOf("/");
1938
+ const tenantId = config.authority.slice(cut + 1);
1939
+ const report = {
1940
+ authority: config.authority,
1941
+ clientId: config.clientId,
1942
+ tenantId,
1943
+ origin: win?.location?.origin ?? null,
1944
+ secureContext: Boolean(win?.isSecureContext ?? globalThis.isSecureContext),
1945
+ webCrypto: Boolean(globalThis.crypto?.subtle),
1946
+ storage: (this.#ensureReady(), this.#storageKind),
1947
+ scopes: [...config.scopes],
1948
+ responseMode: config.responseMode,
1949
+ redirectUri: win ? this.#resolve(config.redirectUri) : config.redirectUri,
1950
+ postLogoutRedirectUri: config.postLogoutRedirectUri && win ? this.#resolve(config.postLogoutRedirectUri) : config.postLogoutRedirectUri,
1951
+ adminConsoleUrl: `${config.authority}/admin`,
1952
+ integrationPageUrl: `${config.authority}/oauth2/integrate/${encodeURIComponent(config.clientId)}`,
1953
+ discoveryUrl: `${config.authority}/.well-known/openid-configuration`,
1954
+ discoveryOk: false,
1955
+ jwksOk: false,
1956
+ tokenEndpointCorsOk: null,
1957
+ provider: null,
1958
+ signingKeys: [],
1959
+ problems: []
1960
+ };
1961
+ if (!report.secureContext || !report.webCrypto) {
1962
+ 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.");
1963
+ }
1964
+ let metadata;
1965
+ try {
1966
+ metadata = await this.metadata({ force: true });
1967
+ report.discoveryOk = true;
1968
+ } catch (error) {
1969
+ report.problems.push(`The provider's discovery document could not be read: ${error.message}`);
1970
+ return report;
1971
+ }
1972
+ report.provider = {
1973
+ issuer: metadata.issuer,
1974
+ authorizationEndpoint: metadata.authorization_endpoint,
1975
+ tokenEndpoint: metadata.token_endpoint,
1976
+ userInfoEndpoint: metadata.userinfo_endpoint,
1977
+ jwksUri: metadata.jwks_uri,
1978
+ endSessionEndpoint: metadata.end_session_endpoint ?? null,
1979
+ revocationEndpoint: metadata.revocation_endpoint ?? null,
1980
+ scopesSupported: metadata.scopes_supported ?? [],
1981
+ grantTypesSupported: metadata.grant_types_supported ?? [],
1982
+ responseModesSupported: metadata.response_modes_supported ?? [],
1983
+ codeChallengeMethodsSupported: metadata.code_challenge_methods_supported ?? [],
1984
+ tokenEndpointAuthMethodsSupported: metadata.token_endpoint_auth_methods_supported ?? [],
1985
+ requirePushedAuthorizationRequests: metadata.require_pushed_authorization_requests === true
1986
+ };
1987
+ try {
1988
+ const keys = await (await this.jwks()).keys({ force: true });
1989
+ report.jwksOk = true;
1990
+ report.signingKeys = keys.map((k) => ({ kid: k.kid ?? null, kty: k.kty, alg: k.alg ?? null, use: k.use ?? null }));
1991
+ } catch (error) {
1992
+ report.problems.push(`The provider's signing keys could not be read: ${error.message}`);
1993
+ }
1994
+ try {
1995
+ await postForm(
1996
+ metadata.token_endpoint,
1997
+ { grant_type: "refresh_token", refresh_token: "ark-setup-probe", client_id: config.clientId },
1998
+ { timeoutMs: config.timeoutMs, fetch: config.fetch }
1999
+ );
2000
+ report.tokenEndpointCorsOk = true;
2001
+ } catch (error) {
2002
+ report.tokenEndpointCorsOk = !(error instanceof ArkNetworkError);
2003
+ if (!report.tokenEndpointCorsOk) report.problems.push(`The token endpoint is not reachable from this page: ${error.message}`);
2004
+ else if (error instanceof ArkOAuthError && ["invalid_client", "unauthorized_client"].includes(error.error)) {
2005
+ report.problems.push(
2006
+ `The token endpoint refused client '${config.clientId}' (${error.error}${error.errorDescription ? `: ${error.errorDescription}` : ""}). 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.`
2007
+ );
2008
+ }
2009
+ }
2010
+ const supportedScopes = new Set(metadata.scopes_supported ?? []);
2011
+ const unknown = supportedScopes.size ? config.scopes.filter((s) => !supportedScopes.has(s)) : [];
2012
+ if (unknown.length) {
2013
+ 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.`);
2014
+ }
2015
+ if (!(metadata.code_challenge_methods_supported ?? []).includes("S256")) {
2016
+ report.problems.push("The tenant does not advertise the S256 PKCE method, which this client always sends.");
2017
+ }
2018
+ const methods = metadata.token_endpoint_auth_methods_supported ?? [];
2019
+ if (methods.length && !methods.includes("none")) {
2020
+ report.problems.push("The tenant does not list the 'none' token endpoint auth method, which a browser (public) client needs.");
2021
+ }
2022
+ const modes = metadata.response_modes_supported ?? [];
2023
+ if (modes.length && !modes.includes(config.responseMode)) {
2024
+ report.problems.push(`The tenant does not support response_mode '${config.responseMode}' (it lists ${modes.join(", ")}).`);
2025
+ }
2026
+ if (config.scopes.includes("offline_access") && !(metadata.grant_types_supported ?? ["refresh_token"]).includes("refresh_token")) {
2027
+ report.problems.push("offline_access is requested but the tenant does not serve the refresh_token grant.");
2028
+ }
2029
+ if (!config.scopes.includes("offline_access")) {
2030
+ report.problems.push("offline_access is not requested, so there is no refresh token: the session ends when the access token expires.");
2031
+ }
2032
+ if (metadata.require_pushed_authorization_requests === true) {
2033
+ report.problems.push("The tenant requires pushed authorization requests, which a browser app cannot make.");
2034
+ }
2035
+ if (!metadata.end_session_endpoint) {
2036
+ report.problems.push("The provider has no end_session_endpoint, so sign-out can only end the local session.");
2037
+ }
2038
+ return report;
2039
+ }
2040
+ /** Stops timers and listeners. For tests, hot-module reloading, and micro-frontends that unmount. */
2041
+ destroy() {
2042
+ this.#destroyed = true;
2043
+ clearTimeout(this.#timer);
2044
+ this.#timer = null;
2045
+ for (const off of this.#detach.splice(0)) off();
2046
+ if (this.#channel) {
2047
+ this.#channel.onmessage = null;
2048
+ this.#channel.close();
2049
+ this.#channel = null;
2050
+ }
2051
+ }
2052
+ // =================================================================
2053
+ // internals: tokens
2054
+ // =================================================================
2055
+ async #exchangeCode({ code, codeVerifier, redirectUri, nonce, maxAge }) {
2056
+ const metadata = await this.metadata();
2057
+ const response = await this.#tokenRequest(metadata.token_endpoint, {
2058
+ grant_type: "authorization_code",
2059
+ code,
2060
+ redirect_uri: redirectUri,
2061
+ code_verifier: codeVerifier
2062
+ });
2063
+ return this.#toTokenSet(response, { nonce, code, maxAge });
2064
+ }
2065
+ /** A public client authenticates with nothing but its id, which goes in the body. */
2066
+ #tokenRequest(endpoint, form) {
2067
+ if (!endpoint) throw new ArkOAuthError("server_error", "the provider's metadata has no 'token_endpoint'.", { endpoint: this.#config.authority });
2068
+ return postForm(endpoint, { ...form, client_id: this.#config.clientId }, { timeoutMs: this.#config.timeoutMs, fetch: this.#config.fetch });
2069
+ }
2070
+ async #toTokenSet(response, { nonce, code = null, maxAge = null, subject = null, previous = null }) {
2071
+ if (!response.access_token) throw new ArkTokenError("the token response contains no access_token.");
2072
+ let claims = null;
2073
+ if (response.id_token) {
2074
+ claims = await this.verifyIdToken(response.id_token, { nonce, accessToken: response.access_token, code, maxAge, subject });
2075
+ } else if (nonce !== null && String(response.scope ?? "").split(" ").includes("openid")) {
2076
+ throw new ArkTokenError("the token response contains no id_token, although the openid scope was granted.");
2077
+ }
2078
+ const merged = { ...response };
2079
+ if (previous) {
2080
+ merged.refresh_token ??= previous.refreshToken;
2081
+ merged.id_token ??= previous.idToken;
2082
+ }
2083
+ return new TokenSet(merged, { claims: claims ?? previous?.claims ?? null });
2084
+ }
2085
+ #setTokens(tokens, { persist = true } = {}) {
2086
+ this.#tokens = tokens;
2087
+ this.#derived = tokens ? { claims: tokens.claims ? Object.freeze({ ...tokens.claims }) : null, arkClaims: Object.freeze(tokens.arkClaims()), scopes: Object.freeze(tokens.scopes()) } : { claims: null, arkClaims: Object.freeze([]), scopes: Object.freeze([]) };
2088
+ if (!persist) return;
2089
+ if (tokens) writeJson(this.#storage, `${this.#prefix}tokens`, tokens.toJSON());
2090
+ else remove(this.#storage, `${this.#prefix}tokens`);
2091
+ }
2092
+ #readStoredTokens() {
2093
+ const data = readJson(this.#storage, `${this.#prefix}tokens`);
2094
+ return data?.access_token ? TokenSet.fromJSON(data) : null;
2095
+ }
2096
+ #restore() {
2097
+ if (!this.#tokens) {
2098
+ const stored = this.#readStoredTokens();
2099
+ if (stored) this.#setTokens(stored, { persist: false });
2100
+ }
2101
+ if (!this.#denial) {
2102
+ const denial = readJson(this.#txStorage, `${this.#prefix}denied`);
2103
+ if (denial && now() - (denial.createdAt ?? 0) <= DENIAL_TTL_SECONDS) this.#denial = denial;
2104
+ else if (denial) remove(this.#txStorage, `${this.#prefix}denied`);
2105
+ }
2106
+ }
2107
+ async #renewIfNeeded() {
2108
+ if (!this.#tokens || !this.#tokens.expired(this.#leeway(this.#tokens))) return;
2109
+ if (!this.#tokens.refreshToken) {
2110
+ if (this.#tokens.expired(0)) this.#endLocalSession("expired", { broadcast: false });
2111
+ return;
2112
+ }
2113
+ try {
2114
+ await this.refresh();
2115
+ } catch {
2116
+ }
2117
+ }
2118
+ #endLocalSession(reason, { broadcast }) {
2119
+ const hadSession = Boolean(this.#tokens || this.#denial);
2120
+ clearTimeout(this.#timer);
2121
+ this.#timer = null;
2122
+ this.#setTokens(null);
2123
+ this.#setDenial(null);
2124
+ this.#publish();
2125
+ if (hadSession) this.#emit("signedOut", { reason });
2126
+ if (broadcast) this.#broadcast("signed-out");
2127
+ }
2128
+ async #revokeQuietly(token, metadata = null) {
2129
+ try {
2130
+ const md = metadata ?? await this.metadata();
2131
+ if (!md.revocation_endpoint) return;
2132
+ await postFormNoCors(
2133
+ md.revocation_endpoint,
2134
+ { token, token_type_hint: "refresh_token", client_id: this.#config.clientId },
2135
+ { timeoutMs: Math.min(this.#config.timeoutMs, 5e3), fetch: this.#config.fetch }
2136
+ );
2137
+ } catch {
2138
+ }
2139
+ }
2140
+ #schedule() {
2141
+ clearTimeout(this.#timer);
2142
+ this.#timer = null;
2143
+ const tokens = this.#tokens;
2144
+ if (this.#destroyed || !tokens || tokens.expiresAt === null || !this.#win) return;
2145
+ const renew = Boolean(this.#config.automaticRefresh && tokens.refreshToken);
2146
+ if (!renew && tokens.refreshToken) return;
2147
+ const at = renew ? tokens.expiresAt - this.#lead(tokens) : tokens.expiresAt;
2148
+ const delay = Math.min(MAX_TIMER_MS, Math.max(0, (at - now()) * 1e3));
2149
+ this.#timer = unref(setTimeout(() => {
2150
+ if (renew) {
2151
+ this.refresh().catch(() => {
2152
+ });
2153
+ } else if (this.#tokens === tokens) {
2154
+ this.#endLocalSession("expired", { broadcast: false });
2155
+ this.#emit("sessionExpired", { reason: "expired" });
2156
+ }
2157
+ }, delay));
2158
+ }
2159
+ #sharedStorage() {
2160
+ return this.#storageKind === "local" || this.#storageKind === "custom";
2161
+ }
2162
+ /**
2163
+ * How early to renew: `refreshBeforeSeconds`, but never more than half the token's lifetime. A
2164
+ * client record with 30- or 60-second access tokens would otherwise be due for renewal the moment
2165
+ * each one arrived, and refresh in a tight loop.
2166
+ */
2167
+ #lead(tokens, max = this.#config.refreshBeforeSeconds) {
2168
+ if (!tokens || tokens.expiresAt === null) return max;
2169
+ const lifetime = tokens.expiresAt - tokens.issuedAt;
2170
+ return lifetime > 0 ? Math.min(max, lifetime / 2) : max;
2171
+ }
2172
+ /** The margin within which a token is renewed on use rather than handed out. */
2173
+ #leeway(tokens) {
2174
+ return this.#lead(tokens, Math.min(30, this.#config.refreshBeforeSeconds));
2175
+ }
2176
+ async #spentHash(token) {
2177
+ return base64UrlEncode(await sha256(`${this.#config.clientId}|${token}`)).slice(0, 24);
2178
+ }
2179
+ async #isSpent(token) {
2180
+ const hash = await this.#spentHash(token);
2181
+ return (readJson(this.#spentStorage, `${this.#prefix}spent`) ?? []).some((entry) => entry?.h === hash);
2182
+ }
2183
+ async #markSpent(token) {
2184
+ const hash = await this.#spentHash(token);
2185
+ const list = (readJson(this.#spentStorage, `${this.#prefix}spent`) ?? []).filter((entry) => entry && entry.h !== hash);
2186
+ list.push({ h: hash, at: now() });
2187
+ writeJson(this.#spentStorage, `${this.#prefix}spent`, list.slice(-SPENT_TOKENS_REMEMBERED));
2188
+ }
2189
+ // =================================================================
2190
+ // internals: state, storage, transactions
2191
+ // =================================================================
2192
+ #ensureReady() {
2193
+ if (this.#ready) return;
2194
+ this.#ready = true;
2195
+ const { storage, kind } = resolveStorage(this.#config.storage, this.#win);
2196
+ this.#storage = storage;
2197
+ this.#storageKind = kind;
2198
+ this.#txStorage = kind === "session" ? storage : resolveStorage("session", this.#win).storage;
2199
+ this.#spentStorage = kind === "local" ? storage : resolveStorage("local", this.#win).storage;
2200
+ }
2201
+ #publish(extra = {}) {
2202
+ const tokens = this.#tokens;
2203
+ const denial = this.#denial;
2204
+ this.#store.set({
2205
+ status: tokens ? "authenticated" : denial ? "denied" : "unauthenticated",
2206
+ user: this.#derived.claims,
2207
+ arkClaims: this.#derived.arkClaims,
2208
+ scopes: this.#derived.scopes,
2209
+ expiresAt: tokens?.expiresAt ?? null,
2210
+ denial: denial ? this.#publicDenial(denial) : null,
2211
+ ...extra
2212
+ });
2213
+ }
2214
+ #publicDenial(denial) {
2215
+ if (this.#publicDenialCache?.source === denial) return this.#publicDenialCache.value;
2216
+ const { idTokenHint: _hint, createdAt: _created, ...visible } = denial;
2217
+ const value = Object.freeze({ ...visible, arkClaims: Object.freeze([...visible.arkClaims ?? []]) });
2218
+ this.#publicDenialCache = { source: denial, value };
2219
+ return value;
2220
+ }
2221
+ #publicDenialCache = null;
2222
+ #setDenial(denial) {
2223
+ this.#denial = denial;
2224
+ if (denial) writeJson(this.#txStorage, `${this.#prefix}denied`, denial);
2225
+ else remove(this.#txStorage, `${this.#prefix}denied`);
2226
+ }
2227
+ #fail(error) {
2228
+ const wrapped = error instanceof ArkError ? error : new ArkError(String(error?.message ?? error), { cause: error });
2229
+ this.#publish({ error: wrapped });
2230
+ this.#schedule();
2231
+ this.#emit("error", wrapped);
2232
+ return this.#store.get();
2233
+ }
2234
+ #saveTransaction(transaction) {
2235
+ writeJson(this.#txStorage, `${this.#prefix}tx:${transaction.state}`, transaction);
2236
+ }
2237
+ /** Reads and deletes a transaction: each one completes at most one sign-in. */
2238
+ #takeTransaction(state) {
2239
+ const key = `${this.#prefix}tx:${state}`;
2240
+ const transaction = readJson(this.#txStorage, key);
2241
+ remove(this.#txStorage, key);
2242
+ if (!transaction) return null;
2243
+ if (now() - (transaction.createdAt ?? 0) > this.#config.transactionTtlSeconds) return null;
2244
+ return transaction;
2245
+ }
2246
+ #takeLogoutTransaction(href) {
2247
+ const state = this.#responseParams(new URL(href)).state;
2248
+ if (!state) return null;
2249
+ const key = `${this.#prefix}logout:${state}`;
2250
+ const transaction = readJson(this.#txStorage, key);
2251
+ remove(this.#txStorage, key);
2252
+ this.#cleanResponseFromUrl(new URL(href));
2253
+ return transaction;
2254
+ }
2255
+ #sweepTransactions() {
2256
+ const limit = this.#config.transactionTtlSeconds;
2257
+ for (const key of keysWithPrefix(this.#txStorage, this.#prefix)) {
2258
+ if (!key.includes(":tx:") && !key.includes(":logout:")) continue;
2259
+ const entry = readJson(this.#txStorage, key);
2260
+ if (!entry || now() - (entry.createdAt ?? 0) > limit) remove(this.#txStorage, key);
2261
+ }
2262
+ }
2263
+ // =================================================================
2264
+ // internals: URLs and navigation
2265
+ // =================================================================
2266
+ #requireWindow() {
2267
+ if (!this.#win) {
2268
+ throw new ArkConfigError(
2269
+ "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."
2270
+ );
2271
+ }
2272
+ return this.#win;
2273
+ }
2274
+ /** A path becomes an absolute URL on the page's origin; an absolute URL is used as it is. */
2275
+ #resolve(value) {
2276
+ if (!value) return value;
2277
+ if (/^https?:\/\//i.test(value)) return value;
2278
+ return new URL(value, this.#requireWindow().location.origin).toString();
2279
+ }
2280
+ /** The response parameters, from the query or the fragment depending on the response mode. */
2281
+ #responseParams(url, responseMode = this.#config.responseMode) {
2282
+ const fromQuery = url.searchParams;
2283
+ const fromHash = new URLSearchParams(url.hash.startsWith("#") ? url.hash.slice(1) : url.hash);
2284
+ const pick = responseMode === "fragment" ? [fromHash, fromQuery] : [fromQuery, fromHash];
2285
+ const source = pick.find((p) => p.has("state") || p.has("code") || p.has("error")) ?? pick[0];
2286
+ const result = {};
2287
+ for (const name of RESPONSE_PARAMS) {
2288
+ const value = source.get(name);
2289
+ if (value !== null) result[name] = value;
2290
+ }
2291
+ return result;
2292
+ }
2293
+ #classify(href) {
2294
+ if (!this.#win) return null;
2295
+ let url;
2296
+ try {
2297
+ url = new URL(href, this.#win.location.href);
2298
+ } catch {
2299
+ return null;
2300
+ }
2301
+ const same = (target) => {
2302
+ if (!target) return false;
2303
+ const t = new URL(this.#resolve(target));
2304
+ return t.origin === url.origin && t.pathname === url.pathname;
2305
+ };
2306
+ const params = this.#responseParams(url);
2307
+ if (same(this.#config.redirectUri) && (params.code || params.error)) return "signin";
2308
+ if (same(this.#config.postLogoutRedirectUri ?? DEFAULT_POST_LOGOUT_PATH) && params.state) {
2309
+ this.#ensureReady();
2310
+ if (readJson(this.#txStorage, `${this.#prefix}logout:${params.state}`)) return "signout";
2311
+ }
2312
+ return null;
2313
+ }
2314
+ #cleanResponseFromUrl(url) {
2315
+ const win = this.#win;
2316
+ if (!win?.history?.replaceState) return;
2317
+ const clean = new URL(url.toString());
2318
+ for (const name of RESPONSE_PARAMS) clean.searchParams.delete(name);
2319
+ if (clean.hash) {
2320
+ const hash = new URLSearchParams(clean.hash.slice(1));
2321
+ if (RESPONSE_PARAMS.some((name) => hash.has(name))) {
2322
+ for (const name of RESPONSE_PARAMS) hash.delete(name);
2323
+ const rest = hash.toString();
2324
+ clean.hash = rest ? `#${rest}` : "";
2325
+ }
2326
+ }
2327
+ const relative = `${clean.pathname}${clean.search}${clean.hash}`;
2328
+ try {
2329
+ win.history.replaceState(win.history.state, "", relative);
2330
+ } catch {
2331
+ }
2332
+ }
2333
+ #authorizationError(params) {
2334
+ return new ArkOAuthError(params.error, params.error_description, {
2335
+ endpoint: `${this.#config.authority}/oauth2/authorize`,
2336
+ errorUri: params.error_uri ?? null,
2337
+ body: params
2338
+ });
2339
+ }
2340
+ async #redirect(url) {
2341
+ if (this.#config.redirect) return this.#config.redirect(url);
2342
+ this.#requireWindow().location.assign(url);
2343
+ }
2344
+ /** In-app navigation to a local path without reloading. See init(). */
2345
+ #navigate(to) {
2346
+ if (this.#config.navigate) return this.#config.navigate(to);
2347
+ const win = this.#win;
2348
+ if (!win) return;
2349
+ try {
2350
+ win.history.replaceState(null, "", to);
2351
+ const PopState = win.PopStateEvent ?? globalThis.PopStateEvent;
2352
+ if (typeof PopState === "function") win.dispatchEvent(new PopState("popstate", { state: null }));
2353
+ } catch {
2354
+ win.location.replace(to);
2355
+ }
2356
+ }
2357
+ // =================================================================
2358
+ // internals: events and cross-tab sync
2359
+ // =================================================================
2360
+ #emit(event, detail) {
2361
+ for (const handler of [...this.#events.get(event) ?? []]) {
2362
+ try {
2363
+ handler(detail);
2364
+ } catch (error) {
2365
+ queueMicrotask(() => {
2366
+ throw error;
2367
+ });
2368
+ }
2369
+ }
2370
+ }
2371
+ #broadcast(type) {
2372
+ try {
2373
+ this.#channel?.postMessage({ type, from: this.#id });
2374
+ } catch {
2375
+ }
2376
+ }
2377
+ #attachListeners() {
2378
+ const win = this.#win;
2379
+ if (!win || this.#detach.length) return;
2380
+ if (this.#config.syncTabs) {
2381
+ const Channel = win.BroadcastChannel ?? globalThis.BroadcastChannel;
2382
+ if (typeof Channel === "function") {
2383
+ this.#channel = unref(new Channel(`ark-oidc:${this.#config.authority}|${this.#config.clientId}`));
2384
+ this.#channel.onmessage = (event) => this.#onTabMessage(event.data);
2385
+ }
2386
+ }
2387
+ const doc = win.document;
2388
+ if (doc?.addEventListener) {
2389
+ const onVisible = () => {
2390
+ if (doc.visibilityState !== "visible" || !this.#tokens) return;
2391
+ if (this.#sharedStorage()) this.#adoptStoredTokens();
2392
+ if (this.#tokens?.expired(this.#lead(this.#tokens))) this.#renewIfNeeded();
2393
+ };
2394
+ doc.addEventListener("visibilitychange", onVisible);
2395
+ this.#detach.push(() => doc.removeEventListener("visibilitychange", onVisible));
2396
+ }
2397
+ }
2398
+ #onTabMessage(message) {
2399
+ if (!message || message.from === this.#id) return;
2400
+ if (message.type === "signed-out") {
2401
+ if (this.#tokens || this.#denial) this.#endLocalSession("signout", { broadcast: false });
2402
+ return;
2403
+ }
2404
+ if ((message.type === "tokens" || message.type === "signed-in") && this.#sharedStorage()) this.#adoptStoredTokens();
2405
+ }
2406
+ #adoptStoredTokens() {
2407
+ const stored = this.#readStoredTokens();
2408
+ if (!stored) {
2409
+ if (this.#tokens) this.#endLocalSession("signout", { broadcast: false });
2410
+ return;
2411
+ }
2412
+ if (stored.accessToken === this.#tokens?.accessToken) return;
2413
+ this.#setTokens(stored, { persist: false });
2414
+ this.#setDenial(null);
2415
+ this.#publish({ error: null });
2416
+ this.#schedule();
2417
+ }
2418
+ };
2419
+ function createArkClient(options) {
2420
+ return new ArkBrowserClient(options);
2421
+ }
2422
+
2423
+ // src/denied.js
2424
+ var PALETTE = {
2425
+ light: { bg: "#f7f7f8", surface: "#ffffff", border: "#e2e2e6", fg: "#17171a", muted: "#6a6a73", accent: "#4f46e5", accentFg: "#ffffff" },
2426
+ dark: { bg: "#111114", surface: "#1a1a1f", border: "#313139", fg: "#ececf1", muted: "#9a9aa5", accent: "#8b85ff", accentFg: "#16161c" }
2427
+ };
2428
+ function el(doc, tag, className, text) {
2429
+ const node = doc.createElement(tag);
2430
+ if (className) node.className = className;
2431
+ if (text !== void 0) node.textContent = text;
2432
+ return node;
2433
+ }
2434
+ function css(node, styles) {
2435
+ for (const [key, value] of Object.entries(styles)) node.style.setProperty(key, value);
2436
+ }
2437
+ function renderAccessDenied(container, client, options = {}) {
2438
+ const doc = container.ownerDocument ?? globalThis.document;
2439
+ const config = client.config.accountSwitch;
2440
+ const denial = client.getSnapshot().denial;
2441
+ const appName = (options.appName ?? config.appDisplayName ?? "").trim() || client.clientId || "this application";
2442
+ const account = config.showSignedInAccount ? denial?.email ?? denial?.name ?? denial?.subject ?? null : null;
2443
+ const dark = Boolean(doc.defaultView?.matchMedia?.("(prefers-color-scheme: dark)").matches);
2444
+ const c = PALETTE[dark ? "dark" : "light"];
2445
+ const styled = !options.unstyled;
2446
+ const root = el(doc, "main", "ark-denied");
2447
+ root.setAttribute("role", "alert");
2448
+ const card = el(doc, "div", "ark-denied__card");
2449
+ root.append(card);
2450
+ card.append(el(doc, "h1", "ark-denied__title", `You do not have access to ${appName}`));
2451
+ const lede = el(doc, "p", "ark-denied__lede");
2452
+ if (account) {
2453
+ lede.append("You are signed in as ", el(doc, "strong", null, account), `, and that account does not have access to ${appName}.`);
2454
+ } else {
2455
+ lede.textContent = `The account you are signed in with does not have access to ${appName}.`;
2456
+ }
2457
+ card.append(lede);
2458
+ card.append(
2459
+ el(
2460
+ doc,
2461
+ "p",
2462
+ "ark-denied__hint",
2463
+ `If somebody else was using this browser, their sign-in is still active and it is the one being offered to ${appName}. Choose \u201CSign in as a different user\u201D to enter your own credentials.`
2464
+ )
2465
+ );
2466
+ const actions = el(doc, "div", "ark-denied__actions");
2467
+ const switchButton = el(doc, "button", "ark-denied__switch", "Sign in as a different user");
2468
+ switchButton.type = "button";
2469
+ switchButton.addEventListener("click", () => client.switchUser({ returnTo: denial?.returnTo ?? void 0 }));
2470
+ actions.append(switchButton);
2471
+ let signOutButton = null;
2472
+ if (config.allowFullSignOut) {
2473
+ signOutButton = el(doc, "button", "ark-denied__signout", "Sign out completely");
2474
+ signOutButton.type = "button";
2475
+ signOutButton.addEventListener("click", () => client.signoutRedirect({ returnTo: config.homePath }));
2476
+ actions.append(signOutButton);
2477
+ }
2478
+ card.append(actions);
2479
+ let foot = null;
2480
+ if (config.supportUrl || config.supportEmail) {
2481
+ foot = el(doc, "p", "ark-denied__foot", `Need access to ${appName}? `);
2482
+ const link = el(doc, "a", null, config.supportUrl ? "Request it here" : config.supportEmail);
2483
+ link.href = config.supportUrl ? config.supportUrl : `mailto:${config.supportEmail}`;
2484
+ foot.append(link);
2485
+ card.append(foot);
2486
+ }
2487
+ const version = el(doc, "p", "ark-denied__version", `ark-oauth-client-js ${VERSION}`);
2488
+ card.append(version);
2489
+ if (styled) {
2490
+ const font = 'ui-sans-serif, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif';
2491
+ css(root, { "min-height": "100vh", display: "flex", "align-items": "center", "justify-content": "center", padding: "24px", "box-sizing": "border-box", background: c.bg, color: c.fg, font: `15px/1.55 ${font}` });
2492
+ css(card, { width: "100%", "max-width": "480px", background: c.surface, border: `1px solid ${c.border}`, "border-radius": "12px", padding: "28px", "box-sizing": "border-box" });
2493
+ for (const p of card.querySelectorAll("p")) css(p, { margin: "0 0 14px", color: c.muted });
2494
+ css(lede, { color: c.fg });
2495
+ css(card.querySelector("h1"), { margin: "0 0 10px", "font-size": "19px", "font-weight": "640" });
2496
+ css(actions, { display: "flex", "flex-direction": "column", gap: "10px", "margin-top": "20px" });
2497
+ const button = { width: "100%", padding: "11px 14px", "border-radius": "8px", font: "inherit", "font-weight": "560", cursor: "pointer" };
2498
+ css(switchButton, { ...button, border: `1px solid ${c.accent}`, background: c.accent, color: c.accentFg });
2499
+ if (signOutButton) css(signOutButton, { ...button, border: `1px solid ${c.border}`, background: "transparent", color: c.fg });
2500
+ if (foot) {
2501
+ css(foot, { "margin-top": "18px", "padding-top": "14px", "border-top": `1px solid ${c.border}`, "font-size": "13px" });
2502
+ css(foot.querySelector("a"), { color: c.accent });
2503
+ }
2504
+ css(version, { margin: "18px 0 0", "padding-top": "14px", "border-top": foot ? "0" : `1px solid ${c.border}`, "font-size": "12px", "text-align": "center" });
2505
+ }
2506
+ container.replaceChildren(root);
2507
+ return () => root.remove();
2508
+ }
2509
+ return __toCommonJS(index_exports);
2510
+ })();