@owlmeans/bot-slack 0.0.0-stage → 0.2.0-alpha.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.
Files changed (66) hide show
  1. package/README.md +74 -2
  2. package/agent-meta/manifest.json +16 -0
  3. package/agent-meta/skills/bot-slack/SKILL.md +117 -0
  4. package/build/api.d.ts +7 -0
  5. package/build/api.d.ts.map +1 -0
  6. package/build/api.js +65 -0
  7. package/build/api.js.map +1 -0
  8. package/build/append.d.ts +9 -0
  9. package/build/append.d.ts.map +1 -0
  10. package/build/append.js +13 -0
  11. package/build/append.js.map +1 -0
  12. package/build/consts.d.ts +70 -0
  13. package/build/consts.d.ts.map +1 -0
  14. package/build/consts.js +205 -0
  15. package/build/consts.js.map +1 -0
  16. package/build/errors.d.ts +22 -0
  17. package/build/errors.d.ts.map +1 -0
  18. package/build/errors.js +35 -0
  19. package/build/errors.js.map +1 -0
  20. package/build/index.d.ts +8 -0
  21. package/build/index.d.ts.map +1 -0
  22. package/build/index.js +7 -0
  23. package/build/index.js.map +1 -0
  24. package/build/mock.d.ts +10 -0
  25. package/build/mock.d.ts.map +1 -0
  26. package/build/mock.js +253 -0
  27. package/build/mock.js.map +1 -0
  28. package/build/normalize.d.ts +4 -0
  29. package/build/normalize.d.ts.map +1 -0
  30. package/build/normalize.js +131 -0
  31. package/build/normalize.js.map +1 -0
  32. package/build/plugin.d.ts +11 -0
  33. package/build/plugin.d.ts.map +1 -0
  34. package/build/plugin.js +165 -0
  35. package/build/plugin.js.map +1 -0
  36. package/build/signature.d.ts +8 -0
  37. package/build/signature.d.ts.map +1 -0
  38. package/build/signature.js +25 -0
  39. package/build/signature.js.map +1 -0
  40. package/build/text.d.ts +9 -0
  41. package/build/text.d.ts.map +1 -0
  42. package/build/text.js +12 -0
  43. package/build/text.js.map +1 -0
  44. package/build/types.d.ts +185 -0
  45. package/build/types.d.ts.map +1 -0
  46. package/build/types.js +2 -0
  47. package/build/types.js.map +1 -0
  48. package/package.json +56 -4
  49. package/src/api.ts +70 -0
  50. package/src/append.ts +18 -0
  51. package/src/consts.ts +231 -0
  52. package/src/errors.ts +38 -0
  53. package/src/index.ts +7 -0
  54. package/src/mock.ts +287 -0
  55. package/src/normalize.ts +157 -0
  56. package/src/plugin.ts +191 -0
  57. package/src/signature.ts +33 -0
  58. package/src/text.ts +16 -0
  59. package/src/types.ts +207 -0
  60. package/tests/context.ts +85 -0
  61. package/tests/descriptor.spec.ts +64 -0
  62. package/tests/mock-ids.spec.ts +36 -0
  63. package/tests/slack-runtime.spec.ts +210 -0
  64. package/tests/slack.spec.ts +420 -0
  65. package/tests/tsconfig.json +12 -0
  66. package/tsconfig.json +16 -0
@@ -0,0 +1,420 @@
1
+ import { describe, expect, test } from 'bun:test'
2
+ import {
3
+ BotActionKind, BotChatKind, BotConnectionStatus, BotReceiveMode, BotTransport, BotUpdateKind,
4
+ type BotConnection,
5
+ } from '@owlmeans/bot'
6
+ import { SLACK_SIGNATURE_HEADER, SLACK_TIMESTAMP_HEADER } from '../src/consts.js'
7
+ import { SlackApiError } from '../src/errors.js'
8
+ import { makeSlackBotPlatform, slackBotPlatform } from '../src/plugin.js'
9
+ import { slackSignatureHelper } from '../src/signature.js'
10
+ import type { BotFetch, BotPlatformConnection, BotPlatformSession } from '@owlmeans/server-bot'
11
+
12
+ const BOT = 'U0BOT00001'
13
+ const APP = 'A0APP00001'
14
+ const TEAM = 'T0TEAM0001'
15
+ const SECRET = '8f742231b10e8888abcd99yyyzzz85a5'
16
+
17
+ /** The bot as `auth.test` answered it. */
18
+ const connection: BotConnection = {
19
+ id: 'slack-1', scope: 'org', platform: 'slack', label: 'Guard', transport: BotTransport.Live,
20
+ status: BotConnectionStatus.Connected, enabled: true, receive: BotReceiveMode.Webhook,
21
+ identity: { id: BOT, username: 'guard', name: 'Owl lovers' }, credentialsSet: ['botToken', 'signingSecret'],
22
+ createdAt: '2026-10-01T00:00:00.000Z', updatedAt: '2026-10-01T00:00:00.000Z',
23
+ }
24
+ const plugin = slackBotPlatform
25
+
26
+ /** An Events API `event_callback` around one event (https://docs.slack.dev/apis/events-api/). */
27
+ const envelope = (event: Record<string, unknown>, eventId: string = 'Ev0001') => ({
28
+ token: 'legacy', team_id: TEAM, api_app_id: APP, event, type: 'event_callback', event_id: eventId,
29
+ event_time: 1761480000,
30
+ authorizations: [{ enterprise_id: null, team_id: TEAM, user_id: BOT, is_bot: true, is_enterprise_install: false }],
31
+ })
32
+
33
+ const message = (fields: Record<string, unknown>) => ({
34
+ type: 'message', channel: 'C0GENERAL1', channel_type: 'channel', user: 'U0ANN00001', team: TEAM,
35
+ text: 'Free money at the casino', ts: '1761480000.000100', event_ts: '1761480000.000100', ...fields,
36
+ })
37
+
38
+ const one = (payload: unknown) => {
39
+ const updates = plugin.normalize(payload, connection)
40
+ expect(updates.length).toBe(1)
41
+ return updates[0]
42
+ }
43
+
44
+ describe('@owlmeans/bot-slack — Slack normalization (Events API shapes)', () => {
45
+ test('a channel message', () => {
46
+ const { platformId, update } = one(envelope(message({})))
47
+
48
+ expect(platformId).toBe('C0GENERAL1:1761480000.000100')
49
+ expect(update).toMatchObject({
50
+ kind: BotUpdateKind.Message,
51
+ chat: { id: 'C0GENERAL1', kind: BotChatKind.Group, space: TEAM },
52
+ sender: { id: 'U0ANN00001', bot: false },
53
+ message: {
54
+ ref: { chat: 'C0GENERAL1', id: '1761480000.000100', space: TEAM },
55
+ text: 'Free money at the casino',
56
+ date: '2025-10-26T12:00:00.000Z',
57
+ },
58
+ addressed: false,
59
+ })
60
+ expect([update.chat.thread, update.message?.replyTo, update.command]).toEqual([undefined, undefined, undefined])
61
+ })
62
+
63
+ test('a thread reply carries its thread and the parent; a reply under the bot\'s post addresses it', () => {
64
+ const reply = one(envelope(message({
65
+ ts: '1761480100.000200', thread_ts: '1761480000.000100', parent_user_id: 'U0BOB00001', text: 'me too',
66
+ }))).update
67
+ expect([reply.chat.thread, reply.message?.ref.thread, reply.addressed]).toEqual(['1761480000.000100', '1761480000.000100', false])
68
+ expect(reply.message?.replyTo).toEqual({
69
+ chat: 'C0GENERAL1', id: '1761480000.000100', thread: '1761480000.000100', space: TEAM, sender: { id: 'U0BOB00001' },
70
+ })
71
+
72
+ const underBot = one(envelope(message({ ts: '1761480200.000300', thread_ts: '1761480000.000100', parent_user_id: BOT, text: 'why?' }))).update
73
+ expect(underBot.addressed).toBe(true)
74
+ expect(underBot.message?.replyTo?.sender).toEqual({ id: BOT, bot: true })
75
+
76
+ // The parent itself (thread_ts === ts) is no reply.
77
+ const parent = one(envelope(message({ thread_ts: '1761480000.000100' }))).update
78
+ expect([parent.chat.thread, parent.message?.replyTo]).toEqual(['1761480000.000100', undefined])
79
+ })
80
+
81
+ test('a direct message is private and addressed; a private channel and a group DM are groups', () => {
82
+ const direct = one(envelope(message({ channel: 'D0DIRECT01', channel_type: 'im', text: 'hi' }))).update
83
+ expect([direct.chat.kind, direct.addressed]).toEqual([BotChatKind.Private, true])
84
+ expect(one(envelope(message({ channel: 'G0PRIVATE1', channel_type: 'group' }))).update.chat.kind).toBe(BotChatKind.Group)
85
+ expect(one(envelope(message({ channel: 'G0MPIM0001', channel_type: 'mpim' }))).update.chat.kind).toBe(BotChatKind.Group)
86
+ })
87
+
88
+ test('app_mention is addressed and keyed like its message event — the pair stores once', () => {
89
+ const text = `<@${BOT}> is this allowed?`
90
+ const mention = one(envelope({
91
+ type: 'app_mention', user: 'U0ANN00001', text, ts: '1761480300.000400', channel: 'C0GENERAL1', event_ts: '1761480300.000400',
92
+ }, 'Ev0002'))
93
+ const twin = one(envelope(message({ text, ts: '1761480300.000400' }), 'Ev0003'))
94
+
95
+ expect([mention.update.kind, mention.update.addressed, mention.update.chat.kind]).toEqual([BotUpdateKind.Message, true, BotChatKind.Group])
96
+ expect([twin.update.addressed, twin.platformId]).toEqual([true, mention.platformId])
97
+ // The legacy `<@U…|name>` form addresses too; another user's mention does not.
98
+ expect(one(envelope(message({ text: `hey <@${BOT}|guard>` }))).update.addressed).toBe(true)
99
+ expect(one(envelope(message({ text: 'hey <@U0OTHER001>' }))).update.addressed).toBe(false)
100
+ })
101
+
102
+ test('escaped text is decoded for people and handlers; the mention is read from the escaped form', () => {
103
+ const update = one(envelope(message({ text: `<@${BOT}> AT&amp;T says &lt;b&gt; &amp;lt;` }))).update
104
+ expect([update.message?.text, update.addressed]).toEqual([`<@${BOT}> AT&T says <b> &lt;`, true])
105
+ // A decoded `<@BOT>` that a person typed literally is no mention.
106
+ expect(one(envelope(message({ text: `&lt;@${BOT}&gt;` }))).update.addressed).toBe(false)
107
+ })
108
+
109
+ test('a /command in the text is a command', () => {
110
+ const command = one(envelope(message({ text: '/report spam above' }))).update
111
+ expect([command.kind, command.command]).toEqual([BotUpdateKind.Command, { name: 'report', args: 'spam above' }])
112
+ })
113
+
114
+ test('an edit with new text is `edited`, keyed by the edit; metadata-only changes are ignored', () => {
115
+ const edited = one(envelope({
116
+ type: 'message', subtype: 'message_changed', hidden: true, channel: 'C0GENERAL1', channel_type: 'channel',
117
+ ts: '1761480500.000600', event_ts: '1761480500.000600',
118
+ message: {
119
+ type: 'message', user: 'U0ANN00001', text: 'now with casino', ts: '1761480000.000100',
120
+ edited: { user: 'U0ANN00001', ts: '1761480500.000000' },
121
+ },
122
+ previous_message: { type: 'message', user: 'U0ANN00001', text: 'hello', ts: '1761480000.000100' },
123
+ }))
124
+ expect(edited.platformId).toBe('C0GENERAL1:1761480000.000100:edited:1761480500.000000')
125
+ expect(edited.update).toMatchObject({
126
+ kind: BotUpdateKind.Edited,
127
+ message: { ref: { id: '1761480000.000100' }, text: 'now with casino', date: '2025-10-26T12:08:20.000Z' },
128
+ sender: { id: 'U0ANN00001' },
129
+ })
130
+
131
+ expect(plugin.normalize(envelope({
132
+ type: 'message', subtype: 'message_changed', channel: 'C0GENERAL1', ts: '1761480600.000700',
133
+ message: { type: 'message', user: 'U0ANN00001', text: 'hello', ts: '1761480000.000100', attachments: [{}] },
134
+ previous_message: { type: 'message', user: 'U0ANN00001', text: 'hello', ts: '1761480000.000100' },
135
+ }), connection)).toEqual([])
136
+ })
137
+
138
+ test('system subtypes, bot_message, the bot\'s own posts and other payloads normalize to nothing', () => {
139
+ for (const subtype of ['bot_message', 'message_deleted', 'channel_join', 'channel_topic']) {
140
+ expect(plugin.normalize(envelope(message({ subtype })), connection)).toEqual([])
141
+ }
142
+ expect(plugin.normalize(envelope(message({ user: BOT, bot_id: 'B0BOT00001' })), connection)).toEqual([])
143
+ expect(plugin.normalize(envelope(message({ user: 'U0OTHERBOT', bot_id: 'B0BOT00001', app_id: APP })), connection)).toEqual([])
144
+ expect(plugin.normalize({ token: 'x', challenge: 'c', type: 'url_verification' }, connection)).toEqual([])
145
+ expect(plugin.normalize({ type: 'app_rate_limited', minute_rate_limited: 1 }, connection)).toEqual([])
146
+ expect(plugin.normalize(envelope({ type: 'reaction_added', user: 'U1' }), connection)).toEqual([])
147
+ expect(plugin.normalize(null, connection)).toEqual([])
148
+
149
+ // Another app's bot is a member like any other — flagged as a bot.
150
+ const other = one(envelope(message({ user: 'U0OTHERBOT', bot_id: 'B0OTHER001', app_id: 'A0OTHER001', bot_profile: { name: 'Feeds' } }))).update
151
+ expect(other.sender).toEqual({ id: 'U0OTHERBOT', name: 'Feeds', bot: true })
152
+ })
153
+
154
+ test('the bot\'s own posts are recognized from the installation before verification', () => {
155
+ const unverified: BotConnection = { ...connection, identity: undefined }
156
+ expect(plugin.normalize(envelope(message({ user: BOT })), unverified)).toEqual([])
157
+ expect(plugin.normalize(envelope(message({ text: `<@${BOT}> hi` })), unverified)[0].update.addressed).toBe(true)
158
+ })
159
+ })
160
+
161
+ describe('@owlmeans/bot-slack — Slack request signing', () => {
162
+ const platformConnection: BotPlatformConnection = {
163
+ ...connection, credentials: { botToken: 'xoxb-1', signingSecret: SECRET }, hookSecret: 'hook-secret-1',
164
+ }
165
+ const now = (): string => `${Math.floor(Date.now() / 1000)}`
166
+ const signedRequest = (rawBody: string, opts: { secret?: string, timestamp?: string, method?: string } = {}) => {
167
+ const timestamp = opts.timestamp ?? now()
168
+ return {
169
+ method: opts.method ?? 'POST',
170
+ headers: {
171
+ 'X-Slack-Request-Timestamp': timestamp,
172
+ 'X-Slack-Signature': slackSignatureHelper.sign(opts.secret ?? SECRET, timestamp, rawBody),
173
+ },
174
+ body: JSON.parse(rawBody),
175
+ rawBody,
176
+ }
177
+ }
178
+ const raw = JSON.stringify(envelope(message({})))
179
+
180
+ test('the documented example signs to the documented signature', () => {
181
+ // https://docs.slack.dev/authentication/verifying-requests-from-slack — the worked example.
182
+ const body = 'token=xyzz0WbapA4vBCDEFasx0q6G&team_id=T1DC2JH3J&team_domain=testteamnow&channel_id=G8PSS9T3V&channel_name=foobar&user_id=U2CERLKJA&user_name=roadrunner&command=%2Fwebhook-collect&text=&response_url=https%3A%2F%2Fhooks.slack.com%2Fcommands%2FT1DC2JH3J%2F397700885554%2F96rGlfmibIGlgcZRskXaIFfN&trigger_id=398738663015.47445629121.803a0bc887a14d10d2c447fce8b6703c'
183
+ expect(slackSignatureHelper.sign('8f742231b10e8888abcd99yyyzzz85a5', '1531420618', body))
184
+ .toBe('v0=a2114d57b48eac39b9ad189dd8316235a7b4a8d21a10bd27519666489c69b503')
185
+ })
186
+
187
+ test('a fresh signature over the raw body is accepted, header names in any case', () => {
188
+ expect(plugin.authenticate(signedRequest(raw), platformConnection)).toEqual({ result: 'ok' })
189
+ const lower = signedRequest(raw)
190
+ const headers = { [SLACK_TIMESTAMP_HEADER]: lower.headers['X-Slack-Request-Timestamp'], [SLACK_SIGNATURE_HEADER]: lower.headers['X-Slack-Signature'] }
191
+ expect(plugin.authenticate({ ...lower, headers }, platformConnection)).toEqual({ result: 'ok' })
192
+ })
193
+
194
+ test('another secret, a tampered body, a stale or future timestamp, a GET and no headers are rejected', () => {
195
+ const reject = (reason: string) => ({ result: 'reject' as const, reason })
196
+ expect(plugin.authenticate(signedRequest(raw, { secret: 'another-secret' }), platformConnection)).toEqual(reject('signature'))
197
+ const tampered = { ...signedRequest(raw), rawBody: raw.replace('casino', 'CASINO') }
198
+ expect(plugin.authenticate(tampered, platformConnection)).toEqual(reject('signature'))
199
+ const stale = `${Math.floor(Date.now() / 1000) - 301}`
200
+ expect(plugin.authenticate(signedRequest(raw, { timestamp: stale }), platformConnection)).toEqual(reject('stale-timestamp'))
201
+ const future = `${Math.floor(Date.now() / 1000) + 301}`
202
+ expect(plugin.authenticate(signedRequest(raw, { timestamp: future }), platformConnection)).toEqual(reject('stale-timestamp'))
203
+ expect(plugin.authenticate(signedRequest(raw, { method: 'GET' }), platformConnection)).toEqual(reject('method'))
204
+ expect(plugin.authenticate({ method: 'POST', headers: {}, rawBody: raw }, platformConnection)).toEqual(reject('stale-timestamp'))
205
+ })
206
+
207
+ test('a live connection never falls back to the hook secret; a mock one accepts it', () => {
208
+ const live: BotPlatformConnection = { ...platformConnection, credentials: { botToken: 'xoxb-1' } }
209
+ expect(plugin.authenticate(signedRequest(raw, { secret: live.hookSecret }), live))
210
+ .toEqual({ result: 'reject', reason: 'no-signing-secret' })
211
+ const mock: BotPlatformConnection = { ...live, transport: BotTransport.Mock }
212
+ expect(plugin.authenticate(signedRequest(raw, { secret: mock.hookSecret }), mock)).toEqual({ result: 'ok' })
213
+ })
214
+
215
+ test('url_verification is answered with its challenge only when signed', () => {
216
+ const handshake = JSON.stringify({ token: 'legacy', challenge: '3eZbrw1aBm2rZgRNFdxV2595E9CY3gmdALWMmHkvFXO7tYXAYM8P', type: 'url_verification' })
217
+ expect(plugin.authenticate(signedRequest(handshake), platformConnection)).toEqual({
218
+ result: 'challenge', reply: { challenge: '3eZbrw1aBm2rZgRNFdxV2595E9CY3gmdALWMmHkvFXO7tYXAYM8P' },
219
+ })
220
+ expect(plugin.authenticate(signedRequest(handshake, { secret: 'forged' }), platformConnection))
221
+ .toEqual({ result: 'reject', reason: 'signature' })
222
+ })
223
+ })
224
+
225
+ describe('@owlmeans/bot-slack — Slack Web API client', () => {
226
+ const credentials = { botToken: 'xoxb-bot', signingSecret: SECRET }
227
+ const sessionOf = (fetch: BotFetch, extra: Record<string, string> = {}): BotPlatformSession => ({
228
+ connection: { ...connection, credentials: { ...credentials, ...extra }, hookSecret: 'h' },
229
+ transport: BotTransport.Live,
230
+ fetch,
231
+ })
232
+ const json = (body: unknown, init: ResponseInit = {}): Response => new Response(JSON.stringify(body), init)
233
+ const bot = { ok: true, url: 'https://owls.slack.com/', team: 'Owl lovers', user: 'guard', team_id: TEAM, user_id: BOT, bot_id: 'B0BOT00001' }
234
+
235
+ test('calls go to `<base>/<method>` with a bearer token and JSON — the base is overridable', async () => {
236
+ const seen: { url: string, headers?: Record<string, string>, body?: string }[] = []
237
+ const proxied = makeSlackBotPlatform({ base: 'https://slack.example.org/api/' })
238
+ const identity = await proxied.verify(sessionOf(async (url, init) => {
239
+ seen.push({ url, headers: init?.headers, body: init?.body })
240
+ return json(bot)
241
+ }))
242
+
243
+ expect(seen).toEqual([{
244
+ url: 'https://slack.example.org/api/auth.test',
245
+ headers: { 'content-type': 'application/json; charset=utf-8', authorization: 'Bearer xoxb-bot' },
246
+ body: '{}',
247
+ }])
248
+ expect(identity).toEqual({ id: BOT, username: 'guard', name: 'Owl lovers' })
249
+ })
250
+
251
+ test('verify: a refused token, a user token as the bot\'s, a foreign admin token are credential refusals', async () => {
252
+ await expect(plugin.verify(sessionOf(async () => json({ ok: false, error: 'invalid_auth' }))))
253
+ .rejects.toThrow('bot:credentials-rejected:slack:invalid_auth')
254
+ await expect(plugin.verify(sessionOf(async () => json({ ...bot, bot_id: undefined }))))
255
+ .rejects.toThrow('bot:credentials-rejected:slack:botToken-not-a-bot-token')
256
+ await expect(plugin.verify({ ...sessionOf(async () => json(bot)), connection: { ...sessionOf(async () => json(bot)).connection, credentials: {} } }))
257
+ .rejects.toThrow('bot:credentials-rejected:missing:botToken,signingSecret')
258
+
259
+ const admin = (answer: object): BotFetch => async (_url, init) =>
260
+ init?.headers?.authorization === 'Bearer xoxp-admin' ? json(answer) : json(bot)
261
+ await expect(plugin.verify(sessionOf(admin({ ok: false, error: 'token_revoked' }), { userToken: 'xoxp-admin' })))
262
+ .rejects.toThrow('bot:credentials-rejected:slack:userToken:token_revoked')
263
+ await expect(plugin.verify(sessionOf(admin(bot), { userToken: 'xoxp-admin' })))
264
+ .rejects.toThrow('bot:credentials-rejected:slack:userToken-not-a-user-token')
265
+ await expect(plugin.verify(sessionOf(admin({ ...bot, user_id: 'U0ADMIN001', bot_id: undefined, team_id: 'T0ELSEWHERE' }), { userToken: 'xoxp-admin' })))
266
+ .rejects.toThrow('bot:credentials-rejected:slack:userToken-another-workspace')
267
+ expect(await plugin.verify(sessionOf(admin({ ...bot, user: 'admin', user_id: 'U0ADMIN001', bot_id: undefined }), { userToken: 'xoxp-admin' })))
268
+ .toEqual({ id: BOT, username: 'guard', name: 'Owl lovers' })
269
+ })
270
+
271
+ test('ok:false is a SlackApiError with method and code; a fault never carries the token', async () => {
272
+ const error = await plugin.act(sessionOf(async () => json({ ok: false, error: 'not_in_channel' })), {
273
+ kind: BotActionKind.Send, chat: { id: 'C1', kind: BotChatKind.Group }, text: 'x',
274
+ }).catch(failure => failure)
275
+ expect(error).toBeInstanceOf(SlackApiError)
276
+ expect([error.message, error.method, error.code]).toEqual(['bot:platform:slack:chat.postMessage:not_in_channel', 'chat.postMessage', 'not_in_channel'])
277
+
278
+ const fault = await plugin.act(sessionOf(async () => { throw new Error('connect ECONNREFUSED xoxb-bot') }), {
279
+ kind: BotActionKind.Send, chat: { id: 'C1', kind: BotChatKind.Group }, text: 'x',
280
+ }).catch(failure => failure)
281
+ expect(fault.message).toBe('bot:platform:slack:chat.postMessage:unreachable')
282
+ })
283
+
284
+ test('a 429 is retried after its Retry-After, a bounded number of times', async () => {
285
+ let calls = 0
286
+ const flaky: BotFetch = async () => ++calls === 1
287
+ ? new Response('', { status: 429, headers: { 'retry-after': '0' } })
288
+ : json({ ok: true, channel: 'C1', ts: '1761480000.000900' })
289
+ const done = await plugin.act(sessionOf(flaky), { kind: BotActionKind.Send, chat: { id: 'C1', kind: BotChatKind.Group }, text: 'x' })
290
+ expect([calls, done.message?.id]).toEqual([2, '1761480000.000900'])
291
+
292
+ let limited = 0
293
+ const always: BotFetch = async () => { limited++; return new Response('', { status: 429, headers: { 'retry-after': '0' } }) }
294
+ const refused = await plugin.act(sessionOf(always), {
295
+ kind: BotActionKind.React, message: { chat: 'C1', id: '1.000001' }, emoji: 'eyes',
296
+ }).catch(failure => failure)
297
+ expect([limited, refused.message]).toEqual([3, 'bot:platform:slack:reactions.add:ratelimited'])
298
+
299
+ // A wait longer than the bound is not waited for.
300
+ let long = 0
301
+ const patient = makeSlackBotPlatform({ maxRetryWaitS: 5 })
302
+ const slow: BotFetch = async () => { long++; return new Response('', { status: 429, headers: { 'retry-after': '60' } }) }
303
+ const tooLong = await patient.act(sessionOf(slow), { kind: BotActionKind.React, message: { chat: 'C1', id: '1.000001' }, emoji: 'eyes' })
304
+ .catch(failure => failure)
305
+ expect([long, tooLong.retryAfter]).toEqual([1, 60])
306
+ })
307
+
308
+ test('act: reply in the thread, send, delete with the user token, react by name; mute and ban are refused', async () => {
309
+ const seen: { method: string, auth?: string, body: Record<string, unknown> }[] = []
310
+ const fetch: BotFetch = async (url, init) => {
311
+ seen.push({ method: url.split('/').pop()!, auth: init?.headers?.authorization, body: JSON.parse(init?.body ?? '{}') })
312
+ return json({ ok: true, channel: 'C1', ts: '1761480999.000001' })
313
+ }
314
+ const session = sessionOf(fetch, { userToken: 'xoxp-admin' })
315
+ const reply = await plugin.act(session, { kind: BotActionKind.Reply, to: { chat: 'C1', id: '1761480000.000100', space: TEAM }, text: 'Please keep to the rules.' })
316
+ const inThread = await plugin.act(session, { kind: BotActionKind.Reply, to: { chat: 'C1', id: '1761480100.000200', thread: '1761480000.000100' }, text: 'ok' })
317
+ await plugin.act(session, { kind: BotActionKind.Send, chat: { id: 'C1', kind: BotChatKind.Group }, text: 'Hello' })
318
+ await plugin.act(session, { kind: BotActionKind.Delete, message: { chat: 'C1', id: '1761480000.000100' } })
319
+ await plugin.act(session, { kind: BotActionKind.React, message: { chat: 'C1', id: '1761480000.000100' }, emoji: ':eyes:' })
320
+ await plugin.act(session, { kind: BotActionKind.React, message: { chat: 'C1', id: '1761480000.000100' }, emoji: '👎' })
321
+ await plugin.act(session, { kind: BotActionKind.React, message: { chat: 'C1', id: '1761480000.000100' }, emoji: '⚠️' })
322
+
323
+ expect(reply.message).toEqual({ chat: 'C1', id: '1761480999.000001', thread: '1761480000.000100', space: TEAM })
324
+ expect(inThread.message?.thread).toBe('1761480000.000100')
325
+ expect(seen).toEqual([
326
+ { method: 'chat.postMessage', auth: 'Bearer xoxb-bot', body: { channel: 'C1', text: 'Please keep to the rules.', thread_ts: '1761480000.000100' } },
327
+ { method: 'chat.postMessage', auth: 'Bearer xoxb-bot', body: { channel: 'C1', text: 'ok', thread_ts: '1761480000.000100' } },
328
+ { method: 'chat.postMessage', auth: 'Bearer xoxb-bot', body: { channel: 'C1', text: 'Hello' } },
329
+ { method: 'chat.delete', auth: 'Bearer xoxp-admin', body: { channel: 'C1', ts: '1761480000.000100' } },
330
+ { method: 'reactions.add', auth: 'Bearer xoxb-bot', body: { channel: 'C1', timestamp: '1761480000.000100', name: 'eyes' } },
331
+ { method: 'reactions.add', auth: 'Bearer xoxb-bot', body: { channel: 'C1', timestamp: '1761480000.000100', name: '-1' } },
332
+ { method: 'reactions.add', auth: 'Bearer xoxb-bot', body: { channel: 'C1', timestamp: '1761480000.000100', name: 'warning' } },
333
+ ])
334
+
335
+ seen.length = 0
336
+ await plugin.act(session, { kind: BotActionKind.Send, chat: { id: 'C1', kind: BotChatKind.Group }, text: 'a < b & <@U1>' })
337
+ expect(seen[0].body.text).toBe('a &lt; b &amp; &lt;@U1&gt;')
338
+
339
+ await expect(plugin.act(sessionOf(fetch), { kind: BotActionKind.Delete, message: { chat: 'C1', id: '1.000001' } }))
340
+ .rejects.toThrow('bot:unsupported-action:delete')
341
+ await expect(plugin.act(session, { kind: BotActionKind.Mute, chat: 'C1', user: 'U1', until: new Date() }))
342
+ .rejects.toThrow('bot:unsupported-action:mute')
343
+ await expect(plugin.act(session, { kind: BotActionKind.Ban, chat: 'C1', user: 'U1' }))
344
+ .rejects.toThrow('bot:unsupported-action:ban')
345
+ })
346
+
347
+ test('setup names the Request URL, the events and the scopes', () => {
348
+ const steps = plugin.setup!({ ...connection, hookUrl: 'https://shop.example.com/api/bot/hook/slack/slack-1', credentials: {}, hookSecret: 'h' })
349
+ expect(steps.some(step => step.endsWith('https://shop.example.com/api/bot/hook/slack/slack-1'))).toBe(true)
350
+ expect(steps.join(' ')).toContain('message.channels, message.groups, message.im, app_mention')
351
+ expect(steps.join(' ')).toContain('chat:write, channels:history, groups:history, im:history, app_mentions:read, reactions:write')
352
+ expect(plugin.setup!({ ...connection, credentials: {}, hookSecret: 'h' })[1]).toContain('public address')
353
+ })
354
+ })
355
+
356
+ describe('@owlmeans/bot-slack — Slack mock', () => {
357
+ const mockConnection = (extra: Record<string, string> = {}): BotPlatformConnection => ({
358
+ ...connection, id: `slack-mock-${crypto.randomUUID()}`, transport: BotTransport.Mock, identity: undefined,
359
+ credentials: extra, hookSecret: 'mock-hook-secret',
360
+ })
361
+ const call = async (fetch: BotFetch, method: string, body: object, token: string = ''): Promise<any> =>
362
+ await (await fetch(`https://slack.com/api/${method}`, {
363
+ method: 'POST', headers: { authorization: `Bearer ${token}` }, body: JSON.stringify(body),
364
+ })).json()
365
+
366
+ test('auth.test answers a stable fake bot — or the admin for the user token', async () => {
367
+ const conn = mockConnection({ userToken: 'xoxp-mock' })
368
+ const fetch = plugin.mock.fetch(conn)
369
+ const fake = plugin.mock.identityOf(conn.id)
370
+ expect(await call(fetch, 'auth.test', {})).toMatchObject({ ok: true, user_id: fake.botUserId, bot_id: fake.botId, team_id: fake.teamId })
371
+ const admin = await call(fetch, 'auth.test', {}, 'xoxp-mock')
372
+ expect([admin.user_id, admin.bot_id, admin.team_id]).toEqual([fake.adminUserId, undefined, fake.teamId])
373
+ })
374
+
375
+ test('chat.postMessage answers increasing ts; chat.delete and reactions.add answer like Slack', async () => {
376
+ const conn = mockConnection({ userToken: 'xoxp-mock' })
377
+ const fetch = plugin.mock.fetch(conn)
378
+ const first = await call(fetch, 'chat.postMessage', { channel: 'C1', text: 'one' })
379
+ const second = await call(fetch, 'chat.postMessage', { channel: 'C1', text: 'two', thread_ts: first.ts })
380
+ expect([first.ok, Number(second.ts) > Number(first.ts), /^\d+\.\d{6}$/.test(first.ts), second.message.thread_ts]).toEqual([true, true, true, first.ts])
381
+ expect(await call(fetch, 'chat.postMessage', { channel: 'C1', text: ' ' })).toEqual({ ok: false, error: 'no_text' })
382
+
383
+ expect(await call(fetch, 'chat.delete', { channel: 'C1', ts: first.ts })).toEqual({ ok: true, channel: 'C1', ts: first.ts })
384
+ expect(await call(fetch, 'chat.delete', { channel: 'C1', ts: '1761480000.000100' })).toEqual({ ok: false, error: 'cant_delete_message' })
385
+ expect(await call(fetch, 'chat.delete', { channel: 'C1', ts: '1761480000.000100' }, 'xoxp-mock')).toMatchObject({ ok: true })
386
+
387
+ expect(await call(fetch, 'reactions.add', { channel: 'C1', timestamp: second.ts, name: 'eyes' })).toEqual({ ok: true })
388
+ expect(await call(fetch, 'reactions.add', { channel: 'C1', timestamp: second.ts, name: 'eyes' })).toEqual({ ok: false, error: 'already_reacted' })
389
+ expect(await call(fetch, 'reactions.add', { channel: 'C1', timestamp: second.ts, name: ':eyes:' })).toEqual({ ok: false, error: 'invalid_name' })
390
+ expect(await call(fetch, 'conversations.kick', {})).toEqual({ ok: false, error: 'unknown_method' })
391
+ expect(plugin.mock.calls(conn.id).map(entry => [entry.method, entry.auth])).toEqual([
392
+ ['chat.postMessage', 'none'], ['chat.postMessage', 'none'], ['chat.postMessage', 'none'],
393
+ ['chat.delete', 'none'], ['chat.delete', 'none'],
394
+ ['chat.delete', 'user'], ['reactions.add', 'none'], ['reactions.add', 'none'], ['reactions.add', 'none'],
395
+ ['conversations.kick', 'none'],
396
+ ])
397
+ })
398
+
399
+ test('inbound is a signed event_callback the plugin accepts; the challenge too', () => {
400
+ const conn = mockConnection()
401
+ const fake = plugin.mock.identityOf(conn.id)
402
+ const inbound = plugin.mock.inbound({ text: `hey @${fake.username} & <@U0OTHER001> <b>`, sender: { id: 'ann', name: 'Ann' } }, conn)
403
+ expect(plugin.authenticate({ method: 'POST', headers: inbound.headers, body: inbound.body, rawBody: inbound.rawBody }, conn)).toEqual({ result: 'ok' })
404
+ const body = inbound.body as any
405
+ expect([body.type, body.team_id, body.event.type, body.event.channel_type, body.event.text]).toEqual([
406
+ 'event_callback', fake.teamId, 'message', 'channel', `hey <@${fake.botUserId}> &amp; <@U0OTHER001> &lt;b&gt;`,
407
+ ])
408
+
409
+ const [{ update }] = plugin.normalize(inbound.body, { ...conn, identity: { id: fake.botUserId, username: fake.username } })
410
+ expect([update.addressed, update.sender?.name, update.chat.kind, update.message?.text])
411
+ .toEqual([true, 'Ann', BotChatKind.Group, `hey <@${fake.botUserId}> & <@U0OTHER001> <b>`])
412
+
413
+ const signedWithSecret = mockConnection({ signingSecret: SECRET })
414
+ const challenge = plugin.mock.challenge(signedWithSecret, 'abc')
415
+ expect(plugin.authenticate({ method: 'POST', headers: challenge.headers, rawBody: challenge.rawBody }, { ...signedWithSecret, transport: BotTransport.Live }))
416
+ .toEqual({ result: 'challenge', reply: { challenge: 'abc' } })
417
+
418
+ expect(() => plugin.mock.feed(conn.id, body)).toThrow('bot:unsupported-action:mock-feed:slack')
419
+ })
420
+ })
@@ -0,0 +1,12 @@
1
+ {
2
+ "extends": [
3
+ "@owlmeans/dep-config/tsconfig.base.json",
4
+ "@owlmeans/dep-config/tsconfig.node.json"
5
+ ],
6
+ "compilerOptions": {
7
+ "types": ["bun"],
8
+ "rootDir": "../",
9
+ "noEmit": true
10
+ },
11
+ "include": ["./**/*", "../src/**/*"]
12
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "extends": [
3
+ "@owlmeans/dep-config/tsconfig.base.json",
4
+ "@owlmeans/dep-config/tsconfig.node.json"
5
+ ],
6
+ "compilerOptions": {
7
+ "rootDir": "./src/",
8
+ "outDir": "./build/"
9
+ },
10
+ "exclude": [
11
+ "./dist/**/*",
12
+ "./build/**/*",
13
+ "./tests/**/*",
14
+ "./*.ts"
15
+ ]
16
+ }