import { createMiddleware } from "hono/factory"; import { getCookie, deleteCookie } from "hono/cookie"; import { getOAuthClient } from "./client.ts"; import type { OAuthSession } from "@atproto/oauth-client-node"; /** Hono env type — augments context with the authenticated user's DID */ export type AuthEnv = { Variables: { did: string; session: OAuthSession; }; }; /** * Middleware that requires authentication. * Returns 401 if no valid session. Sets `c.var.did` and `c.var.session`. */ export const requireAuth = createMiddleware(async (c, next) => { const did = getCookie(c, "sid"); if (!did) { return c.json({ error: "Unauthorized" }, 401); } try { const client = await getOAuthClient(); const session = await client.restore(did); c.set("did", session.did); c.set("session", session); await next(); } catch { deleteCookie(c, "sid", { path: "/" }); return c.json({ error: "Session expired" }, 401); } }); /** * Middleware that optionally attaches auth info. * Does not block unauthenticated requests. */ export const optionalAuth = createMiddleware(async (c, next) => { const did = getCookie(c, "sid"); if (did) { try { const client = await getOAuthClient(); const session = await client.restore(did); c.set("did", session.did); c.set("session", session); } catch { deleteCookie(c, "sid", { path: "/" }); } } await next(); });