@zhin.js/adapter-dingtalk 1.0.81 → 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 +709 -3
- package/PERMITS.md +19 -0
- package/README.md +67 -333
- package/adapters/dingtalk/index.js +33 -0
- package/adapters/dingtalk/index.ts +38 -0
- package/agents/dingtalk/agent.json +20 -0
- package/agents/dingtalk/boundaries.md +3 -0
- package/agents/dingtalk/conventions.md +3 -0
- package/agents/dingtalk/skills/dingtalk/SKILL.md +26 -0
- package/agents/dingtalk/skills/dingtalk/tools/add_chat_members/index.js +19 -0
- package/agents/dingtalk/skills/dingtalk/tools/add_chat_members/index.ts +20 -0
- package/agents/dingtalk/skills/dingtalk/tools/create_chat/index.js +20 -0
- package/agents/dingtalk/skills/dingtalk/tools/create_chat/index.ts +21 -0
- package/agents/dingtalk/skills/dingtalk/tools/dept_info/index.js +15 -0
- package/agents/dingtalk/skills/dingtalk/tools/dept_info/index.ts +15 -0
- package/agents/dingtalk/skills/dingtalk/tools/get_dept_users/index.js +16 -0
- package/agents/dingtalk/skills/dingtalk/tools/get_dept_users/index.ts +16 -0
- package/agents/dingtalk/skills/dingtalk/tools/get_user/index.js +15 -0
- package/agents/dingtalk/skills/dingtalk/tools/get_user/index.ts +15 -0
- package/agents/dingtalk/skills/dingtalk/tools/list_departments/index.js +16 -0
- package/agents/dingtalk/skills/dingtalk/tools/list_departments/index.ts +16 -0
- package/agents/dingtalk/skills/dingtalk/tools/send_work_notice/index.js +18 -0
- package/agents/dingtalk/skills/dingtalk/tools/send_work_notice/index.ts +18 -0
- package/agents/dingtalk/skills/dingtalk/tools/update_chat/index.js +29 -0
- package/agents/dingtalk/skills/dingtalk/tools/update_chat/index.ts +25 -0
- package/agents/dingtalk/system.md +3 -0
- package/commands/dingtalk/endpoint/add/[id]/index.js +3 -0
- package/commands/dingtalk/endpoint/add/[id]/index.ts +3 -0
- package/commands/dingtalk/endpoint/definition.js +19 -0
- package/commands/dingtalk/endpoint/definition.ts +19 -0
- package/commands/dingtalk/endpoint/list/index.js +3 -0
- package/commands/dingtalk/endpoint/list/index.ts +3 -0
- package/commands/dingtalk/endpoint/remove/[id]/index.js +3 -0
- package/commands/dingtalk/endpoint/remove/[id]/index.ts +3 -0
- package/lib/client.d.ts +12 -0
- package/lib/client.js +2 -0
- package/lib/dingtalk-runtime-state.d.ts +1 -0
- package/lib/dingtalk-runtime-state.js +6 -0
- package/lib/endpoint.d.ts +72 -0
- package/lib/endpoint.js +353 -0
- package/lib/index.d.ts +5 -15
- package/lib/index.js +5 -214
- package/lib/platform-permit.d.ts +14 -0
- package/lib/platform-permit.js +33 -0
- package/lib/protocol.d.ts +130 -0
- package/lib/protocol.js +264 -0
- package/lib/webhook.d.ts +13 -0
- package/lib/webhook.js +47 -0
- package/package.json +76 -19
- package/plugin.js +19 -0
- package/schema.json +97 -0
- package/src/client.ts +16 -0
- package/src/dingtalk-runtime-state.ts +7 -0
- package/src/endpoint.ts +439 -0
- package/src/index.ts +44 -228
- package/src/platform-permit.ts +48 -0
- package/src/protocol.ts +377 -0
- package/src/webhook.ts +75 -0
- package/lib/adapter.d.ts +0 -16
- package/lib/adapter.d.ts.map +0 -1
- package/lib/adapter.js +0 -37
- package/lib/adapter.js.map +0 -1
- package/lib/bot.d.ts +0 -46
- package/lib/bot.d.ts.map +0 -1
- package/lib/bot.js +0 -539
- 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 -58
- package/lib/types.d.ts.map +0 -1
- package/lib/types.js +0 -5
- package/lib/types.js.map +0 -1
- package/plugin.yml +0 -3
- package/skills/dingtalk/SKILL.md +0 -91
- package/src/adapter.ts +0 -44
- package/src/bot.ts +0 -590
- package/src/types.ts +0 -56
package/src/index.ts
CHANGED
|
@@ -1,228 +1,44 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
const disposers: (() => void)[] = groupTools.map(t => toolService.addTool(t, plugin.name));
|
|
46
|
-
|
|
47
|
-
disposers.push(toolService.addTool({
|
|
48
|
-
name: 'dingtalk_get_user',
|
|
49
|
-
description: '获取钉钉用户信息',
|
|
50
|
-
parameters: {
|
|
51
|
-
type: 'object',
|
|
52
|
-
properties: {
|
|
53
|
-
bot: { type: 'string', description: 'Bot 名称' },
|
|
54
|
-
user_id: { type: 'string', description: '用户 ID' },
|
|
55
|
-
},
|
|
56
|
-
required: ['bot', 'user_id'],
|
|
57
|
-
},
|
|
58
|
-
platforms: ['dingtalk'],
|
|
59
|
-
tags: ['dingtalk'],
|
|
60
|
-
execute: async (args: Record<string, any>) => {
|
|
61
|
-
const bot = dingtalk.bots.get(args.bot);
|
|
62
|
-
if (!bot) throw new Error(`Bot ${args.bot} 不存在`);
|
|
63
|
-
return await bot.getUserInfo(args.user_id);
|
|
64
|
-
},
|
|
65
|
-
}, plugin.name));
|
|
66
|
-
|
|
67
|
-
disposers.push(toolService.addTool({
|
|
68
|
-
name: 'dingtalk_get_dept_users',
|
|
69
|
-
description: '获取钉钉部门用户列表',
|
|
70
|
-
parameters: {
|
|
71
|
-
type: 'object',
|
|
72
|
-
properties: {
|
|
73
|
-
bot: { type: 'string', description: 'Bot 名称' },
|
|
74
|
-
dept_id: { type: 'string', description: '部门 ID' },
|
|
75
|
-
},
|
|
76
|
-
required: ['bot', 'dept_id'],
|
|
77
|
-
},
|
|
78
|
-
platforms: ['dingtalk'],
|
|
79
|
-
tags: ['dingtalk'],
|
|
80
|
-
execute: async (args: Record<string, any>) => {
|
|
81
|
-
const bot = dingtalk.bots.get(args.bot);
|
|
82
|
-
if (!bot) throw new Error(`Bot ${args.bot} 不存在`);
|
|
83
|
-
const users = await bot.getDepartmentUsers(args.dept_id);
|
|
84
|
-
return { users, count: users.length };
|
|
85
|
-
},
|
|
86
|
-
}, plugin.name));
|
|
87
|
-
|
|
88
|
-
disposers.push(toolService.addTool({
|
|
89
|
-
name: 'dingtalk_list_departments',
|
|
90
|
-
description: '获取钉钉部门列表',
|
|
91
|
-
parameters: {
|
|
92
|
-
type: 'object',
|
|
93
|
-
properties: {
|
|
94
|
-
bot: { type: 'string', description: 'Bot 名称' },
|
|
95
|
-
dept_id: { type: 'string', description: '父部门 ID,默认 1(根部门)' },
|
|
96
|
-
},
|
|
97
|
-
required: ['bot'],
|
|
98
|
-
},
|
|
99
|
-
platforms: ['dingtalk'],
|
|
100
|
-
tags: ['dingtalk'],
|
|
101
|
-
execute: async (args: Record<string, any>) => {
|
|
102
|
-
const bot = dingtalk.bots.get(args.bot);
|
|
103
|
-
if (!bot) throw new Error(`Bot ${args.bot} 不存在`);
|
|
104
|
-
const departments = await bot.getDepartmentList(args.dept_id || '1');
|
|
105
|
-
return { departments, count: departments.length };
|
|
106
|
-
},
|
|
107
|
-
}, plugin.name));
|
|
108
|
-
|
|
109
|
-
disposers.push(toolService.addTool({
|
|
110
|
-
name: 'dingtalk_send_work_notice',
|
|
111
|
-
description: '向指定用户发送钉钉工作通知',
|
|
112
|
-
parameters: {
|
|
113
|
-
type: 'object',
|
|
114
|
-
properties: {
|
|
115
|
-
bot: { type: 'string', description: 'Bot 名称' },
|
|
116
|
-
user_ids: { type: 'string', description: '用户 ID 列表,逗号分隔' },
|
|
117
|
-
content: { type: 'string', description: '通知内容' },
|
|
118
|
-
},
|
|
119
|
-
required: ['bot', 'user_ids', 'content'],
|
|
120
|
-
},
|
|
121
|
-
platforms: ['dingtalk'],
|
|
122
|
-
tags: ['dingtalk'],
|
|
123
|
-
execute: async (args: Record<string, any>) => {
|
|
124
|
-
const bot = dingtalk.bots.get(args.bot);
|
|
125
|
-
if (!bot) throw new Error(`Bot ${args.bot} 不存在`);
|
|
126
|
-
const msgContent = { msgtype: 'text', text: { content: args.content } };
|
|
127
|
-
const success = await bot.sendWorkNotice(args.user_ids.split(','), msgContent);
|
|
128
|
-
return { success, message: success ? '工作通知已发送' : '发送失败' };
|
|
129
|
-
},
|
|
130
|
-
}, plugin.name));
|
|
131
|
-
|
|
132
|
-
disposers.push(toolService.addTool({
|
|
133
|
-
name: 'dingtalk_create_chat',
|
|
134
|
-
description: '创建钉钉群聊',
|
|
135
|
-
parameters: {
|
|
136
|
-
type: 'object',
|
|
137
|
-
properties: {
|
|
138
|
-
bot: { type: 'string', description: 'Bot 名称' },
|
|
139
|
-
name: { type: 'string', description: '群名' },
|
|
140
|
-
owner: { type: 'string', description: '群主用户 ID' },
|
|
141
|
-
members: { type: 'string', description: '成员用户 ID 列表,逗号分隔' },
|
|
142
|
-
},
|
|
143
|
-
required: ['bot', 'name', 'owner', 'members'],
|
|
144
|
-
},
|
|
145
|
-
platforms: ['dingtalk'],
|
|
146
|
-
tags: ['dingtalk'],
|
|
147
|
-
execute: async (args: Record<string, any>) => {
|
|
148
|
-
const bot = dingtalk.bots.get(args.bot);
|
|
149
|
-
if (!bot) throw new Error(`Bot ${args.bot} 不存在`);
|
|
150
|
-
const chatId = await bot.createChat(args.name, args.owner, args.members.split(','));
|
|
151
|
-
return { success: !!chatId, chat_id: chatId, message: chatId ? `群聊创建成功: ${chatId}` : '创建失败' };
|
|
152
|
-
},
|
|
153
|
-
}, plugin.name));
|
|
154
|
-
|
|
155
|
-
disposers.push(toolService.addTool({
|
|
156
|
-
name: 'dingtalk_add_chat_members',
|
|
157
|
-
description: '向钉钉群聊添加成员',
|
|
158
|
-
parameters: {
|
|
159
|
-
type: 'object',
|
|
160
|
-
properties: {
|
|
161
|
-
bot: { type: 'string', description: 'Bot 名称' },
|
|
162
|
-
chat_id: { type: 'string', description: '群聊 ID' },
|
|
163
|
-
user_ids: { type: 'string', description: '要添加的用户 ID 列表,逗号分隔' },
|
|
164
|
-
},
|
|
165
|
-
required: ['bot', 'chat_id', 'user_ids'],
|
|
166
|
-
},
|
|
167
|
-
platforms: ['dingtalk'],
|
|
168
|
-
tags: ['dingtalk'],
|
|
169
|
-
execute: async (args: Record<string, any>) => {
|
|
170
|
-
const bot = dingtalk.bots.get(args.bot);
|
|
171
|
-
if (!bot) throw new Error(`Bot ${args.bot} 不存在`);
|
|
172
|
-
const success = await bot.updateChat(args.chat_id, { add_useridlist: args.user_ids.split(',') });
|
|
173
|
-
return { success, message: success ? '成员添加成功' : '添加失败' };
|
|
174
|
-
},
|
|
175
|
-
}, plugin.name));
|
|
176
|
-
|
|
177
|
-
disposers.push(toolService.addTool({
|
|
178
|
-
name: 'dingtalk_dept_info',
|
|
179
|
-
description: '获取钉钉部门详细信息',
|
|
180
|
-
parameters: {
|
|
181
|
-
type: 'object',
|
|
182
|
-
properties: {
|
|
183
|
-
bot: { type: 'string', description: 'Bot 名称' },
|
|
184
|
-
dept_id: { type: 'string', description: '部门 ID' },
|
|
185
|
-
},
|
|
186
|
-
required: ['bot', 'dept_id'],
|
|
187
|
-
},
|
|
188
|
-
platforms: ['dingtalk'],
|
|
189
|
-
tags: ['dingtalk'],
|
|
190
|
-
execute: async (args: Record<string, any>) => {
|
|
191
|
-
const bot = dingtalk.bots.get(args.bot);
|
|
192
|
-
if (!bot) throw new Error(`Bot ${args.bot} 不存在`);
|
|
193
|
-
return await bot.getDepartmentInfo(Number(args.dept_id));
|
|
194
|
-
},
|
|
195
|
-
}, plugin.name));
|
|
196
|
-
|
|
197
|
-
disposers.push(toolService.addTool({
|
|
198
|
-
name: 'dingtalk_update_chat',
|
|
199
|
-
description: '更新钉钉群聊设置(改名、换群主、增减成员)',
|
|
200
|
-
parameters: {
|
|
201
|
-
type: 'object',
|
|
202
|
-
properties: {
|
|
203
|
-
bot: { type: 'string', description: 'Bot 名称' },
|
|
204
|
-
chat_id: { type: 'string', description: '群聊 ID' },
|
|
205
|
-
name: { type: 'string', description: '新群名(可选)' },
|
|
206
|
-
owner: { type: 'string', description: '新群主 userId(可选)' },
|
|
207
|
-
add_members: { type: 'string', description: '要添加的成员 userId,逗号分隔(可选)' },
|
|
208
|
-
remove_members: { type: 'string', description: '要移除的成员 userId,逗号分隔(可选)' },
|
|
209
|
-
},
|
|
210
|
-
required: ['bot', 'chat_id'],
|
|
211
|
-
},
|
|
212
|
-
platforms: ['dingtalk'],
|
|
213
|
-
tags: ['dingtalk'],
|
|
214
|
-
execute: async (args: Record<string, any>) => {
|
|
215
|
-
const bot = dingtalk.bots.get(args.bot);
|
|
216
|
-
if (!bot) throw new Error(`Bot ${args.bot} 不存在`);
|
|
217
|
-
const options: any = {};
|
|
218
|
-
if (args.name) options.name = args.name;
|
|
219
|
-
if (args.owner) options.owner = args.owner;
|
|
220
|
-
if (args.add_members) options.add_useridlist = args.add_members.split(',').map((s: string) => s.trim());
|
|
221
|
-
if (args.remove_members) options.del_useridlist = args.remove_members.split(',').map((s: string) => s.trim());
|
|
222
|
-
await bot.updateChat(args.chat_id, options);
|
|
223
|
-
return { success: true, message: '群聊设置已更新' };
|
|
224
|
-
},
|
|
225
|
-
}, plugin.name));
|
|
226
|
-
|
|
227
|
-
return () => disposers.forEach(d => d());
|
|
228
|
-
});
|
|
1
|
+
export {
|
|
2
|
+
dingtalkInboundConversation,
|
|
3
|
+
formatInboundContent,
|
|
4
|
+
formatOutboundBody,
|
|
5
|
+
generateMessageId,
|
|
6
|
+
headerValue,
|
|
7
|
+
normalizeWebhookPath,
|
|
8
|
+
readTextBody,
|
|
9
|
+
resolveChatType,
|
|
10
|
+
resolveDingTalkConfig,
|
|
11
|
+
resolveSender,
|
|
12
|
+
verifySignature,
|
|
13
|
+
type AccessToken,
|
|
14
|
+
type DingTalkEndpointConfig,
|
|
15
|
+
type DingTalkApiResponse,
|
|
16
|
+
type DingTalkEvent,
|
|
17
|
+
type DingTalkMessage,
|
|
18
|
+
type DingTalkSendBody,
|
|
19
|
+
type DingTalkWireSegment,
|
|
20
|
+
type ResolvedDingTalkConfig,
|
|
21
|
+
} from './protocol.js';
|
|
22
|
+
|
|
23
|
+
export {
|
|
24
|
+
DingTalkClient,
|
|
25
|
+
DingTalkEndpoint,
|
|
26
|
+
type DingTalkClientApi,
|
|
27
|
+
type DingTalkEndpointOptions,
|
|
28
|
+
type DingTalkFetch,
|
|
29
|
+
} from './endpoint.js';
|
|
30
|
+
|
|
31
|
+
export {
|
|
32
|
+
registerDingTalkWebhookRoutes,
|
|
33
|
+
handleDingTalkWebhookRequest,
|
|
34
|
+
type DingTalkWebhookHandler,
|
|
35
|
+
} from './webhook.js';
|
|
36
|
+
|
|
37
|
+
export { dingtalkClient, type DingtalkClientEventMap } from './client.js';
|
|
38
|
+
|
|
39
|
+
export {
|
|
40
|
+
checkDingtalkPlatformPermit,
|
|
41
|
+
dingtalkGroupPermitResolver,
|
|
42
|
+
normalizeDingtalkSenderForPermit,
|
|
43
|
+
platformPermit,
|
|
44
|
+
} from './platform-permit.js';
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 钉钉 DingTalk platform permit
|
|
3
|
+
*/
|
|
4
|
+
import type { PermissionSubject } from '@zhin.js/permission';
|
|
5
|
+
|
|
6
|
+
const ADAPTER = 'dingtalk';
|
|
7
|
+
|
|
8
|
+
export function platformPermit(perm: string): string {
|
|
9
|
+
return `platform(${ADAPTER},${perm})`;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const FACTORY_PERM_MAP: Record<string, string> = {
|
|
13
|
+
scene_admin: 'chat_admin',
|
|
14
|
+
scene_owner: 'chat_owner',
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export function dingtalkGroupPermitResolver(logicalPerm: string): string {
|
|
18
|
+
return platformPermit(FACTORY_PERM_MAP[logicalPerm] ?? logicalPerm);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function normalizeDingtalkSenderForPermit(input: {
|
|
22
|
+
isOwner?: boolean;
|
|
23
|
+
isAdmin?: boolean;
|
|
24
|
+
}): { role?: string; permissions?: string[] } {
|
|
25
|
+
if (input.isOwner) {
|
|
26
|
+
return { role: 'owner', permissions: ['chat_owner', 'chat_admin'] };
|
|
27
|
+
}
|
|
28
|
+
if (input.isAdmin) {
|
|
29
|
+
return { role: 'admin', permissions: ['chat_admin'] };
|
|
30
|
+
}
|
|
31
|
+
return { role: 'member', permissions: [] };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function checkDingtalkPlatformPermit(perm: string, subject: PermissionSubject): boolean {
|
|
35
|
+
const role = subject.sender?.role?.[0];
|
|
36
|
+
const permissions = subject.sender?.permissions ?? [];
|
|
37
|
+
const has = (t: string) => permissions.includes(t);
|
|
38
|
+
|
|
39
|
+
switch (perm) {
|
|
40
|
+
case 'chat_owner':
|
|
41
|
+
return role === 'owner' || has('chat_owner');
|
|
42
|
+
case 'chat_admin':
|
|
43
|
+
return role === 'owner' || role === 'admin' || has('chat_admin') || has('chat_owner');
|
|
44
|
+
default:
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
package/src/protocol.ts
ADDED
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DingTalk protocol helpers — no legacy Adapter/Endpoint / segment-mapper.
|
|
3
|
+
* Canonicalization is owned by gateway/core before endpoint.send.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { createHmac, timingSafeEqual } from 'node:crypto';
|
|
7
|
+
import type { IncomingMessage } from 'node:http';
|
|
8
|
+
|
|
9
|
+
import { isMediaRef, type ConversationRef } from '@zhin.js/im-contract';
|
|
10
|
+
import { formatCompact, getLogger } from '@zhin.js/logger';
|
|
11
|
+
|
|
12
|
+
const logger = getLogger('dingtalk');
|
|
13
|
+
|
|
14
|
+
/** One endpoint config after AdapterIndex expands `plugins.<instanceKey>.endpoints`. */
|
|
15
|
+
export interface DingTalkEndpointConfig {
|
|
16
|
+
readonly id: string;
|
|
17
|
+
readonly appKey: string;
|
|
18
|
+
readonly appSecret: string;
|
|
19
|
+
readonly webhookPath?: string;
|
|
20
|
+
readonly robotCode?: string;
|
|
21
|
+
readonly apiBaseUrl?: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface ResolvedDingTalkConfig {
|
|
25
|
+
readonly context: 'dingtalk';
|
|
26
|
+
readonly id: string;
|
|
27
|
+
readonly appKey: string;
|
|
28
|
+
readonly appSecret: string;
|
|
29
|
+
readonly webhookPath: string;
|
|
30
|
+
readonly robotCode?: string;
|
|
31
|
+
readonly apiBaseUrl: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface DingTalkMessage {
|
|
35
|
+
readonly msgtype?: string;
|
|
36
|
+
readonly text?: { readonly content?: string };
|
|
37
|
+
readonly msgId?: string;
|
|
38
|
+
readonly createAt?: number;
|
|
39
|
+
readonly conversationType?: string;
|
|
40
|
+
readonly conversationId?: string;
|
|
41
|
+
readonly senderId?: string;
|
|
42
|
+
readonly senderNick?: string;
|
|
43
|
+
readonly senderCorpId?: string;
|
|
44
|
+
readonly sessionWebhook?: string;
|
|
45
|
+
readonly chatbotCorpId?: string;
|
|
46
|
+
readonly chatbotUserId?: string;
|
|
47
|
+
readonly isAdmin?: boolean;
|
|
48
|
+
readonly senderStaffId?: string;
|
|
49
|
+
readonly atUsers?: ReadonlyArray<{ readonly dingtalkId?: string; readonly staffId?: string }>;
|
|
50
|
+
readonly content?: Record<string, unknown>;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface DingTalkEvent extends DingTalkMessage {
|
|
54
|
+
readonly [key: string]: unknown;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* 钉钉回调消息 @ 机器人判定:机器人被 @ 时回调带 `isInAtList: true`;
|
|
59
|
+
* 部分回调形态的 `atUserIds` / `atUsers[].dingtalkId` 会包含机器人 robotCode(来自配置)。
|
|
60
|
+
* 两者都不满足则不标注。
|
|
61
|
+
*/
|
|
62
|
+
export function isDingtalkBotMentioned(event: DingTalkMessage, robotCode?: string): boolean {
|
|
63
|
+
const extra = event as DingTalkMessage & {
|
|
64
|
+
readonly isInAtList?: unknown;
|
|
65
|
+
readonly atUserIds?: unknown;
|
|
66
|
+
};
|
|
67
|
+
if (extra.isInAtList === true) return true;
|
|
68
|
+
if (!robotCode) return false;
|
|
69
|
+
if (Array.isArray(extra.atUserIds) && extra.atUserIds.some((id) => String(id) === robotCode)) {
|
|
70
|
+
return true;
|
|
71
|
+
}
|
|
72
|
+
return (event.atUsers ?? []).some((user) => user.dingtalkId === robotCode);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface AccessToken {
|
|
76
|
+
token: string;
|
|
77
|
+
expires_in: number;
|
|
78
|
+
timestamp: number;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export interface DingTalkApiResponse {
|
|
82
|
+
readonly errcode: number;
|
|
83
|
+
readonly errmsg?: string;
|
|
84
|
+
readonly access_token?: string;
|
|
85
|
+
readonly expires_in?: number;
|
|
86
|
+
readonly msgId?: string;
|
|
87
|
+
readonly chatid?: string;
|
|
88
|
+
readonly result?: unknown;
|
|
89
|
+
readonly chat_info?: unknown;
|
|
90
|
+
readonly [key: string]: unknown;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export interface DingTalkWireSegment {
|
|
94
|
+
readonly type: string;
|
|
95
|
+
readonly data?: Record<string, unknown>;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export interface DingTalkSendBody {
|
|
99
|
+
readonly msgtype: string;
|
|
100
|
+
readonly text?: { readonly content: string };
|
|
101
|
+
readonly picture?: { readonly picURL: string };
|
|
102
|
+
readonly markdown?: { readonly title: string; readonly text: string };
|
|
103
|
+
readonly link?: {
|
|
104
|
+
readonly title: string;
|
|
105
|
+
readonly text: string;
|
|
106
|
+
readonly messageUrl?: string;
|
|
107
|
+
readonly picUrl?: string;
|
|
108
|
+
};
|
|
109
|
+
readonly at?: { readonly atUserIds: string[]; readonly isAtAll: boolean };
|
|
110
|
+
readonly robotCode?: string;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export function resolveDingTalkConfig(config: DingTalkEndpointConfig): ResolvedDingTalkConfig {
|
|
114
|
+
const id = requiredEndpointField(config.id, 'id');
|
|
115
|
+
const appKey = requiredEndpointField(config.appKey, 'appKey');
|
|
116
|
+
const appSecret = requiredEndpointField(config.appSecret, 'appSecret');
|
|
117
|
+
const webhookPath = normalizeWebhookPath(config.webhookPath ?? '/dingtalk/webhook');
|
|
118
|
+
const apiBaseUrl = (config.apiBaseUrl ?? 'https://oapi.dingtalk.com').replace(/\/$/, '');
|
|
119
|
+
const robotCode = config.robotCode;
|
|
120
|
+
return {
|
|
121
|
+
context: 'dingtalk',
|
|
122
|
+
id,
|
|
123
|
+
appKey,
|
|
124
|
+
appSecret,
|
|
125
|
+
webhookPath,
|
|
126
|
+
...(robotCode ? { robotCode } : {}),
|
|
127
|
+
apiBaseUrl,
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function requiredEndpointField(
|
|
132
|
+
value: unknown,
|
|
133
|
+
field: 'id' | 'appKey' | 'appSecret',
|
|
134
|
+
): string {
|
|
135
|
+
if (typeof value !== 'string' || !value.trim()) {
|
|
136
|
+
throw new TypeError(`DingTalk endpoint requires a non-empty ${field}`);
|
|
137
|
+
}
|
|
138
|
+
return value.trim();
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function normalizeWebhookPath(path: string): string {
|
|
142
|
+
const trimmed = path.trim() || '/dingtalk/webhook';
|
|
143
|
+
return trimmed.startsWith('/') ? trimmed : `/${trimmed}`;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function resolveChatType(conversationType?: string): 'group' | 'private' {
|
|
147
|
+
return conversationType === '2' ? 'group' : 'private';
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* 入站归一化 → ConversationRef:`conversationType: '2'` 为群会话(kind 'group'),
|
|
152
|
+
* 其余为单聊(kind 'private');会话原生 id 取 conversationId,缺省回退 senderId。
|
|
153
|
+
* 钉钉无 guild/频道容器概念,不产生 parent。
|
|
154
|
+
*/
|
|
155
|
+
export function dingtalkInboundConversation(endpointKey: string, msg: DingTalkMessage): ConversationRef {
|
|
156
|
+
return {
|
|
157
|
+
endpoint: { id: endpointKey, adapter: endpointKey.split('\0')[0] ?? endpointKey },
|
|
158
|
+
kind: resolveChatType(msg.conversationType),
|
|
159
|
+
id: msg.conversationId || msg.senderId || 'unknown',
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export function resolveSender(msg: DingTalkMessage): string {
|
|
164
|
+
return msg.senderId || msg.senderStaffId || 'unknown';
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export function generateMessageId(msg: DingTalkMessage): string {
|
|
168
|
+
return msg.msgId || `${msg.createAt ?? Date.now()}`;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Build inbound text for OutboundMessageService.receive. */
|
|
172
|
+
export function formatInboundContent(msg: DingTalkMessage): string {
|
|
173
|
+
if (!msg.msgtype) return '';
|
|
174
|
+
switch (msg.msgtype) {
|
|
175
|
+
case 'text':
|
|
176
|
+
return msg.text?.content || '';
|
|
177
|
+
case 'picture':
|
|
178
|
+
return '[image]';
|
|
179
|
+
case 'file': {
|
|
180
|
+
const name = typeof msg.content?.fileName === 'string' ? msg.content.fileName : '';
|
|
181
|
+
return name ? `[file: ${name}]` : '[file]';
|
|
182
|
+
}
|
|
183
|
+
case 'audio':
|
|
184
|
+
return '[audio]';
|
|
185
|
+
case 'video':
|
|
186
|
+
return '[video]';
|
|
187
|
+
case 'richText': {
|
|
188
|
+
const rich = msg.content?.richText;
|
|
189
|
+
if (Array.isArray(rich)) {
|
|
190
|
+
return rich
|
|
191
|
+
.map((item) => (item && typeof item === 'object' && 'text' in item
|
|
192
|
+
? String((item as { text?: string }).text || '')
|
|
193
|
+
: ''))
|
|
194
|
+
.join('');
|
|
195
|
+
}
|
|
196
|
+
return '[richText]';
|
|
197
|
+
}
|
|
198
|
+
case 'markdown':
|
|
199
|
+
return typeof msg.content?.text === 'string' ? msg.content.text : '[markdown]';
|
|
200
|
+
default:
|
|
201
|
+
return `[${msg.msgtype}]`;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** DingTalk timestamps are epoch milliseconds; reject replays outside ±1 hour. */
|
|
206
|
+
export const MAX_TIMESTAMP_DRIFT_MS = 60 * 60 * 1000;
|
|
207
|
+
|
|
208
|
+
export function verifySignature(
|
|
209
|
+
appSecret: string,
|
|
210
|
+
timestamp: string,
|
|
211
|
+
sign: string,
|
|
212
|
+
): boolean {
|
|
213
|
+
try {
|
|
214
|
+
const ts = Number(timestamp);
|
|
215
|
+
if (!Number.isFinite(ts) || Math.abs(Date.now() - ts) > MAX_TIMESTAMP_DRIFT_MS) {
|
|
216
|
+
return false;
|
|
217
|
+
}
|
|
218
|
+
const stringToSign = `${timestamp}\n${appSecret}`;
|
|
219
|
+
const hmac = createHmac('sha256', appSecret);
|
|
220
|
+
hmac.update(stringToSign);
|
|
221
|
+
const calculated = hmac.digest('base64');
|
|
222
|
+
const a = Buffer.from(calculated);
|
|
223
|
+
const b = Buffer.from(sign);
|
|
224
|
+
if (a.length !== b.length) return false;
|
|
225
|
+
return timingSafeEqual(a, b);
|
|
226
|
+
} catch {
|
|
227
|
+
return false;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Wire-encode an already-rendered outbound payload into DingTalk robot body.
|
|
233
|
+
* Segment canonicalization is intentionally not done here: media segments carry
|
|
234
|
+
* the canonical `data.media` MediaRef and nothing else is consulted.
|
|
235
|
+
*
|
|
236
|
+
* 钉钉机器人媒体消息仅支持远程 URL(picture.picURL):
|
|
237
|
+
* - image 段 kind=url → 直发 picture;
|
|
238
|
+
* - 其余 kind / audio / video / file 段无投递面,warn + 丢弃。
|
|
239
|
+
*/
|
|
240
|
+
export function formatOutboundBody(payload: unknown): DingTalkSendBody {
|
|
241
|
+
if (typeof payload === 'string') {
|
|
242
|
+
return { msgtype: 'text', text: { content: payload } };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const items: Array<string | DingTalkWireSegment> = Array.isArray(payload)
|
|
246
|
+
? payload as Array<string | DingTalkWireSegment>
|
|
247
|
+
: payload && typeof payload === 'object' && 'type' in (payload as object)
|
|
248
|
+
? [payload as DingTalkWireSegment]
|
|
249
|
+
: [];
|
|
250
|
+
|
|
251
|
+
if (items.length === 0) {
|
|
252
|
+
const text = payload == null
|
|
253
|
+
? ''
|
|
254
|
+
: typeof payload === 'object'
|
|
255
|
+
? JSON.stringify(payload)
|
|
256
|
+
: String(payload);
|
|
257
|
+
return { msgtype: 'text', text: { content: text } };
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
const textParts: string[] = [];
|
|
261
|
+
const atUserIds: string[] = [];
|
|
262
|
+
let media: DingTalkSendBody | null = null;
|
|
263
|
+
let markdownTitle: string | undefined;
|
|
264
|
+
|
|
265
|
+
for (const item of items) {
|
|
266
|
+
if (typeof item === 'string') {
|
|
267
|
+
textParts.push(item);
|
|
268
|
+
continue;
|
|
269
|
+
}
|
|
270
|
+
const data = item.data ?? {};
|
|
271
|
+
switch (item.type) {
|
|
272
|
+
case 'text':
|
|
273
|
+
textParts.push(String(data.content ?? data.text ?? ''));
|
|
274
|
+
break;
|
|
275
|
+
case 'at': {
|
|
276
|
+
const userId = data.id ?? data.userId;
|
|
277
|
+
if (userId) {
|
|
278
|
+
atUserIds.push(String(userId));
|
|
279
|
+
textParts.push(`@${String(data.name || userId)} `);
|
|
280
|
+
}
|
|
281
|
+
break;
|
|
282
|
+
}
|
|
283
|
+
case 'image': {
|
|
284
|
+
if (media) break;
|
|
285
|
+
const ref = data.media;
|
|
286
|
+
if (isMediaRef(ref) && ref.kind === 'url') {
|
|
287
|
+
media = {
|
|
288
|
+
msgtype: 'picture',
|
|
289
|
+
picture: { picURL: ref.value },
|
|
290
|
+
};
|
|
291
|
+
break;
|
|
292
|
+
}
|
|
293
|
+
logger.warn(formatCompact({
|
|
294
|
+
op: 'dingtalk_outbound_media_dropped',
|
|
295
|
+
type: item.type,
|
|
296
|
+
reason: isMediaRef(ref) ? `unsupported_kind:${ref.kind}` : 'missing_media_ref',
|
|
297
|
+
}));
|
|
298
|
+
break;
|
|
299
|
+
}
|
|
300
|
+
case 'audio':
|
|
301
|
+
case 'video':
|
|
302
|
+
case 'file':
|
|
303
|
+
// 钉钉机器人无音频/视频/文件投递面,warn + 丢弃
|
|
304
|
+
logger.warn(formatCompact({
|
|
305
|
+
op: 'dingtalk_outbound_media_dropped',
|
|
306
|
+
type: item.type,
|
|
307
|
+
reason: 'undeliverable_msgtype',
|
|
308
|
+
}));
|
|
309
|
+
break;
|
|
310
|
+
case 'markdown':
|
|
311
|
+
markdownTitle ??= String(data.title || '消息');
|
|
312
|
+
textParts.push(String(data.content ?? data.text ?? ''));
|
|
313
|
+
break;
|
|
314
|
+
case 'link':
|
|
315
|
+
if (!media) {
|
|
316
|
+
media = {
|
|
317
|
+
msgtype: 'link',
|
|
318
|
+
link: {
|
|
319
|
+
title: String(data.title || '链接'),
|
|
320
|
+
text: String(data.text ?? data.content ?? ''),
|
|
321
|
+
messageUrl: typeof data.url === 'string' ? data.url : undefined,
|
|
322
|
+
picUrl: typeof data.picUrl === 'string' ? data.picUrl : undefined,
|
|
323
|
+
},
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
break;
|
|
327
|
+
default:
|
|
328
|
+
textParts.push(`[${item.type}]`);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
if (media) return media;
|
|
333
|
+
if (markdownTitle !== undefined) {
|
|
334
|
+
return {
|
|
335
|
+
msgtype: 'markdown',
|
|
336
|
+
markdown: { title: markdownTitle, text: textParts.join('') },
|
|
337
|
+
...(atUserIds.length > 0 ? { at: { atUserIds, isAtAll: false } } : {}),
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
const result: DingTalkSendBody = {
|
|
342
|
+
msgtype: 'text',
|
|
343
|
+
text: { content: textParts.join('') },
|
|
344
|
+
};
|
|
345
|
+
if (atUserIds.length > 0) {
|
|
346
|
+
return { ...result, at: { atUserIds, isAtAll: false } };
|
|
347
|
+
}
|
|
348
|
+
return result;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
export function headerValue(
|
|
352
|
+
headers: IncomingMessage['headers'],
|
|
353
|
+
name: string,
|
|
354
|
+
): string {
|
|
355
|
+
const value = headers[name] ?? headers[name.toLowerCase()];
|
|
356
|
+
if (Array.isArray(value)) return value[0] ?? '';
|
|
357
|
+
return value ?? '';
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
export async function readTextBody(
|
|
361
|
+
request: IncomingMessage,
|
|
362
|
+
options: { readonly limit?: number } = {},
|
|
363
|
+
): Promise<string> {
|
|
364
|
+
const limit = options.limit ?? 1_048_576;
|
|
365
|
+
const chunks: Buffer[] = [];
|
|
366
|
+
let size = 0;
|
|
367
|
+
for await (const chunk of request) {
|
|
368
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
369
|
+
size += buffer.length;
|
|
370
|
+
if (size > limit) {
|
|
371
|
+
request.destroy();
|
|
372
|
+
throw new Error(`Request body exceeds ${limit} bytes`);
|
|
373
|
+
}
|
|
374
|
+
chunks.push(buffer);
|
|
375
|
+
}
|
|
376
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
377
|
+
}
|