import crypto from "node:crypto"; import { eq } from "drizzle-orm"; import { createMiddleware } from "hono/factory"; import { getCookie, setCookie, deleteCookie } from "hono/cookie"; import type { Context } from "hono"; import { db } from "../db/index.js"; import { sessions, users, type User } from "../db/schema.js"; const SESSION_COOKIE = "spool_session"; const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000; // 30 days export type AuthEnv = { Variables: { user: User | null } }; // Runs on every request: resolves the session cookie to a user (or null). export const sessionMiddleware = createMiddleware(async (c, next) => { c.set("user", null); const token = getCookie(c, SESSION_COOKIE); if (token) { const [row] = await db .select({ user: users, expiresAt: sessions.expiresAt }) .from(sessions) .innerJoin(users, eq(sessions.userId, users.id)) .where(eq(sessions.id, token)); if (row && row.expiresAt.getTime() > Date.now()) { c.set("user", row.user); } } await next(); }); // Guard for write endpoints — reads stay public. export const requireAuth = createMiddleware(async (c, next) => { if (!c.get("user")) { return c.json({ error: "Authentication required" }, 401); } await next(); }); export async function createSession(c: Context, userId: number) { const token = crypto.randomBytes(32).toString("hex"); await db.insert(sessions).values({ id: token, userId, expiresAt: new Date(Date.now() + SESSION_TTL_MS), }); setCookie(c, SESSION_COOKIE, token, { httpOnly: true, sameSite: "Lax", path: "/", maxAge: SESSION_TTL_MS / 1000, }); } export async function destroySession(c: Context) { const token = getCookie(c, SESSION_COOKIE); if (token) { await db.delete(sessions).where(eq(sessions.id, token)); } deleteCookie(c, SESSION_COOKIE, { path: "/" }); }