@owlmeans/bot-slack 0.0.0-stage → 0.2.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 +74 -2
- package/agent-meta/manifest.json +16 -0
- package/agent-meta/skills/bot-slack/SKILL.md +117 -0
- package/build/api.d.ts +7 -0
- package/build/api.d.ts.map +1 -0
- package/build/api.js +65 -0
- package/build/api.js.map +1 -0
- package/build/append.d.ts +9 -0
- package/build/append.d.ts.map +1 -0
- package/build/append.js +13 -0
- package/build/append.js.map +1 -0
- package/build/consts.d.ts +70 -0
- package/build/consts.d.ts.map +1 -0
- package/build/consts.js +205 -0
- package/build/consts.js.map +1 -0
- package/build/errors.d.ts +22 -0
- package/build/errors.d.ts.map +1 -0
- package/build/errors.js +35 -0
- package/build/errors.js.map +1 -0
- package/build/index.d.ts +8 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +7 -0
- package/build/index.js.map +1 -0
- package/build/mock.d.ts +10 -0
- package/build/mock.d.ts.map +1 -0
- package/build/mock.js +253 -0
- package/build/mock.js.map +1 -0
- package/build/normalize.d.ts +4 -0
- package/build/normalize.d.ts.map +1 -0
- package/build/normalize.js +131 -0
- package/build/normalize.js.map +1 -0
- package/build/plugin.d.ts +11 -0
- package/build/plugin.d.ts.map +1 -0
- package/build/plugin.js +165 -0
- package/build/plugin.js.map +1 -0
- package/build/signature.d.ts +8 -0
- package/build/signature.d.ts.map +1 -0
- package/build/signature.js +25 -0
- package/build/signature.js.map +1 -0
- package/build/text.d.ts +9 -0
- package/build/text.d.ts.map +1 -0
- package/build/text.js +12 -0
- package/build/text.js.map +1 -0
- package/build/types.d.ts +185 -0
- package/build/types.d.ts.map +1 -0
- package/build/types.js +2 -0
- package/build/types.js.map +1 -0
- package/package.json +56 -4
- package/src/api.ts +70 -0
- package/src/append.ts +18 -0
- package/src/consts.ts +231 -0
- package/src/errors.ts +38 -0
- package/src/index.ts +7 -0
- package/src/mock.ts +287 -0
- package/src/normalize.ts +157 -0
- package/src/plugin.ts +191 -0
- package/src/signature.ts +33 -0
- package/src/text.ts +16 -0
- package/src/types.ts +207 -0
- package/tests/context.ts +85 -0
- package/tests/descriptor.spec.ts +64 -0
- package/tests/mock-ids.spec.ts +36 -0
- package/tests/slack-runtime.spec.ts +210 -0
- package/tests/slack.spec.ts +420 -0
- package/tests/tsconfig.json +12 -0
- package/tsconfig.json +16 -0
package/src/consts.ts
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import {
|
|
2
|
+
BotActionKind, BotReceiveMode, type BotCredentialField, type BotPlatformDescriptor, type BotTexts,
|
|
3
|
+
} from '@owlmeans/bot'
|
|
4
|
+
|
|
5
|
+
/** The Web API (https://docs.slack.dev/apis/web-api/) — override `base` for a proxy or a fake server. */
|
|
6
|
+
export const SLACK_API_BASE = 'https://slack.com/api'
|
|
7
|
+
|
|
8
|
+
/** The headers Slack signs an Events API request with (lower-cased, as servers hand them over). */
|
|
9
|
+
export const SLACK_SIGNATURE_HEADER = 'x-slack-signature'
|
|
10
|
+
export const SLACK_TIMESTAMP_HEADER = 'x-slack-request-timestamp'
|
|
11
|
+
/** Set on a redelivery (1, 2, 3) — the inbox's dedupe key absorbs it. */
|
|
12
|
+
export const SLACK_RETRY_NUM_HEADER = 'x-slack-retry-num'
|
|
13
|
+
|
|
14
|
+
/** The signature scheme: `v0=` + hex HMAC-SHA256(signing secret, `v0:<timestamp>:<raw body>`). */
|
|
15
|
+
export const SLACK_SIGNATURE_VERSION = 'v0'
|
|
16
|
+
|
|
17
|
+
/** A request whose timestamp is further than this from now is a replay (seconds). */
|
|
18
|
+
export const SLACK_SIGNATURE_TOLERANCE_S = 300
|
|
19
|
+
|
|
20
|
+
/** How long one Web API call may take. */
|
|
21
|
+
export const SLACK_CALL_TIMEOUT_MS = 15_000
|
|
22
|
+
|
|
23
|
+
/** Retries of a call answered 429, waiting its `Retry-After` each time. */
|
|
24
|
+
export const SLACK_RATE_LIMIT_RETRIES = 2
|
|
25
|
+
|
|
26
|
+
/** A `Retry-After` longer than this (seconds) is not waited for: the call fails `ratelimited`. */
|
|
27
|
+
export const SLACK_RATE_LIMIT_MAX_WAIT_S = 30
|
|
28
|
+
|
|
29
|
+
/** The wait when a 429 names none (seconds). */
|
|
30
|
+
export const SLACK_RATE_LIMIT_DEFAULT_WAIT_S = 1
|
|
31
|
+
|
|
32
|
+
/** Slack truncates longer text; it is clipped here first, without splitting a surrogate pair. */
|
|
33
|
+
export const SLACK_TEXT_MAX = 40_000
|
|
34
|
+
|
|
35
|
+
/** The `message` subtypes that are a member's new message — every other subtype is ignored. */
|
|
36
|
+
export const SLACK_MESSAGE_SUBTYPES = Object.freeze(['thread_broadcast', 'file_share', 'me_message'])
|
|
37
|
+
|
|
38
|
+
/** The subtype of an edit; it carries the new message in `message`. */
|
|
39
|
+
export const SLACK_EDIT_SUBTYPE = 'message_changed'
|
|
40
|
+
|
|
41
|
+
/** `auth.test` refusals that mean the token itself is wrong — `BotCredentialsRejected`, not a fault. */
|
|
42
|
+
export const SLACK_CREDENTIAL_ERRORS = Object.freeze([
|
|
43
|
+
'invalid_auth', 'not_authed', 'account_inactive', 'token_revoked', 'token_expired', 'not_allowed_token_type',
|
|
44
|
+
])
|
|
45
|
+
|
|
46
|
+
/** The bot events a connection subscribes to (Event Subscriptions → Subscribe to bot events). */
|
|
47
|
+
export const SLACK_BOT_EVENTS = Object.freeze(['message.channels', 'message.groups', 'message.im', 'app_mention'])
|
|
48
|
+
|
|
49
|
+
/** The bot token scopes the plugin's calls and events need. */
|
|
50
|
+
export const SLACK_BOT_SCOPES = Object.freeze([
|
|
51
|
+
'chat:write', 'channels:history', 'groups:history', 'im:history', 'app_mentions:read', 'reactions:write',
|
|
52
|
+
])
|
|
53
|
+
|
|
54
|
+
/** The user token scope `chat.delete` needs with an admin's token. */
|
|
55
|
+
export const SLACK_USER_SCOPES = Object.freeze(['chat:write'])
|
|
56
|
+
|
|
57
|
+
/** What a person does first: the credentials, saved before Slack checks the Request URL. */
|
|
58
|
+
export const SLACK_SETUP_CREDENTIALS_STEP = 'In your Slack app (https://api.slack.com/apps) add the bot token scopes '
|
|
59
|
+
+ `${SLACK_BOT_SCOPES.join(', ')} under OAuth & Permissions and install the app to the workspace; save its Bot `
|
|
60
|
+
+ 'User OAuth Token (xoxb-…) as botToken and the Signing Secret (Basic Information → App Credentials) as '
|
|
61
|
+
+ 'signingSecret on this connection BEFORE the next step — Slack checks the Request URL at once.'
|
|
62
|
+
|
|
63
|
+
/** Followed by the connection's hook URL. */
|
|
64
|
+
export const SLACK_SETUP_HOOK_STEP = 'Under Event Subscriptions, turn events on and paste the Request URL: '
|
|
65
|
+
|
|
66
|
+
/** When the connection has no hook URL yet (saved without the application's public address). */
|
|
67
|
+
export const SLACK_SETUP_HOOK_PENDING_STEP = 'Under Event Subscriptions, turn events on and paste this connection\'s '
|
|
68
|
+
+ 'Request URL — open the connection from the application\'s public address to see it.'
|
|
69
|
+
|
|
70
|
+
/** The rest of the manual setup. */
|
|
71
|
+
export const SLACK_SETUP_TAIL_STEPS = Object.freeze([
|
|
72
|
+
`Under "Subscribe to bot events" add ${SLACK_BOT_EVENTS.join(', ')}, save, and reinstall the app if Slack asks.`,
|
|
73
|
+
'Invite the bot to every channel it should read (/invite @your-bot) — it only sees channels it is a member of.',
|
|
74
|
+
'Optional, to delete members\' messages: a workspace admin or owner adds the user token scope '
|
|
75
|
+
+ `${SLACK_USER_SCOPES.join(', ')}, reinstalls the app and saves their User OAuth Token (xoxp-…) as userToken; `
|
|
76
|
+
+ 'without it the bot warns instead of deleting.',
|
|
77
|
+
])
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Slack reacts by emoji NAME. A Unicode emoji a handler written for any platform passes is mapped
|
|
81
|
+
* here (variation selectors stripped first); an unknown one goes as given and Slack answers `invalid_name`.
|
|
82
|
+
*/
|
|
83
|
+
export const SLACK_EMOJI_NAMES: Readonly<Record<string, string>> = Object.freeze({
|
|
84
|
+
'👍': '+1',
|
|
85
|
+
'👎': '-1',
|
|
86
|
+
'✅': 'white_check_mark',
|
|
87
|
+
'✔': 'heavy_check_mark',
|
|
88
|
+
'❌': 'x',
|
|
89
|
+
'⚠': 'warning',
|
|
90
|
+
'🚫': 'no_entry_sign',
|
|
91
|
+
'⛔': 'no_entry',
|
|
92
|
+
'🛑': 'octagonal_sign',
|
|
93
|
+
'👀': 'eyes',
|
|
94
|
+
'🙏': 'pray',
|
|
95
|
+
'❤': 'heart',
|
|
96
|
+
'🔥': 'fire',
|
|
97
|
+
'🎉': 'tada',
|
|
98
|
+
'👋': 'wave',
|
|
99
|
+
'😂': 'joy',
|
|
100
|
+
'😀': 'grinning',
|
|
101
|
+
'🙂': 'slightly_smiling_face',
|
|
102
|
+
'😢': 'cry',
|
|
103
|
+
'😡': 'rage',
|
|
104
|
+
'🤔': 'thinking_face',
|
|
105
|
+
'💯': '100',
|
|
106
|
+
'⭐': 'star',
|
|
107
|
+
'🦉': 'owl',
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
/** The mock's simulated defaults: one public channel and one member of the fake workspace. */
|
|
111
|
+
export const SLACK_MOCK_CHANNEL_ID = 'C0MOCK00001'
|
|
112
|
+
export const SLACK_MOCK_MEMBER_ID = 'U0MOCK00001'
|
|
113
|
+
/** Who wrote a simulated thread's parent when it was not the fake bot. */
|
|
114
|
+
export const SLACK_MOCK_OTHER_ID = 'U0MOCK00002'
|
|
115
|
+
export const SLACK_MOCK_TEAM_NAME = 'Mock workspace'
|
|
116
|
+
/** The deprecated verification token every Events API payload still carries — ignored by the plugin. */
|
|
117
|
+
export const SLACK_MOCK_VERIFICATION_TOKEN = 'mock-verification-token'
|
|
118
|
+
/** A mock `event_id` is `Ev` and this many random characters of {@link SLACK_MOCK_EVENT_ID_ALPHABET}. */
|
|
119
|
+
export const SLACK_MOCK_EVENT_ID_LENGTH = 10
|
|
120
|
+
export const SLACK_MOCK_EVENT_ID_ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
|
|
121
|
+
|
|
122
|
+
/** The platform id — a stored column and a hook URL segment: it never changes. */
|
|
123
|
+
export const SLACK_PLATFORM = 'slack'
|
|
124
|
+
|
|
125
|
+
/** What a Slack connection needs typed (or generated), with its labels and hints in every panel language. */
|
|
126
|
+
export const SLACK_CREDENTIALS: readonly BotCredentialField[] = Object.freeze([
|
|
127
|
+
Object.freeze({
|
|
128
|
+
key: 'botToken',
|
|
129
|
+
secret: true,
|
|
130
|
+
required: true,
|
|
131
|
+
label: Object.freeze({
|
|
132
|
+
en: 'Bot token (xoxb-…)',
|
|
133
|
+
pl: 'Token bota (xoxb-…)',
|
|
134
|
+
ru: 'Токен бота (xoxb-…)',
|
|
135
|
+
be: 'Токен бота (xoxb-…)',
|
|
136
|
+
uk: 'Токен бота (xoxb-…)',
|
|
137
|
+
es: 'Token del bot (xoxb-…)',
|
|
138
|
+
de: 'Bot-Token (xoxb-…)',
|
|
139
|
+
fr: 'Jeton du bot (xoxb-…)',
|
|
140
|
+
}),
|
|
141
|
+
hint: Object.freeze({
|
|
142
|
+
en: 'Your Slack app → OAuth & Permissions → Bot User OAuth Token.',
|
|
143
|
+
pl: 'Twoja aplikacja Slack → OAuth & Permissions → Bot User OAuth Token.',
|
|
144
|
+
ru: 'Ваше приложение Slack → OAuth & Permissions → Bot User OAuth Token.',
|
|
145
|
+
be: 'Ваша праграма Slack → OAuth & Permissions → Bot User OAuth Token.',
|
|
146
|
+
uk: 'Ваш застосунок Slack → OAuth & Permissions → Bot User OAuth Token.',
|
|
147
|
+
es: 'Tu app de Slack → OAuth & Permissions → Bot User OAuth Token.',
|
|
148
|
+
de: 'Ihre Slack-App → OAuth & Permissions → Bot User OAuth Token.',
|
|
149
|
+
fr: 'Votre app Slack → OAuth & Permissions → Bot User OAuth Token.',
|
|
150
|
+
}),
|
|
151
|
+
}),
|
|
152
|
+
Object.freeze({
|
|
153
|
+
key: 'signingSecret',
|
|
154
|
+
secret: true,
|
|
155
|
+
required: true,
|
|
156
|
+
label: Object.freeze({
|
|
157
|
+
en: 'Signing secret',
|
|
158
|
+
pl: 'Sekret podpisu',
|
|
159
|
+
ru: 'Секрет подписи',
|
|
160
|
+
be: 'Сакрэт подпісу',
|
|
161
|
+
uk: 'Секрет підпису',
|
|
162
|
+
es: 'Secreto de firma',
|
|
163
|
+
de: 'Signaturgeheimnis',
|
|
164
|
+
fr: 'Secret de signature',
|
|
165
|
+
}),
|
|
166
|
+
hint: Object.freeze({
|
|
167
|
+
en: 'Your Slack app → Basic Information → App Credentials.',
|
|
168
|
+
pl: 'Twoja aplikacja Slack → Basic Information → App Credentials.',
|
|
169
|
+
ru: 'Ваше приложение Slack → Basic Information → App Credentials.',
|
|
170
|
+
be: 'Ваша праграма Slack → Basic Information → App Credentials.',
|
|
171
|
+
uk: 'Ваш застосунок Slack → Basic Information → App Credentials.',
|
|
172
|
+
es: 'Tu app de Slack → Basic Information → App Credentials.',
|
|
173
|
+
de: 'Ihre Slack-App → Basic Information → App Credentials.',
|
|
174
|
+
fr: 'Votre app Slack → Basic Information → App Credentials.',
|
|
175
|
+
}),
|
|
176
|
+
}),
|
|
177
|
+
Object.freeze({
|
|
178
|
+
key: 'userToken',
|
|
179
|
+
secret: true,
|
|
180
|
+
required: false,
|
|
181
|
+
enables: Object.freeze([BotActionKind.Delete]),
|
|
182
|
+
label: Object.freeze({
|
|
183
|
+
en: 'Admin user token (xoxp-…)',
|
|
184
|
+
pl: 'Token administratora (xoxp-…)',
|
|
185
|
+
ru: 'Токен администратора (xoxp-…)',
|
|
186
|
+
be: 'Токен адміністратара (xoxp-…)',
|
|
187
|
+
uk: 'Токен адміністратора (xoxp-…)',
|
|
188
|
+
es: 'Token de usuario administrador (xoxp-…)',
|
|
189
|
+
de: 'Admin-Benutzertoken (xoxp-…)',
|
|
190
|
+
fr: 'Jeton utilisateur administrateur (xoxp-…)',
|
|
191
|
+
}),
|
|
192
|
+
hint: Object.freeze({
|
|
193
|
+
en: 'Lets the bot delete messages. Installed by a workspace admin; without it the bot warns instead.',
|
|
194
|
+
pl: 'Pozwala botowi usuwać wiadomości. Instaluje go administrator przestrzeni roboczej; bez niego bot zamiast tego ostrzega.',
|
|
195
|
+
ru: 'Позволяет боту удалять сообщения. Устанавливается администратором рабочего пространства; без него бот вместо этого предупреждает.',
|
|
196
|
+
be: 'Дазваляе боту выдаляць паведамленні. Усталёўваецца адміністратарам працоўнай прасторы; без яго бот замест гэтага папярэджвае.',
|
|
197
|
+
uk: 'Дозволяє боту видаляти повідомлення. Встановлює адміністратор робочого простору; без нього бот натомість попереджає.',
|
|
198
|
+
es: 'Permite al bot eliminar mensajes. Lo instala un administrador del espacio de trabajo; sin él, el bot advierte en su lugar.',
|
|
199
|
+
de: 'Erlaubt dem Bot, Nachrichten zu löschen. Ein Workspace-Admin installiert es; ohne es verwarnt der Bot stattdessen.',
|
|
200
|
+
fr: 'Permet au bot de supprimer des messages. Installé par un administrateur de l’espace de travail ; sans lui, le bot avertit à la place.',
|
|
201
|
+
}),
|
|
202
|
+
}),
|
|
203
|
+
]) as readonly BotCredentialField[]
|
|
204
|
+
|
|
205
|
+
/** What a person does in Slack itself so the bot can act — in every panel language. */
|
|
206
|
+
export const SLACK_HINT: BotTexts = Object.freeze({
|
|
207
|
+
en: 'Paste the URL below as the Request URL under Event Subscriptions of your Slack app, subscribe to message events and add the bot to its channels.',
|
|
208
|
+
pl: 'Wklej poniższy adres jako Request URL w Event Subscriptions swojej aplikacji Slack, zasubskrybuj zdarzenia wiadomości i dodaj bota do jego kanałów.',
|
|
209
|
+
ru: 'Вставьте URL ниже как Request URL в разделе Event Subscriptions вашего приложения Slack, подпишитесь на события сообщений и добавьте бота в нужные каналы.',
|
|
210
|
+
be: 'Устаўце URL ніжэй як Request URL у раздзеле Event Subscriptions вашай праграмы Slack, падпішыцеся на падзеі паведамленняў і дадайце бота ў патрэбныя каналы.',
|
|
211
|
+
uk: 'Вставте URL нижче як Request URL у розділі Event Subscriptions вашого застосунку Slack, підпишіться на події повідомлень і додайте бота до потрібних каналів.',
|
|
212
|
+
es: 'Pega la URL de abajo como Request URL en Event Subscriptions de tu app de Slack, suscríbete a los eventos de mensajes y añade el bot a sus canales.',
|
|
213
|
+
de: 'Fügen Sie die URL unten als Request URL unter Event Subscriptions Ihrer Slack-App ein, abonnieren Sie Nachrichtenereignisse und fügen Sie den Bot seinen Kanälen hinzu.',
|
|
214
|
+
fr: 'Collez l’URL ci-dessous comme Request URL dans Event Subscriptions de votre app Slack, abonnez-vous aux événements de message et ajoutez le bot à ses canaux.',
|
|
215
|
+
})
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* The Slack descriptor — what the server verifies and acts by and what the panels draw (`platform.list`).
|
|
219
|
+
* `actions` are the calls the required credentials allow; `note` is never listed.
|
|
220
|
+
*/
|
|
221
|
+
export const SLACK_DESCRIPTOR: BotPlatformDescriptor = Object.freeze({
|
|
222
|
+
platform: SLACK_PLATFORM,
|
|
223
|
+
title: 'Slack',
|
|
224
|
+
glyph: 'hash',
|
|
225
|
+
credentials: SLACK_CREDENTIALS,
|
|
226
|
+
receive: Object.freeze([BotReceiveMode.Webhook]),
|
|
227
|
+
actions: Object.freeze([BotActionKind.Reply, BotActionKind.Send, BotActionKind.React]),
|
|
228
|
+
setup: 'manual',
|
|
229
|
+
docs: 'https://api.slack.com/apis/events-api',
|
|
230
|
+
hint: SLACK_HINT,
|
|
231
|
+
}) as BotPlatformDescriptor
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { BotErrorPlatform } from '@owlmeans/bot'
|
|
2
|
+
import { SLACK_PLATFORM } from './consts.js'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The Web API answered `ok: false` (or not at all) — `bot:platform:slack:<method>:<error>`.
|
|
6
|
+
*
|
|
7
|
+
* Declares no type name of its own: it travels as `BotErrorPlatform`, so a refusal is rebuilt (and
|
|
8
|
+
* explained) wherever this package is not loaded.
|
|
9
|
+
*/
|
|
10
|
+
export class SlackApiError extends BotErrorPlatform {
|
|
11
|
+
/** The refusal as the Web API stated it. */
|
|
12
|
+
public static override of(method: string, error: string, retryAfter?: number): SlackApiError {
|
|
13
|
+
const failure = new SlackApiError(`${method}:${error}`)
|
|
14
|
+
failure.retryAfter = retryAfter
|
|
15
|
+
return failure
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** The Web API method that was called (`chat.delete`). */
|
|
19
|
+
public method: string = ''
|
|
20
|
+
/** Slack's error code (`cant_delete_message`, `ratelimited`, `invalid_auth` …). */
|
|
21
|
+
public code: string = 'error'
|
|
22
|
+
/** Seconds to wait, when the call was rate limited. */
|
|
23
|
+
public retryAfter?: number
|
|
24
|
+
|
|
25
|
+
/** `message` is `<method>:<error>` — prefer {@link SlackApiError.of}. */
|
|
26
|
+
constructor(message: string = 'unknown:error') {
|
|
27
|
+
super(`${SLACK_PLATFORM}:${message}`)
|
|
28
|
+
this.finalizeUnmarshal()
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Method and code are read back from the detail. */
|
|
32
|
+
public override finalizeUnmarshal(): void {
|
|
33
|
+
super.finalizeUnmarshal()
|
|
34
|
+
const found = /^([^:]+):([^:]+)/.exec(this.detail)
|
|
35
|
+
this.method = found?.[1] ?? ''
|
|
36
|
+
this.code = found?.[2] ?? 'error'
|
|
37
|
+
}
|
|
38
|
+
}
|
package/src/index.ts
ADDED
package/src/mock.ts
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
import { createHash, randomBytes, randomInt } from 'node:crypto'
|
|
2
|
+
import { BotChatKind, BotUnsupportedAction, type BotSimulateInput } from '@owlmeans/bot'
|
|
3
|
+
import type { BotFetch, BotFetchInit, BotMockCall, BotNativeInbound, BotPlatformConnection } from '@owlmeans/server-bot'
|
|
4
|
+
import {
|
|
5
|
+
SLACK_MOCK_CHANNEL_ID, SLACK_MOCK_EVENT_ID_ALPHABET, SLACK_MOCK_EVENT_ID_LENGTH, SLACK_MOCK_MEMBER_ID,
|
|
6
|
+
SLACK_MOCK_OTHER_ID, SLACK_MOCK_TEAM_NAME, SLACK_MOCK_VERIFICATION_TOKEN, SLACK_SIGNATURE_HEADER, SLACK_TEXT_MAX, SLACK_TIMESTAMP_HEADER,
|
|
7
|
+
} from './consts.js'
|
|
8
|
+
import { slackSignatureHelper } from './signature.js'
|
|
9
|
+
import { slackTextHelper } from './text.js'
|
|
10
|
+
import type {
|
|
11
|
+
SlackAnswer, SlackAuthTest, SlackEnvelope, SlackMessage, SlackMock, SlackMockIdentity,
|
|
12
|
+
SlackMockState, SlackPosted,
|
|
13
|
+
} from './types.js'
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The Web API and the Events API, faked per connection and in process: the same URLs, `{ ok, error }`
|
|
17
|
+
* answers and payload shapes the real service uses, no network. `auth.test` answers a stable fake
|
|
18
|
+
* bot (or, for the connection's `userToken`, a fake admin), `chat.postMessage` answers increasing
|
|
19
|
+
* `ts`, `chat.delete` lets the bot delete its own posts and the admin token anyone's, and `inbound`
|
|
20
|
+
* builds a signed `event_callback` the plugin's `authenticate` accepts.
|
|
21
|
+
*/
|
|
22
|
+
export const makeSlackMock = (): SlackMock => {
|
|
23
|
+
const states = new Map<string, SlackMockState>()
|
|
24
|
+
|
|
25
|
+
const stateOf = (connection: string): SlackMockState => {
|
|
26
|
+
let state = states.get(connection)
|
|
27
|
+
if (state == null) {
|
|
28
|
+
state = { clock: 0, calls: [], sent: new Set(), reactions: new Set() }
|
|
29
|
+
states.set(connection, state)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
return state
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** A Slack-shaped id (`<prefix>` + 10 upper-case base-36 characters), stable for a text. */
|
|
36
|
+
const idOf = (prefix: string, text: string): string =>
|
|
37
|
+
`${prefix}${BigInt(`0x${createHash('sha256').update(text).digest('hex').slice(0, 15)}`).toString(36).toUpperCase().padStart(10, '0').slice(0, 10)}`
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* A later `ts` than any the connection handed out: `<seconds>.<microseconds>`, the microseconds
|
|
41
|
+
* below the millisecond random — a restarted or another process does not meet a stored one.
|
|
42
|
+
*/
|
|
43
|
+
const nextTs = (state: SlackMockState): string => {
|
|
44
|
+
state.clock = Math.max(Date.now() * 1000 + randomInt(1000), state.clock + 1)
|
|
45
|
+
return `${Math.floor(state.clock / 1_000_000)}.${`${state.clock % 1_000_000}`.padStart(6, '0')}`
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** A random `Ev…` event id. */
|
|
49
|
+
const eventIdOf = (): string =>
|
|
50
|
+
`Ev${Array.from(randomBytes(SLACK_MOCK_EVENT_ID_LENGTH), byte => SLACK_MOCK_EVENT_ID_ALPHABET[byte % SLACK_MOCK_EVENT_ID_ALPHABET.length]).join('')}`
|
|
51
|
+
|
|
52
|
+
/** A simulated thread id as a `ts`: one stays itself, any other text maps to a stable one. */
|
|
53
|
+
const tsOf = (value: string): string => /^\d{9,11}\.\d{6}$/.test(value)
|
|
54
|
+
? value
|
|
55
|
+
: `${1_600_000_000 + Number.parseInt(createHash('sha256').update(value).digest('hex').slice(0, 7), 16) % 100_000_000}.000000`
|
|
56
|
+
|
|
57
|
+
const identityOf = (connection: string): SlackMockIdentity => ({
|
|
58
|
+
teamId: idOf('T', `${connection}:team`),
|
|
59
|
+
teamName: SLACK_MOCK_TEAM_NAME,
|
|
60
|
+
appId: idOf('A', `${connection}:app`),
|
|
61
|
+
botId: idOf('B', `${connection}:bot`),
|
|
62
|
+
botUserId: idOf('U', `${connection}:bot-user`),
|
|
63
|
+
username: `mock_${connection.replace(/[^A-Za-z0-9]/g, '').slice(0, 24).toLowerCase() || 'bot'}_bot`,
|
|
64
|
+
adminUserId: idOf('U', `${connection}:admin`),
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
const answer = (body: SlackAnswer & Record<string, unknown>): Response =>
|
|
68
|
+
new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json; charset=utf-8' } })
|
|
69
|
+
|
|
70
|
+
const refuse = (error: string): Response => answer({ ok: false, error })
|
|
71
|
+
|
|
72
|
+
const aborted = (): Error => {
|
|
73
|
+
const error = new Error('The operation was aborted.')
|
|
74
|
+
error.name = 'AbortError'
|
|
75
|
+
return error
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const text = (value: unknown): string => typeof value === 'string' ? value : ''
|
|
79
|
+
|
|
80
|
+
const fetch = (connection: BotPlatformConnection): BotFetch => async (url: string, init?: BotFetchInit) => {
|
|
81
|
+
if (init?.signal?.aborted === true) {
|
|
82
|
+
throw aborted()
|
|
83
|
+
}
|
|
84
|
+
const method = new URL(url).pathname.split('/').pop() ?? ''
|
|
85
|
+
let params: Record<string, unknown> = {}
|
|
86
|
+
try {
|
|
87
|
+
params = init?.body != null && init.body !== '' ? JSON.parse(init.body) as Record<string, unknown> : {}
|
|
88
|
+
} catch {
|
|
89
|
+
return refuse('invalid_json')
|
|
90
|
+
}
|
|
91
|
+
const authorization = Object.entries(init?.headers ?? {}).find(([key]) => key.toLowerCase() === 'authorization')?.[1] ?? ''
|
|
92
|
+
const bearer = authorization.replace(/^Bearer\s+/i, '')
|
|
93
|
+
const userToken = connection.credentials.userToken ?? ''
|
|
94
|
+
const auth: 'bot' | 'user' | 'none' = userToken !== '' && bearer === userToken ? 'user' : bearer !== '' ? 'bot' : 'none'
|
|
95
|
+
const state = stateOf(connection.id)
|
|
96
|
+
state.calls.push({ method, params, at: new Date().toISOString(), auth })
|
|
97
|
+
const fake = identityOf(connection.id)
|
|
98
|
+
|
|
99
|
+
switch (method) {
|
|
100
|
+
case 'auth.test': {
|
|
101
|
+
const common = { ok: true, url: `https://${fake.teamId.toLowerCase()}.slack.com/`, team: fake.teamName, team_id: fake.teamId }
|
|
102
|
+
const result: SlackAuthTest = auth === 'user'
|
|
103
|
+
? { ...common, user: 'mock_admin', user_id: fake.adminUserId }
|
|
104
|
+
: { ...common, user: fake.username, user_id: fake.botUserId, bot_id: fake.botId }
|
|
105
|
+
return answer({ ...result })
|
|
106
|
+
}
|
|
107
|
+
case 'chat.postMessage': {
|
|
108
|
+
const channel = text(params.channel)
|
|
109
|
+
const body = text(params.text)
|
|
110
|
+
if (channel === '') {
|
|
111
|
+
return refuse('channel_not_found')
|
|
112
|
+
}
|
|
113
|
+
if (body.trim() === '') {
|
|
114
|
+
return refuse('no_text')
|
|
115
|
+
}
|
|
116
|
+
if (body.length > SLACK_TEXT_MAX) {
|
|
117
|
+
return refuse('msg_too_long')
|
|
118
|
+
}
|
|
119
|
+
const ts = nextTs(state)
|
|
120
|
+
state.sent.add(ts)
|
|
121
|
+
const thread = text(params.thread_ts)
|
|
122
|
+
const posted: SlackPosted = {
|
|
123
|
+
ok: true,
|
|
124
|
+
channel,
|
|
125
|
+
ts,
|
|
126
|
+
message: {
|
|
127
|
+
type: 'message', text: body, user: fake.botUserId, bot_id: fake.botId, app_id: fake.appId, team: fake.teamId,
|
|
128
|
+
ts, ...(thread !== '' ? { thread_ts: thread, parent_user_id: state.sent.has(thread) ? fake.botUserId : SLACK_MOCK_MEMBER_ID } : {}),
|
|
129
|
+
},
|
|
130
|
+
}
|
|
131
|
+
return answer({ ...posted })
|
|
132
|
+
}
|
|
133
|
+
case 'chat.delete': {
|
|
134
|
+
const channel = text(params.channel)
|
|
135
|
+
const ts = text(params.ts)
|
|
136
|
+
if (channel === '') {
|
|
137
|
+
return refuse('channel_not_found')
|
|
138
|
+
}
|
|
139
|
+
if (ts === '') {
|
|
140
|
+
return refuse('message_not_found')
|
|
141
|
+
}
|
|
142
|
+
// A bot token deletes only the bot's own posts; an admin's user token deletes anyone's.
|
|
143
|
+
if (!state.sent.has(ts) && auth !== 'user') {
|
|
144
|
+
return refuse('cant_delete_message')
|
|
145
|
+
}
|
|
146
|
+
state.sent.delete(ts)
|
|
147
|
+
return answer({ ok: true, channel, ts })
|
|
148
|
+
}
|
|
149
|
+
case 'reactions.add': {
|
|
150
|
+
const channel = text(params.channel)
|
|
151
|
+
const ts = text(params.timestamp)
|
|
152
|
+
const name = text(params.name)
|
|
153
|
+
if (channel === '') {
|
|
154
|
+
return refuse('channel_not_found')
|
|
155
|
+
}
|
|
156
|
+
if (ts === '') {
|
|
157
|
+
return refuse('bad_timestamp')
|
|
158
|
+
}
|
|
159
|
+
// A name, never `:name:` nor the Unicode character; a skin tone is `name::skin-tone-<2…6>`.
|
|
160
|
+
if (!/^[a-z0-9_+'-]+(?:::skin-tone-[2-6])?$/i.test(name)) {
|
|
161
|
+
return refuse('invalid_name')
|
|
162
|
+
}
|
|
163
|
+
const key = `${channel}:${ts}:${name}`
|
|
164
|
+
if (state.reactions.has(key)) {
|
|
165
|
+
return refuse('already_reacted')
|
|
166
|
+
}
|
|
167
|
+
state.reactions.add(key)
|
|
168
|
+
return answer({ ok: true })
|
|
169
|
+
}
|
|
170
|
+
default:
|
|
171
|
+
return refuse('unknown_method')
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** The secret the mock signs with: the connection's signing secret, else its hook secret. */
|
|
176
|
+
const secretOf = (connection: BotPlatformConnection): string => {
|
|
177
|
+
const secret = connection.credentials.signingSecret ?? ''
|
|
178
|
+
return secret !== '' ? secret : connection.hookSecret
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Bytes and headers as Slack posts them, signed now. */
|
|
182
|
+
const signed = (connection: BotPlatformConnection, body: SlackEnvelope): BotNativeInbound => {
|
|
183
|
+
const rawBody = JSON.stringify(body)
|
|
184
|
+
const timestamp = `${Math.floor(Date.now() / 1000)}`
|
|
185
|
+
|
|
186
|
+
return {
|
|
187
|
+
body,
|
|
188
|
+
rawBody,
|
|
189
|
+
headers: {
|
|
190
|
+
'content-type': 'application/json',
|
|
191
|
+
'user-agent': 'Slackbot 1.0 (+https://api.slack.com/robots)',
|
|
192
|
+
[SLACK_TIMESTAMP_HEADER]: timestamp,
|
|
193
|
+
[SLACK_SIGNATURE_HEADER]: slackSignatureHelper.sign(secretOf(connection), timestamp, rawBody),
|
|
194
|
+
},
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const inbound = (input: BotSimulateInput, connection: BotPlatformConnection): BotNativeInbound => {
|
|
199
|
+
const state = stateOf(connection.id)
|
|
200
|
+
const fake = identityOf(connection.id)
|
|
201
|
+
const botUser = connection.identity?.id ?? fake.botUserId
|
|
202
|
+
const username = connection.identity?.username ?? fake.username
|
|
203
|
+
const kind = input.chat?.kind ?? BotChatKind.Group
|
|
204
|
+
const senderId = input.sender?.id != null && /^[UW][A-Z0-9]{2,}$/.test(input.sender.id)
|
|
205
|
+
? input.sender.id
|
|
206
|
+
: input.sender?.id != null && input.sender.id !== '' ? idOf('U', input.sender.id) : SLACK_MOCK_MEMBER_ID
|
|
207
|
+
const chatId = input.chat?.id
|
|
208
|
+
const channel = kind === BotChatKind.Private
|
|
209
|
+
? chatId != null && /^D[A-Z0-9]{2,}$/.test(chatId) ? chatId : idOf('D', `${connection.id}:${chatId ?? senderId}`)
|
|
210
|
+
: chatId != null && /^[CG][A-Z0-9]{2,}$/.test(chatId) ? chatId
|
|
211
|
+
: chatId != null && chatId !== '' ? idOf('C', chatId) : SLACK_MOCK_CHANNEL_ID
|
|
212
|
+
const ts = nextTs(state)
|
|
213
|
+
const parent = input.replyTo?.id ?? input.chat?.thread
|
|
214
|
+
const thread = parent != null && parent !== '' ? tsOf(parent) : undefined
|
|
215
|
+
// The client escapes `& < >` but keeps control sequences (`<@U…>`, `<#C…>`, `<https://…>`), and
|
|
216
|
+
// a person's `@bot` reaches the API as `<@U…>`.
|
|
217
|
+
const escaped = input.text.split(/(<(?:[@#!][^<>\s]+|https?:\/\/[^<>\s]+)>)/)
|
|
218
|
+
.map((part, index) => index % 2 === 1 ? part : slackTextHelper.encode(part)).join('')
|
|
219
|
+
const body = username !== ''
|
|
220
|
+
? escaped.replace(new RegExp(`(?<![\\w<])@${username.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`, 'gi'), `<@${botUser}>`)
|
|
221
|
+
: escaped
|
|
222
|
+
const name = input.sender?.name
|
|
223
|
+
const bot = input.sender?.bot === true
|
|
224
|
+
const event: SlackMessage = {
|
|
225
|
+
type: 'message',
|
|
226
|
+
...(bot
|
|
227
|
+
? { bot_id: idOf('B', senderId), bot_profile: { id: idOf('B', senderId), name: name ?? 'Another bot', app_id: idOf('A', senderId) } }
|
|
228
|
+
: {}),
|
|
229
|
+
user: senderId,
|
|
230
|
+
text: body,
|
|
231
|
+
ts,
|
|
232
|
+
team: fake.teamId,
|
|
233
|
+
channel,
|
|
234
|
+
event_ts: ts,
|
|
235
|
+
channel_type: kind === BotChatKind.Private ? 'im' : 'channel',
|
|
236
|
+
...(thread != null
|
|
237
|
+
? { thread_ts: thread, parent_user_id: state.sent.has(thread) ? botUser : SLACK_MOCK_OTHER_ID }
|
|
238
|
+
: {}),
|
|
239
|
+
...(!bot && (name != null || input.sender?.username != null)
|
|
240
|
+
? {
|
|
241
|
+
user_profile: {
|
|
242
|
+
...(name != null ? { real_name: name, display_name: name } : {}),
|
|
243
|
+
...(input.sender?.username != null ? { name: input.sender.username } : {}),
|
|
244
|
+
},
|
|
245
|
+
}
|
|
246
|
+
: {}),
|
|
247
|
+
}
|
|
248
|
+
const envelope: SlackEnvelope = {
|
|
249
|
+
token: SLACK_MOCK_VERIFICATION_TOKEN,
|
|
250
|
+
team_id: fake.teamId,
|
|
251
|
+
api_app_id: fake.appId,
|
|
252
|
+
event,
|
|
253
|
+
type: 'event_callback',
|
|
254
|
+
event_id: eventIdOf(),
|
|
255
|
+
event_time: Math.floor(Date.now() / 1000),
|
|
256
|
+
authorizations: [{ enterprise_id: null, team_id: fake.teamId, user_id: botUser, is_bot: true, is_enterprise_install: false }],
|
|
257
|
+
is_ext_shared_channel: false,
|
|
258
|
+
event_context: `4-mock-${connection.id}`,
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
return signed(connection, envelope)
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const challenge = (connection: BotPlatformConnection, value?: string): BotNativeInbound =>
|
|
265
|
+
signed(connection, {
|
|
266
|
+
token: SLACK_MOCK_VERIFICATION_TOKEN,
|
|
267
|
+
challenge: value ?? idOf('', `${connection.id}:${Date.now()}:${Math.random()}`),
|
|
268
|
+
type: 'url_verification',
|
|
269
|
+
})
|
|
270
|
+
|
|
271
|
+
/** Slack only posts to the hook: there is no receiver to feed. */
|
|
272
|
+
const feed = (): void => {
|
|
273
|
+
throw new BotUnsupportedAction('mock-feed:slack')
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
const calls = (connection: string): BotMockCall[] => [...(states.get(connection)?.calls ?? [])]
|
|
277
|
+
|
|
278
|
+
const reset = (connection?: string): void => {
|
|
279
|
+
if (connection == null) {
|
|
280
|
+
states.clear()
|
|
281
|
+
return
|
|
282
|
+
}
|
|
283
|
+
states.delete(connection)
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
return { fetch, inbound, feed, calls, reset, challenge, identityOf }
|
|
287
|
+
}
|