diff --git a/.dev.vars.example b/.dev.vars.example
index b6438263..57103999 100644
--- a/.dev.vars.example
+++ b/.dev.vars.example
@@ -73,6 +73,10 @@ TELEGRAM_BOT_TOKEN=""
# shared secret for setWebhook; required for inbound commands
TELEGRAM_WEBHOOK_SECRET=""
+# --- Discord operator bot ---
+# bot token from the Discord developer portal (Bot tab)
+DISCORD_BOT_TOKEN=""
+
# --- Anti-spam ---
# required when SPAM_PROVIDER = "akismet"
AKISMET_API_KEY=""
diff --git a/AGENTS-OPERATE.md b/AGENTS-OPERATE.md
index dd10478e..d1c2a7b4 100644
--- a/AGENTS-OPERATE.md
+++ b/AGENTS-OPERATE.md
@@ -230,6 +230,8 @@ between the two is a build error, not a silent misclassification.
| `TELEGRAM_BOT_TOKEN` | secret | Optional. BotFather token enabling the Telegram operator bot. With only this set, outbound notifications work (add a `telegram` webhook endpoint with a chat id). Unset = feature off. See `docs/telegram.md`. | `123456789:AAH...` | `wrangler secret put` / `.dev.vars` |
| `TELEGRAM_WEBHOOK_SECRET` | secret | Optional. Shared secret echoed in the `X-Telegram-Bot-Api-Secret-Token` header; required for inbound buttons/slash commands. Pass it to Telegram's `setWebhook` as `secret_token`. Unset = inbound rejected (fail closed). | ``openssl rand -base64 32` output` | `wrangler secret put` / `.dev.vars` |
| `TELEGRAM_BOT_USERNAME` | var | Optional. Bot `@username` (without `@`). When set, `/admin/telegram` renders a one-tap `t.me/
+ The Discord bot is configured with Worker secrets, not in this panel.
+ Paste the endpoint URL below into the Discord developer portal as the
+ Interactions Endpoint URL.
+ Interactions endpoint URL:
+ ${
+ d.endpointUrl
+ ? ` Set Discord ids (enable Developer Mode, then right-click to copy an id). Leave a field empty to clear it. Registers Linked ${formatTs(link.linked_at)}. Buttons and slash commands run under your account, with your current role. Generate a code, then run Your one-time code:
+ Connect Discord to moderate comments from your server. Alerts are posted by
+ a webhook endpoint with the Discord bot adapter;
+ this page sets up the server, links your account and registers slash commands.
+` deep link instead of manual `/start` steps. | `YourGarrulBot` | `wrangler.toml` |
+| `DISCORD_BOT_TOKEN` | secret | Optional. Bot token enabling the Discord operator bot (moderation cards, buttons and slash commands). The bot is active only when `DISCORD_PUBLIC_KEY` is also set. Unset = feature off. | `MTE1...fake.token.example` | `wrangler secret put` / `.dev.vars` |
+| `DISCORD_PUBLIC_KEY` | var | Optional. Discord application public key used to verify Ed25519 signatures on inbound interactions. Public, so a plain var. Required together with `DISCORD_BOT_TOKEN`; unset = inbound interactions rejected. | `0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef` | `wrangler.toml` |
| `SPAM_PROVIDER` | var | Optional. Pluggable content classifier — `akismet`, `workers-ai`, or `decisions` (bring your own key). Unset = no classifier. `workers-ai` also needs an `[ai]` binding; `decisions` needs `SPAM_DECISIONS_API_KEY` and a model. See `docs/ANTISPAM.md`. | `akismet` | `wrangler.toml` |
| `AKISMET_API_KEY` | secret | Optional. Akismet API key. Required when `SPAM_PROVIDER=akismet`. | `...` | `wrangler secret put` / `.dev.vars` |
| `AKISMET_SITE_URL` | secret | Optional. Public site URL sent to Akismet alongside each check. Required when `SPAM_PROVIDER=akismet`. | `https://yourblog.example.com` | `wrangler secret put` / `.dev.vars` |
@@ -997,6 +999,7 @@ tracked by the `_migrations` table. Current set:
- `0030_thread_and_retention_indexes.sql` — indexes for top-level thread paging (chronological and by score) and the IP retention sweep; drops the unused `comments_score_idx`
- `0031_admin_list_indexes.sql` — indexes for the moderation queue, dashboard windows and admin list pages
- `0032_page_engagement_totals.sql` — `posts.page_votes_up` / `page_votes_down` plus `page_reaction_totals`, kept on write so bootstrap no longer counts page reactions and votes on every pageview
+- `0033_discord_links.sql` — `discord_links` (Discord user id ↔ Garrul user id; no digest column, the Discord digest goes to a channel)
Run with `npm run migrate` (local Miniflare) or
`npm run migrate -- --remote` (production D1). Idempotent. Never edit a
@@ -1061,11 +1064,51 @@ Pages (top nav):
| `/admin/subscriptions` | Email subscription list. Filter by email/post/confirmed/unsubscribed. Actions: manual unsubscribe, resend confirmation. |
| `/admin/operator` | Batch operations: rerender stale comments (POSTs `/admin/api/ops/rerender` in 50-row chunks until done), seed-demo (idempotent; gated to `ENV != "production"`), the comment import upload (Disqus XML, a Remark42 backup, a Comentario/Commento JSON export, or the JSON `npm run dump-isso` / `npm run dump-cusdis` produces from an isso `comments.db` or a Cusdis `db.sqlite` — gzipped or not — see below), and two retention cards — IP-hash and audit-log — each showing how many rows are past the configured window and offering a manual drain, and **Export site data** (JSON/CSV download links — see §11). |
| `/admin/settings` | Editable form for feature flags, display/pagination numbers, and the moderation dials (edit window, thread auto-close, community auto-collapse, the three anti-spam heuristics), saved to the `settings` D1 table (no redeploy — see section 5). Also renders a read-only `(set)`/`(unset)` summary of deploy-time config (Turnstile, email, OAuth, spam provider), which still changes via `wrangler secret put` / `wrangler.toml`. |
-| `/admin/webhooks` | Outbound webhook endpoints: add/pause/delete, per-endpoint secret + event filter, adapter (`generic` / `slack` / `discord` / `telegram`), failure counts and retry status. |
+| `/admin/webhooks` | Outbound webhook endpoints: add/pause/delete, per-endpoint secret + event filter, adapter (`generic` / `slack` / `discord` / `discord_bot` / `telegram`), failure counts and retry status. |
| `/admin/telegram` | **Admin-only.** Telegram operator bot: shows whether the bot token/webhook secret are set, links your personal Telegram account (one-time code or deep link), toggles the daily digest, and unlinks. See `docs/telegram.md`. |
+| `/admin/discord` | **Admin-only.** Discord operator bot: guild id, mod/admin role ids, digest channel, link code, **Register commands**, and the Interactions Endpoint URL to paste into the Discord developer portal. See `docs/discord.md`. |
| `/admin/saved-replies` | Moderator saved replies: create/edit canned responses, private or shared scope. Presets are a *prefill* for the reply composer, not the only way to reply — see **Replying from the admin panel** below. |
| `/admin/usage` | Cloudflare analytics (Workers requests, D1 rows, KV operations, Workers AI neurons, comments by domain). Requires `CF_API_TOKEN` + `CF_ACCOUNT_ID`; renders setup instructions when unset. |
+### Operator bots: Telegram and Discord
+
+Both bots run on one platform-neutral core in `src/lib/opbot/` (actor
+resolution, per-action authorization, actions, neutral cards, the oldest-first
+queue walk, the button payload codec). Each transport translates cards to its
+own markup and owns its own verification: `src/routes/telegram.ts`
+(`POST /telegram/webhook`, secret header) and `src/routes/discord.ts`
+(`POST /discord/interactions`, Ed25519). Both routes sit outside `/api/*`, so
+CSRF and sessions do not apply. Every action goes through `src/lib/moderation.ts`
+exactly as the dashboard does.
+
+- **Discord is on only when `DISCORD_BOT_TOKEN` and `DISCORD_PUBLIC_KEY` are
+ both set** (see the config table). `DISCORD_CLIENT_ID` doubles as the
+ application id. The guild id, mod role id, admin role id and digest channel id
+ are admin settings at `/admin/discord`, not env vars.
+- **Interactions**: the signature is verified before any D1/KV access (401), a
+ timestamp more than 5 minutes off is 401, then PING/PONG, then a per-user rate
+ limit. There is no dedupe: a replay inside the window can post a reply twice.
+- **Identity**: a `discord_links` row (or a Discord sign-in row) or a configured
+ Discord role. The higher role wins. Discord roles are never written to
+ `users.role`. A role-derived admin cannot ban or unban a Garrul mod/admin. A
+ banned user, a wrong guild or a DM is refused.
+- **Alerts** use the `discord_bot` webhook adapter: the endpoint URL field holds
+ a channel id, messages are posted with the bot token, and saving validates the
+ channel (same guild, text or announcement). The `discord` incoming-webhook
+ adapter stays for alert-only use. For both Discord adapters a 429 is retried
+ no earlier than `retry_after` and does not raise the endpoint failure counter.
+- **Digest**: each transport has its own gate and timestamp
+ (`tg_digest_last_sent_at`, `dc_digest_last_sent_at`). Discord needs the token,
+ the public key and a digest channel.
+- Features on both transports: who-did-what card edit, queue Review (oldest
+ first, Skip), ban with reason and `/unban`, reply with saved replies. In a
+ Telegram group the saved-reply list shows shared presets only. Discord replies
+ use a select menu and a modal (25-option menu, 4000-char modal).
+- Cost rules: no new KV write per interaction (a ban keeps its one session
+ revocation write); every outbound body sets `allowed_mentions: { parse: [] }`.
+
+Operator setup: `docs/discord.md` and `docs/telegram.md`.
+
State-changing endpoints (all under `/admin/api/...`, all require admin
session + Origin allowlist, all write an `audit_log` row before
responding):
@@ -1106,7 +1149,7 @@ personal data** → *Download JSON*, or `GET /admin/api/users/:id/export`
directly. This is the answer to a GDPR Art. 15 / Art. 20 or CCPA
right-to-know request: one file (`garrul-export-`. The reply is ephemeral.
+3. Garrul writes a `discord_links` row (Discord user id to Garrul user id).
+
+If a Garrul user already exists with `provider='discord'` and the clicker's
+Discord id (they signed in with Discord), that counts as linked, with no code.
+Unlink from the same page. A `discord_links` row wins over the sign-in row if
+both exist.
+
+## 6. Commands
+
+All commands are guild commands and every reply is **ephemeral** (only the
+person who ran it sees it).
+
+| Command | Needs | Shows |
+|---|---|---|
+| `/queue` | mod | pending count, open reports, oldest pending, and a **Review** button |
+| `/stats` | mod | totals and 7-day spam rate |
+| `/comment ` | anyone | links your Discord account |
+
+**Review** walks pending comments **oldest first**, one card at a time, with the
+action buttons and **Skip**. The walk keeps no server state; a comment someone
+else moderated mid-walk does not break it.
+
+**Ban** asks for a reason in a modal (the reason lands in the audit log). `/user`
+reads the latest ban entry from the audit log: "Banned — Bot configuration
+
+
+
+
+ DISCORD_BOT_TOKEN${pill(d.botTokenSet)}
+ DISCORD_PUBLIC_KEY${pill(d.publicKeySet)}
+
+ DISCORD_CLIENT_ID${pill(d.clientIdSet, "pending")}
+ Application id, needed to register commands. ${escapeHtml(d.endpointUrl)}`
+ : `Set PUBLIC_BASE_URL to see the endpoint URL.`
+ }
+ DISCORD_BOT_TOKEN and
+ DISCORD_PUBLIC_KEY via wrangler secret put
+ to enable the bot.Server settings
+ Slash commands
+ /queue, /stats, /comment, /user, /unban and /link in your server. Save the server id first.Your linked account
+ Link your Discord account
+ /link code:<code> in your server. The code expires in 10 minutes.chat id here (e.g. -1001234567890 or
@yourchannel) — not a URL. The bot token comes from the
- TELEGRAM_BOT_TOKEN secret.
+ TELEGRAM_BOT_TOKEN secret. For the Discord
+ bot adapter, put the Channel ID here; the bot posts
+ alerts with moderation buttons.
deep link
// instead of manual /start instructions.
TELEGRAM_BOT_USERNAME?: string;
+ // Discord integration (optional; feature is off unless both are set).
+ // DISCORD_BOT_TOKEN — bot token; used for REST calls (post cards, edit
+ // messages, validate channels).
+ // DISCORD_PUBLIC_KEY — application public key (hex); the /discord route
+ // verifies the Ed25519 signature on every interaction.
+ DISCORD_BOT_TOKEN?: string;
+ DISCORD_PUBLIC_KEY?: string;
// Anti-spam (all optional; each feature opts in when its env var is set).
SPAM_PROVIDER?: string;
AKISMET_API_KEY?: string;
@@ -374,6 +383,7 @@ app.route("/admin", admin);
// Top-level (outside /api/*) so it bypasses corsAndCsrf + sessionMiddleware;
// the route authenticates via the Telegram secret-token header instead.
app.route("/telegram", telegram);
+app.route("/discord", discord);
app.get("/", (c) =>
c.text(
@@ -430,6 +440,11 @@ export default {
log.error("scheduled.telegram_digest", { error: String(err) });
}),
);
+ ctx.waitUntil(
+ runDiscordDigest(env).catch((err) => {
+ log.error("scheduled.discord_digest", { error: String(err) });
+ }),
+ );
// Privacy retention. No-ops unless IP_HASH_RETENTION_DAYS (or its
// settings row) is set — off by default, so this costs one cached
// settings read per tick on an instance that hasn't opted in.
diff --git a/src/lib/discord-digest.ts b/src/lib/discord-digest.ts
new file mode 100644
index 00000000..b769532c
--- /dev/null
+++ b/src/lib/discord-digest.ts
@@ -0,0 +1,69 @@
+/**
+ * Daily operator digest posted to one Discord channel.
+ *
+ * Same data as the Telegram digest (collectDigest), its own gate and its own
+ * last-sent key. The cron calls this every tick; it self-gates to about once
+ * a day through `dc_digest_last_sent_at`. Only counts, slugs and ages are
+ * posted, never comment bodies or names.
+ */
+import { getSetting, setSetting } from "../db/queries";
+import type { Bindings } from "../index";
+import { discordApi, discordEnabled } from "./discord";
+import { log } from "./log";
+import { collectDigest, relativeAge } from "./opbot/readouts";
+import { loadDiscordSettings } from "./settings";
+
+// settings key holding the epoch-ms of the last digest post attempt.
+const LAST_SENT_KEY = "dc_digest_last_sent_at";
+// Same cadence as the Telegram digest: slightly under 24h.
+const INTERVAL_MS = 23 * 3600 * 1000;
+
+const renderDigest = async (env: Bindings, now: number): Promise => {
+ const d = await collectDigest(env, now);
+ const base = env.PUBLIC_BASE_URL ? env.PUBLIC_BASE_URL.replace(/\/$/, "") : null;
+
+ const lines: string[] = ["**Garrul daily digest**"];
+ lines.push(
+ `• Pending: **${d.pending}**`,
+ `• Open reports: **${d.openReports}**${
+ d.topFlagged
+ ? ` — most on \`${d.topFlagged.slug.replace(/`/g, "")}\` (${d.topFlagged.count})`
+ : ""
+ }`,
+ `• Spam (7d): **${d.spamPct}%** of ${d.spamTotal}`,
+ `• Banned users: **${d.banned}**`,
+ );
+ if (d.oldestAgeMs !== null) {
+ lines.push(`• Oldest pending: **${relativeAge(now - d.oldestAgeMs, now)}** old`);
+ }
+ if (base) {
+ lines.push("", `[Open moderation queue](${base}/admin/queue)`);
+ }
+ return lines.join("\n");
+};
+
+export const runDiscordDigest = async (env: Bindings, now: number = Date.now()): Promise => {
+ const token = env.DISCORD_BOT_TOKEN;
+ if (!token || !discordEnabled(env)) return;
+
+ // Daily gate. A missing or garbage stored value reads as "never sent".
+ const last = Number(await getSetting(env.DB, LAST_SENT_KEY));
+ if (Number.isFinite(last) && last > 0 && now - last < INTERVAL_MS) return;
+
+ // No channel configured: do nothing and DON'T stamp the clock, so the first
+ // tick after an operator picks a channel posts a digest.
+ const { digestChannelId } = await loadDiscordSettings(env);
+ if (!digestChannelId) return;
+
+ const content = await renderDigest(env, now);
+ const res = await discordApi(token, "POST", `/channels/${digestChannelId}/messages`, {
+ content,
+ allowed_mentions: { parse: [] },
+ });
+ if (!res.ok) log.warn("discord.digest.failed", { status: res.status });
+
+ // Stamp once a post has been attempted, even when it failed, so one bad
+ // channel does not retry every 15 minutes. The next day retries.
+ await setSetting(env.DB, LAST_SENT_KEY, String(now));
+ if (res.ok) log.info("discord.digest.sent", {});
+};
diff --git a/src/lib/discord.ts b/src/lib/discord.ts
new file mode 100644
index 00000000..1e1694b5
--- /dev/null
+++ b/src/lib/discord.ts
@@ -0,0 +1,202 @@
+// Discord helpers for the operator bot: interaction signature verification,
+// a thin REST client and OpCard -> message rendering. No Discord SDK.
+import type { Bindings } from "../index";
+import { log } from "./log";
+import type { OpCard } from "./opbot/cards";
+import { SNOWFLAKE_RE } from "./opbot/codec";
+import {
+ buttonRows,
+ escapeDiscordMentions,
+ sanitizeDiscordDescription,
+} from "./webhook-adapters";
+
+// Re-exported so existing importers keep one Discord entry point.
+export { buttonRows, SNOWFLAKE_RE };
+
+export type DiscordInteraction = {
+ id: string;
+ type: 1 | 2 | 3 | 5;
+ token: string;
+ application_id: string;
+ guild_id?: string;
+ channel_id?: string;
+ member?: {
+ user: { id: string; username: string; global_name?: string | null };
+ roles?: string[];
+ };
+ user?: { id: string };
+ data?: {
+ name?: string;
+ options?: { name: string; value: string }[];
+ custom_id?: string;
+ values?: string[];
+ components?: { components: { custom_id: string; value: string }[] }[];
+ };
+ message?: {
+ id: string;
+ channel_id: string;
+ embeds?: unknown[];
+ flags?: number;
+ };
+};
+
+export const DISCORD_API = "https://discord.com/api/v10";
+export const EPHEMERAL = 64;
+export const TIMESTAMP_WINDOW_S = 300;
+
+const API_TIMEOUT_MS = 5000;
+const EMBED_COLOR = 0x5865f2;
+
+export const discordEnabled = (
+ env: Pick,
+): boolean => Boolean(env.DISCORD_BOT_TOKEN && env.DISCORD_PUBLIC_KEY);
+
+const hexToBytes = (hex: string, len: number): Uint8Array | null => {
+ if (hex.length !== len * 2 || !/^[0-9a-fA-F]+$/.test(hex)) return null;
+ const out = new Uint8Array(new ArrayBuffer(len));
+ for (let i = 0; i < len; i++) {
+ out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
+ }
+ return out;
+};
+
+/** Verify Discord's Ed25519 signature over `timestamp + rawBody`. Never throws. */
+export const verifyDiscordRequest = async (
+ publicKeyHex: string,
+ signatureHex: string | undefined,
+ timestamp: string | undefined,
+ rawBody: string,
+ nowMs = Date.now(),
+): Promise => {
+ try {
+ if (!signatureHex || !timestamp || !/^\d+$/.test(timestamp)) return false;
+ if (Math.abs(nowMs / 1000 - Number(timestamp)) > TIMESTAMP_WINDOW_S) {
+ return false;
+ }
+ const key = hexToBytes(publicKeyHex, 32);
+ const sig = hexToBytes(signatureHex, 64);
+ if (!key || !sig) return false;
+ const pub = await crypto.subtle.importKey(
+ "raw",
+ key,
+ { name: "Ed25519" },
+ false,
+ ["verify"],
+ );
+ return await crypto.subtle.verify(
+ { name: "Ed25519" },
+ pub,
+ sig,
+ new TextEncoder().encode(`${timestamp}${rawBody}`),
+ );
+ } catch {
+ return false;
+ }
+};
+
+// token null: interaction webhooks authenticate by the interaction token in the path.
+export const discordApi = async (
+ token: string | null,
+ method: "GET" | "POST" | "PATCH" | "PUT",
+ path: string,
+ body?: unknown,
+): Promise<{
+ ok: boolean;
+ status: number;
+ json?: unknown;
+ retryAfterMs?: number;
+}> => {
+ const ctrl = new AbortController();
+ const timer = setTimeout(() => ctrl.abort(), API_TIMEOUT_MS);
+ try {
+ const res = await fetch(`${DISCORD_API}${path}`, {
+ method,
+ headers: {
+ ...(token ? { authorization: `Bot ${token}` } : {}),
+ "content-type": "application/json",
+ },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ signal: ctrl.signal,
+ });
+ let json: unknown;
+ try {
+ json = await res.json();
+ } catch {
+ json = undefined;
+ }
+ const out: {
+ ok: boolean;
+ status: number;
+ json?: unknown;
+ retryAfterMs?: number;
+ } = { ok: res.ok, status: res.status, json };
+ if (res.status === 429) {
+ const ra = Number(res.headers.get("retry-after"));
+ if (Number.isFinite(ra) && ra >= 0) out.retryAfterMs = Math.ceil(ra * 1000);
+ }
+ if (!res.ok) log.warn("discord api non-2xx", { status: res.status, method });
+ return out;
+ } catch {
+ log.warn("discord api request failed", { status: 0, method });
+ return { ok: false, status: 0 };
+ } finally {
+ clearTimeout(timer);
+ }
+};
+
+export const cardToMessage = (
+ card: OpCard,
+ extra: string[] = [],
+): {
+ content?: string;
+ embeds: unknown[];
+ components: unknown[];
+ allowed_mentions: { parse: [] };
+} => {
+ const desc = [
+ ...card.lines.map(escapeDiscordMentions),
+ ...(card.snippet ? [`> ${sanitizeDiscordDescription(card.snippet)}`] : []),
+ ].join("\n");
+ const embed: Record = {
+ title: escapeDiscordMentions(card.title).slice(0, 256),
+ description: desc.slice(0, 4000),
+ color: EMBED_COLOR,
+ };
+ if (card.adminUrl) embed.url = card.adminUrl;
+ if (card.doneBy) {
+ embed.fields = [
+ { name: "Done by", value: escapeDiscordMentions(card.doneBy).slice(0, 1024) },
+ ];
+ }
+ return {
+ embeds: [embed],
+ components: buttonRows(card.buttons, card.commentId, extra),
+ allowed_mentions: { parse: [] },
+ };
+};
+
+export const validateDiscordChannel = async (
+ token: string,
+ channelId: string,
+ guildId: string,
+): Promise<
+ | { ok: true }
+ | {
+ ok: false;
+ error:
+ | "channel_not_found"
+ | "channel_forbidden"
+ | "channel_wrong_guild"
+ | "channel_wrong_type";
+ }
+> => {
+ const r = await discordApi(token, "GET", `/channels/${channelId}`);
+ if (r.status === 401 || r.status === 403) return { ok: false, error: "channel_forbidden" };
+ if (!r.ok) return { ok: false, error: "channel_not_found" };
+ const ch = r.json as { type?: number; guild_id?: string } | undefined;
+ if (ch?.guild_id !== guildId) return { ok: false, error: "channel_wrong_guild" };
+ if (ch.type !== 0 && ch.type !== 5) {
+ return { ok: false, error: "channel_wrong_type" };
+ }
+ return { ok: true };
+};
diff --git a/src/lib/moderation.ts b/src/lib/moderation.ts
index 50eaf778..165a2e58 100644
--- a/src/lib/moderation.ts
+++ b/src/lib/moderation.ts
@@ -33,7 +33,7 @@ import { bustTreeCache } from "./tree-cache";
import { fireWebhook, type WebhookEvent } from "./webhook";
/** waitUntil-capable context (Hono's c.executionCtx). */
-type WaitUntilCtx = { waitUntil(p: Promise): void } | undefined;
+export type WaitUntilCtx = { waitUntil(p: Promise): void } | undefined;
export type CommentAction = "approve" | "spam" | "delete" | "restore";
diff --git a/src/lib/opbot/actions.ts b/src/lib/opbot/actions.ts
new file mode 100644
index 00000000..ea0f6eb8
--- /dev/null
+++ b/src/lib/opbot/actions.ts
@@ -0,0 +1,138 @@
+import {
+ type CommentStatus,
+ countOpenReportsByComment,
+ getComment,
+ getUser,
+ latestBanAudit,
+ type User,
+} from "../../db/queries";
+import type { Bindings } from "../../index";
+import { banUser, moderateComment, resolveReports, type WaitUntilCtx } from "../moderation";
+import type { OpAction } from "./codec";
+import type { OpActor } from "./identity";
+
+// Inbound callers are authenticated operators, so the comment-posting default
+// is far too strict. A generous burst still caps a runaway loop or redelivery
+// storm. Keyed per sender (`dc:`), never per IP.
+export const OPBOT_RATE_LIMIT = {
+ short: { max: 10, windowSec: 10 },
+ long: { max: 120, windowSec: 600 },
+};
+
+export type OpCommand = OpAction | "unban";
+
+const ADMIN_ONLY: ReadonlySet = new Set(["ban", "banr", "bsub", "unban"]);
+
+export const requiredRole = (a: OpCommand): "mod" | "admin" =>
+ ADMIN_ONLY.has(a) ? "admin" : "mod";
+
+export const hasRole = (actor: OpActor, need: "mod" | "admin"): boolean =>
+ need === "mod" || actor.role === "admin";
+
+export type ActionError =
+ | "comment_not_found"
+ | "target_is_staff"
+ | "ban_refused"
+ | "not_authorized";
+
+// A Discord-role admin may not ban or unban Garrul staff; only a real Garrul
+// admin can touch another mod/admin.
+export const guardBanTarget = (actor: OpActor, target: User): boolean =>
+ !(actor.adminViaDiscordRole && (target.role === "mod" || target.role === "admin"));
+
+const VERB = {
+ approve: "Approved",
+ spam: "Marked spam",
+ delete: "Deleted",
+ restore: "Restored",
+ resolve: "Reports resolved",
+ ban: "Banned",
+} as const;
+
+export const runOpAction = async (args: {
+ env: Bindings;
+ executionCtx: WaitUntilCtx;
+ actor: OpActor;
+ action: keyof typeof VERB;
+ commentId: string;
+ reason?: string | null;
+ /** Origin the tree-cache key derives from; defaults to PUBLIC_BASE_URL. */
+ reqUrl?: string;
+}): Promise<
+ | { ok: true; status: CommentStatus; doneBy: string; reported: boolean }
+ | { ok: false; error: ActionError }
+> => {
+ const { env, actor, action, commentId } = args;
+ if (!hasRole(actor, requiredRole(action))) return { ok: false, error: "not_authorized" };
+ const adminId = actor.user.id;
+
+ if (action === "resolve") {
+ const res = await resolveReports({ env, adminId, commentId });
+ if (!res.ok) return { ok: false, error: "comment_not_found" };
+ } else if (action === "ban") {
+ const comment = await getComment(env.DB, commentId);
+ if (!comment) return { ok: false, error: "comment_not_found" };
+ const target = await getUser(env.DB, comment.user_id);
+ if (!target) return { ok: false, error: "comment_not_found" };
+ if (!guardBanTarget(actor, target)) return { ok: false, error: "target_is_staff" };
+ const res = await banUser({
+ env,
+ adminId,
+ userId: target.id,
+ banned: true,
+ fromComment: commentId,
+ reason: args.reason ?? null,
+ });
+ if (!res.ok) return { ok: false, error: "ban_refused" };
+ } else {
+ const res = await moderateComment({
+ env,
+ executionCtx: args.executionCtx,
+ reqUrl: args.reqUrl ?? env.PUBLIC_BASE_URL ?? "https://localhost",
+ adminId,
+ commentId,
+ action,
+ reason: args.reason ?? null,
+ });
+ if (!res.ok) return { ok: false, error: "comment_not_found" };
+ }
+
+ const [after, counts] = await Promise.all([
+ getComment(env.DB, commentId),
+ countOpenReportsByComment(env.DB, [commentId]),
+ ]);
+ if (!after) return { ok: false, error: "comment_not_found" };
+ return {
+ ok: true,
+ status: after.status,
+ doneBy: `${VERB[action]} by ${actor.user.name}`,
+ reported: (counts[commentId] ?? 0) > 0,
+ };
+};
+
+export const unbanUser = async (args: {
+ env: Bindings;
+ actor: OpActor;
+ userId: string;
+}): Promise<
+ { ok: true } | { ok: false; error: "not_found" | "target_is_staff" | "not_authorized" }
+> => {
+ const { env, actor } = args;
+ if (!hasRole(actor, requiredRole("unban"))) return { ok: false, error: "not_authorized" };
+ const target = await getUser(env.DB, args.userId);
+ if (!target) return { ok: false, error: "not_found" };
+ if (!guardBanTarget(actor, target)) return { ok: false, error: "target_is_staff" };
+ const res = await banUser({ env, adminId: actor.user.id, userId: args.userId, banned: false });
+ return res.ok ? { ok: true } : { ok: false, error: "not_found" };
+};
+
+export const banState = async (
+ db: D1Database,
+ user: User,
+): Promise<{ banned: false } | { banned: true; reason: string | null; purged: boolean }> => {
+ if (!user.is_banned) return { banned: false };
+ const last = await latestBanAudit(db, user.id);
+ // Banned with no ban row means the audit trail was purged.
+ if (!last) return { banned: true, reason: null, purged: true };
+ return { banned: true, reason: last.reason ?? null, purged: false };
+};
diff --git a/src/lib/opbot/cards.ts b/src/lib/opbot/cards.ts
new file mode 100644
index 00000000..1e8b2e76
--- /dev/null
+++ b/src/lib/opbot/cards.ts
@@ -0,0 +1,104 @@
+import {
+ type Comment,
+ type CommentStatus,
+ countOpenReportsByComment,
+ getUser,
+} from "../../db/queries";
+import type { Bindings } from "../../index";
+import type { OpAction } from "./codec";
+
+export type OpButton = {
+ action: OpAction;
+ label: string;
+ style: "primary" | "secondary" | "success" | "danger";
+};
+
+// All text is plain; each transport escapes for its own markup.
+export type OpCard = {
+ title: string;
+ lines: string[];
+ snippet?: string;
+ doneBy?: string;
+ adminUrl?: string;
+ commentId: string;
+ buttons: OpButton[][];
+};
+
+/** First `max` code points of `s`; unlike `slice` it never splits a surrogate pair. */
+export const truncateCodePoints = (s: string, max: number): string =>
+ s.length <= max ? s : Array.from(s).slice(0, max).join("");
+
+/** `truncateCodePoints` plus a trailing ellipsis when something was cut. */
+export const ellipsize = (s: string, max: number): string => {
+ const cut = truncateCodePoints(s, max);
+ return cut.length < s.length ? `${cut}…` : s;
+};
+
+export const relativeAge = (since: number, now: number): string => {
+ const ms = Math.max(0, now - since);
+ const mins = Math.floor(ms / 60000);
+ if (mins < 60) return `${mins}m`;
+ const hrs = Math.floor(mins / 60);
+ if (hrs < 24) return `${hrs}h`;
+ return `${Math.floor(hrs / 24)}d`;
+};
+
+export const buttonsFor = (
+ status: CommentStatus | null | undefined,
+ opts: { reported: boolean; queue?: boolean; banLabel?: "ban" | "banr" },
+): OpButton[][] => {
+ // Unknown status falls back to the full triage: an idempotent Approve beats
+ // hiding a needed action.
+ let first: OpButton[];
+ if (status === "spam") {
+ first = [{ action: "restore", label: "✅ Not spam", style: "success" }];
+ } else if (status === "approved") {
+ first = [{ action: "spam", label: "🚫 Spam", style: "danger" }];
+ } else {
+ first = [
+ { action: "approve", label: "✅ Approve", style: "success" },
+ { action: "spam", label: "🚫 Spam", style: "danger" },
+ ];
+ }
+ const second: OpButton[] = [
+ { action: "delete", label: "🗑 Delete", style: "danger" },
+ { action: opts.banLabel ?? "ban", label: "⛔ Ban author", style: "danger" },
+ { action: "reply", label: "↩️ Reply", style: "primary" },
+ ];
+ if (opts.reported) {
+ second.push({
+ action: "resolve",
+ label: "📁 Resolve reports",
+ style: "secondary",
+ });
+ }
+ const rows = [first, second];
+ if (opts.queue) {
+ rows.push([{ action: "nx", label: "⏭ Next", style: "secondary" }]);
+ }
+ return rows;
+};
+
+export const renderQueueCard = async (
+ env: Bindings,
+ comment: Comment,
+): Promise => {
+ const [author, counts] = await Promise.all([
+ getUser(env.DB, comment.user_id),
+ countOpenReportsByComment(env.DB, [comment.id]),
+ ]);
+ const openReports = counts[comment.id] ?? 0;
+ return {
+ title: "Pending comment",
+ lines: [
+ `Author: ${author?.name ?? "unknown"}`,
+ `On: ${comment.post_slug} · ${relativeAge(comment.created_at, Date.now())} ago`,
+ ],
+ snippet: ellipsize(comment.body_md, 200),
+ ...(env.PUBLIC_BASE_URL && {
+ adminUrl: `${env.PUBLIC_BASE_URL.replace(/\/$/, "")}/admin/comments/${encodeURIComponent(comment.id)}`,
+ }),
+ commentId: comment.id,
+ buttons: buttonsFor(comment.status, { reported: openReports > 0, queue: true }),
+ };
+};
diff --git a/src/lib/opbot/codec.ts b/src/lib/opbot/codec.ts
new file mode 100644
index 00000000..c95fd4da
--- /dev/null
+++ b/src/lib/opbot/codec.ts
@@ -0,0 +1,67 @@
+// Shared payload codec for operator-bot buttons (Telegram callback_data and
+// Discord custom_id). Format: "g::[:...]".
+// `banr` = ban with reason prompt/modal; `reply` = open picker; `sr` =
+// Telegram saved reply chosen; `rc` = Telegram custom reply prompt; `pick` =
+// Discord picker select; `rsub` / `bsub` = Discord reply / ban modal submit;
+// `rv` = start queue review (comment id "-"); `nx` = next/skip in queue.
+
+export const OP_ACTIONS = [
+ "approve",
+ "spam",
+ "delete",
+ "restore",
+ "ban",
+ "banr",
+ "resolve",
+ "reply",
+ "sr",
+ "rc",
+ "pick",
+ "rsub",
+ "bsub",
+ "rv",
+ "nx",
+] as const;
+
+export type OpAction = (typeof OP_ACTIONS)[number];
+
+export type Transport = "telegram" | "discord";
+
+// Telegram counts UTF-8 bytes, Discord counts characters.
+export const PAYLOAD_MAX: Record = {
+ telegram: 64,
+ discord: 100,
+};
+
+const PREFIX = "g";
+
+const size = (t: Transport, s: string): number =>
+ t === "telegram" ? new TextEncoder().encode(s).length : s.length;
+
+export const encodePayload = (
+ t: Transport,
+ action: OpAction,
+ commentId: string,
+ extra: string[] = [],
+): string => {
+ const out = [PREFIX, action, commentId, ...extra].join(":");
+ if (size(t, out) > PAYLOAD_MAX[t]) {
+ throw new RangeError(`${t} payload exceeds ${PAYLOAD_MAX[t]}: ${out}`);
+ }
+ return out;
+};
+
+export const decodePayload = (
+ data: string | undefined,
+): { action: OpAction; commentId: string; extra: string[] } | null => {
+ if (typeof data !== "string") return null;
+ const [prefix, action, commentId, ...extra] = data.split(":");
+ if (prefix !== PREFIX) return null;
+ if (!OP_ACTIONS.includes(action as OpAction)) return null;
+ if (!commentId) return null;
+ if ((action === "rv") !== (commentId === "-")) return null;
+ return { action: action as OpAction, commentId, extra };
+};
+
+/** A Discord snowflake id. Leaf constant so settings and webhook code need no Discord module. */
+export const SNOWFLAKE_RE = /^\d{17,20}$/;
diff --git a/src/lib/opbot/identity.ts b/src/lib/opbot/identity.ts
new file mode 100644
index 00000000..8a0a280f
--- /dev/null
+++ b/src/lib/opbot/identity.ts
@@ -0,0 +1,87 @@
+import {
+ getDiscordLinkByDiscordUser,
+ getTelegramLinkByTgUser,
+ getUser,
+ getUserByProvider,
+ upsertOauthUser,
+ type User,
+} from "../../db/queries";
+
+// `adminViaDiscordRole` marks an admin whose authority came from a Discord
+// role rather than their Garrul `users.role`; the ban-target guard keys on it.
+export type OpActor = {
+ user: User;
+ role: "mod" | "admin";
+ adminViaDiscordRole: boolean;
+};
+
+export type ActorRefusal = "not_linked" | "not_authorized" | "banned" | "wrong_guild";
+
+export type DiscordAuthConfig = {
+ guildId: string;
+ modRoleId: string;
+ adminRoleId: string;
+};
+
+type Resolution = { ok: true; actor: OpActor } | { ok: false; reason: ActorRefusal };
+
+const RANK = { user: 0, mod: 1, admin: 2 } as const;
+type Rank = keyof typeof RANK;
+
+// An erased row is never an actor, even if a lookup still finds it.
+const live = (u: User | null): User | null => (u && !u.erased_at ? u : null);
+
+export const resolveTelegramActor = async (
+ db: D1Database,
+ tgUserId: string,
+): Promise => {
+ const link = await getTelegramLinkByTgUser(db, tgUserId);
+ const user = link ? live(await getUser(db, link.user_id)) : null;
+ if (!user) return { ok: false, reason: "not_linked" };
+ if (user.is_banned) return { ok: false, reason: "banned" };
+ if (user.role === "user") return { ok: false, reason: "not_authorized" };
+ return { ok: true, actor: { user, role: user.role, adminViaDiscordRole: false } };
+};
+
+/**
+ * Spec §2 identity precedence: discord_links user (A), else the
+ * provider='discord' row (B), else a new role-holder row. Either candidate
+ * being banned refuses the action; the core never falls back past a ban.
+ */
+export const resolveDiscordActor = async (
+ db: D1Database,
+ cfg: DiscordAuthConfig,
+ i: { guildId?: string | undefined; discordUserId: string; displayName: string; roles?: string[] | undefined },
+): Promise => {
+ if (!i.guildId || i.guildId !== cfg.guildId) return { ok: false, reason: "wrong_guild" };
+
+ const link = await getDiscordLinkByDiscordUser(db, i.discordUserId);
+ const a = link ? live(await getUser(db, link.user_id)) : null;
+ const b = live(await getUserByProvider(db, "discord", i.discordUserId));
+ if (a?.is_banned || b?.is_banned) return { ok: false, reason: "banned" };
+
+ const roles = i.roles ?? [];
+ // An empty configured id never matches (unset role = feature off).
+ const grant: Rank =
+ cfg.adminRoleId && roles.includes(cfg.adminRoleId)
+ ? "admin"
+ : cfg.modRoleId && roles.includes(cfg.modRoleId)
+ ? "mod"
+ : "user";
+
+ let user = a ?? b;
+ if (!user) {
+ if (grant === "user") return { ok: false, reason: "not_linked" };
+ // Only here: upsertOauthUser's update branch would null an existing avatar.
+ user = await upsertOauthUser(db, "discord", i.discordUserId, i.displayName, null, null, new Set());
+ // Guard: erasure nulls provider_id, but never act as an erased row if one still holds the key.
+ if (user.erased_at) return { ok: false, reason: "not_linked" };
+ }
+
+ const effective: Rank = RANK[grant] > RANK[user.role] ? grant : user.role;
+ if (effective === "user") return { ok: false, reason: "not_authorized" };
+ return {
+ ok: true,
+ actor: { user, role: effective, adminViaDiscordRole: effective === "admin" && user.role !== "admin" },
+ };
+};
diff --git a/src/lib/opbot/link-token.ts b/src/lib/opbot/link-token.ts
new file mode 100644
index 00000000..a394bdf7
--- /dev/null
+++ b/src/lib/opbot/link-token.ts
@@ -0,0 +1,41 @@
+import { randomHex } from "../oauth";
+
+// One-time link tokens issued in the admin panel and redeemed by a bot command.
+// Stored in OAUTH_STATE under a per-transport prefix so a Telegram token can
+// never be redeemed for Discord and vice versa.
+const LINK_TOKEN_TTL = 600; // 10 minutes
+const LINK_TOKEN_RE = /^[0-9a-f]{48}$/;
+const linkKey = (prefix: LinkPrefix, token: string): string => `${prefix}:link:${token}`;
+
+export type LinkPrefix = "tg" | "dc";
+
+export const issueLinkToken = async (
+ kv: KVNamespace,
+ prefix: LinkPrefix,
+ user_id: string,
+): Promise => {
+ const token = randomHex(24);
+ await kv.put(
+ linkKey(prefix, token),
+ JSON.stringify({ user_id, created_at: Date.now() }),
+ { expirationTtl: LINK_TOKEN_TTL },
+ );
+ return token;
+};
+
+export const consumeLinkToken = async (
+ kv: KVNamespace,
+ prefix: LinkPrefix,
+ token: string,
+): Promise => {
+ if (!LINK_TOKEN_RE.test(token)) return null;
+ const raw = await kv.get(linkKey(prefix, token));
+ if (!raw) return null;
+ await kv.delete(linkKey(prefix, token)); // one-time use
+ try {
+ const parsed = JSON.parse(raw) as { user_id?: string };
+ return parsed.user_id ?? null;
+ } catch {
+ return null;
+ }
+};
diff --git a/src/lib/opbot/readouts.ts b/src/lib/opbot/readouts.ts
new file mode 100644
index 00000000..fc9225b9
--- /dev/null
+++ b/src/lib/opbot/readouts.ts
@@ -0,0 +1,85 @@
+// Plain-data readouts shared by the Telegram and Discord bots. Each transport
+// formats the result for its own markup.
+import {
+ adminOldestPending,
+ adminOpenReportSummary,
+ adminSpamRate,
+ adminStats,
+ type Comment,
+ countOpenReportsByComment,
+ getComment,
+ getUser,
+ type User,
+} from "../../db/queries";
+import type { Bindings } from "../../index";
+import { banState } from "./actions";
+
+// relativeAge lives in cards.ts: cards must not import this file (cycle through
+// actions -> moderation -> webhook -> webhook-adapters -> cards).
+export { relativeAge } from "./cards";
+
+export const readQueue = async (env: Bindings) => {
+ const [stats, oldest, reports] = await Promise.all([
+ adminStats(env.DB),
+ adminOldestPending(env.DB),
+ adminOpenReportSummary(env.DB),
+ ]);
+ return {
+ pending: stats.pending_comments,
+ reported: reports.open,
+ spam: stats.spam_comments,
+ topFlagged: reports.top,
+ oldest,
+ };
+};
+
+export const readStats = async (env: Bindings) => {
+ const [stats, spam7d] = await Promise.all([adminStats(env.DB), adminSpamRate(env.DB, 7)]);
+ return {
+ totalComments: stats.total_comments,
+ pending: stats.pending_comments,
+ totalUsers: stats.total_users,
+ banned: stats.banned_users,
+ spam7d: { spam: spam7d.spam, total: spam7d.total },
+ };
+};
+
+export const readComment = async (
+ env: Bindings,
+ id: string,
+): Promise<{ comment: Comment; authorName: string; openReports: number } | null> => {
+ const comment = await getComment(env.DB, id);
+ if (!comment) return null;
+ const [author, counts] = await Promise.all([
+ getUser(env.DB, comment.user_id),
+ countOpenReportsByComment(env.DB, [id]),
+ ]);
+ return { comment, authorName: author?.name ?? "unknown", openReports: counts[id] ?? 0 };
+};
+
+export const readUser = async (
+ env: Bindings,
+ id: string,
+): Promise<{ user: User; ban: Awaited> } | null> => {
+ const user = await getUser(env.DB, id);
+ if (!user) return null;
+ return { user, ban: await banState(env.DB, user) };
+};
+
+export const collectDigest = async (env: Bindings, now: number) => {
+ const [stats, reports, spam, oldest] = await Promise.all([
+ adminStats(env.DB),
+ adminOpenReportSummary(env.DB),
+ adminSpamRate(env.DB, 7),
+ adminOldestPending(env.DB),
+ ]);
+ return {
+ pending: stats.pending_comments,
+ openReports: reports.open,
+ topFlagged: reports.top,
+ spamPct: spam.total > 0 ? Math.round((spam.spam / spam.total) * 1000) / 10 : 0,
+ spamTotal: spam.total,
+ banned: stats.banned_users,
+ oldestAgeMs: oldest ? Math.max(0, now - oldest.created_at) : null,
+ };
+};
diff --git a/src/lib/opbot/reply.ts b/src/lib/opbot/reply.ts
new file mode 100644
index 00000000..4704ddae
--- /dev/null
+++ b/src/lib/opbot/reply.ts
@@ -0,0 +1,190 @@
+// Moderator reply, shared by the admin route and the operator bots. Moved out
+// of routes/admin.ts verbatim; the route keeps request parsing and maps
+// ReplyError back to its HTTP contract.
+
+import {
+ applyReplyVars,
+ type ReplyVars,
+} from "../../admin-ui/components/reply-vars";
+import {
+ adminInsertAudit,
+ type Comment,
+ enqueueNotificationsForPost,
+ getComment,
+ getPost,
+ getSavedReply,
+ getUser,
+ insertComment,
+ listSavedRepliesForUser,
+ type SavedReply,
+ type User,
+} from "../../db/queries";
+import type { Bindings } from "../../index";
+import { log } from "../log";
+import { CURRENT_RENDERER_VERSION, renderMarkdown, validateBody } from "../markdown";
+import type { WaitUntilCtx } from "../moderation";
+import { bustTreeCache } from "../tree-cache";
+import { MAX_REPLY_DEPTH } from "../tree";
+import { fireWebhook } from "../webhook";
+
+export type ReplyError =
+ | "comment_not_found"
+ | "comment_deleted"
+ | "thread_too_deep"
+ | "body_required"
+ | "body_too_long"
+ | "saved_reply_not_visible";
+
+/** Operator-facing refusal text shared by the Telegram and Discord bots (English by design). */
+export const replyRefusalText = (e: ReplyError, max?: number): string =>
+ e === "comment_not_found"
+ ? "That comment no longer exists."
+ : e === "comment_deleted"
+ ? "That comment was deleted."
+ : e === "thread_too_deep"
+ ? "That thread is too deep to reply to. Reply higher up from the dashboard."
+ : e === "body_too_long"
+ ? `Reply too long (max ${max} characters).`
+ : e === "body_required"
+ ? "Reply text is empty."
+ : "That saved reply isn't available here.";
+
+type ChatKind = { chat: "group" | "private" };
+
+export const presetVisible = (
+ preset: SavedReply,
+ actorId: string,
+ ctx: ChatKind,
+): boolean =>
+ preset.scope === "shared" ||
+ (ctx.chat === "private" && preset.owner_id === actorId);
+
+export const pickerPresets = async (
+ db: D1Database,
+ actorId: string,
+ ctx: ChatKind,
+): Promise =>
+ (await listSavedRepliesForUser(db, actorId)).filter((p) =>
+ presetVisible(p, actorId, ctx),
+ );
+
+export const expandPreset = (body: string, vars: ReplyVars): string =>
+ applyReplyVars(body, vars);
+
+/** Same values the admin composer resolves client-side; missing stays undefined. */
+export const presetVars = async (
+ env: Bindings,
+ commentId: string,
+ actor: User,
+): Promise => {
+ const comment = await getComment(env.DB, commentId);
+ const author = comment ? await getUser(env.DB, comment.user_id) : null;
+ const post = comment ? await getPost(env.DB, comment.post_slug) : null;
+ return {
+ name: author?.name,
+ post: comment ? post?.title || comment.post_slug : undefined,
+ mod: actor.name,
+ };
+};
+
+export const postModeratorReply = async (args: {
+ env: Bindings;
+ executionCtx?: WaitUntilCtx | undefined;
+ reqUrl: string;
+ actor: User;
+ commentId: string;
+ bodyMd: string;
+ savedReplyId?: string | null | undefined;
+ notify?: boolean | null | undefined;
+ asStaff?: boolean | null | undefined;
+}): Promise<
+ | { ok: true; id: string; notified: boolean }
+ | { ok: false; error: ReplyError; max?: number | undefined }
+> => {
+ const { env, actor } = args;
+ const valid = validateBody(args.bodyMd);
+ if (!valid.ok) {
+ return valid.key === "err.body.too_long"
+ ? { ok: false, error: "body_too_long", max: valid.max }
+ : { ok: false, error: "body_required" };
+ }
+
+ // Provenance has to be a reply the actor can see, or the audit row could
+ // name someone else's private saved reply.
+ let savedReplyId: string | null = null;
+ if (args.savedReplyId != null) {
+ const source = await getSavedReply(env.DB, args.savedReplyId);
+ if (!source || (source.owner_id !== actor.id && source.scope !== "shared")) {
+ return { ok: false, error: "saved_reply_not_visible" };
+ }
+ savedReplyId = source.id;
+ }
+
+ const target: Comment | null = await getComment(env.DB, args.commentId);
+ if (!target) return { ok: false, error: "comment_not_found" };
+ if (target.status === "deleted") return { ok: false, error: "comment_deleted" };
+ // The nesting cap applies to moderators too: the O(N^2) tree-assembly cost
+ // it guards doesn't care who created the chain.
+ const depth = target.depth + 1;
+ if (depth > MAX_REPLY_DEPTH) return { ok: false, error: "thread_too_deep" };
+
+ const inserted = await insertComment(env.DB, {
+ post_slug: target.post_slug,
+ parent_id: target.id,
+ user_id: actor.id,
+ body_md: valid.body,
+ body_html: renderMarkdown(valid.body),
+ renderer_version: CURRENT_RENDERER_VERSION,
+ status: "approved",
+ ip_hash: null,
+ user_agent: null,
+ depth,
+ as_staff: args.asStaff ?? true,
+ });
+
+ // Default on: followers of the thread hear about a mod reply the same way
+ // they hear about a reader's reply.
+ const notify = args.notify ?? true;
+ await adminInsertAudit(env.DB, {
+ admin_id: actor.id,
+ action: "comment.reply",
+ target_kind: "comment",
+ target_id: inserted.id,
+ meta: {
+ from_saved_reply: savedReplyId != null,
+ saved_reply_id: savedReplyId,
+ parent_id: target.id,
+ post_slug: target.post_slug,
+ // The operator's choice, not a delivery count: the fan-out is deferred.
+ notify_subscribers: notify,
+ },
+ });
+ await bustTreeCache(env, args.reqUrl, target.post_slug);
+ fireWebhook(env, args.executionCtx, {
+ event: "comment.posted",
+ comment_id: inserted.id,
+ post_slug: target.post_slug,
+ user_id: actor.id,
+ ts: inserted.created_at,
+ });
+
+ if (notify) {
+ const fanout = (async () => {
+ // Skip the actor's own address: being emailed about your own comment
+ // reads as a bug.
+ const count = await enqueueNotificationsForPost(
+ env.DB,
+ target.post_slug,
+ inserted.id,
+ actor.email?.toLowerCase() ?? null,
+ );
+ log.info("notify.enqueued", { count, post_slug: target.post_slug });
+ })();
+ // Always wait for the enqueue without a waitUntil context, or the runtime
+ // can cancel the orphan promise once the response settles.
+ if (args.executionCtx) args.executionCtx.waitUntil(fanout);
+ else await fanout;
+ }
+
+ return { ok: true, id: inserted.id, notified: notify };
+};
diff --git a/src/lib/settings.ts b/src/lib/settings.ts
index 6032a564..a903e9ec 100644
--- a/src/lib/settings.ts
+++ b/src/lib/settings.ts
@@ -25,6 +25,7 @@ import { COMMENT_SORTS, getAllSettings } from "../db/queries";
import { LOCALES } from "../i18n";
import { AUTO_LOCALE } from "../i18n/negotiate";
import { DEFAULT_REACTION_KINDS, REACTION_KIND_SET } from "../widget/reactions";
+import { SNOWFLAKE_RE } from "./opbot/codec";
import { CLEF_MODELS } from "./spam/workers-ai";
import { MAX_DEPTH } from "./tree";
@@ -684,12 +685,36 @@ const resolve = (
return out;
};
+/**
+ * Discord operator-bot wiring. Deliberately outside TEXT_KEYS/TEXTS so the
+ * /admin/settings save and reset paths never touch these keys.
+ */
+export interface ResolvedDiscord {
+ readonly guildId: string;
+ readonly modRoleId: string;
+ readonly adminRoleId: string;
+ readonly digestChannelId: string;
+}
+
+const snowflake = (dbSettings: Record, key: string): string => {
+ const v = (dbSettings[key] ?? "").trim();
+ return SNOWFLAKE_RE.test(v) ? v : "";
+};
+
+const resolveDiscord = (dbSettings: Record): ResolvedDiscord => ({
+ guildId: snowflake(dbSettings, "discord_guild_id"),
+ modRoleId: snowflake(dbSettings, "discord_mod_role_id"),
+ adminRoleId: snowflake(dbSettings, "discord_admin_role_id"),
+ digestChannelId: snowflake(dbSettings, "discord_digest_channel_id"),
+});
+
/** Every resolved settings group, as held in the per-isolate memo. */
export interface ResolvedSettings {
readonly flags: ResolvedFlags;
readonly numbers: ResolvedNumbers;
readonly strings: ResolvedStrings;
readonly texts: ResolvedTexts;
+ readonly discord: ResolvedDiscord;
}
/** Read D1 and resolve every group. */
@@ -700,6 +725,7 @@ const deriveSettings = async (env: Bindings): Promise => {
numbers: resolveNumbers(env, dbSettings),
strings: resolveStrings(env, dbSettings),
texts: resolveTexts(env, dbSettings),
+ discord: resolveDiscord(dbSettings),
};
};
@@ -793,3 +819,7 @@ export const bustSettingsCache = (env: Bindings): Promise => {
inFlight = null;
return env.TREE_CACHE.delete(CACHE_KEY_RESOLVED).catch(() => {});
};
+
+export const loadDiscordSettings = async (
+ env: Bindings,
+): Promise => (await loadSettings(env)).discord;
diff --git a/src/lib/telegram-digest.ts b/src/lib/telegram-digest.ts
index 6808d534..d6f9df6d 100644
--- a/src/lib/telegram-digest.ts
+++ b/src/lib/telegram-digest.ts
@@ -18,16 +18,10 @@
* only counts, slugs, and ages — so this stays clear of the no-PII logging and
* messaging conventions.
*/
-import {
- adminOldestPending,
- adminOpenReportSummary,
- adminSpamRate,
- adminStats,
- getSetting,
- listTelegramDigestLinks,
- setSetting,
-} from "../db/queries";
+import { getSetting, listTelegramDigestLinks, setSetting } from "../db/queries";
+import type { Bindings } from "../index";
import { log } from "./log";
+import { collectDigest, relativeAge } from "./opbot/readouts";
import { sendMessage } from "./telegram";
type DigestEnv = {
@@ -53,46 +47,30 @@ const escapeTg = (s: string): string =>
.replace(/"/g, """)
.replace(/'/g, "'");
-const relativeAge = (since: number, now: number): string => {
- const ms = Math.max(0, now - since);
- const mins = Math.floor(ms / 60000);
- if (mins < 60) return `${mins}m`;
- const hrs = Math.floor(mins / 60);
- if (hrs < 24) return `${hrs}h`;
- return `${Math.floor(hrs / 24)}d`;
-};
-
const adminBase = (env: DigestEnv): string | null =>
env.PUBLIC_BASE_URL ? env.PUBLIC_BASE_URL.replace(/\/$/, "") : null;
const renderDigest = async (env: DigestEnv, now: number): Promise => {
- const [stats, reports, spam, oldest] = await Promise.all([
- adminStats(env.DB),
- adminOpenReportSummary(env.DB),
- adminSpamRate(env.DB, 7),
- adminOldestPending(env.DB),
- ]);
+ const d = await collectDigest(env as Bindings, now);
const base = adminBase(env);
- const pct =
- spam.total > 0 ? Math.round((spam.spam / spam.total) * 1000) / 10 : 0;
const lines: string[] = ["Garrul daily digest"];
lines.push(
- `• Pending: ${stats.pending_comments}`,
- `• Open reports: ${reports.open}${
- reports.top
- ? ` — most on ${escapeTg(reports.top.slug)} (${reports.top.count})`
+ `• Pending: ${d.pending}`,
+ `• Open reports: ${d.openReports}${
+ d.topFlagged
+ ? ` — most on ${escapeTg(d.topFlagged.slug)} (${d.topFlagged.count})`
: ""
}`,
- `• Spam (7d): ${pct}% of ${spam.total}`,
- `• Banned users: ${stats.banned_users}`,
+ `• Spam (7d): ${d.spamPct}% of ${d.spamTotal}`,
+ `• Banned users: ${d.banned}`,
);
- if (oldest) {
+ if (d.oldestAgeMs !== null) {
lines.push(
- `• Oldest pending: ${relativeAge(oldest.created_at, now)} old`,
+ `• Oldest pending: ${relativeAge(now - d.oldestAgeMs, now)} old`,
);
}
diff --git a/src/lib/telegram.ts b/src/lib/telegram.ts
index 2f8a0bba..54e88c05 100644
--- a/src/lib/telegram.ts
+++ b/src/lib/telegram.ts
@@ -16,6 +16,13 @@
* token at call time.
*/
import { log } from "./log";
+import { buttonsFor, type OpButton } from "./opbot/cards";
+import {
+ type OpAction,
+ PAYLOAD_MAX,
+ decodePayload,
+ encodePayload,
+} from "./opbot/codec";
import type { CommentStatus } from "../db/queries";
import type { WebhookEvent } from "./webhook";
@@ -45,6 +52,7 @@ export type TgMessage = {
chat: TgChat;
from?: TgUser;
text?: string;
+ reply_to_message?: TgMessage;
};
export type TgCallbackQuery = {
@@ -99,40 +107,42 @@ const timingSafeEqual = (a: string, b: string): boolean => {
// under the cap. Ban targets the comment too; the handler resolves the author
// from the comment so we never need to pack a second id.
-export type TgAction =
- | "approve"
- | "spam"
- | "delete"
- | "restore"
- | "ban"
- | "resolve";
+export type TgAction = OpAction;
-const CALLBACK_PREFIX = "g";
-const TG_ACTIONS: readonly TgAction[] = [
+export const CALLBACK_DATA_MAX = PAYLOAD_MAX.telegram;
+
+export const encodeCallback = (action: TgAction, commentId: string): string =>
+ encodePayload("telegram", action, commentId);
+
+// Actions the Telegram route handles today. Later tasks widen this list as
+// they add handlers; anything else decodes to null.
+const TG_HANDLED: readonly OpAction[] = [
"approve",
"spam",
"delete",
"restore",
"ban",
+ "banr",
"resolve",
-] as const;
+ "rv",
+ "nx",
+ "reply",
+ "sr",
+ "rc",
+];
-export const CALLBACK_DATA_MAX = 64;
-
-export const encodeCallback = (action: TgAction, commentId: string): string =>
- `${CALLBACK_PREFIX}:${action}:${commentId}`;
+// The bot's own user id is the numeric part of its token (":").
+export const botIdFromToken = (token: string): number | null => {
+ const n = Number(token.split(":")[0]);
+ return Number.isInteger(n) && n > 0 ? n : null;
+};
export const decodeCallback = (
data: string | undefined,
): { action: TgAction; commentId: string } | null => {
- if (typeof data !== "string") return null;
- const parts = data.split(":");
- if (parts.length !== 3) return null;
- const [prefix, action, commentId] = parts;
- if (prefix !== CALLBACK_PREFIX) return null;
- if (!TG_ACTIONS.includes(action as TgAction)) return null;
- if (!commentId) return null;
- return { action: action as TgAction, commentId };
+ const d = decodePayload(data);
+ if (!d || !TG_HANDLED.includes(d.action)) return null;
+ return { action: d.action, commentId: d.commentId };
};
// --------------------------- Inline keyboard ------------------------------
@@ -148,38 +158,34 @@ export const decodeCallback = (
export type InlineButton = { text: string; callback_data: string };
+export const toInlineKeyboard = (
+ rows: OpButton[][],
+ commentId: string,
+ extra?: string[],
+): { inline_keyboard: InlineButton[][] } => ({
+ inline_keyboard: rows.map((r) =>
+ r.flatMap((b) => {
+ const button = (action: OpButton["action"], text: string) => ({
+ text,
+ callback_data: encodePayload("telegram", action, commentId, extra),
+ });
+ // Telegram-only: a typed ban reason sits right after plain Ban.
+ return b.action === "ban"
+ ? [button("ban", b.label), button("banr", "⛔ Ban with reason")]
+ : [button(b.action, b.label)];
+ }),
+ ),
+});
+
export const moderationKeyboard = (
event: WebhookEvent,
commentId: string,
status?: CommentStatus | null,
-): { inline_keyboard: InlineButton[][] } => {
- const btn = (text: string, action: TgAction): InlineButton => ({
- text,
- callback_data: encodeCallback(action, commentId),
- });
-
- // Fall back to the full triage when status is unknown (comment row was
- // unavailable at render time) — better to offer an idempotent Approve than
- // to hide a needed action.
- let firstRow: InlineButton[];
- if (status === "spam") {
- firstRow = [btn("✅ Not spam", "restore")];
- } else if (status === "approved") {
- firstRow = [btn("🚫 Spam", "spam")];
- } else {
- firstRow = [btn("✅ Approve", "approve"), btn("🚫 Spam", "spam")];
- }
-
- const secondRow: InlineButton[] = [
- btn("🗑 Delete", "delete"),
- btn("⛔ Ban author", "ban"),
- ];
- if (event === "comment.reported") {
- secondRow.push(btn("📁 Resolve reports", "resolve"));
- }
-
- return { inline_keyboard: [firstRow, secondRow] };
-};
+): { inline_keyboard: InlineButton[][] } =>
+ toInlineKeyboard(
+ buttonsFor(status, { reported: event === "comment.reported" }),
+ commentId,
+ );
// ------------------------------ API client --------------------------------
//
@@ -225,7 +231,13 @@ export const sendMessage = (
chatId: string | number,
text: string,
opts: {
- replyMarkup?: { inline_keyboard: InlineButton[][] };
+ replyMarkup?:
+ | { inline_keyboard: InlineButton[][] }
+ | {
+ force_reply: true;
+ selective: true;
+ input_field_placeholder?: string;
+ };
disablePreview?: boolean;
} = {},
): Promise =>
@@ -247,13 +259,14 @@ export const answerCallbackQuery = (
...(text ? { text } : {}),
});
-// Replace a message's text + strip its keyboard after an action resolves, so
-// the buttons can't be tapped twice and the message reflects the outcome.
+// Replace a message's text after an action resolves. Without replyMarkup the
+// keyboard is stripped; with it, the keyboard for the new status is shown.
export const editMessageText = (
token: string,
chatId: string | number,
messageId: number,
text: string,
+ opts: { replyMarkup?: { inline_keyboard: InlineButton[][] } } = {},
): Promise =>
callTelegram(token, "editMessageText", {
chat_id: chatId,
@@ -261,4 +274,5 @@ export const editMessageText = (
text,
parse_mode: "HTML",
disable_web_page_preview: true,
+ ...(opts.replyMarkup ? { reply_markup: opts.replyMarkup } : {}),
});
diff --git a/src/lib/webhook-adapters.ts b/src/lib/webhook-adapters.ts
index 8e595937..5f4a6cbc 100644
--- a/src/lib/webhook-adapters.ts
+++ b/src/lib/webhook-adapters.ts
@@ -33,6 +33,8 @@
*/
import type { CommentStatus } from "../db/queries";
import { getComment, getPost, getUser } from "../db/queries";
+import { buttonsFor, type OpButton } from "./opbot/cards";
+import { encodePayload } from "./opbot/codec";
import { moderationKeyboard } from "./telegram";
import type { WebhookEvent, WebhookPayload } from "./webhook";
@@ -197,7 +199,7 @@ const slackSafeUrl = (url: string): boolean => !/[<>|]/.test(url);
// Inserting a zero-width space breaks the trigger while keeping the
// text legible. (Embeds don't fire mentions, but this is cheap defense
// in depth and keeps the rendered text tidy.)
-const escapeDiscordMentions = (s: string): string =>
+export const escapeDiscordMentions = (s: string): string =>
s
.replace(/@(everyone|here)/gi, "@$1")
.replace(/<@([!&]?\d+)>/g, "<@$1>");
@@ -211,7 +213,7 @@ const escapeDiscordMentions = (s: string): string =>
// would become "\\[x\](url)" — Discord renders "\\" as a literal
// backslash, leaving the "[" unescaped and the masked link live again.
// Escaping "\" → "\\" before the brackets closes that bypass.
-const sanitizeDiscordDescription = (s: string): string =>
+export const sanitizeDiscordDescription = (s: string): string =>
escapeDiscordMentions(s)
.replace(/\\/g, "\\\\")
.replace(/[[\]]/g, "\\$&");
@@ -246,13 +248,10 @@ export const renderSlackBody = async (
return JSON.stringify({ text });
};
-export const renderDiscordBody = async (
- db: WebhookAdapterDb,
+const discordEmbed = (
+ ctx: Ctx,
payload: WebhookPayload,
- opts: AdapterOpts = {},
-): Promise => {
- const ctx = await loadContext(db, payload, opts);
-
+): Record => {
// Wrap the destination in <…> so Discord treats it as a literal URL:
// a bare URL containing ")" (e.g. a "/wiki/Foo_(bar)" page link) would
// otherwise terminate the markdown link early. The URLs are already
@@ -277,7 +276,58 @@ export const renderDiscordBody = async (
embed.fields = [{ name: "Links", value: links.join(" · ") }];
}
- return JSON.stringify({ embeds: [embed] });
+ return embed;
+};
+
+export const renderDiscordBody = async (
+ db: WebhookAdapterDb,
+ payload: WebhookPayload,
+ opts: AdapterOpts = {},
+): Promise => {
+ const ctx = await loadContext(db, payload, opts);
+ return JSON.stringify({ embeds: [discordEmbed(ctx, payload)] });
+};
+
+// Bot-posted variant: the same embed plus moderation buttons. The bot token is
+// never part of the body (it is added to the request headers at send time).
+const BUTTON_STYLE = { primary: 1, secondary: 2, success: 3, danger: 4 } as const;
+
+/** Discord action rows (≤ 5 rows of ≤ 5 buttons) for an OpButton grid. */
+export const buttonRows = (
+ buttons: OpButton[][],
+ commentId: string,
+ extra: string[] = [],
+): unknown[] =>
+ buttons
+ .filter((row) => row.length > 0)
+ .slice(0, 5)
+ .map((row) => ({
+ type: 1,
+ components: row.slice(0, 5).map((b) => ({
+ type: 2,
+ style: BUTTON_STYLE[b.style],
+ label: b.label,
+ custom_id: encodePayload("discord", b.action, commentId, extra),
+ })),
+ }));
+
+export const renderDiscordBotBody = async (
+ db: WebhookAdapterDb,
+ payload: WebhookPayload,
+ opts: AdapterOpts = {},
+): Promise => {
+ const ctx = await loadContext(db, payload, opts);
+ return JSON.stringify({
+ embeds: [discordEmbed(ctx, payload)],
+ components: buttonRows(
+ buttonsFor(ctx.status, {
+ reported: payload.event === "comment.reported",
+ banLabel: "banr",
+ }),
+ payload.comment_id,
+ ),
+ allowed_mentions: { parse: [] },
+ });
};
// ----------------------------- Telegram ------------------------------------
diff --git a/src/lib/webhook.ts b/src/lib/webhook.ts
index 6495427c..1d093175 100644
--- a/src/lib/webhook.ts
+++ b/src/lib/webhook.ts
@@ -52,10 +52,13 @@ import {
type WebhookEndpoint,
} from "../db/queries";
import { log } from "./log";
+import { DISCORD_API, discordEnabled } from "./discord";
+import { SNOWFLAKE_RE } from "./opbot/codec";
import { checkOutboundUrl } from "./url-safety";
import {
type AdapterOpts,
renderDiscordBody,
+ renderDiscordBotBody,
renderSlackBody,
renderTelegramBody,
} from "./webhook-adapters";
@@ -90,6 +93,10 @@ type WebhookEnv = {
// Kept here (env secret) rather than in D1 so the token is never stored
// in plaintext alongside the (non-secret) chat id.
TELEGRAM_BOT_TOKEN?: string;
+ // Discord bot credentials. The `discord_bot` adapter posts to a channel id
+ // held in the endpoint's `url` column; the token is added at send time only.
+ DISCORD_BOT_TOKEN?: string;
+ DISCORD_PUBLIC_KEY?: string;
};
// Fixed, trusted Telegram Bot API host. Telegram endpoints target this URL
@@ -136,6 +143,7 @@ const renderBody = async (
if (adapter === "slack") return renderSlackBody(db, payload, opts);
if (adapter === "discord") return renderDiscordBody(db, payload, opts);
if (adapter === "telegram") return renderTelegramBody(db, payload, opts);
+ if (adapter === "discord_bot") return renderDiscordBotBody(db, payload, opts);
return renderGenericBody(payload);
};
@@ -161,6 +169,7 @@ const buildSyntheticEnvEndpoint = (url: string): WebhookEndpoint => {
};
const buildHeaders = async (
+ env: WebhookEnv,
endpoint: WebhookEndpoint,
body: string,
): Promise => {
@@ -168,6 +177,12 @@ const buildHeaders = async (
"content-type": "application/json",
"user-agent": "Garrul-Webhook/2.0",
};
+ // The bot token is added here, at send time, so it never lands in a stored
+ // delivery row. Discord authenticates by token; no HMAC header.
+ if (endpoint.adapter === "discord_bot") {
+ headers.authorization = `Bot ${env.DISCORD_BOT_TOKEN ?? ""}`;
+ return headers;
+ }
if (endpoint.secret) {
const sig = await signWebhookBody(endpoint.secret, body);
headers["x-garrul-signature"] = sig.header;
@@ -194,16 +209,58 @@ const resolveTarget = (
checkUrl: false,
};
}
+ if (endpoint.adapter === "discord_bot") {
+ // Re-checked here: the row may predate validation or be hand-edited.
+ if (!discordEnabled(env) || !SNOWFLAKE_RE.test(endpoint.url)) return null;
+ return {
+ url: `${DISCORD_API}/channels/${endpoint.url}/messages`,
+ // Fixed, trusted host; the channel id was validated as a snowflake on save.
+ checkUrl: false,
+ };
+ }
return { url: endpoint.url, checkUrl: true };
};
+const isDiscordAdapter = (a: WebhookAdapter): boolean =>
+ a === "discord" || a === "discord_bot";
+
+// Discord's retry_after: JSON body seconds (may be fractional), else the
+// Retry-After header in seconds. Returns ms, or undefined when absent.
+const parseRetryAfterMs = async (res: Response): Promise => {
+ let secs = Number.NaN;
+ try {
+ const j = (await res.json()) as { retry_after?: unknown };
+ if (typeof j?.retry_after === "number") secs = j.retry_after;
+ } catch {
+ // body not JSON; fall through to the header
+ }
+ if (!Number.isFinite(secs)) secs = Number(res.headers.get("retry-after"));
+ return Number.isFinite(secs) && secs >= 0 ? Math.ceil(secs * 1000) : undefined;
+};
+
const postOnce = async (
env: WebhookEnv,
endpoint: WebhookEndpoint,
body: string,
-): Promise<{ ok: boolean; status: number; error?: string }> => {
+): Promise<{
+ ok: boolean;
+ status: number;
+ error?: string;
+ retryAfterMs?: number;
+}> => {
const target = resolveTarget(env, endpoint);
- if (!target) return { ok: false, status: 0, error: "telegram:no_token" };
+ if (!target) {
+ return {
+ ok: false,
+ status: 0,
+ error:
+ endpoint.adapter === "discord_bot"
+ ? discordEnabled(env)
+ ? "discord:bad_channel"
+ : "discord:not_configured"
+ : "telegram:no_token",
+ };
+ }
if (target.checkUrl) {
const safe = checkOutboundUrl(target.url, {
allowHttp: allowHttpFor(endpoint, env),
@@ -214,7 +271,7 @@ const postOnce = async (
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
try {
- const headers = await buildHeaders(endpoint, body);
+ const headers = await buildHeaders(env, endpoint, body);
const res = await fetch(target.url, {
method: "POST",
headers,
@@ -235,6 +292,14 @@ const postOnce = async (
if (res.status >= 300 && res.status < 400) {
return { ok: false, status: res.status, error: "redirect_refused" };
}
+ if (res.status === 429 && isDiscordAdapter(endpoint.adapter)) {
+ const retryAfterMs = await parseRetryAfterMs(res);
+ return {
+ ok: false,
+ status: 429,
+ ...(retryAfterMs === undefined ? {} : { retryAfterMs }),
+ };
+ }
return { ok: res.ok, status: res.status };
} catch (err) {
// The telegram target URL embeds the bot token; some runtimes include the
@@ -250,7 +315,10 @@ const postOnce = async (
// only ever placed in the telegram target URL, but fetch error messages can
// echo that URL back, so we strip the exact secret defensively.
const scrubToken = (s: string, env: WebhookEnv): string =>
- env.TELEGRAM_BOT_TOKEN ? s.split(env.TELEGRAM_BOT_TOKEN).join("***") : s;
+ [env.TELEGRAM_BOT_TOKEN, env.DISCORD_BOT_TOKEN].reduce(
+ (acc, t) => (t ? acc.split(t).join("***") : acc),
+ s,
+ );
const isDevEnv = (env: WebhookEnv): boolean => env.ENV === "dev";
@@ -309,7 +377,8 @@ const dispatchToEndpoint = async (
endpoint.id,
payload.event,
body,
- Date.now() + (RETRY_SCHEDULE_MS[0] ?? 60_000),
+ Date.now() +
+ Math.max(RETRY_SCHEDULE_MS[0] ?? 60_000, result.retryAfterMs ?? 0),
);
};
@@ -425,10 +494,13 @@ const retryDelivery = async (
await markWebhookFailed(
env.DB,
delivery.id,
- giveup ? null : Date.now() + next,
+ giveup ? null : Date.now() + Math.max(next ?? 0, result.retryAfterMs ?? 0),
errorTag,
);
- if (giveup) {
+ if (giveup && result.status === 429 && isDiscordAdapter(endpoint.adapter)) {
+ // Throttled, not broken: never count it toward auto-disable.
+ log.warn("webhook.dropped_throttled", { endpoint_id: endpoint.id });
+ } else if (giveup) {
const newCount = endpoint.fail_count + 1;
await incrementWebhookFailCount(
env.DB,
diff --git a/src/routes/admin.ts b/src/routes/admin.ts
index a6f00d0f..f57668dc 100644
--- a/src/routes/admin.ts
+++ b/src/routes/admin.ts
@@ -49,12 +49,14 @@ import {
countModeratorNotesByTarget,
countOpenReportsByComment,
createWebhookEndpoint,
+ deleteDiscordLinkByUser,
deleteSettings,
deleteTelegramLinkByUser,
deleteWebhookEndpoint,
enqueueNotificationsForPost,
exportUserData,
getComment,
+ getDiscordLinkByUser,
getTelegramLinkByUser,
getPost,
getUser,
@@ -135,7 +137,10 @@ import {
import { renderUserDetail } from "../admin-ui/pages/user-detail";
import { renderUsers } from "../admin-ui/pages/users";
import { renderOperator } from "../admin-ui/pages/operator";
+import { SNOWFLAKE_RE, discordApi, discordEnabled, validateDiscordChannel } from "../lib/discord";
import { renderTelegram } from "../admin-ui/pages/telegram";
+import { renderDiscord } from "../admin-ui/pages/discord";
+import { issueLinkToken } from "../lib/opbot/link-token";
import { issueTelegramLinkToken } from "./telegram";
import { renderSettings } from "../admin-ui/pages/settings";
import { ownerLogin } from "./admin-owner";
@@ -144,6 +149,7 @@ import {
canonicalReactionKinds,
FLAG_KEYS,
isReactionKindsKey,
+ loadDiscordSettings,
loadNumbers,
loadSettings,
NUMBER_KEYS,
@@ -206,6 +212,7 @@ import { runSeedDemo } from "../db/seed-demo";
import { renderConfirmEmailHtml } from "../lib/digest";
import { sendEmail } from "../lib/email";
import { log } from "../lib/log";
+import { postModeratorReply } from "../lib/opbot/reply";
import { fillSubject, subjectTitle } from "../lib/post-title";
import { FALLBACK_LOCALE, tFor } from "../i18n";
@@ -904,6 +911,155 @@ admin.post("/api/telegram/digest", async (c) => {
return c.json({ ok: true, digest: body.digest });
});
+// --- Discord moderation bot ----------------------------------------------
+//
+// Secrets (DISCORD_BOT_TOKEN / _PUBLIC_KEY / _CLIENT_ID) live in the Worker
+// env; the guild/role/channel ids are operator settings. Admin-only, like
+// Telegram linking. Audit meta never carries ids, codes or tokens.
+
+const DISCORD_ID_FIELDS = {
+ guild_id: "discord_guild_id",
+ mod_role_id: "discord_mod_role_id",
+ admin_role_id: "discord_admin_role_id",
+ digest_channel_id: "discord_digest_channel_id",
+} as const;
+
+admin.get("/discord", async (c) => {
+ const user = await requireAdmin(c);
+ if (user instanceof Response) return user;
+ const [updateInfo, link, s] = await Promise.all([
+ peekCachedLatestVersion(c.env),
+ getDiscordLinkByUser(c.env.DB, user.id),
+ loadDiscordSettings(c.env),
+ ]);
+ const base = (c.env.PUBLIC_BASE_URL ?? "").replace(/\/+$/, "");
+ return c.html(
+ renderPage(
+ c,
+ "Discord",
+ renderDiscord({
+ configured: discordEnabled(c.env),
+ botTokenSet: !!c.env.DISCORD_BOT_TOKEN,
+ publicKeySet: !!c.env.DISCORD_PUBLIC_KEY,
+ clientIdSet: !!c.env.DISCORD_CLIENT_ID,
+ endpointUrl: base ? `${base}/discord/interactions` : null,
+ settings: s,
+ link: link ? { linked_at: link.linked_at } : null,
+ }),
+ user,
+ updateInfo,
+ ),
+ );
+});
+
+admin.post("/api/discord/settings", async (c) => {
+ const user = await requireAdmin(c);
+ if (user instanceof Response) return user;
+ const body = await c.req.json>().catch(() => null);
+ if (!body || typeof body !== "object") return c.json({ error: "invalid_body" }, 400);
+ const values: Record = {};
+ for (const field of Object.keys(DISCORD_ID_FIELDS)) {
+ const raw = body[field] ?? "";
+ const v = typeof raw === "string" ? raw.trim() : null;
+ if (v === null || (v !== "" && !SNOWFLAKE_RE.test(v))) {
+ return c.json({ error: `invalid_id:${field}` }, 400);
+ }
+ values[field] = v;
+ }
+ if (values.digest_channel_id) {
+ if (!discordEnabled(c.env) || !c.env.DISCORD_BOT_TOKEN || !values.guild_id) {
+ return c.json({ error: "discord_not_configured" }, 400);
+ }
+ const ch = await validateDiscordChannel(
+ c.env.DISCORD_BOT_TOKEN,
+ values.digest_channel_id,
+ values.guild_id,
+ );
+ if (!ch.ok) return c.json({ error: ch.error }, 400);
+ }
+ const cleared: string[] = [];
+ for (const [field, key] of Object.entries(DISCORD_ID_FIELDS)) {
+ const v = values[field] as string;
+ if (v) await setSetting(c.env.DB, key, v);
+ else cleared.push(key);
+ }
+ await deleteSettings(c.env.DB, cleared);
+ await bustSettingsCache(c.env);
+ await adminInsertAudit(c.env.DB, {
+ admin_id: user.id,
+ action: "discord.settings",
+ target_kind: "system",
+ target_id: null,
+ meta: { set: Object.keys(values).filter((f) => values[f]), cleared: cleared.length },
+ });
+ return c.json({ ok: true });
+});
+
+admin.post("/api/discord/link", async (c) => {
+ const user = await requireAdmin(c);
+ if (user instanceof Response) return user;
+ const code = await issueLinkToken(c.env.OAUTH_STATE, "dc", user.id);
+ await adminInsertAudit(c.env.DB, {
+ admin_id: user.id,
+ action: "discord.link_code",
+ target_kind: "user",
+ target_id: user.id,
+ });
+ return c.json({ ok: true, code });
+});
+
+admin.delete("/api/discord/link", async (c) => {
+ const user = await requireAdmin(c);
+ if (user instanceof Response) return user;
+ const removed = await deleteDiscordLinkByUser(c.env.DB, user.id);
+ if (removed) {
+ await adminInsertAudit(c.env.DB, {
+ admin_id: user.id,
+ action: "discord.unlink",
+ target_kind: "user",
+ target_id: user.id,
+ });
+ }
+ return c.json({ ok: true, removed });
+});
+
+const STRING_OPT = 3;
+const idOption = (name: string, description: string) => [
+ { name, description, type: STRING_OPT, required: true },
+];
+const DISCORD_COMMANDS = [
+ { name: "queue", description: "Review pending comments" },
+ { name: "stats", description: "Show comment statistics" },
+ { name: "comment", description: "Show a comment", options: idOption("id", "Comment id") },
+ { name: "user", description: "Show a commenter", options: idOption("id", "User id") },
+ { name: "unban", description: "Unban a commenter", options: idOption("id", "User id") },
+ { name: "link", description: "Link your Garrul account", options: idOption("code", "Code from the admin page") },
+];
+
+admin.post("/api/discord/commands", async (c) => {
+ const user = await requireAdmin(c);
+ if (user instanceof Response) return user;
+ if (!discordEnabled(c.env) || !c.env.DISCORD_BOT_TOKEN || !c.env.DISCORD_CLIENT_ID) {
+ return c.json({ error: "discord_not_configured" }, 400);
+ }
+ const { guildId } = await loadDiscordSettings(c.env);
+ if (!guildId) return c.json({ error: "guild_not_set" }, 400);
+ const r = await discordApi(
+ c.env.DISCORD_BOT_TOKEN,
+ "PUT",
+ `/applications/${c.env.DISCORD_CLIENT_ID}/guilds/${guildId}/commands`,
+ DISCORD_COMMANDS,
+ );
+ if (!r.ok) return c.json({ error: "discord_error", status: r.status }, 502);
+ await adminInsertAudit(c.env.DB, {
+ admin_id: user.id,
+ action: "discord.commands",
+ target_kind: "system",
+ target_id: null,
+ });
+ return c.json({ ok: true });
+});
+
admin.get("/settings", async (c) => {
const user = await requireAdmin(c);
if (user instanceof Response) return user;
@@ -1225,10 +1381,12 @@ const isValidEvent = (v: unknown): v is (typeof VALID_EVENTS)[number] =>
const isValidTelegramChatId = (v: string): boolean =>
/^-?\d{1,20}$/.test(v) || /^@[A-Za-z][A-Za-z0-9_]{4,31}$/.test(v);
-const parseWebhookBody = (
+const parseWebhookBody = async (
body: WebhookBody,
env: Bindings,
-): { ok: true; fields: WebhookFields } | { ok: false; error: string } => {
+): Promise<
+ { ok: true; fields: WebhookFields } | { ok: false; error: string }
+> => {
if (typeof body.url !== "string" || body.url.length === 0) {
return { ok: false, error: "url_required" };
}
@@ -1246,6 +1404,21 @@ const parseWebhookBody = (
if (!isValidTelegramChatId(body.url)) {
return { ok: false, error: "chat_id_invalid" };
}
+ } else if (adapter === "discord_bot") {
+ // `url` holds a channel id; the real target is the fixed Discord API host.
+ if (!SNOWFLAKE_RE.test(body.url)) {
+ return { ok: false, error: "channel_id_invalid" };
+ }
+ const { guildId } = await loadDiscordSettings(env);
+ if (!discordEnabled(env) || !env.DISCORD_BOT_TOKEN || !guildId) {
+ return { ok: false, error: "discord_not_configured" };
+ }
+ const ch = await validateDiscordChannel(
+ env.DISCORD_BOT_TOKEN,
+ body.url,
+ guildId,
+ );
+ if (!ch.ok) return { ok: false, error: ch.error };
} else {
// allowHttp only in dev — production endpoints must be https to make
// the signing+secret guarantees meaningful end-to-end.
@@ -1301,7 +1474,7 @@ admin.post("/api/webhooks", async (c) => {
if (user instanceof Response) return user;
const body = await c.req.json().catch(() => null);
if (!body) return c.json({ error: "invalid_body" }, 400);
- const parsed = parseWebhookBody(body, c.env);
+ const parsed = await parseWebhookBody(body, c.env);
if (!parsed.ok) return c.json({ error: parsed.error }, 400);
// On create there is nothing to preserve, so "absent" collapses to "unsigned".
const created = await createWebhookEndpoint(c.env.DB, {
@@ -1333,7 +1506,7 @@ admin.patch("/api/webhooks/:id", async (c) => {
if (!existing) return c.json({ error: "not_found" }, 404);
const body = await c.req.json().catch(() => null);
if (!body) return c.json({ error: "invalid_body" }, 400);
- const parsed = parseWebhookBody(body, c.env);
+ const parsed = await parseWebhookBody(body, c.env);
if (!parsed.ok) return c.json({ error: parsed.error }, 400);
await updateWebhookEndpoint(c.env.DB, id, parsed.fields);
await adminInsertAudit(c.env.DB, {
@@ -1861,124 +2034,37 @@ admin.post("/api/comments/:id/reply", async (c) => {
.catch(() => null);
if (!body) return c.json({ error: "invalid_body" }, 400);
- const valid = validateBody(
- typeof body.body_md === "string" ? body.body_md : "",
- );
- if (!valid.ok) {
- return c.json(
- valid.key === "err.body.too_long"
- ? { error: "body_too_long", max: valid.max }
- : { error: "body_required" },
- 400,
- );
- }
-
// Optional, but not coercible: `"false"` and `0` are what a buggy client sends
// when it means "don't email anyone", and silently reading either as true
// mails the whole thread. Absent stays absent; anything present must be a
- // real boolean.
+ // real boolean. `as_staff` follows the same rule.
if (body.notify != null && typeof body.notify !== "boolean") {
return c.json({ error: "invalid_body" }, 400);
}
- // Same rule as `notify`: optional, never coerced. Defaults on — a reply from
- // the moderation panel is the staff voice unless the mod says otherwise.
if (body.as_staff != null && typeof body.as_staff !== "boolean") {
return c.json({ error: "invalid_body" }, 400);
}
+ if (body.saved_reply_id != null && typeof body.saved_reply_id !== "string") {
+ return c.json({ error: "invalid_body" }, 400);
+ }
- // Provenance is optional, but when claimed it has to be a reply this mod can
- // actually see — otherwise the audit row could name someone else's private
- // saved reply. A 400 rather than a 404: the reply body is fine, the claim
- // about where it came from is not.
- let savedReplyId: string | null = null;
- if (body.saved_reply_id != null) {
- if (typeof body.saved_reply_id !== "string") {
- return c.json({ error: "invalid_body" }, 400);
- }
- const source = await getSavedReply(c.env.DB, body.saved_reply_id);
- if (!source || (source.owner_id !== user.id && source.scope !== "shared")) {
- return c.json({ error: "saved_reply_not_visible" }, 400);
- }
- savedReplyId = source.id;
- }
-
- const target = await getComment(c.env.DB, c.req.param("id"));
- if (!target) return c.json({ error: "comment_not_found" }, 404);
- if (target.status === "deleted") {
- return c.json({ error: "comment_deleted" }, 400);
- }
- // The nesting cap applies to moderators too: the O(N^2) tree-assembly cost
- // it guards doesn't care who created the chain. Reply higher up instead.
- const depth = target.depth + 1;
- if (depth > MAX_REPLY_DEPTH) {
- return c.json({ error: "thread_too_deep" }, 400);
- }
-
- const inserted = await insertComment(c.env.DB, {
- post_slug: target.post_slug,
- parent_id: target.id,
- user_id: user.id,
- body_md: valid.body,
- body_html: renderMarkdown(valid.body),
- renderer_version: CURRENT_RENDERER_VERSION,
- status: "approved",
- ip_hash: null,
- user_agent: null,
- depth,
- as_staff: body.as_staff ?? true,
- });
-
- // Default on: this is a real comment on a real thread, so the people
- // following that thread should hear about it the same way they hear about a
- // reader's reply. The composer's checkbox exists so a housekeeping note
- // ("dupe, see above") doesn't have to email everyone.
- const notify = body.notify ?? true;
- await adminInsertAudit(c.env.DB, {
- admin_id: user.id,
- action: "comment.reply",
- target_kind: "comment",
- target_id: inserted.id,
- meta: {
- from_saved_reply: savedReplyId != null,
- saved_reply_id: savedReplyId,
- parent_id: target.id,
- post_slug: target.post_slug,
- // The operator's choice, not a delivery count — the fan-out below is
- // deferred, and a number here would be a guess at what it will write.
- notify_subscribers: notify,
- },
- });
- // Bust the post's tree caches so the new reply is visible immediately.
- await bustTreeCache(c.env, c.req.url, target.post_slug);
- fireWebhook(c.env, c.executionCtx, {
- event: "comment.posted",
- comment_id: inserted.id,
- post_slug: target.post_slug,
- user_id: user.id,
- ts: inserted.created_at,
+ const res = await postModeratorReply({
+ env: c.env,
+ executionCtx: c.executionCtx,
+ reqUrl: c.req.url,
+ actor: user,
+ commentId: c.req.param("id"),
+ bodyMd: typeof body.body_md === "string" ? body.body_md : "",
+ savedReplyId: body.saved_reply_id,
+ notify: body.notify,
+ asStaff: body.as_staff,
});
-
- if (notify) {
- const fanout = (async () => {
- // Skip our own address for the same reason the widget path does: being
- // emailed about your own comment reads as a bug.
- const count = await enqueueNotificationsForPost(
- c.env.DB,
- target.post_slug,
- inserted.id,
- user.email?.toLowerCase() ?? null,
- );
- log.info("notify.enqueued", { count, post_slug: target.post_slug });
- })();
- // Always wait for the enqueue to finish — same reasoning as the widget
- // fan-out in routes/api.comments.ts: without an executionCtx the runtime
- // can cancel the orphan promise once the response settles, and a lost row
- // here is a notification nobody ever gets.
- if (c.executionCtx) c.executionCtx.waitUntil(fanout);
- else await fanout;
+ if (!res.ok) {
+ return res.error === "body_too_long"
+ ? c.json({ error: res.error, max: res.max }, 400)
+ : c.json({ error: res.error }, res.error === "comment_not_found" ? 404 : 400);
}
-
- return c.json({ ok: true, id: inserted.id, notified: notify });
+ return c.json({ ok: true, id: res.id, notified: res.notified });
});
// POST /admin/api/preview { body_md } -> { html }
diff --git a/src/routes/discord.ts b/src/routes/discord.ts
new file mode 100644
index 00000000..020f0ed9
--- /dev/null
+++ b/src/routes/discord.ts
@@ -0,0 +1,642 @@
+/**
+ * Inbound Discord route: the interactive side of the operator bot.
+ *
+ * Mounted top-level at `/discord`, outside `/api/*`, so it bypasses the CSRF
+ * and session middleware. The only authentication is Discord's Ed25519
+ * signature. Nothing touches D1 or KV before it verifies.
+ *
+ * Every interaction is answered synchronously (no defer in this build).
+ */
+import { Hono } from "hono";
+import {
+ countOpenReportsByComment,
+ getComment,
+ getUser,
+ nextPendingAfter,
+ type SavedReply,
+ upsertDiscordLink,
+} from "../db/queries";
+import type { Bindings } from "../index";
+import {
+ buttonRows,
+ cardToMessage,
+ type DiscordInteraction,
+ discordApi,
+ discordEnabled,
+ EPHEMERAL,
+ SNOWFLAKE_RE,
+ verifyDiscordRequest,
+} from "../lib/discord";
+import { log } from "../lib/log";
+import type { WaitUntilCtx } from "../lib/moderation";
+import {
+ hasRole,
+ OPBOT_RATE_LIMIT,
+ requiredRole,
+ runOpAction,
+ unbanUser,
+} from "../lib/opbot/actions";
+import {
+ buttonsFor,
+ ellipsize,
+ type OpCard,
+ renderQueueCard,
+ truncateCodePoints,
+} from "../lib/opbot/cards";
+import { decodePayload, encodePayload } from "../lib/opbot/codec";
+import { type OpActor, resolveDiscordActor } from "../lib/opbot/identity";
+import { consumeLinkToken } from "../lib/opbot/link-token";
+import {
+ expandPreset,
+ pickerPresets,
+ postModeratorReply,
+ presetVars,
+ presetVisible,
+ replyRefusalText,
+} from "../lib/opbot/reply";
+import { readComment, readQueue, readStats, readUser, relativeAge } from "../lib/opbot/readouts";
+import { checkRateLimit } from "../lib/ratelimit";
+import { loadDiscordSettings } from "../lib/settings";
+import { escapeDiscordMentions } from "../lib/webhook-adapters";
+
+export const discord = new Hono<{ Bindings: Bindings }>();
+
+type Reply = Record;
+type Ctx = { env: Bindings; executionCtx: WaitUntilCtx; reqUrl: string };
+
+const NO_MENTIONS = { parse: [] as [] };
+
+const MSG = {
+ slow: "Slow down — too many actions. Try again in a moment.",
+ noAccess: "Your account doesn't have moderation access.",
+ notLinked: "Link your account first with /link, or ask an admin for the mod role.",
+ wrongGuild: "This bot only works in its configured server.",
+ badCode: "That link code is invalid or expired.",
+ gone: "That comment no longer exists.",
+ staffUnban: "You can't unban a moderator or admin with a Discord role grant.",
+ staffBan: "You can't ban a moderator or admin with a Discord role grant.",
+ banRefused: "That ban was refused.",
+ empty: "Queue is empty 🎉",
+ tooLong: "Some saved replies are too long for Discord. Use the dashboard for those.",
+ unknown: "Unknown action.",
+} as const;
+
+const ephemeral = (content: string): Reply => ({
+ type: 4,
+ data: { content, flags: EPHEMERAL, allowed_mentions: NO_MENTIONS },
+});
+
+const update = (data: Reply): Reply => ({ type: 7, data: { ...data, allowed_mentions: NO_MENTIONS } });
+
+const refusal = (reason: "not_linked" | "not_authorized" | "banned" | "wrong_guild"): Reply =>
+ ephemeral(
+ reason === "not_linked" ? MSG.notLinked : reason === "wrong_guild" ? MSG.wrongGuild : MSG.noAccess,
+ );
+
+const senderOf = (i: DiscordInteraction) => i.member?.user ?? null;
+const senderId = (i: DiscordInteraction): string | null => senderOf(i)?.id ?? i.user?.id ?? null;
+const displayName = (i: DiscordInteraction): string =>
+ senderOf(i)?.global_name ?? senderOf(i)?.username ?? "unknown";
+
+discord.post("/interactions", async (c) => {
+ if (!discordEnabled(c.env)) return c.notFound();
+
+ const raw = await c.req.text();
+ const ok = await verifyDiscordRequest(
+ c.env.DISCORD_PUBLIC_KEY as string,
+ c.req.header("x-signature-ed25519"),
+ c.req.header("x-signature-timestamp"),
+ raw,
+ );
+ if (!ok) return c.json({ error: "invalid request signature" }, 401);
+
+ let i: DiscordInteraction;
+ try {
+ i = JSON.parse(raw) as DiscordInteraction;
+ } catch {
+ return c.json({ error: "bad request" }, 400);
+ }
+ if (!i || typeof i !== "object") return c.json({ error: "bad request" }, 400);
+ if (i.type === 1) return c.json({ type: 1 });
+ // Anything but a command, component or modal submit: refuse before any lookup.
+ if (i.type !== 2 && i.type !== 3 && i.type !== 5) return c.json(ephemeral(MSG.unknown));
+
+ // The rate limiter is inside `work` so its latency counts toward the deadline.
+ const work = (async (): Promise => {
+ const uid = senderId(i);
+ if (uid) {
+ const rl = await checkRateLimit(c.req.url, `dc:${uid}`, {
+ scope: "discord",
+ config: OPBOT_RATE_LIMIT,
+ env: c.env,
+ });
+ if (!rl.ok) return ephemeral(MSG.slow);
+ }
+ return dispatch({ env: c.env, executionCtx: c.executionCtx, reqUrl: c.req.url }, i);
+ })().catch((err) => {
+ log.error("discord.handler", { error: String(err) });
+ return ephemeral("Something went wrong. Try again.");
+ });
+ // A modal cannot be deferred; opening one does a fixed, small read.
+ if (opensModal(i, decodePayload(i.data?.custom_id))) return c.json(await work);
+
+ let timer: ReturnType | undefined;
+ const late = new Promise((r) => {
+ timer = setTimeout(() => r(null), DEFER_AFTER_MS);
+ });
+ const first = await Promise.race([work, late]);
+ clearTimeout(timer);
+ if (first) return c.json(first);
+ c.executionCtx.waitUntil(work.then((reply) => deliverLate(i, reply)));
+ return c.json(i.type === 2 ? { type: 5, data: { flags: EPHEMERAL } } : { type: 6 });
+});
+
+// Discord fails an interaction not answered within 3 s, even when the action
+// already committed. Past this budget, acknowledge with a deferred response and
+// deliver the result through the interaction webhook.
+const DEFER_AFTER_MS = 2500;
+
+const opensModal = (i: DiscordInteraction, payload: ReturnType): boolean =>
+ i.type === 3 &&
+ (payload?.action === "banr" ||
+ payload?.action === "ban" ||
+ (payload?.action === "pick" && i.data?.values?.[0] !== "more"));
+
+const deliverLate = async (i: DiscordInteraction, reply: Reply): Promise => {
+ if (!SNOWFLAKE_RE.test(i.application_id ?? "") || !i.token) return;
+ const hook = `/webhooks/${i.application_id}/${encodeURIComponent(i.token)}`;
+ // A command was deferred as an ephemeral message, so its result edits that
+ // message. A component or modal was deferred as an update: type 7 edits the
+ // clicked message, an ephemeral notice goes out as a follow-up.
+ const res =
+ i.type === 2 || reply.type === 7
+ ? await discordApi(null, "PATCH", `${hook}/messages/@original`, reply.data)
+ : await discordApi(null, "POST", hook, reply.data);
+ if (!res.ok) log.error("discord.deliver_late", { status: res.status });
+};
+
+const dispatch = async (ctx: Ctx, i: DiscordInteraction): Promise => {
+ const uid = senderId(i);
+ if (!uid) return refusal("wrong_guild");
+ const cfg = await loadDiscordSettings(ctx.env);
+
+ if (i.type === 2 && i.data?.name === "link") return handleLink(ctx, i, cfg.guildId, uid);
+
+ const payload = i.type === 3 || i.type === 5 ? decodePayload(i.data?.custom_id) : null;
+ if ((i.type === 3 || i.type === 5) && !payload) return ephemeral(MSG.unknown);
+
+ // Opening the ban modal must stay within a fixed D1 read bound and write
+ // nothing, so it skips full actor resolution. The submit re-authorizes.
+ if (payload && opensModal(i, payload)) {
+ return payload.action === "pick"
+ ? openReplyModal(ctx, i, cfg, payload.commentId, payload.extra, i.data?.values?.[0] ?? "")
+ : openBanModal(ctx, i, cfg, payload.commentId, payload.extra[0] === "q");
+ }
+
+ const who = await resolveDiscordActor(ctx.env.DB, cfg, {
+ guildId: i.guild_id,
+ discordUserId: uid,
+ displayName: displayName(i),
+ roles: i.member?.roles,
+ });
+ if (!who.ok) return refusal(who.reason);
+ const { actor } = who;
+
+ if (i.type === 2) return handleCommand(ctx, i, actor);
+ if (!payload) return ephemeral(MSG.unknown);
+ if (!hasRole(actor, requiredRole(payload.action))) return ephemeral(MSG.noAccess);
+
+ const q = payload.extra[0] === "q";
+ const { action, commentId } = payload;
+ if (i.type === 5) {
+ if (action === "rsub") return submitReply(ctx, i, actor, commentId, payload.extra);
+ if (action !== "bsub") return ephemeral(MSG.unknown);
+ const input = i.data?.components?.flatMap((r) => r.components).find((x) => x.custom_id === "reason");
+ const reason = truncateCodePoints(input?.value?.trim() ?? "", 500) || null;
+ return runAndRender(ctx, i, actor, "ban", commentId, q, reason);
+ }
+ switch (action) {
+ case "reply": {
+ const origin = q ? "q" : (i.message?.id ?? "");
+ if (!q && !SNOWFLAKE_RE.test(origin)) return ephemeral(MSG.unknown);
+ const msg = await pickerMessage(ctx.env, actor, commentId, origin, 0);
+ return q ? update(msg) : { type: 4, data: { ...msg, flags: EPHEMERAL, allowed_mentions: NO_MENTIONS } };
+ }
+ case "pick": {
+ // Only "more" reaches here; preset and custom open the modal above.
+ const offset = Math.max(0, Number.parseInt(payload.extra[1] ?? "0", 10) || 0) + PICK_PAGE;
+ return update(await pickerMessage(ctx.env, actor, commentId, payload.extra[0] ?? "q", offset));
+ }
+ case "rv":
+ case "nx": {
+ const next = await nextPendingAfter(ctx.env.DB, action === "rv" ? null : commentId);
+ if (!next) return update({ content: MSG.empty, embeds: [], components: [] });
+ return update(await queueMessage(ctx.env, next.id));
+ }
+ case "approve":
+ case "spam":
+ case "delete":
+ case "restore":
+ case "resolve":
+ return runAndRender(ctx, i, actor, action, commentId, q, null);
+ default:
+ return ephemeral(MSG.unknown);
+ }
+};
+
+const openBanModal = async (
+ ctx: Ctx,
+ i: DiscordInteraction,
+ cfg: { guildId: string; modRoleId: string; adminRoleId: string },
+ commentId: string,
+ q: boolean,
+): Promise => {
+ const who = await lightResolveActor(ctx.env.DB, cfg, i);
+ if ("reason" in who) return refusal(who.reason);
+ if (effectiveRole(who) !== "admin") return ephemeral(MSG.noAccess);
+ return {
+ type: 9,
+ data: {
+ custom_id: encodePayload("discord", "bsub", commentId, q ? ["q"] : []),
+ title: "Ban author",
+ components: [
+ {
+ type: 1,
+ components: [
+ {
+ type: 4,
+ custom_id: "reason",
+ style: 2,
+ label: "Reason (optional)",
+ required: false,
+ max_length: 500,
+ },
+ ],
+ },
+ ],
+ },
+ };
+};
+
+const PICK_PAGE = 23;
+const MODAL_MAX = 4000;
+const CUSTOM_OPTION = { label: "✏️ Write custom", value: "custom" };
+
+const pickerMessage = async (env: Bindings, actor: OpActor, commentId: string, origin: string, offset: number) => {
+ const presets = await pickerPresets(env.DB, actor.user.id, { chat: "private" });
+ const vars = await presetVars(env, commentId, actor.user);
+ // Select options cannot be disabled, so a preset that cannot prefill is left out.
+ const fits = presets.filter((p) => expandPreset(p.body_md, vars).length <= MODAL_MAX);
+ const hasMore = fits.length - offset > PICK_PAGE + 1;
+ const shown = fits.slice(offset, offset + (hasMore ? PICK_PAGE : PICK_PAGE + 1));
+ const options = [
+ ...shown.map((p) => ({
+ label: p.title.length > 100 ? `${p.title.slice(0, 99)}…` : p.title || "(untitled)",
+ value: p.id,
+ })),
+ CUSTOM_OPTION,
+ ...(hasMore ? [{ label: "More…", value: "more" }] : []),
+ ];
+ return {
+ content: ["Pick a saved reply, or write your own.", ...(fits.length < presets.length ? [MSG.tooLong] : [])].join("\n"),
+ embeds: [],
+ components: [
+ {
+ type: 1,
+ components: [
+ {
+ type: 3,
+ custom_id: encodePayload("discord", "pick", commentId, [origin, String(offset)]),
+ placeholder: "Saved replies",
+ options,
+ },
+ ],
+ },
+ ],
+ };
+};
+
+type ActorRow = { id: string; name: string; role: string; is_banned: number; erased_at: number | null; linked: number };
+type LightActor = { user: ActorRow | null; grant: "mod" | "admin" | null };
+
+// Modal-opening path: one D1 read, no writes. Mirrors the actor precedence of
+// resolveDiscordActor (erased rows ignored, any banned live row refuses, link
+// row wins over the provider row) without creating a role-holder row; the
+// submit re-authorizes through the full resolution.
+const lightResolveActor = async (
+ db: D1Database,
+ cfg: { guildId: string; modRoleId: string; adminRoleId: string },
+ i: DiscordInteraction,
+): Promise => {
+ if (!cfg.guildId || i.guild_id !== cfg.guildId) return { reason: "wrong_guild" };
+ const uid = senderId(i) as string;
+ const { results } = await db
+ .prepare(
+ `SELECT u.id, u.name, u.role, u.is_banned, u.erased_at,
+ (u.id = (SELECT user_id FROM discord_links WHERE discord_user_id = ?1)) AS linked
+ FROM users u
+ WHERE u.id = (SELECT user_id FROM discord_links WHERE discord_user_id = ?1)
+ OR (u.provider = 'discord' AND u.provider_id = ?1)`,
+ )
+ .bind(uid)
+ .all();
+ const live = (results ?? []).filter((r) => !r.erased_at);
+ if (live.some((r) => r.is_banned)) return { reason: "banned" };
+ const roles = i.member?.roles ?? [];
+ const has = (id: string) => Boolean(id) && roles.includes(id);
+ return {
+ user: live.find((r) => r.linked) ?? live[0] ?? null,
+ grant: has(cfg.adminRoleId) ? "admin" : has(cfg.modRoleId) ? "mod" : null,
+ };
+};
+
+/** Max of the role grant and the user row's role; null when neither reaches mod. */
+const effectiveRole = (a: LightActor): "mod" | "admin" | null =>
+ a.grant === "admin" || a.user?.role === "admin" ? "admin" : a.grant === "mod" || a.user?.role === "mod" ? "mod" : null;
+
+const openReplyModal = async (
+ ctx: Ctx,
+ i: DiscordInteraction,
+ cfg: { guildId: string; modRoleId: string; adminRoleId: string },
+ commentId: string,
+ extra: string[],
+ value: string,
+): Promise => {
+ const who = await lightResolveActor(ctx.env.DB, cfg, i);
+ if ("reason" in who) return refusal(who.reason);
+ if (!effectiveRole(who)) return refusal(who.user ? "not_authorized" : "not_linked");
+ const { user } = who;
+
+ const presetId = value === "custom" ? null : value;
+ let prefill = "";
+ if (presetId) {
+ const r = await ctx.env.DB.prepare(
+ `SELECT sr.*, a.name AS author_name, c.post_slug, p.title AS post_title
+ FROM saved_replies sr
+ LEFT JOIN comments c ON c.id = ?2
+ LEFT JOIN users a ON a.id = c.user_id
+ LEFT JOIN posts p ON p.slug = c.post_slug
+ WHERE sr.id = ?1`,
+ )
+ .bind(presetId, commentId)
+ .first();
+ if (!r || !presetVisible(r, user?.id ?? "", { chat: "private" })) {
+ return ephemeral(replyRefusalText("saved_reply_not_visible"));
+ }
+ prefill = expandPreset(r.body_md, {
+ name: r.author_name ?? undefined,
+ post: r.post_slug ? r.post_title || r.post_slug : undefined,
+ mod: user?.name ?? displayName(i),
+ });
+ if (prefill.length > MODAL_MAX) return ephemeral(MSG.tooLong);
+ }
+ return {
+ type: 9,
+ data: {
+ custom_id: encodePayload("discord", "rsub", commentId, [extra[0] ?? "q", ...(presetId ? [presetId] : [])]),
+ title: "Reply to comment",
+ components: [
+ {
+ type: 1,
+ components: [
+ {
+ type: 4,
+ custom_id: "body",
+ style: 2,
+ label: "Reply",
+ required: true,
+ max_length: MODAL_MAX,
+ ...(prefill && { value: prefill }),
+ },
+ ],
+ },
+ ],
+ },
+ };
+};
+
+const submitReply = async (
+ ctx: Ctx,
+ i: DiscordInteraction,
+ actor: OpActor,
+ commentId: string,
+ extra: string[],
+): Promise => {
+ const { env } = ctx;
+ const [origin = "", presetId] = extra;
+ const text = i.data?.components?.flatMap((r) => r.components).find((x) => x.custom_id === "body")?.value ?? "";
+ // postModeratorReply refuses a preset the actor cannot see (same rule as presetVisible, private chat).
+ const res = await postModeratorReply({
+ env,
+ executionCtx: ctx.executionCtx,
+ reqUrl: ctx.reqUrl,
+ actor: actor.user,
+ commentId,
+ bodyMd: text,
+ savedReplyId: presetId,
+ });
+ if (!res.ok) return ephemeral(replyRefusalText(res.error, res.max));
+ const doneBy = `Reply posted by ${actor.user.name}`;
+ if (origin === "q") return update(await queueMessage(env, commentId, doneBy));
+
+ const channel = i.channel_id ?? i.message?.channel_id ?? "";
+ if (env.DISCORD_BOT_TOKEN && SNOWFLAKE_RE.test(origin) && SNOWFLAKE_RE.test(channel)) {
+ const job = patchAlert(env, env.DISCORD_BOT_TOKEN, channel, origin, commentId, doneBy).catch((err) =>
+ log.error("discord.reply_patch", { error: String(err) }),
+ );
+ if (ctx.executionCtx) ctx.executionCtx.waitUntil(job);
+ else await job;
+ }
+ return update({ content: "Reply posted ✅", embeds: [], components: [] });
+};
+
+// Embeds are omitted so the alert keeps its card; a failed PATCH never undoes the reply.
+const patchAlert = async (
+ env: Bindings,
+ token: string,
+ channel: string,
+ messageId: string,
+ commentId: string,
+ doneBy: string,
+): Promise => {
+ const [comment, counts] = await Promise.all([
+ getComment(env.DB, commentId),
+ countOpenReportsByComment(env.DB, [commentId]),
+ ]);
+ const res = await discordApi(token, "PATCH", `/channels/${channel}/messages/${messageId}`, {
+ content: escapeDiscordMentions(doneBy),
+ components: buttonRows(
+ buttonsFor(comment?.status, { reported: (counts[commentId] ?? 0) > 0, banLabel: "banr" }),
+ commentId,
+ ),
+ allowed_mentions: NO_MENTIONS,
+ });
+ if (!res.ok) log.warn("discord.reply_patch_failed", { status: res.status });
+};
+
+const queueMessage = async (env: Bindings, commentId: string, doneBy?: string) => {
+ const comment = await getComment(env.DB, commentId);
+ if (!comment) return { content: MSG.gone, embeds: [], components: [] };
+ const card = await renderQueueCard(env, comment);
+ // Discord bans through the reason modal, so the queue card swaps the action.
+ const swapped: OpCard = {
+ ...card,
+ ...(doneBy && { doneBy }),
+ buttons: card.buttons.map((row) => row.map((b) => (b.action === "ban" ? { ...b, action: "banr" as const } : b))),
+ };
+ return { content: "", ...cardToMessage(swapped, ["q"]) };
+};
+
+const runAndRender = async (
+ ctx: Ctx,
+ i: DiscordInteraction,
+ actor: OpActor,
+ action: "approve" | "spam" | "delete" | "restore" | "resolve" | "ban",
+ commentId: string,
+ q: boolean,
+ reason: string | null,
+): Promise => {
+ const res = await runOpAction({
+ env: ctx.env,
+ executionCtx: ctx.executionCtx,
+ reqUrl: ctx.reqUrl,
+ actor,
+ action,
+ commentId,
+ reason,
+ });
+ if (!res.ok) {
+ return ephemeral(
+ res.error === "comment_not_found"
+ ? MSG.gone
+ : res.error === "target_is_staff"
+ ? MSG.staffBan
+ : res.error === "ban_refused"
+ ? MSG.banRefused
+ : MSG.noAccess,
+ );
+ }
+ if (q) return update(await queueMessage(ctx.env, commentId, res.doneBy));
+ return update({
+ content: escapeDiscordMentions(res.doneBy),
+ embeds: i.message?.embeds ?? [],
+ components: buttonRows(
+ buttonsFor(res.status, { reported: res.reported, banLabel: "banr" }),
+ commentId,
+ ),
+ });
+};
+
+const handleLink = async (ctx: Ctx, i: DiscordInteraction, guildId: string, uid: string): Promise => {
+ if (!guildId || i.guild_id !== guildId) return refusal("wrong_guild");
+ const code = i.data?.options?.find((o) => o.name === "code")?.value ?? "";
+ const userId = await consumeLinkToken(ctx.env.OAUTH_STATE, "dc", code.trim());
+ const user = userId ? await getUser(ctx.env.DB, userId) : null;
+ if (!user) return ephemeral(MSG.badCode);
+ await upsertDiscordLink(ctx.env.DB, { discord_user_id: uid, user_id: user.id });
+ return ephemeral(`Linked to ${escapeDiscordMentions(user.name)}.`);
+};
+
+const adminUrl = (env: Bindings, id: string): string | null =>
+ env.PUBLIC_BASE_URL
+ ? `${env.PUBLIC_BASE_URL.replace(/\/$/, "")}/admin/comments/${encodeURIComponent(id)}`
+ : null;
+
+const handleCommand = async (ctx: Ctx, i: DiscordInteraction, actor: OpActor): Promise => {
+ const { env } = ctx;
+ const arg = (i.data?.options?.find((o) => o.name === "id")?.value ?? "").trim();
+ const esc = escapeDiscordMentions;
+ switch (i.data?.name) {
+ case "queue": {
+ const r = await readQueue(env);
+ const lines = [
+ "**Moderation queue**",
+ `⏳ Pending: **${r.pending}**`,
+ `🚩 Reported: **${r.reported}**`,
+ `🚫 Spam: **${r.spam}**`,
+ ];
+ if (r.topFlagged) lines.push(`Most flagged: ${esc(r.topFlagged.slug)} (${r.topFlagged.count})`);
+ if (r.oldest) {
+ const url = adminUrl(env, r.oldest.id);
+ lines.push(`Oldest pending: ${relativeAge(r.oldest.created_at, Date.now())} ago${url ? ` — ${url}` : ""}`);
+ }
+ const reply = ephemeral(lines.join("\n"));
+ (reply.data as Reply).components = [
+ {
+ type: 1,
+ components: [
+ { type: 2, style: 1, label: "Review ▶", custom_id: encodePayload("discord", "rv", "-", ["q"]) },
+ ],
+ },
+ ];
+ return reply;
+ }
+ case "stats": {
+ const s = await readStats(env);
+ const pct = s.spam7d.total > 0 ? Math.round((s.spam7d.spam / s.spam7d.total) * 100) : 0;
+ return ephemeral(
+ [
+ "**Stats**",
+ `💬 Comments: **${s.totalComments}** (${s.pending} pending)`,
+ `👥 Users: **${s.totalUsers}** (${s.banned} banned)`,
+ `🚫 Spam rate (7d): **${pct}%** (${s.spam7d.spam}/${s.spam7d.total})`,
+ ].join("\n"),
+ );
+ }
+ case "comment": {
+ if (!arg) return ephemeral("Usage: /comment ");
+ const r = await readComment(env, arg);
+ if (!r) return ephemeral(MSG.gone);
+ const { comment, authorName, openReports } = r;
+ const snippet = ellipsize(comment.body_md, 200);
+ const url = adminUrl(env, arg);
+ return ephemeral(
+ [
+ `**Comment** ${esc(arg)}`,
+ `Status: **${comment.status}**${openReports > 0 ? ` · ${openReports} open report(s)` : ""}`,
+ `Author: ${esc(authorName)}`,
+ `On: ${esc(comment.post_slug)} · ${relativeAge(comment.created_at, Date.now())} ago`,
+ `> ${esc(snippet).replace(/\n/g, "\n> ")}`,
+ ...(url ? [url] : []),
+ ].join("\n"),
+ );
+ }
+ case "user": {
+ if (!arg) return ephemeral("Usage: /user ");
+ const r = await readUser(env, arg);
+ if (!r) return ephemeral("No such user.");
+ const { user, ban } = r;
+ return ephemeral(
+ [
+ `**User** ${esc(arg)}`,
+ `Name: ${esc(user.name)}`,
+ `Role: **${user.role}**`,
+ `Provider: ${esc(user.provider)}`,
+ `Joined: ${relativeAge(user.created_at, Date.now())} ago`,
+ !ban.banned
+ ? "Not banned"
+ : ban.purged
+ ? "Banned — reason no longer available"
+ : ban.reason
+ ? `Banned — ${esc(ban.reason)}`
+ : "Banned — no reason given",
+ ].join("\n"),
+ );
+ }
+ case "unban": {
+ if (!arg) return ephemeral("Usage: /unban ");
+ const res = await unbanUser({ env, actor, userId: arg });
+ if (res.ok) return ephemeral("Unbanned.");
+ return ephemeral(
+ res.error === "not_found"
+ ? "No such user."
+ : res.error === "target_is_staff"
+ ? MSG.staffUnban
+ : MSG.noAccess,
+ );
+ }
+ default:
+ return ephemeral(MSG.unknown);
+ }
+};
+
diff --git a/src/routes/telegram.ts b/src/routes/telegram.ts
index 1cb17f05..e2f4f834 100644
--- a/src/routes/telegram.ts
+++ b/src/routes/telegram.ts
@@ -20,105 +20,79 @@
*/
import { Hono } from "hono";
import {
- adminOldestPending,
- adminOpenReportSummary,
- adminSpamRate,
- adminStats,
countOpenReportsByComment,
- getComment,
- getTelegramLinkByTgUser,
+ getSavedReply,
getUser,
- type User,
+ nextPendingAfter,
upsertTelegramLink,
} from "../db/queries";
+import { t } from "../i18n";
import type { Bindings } from "../index";
import { log } from "../lib/log";
import {
- banUser,
- type CommentAction,
- moderateComment,
- resolveReports,
-} from "../lib/moderation";
-import { randomHex } from "../lib/oauth";
+ hasRole,
+ OPBOT_RATE_LIMIT,
+ requiredRole,
+ runOpAction,
+ unbanUser,
+} from "../lib/opbot/actions";
+import {
+ buttonsFor,
+ ellipsize,
+ type OpCard,
+ renderQueueCard,
+ truncateCodePoints,
+} from "../lib/opbot/cards";
+import { decodePayload, encodePayload } from "../lib/opbot/codec";
+import { type OpActor, resolveTelegramActor } from "../lib/opbot/identity";
+import { consumeLinkToken, issueLinkToken } from "../lib/opbot/link-token";
+import {
+ readComment,
+ readQueue,
+ readStats,
+ readUser,
+ relativeAge,
+} from "../lib/opbot/readouts";
+import {
+ expandPreset,
+ pickerPresets,
+ postModeratorReply,
+ presetVars,
+ presetVisible,
+ replyRefusalText,
+} from "../lib/opbot/reply";
import { checkRateLimit } from "../lib/ratelimit";
import {
answerCallbackQuery,
+ botIdFromToken,
decodeCallback,
editMessageText,
+ type InlineButton,
SECRET_HEADER,
sendMessage,
- type TgAction,
type TgCallbackQuery,
type TgMessage,
type TgUpdate,
+ toInlineKeyboard,
verifyTelegramSecret,
} from "../lib/telegram";
-import { t } from "../i18n";
export const telegram = new Hono<{ Bindings: Bindings }>();
// --------------------------- Link-token KV flow ---------------------------
//
-// Linking is a short-lived one-time token issued in the admin panel and
-// redeemed via `/start ` to the bot. Stored in OAUTH_STATE (reused
-// namespace) under a dedicated prefix so it can't collide with OAuth state.
-const LINK_TOKEN_TTL = 600; // 10 minutes
-const linkKey = (token: string): string => `tg:link:${token}`;
-const LINK_TOKEN_RE = /^[0-9a-f]{48}$/;
-
+// Linking is a one-time token issued in the admin panel and redeemed via
+// `/start `. The KV logic is shared with Discord (src/lib/opbot/link-token.ts).
/** Issue a one-time link token for `user_id`. Called by the admin route. */
-export const issueTelegramLinkToken = async (
+export const issueTelegramLinkToken = (
kv: KVNamespace,
user_id: string,
-): Promise => {
- const token = randomHex(24);
- await kv.put(
- linkKey(token),
- JSON.stringify({ user_id, created_at: Date.now() }),
- { expirationTtl: LINK_TOKEN_TTL },
- );
- return token;
-};
-
-const consumeLinkToken = async (
- kv: KVNamespace,
- token: string,
-): Promise => {
- if (!LINK_TOKEN_RE.test(token)) return null;
- const raw = await kv.get(linkKey(token));
- if (!raw) return null;
- await kv.delete(linkKey(token)); // one-time use
- try {
- const parsed = JSON.parse(raw) as { user_id?: string };
- return parsed.user_id ?? null;
- } catch {
- return null;
- }
-};
-
-// ------------------------------- Authorization ----------------------------
-
-const hasRole = (user: User, need: "mod" | "admin"): boolean =>
- !user.is_banned &&
- (need === "mod"
- ? user.role === "mod" || user.role === "admin"
- : user.role === "admin");
-
-/** The action's minimum role. Ban is admin-only, matching the HTTP routes. */
-const requiredRole = (action: TgAction): "mod" | "admin" =>
- action === "ban" ? "admin" : "mod";
+): Promise => issueLinkToken(kv, "tg", user_id);
// ------------------------------- Route -------------------------------------
-// Inbound callers are authenticated operators (secret token → linked account →
-// per-action role check), so the comment-posting default (1/10s, 5/10min) is
-// far too strict — a moderator tapping through a queue or running a couple of
-// slash commands would be throttled mid-session. Keep a generous burst that
-// still caps a runaway loop or a redelivery storm.
-const TELEGRAM_RATE_LIMIT = {
- short: { max: 10, windowSec: 10 },
- long: { max: 120, windowSec: 600 },
-};
+// Rate limiting uses OPBOT_RATE_LIMIT, the shared operator-bot burst (callers
+// are authenticated operators, so the comment-posting default is too strict).
telegram.post("/webhook", async (c) => {
// 1. Authenticate the caller. This is the ONLY gate on an originless route.
@@ -149,7 +123,7 @@ telegram.post("/webhook", async (c) => {
if (fromId != null) {
const rl = await checkRateLimit(c.req.url, `tg:${fromId}`, {
scope: "telegram",
- config: TELEGRAM_RATE_LIMIT,
+ config: OPBOT_RATE_LIMIT,
env: c.env,
});
if (!rl.ok) {
@@ -181,9 +155,10 @@ telegram.post("/webhook", async (c) => {
token,
update.callback_query,
c.executionCtx,
+ c.req.url,
);
} else if (update.message) {
- await handleMessage(c.env, token, update.message);
+ await handleMessage(c.env, token, update.message, c.executionCtx, c.req.url);
}
} catch (err) {
log.error("telegram.handler", { error: String(err) });
@@ -198,6 +173,7 @@ const handleCallback = async (
token: string,
cq: TgCallbackQuery,
executionCtx: { waitUntil(p: Promise): void },
+ reqUrl: string,
): Promise => {
const decoded = decodeCallback(cq.data);
if (!decoded) {
@@ -205,31 +181,128 @@ const handleCallback = async (
return;
}
- // Resolve identity → current user → role. The link is identity only; the
- // role is re-checked here every time, so revoking mod/admin disables the
- // buttons even while the link persists.
- const link = await getTelegramLinkByTgUser(env.DB, String(cq.from.id));
- if (!link) {
- await answerCallbackQuery(token, cq.id, t("telegram.not_linked"));
+ // Identity → current role, re-checked on every tap. The link is identity
+ // only, so revoking mod/admin disables the buttons while the link persists.
+ const who = await resolveTelegramActor(env.DB, String(cq.from.id));
+ if (!who.ok) {
+ await answerCallbackQuery(
+ token,
+ cq.id,
+ t(
+ who.reason === "not_linked"
+ ? "telegram.not_linked"
+ : "telegram.not_authorized",
+ ),
+ );
return;
}
- const user = await getUser(env.DB, link.user_id);
- if (!user || !hasRole(user, requiredRole(decoded.action))) {
+ const { actor } = who;
+ if (!hasRole(actor, requiredRole(decoded.action))) {
await answerCallbackQuery(token, cq.id, t("telegram.not_authorized"));
return;
}
-
- const outcome = await runAction(
+ const extra = decodePayload(cq.data)?.extra ?? [];
+ if (
+ decoded.action === "reply" ||
+ decoded.action === "sr" ||
+ decoded.action === "rc"
+ ) {
+ await handleReplyTap(env, token, cq, decoded, extra, actor, executionCtx, reqUrl);
+ return;
+ }
+ if (decoded.action === "banr") {
+ await answerCallbackQuery(token, cq.id);
+ if (cq.message) {
+ await sendMessage(
+ token,
+ cq.message.chat.id,
+ `Ban reason for comment ${escapeTg(decoded.commentId)} — send the reason as a reply to this message, ${mentionOf(cq.from.id, actor.user.name)}.`,
+ { replyMarkup: { force_reply: true, selective: true } },
+ );
+ }
+ return;
+ }
+ if (decoded.action === "rv" || decoded.action === "nx") {
+ await answerCallbackQuery(token, cq.id);
+ const next = await nextPendingAfter(
+ env.DB,
+ decoded.action === "rv" ? null : decoded.commentId,
+ );
+ if (cq.message) {
+ const card = next ? await renderQueueCard(env, next) : null;
+ await editMessageText(
+ token,
+ cq.message.chat.id,
+ cq.message.message_id,
+ card ? tgCardText(card) : "Queue is empty 🎉",
+ card
+ ? {
+ replyMarkup: {
+ // Action rows carry "q" so the post-action keyboard keeps
+ // Next; the Next row (last) does not.
+ inline_keyboard: [
+ ...toInlineKeyboard(card.buttons.slice(0, -1), card.commentId, ["q"])
+ .inline_keyboard,
+ ...toInlineKeyboard(card.buttons.slice(-1), card.commentId)
+ .inline_keyboard,
+ ],
+ },
+ }
+ : undefined,
+ );
+ }
+ return;
+ }
+ // TG_HANDLED guarantees one of the six actions runOpAction accepts.
+ const action = decoded.action as
+ | "approve"
+ | "spam"
+ | "delete"
+ | "restore"
+ | "resolve"
+ | "ban";
+
+ // runOpAction does not report how many reports it closed; read it first.
+ const openBefore =
+ action === "resolve"
+ ? ((await countOpenReportsByComment(env.DB, [decoded.commentId]))[
+ decoded.commentId
+ ] ?? 0)
+ : 0;
+ const res = await runOpAction({
env,
- user,
- decoded.action,
- decoded.commentId,
executionCtx,
+ reqUrl,
+ actor,
+ action,
+ commentId: decoded.commentId,
+ });
+ if (!res.ok) {
+ await answerCallbackQuery(
+ token,
+ cq.id,
+ t(
+ res.error === "comment_not_found"
+ ? "telegram.comment_not_found"
+ : res.error === "not_authorized"
+ ? "telegram.not_authorized"
+ : "telegram.ban_refused",
+ ),
+ );
+ return;
+ }
+ await answerCallbackQuery(
+ token,
+ cq.id,
+ action === "resolve"
+ ? t("telegram.reports_resolved", { count: openBefore })
+ : action === "ban"
+ ? t("telegram.author_banned")
+ : t("telegram.action_applied", { action }),
);
- await answerCallbackQuery(token, cq.id, outcome.toast);
- // Reflect the result in the message and strip the keyboard so the buttons
- // can't be tapped twice. editMessageText with no reply_markup removes it.
+ // Keep the message text, add who did what, and show the keyboard for the
+ // comment's new status.
if (cq.message) {
await editMessageText(
token,
@@ -239,66 +312,96 @@ const handleCallback = async (
// message (entities stripped), so any literal & < > in it must be
// re-escaped before it goes back out under parse_mode=HTML — otherwise
// the edit fails and the stale keyboard stays tappable.
- `${cq.message.text ? `${escapeTg(cq.message.text)}\n\n` : ""}${outcome.toast} — ${escapeTg(user.name)}`,
+ `${cq.message.text ? `${escapeTg(cq.message.text)}\n\n` : ""}${escapeTg(res.doneBy)}`,
+ {
+ replyMarkup: toInlineKeyboard(
+ buttonsFor(res.status, {
+ reported: res.reported,
+ queue: extra[0] === "q",
+ }),
+ decoded.commentId,
+ extra,
+ ),
+ },
);
}
};
-// Run the decoded action through the shared moderation service. Returns a
-// short toast for answerCallbackQuery. bustTreeCache keys on the Worker
-// origin, so we pass PUBLIC_BASE_URL as the synthetic request URL.
-const runAction = async (
+// ------------------------------- Reply flow --------------------------------
+
+const MAX_PRESET_BUTTONS = 99;
+
+const handleReplyTap = async (
env: Bindings,
- user: User,
- action: TgAction,
- commentId: string,
+ token: string,
+ cq: TgCallbackQuery,
+ decoded: { action: string; commentId: string },
+ extra: string[],
+ actor: OpActor,
executionCtx: { waitUntil(p: Promise): void },
-): Promise<{ toast: string }> => {
- const reqUrl = env.PUBLIC_BASE_URL ?? "https://localhost";
-
- if (action === "resolve") {
- const res = await resolveReports({
- env,
- adminId: user.id,
- commentId,
+ reqUrl: string,
+): Promise => {
+ await answerCallbackQuery(token, cq.id);
+ const msg = cq.message;
+ if (!msg) return;
+ const chatId = msg.chat.id;
+ const cid = decoded.commentId;
+ const ctx = { chat: msg.chat.type === "private" ? "private" : "group" } as const;
+
+ if (decoded.action === "reply") {
+ const rows: InlineButton[][] = [];
+ for (const p of await pickerPresets(env.DB, actor.user.id, ctx)) {
+ if (rows.length >= MAX_PRESET_BUTTONS) break;
+ let data: string;
+ try {
+ data = encodePayload("telegram", "sr", cid, [p.id]);
+ } catch {
+ continue; // id too long for a callback payload
+ }
+ const label = p.title.length > 60 ? `${p.title.slice(0, 60)}…` : p.title;
+ rows.push([{ text: label, callback_data: data }]);
+ }
+ rows.push([{ text: "✏️ Write custom", callback_data: encodePayload("telegram", "rc", cid) }]);
+ await sendMessage(token, chatId, `Reply to comment ${escapeTg(cid)}:`, {
+ replyMarkup: { inline_keyboard: rows },
});
- if (!res.ok) return { toast: t("telegram.comment_not_found") };
- return { toast: t("telegram.reports_resolved", { count: res.resolved }) };
+ return;
}
-
- if (action === "ban") {
- const comment = await getComment(env.DB, commentId);
- if (!comment) return { toast: t("telegram.comment_not_found") };
- const res = await banUser({
- env,
- adminId: user.id,
- userId: comment.user_id,
- banned: true,
- fromComment: commentId,
- });
- if (!res.ok) {
- return {
- toast: t(
- res.error === "not_found"
- ? "telegram.comment_not_found"
- : "telegram.ban_refused",
- ),
- };
- }
- return { toast: t("telegram.author_banned") };
+ if (decoded.action === "rc") {
+ await sendMessage(
+ token,
+ chatId,
+ `Reply to comment ${escapeTg(cid)} — send your text as a reply to this message, ${mentionOf(cq.from.id, actor.user.name)}.`,
+ { replyMarkup: { force_reply: true, selective: true } },
+ );
+ return;
}
- // approve | spam | delete | restore → a CommentAction.
- const res = await moderateComment({
+ // sr: post the chosen preset.
+ const preset = extra[0] ? await getSavedReply(env.DB, extra[0]) : null;
+ if (!preset || !presetVisible(preset, actor.user.id, ctx)) {
+ await sendMessage(token, chatId, replyRefusalText("saved_reply_not_visible"));
+ return;
+ }
+ const res = await postModeratorReply({
env,
executionCtx,
reqUrl,
- adminId: user.id,
- commentId,
- action: action as CommentAction,
+ actor: actor.user,
+ commentId: cid,
+ bodyMd: expandPreset(preset.body_md, await presetVars(env, cid, actor.user)),
+ savedReplyId: preset.id,
});
- if (!res.ok) return { toast: t("telegram.comment_not_found") };
- return { toast: t("telegram.action_applied", { action }) };
+ if (!res.ok) {
+ await sendMessage(token, chatId, replyRefusalText(res.error, res.max));
+ return;
+ }
+ await editMessageText(
+ token,
+ chatId,
+ msg.message_id,
+ `Reply posted by ${escapeTg(actor.user.name)}`,
+ );
};
// ----------------------------- Message handler -----------------------------
@@ -314,13 +417,99 @@ const parseCommand = (text: string): { name: string; arg: string } | null => {
return { name, arg };
};
+// A reply to one of the bot's force_reply prompts.
+const PROMPT_RE = /^(Ban reason for|Reply to) comment ([0-9A-HJKMNP-TV-Z]{26})\b/;
+
+const handlePromptAnswer = async (
+ env: Bindings,
+ token: string,
+ msg: TgMessage,
+ prompt: RegExpMatchArray,
+ text: string,
+ executionCtx: { waitUntil(p: Promise): void },
+ reqUrl: string,
+): Promise => {
+ const chatId = msg.chat.id;
+ const who = msg.from
+ ? await resolveTelegramActor(env.DB, String(msg.from.id))
+ : ({ ok: false, reason: "not_linked" } as const);
+ if (!who.ok) {
+ await sendMessage(
+ token,
+ chatId,
+ t(who.reason === "not_linked" ? "telegram.not_linked" : "telegram.not_authorized"),
+ );
+ return;
+ }
+ const { actor } = who;
+ const isReply = prompt[1] === "Reply to";
+ if (!hasRole(actor, requiredRole(isReply ? "reply" : "banr"))) {
+ await sendMessage(token, chatId, t("telegram.not_authorized"));
+ return;
+ }
+ if (isReply) {
+ const res = await postModeratorReply({
+ env,
+ executionCtx,
+ reqUrl,
+ actor: actor.user,
+ commentId: prompt[2] as string,
+ bodyMd: text,
+ });
+ await sendMessage(
+ token,
+ chatId,
+ res.ok
+ ? `Reply posted by ${escapeTg(actor.user.name)}`
+ : replyRefusalText(res.error, res.max),
+ );
+ return;
+ }
+ const res = await runOpAction({
+ env,
+ executionCtx,
+ reqUrl,
+ actor,
+ action: "ban",
+ commentId: prompt[2] as string,
+ reason: truncateCodePoints(text, 500),
+ });
+ await sendMessage(
+ token,
+ chatId,
+ res.ok
+ ? `${escapeTg(res.doneBy)}`
+ : t(
+ res.error === "comment_not_found"
+ ? "telegram.comment_not_found"
+ : res.error === "not_authorized"
+ ? "telegram.not_authorized"
+ : "telegram.ban_refused",
+ ),
+ );
+};
+
const handleMessage = async (
env: Bindings,
token: string,
msg: TgMessage,
+ executionCtx: { waitUntil(p: Promise): void },
+ reqUrl: string,
): Promise => {
const text = (msg.text ?? "").trim();
const chatId = msg.chat.id;
+
+ // Prompt answers come first: only a reply to one of the bot's own prompts
+ // counts, and the actor is re-resolved from the sender, never the prompt.
+ const replied = msg.reply_to_message;
+ const botId = botIdFromToken(token);
+ if (replied?.from?.id !== undefined && replied.from.id === botId) {
+ const prompt = (replied.text ?? "").match(PROMPT_RE);
+ if (prompt) {
+ if (text) await handlePromptAnswer(env, token, msg, prompt, text, executionCtx, reqUrl);
+ return;
+ }
+ }
const cmd = parseCommand(text);
// Linking is the one command that works before a link exists.
@@ -335,22 +524,29 @@ const handleMessage = async (
// Every query command requires a linked operator with at least mod role,
// re-checked here (the link is identity only).
- const link = msg.from
- ? await getTelegramLinkByTgUser(env.DB, String(msg.from.id))
- : null;
- if (!link) {
- await sendMessage(token, chatId, t("telegram.not_linked"));
- return;
- }
- const user = await getUser(env.DB, link.user_id);
- if (!user || !hasRole(user, "mod")) {
- await sendMessage(token, chatId, t("telegram.not_authorized"));
+ const who = msg.from
+ ? await resolveTelegramActor(env.DB, String(msg.from.id))
+ : ({ ok: false, reason: "not_linked" } as const);
+ if (!who.ok) {
+ await sendMessage(
+ token,
+ chatId,
+ t(
+ who.reason === "not_linked"
+ ? "telegram.not_linked"
+ : "telegram.not_authorized",
+ ),
+ );
return;
}
switch (cmd.name) {
case "queue":
- await sendMessage(token, chatId, await renderQueueText(env));
+ await sendMessage(token, chatId, await renderQueueText(env), {
+ replyMarkup: {
+ inline_keyboard: [[{ text: "Review ▶", callback_data: "g:rv:-" }]],
+ },
+ });
break;
case "stats":
await sendMessage(token, chatId, await renderStatsText(env));
@@ -361,6 +557,9 @@ const handleMessage = async (
case "user":
await sendMessage(token, chatId, await renderUserText(env, cmd.arg));
break;
+ case "unban":
+ await sendMessage(token, chatId, await runUnban(env, who.actor, cmd.arg));
+ break;
default:
await sendMessage(token, chatId, commandHelpText());
}
@@ -372,6 +571,26 @@ const handleMessage = async (
// HTML); like the slack/discord adapters, the fixed framing is composed inline
// rather than via t() — only the gate messages use the string table.
+const runUnban = async (
+ env: Bindings,
+ actor: OpActor,
+ arg: string,
+): Promise => {
+ const id = arg.trim();
+ if (!id) return "Usage: /unban <id>";
+ if (!hasRole(actor, requiredRole("unban"))) return t("telegram.not_authorized");
+ const res = await unbanUser({ env, actor, userId: id });
+ if (!res.ok) {
+ return res.error === "not_found"
+ ? "No such user."
+ : res.error === "target_is_staff"
+ ? "You can't unban a moderator or admin."
+ : t("telegram.not_authorized");
+ }
+ const user = await getUser(env.DB, id);
+ return `Unbanned ${escapeTg(user?.name ?? id)}.`;
+};
+
const commandHelpText = (): string =>
[
"Garrul operator bot",
@@ -379,42 +598,30 @@ const commandHelpText = (): string =>
"/stats — totals and 7-day spam rate",
"/comment <id> — a comment's status + author",
"/user <id> — a user's role + status",
+ "/unban <id> — lift a ban",
].join("\n");
-const relativeAge = (since: number, now: number): string => {
- const ms = Math.max(0, now - since);
- const mins = Math.floor(ms / 60000);
- if (mins < 60) return `${mins}m`;
- const hrs = Math.floor(mins / 60);
- if (hrs < 24) return `${hrs}h`;
- return `${Math.floor(hrs / 24)}d`;
-};
-
const adminCommentUrl = (env: Bindings, id: string): string | null =>
env.PUBLIC_BASE_URL
? `${env.PUBLIC_BASE_URL.replace(/\/$/, "")}/admin/comments/${encodeURIComponent(id)}`
: null;
const renderQueueText = async (env: Bindings): Promise => {
- const [stats, oldest, reports] = await Promise.all([
- adminStats(env.DB),
- adminOldestPending(env.DB),
- adminOpenReportSummary(env.DB),
- ]);
+ const q = await readQueue(env);
const lines = [
"Moderation queue",
- `⏳ Pending: ${stats.pending_comments}`,
- `🚩 Reported: ${reports.open}`,
- `🚫 Spam: ${stats.spam_comments}`,
+ `⏳ Pending: ${q.pending}`,
+ `🚩 Reported: ${q.reported}`,
+ `🚫 Spam: ${q.spam}`,
];
- if (reports.top) {
+ if (q.topFlagged) {
lines.push(
- `Most flagged: ${escapeTg(reports.top.slug)} (${reports.top.count})`,
+ `Most flagged: ${escapeTg(q.topFlagged.slug)} (${q.topFlagged.count})`,
);
}
- if (oldest) {
- const age = relativeAge(oldest.created_at, Date.now());
- const url = adminCommentUrl(env, oldest.id);
+ if (q.oldest) {
+ const age = relativeAge(q.oldest.created_at, Date.now());
+ const url = adminCommentUrl(env, q.oldest.id);
lines.push(
`Oldest pending: ${age} ago${url ? ` — ${tgLink(url, "open")}` : ""}`,
);
@@ -423,17 +630,14 @@ const renderQueueText = async (env: Bindings): Promise => {
};
const renderStatsText = async (env: Bindings): Promise => {
- const [stats, spam] = await Promise.all([
- adminStats(env.DB),
- adminSpamRate(env.DB, 7),
- ]);
+ const s = await readStats(env);
const pct =
- spam.total > 0 ? Math.round((spam.spam / spam.total) * 100) : 0;
+ s.spam7d.total > 0 ? Math.round((s.spam7d.spam / s.spam7d.total) * 100) : 0;
return [
"Stats",
- `💬 Comments: ${stats.total_comments} (${stats.pending_comments} pending)`,
- `👥 Users: ${stats.total_users} (${stats.banned_users} banned)`,
- `🚫 Spam rate (7d): ${pct}% (${spam.spam}/${spam.total})`,
+ `💬 Comments: ${s.totalComments} (${s.pending} pending)`,
+ `👥 Users: ${s.totalUsers} (${s.banned} banned)`,
+ `🚫 Spam rate (7d): ${pct}% (${s.spam7d.spam}/${s.spam7d.total})`,
].join("\n");
};
@@ -443,22 +647,15 @@ const renderCommentText = async (
): Promise => {
const id = arg.trim();
if (!id) return "Usage: /comment <id>";
- const comment = await getComment(env.DB, id);
- if (!comment) return t("telegram.comment_not_found");
- const [author, reportCounts] = await Promise.all([
- getUser(env.DB, comment.user_id),
- countOpenReportsByComment(env.DB, [id]),
- ]);
- const openReports = reportCounts[id] ?? 0;
- const snippet =
- comment.body_md.length > 200
- ? `${comment.body_md.slice(0, 200)}…`
- : comment.body_md;
+ const r = await readComment(env, id);
+ if (!r) return t("telegram.comment_not_found");
+ const { comment, authorName, openReports } = r;
+ const snippet = ellipsize(comment.body_md, 200);
const url = adminCommentUrl(env, id);
const lines = [
`Comment ${escapeTg(id)}`,
`Status: ${escapeTg(comment.status)}${openReports > 0 ? ` · ${openReports} open report(s)` : ""}`,
- `Author: ${escapeTg(author?.name ?? "unknown")}`,
+ `Author: ${escapeTg(authorName)}`,
`On: ${escapeTg(comment.post_slug)} · ${relativeAge(comment.created_at, Date.now())} ago`,
`${escapeTg(snippet)}
`,
];
@@ -469,17 +666,33 @@ const renderCommentText = async (
const renderUserText = async (env: Bindings, arg: string): Promise => {
const id = arg.trim();
if (!id) return "Usage: /user <id>";
- const user = await getUser(env.DB, id);
- if (!user) return "No such user.";
+ const r = await readUser(env, id);
+ if (!r) return "No such user.";
+ const { user, ban } = r;
return [
`User ${escapeTg(id)}`,
`Name: ${escapeTg(user.name)}`,
- `Role: ${escapeTg(user.role)}${user.is_banned ? " · ⛔ banned" : ""}`,
+ `Role: ${escapeTg(user.role)}`,
`Provider: ${escapeTg(user.provider)}`,
`Joined: ${relativeAge(user.created_at, Date.now())} ago`,
+ !ban.banned
+ ? "Not banned"
+ : ban.purged
+ ? "Banned — reason no longer available"
+ : ban.reason
+ ? `Banned — ${escapeTg(ban.reason)}`
+ : "Banned — no reason given",
].join("\n");
};
+const tgCardText = (card: OpCard): string =>
+ [
+ `${escapeTg(card.title)}`,
+ ...card.lines.map(escapeTg),
+ ...(card.snippet ? [`${escapeTg(card.snippet)}
`] : []),
+ ...(card.adminUrl ? [tgLink(card.adminUrl, "🔍 Open in admin")] : []),
+ ].join("\n");
+
const tgLink = (url: string, label: string): string =>
`${escapeTg(label)}`;
@@ -495,7 +708,7 @@ const handleStart = async (
return;
}
- const userId = await consumeLinkToken(env.OAUTH_STATE, code);
+ const userId = await consumeLinkToken(env.OAUTH_STATE, "tg", code);
if (!userId) {
await sendMessage(token, chatId, t("telegram.link_invalid"));
return;
@@ -523,6 +736,10 @@ const handleStart = async (
// Quotes are escaped too because this also feeds href="..." attributes via
// tgLink — an unescaped quote there breaks the attribute and Telegram rejects
// the whole message.
+// selective force_reply targets only users @mentioned in the text, so a prompt
+// must mention the moderator who tapped or no one in a group gets the reply box.
+const mentionOf = (id: number, name: string): string => `${escapeTg(name)}`;
+
const escapeTg = (s: string): string =>
s
.replace(/&/g, "&")
diff --git a/tests/admin-discord.test.ts b/tests/admin-discord.test.ts
new file mode 100644
index 00000000..7c694a09
--- /dev/null
+++ b/tests/admin-discord.test.ts
@@ -0,0 +1,223 @@
+/**
+ * /admin/discord page and /admin/api/discord/* against REAL SQLite.
+ * Discord's REST API is a mocked global fetch; ids are fake snowflakes.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { upsertDiscordLink } from "../src/db/queries";
+import { bustSettingsCache } from "../src/lib/settings";
+import { ADMIN_ID, MOD_SID, adminHarness, makeKv } from "./helpers/admin-sqlite";
+
+const GUILD = "111111111111111111";
+const CHAN = "222222222222222222";
+const ROLE = "333333333333333333";
+
+const setup = (extra: Record = {}) => {
+ const kv = makeKv();
+ const h = adminHarness({
+ OAUTH_STATE: kv,
+ DISCORD_BOT_TOKEN: "bot-token",
+ DISCORD_PUBLIC_KEY: "ab".repeat(32),
+ DISCORD_CLIENT_ID: "444444444444444444",
+ PUBLIC_BASE_URL: "https://c.example.test",
+ ...extra,
+ });
+ const audits = () =>
+ h.sqlite.prepare("SELECT action, meta FROM audit_log ORDER BY rowid").all() as Array<{
+ action: string;
+ meta: string | null;
+ }>;
+ const settings = () =>
+ Object.fromEntries(
+ (h.sqlite.prepare("SELECT key, value FROM settings").all() as Array<{ key: string; value: string }>).map(
+ (r) => [r.key, r.value],
+ ),
+ );
+ const setGuild = async () => {
+ h.sqlite.prepare("INSERT INTO settings (key, value, updated_at) VALUES ('discord_guild_id', ?, 0)").run(GUILD);
+ await bustSettingsCache(h.env);
+ };
+ return { ...h, kv, audits, settings, setGuild };
+};
+
+let fetchMock: ReturnType;
+beforeEach(() => {
+ fetchMock = vi.fn();
+ vi.stubGlobal("fetch", fetchMock);
+});
+afterEach(() => vi.unstubAllGlobals());
+
+const jsonRes = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status });
+
+describe("GET /admin/discord", () => {
+ it("shows state, endpoint URL, settings, link controls and the register button", async () => {
+ const { request, setGuild } = setup();
+ await setGuild();
+ const html = await (await request("/admin/discord")).text();
+ expect(html).toContain("https://c.example.test/discord/interactions");
+ expect(html).toContain(GUILD);
+ expect(html).toContain("Generate link code");
+ expect(html).toContain("Register commands");
+ expect(html).toContain("DISCORD_BOT_TOKEN");
+ });
+
+ it("notes an unset PUBLIC_BASE_URL and shows linked state", async () => {
+ const { request, env } = setup({ PUBLIC_BASE_URL: "" });
+ await upsertDiscordLink(env.DB, { discord_user_id: "555555555555555555", user_id: ADMIN_ID });
+ const html = await (await request("/admin/discord")).text();
+ expect(html).toContain("PUBLIC_BASE_URL");
+ expect(html).not.toContain("/discord/interactions ");
+ expect(html).toContain("Unlink Discord");
+ });
+
+ it("is admin-only", async () => {
+ const { request } = setup();
+ expect((await request("/admin/discord", { sid: MOD_SID })).status).toBe(403);
+ });
+});
+
+describe("POST /admin/api/discord/settings", () => {
+ const save = (request: ReturnTypehello
', 1, 'pending', NULL, NULL, 1, 1)`, + ) + .run(MOD_ID); + return { ...h, env, enable }; +}; + +const PAYLOAD = { + event: "comment.posted" as const, + comment_id: "c1", + post_slug: "p", + user_id: MOD_ID, + ts: 1, +}; + +const addEndpoint = (h: ReturnTypesecret body
', 1, 'pending', NULL, NULL, ?, 1)`, + ) + .run(MOD_ID, NOW - 3 * 3600 * 1000); + h.sqlite + .prepare("INSERT INTO reports (id, comment_id, reporter_user_id, reason, created_at) VALUES ('r1', 'c1', ?, 'spam', 1)") + .run(ADMIN_ID); + }; + return { + ...h, + discordEnv, + telegramEnv, + bothEnv, + calls, + setting, + discordCalls, + telegramCalls, + setChannel, + addTelegramOperator, + addOpenReport, + }; +}; + +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +describe("runDiscordDigest gate", () => { + it("does nothing when the bot token is missing", async () => { + const t = setup(); + t.setChannel(CHANNEL); + const { DISCORD_BOT_TOKEN: _token, ...noToken } = t.discordEnv; + await runDiscordDigest(noToken as never, NOW); + expect(t.discordCalls()).toEqual([]); + expect(t.setting("dc_digest_last_sent_at")).toBeUndefined(); + }); + + it("does nothing when the public key is missing", async () => { + const t = setup(); + t.setChannel(CHANNEL); + const { DISCORD_PUBLIC_KEY: _key, ...noKey } = t.discordEnv; + await runDiscordDigest(noKey as never, NOW); + expect(t.discordCalls()).toEqual([]); + expect(t.setting("dc_digest_last_sent_at")).toBeUndefined(); + }); + + it("does nothing and does not stamp the clock when no channel is set", async () => { + const t = setup(); + await runDiscordDigest(t.discordEnv as never, NOW); + expect(t.discordCalls()).toEqual([]); + expect(t.setting("dc_digest_last_sent_at")).toBeUndefined(); + }); +}); + +describe("runDiscordDigest send", () => { + it("posts once to the digest channel with the bot token, then holds for 23 h", async () => { + const t = setup(); + t.setChannel(CHANNEL); + t.addOpenReport(); + await runDiscordDigest(t.discordEnv as never, NOW); + expect(t.discordCalls()).toHaveLength(1); + const call = t.discordCalls()[0] as Call; + expect(call.auth).toBe("Bot fake-bot-token"); + expect(call.body.allowed_mentions).toEqual({ parse: [] }); + expect(t.setting("dc_digest_last_sent_at")).toBe(String(NOW)); + + await runDiscordDigest(t.discordEnv as never, NOW + 22 * 3600 * 1000); + expect(t.discordCalls()).toHaveLength(1); + await runDiscordDigest(t.discordEnv as never, NOW + DAY); + expect(t.discordCalls()).toHaveLength(2); + }); + + it("carries the same counts as the Telegram digest and the queue link, never bodies", async () => { + const t = setup(); + t.setChannel(CHANNEL); + t.addOpenReport(); + await runDiscordDigest(t.discordEnv as never, NOW); + const content = (t.discordCalls()[0]?.body.content ?? "") as string; + expect(content).toContain("Pending: **1**"); + expect(content).toContain("most on `hot-post` (1)"); + expect(content).toContain("Spam (7d)"); + expect(content).toContain("Banned users: **0**"); + expect(content).toContain("Oldest pending: **3h** old"); + expect(content).toContain("[Open moderation queue](https://comments.example.com/admin/queue)"); + expect(content).not.toContain("secret body"); + }); + + it("omits the queue link when PUBLIC_BASE_URL is unset", async () => { + const t = setup(); + t.setChannel(CHANNEL); + const { PUBLIC_BASE_URL: _base, ...noBase } = t.discordEnv; + await runDiscordDigest(noBase as never, NOW); + const content = (t.discordCalls()[0]?.body.content ?? "") as string; + expect(content).not.toContain("Open moderation queue"); + expect(content).toContain("Pending:"); + }); + + it("logs a warning with status only and still stamps the clock when the post fails", async () => { + const t = setup({ discordStatus: 500 }); + t.setChannel(CHANNEL); + const warn = vi.spyOn(log, "warn").mockImplementation(() => {}); + await runDiscordDigest(t.discordEnv as never, NOW); + expect(t.setting("dc_digest_last_sent_at")).toBe(String(NOW)); + const digestWarns = warn.mock.calls.filter(([event]) => event === "discord.digest.failed"); + expect(digestWarns).toEqual([["discord.digest.failed", { status: 500 }]]); + await runDiscordDigest(t.discordEnv as never, NOW + DAY); + expect(t.discordCalls()).toHaveLength(2); + }); +}); + +describe("independent digest gates", () => { + it("Discord only: stamps the Discord key and never the Telegram key", async () => { + const t = setup(); + t.setChannel(CHANNEL); + await runDiscordDigest(t.discordEnv as never, NOW); + await runTelegramDigest(t.bothEnv, NOW); + expect(t.discordCalls()).toHaveLength(1); + expect(t.telegramCalls()).toEqual([]); + expect(t.setting("dc_digest_last_sent_at")).toBe(String(NOW)); + expect(t.setting("tg_digest_last_sent_at")).toBeUndefined(); + }); + + it("Telegram only: stamps the Telegram key and never the Discord key", async () => { + const t = setup(); + await t.addTelegramOperator(); + await runDiscordDigest(t.discordEnv as never, NOW); + await runTelegramDigest(t.telegramEnv, NOW); + expect(t.discordCalls()).toEqual([]); + expect(t.telegramCalls()).toHaveLength(1); + expect(t.setting("tg_digest_last_sent_at")).toBe(String(NOW)); + expect(t.setting("dc_digest_last_sent_at")).toBeUndefined(); + }); + + it("both transports send: each stamps its own key", async () => { + const t = setup(); + t.setChannel(CHANNEL); + await t.addTelegramOperator(); + await runDiscordDigest(t.discordEnv as never, NOW); + await runTelegramDigest(t.bothEnv, NOW); + expect(t.discordCalls()).toHaveLength(1); + expect(t.telegramCalls()).toHaveLength(1); + expect(t.setting("dc_digest_last_sent_at")).toBe(String(NOW)); + expect(t.setting("tg_digest_last_sent_at")).toBe(String(NOW)); + }); + + it("Discord fails while Telegram sends: Telegram stamps, Discord stamps only on its own pass", async () => { + const t = setup({ discordStatus: 500 }); + t.setChannel(CHANNEL); + await t.addTelegramOperator(); + await runDiscordDigest(t.discordEnv as never, NOW); + await runTelegramDigest(t.bothEnv, NOW); + expect(t.telegramCalls()).toHaveLength(1); + expect(t.setting("tg_digest_last_sent_at")).toBe(String(NOW)); + expect(t.setting("dc_digest_last_sent_at")).toBe(String(NOW)); + }); + + it("Telegram fails while Discord sends: Discord stamps, Telegram stamps on its own pass", async () => { + const t = setup({ telegramStatus: 500 }); + t.setChannel(CHANNEL); + await t.addTelegramOperator(); + await runTelegramDigest(t.bothEnv, NOW); + await runDiscordDigest(t.discordEnv as never, NOW); + expect(t.discordCalls()).toHaveLength(1); + expect(t.setting("dc_digest_last_sent_at")).toBe(String(NOW)); + expect(t.setting("tg_digest_last_sent_at")).toBe(String(NOW)); + }); +}); diff --git a/tests/discord-interactions.test.ts b/tests/discord-interactions.test.ts new file mode 100644 index 00000000..1b641b5d --- /dev/null +++ b/tests/discord-interactions.test.ts @@ -0,0 +1,497 @@ +/** + * POST /discord/interactions against REAL SQLite (every migration applied). + * Requests are Ed25519-signed with a generated key pair. fireWebhook and the + * global fetch are mocked: nothing in this route may reach the network. + */ +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { DatabaseSync } from "node:sqlite"; +import { Hono } from "hono"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock("../src/lib/webhook", async (importOriginal) => ({ + ...(await importOriginala comment
", + renderer_version: 1, + status, + ip_hash: null, + user_agent: null, + depth: 1, + }) + ).id; + +const link = (dc: string, userId: string) => + sqlite + .prepare("INSERT INTO discord_links (discord_user_id, user_id, linked_at) VALUES (?, ?, 1)") + .run(dc, userId); + +const signedRequest = async (body: unknown, opts: { ts?: number; sig?: string } = {}) => { + const raw = typeof body === "string" ? body : JSON.stringify(body); + const ts = String(opts.ts ?? Math.floor(Date.now() / 1000)); + const sig = + opts.sig ?? + hex(await crypto.subtle.sign({ name: "Ed25519" }, keys.privateKey, new TextEncoder().encode(ts + raw))); + return { + method: "POST", + headers: { "x-signature-ed25519": sig, "x-signature-timestamp": ts, "content-type": "application/json" }, + body: raw, + }; +}; + +const send = async (body: unknown, opts: { ts?: number; sig?: string; env?: Bindings } = {}) => { + const app = new Hono<{ Bindings: Bindings }>().route("/discord", discord); + const res = await app.request( + "/discord/interactions", + await signedRequest(body, opts), + (opts.env ?? env) as unknown as Recorda comment
", + renderer_version: 1, + status, + ip_hash: null, + user_agent: null, + depth: 1, + }) + ).id; + +const link = (dc: string, userId: string) => + sqlite + .prepare("INSERT INTO discord_links (discord_user_id, user_id, linked_at) VALUES (?, ?, 1)") + .run(dc, userId); + +const signedRequest = async (body: unknown, opts: { ts?: number; sig?: string } = {}) => { + const raw = typeof body === "string" ? body : JSON.stringify(body); + const ts = String(opts.ts ?? Math.floor(Date.now() / 1000)); + const sig = + opts.sig ?? + hex(await crypto.subtle.sign({ name: "Ed25519" }, keys.privateKey, new TextEncoder().encode(ts + raw))); + return { + method: "POST", + headers: { "x-signature-ed25519": sig, "x-signature-timestamp": ts, "content-type": "application/json" }, + body: raw, + }; +}; + +const send = async (body: unknown, opts: { ts?: number; sig?: string; env?: Bindings } = {}) => { + const app = new Hono<{ Bindings: Bindings }>().route("/discord", discord); + const res = await app.request( + "/discord/interactions", + await signedRequest(body, opts), + (opts.env ?? env) as unknown as Recordhello
', 1, ?, NULL, NULL, ?, 1)`, + ); + addComment.run("c1", "plain", "pending", 100); + addComment.run("c2", "mod2", "approved", 200); + sqlite + .prepare( + "INSERT INTO reports (id, comment_id, reporter_user_id, reason, status, created_at) VALUES ('r1','c1','mod','spammy','open',5)", + ) + .run(); + const SESSIONS = makeKv(); + const env = { DB: makeD1(sqlite), SESSIONS, TREE_CACHE: makeKv() } as unknown as Bindings; + return { sqlite, env, SESSIONS }; +}; + +const actorOf = async (env: Bindings, id: string, role: "mod" | "admin", viaRole: boolean) => + ({ user: (await getUser(env.DB, id)) as User, role, adminViaDiscordRole: viaRole }) as OpActor; + +const audits = (sqlite: DatabaseSync, action: string) => + sqlite.prepare("SELECT * FROM audit_log WHERE action = ?").all(action); + +describe("role table", () => { + it("admin for ban/banr/bsub/unban, mod otherwise", () => { + for (const a of ["ban", "banr", "bsub", "unban"] as const) expect(requiredRole(a)).toBe("admin"); + for (const a of ["approve", "spam", "delete", "restore", "resolve", "reply", "sr", "rc", "pick", "rsub", "rv", "nx"] as const) + expect(requiredRole(a)).toBe("mod"); + }); + it("admin satisfies mod, not vice versa", async () => { + const { env } = setup(); + const mod = await actorOf(env, "mod", "mod", false); + const adm = await actorOf(env, "adm", "admin", false); + expect(hasRole(adm, "mod")).toBe(true); + expect(hasRole(mod, "admin")).toBe(false); + }); +}); + +describe("runOpAction", () => { + it("moderation actions change status and return doneBy + reported", async () => { + const { env, sqlite } = setup(); + const actor = await actorOf(env, "mod", "mod", false); + const res = await runOpAction({ env, executionCtx: undefined, actor, action: "approve", commentId: "c1" }); + expect(res).toEqual({ ok: true, status: "approved", doneBy: "Approved by Mo", reported: true }); + expect(audits(sqlite, "approve")).toHaveLength(1); + if (res.ok) { + const first = buttonsFor(res.status, { reported: res.reported })[0]; + expect(first?.some((b) => b.action === "spam")).toBe(true); + } + const spam = await runOpAction({ env, executionCtx: undefined, actor, action: "spam", commentId: "c1" }); + expect(spam).toMatchObject({ ok: true, status: "spam", doneBy: "Marked spam by Mo" }); + const restore = await runOpAction({ env, executionCtx: undefined, actor, action: "restore", commentId: "c1" }); + expect(restore).toMatchObject({ ok: true, status: "approved", doneBy: "Restored by Mo" }); + const del = await runOpAction({ env, executionCtx: undefined, actor, action: "delete", commentId: "c1" }); + expect(del).toMatchObject({ ok: true, status: "deleted", doneBy: "Deleted by Mo" }); + }); + + it("resolve closes reports and reports reported=false", async () => { + const { env, sqlite } = setup(); + const actor = await actorOf(env, "mod", "mod", false); + const res = await runOpAction({ env, executionCtx: undefined, actor, action: "resolve", commentId: "c1" }); + expect(res).toMatchObject({ ok: true, doneBy: "Reports resolved by Mo", reported: false, status: "pending" }); + expect(audits(sqlite, "report.resolve")).toHaveLength(1); + }); + + it("missing comment", async () => { + const { env } = setup(); + const actor = await actorOf(env, "adm", "admin", false); + for (const action of ["approve", "resolve", "ban"] as const) { + expect(await runOpAction({ env, executionCtx: undefined, actor, action, commentId: "nope" })).toEqual({ + ok: false, + error: "comment_not_found", + }); + } + }); + + it("mod cannot ban", async () => { + const { env } = setup(); + const actor = await actorOf(env, "mod", "mod", false); + expect(await runOpAction({ env, executionCtx: undefined, actor, action: "ban", commentId: "c1" })).toEqual({ + ok: false, + error: "not_authorized", + }); + }); + + it("ban writes reason + from_comment audit and revokes sessions", async () => { + const { env, sqlite, SESSIONS } = setup(); + const actor = await actorOf(env, "adm", "admin", false); + const res = await runOpAction({ env, executionCtx: undefined, actor, action: "ban", commentId: "c1", reason: "abuse" }); + expect(res).toMatchObject({ ok: true, doneBy: "Banned by Ada" }); + const row = audits(sqlite, "ban")[0] as { reason: string; meta: string }; + expect(row.reason).toBe("abuse"); + expect(JSON.parse(row.meta)).toEqual({ from_comment: "c1" }); + expect([...SESSIONS.store.keys()]).toContain("sessrev:plain"); + expect((await getUser(env.DB, "plain"))?.is_banned).toBe(true); + }); + + it("staff guard: role-derived admin blocked, real admin succeeds", async () => { + const { env, sqlite } = setup(); + const viaRole = await actorOf(env, "mod", "admin", true); + expect(await runOpAction({ env, executionCtx: undefined, actor: viaRole, action: "ban", commentId: "c2" })).toEqual({ + ok: false, + error: "target_is_staff", + }); + expect(audits(sqlite, "ban")).toHaveLength(0); + const real = await actorOf(env, "adm", "admin", false); + expect(await runOpAction({ env, executionCtx: undefined, actor: real, action: "ban", commentId: "c2" })).toMatchObject({ ok: true }); + expect(audits(sqlite, "ban")).toHaveLength(1); + }); + + it("guardBanTarget", async () => { + const { env } = setup(); + const viaRole = await actorOf(env, "mod", "admin", true); + const real = await actorOf(env, "adm", "admin", false); + const staff = (await getUser(env.DB, "mod2")) as User; + const plain = (await getUser(env.DB, "plain")) as User; + expect(guardBanTarget(viaRole, staff)).toBe(false); + expect(guardBanTarget(viaRole, plain)).toBe(true); + expect(guardBanTarget(real, staff)).toBe(true); + }); +}); + +describe("unbanUser", () => { + it("unbans, guards staff, refuses non-admin, reports not_found", async () => { + const { env, sqlite } = setup(); + const real = await actorOf(env, "adm", "admin", false); + await runOpAction({ env, executionCtx: undefined, actor: real, action: "ban", commentId: "c1" }); + expect(await unbanUser({ env, actor: real, userId: "plain" })).toEqual({ ok: true }); + expect(audits(sqlite, "unban")).toHaveLength(1); + expect(await unbanUser({ env, actor: real, userId: "ghost" })).toEqual({ ok: false, error: "not_found" }); + const viaRole = await actorOf(env, "mod", "admin", true); + expect(await unbanUser({ env, actor: viaRole, userId: "mod2" })).toEqual({ ok: false, error: "target_is_staff" }); + const mod = await actorOf(env, "mod", "mod", false); + expect(await unbanUser({ env, actor: mod, userId: "plain" })).toEqual({ ok: false, error: "not_authorized" }); + }); +}); + +describe("banState", () => { + it("covers banned+row, banned+no row, not banned, and latest-wins", async () => { + const { env, sqlite } = setup(); + const real = await actorOf(env, "adm", "admin", false); + expect(await banState(env.DB, (await getUser(env.DB, "plain")) as User)).toEqual({ banned: false }); + sqlite.prepare("UPDATE users SET is_banned = 1 WHERE id = 'mod2'").run(); + expect(await banState(env.DB, (await getUser(env.DB, "mod2")) as User)).toEqual({ + banned: true, + reason: null, + purged: true, + }); + await runOpAction({ env, executionCtx: undefined, actor: real, action: "ban", commentId: "c1", reason: "abuse" }); + expect(await banState(env.DB, (await getUser(env.DB, "plain")) as User)).toEqual({ + banned: true, + reason: "abuse", + purged: false, + }); + }); + + it("keeps the ban reason after more unrelated audit rows than any fixed window", async () => { + const { env, sqlite } = setup(); + const real = await actorOf(env, "adm", "admin", false); + await runOpAction({ env, executionCtx: undefined, actor: real, action: "ban", commentId: "c1", reason: "abuse" }); + const add = sqlite.prepare( + `INSERT INTO audit_log (id, admin_id, action, target_kind, target_id, created_at) + VALUES (?, 'adm', 'note', 'user', 'plain', ?)`, + ); + for (let n = 0; n < 60; n++) add.run(`zz-note-${n}`, 9_000_000_000_000 + n); + expect(await banState(env.DB, (await getUser(env.DB, "plain")) as User)).toEqual({ + banned: true, + reason: "abuse", + purged: false, + }); + }); +}); + +describe("readouts", () => { + it("readQueue / readStats / readComment / readUser / collectDigest", async () => { + const { env } = setup(); + const q = await readQueue(env); + expect(q).toMatchObject({ pending: 1, reported: 1, spam: 0, topFlagged: { slug: "p", count: 1 } }); + expect(q.oldest?.id).toBe("c1"); + expect(await readStats(env)).toMatchObject({ totalComments: 2, pending: 1, totalUsers: 4, banned: 0 }); + const c = await readComment(env, "c1"); + expect(c).toMatchObject({ authorName: "Plain", openReports: 1 }); + expect(await readComment(env, "zzz")).toBeNull(); + expect((await readUser(env, "plain"))?.ban).toEqual({ banned: false }); + expect(await readUser(env, "zzz")).toBeNull(); + const d = await collectDigest(env, 100 + 3 * 3600_000); + expect(d).toMatchObject({ pending: 1, openReports: 1, banned: 0, oldestAgeMs: 3 * 3600_000 }); + }); + it("relativeAge", () => { + expect(relativeAge(0, 5 * 60000)).toBe("5m"); + expect(relativeAge(0, 3 * 3600000)).toBe("3h"); + expect(relativeAge(0, 2 * 86400000)).toBe("2d"); + }); +}); diff --git a/tests/opbot-codec.test.ts b/tests/opbot-codec.test.ts new file mode 100644 index 00000000..ede085fd --- /dev/null +++ b/tests/opbot-codec.test.ts @@ -0,0 +1,78 @@ +import { describe, expect, it } from "vitest"; +import { decodeCallback } from "../src/lib/telegram"; +import { buttonsFor, type OpButton } from "../src/lib/opbot/cards"; +import { + decodePayload, + encodePayload, + OP_ACTIONS, +} from "../src/lib/opbot/codec"; + +const U = "01HC0000000000000000000000"; +const P = "01HP0000000000000000000000"; + +describe("opbot codec", () => { + it("round-trips every action", () => { + for (const a of OP_ACTIONS) { + const id = a === "rv" ? "-" : U; + expect(decodePayload(encodePayload("discord", a, id, ["q"]))).toEqual({ + action: a, + commentId: id, + extra: ["q"], + }); + } + }); + it("round-trips 0 and 3 extras", () => { + expect(decodePayload(encodePayload("discord", "pick", U))?.extra).toEqual([]); + expect( + decodePayload(encodePayload("discord", "pick", U, ["a", "b", "c"]))?.extra, + ).toEqual(["a", "b", "c"]); + }); + it("rejects bad payloads", () => { + for (const bad of [ + `x:approve:${U}`, + `g:nope:${U}`, + "g:approve:", + `g:rv:${U}`, + undefined, + ]) + expect(decodePayload(bad as string)).toBeNull(); + }); + it("fits the longest payloads", () => { + expect(new TextEncoder().encode(encodePayload("telegram", "sr", U, [P])).length).toBe(58); + expect(encodePayload("telegram", "restore", U, ["q"]).length).toBe(38); + const snowflake = "12345678901234567890"; + expect(encodePayload("discord", "rsub", U, [snowflake, P]).length).toBeLessThanOrEqual(100); + }); + it("throws past the limit", () => { + expect(() => encodePayload("telegram", "sr", U, [P, "x".repeat(10)])).toThrow(RangeError); + }); + it("buttonsFor follows status", () => { + const actions = (rows: OpButton[][]) => rows.map((r) => r.map((b) => b.action)); + expect(actions(buttonsFor("pending", { reported: false }))).toEqual([ + ["approve", "spam"], + ["delete", "ban", "reply"], + ]); + expect(actions(buttonsFor("approved", { reported: true }))).toEqual([ + ["spam"], + ["delete", "ban", "reply", "resolve"], + ]); + expect(actions(buttonsFor("spam", { reported: false }))[0]).toEqual(["restore"]); + expect(actions(buttonsFor("pending", { reported: false, queue: true })).at(-1)).toEqual(["nx"]); + }); +}); + +describe("decodeCallback allowlist", () => { + it("only decodes actions the Telegram route handles", () => { + expect(decodeCallback(`g:pick:${U}`)).toBeNull(); + expect(decodeCallback(`g:rsub:${U}`)).toBeNull(); + expect(decodeCallback(`g:banr:${U}`)).toEqual({ + action: "banr", + commentId: U, + }); + expect(decodeCallback(`g:sr:${U}:${P}`)?.action).toBe("sr"); + expect(decodeCallback(`g:approve:${U}`)).toEqual({ + action: "approve", + commentId: U, + }); + }); +}); diff --git a/tests/opbot-identity.test.ts b/tests/opbot-identity.test.ts new file mode 100644 index 00000000..17bc9f59 --- /dev/null +++ b/tests/opbot-identity.test.ts @@ -0,0 +1,222 @@ +/** Actor resolution + shared link tokens, against REAL SQLite. Spec §2. */ +import { readFileSync, readdirSync } from "node:fs"; +import { join } from "node:path"; +import { DatabaseSync } from "node:sqlite"; +import { describe, expect, it } from "vitest"; +import { upsertDiscordLink, upsertTelegramLink } from "../src/db/queries"; +import { resolveDiscordActor, resolveTelegramActor } from "../src/lib/opbot/identity"; +import { consumeLinkToken, issueLinkToken } from "../src/lib/opbot/link-token"; +import { makeD1, makeKv } from "./helpers/admin-sqlite"; + +const MIGRATIONS_DIR = join(__dirname, "../src/db/migrations"); +const GUILD = "222222222222222222"; +const MOD_ROLE = "333333333333333333"; +const ADMIN_ROLE = "444444444444444444"; +const cfg = { guildId: GUILD, modRoleId: MOD_ROLE, adminRoleId: ADMIN_ROLE }; +const DID = "111111111111111111"; +const DID2 = "555555555555555555"; + +const setup = () => { + const sqlite = new DatabaseSync(":memory:"); + for (const f of readdirSync(MIGRATIONS_DIR).filter((f) => f.endsWith(".sql")).sort()) { + sqlite.exec(readFileSync(join(MIGRATIONS_DIR, f), "utf8")); + } + const user = (id: string, provider: string, pid: string | null, role: string, extra: { banned?: boolean; erased?: boolean; avatar?: string } = {}) => + sqlite + .prepare( + `INSERT INTO users (id, provider, provider_id, name, avatar_url, is_admin, is_banned, role, created_at, erased_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?)`, + ) + .run(id, provider, pid, `name-${id}`, extra.avatar ?? null, role === "admin" ? 1 : 0, extra.banned ? 1 : 0, role, extra.erased ? 5 : null); + return { sqlite, db: makeD1(sqlite), user }; +}; + +const ask = (db: unknown, over: Partial<{ guildId: string | undefined; roles: string[]; discordUserId: string }> = {}) => + resolveDiscordActor(db as never, cfg, { + guildId: GUILD, + discordUserId: DID, + displayName: "Disp", + roles: [], + ...over, + }); + +describe("resolveDiscordActor", () => { + it("link only: linked user's role", async () => { + const { db, user } = setup(); + user("uA", "github", "1", "mod"); + await upsertDiscordLink(db, { discord_user_id: DID, user_id: "uA" }); + const r = await ask(db); + expect(r).toMatchObject({ ok: true, actor: { role: "mod", adminViaDiscordRole: false } }); + }); + + it("OAuth only: provider row counts as linked", async () => { + const { db, user } = setup(); + user("uB", "discord", DID, "admin"); + const r = await ask(db); + expect(r).toMatchObject({ ok: true, actor: { role: "admin", adminViaDiscordRole: false } }); + if (r.ok) expect(r.actor.user.id).toBe("uB"); + }); + + it("role only: creates a discord row with null email and avatar", async () => { + const { db, sqlite } = setup(); + const r = await ask(db, { roles: [MOD_ROLE] }); + expect(r).toMatchObject({ ok: true, actor: { role: "mod", adminViaDiscordRole: false } }); + const row = sqlite.prepare("SELECT * FROM users WHERE provider='discord' AND provider_id=?").get(DID) as Recordc
", + renderer_version: CURRENT_RENDERER_VERSION, + status: (opts.status ?? "approved") as never, + ip_hash: null, + user_agent: null, + depth: opts.depth ?? 0, + }) + ).id; + +const count = () => + (h.sqlite.prepare("SELECT COUNT(*) AS n FROM comments").get() as { n: number }).n; + +const preset = (id: string, owner: string, scope: string) => + h.sqlite + .prepare( + `INSERT INTO saved_replies (id, owner_id, title, body_md, scope, created_at, updated_at) + VALUES (?, ?, 'P', 'b', ?, 1, 1)`, + ) + .run(id, owner, scope); + +const reply = async (commentId: string, extra: Recordx
', 1, ?, NULL, NULL, ?, 1)`, + ); + // Ids are inserted out of order on purpose, so the walk cannot rely on insert order. + add.run(C, "pending", 200); + add.run(D, "approved", 150); + add.run(B, "pending", 200); + add.run(A, "pending", 100); + return { sqlite, DB }; +}; + +describe("nextPendingAfter", () => { + it("walks pending comments oldest-first, ties broken by id", async () => { + const { DB } = seed(); + expect((await nextPendingAfter(DB, null))?.id).toBe(A); + expect((await nextPendingAfter(DB, A))?.id).toBe(B); + expect((await nextPendingAfter(DB, B))?.id).toBe(C); + expect(await nextPendingAfter(DB, C)).toBeNull(); + }); + + it("keeps walking when the cursor comment was moderated mid-walk", async () => { + const { sqlite, DB } = seed(); + sqlite.prepare("UPDATE comments SET status = 'approved' WHERE id = ?").run(A); + expect((await nextPendingAfter(DB, A))?.id).toBe(B); + }); + + it("falls back to the oldest pending comment for an unknown cursor", async () => { + const { DB } = seed(); + expect((await nextPendingAfter(DB, "01ZZZZZZZZZZZZZZZZZZZZZZZZ"))?.id).toBe(A); + }); + + it("returns the Comment shape with the getComment columns", async () => { + const { DB } = seed(); + const row = await nextPendingAfter(DB, null); + expect(row).toMatchObject({ id: A, post_slug: "p", status: "pending", created_at: 100, depth: 1 }); + expect(row).toHaveProperty("score_up"); + expect(row).toHaveProperty("as_staff"); + }); + + it("returns null on an empty queue", async () => { + const { DB } = freshDb(); + expect(await nextPendingAfter(DB, null)).toBeNull(); + }); +}); + +describe("getUserByProvider", () => { + it("returns the user for a provider id, or null", async () => { + const { sqlite, DB } = freshDb(); + sqlite + .prepare( + `INSERT INTO users (id, provider, provider_id, name, is_admin, role, created_at) + VALUES (?, 'discord', '111111111111111111', 'Disc', 0, 'user', 1)`, + ) + .run(A); + const user = await getUserByProvider(DB, "discord", "111111111111111111"); + expect(user).toMatchObject({ id: A, provider: "discord", provider_id: "111111111111111111", name: "Disc" }); + expect(await getUserByProvider(DB, "discord", "999")).toBeNull(); + expect(await getUserByProvider(DB, "github", "111111111111111111")).toBeNull(); + }); +}); diff --git a/tests/ratelimit-do.test.ts b/tests/ratelimit-do.test.ts index 85119364..964b6373 100644 --- a/tests/ratelimit-do.test.ts +++ b/tests/ratelimit-do.test.ts @@ -298,7 +298,7 @@ describe("route wiring", () => { expect(missing).toEqual([]); // Guards the guard: a regex that stopped matching would otherwise pass // vacuously and this test would quietly stop protecting anything. - expect(found).toBe(14); + expect(found).toBe(15); }); }); diff --git a/tests/scheduled.test.ts b/tests/scheduled.test.ts index 6261f642..db3866a5 100644 --- a/tests/scheduled.test.ts +++ b/tests/scheduled.test.ts @@ -24,6 +24,10 @@ vi.mock("../src/lib/webhook", async (importOriginal) => ({ ...(await importOriginal${id} — send the reason as a reply to this message, Boss.`,
+ );
+ expect(replies().at(-1)?.body.reply_markup).toEqual({ force_reply: true, selective: true });
+ expect(tgCalls.find((c) => c.method === "answerCallbackQuery")?.body.text).toBeUndefined();
+ });
+
+ it("ban reason: a mod banr tap is refused with a toast and no prompt", async () => {
+ const id = await seedComment("approved");
+ await post(
+ mkEnv(),
+ {
+ update_id: 22,
+ callback_query: { id: "cb", from: { id: 43 }, message: { message_id: 10, chat: { id: 555 } }, data: encodeCallback("banr", id) },
+ },
+ SECRET,
+ );
+ expect(replies()).toHaveLength(0);
+ expect(tgCalls.find((c) => c.method === "answerCallbackQuery")?.body.text).toBe(
+ "Your account doesn't have moderation access.",
+ );
+ });
+
+ it("ban reason: an admin's reply bans the author with the trimmed, capped text", async () => {
+ const id = await seedComment("approved");
+ await answer("42", ` ${"x".repeat(600)} `, PROMPT(id));
+ expect(isBanned(AUTHOR)).toBe(1);
+ expect(banReason()).toBe("x".repeat(500));
+ expect(lastText()).toBe("Banned by Boss");
+ });
+
+ it("ban reason: a reply to a message not from the bot is ignored as a prompt answer", async () => {
+ const id = await seedComment("approved");
+ await answer("42", "spam farm", PROMPT(id), 999);
+ expect(isBanned(AUTHOR)).toBe(0);
+ expect(auditCount("ban")).toBe(0);
+ });
+
+ it("ban reason: a mod's reply is refused and nothing is banned", async () => {
+ const id = await seedComment("approved");
+ await answer("43", "spam farm", PROMPT(id));
+ expect(lastText()).toBe("Your account doesn't have moderation access.");
+ expect(isBanned(AUTHOR)).toBe(0);
+ expect(auditCount("ban")).toBe(0);
+ });
+
+ it("ban reason: the staff and self guards still run on a prompt answer", async () => {
+ const id = await seedComment("approved");
+ sqlite.prepare("UPDATE comments SET user_id = ? WHERE id = ?").run(ADMIN, id);
+ await answer("42", "oops", PROMPT(id));
+ expect(isBanned(ADMIN)).toBe(0);
+ expect(lastText()).toBe("Not banned: that is you, or the last admin who can still sign in.");
+ });
+
+ it("unban: an admin lifts a ban and it is audited; a mod is refused", async () => {
+ sqlite.prepare("UPDATE users SET is_banned = 1 WHERE id = ?").run(AUTHOR);
+ await say("43", `/unban ${AUTHOR}`);
+ expect(lastText()).toBe("Your account doesn't have moderation access.");
+ expect(isBanned(AUTHOR)).toBe(1);
+ await say("42", "/unban");
+ expect(lastText()).toBe("Usage: /unban <id>");
+ await say("42", "/unban 01HNOPE");
+ expect(lastText()).toBe("No such user.");
+ await say("42", `/unban ${AUTHOR}`);
+ expect(lastText()).toBe("Unbanned Author.");
+ expect(isBanned(AUTHOR)).toBe(0);
+ expect(auditCount("unban")).toBe(1);
+ });
+
+ it("/user shows the ban reason, no reason, purged audit, or not banned", async () => {
+ await say("42", `/user ${AUTHOR}`);
+ expect(lastText()).toContain("\nNot banned");
+ expect(lastText()).not.toContain("⛔");
+ const id = await seedComment("approved");
+ await answer("42", "a reason", PROMPT(id));
+ await say("42", `/user ${AUTHOR}`);
+ expect(lastText()).toContain("Banned — a <b> reason");
+ sqlite.prepare("UPDATE audit_log SET reason = NULL WHERE action = 'ban'").run();
+ await say("42", `/user ${AUTHOR}`);
+ expect(lastText()).toContain("Banned — no reason given");
+ sqlite.prepare("DELETE FROM audit_log").run();
+ await say("42", `/user ${AUTHOR}`);
+ expect(lastText()).toContain("Banned — reason no longer available");
+ });
+});
+
+describe("POST /telegram/webhook — reply with saved replies", () => {
+ const ADMIN = "01HADMIN00000000000000000B";
+ const MOD = "01HMOD0000000000000000000C";
+ const OTHER = "01HMOD0000000000000000000D";
+ const BOT_ID = 123;
+ const TS = 1_700_000_000_000;
+ const sent = () => tgCalls.filter((c) => c.method === "sendMessage");
+ const lastText = () => String(sent().at(-1)?.body.text);
+ const keyboard = () =>
+ (
+ sent().at(-1)?.body.reply_markup as
+ | { inline_keyboard: { text: string; callback_data: string }[][] }
+ | undefined
+ )?.inline_keyboard ?? [];
+ const preset = (id: string, owner: string, scope: "private" | "shared", title: string, body = "Hi {name}") =>
+ sqlite
+ .prepare(
+ "INSERT INTO saved_replies (id, owner_id, title, body_md, scope, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
+ )
+ .run(id, owner, title, body, scope, TS, TS);
+ const tap = (tgUserId: string, data: string, chatType = "private") =>
+ post(
+ mkEnv(),
+ {
+ update_id: 40,
+ callback_query: {
+ id: "cb",
+ from: { id: Number(tgUserId) },
+ message: { message_id: 10, chat: { id: 555, type: chatType }, text: "picker" },
+ data,
+ },
+ },
+ SECRET,
+ );
+ const answerPrompt = (tgUserId: string, text: string, promptText: string, fromId = BOT_ID) =>
+ post(
+ mkEnv(),
+ {
+ update_id: 41,
+ message: {
+ message_id: 30,
+ chat: { id: 555, type: "private" },
+ from: { id: Number(tgUserId) },
+ text,
+ reply_to_message: { message_id: 29, chat: { id: 555 }, from: { id: fromId }, text: promptText },
+ },
+ },
+ SECRET,
+ );
+ const replyRows = () =>
+ sqlite.prepare("SELECT body_md, parent_id FROM comments WHERE parent_id IS NOT NULL").all() as {
+ body_md: string;
+ parent_id: string;
+ }[];
+ const auditSaved = () =>
+ (sqlite.prepare("SELECT meta FROM audit_log WHERE action = 'comment.reply'").get() as { meta: string } | undefined)
+ ?.meta;
+
+ beforeEach(async () => {
+ seedUser(ADMIN, "admin", "Boss");
+ seedUser(MOD, "mod", "Moddy");
+ seedUser(OTHER, "mod", "Other");
+ await linkOperator("42", ADMIN);
+ await linkOperator("43", MOD);
+ await linkOperator("44", OTHER);
+ });
+
+ it("reply tap lists presets with truncated labels, Write custom, and caps at 99", async () => {
+ const id = await seedComment("approved");
+ const long = "L".repeat(70);
+ preset("01HSR00000000000000000000A", MOD, "shared", long);
+ for (let i = 0; i < 100; i++) preset(`01HSR0000000000000000${String(i).padStart(5, "0")}`, MOD, "shared", `t${i}`);
+ await tap("43", encodeCallback("reply", id));
+ expect(lastText()).toBe(`Reply to comment ${id}:`);
+ const rows = keyboard();
+ expect(rows).toHaveLength(100);
+ expect(rows.at(-1)).toEqual([{ text: "✏️ Write custom", callback_data: `g:rc:${id}` }]);
+ const labels = rows.slice(0, -1).map((r) => r[0]?.text ?? "");
+ expect(labels).toContain(`${"L".repeat(60)}…`);
+ expect(rows[0]?.[0]?.callback_data).toMatch(new RegExp(`^g:sr:${id}:01HSR`));
+ });
+
+ it("reply tap with no presets still offers Write custom", async () => {
+ const id = await seedComment("approved");
+ await tap("43", encodeCallback("reply", id));
+ expect(keyboard()).toEqual([[{ text: "✏️ Write custom", callback_data: `g:rc:${id}` }]]);
+ });
+
+ it("group chats list only shared presets; private lists own private plus shared", async () => {
+ const id = await seedComment("approved");
+ preset("01HSR00000000000000000000S", OTHER, "shared", "Shared one");
+ preset("01HSR00000000000000000000M", MOD, "private", "Mine");
+ preset("01HSR00000000000000000000X", OTHER, "private", "Theirs");
+ await tap("43", encodeCallback("reply", id), "supergroup");
+ expect(keyboard().flat().map((b) => b.text)).toEqual(["Shared one", "✏️ Write custom"]);
+ await tap("43", encodeCallback("reply", id), "private");
+ expect(keyboard().flat().map((b) => b.text).sort()).toEqual(["Mine", "Shared one", "✏️ Write custom"].sort());
+ });
+
+ it("sr tap posts the expanded preset, audits saved_reply_id and edits the picker", async () => {
+ const id = await seedComment("approved");
+ preset("01HSR00000000000000000000S", OTHER, "shared", "Hello", "Hi {name} from {mod}");
+ await tap("43", encodePayload("telegram", "sr", id, ["01HSR00000000000000000000S"]));
+ expect(replyRows()).toEqual([{ body_md: "Hi Author from Moddy", parent_id: id }]);
+ expect(auditSaved()).toContain("01HSR00000000000000000000S");
+ const edit = tgCalls.find((c) => c.method === "editMessageText");
+ expect(edit?.body.text).toBe("Reply posted by Moddy");
+ expect(edit?.body.reply_markup).toBeUndefined();
+ });
+
+ it("sr with a private preset from a group or a non-owner posts nothing", async () => {
+ const id = await seedComment("approved");
+ preset("01HSR00000000000000000000M", MOD, "private", "Mine");
+ const data = encodePayload("telegram", "sr", id, ["01HSR00000000000000000000M"]);
+ await tap("43", data, "group");
+ expect(lastText()).toBe("That saved reply isn't available here.");
+ await tap("44", data, "private");
+ expect(lastText()).toBe("That saved reply isn't available here.");
+ expect(replyRows()).toHaveLength(0);
+ });
+
+ it("rc tap sends a force_reply prompt; the reply posts verbatim", async () => {
+ const id = await seedComment("approved");
+ await tap("43", encodeCallback("rc", id));
+ // selective force_reply targets only @mentioned users, so the tapping moderator is mentioned.
+ const prompt = `Reply to comment ${id} — send your text as a reply to this message, Moddy.`;
+ expect(lastText()).toBe(prompt);
+ expect(sent().at(-1)?.body.reply_markup).toEqual({ force_reply: true, selective: true });
+ await answerPrompt("43", "Thanks {name}", `Reply to comment ${id} — send your text as a reply to this message.`);
+ expect(replyRows()).toEqual([{ body_md: "Thanks {name}", parent_id: id }]);
+ expect(lastText()).toBe("Reply posted by Moddy");
+ await answerPrompt("43", "ignored", `Reply to comment ${id} — send`, 999);
+ expect(replyRows()).toHaveLength(1);
+ });
+
+ it("refusals answer the operator in chat", async () => {
+ const gone = await seedComment("deleted");
+ const prompt = (cid: string) => `Reply to comment ${cid} — send your text as a reply to this message.`;
+ await answerPrompt("43", "x", prompt(gone));
+ expect(lastText()).toBe("That comment was deleted.");
+ const ok = await seedComment("approved");
+ await answerPrompt("43", "x".repeat(20_000), prompt(ok));
+ expect(lastText()).toMatch(/^Reply too long \(max \d+ characters\)\.$/);
+ sqlite.prepare("UPDATE comments SET depth = 99 WHERE id = ?").run(ok);
+ await answerPrompt("43", "hi", prompt(ok));
+ expect(lastText()).toBe("That thread is too deep to reply to. Reply higher up from the dashboard.");
+ expect(replyRows()).toHaveLength(0);
+ });
+
+ it("a reply prompt answer passes the real executionCtx downstream", async () => {
+ vi.mocked(fireWebhook).mockClear();
+ const id = await seedComment("approved");
+ await answerPrompt("43", "hello", `Reply to comment ${id} — send your text as a reply to this message.`);
+ expect(vi.mocked(fireWebhook)).toHaveBeenCalled();
+ const [, ctx] = vi.mocked(fireWebhook).mock.calls[0]!;
+ expect(ctx?.waitUntil).toBe(execCtx.waitUntil);
+ });
+
+ it("help lists /unban and the staff refusal has no Discord wording", async () => {
+ const say = (text: string) =>
+ post(mkEnv(), { update_id: 42, message: { message_id: 31, chat: { id: 555 }, from: { id: 42 }, text } }, SECRET);
+ await say("/help");
+ expect(lastText()).toContain("/unban <id> — lift a ban");
+ const { unbanUser } = await import("../src/lib/opbot/actions");
+ vi.mocked(unbanUser).mockResolvedValueOnce({ ok: false, error: "target_is_staff" });
+ await say(`/unban ${MOD}`);
+ expect(lastText()).toBe("You can't unban a moderator or admin.");
+ });
+});
diff --git a/tests/user-erase.test.ts b/tests/user-erase.test.ts
index 9ffb77c9..137a9cf7 100644
--- a/tests/user-erase.test.ts
+++ b/tests/user-erase.test.ts
@@ -206,6 +206,11 @@ beforeEach(() => {
VALUES (?, ?, ?, 0, ?)`,
)
.run("tg-555", "chat-555", TARGET_ID, 1_700_000_000_000);
+ sqlite
+ .prepare(
+ `INSERT INTO discord_links (discord_user_id, user_id, linked_at) VALUES (?, ?, ?)`,
+ )
+ .run("111111111111111111", TARGET_ID, 1_700_000_000_000);
// Three notes, one of each shape the erasure has to tell apart: about the
// target, about a comment of theirs, and authored *by* the target.
@@ -408,6 +413,13 @@ describe("POST /admin/api/users/:id/erase — linked records", () => {
).toBe(0);
});
+ it("removes the Discord link", async () => {
+ await erase({ confirm: "ERASE", redact_bodies: false });
+ expect(
+ count("SELECT COUNT(*) AS n FROM discord_links WHERE user_id = ?", TARGET_ID),
+ ).toBe(0);
+ });
+
it("clears reporter_ip_hash on reports they filed but keeps the report", async () => {
await erase({ confirm: "ERASE", redact_bodies: false });
const r = sqlite
@@ -456,6 +468,7 @@ describe("POST /admin/api/users/:id/erase — audit trail", () => {
subscriptions_deleted: 1,
reports_scrubbed: 1,
telegram_links_deleted: 1,
+ discord_links_deleted: 1,
moderator_notes_deleted: 1,
});
// The point of the action is that this data is gone. Writing the name or
diff --git a/tests/webhook-retries-realdb.test.ts b/tests/webhook-retries-realdb.test.ts
index 62d15e36..dec2ee24 100644
--- a/tests/webhook-retries-realdb.test.ts
+++ b/tests/webhook-retries-realdb.test.ts
@@ -8,7 +8,7 @@
*/
import { afterEach, describe, it, expect, vi } from "vitest";
import { enqueueWebhookDelivery } from "../src/db/queries";
-import { RETRY_SCHEDULE_MS, runWebhookRetries } from "../src/lib/webhook";
+import { RETRY_SCHEDULE_MS, dispatchWebhook, runWebhookRetries } from "../src/lib/webhook";
import { adminHarness } from "./helpers/admin-sqlite";
afterEach(() => {
@@ -79,3 +79,81 @@ describe("runWebhookRetries", () => {
expect(fetchMock).not.toHaveBeenCalled();
});
});
+
+describe("Discord 429 handling", () => {
+ const throttled = () =>
+ new Response(JSON.stringify({ retry_after: 2.5 }), {
+ status: 429,
+ headers: { "retry-after": "3" },
+ });
+
+ const run = async (adapter: string, attempts: number) => {
+ const { env, sqlite } = adminHarness();
+ const e = env as unknown as Record deep link instead of manual /start steps.
# TELEGRAM_BOT_USERNAME = "YourGarrulBot"
+# Discord operator bot (optional; OFF unless DISCORD_BOT_TOKEN, a secret, is also set).
+# Application public key used to verify interaction signatures (public, so a var).
+# DISCORD_PUBLIC_KEY = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
+
# Anti-spam (all optional; OFF by default). See docs/ANTISPAM.md.
# Pluggable content classifier — "akismet", "workers-ai" or "decisions". Leave unset for none.
# SPAM_PROVIDER = "akismet"
@@ -287,6 +291,7 @@ crons = ["*/15 * * * *"]
# WEBHOOK_URL — legacy single-URL webhook; prefer /admin/webhooks endpoints
# TELEGRAM_BOT_TOKEN — BotFather token; see docs/telegram.md
# TELEGRAM_WEBHOOK_SECRET — shared secret for setWebhook; required for inbound commands
+# DISCORD_BOT_TOKEN — bot token from the Discord developer portal (Bot tab)
# AKISMET_API_KEY — required when SPAM_PROVIDER = "akismet"
# AKISMET_SITE_URL — public site URL registered with Akismet
# SPAM_DECISIONS_API_KEY — required when SPAM_PROVIDER = "decisions"