import { deleteCookie, getCookie, getSignedCookie, setCookie, setSignedCookie } from 'hono/cookie'; import type { Ctx, Env, User } from '../env'; import { DAY, HttpError, now, randomToken, sha256Hex } from './util'; const SESSION_COOKIE = 'sf_session'; const SESSION_DAYS = 30; export function secret(env: Env): string { if (!env.SESSION_SECRET || env.SESSION_SECRET.length < 24) throw new HttpError(503, 'Sign-in is not configured yet.'); return env.SESSION_SECRET; } function isSecure(c: Ctx): boolean { return new URL(c.req.url).protocol === 'https:'; } export async function createSession(c: Ctx, userId: string): Promise { const token = randomToken(32); const ts = now(); await c.env.DB.prepare('INSERT INTO sessions (token_hash, user_id, expires_at, created_at) VALUES (?,?,?,?)') .bind(await sha256Hex(token), userId, ts + SESSION_DAYS * DAY, ts) .run(); setCookie(c, SESSION_COOKIE, token, { httpOnly: true, secure: isSecure(c), sameSite: 'Lax', path: '/', maxAge: SESSION_DAYS * DAY }); } export async function loadSessionUser(c: Ctx): Promise { const token = getCookie(c, SESSION_COOKIE); if (!token || token.length < 20) return null; const hash = await sha256Hex(token); const row = await c.env.DB.prepare( 'SELECT u.*, s.expires_at AS session_expires FROM sessions s JOIN users u ON u.id = s.user_id WHERE s.token_hash = ?', ) .bind(hash) .first(); const ts = now(); if (!row || row.session_expires < ts || row.status !== 'active') { if (row) await c.env.DB.prepare('DELETE FROM sessions WHERE token_hash = ?').bind(hash).run(); deleteCookie(c, SESSION_COOKIE, { path: '/' }); return null; } // Sliding expiry: extend at most once a day to keep writes rare. if (row.session_expires - ts < (SESSION_DAYS - 1) * DAY) { c.executionCtx.waitUntil(c.env.DB.prepare('UPDATE sessions SET expires_at = ? WHERE token_hash = ?').bind(ts + SESSION_DAYS * DAY, hash).run()); setCookie(c, SESSION_COOKIE, token, { httpOnly: true, secure: isSecure(c), sameSite: 'Lax', path: '/', maxAge: SESSION_DAYS * DAY }); } const { session_expires: _drop, ...user } = row; return user as User; } export async function destroySession(c: Ctx): Promise { const token = getCookie(c, SESSION_COOKIE); if (token) await c.env.DB.prepare('DELETE FROM sessions WHERE token_hash = ?').bind(await sha256Hex(token)).run(); deleteCookie(c, SESSION_COOKIE, { path: '/' }); } /** Short-lived signed cookie holding JSON, for OAuth state and pending account links. */ export async function setSigned(c: Ctx, name: string, value: unknown, maxAge: number): Promise { await setSignedCookie(c, name, JSON.stringify(value), secret(c.env), { httpOnly: true, secure: isSecure(c), sameSite: 'Lax', path: '/', maxAge }); } export async function getSigned(c: Ctx, name: string): Promise { const raw = await getSignedCookie(c, secret(c.env), name); if (!raw) return null; try { return JSON.parse(raw) as T; } catch { return null; } } export function clearCookie(c: Ctx, name: string): void { deleteCookie(c, name, { path: '/' }); } /** One-shot message shown on the next page. */ export function setFlash(c: Ctx, kind: 'ok' | 'error', text: string): void { setCookie(c, 'sf_flash', encodeURIComponent(JSON.stringify({ kind, text })), { httpOnly: true, secure: isSecure(c), sameSite: 'Lax', path: '/', maxAge: 60 }); } export function takeFlash(c: Ctx): { kind: 'ok' | 'error'; text: string } | null { const raw = getCookie(c, 'sf_flash'); if (!raw) return null; deleteCookie(c, 'sf_flash', { path: '/' }); try { const v = JSON.parse(decodeURIComponent(raw)); if ((v.kind === 'ok' || v.kind === 'error') && typeof v.text === 'string') return { kind: v.kind, text: v.text.slice(0, 400) }; } catch { /* ignore */ } return null; }