@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.
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,157 @@
1
+ import {
2
+ botCommandHelper, BotChatKind, BotUpdateKind, type BotChatRef, type BotConnection, type BotMessage,
3
+ type BotMessageRef, type BotSenderRef,
4
+ } from '@owlmeans/bot'
5
+ import type { BotNormalizedUpdate } from '@owlmeans/server-bot'
6
+ import { SLACK_EDIT_SUBTYPE, SLACK_MESSAGE_SUBTYPES } from './consts.js'
7
+ import { slackTextHelper } from './text.js'
8
+ import type { SlackAppMention, SlackEnvelope, SlackMessage, SlackNormalizer } from './types.js'
9
+
10
+ export const createSlackNormalizer = (): SlackNormalizer => {
11
+ /** `1761480000.000100` → its instant; now when unreadable. */
12
+ const iso = (ts: string | undefined): string => {
13
+ const seconds = Number(ts)
14
+ return new Date(Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : Date.now()).toISOString()
15
+ }
16
+
17
+ /** A DM is private whether `channel_type` says so or only its `D…` id does (`app_mention` has no type). */
18
+ const chatKindOf = (channel: string, channelType?: string): BotChatKind =>
19
+ channelType === 'im' || (channelType == null && channel.startsWith('D')) ? BotChatKind.Private : BotChatKind.Group
20
+
21
+ const escape = (text: string): string => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
22
+
23
+ /** `<@U123>` or the legacy `<@U123|name>` of the bot in the text. */
24
+ const mentions = (text: string, botUser: string | undefined): boolean =>
25
+ botUser != null && botUser !== '' && new RegExp(`<@${escape(botUser)}(?:\\|[^>]*)?>`).test(text)
26
+
27
+ const nameOf = (message: SlackMessage | SlackAppMention): string | undefined => {
28
+ const profile = 'user_profile' in message ? message.user_profile : undefined
29
+ const bot = 'bot_profile' in message ? message.bot_profile : undefined
30
+ const name = profile?.display_name || profile?.real_name || bot?.name
31
+ return name != null && name !== '' ? name : undefined
32
+ }
33
+
34
+ const senderOf = (message: SlackMessage | SlackAppMention): BotSenderRef | undefined => {
35
+ const id = message.user ?? message.bot_id
36
+ if (id == null || id === '') {
37
+ return undefined
38
+ }
39
+ const name = nameOf(message)
40
+ const username = 'user_profile' in message ? message.user_profile?.name : undefined
41
+
42
+ return {
43
+ id,
44
+ ...(name != null ? { name } : {}),
45
+ ...(username != null && username !== '' ? { username } : {}),
46
+ bot: message.bot_id != null,
47
+ }
48
+ }
49
+
50
+ const normalize = (payload: unknown, connection: BotConnection): BotNormalizedUpdate[] => {
51
+ const envelope = payload as SlackEnvelope | null
52
+ if (envelope == null || typeof envelope !== 'object' || envelope.type !== 'event_callback'
53
+ || envelope.event == null || typeof envelope.event !== 'object') {
54
+ return []
55
+ }
56
+ const team = envelope.team_id
57
+ // The bot as verification answered; the installation's own bot user when it is not verified yet.
58
+ const botUser = connection.identity?.id ?? envelope.authorizations?.find(entry => entry.is_bot === true)?.user_id
59
+
60
+ /** The bot's own post: its user, or a bot message of this very app. */
61
+ const own = (message: SlackMessage | SlackAppMention): boolean =>
62
+ (botUser != null && message.user === botUser)
63
+ || (message.bot_id != null && envelope.api_app_id != null
64
+ && (message.app_id === envelope.api_app_id
65
+ || ('bot_profile' in message && message.bot_profile?.app_id === envelope.api_app_id)))
66
+
67
+ const build = (
68
+ message: SlackMessage | SlackAppMention, channel: string, channelType: string | undefined,
69
+ opts: { edited?: string, mention?: boolean }
70
+ ): BotNormalizedUpdate[] => {
71
+ const ts = message.ts
72
+ if (ts == null || ts === '' || own(message)) {
73
+ return []
74
+ }
75
+ // Mentions are control sequences of the escaped text; people (and handlers) read the decoded one.
76
+ const escaped = message.text ?? ''
77
+ const text = slackTextHelper.decode(escaped)
78
+ const thread = message.thread_ts != null && message.thread_ts !== '' ? message.thread_ts : undefined
79
+ const kind = chatKindOf(channel, channelType)
80
+ const space = team ?? message.team
81
+ const chat: BotChatRef = {
82
+ id: channel, kind, ...(thread != null ? { thread } : {}), ...(space != null ? { space } : {}),
83
+ }
84
+ const ref: BotMessageRef = {
85
+ chat: channel, id: ts, ...(thread != null ? { thread } : {}), ...(space != null ? { space } : {}),
86
+ }
87
+ const parentUser = 'parent_user_id' in message ? message.parent_user_id : undefined
88
+ const replied = thread != null && thread !== ts
89
+ const body: BotMessage = {
90
+ ref,
91
+ text,
92
+ date: iso(opts.edited ?? ts),
93
+ ...(replied
94
+ ? {
95
+ replyTo: {
96
+ chat: channel, id: thread, thread, ...(space != null ? { space } : {}),
97
+ ...(parentUser != null ? { sender: { id: parentUser, ...(parentUser === botUser ? { bot: true } : {}) } } : {}),
98
+ },
99
+ }
100
+ : {}),
101
+ }
102
+ const command = opts.edited == null
103
+ ? botCommandHelper.parse(text, connection.identity?.username) ?? undefined
104
+ : undefined
105
+ const sender = senderOf(message)
106
+ const addressed = kind === BotChatKind.Private || opts.mention === true || mentions(escaped, botUser)
107
+ || (replied && botUser != null && parentUser === botUser)
108
+
109
+ return [{
110
+ // One message is one key: a redelivery and the `message` + `app_mention` pair of one mention
111
+ // store once; an edit is keyed by the edit.
112
+ platformId: opts.edited != null ? `${channel}:${ts}:edited:${opts.edited}` : `${channel}:${ts}`,
113
+ update: {
114
+ kind: opts.edited != null ? BotUpdateKind.Edited : command != null ? BotUpdateKind.Command : BotUpdateKind.Message,
115
+ chat,
116
+ ...(sender != null ? { sender } : {}),
117
+ message: body,
118
+ ...(command != null ? { command } : {}),
119
+ addressed,
120
+ raw: envelope,
121
+ },
122
+ }]
123
+ }
124
+
125
+ const event = envelope.event as SlackMessage | SlackAppMention
126
+ const channel = event.channel
127
+ if (channel == null || channel === '') {
128
+ return []
129
+ }
130
+ if (event.type === 'app_mention') {
131
+ return build(event, channel, undefined, { mention: true })
132
+ }
133
+ if (event.type !== 'message') {
134
+ return []
135
+ }
136
+ if (event.subtype === SLACK_EDIT_SUBTYPE) {
137
+ const current = event.message
138
+ const previous = event.previous_message
139
+ // Slack also sends `message_changed` for metadata (unfurls, language): only new text is an edit.
140
+ if (current == null || typeof current.text !== 'string'
141
+ || (current.edited == null && (previous == null || previous.text === current.text))) {
142
+ return []
143
+ }
144
+
145
+ return build(current, channel, event.channel_type, { edited: current.edited?.ts ?? event.event_ts ?? event.ts ?? '' })
146
+ }
147
+ if (event.subtype != null && !SLACK_MESSAGE_SUBTYPES.includes(event.subtype)) {
148
+ return []
149
+ }
150
+
151
+ return build(event, channel, event.channel_type, {})
152
+ }
153
+
154
+ return { normalize }
155
+ }
156
+
157
+ export const slackNormalizer = createSlackNormalizer()
package/src/plugin.ts ADDED
@@ -0,0 +1,191 @@
1
+ import {
2
+ BotActionKind, BotCredentialsRejected, BotTransport, BotUnsupportedAction,
3
+ type BotMessageRef,
4
+ } from '@owlmeans/bot'
5
+ import { botHookHelper } from '@owlmeans/server-bot'
6
+ import type {
7
+ BotAuthentication, BotPlatformAction, BotPlatformActionResult, BotPlatformConnection, BotPlatformIdentity,
8
+ BotPlatformPlugin, BotPlatformSession,
9
+ } from '@owlmeans/server-bot'
10
+ import { makeSlackApi } from './api.js'
11
+ import {
12
+ SLACK_API_BASE, SLACK_CREDENTIAL_ERRORS, SLACK_DESCRIPTOR, SLACK_EMOJI_NAMES, SLACK_PLATFORM,
13
+ SLACK_RATE_LIMIT_MAX_WAIT_S, SLACK_RATE_LIMIT_RETRIES, SLACK_SETUP_CREDENTIALS_STEP,
14
+ SLACK_SETUP_HOOK_PENDING_STEP, SLACK_SETUP_HOOK_STEP, SLACK_SETUP_TAIL_STEPS, SLACK_SIGNATURE_HEADER,
15
+ SLACK_TEXT_MAX, SLACK_TIMESTAMP_HEADER,
16
+ } from './consts.js'
17
+ import { SlackApiError } from './errors.js'
18
+ import { makeSlackMock } from './mock.js'
19
+ import { slackNormalizer } from './normalize.js'
20
+ import { slackSignatureHelper } from './signature.js'
21
+ import { slackTextHelper } from './text.js'
22
+ import type { SlackAnswer, SlackAuthTest, SlackBotPlatform, SlackBotPlatformOptions, SlackPosted } from './types.js'
23
+
24
+ /**
25
+ * The Slack plugin over the Events API and the Web API (https://docs.slack.dev/apis/): `auth.test`
26
+ * verifies, a person pastes the Request URL (manual setup), every hook request is checked against
27
+ * the signing secret, and `chat.postMessage` / `chat.delete` / `reactions.add` act. A reply goes
28
+ * into the message's thread; `delete` uses the admin `userToken`.
29
+ */
30
+ export const makeSlackBotPlatform = (opts: SlackBotPlatformOptions = {}): SlackBotPlatform => {
31
+ const base = (opts.base ?? SLACK_API_BASE).replace(/\/+$/, '')
32
+ const retry = { retries: opts.retries ?? SLACK_RATE_LIMIT_RETRIES, maxRetryWaitS: opts.maxRetryWaitS ?? SLACK_RATE_LIMIT_MAX_WAIT_S }
33
+ const mock = makeSlackMock()
34
+ const api = (session: BotPlatformSession) => makeSlackApi(session, base, retry)
35
+
36
+ /** Clipped to the text limit without splitting a surrogate pair. */
37
+ const clip = (text: string): string => {
38
+ if (text.length <= SLACK_TEXT_MAX) {
39
+ return text
40
+ }
41
+ const cut = text.slice(0, SLACK_TEXT_MAX - 1)
42
+
43
+ return `${/[\uD800-\uDBFF]$/.test(cut) ? cut.slice(0, -1) : cut}…`
44
+ }
45
+
46
+ /** `:thumbsup:` → `thumbsup`; a mapped Unicode emoji → its name; anything else as given. */
47
+ const emojiName = (emoji: string): string => {
48
+ const trimmed = emoji.trim()
49
+ const bare = trimmed.replace(/️/g, '')
50
+
51
+ return SLACK_EMOJI_NAMES[bare] ?? trimmed.replace(/^:+|:+$/g, '')
52
+ }
53
+
54
+ /** A credential refusal of `auth.test` as `BotCredentialsRejected`, anything else as it is. */
55
+ const authTest = async (session: BotPlatformSession, token: string | undefined, label: string): Promise<SlackAuthTest> => {
56
+ try {
57
+ return await api(session).call<SlackAuthTest>('auth.test', {}, token != null ? { token } : {})
58
+ } catch (error) {
59
+ if (error instanceof SlackApiError && SLACK_CREDENTIAL_ERRORS.includes(error.code)) {
60
+ throw new BotCredentialsRejected(`slack:${label}${error.code}`)
61
+ }
62
+ throw error
63
+ }
64
+ }
65
+
66
+ const verify = async (session: BotPlatformSession): Promise<BotPlatformIdentity> => {
67
+ const credentials = session.connection.credentials
68
+ if (session.transport === BotTransport.Live) {
69
+ const missing = ['botToken', 'signingSecret'].filter(key => (credentials[key] ?? '') === '')
70
+ if (missing.length > 0) {
71
+ throw new BotCredentialsRejected(`missing:${missing.join(',')}`)
72
+ }
73
+ }
74
+ const bot = await authTest(session, undefined, '')
75
+ if (bot.bot_id == null || bot.bot_id === '') {
76
+ throw new BotCredentialsRejected('slack:botToken-not-a-bot-token')
77
+ }
78
+ const userToken = credentials.userToken ?? ''
79
+ if (userToken !== '') {
80
+ const admin = await authTest(session, userToken, 'userToken:')
81
+ if (admin.bot_id != null && admin.bot_id !== '') {
82
+ throw new BotCredentialsRejected('slack:userToken-not-a-user-token')
83
+ }
84
+ if (admin.team_id !== bot.team_id) {
85
+ throw new BotCredentialsRejected('slack:userToken-another-workspace')
86
+ }
87
+ }
88
+ const id = bot.user_id ?? bot.bot_id
89
+
90
+ return { id, ...(bot.user != null ? { username: bot.user } : {}), ...(bot.team != null ? { name: bot.team } : {}) }
91
+ }
92
+
93
+ const setup = (connection: BotPlatformConnection): string[] => [
94
+ SLACK_SETUP_CREDENTIALS_STEP,
95
+ connection.hookUrl != null && connection.hookUrl !== '' ? `${SLACK_SETUP_HOOK_STEP}${connection.hookUrl}` : SLACK_SETUP_HOOK_PENDING_STEP,
96
+ ...SLACK_SETUP_TAIL_STEPS,
97
+ ]
98
+
99
+ /**
100
+ * The signature over the raw body with the signing secret (a MOCK connection also accepts its hook
101
+ * secret — what the mock signs with when it has no signing secret), a fresh timestamp, and only
102
+ * then the `url_verification` handshake.
103
+ */
104
+ const authenticate: BotPlatformPlugin['authenticate'] = (request, connection): BotAuthentication => {
105
+ if (request.method.toUpperCase() !== 'POST') {
106
+ return { result: 'reject', reason: 'method' }
107
+ }
108
+ const timestamp = botHookHelper.header(request, SLACK_TIMESTAMP_HEADER)
109
+ if (!slackSignatureHelper.fresh(timestamp, Date.now())) {
110
+ return { result: 'reject', reason: 'stale-timestamp' }
111
+ }
112
+ const secrets = [
113
+ connection.credentials.signingSecret ?? '',
114
+ ...(connection.transport === BotTransport.Mock ? [connection.hookSecret] : []),
115
+ ].filter(secret => secret !== '')
116
+ if (secrets.length === 0) {
117
+ return { result: 'reject', reason: 'no-signing-secret' }
118
+ }
119
+ const signature = botHookHelper.header(request, SLACK_SIGNATURE_HEADER)
120
+ if (!slackSignatureHelper.matches(signature, timestamp!, botHookHelper.rawText(request), secrets)) {
121
+ return { result: 'reject', reason: 'signature' }
122
+ }
123
+ const payload = botHookHelper.json(request) as { type?: unknown, challenge?: unknown } | null
124
+ if (payload != null && payload.type === 'url_verification') {
125
+ return typeof payload.challenge === 'string'
126
+ ? { result: 'challenge', reply: { challenge: payload.challenge } }
127
+ : { result: 'reject', reason: 'challenge' }
128
+ }
129
+
130
+ return { result: 'ok' }
131
+ }
132
+
133
+ const refOf = (posted: SlackPosted, chat: string, thread?: string, space?: string): BotMessageRef => ({
134
+ chat: posted.channel ?? chat,
135
+ id: posted.ts ?? '',
136
+ ...(thread != null && thread !== '' ? { thread } : {}),
137
+ ...(space != null ? { space } : {}),
138
+ })
139
+
140
+ const act = async (session: BotPlatformSession, action: BotPlatformAction): Promise<BotPlatformActionResult> => {
141
+ const client = api(session)
142
+ switch (action.kind) {
143
+ case BotActionKind.Reply: {
144
+ // Slack threads hang off the parent: a reply inside a thread names the thread, else the message.
145
+ const thread = action.to.thread ?? action.to.id
146
+ const posted = await client.call<SlackPosted>('chat.postMessage', {
147
+ channel: action.to.chat, text: slackTextHelper.encode(clip(action.text)), thread_ts: thread,
148
+ })
149
+ return { message: refOf(posted, action.to.chat, thread, action.to.space) }
150
+ }
151
+ case BotActionKind.Send: {
152
+ const thread = action.chat.thread
153
+ const posted = await client.call<SlackPosted>('chat.postMessage', {
154
+ channel: action.chat.id, text: slackTextHelper.encode(clip(action.text)), ...(thread != null && thread !== '' ? { thread_ts: thread } : {}),
155
+ })
156
+ return { message: refOf(posted, action.chat.id, thread, action.chat.space) }
157
+ }
158
+ case BotActionKind.Delete: {
159
+ // A bot token deletes only the bot's own posts: a member's message needs an admin's user token.
160
+ const token = session.connection.credentials.userToken ?? ''
161
+ if (token === '') {
162
+ throw new BotUnsupportedAction(BotActionKind.Delete)
163
+ }
164
+ await client.call<SlackAnswer>('chat.delete', { channel: action.message.chat, ts: action.message.id }, { token })
165
+ return {}
166
+ }
167
+ case BotActionKind.React:
168
+ await client.call<SlackAnswer>('reactions.add', {
169
+ channel: action.message.chat, timestamp: action.message.id, name: emojiName(action.emoji),
170
+ })
171
+ return {}
172
+ case BotActionKind.Mute:
173
+ case BotActionKind.Ban:
174
+ throw new BotUnsupportedAction(action.kind)
175
+ }
176
+ }
177
+
178
+ return {
179
+ platform: SLACK_PLATFORM,
180
+ descriptor: SLACK_DESCRIPTOR,
181
+ verify,
182
+ setup,
183
+ authenticate,
184
+ normalize: slackNormalizer.normalize,
185
+ act,
186
+ mock,
187
+ }
188
+ }
189
+
190
+ /** The built-in instance (`https://slack.com/api`) — its `mock` is the one simulated connections use. */
191
+ export const slackBotPlatform = makeSlackBotPlatform()
@@ -0,0 +1,33 @@
1
+ import { createHmac } from 'node:crypto'
2
+ import { botHookHelper } from '@owlmeans/server-bot'
3
+ import { SLACK_SIGNATURE_TOLERANCE_S, SLACK_SIGNATURE_VERSION } from './consts.js'
4
+ import type { SlackSignatureHelper } from './types.js'
5
+
6
+ /**
7
+ * Slack's request signing (https://docs.slack.dev/authentication/verifying-requests-from-slack):
8
+ * the secret is used as UTF-8 text, the basestring is `v0:<timestamp>:<raw body>`.
9
+ */
10
+ export const createSlackSignatureHelper = (): SlackSignatureHelper => {
11
+ const sign = (secret: string, timestamp: string, body: string): string =>
12
+ `${SLACK_SIGNATURE_VERSION}=${createHmac('sha256', secret).update(`${SLACK_SIGNATURE_VERSION}:${timestamp}:${body}`).digest('hex')}`
13
+
14
+ const matches = (signature: string | undefined, timestamp: string, body: string, secrets: readonly string[]): boolean => {
15
+ let matched = false
16
+ // Every secret is compared, matched or not: the time taken says nothing about which one.
17
+ for (const secret of secrets) {
18
+ if (secret !== '' && botHookHelper.sameSecret(signature, sign(secret, timestamp, body))) {
19
+ matched = true
20
+ }
21
+ }
22
+
23
+ return matched
24
+ }
25
+
26
+ const fresh = (timestamp: string | undefined, nowMs: number): boolean =>
27
+ timestamp != null && /^\d{1,12}$/.test(timestamp)
28
+ && Math.abs(nowMs / 1000 - Number(timestamp)) <= SLACK_SIGNATURE_TOLERANCE_S
29
+
30
+ return { sign, matches, fresh }
31
+ }
32
+
33
+ export const slackSignatureHelper = createSlackSignatureHelper()
package/src/text.ts ADDED
@@ -0,0 +1,16 @@
1
+ import type { SlackTextHelper } from './types.js'
2
+
3
+ /**
4
+ * Slack escapes `&`, `<` and `>` in message text (https://docs.slack.dev/messaging/formatting-message-text/):
5
+ * an inbound text is decoded so handlers match what people read; an outbound text is encoded so the
6
+ * contract's plain text stays literal (no accidental links or mentions).
7
+ */
8
+ export const createSlackTextHelper = (): SlackTextHelper => {
9
+ const decode = (text: string): string => text.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&')
10
+
11
+ const encode = (text: string): string => text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
12
+
13
+ return { decode, encode }
14
+ }
15
+
16
+ export const slackTextHelper = createSlackTextHelper()
package/src/types.ts ADDED
@@ -0,0 +1,207 @@
1
+ import type { BotConnection } from '@owlmeans/bot'
2
+ import type {
3
+ BotMockCall, BotNativeInbound, BotNormalizedUpdate, BotPlatformConnection, BotPlatformMock, BotPlatformPlugin,
4
+ BotPlatformSession,
5
+ } from '@owlmeans/server-bot'
6
+
7
+ // ─── Native Events API shapes (https://docs.slack.dev/apis/events-api/) — the fields used ───
8
+
9
+ export interface SlackProfile {
10
+ real_name?: string
11
+ display_name?: string
12
+ name?: string
13
+ }
14
+
15
+ export interface SlackBotProfile {
16
+ id?: string
17
+ name?: string
18
+ app_id?: string
19
+ }
20
+
21
+ /** A `message` event (or the `message` an edit carries) — `ts` is the message id. */
22
+ export interface SlackMessage {
23
+ type: 'message'
24
+ subtype?: string
25
+ channel?: string
26
+ /** `channel` · `group` (private channel) · `im` · `mpim`. */
27
+ channel_type?: string
28
+ user?: string
29
+ text?: string
30
+ ts?: string
31
+ event_ts?: string
32
+ /** The thread's parent `ts`; equal to `ts` on the parent itself. */
33
+ thread_ts?: string
34
+ /** Who wrote the thread's parent — on a thread reply. */
35
+ parent_user_id?: string
36
+ team?: string
37
+ bot_id?: string
38
+ app_id?: string
39
+ bot_profile?: SlackBotProfile
40
+ /** Delivered on members' messages, not documented on the event's page — read when present. */
41
+ user_profile?: SlackProfile
42
+ edited?: { user?: string, ts?: string }
43
+ hidden?: boolean
44
+ /** `message_changed`: the message as it is now / as it was. */
45
+ message?: SlackMessage
46
+ previous_message?: SlackMessage
47
+ }
48
+
49
+ export interface SlackAppMention {
50
+ type: 'app_mention'
51
+ channel?: string
52
+ user?: string
53
+ text?: string
54
+ ts?: string
55
+ event_ts?: string
56
+ thread_ts?: string
57
+ team?: string
58
+ bot_id?: string
59
+ app_id?: string
60
+ }
61
+
62
+ export interface SlackAuthorization {
63
+ enterprise_id?: string | null
64
+ team_id?: string
65
+ user_id?: string
66
+ is_bot?: boolean
67
+ is_enterprise_install?: boolean
68
+ }
69
+
70
+ /** The outer JSON of every Events API request. */
71
+ export interface SlackEnvelope {
72
+ type: 'event_callback' | 'url_verification' | 'app_rate_limited' | string
73
+ token?: string
74
+ team_id?: string
75
+ api_app_id?: string
76
+ event?: SlackMessage | SlackAppMention | { type: string }
77
+ event_id?: string
78
+ event_time?: number
79
+ authorizations?: SlackAuthorization[]
80
+ is_ext_shared_channel?: boolean
81
+ event_context?: string
82
+ /** `url_verification` only. */
83
+ challenge?: string
84
+ }
85
+
86
+ /** Every Web API answer. */
87
+ export interface SlackAnswer {
88
+ ok: boolean
89
+ error?: string
90
+ warning?: string
91
+ }
92
+
93
+ export interface SlackAuthTest extends SlackAnswer {
94
+ url?: string
95
+ team?: string
96
+ user?: string
97
+ team_id?: string
98
+ user_id?: string
99
+ /** Present for a bot token only. */
100
+ bot_id?: string
101
+ enterprise_id?: string
102
+ is_enterprise_install?: boolean
103
+ }
104
+
105
+ export interface SlackPosted extends SlackAnswer {
106
+ channel?: string
107
+ ts?: string
108
+ message?: SlackMessage
109
+ }
110
+
111
+ // ─── The plugin's parts ───
112
+
113
+ export interface SlackBotPlatformOptions {
114
+ /** The Web API, default `https://slack.com/api`; calls go to `<base>/<method>`. */
115
+ base?: string
116
+ /** Retries of a call answered 429, default 2. */
117
+ retries?: number
118
+ /** The longest `Retry-After` waited for, in seconds, default 30. */
119
+ maxRetryWaitS?: number
120
+ }
121
+
122
+ export interface SlackRetryPolicy {
123
+ retries: number
124
+ maxRetryWaitS: number
125
+ }
126
+
127
+ export interface SlackCallOptions {
128
+ /** Another token than the bot's — the admin `userToken` for `chat.delete`. */
129
+ token?: string
130
+ signal?: AbortSignal
131
+ timeoutMs?: number
132
+ }
133
+
134
+ /** The Web API over a session's transport. */
135
+ export interface SlackApi {
136
+ /**
137
+ * POST `<base>/<method>` with a JSON body and `Authorization: Bearer <token>`; a 429 is retried
138
+ * after its `Retry-After` (bounded). @throws {SlackApiError} `ok: false`, a transport fault
139
+ */
140
+ call: <T extends SlackAnswer>(method: string, params?: Record<string, unknown>, opts?: SlackCallOptions) => Promise<T>
141
+ }
142
+
143
+ export interface SlackApiFactory {
144
+ (session: Pick<BotPlatformSession, 'connection' | 'fetch'>, base: string, retry: SlackRetryPolicy): SlackApi
145
+ }
146
+
147
+ /** The Events API request signature. */
148
+ export interface SlackSignatureHelper {
149
+ /** `v0=` + hex HMAC-SHA256(secret, `v0:<timestamp>:<body>`). */
150
+ sign: (secret: string, timestamp: string, body: string) => string
151
+ /** Whether `signature` signs `body` at `timestamp` with any of `secrets` — timing-safe. */
152
+ matches: (signature: string | undefined, timestamp: string, body: string, secrets: readonly string[]) => boolean
153
+ /** Whether `timestamp` (seconds) is within the tolerance of `nowMs`. */
154
+ fresh: (timestamp: string | undefined, nowMs: number) => boolean
155
+ }
156
+
157
+ /** Slack's three escaped characters in message text. */
158
+ export interface SlackTextHelper {
159
+ /** `&amp;` `&lt;` `&gt;` → `&` `<` `>` — what a person reads. */
160
+ decode: (text: string) => string
161
+ /** `&` `<` `>` → entities — plain text Slack shows as written. */
162
+ encode: (text: string) => string
163
+ }
164
+
165
+ export interface SlackNormalizer {
166
+ /**
167
+ * An `event_callback`'s `message` (new, or edited when it carries new text) or `app_mention` → one
168
+ * update; system subtypes, the bot's own messages and every other payload → none.
169
+ */
170
+ normalize: (payload: unknown, connection: BotConnection) => BotNormalizedUpdate[]
171
+ }
172
+
173
+ /** Who the fake workspace says the fake bot is — stable per connection id. */
174
+ export interface SlackMockIdentity {
175
+ teamId: string
176
+ teamName: string
177
+ appId: string
178
+ botId: string
179
+ botUserId: string
180
+ username: string
181
+ /** The admin `auth.test` answers for the connection's `userToken`. */
182
+ adminUserId: string
183
+ }
184
+
185
+ export interface SlackMock extends BotPlatformMock {
186
+ /** A signed `url_verification` request — what Slack posts when the Request URL is pasted. */
187
+ challenge: (connection: BotPlatformConnection, challenge?: string) => BotNativeInbound
188
+ /** The fake workspace, app and bot of a connection id. */
189
+ identityOf: (connection: string) => SlackMockIdentity
190
+ }
191
+
192
+ /** One mock connection's state. */
193
+ export interface SlackMockState {
194
+ /** The last `ts` handed out, in microseconds — every new one is later. */
195
+ clock: number
196
+ /** Every call, with `auth` — the token it carried (`bot`, `user` or `none`). */
197
+ calls: BotMockCall[]
198
+ /** The `ts` of messages the fake bot posted — a thread under one is the bot's. */
199
+ sent: Set<string>
200
+ /** `<channel>:<ts>:<name>` of reactions already added. */
201
+ reactions: Set<string>
202
+ }
203
+
204
+ /** The Slack plugin, its mock typed as Slack's own. */
205
+ export interface SlackBotPlatform extends BotPlatformPlugin {
206
+ mock: SlackMock
207
+ }