@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,85 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { AppType, makeBasicContext, type BasicConfig, type BasicContext } from '@owlmeans/context'
3
+ import { configureLog } from '@owlmeans/log'
4
+ import type { Resource } from '@owlmeans/resource'
5
+ import {
6
+ appendBot, RES_BOT_ACTIVITY, RES_BOT_CONNECTION, RES_BOT_UPDATE, type BotActivityRecord, type BotConnectionRecord,
7
+ type BotService, type BotServiceOptions, type BotUpdateRecord,
8
+ } from '@owlmeans/server-bot'
9
+ import { makeBotMockHelper } from '@owlmeans/server-bot/mock'
10
+ import { createStaticResource } from '@owlmeans/static-resource'
11
+ import { slackBotPlatform } from '../src/plugin.js'
12
+
13
+ export const SECRET = 'bot-slack-tests-secret'
14
+
15
+ // Refusals and handler failures are expected here; `LOG_LEVEL=debug bun test` shows every line.
16
+ configureLog({ level: process.env.LOG_LEVEL ?? 'error' })
17
+
18
+ /** Native, signed payloads of the ready plugin instance — the one every `makeTestBot()` registers. */
19
+ export const botMockHelper = makeBotMockHelper([slackBotPlatform])
20
+
21
+ export interface TestBot {
22
+ /** The store key: another `makeTestBot(options, store)` reads and writes the same rows (a restart). */
23
+ store: string
24
+ context: BasicContext<BasicConfig>
25
+ service: BotService
26
+ connections: Resource<BotConnectionRecord>
27
+ updates: Resource<BotUpdateRecord>
28
+ activities: Resource<BotActivityRecord>
29
+ }
30
+
31
+ let stores = 0
32
+
33
+ /**
34
+ * One real context per test: the three resources as `@owlmeans/static-resource` stores (a fresh key
35
+ * each time, unless `store` names an earlier bot's — that bot's process restarted), then `appendBot`
36
+ * with this package's ready plugin instance (unless `options.platforms` names others). A fast
37
+ * dispatcher; the secret is a fixture.
38
+ */
39
+ export const makeTestBot = (options: BotServiceOptions = {}, store?: string): TestBot => {
40
+ const key = store ?? `bot-slack-tests-${++stores}`
41
+ const context = makeBasicContext<BasicConfig>({ ready: false, service: 'bot-slack-tests', type: AppType.Backend, services: {} })
42
+ const connections = createStaticResource<BotConnectionRecord>(RES_BOT_CONNECTION, `${key}-connection`)
43
+ const updates = createStaticResource<BotUpdateRecord>(RES_BOT_UPDATE, `${key}-update`)
44
+ const activities = createStaticResource<BotActivityRecord>(RES_BOT_ACTIVITY, `${key}-activity`)
45
+ context.registerResource(connections)
46
+ context.registerResource(updates)
47
+ context.registerResource(activities)
48
+ const service = appendBot(context, {
49
+ secret: () => SECRET, pollMs: 5, reconcileMs: 20, ...options, platforms: options.platforms ?? [slackBotPlatform],
50
+ })
51
+
52
+ return { store: key, context, service, connections, updates, activities }
53
+ }
54
+
55
+ export const scopeOf = (): string => `scope-${randomUUID()}`
56
+
57
+ /** A response the bound handler resolves or rejects — the smallest the transport needs. */
58
+ export const invoke = async (entrypoint: object, request: Record<string, unknown>): Promise<any> => {
59
+ const response: any = {
60
+ resolve: (value: unknown) => { response.value = value },
61
+ reject: (error: Error) => { response.error = error },
62
+ }
63
+ await (entrypoint as { handle: (req: unknown, res: unknown) => Promise<unknown> }).handle({
64
+ alias: 'test', headers: {}, params: {}, query: {}, body: {}, path: '/', ...request,
65
+ }, response)
66
+ if (response.error != null) {
67
+ throw response.error
68
+ }
69
+
70
+ return response.value
71
+ }
72
+
73
+ export const sleep = async (ms: number): Promise<void> => { await new Promise(resolve => setTimeout(resolve, ms)) }
74
+
75
+ /** Poll until `probe` holds (or fail after `timeoutMs`). */
76
+ export const until = async (probe: () => Promise<boolean>, timeoutMs: number = 3_000): Promise<void> => {
77
+ const deadline = Date.now() + timeoutMs
78
+ while (Date.now() < deadline) {
79
+ if (await probe()) {
80
+ return
81
+ }
82
+ await sleep(10)
83
+ }
84
+ throw new Error('condition not reached')
85
+ }
@@ -0,0 +1,64 @@
1
+ import { describe, expect, test } from 'bun:test'
2
+ import { BOT_PLATFORM_ID_PATTERN, BotActionKind, BotTransport, type BotTexts } from '@owlmeans/bot'
3
+ import { BotInboxStatus, botHandler } from '@owlmeans/server-bot'
4
+ import { SLACK_DESCRIPTOR, SLACK_PLATFORM } from '../src/consts.js'
5
+ import { makeSlackBotPlatform } from '../src/plugin.js'
6
+ import { makeTestBot, scopeOf } from './context.js'
7
+
8
+ /** The languages the bot panels ship — every text a descriptor carries is complete in each. */
9
+ const LANGUAGES = ['en', 'pl', 'ru', 'be', 'uk', 'es', 'de', 'fr']
10
+
11
+ const complete = (texts: BotTexts | undefined, what: string): void => {
12
+ for (const language of LANGUAGES) {
13
+ expect([what, language, typeof texts?.[language] === 'string' && texts[language].trim() !== '']).toEqual([what, language, true])
14
+ }
15
+ }
16
+
17
+ describe('@owlmeans/bot-slack — the descriptor', () => {
18
+ test('names a well-formed, stable platform id and is the plugin\'s own', () => {
19
+ expect(SLACK_PLATFORM).toBe('slack')
20
+ expect(new RegExp(BOT_PLATFORM_ID_PATTERN).test(SLACK_PLATFORM)).toBe(true)
21
+ const plugin = makeSlackBotPlatform()
22
+ expect([plugin.platform, plugin.descriptor]).toEqual([SLACK_PLATFORM, SLACK_DESCRIPTOR])
23
+ expect(SLACK_DESCRIPTOR.platform).toBe(SLACK_PLATFORM)
24
+ })
25
+
26
+ test('carries every label and hint in all eight panel languages', () => {
27
+ complete(SLACK_DESCRIPTOR.hint, 'hint')
28
+ for (const field of SLACK_DESCRIPTOR.credentials) {
29
+ complete(field.label, `${field.key}.label`)
30
+ complete(field.hint, `${field.key}.hint`)
31
+ }
32
+ if (SLACK_DESCRIPTOR.link != null) {
33
+ complete(SLACK_DESCRIPTOR.link.label, 'link.label')
34
+ complete(SLACK_DESCRIPTOR.link.pending, 'link.pending')
35
+ }
36
+ })
37
+
38
+ test('lists platform calls only (never note) and a glyph, docs and a receive mode', () => {
39
+ expect(SLACK_DESCRIPTOR.actions).not.toContain(BotActionKind.Note)
40
+ expect(SLACK_DESCRIPTOR.receive.length).toBeGreaterThan(0)
41
+ expect(SLACK_DESCRIPTOR.docs).toStartWith('https://')
42
+ expect(['send', 'phone', 'messages', 'hash', 'chat']).toContain(SLACK_DESCRIPTOR.glyph)
43
+ expect(Object.isFrozen(SLACK_DESCRIPTOR) && Object.isFrozen(SLACK_DESCRIPTOR.credentials)).toBe(true)
44
+ })
45
+
46
+ test('a message simulated after a restart (fresh plugin, same connection and store) is stored and dispatched', async () => {
47
+ const scope = scopeOf()
48
+ const before = makeTestBot({ platforms: [makeSlackBotPlatform()] })
49
+ const saved = await before.service.connections.save(scope, { platform: SLACK_PLATFORM, label: 'Mock', transport: BotTransport.Mock })
50
+ await before.service.connections.verify(scope, saved.id)
51
+ const first = await before.service.simulate(scope, saved.id, { text: 'before the restart' })
52
+ expect(await before.service.runtime([botHandler('seen', async () => undefined)]).dispatch()).toBe(1)
53
+
54
+ const after = makeTestBot({ platforms: [makeSlackBotPlatform()] }, before.store)
55
+ const seen: string[] = []
56
+ const runtime = after.service.runtime([botHandler('seen', async update => { seen.push(update.id) })])
57
+ const second = await after.service.simulate(scope, saved.id, { text: 'after the restart' })
58
+
59
+ expect([first.duplicate, second.duplicate, second.update === first.update]).toEqual([false, false, false])
60
+ expect(await runtime.dispatch()).toBe(1)
61
+ expect(seen).toEqual([second.update])
62
+ expect((await after.updates.get(second.update)).status).toBe(BotInboxStatus.Done)
63
+ })
64
+ })
@@ -0,0 +1,36 @@
1
+ import { describe, expect, test } from 'bun:test'
2
+ import { BotConnectionStatus, BotTransport, type BotSimulateInput } from '@owlmeans/bot'
3
+ import type { BotPlatformConnection, BotPlatformMock } from '@owlmeans/server-bot'
4
+ import { SLACK_DESCRIPTOR } from '../src/consts.js'
5
+ import { makeSlackBotPlatform } from '../src/plugin.js'
6
+
7
+ /** One stored mock connection, as each "process" of a test opens it. */
8
+ const connectionOf = (platform: string): BotPlatformConnection => ({
9
+ id: `conn-${platform}`, scope: 'org', platform, label: 'Mock', transport: BotTransport.Mock,
10
+ status: BotConnectionStatus.Connected, enabled: true, receive: SLACK_DESCRIPTOR.receive[0], credentialsSet: [],
11
+ createdAt: '2026-10-01T00:00:00.000Z', updatedAt: '2026-10-01T00:00:00.000Z', credentials: {}, hookSecret: 'hook-secret',
12
+ })
13
+
14
+ const input: BotSimulateInput = { text: 'hello' }
15
+
16
+ /** The native body of a simulated message, built by `mock`. */
17
+ const bodyOf = (mock: BotPlatformMock, platform: string): any => mock.inbound(input, connectionOf(platform)).body
18
+
19
+ /** Eight fresh mocks — eight process lifetimes of the same connection. */
20
+ const lifetimes = <T>(make: () => { mock: BotPlatformMock }, read: (mock: BotPlatformMock) => T): T[] =>
21
+ Array.from({ length: 8 }, () => read(make().mock))
22
+
23
+ describe('@owlmeans/bot-slack — mock ids: the platform\'s shapes, unique across restarts and processes', () => {
24
+ test('Slack: ts is now with a unique microsecond part, event_id is random; both differ across lifetimes', () => {
25
+ const plugin = makeSlackBotPlatform()
26
+ const one = bodyOf(plugin.mock, 'slack')
27
+ const bodies = [one, bodyOf(plugin.mock, 'slack'), ...lifetimes(makeSlackBotPlatform, mock => bodyOf(mock, 'slack'))]
28
+ const stamps = bodies.map(body => body.event.ts as string)
29
+ const events = bodies.map(body => body.event_id as string)
30
+
31
+ expect(stamps.every(ts => /^\d{10}\.\d{6}$/.test(ts))).toBe(true)
32
+ expect(Math.abs(Number(one.event.ts) - Date.now() / 1000)).toBeLessThan(5)
33
+ expect(events.every(id => /^Ev[0-9A-Z]{10}$/.test(id))).toBe(true)
34
+ expect([new Set(stamps).size, new Set(events).size]).toEqual([bodies.length, bodies.length])
35
+ })
36
+ })
@@ -0,0 +1,210 @@
1
+ import { afterEach, describe, expect, test } from 'bun:test'
2
+ import {
3
+ BotActionKind, BotChatKind, BotConnectionStatus, BotReceiveMode, BotTransport,
4
+ BotUpdateKind, botTextHelper, type BotUpdate,
5
+ } from '@owlmeans/bot'
6
+ import { BotInboxStatus } from '@owlmeans/server-bot'
7
+ import { botHandler } from '@owlmeans/server-bot'
8
+ import { botMockHelper } from './context.js'
9
+ import { makeBotPlatformRegistry } from '@owlmeans/server-bot'
10
+ import { SLACK_DESCRIPTOR, SLACK_RETRY_NUM_HEADER, SLACK_SIGNATURE_HEADER, SLACK_TIMESTAMP_HEADER } from '../src/consts.js'
11
+ import { slackBotPlatform } from '../src/plugin.js'
12
+ import { slackSignatureHelper } from '../src/signature.js'
13
+ import type { BotMockCall } from '@owlmeans/server-bot'
14
+ import type { BotRuntime } from '@owlmeans/server-bot'
15
+ import { makeTestBot, scopeOf, type TestBot } from './context.js'
16
+
17
+ const runtimes: BotRuntime[] = []
18
+ afterEach(async () => {
19
+ await Promise.all(runtimes.splice(0).map(async runtime => { await runtime.stop() }))
20
+ })
21
+
22
+ const ORIGIN = 'https://shop.example.com'
23
+
24
+ const connect = async (bot: TestBot, scope: string, credentials?: Record<string, string>) => {
25
+ const saved = await bot.service.connections.save(scope, {
26
+ platform: 'slack', label: 'Guard', transport: BotTransport.Mock, ...(credentials != null ? { credentials } : {}),
27
+ }, ORIGIN)
28
+ return await bot.service.connections.verify(scope, saved.id, ORIGIN)
29
+ }
30
+
31
+ const callsOf = (connection: string): BotMockCall[] => slackBotPlatform.mock.calls(connection)
32
+
33
+ describe('@owlmeans/bot-slack — Slack through the service (mock transport)', () => {
34
+ test('a service given the plugin lists Slack\'s descriptor', () => {
35
+ const entry = makeBotPlatformRegistry([slackBotPlatform]).platforms().find(item => item.platform === 'slack')
36
+ expect(entry).toBe(SLACK_DESCRIPTOR)
37
+ expect(makeTestBot().service.platforms()).toEqual([SLACK_DESCRIPTOR])
38
+ })
39
+
40
+ test('save → verify: the fake bot\'s identity, a webhook with manual setup naming the Request URL', async () => {
41
+ const bot = makeTestBot()
42
+ const scope = scopeOf()
43
+ const connection = await connect(bot, scope)
44
+ const fake = slackBotPlatform.mock.identityOf(connection.id)
45
+
46
+ expect(connection).toMatchObject({
47
+ status: BotConnectionStatus.Connected, receive: BotReceiveMode.Webhook,
48
+ identity: { id: fake.botUserId, username: fake.username, name: fake.teamName },
49
+ hookUrl: `${ORIGIN}/api/bot/hook/slack/${connection.id}`,
50
+ })
51
+ expect(connection.setup?.some(step => step.endsWith(`${ORIGIN}/api/bot/hook/slack/${connection.id}`))).toBe(true)
52
+ expect(callsOf(connection.id).map(call => call.method)).toEqual(['auth.test'])
53
+ })
54
+
55
+ test('a live connection without its credentials is refused at verify', async () => {
56
+ const bot = makeTestBot()
57
+ const scope = scopeOf()
58
+ const saved = await bot.service.connections.save(scope, { platform: 'slack', label: 'Live' })
59
+ await expect(bot.service.connections.verify(scope, saved.id)).rejects.toThrow('bot:credentials-rejected:missing:botToken,signingSecret')
60
+ expect((await bot.service.connections.get(scope, saved.id)).status).toBe(BotConnectionStatus.Failed)
61
+ })
62
+
63
+ test('simulate → inbox → runtime: a handler replies in the thread and reacts; activity is recorded as mock', async () => {
64
+ const bot = makeTestBot()
65
+ const scope = scopeOf()
66
+ const connection = await connect(bot, scope)
67
+ const fake = slackBotPlatform.mock.identityOf(connection.id)
68
+ // The application's own keyword group with its warning, matched by the handler.
69
+ const spam = { id: 'group-spam', keywords: ['casino'], warning: 'No casino links, please.' }
70
+ const seen: BotUpdate[] = []
71
+ const runtime = bot.service.runtime([botHandler('warn', async (update, actions) => {
72
+ seen.push(update)
73
+ if (botTextHelper.matched(update.message?.text ?? '', spam.keywords).length > 0) {
74
+ expect((await actions.reply(update, spam.warning, { ref: spam.id })).ok).toBe(true)
75
+ expect((await actions.react(update, ':no_entry_sign:', { ref: spam.id })).ok).toBe(true)
76
+ }
77
+ expect(actions.supports(BotActionKind.Mute)).toBe(false)
78
+ })])
79
+ runtimes.push(runtime)
80
+
81
+ const { update } = await bot.service.simulate(scope, connection.id, {
82
+ text: `@${fake.username} Best CASINO in town`, sender: { id: 'spammer', name: 'Spammer' },
83
+ })
84
+ expect(await runtime.dispatch()).toBe(1)
85
+
86
+ const [message] = seen
87
+ expect(message).toMatchObject({
88
+ id: update, kind: BotUpdateKind.Message, addressed: true,
89
+ chat: { kind: BotChatKind.Group, space: fake.teamId }, sender: { name: 'Spammer', bot: false },
90
+ })
91
+ expect(message.message?.text).toEndWith('Best CASINO in town')
92
+ expect((await bot.updates.get(update)).status).toBe(BotInboxStatus.Done)
93
+
94
+ const calls = callsOf(connection.id)
95
+ expect(calls.find(call => call.method === 'chat.postMessage')?.params).toEqual({
96
+ channel: message.chat.id, text: 'No casino links, please.', thread_ts: message.message!.ref.id,
97
+ })
98
+ expect(calls.find(call => call.method === 'reactions.add')?.params).toEqual({
99
+ channel: message.chat.id, timestamp: message.message!.ref.id, name: 'no_entry_sign',
100
+ })
101
+ const activity = await bot.service.activity.list(scope)
102
+ expect(activity.map(entry => [entry.action, entry.ok, entry.transport, entry.ref, entry.update])).toEqual([
103
+ [BotActionKind.React, true, BotTransport.Mock, spam.id, update],
104
+ [BotActionKind.Reply, true, BotTransport.Mock, spam.id, update],
105
+ ])
106
+ })
107
+
108
+ test('a direct message is private and addressed; a thread reply under the bot\'s post is addressed', async () => {
109
+ const bot = makeTestBot()
110
+ const scope = scopeOf()
111
+ const connection = await connect(bot, scope)
112
+ const actions = await bot.service.actions({ scope, connection: connection.id })
113
+ const posted = await actions.send('C0MOCK00001', 'Welcome!')
114
+ expect(posted.ok).toBe(true)
115
+
116
+ const direct = await bot.service.simulate(scope, connection.id, { text: 'hello', chat: { kind: BotChatKind.Private } })
117
+ const reply = await bot.service.simulate(scope, connection.id, { text: 'thanks', replyTo: { id: posted.message!.id } })
118
+ const [first, second] = [(await bot.updates.get(direct.update)).update, (await bot.updates.get(reply.update)).update]
119
+ expect([first.chat.kind, first.addressed, first.chat.id.startsWith('D')]).toEqual([BotChatKind.Private, true, true])
120
+ expect([second.addressed, second.chat.thread, second.message?.replyTo?.id]).toEqual([true, posted.message!.id, posted.message!.id])
121
+ })
122
+
123
+ test('delete: refused without the admin userToken, done with it through the user token', async () => {
124
+ const bot = makeTestBot()
125
+ const scope = scopeOf()
126
+ const plain = await connect(bot, scope)
127
+ const runtimeUpdates: BotUpdate[] = []
128
+ const runtime = bot.service.runtime([botHandler('collect', async update => { runtimeUpdates.push(update) })])
129
+ runtimes.push(runtime)
130
+
131
+ await bot.service.simulate(scope, plain.id, { text: 'casino' })
132
+ await runtime.dispatch()
133
+ const withoutToken = await bot.service.actions(runtimeUpdates[0])
134
+ expect(withoutToken.supports(BotActionKind.Delete)).toBe(false)
135
+ expect(await withoutToken.delete(runtimeUpdates[0])).toEqual({ ok: false, error: 'Slack can delete messages only with the userToken credential.', code: 'bot:unsupported-action:delete' })
136
+ expect(callsOf(plain.id).some(call => call.method === 'chat.delete')).toBe(false)
137
+
138
+ const admin = await connect(bot, scope, { userToken: 'xoxp-mock-admin' })
139
+ expect(admin.credentialsSet).toEqual(['userToken'])
140
+ expect(callsOf(admin.id).map(call => [call.method, call.auth])).toEqual([['auth.test', 'none'], ['auth.test', 'user']])
141
+ await bot.service.simulate(scope, admin.id, { text: 'casino again' })
142
+ await runtime.dispatch()
143
+ const update = runtimeUpdates[1]
144
+ const withToken = await bot.service.actions(update)
145
+ expect(withToken.supports(BotActionKind.Delete)).toBe(true)
146
+ expect(await withToken.delete(update)).toEqual({ ok: true })
147
+ expect(callsOf(admin.id).find(call => call.method === 'chat.delete')).toMatchObject({
148
+ auth: 'user', params: { channel: update.chat.id, ts: update.message!.ref.id },
149
+ })
150
+ const [deleted] = await bot.service.activity.list(scope, { connection: admin.id })
151
+ expect([deleted.action, deleted.ok, deleted.transport]).toEqual([BotActionKind.Delete, true, BotTransport.Mock])
152
+ })
153
+
154
+ test('the hook path: a signed request is stored once — a retry and the app_mention twin are the same row', async () => {
155
+ const bot = makeTestBot()
156
+ const scope = scopeOf()
157
+ const connection = await connect(bot, scope)
158
+ const record = await bot.connections.get(connection.id)
159
+ const fake = slackBotPlatform.mock.identityOf(connection.id)
160
+
161
+ const inbound = botMockHelper.inbound('slack', { text: `<@${fake.botUserId}> help` }, record)
162
+ const request = { method: 'POST', headers: inbound.headers, body: inbound.body, rawBody: inbound.rawBody }
163
+ const first = await bot.service.receive('slack', connection.id, request)
164
+ const retry = await bot.service.receive('slack', connection.id, {
165
+ ...request, headers: { ...request.headers, [SLACK_RETRY_NUM_HEADER]: '1' },
166
+ })
167
+
168
+ const native = inbound.body as { event: { channel: string, ts: string, user: string, text: string } }
169
+ const mention = { ...(inbound.body as object), event_id: 'Ev-mention', event: {
170
+ type: 'app_mention', user: native.event.user, text: native.event.text, ts: native.event.ts,
171
+ channel: native.event.channel, event_ts: native.event.ts,
172
+ } }
173
+ const twinRaw = JSON.stringify(mention)
174
+ const timestamp = `${Math.floor(Date.now() / 1000)}`
175
+ const mentioned = await bot.service.receive('slack', connection.id, {
176
+ method: 'POST', body: mention, rawBody: twinRaw,
177
+ headers: {
178
+ 'content-type': 'application/json',
179
+ [SLACK_TIMESTAMP_HEADER]: timestamp,
180
+ [SLACK_SIGNATURE_HEADER]: slackSignatureHelper.sign(record.hookSecret, timestamp, twinRaw),
181
+ },
182
+ })
183
+
184
+ expect(first.updates.length).toBe(1)
185
+ expect([retry.updates, mentioned.updates]).toEqual([first.updates, first.updates])
186
+ expect((await bot.updates.list({ connection: connection.id })).items.length).toBe(1)
187
+
188
+ const forged = { ...request, headers: { ...request.headers, 'x-slack-signature': 'v0=00' } }
189
+ await expect(bot.service.receive('slack', connection.id, forged)).rejects.toThrow('bot:signature-rejected:signature')
190
+ })
191
+
192
+ test('url_verification through the hook answers the challenge and stores nothing', async () => {
193
+ const bot = makeTestBot()
194
+ const scope = scopeOf()
195
+ const connection = await connect(bot, scope, { signingSecret: 'mock-signing-secret' })
196
+ const record = await bot.connections.get(connection.id)
197
+ const opened = { ...connection, credentials: { signingSecret: 'mock-signing-secret' }, hookSecret: record.hookSecret }
198
+ const handshake = slackBotPlatform.mock.challenge(opened, 'challenge-123')
199
+
200
+ const answer = await bot.service.receive('slack', connection.id, {
201
+ method: 'POST', headers: handshake.headers, body: handshake.body, rawBody: handshake.rawBody,
202
+ })
203
+ expect(answer).toEqual({ reply: { challenge: 'challenge-123' }, updates: [] })
204
+ expect((await bot.updates.list({ connection: connection.id })).items).toEqual([])
205
+
206
+ // A simulated message skips the hook (and its handshake): straight to normalize and the inbox.
207
+ const { update } = await bot.service.simulate(scope, connection.id, { text: 'hi' })
208
+ expect((await bot.updates.get(update)).update.message?.text).toBe('hi')
209
+ })
210
+ })