// require-session.ts: the check at the top of every API route that needs a signed-in person. Server only. // For any method other than GET and HEAD the Origin must also be your site (with the SameSite=Lax cookie, this stops cross-site // requests, CSRF). The Origin is checked first, so a cross-site request learns nothing about who is signed in. import { readCookie, verifySession, SESSION_COOKIE, type Session } from './session.ts'; const json = (body: unknown, status: number): Response => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json', 'cache-control': 'no-store' } }); export function requireSession(request: Request, appOrigin: string, nowMs = Date.now()): Session | Response { const mutating = request.method !== 'GET' && request.method !== 'HEAD'; if (mutating && request.headers.get('origin') !== appOrigin) return json({ error: 'bad_origin' }, 403); return verifySession(readCookie(request, SESSION_COOKIE), nowMs) ?? json({ error: 'not_signed_in' }, 401); } // Use it like this. Every query is scoped to the session's user by your code, because the secret key bypasses RLS. // // export async function GET(request: Request): Promise { // const session = requireSession(request, process.env.APP_ORIGIN!); // if (session instanceof Response) return session; // const projects = await db.listProjects(session.userId); // return json({ projects }, 200); // }