Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
feat(discord): join the server and get GitHub roles from one link
leepokai2ac060cbdb89
diff --git a/.github/workflows/contributor.yml b/.github/workflows/contributor.ymlindex ecdfbcdb..60b1d692 100644--- a/.github/workflows/contributor.yml+++ b/.github/workflows/contributor.yml@@ -1,7 +1,7 @@name: contributor-# A contributor's first merged pull request or first issue gets a thank-you with the link that hands out the-# Discord Contributor / Reporter role. pull_request_target runs this file from the default branch and never+# A contributor's first merged pull request or first issue gets a thank-you with the link that adds them to the+# Discord with the Contributor / Reporter role. pull_request_target runs this file from the default branch and never# checks out the PR's code.on:pull_request_target:@@ -36,4 +36,4 @@ jobs:role=Contributor; what="your first merged contribution"fi[ "$count" -le 1 ] || exit 0- gh api "repos/$REPO/issues/$NUMBER/comments" -f body="Thanks for $what, @$AUTHOR! Join the [Codync Discord](https://discord.gg/KBAX3Qznxh) and claim the **$role** role at https://discord.codync.dev (it checks the GitHub account connected to your Discord profile)."+ gh api "repos/$REPO/issues/$NUMBER/comments" -f body="Thanks for $what, @$AUTHOR! Join the Codync Discord with the **$role** role in one step: https://discord.codync.dev"diff --git a/discord/README.md b/discord/README.mdindex 39df92fe..856395cb 100644--- a/discord/README.md+++ b/discord/README.md@@ -1,26 +1,41 @@# Codync Discord-Cloudflare Worker at `https://discord.codync.dev` that gives the GitHub roles on the Codync Discord.+Cloudflare Worker at `https://discord.codync.dev`: one link that adds a member to the Codync Discord and gives+the GitHub roles.-1. `/` sends the member to Discord sign-in (`identify connections`).-2. `/callback` reads the GitHub account connected in their Discord profile (verified by Discord, so nobody can- claim someone else's) and resolves its login by GitHub user id.+1. `/` sends the member to Discord sign-in (`identify connections guilds.join`).+2. `/callback` adds them to the server, then takes the GitHub account connected in their Discord profile+ (verified by Discord). Without one, they sign in with GitHub (`/github/callback`); the Discord id travels in a+ signed cookie, so nobody can link a GitHub account to someone else's Discord.3. A merged pull request on `leepokai/Codync` earns **Contributor**, an opened issue **Reporter**; the bot adds- each role earned. No GitHub connection, or neither: nothing changes.+ each role earned. The link is stored in KV (`github:<GitHub user id>` → Discord user id), and each new link+ or role is posted to #moderator-only (no pings).+4. `/webhook` takes the repo's `pull_request` and `issues` events: a linked member gets the role the moment+ their pull request merges or their issue opens.-`.github/workflows/contributor.yml` comments the link on a contributor's first merged pull request and first issue.+`.github/workflows/contributor.yml` comments the link on a contributor's first merged pull request and first+issue. The onboarding Server Guide has a "Link your GitHub" to-do that leads to the link in #welcome.## Setup-- Discord application **Codync** (Developer Portal): OAuth2 redirect `https://discord.codync.dev/callback`; bot not public.- Install the bot in the server with Manage Roles, and keep its role above Contributor and Reporter.-- `wrangler.toml` holds the public values (client id, guild, role ids, repo, invite).+- Discord application **Codync** (Developer Portal): OAuth2 redirect `https://discord.codync.dev/callback`; bot+ not public. In the server, its role keeps Manage Roles and Create Invite (`guilds.join` needs it), sits above+ Contributor and Reporter, and can view and send in #moderator-only.+- GitHub OAuth app **Codync Discord** (leepokai's developer settings): callback+ `https://discord.codync.dev/github/callback`, no scopes requested.+- Repo webhook: `https://discord.codync.dev/webhook`, JSON, events `pull_request` and `issues`, secret =+ `GITHUB_WEBHOOK_SECRET`.+- `wrangler.toml` holds the public values (client ids, guild, role and channel ids, repo) and the `LINKS` KV+ namespace.```bashnpm cinpx wrangler secret put DISCORD_CLIENT_SECRETnpx wrangler secret put DISCORD_BOT_TOKEN-npx wrangler secret put GITHUB_TOKEN # classic token, no scopes (public read only)+npx wrangler secret put GITHUB_CLIENT_SECRET # the OAuth app's+npx wrangler secret put GITHUB_TOKEN # classic token, no scopes (public read only)+npx wrangler secret put GITHUB_WEBHOOK_SECRET # the repo webhook's+npx wrangler secret put SESSION_SECRET # any random string (openssl rand -hex 32)npm run deploy```diff --git a/discord/src/guild.ts b/discord/src/guild.tsnew file mode 100644index 00000000..f797db23--- /dev/null+++ b/discord/src/guild.ts@@ -0,0 +1,75 @@+// The Codync server: adding members, the GitHub roles they earn, and the staff channel notice.++import { json } from "./http.ts";+import type { Env } from "./index.ts";++export const DISCORD = "https://discord.com/api/v10";++export interface Role {+ name: string;+ id: string;+ query: string;+}++export const roles = (env: Env): Role[] => [+ { name: "Contributor", id: env.CONTRIBUTOR_ROLE_ID, query: "is:pr is:merged" },+ { name: "Reporter", id: env.REPORTER_ROLE_ID, query: "is:issue" },+];++export const names = (list: Role[]) => list.map((r) => r.name).join(" and ");+export const profile = (login: string) => `[${login}](https://github.com/${login})`;++const bot = (env: Env) => ({ Authorization: `Bot ${env.DISCORD_BOT_TOKEN}` });+const github = (env: Env) => ({ headers: { Authorization: `Bearer ${env.GITHUB_TOKEN}`, "User-Agent": "codync-discord" } });++/** The account's current login; names in connections go stale after a rename, ids don't. */+export async function githubLogin(env: Env, githubId: string): Promise<string> {+ return (await json<{ login: string }>(`https://api.github.com/user/${githubId}`, github(env))).login;+}++/** Roles the GitHub account has earned in the repo so far. */+export async function earnedRoles(env: Env, login: string): Promise<Role[]> {+ const all = roles(env);+ const counts = await Promise.all(all.map(async ({ query }) => {+ const q = encodeURIComponent(`repo:${env.REPO} ${query} author:${login}`);+ return (await json<{ total_count: number }>(`https://api.github.com/search/issues?q=${q}&per_page=1`, github(env))).total_count;+ }));+ return all.filter((_, i) => counts[i] > 0);+}++/** Adds the member to the server with their `guilds.join` token; a no-op when they're already in. */+export async function join(env: Env, discordId: string, accessToken: string): Promise<void> {+ const res = await fetch(`${DISCORD}/guilds/${env.GUILD_ID}/members/${discordId}`, {+ method: "PUT",+ headers: { ...bot(env), "Content-Type": "application/json" },+ body: JSON.stringify({ access_token: accessToken }),+ });+ if (!res.ok) throw new Error(`join ${res.status}: ${await res.text()}`);+}++/** Gives the earned roles the member doesn't hold yet and returns them; none once they've left the server. */+export async function grant(env: Env, discordId: string, earned: Role[], reason: string): Promise<Role[]> {+ if (earned.length === 0) return [];+ const member = `${DISCORD}/guilds/${env.GUILD_ID}/members/${discordId}`;+ const res = await fetch(member, { headers: bot(env) });+ if (res.status === 404) return [];+ if (!res.ok) throw new Error(`member ${res.status}: ${await res.text()}`);+ const held = (await res.json<{ roles: string[] }>()).roles;+ const missing = earned.filter((r) => !held.includes(r.id));+ for (const role of missing) {+ const put = await fetch(`${member}/roles/${role.id}`, { method: "PUT", headers: { ...bot(env), "X-Audit-Log-Reason": reason } });+ if (!put.ok) throw new Error(`role ${role.name} ${put.status}: ${await put.text()}`);+ }+ return missing;+}++/** Posts to the staff channel. A failure is logged and never fails the member's flow. */+export async function notify(env: Env, content: string): Promise<void> {+ const res = await fetch(`${DISCORD}/channels/${env.STAFF_CHANNEL_ID}/messages`, {+ method: "POST",+ headers: { ...bot(env), "Content-Type": "application/json" },+ // No pings; flag 4 drops link previews.+ body: JSON.stringify({ content, allowed_mentions: { parse: [] }, flags: 4 }),+ });+ if (!res.ok) console.error("notify failed", { status: res.status, body: await res.text() });+}diff --git a/discord/src/hmac.ts b/discord/src/hmac.tsnew file mode 100644index 00000000..2b6240a9--- /dev/null+++ b/discord/src/hmac.ts@@ -0,0 +1,19 @@+// HMAC-SHA256 in hex: the signed session cookie and GitHub's webhook signature.++const encoder = new TextEncoder();++const key = (secret: string) =>+ crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);++export async function sign(secret: string, data: string): Promise<string> {+ const mac = await crypto.subtle.sign("HMAC", await key(secret), encoder.encode(data));+ return [...new Uint8Array(mac)].map((b) => b.toString(16).padStart(2, "0")).join("");+}++/** Constant-time check of a hex signature. */+export async function verify(secret: string, data: string, signature: string): Promise<boolean> {+ const pairs = /^(?:[0-9a-f]{2})+$/.test(signature) ? signature.match(/../g) : null;+ if (!pairs) return false;+ const bytes = Uint8Array.from(pairs, (h) => parseInt(h, 16));+ return crypto.subtle.verify("HMAC", await key(secret), bytes, encoder.encode(data));+}diff --git a/discord/src/http.ts b/discord/src/http.tsnew file mode 100644index 00000000..fa81641a--- /dev/null+++ b/discord/src/http.ts@@ -0,0 +1,19 @@+// Fetching JSON from Discord and GitHub, and the small pages the member sees.++export async function json<T>(url: string, init: RequestInit): Promise<T> {+ const res = await fetch(url, init);+ if (!res.ok) throw new Error(`${url} ${res.status}: ${await res.text()}`);+ return res.json<T>();+}++const escape = (s: string) => s.replace(/[&<>"]/g, (c) => `&#${c.charCodeAt(0)};`);++export function page(status: number, title: string, body: string, link?: { href: string; label: string }): Response {+ const html = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width">+<title>Codync Discord</title>+<style>body{font:16px system-ui;display:grid;place-content:center;min-height:90vh;margin:0 16px;text-align:center;color:#111;background:#fff}+@media(prefers-color-scheme:dark){body{color:#eee;background:#111}}p{opacity:.7}+a{display:inline-block;margin-top:8px;padding:10px 20px;border-radius:8px;background:#5865f2;color:#fff;font-weight:600;text-decoration:none}</style>+<h1>${escape(title)}</h1><p>${escape(body)}</p>${link ? `<div><a href="${escape(link.href)}">${escape(link.label)}</a></div>` : ""}`;+ return new Response(html, { status, headers: { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" } });+}diff --git a/discord/src/index.ts b/discord/src/index.tsindex b105cfca..82e1635f 100644--- a/discord/src/index.ts+++ b/discord/src/index.ts@@ -1,59 +1,78 @@-// GitHub roles for the Codync Discord. The member signs in with Discord; we read the GitHub account they-// connected in Discord (Discord verifies it, so nobody can claim someone else's). A merged pull request on-// the repo earns the Contributor role, an opened issue the Reporter role.+// GitHub roles for the Codync Discord, from one link. Signing in with Discord adds the member to the server;+// their GitHub account comes from their Discord connections (verified by Discord) or, when they have none, from+// signing in with GitHub, so nobody can claim someone else's. A merged pull request on the repo earns the+// Contributor role, an opened issue the Reporter role. The link is remembered, so later ones arrive on their+// own (webhook.ts).++import { DISCORD, earnedRoles, githubLogin, grant, join, names, notify, profile } from "./guild.ts";+import { sign, verify } from "./hmac.ts";+import { json, page } from "./http.ts";+import { webhook } from "./webhook.ts";export interface Env {DISCORD_CLIENT_ID: string;DISCORD_CLIENT_SECRET: string;DISCORD_BOT_TOKEN: string;+ GITHUB_CLIENT_ID: string;+ GITHUB_CLIENT_SECRET: string;GITHUB_TOKEN: string;+ GITHUB_WEBHOOK_SECRET: string;+ SESSION_SECRET: string;GUILD_ID: string;CONTRIBUTOR_ROLE_ID: string;REPORTER_ROLE_ID: string;+ STAFF_CHANNEL_ID: string;REPO: string;- INVITE: string;+ /** `github:<GitHub user id>` → Discord user id. */+ LINKS: KVNamespace;}-const DISCORD = "https://discord.com/api/v10";-export default {async fetch(req: Request, env: Env): Promise<Response> {const url = new URL(req.url);- const redirect = `${url.origin}/callback`;- if (url.pathname === "/") return signIn(env, redirect);- if (url.pathname !== "/callback") return page(404, "Not found", "");try {- return await claim(req, url, env, redirect);+ switch (url.pathname) {+ case "/": return discordSignIn(env, url.origin);+ case "/callback": return await discordCallback(req, url, env);+ case "/github/callback": return await githubCallback(req, url, env);+ case "/webhook": return await webhook(req, env);+ default: return page(404, "Not found", "");+ }} catch (e) {- console.error("claim failed", { error: String(e) });+ console.error("request failed", { path: url.pathname, error: String(e) });return page(502, "Something went wrong", "Try again in a minute.");}},};-function signIn(env: Env, redirect: string): Response {+const expired = () => page(400, "This link expired", "Open discord.codync.dev again.");++const cookie = (req: Request, name: string) =>+ req.headers.get("Cookie")?.match(new RegExp(`(?:^|;\\s*)${name}=([^;]+)`))?.[1];++function redirect(location: string, name: string, value: string, path: string): Response {+ return new Response(null, {+ status: 302,+ headers: { Location: location, "Set-Cookie": `${name}=${value}; Path=${path}; Max-Age=600; HttpOnly; Secure; SameSite=Lax` },+ });+}++function discordSignIn(env: Env, origin: string): Response {const state = crypto.randomUUID();const params = new URLSearchParams({client_id: env.DISCORD_CLIENT_ID,response_type: "code",- scope: "identify connections",- redirect_uri: redirect,+ scope: "identify connections guilds.join",+ redirect_uri: `${origin}/callback`,state,});- return new Response(null, {- status: 302,- headers: {- Location: `https://discord.com/oauth2/authorize?${params}`,- "Set-Cookie": `state=${state}; Path=/callback; Max-Age=600; HttpOnly; Secure; SameSite=Lax`,- },- });+ return redirect(`https://discord.com/oauth2/authorize?${params}`, "state", state, "/callback");}-async function claim(req: Request, url: URL, env: Env, redirect: string): Promise<Response> {+async function discordCallback(req: Request, url: URL, env: Env): Promise<Response> {const code = url.searchParams.get("code");const state = url.searchParams.get("state");- const cookie = req.headers.get("Cookie")?.match(/(?:^|;\s*)state=([^;]+)/)?.[1];- if (!code || !state || state !== cookie) return page(400, "This link expired", "Open it again from Discord.");+ if (!code || !state || state !== cookie(req, "state")) return expired();const { access_token } = await json<{ access_token: string }>(`${DISCORD}/oauth2/token`, {method: "POST",@@ -62,7 +81,7 @@ async function claim(req: Request, url: URL, env: Env, redirect: string): Promisclient_secret: env.DISCORD_CLIENT_SECRET,grant_type: "authorization_code",code,- redirect_uri: redirect,+ redirect_uri: `${url.origin}/callback`,}),});const user = { headers: { Authorization: `Bearer ${access_token}` } };@@ -70,53 +89,60 @@ async function claim(req: Request, url: URL, env: Env, redirect: string): Promisjson<{ id: string }>(`${DISCORD}/users/@me`, user),json<{ type: string; id: string; verified: boolean }[]>(`${DISCORD}/users/@me/connections`, user),]);+ await join(env, me.id, access_token);+ // The connection's id is the GitHub user id.const connection = connections.find((c) => c.type === "github" && c.verified);- if (!connection) {- return page(200, "Connect GitHub to Discord first", "Discord → User Settings → Connections → GitHub, then open this link again.");- }-- // The connection's id is the GitHub user id; its name can be stale after a rename.- const github = { headers: { Authorization: `Bearer ${env.GITHUB_TOKEN}`, "User-Agent": "codync-discord" } };- const { login } = await json<{ login: string }>(`https://api.github.com/user/${connection.id}`, github);- const roles = [- { name: "Contributor", id: env.CONTRIBUTOR_ROLE_ID, query: "is:pr is:merged" },- { name: "Reporter", id: env.REPORTER_ROLE_ID, query: "is:issue" },- ];- const counts = await Promise.all(roles.map(async ({ query }) => {- const q = encodeURIComponent(`repo:${env.REPO} ${query} author:${login}`);- return (await json<{ total_count: number }>(`https://api.github.com/search/issues?q=${q}&per_page=1`, github)).total_count;- }));- const earned = roles.filter((_, i) => counts[i] > 0);- if (earned.length === 0) {- return page(200, `Nothing from @${login} in ${env.REPO} yet`, "Open this link again once you open an issue or a pull request of yours is merged.");- }+ return connection ? link(env, me.id, connection.id) : githubSignIn(env, url.origin, me.id);+}- for (const role of earned) {- const res = await fetch(`${DISCORD}/guilds/${env.GUILD_ID}/members/${me.id}/roles/${role.id}`, {- method: "PUT",- headers: { Authorization: `Bot ${env.DISCORD_BOT_TOKEN}`, "X-Audit-Log-Reason": `GitHub @${login}` },- });- if (res.status === 404) return page(200, "Join the server first", "Then open this link again.", env.INVITE);- if (!res.ok) throw new Error(`role ${role.name} ${res.status}: ${await res.text()}`);- }- const names = earned.map((r) => r.name).join(" and ");- console.log("roles granted", { discord: me.id, github: login, roles: names });- return page(200, `You're a ${names}`, `Thanks for your work on Codync, @${login}.`);+async function githubSignIn(env: Env, origin: string, discordId: string): Promise<Response> {+ const state = crypto.randomUUID();+ const params = new URLSearchParams({ client_id: env.GITHUB_CLIENT_ID, redirect_uri: `${origin}/github/callback`, state });+ // Signed, so a forged cookie can't link a GitHub account to someone else's Discord.+ const session = `${state}.${discordId}`;+ const value = `${session}.${await sign(env.SESSION_SECRET, session)}`;+ return redirect(`https://github.com/login/oauth/authorize?${params}`, "session", value, "/github/callback");}-async function json<T>(url: string, init: RequestInit): Promise<T> {- const res = await fetch(url, init);- if (!res.ok) throw new Error(`${url} ${res.status}: ${await res.text()}`);- return res.json<T>();+async function githubCallback(req: Request, url: URL, env: Env): Promise<Response> {+ const code = url.searchParams.get("code");+ const [state, discordId, signature] = cookie(req, "session")?.split(".") ?? [];+ if (!code || !state || !discordId || !signature || url.searchParams.get("state") !== state) return expired();+ if (!(await verify(env.SESSION_SECRET, `${state}.${discordId}`, signature))) return expired();++ const token = await json<{ access_token?: string }>("https://github.com/login/oauth/access_token", {+ method: "POST",+ headers: { Accept: "application/json" },+ body: new URLSearchParams({+ client_id: env.GITHUB_CLIENT_ID,+ client_secret: env.GITHUB_CLIENT_SECRET,+ code,+ redirect_uri: `${url.origin}/github/callback`,+ }),+ });+ // GitHub answers a used or expired code with 200 and an error field.+ if (!token.access_token) return expired();+ const github = { headers: { Authorization: `Bearer ${token.access_token}`, "User-Agent": "codync-discord" } };+ const { id } = await json<{ id: number }>("https://api.github.com/user", github);+ return link(env, discordId, String(id));}-const escape = (s: string) => s.replace(/[&<>"]/g, (c) => `&#${c.charCodeAt(0)};`);+async function link(env: Env, discordId: string, githubId: string): Promise<Response> {+ const login = await githubLogin(env, githubId);+ const earned = await earnedRoles(env, login);+ const key = `github:${githubId}`;+ const known = (await env.LINKS.get(key)) === discordId;+ await env.LINKS.put(key, discordId);+ const granted = await grant(env, discordId, earned, `GitHub @${login}`);+ if (!known || granted.length > 0) {+ const roles = granted.length > 0 ? ` → ${names(granted)}` : "";+ await notify(env, `<@${discordId}> linked GitHub ${profile(login)}${roles}`);+ }+ console.log("linked", { discord: discordId, github: login, roles: names(earned) });-function page(status: number, title: string, body: string, link?: string): Response {- const html = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width">-<title>Codync Discord</title>-<style>body{font:16px system-ui;display:grid;place-content:center;min-height:90vh;margin:0 16px;text-align:center;color:#111;background:#fff}-@media(prefers-color-scheme:dark){body{color:#eee;background:#111}}p{opacity:.7}</style>-<h1>${escape(title)}</h1><p>${escape(body)}</p>${link ? `<p><a href="${escape(link)}">${escape(link)}</a></p>` : ""}`;- return new Response(html, { status, headers: { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" } });+ const server = { href: `https://discord.com/channels/${env.GUILD_ID}`, label: "Open Discord" };+ if (earned.length === 0) {+ return page(200, `You're in, @${login}`, "Your roles show up on their own once you open an issue or a pull request of yours is merged.", server);+ }+ return page(200, `You're a ${names(earned)}`, `Thanks for your work on Codync, @${login}.`, server);}diff --git a/discord/src/webhook.ts b/discord/src/webhook.tsnew file mode 100644index 00000000..6ad04f7d--- /dev/null+++ b/discord/src/webhook.ts@@ -0,0 +1,52 @@+// GitHub webhook (pull_request, issues): a linked member earns a role as soon as their pull request merges or+// their issue opens, without opening the link again.++import { grant, notify, profile, roles, type Role } from "./guild.ts";+import { verify } from "./hmac.ts";+import type { Env } from "./index.ts";++interface Item {+ number: number;+ html_url: string;+ user: { id: number; login: string };+}++interface Payload {+ action: string;+ pull_request?: Item & { merged: boolean };+ issue?: Item;+}++const done = () => new Response(null, { status: 204 });++export async function webhook(req: Request, env: Env): Promise<Response> {+ const body = await req.text();+ const signature = req.headers.get("X-Hub-Signature-256")?.replace(/^sha256=/, "") ?? "";+ if (req.method !== "POST" || !(await verify(env.GITHUB_WEBHOOK_SECRET, body, signature))) {+ return new Response("Bad signature", { status: 401 });+ }+ const earned = earnedBy(req.headers.get("X-GitHub-Event"), JSON.parse(body) as Payload, env);+ if (!earned) return done();+ const { role, item, what } = earned;+ const discordId = await env.LINKS.get(`github:${item.user.id}`);+ if (!discordId) return done();++ const granted = await grant(env, discordId, [role], `GitHub @${item.user.login} ${what}`);+ if (granted.length > 0) {+ await notify(env, `<@${discordId}> (${profile(item.user.login)}) earned ${role.name} with [${what}](${item.html_url})`);+ console.log("role earned", { discord: discordId, github: item.user.login, role: role.name });+ }+ return done();+}++function earnedBy(event: string | null, payload: Payload, env: Env): { role: Role; item: Item; what: string } | null {+ const [contributor, reporter] = roles(env);+ const { pull_request: pr, issue } = payload;+ if (event === "pull_request" && payload.action === "closed" && pr?.merged) {+ return { role: contributor, item: pr, what: `PR #${pr.number}` };+ }+ if (event === "issues" && payload.action === "opened" && issue) {+ return { role: reporter, item: issue, what: `issue #${issue.number}` };+ }+ return null;+}diff --git a/discord/test/claim.test.ts b/discord/test/claim.test.tsindex 42300352..71d53cb0 100644--- a/discord/test/claim.test.ts+++ b/discord/test/claim.test.ts@@ -1,67 +1,154 @@-// Claim flow against stubbed Discord and GitHub: only a verified GitHub connection earns roles, a merged PR-// the Contributor role and an opened issue the Reporter role.+// Link and webhook flows against stubbed Discord, GitHub and KV: signing in adds the member to the server, a+// verified GitHub connection (or a GitHub sign-in) earns roles, the link is remembered, and later merged pull+// requests and opened issues earn roles through the webhook.import assert from "node:assert/strict";+import { sign } from "../src/hmac.ts";import worker from "../src/index.ts";+const links = new Map<string, string>();const env = {- DISCORD_CLIENT_ID: "app", DISCORD_CLIENT_SECRET: "secret", DISCORD_BOT_TOKEN: "bot", GITHUB_TOKEN: "gh",- GUILD_ID: "guild", CONTRIBUTOR_ROLE_ID: "contributor", REPORTER_ROLE_ID: "reporter",- REPO: "leepokai/Codync", INVITE: "https://discord.gg/invite",-};+ DISCORD_CLIENT_ID: "app", DISCORD_CLIENT_SECRET: "secret", DISCORD_BOT_TOKEN: "bot",+ GITHUB_CLIENT_ID: "ghapp", GITHUB_CLIENT_SECRET: "ghsecret", GITHUB_TOKEN: "gh", GITHUB_WEBHOOK_SECRET: "hook",+ SESSION_SECRET: "session", GUILD_ID: "guild", CONTRIBUTOR_ROLE_ID: "contributor", REPORTER_ROLE_ID: "reporter",+ STAFF_CHANNEL_ID: "staff", REPO: "leepokai/Codync",+ LINKS: { get: async (k: string) => links.get(k) ?? null, put: async (k: string, v: string) => void links.set(k, v) },+} as never;++const github = { type: "github", id: "7", verified: true };-function stub(connections: object[], { prs = 0, issues = 0, member = true } = {}) {- const roles: string[] = [];+/** Stubs every upstream call and records the ones with effects: join, role, notify. */+function stub({ connections = [github] as object[], prs = 0, issues = 0, held = [] as string[], member = true } = {}) {+ const calls: string[] = [];globalThis.fetch = (async (input: string, init?: RequestInit) => {const url = String(input);+ const method = init?.method ?? "GET";if (url.endsWith("/oauth2/token")) return Response.json({ access_token: "user" });if (url.endsWith("/users/@me")) return Response.json({ id: "42" });if (url.endsWith("/users/@me/connections")) return Response.json(connections);+ if (url === "https://github.com/login/oauth/access_token") {+ const good = new URLSearchParams(String(init?.body)).get("code") === "good";+ return Response.json(good ? { access_token: "gho" } : { error: "bad_verification_code" });+ }+ if (url === "https://api.github.com/user") return Response.json({ id: 7 });if (url.endsWith("/user/7")) return Response.json({ login: "octo" });if (url.includes("/search/issues")) {const q = decodeURIComponent(url);assert.match(q, /repo:leepokai\/Codync .* author:octo/);return Response.json({ total_count: q.includes("is:pr is:merged") ? prs : issues });}- if (url.includes("/roles/")) {- assert.equal(init?.method, "PUT");- roles.push(url.split("/").pop()!);- return new Response(null, { status: member ? 204 : 404 });+ if (url.endsWith("/guilds/guild/members/42") && method === "PUT") {+ assert.equal(JSON.parse(String(init?.body)).access_token, "user");+ calls.push("join");+ return new Response(null, { status: 201 });+ }+ if (url.endsWith("/guilds/guild/members/42")) return member ? Response.json({ roles: held }) : new Response(null, { status: 404 });+ if (url.includes("/guilds/guild/members/42/roles/")) {+ assert.equal(method, "PUT");+ calls.push(`role ${url.split("/").pop()}`);+ return new Response(null, { status: 204 });+ }+ if (url.endsWith("/channels/staff/messages")) {+ calls.push(`notify ${JSON.parse(String(init?.body)).content}`);+ return Response.json({});}- throw new Error(`unexpected ${url}`);+ throw new Error(`unexpected ${method} ${url}`);}) as typeof fetch;- return roles;+ return calls;}-const callback = async (state = "s", cookie = "s") => {- const res = await worker.fetch(new Request(`https://discord.test/callback?code=c&state=${state}`, { headers: { Cookie: `state=${cookie}` } }), env);- return { status: res.status, text: await res.text() };+const get = (path: string, cookie = "") => worker.fetch(new Request(`https://discord.test${path}`, { headers: { Cookie: cookie } }), env);+const discordCallback = async (state = "s", cookie = "s") => {+ const res = await get(`/callback?code=c&state=${state}`, `state=${cookie}`);+ return { res, text: await res.text() };};-const start = await worker.fetch(new Request("https://discord.test/"), env);+// Sign-in asks Discord for the connections and to add the member to the server.+const start = await get("/");assert.equal(start.status, 302);-const state = start.headers.get("Set-Cookie")!.match(/state=([^;]+)/)![1];-assert.equal(new URL(start.headers.get("Location")!).searchParams.get("state"), state);+const authorize = new URL(start.headers.get("Location")!);+assert.equal(authorize.searchParams.get("scope"), "identify connections guilds.join");+assert.equal(authorize.searchParams.get("state"), start.headers.get("Set-Cookie")!.match(/state=([^;]+)/)![1]);-const github = { type: "github", id: "7", verified: true };-let roles = stub([github], { prs: 1 });-assert.equal((await callback("s", "forged")).status, 400);-assert.match((await callback()).text, /You're a Contributor</);-assert.deepEqual(roles, ["contributor"]);--roles = stub([github], { issues: 2 });-assert.match((await callback()).text, /You're a Reporter</);-assert.deepEqual(roles, ["reporter"]);--roles = stub([github], { prs: 3, issues: 1 });-assert.match((await callback()).text, /You're a Contributor and Reporter/);-assert.deepEqual(roles, ["contributor", "reporter"]);--roles = stub([{ ...github, verified: false }], { prs: 1 });-assert.match((await callback()).text, /Connect GitHub/);-assert.deepEqual(roles, []);-roles = stub([github]);-assert.match((await callback()).text, /Nothing from @octo/);-assert.deepEqual(roles, []);-stub([github], { prs: 1, member: false });-assert.match((await callback()).text, /Join the server first/);+let calls = stub({ prs: 1 });+assert.equal((await discordCallback("s", "forged")).res.status, 400);+assert.deepEqual(calls, []);++// A verified connection with a merged PR: joined, Contributor, remembered, staff told.+assert.match((await discordCallback()).text, /You're a Contributor</);+assert.deepEqual(calls, ["join", "role contributor", "notify <@42> linked GitHub [octo](https://github.com/octo) → Contributor"]);+assert.equal(links.get("github:7"), "42");++// Opening the link again changes nothing and stays quiet.+calls = stub({ prs: 1, held: ["contributor"] });+assert.match((await discordCallback()).text, /You're a Contributor</);+assert.deepEqual(calls, ["join"]);++calls = stub({ prs: 3, issues: 1, held: ["contributor"] });+assert.match((await discordCallback()).text, /You're a Contributor and Reporter/);+assert.deepEqual(calls, ["join", "role reporter", "notify <@42> linked GitHub [octo](https://github.com/octo) → Reporter"]);++// Nothing earned yet: still joined and linked.+links.clear();+calls = stub();+assert.match((await discordCallback()).text, /You're in, @octo/);+assert.deepEqual(calls, ["join", "notify <@42> linked GitHub [octo](https://github.com/octo)"]);+assert.equal(links.get("github:7"), "42");++// No verified connection: joined, then on to GitHub sign-in with a signed session.+links.clear();+calls = stub({ connections: [{ ...github, verified: false }], issues: 1 });+const { res: toGitHub } = await discordCallback();+assert.equal(toGitHub.status, 302);+assert.deepEqual(calls, ["join"]);+const login = new URL(toGitHub.headers.get("Location")!);+assert.equal(login.origin + login.pathname, "https://github.com/login/oauth/authorize");+const session = toGitHub.headers.get("Set-Cookie")!.match(/session=([^;]+)/)![1];+const [state, discordId, signature] = session.split(".");+assert.equal(login.searchParams.get("state"), state);+assert.equal(discordId, "42");++const githubCallback = async (code: string, cookie: string) => {+ const res = await get(`/github/callback?code=${code}&state=${state}`, `session=${cookie}`);+ return { status: res.status, text: await res.text() };+};+assert.equal((await githubCallback("good", `${state}.99.${signature}`)).status, 400);+assert.equal((await githubCallback("good", `${state}.42.${"0".repeat(64)}`)).status, 400);+assert.equal((await githubCallback("used", session)).status, 400);+assert.deepEqual(calls, ["join"]);+assert.match((await githubCallback("good", session)).text, /You're a Reporter</);+assert.deepEqual(calls, ["join", "role reporter", "notify <@42> linked GitHub [octo](https://github.com/octo) → Reporter"]);+assert.equal(links.get("github:7"), "42");++// Webhook: signed by GitHub, and only for linked accounts.+const hook = async (event: string, payload: object, secret = "hook") => {+ const body = JSON.stringify(payload);+ const res = await worker.fetch(new Request("https://discord.test/webhook", {+ method: "POST",+ body,+ headers: { "X-GitHub-Event": event, "X-Hub-Signature-256": `sha256=${await sign(secret, body)}` },+ }), env);+ return res.status;+};+const pr = (merged: boolean, id = 7) => ({+ action: "closed",+ pull_request: { number: 12, merged, html_url: "https://github.com/leepokai/Codync/pull/12", user: { id, login: "octo" } },+});++calls = stub();+assert.equal(await hook("pull_request", pr(true), "wrong"), 401);+assert.equal(await hook("ping", { zen: "hi" }), 204);+assert.equal(await hook("pull_request", pr(false)), 204);+assert.equal(await hook("pull_request", pr(true, 8)), 204);+assert.deepEqual(calls, []);+assert.equal(await hook("pull_request", pr(true)), 204);+assert.deepEqual(calls, ["role contributor", "notify <@42> ([octo](https://github.com/octo)) earned Contributor with [PR #12](https://github.com/leepokai/Codync/pull/12)"]);++calls = stub({ held: ["reporter"] });+const issue = { action: "opened", issue: { number: 5, html_url: "https://github.com/leepokai/Codync/issues/5", user: { id: 7, login: "octo" } } };+assert.equal(await hook("issues", issue), 204);+assert.deepEqual(calls, []);++calls = stub({ member: false });+assert.equal(await hook("pull_request", pr(true)), 204);+assert.deepEqual(calls, []);console.log("claim tests ok");diff --git a/discord/tsconfig.json b/discord/tsconfig.jsonindex 00bf28fc..6b2e8247 100644--- a/discord/tsconfig.json+++ b/discord/tsconfig.json@@ -6,7 +6,8 @@"lib": ["ESNext"],"types": ["@cloudflare/workers-types"],"strict": true,- "noEmit": true+ "noEmit": true,+ "allowImportingTsExtensions": true},"include": ["src"]}diff --git a/discord/wrangler.toml b/discord/wrangler.tomlindex 4dce5a5d..b404e44e 100644--- a/discord/wrangler.toml+++ b/discord/wrangler.toml@@ -3,11 +3,17 @@ main = "src/index.ts"compatibility_date = "2026-09-01"routes = [{ pattern = "discord.codync.dev", custom_domain = true }]-# Secrets: DISCORD_CLIENT_SECRET, DISCORD_BOT_TOKEN, GITHUB_TOKEN (see README.md).+# Secrets: DISCORD_CLIENT_SECRET, DISCORD_BOT_TOKEN, GITHUB_CLIENT_SECRET, GITHUB_TOKEN, GITHUB_WEBHOOK_SECRET,+# SESSION_SECRET (see README.md).[vars]DISCORD_CLIENT_ID = "1559877519933440084"+GITHUB_CLIENT_ID = "Ov23lihjSv0zqUceCMcV"GUILD_ID = "1559449720315973682"CONTRIBUTOR_ROLE_ID = "1559453466894663680"REPORTER_ROLE_ID = "1559885097535148133"+STAFF_CHANNEL_ID = "1559451211860672512"REPO = "leepokai/Codync"-INVITE = "https://discord.gg/KBAX3Qznxh"++[[kv_namespaces]]+binding = "LINKS"+id = "93ad47c1274b421bbb733eb06e41d9a9"