Repository Public
1import type { FastifyReply, FastifyRequest } from "fastify"2import crypto from "node:crypto"3import { config, cookieName } from "./config.js"4import { sql } from "./db.js"5import { bad, sha256 } from "./util.js"67export type Auth = {8 sessionId: string9 userId: string10 deviceId: string | null11 role: "admin" | "member"12 status: "active" | "pending" | "disabled" | "rejected"13}1415export async function createSession(req: FastifyRequest, reply: FastifyReply, userId: string, passkeyId: string | null) {16 const token = crypto.randomBytes(32).toString("base64url")17 const expires = new Date(Date.now() + config.sessionMaxDays * 86400_000)18 const [row] = await sql`19 insert into sessions (token_hash, user_id, passkey_id, ip, user_agent, expires_at)20 values (${sha256(token)}, ${userId}, ${passkeyId}, ${req.ip}, ${String(req.headers["user-agent"] ?? "").slice(0, 300)}, ${expires})21 returning id`22 reply.setCookie(cookieName, token, {23 path: "/",24 httpOnly: true,25 secure: config.secureCookies,26 sameSite: "strict",27 expires,28 })29 return row.id as string30}3132export function clearSessionCookie(reply: FastifyReply) {33 reply.clearCookie(cookieName, { path: "/", httpOnly: true, secure: config.secureCookies, sameSite: "strict" })34}3536export async function authFromToken(token: string | undefined, touch = true): Promise<Auth | null> {37 if (!token || token.length > 200) return null38 const [row] = await sql`39 select s.id, s.user_id, s.device_id, s.last_seen_at, u.role, u.status40 from sessions s join users u on u.id = s.user_id41 where s.token_hash = ${sha256(token)} and s.revoked_at is null and s.expires_at > now()42 and s.last_seen_at > now() - make_interval(days => ${config.sessionIdleDays})`43 if (!row) return null44 if (row.status === "disabled" || row.status === "rejected") return null45 if (touch && Date.now() - new Date(row.last_seen_at).getTime() > 60_000)46 await sql`update sessions set last_seen_at = now() where id = ${row.id}`47 return { sessionId: row.id, userId: row.user_id, deviceId: row.device_id, role: row.role, status: row.status }48}4950declare module "fastify" {51 interface FastifyRequest {52 auth?: Auth53 }54}5556/** Any signed-in account (including accounts still waiting for approval). */57export async function requireSession(req: FastifyRequest): Promise<Auth> {58 const a = await authFromToken(req.cookies[cookieName])59 if (!a) throw bad("unauthenticated", 401)60 req.auth = a61 return a62}63/** Active account. */64export async function requireUser(req: FastifyRequest): Promise<Auth> {65 const a = await requireSession(req)66 if (a.status !== "active") throw bad("account_not_active", 403)67 return a68}69/** Active account with an enrolled, non-revoked device bound to this session. */70export async function requireDevice(req: FastifyRequest): Promise<Auth & { deviceId: string }> {71 const a = await requireUser(req)72 if (!a.deviceId) throw bad("no_device", 403)73 const [d] = await sql`select status from devices where id = ${a.deviceId} and user_id = ${a.userId}`74 if (!d || d.status !== "active") throw bad("device_not_active", 403)75 return a as Auth & { deviceId: string }76}77export async function requireAdmin(req: FastifyRequest): Promise<Auth> {78 const a = await requireUser(req)79 if (a.role !== "admin") throw bad("forbidden", 403)80 return a81}82