@pmndre/pine 0.22.1 → 0.33.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/README.md +2 -1
- package/changes.json +265 -0
- package/docs/SKILL.md +31 -7
- package/docs/references/agents.md +245 -21
- package/docs/references/coding.md +1 -1
- package/docs/references/computer.md +1 -1
- package/docs/references/configuration.md +14 -5
- package/docs/references/mcp.md +9 -0
- package/docs/references/operations.md +20 -9
- package/docs/references/overview.md +3 -1
- package/docs/references/security.md +83 -24
- package/docs/references/setup.md +55 -9
- package/docs/references/source-types.md +1418 -0
- package/docs/references/sources.md +333 -19
- package/docs/references/stack.md +1 -0
- package/docs/references/tui.md +86 -12
- package/examples/home/AGENTS.md +4 -0
- package/examples/home/TOOLS.md +5 -0
- package/examples/home/agents/main/workspace/AGENTS.md +1 -1
- package/examples/home/agents/main/workspace/TOOLS.md +5 -0
- package/mcp/browser.d.ts +6 -0
- package/mcp/browser.js +19 -0
- package/mcp/render.d.ts +1 -0
- package/mcp/render.js +237 -0
- package/package.json +3 -1
- package/src/actions.d.ts +6 -1
- package/src/actions.js +17 -4
- package/src/admin.d.ts +4 -0
- package/src/admin.js +25 -6
- package/src/agents.d.ts +167 -2
- package/src/agents.js +912 -45
- package/src/catalogue.d.ts +60 -0
- package/src/catalogue.js +791 -0
- package/src/cli.js +10 -7
- package/src/config.d.ts +53 -4
- package/src/config.js +30 -5
- package/src/goals.d.ts +1 -1
- package/src/goals.js +14 -1
- package/src/manual.js +24 -2
- package/src/mime.d.ts +78 -0
- package/src/mime.js +342 -0
- package/src/net.d.ts +11 -0
- package/src/net.js +29 -2
- package/src/pine.js +10 -1
- package/src/router.js +3 -3
- package/src/sandbox-linux.d.ts +3 -1
- package/src/sandbox-linux.js +5 -0
- package/src/security.d.ts +22 -6
- package/src/security.js +44 -13
- package/src/slots.d.ts +106 -0
- package/src/slots.js +250 -0
- package/src/source-types.d.ts +20 -0
- package/src/sources/calendar.d.ts +24 -0
- package/src/sources/calendar.js +265 -0
- package/src/sources/command.js +109 -4
- package/src/sources/discord.d.ts +4 -0
- package/src/sources/discord.js +298 -0
- package/src/sources/feed.d.ts +19 -0
- package/src/sources/feed.js +257 -0
- package/src/sources/http.js +154 -103
- package/src/sources/mail.d.ts +51 -0
- package/src/sources/mail.js +1013 -0
- package/src/sources/matrix.d.ts +4 -0
- package/src/sources/matrix.js +232 -0
- package/src/sources/modbus.d.ts +15 -0
- package/src/sources/modbus.js +240 -0
- package/src/sources/onvif.d.ts +35 -0
- package/src/sources/onvif.js +326 -0
- package/src/sources/presence.d.ts +80 -0
- package/src/sources/presence.js +480 -0
- package/src/sources/serial.d.ts +21 -0
- package/src/sources/serial.js +220 -0
- package/src/sources/slack.d.ts +16 -0
- package/src/sources/slack.js +1062 -0
- package/src/sources/smtp.d.ts +4 -0
- package/src/sources/smtp.js +360 -0
- package/src/sources/stream.d.ts +68 -0
- package/src/sources/stream.js +534 -0
- package/src/sources/syslog.d.ts +32 -0
- package/src/sources/syslog.js +243 -0
- package/src/sources/system.d.ts +14 -0
- package/src/sources/system.js +236 -0
- package/src/sources/system.swift +102 -0
- package/src/sources/telegram.js +34 -1
- package/src/sources.d.ts +41 -1
- package/src/sources.js +147 -24
- package/src/tools.d.ts +1 -1
- package/src/tools.js +304 -23
- package/src/tui/app.d.ts +35 -2
- package/src/tui/app.js +306 -43
- package/src/tui/levels.d.ts +68 -0
- package/src/tui/levels.js +273 -0
- package/src/tui/picture.d.ts +17 -1
- package/src/tui/picture.js +72 -5
- package/src/types.d.ts +3 -0
- package/src/update.d.ts +9 -1
- package/src/update.js +75 -3
- package/src/watching.d.ts +156 -0
- package/src/watching.js +609 -4
|
@@ -0,0 +1,1062 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { SocketModeClient } from "@slack/socket-mode";
|
|
4
|
+
import { LogLevel, WebAPIHTTPError, WebAPIPlatformError, WebAPIRateLimitedError, WebClient } from "@slack/web-api";
|
|
5
|
+
import { Type } from "typebox";
|
|
6
|
+
import { Agent, fetch, FormData as Multipart } from "undici";
|
|
7
|
+
import { fileName, keepFiles, pruneFiles } from "../mime.js";
|
|
8
|
+
import { errText } from "../util.js";
|
|
9
|
+
import { capped, clip, shown } from "../watching.js";
|
|
10
|
+
import { guardFor, hold, keywordIn, listOf, ownServer, Plain, word } from "./stream.js";
|
|
11
|
+
/**
|
|
12
|
+
* A Slack workspace, watched through Socket Mode: the app connects out to Slack and is told what
|
|
13
|
+
* happens where it may look. Nothing listens on a port, so it works behind any router. The
|
|
14
|
+
* connection and every call of Slack's Web API are made by Slack's own SDK (@slack/socket-mode,
|
|
15
|
+
* @slack/web-api); connecting again, the status line and what counts are pine's.
|
|
16
|
+
*
|
|
17
|
+
* options: { appToken, token?, events?, channels?, mentions?, keywords?, from?, dms?, bots?, ignore?,
|
|
18
|
+
* sendTo?, perMinute?, maxMb?, keepDays?, apiBase? }
|
|
19
|
+
* appToken the app-level token (xapp-...) that Socket Mode connects with
|
|
20
|
+
* token a bot token (xoxb-) or user token (xoxp-): names for ids, channels by name, "me",
|
|
21
|
+
* the files of a message, and everything that is sent
|
|
22
|
+
* events which kinds of thing are reported: message (the default), reaction, edit, member,
|
|
23
|
+
* channel, pin, command, other
|
|
24
|
+
* channels only these channels, by id or by name. None: every channel the app is told about
|
|
25
|
+
* mentions user ids (or "me", "here", "channel", "everyone", a user group's id): only messages that mention one
|
|
26
|
+
* keywords only messages that contain one of these words
|
|
27
|
+
* from user ids (or "me") whose messages always count, wherever they write and whatever they say
|
|
28
|
+
* dms direct messages count (default true)
|
|
29
|
+
* bots what other apps and integrations post counts too (default false)
|
|
30
|
+
* ignore user ids (or "me") that are never reported: the owner's own account
|
|
31
|
+
* sendTo channel and user ids the agent may write to. Without it nothing can be sent
|
|
32
|
+
* perMinute at most this many reports a minute (60); the rest are counted and dropped
|
|
33
|
+
* maxMb, keepDays files of a message are fetched up to this size (10) and kept this long (7)
|
|
34
|
+
*
|
|
35
|
+
* event "message": { text, user, userName?, channel, channelName?, kind, ts, thread?, reply?, bot?, why, mention?, keyword?, from?, files?, images?, dropped? }
|
|
36
|
+
* why: the reasons it is reported, a word each: "dm", "mention", "keyword", "from", or "channel" for none of these
|
|
37
|
+
* event "reaction": { reaction, added, user, userName?, channel, channelName?, ts, author?, authorName? }
|
|
38
|
+
* event "edited": { text, previous?, user, userName?, channel, channelName?, kind, ts, mention?, keyword?, from? }
|
|
39
|
+
* event "deleted": { channel, channelName?, ts, previous? }
|
|
40
|
+
* event "joined", "left": { user, userName?, channel?, channelName? }
|
|
41
|
+
* event "channel": { what, channel, channelName? }
|
|
42
|
+
* event "pin": { added, channel, channelName?, ts?, user, userName? }
|
|
43
|
+
* event "command": { command, text, user, userName?, channel, channelName? }
|
|
44
|
+
* event "event": { type, data }
|
|
45
|
+
*
|
|
46
|
+
* It can send, to what is on `sendTo` only: { channel, text, thread? } a message; a user id as
|
|
47
|
+
* `channel` a direct message; { channel, ts, react } an emoji on a message; `file` a file.
|
|
48
|
+
*
|
|
49
|
+
* Which message counts, in this order: never the app's own, one of a user on `ignore`, or one of
|
|
50
|
+
* another app unless `bots` is on. One of a user on `from` counts. A direct message counts when
|
|
51
|
+
* `dms` is on. Any other must be in a channel on `channels` (or there is no such list), and if
|
|
52
|
+
* `mentions` or `keywords` are given, one of them must be found in it. The other kinds go the same
|
|
53
|
+
* way as far as they have a user or a channel; mentions and keywords are for messages and edits.
|
|
54
|
+
*/
|
|
55
|
+
const SLACK = "https://slack.com/api";
|
|
56
|
+
/** Where Slack keeps the files of a message. The token is sent there and to no other host. */
|
|
57
|
+
const FILES = "files.slack.com";
|
|
58
|
+
/** Messages with one of these subtypes are somebody writing. Any other subtype says that something happened to a channel. */
|
|
59
|
+
const WRITTEN = ["file_share", "thread_broadcast", "me_message", "bot_message"];
|
|
60
|
+
/** What Slack answers when it is the one that has trouble: tried again, not taken for a no. */
|
|
61
|
+
const PASSING = ["ratelimited", "rate_limited", "internal_error", "fatal_error", "service_unavailable", "request_timeout"];
|
|
62
|
+
/** What somebody who typed a slash command reads. */
|
|
63
|
+
const PASSED = "Passed on.";
|
|
64
|
+
/**
|
|
65
|
+
* Times the tests set: what a second of "wait this long" from Slack lasts, how long a new
|
|
66
|
+
* connection may take to be greeted, within what time Slack has to answer a ping (the SDK pings
|
|
67
|
+
* three times in that time, and takes a connection without an answer for dead), and how long a
|
|
68
|
+
* goodbye is waited for before the socket is cut.
|
|
69
|
+
*/
|
|
70
|
+
export const pace = { second: 1000, hello: 30_000, ping: 5000, bye: 1000 };
|
|
71
|
+
/** The kinds of thing that can be reported, with what the owner reads about each. */
|
|
72
|
+
const KINDS = {
|
|
73
|
+
message: { does: "", short: "messages" },
|
|
74
|
+
reaction: { does: "who puts which emoji on which message, or takes it away", short: "reactions" },
|
|
75
|
+
edit: { does: "messages that are edited or deleted, with what they said before", short: "edits" },
|
|
76
|
+
member: { does: "who joins and who leaves", short: "who joins and leaves" },
|
|
77
|
+
channel: { does: "channels that are created, renamed, archived or deleted", short: "changes to channels" },
|
|
78
|
+
pin: { does: "messages that are pinned or unpinned", short: "pins" },
|
|
79
|
+
command: { does: `the slash commands of your app, each answered with "${PASSED}"`, short: "slash commands" },
|
|
80
|
+
other: { does: "every other event your app is subscribed to, as Slack sends it", short: "other events" },
|
|
81
|
+
};
|
|
82
|
+
/** Slack's events, by the kind they are reported as. A message is sorted by its subtype. */
|
|
83
|
+
const KIND_OF = {
|
|
84
|
+
...{ reaction_added: "reaction", reaction_removed: "reaction" },
|
|
85
|
+
...{ member_joined_channel: "member", member_left_channel: "member", team_join: "member" },
|
|
86
|
+
...{ channel_created: "channel", channel_rename: "channel", channel_archive: "channel", channel_unarchive: "channel", channel_deleted: "channel" },
|
|
87
|
+
...{ group_rename: "channel", group_archive: "channel", group_unarchive: "channel", group_deleted: "channel" },
|
|
88
|
+
...{ pin_added: "pin", pin_removed: "pin" },
|
|
89
|
+
};
|
|
90
|
+
const CHANGED = { created: "created", rename: "renamed", archive: "archived", unarchive: "unarchived", deleted: "deleted" };
|
|
91
|
+
// An id is capitals and digits with a digit in it. A channel's name is written small, so the two are told apart.
|
|
92
|
+
const id = (first) => (x) => new RegExp(`^[${first}][A-Z0-9]{2,20}$`).test(x) && /\d/.test(x);
|
|
93
|
+
const isChannel = id("CGD");
|
|
94
|
+
const isUser = id("UW");
|
|
95
|
+
const isActor = id("UWB");
|
|
96
|
+
const isGroup = id("S");
|
|
97
|
+
const EVERYBODY = ["here", "channel", "everyone"];
|
|
98
|
+
const channelName = (x) => x.replace(/^#/, "").toLowerCase();
|
|
99
|
+
const list = (v) => (Array.isArray(v) ? v : []);
|
|
100
|
+
const plural = (n, one, many = `${one}s`) => (n === 1 ? one : many);
|
|
101
|
+
/** The lists of a set-up as they are used: without "#" and "@" in front, a channel's name written small. */
|
|
102
|
+
function lists(o) {
|
|
103
|
+
const channels = listOf(o.channels).map((x) => (isChannel(x.replace(/^#/, "")) ? x.replace(/^#/, "") : channelName(x)));
|
|
104
|
+
const people = (key) => listOf(o[key]).map((x) => x.replace(/^@/, ""));
|
|
105
|
+
return { channels, mentions: people("mentions"), from: people("from"), ignore: people("ignore"), sendTo: listOf(o.sendTo).map((x) => x.replace(/^[#@]/, "")), keywords: listOf(o.keywords), events: [...new Set(o.events === undefined ? ["message"] : listOf(o.events).map((x) => x.toLowerCase()))] };
|
|
106
|
+
}
|
|
107
|
+
export const type = {
|
|
108
|
+
summary: "a Slack workspace: reports messages (all, or only mentions, keywords, certain people), and reactions, edits, joins, pins, commands. Can post, react and send files to listed channels",
|
|
109
|
+
sends: 'a Slack message to a channel or person on its "sendTo" list: {"channel": "C0123ABCD", "text": "..."}. "thread" (a message\'s ts) answers in that thread; a user id as "channel" writes to that person directly; with "file" a file goes along; {"channel": "...", "ts": "...", "react": "eyes"} puts an emoji on a message',
|
|
110
|
+
files: true,
|
|
111
|
+
options: Type.Object({
|
|
112
|
+
appToken: Type.String({ description: "the app-level token of the Slack app (xapp-...), with the scope connections:write. Socket Mode connects with it", secret: true }),
|
|
113
|
+
token: Type.Optional(Type.String({ description: 'a bot token (xoxb-...) or user token (xoxp-...) of the same app. With it people and channels have names, channels can be given by name, "me" is known, files are fetched, and things can be sent. Name it in "ask" when any of that is wanted', secret: true })),
|
|
114
|
+
events: Type.Optional(Type.Array(Type.String(), { description: 'which kinds of thing to report: "message" (the default, alone), "reaction", "edit" (edited and deleted messages), "member" (who joins and leaves), "channel" (created, renamed, archived), "pin", "command" (the app\'s slash commands), "other" (any other event the app is subscribed to)' })),
|
|
115
|
+
channels: Type.Optional(Type.Array(Type.String(), { description: 'only these channels, by name or id: ["ops", "C0123ABCD"]. A name needs "token". Leave out for every channel the app sees' })),
|
|
116
|
+
mentions: Type.Optional(Type.Array(Type.String(), { description: 'only messages that mention one of these: user ids (["U0123ABCD"]), "me" (the account the token belongs to), "here", "channel", "everyone", or a user group\'s id (S...)' })),
|
|
117
|
+
keywords: Type.Optional(Type.Array(Type.String(), { description: 'only messages that contain one of these words, e.g. ["outage", "invoice"]. Capitals do not matter' })),
|
|
118
|
+
from: Type.Optional(Type.Array(Type.String(), { description: 'user ids (or "me") whose messages always count, in any channel and whatever they say: a boss, a customer' })),
|
|
119
|
+
dms: Type.Optional(Type.Boolean({ description: "direct messages count too. Default true" })),
|
|
120
|
+
bots: Type.Optional(Type.Boolean({ description: "true to report what other apps and integrations post too: alerts, GitHub, a monitoring bot. Default false. What this app posts itself is never reported" })),
|
|
121
|
+
ignore: Type.Optional(Type.Array(Type.String(), { description: "user ids whose messages are never reported. Not needed for your owner's own messages: what the token's account writes is left out by itself" })),
|
|
122
|
+
sendTo: Type.Optional(Type.Array(Type.String(), { description: 'where you may write, by id only: channels (["C0123ABCD"]) and people (["U0123ABCD"], a direct message). Only when your owner wants you to write there; without it nothing can be sent. Needs "token"' })),
|
|
123
|
+
perMinute: Type.Optional(Type.Number({ description: "at most this many reports a minute. Default 60; what comes on top is dropped and counted" })),
|
|
124
|
+
maxMb: Type.Optional(Type.Number({ description: 'files that come with a message are fetched up to this size, in MB. Default 10. Needs "token"' })),
|
|
125
|
+
keepDays: Type.Optional(Type.Number({ description: "fetched files are deleted after this many days. Default 7" })),
|
|
126
|
+
apiBase: Type.Optional(Type.String({ description: "address of a Slack-compatible server of your own, instead of https://slack.com/api" })),
|
|
127
|
+
}, { additionalProperties: false }),
|
|
128
|
+
// What cannot be done without the token of the workspace: pine asks the owner for it, without the agent having to think of it.
|
|
129
|
+
needs(o) {
|
|
130
|
+
const l = lists(o);
|
|
131
|
+
return l.channels.some((c) => !isChannel(c)) || [...l.mentions, ...l.from, ...l.ignore].includes("me") || l.sendTo.length ? ["token"] : [];
|
|
132
|
+
},
|
|
133
|
+
plan(o) {
|
|
134
|
+
// Without a token yet (the owner is about to be asked for it) there is nothing to check.
|
|
135
|
+
if (o.appToken !== undefined && !/^xapp-/.test(String(o.appToken)))
|
|
136
|
+
throw new Error('that is not an app-level token. It starts with xapp- and is made on api.slack.com under "Basic Information", "App-Level Tokens", with the scope connections:write. A token that starts with xoxb- or xoxp- goes into "token"');
|
|
137
|
+
if (o.token !== undefined && !/^xox[bp]-/.test(String(o.token)))
|
|
138
|
+
throw new Error('"token" is a bot token (xoxb-...) or a user token (xoxp-...), from "OAuth & Permissions" of the Slack app. The one that starts with xapp- goes into "appToken"');
|
|
139
|
+
const base = ownServer(o.apiBase, SLACK);
|
|
140
|
+
const l = lists(o);
|
|
141
|
+
const person = 'A person\'s id starts with U and is in their profile under "Copy member ID"';
|
|
142
|
+
const not = (key, odd, what) => {
|
|
143
|
+
if (odd.length)
|
|
144
|
+
throw new Error(`"${key}" takes ${what}: ${odd.join(", ")} is not one. ${person}`);
|
|
145
|
+
};
|
|
146
|
+
const strange = l.channels.filter((c) => !isChannel(c) && !/^[^\s#@<>,|]{1,80}$/.test(c));
|
|
147
|
+
if (strange.length)
|
|
148
|
+
throw new Error(`"channels" takes channel names ("ops") or ids ("C0123ABCD"): ${strange.join(", ")} is neither`);
|
|
149
|
+
not("mentions", l.mentions.filter((x) => x !== "me" && !EVERYBODY.includes(x) && !isUser(x) && !isGroup(x)), 'Slack user ids, "me", "here", "channel" or "everyone", not names');
|
|
150
|
+
not("from", l.from.filter((x) => x !== "me" && !isActor(x)), 'Slack user ids or "me", not names');
|
|
151
|
+
not("ignore", l.ignore.filter((x) => x !== "me" && !isActor(x)), 'Slack user ids or "me", not names');
|
|
152
|
+
const nowhere = l.sendTo.filter((x) => !isChannel(x) && !isUser(x));
|
|
153
|
+
// The one list that says where an agent may write: a name can be given to another channel tomorrow, an id cannot.
|
|
154
|
+
if (nowhere.length)
|
|
155
|
+
throw new Error(`"sendTo" takes ids, not names: ${nowhere.join(", ")} is not one. It says where the agent may write, and a name can come to mean another place. A channel's id starts with C (or G, D) and is at the end of its link. ${person}`);
|
|
156
|
+
const unknown = l.events.filter((k) => !KINDS[k]);
|
|
157
|
+
if (unknown.length)
|
|
158
|
+
throw new Error(`"events" takes ${Object.keys(KINDS).join(", ")}: ${unknown.join(", ")} is not one of them`);
|
|
159
|
+
if (!l.events.length)
|
|
160
|
+
throw new Error(`"events" is empty, so nothing would be reported. It takes ${Object.keys(KINDS).join(", ")}; leave it out for messages`);
|
|
161
|
+
if (o.perMinute !== undefined && !(o.perMinute >= 1 && o.perMinute <= 600))
|
|
162
|
+
throw new Error('"perMinute" is a number from 1 to 600');
|
|
163
|
+
for (const key of ["maxMb", "keepDays"])
|
|
164
|
+
if (o[key] !== undefined && !(Number(o[key]) > 0))
|
|
165
|
+
throw new Error(`"${key}" must be a number above 0`);
|
|
166
|
+
if (o.maxMb !== undefined && o.maxMb > 50)
|
|
167
|
+
throw new Error('"maxMb" is at most 50');
|
|
168
|
+
const who = (x) => (x === "me" ? "the account the token belongs to" : x);
|
|
169
|
+
const some = (xs) => xs.map(who).join(", ");
|
|
170
|
+
const where = l.channels.length ? `the ${plural(l.channels.length, "channel")} ${l.channels.map((c) => (isChannel(c) ? c : `#${c}`)).join(", ")}` : "every channel the app is in";
|
|
171
|
+
const picky = l.mentions.length || l.keywords.length ? `, there only messages that ${[l.mentions.length ? `mention ${some(l.mentions)}` : "", l.keywords.length ? `contain ${l.keywords.map((k) => `"${k}"`).join(", ")}` : ""].filter(Boolean).join(" or ")}` : "";
|
|
172
|
+
const said = [l.from.length ? `everything ${some(l.from)} ${plural(l.from.length, "writes", "write")}` : "", o.dms === false ? "" : "direct messages", `${where}${picky}`].filter(Boolean);
|
|
173
|
+
const messages = l.events.includes("message");
|
|
174
|
+
const more = l.events.filter((k) => k !== "message").map((k) => KINDS[k].does);
|
|
175
|
+
const rooms = l.sendTo.filter(isChannel);
|
|
176
|
+
const persons = l.sendTo.filter(isUser);
|
|
177
|
+
const options = { ...o };
|
|
178
|
+
for (const key of ["channels", "mentions", "keywords", "from", "ignore", "sendTo"]) {
|
|
179
|
+
if (l[key].length)
|
|
180
|
+
options[key] = l[key];
|
|
181
|
+
else
|
|
182
|
+
delete options[key];
|
|
183
|
+
}
|
|
184
|
+
if (o.events !== undefined)
|
|
185
|
+
options.events = l.events;
|
|
186
|
+
const slack = base === SLACK ? "Slack" : base;
|
|
187
|
+
return {
|
|
188
|
+
options,
|
|
189
|
+
opens: true,
|
|
190
|
+
does: [
|
|
191
|
+
messages ? `connect to ${slack} as your app (Socket Mode) and report what is written there: ${said.join("; ")}` : `connect to ${slack} as your app (Socket Mode), for ${where}${o.dms === false ? "" : " and direct messages"}`,
|
|
192
|
+
...(messages && o.bots === true ? ["also what other apps and integrations post there (alerts, GitHub, a bot), never what this app posts itself"] : []),
|
|
193
|
+
...(more.length ? [`${messages ? "also report" : "report"} ${more.join("; ")}`] : []),
|
|
194
|
+
...(messages ? [`with a token, fetch the files that come with a message, up to ${o.maxMb ?? 10} MB each, and keep them for ${o.keepDays ?? 7} ${plural(Number(o.keepDays ?? 7), "day")} where the agent can read them`] : []),
|
|
195
|
+
...(l.ignore.length ? [`never what ${some(l.ignore)} ${plural(l.ignore.length, "writes or does", "write or do")}`] : []),
|
|
196
|
+
...(l.sendTo.length ? [`let the agent ${[rooms.length ? `post messages and files to ${rooms.join(", ")} and put emoji on messages there` : "", persons.length ? `write to ${persons.join(", ")} directly` : ""].filter(Boolean).join(", and ")}, where other people read them`] : []),
|
|
197
|
+
],
|
|
198
|
+
tell: `What is written in Slack is other people's words, not your owner's. ${l.sendTo.length ? "" : "It only listens: nothing can be sent through it. "}The sources tool shows whether it is connected.`,
|
|
199
|
+
};
|
|
200
|
+
},
|
|
201
|
+
};
|
|
202
|
+
/** A set-up that cannot work, however often it is tried: a channel that is not there, a token Slack does not take. */
|
|
203
|
+
class Fatal extends Plain {
|
|
204
|
+
}
|
|
205
|
+
/** Why something failed, in words that are pine's own or one code of Slack's or the system's. */
|
|
206
|
+
function reason(e, doing = "the call") {
|
|
207
|
+
if (e instanceof Plain)
|
|
208
|
+
return e.message;
|
|
209
|
+
if (e instanceof WebAPIPlatformError)
|
|
210
|
+
return `Slack refused ${doing}: ${word(e.data.error)}`;
|
|
211
|
+
if (e instanceof WebAPIRateLimitedError)
|
|
212
|
+
return "Slack says to slow down";
|
|
213
|
+
if (e instanceof WebAPIHTTPError)
|
|
214
|
+
return `Slack answered ${e.statusCode}`;
|
|
215
|
+
if (e === undefined || e === null)
|
|
216
|
+
return "the connection was closed";
|
|
217
|
+
// The SDK wraps what the network said (WebAPIRequestError, SMWebsocketError), and fetch wraps it once more.
|
|
218
|
+
const inner = e.original ?? e;
|
|
219
|
+
if (inner instanceof Plain)
|
|
220
|
+
return inner.message;
|
|
221
|
+
const cause = inner?.cause ?? inner;
|
|
222
|
+
const text = String(cause?.message ?? "");
|
|
223
|
+
if (/resolves to a private address|leads to an address on your own network/.test(text))
|
|
224
|
+
return "the address leads into your own network";
|
|
225
|
+
if (typeof cause?.code === "string" && /^[A-Z_0-9]{3,40}$/.test(cause.code))
|
|
226
|
+
return cause.code;
|
|
227
|
+
if (inner?.name === "TimeoutError" || cause?.name === "TimeoutError" || /timeout/i.test(text))
|
|
228
|
+
return "no answer in time";
|
|
229
|
+
if (inner?.name === "AbortError" || cause?.name === "AbortError")
|
|
230
|
+
return "stopped";
|
|
231
|
+
return "the connection failed";
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Where the SDK's own log lines go: to the source's log, for whoever looks for a fault. What it
|
|
235
|
+
* says for debugging holds what it sent and received word for word (other people's messages, the
|
|
236
|
+
* ticket of a connection), and that is left out; a token is taken out of whatever is said.
|
|
237
|
+
*/
|
|
238
|
+
function sdkLog(source, secrets) {
|
|
239
|
+
const WORDY = /^(Received a message on the WebSocket|Sending a WebSocket message|Calling ack\(\)|http request (url|body|headers|result)|Unable to parse)/;
|
|
240
|
+
const said = new Map();
|
|
241
|
+
const clean = (parts) => {
|
|
242
|
+
let s = parts.map((p) => (p instanceof Error ? p.message : typeof p === "string" ? p : (JSON.stringify(p) ?? ""))).join(" ");
|
|
243
|
+
for (const x of secrets)
|
|
244
|
+
if (x)
|
|
245
|
+
s = s.replaceAll(x, "***");
|
|
246
|
+
s = s.replace(/xapp-[\w-]+|xox[a-z]-[\w-]+/g, "***").replace(/((?:wss?|https?):\/\/[^\s?"')]+)\?[^\s"')]*/g, "$1?…");
|
|
247
|
+
return clip(s.replace(/[\x00-\x1f\x7f]+/g, " "), 300);
|
|
248
|
+
};
|
|
249
|
+
const quietly = (...m) => {
|
|
250
|
+
const s = clean(m);
|
|
251
|
+
if (!WORDY.test(s))
|
|
252
|
+
source.log.debug(`sdk: ${s}`);
|
|
253
|
+
};
|
|
254
|
+
// Said once an hour at most: while Slack cannot be reached the same line comes with every attempt, and the status line carries it.
|
|
255
|
+
const loudly = (...m) => {
|
|
256
|
+
const s = clean(m);
|
|
257
|
+
const now = Date.now();
|
|
258
|
+
if (now - (said.get(s) ?? 0) < 3_600_000)
|
|
259
|
+
return source.log.debug(`sdk: ${s}`);
|
|
260
|
+
if (said.size > 200)
|
|
261
|
+
said.clear();
|
|
262
|
+
said.set(s, now);
|
|
263
|
+
source.log.warn(`sdk: ${s}`);
|
|
264
|
+
};
|
|
265
|
+
return { debug: quietly, info: quietly, warn: loudly, error: loudly, setLevel: () => { }, getLevel: () => LogLevel.INFO, setName: () => { } };
|
|
266
|
+
}
|
|
267
|
+
/** What a block of a message says, piece by piece. Slack's own formats; a button and anything unknown is left out. */
|
|
268
|
+
function blockText(block, add, depth = 0) {
|
|
269
|
+
if (!block || typeof block !== "object" || depth > 4 || block.type === "actions")
|
|
270
|
+
return;
|
|
271
|
+
const inline = (el) => {
|
|
272
|
+
if (!el || typeof el !== "object")
|
|
273
|
+
return "";
|
|
274
|
+
if (el.type === "link")
|
|
275
|
+
return el.text && el.text !== el.url ? `${el.text} (${el.url})` : String(el.url ?? "");
|
|
276
|
+
if (el.type === "user")
|
|
277
|
+
return `<@${el.user_id}>`;
|
|
278
|
+
if (el.type === "channel")
|
|
279
|
+
return `<#${el.channel_id}>`;
|
|
280
|
+
if (el.type === "usergroup")
|
|
281
|
+
return `<!subteam^${el.usergroup_id}>`;
|
|
282
|
+
if (el.type === "broadcast")
|
|
283
|
+
return `<!${el.range}>`;
|
|
284
|
+
if (el.type === "emoji")
|
|
285
|
+
return `:${el.name}:`;
|
|
286
|
+
return typeof el.text === "string" ? el.text : "";
|
|
287
|
+
};
|
|
288
|
+
if (/^rich_text_(section|preformatted|quote)$/.test(String(block.type)))
|
|
289
|
+
return add(list(block.elements).map(inline).join(""));
|
|
290
|
+
add(typeof block.text === "string" ? block.text : block.text?.text);
|
|
291
|
+
if (block.type === "image")
|
|
292
|
+
add(block.title?.text ?? block.alt_text);
|
|
293
|
+
for (const f of list(block.fields).slice(0, 20))
|
|
294
|
+
add(typeof f === "string" ? f : f?.text);
|
|
295
|
+
for (const el of list(block.elements).slice(0, 40)) {
|
|
296
|
+
if (Array.isArray(el?.elements))
|
|
297
|
+
blockText(el, add, depth + 1);
|
|
298
|
+
else
|
|
299
|
+
add(typeof el?.text === "string" ? el.text : (el?.text?.text ?? el?.alt_text));
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* What a reader of a message sees, put together. A person's message says it in `text`. An app's
|
|
304
|
+
* often says it only in its attachments (an alert) or its blocks, and `text` is empty or a stub.
|
|
305
|
+
*/
|
|
306
|
+
function readable(m) {
|
|
307
|
+
const parts = [];
|
|
308
|
+
const add = (s) => {
|
|
309
|
+
const t = typeof s === "string" ? s.trim() : "";
|
|
310
|
+
// The same words are often there twice: as the text and as what stands in for an attachment.
|
|
311
|
+
if (t && parts.length < 60 && !parts.some((p) => p.includes(t)))
|
|
312
|
+
parts.push(t.slice(0, 8000));
|
|
313
|
+
};
|
|
314
|
+
add(m?.text);
|
|
315
|
+
if (!parts.length || m?.bot_id || m?.subtype === "bot_message")
|
|
316
|
+
for (const b of list(m?.blocks).slice(0, 30))
|
|
317
|
+
blockText(b, add);
|
|
318
|
+
for (const a of list(m?.attachments).slice(0, 10)) {
|
|
319
|
+
const before = parts.length;
|
|
320
|
+
add(a?.pretext);
|
|
321
|
+
add(a?.title && a?.title_link ? `${a.title} (${a.title_link})` : a?.title);
|
|
322
|
+
add(a?.text);
|
|
323
|
+
for (const f of list(a?.fields).slice(0, 20))
|
|
324
|
+
add(f?.title && f?.value ? `${f.title}: ${f.value}` : (f?.value ?? f?.title));
|
|
325
|
+
for (const b of list(a?.blocks).slice(0, 30))
|
|
326
|
+
blockText(b, add);
|
|
327
|
+
if (parts.length === before)
|
|
328
|
+
add(a?.fallback);
|
|
329
|
+
}
|
|
330
|
+
return parts.join("\n");
|
|
331
|
+
}
|
|
332
|
+
export default async function slack(source) {
|
|
333
|
+
const o = source.options;
|
|
334
|
+
const appToken = String(o.appToken ?? "");
|
|
335
|
+
if (!appToken)
|
|
336
|
+
throw new Error("the app-level token (xapp-...) is missing");
|
|
337
|
+
const token = typeof o.token === "string" && o.token ? o.token : undefined;
|
|
338
|
+
source.secret(appToken);
|
|
339
|
+
source.secret(token);
|
|
340
|
+
const base = ownServer(o.apiBase, SLACK);
|
|
341
|
+
const api = new URL(base);
|
|
342
|
+
const real = base === SLACK;
|
|
343
|
+
const l = lists(o);
|
|
344
|
+
const { mentions, keywords, from, ignore, sendTo } = l;
|
|
345
|
+
const events = new Set(l.events);
|
|
346
|
+
const channels = new Set(l.channels.filter(isChannel));
|
|
347
|
+
const byName = l.channels.filter((c) => !isChannel(c));
|
|
348
|
+
const dms = o.dms !== false;
|
|
349
|
+
const bots = o.bots === true;
|
|
350
|
+
const cap = capped(Math.min(Math.max(1, Number(o.perMinute ?? 60)), 600));
|
|
351
|
+
const maxBytes = Math.min(Number(o.maxMb ?? 10), 50) * 1024 * 1024;
|
|
352
|
+
const keepMs = Number(o.keepDays ?? 7) * 86_400_000;
|
|
353
|
+
if (!token && [...mentions, ...from, ...ignore].includes("me"))
|
|
354
|
+
throw new Error('"me" is the account the token belongs to, and this source has no token. Set it up again and name "token" in "ask", or write the user id instead of "me"');
|
|
355
|
+
if (!token && byName.length)
|
|
356
|
+
throw new Error(`a channel given by its name (${byName.join(", ")}) has to be looked up, and this source has no token for that. Set it up again and name "token" in "ask", or give the channel's id`);
|
|
357
|
+
const stop = new AbortController();
|
|
358
|
+
const rest = (ms) => new Promise((resolve) => {
|
|
359
|
+
if (stop.signal.aborted)
|
|
360
|
+
return resolve();
|
|
361
|
+
const done = () => {
|
|
362
|
+
clearTimeout(t);
|
|
363
|
+
stop.signal.removeEventListener("abort", done);
|
|
364
|
+
resolve();
|
|
365
|
+
};
|
|
366
|
+
const t = setTimeout(done, ms);
|
|
367
|
+
stop.signal.addEventListener("abort", done, { once: true });
|
|
368
|
+
});
|
|
369
|
+
// ---- the connections ---------------------------------------------------------------------------
|
|
370
|
+
// A server of the owner's own on this machine is reached as it is. Slack itself, and whatever address it hands out, has to be on the public internet.
|
|
371
|
+
const guard = guardFor(source, api.hostname, false, 60_000);
|
|
372
|
+
const local = guard ? undefined : new Agent();
|
|
373
|
+
const net = guard ?? local;
|
|
374
|
+
/**
|
|
375
|
+
* The sockets under the WebSockets. undici takes such a socket out of its pool, so closing the
|
|
376
|
+
* agent does not reach it, and the SDK can only destroy one it made the connection for itself.
|
|
377
|
+
* Noted here, so that stopping the source ends them also when Slack does not answer the goodbye.
|
|
378
|
+
*/
|
|
379
|
+
const sockets = new Set();
|
|
380
|
+
const noted = (handler) => new Proxy(handler, {
|
|
381
|
+
get: (h, key) => {
|
|
382
|
+
const v = h[key];
|
|
383
|
+
if (typeof v !== "function")
|
|
384
|
+
return v;
|
|
385
|
+
if (key !== "onRequestUpgrade" && key !== "onUpgrade")
|
|
386
|
+
return v.bind(h);
|
|
387
|
+
return (...args) => {
|
|
388
|
+
const socket = args.at(-1);
|
|
389
|
+
if (socket && typeof socket.destroy === "function" && typeof socket.once === "function") {
|
|
390
|
+
sockets.add(socket);
|
|
391
|
+
socket.once("close", () => sockets.delete(socket));
|
|
392
|
+
}
|
|
393
|
+
return v.apply(h, args);
|
|
394
|
+
};
|
|
395
|
+
},
|
|
396
|
+
});
|
|
397
|
+
// A WebSocket is asked for over HTTP/1.1, so that it has a socket of its own, as with the SDK's own connections.
|
|
398
|
+
const line = net.compose((dispatch) => (opts, handler) => (opts.upgrade ? dispatch({ ...opts, allowH2: false }, noted(handler)) : dispatch(opts, handler)));
|
|
399
|
+
const ours = (at) => at.host === api.host || (real && at.protocol === "https:" && (at.hostname === "slack.com" || at.hostname.endsWith(".slack.com")));
|
|
400
|
+
/** Every request of the SDK: only to Slack, never along a redirect, ended when the source stops. */
|
|
401
|
+
const send = async (url, init = {}) => {
|
|
402
|
+
const at = new URL(String(url));
|
|
403
|
+
// The SDK sends its token with every request, also to an address that an answer named (where a file is uploaded to).
|
|
404
|
+
if (!ours(at))
|
|
405
|
+
throw new Plain("an address that is not Slack's was named, and nothing is sent there");
|
|
406
|
+
let body = init.body;
|
|
407
|
+
// The SDK builds an upload with Node's own FormData, which this fetch (undici from npm) does not know: it would send the words "[object FormData]".
|
|
408
|
+
if (body instanceof FormData) {
|
|
409
|
+
const form = new Multipart();
|
|
410
|
+
for (const [key, value] of body.entries())
|
|
411
|
+
typeof value === "string" ? form.append(key, value) : form.append(key, value, value.name);
|
|
412
|
+
body = form;
|
|
413
|
+
}
|
|
414
|
+
return (await fetch(at, { ...init, body, redirect: "error", dispatcher: net, signal: AbortSignal.any([stop.signal, AbortSignal.timeout(typeof body === "string" ? 20_000 : 180_000)]) }));
|
|
415
|
+
};
|
|
416
|
+
const log = sdkLog(source, [appToken, token ?? ""]);
|
|
417
|
+
// Nothing is tried again by the SDK and no wait is its own: its timers would outlive the source. The loop below and `call` do both.
|
|
418
|
+
const quiet = { slackApiUrl: `${base}/`, fetch: send, retryConfig: { retries: 0 }, rejectRateLimitedCalls: true, allowAbsoluteUrls: false };
|
|
419
|
+
const web = token ? new WebClient(token, { ...quiet, logger: log }) : undefined;
|
|
420
|
+
// The SDK's own reconnecting is off: when Slack refuses the token on the way back in, it throws where nothing can catch it, and it never says how things stand.
|
|
421
|
+
const client = new SocketModeClient({ appToken, logger: log, autoReconnectEnabled: false, clientPingTimeout: pace.ping, clientOptions: { ...quiet }, dispatcher: line });
|
|
422
|
+
/** A call of the Web API. When Slack says to wait, it is waited here, where the wait ends with the source. */
|
|
423
|
+
let calm = 0;
|
|
424
|
+
const call = async (what) => {
|
|
425
|
+
for (let again = 0;; again++) {
|
|
426
|
+
if (calm > Date.now())
|
|
427
|
+
await rest(calm - Date.now());
|
|
428
|
+
if (stop.signal.aborted)
|
|
429
|
+
throw new Plain("stopped");
|
|
430
|
+
try {
|
|
431
|
+
return await what();
|
|
432
|
+
}
|
|
433
|
+
catch (e) {
|
|
434
|
+
if (!(e instanceof WebAPIRateLimitedError) || again >= 3)
|
|
435
|
+
throw e;
|
|
436
|
+
calm = Date.now() + Math.min(Math.max(e.retryAfter, 1), 60) * pace.second;
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
};
|
|
440
|
+
// ---- names -----------------------------------------------------------------------------------
|
|
441
|
+
// Looked up once each. One that Slack will not give (a scope the app lacks) is not asked for again.
|
|
442
|
+
const names = new Map();
|
|
443
|
+
const nameOf = async (kind, which) => {
|
|
444
|
+
const key = `${kind}:${which}`;
|
|
445
|
+
// (A name an event brought along is known without asking, also to a source without a token.)
|
|
446
|
+
if (which && web && !names.has(key)) {
|
|
447
|
+
if (names.size > 2000)
|
|
448
|
+
names.clear();
|
|
449
|
+
try {
|
|
450
|
+
let name;
|
|
451
|
+
if (kind === "user") {
|
|
452
|
+
const u = (await call(() => web.users.info({ user: which }))).user;
|
|
453
|
+
name = u?.real_name || u?.profile?.display_name || u?.name;
|
|
454
|
+
}
|
|
455
|
+
else
|
|
456
|
+
name = (await call(() => web.conversations.info({ channel: which }))).channel?.name;
|
|
457
|
+
names.set(key, name ? clip(String(name), 80) : null);
|
|
458
|
+
}
|
|
459
|
+
catch (e) {
|
|
460
|
+
// What failed for the moment (no network, "slow down") is asked again with the next message.
|
|
461
|
+
if (e instanceof WebAPIPlatformError && !PASSING.includes(e.data.error))
|
|
462
|
+
names.set(key, null);
|
|
463
|
+
source.log.debug(`no name for ${word(which)}`, reason(e, `${kind === "user" ? "users" : "conversations"}.info`));
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
return names.get(key) ?? undefined;
|
|
467
|
+
};
|
|
468
|
+
/** The name that goes with an id in an event: `userName` beside `user`, `channelName` beside `channel`. */
|
|
469
|
+
const nameAs = async (key, which) => {
|
|
470
|
+
const name = await nameOf(key === "channel" ? "channel" : "user", which);
|
|
471
|
+
return name ? { [`${key}Name`]: name } : {};
|
|
472
|
+
};
|
|
473
|
+
// ---- who the app is, and which channels were meant -------------------------------------------------
|
|
474
|
+
/** The account the token belongs to: "me". With a user token that is the owner, with a bot token the bot. */
|
|
475
|
+
let me = "";
|
|
476
|
+
const self = { app: "", bot: "" };
|
|
477
|
+
let ready = !web;
|
|
478
|
+
const prepare = async () => {
|
|
479
|
+
if (ready || !web)
|
|
480
|
+
return;
|
|
481
|
+
let asking = "auth.test";
|
|
482
|
+
try {
|
|
483
|
+
const who = await call(() => web.auth.test());
|
|
484
|
+
me = String(who.user_id ?? "");
|
|
485
|
+
Object.assign(self, { app: String(who.app_id ?? ""), bot: String(who.bot_id ?? "") });
|
|
486
|
+
asking = "conversations.list";
|
|
487
|
+
const missing = new Set(byName);
|
|
488
|
+
// Private channels need a scope of their own (groups:read). An app without it still finds the public ones.
|
|
489
|
+
for (const types of ["public_channel,private_channel", "public_channel"]) {
|
|
490
|
+
if (!missing.size)
|
|
491
|
+
break;
|
|
492
|
+
try {
|
|
493
|
+
let cursor = "";
|
|
494
|
+
for (let page = 0; page < 200 && missing.size; page++) {
|
|
495
|
+
const got = await call(() => web.conversations.list({ types, exclude_archived: true, limit: 200, ...(cursor ? { cursor } : {}) }));
|
|
496
|
+
for (const c of got.channels ?? []) {
|
|
497
|
+
const name = String(c.name ?? "").toLowerCase();
|
|
498
|
+
if (!c.id || !missing.delete(name))
|
|
499
|
+
continue;
|
|
500
|
+
channels.add(c.id);
|
|
501
|
+
names.set(`channel:${c.id}`, clip(name, 80));
|
|
502
|
+
}
|
|
503
|
+
cursor = String(got.response_metadata?.next_cursor ?? "");
|
|
504
|
+
if (!cursor)
|
|
505
|
+
break;
|
|
506
|
+
}
|
|
507
|
+
break;
|
|
508
|
+
}
|
|
509
|
+
catch (e) {
|
|
510
|
+
if (!(e instanceof WebAPIPlatformError && e.data.error === "missing_scope" && types.includes("private")))
|
|
511
|
+
throw e;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
if (missing.size)
|
|
515
|
+
throw new Fatal(`there is no channel named ${[...missing].map((n) => `"${n}"`).join(", ")} that the app can see. Check the spelling, invite the app to a private channel (/invite), or give the channel's id`);
|
|
516
|
+
ready = true;
|
|
517
|
+
}
|
|
518
|
+
catch (e) {
|
|
519
|
+
if (e instanceof Plain)
|
|
520
|
+
throw e;
|
|
521
|
+
if (!(e instanceof WebAPIPlatformError) || PASSING.includes(e.data.error))
|
|
522
|
+
throw new Plain(reason(e, asking));
|
|
523
|
+
if (asking === "auth.test")
|
|
524
|
+
throw new Fatal(`Slack does not take the token (${word(e.data.error)}). A bot token (xoxb-...) or user token (xoxp-...) is under "OAuth & Permissions" of the Slack app`);
|
|
525
|
+
throw new Fatal(`Slack does not let the app list its channels (${word(e.data.error)}). To find a channel by its name the app needs the scope channels:read, and groups:read for a private one. Or give the channel's id`);
|
|
526
|
+
}
|
|
527
|
+
};
|
|
528
|
+
const on = (people, who) => people.includes(who) || (who === me && people.includes("me"));
|
|
529
|
+
const mentioned = (text) => {
|
|
530
|
+
for (const entry of mentions) {
|
|
531
|
+
const who = entry === "me" ? me : entry;
|
|
532
|
+
if (!who)
|
|
533
|
+
continue;
|
|
534
|
+
const hit = EVERYBODY.includes(who) ? text.includes(`<!${who}>`) || text.includes(`<!${who}|`) : isGroup(who) ? text.includes(`<!subteam^${who}`) : text.includes(`<@${who}>`) || text.includes(`<@${who}|`);
|
|
535
|
+
if (hit)
|
|
536
|
+
return who;
|
|
537
|
+
}
|
|
538
|
+
return undefined;
|
|
539
|
+
};
|
|
540
|
+
/** A message's text the way a reader sees it: <@U123> is a person, <#C123|name> a channel, <https://x|label> a link. */
|
|
541
|
+
const worded = async (raw) => {
|
|
542
|
+
const people = new Map();
|
|
543
|
+
for (const who of [...new Set([...raw.matchAll(/<@([A-Z0-9]+)(?:\|[^>]*)?>/g)].map((x) => x[1]))].slice(0, 10)) {
|
|
544
|
+
const name = await nameOf("user", who);
|
|
545
|
+
if (name)
|
|
546
|
+
people.set(who, name);
|
|
547
|
+
}
|
|
548
|
+
const rooms = new Map();
|
|
549
|
+
for (const which of [...new Set([...raw.matchAll(/<#([A-Z0-9]+)\|?>/g)].map((x) => x[1]))].slice(0, 5)) {
|
|
550
|
+
const name = await nameOf("channel", which);
|
|
551
|
+
if (name)
|
|
552
|
+
rooms.set(which, name);
|
|
553
|
+
}
|
|
554
|
+
return (raw
|
|
555
|
+
.replace(/<@([A-Z0-9]+)(?:\|([^>]*))?>/g, (all, who, label) => (people.has(who) ? `@${people.get(who)}` : label ? `@${label}` : all))
|
|
556
|
+
.replace(/<#([A-Z0-9]+)(?:\|([^>]*))?>/g, (all, which, label) => (label ? `#${label}` : rooms.has(which) ? `#${rooms.get(which)}` : all))
|
|
557
|
+
.replace(/<!(here|channel|everyone)(?:\|[^>]*)?>/g, "@$1")
|
|
558
|
+
.replace(/<!subteam\^[A-Z0-9]+\|@?([^>]+)>/g, "@$1")
|
|
559
|
+
// A link keeps its address next to its words: where it goes is not hidden behind what it says.
|
|
560
|
+
.replace(/<((?:https?:\/\/|mailto:)[^|>\s]+)(?:\|([^>]*))?>/g, (_all, url, label) => (label && label !== url && `mailto:${label}` !== url ? `${label} (${url.replace(/^mailto:/, "")})` : url.replace(/^mailto:/, "")))
|
|
561
|
+
.replace(/</g, "<")
|
|
562
|
+
.replace(/>/g, ">")
|
|
563
|
+
.replace(/&/g, "&"));
|
|
564
|
+
};
|
|
565
|
+
// ---- the files of a message ----------------------------------------------------------------------
|
|
566
|
+
const dir = path.join(source.dataDir, "files");
|
|
567
|
+
let pruner;
|
|
568
|
+
if (token) {
|
|
569
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
570
|
+
source.media(dir);
|
|
571
|
+
pruneFiles(dir, keepMs);
|
|
572
|
+
pruner = setInterval(() => pruneFiles(dir, keepMs), 6 * 3_600_000);
|
|
573
|
+
pruner.unref?.();
|
|
574
|
+
}
|
|
575
|
+
const fromSlack = (at) => (real ? at.protocol === "https:" && at.hostname === FILES : at.protocol === api.protocol && at.host === api.host);
|
|
576
|
+
/** One file of a message: what it is, and its bytes when they could be had. Nothing a message says decides where it is fetched from. */
|
|
577
|
+
const fetched = async (f) => {
|
|
578
|
+
const size = Number(f?.size) || 0;
|
|
579
|
+
const none = { name: clip(fileName(String(f?.name ?? f?.title ?? ""), "file"), 200), type: clip(String(f?.mimetype ?? f?.filetype ?? ""), 80), size, bytes: Buffer.alloc(0), skipped: true };
|
|
580
|
+
if (!token || size > maxBytes)
|
|
581
|
+
return none;
|
|
582
|
+
let at;
|
|
583
|
+
try {
|
|
584
|
+
at = new URL(String(f?.url_private_download ?? f?.url_private ?? ""));
|
|
585
|
+
}
|
|
586
|
+
catch {
|
|
587
|
+
return none;
|
|
588
|
+
}
|
|
589
|
+
if (!fromSlack(at))
|
|
590
|
+
return none;
|
|
591
|
+
try {
|
|
592
|
+
const res = await fetch(at, { headers: { authorization: `Bearer ${token}` }, redirect: "manual", dispatcher: net, signal: AbortSignal.any([stop.signal, AbortSignal.timeout(60_000)]) });
|
|
593
|
+
// A file the token may not read is answered with a redirect to the page where one signs in. That page is not the file, and is not followed.
|
|
594
|
+
const page = /text\/html/i.test(res.headers.get("content-type") ?? "") && !/html/i.test(none.type);
|
|
595
|
+
if (res.status !== 200 || !res.body || page) {
|
|
596
|
+
await res.body?.cancel().catch(() => { });
|
|
597
|
+
return none;
|
|
598
|
+
}
|
|
599
|
+
const chunks = [];
|
|
600
|
+
let got = 0;
|
|
601
|
+
for await (const chunk of res.body) {
|
|
602
|
+
got += chunk.length;
|
|
603
|
+
// What a message says a file's size is, is not what is counted.
|
|
604
|
+
if (got > maxBytes)
|
|
605
|
+
return { ...none, size: Math.max(size, got) };
|
|
606
|
+
chunks.push(chunk);
|
|
607
|
+
}
|
|
608
|
+
return { ...none, size: got, bytes: Buffer.concat(chunks), skipped: false };
|
|
609
|
+
}
|
|
610
|
+
catch (e) {
|
|
611
|
+
source.log.debug("could not fetch a file", reason(e));
|
|
612
|
+
return none;
|
|
613
|
+
}
|
|
614
|
+
};
|
|
615
|
+
/** Whether something by `user` in `channel` counts. With a `text` (a message, an edit) mentions and keywords are looked for in it. */
|
|
616
|
+
const counts = (x) => {
|
|
617
|
+
// (An app that posts has an id as an app, B..., and often one as a user as well: either may be on a list.)
|
|
618
|
+
const one = (people) => Boolean((x.user && on(people, x.user)) || (x.bot && people.includes(x.bot)));
|
|
619
|
+
if (one(ignore))
|
|
620
|
+
return undefined;
|
|
621
|
+
// What the account itself writes is not news to its owner (with a user token, that is the owner). Unless they ask for it: "me" on `from`.
|
|
622
|
+
if (me && x.user === me && !from.includes("me"))
|
|
623
|
+
return undefined;
|
|
624
|
+
const mention = x.text === undefined ? undefined : mentioned(x.text);
|
|
625
|
+
const keyword = x.text === undefined ? undefined : keywordIn(keywords, x.text);
|
|
626
|
+
const found = { ...(mention ? { mention } : {}), ...(keyword ? { keyword } : {}) };
|
|
627
|
+
if (one(from))
|
|
628
|
+
return { from: true, ...found };
|
|
629
|
+
if (x.dm)
|
|
630
|
+
return dms ? found : undefined;
|
|
631
|
+
if (x.channel && l.channels.length && !channels.has(x.channel))
|
|
632
|
+
return undefined;
|
|
633
|
+
if (x.text !== undefined && (mentions.length || keywords.length) && !mention && !keyword)
|
|
634
|
+
return undefined;
|
|
635
|
+
return found;
|
|
636
|
+
};
|
|
637
|
+
/** What this source sent itself: a message by where and when, an emoji by its message and name. */
|
|
638
|
+
const sent = new Set();
|
|
639
|
+
const remember = (key) => {
|
|
640
|
+
sent.add(key);
|
|
641
|
+
if (sent.size > 500)
|
|
642
|
+
for (const k of [...sent].slice(0, 250))
|
|
643
|
+
sent.delete(k);
|
|
644
|
+
};
|
|
645
|
+
/** A post of the app itself: Slack says which app posted, and what went out through here is known. */
|
|
646
|
+
const own = (m, app) => {
|
|
647
|
+
const by = String(m?.app_id ?? m?.bot_profile?.app_id ?? "");
|
|
648
|
+
if (by && (by === app || by === self.app))
|
|
649
|
+
return true;
|
|
650
|
+
if (m?.bot_id && m.bot_id === self.bot)
|
|
651
|
+
return true;
|
|
652
|
+
if (self.bot && m?.user && m.user === me)
|
|
653
|
+
return true;
|
|
654
|
+
return sent.has(`${m?.channel}:${m?.ts}`);
|
|
655
|
+
};
|
|
656
|
+
const placeOf = (channel, said) => {
|
|
657
|
+
const t = typeof said === "string" && said ? said : channel.startsWith("D") ? "im" : channel.startsWith("G") ? "group" : "channel";
|
|
658
|
+
return { dm: t === "im", kind: t === "im" ? "dm" : t === "mpim" || t === "group" ? "group" : "channel" };
|
|
659
|
+
};
|
|
660
|
+
// One after the other: looking a name up or fetching a file must not let a later report overtake an earlier one.
|
|
661
|
+
let queue = Promise.resolve();
|
|
662
|
+
let waiting = 0;
|
|
663
|
+
let lost = 0;
|
|
664
|
+
/** Report something, if the cap allows: `job` gets the number of reports that were left out before it. */
|
|
665
|
+
const later = (job) => {
|
|
666
|
+
if (!cap.ok())
|
|
667
|
+
return false;
|
|
668
|
+
// What waits is bounded too: reports that take long (a file to fetch) must not pile up behind each other.
|
|
669
|
+
if (waiting >= 200) {
|
|
670
|
+
lost++;
|
|
671
|
+
return false;
|
|
672
|
+
}
|
|
673
|
+
waiting++;
|
|
674
|
+
const dropped = cap.dropped() + lost;
|
|
675
|
+
lost = 0;
|
|
676
|
+
queue = queue
|
|
677
|
+
.then(async () => {
|
|
678
|
+
if (!stop.signal.aborted)
|
|
679
|
+
await job(dropped);
|
|
680
|
+
})
|
|
681
|
+
.catch((e) => source.log.warn("could not report an event", reason(e)))
|
|
682
|
+
.finally(() => void waiting--);
|
|
683
|
+
return true;
|
|
684
|
+
};
|
|
685
|
+
const out = (event, payload, dropped) => {
|
|
686
|
+
if (!stop.signal.aborted)
|
|
687
|
+
source.emit(event, { ...payload, ...(dropped ? { dropped } : {}) });
|
|
688
|
+
};
|
|
689
|
+
/** Somebody wrote, or what somebody wrote was changed or taken away. */
|
|
690
|
+
const written = (m, app) => {
|
|
691
|
+
const edit = m.subtype === "message_changed" || m.subtype === "message_deleted";
|
|
692
|
+
if (!events.has(edit ? "edit" : "message"))
|
|
693
|
+
return;
|
|
694
|
+
if (m.subtype && !edit && !WRITTEN.includes(m.subtype))
|
|
695
|
+
return;
|
|
696
|
+
const channel = String(m.channel ?? "");
|
|
697
|
+
const { dm, kind } = placeOf(channel, m.channel_type);
|
|
698
|
+
if (m.subtype === "message_deleted") {
|
|
699
|
+
const before = m.previous_message ?? {};
|
|
700
|
+
if ((before.bot_id && !bots) || own({ ...before, channel }, app))
|
|
701
|
+
return;
|
|
702
|
+
const text = readable(before);
|
|
703
|
+
if (!counts({ user: String(before.user ?? before.bot_id ?? ""), bot: before.bot_id, channel, dm, text }))
|
|
704
|
+
return;
|
|
705
|
+
later(async (dropped) => out("deleted", { channel, ...(dm ? {} : await nameAs("channel", channel)), ts: String(m.deleted_ts ?? before.ts ?? ""), ...(m.previous_message ? { previous: clip(await worded(text)) } : {}) }, dropped));
|
|
706
|
+
return;
|
|
707
|
+
}
|
|
708
|
+
const now = edit ? { ...(m.message ?? {}), channel } : m;
|
|
709
|
+
const byApp = Boolean(now.bot_id) || now.subtype === "bot_message";
|
|
710
|
+
if ((byApp && !bots) || own(now, app))
|
|
711
|
+
return;
|
|
712
|
+
const user = String(now.user ?? now.bot_id ?? "");
|
|
713
|
+
if (!user)
|
|
714
|
+
return;
|
|
715
|
+
const raw = readable(now);
|
|
716
|
+
const before = edit && m.previous_message ? readable(m.previous_message) : undefined;
|
|
717
|
+
// Slack also says "changed" when it has put the preview of a link under a person's message: what they wrote is the same.
|
|
718
|
+
if (edit && m.previous_message && (byApp ? before === raw : String(now.text ?? "") === String(m.previous_message.text ?? "")))
|
|
719
|
+
return;
|
|
720
|
+
const why = counts({ user, bot: now.bot_id, channel, dm, text: raw });
|
|
721
|
+
if (!why)
|
|
722
|
+
return;
|
|
723
|
+
later(async (dropped) => {
|
|
724
|
+
const text = clip(await worded(raw));
|
|
725
|
+
// An app that posts for somebody says under which name; a person's name is looked up.
|
|
726
|
+
const posted = byApp ? clip(String(now.username ?? now.bot_profile?.name ?? ""), 80) : "";
|
|
727
|
+
const who = posted ? { userName: posted } : await nameAs("user", user);
|
|
728
|
+
const place = { channel, ...(dm ? {} : await nameAs("channel", channel)), kind };
|
|
729
|
+
// Why it is reported, in a word each, so that a subscription can pick ("payload.why": {"contains": "mention"}) and an agent need not work it out.
|
|
730
|
+
const because = [...(dm ? ["dm"] : []), ...(why.mention ? ["mention"] : []), ...(why.keyword ? ["keyword"] : []), ...(why.from ? ["from"] : [])];
|
|
731
|
+
const reasons = { why: because.length ? because : ["channel"] };
|
|
732
|
+
if (edit)
|
|
733
|
+
return out("edited", { text, ...(before !== undefined ? { previous: clip(await worded(before)) } : {}), user, ...who, ...place, ts: String(now.ts ?? ""), ...reasons, ...why }, dropped);
|
|
734
|
+
const got = [];
|
|
735
|
+
for (const f of list(m.files).slice(0, 10))
|
|
736
|
+
got.push(await fetched(f));
|
|
737
|
+
const kept = got.length ? keepFiles(dir, { attachments: got }) : undefined;
|
|
738
|
+
out("message", {
|
|
739
|
+
text,
|
|
740
|
+
user,
|
|
741
|
+
...who,
|
|
742
|
+
...place,
|
|
743
|
+
ts: String(m.ts ?? ""),
|
|
744
|
+
...(m.thread_ts && m.thread_ts !== m.ts ? { thread: String(m.thread_ts), reply: true } : {}),
|
|
745
|
+
...(byApp ? { bot: true } : {}),
|
|
746
|
+
...reasons,
|
|
747
|
+
...why,
|
|
748
|
+
...(kept ? { files: kept.attachments.map((a) => ({ name: a.file, type: a.type, size: a.size, ...(a.path ? { path: a.path } : {}) })) } : {}),
|
|
749
|
+
...(kept?.images ? { images: kept.images } : {}),
|
|
750
|
+
}, dropped);
|
|
751
|
+
});
|
|
752
|
+
};
|
|
753
|
+
/** Anything else Slack tells an app: an emoji, somebody joining, a channel, a pin, or an event pine has no name for. */
|
|
754
|
+
const happened = (e) => {
|
|
755
|
+
const t = String(e.type);
|
|
756
|
+
const kind = KIND_OF[t] ?? "other";
|
|
757
|
+
// A new name is the channel's name from here on, whether or not such changes are reported: in its turn, not before what was written earlier.
|
|
758
|
+
if (/_rename$/.test(t) && typeof e.channel?.id === "string" && typeof e.channel.name === "string" && e.channel.name)
|
|
759
|
+
queue = queue.then(() => void names.set(`channel:${e.channel.id}`, clip(e.channel.name, 80)));
|
|
760
|
+
if (!events.has(kind))
|
|
761
|
+
return;
|
|
762
|
+
const text = (v) => (typeof v === "string" ? v : "");
|
|
763
|
+
if (kind === "reaction") {
|
|
764
|
+
if (e.item?.type !== "message")
|
|
765
|
+
return;
|
|
766
|
+
const [user, channel, ts, reaction] = [text(e.user), text(e.item.channel), text(e.item.ts), clip(text(e.reaction), 100)];
|
|
767
|
+
// The emoji the agent put there itself comes back as an event like anybody's.
|
|
768
|
+
if ((self.bot && user === me) || sent.delete(`${channel}:${ts}:${reaction}`))
|
|
769
|
+
return;
|
|
770
|
+
if (!counts({ user, channel, dm: placeOf(channel).dm }))
|
|
771
|
+
return;
|
|
772
|
+
const author = text(e.item_user);
|
|
773
|
+
later(async (dropped) => out("reaction", { reaction, added: t === "reaction_added", user, ...(await nameAs("user", user)), channel, ...(await nameAs("channel", channel)), ts, ...(author ? { author, ...(await nameAs("author", author)) } : {}) }, dropped));
|
|
774
|
+
}
|
|
775
|
+
else if (kind === "member") {
|
|
776
|
+
const user = typeof e.user === "string" ? e.user : text(e.user?.id);
|
|
777
|
+
const channel = text(e.channel);
|
|
778
|
+
if (!user || !counts({ user, channel, dm: false }))
|
|
779
|
+
return;
|
|
780
|
+
later(async (dropped) => {
|
|
781
|
+
// Somebody new to the workspace comes with their name.
|
|
782
|
+
const called = text(e.user?.real_name) || text(e.user?.name);
|
|
783
|
+
if (called && !names.get(`user:${user}`))
|
|
784
|
+
names.set(`user:${user}`, clip(called, 80));
|
|
785
|
+
out(t === "member_left_channel" ? "left" : "joined", { user, ...(await nameAs("user", user)), ...(channel ? { channel, ...(await nameAs("channel", channel)) } : {}) }, dropped);
|
|
786
|
+
});
|
|
787
|
+
}
|
|
788
|
+
else if (kind === "channel") {
|
|
789
|
+
const channel = typeof e.channel === "string" ? e.channel : text(e.channel?.id);
|
|
790
|
+
const what = CHANGED[t.replace(/^(channel|group)_/, "")];
|
|
791
|
+
if (!channel || !what || !counts({ user: text(e.user) || text(e.channel?.creator), channel, dm: false }))
|
|
792
|
+
return;
|
|
793
|
+
later(async (dropped) => {
|
|
794
|
+
// A channel that was just made comes with its name.
|
|
795
|
+
if (typeof e.channel?.name === "string" && e.channel.name)
|
|
796
|
+
names.set(`channel:${channel}`, clip(e.channel.name, 80));
|
|
797
|
+
out("channel", { what, channel, ...(what === "deleted" && !names.get(`channel:${channel}`) ? {} : await nameAs("channel", channel)) }, dropped);
|
|
798
|
+
});
|
|
799
|
+
}
|
|
800
|
+
else if (kind === "pin") {
|
|
801
|
+
const [user, channel, ts] = [text(e.user), text(e.channel_id) || text(e.item?.channel), text(e.item?.message?.ts)];
|
|
802
|
+
if (!channel || !counts({ user, channel, dm: placeOf(channel).dm }))
|
|
803
|
+
return;
|
|
804
|
+
later(async (dropped) => out("pin", { added: t === "pin_added", channel, ...(await nameAs("channel", channel)), ...(ts ? { ts } : {}), user, ...(await nameAs("user", user)) }, dropped));
|
|
805
|
+
}
|
|
806
|
+
else {
|
|
807
|
+
if (!/^[a-z0-9_.:-]{1,80}$/i.test(t))
|
|
808
|
+
return;
|
|
809
|
+
const channel = text(e.channel) || text(e.channel_id);
|
|
810
|
+
if (!counts({ user: text(e.user) || text(e.user?.id) || text(e.user_id), channel, dm: channel ? placeOf(channel).dm : false }))
|
|
811
|
+
return;
|
|
812
|
+
later(async (dropped) => out("event", { type: t, data: shown(e) }, dropped));
|
|
813
|
+
}
|
|
814
|
+
};
|
|
815
|
+
/** A slash command of the app. Says whether it is passed on, which is what its sender is told. */
|
|
816
|
+
const command = (c) => {
|
|
817
|
+
if (!events.has("command") || typeof c?.command !== "string")
|
|
818
|
+
return false;
|
|
819
|
+
const [user, channel] = [String(c.user_id ?? ""), String(c.channel_id ?? "")];
|
|
820
|
+
if (!counts({ user, channel, dm: placeOf(channel).dm }))
|
|
821
|
+
return false;
|
|
822
|
+
return later(async (dropped) => out("command", { command: clip(c.command, 100), text: clip(await worded(String(c.text ?? ""))), user, ...(await nameAs("user", user)), channel, ...(placeOf(channel).dm ? {} : await nameAs("channel", channel)) }, dropped));
|
|
823
|
+
};
|
|
824
|
+
// Slack sends an event again when its acknowledgement was slow, and tells an app about a message
|
|
825
|
+
// that mentions it twice (as a message and as a mention): what was seen is not reported again.
|
|
826
|
+
const seen = new Set();
|
|
827
|
+
const fresh = (key) => {
|
|
828
|
+
if (seen.has(key))
|
|
829
|
+
return false;
|
|
830
|
+
seen.add(key);
|
|
831
|
+
if (seen.size > 2000)
|
|
832
|
+
for (const k of [...seen].slice(0, 1000))
|
|
833
|
+
seen.delete(k);
|
|
834
|
+
return true;
|
|
835
|
+
};
|
|
836
|
+
client.on("slack_event", (env) => {
|
|
837
|
+
let answer;
|
|
838
|
+
try {
|
|
839
|
+
const body = env?.body ?? {};
|
|
840
|
+
const e = body.event;
|
|
841
|
+
if (env?.type === "slash_commands") {
|
|
842
|
+
if (command(body))
|
|
843
|
+
answer = { text: PASSED };
|
|
844
|
+
}
|
|
845
|
+
else if (env?.type === "events_api" && e && typeof e === "object" && typeof e.type === "string" && (!body.event_id || fresh(String(body.event_id)))) {
|
|
846
|
+
const said = e.type === "message" || e.type === "app_mention";
|
|
847
|
+
if (!said)
|
|
848
|
+
happened(e);
|
|
849
|
+
else if (e.subtype === "message_changed" || e.subtype === "message_deleted" || fresh(`${e.channel}:${e.ts}`))
|
|
850
|
+
written(e, String(body.api_app_id ?? ""));
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
catch (e) {
|
|
854
|
+
source.log.warn("could not take an event", errText(e));
|
|
855
|
+
}
|
|
856
|
+
// Every envelope is acknowledged, also one that is not reported (a button, a form): Slack sends again what it thinks was not taken.
|
|
857
|
+
if (typeof env?.ack === "function")
|
|
858
|
+
void Promise.resolve(env.ack(answer)).catch((e) => source.log.debug("could not acknowledge", errText(e)));
|
|
859
|
+
});
|
|
860
|
+
// Slack says why it is about to close a connection, in a message the SDK acts on and does not hand on.
|
|
861
|
+
let closing = "";
|
|
862
|
+
client.on("ws_message", (data) => {
|
|
863
|
+
if (typeof data !== "string" || data.length > 2000 || !data.includes('"disconnect"'))
|
|
864
|
+
return;
|
|
865
|
+
try {
|
|
866
|
+
const m = JSON.parse(data);
|
|
867
|
+
if (m?.type === "disconnect")
|
|
868
|
+
closing = String(m.reason ?? "");
|
|
869
|
+
}
|
|
870
|
+
catch {
|
|
871
|
+
// not for us
|
|
872
|
+
}
|
|
873
|
+
});
|
|
874
|
+
// A socket address that is not encrypted is not connected to. (Thrown here, the SDK takes it for a failed start.)
|
|
875
|
+
client.on("authenticated", (r) => {
|
|
876
|
+
if (guard && !/^wss:\/\//i.test(String(r?.url ?? "")))
|
|
877
|
+
throw new Plain("Slack gave an address that is not wss://");
|
|
878
|
+
});
|
|
879
|
+
/**
|
|
880
|
+
* End the connection. The SDK says goodbye and waits for the answer; a socket that is still
|
|
881
|
+
* open after `pace.bye` is cut, which is the end of the SDK's wait too. Nothing is open after this.
|
|
882
|
+
*/
|
|
883
|
+
const leave = async () => {
|
|
884
|
+
const cut = () => {
|
|
885
|
+
for (const s of sockets)
|
|
886
|
+
s.destroy();
|
|
887
|
+
};
|
|
888
|
+
const late = setTimeout(cut, pace.bye);
|
|
889
|
+
await client.disconnect().catch(() => { });
|
|
890
|
+
clearTimeout(late);
|
|
891
|
+
cut();
|
|
892
|
+
};
|
|
893
|
+
source.onStop(async () => {
|
|
894
|
+
stop.abort();
|
|
895
|
+
clearInterval(pruner);
|
|
896
|
+
await leave();
|
|
897
|
+
await local?.close().catch(() => { });
|
|
898
|
+
});
|
|
899
|
+
// What cannot work (a channel that is not there, a token Slack does not take) is found out now and is why the
|
|
900
|
+
// source does not start. What only fails for the moment (no network yet) is tried again by the loop below.
|
|
901
|
+
try {
|
|
902
|
+
await prepare();
|
|
903
|
+
}
|
|
904
|
+
catch (e) {
|
|
905
|
+
if (e instanceof Fatal)
|
|
906
|
+
throw new Error(e.message);
|
|
907
|
+
}
|
|
908
|
+
const listening = () => {
|
|
909
|
+
const kinds = [...events].map((k) => KINDS[k]?.short ?? k);
|
|
910
|
+
return `listening to ${[l.channels.length ? `${l.channels.length} ${plural(l.channels.length, "channel")}` : "every channel the app is in", ...(dms ? ["direct messages"] : [])].join(" and ")}${events.size === 1 && events.has("message") ? "" : `, for ${kinds.join(", ")}`}`;
|
|
911
|
+
};
|
|
912
|
+
let fatal = false;
|
|
913
|
+
hold(source, {
|
|
914
|
+
host: api.hostname,
|
|
915
|
+
note: listening,
|
|
916
|
+
run: async (signal, up, wait) => {
|
|
917
|
+
// Said once; trying the same again and again would ask Slack for nothing new.
|
|
918
|
+
if (fatal)
|
|
919
|
+
return new Promise((resolve) => signal.addEventListener("abort", () => resolve(), { once: true }));
|
|
920
|
+
try {
|
|
921
|
+
await prepare();
|
|
922
|
+
}
|
|
923
|
+
catch (e) {
|
|
924
|
+
fatal = e instanceof Fatal;
|
|
925
|
+
throw e;
|
|
926
|
+
}
|
|
927
|
+
if (calm > Date.now())
|
|
928
|
+
await rest(calm - Date.now());
|
|
929
|
+
closing = "";
|
|
930
|
+
let trouble;
|
|
931
|
+
let ended = () => { };
|
|
932
|
+
const gone = new Promise((resolve) => (ended = resolve));
|
|
933
|
+
// The first trouble is the reason; what follows from ending the connection is not.
|
|
934
|
+
const failed = (e) => void (trouble ??= e);
|
|
935
|
+
client.on("error", failed);
|
|
936
|
+
client.on("disconnected", ended);
|
|
937
|
+
const greeted = setTimeout(() => {
|
|
938
|
+
trouble = new Plain("Slack did not greet the connection in time");
|
|
939
|
+
void leave();
|
|
940
|
+
}, pace.hello);
|
|
941
|
+
try {
|
|
942
|
+
try {
|
|
943
|
+
await client.start();
|
|
944
|
+
}
|
|
945
|
+
catch (e) {
|
|
946
|
+
if (e instanceof WebAPIRateLimitedError)
|
|
947
|
+
calm = Date.now() + Math.min(Math.max(e.retryAfter, 1), 60) * pace.second;
|
|
948
|
+
throw new Plain(reason(trouble ?? e, "apps.connections.open"));
|
|
949
|
+
}
|
|
950
|
+
finally {
|
|
951
|
+
clearTimeout(greeted);
|
|
952
|
+
}
|
|
953
|
+
up();
|
|
954
|
+
await gone;
|
|
955
|
+
}
|
|
956
|
+
finally {
|
|
957
|
+
// Down for certain before the next attempt: a socket that is still saying goodbye would be taken for the new one.
|
|
958
|
+
await leave();
|
|
959
|
+
client.off("error", failed);
|
|
960
|
+
client.off("disconnected", ended);
|
|
961
|
+
}
|
|
962
|
+
// Slack renews its connections now and then and says so beforehand: connected to again at once.
|
|
963
|
+
if (closing === "warning" || closing === "refresh_requested") {
|
|
964
|
+
wait(10);
|
|
965
|
+
throw new Plain("Slack asked for a new connection");
|
|
966
|
+
}
|
|
967
|
+
throw new Plain(closing ? `Slack closed the connection: ${word(closing)}` : trouble ? reason(trouble) : "the connection was closed");
|
|
968
|
+
},
|
|
969
|
+
});
|
|
970
|
+
// ---- sending: only to what the owner put on the list, whatever the call names ------------------------------
|
|
971
|
+
const direct = new Map();
|
|
972
|
+
const refused = (e, method) => {
|
|
973
|
+
if (!(e instanceof WebAPIPlatformError))
|
|
974
|
+
return new Error(`could not send through Slack: ${reason(e)}`);
|
|
975
|
+
const code = e.data.error;
|
|
976
|
+
const scope = String(e.data.needed ?? "");
|
|
977
|
+
const hint = code === "not_in_channel"
|
|
978
|
+
? ". The app is not in that channel: somebody there writes /invite and its name"
|
|
979
|
+
: code === "missing_scope"
|
|
980
|
+
? `. The app lacks ${/^[\w.:,-]{1,100}$/.test(scope) ? `the scope ${scope}` : "a scope"}: your owner adds it under "OAuth & Permissions" of the Slack app and installs the app again`
|
|
981
|
+
: code === "channel_not_found"
|
|
982
|
+
? ". Slack knows no such channel, or the app may not see it"
|
|
983
|
+
: "";
|
|
984
|
+
return new Error(`Slack refused ${method}: ${word(code)}${hint}`);
|
|
985
|
+
};
|
|
986
|
+
const doing = async (method, what) => {
|
|
987
|
+
try {
|
|
988
|
+
return await call(what);
|
|
989
|
+
}
|
|
990
|
+
catch (e) {
|
|
991
|
+
throw refused(e, method);
|
|
992
|
+
}
|
|
993
|
+
};
|
|
994
|
+
/** The conversation with one person. Slack says which it is; asked once. */
|
|
995
|
+
const directly = async (user) => {
|
|
996
|
+
if (!direct.has(user)) {
|
|
997
|
+
const opened = (await doing("conversations.open", () => web.conversations.open({ users: user }))).channel?.id;
|
|
998
|
+
if (!opened)
|
|
999
|
+
throw new Error("Slack opened no conversation with that person");
|
|
1000
|
+
direct.set(user, opened);
|
|
1001
|
+
}
|
|
1002
|
+
return direct.get(user);
|
|
1003
|
+
};
|
|
1004
|
+
source.onSend(async (message) => {
|
|
1005
|
+
if (!sendTo.length)
|
|
1006
|
+
throw new Error('this source was set up to listen only: it has nowhere to send to. Tell your owner; they can set it up again with "sendTo"');
|
|
1007
|
+
if (!web)
|
|
1008
|
+
throw new Error('this source has no bot or user token, so it cannot send. Set it up again and name "token" in "ask"');
|
|
1009
|
+
const target = String(message.channel ?? (sendTo.length === 1 ? sendTo[0] : "")).replace(/^[#@]/, "");
|
|
1010
|
+
if (!target)
|
|
1011
|
+
throw new Error(`say where to: {"channel": "...", "text": "..."}. It may send to ${sendTo.join(", ")}`);
|
|
1012
|
+
let channel = target;
|
|
1013
|
+
if (isUser(target) && sendTo.includes(target))
|
|
1014
|
+
channel = await directly(target);
|
|
1015
|
+
else if (!sendTo.includes(target)) {
|
|
1016
|
+
// An answer to a direct message names the conversation, and the list names the person: Slack says whether they are the same.
|
|
1017
|
+
let theirs = false;
|
|
1018
|
+
if (target.startsWith("D"))
|
|
1019
|
+
for (const user of sendTo.filter(isUser))
|
|
1020
|
+
theirs ||= (await directly(user)) === target;
|
|
1021
|
+
if (!theirs)
|
|
1022
|
+
throw new Error(`"${target}" is not a ${isUser(target) ? "person" : "channel"} this source may send to (${sendTo.join(", ")})`);
|
|
1023
|
+
}
|
|
1024
|
+
const there = isUser(target) ? `${target} on Slack, directly` : `the Slack channel ${channel}`;
|
|
1025
|
+
const stamp = (v, key) => {
|
|
1026
|
+
if (!/^\d{1,12}\.\d{1,9}$/.test(String(v)))
|
|
1027
|
+
throw new Error(`"${key}" is the ts of a message, as the event had it: "1712345678.000100"`);
|
|
1028
|
+
return String(v);
|
|
1029
|
+
};
|
|
1030
|
+
if (message.react !== undefined) {
|
|
1031
|
+
const name = String(message.react).trim().replace(/^:|:$/g, "").toLowerCase();
|
|
1032
|
+
if (!/^[\p{L}\p{N}_+'-]{1,80}(::skin-tone-[2-6])?$/u.test(name))
|
|
1033
|
+
throw new Error('"react" is the name of an emoji as Slack writes it between colons: "eyes", "white_check_mark", "+1"');
|
|
1034
|
+
const ts = stamp(message.ts, "ts");
|
|
1035
|
+
remember(`${channel}:${ts}:${name}`);
|
|
1036
|
+
try {
|
|
1037
|
+
await call(() => web.reactions.add({ channel, timestamp: ts, name }));
|
|
1038
|
+
}
|
|
1039
|
+
catch (e) {
|
|
1040
|
+
// It is there already: what was asked for is the case.
|
|
1041
|
+
if (!(e instanceof WebAPIPlatformError && e.data.error === "already_reacted"))
|
|
1042
|
+
throw refused(e, "reactions.add");
|
|
1043
|
+
}
|
|
1044
|
+
return `put :${name}: on the message in ${there}`;
|
|
1045
|
+
}
|
|
1046
|
+
// "@channel" and its kind would call on everybody there. What an agent writes says it and calls on nobody.
|
|
1047
|
+
const text = String(message.text ?? "").trim().replace(/<!(channel|here|everyone)(?:\|[^>]*)?>/g, "@$1");
|
|
1048
|
+
const thread = message.thread === undefined || message.thread === "" ? undefined : stamp(message.thread, "thread");
|
|
1049
|
+
const file = message.file;
|
|
1050
|
+
if (file && Buffer.isBuffer(file.bytes)) {
|
|
1051
|
+
const filename = fileName(String(file.name ?? ""), "file");
|
|
1052
|
+
await doing("files.uploadV2", () => web.filesUploadV2({ channel_id: channel, file: file.bytes, filename, ...(text ? { initial_comment: text.slice(0, 39_000) } : {}), ...(thread ? { thread_ts: thread } : {}) }));
|
|
1053
|
+
return `posted ${filename} to ${there}`;
|
|
1054
|
+
}
|
|
1055
|
+
if (!text)
|
|
1056
|
+
throw new Error('there is nothing to send: give "text"');
|
|
1057
|
+
const done = await doing("chat.postMessage", () => web.chat.postMessage({ channel, text: text.slice(0, 39_000), ...(thread ? { thread_ts: thread } : {}) }));
|
|
1058
|
+
if (done.ts)
|
|
1059
|
+
remember(`${done.channel ?? channel}:${done.ts}`);
|
|
1060
|
+
return isUser(target) ? `sent to ${there}` : `posted to ${there}`;
|
|
1061
|
+
});
|
|
1062
|
+
}
|