slack-term 1.57.1 → 1.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,401 @@
1
+ // aip/1 machine link: the frames between this router (tier 1) and one subrouter per machine (tier 2), with their
2
+ // validators. The subrouter lives in another repository and the two sides share no code: this file mirrors the
3
+ // "aip/1 machine link" section of that side's protocol module (plus the Envelope / Receipt / Ack it builds on), and
4
+ // both sides test the same golden frames (worker/test/fixtures/link-frames.json). Change neither the shapes nor the
5
+ // error texts here without changing them there.
6
+ //
7
+ // Pure: no Cloudflare types, so the CLI suite tests it under bun (tests/router-wire.test.ts) and the worker suite
8
+ // tests it inside workerd (worker/test/wire.test.ts).
9
+ //
10
+ // Transport: WebSocket GET /router/link, subprotocol aip.v1, one JSON object per text frame; the bare strings
11
+ // "ping"/"pong" are the keepalive (answered by the runtime). A machine answers the router's challenge with an Ed25519
12
+ // signature; the router keeps only public keys. The router addresses lanes (envelope.to = lane:<name>[@<agent id>]);
13
+ // the subrouter picks the agent and names it in the receipt.
14
+
15
+ export const AIP_VERSION = 1 as const;
16
+
17
+ export const ROLES = ["worker", "observer", "cancel"] as const;
18
+ export type Role = (typeof ROLES)[number];
19
+ /** accepted: in the agent's input. queued: held by the runtime (agent busy/blocked), delivered later, never resend.
20
+ * unreachable: nothing delivered. unknown: may have been delivered (no resend). rejected: refused (version, size). */
21
+ export const RECEIPT_STATUS = ["accepted", "queued", "unreachable", "unknown", "rejected"] as const;
22
+ export type ReceiptStatus = (typeof RECEIPT_STATUS)[number];
23
+ /** ready: idle. busy: mid-turn (a delivery queues). blocked: waits on a prompt. limited: usage limit. down: gone. */
24
+ export const HEALTH = ["ready", "busy", "blocked", "limited", "down", "unknown"] as const;
25
+ export type HealthState = (typeof HEALTH)[number];
26
+ export const ACK_KINDS = ["read", "done", "decline"] as const;
27
+ export type AckKind = (typeof ACK_KINDS)[number];
28
+
29
+ /** Where a message came from. */
30
+ export interface Source {
31
+ kind: "slack";
32
+ workspace: string;
33
+ /** the intake app (Slack app) the router heard it through */
34
+ app?: string;
35
+ channel: string;
36
+ ts: string;
37
+ thread_ts?: string;
38
+ permalink?: string;
39
+ user: { id: string; name?: string; human: boolean };
40
+ }
41
+
42
+ /** router → machine (`deliver`): one message for one listener. `key` = message id + label, the idempotency key. */
43
+ export interface Envelope {
44
+ v: typeof AIP_VERSION;
45
+ key: string;
46
+ id: string;
47
+ /** lane:<name> or lane:<name>@<agent id> on the link */
48
+ to: string;
49
+ role: Role;
50
+ label: string;
51
+ attempt: number;
52
+ src: Source;
53
+ text: string;
54
+ files?: string[];
55
+ reply?: { command: string };
56
+ /** workers only: the receipt token for `ack` */
57
+ ack?: { token: string };
58
+ }
59
+
60
+ export interface Receipt {
61
+ v: typeof AIP_VERSION;
62
+ key: string;
63
+ endpoint: string;
64
+ status: ReceiptStatus;
65
+ at: number;
66
+ detail?: string;
67
+ /** decided, nothing delivered (shadow mode) */
68
+ shadow?: boolean;
69
+ }
70
+
71
+ export interface Ack {
72
+ v: typeof AIP_VERSION;
73
+ token: string;
74
+ kind: AckKind;
75
+ by: string;
76
+ at: number;
77
+ ref?: string;
78
+ }
79
+
80
+ /** A Slack message ts as the link carries it. */
81
+ export const TS = /^\d{10}\.\d{6}$/;
82
+
83
+ export const LINK_SUBPROTOCOL = "aip.v1";
84
+ export const LINK_PATH = "/router/link";
85
+ /** lane and machine names */
86
+ export const NAME = /^[a-z0-9][a-z0-9-]{0,31}$/;
87
+ export const JOB = /^[a-z0-9][a-z0-9._-]{0,63}$/;
88
+ export const CHANNEL = /^[CDG][A-Z0-9]{2,}$/;
89
+ /** a concrete lane address on the link */
90
+ export const LANE_ADDRESS = /^lane:[a-z0-9][a-z0-9-]{0,31}(?:@[0-9a-f]{6,32})?$/;
91
+ /** a worker label: group letter + failover rank */
92
+ export const LABEL = /^[a-z][1-9]$/;
93
+ export const MAX_FRAME_BYTES = 256 * 1024;
94
+ export const LINK_CLOSE = { authFailed: 4401, authTimeout: 4408, replaced: 4409 } as const;
95
+ export const MODES = ["shadow", "live"] as const;
96
+ export type Mode = (typeof MODES)[number];
97
+ export const ALERT_KINDS = ["machine.silent", "job.late", "intake.silent", "delivery.undeliverable", "lane.conflict"] as const;
98
+ export type AlertKind = (typeof ALERT_KINDS)[number];
99
+
100
+ /** the bytes a machine signs to answer a challenge (UTF-8) */
101
+ export const linkSigningInput = (machine: string, nonce: string): string => `aip/1 link\n${machine}\n${nonce}`;
102
+
103
+ /** a lane placed on a machine (welcome, directory) */
104
+ export interface LaneEntry {
105
+ lane: string;
106
+ cwd?: string;
107
+ }
108
+ /** a lane a machine serves now: it has at least one live agent there */
109
+ export interface LaneStatus extends LaneEntry {
110
+ health: HealthState;
111
+ agents: number;
112
+ }
113
+ /** "job X ran" (ok) or "job X failed" (!ok); a job is late after 3 × every_s without an ok beat */
114
+ export interface JobBeat {
115
+ job: string;
116
+ ok: boolean;
117
+ at: number;
118
+ every_s: number;
119
+ detail?: string;
120
+ }
121
+ export interface Alert {
122
+ kind: AlertKind;
123
+ subject: string;
124
+ state: "open" | "cleared";
125
+ since: number;
126
+ detail?: string;
127
+ }
128
+ export interface ThreadRef {
129
+ channel: string;
130
+ thread_ts: string;
131
+ }
132
+
133
+ /** router → machine */
134
+ export type T1Frame =
135
+ | { v: typeof AIP_VERSION; op: "challenge"; nonce: string; epoch: string }
136
+ | { v: typeof AIP_VERSION; op: "welcome"; machine: string; epoch: string; mode: Mode; lanes: LaneEntry[]; now: number }
137
+ | { v: typeof AIP_VERSION; op: "deliver"; envelope: Envelope; late?: boolean }
138
+ | { v: typeof AIP_VERSION; op: "cancel"; key: string; why: string }
139
+ | { v: typeof AIP_VERSION; op: "directory"; lanes: LaneEntry[] }
140
+ | { v: typeof AIP_VERSION; op: "result"; ref: string; ok: boolean; error?: string; owner?: string }
141
+ | { v: typeof AIP_VERSION; op: "alert"; alert: Alert }
142
+ | { v: typeof AIP_VERSION; op: "error"; error: string };
143
+
144
+ /** machine → router */
145
+ export type T2Frame =
146
+ | { v: typeof AIP_VERSION; op: "auth"; machine: string; sig: string; version: string }
147
+ | { v: typeof AIP_VERSION; op: "heartbeat"; lanes: LaneStatus[]; jobs?: JobBeat[] }
148
+ | ({ v: typeof AIP_VERSION; op: "beat" } & JobBeat)
149
+ | { v: typeof AIP_VERSION; op: "receipt"; receipt: Receipt }
150
+ | { v: typeof AIP_VERSION; op: "ack"; ack: Ack }
151
+ | { v: typeof AIP_VERSION; op: "claim"; id: string; lane: string; thread: ThreadRef; to?: Record<string, string>; cc?: string[] }
152
+ | { v: typeof AIP_VERSION; op: "placement"; id: string; lane: string; cwd?: string; move?: boolean };
153
+
154
+ export const T1_OPS = ["challenge", "welcome", "deliver", "cancel", "directory", "result", "alert", "error"] as const;
155
+ export const T2_OPS = ["auth", "heartbeat", "beat", "receipt", "ack", "claim", "placement"] as const;
156
+
157
+ // ---- validators: the problems found ([] = valid). They check what this side relies on and ignore the rest
158
+ // (unknown fields are ignored, so a newer peer may send more).
159
+ type Obj = Record<string, unknown>;
160
+ const isObj = (x: unknown): x is Obj => typeof x === "object" && x !== null && !Array.isArray(x);
161
+
162
+ function base(x: unknown, what: string): { o?: Obj; errs: string[] } {
163
+ if (!isObj(x)) return { errs: [`${what}: not an object`] };
164
+ if (x.v !== AIP_VERSION) return { o: x, errs: [`${what}: unsupported version ${String(x.v)} (this side speaks aip/1)`] };
165
+ return { o: x, errs: [] };
166
+ }
167
+ function need(o: Obj, k: string, type: "string" | "number" | "boolean", errs: string[], what: string): void {
168
+ if (typeof o[k] !== type) errs.push(`${what}.${k}: want ${type}`);
169
+ }
170
+ function oneOf(o: Obj, k: string, allowed: readonly string[], errs: string[], what: string): void {
171
+ if (!allowed.includes(o[k] as string)) errs.push(`${what}.${k}: want one of ${allowed.join("|")}`);
172
+ }
173
+ const named = (o: Obj, k: string, re: RegExp, errs: string[], what: string, desc: string): void => {
174
+ if (typeof o[k] !== "string" || !re.test(o[k] as string)) errs.push(`${what}.${k}: want ${desc}`);
175
+ };
176
+
177
+ export function checkEnvelope(x: unknown): string[] {
178
+ const { o, errs } = base(x, "envelope");
179
+ if (!o || errs.length) return errs;
180
+ for (const k of ["key", "id", "to", "label", "text"]) need(o, k, "string", errs, "envelope");
181
+ need(o, "attempt", "number", errs, "envelope");
182
+ oneOf(o, "role", ROLES, errs, "envelope");
183
+ const s = o.src;
184
+ if (!isObj(s)) errs.push("envelope.src: want an object");
185
+ else {
186
+ for (const k of ["workspace", "channel", "ts"]) need(s, k, "string", errs, "envelope.src");
187
+ if (typeof s.ts === "string" && !TS.test(s.ts)) errs.push("envelope.src.ts: want a Slack ts");
188
+ if (!isObj(s.user) || typeof s.user.id !== "string" || typeof s.user.human !== "boolean") {
189
+ errs.push("envelope.src.user: want {id, human}");
190
+ }
191
+ }
192
+ if (o.role === "worker" && (!isObj(o.ack) || typeof o.ack.token !== "string")) {
193
+ errs.push("envelope.ack.token: a worker envelope needs a receipt token");
194
+ }
195
+ return errs;
196
+ }
197
+
198
+ export function checkReceipt(x: unknown): string[] {
199
+ const { o, errs } = base(x, "receipt");
200
+ if (!o || errs.length) return errs;
201
+ for (const k of ["key", "endpoint"]) need(o, k, "string", errs, "receipt");
202
+ need(o, "at", "number", errs, "receipt");
203
+ oneOf(o, "status", RECEIPT_STATUS, errs, "receipt");
204
+ return errs;
205
+ }
206
+
207
+ export function checkAck(x: unknown): string[] {
208
+ const { o, errs } = base(x, "ack");
209
+ if (!o || errs.length) return errs;
210
+ for (const k of ["token", "by"]) need(o, k, "string", errs, "ack");
211
+ need(o, "at", "number", errs, "ack");
212
+ oneOf(o, "kind", ACK_KINDS, errs, "ack");
213
+ return errs;
214
+ }
215
+
216
+ function laneEntries(x: unknown, what: string, errs: string[], status: boolean): void {
217
+ if (!Array.isArray(x)) return void errs.push(`${what}: want an array`);
218
+ x.forEach((e, i) => {
219
+ const w = `${what}[${i}]`;
220
+ if (!isObj(e)) return void errs.push(`${w}: not an object`);
221
+ named(e, "lane", NAME, errs, w, "a lane name");
222
+ if (e.cwd !== undefined && typeof e.cwd !== "string") errs.push(`${w}.cwd: want string`);
223
+ if (status) {
224
+ oneOf(e, "health", HEALTH, errs, w);
225
+ if (!Number.isInteger(e.agents) || (e.agents as number) < 0) errs.push(`${w}.agents: want a count`);
226
+ }
227
+ });
228
+ }
229
+
230
+ function jobBeat(o: Obj, what: string, errs: string[]): void {
231
+ named(o, "job", JOB, errs, what, "a job name");
232
+ need(o, "ok", "boolean", errs, what);
233
+ need(o, "at", "number", errs, what);
234
+ const e = o.every_s;
235
+ if (!Number.isInteger(e) || (e as number) < 1 || (e as number) > 604_800) errs.push(`${what}.every_s: want 1..604800 seconds`);
236
+ if (o.detail !== undefined && (typeof o.detail !== "string" || o.detail.length > 200)) {
237
+ errs.push(`${what}.detail: want a string of at most 200 chars`);
238
+ }
239
+ }
240
+
241
+ function linkBase(x: unknown, ops: readonly string[]): { o?: Obj; w: string; errs: string[] } {
242
+ const { o, errs } = base(x, "frame");
243
+ if (!o || errs.length) return { w: "frame", errs };
244
+ if (!ops.includes(o.op as string)) return { w: "frame", errs: [`frame.op: want one of ${ops.join("|")}`] };
245
+ return { o, w: `frame(${String(o.op)})`, errs };
246
+ }
247
+
248
+ /** a frame the router sends (the subrouter checks what it receives; the router's tests check what it sends) */
249
+ export function checkT1Frame(x: unknown): string[] {
250
+ const { o, w, errs } = linkBase(x, T1_OPS);
251
+ if (!o) return errs;
252
+ switch (o.op) {
253
+ case "challenge":
254
+ need(o, "nonce", "string", errs, w);
255
+ need(o, "epoch", "string", errs, w);
256
+ break;
257
+ case "welcome":
258
+ named(o, "machine", NAME, errs, w, "a machine name");
259
+ need(o, "epoch", "string", errs, w);
260
+ oneOf(o, "mode", MODES, errs, w);
261
+ need(o, "now", "number", errs, w);
262
+ laneEntries(o.lanes, `${w}.lanes`, errs, false);
263
+ break;
264
+ case "deliver": {
265
+ const env = o.envelope;
266
+ errs.push(...checkEnvelope(env).map((e) => `${w}: ${e}`));
267
+ if (isObj(env) && env.v === AIP_VERSION) {
268
+ named(env, "to", LANE_ADDRESS, errs, `${w}.envelope`, "lane:<name>[@<agent id>]");
269
+ if (env.role === "cancel") errs.push(`${w}.envelope.role: want worker|observer`);
270
+ }
271
+ if (o.late !== undefined && typeof o.late !== "boolean") errs.push(`${w}.late: want boolean`);
272
+ break;
273
+ }
274
+ case "cancel":
275
+ need(o, "key", "string", errs, w);
276
+ need(o, "why", "string", errs, w);
277
+ break;
278
+ case "directory":
279
+ laneEntries(o.lanes, `${w}.lanes`, errs, false);
280
+ break;
281
+ case "result":
282
+ need(o, "ref", "string", errs, w);
283
+ need(o, "ok", "boolean", errs, w);
284
+ for (const k of ["error", "owner"]) if (o[k] !== undefined && typeof o[k] !== "string") errs.push(`${w}.${k}: want string`);
285
+ break;
286
+ case "alert": {
287
+ const a = o.alert;
288
+ if (!isObj(a)) {
289
+ errs.push(`${w}.alert: want an object`);
290
+ break;
291
+ }
292
+ oneOf(a, "kind", ALERT_KINDS, errs, `${w}.alert`);
293
+ need(a, "subject", "string", errs, `${w}.alert`);
294
+ oneOf(a, "state", ["open", "cleared"], errs, `${w}.alert`);
295
+ need(a, "since", "number", errs, `${w}.alert`);
296
+ break;
297
+ }
298
+ case "error":
299
+ need(o, "error", "string", errs, w);
300
+ }
301
+ return errs;
302
+ }
303
+
304
+ /** a frame a machine sends (the router checks what it receives) */
305
+ export function checkT2Frame(x: unknown): string[] {
306
+ const { o, w, errs } = linkBase(x, T2_OPS);
307
+ if (!o) return errs;
308
+ switch (o.op) {
309
+ case "auth":
310
+ named(o, "machine", NAME, errs, w, "a machine name");
311
+ need(o, "sig", "string", errs, w);
312
+ need(o, "version", "string", errs, w);
313
+ break;
314
+ case "heartbeat":
315
+ laneEntries(o.lanes, `${w}.lanes`, errs, true);
316
+ if (o.jobs !== undefined) {
317
+ if (!Array.isArray(o.jobs)) errs.push(`${w}.jobs: want an array`);
318
+ else o.jobs.forEach((j, i) => (isObj(j) ? jobBeat(j, `${w}.jobs[${i}]`, errs) : errs.push(`${w}.jobs[${i}]: not an object`)));
319
+ }
320
+ break;
321
+ case "beat":
322
+ jobBeat(o, w, errs);
323
+ break;
324
+ case "receipt":
325
+ errs.push(...checkReceipt(o.receipt).map((e) => `${w}: ${e}`));
326
+ break;
327
+ case "ack":
328
+ errs.push(...checkAck(o.ack).map((e) => `${w}: ${e}`));
329
+ break;
330
+ case "claim": {
331
+ need(o, "id", "string", errs, w);
332
+ named(o, "lane", NAME, errs, w, "a lane name");
333
+ const t = o.thread;
334
+ if (!isObj(t)) errs.push(`${w}.thread: want {channel, thread_ts}`);
335
+ else {
336
+ named(t, "channel", CHANNEL, errs, `${w}.thread`, "a channel id");
337
+ named(t, "thread_ts", TS, errs, `${w}.thread`, "a Slack ts");
338
+ }
339
+ if (o.to !== undefined) {
340
+ if (!isObj(o.to)) errs.push(`${w}.to: want {label: lane address}`);
341
+ else {
342
+ for (const [l, a] of Object.entries(o.to)) {
343
+ if (!LABEL.test(l)) errs.push(`${w}.to.${l}: want a label like b2`);
344
+ if (typeof a !== "string" || !LANE_ADDRESS.test(a)) errs.push(`${w}.to.${l}: want lane:<name>[@<agent id>]`);
345
+ }
346
+ }
347
+ }
348
+ if (o.cc !== undefined && (!Array.isArray(o.cc) || !o.cc.every((a) => typeof a === "string" && LANE_ADDRESS.test(a)))) {
349
+ errs.push(`${w}.cc: want lane addresses`);
350
+ }
351
+ break;
352
+ }
353
+ case "placement":
354
+ need(o, "id", "string", errs, w);
355
+ named(o, "lane", NAME, errs, w, "a lane name");
356
+ if (o.cwd !== undefined && typeof o.cwd !== "string") errs.push(`${w}.cwd: want string`);
357
+ if (o.move !== undefined && typeof o.move !== "boolean") errs.push(`${w}.move: want boolean`);
358
+ }
359
+ return errs;
360
+ }
361
+
362
+ // ---- encoding and the challenge signature
363
+
364
+ const enc = new TextEncoder();
365
+
366
+ /** base64url without padding, of raw bytes. */
367
+ export function toBase64url(bytes: Uint8Array): string {
368
+ let bin = "";
369
+ for (const b of bytes) bin += String.fromCharCode(b);
370
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
371
+ }
372
+
373
+ /** Raw bytes of a base64url string (padding optional), or null when it is not base64url. */
374
+ export function fromBase64url(s: string): Uint8Array<ArrayBuffer> | null {
375
+ if (!/^[A-Za-z0-9_-]*={0,2}$/.test(s) || s.replace(/=+$/, "").length % 4 === 1) return null;
376
+ const b64 = s.replace(/=+$/, "").replace(/-/g, "+").replace(/_/g, "/");
377
+ const bin = atob(b64 + "===".slice((b64.length + 3) % 4));
378
+ return Uint8Array.from(bin, (c) => c.charCodeAt(0));
379
+ }
380
+
381
+ /** An enrolled machine key: a raw 32-byte Ed25519 public key, base64url without padding (= the JWK `x`). */
382
+ export const PUBKEY = /^[A-Za-z0-9_-]{43}$/;
383
+
384
+ /** A challenge nonce: 32 random bytes, base64url. */
385
+ export function newNonce(): string {
386
+ return toBase64url(crypto.getRandomValues(new Uint8Array(32)));
387
+ }
388
+
389
+ /** Does `sig` (base64url) sign the challenge `nonce` for `machine` under `pubkey` (raw Ed25519, base64url)?
390
+ * Any malformed input is simply false. */
391
+ export async function verifyLinkSignature(pubkey: string, machine: string, nonce: string, sig: string): Promise<boolean> {
392
+ const raw = PUBKEY.test(pubkey) ? fromBase64url(pubkey) : null;
393
+ const s = fromBase64url(sig);
394
+ if (!raw || raw.length !== 32 || !s || s.length !== 64) return false;
395
+ try {
396
+ const key = await crypto.subtle.importKey("raw", raw, { name: "Ed25519" }, false, ["verify"]);
397
+ return await crypto.subtle.verify({ name: "Ed25519" }, key, s, enc.encode(linkSigningInput(machine, nonce)));
398
+ } catch {
399
+ return false;
400
+ }
401
+ }
@@ -87,7 +87,8 @@ export async function verifySlack(
87
87
 
88
88
  // Housekeeping that is never a person talking. message_changed is dropped too:
89
89
  // `slack stream` does not re-emit edits, so ringing for one would only cost a scan.
90
- const SKIP_SUBTYPES = new Set([
90
+ // (The router's intake, router/intake.ts, skips the same subtypes.)
91
+ export const SKIP_SUBTYPES: ReadonlySet<string> = new Set([
91
92
  "message_changed", "message_deleted", "channel_join", "channel_leave", "group_join", "group_leave",
92
93
  "channel_topic", "channel_purpose", "channel_name", "pinned_item", "unpinned_item",
93
94
  // A hidden update to a thread parent: its outer ts names the update, not a
@@ -101,7 +102,7 @@ const USER = /^[UW][A-Z0-9]{2,}$/;
101
102
 
102
103
  /** The receiving app's bot user id when this event is that bot's own post:
103
104
  * the sender is the authorized bot user, or the post carries this app's id. */
104
- function selfPost(p: { api_app_id?: unknown; authorizations?: unknown }, e: Record<string, unknown>): string | undefined {
105
+ export function selfPost(p: { api_app_id?: unknown; authorizations?: unknown }, e: Record<string, unknown>): string | undefined {
105
106
  const auth = Array.isArray(p.authorizations) ? p.authorizations[0] as Record<string, unknown> | undefined : undefined;
106
107
  const botUser = auth && auth.is_bot === true && typeof auth.user_id === "string" && USER.test(auth.user_id) ? auth.user_id : undefined;
107
108
  if (!botUser) return undefined;
package/worker/README.md DELETED
@@ -1,216 +0,0 @@
1
- # slack-hub relay
2
-
3
- A Cloudflare Worker that turns Slack's **Events API** into a resumable stream of
4
- *doorbells* for `slack stream`. Slack posts each event to the Worker; the Worker
5
- keeps only `{channel, ts, thread_ts}` and pushes it over a WebSocket (or, for
6
- older clients, Server-Sent Events) to authenticated clients. Each client then
7
- reads the message itself, with its own token.
8
-
9
- ```
10
- Slack ──POST /slack/events──▶ Worker ──▶ Relay Durable Object (SQLite)
11
- │ seq {channel, ts, thread_ts}
12
- slack stream ◀──GET /ws (WebSocket, hibernating)┤
13
- older clients ◀──GET /stream (SSE, Bearer)──────┘
14
- ```
15
-
16
- ## Cost: why WebSocket
17
-
18
- A Durable Object is billed for **duration** while it is in memory, and an open
19
- SSE response keeps it there for as long as a client is connected — all day,
20
- for a stream that is idle most of the time. `/ws` instead uses the Durable
21
- Object [WebSocket Hibernation API](https://developers.cloudflare.com/durable-objects/best-practices/websockets/):
22
-
23
- - sockets are accepted with `ctx.acceptWebSocket()`, so between bells the object
24
- is evicted and not billed, while the connections stay open;
25
- - the client's keepalive (`"ping"` every 25 s) is answered `"pong"` by the
26
- runtime (`setWebSocketAutoResponse`) **without waking the object**;
27
- - all per-client state (resume position, acked position, replay/live, stall
28
- clock) lives in the socket's attachment (`serializeAttachment`), so it
29
- survives hibernation, and nothing waits on a timer.
30
-
31
- The object wakes only for a Slack event, a client connecting, a client's ack
32
- (sent within ~100 ms of the bells it acknowledges, while the object is still
33
- awake from the event), or the hourly TTL alarm.
34
-
35
- **SSE is kept for one release** so `slack stream` clients from before `/ws`
36
- keep working against a redeployed relay. Each connected SSE client keeps the
37
- object awake as before; `/health` shows `sse_clients` so you can see when none
38
- are left, after which `/stream` can be removed. New clients try `/ws` first and
39
- fall back to `/stream` for a connection only if the socket cannot be opened at
40
- all (an older relay, a proxy that strips upgrades, a runtime without
41
- `WebSocket`); `SLACK_RELAY_TRANSPORT=websocket|sse` pins one.
42
-
43
- ## Endpoints
44
-
45
- | Path | Auth | What |
46
- |---|---|---|
47
- | `POST /slack/events` | Slack signing secret (`X-Slack-Signature`, ±5 min) | Answers `url_verification`; stores one bell per `message` / `app_mention` event. Acks with a single SQLite insert, well inside Slack's 3 s. Retries collapse on `(channel, ts)`. |
48
- | `GET /ws?after=<seq>&epoch=<e>` | Subprotocols `slack-hub-relay.v1` (or the pre-rename `slack-term-relay.v1`) **and** `bearer.<base64url($RELAY_TOKEN)>` (or `Authorization: Bearer`) | WebSocket (below). Rejected with 401 before the upgrade is accepted. |
49
- | `GET /stream?after=<seq>` | `Authorization: Bearer $RELAY_TOKEN` | SSE (kept for older clients). First an `event: hello` frame `{seq, gap, retention_sec}`, then the backlog after `seq`, then live `event: bell` frames (`id:` = seq). A keepalive comment goes out every 25 s. `Last-Event-ID` works as well as `?after`. Pass `&epoch=` from the last hello: the epoch names the relay's storage, so a client resuming against a reset relay is told `gap: true` and gets everything kept, even once the new numbers have passed its old seq. If `after` is omitted, the stream starts from now. `gap: true` means some bells after `after` are gone (expired, or the relay was reset): everything still kept is replayed, and the client should also catch up by polling. |
50
- | `GET /health` | Bearer | `{epoch, latest, oldest, clients, websocket_clients, sse_clients, retention_sec}` |
51
-
52
- At most 16 clients (both kinds) at once; more get 503.
53
-
54
- ### The WebSocket protocol (`/ws`)
55
-
56
- **Auth.** The token is never put in the URL (query strings end up in logs).
57
- Node's built-in `WebSocket` cannot send an `Authorization` header, so the client
58
- offers three subprotocols — `Sec-WebSocket-Protocol: slack-hub-relay.v1, slack-term-relay.v1,
59
- bearer.<base64url(token)>` (base64url because subprotocols must be HTTP tokens;
60
- the same scheme Kubernetes uses) — and the Worker compares the bearer one in
61
- constant time before the request reaches the Durable Object. The server
62
- selects only `slack-hub-relay.v1` (or `slack-term-relay.v1` for an old client), never echoing the token.
63
-
64
- **Messages** are JSON text, one per frame:
65
-
66
- - server → client: `{"type":"hello","seq","gap","retention_sec","epoch"}` first
67
- (same resume rules as SSE: `after`, `epoch`, `gap`); then
68
- `{"type":"bell","seq":n,"bell":{channel,ts,thread_ts?,self?}}` — the backlog
69
- after `seq`, then live bells; and `"pong"` (from the runtime).
70
- - client → server: `"ping"` every 25 s; `{"type":"ack","seq":n}` for the highest
71
- bell received — at once after 32 unacked bells, else within 100 ms.
72
-
73
- **Flow control** replaces SSE's write backpressure, which a WebSocket send
74
- does not give: the backlog is replayed 100 bells at a time, each batch only
75
- after the previous one is acked, and the switch to live happens right after a
76
- storage read comes back empty (synchronously, so no bell falls in between). A
77
- client is closed — and resumes from storage with `?after` — when it has 64 live
78
- bells unacked (`4008 overflow`), makes no ack progress for 30 s while owing one
79
- (`4009 stalled`), or neither pings nor acks for 90 s (`4010 silent`). These
80
- checks run whenever the object is awake (an event, a connect, the alarm), since
81
- a hibernating object runs no timers.
82
-
83
- ## Privacy
84
-
85
- - **No message content is stored or served:** no text, no sender, no attachments.
86
- A bell holds a channel id and two timestamps — plus, on posts by **this app's own
87
- bot** only, `self`: that bot's user id. A client streaming as the bot never prints
88
- its own posts, so it skips the Web API read such a bell would cost (and, for
89
- `--replies-to`, learns from it that the bot is in the thread). No other sender
90
- is ever recorded.
91
- - **Bells are deleted 1 hour after arrival** (`RETENTION_SEC`, enforced by a
92
- Durable Object alarm). That window exists only so a client can resume.
93
- Anything older is covered by the client's catch-up poll, except replies
94
- under a thread parent older than the client's `--thread-window`: the poll
95
- cannot find those, so a bell that expired before the client read it is lost.
96
- - **Nothing logs a request body**, and Workers Logs are off (`observability`).
97
- - **Token holders see activity metadata.** Anyone with `RELAY_TOKEN` can watch
98
- *when* and *where* messages are posted — channel ids, timestamps and thread
99
- structure, for every conversation the bot is in, **including DMs** with it —
100
- even though they never see text or senders. Treat the token like read access
101
- to that timing data: give it only to consumers you trust, and rotate it
102
- (`wrangler secret put RELAY_TOKEN`) when one should lose access.
103
- - **A forged bell costs a few Web API reads at most:** one
104
- `conversations.replies` call, a few pages if needed, and up to 8 retries
105
- if the message is not found. The client applies its own filter to what
106
- Slack returns, so a forged bell never prints anything.
107
-
108
- ## Deploy
109
-
110
- ### Without cloning (recommended)
111
-
112
- The relay ships in the npm package as `slack-hub/worker`. Scaffold a Worker
113
- folder with the CLI:
114
-
115
- ```sh
116
- slack relay init my-relay # or: npx slack-hub relay init my-relay
117
- cd my-relay && npm install
118
- npx wrangler login # or CLOUDFLARE_API_TOKEN + CLOUDFLARE_ACCOUNT_ID (below)
119
- npx wrangler deploy
120
- ```
121
-
122
- `init` writes `package.json` (slack-hub as `^` the CLI's version, wrangler
123
- pinned), `wrangler.jsonc` (the same config as this folder's, with `--name` or
124
- the folder's name), `src/index.ts`, `.gitignore` and a `README.md`. It makes no
125
- network calls and refuses to overwrite existing files unless `--force`. It
126
- prints a freshly generated `RELAY_TOKEN` — not saved anywhere — and the
127
- remaining steps: the secrets, the Slack app settings and the client env, all
128
- as described below (run them from the new folder, with `npx wrangler`).
129
-
130
- Already have a Worker project? `src/index.ts` is just
131
-
132
- ```ts
133
- export { default, Relay } from "slack-hub/worker";
134
- ```
135
-
136
- with a `RELAY` Durable Object binding to class `Relay` and a
137
- `new_sqlite_classes: ["Relay"]` migration — copy them from
138
- [`wrangler.jsonc`](wrangler.jsonc). `Env` is exported too, for typing.
139
- `@cloudflare/workers-types` is an optional peer dependency of slack-hub.
140
-
141
- To update, bump `slack-hub` in the folder's package.json and redeploy.
142
-
143
- ### From a clone of this repo (contributors)
144
-
145
- Wrangler 4 needs **Node ≥ 22**.
146
-
147
- Cloudflare credentials, in the environment:
148
-
149
- - `CLOUDFLARE_API_TOKEN` — a token with the **Workers Scripts: Edit** permission
150
- (the "Edit Cloudflare Workers" template).
151
- - `CLOUDFLARE_ACCOUNT_ID` — from the dashboard sidebar.
152
-
153
- ```sh
154
- cd worker
155
- npx --yes wrangler@4.105.0 deploy
156
- npx --yes wrangler@4.105.0 secret put SLACK_SIGNING_SECRET # Slack app → Basic Information → Signing Secret
157
- npx --yes wrangler@4.105.0 secret put RELAY_TOKEN # long random string, shared with consumers (e.g. openssl rand -hex 32)
158
- npx --yes wrangler@4.105.0 secret put SLACK_TEAM_ID # optional: accept one workspace only (T…)
159
- ```
160
-
161
- Redeploying an existing relay keeps its storage (and epoch): no migration is
162
- needed, the Durable Object class is unchanged. A deploy restarts the object,
163
- which drops every connection; clients reconnect and resume from their last seq.
164
-
165
- ### Then, either way
166
-
167
- Check it (expects `{"ok":true,…}`):
168
-
169
- ```sh
170
- curl -H "Authorization: Bearer $RELAY_TOKEN" https://<worker>/health
171
- # or, with SLACK_RELAY_URL / SLACK_RELAY_TOKEN set:
172
- slack relay health
173
- ```
174
-
175
- Then, in the Slack app:
176
-
177
- 1. Go to **Event Subscriptions** and turn on **Enable Events**.
178
- 2. Set the **Request URL** to `https://<worker>/slack/events`. It should verify at once.
179
- 3. Under **Subscribe to bot events**, add:
180
- - `message.channels`
181
- - `message.groups`
182
- - `message.im`
183
- - `app_mention`
184
- - `message.mpim`, only if the bot has `mpim:history`.
185
- Each needs its bot scope (`channels:history`, `groups:history`, `im:history`,
186
- `app_mentions:read`); Slack offers to add them.
187
- 4. Click **Save**, then reinstall the app if Slack asks.
188
-
189
- The secrets must be in place first: Slack's URL verification is signed.
190
-
191
- Consumers set `SLACK_RELAY_URL=https://<worker>` and `SLACK_RELAY_TOKEN=…`
192
- (the same value as the `RELAY_TOKEN` secret). `slack stream` then uses the relay
193
- automatically and says so on stderr: `relay connected (websocket)` — or
194
- `(sse)` if it fell back. Optional: `SLACK_RELAY_TRANSPORT=websocket` or `sse`.
195
-
196
- ## Develop
197
-
198
- ```sh
199
- cd worker && bun install && bun run typecheck
200
- # or, from the repo root (what CI runs):
201
- bun run typecheck:worker
202
- ```
203
-
204
- The signature and event parsing live in `src/slack.ts`, and the WebSocket
205
- session logic (replay, acks, flow control, auth) in `src/hub.ts`; neither has
206
- Cloudflare types, and the CLI suite tests both (`tests/relay.test.ts`,
207
- `tests/relay-hub.test.ts`, `tests/relay-ws.test.ts`).
208
-
209
- To run the Worker locally (Node ≥ 22; on an older Node,
210
- `npx -y -p node@22 -- …` works):
211
-
212
- ```sh
213
- cd worker
214
- printf 'SLACK_SIGNING_SECRET=dev\nRELAY_TOKEN=dev\n' > .dev.vars # git-ignored
215
- npx --yes wrangler@4.105.0 dev --local
216
- ```