@atol-sh/js 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/claims/claims.ts","../src/oidc/oidc.ts","../src/crypto/base64url.ts","../src/oidc/token-recovery.ts","../src/oidc/silent-renew.ts","../src/oidc/cross-tab-lock.ts","../src/token/token-broadcast.ts","../src/dpop/dpop.ts","../src/verify/verify.ts","../src/crypto/kek-vault.ts","../src/crypto/encryption.ts","../src/client/browser-auth.ts","../src/permissions/permissions.ts"],"names":["RecoveryAction"],"mappings":";;;;;;AAOO,SAAS,cAAc,KAAA,EAAyB;AACrD,EAAA,MAAM,OAAA,GAAU,iBAAiB,KAAK,CAAA;AAEtC,EAAA,MAAM,GAAA,GAAM,CAAC,GAAA,KAAwB;AACnC,IAAA,MAAM,CAAA,GAAI,QAAQ,GAAG,CAAA;AACrB,IAAA,OAAO,OAAO,CAAA,KAAM,QAAA,GAAW,CAAA,GAAI,EAAA;AAAA,EACrC,CAAA;AAEA,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,IAAI,KAAK,CAAA;AAAA,IACb,KAAA,EAAO,IAAI,OAAO,CAAA;AAAA,IAClB,aAAA,EAAe,OAAA,CAAQ,gBAAgB,CAAA,KAAM,IAAA;AAAA,IAC7C,IAAA,EAAM,IAAI,MAAM,CAAA;AAAA,IAChB,KAAA,EAAO,IAAI,aAAa,CAAA;AAAA,IACxB,IAAA,EAAM,IAAI,WAAW,CAAA;AAAA,IACrB,KAAA,EAAO,KAAA,CAAM,OAAA,CAAQ,OAAA,CAAQ,YAAY,CAAC,CAAA,GAAI,OAAA,CAAQ,YAAY,CAAA,GAAgB,EAAC;AAAA,IACnF,UAAA,EAAY,IAAI,kBAAkB,CAAA;AAAA,IAClC,WAAA,EAAa,OAAA,CAAQ,mBAAmB,CAAA,KAAM;AAAA,GAChD;AACF;AAGO,SAAS,iBAAiB,KAAA,EAAwC;AAC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I,CAAA,EAAG,CAAA,GAAI,MAAA,CAAO,QAAQ,CAAA,EAAA,EAAK;AACtC,IAAA,MAAM,GAAA,GAAM,CAAA,EAAG,MAAA,CAAO,CAAC,CAAA,CAAE,MAAM,CAAA,CAAA,EAAI,MAAA,CAAO,CAAC,CAAA,CAAE,QAAQ,CAAA,CAAA;AAGrD,IAAA,WAAA,CAAY,IAAI,GAAA,EAAK,OAAA,CAAQ,CAAC,CAAA,EAAG,YAAY,IAAI,CAAA;AAAA,EACnD;AAEA,EAAA,OAAO,WAAA;AACT;AAGO,SAAS,aAAA,CAAc,QAAgB,QAAA,EAA0B;AACtE,EAAA,OAAO,CAAA,EAAG,MAAM,CAAA,CAAA,EAAI,QAAQ,CAAA,CAAA;AAC9B","file":"index.js","sourcesContent":["import type { AtolUser } from './types'\n\n/**\n * Parse Atol custom claims from a JWT token (ID token or access token).\n * Decodes the payload without verifying the signature — verification is\n * done by the OIDC library. This just extracts the user-facing fields.\n */\nexport function parseAtolUser(token: string): AtolUser {\n const payload = decodeJWTPayload(token)\n\n const str = (key: string): string => {\n const v = payload[key]\n return typeof v === 'string' ? v : ''\n }\n\n return {\n id: str('sub'),\n email: str('email'),\n emailVerified: payload['email_verified'] === true,\n name: str('name'),\n orgId: str('atol:org_id'),\n plan: str('atol:plan'),\n roles: Array.isArray(payload['atol:roles']) ? payload['atol:roles'] as string[] : [],\n authMethod: str('atol:auth_method'),\n mfaVerified: payload['atol:mfa_verified'] === true,\n }\n}\n\n/** Decode a JWT payload (the middle base64url segment) to a plain object. */\nexport function decodeJWTPayload(token: string): Record<string, unknown> {\n const parts = token.split('.')\n if (parts.length !== 3) {\n throw new Error('Invalid JWT: expected 3 parts')\n }\n\n const base64 = parts[1]\n .replace(/-/g, '+')\n .replace(/_/g, '/')\n\n const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4)\n const json = atob(padded)\n return JSON.parse(json)\n}\n\n/**\n * Parse the `exp` claim from a JWT without verifying the signature.\n * Returns the absolute expiry in milliseconds, or null when the token is\n * malformed or carries no numeric `exp`. Single source of truth for all\n * expiry math in the SDK (renew scheduling, stale checks, broadcasts).\n */\nexport function getTokenExpiry(token: string): number | null {\n try {\n const payload = decodeJWTPayload(token)\n return typeof payload.exp === 'number' ? payload.exp * 1000 : null\n } catch {\n return null\n }\n}\n","import {\n InMemoryWebStorage,\n User,\n UserManager,\n WebStorageStateStore,\n type IdTokenClaims,\n type UserManagerSettings,\n} from 'oidc-client-ts'\nimport { decodeJWTPayload, getTokenExpiry } from '../claims/claims'\nimport type { TokenResponse } from './silent-renew'\n\n/**\n * Create an oidc-client-ts UserManager configured for Atol.\n *\n * Storage policy:\n * - `userStore` is IN-MEMORY. The full User object (access token, ID\n * token, and -- when `useRefreshTokens` is on -- the refresh token)\n * never touches sessionStorage or localStorage, so an XSS payload\n * cannot read persisted credentials after the fact. The cost is that\n * a page reload starts with an empty store; the provider recovers by\n * attempting a silent renew against the IdP session cookie.\n * - `stateStore` stays in sessionStorage. It only holds the OIDC\n * state/PKCE verifier, which must survive the same-tab redirect to\n * the Atol login page and back, and is worthless to an attacker\n * after the code exchange completes.\n */\nexport function createUserManager(\n authority: string,\n clientId: string,\n redirectUri: string,\n scope: string,\n audience?: string,\n): UserManager {\n // sessionStorage for PKCE state ONLY -- survives same-tab redirects to\n // the Atol login page and back. Guard for SSR: a \"use client\" component\n // is still rendered on the server for initial HTML, where `window` is\n // undefined. Fall back to in-memory there (the server never performs the\n // redirect dance, so the state store is unused until client hydration).\n const stateStorage =\n typeof window !== 'undefined' ? window.sessionStorage : new InMemoryWebStorage()\n\n const settings: UserManagerSettings = {\n authority,\n client_id: clientId,\n redirect_uri: redirectUri,\n response_type: 'code',\n scope,\n automaticSilentRenew: false,\n // In-memory only -- tokens must never persist to Web Storage.\n userStore: new WebStorageStateStore({ store: new InMemoryWebStorage() }),\n stateStore: new WebStorageStateStore({ store: stateStorage }),\n extraQueryParams: audience ? { audience } : undefined,\n }\n\n return new UserManager(settings)\n}\n\n/** Extract the access token from an oidc-client-ts User. */\nexport function getAccessToken(user: User | null): string | undefined {\n return user?.access_token ?? undefined\n}\n\n/** Extract the ID token from an oidc-client-ts User. */\nexport function getIdToken(user: User | null): string | undefined {\n return user?.id_token ?? undefined\n}\n\n/**\n * Build an oidc-client-ts User from a raw /auth/token response. Used to\n * write renewed tokens back into the UserManager store so `mgr.getUser()`\n * and React state never disagree (e.g. a rotated-away refresh token\n * lingering in the store).\n *\n * `expires_at` prefers the access token's own `exp` claim; falls back to\n * `expires_in` relative to now when the token is opaque.\n */\nexport function userFromTokenResponse(tokens: TokenResponse): User {\n const expMs = getTokenExpiry(tokens.access_token)\n const expiresAt =\n expMs !== null\n ? Math.floor(expMs / 1000)\n : Math.floor(Date.now() / 1000) + (tokens.expires_in ?? 0)\n\n let profile: Record<string, unknown> = {}\n if (tokens.id_token) {\n try {\n profile = decodeJWTPayload(tokens.id_token)\n } catch {\n // Malformed ID token payload -- store the tokens anyway; claims\n // parsing errors surface separately via parseAtolUser.\n }\n }\n\n return new User({\n access_token: tokens.access_token,\n id_token: tokens.id_token,\n refresh_token: tokens.refresh_token,\n token_type: tokens.token_type,\n scope: tokens.scope,\n expires_at: expiresAt,\n profile: profile as IdTokenClaims,\n })\n}\n","/**\n * Shared base64 / base64url helpers.\n *\n * Single source of truth for byte <-> base64 conversion across the SDK\n * (encryption, KEK vault, PKCE, DPoP). The decoder accepts both the\n * standard \"+/\" alphabet and the URL-safe \"-_\" alphabet, with or without\n * padding, because the Atol server emits unpadded base64url while older\n * tooling may emit padded standard base64.\n */\n\n/** Encode raw bytes as unpadded base64url. */\nexport function bytesToBase64Url(bytes: Uint8Array): string {\n let binary = ''\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i])\n }\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\n/** Encode a UTF-8 string as unpadded base64url. */\nexport function stringToBase64Url(input: string): string {\n return bytesToBase64Url(new TextEncoder().encode(input))\n}\n\n/**\n * Decode a base64 or base64url string (padded or not) into raw bytes.\n *\n * This is the trust boundary for attacker-influenceable inputs (the KEK\n * from the URL fragment, the wrapped DEK from a token claim, DPoP\n * signatures). Validate the alphabet and reject impossible lengths\n * explicitly so behavior is deterministic across engines instead of\n * relying on the historically-lenient browser `atob` (which silently\n * strips whitespace and tolerates trailing bits on some implementations).\n */\nexport function base64ToBytes(b64: string): Uint8Array {\n // Normalize to the standard alphabet and drop any trailing padding so we\n // can validate the payload alphabet and re-pad canonically.\n const std = b64.replace(/-/g, '+').replace(/_/g, '/').replace(/=+$/, '')\n if (!/^[A-Za-z0-9+/]*$/.test(std)) {\n throw new Error('base64ToBytes: input contains non-base64 characters')\n }\n // length % 4 === 1 is not a producible base64 length -- reject rather\n // than let re-padding mask a corrupted value.\n if (std.length % 4 === 1) {\n throw new Error('base64ToBytes: invalid base64 length')\n }\n const padded = std + '='.repeat((4 - (std.length % 4)) % 4)\n const binary = atob(padded)\n const bytes = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i)\n }\n return bytes\n}\n","/**\n * Token renewal error classification.\n *\n * The provider's `renewOnce` has three possible reactions to a failed\n * renewal: retry (transient), force re-auth (terminal auth failure,\n * local state is out of sync with the server), or surface (programmer\n * error the caller should see). Spreading those decisions across every\n * catch block drifts; centralizing them here keeps the contract auditable.\n *\n * The classification is deliberately conservative: anything we don't\n * recognize surfaces, rather than silently forcing re-auth or looping.\n */\n\n/**\n * OAuth 2.0 / OIDC protocol error surfaced by the authorization server.\n * Carries the machine-readable `error` code from the token / authorize\n * endpoint response so the recovery layer can act on it precisely.\n */\nexport class OAuthProtocolError extends Error {\n code: string\n description?: string\n constructor(code: string, description?: string) {\n super(description ? `${code}: ${description}` : code)\n this.code = code\n this.description = description\n this.name = \"OAuthProtocolError\"\n }\n}\n\n/**\n * Re-auth-class protocol errors -- login_required, consent_required,\n * interaction_required. Subclass of OAuthProtocolError so existing\n * `instanceof LoginRequiredError` checks keep working AND `instanceof\n * OAuthProtocolError` matches the broader classification.\n */\nexport class LoginRequiredError extends OAuthProtocolError {\n constructor(description?: string) {\n super(\"login_required\", description)\n this.name = \"LoginRequiredError\"\n }\n}\n\n/**\n * Transport / network layer failure -- `fetch` rejected, DNS miss, TLS\n * error, CORS block. Surfaced as retry because the authorization server\n * never saw the request.\n */\nexport class NetworkError extends Error {\n cause?: unknown\n constructor(message: string, cause?: unknown) {\n super(message)\n this.cause = cause\n this.name = \"NetworkError\"\n }\n}\n\n/**\n * What the caller should do when a renewal throws.\n *\n * Retry -- transient (network blip, 5xx). Backoff and try again.\n * ForceReauth -- terminal (stale refresh token, revoked client, session\n * gone). Wipe local state and return the user to the\n * signed-out screen. Don't loop.\n * Surface -- programmer error (invalid_scope, unsupported_grant_type).\n * Throw to the caller so they can see it during dev.\n */\nexport enum RecoveryAction {\n Retry = \"retry\",\n ForceReauth = \"force_reauth\",\n Surface = \"surface\",\n}\n\n/**\n * Classify a renewal error into a recovery action. The full mapping,\n * grouped by cause:\n *\n * Terminal auth (ForceReauth):\n * invalid_grant refresh token expired / revoked / rotated-reused\n * invalid_request stale or malformed token at /auth/token\n * (also what the server returns after a lost HMAC secret)\n * invalid_client client was deleted / secret changed server-side\n * unauthorized_client client no longer permitted this grant\n * login_required prompt=none could not silently re-auth\n * consent_required user consent missing\n * interaction_required user action required\n *\n * Transient (Retry):\n * server_error 500-class error on the authz server\n * temporarily_unavailable documented OAuth retry signal\n * NetworkError fetch rejection, DNS, TLS, CORS\n *\n * Programmer error (Surface):\n * invalid_scope misconfigured scope list\n * unsupported_grant_type wrong grant wiring\n * unsupported_response_type\n * Unknown OAuth codes -- conservative default\n * Unknown Error subclass -- ditto\n */\nexport function classifyRenewalError(err: unknown): RecoveryAction {\n if (err instanceof OAuthProtocolError) {\n switch (err.code) {\n case \"invalid_grant\":\n case \"invalid_request\":\n case \"invalid_client\":\n case \"unauthorized_client\":\n case \"login_required\":\n case \"consent_required\":\n case \"interaction_required\":\n return RecoveryAction.ForceReauth\n\n case \"server_error\":\n case \"temporarily_unavailable\":\n return RecoveryAction.Retry\n\n case \"invalid_scope\":\n case \"unsupported_grant_type\":\n case \"unsupported_response_type\":\n return RecoveryAction.Surface\n\n default:\n return RecoveryAction.Surface\n }\n }\n\n if (err instanceof NetworkError) return RecoveryAction.Retry\n\n // Fetch failures surface as TypeError on most runtimes\n // (\"Failed to fetch\" / \"NetworkError when attempting to fetch resource\").\n if (err instanceof TypeError) return RecoveryAction.Retry\n\n return RecoveryAction.Surface\n}\n\n/**\n * Exponential backoff with full jitter. Cheap, deterministic test\n * surface -- callers can swap out `Math.random` via the seed arg.\n *\n * attempt 0 -> [0, 500) ms\n * attempt 1 -> [0, 1000) ms\n * attempt 2 -> [0, 2000) ms\n * attempt 3 -> [0, 4000) ms\n * attempt N -> [0, 30_000) ms (capped)\n *\n * The cap matters: without it an always-failing transient error fires a\n * renewal an hour later and the user thinks the app is frozen.\n */\nexport function backoffDelay(attempt: number, rand: () => number = Math.random): number {\n const base = 500 // ms\n const cap = 30_000 // ms\n const exp = Math.min(cap, base * Math.pow(2, Math.max(0, attempt)))\n return Math.floor(rand() * exp)\n}\n","/**\n * Silent token renewal via web_message response mode.\n *\n * Opens a hidden iframe to the authorization endpoint with response_mode=web_message\n * and prompt=none. The server validates the session cookie and returns an HTML page\n * that sends the authorization response via postMessage. No SPA loading in the iframe.\n *\n * Spec: draft-sakimura-oauth-wmrm-01\n */\n\nimport { bytesToBase64Url } from '../crypto/base64url'\nimport type { DPoPProofOptions } from '../dpop/dpop'\nimport {\n LoginRequiredError,\n NetworkError,\n OAuthProtocolError,\n} from './token-recovery'\n\n// Re-export for backward compatibility -- the browser auth client and the\n// React provider import LoginRequiredError directly from this module.\nexport { LoginRequiredError } from './token-recovery'\n\ninterface AuthorizationResponse {\n type: 'authorization_response'\n response: {\n code?: string\n state?: string\n error?: string\n error_description?: string\n }\n}\n\ninterface SilentRenewOptions {\n authority: string\n clientId: string\n redirectUri: string\n scope: string\n audience?: string\n /**\n * When true, asks the server to include `atol:wrapped_dek` on the renewed\n * ID token. The KEK is NOT re-delivered (the password isn't available\n * during silent renew), but carrying the wrapped DEK claim keeps it\n * consistently present across every token in the session, so app code\n * that re-reads it after a renewal (tab rehydrate, multi-tab sync) finds\n * the same DEK material it saw at login.\n */\n deriveEncryptionKey?: boolean\n /**\n * Milliseconds to wait for the iframe's postMessage before rejecting.\n * Defaults to 60s. An earlier 10s value was too tight on\n * slow networks and caused the \"return stale token\" fallback to fire\n * unnecessarily, producing `token is expired (exp)` errors on the server.\n */\n timeoutMs?: number\n}\n\n/** Default iframe timeout for silent authorization. */\nexport const DEFAULT_AUTHORIZE_TIMEOUT_MS = 60_000\n\n/** Default retry count for silent authorize on transient errors. */\nexport const DEFAULT_SILENT_RENEW_RETRY_COUNT = 3\n\n\n/**\n * Perform a silent authorization request via web_message.\n * Returns the authorization code + state, or throws on error.\n */\nexport async function silentAuthorize(\n opts: SilentRenewOptions,\n): Promise<{ code: string; state: string; codeVerifier: string }> {\n const timeout = opts.timeoutMs ?? DEFAULT_AUTHORIZE_TIMEOUT_MS\n\n // Generate PKCE challenge.\n const verifier = generateCodeVerifier()\n const challenge = await generateCodeChallenge(verifier)\n\n // Generate state for CSRF.\n const state = generateRandomString(32)\n\n // Build the authorize URL with response_mode=web_message.\n const params = new URLSearchParams({\n client_id: opts.clientId,\n redirect_uri: opts.redirectUri,\n response_type: 'code',\n response_mode: 'web_message',\n scope: opts.scope,\n state,\n prompt: 'none',\n code_challenge: challenge,\n code_challenge_method: 'S256',\n })\n if (opts.audience) {\n params.set('audience', opts.audience)\n }\n if (opts.deriveEncryptionKey) {\n // The server re-emits the stored wrapped DEK on silent renew when this\n // flag is set, without re-deriving the KEK (no password is available).\n // Keeps the `atol:wrapped_dek` claim stable across every token.\n params.set('derive_encryption_key', 'true')\n }\n\n const authorizeUrl = `${opts.authority}/auth/authorize?${params.toString()}`\n const expectedOrigin = new URL(opts.authority).origin\n\n return new Promise<{ code: string; state: string; codeVerifier: string }>((resolve, reject) => {\n let iframe: HTMLIFrameElement | null = null\n let timer: ReturnType<typeof setTimeout> | null = null\n\n function cleanup() {\n if (timer) clearTimeout(timer)\n window.removeEventListener('message', onMessage)\n if (iframe && iframe.parentNode) {\n iframe.parentNode.removeChild(iframe)\n }\n }\n\n function onMessage(event: MessageEvent) {\n // Verify origin matches the authorization server.\n if (event.origin !== expectedOrigin) return\n\n const data = event.data as AuthorizationResponse\n if (!data || data.type !== 'authorization_response') return\n\n cleanup()\n\n const resp = data.response\n if (resp.error) {\n // Map the authorize-endpoint error code to a typed exception so\n // the recovery layer can classify it. login_required /\n // consent_required / interaction_required all mean \"session is\n // gone\", which is a subclass of OAuthProtocolError -- see\n // token-recovery.ts.\n const code = resp.error\n if (\n code === \"login_required\" ||\n code === \"consent_required\" ||\n code === \"interaction_required\"\n ) {\n reject(new LoginRequiredError(resp.error_description || code))\n } else {\n reject(new OAuthProtocolError(code, resp.error_description))\n }\n return\n }\n\n if (!resp.code || !resp.state) {\n reject(new Error('missing code or state in authorization response'))\n return\n }\n\n if (resp.state !== state) {\n reject(new Error('state mismatch'))\n return\n }\n\n resolve({ code: resp.code, state: resp.state, codeVerifier: verifier })\n }\n\n window.addEventListener('message', onMessage)\n\n // Timeout.\n timer = setTimeout(() => {\n cleanup()\n reject(new Error('silent renew timed out'))\n }, timeout)\n\n // Create hidden iframe.\n iframe = document.createElement('iframe')\n iframe.style.display = 'none'\n iframe.setAttribute('aria-hidden', 'true')\n iframe.src = authorizeUrl\n document.body.appendChild(iframe)\n })\n}\n\n/**\n * silentAuthorize with bounded retry on transient errors (default 3\n * attempts). `login_required` and similar\n * re-auth errors are fatal and bypass the retry loop.\n */\nexport async function silentAuthorizeWithRetry(\n opts: SilentRenewOptions,\n retries: number = DEFAULT_SILENT_RENEW_RETRY_COUNT,\n): Promise<{ code: string; state: string; codeVerifier: string }> {\n let lastErr: unknown\n for (let attempt = 0; attempt < retries; attempt++) {\n try {\n return await silentAuthorize(opts)\n } catch (err) {\n lastErr = err\n if (err instanceof LoginRequiredError) throw err\n // Exponential-ish backoff: 200ms, 400ms, 800ms. Cheap to wait; prevents\n // hammering the authorize endpoint when the network is flapping.\n if (attempt < retries - 1) {\n await new Promise((r) => setTimeout(r, 200 * 2 ** attempt))\n }\n }\n }\n throw lastErr instanceof Error\n ? lastErr\n : new Error(\"silent renew failed after retries\")\n}\n\n/** Shape of a successful /auth/token response. */\nexport interface TokenResponse {\n access_token: string\n id_token?: string\n refresh_token?: string\n token_type: string\n expires_in: number\n scope?: string\n}\n\n/**\n * Optional per-request DPoP signer. When provided, token-endpoint calls\n * attach a signed proof header (RFC 9449). When omitted, calls run Bearer-\n * only and the server issues un-bound tokens. The provider wires this\n * through from its DPoPKeyManager when `useDPoP: true`.\n */\nexport interface DPoPSigner {\n signProof(method: string, url: string, options?: DPoPProofOptions): Promise<string>\n}\n\n/**\n * POST to the token endpoint with an optional DPoP proof, transparently\n * handling the RFC 9449 §8 server-nonce challenge: if the server replies\n * `use_dpop_nonce` with a `DPoP-Nonce` header, re-sign the proof with the\n * nonce and retry once. Fetch rejections are wrapped as NetworkError.\n */\nasync function tokenEndpointPost(\n url: string,\n body: string,\n op: string,\n dpop?: DPoPSigner,\n): Promise<Response> {\n const send = async (nonce?: string): Promise<Response> => {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n }\n if (dpop) {\n headers['DPoP'] = await dpop.signProof('POST', url, nonce ? { nonce } : undefined)\n }\n try {\n return await fetch(url, { method: 'POST', headers, body })\n } catch (err) {\n throw new NetworkError(`${op} network error`, err)\n }\n }\n\n let resp = await send()\n if (dpop && (resp.status === 400 || resp.status === 401)) {\n const nonce = resp.headers.get('DPoP-Nonce')\n if (nonce && (await isUseDpopNonce(resp))) {\n resp = await send(nonce)\n }\n }\n return resp\n}\n\n/** Whether a non-2xx token response is the RFC 9449 nonce challenge. */\nasync function isUseDpopNonce(resp: Response): Promise<boolean> {\n const text = await resp.clone().text().catch(() => '')\n if (!text) return false\n try {\n return (JSON.parse(text) as { error?: string }).error === 'use_dpop_nonce'\n } catch {\n return false\n }\n}\n\n/**\n * Exchange an authorization code for tokens via the token endpoint.\n */\nexport async function exchangeCode(\n authority: string,\n clientId: string,\n code: string,\n redirectUri: string,\n codeVerifier: string,\n dpop?: DPoPSigner,\n): Promise<TokenResponse> {\n const url = `${authority}/auth/token`\n const body = new URLSearchParams({\n grant_type: 'authorization_code',\n client_id: clientId,\n code,\n redirect_uri: redirectUri,\n code_verifier: codeVerifier,\n }).toString()\n\n const resp = await tokenEndpointPost(url, body, 'token exchange', dpop)\n if (!resp.ok) {\n throw await oauthErrorFromResponse(resp, 'token exchange')\n }\n\n return resp.json()\n}\n\n/**\n * Renew tokens using a refresh token grant (RFC 6749 §6). This is the\n * `useRefreshTokens: true` path -- a direct POST to the token\n * endpoint, no iframe, no cross-site cookies. Works under Chrome's third-\n * party cookie phaseout, Safari ITP, and Firefox ETP without the user\n * needing to grant Storage Access.\n *\n * The server may rotate the refresh token on each use (RFC 6749 §10.4);\n * callers must read `refresh_token` from the response and replace their\n * stored copy before the next renew.\n *\n * An expired or revoked refresh token surfaces as `LoginRequiredError` so\n * the caller can force a re-auth, matching the semantics of the iframe\n * path for login_required.\n */\nexport async function refreshTokenGrant(\n authority: string,\n clientId: string,\n refreshToken: string,\n scope?: string,\n audience?: string,\n dpop?: DPoPSigner,\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: clientId,\n refresh_token: refreshToken,\n })\n if (scope) body.set('scope', scope)\n if (audience) body.set('audience', audience)\n\n const url = `${authority}/auth/token`\n const resp = await tokenEndpointPost(url, body.toString(), 'refresh token grant', dpop)\n if (!resp.ok) {\n throw await oauthErrorFromResponse(resp, 'refresh token grant')\n }\n\n return resp.json()\n}\n\n/**\n * Revoke a token via the RFC 7009 revocation endpoint. Used on logout to\n * proactively invalidate the refresh token server-side rather than waiting\n * for it to expire. A best-effort call: revocation failures are surfaced\n * to the caller, which typically swallows them (the RP-initiated logout\n * still kills the session cookie).\n *\n * `tokenTypeHint` defaults to `refresh_token` -- the token most worth\n * revoking, since it can mint new access tokens.\n */\nexport async function revokeToken(\n authority: string,\n clientId: string,\n token: string,\n tokenTypeHint: 'refresh_token' | 'access_token' = 'refresh_token',\n): Promise<void> {\n const url = `${authority}/auth/revoke`\n const body = new URLSearchParams({\n client_id: clientId,\n token,\n token_type_hint: tokenTypeHint,\n }).toString()\n\n let resp: Response\n try {\n resp = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body,\n })\n } catch (err) {\n throw new NetworkError('token revocation network error', err)\n }\n // RFC 7009 §2.2: the server responds 200 even for an unknown token. A\n // non-2xx is a real server-side failure worth surfacing.\n if (!resp.ok) {\n throw new Error(`token revocation failed: HTTP ${resp.status}`)\n }\n}\n\n/**\n * Turn a non-2xx /auth/token response into the typed exception the\n * recovery layer expects. The OAuth error body is parsed; if the code\n * falls into the re-auth bucket we surface a LoginRequiredError so both\n * old and new classification paths agree. 5xx with no parseable body\n * becomes an OAuthProtocolError(\"server_error\", ...) so backoff kicks\n * in instead of forcing a sign-out.\n */\nasync function oauthErrorFromResponse(resp: Response, op: string): Promise<Error> {\n const text = await resp.text().catch(() => '')\n let code = ''\n let description: string | undefined\n if (text) {\n try {\n const parsed = JSON.parse(text) as { error?: string; error_description?: string }\n code = parsed.error ?? ''\n description = parsed.error_description\n } catch {\n // Non-JSON body; leave code blank so the status-based fallback fires.\n }\n }\n // 429 Too Many Requests -- the endpoint is throttling us, not refusing\n // the credential. Treat as transient so the backoff path retries rather\n // than forcing an unnecessary sign-out under load.\n if (resp.status === 429) {\n return new OAuthProtocolError(\n 'temporarily_unavailable',\n `${op} rate limited (429)`,\n )\n }\n if (!code) {\n // 5xx without a structured body -- treat as transient.\n if (resp.status >= 500) {\n return new OAuthProtocolError(\n 'server_error',\n `${op} failed: ${resp.status} ${text.slice(0, 200)}`,\n )\n }\n // Other non-2xx without a code -- surface the raw response.\n return new Error(`${op} failed: ${resp.status} ${text.slice(0, 200)}`)\n }\n if (\n code === 'login_required' ||\n code === 'consent_required' ||\n code === 'interaction_required'\n ) {\n return new LoginRequiredError(description ?? code)\n }\n return new OAuthProtocolError(code, description)\n}\n\n// --- PKCE helpers ---\n\nfunction generateRandomString(length: number): string {\n const array = new Uint8Array(length)\n crypto.getRandomValues(array)\n return Array.from(array, (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\nfunction generateCodeVerifier(): string {\n const array = new Uint8Array(32)\n crypto.getRandomValues(array)\n return bytesToBase64Url(array)\n}\n\nasync function generateCodeChallenge(verifier: string): Promise<string> {\n const encoder = new TextEncoder()\n const data = encoder.encode(verifier)\n const digest = await crypto.subtle.digest('SHA-256', data)\n return bytesToBase64Url(new Uint8Array(digest))\n}\n","/**\n * Cross-tab mutual exclusion for renewal work.\n *\n * Uses the native Web Locks API (navigator.locks) for cross-tab mutual\n * exclusion. A leader tab acquires the lock and runs the critical\n * section; followers block until the leader releases, then re-enter the lock\n * themselves (at which point they typically find the state the leader\n * produced and short-circuit).\n *\n * In environments without `navigator.locks` (jsdom under vitest, old Safari,\n * workers with no locks API) we fall through to running `fn` directly. That\n * matches the existing intra-tab dedup semantics -- no regression, just no\n * cross-tab guarantee.\n */\n\ninterface LockManagerShape {\n request<T>(\n name: string,\n options: { mode?: \"exclusive\" | \"shared\"; ifAvailable?: boolean; steal?: boolean; signal?: AbortSignal },\n callback: (lock: unknown) => Promise<T>,\n ): Promise<T>\n}\n\nfunction getLockManager(): LockManagerShape | null {\n if (typeof navigator === \"undefined\") return null\n const mgr = (navigator as Navigator & { locks?: LockManagerShape }).locks\n return mgr && typeof mgr.request === \"function\" ? mgr : null\n}\n\n/**\n * Run `fn` under a cross-tab exclusive lock identified by `name`.\n *\n * The `ms` argument bounds the total wait time for acquiring the lock; if\n * the leader stalls beyond this, we abort and fall through to running `fn`\n * directly rather than deadlocking the caller. A 5s default -- leaders that\n * stall longer are almost certainly broken, and a\n * second POST to /auth/token is preferable to a forever-hung tab.\n *\n * The lock is per-origin (Web Locks is same-origin by construction), so the\n * lock name should include the authority + clientId to avoid cross-tenant\n * contention when multiple atol apps share an origin.\n */\nexport async function withTabLock<T>(\n name: string,\n ms: number,\n fn: () => Promise<T>,\n): Promise<T> {\n const mgr = getLockManager()\n if (!mgr) return fn()\n\n const ac = new AbortController()\n const abort = setTimeout(() => ac.abort(), ms)\n try {\n return await mgr.request(name, { mode: \"exclusive\", signal: ac.signal }, async () => fn())\n } catch (err) {\n // AbortError after the timeout -- degrade to direct execution. Any\n // other error from inside fn propagates to the caller via this catch,\n // so re-throw non-timeout errors explicitly.\n if (err instanceof DOMException && err.name === \"AbortError\") {\n return fn()\n }\n throw err\n } finally {\n clearTimeout(abort)\n }\n}\n\n/** Whether the current environment supports cross-tab locks. Useful for tests. */\nexport function hasTabLockSupport(): boolean {\n return getLockManager() !== null\n}\n","/**\n * Cross-tab token rotation broadcast.\n *\n * When the leader tab rotates tokens, it publishes the new access/id/refresh\n * tokens to a shared `BroadcastChannel`. Follower tabs subscribe to the\n * channel and apply the rotated tokens without running their own renewal,\n * so concurrent open tabs collapse to a single /auth/token POST per cycle.\n *\n * Refresh tokens are deliberately broadcast because the server rotates them\n * on every use (RFC 6749 §10.4). A follower whose refresh token is stale\n * will hit `invalid_grant` on its next renew -- which, under the server's\n * refresh-token reuse detection, invalidates the whole family and signs every\n * tab out. Sharing\n * the rotated value prevents that chain reaction.\n *\n * The channel stays same-origin by construction. If `BroadcastChannel` is\n * unavailable (old Safari, some sandboxed iframes), the helper degrades to\n * a no-op: publish swallows, subscribe never fires. That's a graceful\n * regression to per-tab behavior, not a failure.\n */\n\nexport interface TokenRotatedMessage {\n type: \"token-rotated\"\n /** Access token sent as the Authorization header; always present. */\n accessToken: string\n /** ID token if one was issued on this grant. */\n idToken?: string\n /** Rotated refresh token if the server returned one. */\n refreshToken?: string\n /** ms-since-epoch at which the access token expires; followers compute their own timers off this. */\n expiresAt: number\n /** ms-since-epoch when the message was sent. Lets followers discard stale broadcasts. */\n sentAt: number\n}\n\nexport interface SessionExpiredMessage {\n type: \"session-expired\"\n sentAt: number\n}\n\nexport type BroadcastMessage = TokenRotatedMessage | SessionExpiredMessage\n\nexport interface TokenBroadcast {\n publish(message: BroadcastMessage): void\n subscribe(handler: (message: BroadcastMessage) => void): () => void\n close(): void\n}\n\ninterface BroadcastChannelShape {\n postMessage(message: unknown): void\n addEventListener(\n type: \"message\",\n handler: (event: { data: unknown }) => void,\n ): void\n removeEventListener(\n type: \"message\",\n handler: (event: { data: unknown }) => void,\n ): void\n close(): void\n}\n\nfunction getBroadcastChannelCtor(): (new (name: string) => BroadcastChannelShape) | null {\n if (typeof BroadcastChannel === \"undefined\") return null\n return BroadcastChannel as unknown as new (name: string) => BroadcastChannelShape\n}\n\nfunction isBroadcastMessage(value: unknown): value is BroadcastMessage {\n if (!value || typeof value !== \"object\") return false\n const t = (value as { type?: unknown }).type\n return t === \"token-rotated\" || t === \"session-expired\"\n}\n\n/**\n * Create a token broadcast wrapper for the given channel name. Callers must\n * invoke `close()` when the provider unmounts so the underlying channel\n * stops holding a reference.\n */\nexport function createTokenBroadcast(name: string): TokenBroadcast {\n const Ctor = getBroadcastChannelCtor()\n if (!Ctor) {\n return {\n publish: () => void 0,\n subscribe: () => () => void 0,\n close: () => void 0,\n }\n }\n const channel = new Ctor(name)\n const handlers = new Set<(message: BroadcastMessage) => void>()\n const onMessage = (event: { data: unknown }) => {\n if (!isBroadcastMessage(event.data)) return\n for (const h of handlers) {\n try {\n h(event.data)\n } catch {\n // Handlers must not throw -- swallow to keep the channel healthy.\n }\n }\n }\n channel.addEventListener(\"message\", onMessage)\n return {\n publish(message) {\n channel.postMessage(message)\n },\n subscribe(handler) {\n handlers.add(handler)\n return () => {\n handlers.delete(handler)\n }\n },\n close() {\n channel.removeEventListener(\"message\", onMessage)\n channel.close()\n handlers.clear()\n },\n }\n}\n\n/** Whether the current environment supports cross-tab broadcast. Useful for tests. */\nexport function hasBroadcastSupport(): boolean {\n return getBroadcastChannelCtor() !== null\n}\n","/**\n * DPoP (RFC 9449) client implementation.\n *\n * This module owns the per-tab ES256 keypair used for sender-constrained\n * tokens, plus the proof-JWT builder that clients send on every\n * /auth/token call (and, in future, on every resource-server request).\n *\n * Design choices:\n * - Keys are non-exportable CryptoKey objects (`extractable: false`).\n * XSS can use them to sign but cannot exfiltrate the private bytes.\n * - Keys are regenerated per-tab on provider mount. A page reload ==\n * a new keypair. The cost is one extra round-trip after reload;\n * the benefit is no persistence surface for key material at all.\n * - ES256 / P-256 only. Universal WebCrypto support, matches what the\n * server's DPoP validator accepts first.\n *\n * The module is a no-op fallback when WebCrypto is unavailable (SSR,\n * extremely old browsers). Callers treat a null manager as \"Bearer mode\".\n */\n\nimport { bytesToBase64Url, stringToBase64Url } from \"../crypto/base64url\"\n\n/** Optional per-proof inputs (RFC 9449 resource access + server nonce). */\nexport interface DPoPProofOptions {\n /**\n * Access token being presented. When set, the proof carries an `ath`\n * claim (base64url(SHA-256(accessToken))) binding the proof to that\n * token, as required for DPoP-authenticated resource-server requests\n * (RFC 9449 §4.3 / §7). Omit at the token endpoint.\n */\n accessToken?: string\n /**\n * Server-issued nonce (RFC 9449 §8). When the AS/RS rejects a proof\n * with `use_dpop_nonce` + a `DPoP-Nonce` header, re-sign with that\n * nonce and retry.\n */\n nonce?: string\n}\n\nexport interface DPoPKeyManager {\n /** Sign a proof for a specific (method, url) pair, plus optional ath/nonce. */\n signProof(method: string, url: string, options?: DPoPProofOptions): Promise<string>\n /** Public JWK -- used by the server to compute `cnf.jkt`. */\n publicJWK(): Promise<JsonWebKey>\n}\n\n/**\n * Create a per-tab DPoP key manager. Returns null when WebCrypto is not\n * available -- the caller should fall back to Bearer mode silently.\n */\nexport async function createDPoPKeyManager(): Promise<DPoPKeyManager | null> {\n if (typeof crypto === \"undefined\" || typeof crypto.subtle === \"undefined\") {\n return null\n }\n let keyPair: CryptoKeyPair\n try {\n keyPair = await crypto.subtle.generateKey(\n { name: \"ECDSA\", namedCurve: \"P-256\" },\n false, // non-exportable\n [\"sign\"],\n )\n } catch {\n return null\n }\n\n // Cache the public JWK so we serialize it once per tab. The proof\n // header's `jwk` field must be byte-for-byte stable for the server's\n // thumbprint to match across calls.\n let cachedJWK: JsonWebKey | null = null\n async function pubJWK(): Promise<JsonWebKey> {\n if (cachedJWK) return cachedJWK\n // For the proof header we need an extractable PUBLIC key -- the\n // private side stays non-exportable. WebCrypto only exports extractable\n // keys; the public key of a non-extractable pair is considered\n // exportable because it carries no secret, and browsers honor that.\n cachedJWK = (await crypto.subtle.exportKey(\n \"jwk\",\n keyPair.publicKey,\n )) as JsonWebKey\n // Strip private-ish fields just in case.\n delete (cachedJWK as { d?: string }).d\n return cachedJWK\n }\n\n return {\n async publicJWK() {\n return pubJWK()\n },\n async signProof(method: string, url: string, options?: DPoPProofOptions): Promise<string> {\n const jwk = await pubJWK()\n const header = {\n typ: \"dpop+jwt\",\n alg: \"ES256\",\n jwk,\n }\n const payload: Record<string, unknown> = {\n jti: newJTI(),\n htm: method.toUpperCase(),\n htu: canonicalizeURL(url),\n iat: Math.floor(Date.now() / 1000),\n }\n // RFC 9449 §4.3 / §7: bind the proof to the access token on\n // resource-server requests so a stolen-but-bound token cannot be\n // replayed with a different proof. Omitted at the token endpoint.\n if (options?.accessToken) {\n payload.ath = await accessTokenHash(options.accessToken)\n }\n // RFC 9449 §8: include the server-issued nonce when retrying after\n // a `use_dpop_nonce` challenge.\n if (options?.nonce) {\n payload.nonce = options.nonce\n }\n const headerB64 = stringToBase64Url(JSON.stringify(header))\n const payloadB64 = stringToBase64Url(JSON.stringify(payload))\n const signingInput = `${headerB64}.${payloadB64}`\n\n const sigRaw = await crypto.subtle.sign(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n keyPair.privateKey,\n new TextEncoder().encode(signingInput),\n )\n // WebCrypto returns IEEE P1363 (r||s) signatures, which is what\n // JOSE ES256 expects. No re-encoding needed.\n const sigB64 = bytesToBase64Url(new Uint8Array(sigRaw))\n return `${signingInput}.${sigB64}`\n },\n }\n}\n\n/** RFC 9449 §4.2 htu canonicalization: scheme + authority + path, no query/fragment. */\nfunction canonicalizeURL(raw: string): string {\n let u: URL\n try {\n u = new URL(raw)\n } catch {\n // A non-canonical htu (query/fragment still attached, or a relative\n // URL) is rejected by the server. Fail loud here rather than ship a\n // malformed proof that produces a confusing 400 at the endpoint.\n throw new Error(`DPoP: cannot canonicalize htu, invalid URL: ${raw}`)\n }\n u.search = \"\"\n u.hash = \"\"\n return u.toString()\n}\n\n/** base64url(SHA-256(accessToken)) for the RFC 9449 `ath` claim. */\nasync function accessTokenHash(accessToken: string): Promise<string> {\n const digest = await crypto.subtle.digest(\n \"SHA-256\",\n new TextEncoder().encode(accessToken),\n )\n return bytesToBase64Url(new Uint8Array(digest))\n}\n\n/** A reasonably unique jti. The server's replay cache does the enforcement. */\nfunction newJTI(): string {\n if (typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID()\n }\n const bytes = new Uint8Array(16)\n crypto.getRandomValues(bytes)\n return bytesToBase64Url(bytes)\n}\n","/**\n * JWT signature verification against the IdP's JWKS.\n *\n * Used to authenticate tokens that arrive over an UNTRUSTED in-browser\n * channel -- specifically the cross-tab `BroadcastChannel` (see the\n * browser auth client). BroadcastChannel is same-origin but not\n * same-trust: any script running on the origin (a third-party widget, an\n * XSS payload) can post to a channel whose name is derivable from the\n * public `authority` + `clientId`. Without verification a follower tab\n * would adopt attacker-supplied tokens and rebuild its identity from a\n * forged ID token.\n *\n * Verification is delegated to `jose` (RFC 7515/7517/7519). The JWKS is\n * fetched from the issuer's discovery document and cached with rotation\n * handling by `createRemoteJWKSet`.\n */\n\nimport { createRemoteJWKSet, jwtVerify, type JWTPayload } from 'jose'\n\ninterface Discovered {\n /** The issuer string the IdP advertises -- matched against the `iss` claim. */\n issuer: string\n /** Cached remote JWKS resolver (handles key rotation + cooldown internally). */\n jwks: ReturnType<typeof createRemoteJWKSet>\n}\n\n/**\n * Per-authority discovery cache. Keyed by the raw `authority` string the\n * provider was configured with. A rejected discovery is NOT cached so a\n * transient network failure can be retried on the next broadcast.\n */\nconst discoveryCache = new Map<string, Promise<Discovered>>()\n\nfunction discover(authority: string): Promise<Discovered> {\n const cached = discoveryCache.get(authority)\n if (cached) return cached\n\n const base = authority.replace(/\\/+$/, '')\n const promise = (async (): Promise<Discovered> => {\n const res = await fetch(`${base}/.well-known/openid-configuration`)\n if (!res.ok) {\n throw new Error(`OIDC discovery failed: HTTP ${res.status}`)\n }\n const doc = (await res.json()) as { issuer?: string; jwks_uri?: string }\n if (!doc.jwks_uri) {\n throw new Error('OIDC discovery document is missing jwks_uri')\n }\n return {\n issuer: doc.issuer ?? base,\n jwks: createRemoteJWKSet(new URL(doc.jwks_uri)),\n }\n })().catch((err) => {\n // Do not cache failures -- allow the next call to re-discover.\n discoveryCache.delete(authority)\n throw err\n })\n\n discoveryCache.set(authority, promise)\n return promise\n}\n\n/**\n * Verify an ID token's signature, issuer, and audience against the IdP.\n * Resolves to the verified claims, or rejects when the token is forged,\n * expired, for a different issuer/audience, or carries no `sub`.\n *\n * `audience` is the OIDC `client_id` (the publishable key ID): an ID\n * token's `aud` is always the client it was issued for.\n */\nexport async function verifyIdToken(\n idToken: string,\n opts: { authority: string; clientId: string },\n): Promise<JWTPayload> {\n const { issuer, jwks } = await discover(opts.authority)\n const { payload } = await jwtVerify(idToken, jwks, {\n issuer,\n audience: opts.clientId,\n requiredClaims: ['sub'],\n })\n if (typeof payload.sub !== 'string' || payload.sub.length === 0) {\n throw new Error('verifyIdToken: token carries no usable sub claim')\n }\n return payload\n}\n\n/** Test-only: drop the discovery cache so a test can re-stub the IdP. */\nexport function _resetDiscoveryCache(): void {\n discoveryCache.clear()\n}\n","/**\n * Device-bound KEK vault.\n *\n * Purpose: persist the KEK across page reloads and silent-auth refreshes\n * without exposing it on disk in plaintext.\n *\n * Design: at first login we receive the KEK bytes in the URL fragment\n * (`#atol_enc_key=...`). We generate a non-extractable AES-GCM CryptoKey\n * in WebCrypto (the \"device key\"), encrypt the raw KEK under that device\n * key, and persist the ciphertext + IV + the CryptoKey handle itself in\n * IndexedDB. On any subsequent page load or silent refresh we can load\n * the device key handle and decrypt the stored KEK -- purely locally,\n * no round-trip and no password prompt.\n *\n * Threat model:\n * - The device key is `extractable: false`, so an attacker with JS\n * execution on the origin can *use* it (decrypt under the handle)\n * but cannot copy the key bytes off the device.\n * - The wrapped KEK ciphertext is AES-GCM, so tampering is detected\n * by the auth tag.\n * - IndexedDB is origin-scoped, so cross-origin scripts cannot reach\n * the vault.\n * - An attacker with XSS *can* decrypt live data while present on the\n * page (inherent to any browser-resident key). Mitigations belong\n * upstream: strict CSP, Trusted Types, SRI.\n *\n * Wire format compatibility: the KEK bytes are the raw bytes produced by\n * Atol's Argon2id derivation (32 bytes). The wrapped DEK the caller\n * passes to provision()/rehydrate() is the raw base64-decodable blob\n * straight from the `atol:wrapped_dek` ID token claim -- the vault does\n * not re-encode it.\n */\n\nimport { base64ToBytes } from \"./base64url\";\n\nconst DB_NAME = \"atol-sdk\";\nconst DB_VERSION = 1;\nconst STORE = \"kek-vault\";\nconst RECORD_KEY = \"current\";\n\n/**\n * Stored shape. Note that `deviceKey` is a CryptoKey handle -- IndexedDB\n * is required to support structured-cloning CryptoKey, and every browser\n * that ships IndexedDB + WebCrypto in the last five years does.\n */\ninterface VaultRecord {\n deviceKey: CryptoKey;\n encryptedKEK: Uint8Array;\n iv: Uint8Array;\n version: number;\n}\n\nconst CURRENT_VERSION = 1;\n\n/** Bytes-in / bytes-out shape returned to callers. */\nexport interface UnwrappedDEK {\n dek: Uint8Array;\n}\n\n/**\n * Open (or upgrade) the SDK's IndexedDB database and return a request\n * handle. Factored so tests can stub the name via `indexedDB.deleteDatabase`.\n */\nfunction openDB(): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n if (typeof indexedDB === \"undefined\") {\n reject(new Error(\"KEKVault: IndexedDB is not available\"));\n return;\n }\n const req = indexedDB.open(DB_NAME, DB_VERSION);\n req.onupgradeneeded = () => {\n const db = req.result;\n if (!db.objectStoreNames.contains(STORE)) {\n db.createObjectStore(STORE);\n }\n };\n req.onsuccess = () => resolve(req.result);\n req.onerror = () => reject(req.error ?? new Error(\"KEKVault: open failed\"));\n });\n}\n\nfunction readRecord(db: IDBDatabase): Promise<VaultRecord | null> {\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readonly\");\n const req = tx.objectStore(STORE).get(RECORD_KEY);\n req.onsuccess = () => {\n const v = req.result as VaultRecord | undefined;\n resolve(v ?? null);\n };\n req.onerror = () => reject(req.error ?? new Error(\"KEKVault: read failed\"));\n });\n}\n\nfunction writeRecord(db: IDBDatabase, rec: VaultRecord): Promise<void> {\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readwrite\");\n tx.objectStore(STORE).put(rec, RECORD_KEY);\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error ?? new Error(\"KEKVault: write failed\"));\n tx.onabort = () => reject(tx.error ?? new Error(\"KEKVault: write aborted\"));\n });\n}\n\nfunction deleteRecord(db: IDBDatabase): Promise<void> {\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readwrite\");\n tx.objectStore(STORE).delete(RECORD_KEY);\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error ?? new Error(\"KEKVault: delete failed\"));\n tx.onabort = () => reject(tx.error ?? new Error(\"KEKVault: delete aborted\"));\n });\n}\n\nfunction randomIV(): Uint8Array {\n const iv = new Uint8Array(12);\n crypto.getRandomValues(iv);\n return iv;\n}\n\nfunction zero(bytes: Uint8Array): void {\n for (let i = 0; i < bytes.length; i++) bytes[i] = 0;\n}\n\n/**\n * Unwrap a DEK given raw KEK bytes. Mirrors the Atol server's\n * base64(nonce || ciphertext || tag) wrapping (AES-256-GCM, 12-byte\n * nonce, 16-byte tag, no AAD). Kept private to this module: the public\n * vault API takes `wrappedDEK` as a base64 string and returns raw DEK\n * bytes, hiding the KEK entirely.\n */\nasync function unwrapDEKWithKEK(\n kek: Uint8Array,\n wrappedDEKBase64: string,\n): Promise<Uint8Array> {\n const wrapped = base64ToBytes(wrappedDEKBase64);\n if (wrapped.length < 12 + 16) {\n throw new Error(\"KEKVault: wrapped DEK shorter than nonce+tag\");\n }\n const nonce = wrapped.slice(0, 12);\n const ciphertext = wrapped.slice(12);\n // Cast to ArrayBuffer for TS 5.7 BufferSource narrowing -- the backing\n // buffer is a real ArrayBuffer (base64ToBytes allocates Uint8Array).\n const key = await crypto.subtle.importKey(\n \"raw\",\n kek.buffer as ArrayBuffer,\n { name: \"AES-GCM\" },\n false,\n [\"decrypt\"],\n );\n const plaintext = await crypto.subtle.decrypt(\n { name: \"AES-GCM\", iv: nonce.buffer as ArrayBuffer },\n key,\n ciphertext,\n );\n return new Uint8Array(plaintext);\n}\n\n/**\n * KEKVault is stateless by design -- construction is cheap and every\n * method opens its own IndexedDB transaction. That avoids holding long-\n * lived handles and plays cleanly with tab unload / page hide.\n */\nexport class KEKVault {\n /**\n * Stash the KEK under a fresh device key, then unwrap the DEK and\n * return its bytes. Call this on the first login-callback of a\n * session, when the KEK arrived in the URL fragment.\n *\n * Overwrites any existing vault record (key rotation, password change,\n * or user-switch on the same device all land here).\n *\n * `kekBytes` is zeroed after use. Callers should also drop their\n * local reference.\n */\n async provision(kekBytes: Uint8Array, wrappedDEKBase64: string): Promise<Uint8Array> {\n if (kekBytes.length === 0) {\n throw new Error(\"KEKVault.provision: kekBytes is empty\");\n }\n if (wrappedDEKBase64 === \"\") {\n throw new Error(\"KEKVault.provision: wrappedDEK is empty\");\n }\n\n // Generate a non-extractable AES-GCM device key. `encrypt` + `decrypt`\n // usages let us wrap and unwrap the KEK bytes locally; the key\n // itself never leaves WebCrypto's opaque handle.\n const deviceKey = await crypto.subtle.generateKey(\n { name: \"AES-GCM\", length: 256 },\n false,\n [\"encrypt\", \"decrypt\"],\n );\n\n const iv = randomIV();\n const ciphertext = new Uint8Array(\n await crypto.subtle.encrypt(\n { name: \"AES-GCM\", iv: iv.buffer as ArrayBuffer },\n deviceKey,\n kekBytes.buffer as ArrayBuffer,\n ),\n );\n\n // Unwrap the DEK *before* persisting -- if the KEK is wrong the\n // wrapped-DEK auth tag fails here and we bail without leaving a\n // useless vault entry behind.\n const dek = await unwrapDEKWithKEK(kekBytes, wrappedDEKBase64);\n\n const db = await openDB();\n try {\n await writeRecord(db, {\n deviceKey,\n encryptedKEK: ciphertext,\n iv,\n version: CURRENT_VERSION,\n });\n } finally {\n db.close();\n }\n\n // Best-effort zero. Caller's reference is still live; we don't\n // control it. Document this in JSDoc above.\n zero(kekBytes);\n return dek;\n }\n\n /**\n * Rehydrate the DEK from the vault on silent-auth or page reload.\n * Returns null when there's no prior vault record -- caller falls\n * back to `signinRedirect` with `prompt=login` to repopulate.\n *\n * Returns null (rather than throwing) for the missing-state case\n * because it's a normal branch: new browser, cleared data, freshly\n * installed device. Actual errors (corrupted record, auth-tag fail\n * on the stored KEK) DO throw -- those indicate tampering or a bug\n * and the caller should escalate.\n */\n async rehydrate(wrappedDEKBase64: string): Promise<Uint8Array | null> {\n if (wrappedDEKBase64 === \"\") {\n throw new Error(\"KEKVault.rehydrate: wrappedDEK is empty\");\n }\n const db = await openDB();\n let rec: VaultRecord | null;\n try {\n rec = await readRecord(db);\n } finally {\n db.close();\n }\n if (!rec) return null;\n if (rec.version !== CURRENT_VERSION) {\n // Future version skew: refuse to guess. Caller clears and\n // re-provisions on the next explicit login.\n return null;\n }\n\n const kekBuffer = await crypto.subtle.decrypt(\n { name: \"AES-GCM\", iv: rec.iv.buffer as ArrayBuffer },\n rec.deviceKey,\n rec.encryptedKEK.buffer as ArrayBuffer,\n );\n const kek = new Uint8Array(kekBuffer);\n try {\n return await unwrapDEKWithKEK(kek, wrappedDEKBase64);\n } finally {\n zero(kek);\n }\n }\n\n /**\n * Wipe the vault. Call from the logout path after `signoutRedirect`\n * so the next visit to this origin won't silently rehydrate the\n * previous user's DEK.\n *\n * Idempotent: a missing record is fine.\n */\n async clear(): Promise<void> {\n let db: IDBDatabase;\n try {\n db = await openDB();\n } catch {\n // IndexedDB unavailable -- nothing to clear.\n return;\n }\n try {\n await deleteRecord(db);\n } finally {\n db.close();\n }\n }\n\n /**\n * Non-destructive \"does the vault have a record?\" predicate. The\n * provider uses this to decide whether a silent refresh can succeed\n * or it needs to kick a `prompt=login`.\n */\n async hasRecord(): Promise<boolean> {\n let db: IDBDatabase;\n try {\n db = await openDB();\n } catch {\n return false;\n }\n try {\n const rec = await readRecord(db);\n return rec !== null && rec.version === CURRENT_VERSION;\n } finally {\n db.close();\n }\n }\n}\n","/**\n * Zero-knowledge encryption primitives.\n *\n * The KEK (Key Encryption Key) is delivered via URL fragment by the Atol\n * authorize endpoint. The wrapped DEK (Data Encryption Key) arrives as\n * an ID token claim. The client unwraps the DEK locally and hands the\n * KEK to the vault (see `./kek-vault.ts`) so silent-auth refreshes can\n * rehydrate the DEK without a password prompt.\n *\n * This module stays intentionally small: fragment parsing, byte\n * conversion helpers, and the one-shot unwrap. DEK persistence is the\n * vault's job, not this module's.\n */\n\nimport { base64ToBytes } from './base64url'\n\n/**\n * Extract the KEK from the URL fragment and clean up immediately.\n * The fragment is set by the Atol authorize endpoint: `#atol_enc_key=base64(kek)`.\n * Returns null when not present.\n */\nexport function extractKEKFromFragment(): string | null {\n const hash = window.location.hash\n if (!hash) return null\n\n const params = new URLSearchParams(hash.substring(1))\n const kek = params.get('atol_enc_key')\n\n // Treat an empty value (`#atol_enc_key=`) as \"not present\" so callers\n // can rely on the non-null return shape. Without this guard callers\n // would later crash at atob/base64 decode.\n if (!kek) return null\n\n params.delete('atol_enc_key')\n const remaining = params.toString()\n const newHash = remaining ? '#' + remaining : ''\n window.history.replaceState(\n {},\n document.title,\n window.location.pathname + window.location.search + newHash,\n )\n\n return kek\n}\n\n/**\n * Decode a base64 / base64url string into raw bytes. Accepts either\n * the \"+/\" standard alphabet or the \"-_\" URL-safe alphabet, with or\n * without padding. The Atol authorize endpoint emits base64url without\n * padding; older servers may emit padded base64.\n *\n * Thin alias over the shared decoder in `./base64url` -- kept exported\n * under this name because it is part of the public API.\n */\nexport function kekBase64ToBytes(b64: string): Uint8Array {\n return base64ToBytes(b64)\n}\n\n/**\n * Unwrap a DEK using the KEK via AES-256-GCM (Web Crypto API). The\n * `wrappedDEK` format is `base64(nonce12bytes || ciphertext || tag)`,\n * matching the wire format the Atol authorize endpoint emits.\n *\n * Kept as a public utility so callers that prefer to own DEK lifetime\n * themselves (e.g. tests, or frontends that intentionally avoid\n * persisting the DEK across reloads) can unwrap without pulling in the\n * vault machinery.\n */\nexport async function unwrapDEK(\n kekBase64: string,\n wrappedDEKBase64: string,\n): Promise<Uint8Array> {\n const kek = kekBase64ToBytes(kekBase64)\n const wrapped = kekBase64ToBytes(wrappedDEKBase64)\n\n // Validate sizes before importKey so a corrupted/attacker-supplied value\n // fails with an actionable message instead of an opaque WebCrypto\n // DataError. AES-GCM keys are 16/24/32 bytes; the wrapped blob is\n // nonce(12) || ciphertext || tag(16).\n if (kek.length !== 16 && kek.length !== 24 && kek.length !== 32) {\n throw new Error(`unwrapDEK: KEK must be 16/24/32 bytes, got ${kek.length}`)\n }\n if (wrapped.length < 12 + 16) {\n throw new Error('unwrapDEK: wrapped DEK shorter than nonce+tag')\n }\n\n const nonce = wrapped.slice(0, 12) // AES-GCM standard nonce size\n const ciphertext = wrapped.slice(12)\n\n // Cast to ArrayBuffer for TS 5.7 BufferSource narrowing -- the backing\n // buffer is a real ArrayBuffer (kekBase64ToBytes allocates fresh).\n const key = await crypto.subtle.importKey(\n 'raw',\n kek.buffer as ArrayBuffer,\n { name: 'AES-GCM' },\n false,\n ['decrypt'],\n )\n\n const plaintext = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv: nonce.buffer as ArrayBuffer },\n key,\n ciphertext,\n )\n\n return new Uint8Array(plaintext)\n}\n","/**\n * createAtolBrowserAuth: the config-driven browser auth client.\n *\n * This is the keystone of @atol-sh/js. It wraps oidc-client-ts with the\n * proven Atol logic that previously lived only inside the React provider:\n * PKCE authorization-code login, in-memory token storage, DPoP-aware token\n * access, proactive + on-demand silent renewal with single-flight\n * coordination, cross-tab rotation broadcast (authenticated via JWKS), and\n * RP-initiated logout with refresh-token revocation.\n *\n * Framework bindings (React, Vue, ...) become thin wrappers over this: they\n * subscribe with `onSessionChange` and render, delegating every credential\n * decision here.\n *\n * Storage policy: tokens are MEMORY-ONLY. The oidc-client-ts user store is\n * `InMemoryWebStorage`; sessionStorage holds only the OIDC state/PKCE\n * verifier needed to survive the login redirect. A page reload starts with\n * an empty store, and the client recovers via a silent renew against the\n * IdP session cookie.\n */\n\nimport type { User, UserManager } from 'oidc-client-ts'\nimport {\n createUserManager,\n getAccessToken,\n getIdToken,\n userFromTokenResponse,\n} from '../oidc/oidc'\nimport { getTokenExpiry, parseAtolUser } from '../claims/claims'\nimport {\n DEFAULT_SILENT_RENEW_RETRY_COUNT,\n LoginRequiredError,\n exchangeCode,\n refreshTokenGrant,\n revokeToken,\n silentAuthorizeWithRetry,\n type TokenResponse,\n} from '../oidc/silent-renew'\nimport {\n RecoveryAction,\n backoffDelay,\n classifyRenewalError,\n} from '../oidc/token-recovery'\nimport { withTabLock } from '../oidc/cross-tab-lock'\nimport {\n createTokenBroadcast,\n type BroadcastMessage,\n type TokenBroadcast,\n} from '../token/token-broadcast'\nimport { createDPoPKeyManager, type DPoPKeyManager } from '../dpop/dpop'\nimport { verifyIdToken } from '../verify/verify'\nimport { decodeJWTPayload } from '../claims/claims'\nimport { KEKVault } from '../crypto/kek-vault'\nimport { extractKEKFromFragment, kekBase64ToBytes } from '../crypto/encryption'\nimport type { AtolUser, DPoPProofResult } from '../claims/types'\n\n/** DPoP configuration: a boolean toggle or an object with `required`. */\nexport type DPoPConfig = boolean | { required?: boolean }\n\n/** Configuration for {@link createAtolBrowserAuth}. */\nexport interface AtolBrowserAuthConfig {\n /** OIDC issuer URL (e.g. https://auth.atol.sh). */\n issuer: string\n /** Publishable OIDC client id / key id (atol_kid_...). Safe for the browser. */\n clientId: string\n /** API audience identifier. Optional. */\n audience?: string\n /** OIDC scopes. Default: \"openid profile email\". */\n scopes?: string\n /** URL to redirect to after login (and after logout). */\n redirectUri: string\n /**\n * Request DPoP-bound tokens (RFC 9449). `true` (or `{ required: true }`)\n * generates a per-tab non-exportable ES256 keypair on init and attaches a\n * proof to every token-endpoint call. `false` (default) uses Bearer.\n */\n dpop?: DPoPConfig\n /**\n * Silent renewal strategy. Default (false): hidden-iframe silent\n * authentication against the IdP session cookie (prompt=none) - no\n * refresh token is requested or stored. The iframe path\n * relies on the IdP session cookie being sent from a third-party context,\n * which Safari ITP blocks and Chrome's third-party-cookie phase-out\n * removes, so it fails UNCONDITIONALLY for a cross-site app (one served on\n * a different registrable domain than the IdP). Cross-site apps MUST set\n * this true: it requests offline_access and renews via the refresh-token\n * grant (memory-only, rotated, DPoP-bound when dpop is on). Same-site apps\n * (e.g. an admin console on a subdomain of the IdP) reach the first-party\n * session cookie in the iframe and leave this false.\n */\n useRefreshTokens?: boolean\n /**\n * When useRefreshTokens is true, fall back to the hidden-iframe silent\n * authentication if a refresh-token grant fails transiently (network /\n * transient server error), instead of only backing off. No effect when\n * useRefreshTokens is false (iframe is already the path).\n */\n useRefreshTokensFallback?: boolean\n /**\n * Request the zero-knowledge encryption-key claim. When true, the client\n * appends `derive_encryption_key=true` to the login authorize request and\n * to every silent (iframe) renew, so the issuer emits the\n * `atol:wrapped_dek` claim on the ID token consistently across the\n * session. The client itself does no crypto with the claim; a framework\n * binding reads it from {@link AtolBrowserAuth.getIdToken} and derives the\n * data-encryption key. Defaults to false.\n */\n deriveEncryptionKey?: boolean\n /**\n * Token storage backend. Only `'memory'` is supported: tokens live in an\n * in-memory oidc-client-ts store and are never written to Web Storage.\n * Accepted as a config knob for forward-compat and to make the guarantee\n * explicit at the call site.\n */\n storage?: 'memory'\n}\n\n/** The current auth session, delivered to `onSessionChange` subscribers. */\nexport interface AtolSession {\n /** Whether a user is currently authenticated. */\n isAuthenticated: boolean\n /** The authenticated user, or null. */\n user: AtolUser | null\n /**\n * The unwrapped zero-knowledge data-encryption key (DEK), when\n * `deriveEncryptionKey` is enabled and the KEK/wrapped-DEK derivation\n * succeeded for the current session. `undefined` when the feature is off,\n * when there is no session, or when derivation failed (see\n * {@link AtolSession.encryptionError}). Framework bindings consume this\n * instead of re-deriving the key themselves.\n */\n encryptionKey?: Uint8Array\n /**\n * Non-`undefined` when `deriveEncryptionKey` is enabled but the expected\n * DEK could not be unwrapped: a wrong KEK, a tampered wrapped-DEK\n * (AES-GCM auth-tag failure), or a vault error. Surfaced so the app can\n * deny encrypted operations instead of silently treating a failure as\n * \"encryption off\" -- an auth-tag failure must never present as a\n * silently-wrong key. Mutually exclusive with a present\n * {@link AtolSession.encryptionKey}.\n */\n encryptionError?: Error\n}\n\n/** Options for {@link AtolBrowserAuth.getAccessToken}. */\nexport interface GetAccessTokenOptions {\n /**\n * When present, and DPoP is active, the returned result carries a proof\n * JWT bound (via `ath`) to the returned access token for the given\n * (method, url). When DPoP is inactive the proof is omitted.\n */\n dpop?: { method: string; url: string }\n}\n\n/** Options for {@link AtolBrowserAuth.beginLogin}. */\nexport interface BeginLoginOptions {\n /** Same-origin path to return to after login (overrides the redirect URI). */\n returnTo?: string\n /**\n * OIDC `prompt` value (e.g. `'login'` to force re-authentication, `'none'`\n * for silent). Sent as an authorize-request parameter.\n */\n prompt?: string\n /**\n * OIDC `max_age` (seconds): the maximum acceptable age of the End-User's\n * authentication. `0` forces a fresh login.\n */\n maxAge?: number\n /** OIDC `acr_values`: requested authentication assurance level(s). */\n acrValues?: string\n}\n\n/** Options for {@link AtolBrowserAuth.stepUp}. */\nexport interface StepUpOptions {\n /** Same-origin path to return to after the step-up re-authentication. */\n returnTo?: string\n /**\n * OIDC `max_age` (seconds). Defaults to `0` (force a brand-new login). Set a\n * small positive value to accept a very recent existing authentication.\n */\n maxAge?: number\n /** OIDC `acr_values`. Defaults to `'mfa'`. */\n acrValues?: string\n}\n\n/** The browser auth client returned by {@link createAtolBrowserAuth}. */\nexport interface AtolBrowserAuth {\n /**\n * Initialize the client: install the DPoP key (if enabled), wire the\n * cross-tab broadcast, and attempt to restore a session (handling a\n * redirect callback if the current URL is one). Idempotent; safe to call\n * once at startup. Resolves once the initial session state is settled.\n */\n init(): Promise<AtolSession>\n /**\n * Begin an authorization-code + PKCE login by redirecting the browser to\n * the Atol authorize endpoint. `returnTo` (a same-origin path) overrides\n * the post-login redirect target for this call. `prompt` / `maxAge` /\n * `acrValues` are forwarded as OIDC authorize-request parameters (used by\n * {@link AtolBrowserAuth.stepUp} to force re-authentication).\n */\n beginLogin(options?: BeginLoginOptions): Promise<void>\n /**\n * Force a step-up re-authentication: redirect to the authorize endpoint with\n * `prompt=login` + `max_age=0` (and `acr_values=mfa` by default) so the\n * issuer mints a token with a fresh `auth_time` and a completed second\n * factor. Use this when a sensitive management operation returns a\n * \"step_up_required\" challenge; after the redirect completes, retry the\n * operation. Overridable via {@link StepUpOptions}.\n */\n stepUp(options?: StepUpOptions): Promise<void>\n /**\n * Complete a login redirect: exchange the authorization code for tokens,\n * verify the ID token, and establish the session. Call on the redirect\n * URI page. A no-op returning the current session when the URL is not a\n * callback. `init()` calls this automatically.\n */\n completeLogin(): Promise<AtolSession>\n /**\n * Return the current access token, renewing it when it is inside the 60s\n * expiry window. With `opts.dpop` and DPoP active, also returns a bound\n * proof. Resolves to `undefined` when there is no session.\n */\n getAccessToken(\n opts?: GetAccessTokenOptions,\n ): Promise<{ token: string; proof?: string } | undefined>\n /**\n * The current raw ID token (the JWT), or `undefined` when there is no\n * session. Exposed so framework bindings can read issuer-specific ID\n * token claims the parsed {@link AtolUser} does not carry (e.g. an\n * app-specific encryption-key claim) without re-implementing token\n * storage. Read-only; the client owns renewal and rotation.\n */\n getIdToken(): string | undefined\n /**\n * The current unwrapped zero-knowledge data-encryption key (DEK), or\n * `undefined`. Only ever non-`undefined` when `deriveEncryptionKey` is\n * enabled and derivation succeeded for the active session. Framework\n * bindings read this (or the {@link AtolSession.encryptionKey} field on\n * the session-change payload) instead of re-deriving the key. The\n * returned array is the client's live buffer; do not mutate it.\n */\n getEncryptionKey(): Uint8Array | undefined\n /**\n * The last zero-knowledge key-derivation error, or `undefined`. Set when\n * `deriveEncryptionKey` is enabled but the DEK could not be unwrapped\n * (wrong KEK, tampered wrapped-DEK auth-tag failure, or vault error), so\n * the caller can fail loud rather than treat a tamper as \"encryption\n * off\". Cleared on the next successful derivation and on logout/destroy.\n */\n getEncryptionError(): Error | undefined\n /**\n * Sign out via OIDC RP-Initiated Logout: revoke the refresh token\n * (best-effort), clear local state, then redirect to the end_session\n * endpoint with `id_token_hint` + `post_logout_redirect_uri`.\n */\n logout(): Promise<void>\n /**\n * Force an immediate silent renew, bypassing the freshness check.\n * Resolves to the new access token, or undefined on failure.\n */\n forceRenew(): Promise<string | undefined>\n /**\n * Sign a DPoP resource-server proof (RFC 9449 §7) for a request to your\n * own protected resource. Fetches a fresh token first so `ath` binds to\n * the token actually presented. Resolves undefined when there is no\n * session; `proof` is undefined when DPoP is inactive.\n */\n signDPoPProof(method: string, url: string): Promise<DPoPProofResult | undefined>\n /** Whether DPoP is active (enabled AND WebCrypto produced a key manager). */\n isDPoPActive(): boolean\n /**\n * Subscribe to session changes (login, logout, renewal, cross-tab\n * rotation). The callback fires immediately with the current session, and\n * again on every subsequent change. Returns an unsubscribe function.\n */\n onSessionChange(cb: (session: AtolSession) => void): () => void\n /** Tear down timers, the broadcast channel, and subscriptions. */\n destroy(): void\n}\n\nconst DEFAULT_SCOPES = 'openid profile email'\n/** Renew when the access token is within this window of expiry. */\nconst RENEW_WINDOW_MS = 60_000\n\nfunction dpopEnabled(cfg: DPoPConfig | undefined): boolean {\n if (typeof cfg === 'boolean') return cfg\n return cfg?.required === true\n}\n\n/**\n * Create a framework-agnostic Atol browser auth client. See\n * {@link AtolBrowserAuthConfig} for options. Call {@link AtolBrowserAuth.init}\n * once at startup.\n */\nexport function createAtolBrowserAuth(config: AtolBrowserAuthConfig): AtolBrowserAuth {\n const issuer = config.issuer\n const clientId = config.clientId\n const audience = config.audience\n const redirectUri = config.redirectUri\n const useDPoP = dpopEnabled(config.dpop)\n const useRefreshTokens = config.useRefreshTokens ?? false\n const useRefreshTokensFallback = config.useRefreshTokensFallback ?? false\n const deriveEncryptionKey = config.deriveEncryptionKey ?? false\n\n // Renewal model: by default (useRefreshTokens=false) renewal is a\n // hidden-iframe silent authorize against the IdP session cookie\n // (prompt=none), so no refresh token is requested or stored. DPoP still\n // works in this path: the iframe code exchange sends a proof. Only when\n // useRefreshTokens=true do we append `offline_access` so the server mints\n // a refresh token and renew via the refresh-token grant.\n const requestedScopes = config.scopes ?? DEFAULT_SCOPES\n const scope =\n useRefreshTokens && !requestedScopes.split(' ').includes('offline_access')\n ? `${requestedScopes} offline_access`\n : requestedScopes\n\n const manager: UserManager = createUserManager(issuer, clientId, redirectUri, scope, audience)\n\n // Session state.\n let currentUser: AtolUser | null = null\n let currentIdToken: string | undefined\n let accessToken: string | undefined\n let refreshToken: string | undefined\n\n // Zero-knowledge encryption state (only touched when deriveEncryptionKey\n // is set -- when off, these stay undefined and no crypto/vault/fragment\n // work ever runs). `encKey` is the unwrapped DEK for the active session;\n // `encError` is the last derivation failure (tamper / vault error),\n // surfaced so a binding can fail loud instead of treating it as\n // \"encryption off\". `fragmentKEK` is the base64 KEK captured from the URL\n // fragment on init (before the callback strips the URL) and consumed once\n // to provision the vault. `vault` is created lazily on first use.\n let encKey: Uint8Array | undefined\n let encError: Error | undefined\n let fragmentKEK: string | null = null\n let vault: KEKVault | null = null\n\n // DPoP + broadcast + renewal machinery.\n let dpop: DPoPKeyManager | null = null\n let broadcast: TokenBroadcast | null = null\n let renewTimer: ReturnType<typeof setTimeout> | null = null\n let renewInFlight: Promise<string | undefined> | null = null\n let renewBackoff = 0\n let restoreInFlight: Promise<TokenResponse> | null = null\n let destroyed = false\n\n const subscribers = new Set<(session: AtolSession) => void>()\n\n function session(): AtolSession {\n return {\n isAuthenticated: currentUser !== null,\n user: currentUser,\n encryptionKey: encKey,\n encryptionError: encError,\n }\n }\n\n function emit(): void {\n const snap = session()\n for (const cb of subscribers) {\n try {\n cb(snap)\n } catch {\n // Subscribers must not throw -- swallow to keep the notifier healthy.\n }\n }\n }\n\n function toUser(idToken: string | undefined): AtolUser | null {\n if (!idToken) return null\n const u = parseAtolUser(idToken)\n return u.id ? u : null\n }\n\n // ---- Zero-knowledge encryption-key orchestration ----\n //\n // All of the following is inert unless `deriveEncryptionKey` is set: the\n // early `if (!deriveEncryptionKey) return` guards ensure zero crypto,\n // vault, or fragment work when the option is off. The DEK derivation runs\n // on every session (login callback + every silent renew) so the key is\n // available consistently: on a fresh login-callback the KEK is still in\n // the URL fragment (captured in init before the callback strips the URL)\n // and provisions the device-bound vault; on a restore/renew there is no\n // fragment, so we rehydrate the KEK from the vault. Either way the wrapped\n // DEK rides the ID token's `atol:wrapped_dek` claim and is unwrapped\n // locally. Never log key material.\n\n function getVault(): KEKVault {\n return (vault ??= new KEKVault())\n }\n\n /** Read the base64 wrapped-DEK claim from the current ID token, if any. */\n function wrappedDEKFromIdToken(): string | undefined {\n if (!currentIdToken) return undefined\n try {\n const claim = decodeJWTPayload(currentIdToken)['atol:wrapped_dek']\n return typeof claim === 'string' && claim !== '' ? claim : undefined\n } catch {\n // A malformed ID token is not a tamper signal for the DEK path -- the\n // OIDC layer already validated the token to establish the session.\n // Treat an unreadable claim as absent (graceful: no key, no crash).\n return undefined\n }\n }\n\n /** Best-effort zero the current DEK buffer and drop the reference. */\n function zeroEncKey(): void {\n if (encKey) {\n for (let i = 0; i < encKey.length; i++) encKey[i] = 0\n }\n encKey = undefined\n }\n\n /**\n * Provision the vault from the URL-fragment KEK + the wrapped-DEK claim on\n * a fresh login-callback. A wrapped-DEK auth-tag failure is a TAMPER\n * signal, not a benign branch: surface it as encError (never a silently\n * wrong key) and clear the vault so the next explicit login re-provisions.\n */\n async function provisionDEK(kek: string): Promise<void> {\n const wrappedDEK = wrappedDEKFromIdToken()\n if (!wrappedDEK) return\n try {\n const dek = await getVault().provision(kekBase64ToBytes(kek), wrappedDEK)\n encKey = dek\n encError = undefined\n } catch (err) {\n zeroEncKey()\n encError = err instanceof Error ? err : new Error(String(err))\n await getVault().clear().catch(() => undefined)\n }\n }\n\n /**\n * Rehydrate the DEK from the device-bound vault on a restored/renewed\n * session (no URL fragment). A corrupted vault or KEK/DEK mismatch\n * (possible tamper) surfaces as encError and clears the vault. A missing\n * vault record (rehydrate resolves null) is a normal branch -- leave the\n * key absent without an error.\n */\n async function rehydrateDEK(): Promise<void> {\n const wrappedDEK = wrappedDEKFromIdToken()\n if (!wrappedDEK) return\n try {\n const dek = await getVault().rehydrate(wrappedDEK)\n if (dek) {\n encKey = dek\n encError = undefined\n }\n } catch (err) {\n zeroEncKey()\n encError = err instanceof Error ? err : new Error(String(err))\n await getVault().clear().catch(() => undefined)\n }\n }\n\n /**\n * Derive the encryption key for the current session. Provisions from the\n * one-shot fragment KEK when present (fresh callback), otherwise\n * rehydrates from the vault (restore/renew). No-op when the feature is off\n * or the key is already derived. Emits nothing itself -- the caller\n * emits after the session settles.\n */\n async function deriveEncKey(): Promise<void> {\n if (!deriveEncryptionKey) return\n if (encKey) return\n if (fragmentKEK) {\n const kek = fragmentKEK\n fragmentKEK = null\n await provisionDEK(kek)\n } else {\n await rehydrateDEK()\n }\n }\n\n function clearRenewTimer(): void {\n if (renewTimer) {\n clearTimeout(renewTimer)\n renewTimer = null\n }\n }\n\n /**\n * Schedule the proactive renew for (exp - 60s), plus a backoff term when\n * recent renews have been failing transiently. Re-armed whenever the\n * access token changes.\n */\n function scheduleRenew(): void {\n clearRenewTimer()\n if (!accessToken) return\n const exp = getTokenExpiry(accessToken)\n if (exp === null) return\n const baseDelay = Math.max(0, exp - RENEW_WINDOW_MS - Date.now())\n const delay = baseDelay + backoffDelay(renewBackoff)\n renewTimer = setTimeout(() => {\n if (!renewInFlight) {\n renewInFlight = renewOnce()\n .catch(() => undefined)\n .finally(() => {\n renewInFlight = null\n })\n }\n }, delay)\n }\n\n /**\n * Apply a token response to session state + the oidc-client-ts store,\n * derive the encryption key (when enabled), then emit. Async because DEK\n * derivation is async and must complete before we emit so subscribers see\n * the key in the same session payload.\n */\n async function applyTokens(tokens: TokenResponse): Promise<void> {\n accessToken = tokens.access_token\n // Only retain a refresh token when the caller opted into the\n // refresh-token renewal strategy. In the default iframe model a stray\n // server-issued RT is dropped -- neither kept in memory nor persisted to\n // the oidc-client-ts store -- so renewal stays on the iframe path.\n const stored = useRefreshTokens ? tokens : { ...tokens, refresh_token: undefined }\n if (useRefreshTokens && tokens.refresh_token) {\n refreshToken = tokens.refresh_token\n }\n void manager.storeUser(userFromTokenResponse(stored)).catch(() => undefined)\n if (tokens.id_token) {\n currentIdToken = tokens.id_token\n currentUser = toUser(tokens.id_token)\n }\n scheduleRenew()\n await deriveEncKey()\n emit()\n }\n\n /** Clear all local session state (terminal auth failure / logout). */\n function clearSession(): void {\n clearRenewTimer()\n accessToken = undefined\n refreshToken = undefined\n currentUser = null\n currentIdToken = undefined\n // Drop the derived encryption key + error and best-effort zero the DEK\n // buffer. The vault record is wiped on logout (see logout()); a terminal\n // renewal failure keeps the vault so a subsequent silent restore can\n // rehydrate.\n zeroEncKey()\n encError = undefined\n void manager.removeUser().catch(() => undefined)\n emit()\n }\n\n /** Silent renew via the iframe + web_message flow (raw tokens). */\n async function renewViaIframe(): Promise<TokenResponse> {\n const result = await silentAuthorizeWithRetry(\n { authority: issuer, clientId, redirectUri, scope, audience, deriveEncryptionKey },\n DEFAULT_SILENT_RENEW_RETRY_COUNT,\n )\n return exchangeCode(\n issuer,\n clientId,\n result.code,\n redirectUri,\n result.codeVerifier,\n dpop ?? undefined,\n )\n }\n\n /**\n * Run the renew once, under a cross-tab lock so simultaneous tabs collapse\n * to a single /auth/token POST. Broadcasts the rotated tokens. Terminal\n * auth errors clear the session; transient errors re-throw for backoff.\n */\n async function renewOnce(force = false): Promise<string | undefined> {\n const lockName = `atol:renew:${issuer}:${clientId}`\n return withTabLock(lockName, 30_000, async () => {\n if (!force && accessToken) {\n const exp = getTokenExpiry(accessToken)\n if (exp !== null && Date.now() < exp - RENEW_WINDOW_MS) {\n return accessToken\n }\n }\n\n try {\n let tokens: TokenResponse\n if (useRefreshTokens && refreshToken) {\n try {\n tokens = await refreshTokenGrant(\n issuer,\n clientId,\n refreshToken,\n scope,\n audience,\n dpop ?? undefined,\n )\n } catch (grantErr) {\n // A TRANSIENT refresh-token grant failure (network blip, 5xx,\n // 429) can fall back to the hidden-iframe path once when the\n // caller opted in via useRefreshTokensFallback. Terminal auth\n // failures (invalid_grant / login_required -> ForceReauth) and\n // programmer errors (Surface) are re-thrown to the outer catch,\n // which clears the session, so a dead refresh token never\n // silently degrades into an iframe renew.\n if (\n !useRefreshTokensFallback ||\n classifyRenewalError(grantErr) !== RecoveryAction.Retry\n ) {\n throw grantErr\n }\n tokens = await renewViaIframe()\n }\n } else {\n tokens = await renewViaIframe()\n }\n await applyTokens(tokens)\n\n if (broadcast) {\n const exp =\n getTokenExpiry(tokens.access_token) ??\n Date.now() + (tokens.expires_in ?? 3600) * 1000\n broadcast.publish({\n type: 'token-rotated',\n accessToken: tokens.access_token,\n idToken: tokens.id_token,\n // Only carry a refresh token cross-tab in the refresh-token\n // model; in the iframe model each tab renews on its own.\n refreshToken: useRefreshTokens ? tokens.refresh_token : undefined,\n expiresAt: exp,\n sentAt: Date.now(),\n })\n }\n\n renewBackoff = 0\n return tokens.access_token\n } catch (err) {\n switch (classifyRenewalError(err)) {\n case RecoveryAction.ForceReauth: {\n clearSession()\n if (broadcast) {\n broadcast.publish({ type: 'session-expired', sentAt: Date.now() })\n }\n return undefined\n }\n case RecoveryAction.Retry: {\n renewBackoff = Math.min(10, renewBackoff + 1)\n throw err\n }\n case RecoveryAction.Surface:\n default:\n throw err\n }\n }\n })\n }\n\n /** Return the current token, renewing when stale. Dedupes concurrent calls. */\n async function getToken(): Promise<string | undefined> {\n if (accessToken) {\n const exp = getTokenExpiry(accessToken)\n if (exp !== null && Date.now() < exp - RENEW_WINDOW_MS) {\n return accessToken\n }\n } else {\n const stored = getAccessToken((await manager.getUser()) ?? null)\n if (stored) {\n const exp = getTokenExpiry(stored)\n if (exp !== null && Date.now() < exp - RENEW_WINDOW_MS) {\n return stored\n }\n } else {\n return undefined\n }\n }\n if (!renewInFlight) {\n renewInFlight = renewOnce().finally(() => {\n renewInFlight = null\n })\n }\n return renewInFlight\n }\n\n /**\n * Cross-tab broadcast handler: adopt rotated tokens only after\n * authenticating the ID token (signature, issuer, audience) against the\n * IdP JWKS and pinning the subject. Never trust a raw channel message.\n */\n async function onBroadcast(message: BroadcastMessage): Promise<void> {\n if (message.type === 'session-expired') {\n // Re-verify with the server rather than trusting the message: a forged\n // session-expired is a no-op because forceRenew only clears when the\n // refresh token is actually dead.\n void forceRenew()\n return\n }\n const rotated = message\n // Forward-progress only.\n if (accessToken) {\n const existingExp = getTokenExpiry(accessToken)\n if (existingExp !== null && existingExp >= rotated.expiresAt) return\n }\n if (!rotated.idToken) return\n let claims\n try {\n claims = await verifyIdToken(rotated.idToken, { authority: issuer, clientId })\n } catch {\n return // Unverifiable -> never adopt.\n }\n // Identity pinning: a broadcast must not switch the active user.\n if (currentUser && claims.sub !== currentUser.id) return\n\n // Under DPoP each tab owns its own key, so the leader's refresh token is\n // bound to a different cnf.jkt. Adopting it would poison the family on\n // the next renew. Drop the RT under DPoP; keep it otherwise.\n const dpopActive = dpop !== null\n await applyTokens({\n access_token: rotated.accessToken,\n id_token: rotated.idToken,\n refresh_token: dpopActive ? undefined : rotated.refreshToken,\n token_type: 'bearer',\n expires_in: Math.max(0, Math.floor((rotated.expiresAt - Date.now()) / 1000)),\n })\n }\n\n async function forceRenew(): Promise<string | undefined> {\n if (!renewInFlight) {\n renewInFlight = renewOnce(true).finally(() => {\n renewInFlight = null\n })\n }\n return renewInFlight\n }\n\n function isCallbackUrl(): boolean {\n if (typeof window === 'undefined') return false\n const s = window.location.search\n return s.includes('code=') || s.includes('error=')\n }\n\n async function completeLogin(): Promise<AtolSession> {\n if (!isCallbackUrl()) return session()\n const oidcUser = await manager.signinRedirectCallback()\n await adoptOidcUser(oidcUser)\n // Clean the code/state out of the address bar.\n if (typeof window !== 'undefined') {\n window.history.replaceState({}, document.title, window.location.pathname)\n }\n return session()\n }\n\n /** Adopt an oidc-client-ts User into session state. */\n async function adoptOidcUser(oidcUser: User): Promise<void> {\n accessToken = getAccessToken(oidcUser)\n // Only adopt a refresh token under the refresh-token strategy; the\n // default iframe model never renews from a stored RT.\n if (useRefreshTokens && oidcUser.refresh_token) {\n refreshToken = oidcUser.refresh_token\n }\n currentIdToken = getIdToken(oidcUser)\n currentUser = toUser(currentIdToken)\n scheduleRenew()\n await deriveEncKey()\n emit()\n }\n\n async function restoreSession(): Promise<void> {\n let oidcUser: User | null = await manager.getUser()\n if (oidcUser?.expired) oidcUser = null\n if (!oidcUser) {\n try {\n if (!restoreInFlight) {\n restoreInFlight = renewViaIframe()\n }\n const tokens = await restoreInFlight\n // In the iframe model, drop any stray RT before it reaches the store.\n oidcUser = userFromTokenResponse(\n useRefreshTokens ? tokens : { ...tokens, refresh_token: undefined },\n )\n await manager.storeUser(oidcUser)\n } catch (err) {\n // login_required is the normal \"no IdP session\" answer.\n if (!(err instanceof LoginRequiredError)) {\n // Non-terminal restore failures are swallowed: the on-demand path\n // retries on the next getAccessToken. Never log token material.\n }\n oidcUser = null\n } finally {\n restoreInFlight = null\n }\n }\n if (oidcUser) {\n await adoptOidcUser(oidcUser)\n } else {\n emit()\n }\n }\n\n let initPromise: Promise<AtolSession> | null = null\n\n async function init(): Promise<AtolSession> {\n if (initPromise) return initPromise\n initPromise = (async () => {\n // Capture the zero-knowledge KEK from the URL fragment FIRST, before\n // anything touches the URL. On a fresh login-callback the Atol\n // authorize endpoint delivers the KEK in the fragment\n // (`#atol_enc_key=...`) alongside the `?code=` query; completeLogin\n // strips the query below and extractKEKFromFragment strips the\n // fragment here, so this must run before either. Gated on the option:\n // when off, the fragment is never read. The captured KEK is consumed\n // once by deriveEncKey() to provision the vault.\n if (deriveEncryptionKey) {\n fragmentKEK = extractKEKFromFragment()\n }\n // DPoP key install (best-effort; null => Bearer).\n if (useDPoP) {\n dpop = await createDPoPKeyManager()\n }\n // Cross-tab broadcast wiring.\n broadcast = createTokenBroadcast(`atol:tokens:${issuer}:${clientId}`)\n broadcast.subscribe((message) => {\n void onBroadcast(message)\n })\n // Restore or complete-login.\n if (isCallbackUrl()) {\n try {\n await completeLogin()\n } catch {\n // A stale/failed callback settles unauthenticated; the caller can\n // retry beginLogin. Never surface token material in the error.\n clearSession()\n }\n } else {\n await restoreSession()\n }\n return session()\n })()\n return initPromise\n }\n\n async function beginLogin(options?: BeginLoginOptions): Promise<void> {\n const extraQueryParams: Record<string, string> = {}\n if (audience) extraQueryParams.audience = audience\n // Ask the issuer to mint the zero-knowledge encryption-key claim on the\n // ID token so a framework binding can derive the data-encryption key.\n if (deriveEncryptionKey) extraQueryParams.derive_encryption_key = 'true'\n // Step-up / forced-reauth parameters (OIDC Core). `prompt=login` re-prompts\n // for authentication; `max_age` caps the acceptable authentication age\n // (`max_age=0` forces a brand-new login); `acr_values` requests a specific\n // assurance level (e.g. \"mfa\"). Passed straight through to the authorize URL.\n if (options?.prompt) extraQueryParams.prompt = options.prompt\n if (options?.maxAge !== undefined) extraQueryParams.max_age = String(options.maxAge)\n if (options?.acrValues) extraQueryParams.acr_values = options.acrValues\n await manager.signinRedirect({\n redirect_uri:\n options?.returnTo && typeof window !== 'undefined'\n ? `${window.location.origin}${options.returnTo}`\n : redirectUri,\n extraQueryParams,\n })\n }\n\n async function stepUp(options?: StepUpOptions): Promise<void> {\n // A step-up is a forced re-authentication: prompt=login + max_age=0 so the\n // issuer mints a token with a fresh auth_time (and a completed second\n // factor), which the management API's step-up gate requires for sensitive\n // operations. Defaults request the \"mfa\" assurance level; callers may\n // override acrValues or set a non-zero maxAge.\n await beginLogin({\n returnTo: options?.returnTo,\n prompt: 'login',\n maxAge: options?.maxAge ?? 0,\n acrValues: options?.acrValues ?? 'mfa',\n })\n }\n\n async function logout(): Promise<void> {\n // Best-effort refresh-token revocation (RFC 7009) before we drop it.\n if (refreshToken) {\n await revokeToken(issuer, clientId, refreshToken).catch(() => undefined)\n }\n // Look up the id_token_hint for RP-initiated logout validation.\n let idTokenHint: string | undefined\n try {\n const u = await manager.getUser()\n idTokenHint = u?.id_token ?? undefined\n } catch {\n // getUser failure must not block logout.\n }\n clearSession()\n // Wipe the device-bound KEK vault so the next visit to this origin does\n // not silently rehydrate this user's DEK. Best-effort and non-blocking:\n // the logout redirect must not wait on IndexedDB, and a missing record\n // is fine (clear is idempotent). Only when the feature is on.\n if (deriveEncryptionKey) {\n void getVault().clear().catch(() => undefined)\n }\n await manager.signoutRedirect({\n post_logout_redirect_uri: redirectUri,\n ...(idTokenHint ? { id_token_hint: idTokenHint } : {}),\n })\n }\n\n async function getAccessTokenPublic(\n opts?: GetAccessTokenOptions,\n ): Promise<{ token: string; proof?: string } | undefined> {\n const token = await getToken()\n if (!token) return undefined\n if (opts?.dpop && dpop) {\n const proof = await dpop.signProof(opts.dpop.method, opts.dpop.url, {\n accessToken: token,\n })\n return { token, proof }\n }\n return { token }\n }\n\n async function signDPoPProof(\n method: string,\n url: string,\n ): Promise<DPoPProofResult | undefined> {\n const token = await getToken()\n if (!token) return undefined\n const proof = dpop ? await dpop.signProof(method, url, { accessToken: token }) : undefined\n return { token, proof }\n }\n\n function onSessionChange(cb: (s: AtolSession) => void): () => void {\n subscribers.add(cb)\n // Fire immediately with the current snapshot.\n try {\n cb(session())\n } catch {\n // ignore subscriber errors on initial fire\n }\n return () => {\n subscribers.delete(cb)\n }\n }\n\n function destroy(): void {\n if (destroyed) return\n destroyed = true\n clearRenewTimer()\n if (broadcast) {\n broadcast.close()\n broadcast = null\n }\n subscribers.clear()\n dpop = null\n // Best-effort zero the DEK buffer and drop derived encryption state.\n zeroEncKey()\n encError = undefined\n }\n\n return {\n init,\n beginLogin,\n stepUp,\n completeLogin,\n getAccessToken: getAccessTokenPublic,\n getIdToken: () => currentIdToken,\n getEncryptionKey: () => encKey,\n getEncryptionError: () => encError,\n logout,\n forceRenew,\n signDPoPProof,\n isDPoPActive: () => dpop !== null,\n onSessionChange,\n destroy,\n }\n}\n","import type { PermissionCheck } from '../claims/types'\nimport type { DPoPSigner } from '../oidc/silent-renew'\n\n/** Inputs for a bulk permission load. */\nexport interface LoadPermissionsOptions {\n /**\n * Control-plane API base URL (e.g. https://api.atol.sh). This is the\n * Connect-RPC host that serves AccessService -- NOT the OIDC issuer\n * (`authority`), which only mints tokens. Mixing them up sends the\n * authorization check to the wrong host.\n */\n apiUrl: string\n /** Publishable key ID (atol_kid_...). */\n keyId: string\n /** Bearer access token for the call. */\n accessToken: string\n /** Authenticated user's ID (JWT sub). */\n userId: string\n /** Authenticated user's org ID. */\n orgId: string\n /** Permission checks to evaluate. */\n checks: PermissionCheck[]\n /**\n * Optional DPoP signer. When the access token is DPoP-bound (`cnf.jkt`),\n * the resource server expects the `DPoP` auth scheme plus a proof whose\n * `ath` claim hashes the access token (RFC 9449 §4.3). Without this a\n * bound token is presented as plain Bearer and a strict server rejects\n * it -- or, worse, the sender-constraint is silently lost on the most\n * security-sensitive call in the SDK.\n */\n dpop?: DPoPSigner\n}\n\n/**\n * Bulk-load permissions from the Atol control plane.\n * Uses the batch-check endpoint with the user's JWT + publishable key.\n * Returns a Map keyed by \"action:resource\" -> boolean.\n */\nexport async function loadPermissions(\n opts: LoadPermissionsOptions,\n): Promise<Map<string, boolean>> {\n const { apiUrl, keyId, accessToken, userId, orgId, checks, dpop } = opts\n const permissions = new Map<string, boolean>()\n\n if (checks.length === 0) {\n return permissions\n }\n\n const body = {\n orgId: orgId,\n checks: checks.map((c) => ({\n user: `user:${userId}`,\n relation: c.action,\n object: c.resource,\n })),\n }\n\n // Use the Connect-go JSON endpoint (not REST) on the control-plane API host.\n const url = `${apiUrl.replace(/\\/+$/, '')}/atol.api.v1.AccessService/BatchCheckAccess`\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'X-Atol-Key': keyId,\n }\n // Present the token under the DPoP scheme with a bound proof when the\n // session uses sender-constrained tokens; otherwise plain Bearer.\n if (dpop) {\n headers['Authorization'] = `DPoP ${accessToken}`\n headers['DPoP'] = await dpop.signProof('POST', url, { accessToken })\n } else {\n headers['Authorization'] = `Bearer ${accessToken}`\n }\n\n const response = await fetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n })\n\n if (!response.ok) {\n throw new Error(`Permission check failed: HTTP ${response.status}`)\n }\n\n const data = (await response.json()) as { results?: Array<{ allowed?: boolean }> }\n const results = data.results ?? []\n\n // Fail loud on a shape mismatch: results are correlated to checks by\n // position, so a short/extra/reordered array would silently misattribute\n // allow/deny across (action, resource) pairs. Deny-by-default only holds\n // when the counts line up.\n if (results.length !== checks.length) {\n throw new Error(\n `Permission check returned ${results.length} results for ${checks.length} checks`,\n )\n }\n\n for (let i = 0; i < checks.length; i++) {\n const key = `${checks[i].action}:${checks[i].resource}`\n // Strict === true: any non-true value (missing, null, truthy-but-not-\n // boolean) denies.\n permissions.set(key, results[i]?.allowed === true)\n }\n\n return permissions\n}\n\n/** Build the permission map key from action + resource. */\nexport function permissionKey(action: string, resource: string): string {\n return `${action}:${resource}`\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,101 @@
1
+ {
2
+ "name": "@atol-sh/js",
3
+ "version": "0.1.0",
4
+ "description": "Atol core JS SDK - framework-agnostic browser security core: OIDC (PKCE), DPoP, silent renew, permissions, WebCrypto",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "main": "./dist/index.cjs",
8
+ "module": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "import": {
13
+ "types": "./dist/index.d.ts",
14
+ "default": "./dist/index.js"
15
+ },
16
+ "require": {
17
+ "types": "./dist/index.d.cts",
18
+ "default": "./dist/index.cjs"
19
+ },
20
+ "default": "./dist/index.js"
21
+ },
22
+ "./device": {
23
+ "import": {
24
+ "types": "./dist/device.d.ts",
25
+ "default": "./dist/device.js"
26
+ },
27
+ "require": {
28
+ "types": "./dist/device.d.cts",
29
+ "default": "./dist/device.cjs"
30
+ },
31
+ "default": "./dist/device.js"
32
+ },
33
+ "./package.json": "./package.json"
34
+ },
35
+ "sideEffects": false,
36
+ "files": [
37
+ "dist",
38
+ "CHANGELOG.md",
39
+ "NOTICE"
40
+ ],
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "scripts": {
45
+ "build": "tsup",
46
+ "dev": "tsup --watch",
47
+ "test": "vitest run",
48
+ "test:watch": "vitest",
49
+ "test:coverage": "vitest run --coverage",
50
+ "typecheck": "tsc --noEmit",
51
+ "lint": "tsc --noEmit",
52
+ "clean": "rm -rf dist",
53
+ "prepublishOnly": "npm run typecheck && npm test && npm run build",
54
+ "verify:pack": "publint && attw --pack . --profile node16"
55
+ },
56
+ "engines": {
57
+ "node": ">=18"
58
+ },
59
+ "author": "Atol",
60
+ "dependencies": {
61
+ "jose": "^5.10.0",
62
+ "oidc-client-ts": "^3.3.0"
63
+ },
64
+ "peerDependencies": {
65
+ "@atol-sh/fingerprint": ">=0.1.0"
66
+ },
67
+ "peerDependenciesMeta": {
68
+ "@atol-sh/fingerprint": {
69
+ "optional": true
70
+ }
71
+ },
72
+ "devDependencies": {
73
+ "@arethetypeswrong/cli": "^0.18.4",
74
+ "@types/node": "^22.20.0",
75
+ "@vitest/coverage-v8": "^3.2.6",
76
+ "fake-indexeddb": "^6.2.5",
77
+ "jsdom": "^26.1.0",
78
+ "publint": "^0.3.21",
79
+ "tsup": "^8.4.0",
80
+ "typescript": "^5.7.0",
81
+ "vitest": "^3.1.0"
82
+ },
83
+ "repository": {
84
+ "type": "git",
85
+ "url": "git+https://github.com/atol-sh/atol-sdk-js.git"
86
+ },
87
+ "homepage": "https://atol.sh",
88
+ "bugs": {
89
+ "url": "https://github.com/atol-sh/atol-sdk-js/issues"
90
+ },
91
+ "keywords": [
92
+ "atol",
93
+ "auth",
94
+ "authorization",
95
+ "oidc",
96
+ "pkce",
97
+ "dpop",
98
+ "webcrypto",
99
+ "permissions"
100
+ ]
101
+ }