import { Hono } from "hono"; import { getOAuthURL, handleOAuthCallback } from "./github-oauth"; import { removeToken, saveDiscordLink } from "./token-store"; import { createAdminSession, adminCookie } from "./admin-session"; import { loadGroups, resolveScope, hasAnyAccess } from "./groups"; import type { Env } from "./types"; interface PendingState { redirectTo: string; expiresAt: number; discordUserId?: string; } function linkedPage(login: string): string { return `绑定成功
✓

GitHub 账号已绑定

已连接为 @${login},现在可以回到 Discord 用 GitHub 评论了。

`; } function generateRandomHex(length: number): string { const bytes = new Uint8Array(length); crypto.getRandomValues(bytes); return Array.from(bytes) .map((b) => b.toString(16).padStart(2, "0")) .join(""); } function safeRedirectPath(value: string | undefined): string { if (!value) return "/"; if (!value.startsWith("/")) return "/"; if (value.startsWith("//")) return "/"; if (/^\/\\/.test(value)) return "/"; return value; } export function createOAuthRoutes(): Hono<{ Bindings: Env }> { const app = new Hono<{ Bindings: Env }>(); app.get("/github", async (c) => { const redirectTo = safeRedirectPath(c.req.query("redirect")); const state = generateRandomHex(16); const pending: PendingState = { redirectTo, expiresAt: Date.now() + 10 * 60 * 1000, }; await c.env.KV.put(`state:${state}`, JSON.stringify(pending), { expirationTtl: 600, }); const url = getOAuthURL(c.env.GITHUB_CLIENT_ID ?? "", state); return c.redirect(url); }); app.get("/github/callback", async (c) => { const code = c.req.query("code"); const state = c.req.query("state"); if (!code || !state) { return c.json({ error: "Missing code or state" }, 400); } const raw = await c.env.KV.get(`state:${state}`, "json"); if (!raw) { return c.json({ error: "Invalid or expired state" }, 400); } const pending = raw as PendingState; if (Date.now() > pending.expiresAt) { await c.env.KV.delete(`state:${state}`); return c.json({ error: "Invalid or expired state" }, 400); } await c.env.KV.delete(`state:${state}`); const result = await handleOAuthCallback( c.env.GITHUB_CLIENT_ID ?? "", c.env.GITHUB_CLIENT_SECRET ?? "", code, state, c.env.KV, ); if (!result) { return c.json({ error: "OAuth failed" }, 400); } // Discord account-linking flow: bind the Discord user to this GitHub account. if (pending.discordUserId) { await saveDiscordLink(c.env.KV, pending.discordUserId, result.userId); const isBrowserLink = (c.req.header("accept") ?? "").includes("text/html"); if (isBrowserLink) { return c.html(linkedPage(result.login)); } return c.json({ ok: true, discordUserId: pending.discordUserId, login: result.login }); } const isBrowser = (c.req.header("accept") ?? "").includes("text/html"); if (isBrowser) { const groups = await loadGroups(c.env.KV); const scope = resolveScope(c.env, groups, result.userId, result.login); if (!hasAnyAccess(scope)) { return c.redirect("/admin?error=forbidden"); } const sessionId = await createAdminSession(c.env.KV, result.userId, result.login); c.header("Set-Cookie", adminCookie(sessionId)); return c.redirect(pending.redirectTo); } return c.json({ userId: result.userId, login: result.login, redirectTo: pending.redirectTo, }); }); app.delete("/token/:userId", async (c) => { await removeToken(c.env.KV, c.req.param("userId")); return c.json({ ok: true }); }); return app; }