import type { Database } from 'bun:sqlite'; const DAY = 24 * 3600_000; export const SESSION_TTL = { guest: 365 * DAY, member: 90 * DAY } as const; export const SESSION_COOKIE = 'sid'; /** users.last_seen_at is written at most this often per user. */ const SEEN_EVERY = 60_000; export function randomToken(bytes = 32): string { const buf = new Uint8Array(bytes); crypto.getRandomValues(buf); return Buffer.from(buf).toString('base64url'); } export function sha256Hex(input: string): string { return new Bun.CryptoHasher('sha256').update(input).digest('hex'); } export class Sessions { constructor(private db: Database) {} create(userId: string, kind: 'guest' | 'member', userAgent: string | null, now = Date.now()): { token: string; expiresAt: number } { const token = randomToken(); const expiresAt = now + SESSION_TTL[kind]; this.db .query('INSERT INTO sessions (token_hash, user_id, created_at, expires_at, last_used_at, user_agent) VALUES (?, ?, ?, ?, ?, ?)') .run(sha256Hex(token), userId, now, expiresAt, now, userAgent?.slice(0, 200) ?? null); return { token, expiresAt }; } /** Resolves a token to a user id; slides expiry at most once per day. */ resolve(token: string, now = Date.now()): string | null { const hash = sha256Hex(token); const row = this.db .query<{ user_id: string; expires_at: number; last_used_at: number; kind: 'guest' | 'member'; last_seen_at: number }, [string]>( `SELECT s.user_id, s.expires_at, s.last_used_at, u.kind, u.last_seen_at FROM sessions s JOIN users u ON u.id = s.user_id WHERE s.token_hash = ? AND u.deleted_at IS NULL AND u.banned_at IS NULL`, ) .get(hash); if (!row) return null; if (row.expires_at <= now) { this.db.query('DELETE FROM sessions WHERE token_hash = ?').run(hash); return null; } if (now - row.last_used_at > DAY) { this.db .query('UPDATE sessions SET last_used_at = ?, expires_at = ? WHERE token_hash = ?') .run(now, now + SESSION_TTL[row.kind], hash); } // Idle guests are deleted after a day (docs/02), so remember when the user was last here. if (now - row.last_seen_at > SEEN_EVERY) this.db.query('UPDATE users SET last_seen_at = ? WHERE id = ?').run(now, row.user_id); return row.user_id; } revoke(token: string): void { this.db.query('DELETE FROM sessions WHERE token_hash = ?').run(sha256Hex(token)); } revokeAll(userId: string): void { this.db.query('DELETE FROM sessions WHERE user_id = ?').run(userId); } purgeExpired(now = Date.now()): number { return this.db.query('DELETE FROM sessions WHERE expires_at <= ?').run(now).changes; } } /** Minimal HMAC-signed value for short-lived cookies (OAuth state + PKCE verifier). */ export async function signValue(secret: string, value: string): Promise { const mac = await hmac(secret, value); return `${Buffer.from(value).toString('base64url')}.${mac}`; } export async function unsignValue(secret: string, signed: string): Promise { const dot = signed.lastIndexOf('.'); if (dot < 0) return null; const value = Buffer.from(signed.slice(0, dot), 'base64url').toString(); const expected = await hmac(secret, value); const given = signed.slice(dot + 1); if (expected.length !== given.length) return null; let diff = 0; for (let i = 0; i < expected.length; i++) diff |= expected.charCodeAt(i) ^ given.charCodeAt(i); return diff === 0 ? value : null; } async function hmac(secret: string, value: string): Promise { const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']); const sig = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(value)); return Buffer.from(sig).toString('base64url'); }