import crypto from "node:crypto"; import { Hono } from "hono"; import { getCookie, setCookie, deleteCookie } from "hono/cookie"; import { db } from "../db/index.js"; import { users } from "../db/schema.js"; import { createSession, destroySession, type AuthEnv } from "./session.js"; const APP_URL = process.env.APP_URL ?? "http://localhost:5173"; const auth = new Hono(); auth.get("/github", (c) => { const clientId = process.env.GITHUB_CLIENT_ID; if (!clientId) { return c.text("GITHUB_CLIENT_ID is not set — see server/.env.example", 500); } // `state` defends against CSRF: GitHub echoes it back and we compare. const state = crypto.randomBytes(16).toString("hex"); setCookie(c, "oauth_state", state, { httpOnly: true, sameSite: "Lax", path: "/", maxAge: 600, }); const url = new URL("https://github.com/login/oauth/authorize"); url.searchParams.set("client_id", clientId); url.searchParams.set("redirect_uri", `${APP_URL}/auth/github/callback`); url.searchParams.set("state", state); // No scopes requested — public profile is all we need. return c.redirect(url.toString()); }); auth.get("/github/callback", async (c) => { const code = c.req.query("code"); const state = c.req.query("state"); const expectedState = getCookie(c, "oauth_state"); deleteCookie(c, "oauth_state", { path: "/" }); if (!code || !state || state !== expectedState) { return c.text("OAuth state mismatch — try signing in again", 400); } const tokenRes = await fetch("https://github.com/login/oauth/access_token", { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json" }, body: JSON.stringify({ client_id: process.env.GITHUB_CLIENT_ID, client_secret: process.env.GITHUB_CLIENT_SECRET, code, }), }); const tokenData = (await tokenRes.json()) as { access_token?: string }; if (!tokenData.access_token) { return c.text("GitHub token exchange failed", 502); } const userRes = await fetch("https://api.github.com/user", { headers: { Authorization: `Bearer ${tokenData.access_token}`, Accept: "application/vnd.github+json", "User-Agent": "spool", }, }); const ghUser = (await userRes.json()) as { id: number; login: string; avatar_url: string | null; }; const [user] = await db .insert(users) .values({ githubId: ghUser.id, username: ghUser.login, avatarUrl: ghUser.avatar_url, }) .onConflictDoUpdate({ target: users.githubId, set: { username: ghUser.login, avatarUrl: ghUser.avatar_url }, }) .returning(); await createSession(c, user.id); return c.redirect(APP_URL); }); auth.post("/logout", async (c) => { await destroySession(c); return c.json({ ok: true }); }); export default auth;