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.
- package/dist/cli.js +278 -271
- package/package.json +15 -7
- package/ts/ask.ts +41 -0
- package/ts/askPush.ts +21 -17
- package/ts/asyncArgs.ts +21 -0
- package/ts/cli.ts +275 -36
- package/ts/profiles.ts +19 -7
- package/ts/slack.ts +124 -11
- package/worker/src/index.ts +27 -0
- package/worker/src/router/admin.ts +80 -0
- package/worker/src/router/core.ts +1222 -0
- package/worker/src/router/do.ts +355 -0
- package/worker/src/router/fetch.ts +76 -0
- package/worker/src/router/intake.ts +82 -0
- package/worker/src/router/wire.ts +401 -0
- package/worker/src/slack.ts +3 -2
- package/worker/README.md +0 -216
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
// The Router Durable Object: a thin adapter from Cloudflare's runtime to the pure state machine in core.ts.
|
|
2
|
+
//
|
|
3
|
+
// - SQLite (ctx.storage.sql) and transactionSync → core's `Sql` / `Tx`;
|
|
4
|
+
// - hibernating WebSockets (ctx.acceptWebSocket) → core's `Link`. Per-socket auth state lives in the socket's
|
|
5
|
+
// attachment, so it survives hibernation; "ping" is answered "pong" by the runtime without waking the object, and
|
|
6
|
+
// a machine's liveness is max(its last frame, the runtime's last auto-response);
|
|
7
|
+
// - the alarm is always set to the earliest pending deadline (core.nextDeadline, plus unauthenticated sockets'
|
|
8
|
+
// 30 s auth timeout); there is no fixed tick.
|
|
9
|
+
//
|
|
10
|
+
// Opt-in: it exists only where a ROUTER binding is configured (wrangler.router.jsonc). Unlike the relay it stores
|
|
11
|
+
// message text: routed messages only, until delivery is final, at most 7 days (core.ts).
|
|
12
|
+
|
|
13
|
+
import { DurableObject } from "cloudflare:workers";
|
|
14
|
+
import type { Env } from "../index.ts";
|
|
15
|
+
import { readLimited } from "../slack.ts";
|
|
16
|
+
import { admin } from "./admin.ts";
|
|
17
|
+
import { type IntakeResult, type Link, RouterCore, type SqlCursor, type SqlValue } from "./core.ts";
|
|
18
|
+
import type { IntakeEvent } from "./intake.ts";
|
|
19
|
+
import {
|
|
20
|
+
AIP_VERSION, LINK_CLOSE, LINK_PATH, LINK_SUBPROTOCOL, MAX_FRAME_BYTES, type Mode, type T1Frame, type T2Frame, checkT2Frame, newNonce,
|
|
21
|
+
verifyLinkSignature,
|
|
22
|
+
} from "./wire.ts";
|
|
23
|
+
|
|
24
|
+
/** Per-socket state, kept with serializeAttachment (2 KiB max; this is ~150 B). Times are the router clock (ms). */
|
|
25
|
+
type Attachment = {
|
|
26
|
+
/** names this socket (and is the challenge it must sign) */
|
|
27
|
+
nonce: string;
|
|
28
|
+
opened: number;
|
|
29
|
+
/** new: challenged, not authenticated yet. authed: serving `machine`. closed: replaced, revoked or closing. */
|
|
30
|
+
state: "new" | "authed" | "closed";
|
|
31
|
+
machine?: string;
|
|
32
|
+
/** last frame received */
|
|
33
|
+
lastSeen: number;
|
|
34
|
+
/** its first heartbeat arrived (handshake step 6) */
|
|
35
|
+
hb: boolean;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
/** A pending handshake younger than this is never evicted to make room (a signed auth takes well under this). */
|
|
39
|
+
export const EVICT_AFTER_MS = 5_000;
|
|
40
|
+
/** No auth within this long: close 4408. */
|
|
41
|
+
export const AUTH_TIMEOUT_MS = 30_000;
|
|
42
|
+
/** Sockets at once, authenticated or not (one per machine is the norm). At the cap the oldest socket still in its
|
|
43
|
+
* handshake (and at least EVICT_AFTER_MS old) makes room, so unauthenticated sockets cannot lock machines out;
|
|
44
|
+
* authenticated ones are never evicted. */
|
|
45
|
+
export const MAX_SOCKETS = 64;
|
|
46
|
+
const ADMIN_BODY_MAX = 64 * 1024;
|
|
47
|
+
|
|
48
|
+
const att = (ws: WebSocket): Attachment | null => ws.deserializeAttachment() as Attachment | null;
|
|
49
|
+
|
|
50
|
+
export function modeOf(v: string | undefined): Mode {
|
|
51
|
+
return v === "live" ? "live" : "shadow";
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** "8-22" / "08-22" → JST hours; anything else → the default window. */
|
|
55
|
+
export function daytimeOf(v: string | undefined): { start: number; end: number } | undefined {
|
|
56
|
+
const m = /^(\d{1,2})-(\d{1,2})$/.exec(v ?? "");
|
|
57
|
+
if (!m) return undefined;
|
|
58
|
+
const start = Number(m[1]);
|
|
59
|
+
const end = Number(m[2]);
|
|
60
|
+
return start < end && end <= 24 ? { start, end } : undefined;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export class Router extends DurableObject<Env> {
|
|
64
|
+
/** TEST SEAM state (tickAt): clock offsets (ms) and the real time each began, so a runtime ping timestamp maps to
|
|
65
|
+
* the router clock of its own moment. Always empty in production: the router clock is Date.now(). */
|
|
66
|
+
private readonly skews: { from: number; skew: number }[] = [];
|
|
67
|
+
/** The alarm time last set (router clock); undefined after a restart, until set again. */
|
|
68
|
+
private armedFor: number | null | undefined;
|
|
69
|
+
/** Sockets (by nonce) closed by this instance or whose close handler ran: never counted again. */
|
|
70
|
+
private readonly gone = new Set<string>();
|
|
71
|
+
|
|
72
|
+
private readonly link: Link = {
|
|
73
|
+
machines: () => this.authed().map(([ws, a]) => {
|
|
74
|
+
const ping = this.ctx.getWebSocketAutoResponseTimestamp(ws);
|
|
75
|
+
return { machine: a.machine!, lastSeen: Math.max(a.lastSeen, ping ? this.clockAt(ping.getTime()) : 0) };
|
|
76
|
+
}),
|
|
77
|
+
send: (machine, frame) => {
|
|
78
|
+
let sent = false;
|
|
79
|
+
for (const [ws] of this.authed(machine)) sent = this.sendTo(ws, frame) || sent;
|
|
80
|
+
return sent;
|
|
81
|
+
},
|
|
82
|
+
close: (machine, code, reason) => {
|
|
83
|
+
for (const [ws] of this.authed(machine)) this.closeWs(ws, code, reason);
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
private readonly core: RouterCore;
|
|
88
|
+
|
|
89
|
+
constructor(ctx: DurableObjectState, env: Env) {
|
|
90
|
+
super(ctx, env);
|
|
91
|
+
ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair("ping", "pong"));
|
|
92
|
+
const daytime = daytimeOf(env.ROUTER_DAYTIME_JST);
|
|
93
|
+
this.core = new RouterCore({
|
|
94
|
+
sql: { exec: <T>(q: string, ...b: SqlValue[]) => ctx.storage.sql.exec(q, ...b) as unknown as SqlCursor<T> },
|
|
95
|
+
tx: (fn) => ctx.storage.transactionSync(fn),
|
|
96
|
+
link: this.link,
|
|
97
|
+
mode: modeOf(env.ROUTER_MODE),
|
|
98
|
+
...(daytime ? { daytime } : {}),
|
|
99
|
+
});
|
|
100
|
+
this.core.init();
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
private get skew(): number {
|
|
104
|
+
return this.skews.at(-1)?.skew ?? 0;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
private now(): number {
|
|
108
|
+
return Date.now() + this.skew;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** A runtime timestamp (real ms) → the router clock at that moment. */
|
|
112
|
+
private clockAt(real: number): number {
|
|
113
|
+
let skew = 0;
|
|
114
|
+
for (const k of this.skews) if (k.from < real) skew = k.skew;
|
|
115
|
+
return real + skew;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Intake RPC (from the Worker's POST /slack/events/<app>): dedupe, store, route — one transaction. */
|
|
119
|
+
async intake(app: string, ev: IntakeEvent): Promise<IntakeResult> {
|
|
120
|
+
const now = this.now();
|
|
121
|
+
this.expireAuth(now);
|
|
122
|
+
const r = this.core.intake(app, ev, now);
|
|
123
|
+
await this.arm(now);
|
|
124
|
+
return r;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** GET /router/link (the WebSocket) and the admin API; the Worker checked the admin bearer already. */
|
|
128
|
+
override async fetch(req: Request): Promise<Response> {
|
|
129
|
+
const url = new URL(req.url);
|
|
130
|
+
if (url.pathname === LINK_PATH) return this.accept(req);
|
|
131
|
+
let body: unknown;
|
|
132
|
+
if (req.method === "PUT" || req.method === "POST") {
|
|
133
|
+
const text = await readLimited(req.body, ADMIN_BODY_MAX);
|
|
134
|
+
if (text === null) return Response.json({ ok: false, error: "too large" }, { status: 413 });
|
|
135
|
+
try {
|
|
136
|
+
body = text ? JSON.parse(text) : undefined;
|
|
137
|
+
} catch {
|
|
138
|
+
return Response.json({ ok: false, error: "bad json" }, { status: 400 });
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
const now = this.now();
|
|
142
|
+
this.expireAuth(now);
|
|
143
|
+
this.core.tick(now);
|
|
144
|
+
const r = admin(this.core, { method: req.method, path: url.pathname, query: url.searchParams, body }, now);
|
|
145
|
+
await this.arm(now);
|
|
146
|
+
return Response.json(r.body, { status: r.status });
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
private async accept(req: Request): Promise<Response> {
|
|
150
|
+
const offered = (req.headers.get("sec-websocket-protocol") ?? "").split(",").map((p) => p.trim());
|
|
151
|
+
if (!offered.includes(LINK_SUBPROTOCOL)) return new Response(`offer subprotocol ${LINK_SUBPROTOCOL}`, { status: 400 });
|
|
152
|
+
const now = this.now();
|
|
153
|
+
this.expireAuth(now);
|
|
154
|
+
// `gone` only needs the nonces of sockets the runtime still lists; without this it grew with every churned socket.
|
|
155
|
+
const listed = new Set(this.ctx.getWebSockets().flatMap((ws) => att(ws)?.nonce ?? []));
|
|
156
|
+
for (const n of this.gone) if (!listed.has(n)) this.gone.delete(n);
|
|
157
|
+
const open = this.ctx.getWebSockets().flatMap((ws) => {
|
|
158
|
+
const s = att(ws);
|
|
159
|
+
return s && s.state !== "closed" && !this.gone.has(s.nonce) ? [[ws, s] as const] : [];
|
|
160
|
+
});
|
|
161
|
+
if (open.length >= MAX_SOCKETS) {
|
|
162
|
+
// Anyone who knows the URL can open sockets; only authenticated ones keep their slot.
|
|
163
|
+
// Only a handshake that had time to sign is evicted: churning sockets cannot push out a machine whose signed
|
|
164
|
+
// auth is in flight. With none that old the newcomer waits (503) and retries.
|
|
165
|
+
const pending = open.filter(([, s]) => s.state === "new" && now - s.opened >= EVICT_AFTER_MS).sort((x, y) => x[1].opened - y[1].opened);
|
|
166
|
+
if (!pending.length) return new Response("too many sockets", { status: 503 });
|
|
167
|
+
this.closeWs(pending[0]![0], LINK_CLOSE.authTimeout, "room for a newer handshake");
|
|
168
|
+
}
|
|
169
|
+
const [client, server] = Object.values(new WebSocketPair()) as [WebSocket, WebSocket];
|
|
170
|
+
this.ctx.acceptWebSocket(server);
|
|
171
|
+
const a: Attachment = { nonce: newNonce(), opened: now, state: "new", lastSeen: now, hb: false };
|
|
172
|
+
server.serializeAttachment(a);
|
|
173
|
+
this.sendTo(server, { v: AIP_VERSION, op: "challenge", nonce: a.nonce, epoch: this.core.epoch });
|
|
174
|
+
await this.arm(now);
|
|
175
|
+
return new Response(null, { status: 101, webSocket: client, headers: { "sec-websocket-protocol": LINK_SUBPROTOCOL } });
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
override async webSocketMessage(ws: WebSocket, data: string | ArrayBuffer): Promise<void> {
|
|
179
|
+
const a = att(ws);
|
|
180
|
+
if (!a || a.state === "closed" || this.gone.has(a.nonce)) return;
|
|
181
|
+
const now = this.now();
|
|
182
|
+
const p = parseFrame(data);
|
|
183
|
+
if (a.state === "new") return this.auth(ws, a, p);
|
|
184
|
+
a.lastSeen = now;
|
|
185
|
+
let first = false;
|
|
186
|
+
if (p.frame?.op === "heartbeat" && !a.hb) first = a.hb = true;
|
|
187
|
+
ws.serializeAttachment(a);
|
|
188
|
+
this.expireAuth(now);
|
|
189
|
+
if (!p.frame) this.sendTo(ws, { v: AIP_VERSION, op: "error", error: p.error });
|
|
190
|
+
else this.core.handle(a.machine!, p.frame, now, first);
|
|
191
|
+
await this.arm(now);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** The first frame must be `auth`, signed over the challenge with the machine's enrolled key. */
|
|
195
|
+
private async auth(ws: WebSocket, a: Attachment, p: { frame?: T2Frame; error: string; op?: unknown }): Promise<void> {
|
|
196
|
+
if (p.op !== "auth") return this.closeWs(ws, LINK_CLOSE.authFailed, "auth required");
|
|
197
|
+
const f = p.frame?.op === "auth" ? p.frame : undefined;
|
|
198
|
+
const pub = f ? this.core.pubkeyOf(f.machine) : null;
|
|
199
|
+
const good = f !== undefined && pub !== null && (await verifyLinkSignature(pub, f.machine, a.nonce, f.sig));
|
|
200
|
+
// The socket may have closed, or another auth frame raced this one, while the signature was checked.
|
|
201
|
+
const cur = att(ws);
|
|
202
|
+
if (!cur || cur.state !== "new" || this.gone.has(cur.nonce) || ws.readyState !== 1 /* OPEN */) return;
|
|
203
|
+
if (!good || !f) {
|
|
204
|
+
this.sendTo(ws, { v: AIP_VERSION, op: "error", error: "auth failed" });
|
|
205
|
+
return this.closeWs(ws, LINK_CLOSE.authFailed, "auth failed");
|
|
206
|
+
}
|
|
207
|
+
const now = this.now();
|
|
208
|
+
Object.assign(cur, { state: "authed", machine: f.machine, lastSeen: now } satisfies Partial<Attachment>);
|
|
209
|
+
ws.serializeAttachment(cur);
|
|
210
|
+
// One socket per machine: the newer replaces the older.
|
|
211
|
+
for (const [old, oa] of this.authed(f.machine)) if (oa.nonce !== cur.nonce) this.closeWs(old, LINK_CLOSE.replaced, "replaced");
|
|
212
|
+
this.expireAuth(now);
|
|
213
|
+
this.core.authenticated(f.machine, f.version, now);
|
|
214
|
+
await this.arm(now);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
override async webSocketClose(ws: WebSocket, code: number): Promise<void> {
|
|
218
|
+
await this.closed(ws, code === 1005 || code === 1006 ? 1000 : code);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
override async webSocketError(ws: WebSocket): Promise<void> {
|
|
222
|
+
await this.closed(ws, 1011);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
private async closed(ws: WebSocket, code: number): Promise<void> {
|
|
226
|
+
const a = att(ws);
|
|
227
|
+
if (a) {
|
|
228
|
+
this.gone.add(a.nonce);
|
|
229
|
+
// Also on the socket itself: `gone` is pruned, and an auth still verifying must not revive this socket.
|
|
230
|
+
try {
|
|
231
|
+
ws.serializeAttachment({ ...a, state: "closed" } satisfies Attachment);
|
|
232
|
+
} catch {
|
|
233
|
+
/* closed already */
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
try {
|
|
237
|
+
ws.close(code, "bye");
|
|
238
|
+
} catch {
|
|
239
|
+
/* already closed */
|
|
240
|
+
}
|
|
241
|
+
const now = this.now();
|
|
242
|
+
this.expireAuth(now);
|
|
243
|
+
if (a?.state === "authed") this.core.tick(now); // its machine may be offline now (q2: fail over at once)
|
|
244
|
+
await this.arm(now);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
override async alarm(): Promise<void> {
|
|
248
|
+
this.armedFor = null;
|
|
249
|
+
await this.run(this.now());
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** TEST SEAM (worker/test only; nothing in the Worker calls it): move this object's clock forward to `ms` (never
|
|
253
|
+
* back; tickAt(0) just reads it) and run exactly what the alarm runs. Returns the router clock. The offset stays,
|
|
254
|
+
* so later events (frames, intake, the real alarm, which is set `offset` earlier) see the same clock, and a
|
|
255
|
+
* runtime ping counts at the router time it happened. */
|
|
256
|
+
async tickAt(ms: number): Promise<number> {
|
|
257
|
+
// Refused unless the worker suite's own binding is set (worker/vitest.config.ts): a deployed Router's clock is
|
|
258
|
+
// Date.now(), whatever calls this.
|
|
259
|
+
if (this.env.ROUTER_TEST_SEAM !== "1") throw new Error("tickAt is a test seam (ROUTER_TEST_SEAM is not set)");
|
|
260
|
+
const skew = Math.max(this.skew, ms - Date.now());
|
|
261
|
+
if (skew !== this.skew) this.skews.push({ from: Date.now(), skew });
|
|
262
|
+
const now = this.now();
|
|
263
|
+
await this.run(now);
|
|
264
|
+
return now;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
private async run(now: number): Promise<void> {
|
|
268
|
+
this.expireAuth(now);
|
|
269
|
+
this.core.tick(now);
|
|
270
|
+
await this.arm(now);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Close sockets that did not authenticate within AUTH_TIMEOUT_MS (checked whenever the object is awake). */
|
|
274
|
+
private expireAuth(now: number): void {
|
|
275
|
+
for (const ws of this.ctx.getWebSockets()) {
|
|
276
|
+
const a = att(ws);
|
|
277
|
+
if (a?.state === "new" && !this.gone.has(a.nonce) && now - a.opened >= AUTH_TIMEOUT_MS) this.closeWs(ws, LINK_CLOSE.authTimeout, "auth timeout");
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** Set the alarm to the earliest pending deadline, or clear it. */
|
|
282
|
+
private async arm(now: number): Promise<void> {
|
|
283
|
+
let next = this.core.nextDeadline(now);
|
|
284
|
+
for (const ws of this.ctx.getWebSockets()) {
|
|
285
|
+
const a = att(ws);
|
|
286
|
+
if (a?.state === "new" && !this.gone.has(a.nonce)) next = Math.min(next ?? Infinity, a.opened + AUTH_TIMEOUT_MS);
|
|
287
|
+
}
|
|
288
|
+
if (next === null) {
|
|
289
|
+
if (this.armedFor !== null) await this.ctx.storage.deleteAlarm();
|
|
290
|
+
this.armedFor = null;
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
const at = Math.max(next, now + 500);
|
|
294
|
+
if (this.armedFor === at) return;
|
|
295
|
+
await this.ctx.storage.setAlarm(at - this.skew);
|
|
296
|
+
this.armedFor = at;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** Open, authenticated sockets (of one machine). */
|
|
300
|
+
private authed(machine?: string): [WebSocket, Attachment][] {
|
|
301
|
+
const out: [WebSocket, Attachment][] = [];
|
|
302
|
+
for (const ws of this.ctx.getWebSockets()) {
|
|
303
|
+
if (ws.readyState !== WebSocket.OPEN) continue;
|
|
304
|
+
const a = att(ws);
|
|
305
|
+
if (a?.state === "authed" && !this.gone.has(a.nonce) && (machine === undefined || a.machine === machine)) out.push([ws, a]);
|
|
306
|
+
}
|
|
307
|
+
return out;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
private sendTo(ws: WebSocket, frame: T1Frame): boolean {
|
|
311
|
+
try {
|
|
312
|
+
ws.send(JSON.stringify(frame));
|
|
313
|
+
return true;
|
|
314
|
+
} catch {
|
|
315
|
+
this.closeWs(ws, 1011, "send failed");
|
|
316
|
+
return false;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
private closeWs(ws: WebSocket, code: number, reason: string): void {
|
|
321
|
+
const a = att(ws);
|
|
322
|
+
if (a) {
|
|
323
|
+
this.gone.add(a.nonce);
|
|
324
|
+
try {
|
|
325
|
+
ws.serializeAttachment({ ...a, state: "closed" } satisfies Attachment);
|
|
326
|
+
} catch {
|
|
327
|
+
/* closed already */
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
try {
|
|
331
|
+
ws.close(code, reason);
|
|
332
|
+
} catch {
|
|
333
|
+
/* closed already */
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
const enc = new TextEncoder();
|
|
339
|
+
|
|
340
|
+
/** One text frame → a validated machine frame, or the error to answer with. `op`: the op it claimed, if any. */
|
|
341
|
+
export function parseFrame(data: string | ArrayBuffer): { frame?: T2Frame; error: string; op?: unknown } {
|
|
342
|
+
if (typeof data !== "string") return { error: "binary frames are not part of aip/1" };
|
|
343
|
+
if (data.length > MAX_FRAME_BYTES || (data.length * 3 > MAX_FRAME_BYTES && enc.encode(data).length > MAX_FRAME_BYTES)) {
|
|
344
|
+
return { error: `frame larger than ${MAX_FRAME_BYTES} bytes` };
|
|
345
|
+
}
|
|
346
|
+
let x: unknown;
|
|
347
|
+
try {
|
|
348
|
+
x = JSON.parse(data);
|
|
349
|
+
} catch {
|
|
350
|
+
return { error: "not JSON" };
|
|
351
|
+
}
|
|
352
|
+
const op = x && typeof x === "object" ? (x as { op?: unknown }).op : undefined;
|
|
353
|
+
const errs = checkT2Frame(x);
|
|
354
|
+
return errs.length ? { error: errs.join("; "), op } : { frame: x as T2Frame, error: "", op };
|
|
355
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// The Worker side of the Router: /router/* and POST /slack/events/<app>. index.ts calls this only when the ROUTER
|
|
2
|
+
// binding exists; without it those paths answer 404 exactly as before.
|
|
3
|
+
//
|
|
4
|
+
// POST /slack/events/<app> Slack Events API for one app: its own signing secret SLACK_SIGNING_SECRET_<APP> (app
|
|
5
|
+
// upper-cased, "-" → "_"; missing → 404), optional SLACK_TEAM_ID_<APP>. The same
|
|
6
|
+
// pre-checks as /slack/events. The event goes to the Router (intake RPC); when
|
|
7
|
+
// ROUTER_BELL_APP is <app> it also rings the relay's doorbell exactly as /slack/events
|
|
8
|
+
// does, so one Slack Request URL can feed both.
|
|
9
|
+
// GET /router/link the machines' WebSocket (aip/1 link; auth is the challenge, inside the object)
|
|
10
|
+
// /router/* admin API, Authorization: Bearer <ROUTER_ADMIN_TOKEN> (unset → always 401)
|
|
11
|
+
|
|
12
|
+
import type { Env, Relay } from "../index.ts";
|
|
13
|
+
import { MAX_BODY_BYTES, doorbellOf, plausiblySigned, readLimited, safeEqual, verifySlack } from "../slack.ts";
|
|
14
|
+
import type { Router } from "./do.ts";
|
|
15
|
+
import { intakeOf } from "./intake.ts";
|
|
16
|
+
import { LINK_PATH, NAME } from "./wire.ts";
|
|
17
|
+
|
|
18
|
+
/** The Worker variable for one app's setting: SLACK_SIGNING_SECRET_<APP>, app upper-cased, "-" → "_". */
|
|
19
|
+
export const appVar = (prefix: string, app: string): string => `${prefix}_${app.toUpperCase().replace(/-/g, "_")}`;
|
|
20
|
+
|
|
21
|
+
const notFound = (): Response => new Response("not found", { status: 404 });
|
|
22
|
+
|
|
23
|
+
function envString(env: Env, name: string): string | undefined {
|
|
24
|
+
const v = (env as unknown as Record<string, unknown>)[name];
|
|
25
|
+
return typeof v === "string" && v ? v : undefined;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export async function routerFetch(
|
|
29
|
+
req: Request, url: URL, env: Env, router: DurableObjectStub<Router>, relay: DurableObjectStub<Relay>,
|
|
30
|
+
): Promise<Response> {
|
|
31
|
+
const ev = /^\/slack\/events\/([^/]+)$/.exec(url.pathname);
|
|
32
|
+
if (ev) return slackEvents(req, ev[1]!, env, router, relay);
|
|
33
|
+
if (url.pathname === LINK_PATH) {
|
|
34
|
+
if (req.method !== "GET") return new Response("method not allowed", { status: 405 });
|
|
35
|
+
if (req.headers.get("upgrade")?.toLowerCase() !== "websocket") return new Response("upgrade required", { status: 426 });
|
|
36
|
+
return router.fetch(req);
|
|
37
|
+
}
|
|
38
|
+
if (url.pathname.startsWith("/router/")) {
|
|
39
|
+
const token = env.ROUTER_ADMIN_TOKEN;
|
|
40
|
+
if (!token || !safeEqual(req.headers.get("authorization") ?? "", `Bearer ${token}`)) return new Response("unauthorized", { status: 401 });
|
|
41
|
+
return router.fetch(req);
|
|
42
|
+
}
|
|
43
|
+
return notFound();
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function slackEvents(req: Request, app: string, env: Env, router: DurableObjectStub<Router>, relay: DurableObjectStub<Relay>): Promise<Response> {
|
|
47
|
+
const secret = NAME.test(app) ? envString(env, appVar("SLACK_SIGNING_SECRET", app)) : undefined;
|
|
48
|
+
if (!secret) return notFound();
|
|
49
|
+
if (req.method !== "POST") return new Response("method not allowed", { status: 405 });
|
|
50
|
+
const timestamp = req.headers.get("x-slack-request-timestamp");
|
|
51
|
+
const signature = req.headers.get("x-slack-signature");
|
|
52
|
+
if (!plausiblySigned(timestamp, signature, Date.now() / 1000)) return new Response("bad signature", { status: 401 });
|
|
53
|
+
if (Number(req.headers.get("content-length") ?? 0) > MAX_BODY_BYTES) return new Response("too large", { status: 413 });
|
|
54
|
+
const body = await readLimited(req.body);
|
|
55
|
+
if (body === null) return new Response("too large", { status: 413 });
|
|
56
|
+
if (!(await verifySlack(secret, timestamp, signature, body, Date.now() / 1000))) return new Response("bad signature", { status: 401 });
|
|
57
|
+
let payload: { type?: unknown; challenge?: unknown };
|
|
58
|
+
try {
|
|
59
|
+
payload = JSON.parse(body) as typeof payload;
|
|
60
|
+
} catch {
|
|
61
|
+
return new Response("bad json", { status: 400 });
|
|
62
|
+
}
|
|
63
|
+
if (payload.type === "url_verification" && typeof payload.challenge === "string") {
|
|
64
|
+
return new Response(payload.challenge, { headers: { "content-type": "text/plain" } });
|
|
65
|
+
}
|
|
66
|
+
// The doorbell first: a Router that fails (500, so Slack retries) never delays a bell, and the retry's bell
|
|
67
|
+
// collapses on the relay's UNIQUE (channel, ts, rid).
|
|
68
|
+
if (env.ROUTER_BELL_APP === app) {
|
|
69
|
+
const bell = doorbellOf(payload, env.SLACK_TEAM_ID || undefined);
|
|
70
|
+
if (bell) await relay.ring(bell);
|
|
71
|
+
}
|
|
72
|
+
// One SQLite transaction in the Router: dedupe (event_id, then team/channel/ts), store, route.
|
|
73
|
+
const intake = intakeOf(payload, envString(env, appVar("SLACK_TEAM_ID", app)));
|
|
74
|
+
if (intake) await router.intake(app, intake);
|
|
75
|
+
return new Response(null, { status: 200 });
|
|
76
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// The router's intake: one Events API payload → the message the router routes. Pure (no Cloudflare types), tested
|
|
2
|
+
// under bun (tests/router-intake.test.ts).
|
|
3
|
+
//
|
|
4
|
+
// Unlike the relay's doorbell (slack.ts), this keeps the text: the router hands it to the machine that serves the
|
|
5
|
+
// target lane, so no machine needs a Slack token to read it. The Router keeps it only for routed messages and only
|
|
6
|
+
// until every delivery of the message is final, at most 7 days (see core.ts).
|
|
7
|
+
|
|
8
|
+
import { SKIP_SUBTYPES, selfPost } from "../slack.ts";
|
|
9
|
+
import { CHANNEL, TS } from "./wire.ts";
|
|
10
|
+
|
|
11
|
+
/** One message as the router routes it. */
|
|
12
|
+
export type RoutedMessage = {
|
|
13
|
+
/** the payload's team_id (T…), or "-" when absent */
|
|
14
|
+
team: string;
|
|
15
|
+
channel: string;
|
|
16
|
+
ts: string;
|
|
17
|
+
/** set on a reply only (a root has none, even when Slack sends thread_ts == ts) */
|
|
18
|
+
thread_ts?: string;
|
|
19
|
+
/** the sender: a U…/W… user id, else the bot id, else "" */
|
|
20
|
+
user: string;
|
|
21
|
+
/** a person: a U…/W… user, no bot_id, not a bot_message, not the receiving app's own bot */
|
|
22
|
+
human: boolean;
|
|
23
|
+
/** posted by a bot (bot_id or subtype bot_message) */
|
|
24
|
+
bot: boolean;
|
|
25
|
+
/** posted by the receiving app's own bot: never delivered */
|
|
26
|
+
self: boolean;
|
|
27
|
+
text: string;
|
|
28
|
+
/** attached files' names (never their content) */
|
|
29
|
+
files?: string[];
|
|
30
|
+
/** a thread root's "[lane] …" prefix (after an optional :emoji: and *; "[lane@host]" too) */
|
|
31
|
+
root?: string;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/** What the router learns from one event_callback: always the app's sign of life (event_id when Slack sent one),
|
|
35
|
+
* and the message when the event is one it can route. */
|
|
36
|
+
export type IntakeEvent = { event_id?: string; message?: RoutedMessage };
|
|
37
|
+
|
|
38
|
+
const USER = /^[UW][A-Z0-9]{2,}$/;
|
|
39
|
+
/** "[alpha] …", ":robot_face: *[alpha]* …", "[alpha@host] …" → alpha */
|
|
40
|
+
export const ROOT_PREFIX = /^(?::[a-z0-9_+-]+:\s*)?\*?\[([a-z0-9][a-z0-9-]{0,31})(?:@[a-z0-9-]+)?\]/;
|
|
41
|
+
|
|
42
|
+
/** The intake view of one Events API payload; null when it is not an event_callback (or another team's, when
|
|
43
|
+
* `teamId` is set). */
|
|
44
|
+
export function intakeOf(payload: unknown, teamId?: string): IntakeEvent | null {
|
|
45
|
+
if (!payload || typeof payload !== "object") return null;
|
|
46
|
+
const p = payload as { type?: unknown; team_id?: unknown; event_id?: unknown; api_app_id?: unknown; authorizations?: unknown; event?: unknown };
|
|
47
|
+
if (p.type !== "event_callback" || !p.event || typeof p.event !== "object") return null;
|
|
48
|
+
if (teamId && p.team_id !== teamId) return null;
|
|
49
|
+
const out: IntakeEvent = typeof p.event_id === "string" && p.event_id ? { event_id: p.event_id } : {};
|
|
50
|
+
const m = messageOf(p, p.event as Record<string, unknown>);
|
|
51
|
+
if (m) out.message = m;
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function messageOf(p: { team_id?: unknown; api_app_id?: unknown; authorizations?: unknown }, e: Record<string, unknown>): RoutedMessage | null {
|
|
56
|
+
if (e.type !== "message" && e.type !== "app_mention") return null;
|
|
57
|
+
if (typeof e.subtype === "string" && SKIP_SUBTYPES.has(e.subtype)) return null;
|
|
58
|
+
if (e.hidden === true) return null;
|
|
59
|
+
const { channel, ts } = e;
|
|
60
|
+
// The link carries Slack's own ts shape only (the subrouter rejects anything else).
|
|
61
|
+
if (typeof channel !== "string" || !CHANNEL.test(channel) || typeof ts !== "string" || !TS.test(ts)) return null;
|
|
62
|
+
const thread_ts = typeof e.thread_ts === "string" && TS.test(e.thread_ts) && e.thread_ts !== ts ? e.thread_ts : undefined;
|
|
63
|
+
const self = selfPost(p, e) !== undefined;
|
|
64
|
+
const userId = typeof e.user === "string" && USER.test(e.user) ? e.user : undefined;
|
|
65
|
+
const botId = typeof e.bot_id === "string" && e.bot_id ? e.bot_id : undefined;
|
|
66
|
+
const bot = botId !== undefined || e.subtype === "bot_message";
|
|
67
|
+
const text = typeof e.text === "string" ? e.text : "";
|
|
68
|
+
const files = Array.isArray(e.files)
|
|
69
|
+
? e.files.flatMap((f) => (f && typeof f === "object" && typeof (f as { name?: unknown }).name === "string" ? [(f as { name: string }).name] : []))
|
|
70
|
+
: [];
|
|
71
|
+
const root = thread_ts === undefined ? ROOT_PREFIX.exec(text)?.[1] : undefined;
|
|
72
|
+
return {
|
|
73
|
+
team: typeof p.team_id === "string" && p.team_id ? p.team_id : "-",
|
|
74
|
+
channel, ts,
|
|
75
|
+
...(thread_ts !== undefined ? { thread_ts } : {}),
|
|
76
|
+
user: userId ?? botId ?? "",
|
|
77
|
+
human: userId !== undefined && !bot && !self,
|
|
78
|
+
bot, self, text,
|
|
79
|
+
...(files.length ? { files } : {}),
|
|
80
|
+
...(root !== undefined ? { root } : {}),
|
|
81
|
+
};
|
|
82
|
+
}
|