Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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):

```
Expand Down
31 changes: 31 additions & 0 deletions src/gateway.test.ts
Original file line number Diff line number Diff line change
@@ -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 });
});
});

203 changes: 203 additions & 0 deletions src/gateway.ts
Original file line number Diff line number Diff line change
@@ -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<Response> {
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<void> {
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<void> {
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<GatewaySession> {
return (await this.ctx.storage.get<GatewaySession>('session')) ?? freshSession();
}

private async scheduleReconnect(session: GatewaySession): Promise<void> {
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<void> {
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<void> {
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<void> {
if (typeof message !== 'string') return;
let payload: { op?: number; s?: number | null; d?: Record<string, unknown> };
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<void> {
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<void> {
await this.scheduleReconnect(await this.getSession());
}
}

11 changes: 11 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand All @@ -12,6 +16,13 @@ export default {
}
return handleInteraction(request, env);
},
async scheduled(_controller: ScheduledController, env: Env, _ctx: ExecutionContext): Promise<void> {
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 };

8 changes: 8 additions & 0 deletions src/interactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
43 changes: 43 additions & 0 deletions src/workers-types.d.ts
Original file line number Diff line number Diff line change
@@ -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<T>(key: string): Promise<T | undefined>;
put(key: string, value: unknown): Promise<void>;
deleteAll(): Promise<void>;
}

declare interface DurableObjectState {
storage: DurableObjectStorage;
acceptWebSocket(ws: WebSocket): void;
getWebSockets(): WebSocket[];
setAlarm(time: number | Date): Promise<void>;
getAlarm(): Promise<number | null>;
}

declare interface DurableObjectId {
toString(): string;
}

declare interface DurableObjectStub {
fetch(url: string | Request): Promise<Response>;
}

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<unknown>): void;
passThroughOnException(): void;
}

14 changes: 14 additions & 0 deletions wrangler.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -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 * * * *"]
}
}