Repository Public
1import { sql } from "./db";2import { sha256 } from "./crypto";34/** Session lookup without any Next.js import, so the worker and the custom server can use it too. */5export const SESSION_COOKIE = "sheet_session";6export const PREAUTH_COOKIE = "sheet_preauth";7export type SessionMethod = "passkey" | "setup" | "recovery_code";8export interface UserContext {9 userId: string; email: string; displayName: string; locale: "fr" | "en";10 sessionId: string; csrfToken: string; method: SessionMethod;11 /** Last passkey verification in this session, if any. */12 reauthAt: Date | null;13}1415export async function userFromToken(token: string | undefined | null): Promise<UserContext | null> {16 if (!token) return null;17 const [row] = await sql<{ id: string; user_id: string; csrf_token: string; email: string; display_name: string; locale: "fr" | "en"; method: SessionMethod; reauth_at: Date | null; last_seen_at: Date }[]>`18 SELECT s.id, s.user_id, s.csrf_token, s.method, s.reauth_at, s.last_seen_at, u.email, u.display_name, u.locale19 FROM sessions s JOIN users u ON u.id = s.user_id20 WHERE s.token_hash = ${sha256(token)} AND s.revoked_at IS NULL AND s.expires_at > now() AND s.last_seen_at > now() - interval '7 days' AND u.disabled_at IS NULL`;21 if (!row) return null;22 if (Date.now() - new Date(row.last_seen_at).getTime() > 60_000) await sql`UPDATE sessions SET last_seen_at = now() WHERE id = ${row.id}`;23 return { userId: row.user_id, email: row.email, displayName: row.display_name, locale: row.locale, sessionId: row.id, csrfToken: row.csrf_token, method: row.method, reauthAt: row.reauth_at };24}25