import process from "node:process"; import { Hono } from "hono"; import { JoseKey } from "@atproto/oauth-client-node"; import { getOAuthClient, SCOPE } from "./server/lib/auth/client"; import { deleteCookie, setCookie } from "hono/cookie"; import { getDid, getSession } from "./server/lib/auth/session"; const app = new Hono(); app.get("/api/hello", (c) => { return c.json({ message: "Hello" }); }); app.post("/api/oauth/login", async (c) => { try { const { handle } = await c.req.json(); if (!handle || typeof handle !== "string") { return c.json({ error: "Handle is required!", }, 400); } const client = await getOAuthClient(); const authUrl = await client.authorize(handle, { scope: SCOPE, }); return c.json({ redirectUrl: authUrl.toString() }); } catch (e) { console.error("OAuth login error:", e); return c.json({ error: e instanceof Error ? e.message : "Login failed", }, 500); } }); app.post("/api/oauth/logout", async (c) => { try { const did = await getDid(c); if (did) { const client = await getOAuthClient(); client.revoke(did); } deleteCookie(c, "did"); return c.json({ success: true }); } catch (e) { console.error("Logout error:", e); deleteCookie(c, "did"); return c.json({ success: true }); } }); app.get("/oauth/callback", async (c) => { const PUBLIC_URL = process.env.PUBLIC_URL || "http://127.0.0.1:3000"; try { const params = new URL(c.req.url).searchParams; const client = await getOAuthClient(); const { session } = await client.callback(params); setCookie(c, "did", session.did, { httpOnly: true, secure: process.env.NODE_ENV === "production", sameSite: "Lax", maxAge: 60 * 60 * 24 * 7, // 1 week path: "/", }); return c.redirect(new URL("/", PUBLIC_URL)); } catch (e) { console.error("OAuth callback error:", e); return c.redirect(new URL("/?error=login_failed", PUBLIC_URL)); } }); app.get("/oauth-client-metadata.json", async (c) => { const client = await getOAuthClient(); return c.json(client.clientMetadata); }); app.get("/.well-known/jwks.json", async (c) => { const PRIVATE_KEY = process.env.PRIVATE_KEY; if (!PRIVATE_KEY) return c.json({ keys: [] }) const key = await JoseKey.fromJWK(JSON.parse(PRIVATE_KEY)); return c.json({ keys: [key.publicJwk] }) }) app.get("/api/session", async (c) => { const session = await getSession(c); return c.json(session) }) export default app;