wcz-layout
Version:
1 lines • 9.48 kB
Source Map (JSON)
{"version":3,"file":"user-Bc2nLjAG.mjs","names":[],"sources":["../src/lib/auth/offline.ts","../src/lib/auth/session.ts","../src/lib/auth/user.ts"],"sourcesContent":["/**\n * Offline fallback for identity. The refresh token never leaves the sealed\n * httpOnly cookie — what is cached here is only the display snapshot (user\n * claims and avatar) so the UI and offline route permissions can still work\n * while the server is unreachable. Server requests remain independently\n * authorized. At-rest protection is the device's OS login and disk encryption.\n */\n\nexport const OFFLINE_USER_KEY = \"auth-user\";\nexport const OFFLINE_PHOTO_KEY = \"auth-photo\";\n\n/** One shift — matches Intune's default offline grace period. */\nconst GRACE_PERIOD = 12 * 60 * 60 * 1000;\n\ntype Cached<T> = { value: T; savedAt: number };\n\nconst recall = <T>(key: string): T | null => {\n if (typeof localStorage === \"undefined\") return null;\n try {\n const raw = localStorage.getItem(key);\n if (!raw) return null;\n const { value, savedAt } = JSON.parse(raw) as Cached<T>;\n if (Date.now() - savedAt > GRACE_PERIOD) {\n localStorage.removeItem(key);\n return null;\n }\n return value;\n } catch {\n localStorage.removeItem(key);\n return null;\n }\n};\n\nconst remember = (key: string, value: unknown): void => {\n if (typeof localStorage === \"undefined\") return;\n try {\n if (value === null || value === undefined) localStorage.removeItem(key);\n else localStorage.setItem(key, JSON.stringify({ value, savedAt: Date.now() }));\n } catch {\n // Storage full or blocked — the offline fallback is best-effort.\n }\n};\n\nconst isOfflineFailure = (error: unknown): boolean =>\n (typeof navigator !== \"undefined\" && !navigator.onLine) || error instanceof TypeError;\n\n/**\n * Answers from the server when reachable, remembering the result; when the call\n * has a transport failure, replays the last result instead, for up to\n * {@link GRACE_PERIOD} since it was last confirmed.\n *\n * Cached values are untrusted client state. Server authorization must never\n * depend on them.\n */\nexport const withOfflineFallback = async <T>(\n key: string,\n fetchFresh: () => Promise<T>,\n): Promise<T | null> => {\n try {\n const fresh = await fetchFresh();\n remember(key, fresh);\n return fresh;\n } catch (error) {\n if (!isOfflineFailure(error)) throw error;\n return recall<T>(key);\n }\n};\n\n/** Drops the cached identity. Call on logout, before leaving the page. */\nexport const clearSessionSnapshot = (): void => {\n if (typeof localStorage === \"undefined\") return;\n localStorage.removeItem(OFFLINE_USER_KEY);\n localStorage.removeItem(OFFLINE_PHOTO_KEY);\n localStorage.setItem(\"auth-logout\", String(Date.now()));\n};\n\nif (typeof window !== \"undefined\")\n window.addEventListener(\"storage\", (event) => {\n if (event.key === \"auth-logout\") location.href = \"/auth/logout\";\n });\n","import type { IronSession } from \"iron-session\";\nimport { serverEnv } from \"~/env\";\nimport type { ProviderId, User } from \"~/models/User\";\n\nexport interface AppSessionData {\n /** Which identity provider signed this user in. */\n provider?: ProviderId;\n /** The only token persisted; delegated access tokens are minted from it. */\n refreshToken?: string;\n user?: User;\n /** Transient, only between /auth/login and /auth/callback. */\n pkceVerifier?: string;\n state?: string;\n returnTo?: string;\n}\n\nexport type AppSession = IronSession<AppSessionData>;\n\nexport const getAppSession = async (): Promise<AppSession> => {\n // Dynamic import: `@tanstack/react-start/server` is the server entry and drags\n // in the SSR renderer (`react-dom/server`). Keep it out of the client graph —\n // this helper is only ever called server-side, and all callers already await it.\n const [{ getIronSession }, { getCookie, setCookie }] = await Promise.all([\n import(\"iron-session\"),\n import(\"@tanstack/react-start/server\"),\n ]);\n\n return getIronSession<AppSessionData>(\n { read: getCookie, write: setCookie },\n {\n // Not `session`: that name holds the pre-stable `useSession` seal, which\n // iron-session can't read. Users sign in once more after the upgrade.\n cookieName: \"app-session\",\n password: serverEnv.SESSION_SECRET,\n chunk: true,\n cookieOptions: {\n secure: process.env.NODE_ENV === \"production\",\n sameSite: \"lax\",\n httpOnly: true,\n path: \"/\",\n // Explicit `undefined`: browser-session cookie and a seal that never\n // expires — what `useSession` did. Omit it to fall back to iron's 14-day `ttl`.\n maxAge: undefined,\n },\n },\n );\n};\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { createServerFn } from \"@tanstack/react-start\";\nimport type { QueryClientParam } from \"~/models/QueryClientParam\";\nimport type { ProviderId, User } from \"~/models/User\";\nimport { OFFLINE_USER_KEY, withOfflineFallback } from \"./offline\";\nimport { getAppSession } from \"./session\";\n\n/**\n * Reads the signed-in user from the session cookie, or null. As a server function\n * it runs in-process when called on the server (SSR, middleware) and as an RPC\n * when called from the client — so it doubles as the client `queryFn`.\n */\nexport const getSessionUser = createServerFn({ method: \"GET\" }).handler(\n async (): Promise<User | null> => {\n const session = await getAppSession();\n return session.user ?? null;\n },\n);\n\n/** The identity providers the server offers, for the login page. */\nexport const getLoginProviders = createServerFn({ method: \"GET\" }).handler(\n async (): Promise<Array<{ id: ProviderId; label: string }>> => {\n // Dynamic import: `providers` reads `serverEnv` and must not reach the client.\n const { providers } = await import(\"./providers\");\n return providers.map(({ id, label }) => ({ id, label }));\n },\n);\n\n/**\n * Feeds `LoginForm`. Server config, not per-user, so it is safe to prime on the\n * server — the `/login` route's loader does that to avoid a flash of empty card.\n */\nexport const loginProvidersQueryOptions = queryOptions({\n queryKey: [\"auth\", \"providers\"],\n queryFn: () => getLoginProviders(),\n staleTime: \"static\",\n});\n\n/**\n * Client-side query for the signed-in user. Shared between `getUser` (route\n * `beforeLoad`) and the always-mounted observer in `LayoutProvider` — the\n * observer is what seeds the offline snapshot on the very first page load\n * (`beforeLoad` does not re-run after SSR hydration) and what makes\n * `refetchOnReconnect` fire once connectivity returns.\n */\nexport const userQueryOptions = queryOptions({\n queryKey: [\"auth\", \"user\"],\n queryFn: () => withOfflineFallback(OFFLINE_USER_KEY, () => getSessionUser()),\n staleTime: Infinity,\n // Default \"online\" pauses the query (never calling queryFn) once the browser\n // reports no connection — which is exactly when the fallback is needed.\n networkMode: \"offlineFirst\",\n // Back online: re-confirm the session and re-stamp the snapshot's grace period.\n refetchOnReconnect: \"always\",\n});\n\nexport const getUser = ({ queryClient }: QueryClientParam): Promise<User | null> => {\n if (import.meta.env.SSR) return getSessionUser();\n\n return queryClient.ensureQueryData(userQueryOptions);\n};\n"],"mappings":";;;;;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