@zhin.js/adapter-slack 1.0.78 → 1.1.2
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/CHANGELOG.md +731 -2
- package/PERMITS.md +24 -0
- package/README.md +111 -158
- package/adapters/slack/index.js +40 -0
- package/adapters/slack/index.ts +45 -0
- package/agents/slack/agent.json +20 -0
- package/agents/slack/boundaries.md +3 -0
- package/agents/slack/conventions.md +3 -0
- package/agents/slack/skills/slack-channels/SKILL.md +24 -0
- package/agents/slack/skills/slack-channels/tools/archive_channel/index.js +19 -0
- package/agents/slack/skills/slack-channels/tools/archive_channel/index.ts +21 -0
- package/agents/slack/skills/slack-channels/tools/invite_to_channel/index.js +20 -0
- package/agents/slack/skills/slack-channels/tools/invite_to_channel/index.ts +23 -0
- package/agents/slack/skills/slack-channels/tools/set_purpose/index.js +20 -0
- package/agents/slack/skills/slack-channels/tools/set_purpose/index.ts +23 -0
- package/agents/slack/skills/slack-channels/tools/set_topic/index.js +20 -0
- package/agents/slack/skills/slack-channels/tools/set_topic/index.ts +23 -0
- package/agents/slack/skills/slack-channels/tools/unarchive/index.js +19 -0
- package/agents/slack/skills/slack-channels/tools/unarchive/index.ts +21 -0
- package/agents/slack/skills/slack-channels/tools/user_info/index.js +27 -0
- package/agents/slack/skills/slack-channels/tools/user_info/index.ts +29 -0
- package/agents/slack/skills/slack-messages/SKILL.md +22 -0
- package/agents/slack/skills/slack-messages/tools/add_reaction/index.js +27 -0
- package/agents/slack/skills/slack-messages/tools/add_reaction/index.ts +29 -0
- package/agents/slack/skills/slack-messages/tools/edit_message/index.js +21 -0
- package/agents/slack/skills/slack-messages/tools/edit_message/index.ts +25 -0
- package/agents/slack/skills/slack-messages/tools/pin_message/index.js +20 -0
- package/agents/slack/skills/slack-messages/tools/pin_message/index.ts +23 -0
- package/agents/slack/skills/slack-messages/tools/remove_reaction/index.js +30 -0
- package/agents/slack/skills/slack-messages/tools/remove_reaction/index.ts +32 -0
- package/agents/slack/skills/slack-messages/tools/unpin_message/index.js +20 -0
- package/agents/slack/skills/slack-messages/tools/unpin_message/index.ts +23 -0
- package/agents/slack/system.md +3 -0
- package/commands/slack/endpoint/add/[id]/index.js +3 -0
- package/commands/slack/endpoint/add/[id]/index.ts +3 -0
- package/commands/slack/endpoint/definition.js +19 -0
- package/commands/slack/endpoint/definition.ts +19 -0
- package/commands/slack/endpoint/list/index.js +3 -0
- package/commands/slack/endpoint/list/index.ts +3 -0
- package/commands/slack/endpoint/remove/[id]/index.js +3 -0
- package/commands/slack/endpoint/remove/[id]/index.ts +3 -0
- package/lib/client.d.ts +25 -0
- package/lib/client.js +2 -0
- package/lib/endpoint.d.ts +153 -0
- package/lib/endpoint.js +425 -0
- package/lib/index.d.ts +10 -10
- package/lib/index.js +10 -242
- package/lib/markdown-to-mrkdwn.d.ts +9 -0
- package/lib/markdown-to-mrkdwn.js +121 -0
- package/lib/mrkdwn-to-markdown.d.ts +4 -0
- package/lib/mrkdwn-to-markdown.js +30 -0
- package/lib/platform-permit.d.ts +15 -0
- package/lib/platform-permit.js +43 -0
- package/lib/protocol.d.ts +144 -0
- package/lib/protocol.js +258 -0
- package/lib/side-event-dispatch.d.ts +4 -0
- package/lib/side-event-dispatch.js +45 -0
- package/lib/slack-inbound-filter.d.ts +12 -0
- package/lib/slack-inbound-filter.js +46 -0
- package/lib/slack-message-ref.d.ts +7 -0
- package/lib/slack-message-ref.js +17 -0
- package/lib/slack-outbound.d.ts +24 -0
- package/lib/slack-outbound.js +111 -0
- package/lib/slack-reaction.d.ts +1 -0
- package/lib/slack-reaction.js +26 -0
- package/lib/slack-response-url.d.ts +5 -0
- package/lib/slack-response-url.js +16 -0
- package/lib/slack-runtime-state.d.ts +1 -0
- package/lib/slack-runtime-state.js +6 -0
- package/lib/webhook.d.ts +14 -0
- package/lib/webhook.js +72 -0
- package/package.json +80 -16
- package/plugin.js +19 -0
- package/schema.json +108 -0
- package/src/client.ts +30 -0
- package/src/endpoint.ts +526 -0
- package/src/index.ts +59 -265
- package/src/markdown-to-mrkdwn.ts +117 -0
- package/src/mrkdwn-to-markdown.ts +29 -0
- package/src/platform-permit.ts +59 -0
- package/src/protocol.ts +406 -0
- package/src/side-event-dispatch.ts +54 -0
- package/src/slack-inbound-filter.ts +60 -0
- package/src/slack-message-ref.ts +18 -0
- package/src/slack-outbound.ts +170 -0
- package/src/slack-reaction.ts +23 -0
- package/src/slack-response-url.ts +26 -0
- package/src/slack-runtime-state.ts +7 -0
- package/src/webhook.ts +106 -0
- package/lib/adapter.d.ts +0 -16
- package/lib/adapter.d.ts.map +0 -1
- package/lib/adapter.js +0 -43
- package/lib/adapter.js.map +0 -1
- package/lib/bot.d.ts +0 -106
- package/lib/bot.d.ts.map +0 -1
- package/lib/bot.js +0 -628
- package/lib/bot.js.map +0 -1
- package/lib/index.d.ts.map +0 -1
- package/lib/index.js.map +0 -1
- package/lib/types.d.ts +0 -17
- package/lib/types.d.ts.map +0 -1
- package/lib/types.js +0 -2
- package/lib/types.js.map +0 -1
- package/plugin.yml +0 -3
- package/skills/slack/SKILL.md +0 -91
- package/src/adapter.ts +0 -52
- package/src/bot.ts +0 -688
- package/src/types.ts +0 -18
package/src/protocol.ts
ADDED
|
@@ -0,0 +1,406 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Slack protocol helpers — no legacy Adapter/Endpoint / segment-mapper.
|
|
3
|
+
* Canonicalization is owned by gateway/core before endpoint.send.
|
|
4
|
+
*/
|
|
5
|
+
import { createHmac, timingSafeEqual } from 'node:crypto';
|
|
6
|
+
import type { IncomingMessage } from 'node:http';
|
|
7
|
+
import { isMediaRef, type MediaRef, type ConversationKind, type ConversationRef } from '@zhin.js/im-contract';
|
|
8
|
+
import { formatCompact, getLogger } from '@zhin.js/logger';
|
|
9
|
+
import { mrkdwnToMarkdown } from './mrkdwn-to-markdown.js';
|
|
10
|
+
|
|
11
|
+
const logger = getLogger('slack');
|
|
12
|
+
|
|
13
|
+
/** 无 canonical MediaRef 或不可投递时留痕(对齐 QQ `*_outbound_media_dropped` 风格)。 */
|
|
14
|
+
function dropOutboundMedia(type: string, reason: string): void {
|
|
15
|
+
logger.warn(formatCompact({ op: 'slack_outbound_media_dropped', type, reason }));
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const SLACK_SIG_VERSION = 'v0';
|
|
19
|
+
const MAX_TIMESTAMP_DRIFT_SECONDS = 300;
|
|
20
|
+
|
|
21
|
+
/** One endpoint config after AdapterIndex expands `plugins.<instanceKey>.endpoints`. */
|
|
22
|
+
export interface SlackEndpointConfig {
|
|
23
|
+
readonly id: string;
|
|
24
|
+
readonly token: string;
|
|
25
|
+
readonly signingSecret?: string;
|
|
26
|
+
readonly appToken?: string;
|
|
27
|
+
/** Default true (Socket Mode). Set false for HTTP Events API via httpHostToken. */
|
|
28
|
+
readonly socketMode?: boolean;
|
|
29
|
+
readonly webhookPath?: string;
|
|
30
|
+
readonly clientPingTimeout?: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface ResolvedSlackConfig {
|
|
34
|
+
readonly context: 'slack';
|
|
35
|
+
readonly id: string;
|
|
36
|
+
readonly token: string;
|
|
37
|
+
readonly mode: 'socket' | 'http';
|
|
38
|
+
readonly signingSecret: string;
|
|
39
|
+
readonly appToken?: string;
|
|
40
|
+
readonly webhookPath: string;
|
|
41
|
+
readonly clientPingTimeout: number;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface SlackEventEnvelope {
|
|
45
|
+
readonly token?: string;
|
|
46
|
+
readonly team_id?: string;
|
|
47
|
+
readonly api_app_id?: string;
|
|
48
|
+
readonly event: SlackEvent;
|
|
49
|
+
readonly type: 'event_callback';
|
|
50
|
+
readonly event_id?: string;
|
|
51
|
+
readonly event_time?: number;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface SlackUrlVerification {
|
|
55
|
+
readonly type: 'url_verification';
|
|
56
|
+
readonly token: string;
|
|
57
|
+
readonly challenge: string;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface SlackInteractionPayload {
|
|
61
|
+
readonly type: 'block_actions' | 'message_action' | 'shortcut' | 'view_submission' | 'view_closed';
|
|
62
|
+
readonly trigger_id?: string;
|
|
63
|
+
readonly user: { id: string; username?: string; name?: string; team_id?: string };
|
|
64
|
+
readonly channel?: { id: string; name?: string };
|
|
65
|
+
readonly message?: { ts: string; text?: string; [key: string]: unknown };
|
|
66
|
+
readonly actions?: SlackBlockAction[];
|
|
67
|
+
readonly response_url?: string;
|
|
68
|
+
readonly [key: string]: unknown;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface SlackBlockAction {
|
|
72
|
+
readonly type: string;
|
|
73
|
+
readonly action_id: string;
|
|
74
|
+
readonly block_id: string;
|
|
75
|
+
readonly value?: string;
|
|
76
|
+
readonly text?: { type: string; text: string };
|
|
77
|
+
readonly action_ts?: string;
|
|
78
|
+
readonly [key: string]: unknown;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export interface SlackSlashCommand {
|
|
82
|
+
readonly token: string;
|
|
83
|
+
readonly team_id: string;
|
|
84
|
+
readonly channel_id: string;
|
|
85
|
+
readonly channel_name: string;
|
|
86
|
+
readonly user_id: string;
|
|
87
|
+
readonly user_name: string;
|
|
88
|
+
readonly command: string;
|
|
89
|
+
readonly text: string;
|
|
90
|
+
readonly response_url: string;
|
|
91
|
+
readonly trigger_id: string;
|
|
92
|
+
readonly api_app_id?: string;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export interface SlackEvent {
|
|
96
|
+
readonly type: string;
|
|
97
|
+
readonly ts?: string;
|
|
98
|
+
readonly event_ts?: string;
|
|
99
|
+
readonly user?: string;
|
|
100
|
+
readonly channel?: string;
|
|
101
|
+
readonly channel_type?: string;
|
|
102
|
+
readonly text?: string;
|
|
103
|
+
readonly thread_ts?: string;
|
|
104
|
+
readonly subtype?: string;
|
|
105
|
+
readonly bot_id?: string;
|
|
106
|
+
readonly [key: string]: unknown;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export type SlackMessageEvent = SlackEvent & {
|
|
110
|
+
readonly type: 'message' | 'app_mention';
|
|
111
|
+
readonly ts: string;
|
|
112
|
+
readonly channel: string;
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
export interface SlackWireSegment {
|
|
116
|
+
readonly type: string;
|
|
117
|
+
readonly data?: Record<string, unknown>;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function resolveSlackConfig(config: SlackEndpointConfig): ResolvedSlackConfig {
|
|
121
|
+
const id = requiredEndpointField(config.id, 'id');
|
|
122
|
+
const token = requiredEndpointField(config.token, 'token');
|
|
123
|
+
const socketMode = config.socketMode;
|
|
124
|
+
// Prefer Socket Mode (default true) — no public URL required.
|
|
125
|
+
const mode: 'socket' | 'http' = socketMode === false ? 'http' : 'socket';
|
|
126
|
+
|
|
127
|
+
const signingSecret = mode === 'http'
|
|
128
|
+
? requiredEndpointField(config.signingSecret, 'signingSecret')
|
|
129
|
+
: config.signingSecret?.trim() ?? '';
|
|
130
|
+
const appToken = mode === 'socket'
|
|
131
|
+
? requiredEndpointField(config.appToken, 'appToken')
|
|
132
|
+
: config.appToken?.trim();
|
|
133
|
+
|
|
134
|
+
return {
|
|
135
|
+
context: 'slack',
|
|
136
|
+
id,
|
|
137
|
+
token,
|
|
138
|
+
mode,
|
|
139
|
+
signingSecret,
|
|
140
|
+
appToken,
|
|
141
|
+
webhookPath: normalizeWebhookPath(
|
|
142
|
+
config.webhookPath ?? '/slack/events',
|
|
143
|
+
),
|
|
144
|
+
clientPingTimeout: config.clientPingTimeout ?? 15_000,
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function requiredEndpointField(
|
|
149
|
+
value: unknown,
|
|
150
|
+
field: 'id' | 'token' | 'signingSecret' | 'appToken',
|
|
151
|
+
): string {
|
|
152
|
+
if (typeof value !== 'string' || !value.trim()) {
|
|
153
|
+
throw new TypeError(`Slack endpoint requires a non-empty ${field}`);
|
|
154
|
+
}
|
|
155
|
+
return value.trim();
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export function normalizeWebhookPath(path: string): string {
|
|
159
|
+
const trimmed = path.trim() || '/slack/events';
|
|
160
|
+
return trimmed.startsWith('/') ? trimmed : `/${trimmed}`;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export function resolveSlackChannelType(event: Pick<SlackEvent, 'channel_type'>): 'private' | 'group' {
|
|
164
|
+
return event.channel_type === 'im' ? 'private' : 'group';
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* 入站归一化 → ConversationRef:channel_type `im` → private,其余(channel/group/mpim)
|
|
169
|
+
* → group;交互/斜杠命令无 channel_type 时按平台 id 前缀推断(D* 为 DM)。Slack 无
|
|
170
|
+
* guild 容器概念(team 为 workspace 级,不进 parent);线程根 ts 进 `threadId`。
|
|
171
|
+
*/
|
|
172
|
+
export function slackInboundConversation(
|
|
173
|
+
endpointKey: string,
|
|
174
|
+
opts: {
|
|
175
|
+
readonly channelId: string;
|
|
176
|
+
readonly channelType?: string;
|
|
177
|
+
readonly threadId?: string;
|
|
178
|
+
},
|
|
179
|
+
): ConversationRef {
|
|
180
|
+
const kind: ConversationKind = opts.channelType != null
|
|
181
|
+
? (opts.channelType === 'im' ? 'private' : 'group')
|
|
182
|
+
: (opts.channelId.startsWith('D') ? 'private' : 'group');
|
|
183
|
+
return {
|
|
184
|
+
endpoint: { id: endpointKey, adapter: endpointKey.split('\0')[0] ?? endpointKey },
|
|
185
|
+
kind,
|
|
186
|
+
id: opts.channelId,
|
|
187
|
+
...(opts.threadId ? { threadId: opts.threadId } : {}),
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Build inbound text for OutboundMessageService.receive. */
|
|
192
|
+
export function formatInboundContent(event: SlackMessageEvent | SlackEvent): string {
|
|
193
|
+
const text = typeof event.text === 'string' ? event.text : '';
|
|
194
|
+
if (text) return mrkdwnToMarkdown(text);
|
|
195
|
+
if ('files' in event && Array.isArray(event.files) && event.files.length > 0) {
|
|
196
|
+
return '[file]';
|
|
197
|
+
}
|
|
198
|
+
return '';
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export function formatInteractionContent(payload: SlackInteractionPayload): string {
|
|
202
|
+
const action = payload.actions?.[0];
|
|
203
|
+
if (!action) return '[action]';
|
|
204
|
+
const label = action.text?.text ?? action.value ?? action.action_id;
|
|
205
|
+
return `[action: ${action.action_id}${label ? ` ${label}` : ''}]`;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
export function formatSlashContent(cmd: SlackSlashCommand): string {
|
|
209
|
+
return `${cmd.command} ${cmd.text}`.trim();
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Wire-encode an already-rendered outbound payload into Slack text + Block Kit blocks.
|
|
214
|
+
* Segment canonicalization is intentionally not done here.
|
|
215
|
+
*/
|
|
216
|
+
export function formatOutboundWire(payload: unknown): {
|
|
217
|
+
text: string;
|
|
218
|
+
blocks: Record<string, unknown>[];
|
|
219
|
+
attachments: Record<string, unknown>[];
|
|
220
|
+
files: Array<{ buffer?: Buffer; url?: string; path?: string; name?: string }>;
|
|
221
|
+
} {
|
|
222
|
+
if (typeof payload === 'string') {
|
|
223
|
+
return { text: payload, blocks: [], attachments: [], files: [] };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const items: Array<string | SlackWireSegment> = Array.isArray(payload)
|
|
227
|
+
? payload as Array<string | SlackWireSegment>
|
|
228
|
+
: payload && typeof payload === 'object' && 'type' in (payload as object)
|
|
229
|
+
? [payload as SlackWireSegment]
|
|
230
|
+
: [];
|
|
231
|
+
|
|
232
|
+
if (items.length === 0) {
|
|
233
|
+
const text = payload == null
|
|
234
|
+
? ''
|
|
235
|
+
: typeof payload === 'object'
|
|
236
|
+
? JSON.stringify(payload)
|
|
237
|
+
: String(payload);
|
|
238
|
+
return { text, blocks: [], attachments: [], files: [] };
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
let text = '';
|
|
242
|
+
const blocks: Record<string, unknown>[] = [];
|
|
243
|
+
const attachments: Record<string, unknown>[] = [];
|
|
244
|
+
const files: Array<{ buffer?: Buffer; url?: string; path?: string; name?: string }> = [];
|
|
245
|
+
|
|
246
|
+
for (const item of items) {
|
|
247
|
+
if (typeof item === 'string') {
|
|
248
|
+
text += item;
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
const data = item.data ?? {};
|
|
252
|
+
switch (item.type) {
|
|
253
|
+
case 'text':
|
|
254
|
+
text += String(data.text ?? data.content ?? '');
|
|
255
|
+
break;
|
|
256
|
+
case 'at':
|
|
257
|
+
case 'mention':
|
|
258
|
+
text += `<@${String(data.id ?? data.target ?? '')}>`;
|
|
259
|
+
break;
|
|
260
|
+
case 'channel_mention':
|
|
261
|
+
text += `<#${String(data.id ?? '')}>`;
|
|
262
|
+
break;
|
|
263
|
+
case 'link':
|
|
264
|
+
if (data.text && data.text !== data.url) {
|
|
265
|
+
text += `<${String(data.url)}|${String(data.text)}>`;
|
|
266
|
+
} else {
|
|
267
|
+
text += `<${String(data.url ?? '')}>`;
|
|
268
|
+
}
|
|
269
|
+
break;
|
|
270
|
+
case 'image': {
|
|
271
|
+
// canonical MediaRef 唯一来源;kind=url 走 attachment 直发,其余物化后 files.uploadV2 上传
|
|
272
|
+
const media = data.media;
|
|
273
|
+
if (!isMediaRef(media)) {
|
|
274
|
+
dropOutboundMedia(item.type, 'missing_media_ref');
|
|
275
|
+
break;
|
|
276
|
+
}
|
|
277
|
+
if (media.kind === 'url') {
|
|
278
|
+
attachments.push({
|
|
279
|
+
image_url: media.value,
|
|
280
|
+
title: String(data.alt ?? data.title ?? media.file_name ?? ''),
|
|
281
|
+
});
|
|
282
|
+
break;
|
|
283
|
+
}
|
|
284
|
+
const imageFile = resolveMediaToFile(media, String(data.alt ?? media.file_name ?? 'image'));
|
|
285
|
+
if (imageFile) files.push(imageFile);
|
|
286
|
+
else dropOutboundMedia(item.type, 'unsupported_media_kind');
|
|
287
|
+
break;
|
|
288
|
+
}
|
|
289
|
+
case 'audio':
|
|
290
|
+
case 'video':
|
|
291
|
+
case 'file': {
|
|
292
|
+
const media = data.media;
|
|
293
|
+
if (!isMediaRef(media)) {
|
|
294
|
+
dropOutboundMedia(item.type, 'missing_media_ref');
|
|
295
|
+
break;
|
|
296
|
+
}
|
|
297
|
+
const mediaFile = resolveMediaToFile(media, String(data.name ?? media.file_name ?? item.type));
|
|
298
|
+
if (mediaFile) files.push(mediaFile);
|
|
299
|
+
else dropOutboundMedia(item.type, 'unsupported_media_kind');
|
|
300
|
+
break;
|
|
301
|
+
}
|
|
302
|
+
case 'keyboard':
|
|
303
|
+
blocks.push(...keyboardToBlockKitBlocks(data));
|
|
304
|
+
break;
|
|
305
|
+
default:
|
|
306
|
+
text += String(data.text ?? `[${item.type}]`);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
return { text, blocks, attachments, files };
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
export function keyboardToBlockKitBlocks(data: Record<string, unknown>): Record<string, unknown>[] {
|
|
314
|
+
const rows = data.rows as Array<Array<Record<string, unknown>>> | undefined;
|
|
315
|
+
if (!rows?.length) return [];
|
|
316
|
+
|
|
317
|
+
const blocks: Record<string, unknown>[] = [];
|
|
318
|
+
for (const row of rows) {
|
|
319
|
+
const elements = row.slice(0, 5).map((btn, index) => ({
|
|
320
|
+
type: 'button',
|
|
321
|
+
text: { type: 'plain_text', text: String(btn.label ?? btn.text ?? 'button').slice(0, 75) },
|
|
322
|
+
action_id: String(btn.id ?? btn.action_id ?? `btn_${blocks.length}_${index}`),
|
|
323
|
+
...(btn.value != null ? { value: String(btn.value) } : {}),
|
|
324
|
+
...(btn.style === 'primary' ? { style: 'primary' } : {}),
|
|
325
|
+
...(btn.style === 'danger' ? { style: 'danger' } : {}),
|
|
326
|
+
}));
|
|
327
|
+
if (elements.length > 0) {
|
|
328
|
+
blocks.push({ type: 'actions', elements });
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
return blocks;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* MediaRef → 待上传文件描述:
|
|
336
|
+
* - kind=url → 记录 URL,由 files.uploadV2 前拉取物化;
|
|
337
|
+
* - kind=base64 → 解码为 buffer 直传;
|
|
338
|
+
* - kind=path → 记录本地路径,上传前读盘;
|
|
339
|
+
* - kind=file → Slack 无平台不透明文件引用可直发,返回 undefined 由调用方丢弃留痕。
|
|
340
|
+
*/
|
|
341
|
+
function resolveMediaToFile(
|
|
342
|
+
media: MediaRef,
|
|
343
|
+
name: string,
|
|
344
|
+
): { buffer?: Buffer; url?: string; path?: string; name: string } | undefined {
|
|
345
|
+
switch (media.kind) {
|
|
346
|
+
case 'base64':
|
|
347
|
+
return {
|
|
348
|
+
buffer: Buffer.from(media.value.replace(/^base64:\/\//, ''), 'base64'),
|
|
349
|
+
name,
|
|
350
|
+
};
|
|
351
|
+
case 'url':
|
|
352
|
+
return { url: media.value, name };
|
|
353
|
+
case 'path':
|
|
354
|
+
return { path: media.value, name };
|
|
355
|
+
default:
|
|
356
|
+
return undefined;
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
export function verifySlackSignature(
|
|
361
|
+
signingSecret: string,
|
|
362
|
+
rawBody: string,
|
|
363
|
+
timestamp: string,
|
|
364
|
+
signature: string,
|
|
365
|
+
): boolean {
|
|
366
|
+
const now = Math.floor(Date.now() / 1000);
|
|
367
|
+
const ts = parseInt(timestamp, 10);
|
|
368
|
+
if (Number.isNaN(ts) || Math.abs(now - ts) > MAX_TIMESTAMP_DRIFT_SECONDS) {
|
|
369
|
+
return false;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
const baseString = `${SLACK_SIG_VERSION}:${timestamp}:${rawBody}`;
|
|
373
|
+
const hmac = createHmac('sha256', signingSecret).update(baseString).digest('hex');
|
|
374
|
+
const expected = `${SLACK_SIG_VERSION}=${hmac}`;
|
|
375
|
+
|
|
376
|
+
if (expected.length !== signature.length) return false;
|
|
377
|
+
return timingSafeEqual(Buffer.from(expected), Buffer.from(signature));
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
export async function readTextBody(
|
|
381
|
+
request: IncomingMessage,
|
|
382
|
+
options: { readonly limit?: number } = {},
|
|
383
|
+
): Promise<string> {
|
|
384
|
+
const limit = options.limit ?? 1_048_576;
|
|
385
|
+
const chunks: Buffer[] = [];
|
|
386
|
+
let size = 0;
|
|
387
|
+
for await (const chunk of request) {
|
|
388
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
389
|
+
size += buffer.length;
|
|
390
|
+
if (size > limit) {
|
|
391
|
+
request.destroy();
|
|
392
|
+
throw new Error(`Request body exceeds ${limit} bytes`);
|
|
393
|
+
}
|
|
394
|
+
chunks.push(buffer);
|
|
395
|
+
}
|
|
396
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
export function headerValue(
|
|
400
|
+
headers: IncomingMessage['headers'],
|
|
401
|
+
name: string,
|
|
402
|
+
): string {
|
|
403
|
+
const raw = headers[name.toLowerCase()];
|
|
404
|
+
if (Array.isArray(raw)) return raw[0] ?? '';
|
|
405
|
+
return raw ?? '';
|
|
406
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { buildNotice, mapNoticeParts, senderFromId, SLACK_NOTICE_PARTS_MAP } from '@zhin.js/core';
|
|
2
|
+
import type { EndpointEventEmitter } from 'zhin.js/adapter';
|
|
3
|
+
import { formatCompact, type getAdapterLogger } from '@zhin.js/logger';
|
|
4
|
+
import type { SlackEvent } from './protocol.js';
|
|
5
|
+
|
|
6
|
+
export function receiveSlackSideEvent(
|
|
7
|
+
emit: EndpointEventEmitter,
|
|
8
|
+
endpointKey: string,
|
|
9
|
+
configId: string,
|
|
10
|
+
event: SlackEvent,
|
|
11
|
+
logger: ReturnType<typeof getAdapterLogger>,
|
|
12
|
+
): void {
|
|
13
|
+
if (!emit) return;
|
|
14
|
+
const eventType = String(event.type ?? '');
|
|
15
|
+
if (!Object.prototype.hasOwnProperty.call(SLACK_NOTICE_PARTS_MAP, eventType)) return;
|
|
16
|
+
const record = event as Record<string, unknown>;
|
|
17
|
+
const parts = mapNoticeParts('slack', eventType);
|
|
18
|
+
const channel = typeof record.channel === 'string' ? record.channel : undefined;
|
|
19
|
+
const user = typeof record.user === 'string' ? record.user : undefined;
|
|
20
|
+
const sceneId = channel ?? user ?? configId;
|
|
21
|
+
const dedupeKey = [
|
|
22
|
+
eventType,
|
|
23
|
+
channel ?? '',
|
|
24
|
+
user ?? '',
|
|
25
|
+
String(record.ts ?? record.event_ts ?? ''),
|
|
26
|
+
].join(':');
|
|
27
|
+
void emit('notice.receive', buildNotice(record, {
|
|
28
|
+
$id: `slack:${dedupeKey}`,
|
|
29
|
+
$adapter: 'slack' as never,
|
|
30
|
+
$endpoint: configId,
|
|
31
|
+
$type: 'notice',
|
|
32
|
+
$scene_id: sceneId,
|
|
33
|
+
$scene_type: parts.scene_type,
|
|
34
|
+
$sub_type: parts.sub_type,
|
|
35
|
+
$actor: senderFromId(user),
|
|
36
|
+
$target: senderFromId(
|
|
37
|
+
typeof record.item_user === 'string' ? record.item_user : undefined,
|
|
38
|
+
),
|
|
39
|
+
$timestamp: toMillis(record.event_ts ?? record.ts),
|
|
40
|
+
})).catch((err) => {
|
|
41
|
+
logger.warn(formatCompact({
|
|
42
|
+
op: 'slack_side_event_failed',
|
|
43
|
+
endpoint: configId,
|
|
44
|
+
event: eventType,
|
|
45
|
+
error: err instanceof Error ? err.message : String(err),
|
|
46
|
+
}));
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function toMillis(time: unknown): number {
|
|
51
|
+
const value = Number(time);
|
|
52
|
+
if (!Number.isFinite(value) || value <= 0) return Date.now();
|
|
53
|
+
return value < 1e12 ? Math.round(value * 1000) : Math.round(value);
|
|
54
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { SlackMessageEvent } from './protocol.js';
|
|
2
|
+
|
|
3
|
+
const DEDUPE_TTL_MS = 60_000;
|
|
4
|
+
|
|
5
|
+
export interface SlackInboundFilterState {
|
|
6
|
+
seenInbound: Map<string, number>;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function createSlackInboundFilterState(): SlackInboundFilterState {
|
|
10
|
+
return { seenInbound: new Map() };
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function pruneSeen(state: SlackInboundFilterState, now: number): void {
|
|
14
|
+
if (state.seenInbound.size < 512) return;
|
|
15
|
+
for (const [key, at] of state.seenInbound) {
|
|
16
|
+
if (now - at > DEDUPE_TTL_MS) {
|
|
17
|
+
state.seenInbound.delete(key);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* 过滤不应进入 IM 管道的 Slack 入站消息。
|
|
24
|
+
* - 跳过 Bot 自身消息
|
|
25
|
+
* - 频道内 @Bot:只保留 app_mention,丢弃重复的 message 事件
|
|
26
|
+
* - channel:ts 去重(message + app_mention 等同一条)
|
|
27
|
+
*/
|
|
28
|
+
export function shouldDropSlackInboundMessage(
|
|
29
|
+
event: SlackMessageEvent,
|
|
30
|
+
state: SlackInboundFilterState,
|
|
31
|
+
botUserId?: string,
|
|
32
|
+
): boolean {
|
|
33
|
+
if (event.subtype === 'bot_message' || event.subtype === 'message_changed') {
|
|
34
|
+
return true;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
if (event.bot_id) return true;
|
|
38
|
+
if (botUserId && event.user === botUserId) return true;
|
|
39
|
+
|
|
40
|
+
const channelType = event.channel_type ?? 'channel';
|
|
41
|
+
const text = event.text ?? '';
|
|
42
|
+
|
|
43
|
+
if (event.type === 'message' && channelType !== 'im' && botUserId) {
|
|
44
|
+
if (text.includes(`<@${botUserId}>`)) {
|
|
45
|
+
return true;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (!event.channel || !event.ts) return true;
|
|
50
|
+
|
|
51
|
+
const key = `${event.channel}:${event.ts}`;
|
|
52
|
+
const now = Date.now();
|
|
53
|
+
const seenAt = state.seenInbound.get(key);
|
|
54
|
+
if (seenAt != null && now - seenAt < DEDUPE_TTL_MS) {
|
|
55
|
+
return true;
|
|
56
|
+
}
|
|
57
|
+
state.seenInbound.set(key, now);
|
|
58
|
+
pruneSeen(state, now);
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** Slack 消息定位:channel + ts(Activity Feedback / recall / reaction 共用) */
|
|
2
|
+
|
|
3
|
+
export function formatSlackMessageRef(channel: string, ts: string): string {
|
|
4
|
+
return `${channel}:${ts}`;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function parseSlackMessageRef(ref: string): { channel: string; ts: string } | null {
|
|
8
|
+
const sep = ref.indexOf(':');
|
|
9
|
+
if (sep <= 0) return null;
|
|
10
|
+
const channel = ref.slice(0, sep);
|
|
11
|
+
const ts = ref.slice(sep + 1);
|
|
12
|
+
if (!channel || !ts) return null;
|
|
13
|
+
return { channel, ts };
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function slackMessageTs(ref: string): string {
|
|
17
|
+
return parseSlackMessageRef(ref)?.ts ?? ref;
|
|
18
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Slack outbound — chat.postMessage + Block Kit + files.uploadV2
|
|
3
|
+
*/
|
|
4
|
+
import type { Logger } from '@zhin.js/logger';
|
|
5
|
+
import { markdownToMrkdwn, mrkdwnToPlainFallback, splitMrkdwnText } from './markdown-to-mrkdwn.js';
|
|
6
|
+
import { formatOutboundWire, keyboardToBlockKitBlocks } from './protocol.js';
|
|
7
|
+
|
|
8
|
+
export interface SlackOutboundResult {
|
|
9
|
+
ts: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface SlackSendOptions {
|
|
13
|
+
channel: string;
|
|
14
|
+
threadTs?: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface SlackChatClient {
|
|
18
|
+
chat: {
|
|
19
|
+
postMessage(opts: Record<string, unknown>): Promise<{ ts?: string }>;
|
|
20
|
+
update(opts: Record<string, unknown>): Promise<unknown>;
|
|
21
|
+
};
|
|
22
|
+
filesUploadV2?(opts: Record<string, unknown>): Promise<unknown>;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const SLACK_MAX_BLOCKS_PER_MESSAGE = 48;
|
|
26
|
+
|
|
27
|
+
export async function sendSlackContent(
|
|
28
|
+
client: SlackChatClient,
|
|
29
|
+
content: unknown,
|
|
30
|
+
opts: SlackSendOptions,
|
|
31
|
+
logger: Logger,
|
|
32
|
+
): Promise<SlackOutboundResult> {
|
|
33
|
+
const wire = formatOutboundWire(content);
|
|
34
|
+
const blocks = [...wire.blocks];
|
|
35
|
+
const textDelivery = applyTextMrkdwnBlocks(wire.text, blocks);
|
|
36
|
+
|
|
37
|
+
for (const pf of wire.files) {
|
|
38
|
+
try {
|
|
39
|
+
await uploadFile(client, opts.channel, pf, opts.threadTs);
|
|
40
|
+
} catch (e) {
|
|
41
|
+
logger.error('Failed to upload file:', e);
|
|
42
|
+
throw e;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
return postSlackMessage(client, {
|
|
47
|
+
channel: opts.channel,
|
|
48
|
+
threadTs: opts.threadTs,
|
|
49
|
+
blocks,
|
|
50
|
+
attachments: wire.attachments,
|
|
51
|
+
fallbackText: textDelivery.fallbackText,
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export async function editSlackContent(
|
|
56
|
+
client: SlackChatClient,
|
|
57
|
+
channel: string,
|
|
58
|
+
ts: string,
|
|
59
|
+
content: unknown,
|
|
60
|
+
): Promise<void> {
|
|
61
|
+
const wire = formatOutboundWire(content);
|
|
62
|
+
const blocks = [...wire.blocks];
|
|
63
|
+
const textDelivery = applyTextMrkdwnBlocks(wire.text, blocks);
|
|
64
|
+
const payloadBlocks = blocks.slice(0, SLACK_MAX_BLOCKS_PER_MESSAGE);
|
|
65
|
+
|
|
66
|
+
const updateOpts: Record<string, unknown> = {
|
|
67
|
+
channel,
|
|
68
|
+
ts,
|
|
69
|
+
text: textDelivery.fallbackText || ' ',
|
|
70
|
+
};
|
|
71
|
+
if (payloadBlocks.length > 0) updateOpts.blocks = payloadBlocks;
|
|
72
|
+
await client.chat.update(updateOpts);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function applyTextMrkdwnBlocks(
|
|
76
|
+
textContent: string,
|
|
77
|
+
blocks: Record<string, unknown>[],
|
|
78
|
+
): { fallbackText: string } {
|
|
79
|
+
const trimmed = textContent.trim();
|
|
80
|
+
if (!trimmed) return { fallbackText: '' };
|
|
81
|
+
|
|
82
|
+
const mrkdwn = markdownToMrkdwn(trimmed);
|
|
83
|
+
const sections = splitMrkdwnText(mrkdwn).map((chunk) => ({
|
|
84
|
+
type: 'section',
|
|
85
|
+
text: { type: 'mrkdwn', text: chunk },
|
|
86
|
+
}));
|
|
87
|
+
|
|
88
|
+
if (blocks.length > 0) {
|
|
89
|
+
blocks.unshift(...sections);
|
|
90
|
+
return { fallbackText: '' };
|
|
91
|
+
}
|
|
92
|
+
blocks.push(...sections);
|
|
93
|
+
return { fallbackText: mrkdwnToPlainFallback(mrkdwn) };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async function postSlackMessage(
|
|
97
|
+
client: SlackChatClient,
|
|
98
|
+
opts: {
|
|
99
|
+
channel: string;
|
|
100
|
+
threadTs?: string;
|
|
101
|
+
blocks: Record<string, unknown>[];
|
|
102
|
+
attachments: Record<string, unknown>[];
|
|
103
|
+
fallbackText: string;
|
|
104
|
+
},
|
|
105
|
+
): Promise<SlackOutboundResult> {
|
|
106
|
+
const { channel, blocks, attachments, fallbackText } = opts;
|
|
107
|
+
let threadTs = opts.threadTs;
|
|
108
|
+
let firstTs = '';
|
|
109
|
+
|
|
110
|
+
if (blocks.length === 0) {
|
|
111
|
+
const result = await client.chat.postMessage({
|
|
112
|
+
channel,
|
|
113
|
+
text: fallbackText || 'Message',
|
|
114
|
+
...(threadTs ? { thread_ts: threadTs } : {}),
|
|
115
|
+
...(attachments.length > 0 ? { attachments } : {}),
|
|
116
|
+
});
|
|
117
|
+
return { ts: requireMessageTimestamp(result) };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
for (let offset = 0; offset < blocks.length; offset += SLACK_MAX_BLOCKS_PER_MESSAGE) {
|
|
121
|
+
const chunk = blocks.slice(offset, offset + SLACK_MAX_BLOCKS_PER_MESSAGE);
|
|
122
|
+
const result = await client.chat.postMessage({
|
|
123
|
+
channel,
|
|
124
|
+
text: offset === 0 ? (fallbackText || ' ') : ' ',
|
|
125
|
+
blocks: chunk,
|
|
126
|
+
...(threadTs ? { thread_ts: threadTs } : {}),
|
|
127
|
+
...(offset === 0 && attachments.length > 0 ? { attachments } : {}),
|
|
128
|
+
});
|
|
129
|
+
const ts = requireMessageTimestamp(result);
|
|
130
|
+
if (!firstTs) firstTs = ts;
|
|
131
|
+
if (!threadTs) threadTs = ts;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return { ts: firstTs };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function requireMessageTimestamp(result: { ts?: string } | null | undefined): string {
|
|
138
|
+
if (typeof result?.ts !== 'string' || !result.ts.trim()) {
|
|
139
|
+
throw new Error('Slack chat.postMessage returned no valid ts; delivery is unconfirmed');
|
|
140
|
+
}
|
|
141
|
+
return result.ts;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async function uploadFile(
|
|
145
|
+
client: SlackChatClient,
|
|
146
|
+
channel: string,
|
|
147
|
+
file: { buffer?: Buffer; url?: string; path?: string; name?: string },
|
|
148
|
+
threadTs?: string,
|
|
149
|
+
): Promise<void> {
|
|
150
|
+
if (!client.filesUploadV2) throw new Error('Slack client does not support file uploads');
|
|
151
|
+
let buffer = file.buffer;
|
|
152
|
+
if (!buffer && file.path) {
|
|
153
|
+
const { readFile } = await import('node:fs/promises');
|
|
154
|
+
buffer = await readFile(file.path);
|
|
155
|
+
}
|
|
156
|
+
if (!buffer && file.url) {
|
|
157
|
+
const res = await fetch(file.url);
|
|
158
|
+
if (!res.ok) throw new Error(`fetch ${file.url}: ${res.status}`);
|
|
159
|
+
buffer = Buffer.from(await res.arrayBuffer());
|
|
160
|
+
}
|
|
161
|
+
if (!buffer) throw new Error('Slack file contains no uploadable content');
|
|
162
|
+
|
|
163
|
+
await client.filesUploadV2(
|
|
164
|
+
threadTs
|
|
165
|
+
? { channel_id: channel, file: buffer, filename: file.name ?? 'file', thread_ts: threadTs }
|
|
166
|
+
: { channel_id: channel, file: buffer, filename: file.name ?? 'file' },
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export { keyboardToBlockKitBlocks };
|