@lumoauth/client 1.4.1 → 1.5.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.
- package/README.md +14 -4
- package/dist/index.d.mts +7 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +6 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +6 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -346,9 +346,9 @@ const found = await client.auth.checkEmailExists('ada@example.com');
|
|
|
346
346
|
// found.exists, found.passwordEnabled, found.passkeyEnabled, found.magicLinkEnabled,
|
|
347
347
|
// found.hasPasskey, found.hasPushDevice, found.maskedEmail, …
|
|
348
348
|
|
|
349
|
-
// Email a one-time sign-in link. The
|
|
350
|
-
// so the response never reveals
|
|
351
|
-
await client.auth.requestMagicLink({ email: 'ada@example.com',
|
|
349
|
+
// Email a one-time sign-in link. The answer is { sent: true } whether or not
|
|
350
|
+
// the account exists, so the response never reveals that.
|
|
351
|
+
await client.auth.requestMagicLink({ email: 'ada@example.com', returnTo: 'https://myapp.example.com/signed-in' });
|
|
352
352
|
|
|
353
353
|
// Sign in with a password on your own form
|
|
354
354
|
const result = await client.auth.loginWithPassword({ email, password });
|
|
@@ -363,6 +363,16 @@ if (result.status === 'complete') {
|
|
|
363
363
|
`checkEmailExists` never throws for a network failure or an unknown email. It returns an object
|
|
364
364
|
in which every flag is `false`, so your screen can fall back to the hosted login page.
|
|
365
365
|
|
|
366
|
+
`requestMagicLink` names your application (`clientId`) and sends no cookie. From a browser, the
|
|
367
|
+
origin of your app must be one of the application's allowed origins. The link opens a
|
|
368
|
+
confirmation page at LumoAuth. After the person confirms, they are signed in at LumoAuth and sent
|
|
369
|
+
to `returnTo`: a page of your app on an allowed origin or on the origin of a redirect URI, with at
|
|
370
|
+
most 1,024 characters. Start the PKCE redirect on that page. LumoAuth issues a code without
|
|
371
|
+
showing its own login page. The call throws a `LumoAuthApiError` when the server refuses the
|
|
372
|
+
request. `code` holds the reason: `magic_link_disabled`, `invalid_client`, `origin_not_allowed`,
|
|
373
|
+
`invalid_return_to`, `captcha_required`, `captcha_failed` or `rate_limited`. When the organization
|
|
374
|
+
protects sign-in link requests with a CAPTCHA, pass the token of the widget as `captchaToken`.
|
|
375
|
+
|
|
366
376
|
`loginWithPassword` returns one of these statuses: `complete`, `mfa_required`,
|
|
367
377
|
`invalid_credentials`, `blocked`, `inactive`, `rate_limited`, `invalid_request` or `error`. The
|
|
368
378
|
request is sent with `credentials: 'include'`, so your origin must be in the client's allowed
|
|
@@ -702,7 +712,7 @@ Every request and response also has a Zod schema, exported with its type, such a
|
|
|
702
712
|
| | `revokeToken(token, accessToken?)` | `void` | `orgId`, `clientId` |
|
|
703
713
|
| | `getUserInfo(accessToken)` | `UserInfo` | `orgId` |
|
|
704
714
|
| | `checkEmailExists(email)` | `EmailCheckResult` | `orgId` |
|
|
705
|
-
| | `requestMagicLink({ email,
|
|
715
|
+
| | `requestMagicLink({ email, returnTo?, captchaToken? })` | `{ sent: true }` | `orgId`, `clientId` |
|
|
706
716
|
| | `loginWithPassword({ email, password })` | `{ status, challengeUrl? }` | `orgId` |
|
|
707
717
|
| | `passwordGrant(username, password, …)` | `TokenResponse` | older grant; the organization must allow it |
|
|
708
718
|
| `agents` | `ask(action, context?)` / `isAllowed(action, context?)` | decision / `boolean` | `orgId` |
|
package/dist/index.d.mts
CHANGED
|
@@ -163,6 +163,13 @@ interface TokenStorage {
|
|
|
163
163
|
* cookies) can implement this so other tabs stay in sync.
|
|
164
164
|
*/
|
|
165
165
|
subscribe?(onExternalChange: () => void): () => void;
|
|
166
|
+
/**
|
|
167
|
+
* Optional. `true` when a same-origin server holds the tokens and
|
|
168
|
+
* `clear()` asks that server to end the session (the cookie adapter).
|
|
169
|
+
* The server then revokes the tokens, so the browser must not send a
|
|
170
|
+
* revocation request of its own.
|
|
171
|
+
*/
|
|
172
|
+
readonly serverManaged?: boolean;
|
|
166
173
|
}
|
|
167
174
|
/**
|
|
168
175
|
* Default. Per-tab, cleared when the tab closes.
|
package/dist/index.d.ts
CHANGED
|
@@ -163,6 +163,13 @@ interface TokenStorage {
|
|
|
163
163
|
* cookies) can implement this so other tabs stay in sync.
|
|
164
164
|
*/
|
|
165
165
|
subscribe?(onExternalChange: () => void): () => void;
|
|
166
|
+
/**
|
|
167
|
+
* Optional. `true` when a same-origin server holds the tokens and
|
|
168
|
+
* `clear()` asks that server to end the session (the cookie adapter).
|
|
169
|
+
* The server then revokes the tokens, so the browser must not send a
|
|
170
|
+
* revocation request of its own.
|
|
171
|
+
*/
|
|
172
|
+
readonly serverManaged?: boolean;
|
|
166
173
|
}
|
|
167
174
|
/**
|
|
168
175
|
* Default. Per-tab, cleared when the tab closes.
|
package/dist/index.js
CHANGED
|
@@ -197,6 +197,7 @@ function cookieStorageAdapter(options = {}) {
|
|
|
197
197
|
const doFetch = options.fetch ?? ((...a) => globalThis.fetch(...a));
|
|
198
198
|
return {
|
|
199
199
|
name: "cookie",
|
|
200
|
+
serverManaged: true,
|
|
200
201
|
async get() {
|
|
201
202
|
if (!hasWindow()) return EMPTY_TOKENS;
|
|
202
203
|
try {
|
|
@@ -222,7 +223,11 @@ function cookieStorageAdapter(options = {}) {
|
|
|
222
223
|
async clear() {
|
|
223
224
|
if (!hasWindow()) return;
|
|
224
225
|
try {
|
|
225
|
-
await doFetch(logoutEndpoint, {
|
|
226
|
+
await doFetch(logoutEndpoint, {
|
|
227
|
+
method: "POST",
|
|
228
|
+
credentials: "include",
|
|
229
|
+
redirect: "manual"
|
|
230
|
+
});
|
|
226
231
|
} catch {
|
|
227
232
|
}
|
|
228
233
|
}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/client.ts","../src/guard.ts","../src/storage.ts","../src/session.ts"],"sourcesContent":["// @lumoauth/client — the browser SDK.\n//\n// This is the package application code imports. It re-exports all of\n// @lumoauth/shared so callers need a single dependency, and adds the\n// `LumoAuth` client itself.\n//\n// It is browser-safe by construction: constructing it with a tenant API key\n// (`lmk_…`) in a browser is a hard error. Server-only surfaces live in\n// @lumoauth/backend (token verification, admin) and @lumoauth/agent (AAuth,\n// which needs `node:crypto`).\n\nexport { LumoAuth, type LumoAuthConfig, type ClientApprovals } from './client';\n\n// ─── Session runtime (framework-agnostic) ─────────────────────────────\n// The store @lumoauth/react binds to. Exported so a Vue/Svelte binding can\n// use the same runtime instead of reimplementing refresh and cross-tab logic.\nexport {\n LumoAuthSession,\n type SessionState,\n type SessionStatus,\n type SessionOptions,\n} from './session';\n\n// ─── Token storage ────────────────────────────────────────────────────\nexport {\n type TokenStorage,\n type StoredTokens,\n type CookieStorageOptions,\n EMPTY_TOKENS,\n sessionStorageAdapter,\n localStorageAdapter,\n memoryStorageAdapter,\n cookieStorageAdapter,\n defaultStorage,\n} from './storage';\n\n// The full isomorphic surface: authorization modules, OAuth/PKCE helpers,\n// schemas, errors, and the HTTP client.\nexport * from '@lumoauth/shared';\n","import {\n HttpClient,\n type HttpClientConfig,\n PermissionsModule,\n type PermissionsModuleOptions,\n ZanzibarModule,\n AbacModule,\n AuthModule,\n type AuthModuleConfig,\n AgentsModule,\n ApprovalsModule,\n LumoAuthConfigError,\n} from '@lumoauth/shared';\nimport { assertBrowserSafeCredential } from './guard';\n\n// ─── Config ───────────────────────────────────────────────────────────\n\nexport interface LumoAuthConfig {\n /**\n * Base URL of your LumoAuth instance.\n * @example \"https://auth.example.com\"\n */\n baseUrl: string;\n\n /**\n * Access token for the authenticated user.\n * Can be a static string or an async function that returns a fresh token.\n *\n * Optional — not needed before first sign-in when using PKCE flow.\n *\n * @example\n * // Static token\n * token: 'eyJhbGciOi...'\n *\n * // Dynamic token (recommended for SPAs & server-side)\n * token: () => getAccessTokenFromSession()\n */\n token?: string | (() => string | Promise<string>);\n\n /**\n * Authentication strategy.\n * - `'pkce'` — OAuth 2.0 Authorization Code + PKCE (default, recommended for SPAs)\n * - `'password'` — Resource Owner Password Credentials grant (legacy)\n *\n * @default 'pkce'\n */\n authStrategy?: 'pkce' | 'password';\n\n /**\n * Your organization ID (e.g. \"acme-corp\").\n * Required for building authorization URLs.\n */\n orgId?: string;\n\n /**\n * OAuth client ID.\n * Required when using the auth module.\n */\n clientId?: string;\n\n /** Request timeout in milliseconds. Default: 30 000 ms. */\n timeout?: number;\n\n /**\n * Custom `fetch` implementation.\n * Defaults to the global `fetch`. Useful for testing or\n * environments without a global `fetch` (e.g. older Node.js).\n */\n fetch?: typeof globalThis.fetch;\n\n /** Additional headers sent with every request. */\n headers?: Record<string, string>;\n\n /** Options for the permissions module cache. */\n cache?: boolean | PermissionsModuleOptions['cache'];\n}\n\n/**\n * Browser-safe subset of the approvals surface: status polling only.\n * Creating approvals lives on the server/agent SDKs.\n */\nexport type ClientApprovals = Pick<ApprovalsModule, 'getStatus' | 'wait'>;\n\n// ─── Client ───────────────────────────────────────────────────────────\n\n/**\n * The main LumoAuth client. Provides access to all authorization and\n * authentication modules.\n *\n * @example\n * ```ts\n * import { LumoAuth } from '@lumoauth/client';\n *\n * // PKCE mode (recommended)\n * const client = new LumoAuth({\n * baseUrl: 'https://auth.example.com',\n * orgId: 'acme-corp',\n * clientId: 'my-client-id',\n * });\n *\n * // Build authorization URL and redirect\n * const { url, codeVerifier, state } = await client.auth.buildAuthorizationUrl({\n * redirectUri: 'http://localhost:3000/callback',\n * });\n *\n * // Legacy mode with token\n * const authedClient = new LumoAuth({\n * baseUrl: 'https://auth.example.com',\n * token: () => getAccessToken(),\n * });\n *\n * // Permission checks (RBAC)\n * const canEdit = await authedClient.permissions.check('document.edit');\n * ```\n */\nexport class LumoAuth {\n /** RBAC permission checks. */\n public readonly permissions: PermissionsModule;\n /** Zanzibar-style (ReBAC) relationship checks. */\n public readonly zanzibar: ZanzibarModule;\n /** ABAC policy evaluation and attribute management. */\n public readonly abac: AbacModule;\n /** OAuth 2.0 authentication — PKCE flow, token exchange, refresh. */\n public readonly auth: AuthModule;\n /** Agent identity — ask/isAllowed and self-inspection. */\n public readonly agents: AgentsModule;\n /**\n * Approval status polling — the browser-safe subset of the approvals\n * surface. Creating approvals (`require()`) is an agent/server action;\n * use `@lumoauth/backend` or `@lumoauth/agent` for that.\n */\n public readonly approvals: ClientApprovals;\n\n private readonly http: HttpClient;\n\n constructor(config: LumoAuthConfig) {\n if (!config.baseUrl) {\n throw new LumoAuthConfigError('baseUrl is required');\n }\n\n // Refuse a server credential in a client that ships to browsers.\n // See ./guard for why this is a hard error rather than a warning.\n assertBrowserSafeCredential(config.token);\n\n // Token is optional when using PKCE flow (no token before first sign-in)\n const tokenProvider = config.token ?? (() => '');\n\n const httpConfig: HttpClientConfig = {\n baseUrl: config.baseUrl,\n token: tokenProvider,\n timeout: config.timeout,\n fetch: config.fetch,\n headers: config.headers,\n };\n\n this.http = new HttpClient(httpConfig);\n\n this.permissions = new PermissionsModule(this.http, {\n cache: config.cache,\n });\n this.zanzibar = new ZanzibarModule(this.http);\n this.abac = new AbacModule(this.http, config.orgId ?? '');\n\n // Auth module\n const authConfig: AuthModuleConfig = {\n baseUrl: config.baseUrl,\n orgId: config.orgId ?? '',\n clientId: config.clientId ?? '',\n fetch: config.fetch,\n };\n this.auth = new AuthModule(authConfig);\n\n // Agents module — org-scoped, so it needs `orgId`; the guard fires\n // lazily when a method is called.\n this.agents = new AgentsModule(this.http, config.orgId ?? '');\n\n // Approvals — browser-safe subset (status polling only).\n const approvals = new ApprovalsModule(this.http, config.orgId ?? '');\n this.approvals = {\n getStatus: approvals.getStatus.bind(approvals),\n wait: approvals.wait.bind(approvals),\n };\n }\n\n /**\n * @deprecated Renamed to {@link agents}. This alias will be removed\n * before 2.0.\n */\n get agent(): AgentsModule {\n return this.agents;\n }\n\n /**\n * Clear all client-side caches.\n * Call after the user's roles, groups, or attributes change.\n */\n clearCache(): void {\n this.permissions.clearCache();\n }\n}\n","import { LumoAuthConfigError } from '@lumoauth/shared';\n\n/**\n * Prefix of a LumoAuth tenant API key (`TenantApiKeyService::KEY_PREFIX`).\n * These are server credentials: they authenticate as the tenant, not as a\n * user, and they do not expire on their own.\n */\nconst TENANT_API_KEY_PREFIX = 'lmk_';\n\n/** True when this code is executing in something that looks like a browser. */\nfunction inBrowser(): boolean {\n return typeof window !== 'undefined' && typeof window.document !== 'undefined';\n}\n\n/**\n * Reject server credentials in `@lumoauth/client`.\n *\n * `@lumoauth/client` is designed to ship to browsers, where anything it holds\n * is readable by the user and by any script on the origin. A user access token\n * is fine there — it is short-lived and scoped to one person. A tenant API key\n * (`lmk_…`) is not: it authenticates as the whole organization.\n *\n * This is a hard error rather than a warning because the failure is silent\n * otherwise. The mistake it prevents is the easy one: copying a server-side\n * setup (`token: process.env.LUMOAUTH_AGENT_TOKEN`) into a component that ends\n * up in the client bundle. Nothing else catches that — bundlers happily inline\n * the value, and the request succeeds, so it looks like it works.\n *\n * Server-side code should import `@lumoauth/backend` instead, which accepts\n * these credentials and refuses to construct in a browser.\n *\n * Only static string tokens can be checked here. A `() => string` provider is\n * resolved per-request and may legitimately return a user token, so it is left\n * alone — the guard cannot tell the two apart without calling it.\n */\nexport function assertBrowserSafeCredential(\n token: string | (() => string | Promise<string>) | undefined,\n): void {\n if (typeof token !== 'string' || token === '') return;\n if (!token.startsWith(TENANT_API_KEY_PREFIX)) return;\n if (!inBrowser()) return;\n\n throw new LumoAuthConfigError(\n 'Refusing to use a LumoAuth tenant API key (lmk_…) in @lumoauth/client. ' +\n 'This package runs in the browser, where the key would be readable by ' +\n 'anyone using the app, and it authenticates as your entire organization. ' +\n 'Use a per-user access token here, and move any code that needs the API ' +\n 'key to the server with @lumoauth/backend.',\n );\n}\n","/**\n * Token storage adapters.\n *\n * Where tokens live is the single most consequential security decision in a\n * browser SDK, and the right answer depends on the app. This module makes it a\n * choice rather than a hardcoded default.\n *\n * The trade-off:\n *\n * | Adapter | XSS-readable | Survives reload | Cross-tab | SSR |\n * |------------------|--------------|-----------------|-----------|-----|\n * | `sessionStorage` | yes | per tab | no | no |\n * | `localStorage` | yes | yes | yes | no |\n * | `memory` | no* | no | no | yes |\n * | `cookie` (BFF) | no | yes | yes | yes |\n *\n * \\* memory is not readable from another origin's script, but it is still in\n * the JS heap; it is \"safe\" only in the sense that nothing persists.\n *\n * `cookie` is the strongest option: tokens live in an httpOnly cookie your\n * server sets, and never enter JavaScript at all. It requires a same-origin\n * backend to exchange and refresh on the browser's behalf, which is what\n * @lumoauth/express and (Phase 3) @lumoauth/nextjs provide.\n */\n\nexport interface StoredTokens {\n accessToken: string | null;\n refreshToken: string | null;\n idToken: string | null;\n /** Absolute expiry, epoch milliseconds. */\n expiresAt: number | null;\n}\n\nexport const EMPTY_TOKENS: StoredTokens = {\n accessToken: null,\n refreshToken: null,\n idToken: null,\n expiresAt: null,\n};\n\nexport interface TokenStorage {\n /** Identifies the adapter in errors and diagnostics. */\n readonly name: string;\n get(): StoredTokens | Promise<StoredTokens>;\n set(tokens: StoredTokens): void | Promise<void>;\n clear(): void | Promise<void>;\n /**\n * Optional. Called when the store changes outside this tab; return an\n * unsubscribe function. Adapters backed by a shared medium (localStorage,\n * cookies) can implement this so other tabs stay in sync.\n */\n subscribe?(onExternalChange: () => void): () => void;\n}\n\nconst TOKEN_KEY = 'lumoauth_tokens';\n\nfunction hasWindow(): boolean {\n return typeof window !== 'undefined';\n}\n\n/** Parse without throwing — corrupt storage should sign the user out, not crash. */\nfunction parse(raw: string | null): StoredTokens {\n if (!raw) return EMPTY_TOKENS;\n try {\n const v = JSON.parse(raw) as Partial<StoredTokens>;\n return {\n accessToken: v.accessToken ?? null,\n refreshToken: v.refreshToken ?? null,\n idToken: v.idToken ?? null,\n expiresAt: typeof v.expiresAt === 'number' ? v.expiresAt : null,\n };\n } catch {\n return EMPTY_TOKENS;\n }\n}\n\nfunction webStorageAdapter(\n name: string,\n pick: () => Storage | null,\n crossTab: boolean,\n): TokenStorage {\n const store = (): Storage | null => {\n if (!hasWindow()) return null;\n try {\n return pick();\n } catch {\n // Private browsing and some embedded webviews throw on access.\n return null;\n }\n };\n\n return {\n name,\n get() {\n try {\n return parse(store()?.getItem(TOKEN_KEY) ?? null);\n } catch {\n return EMPTY_TOKENS;\n }\n },\n set(tokens) {\n try {\n const s = store();\n if (!s) return;\n if (tokens.accessToken) s.setItem(TOKEN_KEY, JSON.stringify(tokens));\n else s.removeItem(TOKEN_KEY);\n } catch {\n // Quota or private-browsing failure: the session degrades to\n // in-memory for this tab rather than breaking sign-in.\n }\n },\n clear() {\n try {\n store()?.removeItem(TOKEN_KEY);\n } catch {\n /* ignore */\n }\n },\n // Only localStorage raises `storage` in other tabs. sessionStorage is\n // per-tab by definition, so there is nothing to subscribe to.\n subscribe: crossTab\n ? (onExternalChange) => {\n if (!hasWindow()) return () => {};\n const handler = (e: StorageEvent) => {\n if (e.key === TOKEN_KEY || e.key === null) onExternalChange();\n };\n window.addEventListener('storage', handler);\n return () => window.removeEventListener('storage', handler);\n }\n : undefined,\n };\n}\n\n/**\n * Default. Per-tab, cleared when the tab closes.\n *\n * Note this means a new tab starts signed out and must complete a redirect\n * round-trip. Use {@link localStorageAdapter} to share the session across tabs,\n * or {@link cookieStorageAdapter} to keep tokens out of JavaScript entirely.\n */\nexport function sessionStorageAdapter(): TokenStorage {\n return webStorageAdapter('sessionStorage', () => window.sessionStorage, false);\n}\n\n/** Shared across tabs and survives a browser restart. Still XSS-readable. */\nexport function localStorageAdapter(): TokenStorage {\n return webStorageAdapter('localStorage', () => window.localStorage, true);\n}\n\n/**\n * In-memory only. Nothing persists, so a reload signs the user out.\n *\n * This is the correct default on the server: it is inert during SSR instead of\n * touching a `window` that does not exist.\n */\nexport function memoryStorageAdapter(): TokenStorage {\n let tokens: StoredTokens = EMPTY_TOKENS;\n return {\n name: 'memory',\n get: () => tokens,\n set: (t) => {\n tokens = t;\n },\n clear: () => {\n tokens = EMPTY_TOKENS;\n },\n };\n}\n\nexport interface CookieStorageOptions {\n /**\n * Same-origin endpoint that returns the current session as JSON\n * (`{accessToken, expiresAt, ...}`) reading it from an httpOnly cookie.\n * @default '/auth/session'\n */\n sessionEndpoint?: string;\n /**\n * Same-origin endpoint that clears the session cookie.\n * @default '/auth/logout'\n */\n logoutEndpoint?: string;\n fetch?: typeof globalThis.fetch;\n}\n\n/**\n * Backend-for-frontend adapter: tokens live in an httpOnly cookie and are never\n * exposed to JavaScript.\n *\n * This is the only option here that survives XSS. The cost is that a\n * same-origin server must own the OAuth exchange and refresh —\n * @lumoauth/express already provides those routes.\n *\n * `set()` is intentionally a no-op: the browser cannot write an httpOnly\n * cookie, so only the server may establish the session. Reads go over the\n * network, so the session store caches them rather than calling per request.\n */\nexport function cookieStorageAdapter(options: CookieStorageOptions = {}): TokenStorage {\n const sessionEndpoint = options.sessionEndpoint ?? '/auth/session';\n const logoutEndpoint = options.logoutEndpoint ?? '/auth/logout';\n const doFetch = options.fetch ?? ((...a: Parameters<typeof fetch>) => globalThis.fetch(...a));\n\n return {\n name: 'cookie',\n async get() {\n if (!hasWindow()) return EMPTY_TOKENS;\n try {\n const res = await doFetch(sessionEndpoint, {\n credentials: 'include',\n headers: { Accept: 'application/json' },\n });\n if (!res.ok) return EMPTY_TOKENS;\n const data = (await res.json()) as Partial<StoredTokens>;\n return {\n accessToken: data.accessToken ?? null,\n refreshToken: null, // never leaves the server\n idToken: data.idToken ?? null,\n expiresAt: typeof data.expiresAt === 'number' ? data.expiresAt : null,\n };\n } catch {\n return EMPTY_TOKENS;\n }\n },\n set() {\n // No-op by design — see the note above.\n },\n async clear() {\n if (!hasWindow()) return;\n try {\n await doFetch(logoutEndpoint, { method: 'POST', credentials: 'include' });\n } catch {\n /* best-effort */\n }\n },\n };\n}\n\n/**\n * The default: `sessionStorage` in a browser, memory on the server.\n *\n * Chosen so that importing the SDK into an SSR framework does not blow up on a\n * missing `window`, while browser behaviour is unchanged.\n */\nexport function defaultStorage(): TokenStorage {\n return hasWindow() ? sessionStorageAdapter() : memoryStorageAdapter();\n}\n","import { AuthModule, type TokenResponse } from '@lumoauth/shared';\nimport {\n defaultStorage,\n EMPTY_TOKENS,\n type StoredTokens,\n type TokenStorage,\n} from './storage';\n\n/**\n * Framework-agnostic session runtime.\n *\n * This owns everything that is not React: token persistence, the refresh\n * schedule, the PKCE handshake, and cross-tab coordination. `@lumoauth/react`\n * is a thin binding over it, and a Vue or Svelte binding would be the same\n * shape — which is the reason this exists as a standalone class rather than\n * living inside a provider component.\n *\n * Subscribe/getSnapshot are deliberately shaped for React's\n * `useSyncExternalStore`, but they are plain functions with no React\n * dependency.\n */\n\nexport type SessionStatus = 'loading' | 'authenticated' | 'unauthenticated';\n\nexport interface SessionState {\n status: SessionStatus;\n isLoaded: boolean;\n isSignedIn: boolean;\n /**\n * Why the last operation failed, if it did. The previous implementation\n * discarded this — an ERROR action collapsed to `unauthenticated` and the\n * message was dropped, so callers could not tell \"signed out\" from\n * \"refresh failed\".\n */\n error: string | null;\n}\n\nconst INITIAL: SessionState = {\n status: 'loading',\n isLoaded: false,\n isSignedIn: false,\n error: null,\n};\n\n/** Refresh this long before expiry rather than at it. */\nconst REFRESH_MARGIN_MS = 60_000;\n/** `getToken()` refreshes proactively inside this window. */\nconst PROACTIVE_WINDOW_MS = 30_000;\n/** Never schedule a timer shorter than this, to avoid a refresh storm. */\nconst MIN_TIMER_MS = 5_000;\n\n/** Cross-tab channel name. Also used as the leader-election lock name. */\nconst CHANNEL = 'lumoauth.session';\n\nexport interface SessionOptions {\n auth: AuthModule;\n redirectUri: string;\n scope?: string;\n storage?: TokenStorage;\n /**\n * Share the session across tabs. When enabled, a token refresh in one tab\n * is broadcast to the others, and only one tab performs the refresh.\n *\n * Independent of the storage adapter: `sessionStorage` is per-tab, so\n * broadcasting keeps siblings live for the current session even though\n * nothing is shared on disk.\n * @default true\n */\n crossTab?: boolean;\n /** Called after tokens change, so the host can refetch the user. */\n onTokens?: (tokens: StoredTokens) => void;\n}\n\ninterface Broadcast {\n type: 'tokens' | 'signout';\n tokens?: StoredTokens;\n}\n\nexport class LumoAuthSession {\n private state: SessionState = INITIAL;\n private tokens: StoredTokens = EMPTY_TOKENS;\n private listeners = new Set<() => void>();\n private timer: ReturnType<typeof setTimeout> | null = null;\n private channel: BroadcastChannel | null = null;\n private unsubscribeStorage: (() => void) | null = null;\n private inflightRefresh: Promise<string | null> | null = null;\n\n private readonly auth: AuthModule;\n private readonly storage: TokenStorage;\n private readonly redirectUri: string;\n private readonly scope: string;\n private readonly onTokens?: (t: StoredTokens) => void;\n\n constructor(opts: SessionOptions) {\n this.auth = opts.auth;\n this.storage = opts.storage ?? defaultStorage();\n this.redirectUri = opts.redirectUri;\n this.scope = opts.scope ?? 'openid profile email';\n this.onTokens = opts.onTokens;\n\n if (opts.crossTab !== false && typeof BroadcastChannel !== 'undefined') {\n this.channel = new BroadcastChannel(CHANNEL);\n this.channel.onmessage = (e: MessageEvent<Broadcast>) => this.onBroadcast(e.data);\n }\n this.unsubscribeStorage =\n this.storage.subscribe?.(() => {\n void this.hydrate();\n }) ?? null;\n }\n\n // ── Store interface ──────────────────────────────────────────────\n\n subscribe = (fn: () => void): (() => void) => {\n this.listeners.add(fn);\n return () => this.listeners.delete(fn);\n };\n\n getSnapshot = (): SessionState => this.state;\n\n /** Server snapshot for `useSyncExternalStore` — always the loading state. */\n getServerSnapshot = (): SessionState => INITIAL;\n\n private emit(next: Partial<SessionState>): void {\n this.state = { ...this.state, ...next };\n this.listeners.forEach((l) => l());\n }\n\n // ── Lifecycle ────────────────────────────────────────────────────\n\n /** Load persisted tokens and settle into signed-in or signed-out. */\n async hydrate(): Promise<void> {\n const tokens = await this.storage.get();\n this.tokens = tokens;\n\n if (!tokens.accessToken) {\n this.emit({ status: 'unauthenticated', isLoaded: true, isSignedIn: false });\n return;\n }\n if (tokens.expiresAt && tokens.expiresAt <= Date.now()) {\n const refreshed = await this.refresh();\n if (!refreshed) return; // refresh() already emitted signed-out\n }\n this.scheduleRefresh();\n this.emit({ status: 'authenticated', isLoaded: true, isSignedIn: true, error: null });\n this.onTokens?.(this.tokens);\n }\n\n dispose(): void {\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n this.channel?.close();\n this.channel = null;\n this.unsubscribeStorage?.();\n this.unsubscribeStorage = null;\n this.listeners.clear();\n }\n\n // ── Tokens ───────────────────────────────────────────────────────\n\n getTokens(): Readonly<StoredTokens> {\n return this.tokens;\n }\n\n private async persist(tokens: StoredTokens, broadcast = true): Promise<void> {\n this.tokens = tokens;\n await this.storage.set(tokens);\n if (broadcast) this.channel?.postMessage({ type: 'tokens', tokens } satisfies Broadcast);\n this.onTokens?.(tokens);\n }\n\n static tokensFrom(res: TokenResponse, previous?: StoredTokens): StoredTokens {\n return {\n accessToken: res.access_token,\n // A refresh response may omit the refresh token when it is not\n // rotated; keep the existing one rather than losing the session.\n refreshToken: res.refresh_token ?? previous?.refreshToken ?? null,\n idToken: res.id_token ?? previous?.idToken ?? null,\n expiresAt: Date.now() + res.expires_in * 1000,\n };\n }\n\n /**\n * A valid access token, refreshing first if it is about to expire.\n * Returns null when there is no session.\n */\n async getToken(): Promise<string | null> {\n const { accessToken, expiresAt } = this.tokens;\n if (!accessToken) return null;\n if (expiresAt && expiresAt - Date.now() < PROACTIVE_WINDOW_MS) {\n return this.refresh();\n }\n return accessToken;\n }\n\n /**\n * Refresh the access token.\n *\n * Concurrent callers share one in-flight request. Across tabs, a Web Lock\n * elects a single refresher — without it, every tab refreshes on its own\n * timer and they race on a rotated refresh token, so all but the winner\n * are signed out.\n */\n async refresh(): Promise<string | null> {\n if (this.inflightRefresh) return this.inflightRefresh;\n this.inflightRefresh = this.doRefresh().finally(() => {\n this.inflightRefresh = null;\n });\n return this.inflightRefresh;\n }\n\n private async doRefresh(): Promise<string | null> {\n if (!this.tokens.refreshToken) {\n await this.clearSession('no_refresh_token');\n return null;\n }\n\n const run = async (): Promise<string | null> => {\n // Another tab may have refreshed while we waited for the lock.\n //\n // Check BOTH the shared store and our own in-memory tokens. Storage\n // alone is not enough: with a per-tab adapter (the default,\n // sessionStorage) `storage.get()` returns this tab's private copy\n // and never sees the winner's rotated token — but the winner also\n // broadcasts, and onBroadcast() updates `this.tokens`. Consulting\n // both makes the check work for shared and per-tab adapters alike.\n const stored = await this.storage.get();\n const fresher = [stored, this.tokens]\n .filter((t) => t.accessToken && t.expiresAt)\n .sort((a, b) => (b.expiresAt ?? 0) - (a.expiresAt ?? 0))[0];\n\n if (fresher && (fresher.expiresAt ?? 0) - Date.now() > PROACTIVE_WINDOW_MS) {\n this.tokens = fresher;\n this.scheduleRefresh();\n return fresher.accessToken;\n }\n\n // Read the refresh token HERE, inside the lock, not before waiting\n // for it. The server rotates and revokes on use, so a value\n // captured before the lock is already spent by the time the loser\n // acquires it — the request 400s and the tab is signed out.\n const refreshToken = this.tokens.refreshToken;\n if (!refreshToken) {\n await this.clearSession('no_refresh_token');\n return null;\n }\n\n try {\n const res = await this.auth.refreshToken(refreshToken);\n await this.persist(LumoAuthSession.tokensFrom(res, this.tokens));\n this.scheduleRefresh();\n this.emit({ status: 'authenticated', isLoaded: true, isSignedIn: true, error: null });\n return this.tokens.accessToken;\n } catch {\n await this.clearSession('refresh_failed');\n return null;\n }\n };\n\n const locks = (globalThis as { navigator?: { locks?: LockManager } }).navigator?.locks;\n if (locks?.request) {\n return locks.request(CHANNEL + '.refresh', run) as Promise<string | null>;\n }\n return run();\n }\n\n private scheduleRefresh(): void {\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n const { expiresAt, refreshToken } = this.tokens;\n if (!expiresAt || !refreshToken) return;\n const delay = Math.max(expiresAt - Date.now() - REFRESH_MARGIN_MS, MIN_TIMER_MS);\n this.timer = setTimeout(() => void this.refresh(), delay);\n }\n\n // ── Flows ────────────────────────────────────────────────────────\n\n /** Adopt tokens obtained elsewhere (e.g. a completed code exchange). */\n async adopt(res: TokenResponse): Promise<void> {\n await this.persist(LumoAuthSession.tokensFrom(res, this.tokens));\n this.scheduleRefresh();\n this.emit({ status: 'authenticated', isLoaded: true, isSignedIn: true, error: null });\n }\n\n /** Build the PKCE authorization URL; the caller persists verifier + state. */\n buildAuthorizationUrl(extraParams?: Record<string, string>) {\n return this.auth.buildAuthorizationUrl({\n redirectUri: this.redirectUri,\n scope: this.scope,\n ...(extraParams ? { extraParams } : {}),\n });\n }\n\n /**\n * Drop the session.\n *\n * `emit: false` clears tokens and storage without notifying subscribers.\n * That is required during sign-out: emitting re-renders the tree, which\n * mounts any `<SignedOut><RedirectToSignIn/></SignedOut>` guard, whose\n * effect then races the pending logout navigation and sends the user back\n * to /authorize — where the IdP session is still alive and silently\n * re-issues a code, defeating logout entirely.\n */\n async clearSession(\n error: string | null = null,\n opts: { broadcast?: boolean; emit?: boolean } = {},\n ): Promise<void> {\n const { broadcast = true, emit = true } = opts;\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n this.tokens = EMPTY_TOKENS;\n await this.storage.clear();\n if (broadcast) this.channel?.postMessage({ type: 'signout' } satisfies Broadcast);\n if (emit) {\n this.emit({ status: 'unauthenticated', isLoaded: true, isSignedIn: false, error });\n }\n }\n\n // ── Cross-tab ────────────────────────────────────────────────────\n\n private onBroadcast(msg: Broadcast): void {\n if (!msg) return;\n if (msg.type === 'signout') {\n // Do not re-broadcast: that would ping-pong between tabs.\n void this.clearSession(null, { broadcast: false });\n return;\n }\n if (msg.type === 'tokens' && msg.tokens) {\n this.tokens = msg.tokens;\n this.scheduleRefresh();\n this.emit({ status: 'authenticated', isLoaded: true, isSignedIn: true, error: null });\n this.onTokens?.(msg.tokens);\n }\n }\n}\n\n/** Minimal shape of the Web Locks API; not in every lib.dom version. */\ninterface LockManager {\n request<T>(name: string, cb: () => Promise<T>): Promise<T>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,iBAYO;;;ACZP,oBAAoC;AAOpC,IAAM,wBAAwB;AAG9B,SAAS,YAAqB;AAC1B,SAAO,OAAO,WAAW,eAA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AAAA,EAGA,sBAAsB,aAAsC;AACxD,WAAO,KAAK,KAAK,sBAAsB;AAAA,MACnC,aAAa,KAAK;AAAA,MAClB,OAAO,KAAK;AAAA,MACZ,GAAI,cAAc,EAAE,YAAY,IAAI,CAAC;AAAA,IACzC,CAAC;AAAA,EACL;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,MAAM,aACF,QAAuB,MACvB,OAAgD,CAAC,GACpC;AACb,UAAM,EAAE,YAAY,MAAM,OAAO,KAAK,IAAI;AAC1C,QAAI,KAAK,MAAO,cAAa,KAAK,KAAK;AACvC,SAAK,QAAQ;AACb,SAAK,SAAS;AACd,UAAM,KAAK,QAAQ,MAAM;AACzB,QAAI,UAAW,MAAK,SAAS,YAAY,EAAE,MAAM,UAAU,CAAqB;AAChF,QAAI,MAAM;AACN,WAAK,KAAK,EAAE,QAAQ,mBAAmB,UAAU,MAAM,YAAY,OAAO,MAAM,CAAC;AAAA,IACrF;AAAA,EACJ;AAAA;AAAA,EAIQ,YAAY,KAAsB;AACtC,QAAI,CAAC,IAAK;AACV,QAAI,IAAI,SAAS,WAAW;AAExB,WAAK,KAAK,aAAa,MAAM,EAAE,WAAW,MAAM,CAAC;AACjD;AAAA,IACJ;AACA,QAAI,IAAI,SAAS,YAAY,IAAI,QAAQ;AACrC,WAAK,SAAS,IAAI;AAClB,WAAK,gBAAgB;AACrB,WAAK,KAAK,EAAE,QAAQ,iBAAiB,UAAU,MAAM,YAAY,MAAM,OAAO,KAAK,CAAC;AACpF,WAAK,WAAW,IAAI,MAAM;AAAA,IAC9B;AAAA,EACJ;AACJ;;;AJvSA,0BAAc,6BAtCd;","names":["import_shared"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/client.ts","../src/guard.ts","../src/storage.ts","../src/session.ts"],"sourcesContent":["// @lumoauth/client — the browser SDK.\n//\n// This is the package application code imports. It re-exports all of\n// @lumoauth/shared so callers need a single dependency, and adds the\n// `LumoAuth` client itself.\n//\n// It is browser-safe by construction: constructing it with a tenant API key\n// (`lmk_…`) in a browser is a hard error. Server-only surfaces live in\n// @lumoauth/backend (token verification, admin) and @lumoauth/agent (AAuth,\n// which needs `node:crypto`).\n\nexport { LumoAuth, type LumoAuthConfig, type ClientApprovals } from './client';\n\n// ─── Session runtime (framework-agnostic) ─────────────────────────────\n// The store @lumoauth/react binds to. Exported so a Vue/Svelte binding can\n// use the same runtime instead of reimplementing refresh and cross-tab logic.\nexport {\n LumoAuthSession,\n type SessionState,\n type SessionStatus,\n type SessionOptions,\n} from './session';\n\n// ─── Token storage ────────────────────────────────────────────────────\nexport {\n type TokenStorage,\n type StoredTokens,\n type CookieStorageOptions,\n EMPTY_TOKENS,\n sessionStorageAdapter,\n localStorageAdapter,\n memoryStorageAdapter,\n cookieStorageAdapter,\n defaultStorage,\n} from './storage';\n\n// The full isomorphic surface: authorization modules, OAuth/PKCE helpers,\n// schemas, errors, and the HTTP client.\nexport * from '@lumoauth/shared';\n","import {\n HttpClient,\n type HttpClientConfig,\n PermissionsModule,\n type PermissionsModuleOptions,\n ZanzibarModule,\n AbacModule,\n AuthModule,\n type AuthModuleConfig,\n AgentsModule,\n ApprovalsModule,\n LumoAuthConfigError,\n} from '@lumoauth/shared';\nimport { assertBrowserSafeCredential } from './guard';\n\n// ─── Config ───────────────────────────────────────────────────────────\n\nexport interface LumoAuthConfig {\n /**\n * Base URL of your LumoAuth instance.\n * @example \"https://auth.example.com\"\n */\n baseUrl: string;\n\n /**\n * Access token for the authenticated user.\n * Can be a static string or an async function that returns a fresh token.\n *\n * Optional — not needed before first sign-in when using PKCE flow.\n *\n * @example\n * // Static token\n * token: 'eyJhbGciOi...'\n *\n * // Dynamic token (recommended for SPAs & server-side)\n * token: () => getAccessTokenFromSession()\n */\n token?: string | (() => string | Promise<string>);\n\n /**\n * Authentication strategy.\n * - `'pkce'` — OAuth 2.0 Authorization Code + PKCE (default, recommended for SPAs)\n * - `'password'` — Resource Owner Password Credentials grant (legacy)\n *\n * @default 'pkce'\n */\n authStrategy?: 'pkce' | 'password';\n\n /**\n * Your organization ID (e.g. \"acme-corp\").\n * Required for building authorization URLs.\n */\n orgId?: string;\n\n /**\n * OAuth client ID.\n * Required when using the auth module.\n */\n clientId?: string;\n\n /** Request timeout in milliseconds. Default: 30 000 ms. */\n timeout?: number;\n\n /**\n * Custom `fetch` implementation.\n * Defaults to the global `fetch`. Useful for testing or\n * environments without a global `fetch` (e.g. older Node.js).\n */\n fetch?: typeof globalThis.fetch;\n\n /** Additional headers sent with every request. */\n headers?: Record<string, string>;\n\n /** Options for the permissions module cache. */\n cache?: boolean | PermissionsModuleOptions['cache'];\n}\n\n/**\n * Browser-safe subset of the approvals surface: status polling only.\n * Creating approvals lives on the server/agent SDKs.\n */\nexport type ClientApprovals = Pick<ApprovalsModule, 'getStatus' | 'wait'>;\n\n// ─── Client ───────────────────────────────────────────────────────────\n\n/**\n * The main LumoAuth client. Provides access to all authorization and\n * authentication modules.\n *\n * @example\n * ```ts\n * import { LumoAuth } from '@lumoauth/client';\n *\n * // PKCE mode (recommended)\n * const client = new LumoAuth({\n * baseUrl: 'https://auth.example.com',\n * orgId: 'acme-corp',\n * clientId: 'my-client-id',\n * });\n *\n * // Build authorization URL and redirect\n * const { url, codeVerifier, state } = await client.auth.buildAuthorizationUrl({\n * redirectUri: 'http://localhost:3000/callback',\n * });\n *\n * // Legacy mode with token\n * const authedClient = new LumoAuth({\n * baseUrl: 'https://auth.example.com',\n * token: () => getAccessToken(),\n * });\n *\n * // Permission checks (RBAC)\n * const canEdit = await authedClient.permissions.check('document.edit');\n * ```\n */\nexport class LumoAuth {\n /** RBAC permission checks. */\n public readonly permissions: PermissionsModule;\n /** Zanzibar-style (ReBAC) relationship checks. */\n public readonly zanzibar: ZanzibarModule;\n /** ABAC policy evaluation and attribute management. */\n public readonly abac: AbacModule;\n /** OAuth 2.0 authentication — PKCE flow, token exchange, refresh. */\n public readonly auth: AuthModule;\n /** Agent identity — ask/isAllowed and self-inspection. */\n public readonly agents: AgentsModule;\n /**\n * Approval status polling — the browser-safe subset of the approvals\n * surface. Creating approvals (`require()`) is an agent/server action;\n * use `@lumoauth/backend` or `@lumoauth/agent` for that.\n */\n public readonly approvals: ClientApprovals;\n\n private readonly http: HttpClient;\n\n constructor(config: LumoAuthConfig) {\n if (!config.baseUrl) {\n throw new LumoAuthConfigError('baseUrl is required');\n }\n\n // Refuse a server credential in a client that ships to browsers.\n // See ./guard for why this is a hard error rather than a warning.\n assertBrowserSafeCredential(config.token);\n\n // Token is optional when using PKCE flow (no token before first sign-in)\n const tokenProvider = config.token ?? (() => '');\n\n const httpConfig: HttpClientConfig = {\n baseUrl: config.baseUrl,\n token: tokenProvider,\n timeout: config.timeout,\n fetch: config.fetch,\n headers: config.headers,\n };\n\n this.http = new HttpClient(httpConfig);\n\n this.permissions = new PermissionsModule(this.http, {\n cache: config.cache,\n });\n this.zanzibar = new ZanzibarModule(this.http);\n this.abac = new AbacModule(this.http, config.orgId ?? '');\n\n // Auth module\n const authConfig: AuthModuleConfig = {\n baseUrl: config.baseUrl,\n orgId: config.orgId ?? '',\n clientId: config.clientId ?? '',\n fetch: config.fetch,\n };\n this.auth = new AuthModule(authConfig);\n\n // Agents module — org-scoped, so it needs `orgId`; the guard fires\n // lazily when a method is called.\n this.agents = new AgentsModule(this.http, config.orgId ?? '');\n\n // Approvals — browser-safe subset (status polling only).\n const approvals = new ApprovalsModule(this.http, config.orgId ?? '');\n this.approvals = {\n getStatus: approvals.getStatus.bind(approvals),\n wait: approvals.wait.bind(approvals),\n };\n }\n\n /**\n * @deprecated Renamed to {@link agents}. This alias will be removed\n * before 2.0.\n */\n get agent(): AgentsModule {\n return this.agents;\n }\n\n /**\n * Clear all client-side caches.\n * Call after the user's roles, groups, or attributes change.\n */\n clearCache(): void {\n this.permissions.clearCache();\n }\n}\n","import { LumoAuthConfigError } from '@lumoauth/shared';\n\n/**\n * Prefix of a LumoAuth tenant API key (`TenantApiKeyService::KEY_PREFIX`).\n * These are server credentials: they authenticate as the tenant, not as a\n * user, and they do not expire on their own.\n */\nconst TENANT_API_KEY_PREFIX = 'lmk_';\n\n/** True when this code is executing in something that looks like a browser. */\nfunction inBrowser(): boolean {\n return typeof window !== 'undefined' && typeof window.document !== 'undefined';\n}\n\n/**\n * Reject server credentials in `@lumoauth/client`.\n *\n * `@lumoauth/client` is designed to ship to browsers, where anything it holds\n * is readable by the user and by any script on the origin. A user access token\n * is fine there — it is short-lived and scoped to one person. A tenant API key\n * (`lmk_…`) is not: it authenticates as the whole organization.\n *\n * This is a hard error rather than a warning because the failure is silent\n * otherwise. The mistake it prevents is the easy one: copying a server-side\n * setup (`token: process.env.LUMOAUTH_AGENT_TOKEN`) into a component that ends\n * up in the client bundle. Nothing else catches that — bundlers happily inline\n * the value, and the request succeeds, so it looks like it works.\n *\n * Server-side code should import `@lumoauth/backend` instead, which accepts\n * these credentials and refuses to construct in a browser.\n *\n * Only static string tokens can be checked here. A `() => string` provider is\n * resolved per-request and may legitimately return a user token, so it is left\n * alone — the guard cannot tell the two apart without calling it.\n */\nexport function assertBrowserSafeCredential(\n token: string | (() => string | Promise<string>) | undefined,\n): void {\n if (typeof token !== 'string' || token === '') return;\n if (!token.startsWith(TENANT_API_KEY_PREFIX)) return;\n if (!inBrowser()) return;\n\n throw new LumoAuthConfigError(\n 'Refusing to use a LumoAuth tenant API key (lmk_…) in @lumoauth/client. ' +\n 'This package runs in the browser, where the key would be readable by ' +\n 'anyone using the app, and it authenticates as your entire organization. ' +\n 'Use a per-user access token here, and move any code that needs the API ' +\n 'key to the server with @lumoauth/backend.',\n );\n}\n","/**\n * Token storage adapters.\n *\n * Where tokens live is the single most consequential security decision in a\n * browser SDK, and the right answer depends on the app. This module makes it a\n * choice rather than a hardcoded default.\n *\n * The trade-off:\n *\n * | Adapter | XSS-readable | Survives reload | Cross-tab | SSR |\n * |------------------|--------------|-----------------|-----------|-----|\n * | `sessionStorage` | yes | per tab | no | no |\n * | `localStorage` | yes | yes | yes | no |\n * | `memory` | no* | no | no | yes |\n * | `cookie` (BFF) | no | yes | yes | yes |\n *\n * \\* memory is not readable from another origin's script, but it is still in\n * the JS heap; it is \"safe\" only in the sense that nothing persists.\n *\n * `cookie` is the strongest option: tokens live in an httpOnly cookie your\n * server sets, and never enter JavaScript at all. It requires a same-origin\n * backend to exchange and refresh on the browser's behalf, which is what\n * @lumoauth/express and (Phase 3) @lumoauth/nextjs provide.\n */\n\nexport interface StoredTokens {\n accessToken: string | null;\n refreshToken: string | null;\n idToken: string | null;\n /** Absolute expiry, epoch milliseconds. */\n expiresAt: number | null;\n}\n\nexport const EMPTY_TOKENS: StoredTokens = {\n accessToken: null,\n refreshToken: null,\n idToken: null,\n expiresAt: null,\n};\n\nexport interface TokenStorage {\n /** Identifies the adapter in errors and diagnostics. */\n readonly name: string;\n get(): StoredTokens | Promise<StoredTokens>;\n set(tokens: StoredTokens): void | Promise<void>;\n clear(): void | Promise<void>;\n /**\n * Optional. Called when the store changes outside this tab; return an\n * unsubscribe function. Adapters backed by a shared medium (localStorage,\n * cookies) can implement this so other tabs stay in sync.\n */\n subscribe?(onExternalChange: () => void): () => void;\n /**\n * Optional. `true` when a same-origin server holds the tokens and\n * `clear()` asks that server to end the session (the cookie adapter).\n * The server then revokes the tokens, so the browser must not send a\n * revocation request of its own.\n */\n readonly serverManaged?: boolean;\n}\n\nconst TOKEN_KEY = 'lumoauth_tokens';\n\nfunction hasWindow(): boolean {\n return typeof window !== 'undefined';\n}\n\n/** Parse without throwing — corrupt storage should sign the user out, not crash. */\nfunction parse(raw: string | null): StoredTokens {\n if (!raw) return EMPTY_TOKENS;\n try {\n const v = JSON.parse(raw) as Partial<StoredTokens>;\n return {\n accessToken: v.accessToken ?? null,\n refreshToken: v.refreshToken ?? null,\n idToken: v.idToken ?? null,\n expiresAt: typeof v.expiresAt === 'number' ? v.expiresAt : null,\n };\n } catch {\n return EMPTY_TOKENS;\n }\n}\n\nfunction webStorageAdapter(\n name: string,\n pick: () => Storage | null,\n crossTab: boolean,\n): TokenStorage {\n const store = (): Storage | null => {\n if (!hasWindow()) return null;\n try {\n return pick();\n } catch {\n // Private browsing and some embedded webviews throw on access.\n return null;\n }\n };\n\n return {\n name,\n get() {\n try {\n return parse(store()?.getItem(TOKEN_KEY) ?? null);\n } catch {\n return EMPTY_TOKENS;\n }\n },\n set(tokens) {\n try {\n const s = store();\n if (!s) return;\n if (tokens.accessToken) s.setItem(TOKEN_KEY, JSON.stringify(tokens));\n else s.removeItem(TOKEN_KEY);\n } catch {\n // Quota or private-browsing failure: the session degrades to\n // in-memory for this tab rather than breaking sign-in.\n }\n },\n clear() {\n try {\n store()?.removeItem(TOKEN_KEY);\n } catch {\n /* ignore */\n }\n },\n // Only localStorage raises `storage` in other tabs. sessionStorage is\n // per-tab by definition, so there is nothing to subscribe to.\n subscribe: crossTab\n ? (onExternalChange) => {\n if (!hasWindow()) return () => {};\n const handler = (e: StorageEvent) => {\n if (e.key === TOKEN_KEY || e.key === null) onExternalChange();\n };\n window.addEventListener('storage', handler);\n return () => window.removeEventListener('storage', handler);\n }\n : undefined,\n };\n}\n\n/**\n * Default. Per-tab, cleared when the tab closes.\n *\n * Note this means a new tab starts signed out and must complete a redirect\n * round-trip. Use {@link localStorageAdapter} to share the session across tabs,\n * or {@link cookieStorageAdapter} to keep tokens out of JavaScript entirely.\n */\nexport function sessionStorageAdapter(): TokenStorage {\n return webStorageAdapter('sessionStorage', () => window.sessionStorage, false);\n}\n\n/** Shared across tabs and survives a browser restart. Still XSS-readable. */\nexport function localStorageAdapter(): TokenStorage {\n return webStorageAdapter('localStorage', () => window.localStorage, true);\n}\n\n/**\n * In-memory only. Nothing persists, so a reload signs the user out.\n *\n * This is the correct default on the server: it is inert during SSR instead of\n * touching a `window` that does not exist.\n */\nexport function memoryStorageAdapter(): TokenStorage {\n let tokens: StoredTokens = EMPTY_TOKENS;\n return {\n name: 'memory',\n get: () => tokens,\n set: (t) => {\n tokens = t;\n },\n clear: () => {\n tokens = EMPTY_TOKENS;\n },\n };\n}\n\nexport interface CookieStorageOptions {\n /**\n * Same-origin endpoint that returns the current session as JSON\n * (`{accessToken, expiresAt, ...}`) reading it from an httpOnly cookie.\n * @default '/auth/session'\n */\n sessionEndpoint?: string;\n /**\n * Same-origin endpoint that clears the session cookie.\n * @default '/auth/logout'\n */\n logoutEndpoint?: string;\n fetch?: typeof globalThis.fetch;\n}\n\n/**\n * Backend-for-frontend adapter: tokens live in an httpOnly cookie and are never\n * exposed to JavaScript.\n *\n * This is the only option here that survives XSS. The cost is that a\n * same-origin server must own the OAuth exchange and refresh —\n * @lumoauth/express already provides those routes.\n *\n * `set()` is intentionally a no-op: the browser cannot write an httpOnly\n * cookie, so only the server may establish the session. Reads go over the\n * network, so the session store caches them rather than calling per request.\n */\nexport function cookieStorageAdapter(options: CookieStorageOptions = {}): TokenStorage {\n const sessionEndpoint = options.sessionEndpoint ?? '/auth/session';\n const logoutEndpoint = options.logoutEndpoint ?? '/auth/logout';\n const doFetch = options.fetch ?? ((...a: Parameters<typeof fetch>) => globalThis.fetch(...a));\n\n return {\n name: 'cookie',\n serverManaged: true,\n async get() {\n if (!hasWindow()) return EMPTY_TOKENS;\n try {\n const res = await doFetch(sessionEndpoint, {\n credentials: 'include',\n headers: { Accept: 'application/json' },\n });\n if (!res.ok) return EMPTY_TOKENS;\n const data = (await res.json()) as Partial<StoredTokens>;\n return {\n accessToken: data.accessToken ?? null,\n refreshToken: null, // never leaves the server\n idToken: data.idToken ?? null,\n expiresAt: typeof data.expiresAt === 'number' ? data.expiresAt : null,\n };\n } catch {\n return EMPTY_TOKENS;\n }\n },\n set() {\n // No-op by design — see the note above.\n },\n async clear() {\n if (!hasWindow()) return;\n try {\n // The logout route answers with a redirect to the LumoAuth\n // logout page. Do not follow it: the caller navigates there\n // itself, and following it from fetch() is a cross-origin\n // request that the browser blocks and logs as a CORS error.\n // The cookie is cleared by the redirect response either way.\n await doFetch(logoutEndpoint, {\n method: 'POST',\n credentials: 'include',\n redirect: 'manual',\n });\n } catch {\n /* best-effort */\n }\n },\n };\n}\n\n/**\n * The default: `sessionStorage` in a browser, memory on the server.\n *\n * Chosen so that importing the SDK into an SSR framework does not blow up on a\n * missing `window`, while browser behaviour is unchanged.\n */\nexport function defaultStorage(): TokenStorage {\n return hasWindow() ? sessionStorageAdapter() : memoryStorageAdapter();\n}\n","import { AuthModule, type TokenResponse } from '@lumoauth/shared';\nimport {\n defaultStorage,\n EMPTY_TOKENS,\n type StoredTokens,\n type TokenStorage,\n} from './storage';\n\n/**\n * Framework-agnostic session runtime.\n *\n * This owns everything that is not React: token persistence, the refresh\n * schedule, the PKCE handshake, and cross-tab coordination. `@lumoauth/react`\n * is a thin binding over it, and a Vue or Svelte binding would be the same\n * shape — which is the reason this exists as a standalone class rather than\n * living inside a provider component.\n *\n * Subscribe/getSnapshot are deliberately shaped for React's\n * `useSyncExternalStore`, but they are plain functions with no React\n * dependency.\n */\n\nexport type SessionStatus = 'loading' | 'authenticated' | 'unauthenticated';\n\nexport interface SessionState {\n status: SessionStatus;\n isLoaded: boolean;\n isSignedIn: boolean;\n /**\n * Why the last operation failed, if it did. The previous implementation\n * discarded this — an ERROR action collapsed to `unauthenticated` and the\n * message was dropped, so callers could not tell \"signed out\" from\n * \"refresh failed\".\n */\n error: string | null;\n}\n\nconst INITIAL: SessionState = {\n status: 'loading',\n isLoaded: false,\n isSignedIn: false,\n error: null,\n};\n\n/** Refresh this long before expiry rather than at it. */\nconst REFRESH_MARGIN_MS = 60_000;\n/** `getToken()` refreshes proactively inside this window. */\nconst PROACTIVE_WINDOW_MS = 30_000;\n/** Never schedule a timer shorter than this, to avoid a refresh storm. */\nconst MIN_TIMER_MS = 5_000;\n\n/** Cross-tab channel name. Also used as the leader-election lock name. */\nconst CHANNEL = 'lumoauth.session';\n\nexport interface SessionOptions {\n auth: AuthModule;\n redirectUri: string;\n scope?: string;\n storage?: TokenStorage;\n /**\n * Share the session across tabs. When enabled, a token refresh in one tab\n * is broadcast to the others, and only one tab performs the refresh.\n *\n * Independent of the storage adapter: `sessionStorage` is per-tab, so\n * broadcasting keeps siblings live for the current session even though\n * nothing is shared on disk.\n * @default true\n */\n crossTab?: boolean;\n /** Called after tokens change, so the host can refetch the user. */\n onTokens?: (tokens: StoredTokens) => void;\n}\n\ninterface Broadcast {\n type: 'tokens' | 'signout';\n tokens?: StoredTokens;\n}\n\nexport class LumoAuthSession {\n private state: SessionState = INITIAL;\n private tokens: StoredTokens = EMPTY_TOKENS;\n private listeners = new Set<() => void>();\n private timer: ReturnType<typeof setTimeout> | null = null;\n private channel: BroadcastChannel | null = null;\n private unsubscribeStorage: (() => void) | null = null;\n private inflightRefresh: Promise<string | null> | null = null;\n\n private readonly auth: AuthModule;\n private readonly storage: TokenStorage;\n private readonly redirectUri: string;\n private readonly scope: string;\n private readonly onTokens?: (t: StoredTokens) => void;\n\n constructor(opts: SessionOptions) {\n this.auth = opts.auth;\n this.storage = opts.storage ?? defaultStorage();\n this.redirectUri = opts.redirectUri;\n this.scope = opts.scope ?? 'openid profile email';\n this.onTokens = opts.onTokens;\n\n if (opts.crossTab !== false && typeof BroadcastChannel !== 'undefined') {\n this.channel = new BroadcastChannel(CHANNEL);\n this.channel.onmessage = (e: MessageEvent<Broadcast>) => this.onBroadcast(e.data);\n }\n this.unsubscribeStorage =\n this.storage.subscribe?.(() => {\n void this.hydrate();\n }) ?? null;\n }\n\n // ── Store interface ──────────────────────────────────────────────\n\n subscribe = (fn: () => void): (() => void) => {\n this.listeners.add(fn);\n return () => this.listeners.delete(fn);\n };\n\n getSnapshot = (): SessionState => this.state;\n\n /** Server snapshot for `useSyncExternalStore` — always the loading state. */\n getServerSnapshot = (): SessionState => INITIAL;\n\n private emit(next: Partial<SessionState>): void {\n this.state = { ...this.state, ...next };\n this.listeners.forEach((l) => l());\n }\n\n // ── Lifecycle ────────────────────────────────────────────────────\n\n /** Load persisted tokens and settle into signed-in or signed-out. */\n async hydrate(): Promise<void> {\n const tokens = await this.storage.get();\n this.tokens = tokens;\n\n if (!tokens.accessToken) {\n this.emit({ status: 'unauthenticated', isLoaded: true, isSignedIn: false });\n return;\n }\n if (tokens.expiresAt && tokens.expiresAt <= Date.now()) {\n const refreshed = await this.refresh();\n if (!refreshed) return; // refresh() already emitted signed-out\n }\n this.scheduleRefresh();\n this.emit({ status: 'authenticated', isLoaded: true, isSignedIn: true, error: null });\n this.onTokens?.(this.tokens);\n }\n\n dispose(): void {\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n this.channel?.close();\n this.channel = null;\n this.unsubscribeStorage?.();\n this.unsubscribeStorage = null;\n this.listeners.clear();\n }\n\n // ── Tokens ───────────────────────────────────────────────────────\n\n getTokens(): Readonly<StoredTokens> {\n return this.tokens;\n }\n\n private async persist(tokens: StoredTokens, broadcast = true): Promise<void> {\n this.tokens = tokens;\n await this.storage.set(tokens);\n if (broadcast) this.channel?.postMessage({ type: 'tokens', tokens } satisfies Broadcast);\n this.onTokens?.(tokens);\n }\n\n static tokensFrom(res: TokenResponse, previous?: StoredTokens): StoredTokens {\n return {\n accessToken: res.access_token,\n // A refresh response may omit the refresh token when it is not\n // rotated; keep the existing one rather than losing the session.\n refreshToken: res.refresh_token ?? previous?.refreshToken ?? null,\n idToken: res.id_token ?? previous?.idToken ?? null,\n expiresAt: Date.now() + res.expires_in * 1000,\n };\n }\n\n /**\n * A valid access token, refreshing first if it is about to expire.\n * Returns null when there is no session.\n */\n async getToken(): Promise<string | null> {\n const { accessToken, expiresAt } = this.tokens;\n if (!accessToken) return null;\n if (expiresAt && expiresAt - Date.now() < PROACTIVE_WINDOW_MS) {\n return this.refresh();\n }\n return accessToken;\n }\n\n /**\n * Refresh the access token.\n *\n * Concurrent callers share one in-flight request. Across tabs, a Web Lock\n * elects a single refresher — without it, every tab refreshes on its own\n * timer and they race on a rotated refresh token, so all but the winner\n * are signed out.\n */\n async refresh(): Promise<string | null> {\n if (this.inflightRefresh) return this.inflightRefresh;\n this.inflightRefresh = this.doRefresh().finally(() => {\n this.inflightRefresh = null;\n });\n return this.inflightRefresh;\n }\n\n private async doRefresh(): Promise<string | null> {\n if (!this.tokens.refreshToken) {\n await this.clearSession('no_refresh_token');\n return null;\n }\n\n const run = async (): Promise<string | null> => {\n // Another tab may have refreshed while we waited for the lock.\n //\n // Check BOTH the shared store and our own in-memory tokens. Storage\n // alone is not enough: with a per-tab adapter (the default,\n // sessionStorage) `storage.get()` returns this tab's private copy\n // and never sees the winner's rotated token — but the winner also\n // broadcasts, and onBroadcast() updates `this.tokens`. Consulting\n // both makes the check work for shared and per-tab adapters alike.\n const stored = await this.storage.get();\n const fresher = [stored, this.tokens]\n .filter((t) => t.accessToken && t.expiresAt)\n .sort((a, b) => (b.expiresAt ?? 0) - (a.expiresAt ?? 0))[0];\n\n if (fresher && (fresher.expiresAt ?? 0) - Date.now() > PROACTIVE_WINDOW_MS) {\n this.tokens = fresher;\n this.scheduleRefresh();\n return fresher.accessToken;\n }\n\n // Read the refresh token HERE, inside the lock, not before waiting\n // for it. The server rotates and revokes on use, so a value\n // captured before the lock is already spent by the time the loser\n // acquires it — the request 400s and the tab is signed out.\n const refreshToken = this.tokens.refreshToken;\n if (!refreshToken) {\n await this.clearSession('no_refresh_token');\n return null;\n }\n\n try {\n const res = await this.auth.refreshToken(refreshToken);\n await this.persist(LumoAuthSession.tokensFrom(res, this.tokens));\n this.scheduleRefresh();\n this.emit({ status: 'authenticated', isLoaded: true, isSignedIn: true, error: null });\n return this.tokens.accessToken;\n } catch {\n await this.clearSession('refresh_failed');\n return null;\n }\n };\n\n const locks = (globalThis as { navigator?: { locks?: LockManager } }).navigator?.locks;\n if (locks?.request) {\n return locks.request(CHANNEL + '.refresh', run) as Promise<string | null>;\n }\n return run();\n }\n\n private scheduleRefresh(): void {\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n const { expiresAt, refreshToken } = this.tokens;\n if (!expiresAt || !refreshToken) return;\n const delay = Math.max(expiresAt - Date.now() - REFRESH_MARGIN_MS, MIN_TIMER_MS);\n this.timer = setTimeout(() => void this.refresh(), delay);\n }\n\n // ── Flows ────────────────────────────────────────────────────────\n\n /** Adopt tokens obtained elsewhere (e.g. a completed code exchange). */\n async adopt(res: TokenResponse): Promise<void> {\n await this.persist(LumoAuthSession.tokensFrom(res, this.tokens));\n this.scheduleRefresh();\n this.emit({ status: 'authenticated', isLoaded: true, isSignedIn: true, error: null });\n }\n\n /** Build the PKCE authorization URL; the caller persists verifier + state. */\n buildAuthorizationUrl(extraParams?: Record<string, string>) {\n return this.auth.buildAuthorizationUrl({\n redirectUri: this.redirectUri,\n scope: this.scope,\n ...(extraParams ? { extraParams } : {}),\n });\n }\n\n /**\n * Drop the session.\n *\n * `emit: false` clears tokens and storage without notifying subscribers.\n * That is required during sign-out: emitting re-renders the tree, which\n * mounts any `<SignedOut><RedirectToSignIn/></SignedOut>` guard, whose\n * effect then races the pending logout navigation and sends the user back\n * to /authorize — where the IdP session is still alive and silently\n * re-issues a code, defeating logout entirely.\n */\n async clearSession(\n error: string | null = null,\n opts: { broadcast?: boolean; emit?: boolean } = {},\n ): Promise<void> {\n const { broadcast = true, emit = true } = opts;\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n this.tokens = EMPTY_TOKENS;\n await this.storage.clear();\n if (broadcast) this.channel?.postMessage({ type: 'signout' } satisfies Broadcast);\n if (emit) {\n this.emit({ status: 'unauthenticated', isLoaded: true, isSignedIn: false, error });\n }\n }\n\n // ── Cross-tab ────────────────────────────────────────────────────\n\n private onBroadcast(msg: Broadcast): void {\n if (!msg) return;\n if (msg.type === 'signout') {\n // Do not re-broadcast: that would ping-pong between tabs.\n void this.clearSession(null, { broadcast: false });\n return;\n }\n if (msg.type === 'tokens' && msg.tokens) {\n this.tokens = msg.tokens;\n this.scheduleRefresh();\n this.emit({ status: 'authenticated', isLoaded: true, isSignedIn: true, error: null });\n this.onTokens?.(msg.tokens);\n }\n }\n}\n\n/** Minimal shape of the Web Locks API; not in every lib.dom version.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AAiB,UAAU,MAAM,YAAY,MAAM,OAAO,KAAK,CAAC;AACpF,WAAK,WAAW,IAAI,MAAM;AAAA,IAC9B;AAAA,EACJ;AACJ;;;AJvSA,0BAAc,6BAtCd;","names":["import_shared"]}
|
package/dist/index.mjs
CHANGED
|
@@ -172,6 +172,7 @@ function cookieStorageAdapter(options = {}) {
|
|
|
172
172
|
const doFetch = options.fetch ?? ((...a) => globalThis.fetch(...a));
|
|
173
173
|
return {
|
|
174
174
|
name: "cookie",
|
|
175
|
+
serverManaged: true,
|
|
175
176
|
async get() {
|
|
176
177
|
if (!hasWindow()) return EMPTY_TOKENS;
|
|
177
178
|
try {
|
|
@@ -197,7 +198,11 @@ function cookieStorageAdapter(options = {}) {
|
|
|
197
198
|
async clear() {
|
|
198
199
|
if (!hasWindow()) return;
|
|
199
200
|
try {
|
|
200
|
-
await doFetch(logoutEndpoint, {
|
|
201
|
+
await doFetch(logoutEndpoint, {
|
|
202
|
+
method: "POST",
|
|
203
|
+
credentials: "include",
|
|
204
|
+
redirect: "manual"
|
|
205
|
+
});
|
|
201
206
|
} catch {
|
|
202
207
|
}
|
|
203
208
|
}
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client.ts","../src/guard.ts","../src/storage.ts","../src/session.ts","../src/index.ts"],"sourcesContent":["import {\n HttpClient,\n type HttpClientConfig,\n PermissionsModule,\n type PermissionsModuleOptions,\n ZanzibarModule,\n AbacModule,\n AuthModule,\n type AuthModuleConfig,\n AgentsModule,\n ApprovalsModule,\n LumoAuthConfigError,\n} from '@lumoauth/shared';\nimport { assertBrowserSafeCredential } from './guard';\n\n// ─── Config ───────────────────────────────────────────────────────────\n\nexport interface LumoAuthConfig {\n /**\n * Base URL of your LumoAuth instance.\n * @example \"https://auth.example.com\"\n */\n baseUrl: string;\n\n /**\n * Access token for the authenticated user.\n * Can be a static string or an async function that returns a fresh token.\n *\n * Optional — not needed before first sign-in when using PKCE flow.\n *\n * @example\n * // Static token\n * token: 'eyJhbGciOi...'\n *\n * // Dynamic token (recommended for SPAs & server-side)\n * token: () => getAccessTokenFromSession()\n */\n token?: string | (() => string | Promise<string>);\n\n /**\n * Authentication strategy.\n * - `'pkce'` — OAuth 2.0 Authorization Code + PKCE (default, recommended for SPAs)\n * - `'password'` — Resource Owner Password Credentials grant (legacy)\n *\n * @default 'pkce'\n */\n authStrategy?: 'pkce' | 'password';\n\n /**\n * Your organization ID (e.g. \"acme-corp\").\n * Required for building authorization URLs.\n */\n orgId?: string;\n\n /**\n * OAuth client ID.\n * Required when using the auth module.\n */\n clientId?: string;\n\n /** Request timeout in milliseconds. Default: 30 000 ms. */\n timeout?: number;\n\n /**\n * Custom `fetch` implementation.\n * Defaults to the global `fetch`. Useful for testing or\n * environments without a global `fetch` (e.g. older Node.js).\n */\n fetch?: typeof globalThis.fetch;\n\n /** Additional headers sent with every request. */\n headers?: Record<string, string>;\n\n /** Options for the permissions module cache. */\n cache?: boolean | PermissionsModuleOptions['cache'];\n}\n\n/**\n * Browser-safe subset of the approvals surface: status polling only.\n * Creating approvals lives on the server/agent SDKs.\n */\nexport type ClientApprovals = Pick<ApprovalsModule, 'getStatus' | 'wait'>;\n\n// ─── Client ───────────────────────────────────────────────────────────\n\n/**\n * The main LumoAuth client. Provides access to all authorization and\n * authentication modules.\n *\n * @example\n * ```ts\n * import { LumoAuth } from '@lumoauth/client';\n *\n * // PKCE mode (recommended)\n * const client = new LumoAuth({\n * baseUrl: 'https://auth.example.com',\n * orgId: 'acme-corp',\n * clientId: 'my-client-id',\n * });\n *\n * // Build authorization URL and redirect\n * const { url, codeVerifier, state } = await client.auth.buildAuthorizationUrl({\n * redirectUri: 'http://localhost:3000/callback',\n * });\n *\n * // Legacy mode with token\n * const authedClient = new LumoAuth({\n * baseUrl: 'https://auth.example.com',\n * token: () => getAccessToken(),\n * });\n *\n * // Permission checks (RBAC)\n * const canEdit = await authedClient.permissions.check('document.edit');\n * ```\n */\nexport class LumoAuth {\n /** RBAC permission checks. */\n public readonly permissions: PermissionsModule;\n /** Zanzibar-style (ReBAC) relationship checks. */\n public readonly zanzibar: ZanzibarModule;\n /** ABAC policy evaluation and attribute management. */\n public readonly abac: AbacModule;\n /** OAuth 2.0 authentication — PKCE flow, token exchange, refresh. */\n public readonly auth: AuthModule;\n /** Agent identity — ask/isAllowed and self-inspection. */\n public readonly agents: AgentsModule;\n /**\n * Approval status polling — the browser-safe subset of the approvals\n * surface. Creating approvals (`require()`) is an agent/server action;\n * use `@lumoauth/backend` or `@lumoauth/agent` for that.\n */\n public readonly approvals: ClientApprovals;\n\n private readonly http: HttpClient;\n\n constructor(config: LumoAuthConfig) {\n if (!config.baseUrl) {\n throw new LumoAuthConfigError('baseUrl is required');\n }\n\n // Refuse a server credential in a client that ships to browsers.\n // See ./guard for why this is a hard error rather than a warning.\n assertBrowserSafeCredential(config.token);\n\n // Token is optional when using PKCE flow (no token before first sign-in)\n const tokenProvider = config.token ?? (() => '');\n\n const httpConfig: HttpClientConfig = {\n baseUrl: config.baseUrl,\n token: tokenProvider,\n timeout: config.timeout,\n fetch: config.fetch,\n headers: config.headers,\n };\n\n this.http = new HttpClient(httpConfig);\n\n this.permissions = new PermissionsModule(this.http, {\n cache: config.cache,\n });\n this.zanzibar = new ZanzibarModule(this.http);\n this.abac = new AbacModule(this.http, config.orgId ?? '');\n\n // Auth module\n const authConfig: AuthModuleConfig = {\n baseUrl: config.baseUrl,\n orgId: config.orgId ?? '',\n clientId: config.clientId ?? '',\n fetch: config.fetch,\n };\n this.auth = new AuthModule(authConfig);\n\n // Agents module — org-scoped, so it needs `orgId`; the guard fires\n // lazily when a method is called.\n this.agents = new AgentsModule(this.http, config.orgId ?? '');\n\n // Approvals — browser-safe subset (status polling only).\n const approvals = new ApprovalsModule(this.http, config.orgId ?? '');\n this.approvals = {\n getStatus: approvals.getStatus.bind(approvals),\n wait: approvals.wait.bind(approvals),\n };\n }\n\n /**\n * @deprecated Renamed to {@link agents}. This alias will be removed\n * before 2.0.\n */\n get agent(): AgentsModule {\n return this.agents;\n }\n\n /**\n * Clear all client-side caches.\n * Call after the user's roles, groups, or attributes change.\n */\n clearCache(): void {\n this.permissions.clearCache();\n }\n}\n","import { LumoAuthConfigError } from '@lumoauth/shared';\n\n/**\n * Prefix of a LumoAuth tenant API key (`TenantApiKeyService::KEY_PREFIX`).\n * These are server credentials: they authenticate as the tenant, not as a\n * user, and they do not expire on their own.\n */\nconst TENANT_API_KEY_PREFIX = 'lmk_';\n\n/** True when this code is executing in something that looks like a browser. */\nfunction inBrowser(): boolean {\n return typeof window !== 'undefined' && typeof window.document !== 'undefined';\n}\n\n/**\n * Reject server credentials in `@lumoauth/client`.\n *\n * `@lumoauth/client` is designed to ship to browsers, where anything it holds\n * is readable by the user and by any script on the origin. A user access token\n * is fine there — it is short-lived and scoped to one person. A tenant API key\n * (`lmk_…`) is not: it authenticates as the whole organization.\n *\n * This is a hard error rather than a warning because the failure is silent\n * otherwise. The mistake it prevents is the easy one: copying a server-side\n * setup (`token: process.env.LUMOAUTH_AGENT_TOKEN`) into a component that ends\n * up in the client bundle. Nothing else catches that — bundlers happily inline\n * the value, and the request succeeds, so it looks like it works.\n *\n * Server-side code should import `@lumoauth/backend` instead, which accepts\n * these credentials and refuses to construct in a browser.\n *\n * Only static string tokens can be checked here. A `() => string` provider is\n * resolved per-request and may legitimately return a user token, so it is left\n * alone — the guard cannot tell the two apart without calling it.\n */\nexport function assertBrowserSafeCredential(\n token: string | (() => string | Promise<string>) | undefined,\n): void {\n if (typeof token !== 'string' || token === '') return;\n if (!token.startsWith(TENANT_API_KEY_PREFIX)) return;\n if (!inBrowser()) return;\n\n throw new LumoAuthConfigError(\n 'Refusing to use a LumoAuth tenant API key (lmk_…) in @lumoauth/client. ' +\n 'This package runs in the browser, where the key would be readable by ' +\n 'anyone using the app, and it authenticates as your entire organization. ' +\n 'Use a per-user access token here, and move any code that needs the API ' +\n 'key to the server with @lumoauth/backend.',\n );\n}\n","/**\n * Token storage adapters.\n *\n * Where tokens live is the single most consequential security decision in a\n * browser SDK, and the right answer depends on the app. This module makes it a\n * choice rather than a hardcoded default.\n *\n * The trade-off:\n *\n * | Adapter | XSS-readable | Survives reload | Cross-tab | SSR |\n * |------------------|--------------|-----------------|-----------|-----|\n * | `sessionStorage` | yes | per tab | no | no |\n * | `localStorage` | yes | yes | yes | no |\n * | `memory` | no* | no | no | yes |\n * | `cookie` (BFF) | no | yes | yes | yes |\n *\n * \\* memory is not readable from another origin's script, but it is still in\n * the JS heap; it is \"safe\" only in the sense that nothing persists.\n *\n * `cookie` is the strongest option: tokens live in an httpOnly cookie your\n * server sets, and never enter JavaScript at all. It requires a same-origin\n * backend to exchange and refresh on the browser's behalf, which is what\n * @lumoauth/express and (Phase 3) @lumoauth/nextjs provide.\n */\n\nexport interface StoredTokens {\n accessToken: string | null;\n refreshToken: string | null;\n idToken: string | null;\n /** Absolute expiry, epoch milliseconds. */\n expiresAt: number | null;\n}\n\nexport const EMPTY_TOKENS: StoredTokens = {\n accessToken: null,\n refreshToken: null,\n idToken: null,\n expiresAt: null,\n};\n\nexport interface TokenStorage {\n /** Identifies the adapter in errors and diagnostics. */\n readonly name: string;\n get(): StoredTokens | Promise<StoredTokens>;\n set(tokens: StoredTokens): void | Promise<void>;\n clear(): void | Promise<void>;\n /**\n * Optional. Called when the store changes outside this tab; return an\n * unsubscribe function. Adapters backed by a shared medium (localStorage,\n * cookies) can implement this so other tabs stay in sync.\n */\n subscribe?(onExternalChange: () => void): () => void;\n}\n\nconst TOKEN_KEY = 'lumoauth_tokens';\n\nfunction hasWindow(): boolean {\n return typeof window !== 'undefined';\n}\n\n/** Parse without throwing — corrupt storage should sign the user out, not crash. */\nfunction parse(raw: string | null): StoredTokens {\n if (!raw) return EMPTY_TOKENS;\n try {\n const v = JSON.parse(raw) as Partial<StoredTokens>;\n return {\n accessToken: v.accessToken ?? null,\n refreshToken: v.refreshToken ?? null,\n idToken: v.idToken ?? null,\n expiresAt: typeof v.expiresAt === 'number' ? v.expiresAt : null,\n };\n } catch {\n return EMPTY_TOKENS;\n }\n}\n\nfunction webStorageAdapter(\n name: string,\n pick: () => Storage | null,\n crossTab: boolean,\n): TokenStorage {\n const store = (): Storage | null => {\n if (!hasWindow()) return null;\n try {\n return pick();\n } catch {\n // Private browsing and some embedded webviews throw on access.\n return null;\n }\n };\n\n return {\n name,\n get() {\n try {\n return parse(store()?.getItem(TOKEN_KEY) ?? null);\n } catch {\n return EMPTY_TOKENS;\n }\n },\n set(tokens) {\n try {\n const s = store();\n if (!s) return;\n if (tokens.accessToken) s.setItem(TOKEN_KEY, JSON.stringify(tokens));\n else s.removeItem(TOKEN_KEY);\n } catch {\n // Quota or private-browsing failure: the session degrades to\n // in-memory for this tab rather than breaking sign-in.\n }\n },\n clear() {\n try {\n store()?.removeItem(TOKEN_KEY);\n } catch {\n /* ignore */\n }\n },\n // Only localStorage raises `storage` in other tabs. sessionStorage is\n // per-tab by definition, so there is nothing to subscribe to.\n subscribe: crossTab\n ? (onExternalChange) => {\n if (!hasWindow()) return () => {};\n const handler = (e: StorageEvent) => {\n if (e.key === TOKEN_KEY || e.key === null) onExternalChange();\n };\n window.addEventListener('storage', handler);\n return () => window.removeEventListener('storage', handler);\n }\n : undefined,\n };\n}\n\n/**\n * Default. Per-tab, cleared when the tab closes.\n *\n * Note this means a new tab starts signed out and must complete a redirect\n * round-trip. Use {@link localStorageAdapter} to share the session across tabs,\n * or {@link cookieStorageAdapter} to keep tokens out of JavaScript entirely.\n */\nexport function sessionStorageAdapter(): TokenStorage {\n return webStorageAdapter('sessionStorage', () => window.sessionStorage, false);\n}\n\n/** Shared across tabs and survives a browser restart. Still XSS-readable. */\nexport function localStorageAdapter(): TokenStorage {\n return webStorageAdapter('localStorage', () => window.localStorage, true);\n}\n\n/**\n * In-memory only. Nothing persists, so a reload signs the user out.\n *\n * This is the correct default on the server: it is inert during SSR instead of\n * touching a `window` that does not exist.\n */\nexport function memoryStorageAdapter(): TokenStorage {\n let tokens: StoredTokens = EMPTY_TOKENS;\n return {\n name: 'memory',\n get: () => tokens,\n set: (t) => {\n tokens = t;\n },\n clear: () => {\n tokens = EMPTY_TOKENS;\n },\n };\n}\n\nexport interface CookieStorageOptions {\n /**\n * Same-origin endpoint that returns the current session as JSON\n * (`{accessToken, expiresAt, ...}`) reading it from an httpOnly cookie.\n * @default '/auth/session'\n */\n sessionEndpoint?: string;\n /**\n * Same-origin endpoint that clears the session cookie.\n * @default '/auth/logout'\n */\n logoutEndpoint?: string;\n fetch?: typeof globalThis.fetch;\n}\n\n/**\n * Backend-for-frontend adapter: tokens live in an httpOnly cookie and are never\n * exposed to JavaScript.\n *\n * This is the only option here that survives XSS. The cost is that a\n * same-origin server must own the OAuth exchange and refresh —\n * @lumoauth/express already provides those routes.\n *\n * `set()` is intentionally a no-op: the browser cannot write an httpOnly\n * cookie, so only the server may establish the session. Reads go over the\n * network, so the session store caches them rather than calling per request.\n */\nexport function cookieStorageAdapter(options: CookieStorageOptions = {}): TokenStorage {\n const sessionEndpoint = options.sessionEndpoint ?? '/auth/session';\n const logoutEndpoint = options.logoutEndpoint ?? '/auth/logout';\n const doFetch = options.fetch ?? ((...a: Parameters<typeof fetch>) => globalThis.fetch(...a));\n\n return {\n name: 'cookie',\n async get() {\n if (!hasWindow()) return EMPTY_TOKENS;\n try {\n const res = await doFetch(sessionEndpoint, {\n credentials: 'include',\n headers: { Accept: 'application/json' },\n });\n if (!res.ok) return EMPTY_TOKENS;\n const data = (await res.json()) as Partial<StoredTokens>;\n return {\n accessToken: data.accessToken ?? null,\n refreshToken: null, // never leaves the server\n idToken: data.idToken ?? null,\n expiresAt: typeof data.expiresAt === 'number' ? data.expiresAt : null,\n };\n } catch {\n return EMPTY_TOKENS;\n }\n },\n set() {\n // No-op by design — see the note above.\n },\n async clear() {\n if (!hasWindow()) return;\n try {\n await doFetch(logoutEndpoint, { method: 'POST', credentials: 'include' });\n } catch {\n /* best-effort */\n }\n },\n };\n}\n\n/**\n * The default: `sessionStorage` in a browser, memory on the server.\n *\n * Chosen so that importing the SDK into an SSR framework does not blow up on a\n * missing `window`, while browser behaviour is unchanged.\n */\nexport function defaultStorage(): TokenStorage {\n return hasWindow() ? sessionStorageAdapter() : memoryStorageAdapter();\n}\n","import { AuthModule, type TokenResponse } from '@lumoauth/shared';\nimport {\n defaultStorage,\n EMPTY_TOKENS,\n type StoredTokens,\n type TokenStorage,\n} from './storage';\n\n/**\n * Framework-agnostic session runtime.\n *\n * This owns everything that is not React: token persistence, the refresh\n * schedule, the PKCE handshake, and cross-tab coordination. `@lumoauth/react`\n * is a thin binding over it, and a Vue or Svelte binding would be the same\n * shape — which is the reason this exists as a standalone class rather than\n * living inside a provider component.\n *\n * Subscribe/getSnapshot are deliberately shaped for React's\n * `useSyncExternalStore`, but they are plain functions with no React\n * dependency.\n */\n\nexport type SessionStatus = 'loading' | 'authenticated' | 'unauthenticated';\n\nexport interface SessionState {\n status: SessionStatus;\n isLoaded: boolean;\n isSignedIn: boolean;\n /**\n * Why the last operation failed, if it did. The previous implementation\n * discarded this — an ERROR action collapsed to `unauthenticated` and the\n * message was dropped, so callers could not tell \"signed out\" from\n * \"refresh failed\".\n */\n error: string | null;\n}\n\nconst INITIAL: SessionState = {\n status: 'loading',\n isLoaded: false,\n isSignedIn: false,\n error: null,\n};\n\n/** Refresh this long before expiry rather than at it. */\nconst REFRESH_MARGIN_MS = 60_000;\n/** `getToken()` refreshes proactively inside this window. */\nconst PROACTIVE_WINDOW_MS = 30_000;\n/** Never schedule a timer shorter than this, to avoid a refresh storm. */\nconst MIN_TIMER_MS = 5_000;\n\n/** Cross-tab channel name. Also used as the leader-election lock name. */\nconst CHANNEL = 'lumoauth.session';\n\nexport interface SessionOptions {\n auth: AuthModule;\n redirectUri: string;\n scope?: string;\n storage?: TokenStorage;\n /**\n * Share the session across tabs. When enabled, a token refresh in one tab\n * is broadcast to the others, and only one tab performs the refresh.\n *\n * Independent of the storage adapter: `sessionStorage` is per-tab, so\n * broadcasting keeps siblings live for the current session even though\n * nothing is shared on disk.\n * @default true\n */\n crossTab?: boolean;\n /** Called after tokens change, so the host can refetch the user. */\n onTokens?: (tokens: StoredTokens) => void;\n}\n\ninterface Broadcast {\n type: 'tokens' | 'signout';\n tokens?: StoredTokens;\n}\n\nexport class LumoAuthSession {\n private state: SessionState = INITIAL;\n private tokens: StoredTokens = EMPTY_TOKENS;\n private listeners = new Set<() => void>();\n private timer: ReturnType<typeof setTimeout> | null = null;\n private channel: BroadcastChannel | null = null;\n private unsubscribeStorage: (() => void) | null = null;\n private inflightRefresh: Promise<string | null> | null = null;\n\n private readonly auth: AuthModule;\n private readonly storage: TokenStorage;\n private readonly redirectUri: string;\n private readonly scope: string;\n private readonly onTokens?: (t: StoredTokens) => void;\n\n constructor(opts: SessionOptions) {\n this.auth = opts.auth;\n this.storage = opts.storage ?? defaultStorage();\n this.redirectUri = opts.redirectUri;\n this.scope = opts.scope ?? 'openid profile email';\n this.onTokens = opts.onTokens;\n\n if (opts.crossTab !== false && typeof BroadcastChannel !== 'undefined') {\n this.channel = new BroadcastChannel(CHANNEL);\n this.channel.onmessage = (e: MessageEvent<Broadcast>) => this.onBroadcast(e.data);\n }\n this.unsubscribeStorage =\n this.storage.subscribe?.(() => {\n void this.hydrate();\n }) ?? null;\n }\n\n // ── Store interface ──────────────────────────────────────────────\n\n subscribe = (fn: () => void): (() => void) => {\n this.listeners.add(fn);\n return () => this.listeners.delete(fn);\n };\n\n getSnapshot = (): SessionState => this.state;\n\n /** Server snapshot for `useSyncExternalStore` — always the loading state. */\n getServerSnapshot = (): SessionState => INITIAL;\n\n private emit(next: Partial<SessionState>): void {\n this.state = { ...this.state, ...next };\n this.listeners.forEach((l) => l());\n }\n\n // ── Lifecycle ────────────────────────────────────────────────────\n\n /** Load persisted tokens and settle into signed-in or signed-out. */\n async hydrate(): Promise<void> {\n const tokens = await this.storage.get();\n this.tokens = tokens;\n\n if (!tokens.accessToken) {\n this.emit({ status: 'unauthenticated', isLoaded: true, isSignedIn: false });\n return;\n }\n if (tokens.expiresAt && tokens.expiresAt <= Date.now()) {\n const refreshed = await this.refresh();\n if (!refreshed) return; // refresh() already emitted signed-out\n }\n this.scheduleRefresh();\n this.emit({ status: 'authenticated', isLoaded: true, isSignedIn: true, error: null });\n this.onTokens?.(this.tokens);\n }\n\n dispose(): void {\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n this.channel?.close();\n this.channel = null;\n this.unsubscribeStorage?.();\n this.unsubscribeStorage = null;\n this.listeners.clear();\n }\n\n // ── Tokens ───────────────────────────────────────────────────────\n\n getTokens(): Readonly<StoredTokens> {\n return this.tokens;\n }\n\n private async persist(tokens: StoredTokens, broadcast = true): Promise<void> {\n this.tokens = tokens;\n await this.storage.set(tokens);\n if (broadcast) this.channel?.postMessage({ type: 'tokens', tokens } satisfies Broadcast);\n this.onTokens?.(tokens);\n }\n\n static tokensFrom(res: TokenResponse, previous?: StoredTokens): StoredTokens {\n return {\n accessToken: res.access_token,\n // A refresh response may omit the refresh token when it is not\n // rotated; keep the existing one rather than losing the session.\n refreshToken: res.refresh_token ?? previous?.refreshToken ?? null,\n idToken: res.id_token ?? previous?.idToken ?? null,\n expiresAt: Date.now() + res.expires_in * 1000,\n };\n }\n\n /**\n * A valid access token, refreshing first if it is about to expire.\n * Returns null when there is no session.\n */\n async getToken(): Promise<string | null> {\n const { accessToken, expiresAt } = this.tokens;\n if (!accessToken) return null;\n if (expiresAt && expiresAt - Date.now() < PROACTIVE_WINDOW_MS) {\n return this.refresh();\n }\n return accessToken;\n }\n\n /**\n * Refresh the access token.\n *\n * Concurrent callers share one in-flight request. Across tabs, a Web Lock\n * elects a single refresher — without it, every tab refreshes on its own\n * timer and they race on a rotated refresh token, so all but the winner\n * are signed out.\n */\n async refresh(): Promise<string | null> {\n if (this.inflightRefresh) return this.inflightRefresh;\n this.inflightRefresh = this.doRefresh().finally(() => {\n this.inflightRefresh = null;\n });\n return this.inflightRefresh;\n }\n\n private async doRefresh(): Promise<string | null> {\n if (!this.tokens.refreshToken) {\n await this.clearSession('no_refresh_token');\n return null;\n }\n\n const run = async (): Promise<string | null> => {\n // Another tab may have refreshed while we waited for the lock.\n //\n // Check BOTH the shared store and our own in-memory tokens. Storage\n // alone is not enough: with a per-tab adapter (the default,\n // sessionStorage) `storage.get()` returns this tab's private copy\n // and never sees the winner's rotated token — but the winner also\n // broadcasts, and onBroadcast() updates `this.tokens`. Consulting\n // both makes the check work for shared and per-tab adapters alike.\n const stored = await this.storage.get();\n const fresher = [stored, this.tokens]\n .filter((t) => t.accessToken && t.expiresAt)\n .sort((a, b) => (b.expiresAt ?? 0) - (a.expiresAt ?? 0))[0];\n\n if (fresher && (fresher.expiresAt ?? 0) - Date.now() > PROACTIVE_WINDOW_MS) {\n this.tokens = fresher;\n this.scheduleRefresh();\n return fresher.accessToken;\n }\n\n // Read the refresh token HERE, inside the lock, not before waiting\n // for it. The server rotates and revokes on use, so a value\n // captured before the lock is already spent by the time the loser\n // acquires it — the request 400s and the tab is signed out.\n const refreshToken = this.tokens.refreshToken;\n if (!refreshToken) {\n await this.clearSession('no_refresh_token');\n return null;\n }\n\n try {\n const res = await this.auth.refreshToken(refreshToken);\n await this.persist(LumoAuthSession.tokensFrom(res, this.tokens));\n this.scheduleRefresh();\n this.emit({ status: 'authenticated', isLoaded: true, isSignedIn: true, error: null });\n return this.tokens.accessToken;\n } catch {\n await this.clearSession('refresh_failed');\n return null;\n }\n };\n\n const locks = (globalThis as { navigator?: { locks?: LockManager } }).navigator?.locks;\n if (locks?.request) {\n return locks.request(CHANNEL + '.refresh', run) as Promise<string | null>;\n }\n return run();\n }\n\n private scheduleRefresh(): void {\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n const { expiresAt, refreshToken } = this.tokens;\n if (!expiresAt || !refreshToken) return;\n const delay = Math.max(expiresAt - Date.now() - REFRESH_MARGIN_MS, MIN_TIMER_MS);\n this.timer = setTimeout(() => void this.refresh(), delay);\n }\n\n // ── Flows ────────────────────────────────────────────────────────\n\n /** Adopt tokens obtained elsewhere (e.g. a completed code exchange). */\n async adopt(res: TokenResponse): Promise<void> {\n await this.persist(LumoAuthSession.tokensFrom(res, this.tokens));\n this.scheduleRefresh();\n this.emit({ status: 'authenticated', isLoaded: true, isSignedIn: true, error: null });\n }\n\n /** Build the PKCE authorization URL; the caller persists verifier + state. */\n buildAuthorizationUrl(extraParams?: Record<string, string>) {\n return this.auth.buildAuthorizationUrl({\n redirectUri: this.redirectUri,\n scope: this.scope,\n ...(extraParams ? { extraParams } : {}),\n });\n }\n\n /**\n * Drop the session.\n *\n * `emit: false` clears tokens and storage without notifying subscribers.\n * That is required during sign-out: emitting re-renders the tree, which\n * mounts any `<SignedOut><RedirectToSignIn/></SignedOut>` guard, whose\n * effect then races the pending logout navigation and sends the user back\n * to /authorize — where the IdP session is still alive and silently\n * re-issues a code, defeating logout entirely.\n */\n async clearSession(\n error: string | null = null,\n opts: { broadcast?: boolean; emit?: boolean } = {},\n ): Promise<void> {\n const { broadcast = true, emit = true } = opts;\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n this.tokens = EMPTY_TOKENS;\n await this.storage.clear();\n if (broadcast) this.channel?.postMessage({ type: 'signout' } satisfies Broadcast);\n if (emit) {\n this.emit({ status: 'unauthenticated', isLoaded: true, isSignedIn: false, error });\n }\n }\n\n // ── Cross-tab ────────────────────────────────────────────────────\n\n private onBroadcast(msg: Broadcast): void {\n if (!msg) return;\n if (msg.type === 'signout') {\n // Do not re-broadcast: that would ping-pong between tabs.\n void this.clearSession(null, { broadcast: false });\n return;\n }\n if (msg.type === 'tokens' && msg.tokens) {\n this.tokens = msg.tokens;\n this.scheduleRefresh();\n this.emit({ status: 'authenticated', isLoaded: true, isSignedIn: true, error: null });\n this.onTokens?.(msg.tokens);\n }\n }\n}\n\n/** Minimal shape of the Web Locks API; not in every lib.dom version. */\ninterface LockManager {\n request<T>(name: string, cb: () => Promise<T>): Promise<T>;\n}\n","// @lumoauth/client — the browser SDK.\n//\n// This is the package application code imports. It re-exports all of\n// @lumoauth/shared so callers need a single dependency, and adds the\n// `LumoAuth` client itself.\n//\n// It is browser-safe by construction: constructing it with a tenant API key\n// (`lmk_…`) in a browser is a hard error. Server-only surfaces live in\n// @lumoauth/backend (token verification, admin) and @lumoauth/agent (AAuth,\n// which needs `node:crypto`).\n\nexport { LumoAuth, type LumoAuthConfig, type ClientApprovals } from './client';\n\n// ─── Session runtime (framework-agnostic) ─────────────────────────────\n// The store @lumoauth/react binds to. Exported so a Vue/Svelte binding can\n// use the same runtime instead of reimplementing refresh and cross-tab logic.\nexport {\n LumoAuthSession,\n type SessionState,\n type SessionStatus,\n type SessionOptions,\n} from './session';\n\n// ─── Token storage ────────────────────────────────────────────────────\nexport {\n type TokenStorage,\n type StoredTokens,\n type CookieStorageOptions,\n EMPTY_TOKENS,\n sessionStorageAdapter,\n localStorageAdapter,\n memoryStorageAdapter,\n cookieStorageAdapter,\n defaultStorage,\n} from './storage';\n\n// The full isomorphic surface: authorization modules, OAuth/PKCE helpers,\n// schemas, errors, and the HTTP client.\nexport * from '@lumoauth/shared';\n"],"mappings":";AAAA;AAAA,EACI;AAAA,EAEA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA,uBAAAA;AAAA,OACG;;;ACZP,SAAS,2BAA2B;AAOpC,IAAM,wBAAwB;AAG9B,SAAS,YAAqB;AAC1B,SAAO,OAAO,WAAW,eAAe,OAAO,OAAO,aAAa;AACvE;AAuBO,SAAS,4BACZ,OACI;AACJ,MAAI,OAAO,UAAU,YAAY,UAAU,GAAI;AAC/C,MAAI,CAAC,MAAM,WAAW,qBAAqB,EAAG;AAC9C,MAAI,CAAC,UAAU,EAAG;AAElB,QAAM,IAAI;AAAA,IACN;AAAA,EAKJ;AACJ;;;ADkEO,IAAM,WAAN,MAAe;AAAA,EAoBlB,YAAY,QAAwB;AAChC,QAAI,CAAC,OAAO,SAAS;AACjB,YAAM,IAA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AAM,OAAO,KAAK,IAAI;AAC1C,QAAI,KAAK,MAAO,cAAa,KAAK,KAAK;AACvC,SAAK,QAAQ;AACb,SAAK,SAAS;AACd,UAAM,KAAK,QAAQ,MAAM;AACzB,QAAI,UAAW,MAAK,SAAS,YAAY,EAAE,MAAM,UAAU,CAAqB;AAChF,QAAI,MAAM;AACN,WAAK,KAAK,EAAE,QAAQ,mBAAmB,UAAU,MAAM,YAAY,OAAO,MAAM,CAAC;AAAA,IACrF;AAAA,EACJ;AAAA;AAAA,EAIQ,YAAY,KAAsB;AACtC,QAAI,CAAC,IAAK;AACV,QAAI,IAAI,SAAS,WAAW;AAExB,WAAK,KAAK,aAAa,MAAM,EAAE,WAAW,MAAM,CAAC;AACjD;AAAA,IACJ;AACA,QAAI,IAAI,SAAS,YAAY,IAAI,QAAQ;AACrC,WAAK,SAAS,IAAI;AAClB,WAAK,gBAAgB;AACrB,WAAK,KAAK,EAAE,QAAQ,iBAAiB,UAAU,MAAM,YAAY,MAAM,OAAO,KAAK,CAAC;AACpF,WAAK,WAAW,IAAI,MAAM;AAAA,IAC9B;AAAA,EACJ;AACJ;;;ACvSA,cAAc;","names":["LumoAuthConfigError","LumoAuthConfigError"]}
|
|
1
|
+
{"version":3,"sources":["../src/client.ts","../src/guard.ts","../src/storage.ts","../src/session.ts","../src/index.ts"],"sourcesContent":["import {\n HttpClient,\n type HttpClientConfig,\n PermissionsModule,\n type PermissionsModuleOptions,\n ZanzibarModule,\n AbacModule,\n AuthModule,\n type AuthModuleConfig,\n AgentsModule,\n ApprovalsModule,\n LumoAuthConfigError,\n} from '@lumoauth/shared';\nimport { assertBrowserSafeCredential } from './guard';\n\n// ─── Config ───────────────────────────────────────────────────────────\n\nexport interface LumoAuthConfig {\n /**\n * Base URL of your LumoAuth instance.\n * @example \"https://auth.example.com\"\n */\n baseUrl: string;\n\n /**\n * Access token for the authenticated user.\n * Can be a static string or an async function that returns a fresh token.\n *\n * Optional — not needed before first sign-in when using PKCE flow.\n *\n * @example\n * // Static token\n * token: 'eyJhbGciOi...'\n *\n * // Dynamic token (recommended for SPAs & server-side)\n * token: () => getAccessTokenFromSession()\n */\n token?: string | (() => string | Promise<string>);\n\n /**\n * Authentication strategy.\n * - `'pkce'` — OAuth 2.0 Authorization Code + PKCE (default, recommended for SPAs)\n * - `'password'` — Resource Owner Password Credentials grant (legacy)\n *\n * @default 'pkce'\n */\n authStrategy?: 'pkce' | 'password';\n\n /**\n * Your organization ID (e.g. \"acme-corp\").\n * Required for building authorization URLs.\n */\n orgId?: string;\n\n /**\n * OAuth client ID.\n * Required when using the auth module.\n */\n clientId?: string;\n\n /** Request timeout in milliseconds. Default: 30 000 ms. */\n timeout?: number;\n\n /**\n * Custom `fetch` implementation.\n * Defaults to the global `fetch`. Useful for testing or\n * environments without a global `fetch` (e.g. older Node.js).\n */\n fetch?: typeof globalThis.fetch;\n\n /** Additional headers sent with every request. */\n headers?: Record<string, string>;\n\n /** Options for the permissions module cache. */\n cache?: boolean | PermissionsModuleOptions['cache'];\n}\n\n/**\n * Browser-safe subset of the approvals surface: status polling only.\n * Creating approvals lives on the server/agent SDKs.\n */\nexport type ClientApprovals = Pick<ApprovalsModule, 'getStatus' | 'wait'>;\n\n// ─── Client ───────────────────────────────────────────────────────────\n\n/**\n * The main LumoAuth client. Provides access to all authorization and\n * authentication modules.\n *\n * @example\n * ```ts\n * import { LumoAuth } from '@lumoauth/client';\n *\n * // PKCE mode (recommended)\n * const client = new LumoAuth({\n * baseUrl: 'https://auth.example.com',\n * orgId: 'acme-corp',\n * clientId: 'my-client-id',\n * });\n *\n * // Build authorization URL and redirect\n * const { url, codeVerifier, state } = await client.auth.buildAuthorizationUrl({\n * redirectUri: 'http://localhost:3000/callback',\n * });\n *\n * // Legacy mode with token\n * const authedClient = new LumoAuth({\n * baseUrl: 'https://auth.example.com',\n * token: () => getAccessToken(),\n * });\n *\n * // Permission checks (RBAC)\n * const canEdit = await authedClient.permissions.check('document.edit');\n * ```\n */\nexport class LumoAuth {\n /** RBAC permission checks. */\n public readonly permissions: PermissionsModule;\n /** Zanzibar-style (ReBAC) relationship checks. */\n public readonly zanzibar: ZanzibarModule;\n /** ABAC policy evaluation and attribute management. */\n public readonly abac: AbacModule;\n /** OAuth 2.0 authentication — PKCE flow, token exchange, refresh. */\n public readonly auth: AuthModule;\n /** Agent identity — ask/isAllowed and self-inspection. */\n public readonly agents: AgentsModule;\n /**\n * Approval status polling — the browser-safe subset of the approvals\n * surface. Creating approvals (`require()`) is an agent/server action;\n * use `@lumoauth/backend` or `@lumoauth/agent` for that.\n */\n public readonly approvals: ClientApprovals;\n\n private readonly http: HttpClient;\n\n constructor(config: LumoAuthConfig) {\n if (!config.baseUrl) {\n throw new LumoAuthConfigError('baseUrl is required');\n }\n\n // Refuse a server credential in a client that ships to browsers.\n // See ./guard for why this is a hard error rather than a warning.\n assertBrowserSafeCredential(config.token);\n\n // Token is optional when using PKCE flow (no token before first sign-in)\n const tokenProvider = config.token ?? (() => '');\n\n const httpConfig: HttpClientConfig = {\n baseUrl: config.baseUrl,\n token: tokenProvider,\n timeout: config.timeout,\n fetch: config.fetch,\n headers: config.headers,\n };\n\n this.http = new HttpClient(httpConfig);\n\n this.permissions = new PermissionsModule(this.http, {\n cache: config.cache,\n });\n this.zanzibar = new ZanzibarModule(this.http);\n this.abac = new AbacModule(this.http, config.orgId ?? '');\n\n // Auth module\n const authConfig: AuthModuleConfig = {\n baseUrl: config.baseUrl,\n orgId: config.orgId ?? '',\n clientId: config.clientId ?? '',\n fetch: config.fetch,\n };\n this.auth = new AuthModule(authConfig);\n\n // Agents module — org-scoped, so it needs `orgId`; the guard fires\n // lazily when a method is called.\n this.agents = new AgentsModule(this.http, config.orgId ?? '');\n\n // Approvals — browser-safe subset (status polling only).\n const approvals = new ApprovalsModule(this.http, config.orgId ?? '');\n this.approvals = {\n getStatus: approvals.getStatus.bind(approvals),\n wait: approvals.wait.bind(approvals),\n };\n }\n\n /**\n * @deprecated Renamed to {@link agents}. This alias will be removed\n * before 2.0.\n */\n get agent(): AgentsModule {\n return this.agents;\n }\n\n /**\n * Clear all client-side caches.\n * Call after the user's roles, groups, or attributes change.\n */\n clearCache(): void {\n this.permissions.clearCache();\n }\n}\n","import { LumoAuthConfigError } from '@lumoauth/shared';\n\n/**\n * Prefix of a LumoAuth tenant API key (`TenantApiKeyService::KEY_PREFIX`).\n * These are server credentials: they authenticate as the tenant, not as a\n * user, and they do not expire on their own.\n */\nconst TENANT_API_KEY_PREFIX = 'lmk_';\n\n/** True when this code is executing in something that looks like a browser. */\nfunction inBrowser(): boolean {\n return typeof window !== 'undefined' && typeof window.document !== 'undefined';\n}\n\n/**\n * Reject server credentials in `@lumoauth/client`.\n *\n * `@lumoauth/client` is designed to ship to browsers, where anything it holds\n * is readable by the user and by any script on the origin. A user access token\n * is fine there — it is short-lived and scoped to one person. A tenant API key\n * (`lmk_…`) is not: it authenticates as the whole organization.\n *\n * This is a hard error rather than a warning because the failure is silent\n * otherwise. The mistake it prevents is the easy one: copying a server-side\n * setup (`token: process.env.LUMOAUTH_AGENT_TOKEN`) into a component that ends\n * up in the client bundle. Nothing else catches that — bundlers happily inline\n * the value, and the request succeeds, so it looks like it works.\n *\n * Server-side code should import `@lumoauth/backend` instead, which accepts\n * these credentials and refuses to construct in a browser.\n *\n * Only static string tokens can be checked here. A `() => string` provider is\n * resolved per-request and may legitimately return a user token, so it is left\n * alone — the guard cannot tell the two apart without calling it.\n */\nexport function assertBrowserSafeCredential(\n token: string | (() => string | Promise<string>) | undefined,\n): void {\n if (typeof token !== 'string' || token === '') return;\n if (!token.startsWith(TENANT_API_KEY_PREFIX)) return;\n if (!inBrowser()) return;\n\n throw new LumoAuthConfigError(\n 'Refusing to use a LumoAuth tenant API key (lmk_…) in @lumoauth/client. ' +\n 'This package runs in the browser, where the key would be readable by ' +\n 'anyone using the app, and it authenticates as your entire organization. ' +\n 'Use a per-user access token here, and move any code that needs the API ' +\n 'key to the server with @lumoauth/backend.',\n );\n}\n","/**\n * Token storage adapters.\n *\n * Where tokens live is the single most consequential security decision in a\n * browser SDK, and the right answer depends on the app. This module makes it a\n * choice rather than a hardcoded default.\n *\n * The trade-off:\n *\n * | Adapter | XSS-readable | Survives reload | Cross-tab | SSR |\n * |------------------|--------------|-----------------|-----------|-----|\n * | `sessionStorage` | yes | per tab | no | no |\n * | `localStorage` | yes | yes | yes | no |\n * | `memory` | no* | no | no | yes |\n * | `cookie` (BFF) | no | yes | yes | yes |\n *\n * \\* memory is not readable from another origin's script, but it is still in\n * the JS heap; it is \"safe\" only in the sense that nothing persists.\n *\n * `cookie` is the strongest option: tokens live in an httpOnly cookie your\n * server sets, and never enter JavaScript at all. It requires a same-origin\n * backend to exchange and refresh on the browser's behalf, which is what\n * @lumoauth/express and (Phase 3) @lumoauth/nextjs provide.\n */\n\nexport interface StoredTokens {\n accessToken: string | null;\n refreshToken: string | null;\n idToken: string | null;\n /** Absolute expiry, epoch milliseconds. */\n expiresAt: number | null;\n}\n\nexport const EMPTY_TOKENS: StoredTokens = {\n accessToken: null,\n refreshToken: null,\n idToken: null,\n expiresAt: null,\n};\n\nexport interface TokenStorage {\n /** Identifies the adapter in errors and diagnostics. */\n readonly name: string;\n get(): StoredTokens | Promise<StoredTokens>;\n set(tokens: StoredTokens): void | Promise<void>;\n clear(): void | Promise<void>;\n /**\n * Optional. Called when the store changes outside this tab; return an\n * unsubscribe function. Adapters backed by a shared medium (localStorage,\n * cookies) can implement this so other tabs stay in sync.\n */\n subscribe?(onExternalChange: () => void): () => void;\n /**\n * Optional. `true` when a same-origin server holds the tokens and\n * `clear()` asks that server to end the session (the cookie adapter).\n * The server then revokes the tokens, so the browser must not send a\n * revocation request of its own.\n */\n readonly serverManaged?: boolean;\n}\n\nconst TOKEN_KEY = 'lumoauth_tokens';\n\nfunction hasWindow(): boolean {\n return typeof window !== 'undefined';\n}\n\n/** Parse without throwing — corrupt storage should sign the user out, not crash. */\nfunction parse(raw: string | null): StoredTokens {\n if (!raw) return EMPTY_TOKENS;\n try {\n const v = JSON.parse(raw) as Partial<StoredTokens>;\n return {\n accessToken: v.accessToken ?? null,\n refreshToken: v.refreshToken ?? null,\n idToken: v.idToken ?? null,\n expiresAt: typeof v.expiresAt === 'number' ? v.expiresAt : null,\n };\n } catch {\n return EMPTY_TOKENS;\n }\n}\n\nfunction webStorageAdapter(\n name: string,\n pick: () => Storage | null,\n crossTab: boolean,\n): TokenStorage {\n const store = (): Storage | null => {\n if (!hasWindow()) return null;\n try {\n return pick();\n } catch {\n // Private browsing and some embedded webviews throw on access.\n return null;\n }\n };\n\n return {\n name,\n get() {\n try {\n return parse(store()?.getItem(TOKEN_KEY) ?? null);\n } catch {\n return EMPTY_TOKENS;\n }\n },\n set(tokens) {\n try {\n const s = store();\n if (!s) return;\n if (tokens.accessToken) s.setItem(TOKEN_KEY, JSON.stringify(tokens));\n else s.removeItem(TOKEN_KEY);\n } catch {\n // Quota or private-browsing failure: the session degrades to\n // in-memory for this tab rather than breaking sign-in.\n }\n },\n clear() {\n try {\n store()?.removeItem(TOKEN_KEY);\n } catch {\n /* ignore */\n }\n },\n // Only localStorage raises `storage` in other tabs. sessionStorage is\n // per-tab by definition, so there is nothing to subscribe to.\n subscribe: crossTab\n ? (onExternalChange) => {\n if (!hasWindow()) return () => {};\n const handler = (e: StorageEvent) => {\n if (e.key === TOKEN_KEY || e.key === null) onExternalChange();\n };\n window.addEventListener('storage', handler);\n return () => window.removeEventListener('storage', handler);\n }\n : undefined,\n };\n}\n\n/**\n * Default. Per-tab, cleared when the tab closes.\n *\n * Note this means a new tab starts signed out and must complete a redirect\n * round-trip. Use {@link localStorageAdapter} to share the session across tabs,\n * or {@link cookieStorageAdapter} to keep tokens out of JavaScript entirely.\n */\nexport function sessionStorageAdapter(): TokenStorage {\n return webStorageAdapter('sessionStorage', () => window.sessionStorage, false);\n}\n\n/** Shared across tabs and survives a browser restart. Still XSS-readable. */\nexport function localStorageAdapter(): TokenStorage {\n return webStorageAdapter('localStorage', () => window.localStorage, true);\n}\n\n/**\n * In-memory only. Nothing persists, so a reload signs the user out.\n *\n * This is the correct default on the server: it is inert during SSR instead of\n * touching a `window` that does not exist.\n */\nexport function memoryStorageAdapter(): TokenStorage {\n let tokens: StoredTokens = EMPTY_TOKENS;\n return {\n name: 'memory',\n get: () => tokens,\n set: (t) => {\n tokens = t;\n },\n clear: () => {\n tokens = EMPTY_TOKENS;\n },\n };\n}\n\nexport interface CookieStorageOptions {\n /**\n * Same-origin endpoint that returns the current session as JSON\n * (`{accessToken, expiresAt, ...}`) reading it from an httpOnly cookie.\n * @default '/auth/session'\n */\n sessionEndpoint?: string;\n /**\n * Same-origin endpoint that clears the session cookie.\n * @default '/auth/logout'\n */\n logoutEndpoint?: string;\n fetch?: typeof globalThis.fetch;\n}\n\n/**\n * Backend-for-frontend adapter: tokens live in an httpOnly cookie and are never\n * exposed to JavaScript.\n *\n * This is the only option here that survives XSS. The cost is that a\n * same-origin server must own the OAuth exchange and refresh —\n * @lumoauth/express already provides those routes.\n *\n * `set()` is intentionally a no-op: the browser cannot write an httpOnly\n * cookie, so only the server may establish the session. Reads go over the\n * network, so the session store caches them rather than calling per request.\n */\nexport function cookieStorageAdapter(options: CookieStorageOptions = {}): TokenStorage {\n const sessionEndpoint = options.sessionEndpoint ?? '/auth/session';\n const logoutEndpoint = options.logoutEndpoint ?? '/auth/logout';\n const doFetch = options.fetch ?? ((...a: Parameters<typeof fetch>) => globalThis.fetch(...a));\n\n return {\n name: 'cookie',\n serverManaged: true,\n async get() {\n if (!hasWindow()) return EMPTY_TOKENS;\n try {\n const res = await doFetch(sessionEndpoint, {\n credentials: 'include',\n headers: { Accept: 'application/json' },\n });\n if (!res.ok) return EMPTY_TOKENS;\n const data = (await res.json()) as Partial<StoredTokens>;\n return {\n accessToken: data.accessToken ?? null,\n refreshToken: null, // never leaves the server\n idToken: data.idToken ?? null,\n expiresAt: typeof data.expiresAt === 'number' ? data.expiresAt : null,\n };\n } catch {\n return EMPTY_TOKENS;\n }\n },\n set() {\n // No-op by design — see the note above.\n },\n async clear() {\n if (!hasWindow()) return;\n try {\n // The logout route answers with a redirect to the LumoAuth\n // logout page. Do not follow it: the caller navigates there\n // itself, and following it from fetch() is a cross-origin\n // request that the browser blocks and logs as a CORS error.\n // The cookie is cleared by the redirect response either way.\n await doFetch(logoutEndpoint, {\n method: 'POST',\n credentials: 'include',\n redirect: 'manual',\n });\n } catch {\n /* best-effort */\n }\n },\n };\n}\n\n/**\n * The default: `sessionStorage` in a browser, memory on the server.\n *\n * Chosen so that importing the SDK into an SSR framework does not blow up on a\n * missing `window`, while browser behaviour is unchanged.\n */\nexport function defaultStorage(): TokenStorage {\n return hasWindow() ? sessionStorageAdapter() : memoryStorageAdapter();\n}\n","import { AuthModule, type TokenResponse } from '@lumoauth/shared';\nimport {\n defaultStorage,\n EMPTY_TOKENS,\n type StoredTokens,\n type TokenStorage,\n} from './storage';\n\n/**\n * Framework-agnostic session runtime.\n *\n * This owns everything that is not React: token persistence, the refresh\n * schedule, the PKCE handshake, and cross-tab coordination. `@lumoauth/react`\n * is a thin binding over it, and a Vue or Svelte binding would be the same\n * shape — which is the reason this exists as a standalone class rather than\n * living inside a provider component.\n *\n * Subscribe/getSnapshot are deliberately shaped for React's\n * `useSyncExternalStore`, but they are plain functions with no React\n * dependency.\n */\n\nexport type SessionStatus = 'loading' | 'authenticated' | 'unauthenticated';\n\nexport interface SessionState {\n status: SessionStatus;\n isLoaded: boolean;\n isSignedIn: boolean;\n /**\n * Why the last operation failed, if it did. The previous implementation\n * discarded this — an ERROR action collapsed to `unauthenticated` and the\n * message was dropped, so callers could not tell \"signed out\" from\n * \"refresh failed\".\n */\n error: string | null;\n}\n\nconst INITIAL: SessionState = {\n status: 'loading',\n isLoaded: false,\n isSignedIn: false,\n error: null,\n};\n\n/** Refresh this long before expiry rather than at it. */\nconst REFRESH_MARGIN_MS = 60_000;\n/** `getToken()` refreshes proactively inside this window. */\nconst PROACTIVE_WINDOW_MS = 30_000;\n/** Never schedule a timer shorter than this, to avoid a refresh storm. */\nconst MIN_TIMER_MS = 5_000;\n\n/** Cross-tab channel name. Also used as the leader-election lock name. */\nconst CHANNEL = 'lumoauth.session';\n\nexport interface SessionOptions {\n auth: AuthModule;\n redirectUri: string;\n scope?: string;\n storage?: TokenStorage;\n /**\n * Share the session across tabs. When enabled, a token refresh in one tab\n * is broadcast to the others, and only one tab performs the refresh.\n *\n * Independent of the storage adapter: `sessionStorage` is per-tab, so\n * broadcasting keeps siblings live for the current session even though\n * nothing is shared on disk.\n * @default true\n */\n crossTab?: boolean;\n /** Called after tokens change, so the host can refetch the user. */\n onTokens?: (tokens: StoredTokens) => void;\n}\n\ninterface Broadcast {\n type: 'tokens' | 'signout';\n tokens?: StoredTokens;\n}\n\nexport class LumoAuthSession {\n private state: SessionState = INITIAL;\n private tokens: StoredTokens = EMPTY_TOKENS;\n private listeners = new Set<() => void>();\n private timer: ReturnType<typeof setTimeout> | null = null;\n private channel: BroadcastChannel | null = null;\n private unsubscribeStorage: (() => void) | null = null;\n private inflightRefresh: Promise<string | null> | null = null;\n\n private readonly auth: AuthModule;\n private readonly storage: TokenStorage;\n private readonly redirectUri: string;\n private readonly scope: string;\n private readonly onTokens?: (t: StoredTokens) => void;\n\n constructor(opts: SessionOptions) {\n this.auth = opts.auth;\n this.storage = opts.storage ?? defaultStorage();\n this.redirectUri = opts.redirectUri;\n this.scope = opts.scope ?? 'openid profile email';\n this.onTokens = opts.onTokens;\n\n if (opts.crossTab !== false && typeof BroadcastChannel !== 'undefined') {\n this.channel = new BroadcastChannel(CHANNEL);\n this.channel.onmessage = (e: MessageEvent<Broadcast>) => this.onBroadcast(e.data);\n }\n this.unsubscribeStorage =\n this.storage.subscribe?.(() => {\n void this.hydrate();\n }) ?? null;\n }\n\n // ── Store interface ──────────────────────────────────────────────\n\n subscribe = (fn: () => void): (() => void) => {\n this.listeners.add(fn);\n return () => this.listeners.delete(fn);\n };\n\n getSnapshot = (): SessionState => this.state;\n\n /** Server snapshot for `useSyncExternalStore` — always the loading state. */\n getServerSnapshot = (): SessionState => INITIAL;\n\n private emit(next: Partial<SessionState>): void {\n this.state = { ...this.state, ...next };\n this.listeners.forEach((l) => l());\n }\n\n // ── Lifecycle ────────────────────────────────────────────────────\n\n /** Load persisted tokens and settle into signed-in or signed-out. */\n async hydrate(): Promise<void> {\n const tokens = await this.storage.get();\n this.tokens = tokens;\n\n if (!tokens.accessToken) {\n this.emit({ status: 'unauthenticated', isLoaded: true, isSignedIn: false });\n return;\n }\n if (tokens.expiresAt && tokens.expiresAt <= Date.now()) {\n const refreshed = await this.refresh();\n if (!refreshed) return; // refresh() already emitted signed-out\n }\n this.scheduleRefresh();\n this.emit({ status: 'authenticated', isLoaded: true, isSignedIn: true, error: null });\n this.onTokens?.(this.tokens);\n }\n\n dispose(): void {\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n this.channel?.close();\n this.channel = null;\n this.unsubscribeStorage?.();\n this.unsubscribeStorage = null;\n this.listeners.clear();\n }\n\n // ── Tokens ───────────────────────────────────────────────────────\n\n getTokens(): Readonly<StoredTokens> {\n return this.tokens;\n }\n\n private async persist(tokens: StoredTokens, broadcast = true): Promise<void> {\n this.tokens = tokens;\n await this.storage.set(tokens);\n if (broadcast) this.channel?.postMessage({ type: 'tokens', tokens } satisfies Broadcast);\n this.onTokens?.(tokens);\n }\n\n static tokensFrom(res: TokenResponse, previous?: StoredTokens): StoredTokens {\n return {\n accessToken: res.access_token,\n // A refresh response may omit the refresh token when it is not\n // rotated; keep the existing one rather than losing the session.\n refreshToken: res.refresh_token ?? previous?.refreshToken ?? null,\n idToken: res.id_token ?? previous?.idToken ?? null,\n expiresAt: Date.now() + res.expires_in * 1000,\n };\n }\n\n /**\n * A valid access token, refreshing first if it is about to expire.\n * Returns null when there is no session.\n */\n async getToken(): Promise<string | null> {\n const { accessToken, expiresAt } = this.tokens;\n if (!accessToken) return null;\n if (expiresAt && expiresAt - Date.now() < PROACTIVE_WINDOW_MS) {\n return this.refresh();\n }\n return accessToken;\n }\n\n /**\n * Refresh the access token.\n *\n * Concurrent callers share one in-flight request. Across tabs, a Web Lock\n * elects a single refresher — without it, every tab refreshes on its own\n * timer and they race on a rotated refresh token, so all but the winner\n * are signed out.\n */\n async refresh(): Promise<string | null> {\n if (this.inflightRefresh) return this.inflightRefresh;\n this.inflightRefresh = this.doRefresh().finally(() => {\n this.inflightRefresh = null;\n });\n return this.inflightRefresh;\n }\n\n private async doRefresh(): Promise<string | null> {\n if (!this.tokens.refreshToken) {\n await this.clearSession('no_refresh_token');\n return null;\n }\n\n const run = async (): Promise<string | null> => {\n // Another tab may have refreshed while we waited for the lock.\n //\n // Check BOTH the shared store and our own in-memory tokens. Storage\n // alone is not enough: with a per-tab adapter (the default,\n // sessionStorage) `storage.get()` returns this tab's private copy\n // and never sees the winner's rotated token — but the winner also\n // broadcasts, and onBroadcast() updates `this.tokens`. Consulting\n // both makes the check work for shared and per-tab adapters alike.\n const stored = await this.storage.get();\n const fresher = [stored, this.tokens]\n .filter((t) => t.accessToken && t.expiresAt)\n .sort((a, b) => (b.expiresAt ?? 0) - (a.expiresAt ?? 0))[0];\n\n if (fresher && (fresher.expiresAt ?? 0) - Date.now() > PROACTIVE_WINDOW_MS) {\n this.tokens = fresher;\n this.scheduleRefresh();\n return fresher.accessToken;\n }\n\n // Read the refresh token HERE, inside the lock, not before waiting\n // for it. The server rotates and revokes on use, so a value\n // captured before the lock is already spent by the time the loser\n // acquires it — the request 400s and the tab is signed out.\n const refreshToken = this.tokens.refreshToken;\n if (!refreshToken) {\n await this.clearSession('no_refresh_token');\n return null;\n }\n\n try {\n const res = await this.auth.refreshToken(refreshToken);\n await this.persist(LumoAuthSession.tokensFrom(res, this.tokens));\n this.scheduleRefresh();\n this.emit({ status: 'authenticated', isLoaded: true, isSignedIn: true, error: null });\n return this.tokens.accessToken;\n } catch {\n await this.clearSession('refresh_failed');\n return null;\n }\n };\n\n const locks = (globalThis as { navigator?: { locks?: LockManager } }).navigator?.locks;\n if (locks?.request) {\n return locks.request(CHANNEL + '.refresh', run) as Promise<string | null>;\n }\n return run();\n }\n\n private scheduleRefresh(): void {\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n const { expiresAt, refreshToken } = this.tokens;\n if (!expiresAt || !refreshToken) return;\n const delay = Math.max(expiresAt - Date.now() - REFRESH_MARGIN_MS, MIN_TIMER_MS);\n this.timer = setTimeout(() => void this.refresh(), delay);\n }\n\n // ── Flows ────────────────────────────────────────────────────────\n\n /** Adopt tokens obtained elsewhere (e.g. a completed code exchange). */\n async adopt(res: TokenResponse): Promise<void> {\n await this.persist(LumoAuthSession.tokensFrom(res, this.tokens));\n this.scheduleRefresh();\n this.emit({ status: 'authenticated', isLoaded: true, isSignedIn: true, error: null });\n }\n\n /** Build the PKCE authorization URL; the caller persists verifier + state. */\n buildAuthorizationUrl(extraParams?: Record<string, string>) {\n return this.auth.buildAuthorizationUrl({\n redirectUri: this.redirectUri,\n scope: this.scope,\n ...(extraParams ? { extraParams } : {}),\n });\n }\n\n /**\n * Drop the session.\n *\n * `emit: false` clears tokens and storage without notifying subscribers.\n * That is required during sign-out: emitting re-renders the tree, which\n * mounts any `<SignedOut><RedirectToSignIn/></SignedOut>` guard, whose\n * effect then races the pending logout navigation and sends the user back\n * to /authorize — where the IdP session is still alive and silently\n * re-issues a code, defeating logout entirely.\n */\n async clearSession(\n error: string | null = null,\n opts: { broadcast?: boolean; emit?: boolean } = {},\n ): Promise<void> {\n const { broadcast = true, emit = true } = opts;\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n this.tokens = EMPTY_TOKENS;\n await this.storage.clear();\n if (broadcast) this.channel?.postMessage({ type: 'signout' } satisfies Broadcast);\n if (emit) {\n this.emit({ status: 'unauthenticated', isLoaded: true, isSignedIn: false, error });\n }\n }\n\n // ── Cross-tab ────────────────────────────────────────────────────\n\n private onBroadcast(msg: Broadcast): void {\n if (!msg) return;\n if (msg.type === 'signout') {\n // Do not re-broadcast: that would ping-pong between tabs.\n void this.clearSession(null, { broadcast: false });\n return;\n }\n if (msg.type === 'tokens' && msg.tokens) {\n this.tokens = msg.tokens;\n this.scheduleRefresh();\n this.emit({ status: 'authenticated', isLoaded: true, isSignedIn: true, error: null });\n this.onTokens?.(msg.tokens);\n }\n }\n}\n\n/** Minimal shape of the Web Locks API; not in every lib.dom version. */\ninterface LockManager {\n request<T>(name: string, cb: () => Promise<T>): Promise<T>;\n}\n","// @lumoauth/client — the browser SDK.\n//\n// This is the package application code imports. It re-exports all of\n// @lumoauth/shared so callers need a single dependency, and adds the\n// `LumoAuth` client itself.\n//\n// It is browser-safe by construction: constructing it with a tenant API key\n// (`lmk_…`) in a browser is a hard error. Server-only surfaces live in\n// @lumoauth/backend (token verification, admin) and @lumoauth/agent (AAuth,\n// which needs `node:crypto`).\n\nexport { LumoAuth, type LumoAuthConfig, type ClientApprovals } from './client';\n\n// ─── Session runtime (framework-agnostic) ─────────────────────────────\n// The store @lumoauth/react binds to. Exported so a Vue/Svelte binding can\n// use the same runtime instead of reimplementing refresh and cross-tab logic.\nexport {\n LumoAuthSession,\n type SessionState,\n type SessionStatus,\n type SessionOptions,\n} from './session';\n\n// ─── Token storage ────────────────────────────────────────────────────\nexport {\n type TokenStorage,\n type StoredTokens,\n type CookieStorageOptions,\n EMPTY_TOKENS,\n sessionStorageAdapter,\n localStorageAdapter,\n memoryStorageAdapter,\n cookieStorageAdapter,\n defaultStorage,\n} from './storage';\n\n// The full isomorphic surface: authorization modules, OAuth/PKCE helpers,\n// schemas, errors, and the HTTP client.\nexport * from '@lumoauth/shared';\n"],"mappings":";AAAA;AAAA,EACI;AAAA,EAEA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA,uBAAAA;AAAA,OACG;;;ACZP,SAAS,2BAA2B;AAOpC,IAAM,wBAAwB;AAG9B,SAAS,YAAqB;AAC1B,SAAO,OAAO,WAAW,eAAe,OAAO,OAAO,aAAa;AACvE;AAuBO,SAAS,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A;AAAA,EAGA,sBAAsB,aAAsC;AACxD,WAAO,KAAK,KAAK,sBAAsB;AAAA,MACnC,aAAa,KAAK;AAAA,MAClB,OAAO,KAAK;AAAA,MACZ,GAAI,cAAc,EAAE,YAAY,IAAI,CAAC;AAAA,IACzC,CAAC;AAAA,EACL;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,MAAM,aACF,QAAuB,MACvB,OAAgD,CAAC,GACpC;AACb,UAAM,EAAE,YAAY,MAAM,OAAO,KAAK,IAAI;AAC1C,QAAI,KAAK,MAAO,cAAa,KAAK,KAAK;AACvC,SAAK,QAAQ;AACb,SAAK,SAAS;AACd,UAAM,KAAK,QAAQ,MAAM;AACzB,QAAI,UAAW,MAAK,SAAS,YAAY,EAAE,MAAM,UAAU,CAAqB;AAChF,QAAI,MAAM;AACN,WAAK,KAAK,EAAE,QAAQ,mBAAmB,UAAU,MAAM,YAAY,OAAO,MAAM,CAAC;AAAA,IACrF;AAAA,EACJ;AAAA;AAAA,EAIQ,YAAY,KAAsB;AACtC,QAAI,CAAC,IAAK;AACV,QAAI,IAAI,SAAS,WAAW;AAExB,WAAK,KAAK,aAAa,MAAM,EAAE,WAAW,MAAM,CAAC;AACjD;AAAA,IACJ;AACA,QAAI,IAAI,SAAS,YAAY,IAAI,QAAQ;AACrC,WAAK,SAAS,IAAI;AAClB,WAAK,gBAAgB;AACrB,WAAK,KAAK,EAAE,QAAQ,iBAAiB,UAAU,MAAM,YAAY,MAAM,OAAO,KAAK,CAAC;AACpF,WAAK,WAAW,IAAI,MAAM;AAAA,IAC9B;AAAA,EACJ;AACJ;;;ACvSA,cAAc;","names":["LumoAuthConfigError","LumoAuthConfigError"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lumoauth/client",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.0",
|
|
4
4
|
"description": "Official LumoAuth browser SDK — OAuth 2.0 PKCE, permissions, Zanzibar (ReBAC), and ABAC for any JavaScript/TypeScript application.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "LumoAuth",
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
"browser"
|
|
39
39
|
],
|
|
40
40
|
"dependencies": {
|
|
41
|
-
"@lumoauth/shared": "^1.
|
|
41
|
+
"@lumoauth/shared": "^1.5.0",
|
|
42
42
|
"zod": "^4.6.7"
|
|
43
43
|
},
|
|
44
44
|
"devDependencies": {
|