refactor: modularize into core/events/formatters/drivers

This commit is contained in:
RhenCloud committed 2026-08-03 03:36:36 +08:00
1 parent 7b341ff9f4
commit 0af6b9a4b8
62 files changed
+2430 -2015

No files matched your search

+187
View File
@@ -0,0 +1,187 @@
import { Hono } from "hono";
import { getUserOctokit } from "../github/oauth";
import { findUserIdByToken } from "../github/store";
import type { Env } from "../types";
import { log } from "../lib/log";
function extractBearerToken(c: {
req: { header: (name: string) => string | undefined };
}): string | null {
const auth = c.req.header("authorization");
if (!auth?.startsWith("Bearer ")) return null;
return auth.slice(7);
}
function isNonEmptyString(value: unknown): value is string {
return typeof value === "string" && value.length > 0;
}
function isValidId(value: unknown): value is number {
return typeof value === "number" && Number.isFinite(value) && value > 0;
}
async function readJson(c: {
req: { json: <T>() => Promise<T> };
}): Promise<Record<string, unknown> | null> {
try {
return (await c.req.json()) as Record<string, unknown>;
} catch {
return null;
}
}
export function createActionRoutes(): Hono<{ Bindings: Env }> {
const app = new Hono<{ Bindings: Env }>();
app.post("/api/comment", async (c) => {
const token = extractBearerToken(c);
if (!token) return c.json({ error: "Missing authorization" }, 401);
const userId = await findUserIdByToken(c.env.KV, token);
if (!userId) return c.json({ error: "Invalid or expired token" }, 401);
const body = await readJson(c);
if (
!body ||
!isNonEmptyString(body.owner) ||
!isNonEmptyString(body.repo) ||
!isValidId(body.issueNumber) ||
!isNonEmptyString(body.body)
) {
return c.json({ error: "Invalid request body" }, 400);
}
const octokit = await getUserOctokit(userId, c.env.KV);
if (!octokit) return c.json({ error: "Not authorized" }, 401);
try {
await octokit.rest.issues.createComment({
owner: body.owner,
repo: body.repo,
issue_number: body.issueNumber,
body: body.body,
});
} catch (err) {
log.error({ err }, "Failed to create comment");
return c.json({ error: "GitHub API error" }, 500);
}
return c.json({ ok: true });
});
app.post("/api/merge", async (c) => {
const token = extractBearerToken(c);
if (!token) return c.json({ error: "Missing authorization" }, 401);
const userId = await findUserIdByToken(c.env.KV, token);
if (!userId) return c.json({ error: "Invalid or expired token" }, 401);
const body = await readJson(c);
if (
!body ||
!isNonEmptyString(body.owner) ||
!isNonEmptyString(body.repo) ||
!isValidId(body.pullNumber)
) {
return c.json({ error: "Invalid request body" }, 400);
}
const method = body.method === undefined ? "squash" : body.method;
if (method !== "merge" && method !== "squash" && method !== "rebase") {
return c.json({ error: "Invalid request body" }, 400);
}
const octokit = await getUserOctokit(userId, c.env.KV);
if (!octokit) return c.json({ error: "Not authorized" }, 401);
try {
await octokit.rest.pulls.merge({
owner: body.owner,
repo: body.repo,
pull_number: body.pullNumber,
merge_method: method,
});
} catch (err) {
log.error({ err }, "Failed to merge pull request");
return c.json({ error: "GitHub API error" }, 500);
}
return c.json({ ok: true });
});
app.post("/api/close", async (c) => {
const token = extractBearerToken(c);
if (!token) return c.json({ error: "Missing authorization" }, 401);
const userId = await findUserIdByToken(c.env.KV, token);
if (!userId) return c.json({ error: "Invalid or expired token" }, 401);
const body = await readJson(c);
if (
!body ||
!isNonEmptyString(body.owner) ||
!isNonEmptyString(body.repo) ||
!isValidId(body.pullNumber)
) {
return c.json({ error: "Invalid request body" }, 400);
}
const octokit = await getUserOctokit(userId, c.env.KV);
if (!octokit) return c.json({ error: "Not authorized" }, 401);
try {
await octokit.rest.pulls.update({
owner: body.owner,
repo: body.repo,
pull_number: body.pullNumber,
state: "closed",
});
} catch (err) {
log.error({ err }, "Failed to close pull request");
return c.json({ error: "GitHub API error" }, 500);
}
return c.json({ ok: true });
});
app.post("/api/react", async (c) => {
const token = extractBearerToken(c);
if (!token) return c.json({ error: "Missing authorization" }, 401);
const userId = await findUserIdByToken(c.env.KV, token);
if (!userId) return c.json({ error: "Invalid or expired token" }, 401);
const body = await readJson(c);
const reactions = [
"+1",
"-1",
"laugh",
"confused",
"heart",
"hooray",
"rocket",
"eyes",
] as const;
if (
!body ||
!isNonEmptyString(body.owner) ||
!isNonEmptyString(body.repo) ||
!isValidId(body.issueNumber) ||
!isNonEmptyString(body.reaction) ||
!(reactions as readonly string[]).includes(body.reaction)
) {
return c.json({ error: "Invalid request body" }, 400);
}
const octokit = await getUserOctokit(userId, c.env.KV);
if (!octokit) return c.json({ error: "Not authorized" }, 401);
try {
await octokit.rest.reactions.createForIssue({
owner: body.owner,
repo: body.repo,
issue_number: body.issueNumber,
content: body.reaction as
"+1" | "-1" | "laugh" | "confused" | "heart" | "hooray" | "rocket" | "eyes",
});
} catch (err) {
log.error({ err }, "Failed to create reaction");
return c.json({ error: "GitHub API error" }, 500);
}
return c.json({ ok: true });
});
return app;
}
+373
View File
@@ -0,0 +1,373 @@
import { Hono } from "hono";
import type { Env, Route, Group } from "../types";
import { loadRoutes, saveRoutes } from "../config";
import {
getAdminSession,
destroyAdminSession,
clearAdminCookie,
type AdminSession,
} from "./session";
import { loadGroups, saveGroups, resolveScope, hasAnyAccess, type AccessScope } from "./groups";
import { getSendLog } from "../lib/send-log";
import { log } from "../lib/log";
const VALID_FILTER_TYPES = new Set(["event", "repo", "actor", "action", "branch", "keyword"]);
const ID_RE = /^[a-z0-9][a-z0-9-]*$/;
function isValidMatch(match: unknown): match is string | string[] {
if (typeof match === "string") return match.trim().length > 0;
if (Array.isArray(match))
return match.length > 0 && match.every((m) => typeof m === "string" && m.trim().length > 0);
return false;
}
function deepEqual(a: unknown, b: unknown): boolean {
if (a === b) return true;
if (typeof a !== typeof b || a === null || b === null) return false;
if (Array.isArray(a) || Array.isArray(b)) {
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
return a.every((x, i) => deepEqual(x, b[i]));
}
if (typeof a === "object" && typeof b === "object") {
const ao = a as Record<string, unknown>;
const bo = b as Record<string, unknown>;
const ak = Object.keys(ao);
const bk = Object.keys(bo);
if (ak.length !== bk.length) return false;
return ak.every((k) => Object.prototype.hasOwnProperty.call(bo, k) && deepEqual(ao[k], bo[k]));
}
return false;
}
/**
* Validates the submitted routes. Routes that are byte-for-byte identical to an
* entry in `unchanged` (keyed by id) skip the full content check, so a pre-existing
* incomplete route can never block edits to a different route. Only new or modified
* routes are fully validated. Structural checks (id shape, uniqueness) still run for all.
*/
function validateRoutes(
routes: unknown,
unchanged?: Map<string, Route>,
): { ok: true; routes: Route[] } | { ok: false; error: string } {
if (!Array.isArray(routes)) return { ok: false, error: "routes must be an array" };
if (routes.length > 200) return { ok: false, error: "too many routes" };
const seen = new Set<string>();
for (let i = 0; i < routes.length; i++) {
const r = routes[i] as Record<string, unknown>;
if (!r || typeof r !== "object") return { ok: false, error: `route[${i}] is not an object` };
if (typeof r.id !== "string" || !ID_RE.test(r.id)) {
return { ok: false, error: `route[${i}].id is invalid` };
}
if (seen.has(r.id)) return { ok: false, error: `duplicate route id "${r.id}"` };
seen.add(r.id);
// Skip full validation for routes that are unchanged from what is stored.
const prev = unchanged?.get(r.id);
if (prev && deepEqual(r, prev)) continue;
if (typeof r.name !== "string" || r.name.trim().length === 0) {
return { ok: false, error: `route "${r.id}" needs a name` };
}
if (typeof r.groupId !== "string" || r.groupId.trim().length === 0) {
return { ok: false, error: `route "${r.id}" needs a group` };
}
if (typeof r.enabled !== "boolean")
return { ok: false, error: `route "${r.id}".enabled must be boolean` };
if (r.lang !== undefined && typeof r.lang !== "string") {
return { ok: false, error: `route "${r.id}".lang must be a string` };
}
if (r.fallback !== undefined && typeof r.fallback !== "boolean") {
return { ok: false, error: `route "${r.id}".fallback must be a boolean` };
}
if (!Array.isArray(r.filters)) {
return { ok: false, error: `route "${r.id}".filters must be an array` };
}
if (r.fallback !== true && r.filters.length === 0) {
return { ok: false, error: `route "${r.id}" needs at least one filter` };
}
for (let j = 0; j < r.filters.length; j++) {
const f = r.filters[j] as Record<string, unknown>;
if (!f || typeof f !== "object")
return { ok: false, error: `route "${r.id}" filter[${j}] invalid` };
if (!VALID_FILTER_TYPES.has(f.type as string)) {
return { ok: false, error: `route "${r.id}" filter[${j}] has unknown type` };
}
if (!isValidMatch(f.match)) {
return { ok: false, error: `route "${r.id}" filter[${j}] needs a match value` };
}
if (f.exclude !== undefined && typeof f.exclude !== "boolean") {
return { ok: false, error: `route "${r.id}" filter[${j}].exclude must be boolean` };
}
}
const target = r.target as Record<string, unknown> | undefined;
if (!target || typeof target !== "object")
return { ok: false, error: `route "${r.id}" needs a target` };
if (typeof target.channelId !== "string" || target.channelId.trim().length === 0)
return { ok: false, error: `route "${r.id}".target.channelId is required` };
if (target.threadId !== undefined && typeof target.threadId !== "string") {
return { ok: false, error: `route "${r.id}".target.threadId must be a string` };
}
}
return { ok: true, routes: routes as Route[] };
}
function validateGroups(
groups: unknown,
): { ok: true; groups: Group[] } | { ok: false; error: string } {
if (!Array.isArray(groups)) return { ok: false, error: "groups must be an array" };
if (groups.length > 100) return { ok: false, error: "too many groups" };
const seen = new Set<string>();
for (let i = 0; i < groups.length; i++) {
const g = groups[i] as Record<string, unknown>;
if (!g || typeof g !== "object") return { ok: false, error: `group[${i}] is not an object` };
if (typeof g.id !== "string" || !ID_RE.test(g.id)) {
return { ok: false, error: `group[${i}].id is invalid` };
}
if (seen.has(g.id)) return { ok: false, error: `duplicate group id "${g.id}"` };
seen.add(g.id);
if (typeof g.name !== "string" || g.name.trim().length === 0) {
return { ok: false, error: `group "${g.id}" needs a name` };
}
if (
!Array.isArray(g.adminIds) ||
!g.adminIds.every((a) => typeof a === "string" && a.trim().length > 0)
) {
return { ok: false, error: `group "${g.id}".adminIds must be a list of strings` };
}
if (
g.owners !== undefined &&
(!Array.isArray(g.owners) ||
!g.owners.every((o) => typeof o === "string" && o.trim().length > 0))
) {
return { ok: false, error: `group "${g.id}".owners must be a list of strings` };
}
if (g.emoji !== undefined && typeof g.emoji !== "boolean") {
return { ok: false, error: `group "${g.id}".emoji must be a boolean` };
}
}
return { ok: true, groups: groups as Group[] };
}
export function createAdminRoutes(): Hono<{ Bindings: Env }> {
const app = new Hono<{ Bindings: Env }>();
async function loadScope(c: {
env: Env;
req: { header: (name: string) => string | undefined };
}): Promise<{ session: AdminSession; scope: AccessScope; groups: Group[] } | null> {
const session = await getAdminSession(c.env.KV, c.req.header("cookie"));
if (!session) return null;
const groups = await loadGroups(c.env.KV);
const scope = resolveScope(c.env, groups, session.userId, session.login);
if (!hasAnyAccess(scope)) return null;
return { session, scope, groups };
}
app.get("/login", (c) => {
return c.redirect("/auth/github?redirect=/admin");
});
app.get("/logout", async (c) => {
await destroyAdminSession(c.env.KV, c.req.header("cookie"));
c.header("Set-Cookie", clearAdminCookie());
return c.redirect("/admin");
});
app.get("/api/me", async (c) => {
const s = await loadScope(c);
if (!s) return c.json({ error: "Unauthorized" }, 401);
return c.json({
login: s.session.login,
userId: s.session.userId,
isSuper: s.scope.isSuper,
groups: s.scope.groups,
});
});
app.get("/api/groups", async (c) => {
const s = await loadScope(c);
if (!s) return c.json({ error: "Unauthorized" }, 401);
return c.json({ groups: s.scope.groups, isSuper: s.scope.isSuper });
});
app.put("/api/groups", async (c) => {
const s = await loadScope(c);
if (!s) return c.json({ error: "Unauthorized" }, 401);
if (!s.scope.isSuper) return c.json({ error: "Forbidden" }, 403);
let body: unknown;
try {
body = await c.req.json();
} catch {
return c.json({ error: "Invalid JSON body" }, 400);
}
const result = validateGroups((body as { groups?: unknown })?.groups);
if (!result.ok) return c.json({ error: result.error }, 400);
try {
await saveGroups(c.env.KV, result.groups);
} catch (err) {
log.error({ err }, "Failed to save groups");
return c.json({ error: "Failed to save groups" }, 500);
}
log.info({ count: result.groups.length }, "Groups updated via admin UI");
return c.json({ ok: true, count: result.groups.length });
});
app.get("/api/routes", async (c) => {
const s = await loadScope(c);
if (!s) return c.json({ error: "Unauthorized" }, 401);
const all = await loadRoutes(c.env.KV);
const routes = s.scope.isSuper
? all
: all.filter((r) => r.groupId != null && s.scope.groupIds.has(r.groupId));
return c.json({ routes });
});
app.get("/api/logs", async (c) => {
const s = await loadScope(c);
if (!s) return c.json({ error: "Unauthorized" }, 401);
const limit = Math.min(Math.max(Number(c.req.query("limit") ?? 50), 1), 100);
if (s.scope.isSuper) {
return c.json({ logs: await getSendLog(c.env.KV, limit) });
}
const all = await loadRoutes(c.env.KV);
const allowed = new Set(
all.filter((r) => r.groupId != null && s.scope.groupIds.has(r.groupId)).map((r) => r.id),
);
const logs = (await getSendLog(c.env.KV, 200))
.filter((l) => allowed.has(l.routeId))
.slice(0, limit);
return c.json({ logs });
});
app.put("/api/routes", async (c) => {
const s = await loadScope(c);
if (!s) return c.json({ error: "Unauthorized" }, 401);
let body: unknown;
try {
body = await c.req.json();
} catch {
return c.json({ error: "Invalid JSON body" }, 400);
}
const existing = await loadRoutes(c.env.KV);
const unchanged = new Map(existing.map((r) => [r.id, r]));
const result = validateRoutes((body as { routes?: unknown })?.routes, unchanged);
if (!result.ok) return c.json({ error: result.error }, 400);
let nextAll: Route[];
if (s.scope.isSuper) {
// Super admins see and submit every route: full replace.
nextAll = result.routes;
} else {
// Group admins may only write routes inside their own groups. Reject any
// submitted route that targets a group they do not manage, then splice
// their groups' routes in place while preserving all other groups' routes.
const writable = s.scope.groupIds;
for (const r of result.routes) {
if (!r.groupId || !writable.has(r.groupId)) {
return c.json({ error: `route "${r.id}" is outside your groups` }, 403);
}
}
nextAll = [
...existing.filter((r) => !(r.groupId != null && writable.has(r.groupId))),
...result.routes,
];
}
// Guard against duplicate ids across the merged set.
const ids = new Set<string>();
for (const r of nextAll) {
if (ids.has(r.id)) return c.json({ error: `duplicate route id "${r.id}"` }, 400);
ids.add(r.id);
}
try {
await saveRoutes(c.env.KV, nextAll);
} catch (err) {
log.error({ err }, "Failed to save routes");
return c.json({ error: "Failed to save routes" }, 500);
}
log.info({ count: nextAll.length }, "Routes updated via admin UI");
return c.json({ ok: true, count: nextAll.length });
});
// Routes scoped to a single group. The group is the container: the console
// enters a group and then lists / edits only that group's routes.
function groupAccess(
s: { scope: AccessScope; groups: Group[] },
groupId: string,
): { ok: true; group: Group } | { ok: false; status: 403 | 404 } {
const group = s.groups.find((g) => g.id === groupId);
if (!group) return { ok: false, status: 404 };
if (!s.scope.isSuper && !s.scope.groupIds.has(groupId)) return { ok: false, status: 403 };
return { ok: true, group };
}
app.get("/api/groups/:groupId/routes", async (c) => {
const s = await loadScope(c);
if (!s) return c.json({ error: "Unauthorized" }, 401);
const groupId = c.req.param("groupId");
const access = groupAccess(s, groupId);
if (!access.ok) {
return c.json(
{ error: access.status === 404 ? "Group not found" : "Forbidden" },
access.status,
);
}
const all = await loadRoutes(c.env.KV);
return c.json({ group: access.group, routes: all.filter((r) => r.groupId === groupId) });
});
app.put("/api/groups/:groupId/routes", async (c) => {
const s = await loadScope(c);
if (!s) return c.json({ error: "Unauthorized" }, 401);
const groupId = c.req.param("groupId");
const access = groupAccess(s, groupId);
if (!access.ok) {
return c.json(
{ error: access.status === 404 ? "Group not found" : "Forbidden" },
access.status,
);
}
let body: unknown;
try {
body = await c.req.json();
} catch {
return c.json({ error: "Invalid JSON body" }, 400);
}
// Force every submitted route into this group so the client never has to
// carry a groupId; the path parameter is the single source of truth.
const submitted = (body as { routes?: unknown })?.routes;
const scoped = Array.isArray(submitted)
? submitted.map((r) => ({ ...(r as Record<string, unknown>), groupId }))
: submitted;
const existing = await loadRoutes(c.env.KV);
const unchanged = new Map(existing.map((r) => [r.id, r]));
const result = validateRoutes(scoped, unchanged);
if (!result.ok) return c.json({ error: result.error }, 400);
// Replace only this group's routes; every other group is preserved untouched.
const others = existing.filter((r) => r.groupId !== groupId);
const nextAll = [...others, ...result.routes];
// Guard against ids colliding with routes in other groups.
const ids = new Set<string>();
for (const r of nextAll) {
if (ids.has(r.id)) return c.json({ error: `duplicate route id "${r.id}"` }, 400);
ids.add(r.id);
}
try {
await saveRoutes(c.env.KV, nextAll);
} catch (err) {
log.error({ err }, "Failed to save routes");
return c.json({ error: "Failed to save routes" }, 500);
}
log.info({ groupId, count: result.routes.length }, "Group routes updated via admin UI");
return c.json({ ok: true, count: result.routes.length });
});
return app;
}
+69
View File
@@ -0,0 +1,69 @@
import type { Env, Group } from "../types";
import { isAdminUser } from "./session";
import { log } from "../lib/log";
const GROUPS_KEY = "config:groups";
export async function loadGroups(kv: KVNamespace): Promise<Group[]> {
try {
const stored = await kv.get<Group[]>(GROUPS_KEY, "json");
if (Array.isArray(stored)) return stored;
} catch (err) {
log.warn({ err }, "Failed to load groups from KV");
}
return [];
}
export async function saveGroups(kv: KVNamespace, groups: Group[]): Promise<void> {
await kv.put(GROUPS_KEY, JSON.stringify(groups));
}
/** Case-insensitive match of a GitHub userId or login against a list of ids/logins. */
export function identityMatches(ids: string[], userId: string, login: string): boolean {
const wanted = ids.map((s) => s.trim()).filter(Boolean);
if (wanted.length === 0) return false;
return wanted.some((id) => id === userId || id.toLowerCase() === login.toLowerCase());
}
export function isGroupAdmin(group: Group, userId: string, login: string): boolean {
return identityMatches(group.adminIds ?? [], userId, login);
}
/**
* Whether an event originating from `owners` (org/user logins) is allowed into
* this group. A group with no owner restriction accepts everything.
*/
export function groupAcceptsOwners(group: Group, owners: string[]): boolean {
const restrict = (group.owners ?? []).map((s) => s.trim().toLowerCase()).filter(Boolean);
if (restrict.length === 0) return true;
const seen = owners.map((s) => s.trim().toLowerCase()).filter(Boolean);
return seen.some((o) => restrict.includes(o));
}
export interface AccessScope {
isSuper: boolean;
/** Groups the user may view/edit. When isSuper, this is every group. */
groups: Group[];
/** Ids of accessible groups, for quick membership checks. */
groupIds: Set<string>;
}
export function resolveScope(
env: Env,
groups: Group[],
userId: string,
login: string,
): AccessScope {
const isSuper = isAdminUser(env, userId, login);
const visible = isSuper ? groups : groups.filter((g) => isGroupAdmin(g, userId, login));
return {
isSuper,
groups: visible,
groupIds: new Set(visible.map((g) => g.id)),
};
}
/** True if the user is a super admin or manages at least one group. */
export function hasAnyAccess(scope: AccessScope): boolean {
return scope.isSuper || scope.groups.length > 0;
}
+193
View File
@@ -0,0 +1,193 @@
import { Hono } from "hono";
import type { Env } from "../types";
type Lang = "zh" | "en";
const DEFAULT_REPO = "https://github.com/ReCloudStudio/WebHooker";
const DEFAULT_DOCS = "https://webhooker.docs.worldexecute.me";
function pickLang(raw: string | undefined): Lang {
return raw === "en" ? "en" : "zh";
}
interface LinkItem {
href: string;
label: string;
desc: string;
icon: string;
external: boolean;
primary?: boolean;
}
function icon(name: string): string {
const paths: Record<string, string> = {
docs: '<path d="M4 4a2 2 0 0 1 2-2h7l5 5v13a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V4z"/><path d="M13 2v5h5"/><path d="M8 12h8M8 16h6"/>',
github:
'<path d="M12 2a10 10 0 0 0-3.16 19.49c.5.09.68-.22.68-.48v-1.7c-2.78.6-3.37-1.34-3.37-1.34-.45-1.16-1.11-1.47-1.11-1.47-.91-.62.07-.6.07-.6 1 .07 1.53 1.03 1.53 1.03.9 1.53 2.36 1.09 2.94.83.09-.65.35-1.09.63-1.34-2.22-.25-4.55-1.11-4.55-4.94 0-1.09.39-1.98 1.03-2.68-.1-.25-.45-1.27.1-2.65 0 0 .84-.27 2.75 1.02a9.5 9.5 0 0 1 5 0c1.91-1.29 2.75-1.02 2.75-1.02.55 1.38.2 2.4.1 2.65.64.7 1.03 1.59 1.03 2.68 0 3.84-2.34 4.68-4.57 4.93.36.31.68.92.68 1.85v2.74c0 .27.18.58.69.48A10 10 0 0 0 12 2z"/>',
terms:
'<path d="M9 12h6M9 16h6M9 8h2"/><path d="M6 2h9l5 5v13a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2z"/>',
privacy:
'<path d="M12 2l7 3v6c0 5-3.5 8.5-7 10-3.5-1.5-7-5-7-10V5l7-3z"/><path d="M9 12l2 2 4-4"/>',
login:
'<path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/><path d="M10 17l5-5-5-5"/><path d="M15 12H3"/>',
};
return `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" width="22" height="22">${paths[name] ?? ""}</svg>`;
}
function layout(lang: Lang, repo: string, docsBase: string): string {
const t = (zh: string, en: string): string => (lang === "zh" ? zh : en);
const q = (p: string): string => `${p}?lang=${lang}`;
const altLang: Lang = lang === "zh" ? "en" : "zh";
const docs = lang === "zh" ? `${docsBase}/zh` : `${docsBase}/`;
const items: LinkItem[] = [
{
href: docs,
label: t("文档", "Documentation"),
desc: t("部署、配置与事件参考", "Deployment, configuration & event reference"),
icon: "docs",
external: true,
},
{
href: repo,
label: t("GitHub 仓库", "GitHub Repository"),
desc: t("源代码、问题与发布", "Source code, issues & releases"),
icon: "github",
external: true,
},
{
href: q("/terms"),
label: t("服务条款", "Terms of Service"),
desc: t("使用本服务的条款", "The terms for using this service"),
icon: "terms",
external: false,
},
{
href: q("/privacy"),
label: t("隐私政策", "Privacy Policy"),
desc: t("我们如何处理你的数据", "How we handle your data"),
icon: "privacy",
external: false,
},
{
href: "/admin/login",
label: t("登录控制台", "Sign in to Console"),
desc: t("管理路由与分组", "Manage routes and groups"),
icon: "login",
external: false,
primary: true,
},
];
const cards = items
.map((it) => {
const attrs = it.external ? ' target="_blank" rel="noopener noreferrer"' : "";
return `<a class="tile${it.primary ? " tile-primary" : ""}" href="${it.href}"${attrs}>
<span class="tile-icon">${icon(it.icon)}</span>
<span class="tile-body">
<span class="tile-label">${it.label}</span>
<span class="tile-desc">${it.desc}</span>
</span>
<span class="tile-arrow">${it.external ? "↗" : "→"}</span>
</a>`;
})
.join("\n");
return `<!doctype html>
<html lang="${lang === "zh" ? "zh-CN" : "en"}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="robots" content="index,follow">
<title>WebHooker</title>
<meta name="description" content="${t("GitHub webhook 转发到 Discord", "GitHub webhooks forwarded to Discord")}">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&display=swap">
<style>
:root{
--bg:#f6f7f9;--surface:#fff;--surface-2:#f3f4f6;--border:#e6e8ec;--border-strong:#d4d8de;
--text:#0f172a;--muted:#5b6472;--faint:#9aa3b2;--accent:#4f46e5;--accent-strong:#4338ca;
--accent-dim:#eef2ff;--accent-text:#3730a3;--shadow:0 1px 3px rgba(15,23,42,.06);
--dot:rgba(15,23,42,.05);
}
@media (prefers-color-scheme:dark){
:root{
--bg:#0b0f17;--surface:#141a24;--surface-2:#1b2330;--border:#232c3a;--border-strong:#33405280;
--text:#e7ecf3;--muted:#9aa6b6;--faint:#6b7686;--accent:#818cf8;--accent-strong:#a5b4fc;
--accent-dim:#1e2537;--accent-text:#c7d2fe;--shadow:0 1px 3px rgba(0,0,0,.4);
--dot:rgba(255,255,255,.05);
}
}
*{box-sizing:border-box}
body{margin:0;min-height:100vh;background:var(--bg);color:var(--text);
font-family:'Plus Jakarta Sans',system-ui,-apple-system,'Segoe UI',sans-serif;
-webkit-font-smoothing:antialiased;position:relative}
body::before{content:"";position:fixed;inset:0;z-index:0;pointer-events:none;
background-image:radial-gradient(var(--dot) 1px,transparent 1px);background-size:22px 22px}
.wrap{position:relative;z-index:1;max-width:720px;margin:0 auto;
padding:72px 20px 64px;display:flex;flex-direction:column;min-height:100vh}
.hero{text-align:center;margin-bottom:40px}
.mark{display:inline-flex;align-items:center;justify-content:center;width:56px;height:56px;
border-radius:16px;background:var(--accent);color:#fff;font-weight:800;font-size:20px;
letter-spacing:-.02em;margin-bottom:20px;box-shadow:0 8px 24px -8px var(--accent)}
h1{font-size:34px;margin:0 0 10px;letter-spacing:-.03em;font-weight:800}
h1 span{color:var(--accent)}
.sub{color:var(--muted);font-size:15px;margin:0;line-height:1.6}
.grid{display:grid;gap:12px}
.tile{display:flex;align-items:center;gap:16px;text-decoration:none;
background:var(--surface);border:1px solid var(--border);border-radius:14px;
padding:18px 20px;color:var(--text);transition:transform .15s ease,border-color .15s ease,box-shadow .15s ease;
box-shadow:var(--shadow)}
.tile:hover{transform:translateY(-2px);border-color:var(--border-strong);box-shadow:0 8px 24px -12px rgba(15,23,42,.25)}
.tile-icon{display:flex;align-items:center;justify-content:center;width:44px;height:44px;flex:none;
border-radius:11px;background:var(--surface-2);color:var(--accent)}
.tile-body{display:flex;flex-direction:column;gap:2px;flex:1;min-width:0}
.tile-label{font-weight:700;font-size:15px}
.tile-desc{color:var(--muted);font-size:13px}
.tile-arrow{color:var(--faint);font-size:18px;flex:none}
.tile-primary{background:var(--accent);border-color:var(--accent)}
.tile-primary .tile-label,.tile-primary .tile-desc,.tile-primary .tile-arrow{color:#fff}
.tile-primary .tile-desc{color:rgba(255,255,255,.82)}
.tile-primary .tile-icon{background:rgba(255,255,255,.16);color:#fff}
.tile-primary:hover{box-shadow:0 12px 28px -10px var(--accent)}
footer{margin-top:auto;padding-top:40px;display:flex;justify-content:space-between;
align-items:center;gap:12px;flex-wrap:wrap}
.muted{color:var(--muted);font-size:13px}
.langlink{font-size:13px;text-decoration:none;color:var(--muted);
border:1px solid var(--border);border-radius:999px;padding:6px 14px;background:var(--surface)}
.langlink:hover{color:var(--text);border-color:var(--border-strong)}
</style>
</head>
<body>
<div class="wrap">
<div class="hero">
<div class="mark">WH</div>
<h1>Web<span>Hooker</span></h1>
<p class="sub">${t(
"将 GitHub webhook 事件转发到 Discord 频道,并支持在 Discord 中以你本人身份操作 GitHub。",
"Forward GitHub webhook events to Discord, and act on GitHub from Discord as yourself.",
)}</p>
</div>
<nav class="grid">
${cards}
</nav>
<footer>
<span class="muted">WebHooker · GitHub → Discord</span>
<a class="langlink" href="/?lang=${altLang}">${t("English", "中文")}</a>
</footer>
</div>
</body>
</html>`;
}
export function createHomeRoutes(): Hono<{ Bindings: Env }> {
const app = new Hono<{ Bindings: Env }>();
app.get("/", (c) => {
const lang = pickLang(c.req.query("lang"));
const repo = c.env.GITHUB_REPO_URL ?? DEFAULT_REPO;
const docsBase = (c.env.DOCS_URL ?? DEFAULT_DOCS).replace(/\/+$/, "");
return c.html(layout(lang, repo, docsBase));
});
return app;
}
+248
View File
@@ -0,0 +1,248 @@
import { Hono } from "hono";
import type { Env } from "../types";
type Lang = "zh" | "en";
const CONTACT_FALLBACK = "the repository maintainer (open an issue on the project repository)";
const CONTACT_FALLBACK_ZH = "项目维护者(在项目仓库提交 issue)";
function pickLang(raw: string | undefined): Lang {
return raw === "en" ? "en" : "zh";
}
function layout(opts: {
lang: Lang;
active: "terms" | "privacy";
title: string;
updated: string;
body: string;
}): string {
const { lang, active, title, updated, body } = opts;
const altLang: Lang = lang === "zh" ? "en" : "zh";
const t = (zh: string, en: string): string => (lang === "zh" ? zh : en);
const q = (p: string): string => `${p}?lang=${lang}`;
const langLabel = t("English", "中文");
return `<!doctype html>
<html lang="${lang === "zh" ? "zh-CN" : "en"}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="robots" content="index,follow">
<title>${title} · WebHooker</title>
<style>
:root{--bg:#f6f7f9;--surface:#fff;--border:#e5e7eb;--text:#1f2328;--muted:#57606a;--accent:#4f46e5;--body-text:#30363d;--code-bg:#f0f1f3;--accent-dim:#eef2ff;--accent-border:#e0e7ff;--shadow:rgba(0,0,0,.05)}
@media (prefers-color-scheme:dark){:root{--bg:#0b0f17;--surface:#131a24;--border:#273143;--text:#e6e9ef;--muted:#9aa6b8;--accent:#818cf8;--body-text:#c3cad6;--code-bg:#1a2230;--accent-dim:#1c2140;--accent-border:#2f3766;--shadow:rgba(0,0,0,.5);color-scheme:dark}}
*{box-sizing:border-box}
body{margin:0;background:var(--bg);color:var(--text);font-family:'Plus Jakarta Sans',system-ui,-apple-system,'Segoe UI',sans-serif;line-height:1.7;-webkit-font-smoothing:antialiased}
.wrap{max-width:760px;margin:0 auto;padding:48px 20px 80px}
header{display:flex;align-items:center;justify-content:space-between;gap:16px;margin-bottom:28px;flex-wrap:wrap}
.brand{font-weight:800;font-size:16px;letter-spacing:-.01em;text-decoration:none;color:var(--text)}
.brand span{color:var(--accent)}
.tabs{display:flex;gap:8px}
.tab{font-size:13px;text-decoration:none;color:var(--muted);padding:6px 14px;border-radius:999px;border:1px solid transparent}
.tab.active{color:var(--accent);background:var(--accent-dim);border-color:var(--accent-border)}
.tab:hover{color:var(--text)}
.card{background:var(--surface);border:1px solid var(--border);border-radius:12px;padding:36px 40px;box-shadow:0 1px 3px var(--shadow)}
h1{font-size:26px;margin:0 0 6px;letter-spacing:-.02em}
.updated{color:var(--muted);font-size:13px;margin:0 0 24px}
h2{font-size:17px;margin:28px 0 8px}
p,li{color:var(--body-text);font-size:15px}
a{color:var(--accent)}
ul{padding-left:20px}
code{background:var(--code-bg);border:1px solid var(--border);border-radius:6px;padding:1px 6px;font-family:'JetBrains Mono',ui-monospace,monospace;font-size:13px}
footer{margin-top:24px;display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap}
.langlink{font-size:13px;text-decoration:none;color:var(--muted);border:1px solid var(--border);border-radius:999px;padding:6px 14px;background:var(--surface)}
.langlink:hover{color:var(--text)}
.muted{color:var(--muted);font-size:13px}
</style>
</head>
<body>
<div class="wrap">
<header>
<a class="brand" href="${q("/terms")}">Web<span>Hooker</span></a>
<nav class="tabs">
<a class="tab ${active === "terms" ? "active" : ""}" href="${q("/terms")}">${t("服务条款", "Terms")}</a>
<a class="tab ${active === "privacy" ? "active" : ""}" href="${q("/privacy")}">${t("隐私政策", "Privacy")}</a>
</nav>
</header>
<article class="card">
<h1>${title}</h1>
<p class="updated">${t("最后更新", "Last updated")}: ${updated}</p>
${body}
</article>
<footer>
<span class="muted">WebHooker · GitHub → Discord</span>
<a class="langlink" href="${q(active === "terms" ? "/terms" : "/privacy").replace(`lang=${lang}`, `lang=${altLang}`)}">${langLabel}</a>
</footer>
</div>
</body>
</html>`;
}
function termsBody(lang: Lang, contact: string): string {
if (lang === "en") {
return `
<p>These Terms of Service ("Terms") govern your use of the WebHooker Discord application and bot ("the Service"), which forwards GitHub webhook events to Discord channels and lets you comment on GitHub from Discord using your own linked GitHub account.</p>
<h2>1. Acceptance</h2>
<p>By adding the bot to a Discord server, using its slash commands, or linking your GitHub account, you agree to these Terms. If you do not agree, do not use the Service.</p>
<h2>2. The Service</h2>
<ul>
<li>Delivers GitHub repository notifications to configured Discord channels.</li>
<li>Provides <code>/gh</code> commands to link a GitHub account and to create, edit, or delete GitHub issue/PR comments as that linked account.</li>
<li>All GitHub write actions are performed with your own OAuth authorization and are subject to your GitHub permissions and to GitHub's Terms of Service.</li>
</ul>
<h2>3. Acceptable Use</h2>
<ul>
<li>Do not use the Service to post spam, harassment, or unlawful content.</li>
<li>Do not attempt to disrupt, overload, reverse-engineer, or gain unauthorized access to the Service.</li>
<li>You are responsible for all activity performed through your linked account.</li>
</ul>
<h2>4. Account Linking &amp; Revocation</h2>
<p>Linking is optional and initiated by you via <code>/gh login</code>. You may unlink at any time with <code>/gh logout</code>, or revoke access from your GitHub account settings under authorized OAuth applications.</p>
<h2>5. Availability &amp; Warranty</h2>
<p>The Service is provided "as is" and "as available", without warranties of any kind. It may be modified, suspended, or discontinued at any time without notice.</p>
<h2>6. Limitation of Liability</h2>
<p>To the maximum extent permitted by law, the operator shall not be liable for any indirect, incidental, or consequential damages arising from your use of the Service.</p>
<h2>7. Changes</h2>
<p>These Terms may be updated. Continued use after changes constitutes acceptance of the revised Terms.</p>
<h2>8. Contact</h2>
<p>Questions about these Terms can be directed to ${contact}.</p>`;
}
return `
<p>本《服务条款》(下称"条款")适用于你对 WebHooker Discord 应用与机器人(下称"本服务")的使用。本服务用于将 GitHub 的 webhook 事件转发到 Discord 频道,并允许你在 Discord 中以你本人绑定的 GitHub 账号对 GitHub 进行评论。</p>
<h2>1. 接受条款</h2>
<p>当你将机器人添加到 Discord 服务器、使用其斜杠命令,或绑定你的 GitHub 账号时,即表示你同意本条款。如不同意,请勿使用本服务。</p>
<h2>2. 服务内容</h2>
<ul>
<li>将 GitHub 仓库通知投递到已配置的 Discord 频道。</li>
<li>提供 <code>/gh</code> 命令用于绑定 GitHub 账号,并以该绑定账号创建、编辑或删除 GitHub issue/PR 评论。</li>
<li>所有对 GitHub 的写入操作均使用你本人的 OAuth 授权执行,受你的 GitHub 权限以及 GitHub 服务条款约束。</li>
</ul>
<h2>3. 可接受使用</h2>
<ul>
<li>不得利用本服务发布垃圾信息、骚扰或违法内容。</li>
<li>不得试图干扰、超载、逆向工程或未经授权访问本服务。</li>
<li>你对通过绑定账号执行的一切操作负责。</li>
</ul>
<h2>4. 账号绑定与解除</h2>
<p>绑定为可选,由你通过 <code>/gh login</code> 主动发起。你可随时使用 <code>/gh logout</code> 解除绑定,或在 GitHub 账号设置的已授权 OAuth 应用中撤销授权。</p>
<h2>5. 可用性与免责声明</h2>
<p>本服务按"现状"和"现有可用"基础提供,不作任何形式的保证。服务可能随时被修改、暂停或终止,恕不另行通知。</p>
<h2>6. 责任限制</h2>
<p>在法律允许的最大范围内,运营者对因使用本服务而产生的任何间接、附带或后果性损害不承担责任。</p>
<h2>7. 条款变更</h2>
<p>本条款可能会更新。变更后继续使用即视为接受修订后的条款。</p>
<h2>8. 联系方式</h2>
<p>关于本条款的问题可联系${contact}。</p>`;
}
function privacyBody(lang: Lang, contact: string): string {
if (lang === "en") {
return `
<p>This Privacy Policy explains what data the WebHooker Discord application ("the Service") processes, why, and how it is stored.</p>
<h2>1. Data We Process</h2>
<ul>
<li><b>Discord identifiers</b>: your Discord user ID, only when you run <code>/gh login</code>, to link you to a GitHub account.</li>
<li><b>GitHub OAuth tokens</b>: an access token (and refresh token, if provided) issued when you authorize the app, used to act on GitHub on your behalf.</li>
<li><b>GitHub account info</b>: your GitHub user ID and login name, returned during authorization.</li>
<li><b>Webhook payloads</b>: GitHub event data is received and forwarded to Discord. It is processed in transit and is not stored beyond short-lived delivery de-duplication keys.</li>
<li><b>Operational logs</b>: minimal send/delivery records kept temporarily for troubleshooting.</li>
</ul>
<h2>2. How Data Is Stored</h2>
<ul>
<li>Data is stored in Cloudflare Workers KV within the operator's Cloudflare account.</li>
<li>Delivery de-duplication keys expire automatically (about 5 minutes).</li>
<li>Send logs expire automatically (about 1 hour).</li>
<li>OAuth tokens persist until you unlink or the token expires/is revoked.</li>
</ul>
<h2>3. How Data Is Used</h2>
<p>Solely to operate the Service: forwarding notifications and performing GitHub actions (comment create/edit/delete) that you explicitly request. We do not sell your data or use it for advertising.</p>
<h2>4. Sharing</h2>
<p>Data is shared only with the platforms required to deliver the Service — GitHub and Discord — through their official APIs, and with Cloudflare as the hosting/storage provider. No other third-party sharing occurs.</p>
<h2>5. Your Choices</h2>
<ul>
<li>Run <code>/gh logout</code> to delete the Discord-to-GitHub link.</li>
<li>Revoke the OAuth authorization from your GitHub settings (Applications → Authorized OAuth Apps) to invalidate stored tokens.</li>
<li>Remove the bot from a server to stop notification delivery.</li>
</ul>
<h2>6. Data Retention</h2>
<p>We retain data only as long as needed for the Service. Transient data expires automatically as described above; account links and tokens are removed when you unlink or revoke access.</p>
<h2>7. Children</h2>
<p>The Service is not directed to individuals under the age required by Discord's Terms of Service, and we do not knowingly collect their data.</p>
<h2>8. Changes</h2>
<p>This policy may be updated. Material changes will be reflected by the "Last updated" date above.</p>
<h2>9. Contact</h2>
<p>For privacy questions or data-removal requests, contact ${contact}.</p>`;
}
return `
<p>本《隐私政策》说明 WebHooker Discord 应用(下称"本服务")处理哪些数据、为何处理以及如何存储。</p>
<h2>1. 我们处理的数据</h2>
<ul>
<li><b>Discord 标识</b>:仅在你执行 <code>/gh login</code> 时收集你的 Discord 用户 ID,用于将你与 GitHub 账号绑定。</li>
<li><b>GitHub OAuth 令牌</b>:在你授权应用时签发的访问令牌(如提供,还包括刷新令牌),用于代表你在 GitHub 上执行操作。</li>
<li><b>GitHub 账号信息</b>:授权过程中返回的 GitHub 用户 ID 和登录名。</li>
<li><b>Webhook 负载</b>:接收 GitHub 事件数据并转发到 Discord,仅在传输过程中处理,除短期的投递去重键外不作留存。</li>
<li><b>运行日志</b>:为便于排障而临时保留的极少量发送/投递记录。</li>
</ul>
<h2>2. 数据如何存储</h2>
<ul>
<li>数据存储于运营者 Cloudflare 账号下的 Cloudflare Workers KV 中。</li>
<li>投递去重键自动过期(约 5 分钟)。</li>
<li>发送日志自动过期(约 1 小时)。</li>
<li>OAuth 令牌在你解除绑定或令牌过期/被撤销前持续保留。</li>
</ul>
<h2>3. 数据如何使用</h2>
<p>仅用于运行本服务:转发通知,以及执行你明确请求的 GitHub 操作(评论的创建/编辑/删除)。我们不出售你的数据,也不用于广告。</p>
<h2>4. 数据共享</h2>
<p>数据仅通过官方 API 与提供本服务所必需的平台共享——即 GitHub 与 Discord——以及作为托管/存储提供方的 Cloudflare。不存在其他第三方共享。</p>
<h2>5. 你的选择</h2>
<ul>
<li>执行 <code>/gh logout</code> 删除 Discord 与 GitHub 的绑定。</li>
<li>在 GitHub 设置(Applications → Authorized OAuth Apps)中撤销 OAuth 授权,使已存令牌失效。</li>
<li>将机器人移出服务器以停止通知投递。</li>
</ul>
<h2>6. 数据留存</h2>
<p>我们仅在提供本服务所需的期间内保留数据。临时数据按上文自动过期;账号绑定与令牌在你解除绑定或撤销授权时被删除。</p>
<h2>7. 未成年人</h2>
<p>本服务不面向低于 Discord 服务条款所要求年龄的个人,我们也不会有意收集其数据。</p>
<h2>8. 政策变更</h2>
<p>本政策可能会更新。重大变更将通过上方"最后更新"日期体现。</p>
<h2>9. 联系方式</h2>
<p>如有隐私问题或数据删除请求,请联系${contact}。</p>`;
}
const UPDATED = "2026-08-01";
export function createLegalRoutes(): Hono<{ Bindings: Env }> {
const app = new Hono<{ Bindings: Env }>();
app.get("/terms", (c) => {
const lang = pickLang(c.req.query("lang"));
const contact = c.env.LEGAL_CONTACT ?? (lang === "zh" ? CONTACT_FALLBACK_ZH : CONTACT_FALLBACK);
return c.html(
layout({
lang,
active: "terms",
title: lang === "zh" ? "服务条款" : "Terms of Service",
updated: UPDATED,
body: termsBody(lang, contact),
}),
);
});
app.get("/privacy", (c) => {
const lang = pickLang(c.req.query("lang"));
const contact = c.env.LEGAL_CONTACT ?? (lang === "zh" ? CONTACT_FALLBACK_ZH : CONTACT_FALLBACK);
return c.html(
layout({
lang,
active: "privacy",
title: lang === "zh" ? "隐私政策" : "Privacy Policy",
updated: UPDATED,
body: privacyBody(lang, contact),
}),
);
});
return app;
}
+119
View File
@@ -0,0 +1,119 @@
import { Hono } from "hono";
import { getOAuthURL, handleOAuthCallback } from "../github/oauth";
import { removeToken, saveDiscordLink } from "../github/store";
import { createAdminSession, adminCookie } from "./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 `<!doctype html><html lang="zh"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>绑定成功</title><style>body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;font-family:system-ui,-apple-system,'Segoe UI',sans-serif;background:#f6f7f9;color:#1f2328}.card{background:#fff;border:1px solid #e5e7eb;border-radius:12px;padding:32px 40px;text-align:center;box-shadow:0 1px 3px rgba(0,0,0,.06)}.ok{color:#16a34a;font-size:40px}h1{font-size:18px;margin:12px 0 4px}p{color:#57606a;font-size:14px;margin:0}</style></head><body><div class="card"><div class="ok">✓</div><h1>GitHub 账号已绑定</h1><p>已连接为 <b>@${login}</b>,现在可以回到 Discord 用 GitHub 评论了。</p></div></body></html>`;
}
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;
}
+77
View File
@@ -0,0 +1,77 @@
import type { Env } from "../types";
const SESSION_COOKIE = "wh_admin_session";
const SESSION_TTL = 7 * 24 * 3600;
export interface AdminSession {
userId: string;
login: string;
}
export function isAdminUser(env: Env, userId: string, login: string): boolean {
const ids = (env.ADMIN_USER_IDS ?? "")
.split(",")
.map((s) => s.trim())
.filter(Boolean);
if (ids.length === 0) return false;
return ids.includes(userId) || ids.some((id) => id.toLowerCase() === login.toLowerCase());
}
function generateSessionId(): string {
const bytes = new Uint8Array(32);
crypto.getRandomValues(bytes);
return Array.from(bytes)
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
}
export async function createAdminSession(
kv: KVNamespace,
userId: string,
login: string,
): Promise<string> {
const sessionId = generateSessionId();
const session: AdminSession = { userId, login };
await kv.put(`session:${sessionId}`, JSON.stringify(session), {
expirationTtl: SESSION_TTL,
});
return sessionId;
}
export function adminCookie(sessionId: string): string {
return `${SESSION_COOKIE}=${sessionId}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=${SESSION_TTL}`;
}
export function clearAdminCookie(): string {
return `${SESSION_COOKIE}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`;
}
function parseCookies(header: string | undefined): Record<string, string> {
const out: Record<string, string> = {};
if (!header) return out;
for (const part of header.split(";")) {
const idx = part.indexOf("=");
if (idx === -1) continue;
out[part.slice(0, idx).trim()] = part.slice(idx + 1).trim();
}
return out;
}
export async function getAdminSession(
kv: KVNamespace,
cookieHeader: string | undefined,
): Promise<AdminSession | null> {
const sessionId = parseCookies(cookieHeader)[SESSION_COOKIE];
if (!sessionId) return null;
const raw = await kv.get<AdminSession>(`session:${sessionId}`, "json");
if (!raw) return null;
return raw;
}
export async function destroyAdminSession(
kv: KVNamespace,
cookieHeader: string | undefined,
): Promise<void> {
const sessionId = parseCookies(cookieHeader)[SESSION_COOKIE];
if (sessionId) await kv.delete(`session:${sessionId}`);
}