UNPKG

wcz-layout

Version:

136 lines (135 loc) • 5.02 kB
import { n as serverEnv } from "./env-Cddts_dn.mjs"; import { queryOptions } from "@tanstack/react-query"; import { createServerFn } from "@tanstack/react-start"; // src/lib/auth/offline.ts /** * Offline fallback for identity. The refresh token never leaves the sealed * httpOnly cookie — what is cached here is only the display snapshot (user * claims and avatar) so the UI and offline route permissions can still work * while the server is unreachable. Server requests remain independently * authorized. At-rest protection is the device's OS login and disk encryption. */ const OFFLINE_USER_KEY = "auth-user"; const OFFLINE_PHOTO_KEY = "auth-photo"; /** One shift — matches Intune's default offline grace period. */ const GRACE_PERIOD = 432e5; const recall = (key) => { if (typeof localStorage === "undefined") return null; try { const raw = localStorage.getItem(key); if (!raw) return null; const { value, savedAt } = JSON.parse(raw); if (Date.now() - savedAt > GRACE_PERIOD) { localStorage.removeItem(key); return null; } return value; } catch { localStorage.removeItem(key); return null; } }; const remember = (key, value) => { if (typeof localStorage === "undefined") return; try { if (value === null || value === void 0) localStorage.removeItem(key); else localStorage.setItem(key, JSON.stringify({ value, savedAt: Date.now() })); } catch {} }; const isOfflineFailure = (error) => typeof navigator !== "undefined" && !navigator.onLine || error instanceof TypeError; /** * Answers from the server when reachable, remembering the result; when the call * has a transport failure, replays the last result instead, for up to * {@link GRACE_PERIOD} since it was last confirmed. * * Cached values are untrusted client state. Server authorization must never * depend on them. */ const withOfflineFallback = async (key, fetchFresh) => { try { const fresh = await fetchFresh(); remember(key, fresh); return fresh; } catch (error) { if (!isOfflineFailure(error)) throw error; return recall(key); } }; /** Drops the cached identity. Call on logout, before leaving the page. */ const clearSessionSnapshot = () => { if (typeof localStorage === "undefined") return; localStorage.removeItem(OFFLINE_USER_KEY); localStorage.removeItem(OFFLINE_PHOTO_KEY); localStorage.setItem("auth-logout", String(Date.now())); }; if (typeof window !== "undefined") window.addEventListener("storage", (event) => { if (event.key === "auth-logout") location.href = "/auth/logout"; }); // src/lib/auth/session.ts const getAppSession = async () => { const [{ getIronSession }, { getCookie, setCookie }] = await Promise.all([import("iron-session"), import("@tanstack/react-start/server")]); return getIronSession({ read: getCookie, write: setCookie }, { cookieName: "app-session", password: serverEnv.SESSION_SECRET, chunk: true, cookieOptions: { secure: process.env.NODE_ENV === "production", sameSite: "lax", httpOnly: true, path: "/", maxAge: void 0 } }); }; // src/lib/auth/user.ts /** * Reads the signed-in user from the session cookie, or null. As a server function * it runs in-process when called on the server (SSR, middleware) and as an RPC * when called from the client — so it doubles as the client `queryFn`. */ const getSessionUser = createServerFn({ method: "GET" }).handler(async () => { return (await getAppSession()).user ?? null; }); /** The identity providers the server offers, for the login page. */ const getLoginProviders = createServerFn({ method: "GET" }).handler(async () => { const { providers } = await import("./providers-DOFje2P6.mjs").then((n) => n.i); return providers.map(({ id, label }) => ({ id, label })); }); /** * Feeds `LoginForm`. Server config, not per-user, so it is safe to prime on the * server — the `/login` route's loader does that to avoid a flash of empty card. */ const loginProvidersQueryOptions = queryOptions({ queryKey: ["auth", "providers"], queryFn: () => getLoginProviders(), staleTime: "static" }); /** * Client-side query for the signed-in user. Shared between `getUser` (route * `beforeLoad`) and the always-mounted observer in `LayoutProvider` — the * observer is what seeds the offline snapshot on the very first page load * (`beforeLoad` does not re-run after SSR hydration) and what makes * `refetchOnReconnect` fire once connectivity returns. */ const userQueryOptions = queryOptions({ queryKey: ["auth", "user"], queryFn: () => withOfflineFallback(OFFLINE_USER_KEY, () => getSessionUser()), staleTime: Infinity, networkMode: "offlineFirst", refetchOnReconnect: "always" }); const getUser = ({ queryClient }) => { if (import.meta.env.SSR) return getSessionUser(); return queryClient.ensureQueryData(userQueryOptions); }; export { getAppSession as a, withOfflineFallback as c, userQueryOptions as i, getUser as n, OFFLINE_PHOTO_KEY as o, loginProvidersQueryOptions as r, clearSessionSnapshot as s, getSessionUser as t }; //# sourceMappingURL=user-Bc2nLjAG.mjs.map