ark-oauth-client-js 0.0.0-stage → 2.1.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +56 -0
- package/LICENSE +21 -0
- package/README.md +578 -2
- package/dist/ark-oauth-client.esm.min.js +3 -0
- package/dist/ark-oauth-client.esm.min.js.map +7 -0
- package/dist/ark-oauth-client.global.js +2510 -0
- package/dist/ark-oauth-client.global.min.js +3 -0
- package/dist/ark-oauth-client.global.min.js.map +7 -0
- package/package.json +122 -4
- package/src/access.js +141 -0
- package/src/angular.js +175 -0
- package/src/client.js +1426 -0
- package/src/config.js +196 -0
- package/src/crypto.js +121 -0
- package/src/denied.js +119 -0
- package/src/discovery.js +84 -0
- package/src/errors.js +110 -0
- package/src/http.js +190 -0
- package/src/index.js +44 -0
- package/src/jwks.js +124 -0
- package/src/jwt.js +223 -0
- package/src/lock.js +19 -0
- package/src/next.js +28 -0
- package/src/pkce.js +35 -0
- package/src/popup.js +162 -0
- package/src/react.js +225 -0
- package/src/storage.js +127 -0
- package/src/store.js +57 -0
- package/src/tokens.js +97 -0
- package/src/version.js +5 -0
- package/src/vue.js +110 -0
- package/types/angular.d.ts +61 -0
- package/types/index.d.ts +431 -0
- package/types/next.d.ts +19 -0
- package/types/react.d.ts +71 -0
- package/types/vue.d.ts +67 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/version.js", "../src/errors.js", "../src/access.js", "../src/config.js", "../src/http.js", "../src/discovery.js", "../src/crypto.js", "../src/jwt.js", "../src/jwks.js", "../src/tokens.js", "../src/pkce.js", "../src/store.js", "../src/storage.js", "../src/lock.js", "../src/popup.js", "../src/client.js", "../src/denied.js"],
|
|
4
|
+
"sourcesContent": ["/**\n * The package version. Kept in step with `ark-oauth-client` (npm), `ark-oauth-client` (PyPI) and\n * `Ark.oAuth.Client` (NuGet): the four clients are ports of each other and release together.\n */\nexport const VERSION = '2.1.8';\n", "/**\n * The error types this library throws.\n *\n * Every failure that came from the authorization server arrives as an ArkOAuthError carrying the\n * `error` code the spec defines, because that code is the only part a caller can branch on. A\n * library that collapses `invalid_grant` and a CORS failure into one thrown string forces the\n * application to parse English to decide whether to retry, sign the user in again, or give up.\n *\n * The names and fields match `ark-oauth-client` for Node, so code that handles errors from one\n * reads the same against the other.\n */\n\n/** Base class, so `catch (e) { if (e instanceof ArkError) ... }` covers everything from here. */\nexport class ArkError extends Error {\n constructor(message, options) {\n super(message, options);\n this.name = new.target.name;\n }\n}\n\n/**\n * The client is misconfigured: a missing authority, a client secret handed to a browser, a\n * redirect URI with a fragment. Thrown at construction wherever possible, so the mistake shows up\n * the first time the page loads and not on a user's failed sign-in.\n */\nexport class ArkConfigError extends ArkError {}\n\n/**\n * An RFC 6749 \u00A75.2 error: the server (or the authorization response) said `error=...`.\n *\n * `error` is the machine-readable code (`invalid_grant`, `access_denied`, `login_required`, ...),\n * `status` the HTTP status it came with (0 for a redirect), and `endpoint` the URL that produced\n * it, which tells \"the token endpoint refused the code\" apart from \"userinfo refused the token\".\n */\nexport class ArkOAuthError extends ArkError {\n constructor(error, description, { status = 0, endpoint = null, errorUri = null, body = null } = {}) {\n super(description ? `${error}: ${description}` : error);\n this.error = error;\n this.errorDescription = description ?? null;\n this.errorUri = errorUri;\n this.status = status;\n this.endpoint = endpoint;\n this.body = body;\n }\n\n /** Builds the error from a parsed response body, falling back to the HTTP status. */\n static fromResponse(status, body, endpoint) {\n if (body && typeof body === 'object' && typeof body.error === 'string') {\n return new ArkOAuthError(body.error, body.error_description, {\n status,\n endpoint,\n errorUri: body.error_uri ?? null,\n body\n });\n }\n return new ArkOAuthError('server_error', `the endpoint returned HTTP ${status}.`, { status, endpoint, body });\n }\n}\n\n/**\n * A token arrived but did not survive validation: a bad signature, the wrong issuer or audience,\n * an expired `exp`, a `nonce` that is not the one sent, an `at_hash` that does not cover the\n * access token beside it.\n *\n * Separate from ArkOAuthError on purpose. An OAuth error means the server refused; this means the\n * server answered and the answer cannot be trusted, which is worse and must never be retried.\n */\nexport class ArkTokenError extends ArkError {\n constructor(message, { claim = null } = {}) {\n super(message);\n this.claim = claim;\n }\n}\n\n/**\n * The authorization response could not be tied to a sign-in this page started: an unknown or\n * missing `state`, an expired transaction, an `iss` that is not the provider the user was sent to\n * (RFC 9207). Treat it as an attempted CSRF or mix-up attack, not as a user error.\n */\nexport class ArkCallbackError extends ArkError {}\n\n/**\n * The request did not complete: offline, DNS, timeout, aborted, or (in a browser, and much more\n * often than the others) refused by CORS. A browser reports all of those as the same opaque\n * `TypeError: Failed to fetch`, so the message says which one is likely and what to change.\n */\nexport class ArkNetworkError extends ArkError {}\n\n/**\n * The action needs a signed-in user and there is none, or the session can no longer be renewed.\n * `ark.fetch()` throws it; the remedy is `ark.signinRedirect()`.\n */\nexport class ArkLoginRequiredError extends ArkError {\n constructor(message = 'no user is signed in, or the session has ended. Call signinRedirect() to sign in.') {\n super(message);\n this.error = 'login_required';\n }\n}\n\n/**\n * The popup sign-in did not finish. `reason` is `blocked` (the browser refused to open it, almost\n * always because `signinPopup()` was not called straight from a click), `closed` (the user closed\n * it) or `timeout`.\n */\nexport class ArkPopupError extends ArkError {\n constructor(reason, message) {\n super(message);\n this.reason = reason;\n }\n}\n", "import { ArkConfigError } from './errors.js';\n\n/**\n * Account switching on a shared browser.\n *\n * Single sign-on is browser-wide: once one person signs in anywhere, the provider's session answers\n * every other app's sign-in in that browser. The next person opens this app, is signed in as the\n * previous one, and is told they have no access, for an account that is not even theirs. Signing in\n * again goes back to the same provider session and gives the same answer.\n *\n * Breaking that loop needs two things: a dead end that is honest about whose session it is, and a\n * sign-in that sends `prompt=login`, the one parameter a provider must honour by ignoring its\n * session and drawing the sign-in form (OIDC Core \u00A73.1.2.1).\n *\n * The same feature, under the same names, as `AccountSwitch` in the .NET client, `account_switch`\n * in Python and `accountSwitch` in Node. Off by default, as there.\n */\n\nexport const ArkAccessDeniedReasons = Object.freeze({\n /** The provider authenticated them, but they hold no authorization claims for this client. */\n NO_APP_ACCESS: 'no_app_access',\n /** They are signed in, but a guard refused the page they asked for. */\n FORBIDDEN: 'forbidden'\n});\n\nexport const ACCOUNT_SWITCH_DEFAULTS = Object.freeze({\n /**\n * Refuse the sign-in when the access token carries no `ark_claims` for this client. Off, the wrong\n * account is signed in and every guarded view says \"forbidden\". On, the callback stops before any\n * token is stored and the state becomes `denied`, from where the user can switch.\n *\n * Ark issues the user's whole claim mapping as `ark_claims`, identity names like `email`\n * included, so this check alone admits a user with an identity-only mapping. Name the claims\n * that mean \"may use this app\" in `requiredClaims`.\n */\n requireArkClaims: false,\n /** Narrow that check: at least one of these. Empty means any `ark_claims` will do. */\n requiredClaims: Object.freeze([]),\n /** Where to send the browser after a refused sign-in. Null stays on the page the user asked for. */\n accessDeniedPath: null,\n /** Sent as `prompt` when switching. `login` is the one every provider honours. */\n prompt: 'login',\n /**\n * Make switching a full RP-initiated logout first. Off, only this app's tokens are dropped and\n * the previous user's other apps are left alone; on, they are signed out everywhere (right for a\n * kiosk, heavy-handed for a laptop).\n */\n endProviderSessionOnSwitch: false,\n /** The app's name on the built-in page. Defaults to the client id. */\n appDisplayName: null,\n /** Name the refused account on the page. On a shared browser it is somebody else's address. */\n showSignedInAccount: true,\n /** Offer \"Sign out completely\" beside \"Sign in as a different user\". */\n allowFullSignOut: true,\n /** Where \"Sign out completely\" lands, and the fallback for an absent or off-site return URL. */\n homePath: '/',\n supportUrl: null,\n supportEmail: null\n});\n\n/**\n * Keeps a return URL inside this app. Echoing an arbitrary one would make sign-in an open redirect:\n * a phishing link that keeps your domain in the address bar until it hands the user to somebody else.\n */\nexport function localOrDefault(url, fallback = '/') {\n const home = typeof fallback === 'string' && fallback.trim() ? fallback : fallback === null ? null : '/';\n if (typeof url !== 'string' || !url.trim()) return home;\n const candidate = url.trim();\n if (!candidate.startsWith('/') || candidate.startsWith('//')) return home;\n // Browsers read `\\` as `/`, so `/\\evil.example` is `//evil.example`, another host. They also\n // strip tabs and newlines before parsing, so `/\\t/evil.example` collapses to the same thing.\n if (candidate.startsWith('/\\\\')) return home;\n // eslint-disable-next-line no-control-regex\n if (/[\\u0000-\\u001f\\u007f]/.test(candidate)) return home;\n return candidate;\n}\n\n/** Fills in the defaults and refuses what could only fail later, in front of a user. */\nexport function normalizeAccountSwitch(options = {}) {\n const merged = { ...ACCOUNT_SWITCH_DEFAULTS };\n for (const [key, value] of Object.entries(options ?? {})) {\n if (Object.prototype.hasOwnProperty.call(ACCOUNT_SWITCH_DEFAULTS, key) && value !== undefined) merged[key] = value;\n }\n for (const key of ['accessDeniedPath', 'homePath']) {\n if (merged[key] !== null && localOrDefault(merged[key], null) !== merged[key]) {\n throw new ArkConfigError(`ark_oauth_client: accountSwitch.${key} must be a local path starting with '/', but is '${merged[key]}'.`);\n }\n }\n if (merged.supportUrl && !/^https?:\\/\\//i.test(merged.supportUrl)) {\n throw new ArkConfigError(`ark_oauth_client: accountSwitch.supportUrl must be an http(s) URL, but is '${merged.supportUrl}'.`);\n }\n merged.requiredClaims = Object.freeze([...(merged.requiredClaims ?? [])].map(String));\n return Object.freeze(merged);\n}\n\n/**\n * The sign-in options that make \"sign in as a different user\" work. Without `prompt=login` the\n * provider answers from the session it already has, and the wrong person is signed in again.\n * The result is what `signinRedirect()` and `signinPopup()` accept.\n */\nexport const ArkChallengeProperties = Object.freeze({\n switchUser(returnTo = null, loginHint = null, prompt = 'login') {\n return { returnTo: returnTo || '/', prompt: prompt || 'login', ...(loginHint ? { loginHint } : {}) };\n },\n\n /** The provider's account picker. A provider without one falls back to its sign-in form. */\n selectAccount(returnTo = null) {\n return ArkChallengeProperties.switchUser(returnTo, null, 'select_account');\n }\n});\n\n/**\n * The entitlement decision, made once per sign-in at the callback: not \"may this user open that\n * view\" but \"may this user use this app at all\". Refusing there means no token is ever stored.\n *\n * `onEvaluateAccess` replaces the configured rule rather than being ANDed with it; a handler that\n * wants both reads `allowedByConfiguration` and says so.\n */\nexport async function evaluateAccess(options, onEvaluateAccess, { claims = {}, arkClaims = [], tokens = null } = {}) {\n const required = options.requiredClaims.map((c) => c.toLowerCase());\n const allowedByConfiguration =\n !options.requireArkClaims || (required.length ? arkClaims.some((c) => required.includes(String(c).toLowerCase())) : arkClaims.length > 0);\n if (typeof onEvaluateAccess !== 'function') return allowedByConfiguration;\n return Boolean(await onEvaluateAccess({ claims: { ...claims }, arkClaims: [...arkClaims], allowedByConfiguration, tokens }));\n}\n\n/** What is known about a refused account, read off whatever identity there is. */\nexport function describeDenial(reason, claims, arkClaims, returnTo) {\n const first = (...names) => {\n for (const name of names) if (claims?.[name]) return String(claims[name]);\n return null;\n };\n return {\n reason,\n subject: first('sub'),\n email: first('email', 'preferred_username'),\n name: first('name'),\n arkClaims: [...(arkClaims ?? [])],\n returnTo: returnTo ?? null\n };\n}\n", "import { ArkConfigError } from './errors.js';\nimport { normalizeAccountSwitch } from './access.js';\n\n/**\n * Normalises and checks what the application configured.\n *\n * Everything that can be caught without the network is caught here, when the client is created,\n * because the alternative is finding out from a user's failed sign-in. A client secret shipped to\n * a browser, an authority that is really a base URL with the tenant id missing, a redirect URI with\n * a fragment: each produces an `invalid_request` page later and an afternoon of reading server\n * logs, or one sentence here.\n *\n * Nothing in here touches `window`, so a client can be created during server-side rendering\n * (Next.js, Nuxt, Angular SSR). Relative URIs are resolved against the page's origin later, in the\n * browser.\n */\n\nexport const DEFAULT_SCOPES = Object.freeze(['openid', 'profile', 'email', 'offline_access']);\nexport const DEFAULT_REDIRECT_PATH = '/signin-oidc';\nexport const DEFAULT_POST_LOGOUT_PATH = '/signout-callback-oidc';\n\nfunction isLoopback(url) {\n return ['localhost', '127.0.0.1', '[::1]', '::1'].includes(url.hostname);\n}\n\nfunction parseAbsolute(value, setting) {\n let url;\n try {\n url = new URL(value);\n } catch {\n throw new ArkConfigError(`ark_oauth_client: '${setting}' must be an absolute URL, but is '${value}'.`);\n }\n if (url.protocol !== 'https:' && url.protocol !== 'http:') {\n throw new ArkConfigError(`ark_oauth_client: '${setting}' must be an http or https URL, but is '${value}'.`);\n }\n return url;\n}\n\n/**\n * A redirect target: an absolute URL, or a path starting with `/` that is resolved against the\n * page's origin at runtime. The server matches redirect URIs byte for byte, so what is registered\n * must be exactly what this resolves to.\n */\nfunction checkRedirect(value, setting) {\n if (value === null || value === undefined || value === '') return null;\n const text = String(value);\n if (text.startsWith('/') && !text.startsWith('//')) {\n if (text.includes('#')) throw new ArkConfigError(`ark_oauth_client: '${setting}' must not contain a fragment: ${text}`);\n return text;\n }\n const url = parseAbsolute(text, setting);\n if (url.hash) throw new ArkConfigError(`ark_oauth_client: '${setting}' must not contain a fragment: ${text}`);\n if (url.protocol !== 'https:' && !isLoopback(url)) {\n throw new ArkConfigError(`ark_oauth_client: '${setting}' is ${text}. The server accepts http only for loopback addresses (RFC 8252 \u00A77.3).`);\n }\n return text;\n}\n\nfunction normalizeOrigins(list) {\n return Object.freeze(\n [...(list ?? [])].map((value) => {\n if (value === '*') {\n throw new ArkConfigError(\"ark_oauth_client: 'apiOrigins' cannot be '*'. List the exact origins the access token may be sent to.\");\n }\n return parseAbsolute(String(value), 'apiOrigins').origin;\n })\n );\n}\n\nexport function normalizeConfig(options = {}) {\n const {\n authority,\n authServerUrl,\n tenantId,\n clientId,\n clientSecret,\n privateKeyJwt,\n tokenEndpointAuthMethod,\n usePar,\n redirectUri = DEFAULT_REDIRECT_PATH,\n postLogoutRedirectUri = DEFAULT_POST_LOGOUT_PATH,\n scopes,\n responseMode = 'query',\n prompt = null,\n acrValues = null,\n extraAuthorizationParams = null,\n storage = 'session',\n automaticRefresh = true,\n refreshBeforeSeconds = 60,\n apiOrigins = [],\n syncTabs = true,\n accountSwitch,\n onEvaluateAccess = null,\n onRedirectCallback = null,\n navigate = null,\n redirect = null,\n popup = {},\n transactionTtlSeconds = 600,\n clockToleranceSeconds = 60,\n requireHttps = true,\n requireTokenHashes = true,\n idTokenSigningAlgorithms = null,\n timeoutMs = 10_000,\n metadataTtlMs = 5 * 60_000,\n jwksTtlMs = 5 * 60_000,\n jwksMinRefreshIntervalMs = 10_000,\n fetch: fetchImpl = undefined\n } = options;\n\n // The .NET client accepts AuthServerUrl + TenantId as well as Authority, so the values already in\n // an appsettings.json or a .env can be used as they are.\n let resolvedAuthority = String(authority ?? '').trim();\n if (!resolvedAuthority && authServerUrl && tenantId) resolvedAuthority = `${String(authServerUrl).replace(/\\/+$/, '')}/${tenantId}`;\n if (!resolvedAuthority) {\n throw new ArkConfigError(\n \"ark_oauth_client: set 'authority' to the issuer URL of your Ark tenant, {BaseUrl}/{TenantId}, e.g. \" +\n 'https://idp.example.com/my_idp. (Or set authServerUrl + tenantId and they are joined for you.)'\n );\n }\n resolvedAuthority = resolvedAuthority.replace(/\\/+$/, '');\n const authorityUrl = parseAbsolute(resolvedAuthority, 'authority');\n if (requireHttps && authorityUrl.protocol !== 'https:' && !isLoopback(authorityUrl)) {\n throw new ArkConfigError(\n `ark_oauth_client: 'authority' is ${resolvedAuthority}, which is plain http. Tokens would cross the network in the clear. ` +\n 'Use https, or set requireHttps:false, only ever for local development.'\n );\n }\n\n if (!clientId || typeof clientId !== 'string') {\n throw new ArkConfigError(\"ark_oauth_client: 'clientId' is required: the client id registered with the tenant.\");\n }\n\n // Everything shipped to a browser is public. A secret in a bundle is a secret on every visitor's\n // disk, and the server cannot tell the app from anyone who copied it. Register the SPA as a\n // public client (token_endpoint_auth_method \"none\"); keep confidential clients on a server.\n if (clientSecret || privateKeyJwt || (tokenEndpointAuthMethod && tokenEndpointAuthMethod !== 'none')) {\n throw new ArkConfigError(\n 'ark_oauth_client: a browser app cannot keep a client secret or a private key: anything in the bundle is readable by ' +\n \"every visitor. Register this app as a public client (token endpoint auth method 'none'; PKCE protects the code), \" +\n 'or keep the confidential client on a server with ark-oauth-client (Node), ark-oauth-client (Python) or Ark.oAuth.Client (.NET).'\n );\n }\n\n // The pushed authorization request endpoint needs client authentication and grants no CORS, so a\n // browser cannot use it. Said now rather than as a failed preflight later.\n if (usePar) {\n throw new ArkConfigError(\n \"ark_oauth_client: 'usePar' is not available in a browser app: /oauth2/par needs client authentication and serves no CORS. \" +\n 'Leave PAR to a server-side client.'\n );\n }\n\n if (!['query', 'fragment'].includes(responseMode)) {\n throw new ArkConfigError(\n `ark_oauth_client: 'responseMode' is '${responseMode}'. A browser app reads the response from its own URL, so use 'query' or 'fragment'` +\n (responseMode === 'form_post' ? '; form_post POSTs to a server, which a single-page app does not have.' : '.')\n );\n }\n\n if (!Number.isFinite(refreshBeforeSeconds) || refreshBeforeSeconds < 0) {\n throw new ArkConfigError(`ark_oauth_client: 'refreshBeforeSeconds' must be a number of seconds, not '${refreshBeforeSeconds}'.`);\n }\n\n return Object.freeze({\n authority: resolvedAuthority,\n clientId,\n redirectUri: checkRedirect(redirectUri, 'redirectUri') ?? DEFAULT_REDIRECT_PATH,\n postLogoutRedirectUri: checkRedirect(postLogoutRedirectUri, 'postLogoutRedirectUri'),\n scopes: Object.freeze(scopes?.length ? [...scopes] : [...DEFAULT_SCOPES]),\n responseMode,\n prompt,\n acrValues,\n extraAuthorizationParams: extraAuthorizationParams ? Object.freeze({ ...extraAuthorizationParams }) : null,\n storage,\n automaticRefresh: Boolean(automaticRefresh),\n refreshBeforeSeconds,\n apiOrigins: normalizeOrigins(apiOrigins),\n syncTabs: Boolean(syncTabs),\n accountSwitch: normalizeAccountSwitch(accountSwitch),\n onEvaluateAccess,\n onRedirectCallback,\n navigate,\n redirect,\n popup: Object.freeze({ width: 520, height: 680, timeoutMs: 5 * 60_000, ...popup }),\n transactionTtlSeconds,\n clockToleranceSeconds,\n requireHttps,\n requireTokenHashes,\n idTokenSigningAlgorithms: idTokenSigningAlgorithms ? Object.freeze([...idTokenSigningAlgorithms]) : null,\n timeoutMs,\n metadataTtlMs,\n jwksTtlMs,\n jwksMinRefreshIntervalMs,\n fetch: fetchImpl\n });\n}\n", "import { ArkNetworkError, ArkOAuthError } from './errors.js';\n\n/**\n * The HTTP layer: the one place that knows how the server answers and how a browser fails.\n *\n * Every non-2xx response becomes an ArkOAuthError carrying the server's own `error` code. Every\n * request has a timeout. And because a browser reports a CORS refusal, a DNS failure and a dead\n * server as the same bare `TypeError`, a failed fetch is turned into a message that names the\n * likeliest cause (the app's origin missing from the provider's `CorsOrigins`) and how to fix it.\n */\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\n\nfunction timeoutSignal(signal, timeoutMs) {\n let timeout;\n if (typeof AbortSignal.timeout === 'function') {\n timeout = AbortSignal.timeout(timeoutMs);\n } else {\n const controller = new AbortController();\n setTimeout(() => controller.abort(new DOMException('The operation timed out.', 'TimeoutError')), timeoutMs);\n timeout = controller.signal;\n }\n if (!signal) return timeout;\n if (typeof AbortSignal.any === 'function') return AbortSignal.any([signal, timeout]);\n const controller = new AbortController();\n const forward = (source) => () => controller.abort(source.reason);\n if (signal.aborted) controller.abort(signal.reason);\n signal.addEventListener('abort', forward(signal), { once: true });\n timeout.addEventListener('abort', forward(timeout), { once: true });\n return controller.signal;\n}\n\nasync function readBody(response) {\n const text = await response.text();\n if (!text) return null;\n const type = response.headers.get('content-type') ?? '';\n const trimmed = text.trimStart();\n if (type.includes('json') || trimmed.startsWith('{') || trimmed.startsWith('[')) {\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n }\n return text;\n}\n\nfunction currentOrigin() {\n try {\n return globalThis.location?.origin ?? null;\n } catch {\n return null;\n }\n}\n\n/** The explanation attached to a fetch that failed without a response. */\nexport function describeFetchFailure(method, url, cause, timeoutMs) {\n const timedOut = cause?.name === 'TimeoutError' || cause?.cause?.name === 'TimeoutError';\n if (timedOut) return `${method} ${url} timed out after ${timeoutMs}ms.`;\n if (cause?.name === 'AbortError') return `${method} ${url} was aborted.`;\n const origin = currentOrigin();\n return (\n `${method} ${url} failed: ${cause?.message ?? cause}. In a browser this is most often CORS: the provider must list ` +\n `this app's origin${origin && origin !== 'null' ? ` (${origin})` : ''} in ark_oauth_server:Oidc:CorsOrigins ` +\n '(the Protocol step of the setup wizard). Otherwise the provider is unreachable from here: wrong host or port, offline, or stopped.'\n );\n}\n\n/**\n * Performs one request and returns `{ status, body, headers }`.\n *\n * @param {string} url\n * @param {object} [options]\n * @param {'GET'|'POST'} [options.method]\n * @param {Record<string, string|undefined|null>} [options.form] form-urlencoded body; empty entries dropped\n * @param {Record<string, string>} [options.headers]\n * @param {RequestCache} [options.cache] GETs of metadata and keys honour the server's Cache-Control\n * @param {number} [options.timeoutMs]\n * @param {AbortSignal} [options.signal]\n * @param {typeof fetch} [options.fetch]\n */\nexport async function request(url, options = {}) {\n const {\n method = 'GET',\n form,\n headers = {},\n cache,\n timeoutMs = DEFAULT_TIMEOUT_MS,\n signal,\n fetch: fetchImpl = globalThis.fetch\n } = options;\n\n if (typeof fetchImpl !== 'function') {\n throw new ArkNetworkError('no fetch implementation is available; pass `fetch` in the client options.');\n }\n\n const init = {\n method,\n headers: { Accept: 'application/json', ...headers },\n signal: timeoutSignal(signal, timeoutMs),\n // Token and userinfo responses are never cached: a cached userinfo keyed on a bearer token is\n // a different user's tomorrow. Discovery and JWKS pass `default` to reuse the server's max-age.\n cache: cache ?? 'no-store',\n // The provider grants CORS without credentials, and nothing here should ever carry the\n // provider's session cookie: a bearer token in a header is the whole of the authentication.\n credentials: 'omit',\n // A GET of metadata or keys may follow a redirect (http to https is common), and the issuer\n // check on the document is what establishes trust. A POST carries a code or a refresh token,\n // and a redirect would forward it somewhere else.\n redirect: method === 'GET' ? 'follow' : 'manual'\n };\n\n if (form) {\n const body = new URLSearchParams();\n for (const [key, value] of Object.entries(form)) {\n if (value === undefined || value === null || value === '') continue;\n body.set(key, String(value));\n }\n init.body = body;\n init.headers['Content-Type'] = 'application/x-www-form-urlencoded';\n }\n\n let response;\n try {\n response = await fetchImpl(url, init);\n } catch (cause) {\n throw new ArkNetworkError(describeFetchFailure(method, url, cause, timeoutMs), { cause });\n }\n\n if (response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400)) {\n throw new ArkOAuthError('server_error', `${method} ${url} answered with a redirect, which is not followed for a token request.`, {\n status: response.status,\n endpoint: url\n });\n }\n\n const body = await readBody(response);\n if (!response.ok) throw ArkOAuthError.fromResponse(response.status, body, url);\n return { status: response.status, body, headers: response.headers };\n}\n\n/** GET returning a JSON object. */\nexport async function getJson(url, options) {\n const { body } = await request(url, { ...options, method: 'GET' });\n if (!body || typeof body !== 'object') {\n throw new ArkOAuthError('server_error', `${url} did not return a JSON object.`, { endpoint: url, body });\n }\n return body;\n}\n\n/** POST a form, returning the JSON response. */\nexport async function postForm(url, form, options) {\n const { body, status } = await request(url, { ...options, method: 'POST', form });\n if (body === null) return {};\n if (typeof body !== 'object') {\n throw new ArkOAuthError('server_error', `${url} returned HTTP ${status} with a non-JSON body.`, { endpoint: url, status, body });\n }\n return body;\n}\n\n/**\n * POST a form without reading the answer: `mode: 'no-cors'`.\n *\n * For token revocation. The Ark server grants CORS on the token, userinfo, discovery and JWKS\n * endpoints, but not on `/revoke`, so a normal fetch from a page is delivered and then refused at\n * the response. A form-urlencoded POST with no custom header is a CORS-safelisted request, so in\n * `no-cors` mode it is delivered just the same, and the browser hands back an opaque response\n * rather than an error. Revocation answers 200 whether or not the token existed (RFC 7009 \u00A72.2),\n * so there is nothing in the response worth reading anyway: resolving means it was delivered.\n */\nexport async function postFormNoCors(url, form, { timeoutMs = DEFAULT_TIMEOUT_MS, fetch: fetchImpl = globalThis.fetch } = {}) {\n const body = new URLSearchParams();\n for (const [key, value] of Object.entries(form)) {\n if (value !== undefined && value !== null && value !== '') body.set(key, String(value));\n }\n try {\n await fetchImpl(url, {\n method: 'POST',\n mode: 'no-cors',\n credentials: 'omit',\n cache: 'no-store',\n // Survives the page navigating away, which is exactly what a sign-out does next.\n keepalive: true,\n body,\n signal: timeoutSignal(undefined, timeoutMs)\n });\n } catch (cause) {\n throw new ArkNetworkError(describeFetchFailure('POST', url, cause, timeoutMs), { cause });\n }\n}\n", "import { getJson } from './http.js';\nimport { ArkConfigError, ArkOAuthError } from './errors.js';\n\n/**\n * The discovery document (OpenID Connect Discovery 1.0 / RFC 8414).\n *\n * The issuer is the only URL an Ark app is told. Every endpoint comes from here, which is what lets\n * the provider move an endpoint or rotate a key without a single SPA being rebuilt.\n */\n\nconst DEFAULT_TTL_MS = 5 * 60_000; // the server sends Cache-Control: max-age=300\n\n/** Both spellings of the metadata URL: OIDC appends the well-known path, RFC 8414 inserts it. */\nexport function discoveryUrls(authority) {\n const base = authority.replace(/\\/+$/, '');\n const url = new URL(base);\n const path = url.pathname.replace(/\\/+$/, '');\n return [`${base}/.well-known/openid-configuration`, `${url.origin}/.well-known/oauth-authorization-server${path}`];\n}\n\n/** Fetches and caches provider metadata for one authority. Concurrent callers share one request. */\nexport class MetadataResolver {\n #authority;\n #ttlMs;\n #http;\n #entry = null;\n\n constructor(authority, { ttlMs = DEFAULT_TTL_MS, ...http } = {}) {\n this.#authority = authority.replace(/\\/+$/, '');\n this.#ttlMs = ttlMs;\n this.#http = http;\n }\n\n get(force = false) {\n const hit = this.#entry;\n if (hit && !force && (hit.pending || Date.now() - hit.fetchedAt <= this.#ttlMs)) return hit.promise;\n\n const entry = { fetchedAt: Date.now(), pending: true };\n entry.promise = this.#fetch(force).then(\n (metadata) => {\n entry.pending = false;\n return metadata;\n },\n (error) => {\n // A failed lookup is not cached, or one bad moment would wedge the page for the whole TTL.\n if (this.#entry === entry) this.#entry = null;\n throw error;\n }\n );\n this.#entry = entry;\n return entry.promise;\n }\n\n clear() {\n this.#entry = null;\n }\n\n async #fetch(force) {\n const [primary, fallback] = discoveryUrls(this.#authority);\n // `default` lets the browser's HTTP cache answer within the server's max-age, which saves a\n // round trip on every page load; a forced read revalidates instead.\n const options = { ...this.#http, cache: force ? 'no-cache' : 'default' };\n let metadata;\n try {\n metadata = await getJson(primary, options);\n } catch (error) {\n if (error instanceof ArkOAuthError && error.status === 404) metadata = await getJson(fallback, options);\n else throw error;\n }\n\n if (!metadata.issuer) {\n throw new ArkOAuthError('server_error', `${primary} returned a document with no 'issuer'.`, { endpoint: primary });\n }\n // OIDC Discovery \u00A74.3: the document's issuer must equal the one used to look it up. A mismatch\n // is the shape of a mix-up attack, and far more often a missing tenant id in configuration.\n if (metadata.issuer.replace(/\\/+$/, '') !== this.#authority) {\n throw new ArkConfigError(\n `the provider at ${primary} identifies itself as '${metadata.issuer}', but this client is configured for ` +\n `'${this.#authority}'. Set 'authority' to exactly the issuer value: for Ark that is {BaseUrl}/{TenantId}.`\n );\n }\n return Object.freeze(metadata);\n }\n}\n", "import { ArkConfigError, ArkTokenError } from './errors.js';\n\n/**\n * The small cryptographic primitives the protocol is built from, on the Web Crypto API.\n *\n * No dependency supplies any of it: nothing in the chain that mints a PKCE verifier or checks an\n * ID token signature can be swapped out by a typosquatted package on install.\n *\n * `crypto.subtle` exists only in a secure context, meaning https, or http on localhost/127.0.0.1.\n * A page served over plain http from a LAN address has no SubtleCrypto at all. That is reported\n * by name here, because otherwise it surfaces as \"cannot read properties of undefined\" deep inside\n * a sign-in.\n */\n\nfunction webCrypto() {\n const c = globalThis.crypto;\n if (!c?.getRandomValues) {\n throw new ArkConfigError('ark_oauth_client: this environment has no Web Crypto API (globalThis.crypto).');\n }\n return c;\n}\n\nexport function subtle() {\n const s = webCrypto().subtle;\n if (!s) {\n throw new ArkConfigError(\n 'ark_oauth_client: crypto.subtle is unavailable because this page is not a secure context. ' +\n 'Serve the app over https, or over http only on localhost / 127.0.0.1 during development.'\n );\n }\n return s;\n}\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\nfunction toBytes(input) {\n if (input instanceof Uint8Array) return input;\n if (input instanceof ArrayBuffer) return new Uint8Array(input);\n if (ArrayBuffer.isView(input)) return new Uint8Array(input.buffer, input.byteOffset, input.byteLength);\n return encoder.encode(String(input));\n}\n\n/** base64url without padding (RFC 7515 \u00A72). Accepts bytes or a string (encoded as UTF-8). */\nexport function base64UrlEncode(input) {\n const bytes = toBytes(input);\n let binary = '';\n // Chunked, so a large input cannot overflow the argument list of String.fromCharCode.\n for (let i = 0; i < bytes.length; i += 0x8000) {\n binary += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000));\n }\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\n/** Decodes base64url to bytes, tolerating the padding some encoders leave on. */\nexport function base64UrlDecode(value) {\n const normalized = String(value).replace(/-/g, '+').replace(/_/g, '/');\n const padded = normalized + '='.repeat((4 - (normalized.length % 4)) % 4);\n let binary;\n try {\n binary = atob(padded);\n } catch (cause) {\n throw new ArkTokenError('a token segment is not valid base64url.', { cause });\n }\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\n\n/** base64url to a UTF-8 string. */\nexport function base64UrlDecodeToString(value) {\n return decoder.decode(base64UrlDecode(value));\n}\n\n/**\n * Cryptographically random bytes as base64url.\n *\n * Every unguessable value in the flow (`state`, `nonce`, the PKCE verifier) comes from here and\n * only from here. The .NET client this family descends from was rewritten because its predecessor\n * derived the PKCE verifier from a timestamp, which made it guessable and PKCE worthless.\n */\nexport function randomToken(bytes = 32) {\n const buffer = new Uint8Array(bytes);\n webCrypto().getRandomValues(buffer);\n return base64UrlEncode(buffer);\n}\n\n/** A digest as bytes. `hash` is a Web Crypto name: SHA-256, SHA-384 or SHA-512. */\nexport async function digest(input, hash = 'SHA-256') {\n return new Uint8Array(await subtle().digest(hash, toBytes(input)));\n}\n\nexport function sha256(input) {\n return digest(input, 'SHA-256');\n}\n\n/**\n * The left-most half of a digest, base64url encoded: the construction OIDC Core \u00A73.1.3.6 uses for\n * `at_hash` and `c_hash`. The hash follows the ID token's `alg` (SHA-256 for RS256, which is what\n * Ark signs with).\n */\nexport async function leftHalfHash(value, hash = 'SHA-256') {\n const full = await digest(value, hash);\n return base64UrlEncode(full.subarray(0, full.length / 2));\n}\n\n/**\n * Compares two strings without returning early on the first difference.\n *\n * Used for `state`. A browser comparing its own state is not much of a timing oracle, but the\n * comparison costs nothing to get right, and it keeps this check the same shape as the server\n * clients'.\n */\nexport function constantTimeEqual(a, b) {\n if (typeof a !== 'string' || typeof b !== 'string') return false;\n const x = encoder.encode(a);\n const y = encoder.encode(b);\n let diff = x.length ^ y.length;\n for (let i = 0; i < Math.max(x.length, y.length); i++) diff |= (x[i] ?? 0) ^ (y[i] ?? 0);\n return diff === 0;\n}\n", "import { base64UrlDecode, base64UrlDecodeToString, leftHalfHash, subtle } from './crypto.js';\nimport { ArkTokenError } from './errors.js';\n\n/**\n * JWT decoding, signature verification (Web Crypto) and claim validation.\n *\n * Ark signs with RS256 and publishes its keys at `jwks_uri`. The other JWS families are accepted so\n * the same client works against another provider without a second implementation. `none` is never\n * accepted: an unsigned token is one anyone can write, and every JWT library vulnerability of note\n * came from honouring the `alg` header before deciding which algorithms are acceptable.\n */\n\nconst ALGORITHMS = {\n RS256: { kty: 'RSA', hash: 'SHA-256', importParams: { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, verifyParams: { name: 'RSASSA-PKCS1-v1_5' } },\n RS384: { kty: 'RSA', hash: 'SHA-384', importParams: { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-384' }, verifyParams: { name: 'RSASSA-PKCS1-v1_5' } },\n RS512: { kty: 'RSA', hash: 'SHA-512', importParams: { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-512' }, verifyParams: { name: 'RSASSA-PKCS1-v1_5' } },\n PS256: { kty: 'RSA', hash: 'SHA-256', importParams: { name: 'RSA-PSS', hash: 'SHA-256' }, verifyParams: { name: 'RSA-PSS', saltLength: 32 } },\n PS384: { kty: 'RSA', hash: 'SHA-384', importParams: { name: 'RSA-PSS', hash: 'SHA-384' }, verifyParams: { name: 'RSA-PSS', saltLength: 48 } },\n PS512: { kty: 'RSA', hash: 'SHA-512', importParams: { name: 'RSA-PSS', hash: 'SHA-512' }, verifyParams: { name: 'RSA-PSS', saltLength: 64 } },\n // JWS carries ECDSA signatures as raw r||s, which is also what Web Crypto expects.\n ES256: { kty: 'EC', hash: 'SHA-256', crv: 'P-256', importParams: { name: 'ECDSA', namedCurve: 'P-256' }, verifyParams: { name: 'ECDSA', hash: 'SHA-256' } },\n ES384: { kty: 'EC', hash: 'SHA-384', crv: 'P-384', importParams: { name: 'ECDSA', namedCurve: 'P-384' }, verifyParams: { name: 'ECDSA', hash: 'SHA-384' } },\n ES512: { kty: 'EC', hash: 'SHA-512', crv: 'P-521', importParams: { name: 'ECDSA', namedCurve: 'P-521' }, verifyParams: { name: 'ECDSA', hash: 'SHA-512' } }\n};\n\nexport const SUPPORTED_ALGORITHMS = Object.freeze(Object.keys(ALGORITHMS));\n\n/** The Web Crypto hash an algorithm's `at_hash`/`c_hash` is computed with. */\nexport function hashForAlgorithm(alg) {\n return ALGORITHMS[alg]?.hash ?? 'SHA-256';\n}\n\nconst isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);\n\n/**\n * Splits a compact JWS without verifying anything: for reading `kid` before a key is chosen, or a\n * claim for display. Nothing in this library authorises on the result of a decode alone.\n */\nexport function decodeJwt(token) {\n if (typeof token !== 'string') throw new ArkTokenError('the token is not a string.');\n const parts = token.split('.');\n if (parts.length !== 3) throw new ArkTokenError(`the token is not a compact JWS: expected 3 segments, found ${parts.length}.`);\n\n let header;\n let payload;\n try {\n header = JSON.parse(base64UrlDecodeToString(parts[0]));\n payload = JSON.parse(base64UrlDecodeToString(parts[1]));\n } catch (cause) {\n throw new ArkTokenError('the token header or payload is not valid JSON.', { cause });\n }\n if (!isObject(header) || !isObject(payload)) throw new ArkTokenError('the token header and payload must both be JSON objects.');\n\n return { header, payload, signature: base64UrlDecode(parts[2]), signingInput: `${parts[0]}.${parts[1]}` };\n}\n\n/**\n * Imports one published JWK for verification. Only the key material is passed on, so a provider's\n * extra members (`x5c`, `key_ops`, an `alg` spelled differently) cannot make the import itself fail;\n * the `alg`/`use`/`kty` checks that matter are made explicitly in verifySignature.\n */\nexport async function importVerifyKey(jwk, alg) {\n const spec = ALGORITHMS[alg];\n if (!spec) throw new ArkTokenError(`unsupported signing algorithm '${alg}'.`);\n const material = spec.kty === 'RSA' ? { kty: 'RSA', n: jwk.n, e: jwk.e } : { kty: 'EC', crv: jwk.crv, x: jwk.x, y: jwk.y };\n try {\n return await subtle().importKey('jwk', { ...material, ext: true }, spec.importParams, false, ['verify']);\n } catch (cause) {\n throw new ArkTokenError(`the published key for kid '${jwk.kid}' could not be imported: ${cause?.message ?? cause}`, { cause });\n }\n}\n\n/**\n * Verifies the signature of a decoded token against one JWK.\n *\n * @param {ReturnType<typeof decodeJwt>} decoded\n * @param {object} jwk\n * @param {{ algorithms?: string[], key?: CryptoKey }} [options] `key` is a pre-imported CryptoKey for `jwk`\n */\nexport async function verifySignature(decoded, jwk, { algorithms, key } = {}) {\n const alg = decoded.header.alg;\n if (!alg || alg === 'none') throw new ArkTokenError(`the token declares alg '${alg ?? 'missing'}'; unsigned tokens are never accepted.`);\n\n const allowed = algorithms ?? SUPPORTED_ALGORITHMS;\n if (!allowed.includes(alg)) throw new ArkTokenError(`the token is signed with ${alg}, which this client does not accept (allowed: ${allowed.join(', ')}).`);\n\n const spec = ALGORITHMS[alg];\n if (!spec) throw new ArkTokenError(`unsupported signing algorithm '${alg}'.`);\n if (jwk.kty !== spec.kty) throw new ArkTokenError(`the signing key is a ${jwk.kty} key but the token declares ${alg}.`);\n if (jwk.alg && jwk.alg !== alg) throw new ArkTokenError(`the key published for kid '${jwk.kid}' is registered for ${jwk.alg}, not ${alg}.`);\n if (jwk.use && jwk.use !== 'sig') throw new ArkTokenError(`the key published for kid '${jwk.kid}' is for '${jwk.use}', not signing.`);\n 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}.`);\n\n const cryptoKey = key ?? (await importVerifyKey(jwk, alg));\n const ok = await subtle().verify(spec.verifyParams, cryptoKey, decoded.signature, new TextEncoder().encode(decoded.signingInput));\n if (!ok) throw new ArkTokenError('the token signature does not verify against the published key.');\n return true;\n}\n\n/**\n * Validates the registered claims. Skipping any single one of these is how a token meant for\n * another app, another provider or another moment ends up being accepted.\n */\nexport function validateClaims(payload, options = {}) {\n const {\n issuer,\n audience,\n subject,\n nonce,\n maxAgeSeconds,\n clockToleranceSeconds = 60,\n requireExp = true,\n requireIat = false,\n now = Math.floor(Date.now() / 1000)\n } = options;\n\n const fail = (message, claim) => {\n throw new ArkTokenError(message, { claim });\n };\n\n if (issuer) {\n if (!payload.iss) fail('the token has no `iss` claim.', 'iss');\n if (payload.iss !== issuer) fail(`the token was issued by '${payload.iss}', not by '${issuer}'.`, 'iss');\n }\n\n if (audience) {\n const auds = Array.isArray(payload.aud) ? payload.aud : payload.aud ? [payload.aud] : [];\n if (auds.length === 0) fail('the token has no `aud` claim.', 'aud');\n if (!auds.includes(audience)) fail(`the token is addressed to ${auds.map((a) => `'${a}'`).join(', ')}, not to '${audience}'.`, 'aud');\n // OIDC Core \u00A73.1.3.7: with several audiences, `azp` must name the party the token is for.\n if (auds.length > 1 && payload.azp && payload.azp !== audience) fail(`the token names '${payload.azp}' as its authorized party, not '${audience}'.`, 'azp');\n }\n\n if (subject && payload.sub !== subject) fail(`the token belongs to subject '${payload.sub}', not '${subject}'.`, 'sub');\n\n if (payload.exp === undefined) {\n if (requireExp) fail('the token has no `exp` claim.', 'exp');\n } else if (typeof payload.exp !== 'number' || now >= payload.exp + clockToleranceSeconds) {\n fail(`the token expired at ${new Date((Number(payload.exp) || 0) * 1000).toISOString()}.`, 'exp');\n }\n\n // A time claim that is not a number compares false against everything and would pass the checks\n // below unnoticed. RFC 7519 \u00A72 makes them NumericDate; anything else is a malformed token.\n for (const claim of ['nbf', 'iat']) {\n if (payload[claim] !== undefined && (typeof payload[claim] !== 'number' || !Number.isFinite(payload[claim]))) {\n fail(`the token's \\`${claim}\\` is not a NumericDate.`, claim);\n }\n }\n if (payload.nbf !== undefined && now + clockToleranceSeconds < payload.nbf) {\n fail(`the token is not valid before ${new Date(payload.nbf * 1000).toISOString()}.`, 'nbf');\n }\n if (payload.iat === undefined) {\n if (requireIat) fail('the token has no `iat` claim.', 'iat');\n } else if (now + clockToleranceSeconds < payload.iat) {\n fail(`the token was issued in the future, at ${new Date(payload.iat * 1000).toISOString()}.`, 'iat');\n }\n\n if (nonce !== undefined && nonce !== null) {\n // A missing nonce is as bad as a wrong one: the ID token was not bound to this sign-in.\n if (!payload.nonce) fail('the ID token has no `nonce`, so it cannot be tied to this sign-in.', 'nonce');\n if (payload.nonce !== nonce) fail('the ID token `nonce` does not match the one sent with the authorization request.', 'nonce');\n }\n\n if (maxAgeSeconds !== undefined && maxAgeSeconds !== null) {\n if (typeof payload.auth_time !== 'number') fail('`max_age` was requested but the ID token carries no `auth_time`.', 'auth_time');\n if (now - payload.auth_time > maxAgeSeconds + clockToleranceSeconds) {\n fail(`the user authenticated ${now - payload.auth_time}s ago, beyond the requested max_age of ${maxAgeSeconds}s.`, 'auth_time');\n }\n }\n return payload;\n}\n\n/**\n * Checks `at_hash` / `c_hash` (OIDC Core \u00A73.1.3.6): what stops an access token or a code of an\n * attacker's being presented beside a genuine ID token. Ark always issues both, so a missing one is\n * an error unless `require` is false.\n */\nexport async function validateTokenHashes(payload, { alg = 'RS256', accessToken, code, require: required = true } = {}) {\n const hash = hashForAlgorithm(alg);\n for (const [claim, value] of [\n ['at_hash', accessToken],\n ['c_hash', code]\n ]) {\n if (!value) continue;\n const present = payload[claim];\n if (!present) {\n if (required) {\n throw new ArkTokenError(\n `the ID token has no \\`${claim}\\`, so the ${claim === 'at_hash' ? 'access token' : 'authorization code'} it arrived with cannot be tied to it.`,\n { claim }\n );\n }\n continue;\n }\n if (present !== (await leftHalfHash(value, hash))) {\n throw new ArkTokenError(`the ID token \\`${claim}\\` does not cover the value it arrived with; it may have been substituted.`, { claim });\n }\n }\n return payload;\n}\n\n/**\n * The whole check for one token: signature against the provider's published keys, then claims,\n * then the token hashes.\n *\n * @param {string} token\n * @param {{ getSigningKey(kid: string|undefined, alg: string): Promise<{ jwk: object, key: CryptoKey }> }} jwks\n */\nexport async function verifyJwt(token, jwks, options = {}) {\n const decoded = decodeJwt(token);\n const { jwk, key } = await jwks.getSigningKey(decoded.header.kid, decoded.header.alg);\n await verifySignature(decoded, jwk, { algorithms: options.algorithms, key });\n validateClaims(decoded.payload, options);\n if (options.accessToken || options.code) {\n await validateTokenHashes(decoded.payload, {\n alg: decoded.header.alg,\n accessToken: options.accessToken,\n code: options.code,\n require: options.requireTokenHashes !== false\n });\n }\n return decoded.payload;\n}\n", "import { getJson } from './http.js';\nimport { importVerifyKey } from './jwt.js';\nimport { ArkTokenError } from './errors.js';\n\nconst KTY_FOR_ALG = { RS: 'RSA', PS: 'RSA', ES: 'EC' };\nconst MAX_REMEMBERED_MISSES = 64;\n\n/**\n * The provider's signing keys, cached and refreshed on rotation.\n *\n * Ark rotates in two phases: the new key starts signing and the old one stays published until the\n * last token it signed has expired. A client that caches the JWKS keeps validating across the change,\n * as long as it refetches when it meets a `kid` it has never seen. That refetch is the point of this\n * class. The v1 Ark client could not do it at all: its key was pasted into configuration, so every\n * rotation broke every deployment.\n *\n * Refetches are rate-limited and each unknown `kid` earns only one, so a page fed tokens with\n * invented key ids cannot turn into a request flood against the identity server.\n */\nexport class JwksCache {\n #uri;\n #ttlMs;\n #cooldownMs;\n #http;\n #keys = null;\n #fetchedAt = 0;\n #forcedAt = 0;\n #inFlight = null;\n #missing = new Set();\n #imported = new Map();\n\n constructor(jwksUri, { ttlMs = 5 * 60_000, minRefreshIntervalMs = 10_000, ...http } = {}) {\n this.#uri = jwksUri;\n this.#ttlMs = ttlMs;\n this.#cooldownMs = minRefreshIntervalMs;\n this.#http = http;\n }\n\n get uri() {\n return this.#uri;\n }\n\n /** Every published key, fetching or refreshing as needed. */\n async keys({ force = false } = {}) {\n const stale = Date.now() - this.#fetchedAt > this.#ttlMs;\n if (this.#keys && !force && !stale) return this.#keys;\n return this.#load(force);\n }\n\n /**\n * The key that signed a token, as `{ jwk, key }` where `key` is the imported CryptoKey.\n *\n * A token with no `kid` resolves only when exactly one usable key is published: guessing among\n * several would mean trying each until one verifies.\n */\n async getSigningKey(kid, alg) {\n let candidates = this.#select(await this.keys(), kid, alg);\n\n if (candidates.length === 0) {\n const marker = kid ?? '\\u0000none';\n // The cooldown runs from the last *revalidated* fetch. A normal load may be answered by the\n // browser's HTTP cache (Ark sends max-age=300), so just after a rotation it can hand back the\n // old document: the first miss after that must still get one revalidating fetch.\n if (!this.#missing.has(marker) && Date.now() - this.#forcedAt >= this.#cooldownMs) {\n candidates = this.#select(await this.keys({ force: true }), kid, alg);\n }\n if (candidates.length === 0) {\n if (this.#missing.size >= MAX_REMEMBERED_MISSES) this.#missing.clear();\n this.#missing.add(marker);\n }\n }\n\n if (candidates.length === 0) {\n throw new ArkTokenError(\n kid\n ? `no key with kid '${kid}' is published at ${this.#uri}; the token may have been signed by a different provider.`\n : `the token carries no 'kid' and ${this.#uri} publishes more than one key, so the signing key is ambiguous.`\n );\n }\n\n const jwk = candidates[0];\n const cacheKey = `${jwk.kid ?? ''}|${alg}|${jwk.n ?? jwk.x ?? ''}`;\n let key = this.#imported.get(cacheKey);\n if (!key) {\n key = await importVerifyKey(jwk, alg);\n this.#imported.set(cacheKey, key);\n }\n return { jwk, key };\n }\n\n clear() {\n this.#keys = null;\n this.#fetchedAt = 0;\n this.#forcedAt = 0;\n this.#missing.clear();\n this.#imported.clear();\n }\n\n #select(keys, kid, alg) {\n const wantedKty = KTY_FOR_ALG[String(alg ?? '').slice(0, 2)];\n const usable = keys.filter((k) => (!k.use || k.use === 'sig') && (!wantedKty || k.kty === wantedKty) && (!k.alg || !alg || k.alg === alg));\n if (kid) return usable.filter((k) => k.kid === kid);\n return usable.length === 1 ? usable : [];\n }\n\n async #load(force) {\n if (force) this.#forcedAt = Date.now();\n // Concurrent misses share one request: a burst just after a rotation costs one JWKS fetch.\n this.#inFlight ??= (async () => {\n try {\n const document = await getJson(this.#uri, { ...this.#http, cache: force ? 'no-cache' : 'default' });\n const keys = Array.isArray(document.keys) ? document.keys : [];\n if (keys.length === 0) throw new ArkTokenError(`${this.#uri} published no keys.`);\n this.#keys = keys;\n this.#fetchedAt = Date.now();\n this.#missing.clear();\n return keys;\n } finally {\n this.#inFlight = null;\n }\n })();\n return this.#inFlight;\n }\n}\n", "import { decodeJwt } from './jwt.js';\n\n/**\n * One token endpoint response, with the parts an application asks for.\n *\n * `expires_in` becomes an absolute `expiresAt` the moment the response arrives. A relative lifetime\n * means something only at the instant it is received, and a token set read back from sessionStorage\n * after a reload cannot answer \"are you still valid\" from a number relative to a forgotten moment.\n *\n * The same class, fields and JSON shape as `TokenSet` in `ark-oauth-client` for Node.\n */\nexport class TokenSet {\n /**\n * @param {object} response the raw JSON from /oauth2/token\n * @param {{ issuedAt?: number, claims?: object|null }} [options]\n */\n constructor(response = {}, { issuedAt = Math.floor(Date.now() / 1000), claims = null } = {}) {\n this.accessToken = response.access_token ?? null;\n this.tokenType = response.token_type ?? 'Bearer';\n this.refreshToken = response.refresh_token ?? null;\n this.idToken = response.id_token ?? null;\n this.scope = response.scope ?? null;\n this.issuedAt = issuedAt;\n this.expiresAt = typeof response.expires_in === 'number' ? issuedAt + response.expires_in : (response.expires_at ?? null);\n /** Validated ID token claims: who the user is. */\n this.claims = claims;\n }\n\n /** Seconds until expiry; negative once passed; null when the server gave no lifetime. */\n expiresIn(now = Math.floor(Date.now() / 1000)) {\n return this.expiresAt === null ? null : this.expiresAt - now;\n }\n\n /** Whether the access token should be treated as spent, `leewaySeconds` early. */\n expired(leewaySeconds = 0, now = Math.floor(Date.now() / 1000)) {\n if (this.expiresAt === null) return false;\n return now >= this.expiresAt - leewaySeconds;\n }\n\n scopes() {\n return this.scope ? this.scope.split(' ').filter(Boolean) : [];\n }\n\n hasScope(...wanted) {\n const granted = new Set(this.scopes());\n return wanted.flat().every((s) => granted.has(s));\n }\n\n /**\n * The tenant's authorization claims from the access token: Ark's `ark_claims`.\n *\n * These, not scopes, are what an app authorises against. Scopes say what the client asked for;\n * `ark_claims` say what this user may do in this client.\n */\n arkClaims() {\n const claims = this.accessTokenClaims()?.ark_claims;\n if (Array.isArray(claims)) return claims.map(String);\n return typeof claims === 'string' ? [claims] : [];\n }\n\n /** The access token's own claims, unverified: for display and `sub`, never for authorising. */\n accessTokenClaims() {\n if (!this.accessToken) return null;\n try {\n return decodeJwt(this.accessToken).payload;\n } catch {\n return null; // an opaque token from another provider simply has no readable claims\n }\n }\n\n get subject() {\n return this.claims?.sub ?? this.accessTokenClaims()?.sub ?? null;\n }\n\n authorizationHeader() {\n return `${this.tokenType} ${this.accessToken}`;\n }\n\n toJSON() {\n return {\n access_token: this.accessToken,\n token_type: this.tokenType,\n refresh_token: this.refreshToken,\n id_token: this.idToken,\n scope: this.scope,\n expires_at: this.expiresAt,\n issued_at: this.issuedAt,\n claims: this.claims\n };\n }\n\n static fromJSON(data) {\n if (!data) return null;\n if (data instanceof TokenSet) return data;\n return new TokenSet(data, { issuedAt: data.issued_at ?? Math.floor(Date.now() / 1000), claims: data.claims ?? null });\n }\n}\n", "import { base64UrlEncode, randomToken, sha256 } from './crypto.js';\n\n/**\n * PKCE (RFC 7636), `state` and `nonce`.\n *\n * A browser app is a public client, and the Ark server requires PKCE from every public client and\n * accepts `S256` only. `plain` is not implemented: a plain challenge is the verifier, so it\n * protects nothing once the authorization request has been seen.\n */\n\n/** 32 random bytes as base64url: 43 characters, the minimum RFC 7636 \u00A74.1 allows. */\nexport function createCodeVerifier() {\n return randomToken(32);\n}\n\n/** BASE64URL(SHA256(verifier)), the `code_challenge` for `code_challenge_method=S256`. */\nexport async function codeChallengeFor(verifier) {\n return base64UrlEncode(await sha256(verifier));\n}\n\n/** CSRF protection for the authorization response, and the key the sign-in transaction is stored under. */\nexport function createState() {\n return randomToken(24);\n}\n\n/** Binds the ID token to this authorization request, so a captured one cannot be replayed. */\nexport function createNonce() {\n return randomToken(24);\n}\n\n/** Verifier, challenge and method in one object, for callers driving the flow by hand. */\nexport async function createPkcePair() {\n const codeVerifier = createCodeVerifier();\n return { codeVerifier, codeChallenge: await codeChallengeFor(codeVerifier), codeChallengeMethod: 'S256' };\n}\n", "/**\n * The authentication state as an observable value, the one thing every framework adapter binds to.\n *\n * The contract is the smallest one React, Vue, Angular, Svelte, Solid and plain DOM code all\n * understand:\n *\n * - `getSnapshot()` returns an immutable object, and the *same* object until something changes.\n * React's `useSyncExternalStore` depends on that identity: a fresh object on every call would\n * render forever.\n * - `subscribe(listener)` registers a callback for every change and returns the unsubscribe.\n */\n\nexport const INITIAL_SNAPSHOT = Object.freeze({\n status: 'loading',\n isLoading: true,\n isAuthenticated: false,\n user: null,\n arkClaims: Object.freeze([]),\n scopes: Object.freeze([]),\n expiresAt: null,\n error: null,\n denial: null\n});\n\nexport class ArkStore {\n #state = INITIAL_SNAPSHOT;\n #listeners = new Set();\n\n get() {\n return this.#state;\n }\n\n /** Replaces the state with `patch` merged in, and notifies, unless nothing changed. */\n set(patch) {\n const next = { ...this.#state, ...patch };\n next.isLoading = next.status === 'loading';\n next.isAuthenticated = next.status === 'authenticated';\n if (Object.keys(next).every((key) => Object.is(next[key], this.#state[key]))) return this.#state;\n this.#state = Object.freeze(next);\n for (const listener of [...this.#listeners]) {\n try {\n listener(this.#state);\n } catch (error) {\n // One broken subscriber must not stop the others hearing about a sign-out.\n queueMicrotask(() => {\n throw error;\n });\n }\n }\n return this.#state;\n }\n\n subscribe(listener) {\n this.#listeners.add(listener);\n return () => this.#listeners.delete(listener);\n }\n}\n", "import { ArkConfigError } from './errors.js';\n\n/**\n * Where the token set lives between page loads.\n *\n * - `session` (default): sessionStorage. Survives a reload, is private to the tab, and is gone\n * when the tab closes. Each tab signs in on its own (silently, through the provider's session).\n * - `local`: localStorage. Shared by every tab of the app and kept across browser restarts.\n * Refreshes are coordinated across tabs (see lock.js), because two tabs redeeming the same\n * rotating refresh token would get the whole token family revoked.\n * - `memory`: nothing written anywhere. The safest against XSS, but every reload is a round trip\n * to the provider (silent if its session is alive).\n * - any object with getItem/setItem/removeItem, for an encrypted or native store.\n *\n * Whatever is chosen, anything that can run script on the page can read a token the page can use.\n * Storage choice changes how long a stolen token is good for, not whether XSS can reach it. A\n * Content-Security-Policy is what stops XSS, and short access-token lifetimes are what limit it.\n */\n\nexport class MemoryStorage {\n #map = new Map();\n\n getItem(key) {\n return this.#map.has(key) ? this.#map.get(key) : null;\n }\n\n setItem(key, value) {\n this.#map.set(key, String(value));\n }\n\n removeItem(key) {\n this.#map.delete(key);\n }\n\n key(index) {\n return [...this.#map.keys()][index] ?? null;\n }\n\n get length() {\n return this.#map.size;\n }\n\n clear() {\n this.#map.clear();\n }\n}\n\nfunction isStorageLike(value) {\n return value && typeof value.getItem === 'function' && typeof value.setItem === 'function' && typeof value.removeItem === 'function';\n}\n\n/** Web Storage can exist and still throw: Safari private mode, a sandboxed iframe, cookies blocked. */\nfunction probe(storage) {\n try {\n const key = '__ark_probe__';\n storage.setItem(key, '1');\n storage.removeItem(key);\n return storage;\n } catch {\n return null;\n }\n}\n\n/**\n * @param {'session'|'local'|'memory'|Storage} option\n * @param {Window|null} win\n * @returns {{ storage: Storage, kind: string }}\n */\nexport function resolveStorage(option, win) {\n if (isStorageLike(option)) return { storage: option, kind: 'custom' };\n if (option === 'memory' || !win) return { storage: new MemoryStorage(), kind: 'memory' };\n if (option === 'session' || option === 'local') {\n let candidate = null;\n try {\n candidate = option === 'session' ? win.sessionStorage : win.localStorage;\n } catch {\n candidate = null;\n }\n const usable = candidate ? probe(candidate) : null;\n // Falling back to memory keeps the app working (each reload signs in again) rather than\n // failing outright where storage is blocked.\n return usable ? { storage: usable, kind: option } : { storage: new MemoryStorage(), kind: 'memory' };\n }\n throw new ArkConfigError(`ark_oauth_client: 'storage' must be 'session', 'local', 'memory' or a Storage-like object, not '${option}'.`);\n}\n\n/** JSON read that treats a corrupt or foreign value as absent rather than crashing the page. */\nexport function readJson(storage, key) {\n try {\n const raw = storage.getItem(key);\n return raw ? JSON.parse(raw) : null;\n } catch {\n return null;\n }\n}\n\nexport function writeJson(storage, key, value) {\n try {\n storage.setItem(key, JSON.stringify(value));\n return true;\n } catch {\n return false; // quota exceeded or storage revoked: the session lives on in memory\n }\n}\n\nexport function remove(storage, key) {\n try {\n storage.removeItem(key);\n } catch {\n /* nothing to do */\n }\n}\n\n/** Keys in a storage that start with a prefix, for sweeping expired transactions. */\nexport function keysWithPrefix(storage, prefix) {\n const found = [];\n try {\n const count = storage.length ?? 0;\n for (let i = 0; i < count; i++) {\n const key = storage.key(i);\n if (key && key.startsWith(prefix)) found.push(key);\n }\n } catch {\n /* a custom store without key()/length simply is not swept */\n }\n return found;\n}\n", "/**\n * Cross-tab mutual exclusion for refreshing tokens.\n *\n * Ark rotates refresh tokens and treats a retired one coming back as theft: the whole family is\n * revoked and the user is signed out everywhere. Two tabs sharing localStorage that both notice the\n * access token expiring would each present the same refresh token, and the second presentation\n * looks exactly like that theft. The Web Locks API serialises them across every tab of the origin;\n * the tab that waited then re-reads storage and finds the tokens the first one already obtained.\n *\n * Where Web Locks is missing (it is in every current browser), the refresh still runs, and the\n * in-tab de-duplication in the client is the only protection.\n */\nexport async function withLock(name, fn, win) {\n const locks = win?.navigator?.locks ?? globalThis.navigator?.locks;\n if (locks && typeof locks.request === 'function') {\n return locks.request(name, { mode: 'exclusive' }, () => fn());\n }\n return fn();\n}\n", "import { ArkPopupError } from './errors.js';\n\n/**\n * Popup sign-in: the authorization request runs in a small window and its answer is handed back to\n * the page that opened it, which never navigates away.\n *\n * Opening the window is synchronous and happens before anything is awaited. Browsers let a page\n * open a popup only in direct response to a click, and the sign-in URL needs a SHA-256 (async) and\n * possibly a discovery fetch before it exists, so the window is opened blank first and pointed at\n * the provider once the URL is ready.\n *\n * The callback reaches the opener two ways, and whichever arrives first wins: `postMessage` to\n * `window.opener` (restricted to this origin), and a BroadcastChannel, for the case where a\n * Cross-Origin-Opener-Policy along the way has severed `opener`. Either way the opener accepts only\n * a response whose `state` is the one it is waiting for.\n */\n\nexport const POPUP_MESSAGE_TYPE = 'ark-oidc:callback';\n\nexport function popupChannelName(authority, clientId) {\n return `ark-oidc:${authority}|${clientId}:popup`;\n}\n\n/** Opens the (blank) popup window. Throws ArkPopupError('blocked') when the browser refuses. */\nexport function openPopupWindow(win, { width = 520, height = 680 } = {}) {\n const screenLeft = win.screenX ?? win.screenLeft ?? 0;\n const screenTop = win.screenY ?? win.screenTop ?? 0;\n const outerWidth = win.outerWidth ?? width;\n const outerHeight = win.outerHeight ?? height;\n const left = Math.max(0, Math.round(screenLeft + (outerWidth - width) / 2));\n const top = Math.max(0, Math.round(screenTop + (outerHeight - height) / 2));\n const features = `popup=yes,width=${width},height=${height},left=${left},top=${top},resizable=yes,scrollbars=yes`;\n let popup = null;\n try {\n popup = win.open('', 'ark-oidc-popup', features);\n } catch {\n popup = null;\n }\n if (!popup) {\n throw new ArkPopupError(\n 'blocked',\n 'the browser blocked the sign-in popup. Call signinPopup() directly from a click handler, before any await, or use signinRedirect().'\n );\n }\n return popup;\n}\n\n/**\n * Waits for the popup to report back with the URL it landed on.\n *\n * @returns {{ promise: Promise<string>, cancel: () => void }}\n */\nexport function waitForPopupCallback(win, popup, { state, channelName, timeoutMs }) {\n let settle;\n const promise = new Promise((resolve, reject) => {\n let done = false;\n let channel = null;\n let closedTimer = null;\n let closedGrace = null;\n let timeoutTimer = null;\n\n const cleanup = () => {\n done = true;\n win.removeEventListener('message', onMessage);\n if (channel) {\n channel.onmessage = null;\n channel.close();\n }\n clearInterval(closedTimer);\n clearTimeout(closedGrace);\n clearTimeout(timeoutTimer);\n };\n\n const accept = (data) => {\n if (done || !data || data.type !== POPUP_MESSAGE_TYPE || data.state !== state || typeof data.url !== 'string') return;\n cleanup();\n resolve(data.url);\n };\n\n const onMessage = (event) => {\n if (event.origin !== win.location.origin) return;\n accept(event.data);\n };\n\n win.addEventListener('message', onMessage);\n const Channel = win.BroadcastChannel ?? globalThis.BroadcastChannel;\n if (typeof Channel === 'function') {\n channel = new Channel(channelName);\n channel.onmessage = (event) => accept(event.data);\n }\n\n // The popup posts its result and then closes itself, so a closed window may be one whose\n // message is still in flight. A short grace period tells that apart from the user closing it.\n closedTimer = setInterval(() => {\n let closed = false;\n try {\n closed = popup.closed;\n } catch {\n closed = false;\n }\n if (closed && !done && !closedGrace) {\n closedGrace = setTimeout(() => {\n if (done) return;\n cleanup();\n reject(new ArkPopupError('closed', 'the sign-in popup was closed before the sign-in finished.'));\n }, 400);\n }\n }, 250);\n\n timeoutTimer = setTimeout(() => {\n if (done) return;\n cleanup();\n try {\n popup.close();\n } catch {\n /* already gone */\n }\n reject(new ArkPopupError('timeout', `the sign-in popup did not finish within ${Math.round(timeoutMs / 1000)}s.`));\n }, timeoutMs);\n\n settle = (error) => {\n if (done) return;\n cleanup();\n reject(error);\n };\n });\n return { promise, cancel: (error) => settle(error ?? new ArkPopupError('closed', 'the sign-in popup was cancelled.')) };\n}\n\n/**\n * Runs in the popup when it lands back on the redirect URI: hands the URL to the opener, then\n * closes. Returns false when this window is not a popup we can report to.\n */\nexport function relayToOpener(win, url, state, channelName) {\n let delivered = false;\n const message = { type: POPUP_MESSAGE_TYPE, url, state };\n\n try {\n const opener = win.opener;\n if (opener && opener !== win) {\n // targetOrigin is our own origin: the code and state are never posted to another site, even\n // if something navigated the opener away in the meantime.\n opener.postMessage(message, win.location.origin);\n delivered = true;\n }\n } catch {\n /* opener inaccessible */\n }\n\n const Channel = win.BroadcastChannel ?? globalThis.BroadcastChannel;\n if (typeof Channel === 'function') {\n try {\n const channel = new Channel(channelName);\n channel.postMessage(message);\n channel.close();\n delivered = delivered || Boolean(win.opener) || win.name === 'ark-oidc-popup';\n } catch {\n /* no channel */\n }\n }\n return delivered;\n}\n", "import { DEFAULT_POST_LOGOUT_PATH, normalizeConfig } from './config.js';\nimport { MetadataResolver } from './discovery.js';\nimport { JwksCache } from './jwks.js';\nimport { TokenSet } from './tokens.js';\nimport { getJson, postForm, postFormNoCors } from './http.js';\nimport { createNonce, createPkcePair, createState } from './pkce.js';\nimport { base64UrlEncode, constantTimeEqual, sha256 } from './crypto.js';\nimport { verifyJwt } from './jwt.js';\nimport { ArkStore, INITIAL_SNAPSHOT } from './store.js';\nimport { keysWithPrefix, readJson, remove, resolveStorage, writeJson } from './storage.js';\nimport { withLock } from './lock.js';\nimport { openPopupWindow, popupChannelName, relayToOpener, waitForPopupCallback } from './popup.js';\nimport { ArkAccessDeniedReasons, describeDenial, evaluateAccess, localOrDefault } from './access.js';\nimport {\n ArkCallbackError,\n ArkConfigError,\n ArkError,\n ArkLoginRequiredError,\n ArkNetworkError,\n ArkOAuthError,\n ArkTokenError\n} from './errors.js';\n\n/** Parameters of an authorization response, stripped from the URL once read. */\nconst RESPONSE_PARAMS = ['code', 'state', 'iss', 'error', 'error_description', 'error_uri', 'session_state'];\nconst DENIAL_TTL_SECONDS = 300;\nconst RETRY_AFTER_NETWORK_FAILURE_MS = 15_000;\nconst SPENT_TOKENS_REMEMBERED = 50;\nconst MAX_TIMER_MS = 2_147_483_647;\nconst EVENTS = ['signedIn', 'signedOut', 'tokensRefreshed', 'refreshFailed', 'sessionExpired', 'accessDenied', 'error'];\n\nconst now = () => Math.floor(Date.now() / 1000);\nlet instanceCounter = 0;\n\n/**\n * Lets a long-lived timer or channel not hold a Node process open (unit tests of an app, SSR).\n * Browsers return a number from setTimeout and have no unref, so this is a no-op there.\n */\nfunction unref(handle) {\n if (handle && typeof handle.unref === 'function') handle.unref();\n return handle;\n}\n\n/**\n * The Ark OpenID Connect client for browser apps: React, Next.js, Vue, Angular, Svelte, or none.\n *\n * One instance per app. It runs the authorization code flow with PKCE as a public client, validates\n * the ID token (signature, issuer, audience, nonce, at_hash, c_hash) in the browser, keeps the\n * session renewed with rotating refresh tokens, and exposes the result as a small observable state\n * that any framework can bind to. The framework adapters (`ark-oauth-client-js/react`, `/vue`,\n * `/angular`, `/next`) are thin wrappers over exactly this object.\n *\n * const ark = new ArkBrowserClient({ authority: 'https://idp.example.com/my_idp', clientId: 'my-spa' });\n * await ark.init(); // handles /signin-oidc, restores the session\n * if (!ark.getSnapshot().isAuthenticated) await ark.signinRedirect();\n * const res = await ark.fetch('/api/orders'); // bearer attached, refreshed when needed\n *\n * Nothing touches `window` until `init()` or a sign-in method is called, so creating the client\n * during server-side rendering is safe; on the server it simply stays in the `loading` state.\n */\nexport class ArkBrowserClient {\n #config;\n #win;\n #metadata;\n #jwks = null;\n #store = new ArkStore();\n #events = new Map(EVENTS.map((name) => [name, new Set()]));\n #id = `ark-${++instanceCounter}-${Math.random().toString(36).slice(2, 8)}`;\n\n #ready = false;\n #storage = null;\n #storageKind = 'memory';\n #txStorage = null;\n #spentStorage = null;\n #prefix;\n\n #tokens = null;\n #derived = { claims: null, arkClaims: Object.freeze([]), scopes: Object.freeze([]) };\n #denial = null;\n\n #initPromise = null;\n #refreshPromise = null;\n #timer = null;\n #channel = null;\n #detach = [];\n #destroyed = false;\n\n constructor(options = {}) {\n this.#config = normalizeConfig(options);\n this.#win = options.window !== undefined ? options.window : typeof window !== 'undefined' ? window : null;\n this.#prefix = `ark.oidc:${this.#config.clientId}@${this.#config.authority}:`;\n this.#metadata = new MetadataResolver(this.#config.authority, {\n ttlMs: this.#config.metadataTtlMs,\n timeoutMs: this.#config.timeoutMs,\n fetch: this.#config.fetch\n });\n\n // Stable references: React's useSyncExternalStore and Svelte's `$store` call these detached.\n this.subscribe = this.subscribe.bind(this);\n this.getSnapshot = this.getSnapshot.bind(this);\n this.getServerSnapshot = this.getServerSnapshot.bind(this);\n this.fetch = this.fetch.bind(this);\n this.getAccessToken = this.getAccessToken.bind(this);\n }\n\n get config() {\n return this.#config;\n }\n\n get authority() {\n return this.#config.authority;\n }\n\n get clientId() {\n return this.#config.clientId;\n }\n\n /**\n * False during server-side rendering (no window): the client stays `loading` and every action\n * that needs a browser waits for one. Route guards use it to cancel quietly on the server and\n * decide in the browser, after hydration.\n */\n get isBrowser() {\n return Boolean(this.#win);\n }\n\n // =================================================================\n // State: the framework-agnostic surface\n // =================================================================\n\n /** The current state. The same frozen object until something changes. */\n getSnapshot() {\n return this.#store.get();\n }\n\n /** The state during server-side rendering and hydration: always `loading`. */\n getServerSnapshot() {\n return INITIAL_SNAPSHOT;\n }\n\n /** Calls `listener(snapshot)` on every change. Returns the unsubscribe function. */\n subscribe(listener) {\n return this.#store.subscribe(listener);\n }\n\n /**\n * The state as a Svelte-compatible store (`$ark.state` in a component): `subscribe` calls the\n * listener straight away with the current value, then on every change.\n */\n get state() {\n return {\n subscribe: (run) => {\n run(this.#store.get());\n return this.#store.subscribe(run);\n }\n };\n }\n\n /** The signed-in user's ID token claims, or null. */\n getUser() {\n return this.#store.get().user;\n }\n\n /**\n * Listens for one event: `signedIn`, `signedOut`, `tokensRefreshed`, `refreshFailed`,\n * `sessionExpired`, `accessDenied` or `error`. Returns the unsubscribe function.\n */\n on(event, handler) {\n const set = this.#events.get(event);\n if (!set) throw new ArkConfigError(`ark_oauth_client: unknown event '${event}'. Known events: ${EVENTS.join(', ')}.`);\n set.add(handler);\n return () => set.delete(handler);\n }\n\n /** True when the user holds every one of these Ark authorization claims. */\n hasArkClaims(...claims) {\n const held = this.#store.get().arkClaims;\n return claims.flat().every((c) => held.includes(c));\n }\n\n /** True when the user holds at least one of these Ark authorization claims. */\n hasAnyArkClaim(...claims) {\n const held = this.#store.get().arkClaims;\n return claims.flat().some((c) => held.includes(c));\n }\n\n /** True when every one of these scopes was granted. */\n hasScopes(...scopes) {\n const granted = this.#store.get().scopes;\n return scopes.flat().every((s) => granted.includes(s));\n }\n\n // =================================================================\n // Start-up\n // =================================================================\n\n /**\n * Starts the client: completes a sign-in when the page is the redirect URI, completes a sign-out\n * when it is the post-logout URI, otherwise restores the stored session (refreshing it if the\n * access token expired while the page was closed). Resolves with the snapshot; never rejects: a\n * failure lands in `snapshot.error` and the `error` event.\n *\n * Idempotent: every call after the first returns the first call's promise, so React StrictMode's\n * double effects and several components calling it at once all share one start-up.\n *\n * After a completed sign-in the browser is sent to the page the user started from, through\n * `onRedirectCallback(returnTo)` when given (pass your router's navigate here), otherwise through\n * `history.replaceState` plus a `popstate` event, which React Router and the Angular router follow.\n *\n * @param {{ handleCallback?: boolean, onRedirectCallback?: (returnTo: string, result: object) => unknown }} [options]\n */\n init(options = {}) {\n if (!this.#win) return Promise.resolve(this.#store.get());\n this.#initPromise ??= this.#runInit(options);\n return this.#initPromise;\n }\n\n async #runInit({ handleCallback = true, onRedirectCallback } = {}) {\n this.#ensureReady();\n this.#attachListeners();\n this.#sweepTransactions();\n\n const href = this.#win.location.href;\n // Not awaited: a router navigation runs the app's guards, and a guard that awaits init() would\n // otherwise wait on the very promise that is waiting on it.\n const navigate = (to, result) => {\n const handler = onRedirectCallback ?? this.#config.onRedirectCallback;\n if (!handler) return this.#navigate(to);\n try {\n Promise.resolve(handler(to, result)).catch((error) => this.#emit('error', error));\n } catch (error) {\n this.#emit('error', error);\n }\n };\n\n try {\n const kind = handleCallback ? this.#classify(href) : null;\n\n if (kind === 'signin') {\n let result;\n try {\n result = await this.handleRedirectCallback(href);\n } catch (error) {\n // The page stays on the (now cleaned) callback URL with the error in the state: sending\n // the user back to a guarded page would start the same failing sign-in again, in a loop.\n this.#restore();\n await this.#renewIfNeeded();\n return this.#fail(error);\n }\n if (result.relayed) return this.#store.get(); // a popup, about to close\n navigate(result.returnTo, result);\n return this.#store.get();\n }\n\n if (kind === 'signout') {\n const next = this.#takeLogoutTransaction(href);\n if (next?.then === 'signin') {\n // The second half of an account switch. The state stays `loading` until the browser has\n // left: published as `unauthenticated`, a route guard would start a sign-in of its own,\n // without the prompt=login this one carries.\n await this.signinRedirect({ prompt: next.prompt ?? this.#config.accountSwitch.prompt, returnTo: next.returnTo, loginHint: next.loginHint });\n return this.#store.get();\n }\n this.#publish({ error: null });\n navigate(next?.returnTo ?? localOrDefault(this.#config.accountSwitch.homePath), { signedOut: true });\n return this.#store.get();\n }\n\n this.#restore();\n await this.#renewIfNeeded();\n this.#publish();\n this.#schedule();\n } catch (error) {\n return this.#fail(error);\n }\n return this.#store.get();\n }\n\n // =================================================================\n // Signing in\n // =================================================================\n\n /**\n * Builds the authorization request and the transaction that must survive until the user comes\n * back. For custom flows; `signinRedirect()` and `signinPopup()` use it.\n *\n * @returns {Promise<{ url: string, transaction: object }>}\n */\n async createAuthorizationUrl(options = {}) {\n const win = this.#requireWindow();\n const config = this.#config;\n const metadata = await this.metadata();\n\n if (metadata.require_pushed_authorization_requests === true) {\n throw new ArkConfigError(\n 'the tenant requires pushed authorization requests, which a browser app cannot make (/oauth2/par needs client ' +\n 'authentication and serves no CORS). Turn RequirePushedAuthorizationRequests off for this tenant, or the client\\'s ' +\n 'require_par flag, or sign in through a server-side client.'\n );\n }\n if (!metadata.authorization_endpoint) {\n throw new ArkOAuthError('server_error', \"the provider's metadata has no 'authorization_endpoint'.\", { endpoint: config.authority });\n }\n\n const redirectUri = this.#resolve(options.redirectUri ?? config.redirectUri);\n const scopes = options.scopes?.length ? [...options.scopes] : [...config.scopes];\n const { codeVerifier, codeChallenge, codeChallengeMethod } = await createPkcePair();\n const state = createState();\n const nonce = scopes.includes('openid') ? createNonce() : null;\n const prompt = options.prompt ?? config.prompt;\n const acrValues = options.acrValues ?? config.acrValues;\n const responseMode = options.responseMode ?? config.responseMode;\n\n // Extra parameters go first so they can add to the request but never replace what its security\n // rests on: an `extra` carrying its own state or code_challenge would detach the response from\n // the transaction returned here.\n const params = {\n ...config.extraAuthorizationParams,\n ...options.extra,\n response_type: 'code',\n client_id: config.clientId,\n redirect_uri: redirectUri,\n scope: scopes.join(' '),\n state,\n code_challenge: codeChallenge,\n code_challenge_method: codeChallengeMethod,\n response_mode: responseMode,\n ...(nonce ? { nonce } : {}),\n ...(prompt ? { prompt } : {}),\n ...(options.loginHint ? { login_hint: options.loginHint } : {}),\n ...(options.maxAge !== undefined && options.maxAge !== null ? { max_age: String(options.maxAge) } : {}),\n ...(acrValues ? { acr_values: acrValues } : {})\n };\n const query = new URLSearchParams(Object.entries(params).filter(([, v]) => v !== undefined && v !== null && v !== ''));\n\n const here = `${win.location.pathname}${win.location.search}${win.location.hash}`;\n const returnTo = localOrDefault(options.returnTo ?? (this.#classify(win.location.href) ? '/' : here), '/');\n\n return {\n url: `${metadata.authorization_endpoint}${metadata.authorization_endpoint.includes('?') ? '&' : '?'}${query}`,\n transaction: {\n state,\n nonce,\n codeVerifier,\n redirectUri,\n responseMode,\n scope: scopes.join(' '),\n maxAge: options.maxAge ?? null,\n returnTo,\n createdAt: now()\n }\n };\n }\n\n /**\n * Sends the browser to the provider's sign-in page. The promise resolves as the page unloads.\n *\n * @param {{ returnTo?: string, prompt?: string, loginHint?: string, scopes?: string[], maxAge?: number,\n * acrValues?: string, extra?: Record<string, string> }} [options]\n */\n async signinRedirect(options = {}) {\n this.#ensureReady();\n const { url, transaction } = await this.createAuthorizationUrl(options);\n this.#saveTransaction(transaction);\n await this.#redirect(url);\n }\n\n /**\n * Signs in through a popup window; the page never navigates. Call it straight from a click\n * handler, before any `await`, or the browser blocks the popup. The popup lands on the redirect\n * URI, whose page (this same app, calling `init()`) passes the result back here and closes.\n *\n * @returns {Promise<{ user: object|null, denied: boolean, returnTo: string }>}\n */\n async signinPopup(options = {}) {\n const win = this.#requireWindow();\n // Synchronously, before anything is awaited: see popup.js.\n const popup = options.popupWindow ?? openPopupWindow(win, this.#config.popup);\n let waiter = null;\n try {\n this.#ensureReady();\n const { url, transaction } = await this.createAuthorizationUrl(options);\n waiter = waitForPopupCallback(win, popup, {\n state: transaction.state,\n channelName: popupChannelName(this.#config.authority, this.#config.clientId),\n timeoutMs: this.#config.popup.timeoutMs\n });\n popup.location.href = url;\n const responseUrl = await waiter.promise;\n const params = this.#responseParams(new URL(responseUrl), transaction.responseMode);\n if (params.error) throw this.#authorizationError(params);\n return await this.#completeSignin(params, transaction);\n } catch (error) {\n waiter?.cancel(error);\n this.#publish({ error: error instanceof ArkError ? error : new ArkError(String(error?.message ?? error)) });\n this.#emit('error', error);\n throw error;\n } finally {\n try {\n if (!popup.closed) popup.close();\n } catch {\n /* already gone */\n }\n }\n }\n\n /** Whether a URL is this client's sign-in callback: the redirect URI carrying a code or an error. */\n isSigninCallback(url) {\n return this.#classify(String(url ?? this.#requireWindow().location.href)) === 'signin';\n }\n\n /**\n * Completes a sign-in from the authorization response in `url` (default: the current URL).\n * `init()` calls this for you; call it yourself only with `init({ handleCallback: false })`.\n *\n * The checks, in order: an `error` response surfaces as an error; `state` must match a sign-in this\n * tab started (constant-time, single use); `iss` must be the provider (RFC 9207); the code is\n * redeemed with the PKCE verifier only this tab holds; the ID token is verified against the\n * provider's keys, the `nonce`, `at_hash` and `c_hash`; then the access check, when configured.\n * The response parameters are removed from the address bar either way, so a reload cannot replay them.\n *\n * @returns {Promise<{ returnTo: string, user: object|null, denied: boolean, relayed?: boolean }>}\n */\n async handleRedirectCallback(url) {\n const win = this.#requireWindow();\n this.#ensureReady();\n const href = String(url ?? win.location.href);\n const parsed = new URL(href, win.location.href);\n const params = this.#responseParams(parsed);\n const transaction = params.state ? this.#takeTransaction(params.state) : null;\n\n if (!transaction && params.state) {\n // No sign-in with this state started in this tab: if this window is a sign-in popup, the\n // opener holds the transaction. Hand the response over and close.\n if (relayToOpener(win, href, params.state, popupChannelName(this.#config.authority, this.#config.clientId))) {\n setTimeout(() => {\n try {\n win.close();\n } catch {\n /* not closable */\n }\n }, 50);\n return { relayed: true, returnTo: null, user: null, denied: false };\n }\n }\n\n this.#cleanResponseFromUrl(parsed);\n\n if (params.error) throw this.#authorizationError(params);\n if (!params.state) throw new ArkCallbackError('the authorization response carried no `state`.');\n if (!transaction) {\n throw new ArkCallbackError(\n 'the authorization response does not belong to a sign-in started in this tab (unknown or expired `state`). ' +\n 'Start the sign-in again. If this keeps happening, check that the redirect URI is served by this same origin, ' +\n 'and that storage is not being cleared between the two pages.'\n );\n }\n if (!constantTimeEqual(String(params.state), String(transaction.state))) {\n throw new ArkCallbackError('the authorization response `state` does not match the request. Treat this as a CSRF attempt.');\n }\n return this.#completeSignin(params, transaction);\n }\n\n async #completeSignin(params, transaction) {\n const metadata = await this.metadata();\n\n // RFC 9207. Ark always sends `iss`; when the provider advertises it, a response without one is\n // as suspect as a wrong one, because stripping the parameter is how a mix-up attack hides.\n if (params.iss || metadata.authorization_response_iss_parameter_supported) {\n if (!params.iss) throw new ArkCallbackError('the provider advertises `iss` in authorization responses but this one has none.');\n if (params.iss !== metadata.issuer) throw new ArkCallbackError(`the authorization response came from '${params.iss}', not from '${metadata.issuer}'.`);\n }\n if (!params.code) throw new ArkCallbackError('the authorization response carried no `code`.');\n\n const tokens = await this.#exchangeCode({\n code: params.code,\n codeVerifier: transaction.codeVerifier,\n redirectUri: transaction.redirectUri,\n nonce: transaction.nonce ?? null,\n maxAge: transaction.maxAge ?? null\n });\n\n const returnTo = localOrDefault(transaction.returnTo, '/');\n const arkClaims = tokens.arkClaims();\n const allowed = await evaluateAccess(this.#config.accountSwitch, this.#config.onEvaluateAccess, {\n claims: tokens.claims ?? {},\n arkClaims,\n tokens\n });\n\n if (!allowed) {\n // No token is stored for an account that cannot use the app. The refused identity is kept\n // briefly, tab-local, so the dead end can say whose session it is and offer the way out.\n const denial = describeDenial(ArkAccessDeniedReasons.NO_APP_ACCESS, tokens.claims, arkClaims, returnTo);\n this.#setDenial({ ...denial, idTokenHint: tokens.idToken, createdAt: now() });\n this.#setTokens(null);\n if (tokens.refreshToken) this.#revokeQuietly(tokens.refreshToken);\n this.#publish({ error: null });\n this.#emit('accessDenied', this.#store.get().denial);\n return { returnTo: this.#config.accountSwitch.accessDeniedPath ?? returnTo, user: tokens.claims, denied: true };\n }\n\n this.#setDenial(null);\n this.#setTokens(tokens);\n this.#publish({ error: null });\n this.#schedule();\n this.#emit('signedIn', { user: tokens.claims, returnTo });\n this.#broadcast('signed-in');\n return { returnTo, user: tokens.claims, denied: false };\n }\n\n // =================================================================\n // Using the session\n // =================================================================\n\n /**\n * The access token for an API call, refreshed first when it is about to expire; null when nobody\n * is signed in or the session can no longer be renewed.\n *\n * Read it per call and never keep it: the client replaces it underneath you on every refresh.\n */\n async getAccessToken({ forceRefresh = false } = {}) {\n if (!this.#win) return null;\n this.#ensureReady();\n if (this.#initPromise) await this.#initPromise;\n else this.#restore();\n\n if (!this.#tokens) return null;\n if (forceRefresh || this.#tokens.expired(this.#leeway(this.#tokens))) {\n if (!this.#tokens.refreshToken) {\n if (this.#tokens.expired(0)) {\n this.#endLocalSession('expired', { broadcast: false });\n this.#emit('sessionExpired', { reason: 'expired' });\n return null;\n }\n return this.#tokens.accessToken;\n }\n try {\n await this.refresh();\n } catch (error) {\n if (!this.#tokens) return null; // the session ended (refresh token refused)\n if (this.#tokens.expired(0)) throw error; // offline with a dead token: say so\n }\n }\n return this.#tokens?.accessToken ?? null;\n }\n\n /**\n * Redeems the refresh token now. Concurrent calls, in this tab and (with Web Locks) across tabs,\n * share one request: Ark rotates refresh tokens and revokes the whole family if a retired one is\n * presented again, so two refreshes racing with the same token would sign the user out.\n */\n refresh() {\n this.#refreshPromise ??= this.#refreshUnderLock().finally(() => {\n this.#refreshPromise = null;\n });\n return this.#refreshPromise;\n }\n\n async #refreshUnderLock() {\n this.#ensureReady();\n if (!this.#tokens?.refreshToken) throw new ArkLoginRequiredError('there is no refresh token to renew the session with.');\n\n return withLock(`${this.#prefix}refresh`, async () => {\n if (this.#destroyed) throw new ArkError('the client was destroyed.');\n let current = this.#tokens;\n if (!current?.refreshToken) throw new ArkLoginRequiredError();\n\n if (this.#storageKind !== 'memory') {\n // Another tab (localStorage), or another instance on this page (a hot-module reload, a\n // micro-frontend; sessionStorage too), may have refreshed or signed out while this one\n // waited for the lock. Redeeming the token it already spent would revoke the family.\n const stored = this.#readStoredTokens();\n if (!stored) {\n this.#endLocalSession('signout', { broadcast: false });\n throw new ArkLoginRequiredError();\n }\n if (stored.refreshToken !== current.refreshToken) {\n if (!stored.expired(this.#leeway(stored))) {\n this.#setTokens(stored, { persist: false });\n this.#publish({ error: null });\n this.#schedule();\n return stored;\n }\n current = stored;\n }\n }\n\n if (await this.#isSpent(current.refreshToken)) {\n // Redeemed already, from a copy of this tab's storage (\"Duplicate tab\" copies\n // sessionStorage). Presenting it again would look like theft to the server and revoke the\n // family for both tabs; this tab signs in afresh instead (silently, while SSO lasts).\n this.#endLocalSession('expired', { broadcast: false });\n this.#emit('sessionExpired', { reason: 'refresh_token_spent' });\n throw new ArkLoginRequiredError('this tab\\'s refresh token was already redeemed by a copy of it (a duplicated tab). Sign in again.');\n }\n\n let tokens;\n try {\n const metadata = await this.metadata();\n const response = await this.#tokenRequest(metadata.token_endpoint, {\n grant_type: 'refresh_token',\n refresh_token: current.refreshToken\n });\n if (response.refresh_token && response.refresh_token !== current.refreshToken) {\n // The server has rotated: the token just presented is spent, whatever happens next. Keep\n // the new one before anything else can fail (the ID token check below may fetch JWKS),\n // or a retry would present the spent token and the whole family would be revoked.\n await this.#markSpent(current.refreshToken);\n current = TokenSet.fromJSON({ ...current.toJSON(), refresh_token: response.refresh_token });\n this.#setTokens(current);\n }\n tokens = await this.#toTokenSet(response, { nonce: null, subject: current.claims?.sub ?? null, previous: current });\n } catch (error) {\n this.#onRefreshFailure(error);\n throw error;\n }\n\n // Stored even by a client destroyed mid-request: the server has already rotated, so the old\n // refresh token in storage is spent, and the next instance must find the new one there.\n this.#setTokens(tokens);\n if (this.#destroyed) return tokens;\n this.#publish({ error: null });\n this.#schedule();\n this.#emit('tokensRefreshed', { expiresAt: tokens.expiresAt });\n this.#broadcast('tokens');\n return tokens;\n }, this.#win);\n }\n\n #onRefreshFailure(error) {\n const fatal =\n error instanceof ArkTokenError ||\n (error instanceof ArkOAuthError && ['invalid_grant', 'invalid_client', 'unauthorized_client'].includes(error.error));\n if (fatal) {\n // The refresh token was refused (expired, revoked, its session ended, the account or the\n // client deactivated) or what came back cannot be trusted. Either way the session is over.\n // Other tabs hear about it only when they share these tokens; with per-tab storage each tab\n // holds its own refresh token and finds out for itself.\n const untrusted = error instanceof ArkTokenError ? this.#tokens?.refreshToken : null;\n this.#endLocalSession('expired', { broadcast: this.#sharedStorage() });\n // A response that failed validation may still have rotated: withdraw the token it brought.\n if (untrusted) this.#revokeQuietly(untrusted);\n this.#emit('sessionExpired', { reason: 'refresh_refused', error });\n return;\n }\n this.#emit('refreshFailed', { error });\n if (this.#config.automaticRefresh && this.#tokens && !this.#destroyed) {\n clearTimeout(this.#timer);\n this.#timer = unref(setTimeout(() => this.refresh().catch(() => {}), RETRY_AFTER_NETWORK_FAILURE_MS));\n }\n }\n\n /** Whether `ark.fetch()` may attach the access token to this URL: the app's own origin or one in `apiOrigins`. */\n isApiUrl(url) {\n const win = this.#win;\n let target;\n try {\n target = new URL(String(url), win?.location?.href);\n } catch {\n return false;\n }\n const own = win?.location?.origin;\n return target.origin === own || this.#config.apiOrigins.includes(target.origin);\n }\n\n /**\n * `fetch` with the access token attached, for the app's own API.\n *\n * The token is sent only to the page's own origin and the origins in `apiOrigins`; anything else\n * is refused rather than quietly handed a bearer token. A 401 that says the token is invalid is\n * retried once after a refresh. Throws ArkLoginRequiredError when nobody is signed in.\n */\n async fetch(input, init = {}) {\n const win = this.#requireWindow();\n const rawUrl = typeof input === 'string' || input instanceof URL ? String(input) : input?.url;\n if (!this.isApiUrl(rawUrl)) {\n const origin = (() => {\n try {\n return new URL(rawUrl, win.location.href).origin;\n } catch {\n return rawUrl;\n }\n })();\n throw new ArkConfigError(\n `ark_oauth_client: refusing to send the access token to ${origin}. Add that origin to 'apiOrigins' if it is your API, ` +\n 'or call it with plain fetch().'\n );\n }\n\n const fetchImpl = this.#config.fetch ?? globalThis.fetch;\n const send = (token) => {\n const headers = new Headers(init.headers ?? (typeof Request !== 'undefined' && input instanceof Request ? input.headers : undefined));\n headers.set('Authorization', `Bearer ${token}`);\n return fetchImpl(input, { ...init, headers });\n };\n\n const token = await this.getAccessToken();\n if (!token) throw new ArkLoginRequiredError();\n let response = await send(token);\n\n const replayable = !(typeof Request !== 'undefined' && input instanceof Request) && !(init.body && typeof init.body.getReader === 'function');\n if (response.status === 401 && replayable && this.#tokens?.refreshToken) {\n const challenge = response.headers.get('WWW-Authenticate') ?? '';\n if (!challenge || /invalid_token/i.test(challenge)) {\n const renewed = await this.getAccessToken({ forceRefresh: true }).catch(() => null);\n if (renewed) response = await send(renewed);\n }\n }\n return response;\n }\n\n /** The UserInfo endpoint (OIDC Core \u00A75.3), with the current access token. */\n async userInfo() {\n const token = await this.getAccessToken();\n if (!token) throw new ArkLoginRequiredError();\n const metadata = await this.metadata();\n return getJson(metadata.userinfo_endpoint, {\n headers: { Authorization: `Bearer ${token}` },\n timeoutMs: this.#config.timeoutMs,\n fetch: this.#config.fetch\n });\n }\n\n // =================================================================\n // Signing out and switching account\n // =================================================================\n\n /**\n * Signs out of this app and the provider: drops the tokens here, revokes the refresh token, then\n * sends the browser to the provider's end-session endpoint with `id_token_hint`, so the provider\n * ends its session without asking and returns to `postLogoutRedirectUri`.\n *\n * Both halves matter. Dropping only the local tokens leaves the provider's session alive, and the\n * next sign-in is silent, as the same person.\n *\n * @param {{ returnTo?: string, postLogoutRedirectUri?: string, revoke?: boolean }} [options]\n */\n async signoutRedirect({ returnTo, postLogoutRedirectUri, revoke = true, ...internal } = {}) {\n this.#requireWindow();\n this.#ensureReady();\n const idTokenHint = this.#tokens?.idToken ?? this.#denial?.idTokenHint ?? null;\n const refreshToken = this.#tokens?.refreshToken ?? null;\n let metadata = null;\n try {\n metadata = await this.metadata();\n } catch {\n metadata = null; // provider unreachable: still sign out locally\n }\n\n this.#endLocalSession('signout', { broadcast: true });\n if (revoke && refreshToken && metadata?.revocation_endpoint) await this.#revokeQuietly(refreshToken, metadata);\n\n const home = localOrDefault(returnTo ?? this.#config.accountSwitch.homePath, '/');\n if (!metadata?.end_session_endpoint) {\n this.#navigate(home);\n return;\n }\n\n const params = new URLSearchParams({ client_id: this.#config.clientId });\n if (idTokenHint) params.set('id_token_hint', idTokenHint);\n const target = postLogoutRedirectUri ?? this.#config.postLogoutRedirectUri;\n if (target) {\n const state = createState();\n params.set('post_logout_redirect_uri', this.#resolve(target));\n params.set('state', state);\n writeJson(this.#txStorage, `${this.#prefix}logout:${state}`, {\n returnTo: home,\n then: internal.then ?? null,\n prompt: internal.prompt ?? null,\n loginHint: internal.loginHint ?? null,\n createdAt: now()\n });\n }\n const endpoint = metadata.end_session_endpoint;\n await this.#redirect(`${endpoint}${endpoint.includes('?') ? '&' : '?'}${params}`);\n }\n\n /**\n * Signs out of this app only: tokens dropped and the refresh token revoked, the provider's session\n * left alone (the user's other apps stay signed in, and the next sign-in here is silent).\n */\n async signoutLocal({ revoke = true } = {}) {\n this.#ensureReady();\n const refreshToken = this.#tokens?.refreshToken ?? null;\n this.#endLocalSession('signout', { broadcast: true });\n if (revoke && refreshToken) await this.#revokeQuietly(refreshToken);\n }\n\n /**\n * \"Sign in as a different user\": drops this app's session and signs in again with\n * `prompt=login`, so the provider draws its sign-in form instead of answering from the session\n * already in this browser. With `accountSwitch.endProviderSessionOnSwitch`, the provider session\n * is ended first and the sign-in follows when the browser comes back.\n */\n async switchUser({ returnTo, loginHint } = {}) {\n const options = this.#config.accountSwitch;\n const target = localOrDefault(returnTo ?? this.#denial?.returnTo ?? null, options.homePath);\n if (options.endProviderSessionOnSwitch) {\n await this.signoutRedirect({ returnTo: target, then: 'signin', prompt: options.prompt, loginHint });\n return;\n }\n await this.signoutLocal();\n await this.signinRedirect({ prompt: options.prompt || 'login', returnTo: target, loginHint });\n }\n\n /** Clears a refused sign-in's state without signing in again. */\n clearDenial() {\n this.#ensureReady();\n this.#setDenial(null);\n this.#publish();\n }\n\n // =================================================================\n // Provider metadata and token checks\n // =================================================================\n\n /** The provider's discovery document, cached. */\n metadata({ force = false } = {}) {\n return this.#metadata.get(force);\n }\n\n async jwks() {\n const { jwks_uri: uri } = await this.metadata();\n if (!uri) throw new ArkOAuthError('server_error', \"the provider's metadata has no 'jwks_uri'.\", { endpoint: this.#config.authority });\n if (!this.#jwks || this.#jwks.uri !== uri) {\n this.#jwks = new JwksCache(uri, {\n ttlMs: this.#config.jwksTtlMs,\n minRefreshIntervalMs: this.#config.jwksMinRefreshIntervalMs,\n timeoutMs: this.#config.timeoutMs,\n fetch: this.#config.fetch\n });\n }\n return this.#jwks;\n }\n\n /** Verifies an ID token against the provider's keys and the values of the sign-in it belongs to. */\n async verifyIdToken(idToken, { nonce = null, accessToken = null, code = null, maxAge = null, subject = null } = {}) {\n const metadata = await this.metadata();\n return verifyJwt(idToken, await this.jwks(), {\n issuer: metadata.issuer,\n audience: this.#config.clientId,\n subject: subject ?? undefined,\n nonce,\n accessToken,\n code,\n maxAgeSeconds: maxAge,\n requireTokenHashes: this.#config.requireTokenHashes,\n requireIat: true,\n clockToleranceSeconds: this.#config.clockToleranceSeconds,\n algorithms: this.#config.idTokenSigningAlgorithms ?? metadata.id_token_signing_alg_values_supported ?? undefined\n });\n }\n\n // =================================================================\n // Diagnostics\n // =================================================================\n\n /**\n * Pairs this app's configuration with the provider's live metadata and reports what does not\n * line up: the browser counterpart of `checkSetup()` in the Node client and `ArkSetupProbe` in\n * .NET. In a browser it also proves CORS, which is the usual first failure of a new SPA and\n * otherwise surfaces as a bare \"Failed to fetch\". Render it on a setup or health page.\n */\n async checkSetup() {\n const win = this.#win;\n const config = this.#config;\n const cut = config.authority.lastIndexOf('/');\n const tenantId = config.authority.slice(cut + 1);\n const report = {\n authority: config.authority,\n clientId: config.clientId,\n tenantId,\n origin: win?.location?.origin ?? null,\n secureContext: Boolean(win?.isSecureContext ?? globalThis.isSecureContext),\n webCrypto: Boolean(globalThis.crypto?.subtle),\n storage: (this.#ensureReady(), this.#storageKind),\n scopes: [...config.scopes],\n responseMode: config.responseMode,\n redirectUri: win ? this.#resolve(config.redirectUri) : config.redirectUri,\n postLogoutRedirectUri: config.postLogoutRedirectUri && win ? this.#resolve(config.postLogoutRedirectUri) : config.postLogoutRedirectUri,\n adminConsoleUrl: `${config.authority}/admin`,\n integrationPageUrl: `${config.authority}/oauth2/integrate/${encodeURIComponent(config.clientId)}`,\n discoveryUrl: `${config.authority}/.well-known/openid-configuration`,\n discoveryOk: false,\n jwksOk: false,\n tokenEndpointCorsOk: null,\n provider: null,\n signingKeys: [],\n problems: []\n };\n\n if (!report.secureContext || !report.webCrypto) {\n 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.');\n }\n\n let metadata;\n try {\n metadata = await this.metadata({ force: true });\n report.discoveryOk = true;\n } catch (error) {\n report.problems.push(`The provider's discovery document could not be read: ${error.message}`);\n return report;\n }\n\n report.provider = {\n issuer: metadata.issuer,\n authorizationEndpoint: metadata.authorization_endpoint,\n tokenEndpoint: metadata.token_endpoint,\n userInfoEndpoint: metadata.userinfo_endpoint,\n jwksUri: metadata.jwks_uri,\n endSessionEndpoint: metadata.end_session_endpoint ?? null,\n revocationEndpoint: metadata.revocation_endpoint ?? null,\n scopesSupported: metadata.scopes_supported ?? [],\n grantTypesSupported: metadata.grant_types_supported ?? [],\n responseModesSupported: metadata.response_modes_supported ?? [],\n codeChallengeMethodsSupported: metadata.code_challenge_methods_supported ?? [],\n tokenEndpointAuthMethodsSupported: metadata.token_endpoint_auth_methods_supported ?? [],\n requirePushedAuthorizationRequests: metadata.require_pushed_authorization_requests === true\n };\n\n try {\n const keys = await (await this.jwks()).keys({ force: true });\n report.jwksOk = true;\n report.signingKeys = keys.map((k) => ({ kid: k.kid ?? null, kty: k.kty, alg: k.alg ?? null, use: k.use ?? null }));\n } catch (error) {\n report.problems.push(`The provider's signing keys could not be read: ${error.message}`);\n }\n\n // A refresh with a token that cannot exist. Any OAuth error back proves the token endpoint is\n // reachable *and* answers this origin; a network error means CORS (or the endpoint) is missing.\n // Nothing is created or changed on the server.\n try {\n await postForm(\n metadata.token_endpoint,\n { grant_type: 'refresh_token', refresh_token: 'ark-setup-probe', client_id: config.clientId },\n { timeoutMs: config.timeoutMs, fetch: config.fetch }\n );\n report.tokenEndpointCorsOk = true;\n } catch (error) {\n report.tokenEndpointCorsOk = !(error instanceof ArkNetworkError);\n if (!report.tokenEndpointCorsOk) report.problems.push(`The token endpoint is not reachable from this page: ${error.message}`);\n else if (error instanceof ArkOAuthError && ['invalid_client', 'unauthorized_client'].includes(error.error)) {\n report.problems.push(\n `The token endpoint refused client '${config.clientId}' (${error.error}${error.errorDescription ? `: ${error.errorDescription}` : ''}). ` +\n \"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.\"\n );\n }\n }\n\n const supportedScopes = new Set(metadata.scopes_supported ?? []);\n const unknown = supportedScopes.size ? config.scopes.filter((s) => !supportedScopes.has(s)) : [];\n if (unknown.length) {\n 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.`);\n }\n if (!(metadata.code_challenge_methods_supported ?? []).includes('S256')) {\n report.problems.push('The tenant does not advertise the S256 PKCE method, which this client always sends.');\n }\n const methods = metadata.token_endpoint_auth_methods_supported ?? [];\n if (methods.length && !methods.includes('none')) {\n report.problems.push(\"The tenant does not list the 'none' token endpoint auth method, which a browser (public) client needs.\");\n }\n const modes = metadata.response_modes_supported ?? [];\n if (modes.length && !modes.includes(config.responseMode)) {\n report.problems.push(`The tenant does not support response_mode '${config.responseMode}' (it lists ${modes.join(', ')}).`);\n }\n if (config.scopes.includes('offline_access') && !(metadata.grant_types_supported ?? ['refresh_token']).includes('refresh_token')) {\n report.problems.push('offline_access is requested but the tenant does not serve the refresh_token grant.');\n }\n if (!config.scopes.includes('offline_access')) {\n report.problems.push('offline_access is not requested, so there is no refresh token: the session ends when the access token expires.');\n }\n if (metadata.require_pushed_authorization_requests === true) {\n report.problems.push('The tenant requires pushed authorization requests, which a browser app cannot make.');\n }\n if (!metadata.end_session_endpoint) {\n report.problems.push('The provider has no end_session_endpoint, so sign-out can only end the local session.');\n }\n return report;\n }\n\n /** Stops timers and listeners. For tests, hot-module reloading, and micro-frontends that unmount. */\n destroy() {\n this.#destroyed = true;\n clearTimeout(this.#timer);\n this.#timer = null;\n for (const off of this.#detach.splice(0)) off();\n if (this.#channel) {\n this.#channel.onmessage = null;\n this.#channel.close();\n this.#channel = null;\n }\n }\n\n // =================================================================\n // internals: tokens\n // =================================================================\n\n async #exchangeCode({ code, codeVerifier, redirectUri, nonce, maxAge }) {\n const metadata = await this.metadata();\n const response = await this.#tokenRequest(metadata.token_endpoint, {\n grant_type: 'authorization_code',\n code,\n redirect_uri: redirectUri,\n code_verifier: codeVerifier\n });\n return this.#toTokenSet(response, { nonce, code, maxAge });\n }\n\n /** A public client authenticates with nothing but its id, which goes in the body. */\n #tokenRequest(endpoint, form) {\n if (!endpoint) throw new ArkOAuthError('server_error', \"the provider's metadata has no 'token_endpoint'.\", { endpoint: this.#config.authority });\n return postForm(endpoint, { ...form, client_id: this.#config.clientId }, { timeoutMs: this.#config.timeoutMs, fetch: this.#config.fetch });\n }\n\n async #toTokenSet(response, { nonce, code = null, maxAge = null, subject = null, previous = null }) {\n if (!response.access_token) throw new ArkTokenError('the token response contains no access_token.');\n let claims = null;\n if (response.id_token) {\n // On refresh, OIDC Core \u00A712.2: the new ID token must be about the same user.\n claims = await this.verifyIdToken(response.id_token, { nonce, accessToken: response.access_token, code, maxAge, subject });\n } else if (nonce !== null && String(response.scope ?? '').split(' ').includes('openid')) {\n throw new ArkTokenError('the token response contains no id_token, although the openid scope was granted.');\n }\n const merged = { ...response };\n if (previous) {\n // Rotation off: the server sends no new refresh token and the old one stays valid. A refresh\n // response may also omit the ID token; the last one still serves as id_token_hint at sign-out.\n merged.refresh_token ??= previous.refreshToken;\n merged.id_token ??= previous.idToken;\n }\n return new TokenSet(merged, { claims: claims ?? previous?.claims ?? null });\n }\n\n #setTokens(tokens, { persist = true } = {}) {\n this.#tokens = tokens;\n this.#derived = tokens\n ? { claims: tokens.claims ? Object.freeze({ ...tokens.claims }) : null, arkClaims: Object.freeze(tokens.arkClaims()), scopes: Object.freeze(tokens.scopes()) }\n : { claims: null, arkClaims: Object.freeze([]), scopes: Object.freeze([]) };\n if (!persist) return;\n if (tokens) writeJson(this.#storage, `${this.#prefix}tokens`, tokens.toJSON());\n else remove(this.#storage, `${this.#prefix}tokens`);\n }\n\n #readStoredTokens() {\n const data = readJson(this.#storage, `${this.#prefix}tokens`);\n return data?.access_token ? TokenSet.fromJSON(data) : null;\n }\n\n #restore() {\n if (!this.#tokens) {\n const stored = this.#readStoredTokens();\n if (stored) this.#setTokens(stored, { persist: false });\n }\n if (!this.#denial) {\n const denial = readJson(this.#txStorage, `${this.#prefix}denied`);\n if (denial && now() - (denial.createdAt ?? 0) <= DENIAL_TTL_SECONDS) this.#denial = denial;\n else if (denial) remove(this.#txStorage, `${this.#prefix}denied`);\n }\n }\n\n async #renewIfNeeded() {\n if (!this.#tokens || !this.#tokens.expired(this.#leeway(this.#tokens))) return;\n if (!this.#tokens.refreshToken) {\n if (this.#tokens.expired(0)) this.#endLocalSession('expired', { broadcast: false });\n return;\n }\n try {\n await this.refresh();\n } catch {\n /* already reflected in the state: session ended, or a retry is scheduled */\n }\n }\n\n #endLocalSession(reason, { broadcast }) {\n const hadSession = Boolean(this.#tokens || this.#denial);\n clearTimeout(this.#timer);\n this.#timer = null;\n this.#setTokens(null);\n this.#setDenial(null);\n this.#publish();\n if (hadSession) this.#emit('signedOut', { reason });\n if (broadcast) this.#broadcast('signed-out');\n }\n\n async #revokeQuietly(token, metadata = null) {\n try {\n const md = metadata ?? (await this.metadata());\n if (!md.revocation_endpoint) return;\n await postFormNoCors(\n md.revocation_endpoint,\n { token, token_type_hint: 'refresh_token', client_id: this.#config.clientId },\n { timeoutMs: Math.min(this.#config.timeoutMs, 5000), fetch: this.#config.fetch }\n );\n } catch {\n // Best effort. The provider-side logout ends the session behind the token anyway, and a\n // refresh token whose session has ended is refused.\n }\n }\n\n #schedule() {\n clearTimeout(this.#timer);\n this.#timer = null;\n const tokens = this.#tokens;\n if (this.#destroyed || !tokens || tokens.expiresAt === null || !this.#win) return;\n const renew = Boolean(this.#config.automaticRefresh && tokens.refreshToken);\n // automaticRefresh off with a refresh token in hand: nothing to time; getAccessToken() renews on demand.\n if (!renew && tokens.refreshToken) return;\n const at = renew ? tokens.expiresAt - this.#lead(tokens) : tokens.expiresAt;\n const delay = Math.min(MAX_TIMER_MS, Math.max(0, (at - now()) * 1000));\n this.#timer = unref(setTimeout(() => {\n if (renew) {\n this.refresh().catch(() => {});\n } else if (this.#tokens === tokens) {\n this.#endLocalSession('expired', { broadcast: false });\n this.#emit('sessionExpired', { reason: 'expired' });\n }\n }, delay));\n }\n\n #sharedStorage() {\n return this.#storageKind === 'local' || this.#storageKind === 'custom';\n }\n\n /**\n * How early to renew: `refreshBeforeSeconds`, but never more than half the token's lifetime. A\n * client record with 30- or 60-second access tokens would otherwise be due for renewal the moment\n * each one arrived, and refresh in a tight loop.\n */\n #lead(tokens, max = this.#config.refreshBeforeSeconds) {\n if (!tokens || tokens.expiresAt === null) return max;\n const lifetime = tokens.expiresAt - tokens.issuedAt;\n return lifetime > 0 ? Math.min(max, lifetime / 2) : max;\n }\n\n /** The margin within which a token is renewed on use rather than handed out. */\n #leeway(tokens) {\n return this.#lead(tokens, Math.min(30, this.#config.refreshBeforeSeconds));\n }\n\n async #spentHash(token) {\n return base64UrlEncode(await sha256(`${this.#config.clientId}|${token}`)).slice(0, 24);\n }\n\n async #isSpent(token) {\n const hash = await this.#spentHash(token);\n return (readJson(this.#spentStorage, `${this.#prefix}spent`) ?? []).some((entry) => entry?.h === hash);\n }\n\n async #markSpent(token) {\n const hash = await this.#spentHash(token);\n const list = (readJson(this.#spentStorage, `${this.#prefix}spent`) ?? []).filter((entry) => entry && entry.h !== hash);\n list.push({ h: hash, at: now() });\n writeJson(this.#spentStorage, `${this.#prefix}spent`, list.slice(-SPENT_TOKENS_REMEMBERED));\n }\n\n // =================================================================\n // internals: state, storage, transactions\n // =================================================================\n\n #ensureReady() {\n if (this.#ready) return;\n this.#ready = true;\n const { storage, kind } = resolveStorage(this.#config.storage, this.#win);\n this.#storage = storage;\n this.#storageKind = kind;\n // The sign-in transaction has to survive one navigation to the provider and back, in this tab\n // only. sessionStorage is exactly that, whatever the token storage is.\n this.#txStorage = kind === 'session' ? storage : resolveStorage('session', this.#win).storage;\n // Shared by every tab of the origin, so a duplicated tab can see that a refresh token it copied\n // has been redeemed already. Holds hashes, never tokens.\n this.#spentStorage = kind === 'local' ? storage : resolveStorage('local', this.#win).storage;\n }\n\n #publish(extra = {}) {\n const tokens = this.#tokens;\n const denial = this.#denial;\n this.#store.set({\n status: tokens ? 'authenticated' : denial ? 'denied' : 'unauthenticated',\n user: this.#derived.claims,\n arkClaims: this.#derived.arkClaims,\n scopes: this.#derived.scopes,\n expiresAt: tokens?.expiresAt ?? null,\n denial: denial ? this.#publicDenial(denial) : null,\n ...extra\n });\n }\n\n #publicDenial(denial) {\n if (this.#publicDenialCache?.source === denial) return this.#publicDenialCache.value;\n // The ID token kept for the sign-out hint stays internal.\n const { idTokenHint: _hint, createdAt: _created, ...visible } = denial;\n const value = Object.freeze({ ...visible, arkClaims: Object.freeze([...(visible.arkClaims ?? [])]) });\n this.#publicDenialCache = { source: denial, value };\n return value;\n }\n\n #publicDenialCache = null;\n\n #setDenial(denial) {\n this.#denial = denial;\n if (denial) writeJson(this.#txStorage, `${this.#prefix}denied`, denial);\n else remove(this.#txStorage, `${this.#prefix}denied`);\n }\n\n #fail(error) {\n const wrapped = error instanceof ArkError ? error : new ArkError(String(error?.message ?? error), { cause: error });\n this.#publish({ error: wrapped });\n this.#schedule();\n this.#emit('error', wrapped);\n return this.#store.get();\n }\n\n #saveTransaction(transaction) {\n writeJson(this.#txStorage, `${this.#prefix}tx:${transaction.state}`, transaction);\n }\n\n /** Reads and deletes a transaction: each one completes at most one sign-in. */\n #takeTransaction(state) {\n const key = `${this.#prefix}tx:${state}`;\n const transaction = readJson(this.#txStorage, key);\n remove(this.#txStorage, key);\n if (!transaction) return null;\n if (now() - (transaction.createdAt ?? 0) > this.#config.transactionTtlSeconds) return null;\n return transaction;\n }\n\n #takeLogoutTransaction(href) {\n const state = this.#responseParams(new URL(href)).state;\n if (!state) return null;\n const key = `${this.#prefix}logout:${state}`;\n const transaction = readJson(this.#txStorage, key);\n remove(this.#txStorage, key);\n this.#cleanResponseFromUrl(new URL(href));\n return transaction;\n }\n\n #sweepTransactions() {\n const limit = this.#config.transactionTtlSeconds;\n for (const key of keysWithPrefix(this.#txStorage, this.#prefix)) {\n if (!key.includes(':tx:') && !key.includes(':logout:')) continue;\n const entry = readJson(this.#txStorage, key);\n if (!entry || now() - (entry.createdAt ?? 0) > limit) remove(this.#txStorage, key);\n }\n }\n\n // =================================================================\n // internals: URLs and navigation\n // =================================================================\n\n #requireWindow() {\n if (!this.#win) {\n throw new ArkConfigError(\n '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.'\n );\n }\n return this.#win;\n }\n\n /** A path becomes an absolute URL on the page's origin; an absolute URL is used as it is. */\n #resolve(value) {\n if (!value) return value;\n if (/^https?:\\/\\//i.test(value)) return value;\n return new URL(value, this.#requireWindow().location.origin).toString();\n }\n\n /** The response parameters, from the query or the fragment depending on the response mode. */\n #responseParams(url, responseMode = this.#config.responseMode) {\n const fromQuery = url.searchParams;\n const fromHash = new URLSearchParams(url.hash.startsWith('#') ? url.hash.slice(1) : url.hash);\n const pick = responseMode === 'fragment' ? [fromHash, fromQuery] : [fromQuery, fromHash];\n const source = pick.find((p) => p.has('state') || p.has('code') || p.has('error')) ?? pick[0];\n const result = {};\n for (const name of RESPONSE_PARAMS) {\n const value = source.get(name);\n if (value !== null) result[name] = value;\n }\n return result;\n }\n\n #classify(href) {\n if (!this.#win) return null;\n let url;\n try {\n url = new URL(href, this.#win.location.href);\n } catch {\n return null;\n }\n const same = (target) => {\n if (!target) return false;\n const t = new URL(this.#resolve(target));\n return t.origin === url.origin && t.pathname === url.pathname;\n };\n const params = this.#responseParams(url);\n if (same(this.#config.redirectUri) && (params.code || params.error)) return 'signin';\n if (same(this.#config.postLogoutRedirectUri ?? DEFAULT_POST_LOGOUT_PATH) && params.state) {\n this.#ensureReady();\n if (readJson(this.#txStorage, `${this.#prefix}logout:${params.state}`)) return 'signout';\n }\n return null;\n }\n\n #cleanResponseFromUrl(url) {\n const win = this.#win;\n if (!win?.history?.replaceState) return;\n const clean = new URL(url.toString());\n for (const name of RESPONSE_PARAMS) clean.searchParams.delete(name);\n if (clean.hash) {\n const hash = new URLSearchParams(clean.hash.slice(1));\n if (RESPONSE_PARAMS.some((name) => hash.has(name))) {\n for (const name of RESPONSE_PARAMS) hash.delete(name);\n const rest = hash.toString();\n clean.hash = rest ? `#${rest}` : '';\n }\n }\n const relative = `${clean.pathname}${clean.search}${clean.hash}`;\n try {\n win.history.replaceState(win.history.state, '', relative);\n } catch {\n /* sandboxed: nothing to clean */\n }\n }\n\n #authorizationError(params) {\n return new ArkOAuthError(params.error, params.error_description, {\n endpoint: `${this.#config.authority}/oauth2/authorize`,\n errorUri: params.error_uri ?? null,\n body: params\n });\n }\n\n async #redirect(url) {\n if (this.#config.redirect) return this.#config.redirect(url);\n this.#requireWindow().location.assign(url);\n }\n\n /** In-app navigation to a local path without reloading. See init(). */\n #navigate(to) {\n if (this.#config.navigate) return this.#config.navigate(to);\n const win = this.#win;\n if (!win) return;\n try {\n win.history.replaceState(null, '', to);\n const PopState = win.PopStateEvent ?? globalThis.PopStateEvent;\n if (typeof PopState === 'function') win.dispatchEvent(new PopState('popstate', { state: null }));\n } catch {\n win.location.replace(to);\n }\n }\n\n // =================================================================\n // internals: events and cross-tab sync\n // =================================================================\n\n #emit(event, detail) {\n for (const handler of [...(this.#events.get(event) ?? [])]) {\n try {\n handler(detail);\n } catch (error) {\n queueMicrotask(() => {\n throw error;\n });\n }\n }\n }\n\n #broadcast(type) {\n try {\n this.#channel?.postMessage({ type, from: this.#id });\n } catch {\n /* channel closed */\n }\n }\n\n #attachListeners() {\n const win = this.#win;\n if (!win || this.#detach.length) return;\n\n if (this.#config.syncTabs) {\n const Channel = win.BroadcastChannel ?? globalThis.BroadcastChannel;\n if (typeof Channel === 'function') {\n this.#channel = unref(new Channel(`ark-oidc:${this.#config.authority}|${this.#config.clientId}`));\n this.#channel.onmessage = (event) => this.#onTabMessage(event.data);\n }\n }\n\n // Timers in a background tab are throttled or frozen; coming back is the moment to catch up.\n const doc = win.document;\n if (doc?.addEventListener) {\n const onVisible = () => {\n if (doc.visibilityState !== 'visible' || !this.#tokens) return;\n if (this.#sharedStorage()) this.#adoptStoredTokens();\n if (this.#tokens?.expired(this.#lead(this.#tokens))) this.#renewIfNeeded();\n };\n doc.addEventListener('visibilitychange', onVisible);\n this.#detach.push(() => doc.removeEventListener('visibilitychange', onVisible));\n }\n }\n\n #onTabMessage(message) {\n if (!message || message.from === this.#id) return;\n if (message.type === 'signed-out') {\n if (this.#tokens || this.#denial) this.#endLocalSession('signout', { broadcast: false });\n return;\n }\n if ((message.type === 'tokens' || message.type === 'signed-in') && this.#sharedStorage()) this.#adoptStoredTokens();\n }\n\n #adoptStoredTokens() {\n const stored = this.#readStoredTokens();\n if (!stored) {\n if (this.#tokens) this.#endLocalSession('signout', { broadcast: false });\n return;\n }\n if (stored.accessToken === this.#tokens?.accessToken) return;\n this.#setTokens(stored, { persist: false });\n this.#setDenial(null);\n this.#publish({ error: null });\n this.#schedule();\n }\n}\n\n/** Convenience factory, for callers who prefer not to write `new`. */\nexport function createArkClient(options) {\n return new ArkBrowserClient(options);\n}\n", "import { VERSION } from './version.js';\n\n/**\n * The built-in dead end for a refused sign-in, for apps without a framework (or that want one\n * ready-made). The same wording as the access-denied page of the .NET, Python and Node clients.\n *\n * Built with DOM calls and `textContent` only (no innerHTML, so nothing from a token can become\n * markup) and styled through the CSSOM, which a strict Content-Security-Policy allows where an\n * injected <style> element or a `style` attribute would be blocked. Pass `unstyled: true` and style\n * the `ark-denied*` classes yourself to match the app.\n *\n * ark.subscribe((s) => { if (s.status === 'denied') renderAccessDenied(document.body, ark); });\n */\n\nconst PALETTE = {\n light: { bg: '#f7f7f8', surface: '#ffffff', border: '#e2e2e6', fg: '#17171a', muted: '#6a6a73', accent: '#4f46e5', accentFg: '#ffffff' },\n dark: { bg: '#111114', surface: '#1a1a1f', border: '#313139', fg: '#ececf1', muted: '#9a9aa5', accent: '#8b85ff', accentFg: '#16161c' }\n};\n\nfunction el(doc, tag, className, text) {\n const node = doc.createElement(tag);\n if (className) node.className = className;\n if (text !== undefined) node.textContent = text;\n return node;\n}\n\nfunction css(node, styles) {\n for (const [key, value] of Object.entries(styles)) node.style.setProperty(key, value);\n}\n\n/**\n * Renders the access-denied card into `container`, replacing its content.\n *\n * @param {Element} container\n * @param {import('./client.js').ArkBrowserClient} client\n * @param {{ unstyled?: boolean, appName?: string }} [options]\n * @returns {() => void} removes the card again\n */\nexport function renderAccessDenied(container, client, options = {}) {\n const doc = container.ownerDocument ?? globalThis.document;\n const config = client.config.accountSwitch;\n const denial = client.getSnapshot().denial;\n const appName = (options.appName ?? config.appDisplayName ?? '').trim() || client.clientId || 'this application';\n const account = config.showSignedInAccount ? (denial?.email ?? denial?.name ?? denial?.subject ?? null) : null;\n const dark = Boolean(doc.defaultView?.matchMedia?.('(prefers-color-scheme: dark)').matches);\n const c = PALETTE[dark ? 'dark' : 'light'];\n const styled = !options.unstyled;\n\n const root = el(doc, 'main', 'ark-denied');\n root.setAttribute('role', 'alert');\n const card = el(doc, 'div', 'ark-denied__card');\n root.append(card);\n\n card.append(el(doc, 'h1', 'ark-denied__title', `You do not have access to ${appName}`));\n\n const lede = el(doc, 'p', 'ark-denied__lede');\n if (account) {\n lede.append('You are signed in as ', el(doc, 'strong', null, account), `, and that account does not have access to ${appName}.`);\n } else {\n lede.textContent = `The account you are signed in with does not have access to ${appName}.`;\n }\n card.append(lede);\n card.append(\n el(\n doc,\n 'p',\n 'ark-denied__hint',\n `If somebody else was using this browser, their sign-in is still active and it is the one being offered to ${appName}. ` +\n 'Choose \u201CSign in as a different user\u201D to enter your own credentials.'\n )\n );\n\n const actions = el(doc, 'div', 'ark-denied__actions');\n const switchButton = el(doc, 'button', 'ark-denied__switch', 'Sign in as a different user');\n switchButton.type = 'button';\n switchButton.addEventListener('click', () => client.switchUser({ returnTo: denial?.returnTo ?? undefined }));\n actions.append(switchButton);\n\n let signOutButton = null;\n if (config.allowFullSignOut) {\n signOutButton = el(doc, 'button', 'ark-denied__signout', 'Sign out completely');\n signOutButton.type = 'button';\n signOutButton.addEventListener('click', () => client.signoutRedirect({ returnTo: config.homePath }));\n actions.append(signOutButton);\n }\n card.append(actions);\n\n let foot = null;\n if (config.supportUrl || config.supportEmail) {\n foot = el(doc, 'p', 'ark-denied__foot', `Need access to ${appName}? `);\n const link = el(doc, 'a', null, config.supportUrl ? 'Request it here' : config.supportEmail);\n link.href = config.supportUrl ? config.supportUrl : `mailto:${config.supportEmail}`;\n foot.append(link);\n card.append(foot);\n }\n const version = el(doc, 'p', 'ark-denied__version', `ark-oauth-client-js ${VERSION}`);\n card.append(version);\n\n if (styled) {\n const font = 'ui-sans-serif, -apple-system, \"Segoe UI\", Roboto, Helvetica, Arial, sans-serif';\n 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}` });\n css(card, { width: '100%', 'max-width': '480px', background: c.surface, border: `1px solid ${c.border}`, 'border-radius': '12px', padding: '28px', 'box-sizing': 'border-box' });\n for (const p of card.querySelectorAll('p')) css(p, { margin: '0 0 14px', color: c.muted });\n css(lede, { color: c.fg });\n css(card.querySelector('h1'), { margin: '0 0 10px', 'font-size': '19px', 'font-weight': '640' });\n css(actions, { display: 'flex', 'flex-direction': 'column', gap: '10px', 'margin-top': '20px' });\n const button = { width: '100%', padding: '11px 14px', 'border-radius': '8px', font: 'inherit', 'font-weight': '560', cursor: 'pointer' };\n css(switchButton, { ...button, border: `1px solid ${c.accent}`, background: c.accent, color: c.accentFg });\n if (signOutButton) css(signOutButton, { ...button, border: `1px solid ${c.border}`, background: 'transparent', color: c.fg });\n if (foot) {\n css(foot, { 'margin-top': '18px', 'padding-top': '14px', 'border-top': `1px solid ${c.border}`, 'font-size': '13px' });\n css(foot.querySelector('a'), { color: c.accent });\n }\n css(version, { margin: '18px 0 0', 'padding-top': '14px', 'border-top': foot ? '0' : `1px solid ${c.border}`, 'font-size': '12px', 'text-align': 'center' });\n }\n\n container.replaceChildren(root);\n return () => root.remove();\n}\n"],
|
|
5
|
+
"mappings": ";AAIO,IAAMA,GAAU,QCShB,IAAMC,EAAN,cAAuB,KAAM,CAClC,YAAYC,EAASC,EAAS,CAC5B,MAAMD,EAASC,CAAO,EACtB,KAAK,KAAO,WAAW,IACzB,CACF,EAOaC,EAAN,cAA6BH,CAAS,CAAC,EASjCI,EAAN,MAAMC,UAAsBL,CAAS,CAC1C,YAAYM,EAAOC,EAAa,CAAE,OAAAC,EAAS,EAAG,SAAAC,EAAW,KAAM,SAAAC,EAAW,KAAM,KAAAC,EAAO,IAAK,EAAI,CAAC,EAAG,CAClG,MAAMJ,EAAc,GAAGD,CAAK,KAAKC,CAAW,GAAKD,CAAK,EACtD,KAAK,MAAQA,EACb,KAAK,iBAAmBC,GAAe,KACvC,KAAK,SAAWG,EAChB,KAAK,OAASF,EACd,KAAK,SAAWC,EAChB,KAAK,KAAOE,CACd,CAGA,OAAO,aAAaH,EAAQG,EAAMF,EAAU,CAC1C,OAAIE,GAAQ,OAAOA,GAAS,UAAY,OAAOA,EAAK,OAAU,SACrD,IAAIN,EAAcM,EAAK,MAAOA,EAAK,kBAAmB,CAC3D,OAAAH,EACA,SAAAC,EACA,SAAUE,EAAK,WAAa,KAC5B,KAAAA,CACF,CAAC,EAEI,IAAIN,EAAc,eAAgB,8BAA8BG,CAAM,IAAK,CAAE,OAAAA,EAAQ,SAAAC,EAAU,KAAAE,CAAK,CAAC,CAC9G,CACF,EAUaC,EAAN,cAA4BZ,CAAS,CAC1C,YAAYC,EAAS,CAAE,MAAAY,EAAQ,IAAK,EAAI,CAAC,EAAG,CAC1C,MAAMZ,C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AY,cAAe,MAAOA,EAAE,EAAG,CAAC,EACxHQ,IACFrB,EAAIqB,EAAM,CAAE,aAAc,OAAQ,cAAe,OAAQ,aAAc,aAAaR,EAAE,MAAM,GAAI,YAAa,MAAO,CAAC,EACrHb,EAAIqB,EAAK,cAAc,GAAG,EAAG,CAAE,MAAOR,EAAE,MAAO,CAAC,GAElDb,EAAIuB,EAAS,CAAE,OAAQ,WAAY,cAAe,OAAQ,aAAcF,EAAO,IAAM,aAAaR,EAAE,MAAM,GAAI,YAAa,OAAQ,aAAc,QAAS,CAAC,CAC7J,CAEA,OAAAR,EAAU,gBAAgBU,CAAI,EACvB,IAAMA,EAAK,OAAO,CAC3B",
|
|
6
|
+
"names": ["VERSION", "ArkError", "message", "options", "ArkConfigError", "ArkOAuthError", "_ArkOAuthError", "error", "description", "status", "endpoint", "errorUri", "body", "ArkTokenError", "claim", "ArkCallbackError", "ArkNetworkError", "ArkLoginRequiredError", "ArkPopupError", "reason", "ArkAccessDeniedReasons", "ACCOUNT_SWITCH_DEFAULTS", "localOrDefault", "url", "fallback", "home", "candidate", "normalizeAccountSwitch", "options", "merged", "key", "value", "ArkConfigError", "ArkChallengeProperties", "returnTo", "loginHint", "prompt", "evaluateAccess", "onEvaluateAccess", "claims", "arkClaims", "tokens", "required", "c", "allowedByConfiguration", "describeDenial", "reason", "first", "names", "name", "DEFAULT_SCOPES", "DEFAULT_REDIRECT_PATH", "DEFAULT_POST_LOGOUT_PATH", "isLoopback", "url", "parseAbsolute", "value", "setting", "ArkConfigError", "checkRedirect", "text", "normalizeOrigins", "list", "normalizeConfig", "options", "authority", "authServerUrl", "tenantId", "clientId", "clientSecret", "privateKeyJwt", "tokenEndpointAuthMethod", "usePar", "redirectUri", "postLogoutRedirectUri", "scopes", "responseMode", "prompt", "acrValues", "extraAuthorizationParams", "storage", "automaticRefresh", "refreshBeforeSeconds", "apiOrigins", "syncTabs", "accountSwitch", "onEvaluateAccess", "onRedirectCallback", "navigate", "redirect", "popup", "transactionTtlSeconds", "clockToleranceSeconds", "requireHttps", "requireTokenHashes", "idTokenSigningAlgorithms", "timeoutMs", "metadataTtlMs", "jwksTtlMs", "jwksMinRefreshIntervalMs", "fetchImpl", "resolvedAuthority", "authorityUrl", "normalizeAccountSwitch", "DEFAULT_TIMEOUT_MS", "timeoutSignal", "signal", "timeoutMs", "timeout", "controller", "forward", "source", "readBody", "response", "text", "type", "trimmed", "currentOrigin", "describeFetchFailure", "method", "url", "cause", "origin", "request", "options", "form", "headers", "cache", "fetchImpl", "ArkNetworkError", "init", "body", "key", "value", "ArkOAuthError", "getJson", "postForm", "status", "postFormNoCors", "DEFAULT_TTL_MS", "discoveryUrls", "authority", "base", "url", "path", "MetadataResolver", "#authority", "#ttlMs", "#http", "#entry", "ttlMs", "http", "force", "hit", "entry", "#fetch", "metadata", "error", "primary", "fallback", "options", "getJson", "ArkOAuthError", "ArkConfigError", "webCrypto", "c", "ArkConfigError", "subtle", "s", "encoder", "decoder", "toBytes", "input", "base64UrlEncode", "bytes", "binary", "i", "base64UrlDecode", "value", "normalized", "padded", "cause", "ArkTokenError", "base64UrlDecodeToString", "randomToken", "buffer", "digest", "hash", "sha256", "leftHalfHash", "full", "constantTimeEqual", "a", "b", "x", "y", "diff", "ALGORITHMS", "SUPPORTED_ALGORITHMS", "hashForAlgorithm", "alg", "isObject", "value", "decodeJwt", "token", "ArkTokenError", "parts", "header", "payload", "base64UrlDecodeToString", "cause", "base64UrlDecode", "importVerifyKey", "jwk", "spec", "material", "subtle", "verifySignature", "decoded", "algorithms", "key", "allowed", "cryptoKey", "validateClaims", "options", "issuer", "audience", "subject", "nonce", "maxAgeSeconds", "clockToleranceSeconds", "requireExp", "requireIat", "now", "fail", "message", "claim", "auds", "a", "validateTokenHashes", "accessToken", "code", "required", "hash", "present", "leftHalfHash", "verifyJwt", "jwks", "KTY_FOR_ALG", "MAX_REMEMBERED_MISSES", "JwksCache", "#uri", "#ttlMs", "#cooldownMs", "#http", "#keys", "#fetchedAt", "#forcedAt", "#inFlight", "#missing", "#imported", "jwksUri", "ttlMs", "minRefreshIntervalMs", "http", "force", "stale", "#load", "kid", "alg", "candidates", "#select", "marker", "ArkTokenError", "jwk", "cacheKey", "key", "importVerifyKey", "keys", "wantedKty", "usable", "k", "document", "getJson", "TokenSet", "_TokenSet", "response", "issuedAt", "claims", "now", "leewaySeconds", "wanted", "granted", "s", "decodeJwt", "data", "createCodeVerifier", "randomToken", "codeChallengeFor", "verifier", "base64UrlEncode", "sha256", "createState", "createNonce", "createPkcePair", "codeVerifier", "INITIAL_SNAPSHOT", "ArkStore", "#state", "#listeners", "patch", "next", "key", "listener", "error", "MemoryStorage", "#map", "key", "value", "index", "isStorageLike", "probe", "storage", "resolveStorage", "option", "win", "candidate", "usable", "ArkConfigError", "readJson", "raw", "writeJson", "remove", "keysWithPrefix", "prefix", "found", "count", "i", "withLock", "name", "fn", "win", "locks", "POPUP_MESSAGE_TYPE", "popupChannelName", "authority", "clientId", "openPopupWindow", "win", "width", "height", "screenLeft", "screenTop", "outerWidth", "outerHeight", "left", "top", "features", "popup", "ArkPopupError", "waitForPopupCallback", "state", "channelName", "timeoutMs", "settle", "resolve", "reject", "done", "channel", "closedTimer", "closedGrace", "timeoutTimer", "cleanup", "onMessage", "accept", "data", "event", "Channel", "closed", "error", "relayToOpener", "url", "delivered", "message", "opener", "RESPONSE_PARAMS", "DENIAL_TTL_SECONDS", "RETRY_AFTER_NETWORK_FAILURE_MS", "SPENT_TOKENS_REMEMBERED", "MAX_TIMER_MS", "EVENTS", "now", "instanceCounter", "unref", "handle", "ArkBrowserClient", "#config", "#win", "#metadata", "#jwks", "#store", "ArkStore", "#events", "name", "#id", "#ready", "#storage", "#storageKind", "#txStorage", "#spentStorage", "#prefix", "#tokens", "#derived", "#denial", "#initPromise", "#refreshPromise", "#timer", "#channel", "#detach", "#destroyed", "options", "normalizeConfig", "MetadataResolver", "INITIAL_SNAPSHOT", "listener", "run", "event", "handler", "set", "ArkConfigError", "claims", "held", "c", "scopes", "granted", "s", "#runInit", "handleCallback", "onRedirectCallback", "#ensureReady", "#attachListeners", "#sweepTransactions", "href", "navigate", "to", "result", "#navigate", "error", "#emit", "kind", "#classify", "#restore", "#renewIfNeeded", "#fail", "next", "#takeLogoutTransaction", "#publish", "localOrDefault", "#schedule", "win", "#requireWindow", "config", "metadata", "ArkOAuthError", "redirectUri", "#resolve", "codeVerifier", "codeChallenge", "codeChallengeMethod", "createPkcePair", "state", "createState", "nonce", "createNonce", "prompt", "acrValues", "responseMode", "params", "query", "v", "here", "returnTo", "url", "transaction", "#saveTransaction", "#redirect", "popup", "openPopupWindow", "waiter", "waitForPopupCallback", "popupChannelName", "responseUrl", "#responseParams", "#authorizationError", "#completeSignin", "ArkError", "parsed", "#takeTransaction", "relayToOpener", "#cleanResponseFromUrl", "ArkCallbackError", "constantTimeEqual", "tokens", "#exchangeCode", "arkClaims", "evaluateAccess", "denial", "describeDenial", "ArkAccessDeniedReasons", "#setDenial", "#setTokens", "#revokeQuietly", "#broadcast", "forceRefresh", "#leeway", "#endLocalSession", "#refreshUnderLock", "ArkLoginRequiredError", "withLock", "current", "stored", "#readStoredTokens", "#isSpent", "response", "#tokenRequest", "#markSpent", "TokenSet", "#toTokenSet", "#onRefreshFailure", "ArkTokenError", "untrusted", "#sharedStorage", "target", "own", "input", "init", "rawUrl", "origin", "fetchImpl", "send", "token", "headers", "replayable", "challenge", "renewed", "getJson", "postLogoutRedirectUri", "revoke", "internal", "idTokenHint", "refreshToken", "home", "writeJson", "endpoint", "loginHint", "force", "uri", "JwksCache", "idToken", "accessToken", "code", "maxAge", "subject", "verifyJwt", "cut", "tenantId", "report", "keys", "k", "postForm", "ArkNetworkError", "supportedScopes", "unknown", "methods", "modes", "off", "form", "previous", "merged", "persist", "remove", "data", "readJson", "reason", "broadcast", "hadSession", "md", "postFormNoCors", "renew", "at", "#lead", "delay", "max", "lifetime", "#spentHash", "base64UrlEncode", "sha256", "hash", "entry", "list", "storage", "resolveStorage", "extra", "#publicDenial", "#publicDenialCache", "_hint", "_created", "visible", "value", "wrapped", "key", "limit", "keysWithPrefix", "fromQuery", "fromHash", "pick", "source", "p", "same", "t", "DEFAULT_POST_LOGOUT_PATH", "clean", "rest", "relative", "PopState", "detail", "type", "Channel", "#onTabMessage", "doc", "onVisible", "#adoptStoredTokens", "message", "createArkClient", "PALETTE", "el", "doc", "tag", "className", "text", "node", "css", "styles", "key", "value", "renderAccessDenied", "container", "client", "options", "config", "denial", "appName", "account", "dark", "c", "styled", "root", "card", "lede", "actions", "switchButton", "signOutButton", "foot", "link", "version", "VERSION", "p", "button"]
|
|
7
|
+
}
|