Skillfarm / website · skillfarm.ai / src / lib / session.ts
| 1 | import { deleteCookie, getCookie, getSignedCookie, setCookie, setSignedCookie } from 'hono/cookie'; |
| 2 | import type { Ctx, Env, User } from '../env'; |
| 3 | import { DAY, HttpError, now, randomToken, sha256Hex } from './util'; |
| 4 | |
| 5 | const SESSION_COOKIE = 'sf_session'; |
| 6 | const SESSION_DAYS = 30; |
| 7 | |
| 8 | export function secret(env: Env): string { |
| 9 | if (!env.SESSION_SECRET || env.SESSION_SECRET.length < 24) throw new HttpError(503, 'Sign-in is not configured yet.'); |
| 10 | return env.SESSION_SECRET; |
| 11 | } |
| 12 | |
| 13 | function isSecure(c: Ctx): boolean { |
| 14 | return new URL(c.req.url).protocol === 'https:'; |
| 15 | } |
| 16 | |
| 17 | export async function createSession(c: Ctx, userId: string): Promise<void> { |
| 18 | const token = randomToken(32); |
| 19 | const ts = now(); |
| 20 | await c.env.DB.prepare('INSERT INTO sessions (token_hash, user_id, expires_at, created_at) VALUES (?,?,?,?)') |
| 21 | .bind(await sha256Hex(token), userId, ts + SESSION_DAYS * DAY, ts) |
| 22 | .run(); |
| 23 | setCookie(c, SESSION_COOKIE, token, { httpOnly: true, secure: isSecure(c), sameSite: 'Lax', path: '/', maxAge: SESSION_DAYS * DAY }); |
| 24 | } |
| 25 | |
| 26 | export async function loadSessionUser(c: Ctx): Promise<User | null> { |
| 27 | const token = getCookie(c, SESSION_COOKIE); |
| 28 | if (!token || token.length < 20) return null; |
| 29 | const hash = await sha256Hex(token); |
| 30 | const row = await c.env.DB.prepare( |
| 31 | 'SELECT u.*, s.expires_at AS session_expires FROM sessions s JOIN users u ON u.id = s.user_id WHERE s.token_hash = ?', |
| 32 | ) |
| 33 | .bind(hash) |
| 34 | .first<User & { session_expires: number }>(); |
| 35 | const ts = now(); |
| 36 | if (!row || row.session_expires < ts || row.status !== 'active') { |
| 37 | if (row) await c.env.DB.prepare('DELETE FROM sessions WHERE token_hash = ?').bind(hash).run(); |
| 38 | deleteCookie(c, SESSION_COOKIE, { path: '/' }); |
| 39 | return null; |
| 40 | } |
| 41 | // Sliding expiry: extend at most once a day to keep writes rare. |
| 42 | if (row.session_expires - ts < (SESSION_DAYS - 1) * DAY) { |
| 43 | c.executionCtx.waitUntil(c.env.DB.prepare('UPDATE sessions SET expires_at = ? WHERE token_hash = ?').bind(ts + SESSION_DAYS * DAY, hash).run()); |
| 44 | setCookie(c, SESSION_COOKIE, token, { httpOnly: true, secure: isSecure(c), sameSite: 'Lax', path: '/', maxAge: SESSION_DAYS * DAY }); |
| 45 | } |
| 46 | const { session_expires: _drop, ...user } = row; |
| 47 | return user as User; |
| 48 | } |
| 49 | |
| 50 | export async function destroySession(c: Ctx): Promise<void> { |
| 51 | const token = getCookie(c, SESSION_COOKIE); |
| 52 | if (token) await c.env.DB.prepare('DELETE FROM sessions WHERE token_hash = ?').bind(await sha256Hex(token)).run(); |
| 53 | deleteCookie(c, SESSION_COOKIE, { path: '/' }); |
| 54 | } |
| 55 | |
| 56 | /** Short-lived signed cookie holding JSON, for OAuth state and pending account links. */ |
| 57 | export async function setSigned(c: Ctx, name: string, value: unknown, maxAge: number): Promise<void> { |
| 58 | await setSignedCookie(c, name, JSON.stringify(value), secret(c.env), { httpOnly: true, secure: isSecure(c), sameSite: 'Lax', path: '/', maxAge }); |
| 59 | } |
| 60 | |
| 61 | export async function getSigned<T>(c: Ctx, name: string): Promise<T | null> { |
| 62 | const raw = await getSignedCookie(c, secret(c.env), name); |
| 63 | if (!raw) return null; |
| 64 | try { |
| 65 | return JSON.parse(raw) as T; |
| 66 | } catch { |
| 67 | return null; |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | export function clearCookie(c: Ctx, name: string): void { |
| 72 | deleteCookie(c, name, { path: '/' }); |
| 73 | } |
| 74 | |
| 75 | /** One-shot message shown on the next page. */ |
| 76 | export function setFlash(c: Ctx, kind: 'ok' | 'error', text: string): void { |
| 77 | setCookie(c, 'sf_flash', encodeURIComponent(JSON.stringify({ kind, text })), { httpOnly: true, secure: isSecure(c), sameSite: 'Lax', path: '/', maxAge: 60 }); |
| 78 | } |
| 79 | |
| 80 | export function takeFlash(c: Ctx): { kind: 'ok' | 'error'; text: string } | null { |
| 81 | const raw = getCookie(c, 'sf_flash'); |
| 82 | if (!raw) return null; |
| 83 | deleteCookie(c, 'sf_flash', { path: '/' }); |
| 84 | try { |
| 85 | const v = JSON.parse(decodeURIComponent(raw)); |
| 86 | if ((v.kind === 'ok' || v.kind === 'error') && typeof v.text === 'string') return { kind: v.kind, text: v.text.slice(0, 400) }; |
| 87 | } catch { |
| 88 | /* ignore */ |
| 89 | } |
| 90 | return null; |
| 91 | } |