From b77f1b0dc4a97cf26582d646e697c8e84847c8c8 Mon Sep 17 00:00:00 2001 From: JordanNewell <58616955+JordanNewell@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:13:29 +0000 Subject: [PATCH] =?UTF-8?q?feat:=20GatewayPresence=20DO=20=E2=80=94=20keep?= =?UTF-8?q?=20.curtBot=20Online=20(intents-0=20gateway=20keep-alive)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 20 +++- src/gateway.test.ts | 31 +++++++ src/gateway.ts | 203 +++++++++++++++++++++++++++++++++++++++++ src/index.ts | 11 +++ src/interactions.ts | 8 ++ src/workers-types.d.ts | 43 +++++++++ wrangler.jsonc | 14 +++ 7 files changed, 326 insertions(+), 4 deletions(-) create mode 100644 src/gateway.test.ts create mode 100644 src/gateway.ts create mode 100644 src/workers-types.d.ts diff --git a/README.md b/README.md index f7a2228..ea3821c 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,17 @@ Zero-process Cloudflare Worker. `/curt`, `/tools`, `/adopt`, `/faq` — guild-scoped static responses, no message-content intent, no external calls at invoke time. +## Presence (.curtBot shows Online) + +A `GatewayPresence` Durable Object holds one outbound gateway WebSocket with +**intents 0** — zero events, just the connection — so the bot shows Online in +the member list. WebSocket Hibernation parks the socket at Cloudflare's edge; +a 5-minute cron trigger (`/ensure`) is the self-healing backstop. Commands +never touch this path; without `DISCORD_TOKEN` the DO simply never connects +and commands keep working. + +One-time setup after deploy: `npx wrangler secret put DISCORD_TOKEN`. + ## Setup (Jordan-only, Discord dev portal) 1. Create the Discord app **`.curtbot`** in the @@ -17,10 +28,11 @@ message-content intent, no external calls at invoke time. scope. 3. Set the repo secrets (GitHub): `CLOUDFLARE_API_TOKEN`, `CLOUDFLARE_ACCOUNT_ID`. -4. Set the Worker secret (once, via `wrangler secret put`): `DISCORD_PUBLIC_KEY` - — the only secret the Worker reads at runtime. `DISCORD_APPLICATION_ID`, - `DISCORD_GUILD_ID`, and `DISCORD_TOKEN` are env vars for `npm run register` - only (local, at registration time — never a Worker secret). +4. `DISCORD_PUBLIC_KEY` ships as a plain var in `wrangler.jsonc` (the app's + public key — publishable by design). `DISCORD_TOKEN` is the one real Worker + secret (presence only): `npx wrangler secret put DISCORD_TOKEN`. + `DISCORD_APPLICATION_ID` and `DISCORD_GUILD_ID` are env vars for `npm run register` + (local, at registration time — never Worker secrets). 5. Register the slash commands (after the env vars exist locally): ``` diff --git a/src/gateway.test.ts b/src/gateway.test.ts new file mode 100644 index 0000000..1531746 --- /dev/null +++ b/src/gateway.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from 'vitest'; +import { classifyClose, heartbeatPayload, nextBackoff } from './gateway'; + +describe('classifyClose', () => { + it('marks auth and invalid-session codes as fatal', () => { + for (const code of [4004, 4010, 4012, 4013, 4014]) { + expect(classifyClose(code)).toBe('fatal'); + } + }); + it('marks transient and network codes as retry', () => { + for (const code of [1000, 1006, 4000, 4001, 4009]) { + expect(classifyClose(code)).toBe('retry'); + } + }); +}); + +describe('nextBackoff', () => { + it('doubles the previous delay, capped', () => { + expect(nextBackoff(5_000)).toBe(10_000); + expect(nextBackoff(300_000)).toBe(600_000); + expect(nextBackoff(600_000)).toBe(600_000); + }); +}); + +describe('heartbeatPayload', () => { + it('carries the last sequence number, or null before any event', () => { + expect(JSON.parse(heartbeatPayload(42))).toEqual({ op: 1, d: 42 }); + expect(JSON.parse(heartbeatPayload(null))).toEqual({ op: 1, d: null }); + }); +}); + diff --git a/src/gateway.ts b/src/gateway.ts new file mode 100644 index 0000000..1ee0a1f --- /dev/null +++ b/src/gateway.ts @@ -0,0 +1,203 @@ +/** + * GatewayPresence — a Durable Object that holds one outbound Discord gateway + * WebSocket with intents 0. Its only job: keep .curtBot showing Online in + * the member list. Intents 0 means zero events — no messages, no presence + * reads — just the connection, the handshake, and heartbeats. + * + * WebSocket Hibernation: ctx.acceptWebSocket() parks the socket with the + * Cloudflare edge and evicts the object between events; DO alarms wake it + * for heartbeats. A cron trigger (every 5 min) pings /ensure as a + * self-healing backstop. Nothing here needs a process or a keep-alive server. + * + * Token: DISCORD_TOKEN — a real Worker secret (wrangler secret put), the + * only secret this Worker reads. If it is unset, the DO simply never + * connects; commands keep working without it. + */ +import type { Env } from './interactions'; + +const GATEWAY_BOT_URL = 'https://discord.com/api/v10/gateway/bot'; +const MIN_BACKOFF_MS = 5_000; +const MAX_BACKOFF_MS = 600_000; +const FATAL_CLOSE_CODES = new Set([4004, 4010, 4012, 4013, 4014]); +const FATAL_COOLDOWN_MS = 900_000; // bad token etc. — retry slowly via the cron backstop +const DEFAULT_HEARTBEAT_MS = 41_250; + +interface GatewaySession { + heartbeatIntervalMs: number | null; + lastSeq: number | null; + awaitingAck: boolean; + reconnectBackoffMs: number; + lastFatalAt: number | null; +} + +export function classifyClose(code: number): 'fatal' | 'retry' { + return FATAL_CLOSE_CODES.has(code) ? 'fatal' : 'retry'; +} + +export function nextBackoff(prev: number): number { + return Math.min(prev * 2, MAX_BACKOFF_MS); +} + +export function heartbeatPayload(lastSeq: number | null): string { + return JSON.stringify({ op: 1, d: lastSeq }); +} + +function jitter(intervalMs: number): number { + return Math.floor(Math.random() * intervalMs); +} + +function freshSession(): GatewaySession { + return { + heartbeatIntervalMs: null, + lastSeq: null, + awaitingAck: false, + reconnectBackoffMs: MIN_BACKOFF_MS, + lastFatalAt: null, + }; +} + +export class GatewayPresence { + constructor(private ctx: DurableObjectState, private env: Env) {} + + async fetch(request: Request): Promise { + const url = new URL(request.url); + if (url.pathname !== '/ensure') return new Response('Not found', { status: 404 }); + await this.ensure(); + const session = await this.getSession(); + return Response.json({ sockets: this.ctx.getWebSockets().length, session }); + } + + /** Cron backstop: connect if there is no live socket and no recent fatal. */ + async ensure(): Promise { + if (this.ctx.getWebSockets().length > 0) return; + const session = await this.getSession(); + if (session.lastFatalAt !== null && Date.now() - session.lastFatalAt < FATAL_COOLDOWN_MS) { + return; + } + await this.connect(); + } + + private async connect(): Promise { + const token = this.env.DISCORD_TOKEN; + if (!token) return; + let url: string; + try { + const res = await fetch(GATEWAY_BOT_URL, { headers: { Authorization: 'Bot ' + token } }); + if (!res.ok) { + const session = await this.getSession(); + session.lastFatalAt = Date.now(); + await this.ctx.storage.put('session', session); + return; + } + const gw = (await res.json()) as { url?: string }; + if (!gw.url) return; + url = gw.url; + } catch { + await this.scheduleReconnect(await this.getSession()); + return; + } + await this.ctx.storage.put('session', freshSession()); + const ws = new WebSocket(url + (url.includes('?') ? '&' : '?') + 'v=10&encoding=json'); + this.ctx.acceptWebSocket(ws); + // Safety: if HELLO never arrives, the alarm resets the zombie socket. + await this.ctx.setAlarm(Date.now() + 30_000); + } + + private async getSession(): Promise { + return (await this.ctx.storage.get('session')) ?? freshSession(); + } + + private async scheduleReconnect(session: GatewaySession): Promise { + const delay = session.reconnectBackoffMs; + session.reconnectBackoffMs = nextBackoff(delay); + await this.ctx.storage.put('session', session); + await this.ctx.setAlarm(Date.now() + delay); + } + + private async sendHeartbeat(ws: WebSocket, session: GatewaySession): Promise { + ws.send(heartbeatPayload(session.lastSeq)); + session.awaitingAck = true; + await this.ctx.storage.put('session', session); + await this.ctx.setAlarm(Date.now() + (session.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_MS)); + } + + async alarm(): Promise { + const session = await this.getSession(); + const sockets = this.ctx.getWebSockets(); + const ws = sockets[0]; + if (!ws) { + await this.ensure(); + return; + } + if (session.heartbeatIntervalMs === null) { + // HELLO never arrived — zombie socket; close triggers the reconnect path. + try { ws.close(4000, 'no hello'); } catch { /* already closed */ } + return; + } + if (session.awaitingAck) { + // Missed heartbeat ACK — the gateway spec says reconnect. + try { ws.close(4000, 'missed ack'); } catch { /* already closed */ } + return; + } + await this.sendHeartbeat(ws, session); + } + + async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise { + if (typeof message !== 'string') return; + let payload: { op?: number; s?: number | null; d?: Record }; + try { + payload = JSON.parse(message) as typeof payload; + } catch { + return; + } + const session = await this.getSession(); + if (typeof payload.s === 'number') session.lastSeq = payload.s; + const op = payload.op; + if (op === 10) { + const hello = payload.d as { heartbeat_interval?: number } | undefined; + session.heartbeatIntervalMs = hello?.heartbeat_interval ?? DEFAULT_HEARTBEAT_MS; + session.awaitingAck = false; + session.reconnectBackoffMs = MIN_BACKOFF_MS; + session.lastFatalAt = null; + await this.ctx.storage.put('session', session); + if (this.env.DISCORD_TOKEN) { + ws.send(JSON.stringify({ + op: 2, + d: { + token: this.env.DISCORD_TOKEN, + intents: 0, + properties: { os: 'linux', browser: 'curtbot', device: 'curtbot' }, + }, + })); + } + await this.ctx.setAlarm(Date.now() + jitter(session.heartbeatIntervalMs)); + } else if (op === 11) { + session.awaitingAck = false; + await this.ctx.storage.put('session', session); + } else if (op === 1) { + await this.sendHeartbeat(ws, session); + } else if (op === 7 || op === 9) { + // Server-requested reconnect / invalid session — fresh identify. + try { ws.close(4000, 'server requested reconnect'); } catch { /* already closed */ } + } else if (op === 0) { + // READY and friends — presence is set by the connection itself; + // persist the sequence number. + await this.ctx.storage.put('session', session); + } + } + + async webSocketClose(ws: WebSocket, code: number, _reason: string, _wasClean: boolean): Promise { + const session = await this.getSession(); + if (classifyClose(code) === 'fatal') { + session.lastFatalAt = Date.now(); + await this.ctx.storage.put('session', session); + return; // the cron backstop retries after the cooldown + } + await this.scheduleReconnect(session); + } + + async webSocketError(_ws: WebSocket, _error: unknown): Promise { + await this.scheduleReconnect(await this.getSession()); + } +} + diff --git a/src/index.ts b/src/index.ts index c0c018a..c36e24d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,10 @@ /** * .curtbot Worker entry point — one POST route: /api/discord/interactions. * Zero processes: the Worker only ever answers Discord's signed requests. + * + * The scheduled handler is the presence backstop: every 5 minutes it nudges + * the GatewayPresence Durable Object, which holds the gateway WebSocket that + * keeps .curtBot Online in the member list. Commands never touch it. */ import { handleInteraction, type Env } from './interactions'; @@ -12,6 +16,13 @@ export default { } return handleInteraction(request, env); }, + async scheduled(_controller: ScheduledController, env: Env, _ctx: ExecutionContext): Promise { + if (!env.GATEWAY) return; + const id = env.GATEWAY.idFromName('presence'); + await env.GATEWAY.get(id).fetch('https://presence/ensure'); + }, }; +export { GatewayPresence } from './gateway'; export type { Env }; + diff --git a/src/interactions.ts b/src/interactions.ts index 5e5c2ff..e4a7cb8 100644 --- a/src/interactions.ts +++ b/src/interactions.ts @@ -9,6 +9,14 @@ import { verifyInteraction } from './verify'; export interface Env { DISCORD_PUBLIC_KEY?: string; + /** + * Bot token — the one real Worker secret (wrangler secret put + * DISCORD_TOKEN). Read only by the GatewayPresence Durable Object for + * its gateway IDENTIFY; commands never use it. + */ + DISCORD_TOKEN?: string; + /** Durable Object binding for the presence keep-alive (wrangler.jsonc). */ + GATEWAY?: DurableObjectNamespace; } interface InteractionPayload { diff --git a/src/workers-types.d.ts b/src/workers-types.d.ts new file mode 100644 index 0000000..eb6df59 --- /dev/null +++ b/src/workers-types.d.ts @@ -0,0 +1,43 @@ +/** + * Minimal ambient types for the Cloudflare Workers runtime pieces this repo + * uses (Durable Objects, hibernation WebSocket handlers, cron triggers). + * Declared locally so the repo stays zero-dependency; swap for + * @cloudflare/workers-types if the surface ever grows. + */ +declare interface DurableObjectStorage { + get(key: string): Promise; + put(key: string, value: unknown): Promise; + deleteAll(): Promise; +} + +declare interface DurableObjectState { + storage: DurableObjectStorage; + acceptWebSocket(ws: WebSocket): void; + getWebSockets(): WebSocket[]; + setAlarm(time: number | Date): Promise; + getAlarm(): Promise; +} + +declare interface DurableObjectId { + toString(): string; +} + +declare interface DurableObjectStub { + fetch(url: string | Request): Promise; +} + +declare interface DurableObjectNamespace { + idFromName(name: string): DurableObjectId; + get(id: DurableObjectId): DurableObjectStub; +} + +declare interface ScheduledController { + readonly cron: string; + readonly scheduledTime: number; +} + +declare interface ExecutionContext { + waitUntil(promise: Promise): void; + passThroughOnException(): void; +} + diff --git a/wrangler.jsonc b/wrangler.jsonc index 8352cb5..f42510e 100644 --- a/wrangler.jsonc +++ b/wrangler.jsonc @@ -9,5 +9,19 @@ // need nothing outside GitHub Actions. No secret bindings needed. "vars": { "DISCORD_PUBLIC_KEY": "6cb62abb31d21b5d69d84a89dac74d02d6180b864fbf7526a4ba0c79c42b4739" + }, + + // Presence: one Durable Object holds the gateway WebSocket (intents 0) + // so .curtBot shows Online; a 5-min cron backstop pings /ensure. + "durable_objects": { + "bindings": [ + { "name": "GATEWAY", "class_name": "GatewayPresence" } + ] + }, + "migrations": [ + { "tag": "v1-presence", "new_classes": ["GatewayPresence"] } + ], + "triggers": { + "crons": ["*/5 * * * *"] } }