UNPKG

@softr/sdk

Version:

The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.

85 lines (83 loc) • 2.72 kB
import { clearSession, readSessionToken } from "./session.js"; import { readSoftrContext } from "./context.js"; import { settings } from "./methods/settings.js"; import { useCurrentUser } from "./isomorphic.js"; import { startIdleClock } from "./idle-clock.js"; import { z } from "zod"; import { useEffect } from "react"; import { createServerFn } from "@tanstack/react-start"; //#region src/auth/idle-timeout.ts /** * The "End session if idle" setting from Studio, with when this session began. * `null` when it does not apply: nobody is signed in, it is set to never, or * this is not a production build. Preview runs on a dev server and is the * owner's own session. */ const readIdleTimeout = createServerFn({ method: "GET" }).handler(async () => { if (process.env.NODE_ENV !== "production") return null; if (readSoftrContext().user === null) return null; const minutes = (await settings()).inactivityTimeoutMinutes; if (minutes === null) return null; return { idleMs: minutes * 6e4, sessionStartedAt: sessionStartedAt() }; }); const tokenClaims = z.object({ iat: z.number() }); /** The platform signs its token with the sign-in time, in seconds. */ function sessionStartedAt() { const payload = readSessionToken()?.split(".")[1]; if (payload === void 0) return null; try { const claims = tokenClaims.safeParse(JSON.parse(Buffer.from(payload, "base64url").toString())); return claims.success ? claims.data.iat * 1e3 : null; } catch { return null; } } /** * Signs this browser out and nothing else. Unlike `auth.signOut()`, the user's * other devices stay signed in. */ const endIdleSession = createServerFn({ method: "POST" }).handler(() => { clearSession(); }); /** * Signs the visitor out of this browser after the idle time set in Studio's * "End session if idle", and sends them to `/`. Activity in any tab of the app * keeps the session alive. Does nothing for anonymous visitors. * * Call it once, in the root route's document component. * * @example * function RootDocument({ children }: { children: React.ReactNode }) { * useIdleTimeout() * // ... * } */ function useIdleTimeout() { const signedIn = useCurrentUser() !== null; useEffect(() => { if (!signedIn) return; let stop = null; let retry; let unmounted = false; function read() { readIdleTimeout().then((timeout) => { if (unmounted || timeout === null) return; stop = startIdleClock(timeout.idleMs, endIdleSession, timeout.sessionStartedAt); }, () => { if (!unmounted) retry = setTimeout(read, READ_RETRY_MS); }); } read(); return () => { unmounted = true; clearTimeout(retry); stop?.(); }; }, [signedIn]); } const READ_RETRY_MS = 6e4; //#endregion export { useIdleTimeout };