slack-term 1.57.0 → 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/ts/slack.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  // Slack Web API client (user token, Authorization: Bearer)
2
+ import { hubEnv } from "./brand.ts";
2
3
  import { resolveCookie } from "./profiles.ts";
3
4
  import { linkifyRichText } from "./urlGuard.ts";
4
5
  import { repairMessageText } from "./newlines.ts";
@@ -41,6 +42,40 @@ function base(): string {
41
42
  return (process.env.SLACK_API_BASE ?? "https://slack.com/api").replace(/\/$/, "");
42
43
  }
43
44
 
45
+ /** Where a request went, for an error message: the URL's origin, or the text
46
+ * itself when it is not a URL. */
47
+ function originOf(url: string): string {
48
+ return URL.canParse(url) ? new URL(url).origin : url;
49
+ }
50
+
51
+ /** `fetch`, except that getting no answer at all is reported in words of our
52
+ * own rather than the runtime's: `Slack request failed on <what>: no answer
53
+ * from <origin>`. The same on every runtime and in the Rust port, which has
54
+ * to print exactly what this prints once a write has gone out. */
55
+ export async function fetchOrSay(what: string, url: string, init?: RequestInit): Promise<Response> {
56
+ try {
57
+ return await fetch(url, init);
58
+ } catch {
59
+ throw new Error(`Slack request failed on ${what}: no answer from ${originOf(url)}`);
60
+ }
61
+ }
62
+
63
+ /** The body of an answer as JSON, or an error of our own when it is not JSON
64
+ * (an HTML error page from a proxy, a cut-off body). */
65
+ export async function jsonOrSay(what: string, res: Response): Promise<unknown> {
66
+ let text: string;
67
+ try {
68
+ text = await res.text();
69
+ } catch {
70
+ throw new Error(`Slack request failed on ${what}: the answer (HTTP ${res.status}) was cut off`);
71
+ }
72
+ try {
73
+ return JSON.parse(text);
74
+ } catch {
75
+ throw new Error(`Slack error on ${what}: the answer (HTTP ${res.status}) is not JSON`);
76
+ }
77
+ }
78
+
44
79
  /** How long one call may spend waiting out 429s before it throws
45
80
  * RateLimitError (seconds, summed over its retries). A 429 means Slack
46
81
  * rejected the request unprocessed, so retrying it — even a write — cannot
@@ -79,7 +114,8 @@ async function callOnce(token: string, method: string, init: RequestInit, cookie
79
114
  cookie = token.startsWith("xoxc-") ? (cookie ?? resolveCookie()) : undefined;
80
115
  const extraHeaders: Record<string, string> = {};
81
116
  if (cookie) extraHeaders["Cookie"] = `d=${cookie}`;
82
- const res = await fetch(`${base()}/${method}`, {
117
+ const started = performance.now();
118
+ const res = await fetchOrSay(method, `${base()}/${method}`, {
83
119
  ...init,
84
120
  headers: {
85
121
  ...(init.headers ?? {}),
@@ -87,11 +123,12 @@ async function callOnce(token: string, method: string, init: RequestInit, cookie
87
123
  ...extraHeaders,
88
124
  },
89
125
  });
126
+ timing(method.replace(/\?.*$/, ""), res.status, performance.now() - started);
90
127
  if (res.status === 429) {
91
128
  const retryAfter = parseInt(res.headers.get("retry-after") ?? "60", 10);
92
129
  throw new RateLimitError(isNaN(retryAfter) ? 60 : retryAfter, method);
93
130
  }
94
- const body = (await res.json()) as { ok?: boolean; error?: string } & Record<string, Json>;
131
+ const body = (await jsonOrSay(method, res)) as { ok?: boolean; error?: string } & Record<string, Json>;
95
132
  if (body.ok !== true) {
96
133
  const err = body.error ?? "unknown";
97
134
  if (err === "ratelimited") throw new RateLimitError(60, method);
@@ -121,11 +158,24 @@ async function callOnce(token: string, method: string, init: RequestInit, cookie
121
158
  ` Or import your Slack desktop session: slack auth login`,
122
159
  );
123
160
  }
124
- throw new Error(`Slack error on ${method}: ${err}`);
161
+ throw new Error(`Slack error on ${method}: ${err}${authSourceHint(err, token)}`);
125
162
  }
126
163
  return body as Json;
127
164
  }
128
165
 
166
+ // Which credential the CLI is using, by NAME only ("SLACK_TOKEN", `profile "acme"`).
167
+ // Set by cli.ts once the token is resolved, so an auth failure can say which
168
+ // source failed — a revoked exported SLACK_TOKEN otherwise looks like a broken profile.
169
+ let authSourceLabel: string | undefined;
170
+ export function setAuthSourceLabel(label: string | undefined): void { authSourceLabel = label; }
171
+ const AUTH_ERRORS = new Set(["invalid_auth", "not_authed", "token_revoked", "token_expired", "account_inactive"]);
172
+ export function authSourceHint(err: string, token = ""): string {
173
+ if (!AUTH_ERRORS.has(err)) return "";
174
+ // Bot tokens only ever come from SLACK_BOT_TOKEN (or an identity's env).
175
+ if (token.startsWith("xoxb-")) return ` (bot token from ${process.env.SLACK_HUB_IDENTITY ? `identity @${process.env.SLACK_HUB_IDENTITY}` : "SLACK_BOT_TOKEN"})`;
176
+ return authSourceLabel ? ` (token from ${authSourceLabel})` : "";
177
+ }
178
+
129
179
  // Internal Slack API caller — does NOT reject xoxc tokens.
130
180
  // Used for hidden endpoints (drafts, etc.) only accessible via session tokens.
131
181
  // cookie: raw xoxd value (without "d=" prefix); injected as Cookie header when present.
@@ -136,7 +186,8 @@ function callSession(token: string, method: string, init: RequestInit, cookie?:
136
186
  async function callSessionOnce(token: string, method: string, init: RequestInit, cookie?: string): Promise<Json> {
137
187
  const extraHeaders: Record<string, string> = {};
138
188
  if (cookie) extraHeaders["Cookie"] = `d=${cookie}`;
139
- const res = await fetch(`${base()}/${method}`, {
189
+ const started = performance.now();
190
+ const res = await fetchOrSay(method, `${base()}/${method}`, {
140
191
  ...init,
141
192
  headers: {
142
193
  ...(init.headers ?? {}),
@@ -144,11 +195,12 @@ async function callSessionOnce(token: string, method: string, init: RequestInit,
144
195
  ...extraHeaders,
145
196
  },
146
197
  });
198
+ timing(method.replace(/\?.*$/, ""), res.status, performance.now() - started);
147
199
  if (res.status === 429) {
148
200
  const retryAfter = parseInt(res.headers.get("retry-after") ?? "60", 10);
149
201
  throw new RateLimitError(isNaN(retryAfter) ? 60 : retryAfter, method);
150
202
  }
151
- const body = (await res.json()) as { ok?: boolean; error?: string } & Record<string, Json>;
203
+ const body = (await jsonOrSay(method, res)) as { ok?: boolean; error?: string } & Record<string, Json>;
152
204
  if (body.ok !== true) {
153
205
  const err = body.error ?? "unknown";
154
206
  if (err === "ratelimited") throw new RateLimitError(60, method);
@@ -164,7 +216,7 @@ async function callSessionOnce(token: string, method: string, init: RequestInit,
164
216
  `Attach it with: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)`,
165
217
  );
166
218
  }
167
- throw new Error(`Slack error on ${method}: ${err}`);
219
+ throw new Error(`Slack error on ${method}: ${err}${authSourceHint(err, token)}`);
168
220
  }
169
221
  return body as Json;
170
222
  }
@@ -179,12 +231,53 @@ function postSession(token: string, method: string, params: Record<string, strin
179
231
  }, cookie);
180
232
  }
181
233
 
234
+ // Lookups one command repeats (11-30: a dry-run `reply` asked conversations.info
235
+ // three times, auth.test twice and users.info five times, one after another, at
236
+ // ~200 ms each). The CLI turns this on for its own process; the answers are
237
+ // kept for a minute, so a long-running watcher still sees renames and joins.
238
+ const READ_CACHE_METHODS = new Set(["auth.test", "conversations.info", "users.info"]);
239
+ const READ_CACHE_MS = 60_000;
240
+ let readCacheOn = false;
241
+ const readCache = new Map<string, { at: number; value: Promise<Json> }>();
242
+
243
+ /** Reuse auth.test / conversations.info / users.info answers within this process. */
244
+ export function enableReadCache(on = true): void {
245
+ readCacheOn = on;
246
+ readCache.clear();
247
+ }
248
+
249
+ function readCacheKey(token: string, method: string, qs: string, cookie?: string): string {
250
+ const effectiveCookie = token.startsWith("xoxc-") ? (cookie ?? resolveCookie()) : undefined;
251
+ return JSON.stringify([base(), token, effectiveCookie, method, qs]);
252
+ }
253
+
254
+ function cachedGet(key: string, method: string, load: () => Promise<Json>): Promise<Json> {
255
+ if (!readCacheOn || !READ_CACHE_METHODS.has(method)) return load();
256
+ const hit = readCache.get(key);
257
+ if (hit && Date.now() - hit.at < READ_CACHE_MS) {
258
+ timing(method, "cached", 0);
259
+ return hit.value;
260
+ }
261
+ const value = load();
262
+ readCache.set(key, { at: Date.now(), value });
263
+ value.catch(() => { if (readCache.get(key)?.value === value) readCache.delete(key); });
264
+ return value;
265
+ }
266
+
267
+ /** SLACK_HUB_TIMING=1: one stderr line per Slack call (method, status, ms) —
268
+ * never the token, the arguments or the answer. */
269
+ export function timing(method: string, status: number | string, ms: number): void {
270
+ if (hubEnv("TIMING") !== "1") return;
271
+ console.error(`slack-hub timing: ${(performance.now() / 1000).toFixed(2)}s ${method} ${status} ${Math.round(ms)}ms`);
272
+ }
273
+
182
274
  function get(token: string, method: string, params: Record<string, string>, cookie?: string): Promise<Json> {
183
275
  const qs = new URLSearchParams(params).toString();
184
- return call(token, `${method}?${qs}`, { method: "GET" }, cookie);
276
+ return cachedGet(readCacheKey(token, method, qs, cookie), method, () => call(token, `${method}?${qs}`, { method: "GET" }, cookie));
185
277
  }
186
278
 
187
279
  function post(token: string, method: string, body: Record<string, Json>, cookie?: string): Promise<Json> {
280
+ readCache.clear(); // a write may change what the lookups answer
188
281
  return call(token, method, {
189
282
  method: "POST",
190
283
  headers: { "Content-Type": "application/json" },
@@ -239,16 +332,20 @@ export async function authScopes(token: string, cookie?: string): Promise<{
239
332
  cookie = token.startsWith("xoxc-") ? (cookie ?? resolveCookie()) : undefined;
240
333
  const headers: Record<string, string> = { Authorization: `Bearer ${token}` };
241
334
  if (cookie) headers["Cookie"] = `d=${cookie}`;
242
- const res = await fetch(`${base()}/auth.test`, { method: "GET", headers });
335
+ const started = performance.now();
336
+ const res = await fetchOrSay("auth.test", `${base()}/auth.test`, { method: "GET", headers });
337
+ timing("auth.test", res.status, performance.now() - started);
243
338
  if (res.status === 429) {
244
339
  const retryAfter = parseInt(res.headers.get("retry-after") ?? "60", 10);
245
340
  throw new RateLimitError(isNaN(retryAfter) ? 60 : retryAfter, "auth.test");
246
341
  }
247
342
  const scopesHeader = res.headers.get("x-oauth-scopes") ?? "";
248
- const body = (await res.json()) as {
343
+ const body = (await jsonOrSay("auth.test", res)) as {
249
344
  ok?: boolean; error?: string; user_id?: string; user?: string; bot_id?: string; team?: string; url?: string;
250
345
  };
251
346
  if (body.ok !== true) throw new Error(`Slack error on auth.test: ${body.error ?? "unknown"}`);
347
+ // A later authTest() for the same token is answered from this one.
348
+ if (readCacheOn) readCache.set(readCacheKey(token, "auth.test", "", cookie), { at: Date.now(), value: Promise.resolve(body as Json) });
252
349
  return {
253
350
  userId: body.user_id ?? "",
254
351
  // The token owner's @handle (for a bot token, the bot user's name) — lets a
@@ -650,7 +747,23 @@ export async function reactionAdd(
650
747
  name: string,
651
748
  cookie?: string,
652
749
  ): Promise<void> {
653
- await post(token, "reactions.add", { channel, timestamp: ts, name }, cookie);
750
+ const params = { channel, timestamp: ts, name };
751
+ try {
752
+ await post(token, "reactions.add", params, cookie);
753
+ } catch (e) {
754
+ // chat:write.public can post without membership, but cannot seed answer
755
+ // pills there. Only recover a bot's membership error; joining a public
756
+ // channel needs channels:join and cannot invite a bot to a private one.
757
+ if (!token.startsWith("xoxb-") || !channel.startsWith("C") ||
758
+ !(e instanceof Error) || e.message !== "Slack error on reactions.add: not_in_channel") throw e;
759
+ try {
760
+ await post(token, "conversations.join", { channel }, cookie);
761
+ } catch (joinError) {
762
+ throw new Error(`Could not join channel to add reaction: ${joinError instanceof Error ? joinError.message : String(joinError)}\n Invite the bot to the channel, or grant channels:join for public channels.`);
763
+ }
764
+ // Retry once: a failed join or retry still reaches the caller's warning.
765
+ await post(token, "reactions.add", params, cookie);
766
+ }
654
767
  }
655
768
 
656
769
  // Read the reactions currently on a message. Returns one entry per emoji with
@@ -1301,7 +1414,7 @@ export async function uploadFile(
1301
1414
 
1302
1415
  // Step 2: ファイルデータを外部URLへ PUT
1303
1416
  const fileData = readFileSync(filePath);
1304
- const putResp = await fetch(uploadUrl, {
1417
+ const putResp = await fetchOrSay("the upload", uploadUrl, {
1305
1418
  method: "POST",
1306
1419
  headers: { "Content-Type": "application/octet-stream" },
1307
1420
  body: fileData,
@@ -17,10 +17,19 @@
17
17
  // most one extra scan. Bells are deleted RETENTION_SEC after they arrive; that
18
18
  // window only exists so a reconnecting client can resume from its last seq.
19
19
  // Nothing here logs a request body.
20
+ //
21
+ // Router (opt-in): with a ROUTER Durable Object binding (wrangler.router.jsonc), /router/* and
22
+ // POST /slack/events/<app> serve the Slack thread router (router/: per-app intake, an aip/1 link to one subrouter
23
+ // per machine, routing, a delivery ledger and alerts). It stores message text — routed messages only, until delivery
24
+ // is final, at most 7 days. Without the binding those paths answer 404 and nothing here changes.
20
25
 
21
26
  import { DurableObject } from "cloudflare:workers";
22
27
  import { type Doorbell, doorbellOf, MAX_BODY_BYTES, plausiblySigned, readLimited, safeEqual, verifySlack } from "./slack.ts";
23
28
  import * as hub from "./hub.ts";
29
+ import type { Router } from "./router/do.ts";
30
+ import { routerFetch } from "./router/fetch.ts";
31
+
32
+ export { Router } from "./router/do.ts";
24
33
 
25
34
  export interface Env {
26
35
  RELAY: DurableObjectNamespace<Relay>;
@@ -30,6 +39,20 @@ export interface Env {
30
39
  RELAY_TOKEN: string;
31
40
  /** Optional: drop events from any other workspace. */
32
41
  SLACK_TEAM_ID?: string;
42
+ /** Opt-in: the Router Durable Object (wrangler.router.jsonc). Absent: /router/* and /slack/events/<app> are 404. */
43
+ ROUTER?: DurableObjectNamespace<Router>;
44
+ /** Bearer for the Router's admin API (/router/*); unset: every admin request is 401. */
45
+ ROUTER_ADMIN_TOKEN?: string;
46
+ /** "shadow" (default) or "live": reported to the machines in welcome, which act on it. */
47
+ ROUTER_MODE?: string;
48
+ /** An app whose /slack/events/<app> events also ring the relay doorbell, as /slack/events does. */
49
+ ROUTER_BELL_APP?: string;
50
+ /** JST hours intake.silent is evaluated in, "8-22" by default. */
51
+ ROUTER_DAYTIME_JST?: string;
52
+ /** Test only: "1" lets the worker suite move the Router's clock (Router.tickAt). Never set it on a deployment. */
53
+ ROUTER_TEST_SEAM?: string;
54
+ // Per app <APP> (upper-cased, "-" → "_"): SLACK_SIGNING_SECRET_<APP> (required for /slack/events/<app>),
55
+ // SLACK_TEAM_ID_<APP> (optional team filter).
33
56
  }
34
57
 
35
58
  /** How long a bell is kept for resume. Longer gaps are covered by the client's
@@ -91,6 +114,10 @@ export default {
91
114
  return relay.fetch(req);
92
115
  }
93
116
 
117
+ if (env.ROUTER && (url.pathname.startsWith("/router/") || url.pathname.startsWith("/slack/events/"))) {
118
+ return routerFetch(req, url, env, env.ROUTER.get(env.ROUTER.idFromName("router")), relay);
119
+ }
120
+
94
121
  return new Response("not found", { status: 404 });
95
122
  },
96
123
  } satisfies ExportedHandler<Env>;
@@ -0,0 +1,80 @@
1
+ // The Router's admin HTTP API (Authorization: Bearer <ROUTER_ADMIN_TOKEN>, checked by the Worker before a request
2
+ // gets here), as pure logic: method + path + query + parsed JSON body → status + JSON body. No Cloudflare types.
3
+ //
4
+ // GET /router/health {ok, mode, epoch, machines:[{machine, online, last_seen}], open_deliveries, alerts_open}
5
+ // PUT /router/machines/<m> {pubkey} enroll, or rotate the key
6
+ // DELETE /router/machines/<m> revoke (closes its socket)
7
+ // GET /router/lanes {lanes:[{lane, machine, cwd, placed_at, prev_machine}], audit:[last 100]}
8
+ // PUT /router/lanes/<lane> {machine, cwd?} seed or move (audit lane.seed)
9
+ // GET /router/routes {routes:[…]}
10
+ // PUT /router/routes {channel, thread_ts?, to, cc?, from?, read_s?, queue_max_s?, ack_s?, fallback?, offline?}
11
+ // DELETE /router/routes?channel=&thread_ts=
12
+ // GET /router/messages?channel=&ts= {id, app, text (null once final), final, at, deliveries:[…]}, 404 if unknown
13
+ // GET /router/alerts {alerts:[{kind, subject, state, since, detail}]}
14
+
15
+ import { checkRoute, type RouteInput, type RouterCore } from "./core.ts";
16
+ import { CHANNEL, TS } from "./wire.ts";
17
+
18
+ export type AdminRequest = { method: string; path: string; query: URLSearchParams; body: unknown };
19
+ export type AdminResponse = { status: number; body: unknown };
20
+
21
+ const bad = (error: string, status = 400): AdminResponse => ({ status, body: { ok: false, error } });
22
+ const ok = (body: unknown): AdminResponse => ({ status: 200, body });
23
+
24
+ export function admin(core: RouterCore, req: AdminRequest, now: number): AdminResponse {
25
+ const { method, path, query, body } = req;
26
+ const obj = body && typeof body === "object" && !Array.isArray(body) ? (body as Record<string, unknown>) : undefined;
27
+ const allow = (...methods: string[]): AdminResponse | null => (methods.includes(method) ? null : bad(`method not allowed (${methods.join(", ")})`, 405));
28
+
29
+ if (path === "/router/health") return allow("GET") ?? ok(core.health(now));
30
+ if (path === "/router/lanes") return allow("GET") ?? ok(core.lanesView());
31
+ if (path === "/router/alerts") return allow("GET") ?? ok(core.alertsView());
32
+
33
+ let m = /^\/router\/machines\/([^/]+)$/.exec(path);
34
+ if (m) {
35
+ const machine = decodeURIComponent(m[1]!);
36
+ if (method === "PUT") {
37
+ if (!obj || typeof obj.pubkey !== "string") return bad("want {pubkey}");
38
+ const r = core.enroll(machine, obj.pubkey, now);
39
+ return r.ok ? ok(r) : bad(r.error);
40
+ }
41
+ if (method === "DELETE") return core.revoke(machine, now) ? ok({ ok: true, machine }) : bad(`machine ${machine} is not enrolled`, 404);
42
+ return bad("method not allowed (PUT, DELETE)", 405);
43
+ }
44
+
45
+ m = /^\/router\/lanes\/([^/]+)$/.exec(path);
46
+ if (m) {
47
+ const no = allow("PUT");
48
+ if (no) return no;
49
+ if (!obj || typeof obj.machine !== "string" || (obj.cwd !== undefined && typeof obj.cwd !== "string")) return bad("want {machine, cwd?}");
50
+ const r = core.seedLane(decodeURIComponent(m[1]!), obj.machine, obj.cwd as string | undefined, now);
51
+ return r.ok ? ok({ ok: true, lane: r.lane }) : bad(r.error);
52
+ }
53
+
54
+ if (path === "/router/routes") {
55
+ if (method === "GET") return ok(core.routesView());
56
+ if (method === "PUT") {
57
+ const errs = checkRoute(body);
58
+ return errs.length ? bad(errs.join("; ")) : ok({ ok: true, route: core.putRoute(body as RouteInput, now) });
59
+ }
60
+ if (method === "DELETE") {
61
+ const channel = query.get("channel") ?? "";
62
+ const thread_ts = query.get("thread_ts") ?? "";
63
+ if (!CHANNEL.test(channel) || (thread_ts !== "" && !TS.test(thread_ts))) return bad("want ?channel=<id>[&thread_ts=<ts>]");
64
+ return core.deleteRoute(channel, thread_ts, now) ? ok({ ok: true }) : bad("no such route", 404);
65
+ }
66
+ return bad("method not allowed (GET, PUT, DELETE)", 405);
67
+ }
68
+
69
+ if (path === "/router/messages") {
70
+ const no = allow("GET");
71
+ if (no) return no;
72
+ const channel = query.get("channel") ?? "";
73
+ const ts = query.get("ts") ?? "";
74
+ if (!CHANNEL.test(channel) || !TS.test(ts)) return bad("want ?channel=<id>&ts=<ts>");
75
+ const v = core.messageView(channel, ts);
76
+ return v ? ok(v) : bad("unknown message", 404);
77
+ }
78
+
79
+ return bad("not found", 404);
80
+ }