@zhin.js/adapter-dingtalk 4.0.1 → 4.0.3

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 (56) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +58 -335
  3. package/adapters/dingtalk.ts +26 -0
  4. package/agent/tools/add_chat_members.ts +22 -0
  5. package/agent/tools/create_chat.ts +23 -0
  6. package/agent/tools/dept_info.ts +17 -0
  7. package/agent/tools/get_dept_users.ts +18 -0
  8. package/agent/tools/get_user.ts +17 -0
  9. package/agent/tools/list_departments.ts +18 -0
  10. package/agent/tools/send_work_notice.ts +20 -0
  11. package/agent/tools/update_chat.ts +27 -0
  12. package/lib/dingtalk-agent-deps.d.ts +26 -0
  13. package/lib/dingtalk-agent-deps.js +30 -0
  14. package/lib/endpoint.d.ts +45 -36
  15. package/lib/endpoint.js +199 -434
  16. package/lib/index.d.ts +5 -15
  17. package/lib/index.js +5 -219
  18. package/lib/platform-permit.d.ts +1 -2
  19. package/lib/platform-permit.js +4 -2
  20. package/lib/protocol.d.ts +121 -0
  21. package/lib/protocol.js +221 -0
  22. package/lib/webhook.d.ts +13 -0
  23. package/lib/webhook.js +48 -0
  24. package/package.json +51 -19
  25. package/plugin.ts +12 -0
  26. package/schema.json +23 -0
  27. package/src/dingtalk-agent-deps.ts +58 -0
  28. package/src/endpoint.ts +263 -479
  29. package/src/index.ts +46 -235
  30. package/src/platform-permit.ts +1 -2
  31. package/src/protocol.ts +338 -0
  32. package/src/webhook.ts +76 -0
  33. package/lib/adapter.d.ts +0 -19
  34. package/lib/adapter.d.ts.map +0 -1
  35. package/lib/adapter.js +0 -40
  36. package/lib/adapter.js.map +0 -1
  37. package/lib/endpoint.d.ts.map +0 -1
  38. package/lib/endpoint.js.map +0 -1
  39. package/lib/index.d.ts.map +0 -1
  40. package/lib/index.js.map +0 -1
  41. package/lib/platform-permit.d.ts.map +0 -1
  42. package/lib/platform-permit.js.map +0 -1
  43. package/lib/segment-mapper.d.ts +0 -2
  44. package/lib/segment-mapper.d.ts.map +0 -1
  45. package/lib/segment-mapper.js +0 -2
  46. package/lib/segment-mapper.js.map +0 -1
  47. package/lib/types.d.ts +0 -58
  48. package/lib/types.d.ts.map +0 -1
  49. package/lib/types.js +0 -5
  50. package/lib/types.js.map +0 -1
  51. package/plugin.yml +0 -3
  52. package/src/adapter.ts +0 -46
  53. package/src/segment-mapper.ts +0 -1
  54. package/src/types.ts +0 -56
  55. /package/{skills/dingtalk → agent}/PERMITS.md +0 -0
  56. /package/{skills/dingtalk/SKILL.md → agent/skills/dingtalk.md} +0 -0
package/src/index.ts CHANGED
@@ -1,238 +1,49 @@
1
- /**
2
- * 钉钉适配器入口:类型扩展、导出、注册
3
- */
4
- import { usePlugin, type Plugin, type ISceneManagement, createSceneManagementTools, type ToolFeature } from "zhin.js";
5
- import { DingTalkAdapter } from "./adapter.js";
6
- import {
1
+ export {
2
+ formatInboundContent,
3
+ formatOutboundBody,
4
+ generateMessageId,
5
+ headerValue,
6
+ normalizeWebhookPath,
7
+ readTextBody,
8
+ resolveChatType,
9
+ resolveDingTalkConfig,
10
+ resolveSender,
11
+ resolveTarget,
12
+ verifySignature,
13
+ type AccessToken,
14
+ type DingTalkAdapterConfig,
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
+ DingTalkEndpoint,
25
+ type DingTalkEndpointOptions,
26
+ type DingTalkFetch,
27
+ } from './endpoint.js';
28
+
29
+ export {
30
+ registerDingTalkWebhookRoutes,
31
+ handleDingTalkWebhookRequest,
32
+ type DingTalkWebhookHandler,
33
+ } from './webhook.js';
34
+
35
+ export {
36
+ getDingtalkAgentDeps,
37
+ registerDingtalkAgentEndpoint,
38
+ setDingtalkAgentDeps,
39
+ type DingtalkAgentDeps,
40
+ type DingtalkAgentEndpoint,
41
+ } from './dingtalk-agent-deps.js';
42
+
43
+ export {
44
+ checkDingtalkPlatformPermit,
7
45
  dingtalkGroupPermitResolver,
46
+ normalizeDingtalkSenderForPermit,
8
47
  platformPermit,
9
48
  registerDingtalkPlatformPermitChecker,
10
- } from "./platform-permit.js";
11
-
12
- declare module "zhin.js" {
13
- namespace Plugin {
14
- interface Contexts {
15
- router: import("@zhin.js/host-router").Router;
16
- }
17
- }
18
- interface Adapters {
19
- dingtalk: DingTalkAdapter;
20
- }
21
- }
22
-
23
- export * from "./types.js";
24
- export { DingTalkEndpoint } from "./endpoint.js";
25
- export { DingTalkAdapter } from "./adapter.js";
26
-
27
- const plugin = usePlugin();
28
- const { provide, useContext } = plugin;
29
-
30
- useContext("router", (router: any) => {
31
- provide({
32
- name: "dingtalk",
33
- description: "DingTalk Endpoint Adapter",
34
- mounted: async (p: Plugin) => {
35
- const adapter = new DingTalkAdapter(p, router);
36
- await adapter.start();
37
- return adapter;
38
- },
39
- dispose: async (adapter: DingTalkAdapter) => {
40
- await adapter.stop();
41
- },
42
- });
43
- });
44
-
45
- useContext('tool', 'dingtalk', (toolService: ToolFeature, dingtalk: DingTalkAdapter) => {
46
- const disposers: (() => void)[] = [];
47
- disposers.push(registerDingtalkPlatformPermitChecker());
48
- const sceneTools = createSceneManagementTools(
49
- dingtalk as unknown as ISceneManagement,
50
- 'dingtalk',
51
- { permitResolver: dingtalkGroupPermitResolver, registerChecker: false },
52
- );
53
- disposers.push(...sceneTools.map(t => toolService.addTool(t, plugin.name)));
54
-
55
- disposers.push(toolService.addTool({
56
- name: 'dingtalk_get_user',
57
- description: '获取钉钉用户信息',
58
- parameters: {
59
- type: 'object',
60
- properties: {
61
- endpoint_id: { type: 'string', description: 'Endpoint 名称', contextKey: 'endpointId' },
62
- user_id: { type: 'string', description: '用户 ID' },
63
- },
64
- required: ['endpoint_id', 'user_id'],
65
- },
66
- platforms: ['dingtalk'],
67
- tags: ['dingtalk'],
68
- execute: async (args: Record<string, any>) => {
69
- const endpoint = dingtalk.endpoints.get(args.endpoint_id);
70
- if (!endpoint) throw new Error(`Endpoint ${args.endpoint_id} 不存在`);
71
- return await endpoint.getUserInfo(args.user_id);
72
- },
73
- }, plugin.name));
74
-
75
- disposers.push(toolService.addTool({
76
- name: 'dingtalk_get_dept_users',
77
- description: '获取钉钉部门用户列表',
78
- parameters: {
79
- type: 'object',
80
- properties: {
81
- endpoint_id: { type: 'string', description: 'Endpoint 名称', contextKey: 'endpointId' },
82
- dept_id: { type: 'string', description: '部门 ID' },
83
- },
84
- required: ['endpoint_id', 'dept_id'],
85
- },
86
- platforms: ['dingtalk'],
87
- tags: ['dingtalk'],
88
- execute: async (args: Record<string, any>) => {
89
- const endpoint = dingtalk.endpoints.get(args.endpoint_id);
90
- if (!endpoint) throw new Error(`Endpoint ${args.endpoint_id} 不存在`);
91
- const users = await endpoint.getDepartmentUsers(args.dept_id);
92
- return { users, count: users.length };
93
- },
94
- }, plugin.name));
95
-
96
- disposers.push(toolService.addTool({
97
- name: 'dingtalk_list_departments',
98
- description: '获取钉钉部门列表',
99
- parameters: {
100
- type: 'object',
101
- properties: {
102
- endpoint_id: { type: 'string', description: 'Endpoint 名称', contextKey: 'endpointId' },
103
- dept_id: { type: 'string', description: '父部门 ID,默认 1(根部门)' },
104
- },
105
- required: ['endpoint_id'],
106
- },
107
- platforms: ['dingtalk'],
108
- tags: ['dingtalk'],
109
- execute: async (args: Record<string, any>) => {
110
- const endpoint = dingtalk.endpoints.get(args.endpoint_id);
111
- if (!endpoint) throw new Error(`Endpoint ${args.endpoint_id} 不存在`);
112
- const departments = await endpoint.getDepartmentList(args.dept_id || '1');
113
- return { departments, count: departments.length };
114
- },
115
- }, plugin.name));
116
-
117
- disposers.push(toolService.addTool({
118
- name: 'dingtalk_send_work_notice',
119
- description: '向指定用户发送钉钉工作通知',
120
- parameters: {
121
- type: 'object',
122
- properties: {
123
- endpoint_id: { type: 'string', description: 'Endpoint 名称', contextKey: 'endpointId' },
124
- user_ids: { type: 'string', description: '用户 ID 列表,逗号分隔' },
125
- content: { type: 'string', description: '通知内容' },
126
- },
127
- required: ['endpoint_id', 'user_ids', 'content'],
128
- },
129
- platforms: ['dingtalk'],
130
- tags: ['dingtalk'],
131
- execute: async (args: Record<string, any>) => {
132
- const endpoint = dingtalk.endpoints.get(args.endpoint_id);
133
- if (!endpoint) throw new Error(`Endpoint ${args.endpoint_id} 不存在`);
134
- const msgContent = { msgtype: 'text', text: { content: args.content } };
135
- const success = await endpoint.sendWorkNotice(args.user_ids.split(','), msgContent);
136
- return { success, message: success ? '工作通知已发送' : '发送失败' };
137
- },
138
- }, plugin.name));
139
-
140
- disposers.push(toolService.addTool({
141
- name: 'dingtalk_create_chat',
142
- description: '创建钉钉群聊',
143
- parameters: {
144
- type: 'object',
145
- properties: {
146
- endpoint_id: { type: 'string', description: 'Endpoint 名称', contextKey: 'endpointId' },
147
- name: { type: 'string', description: '群名' },
148
- owner: { type: 'string', description: '群主用户 ID' },
149
- members: { type: 'string', description: '成员用户 ID 列表,逗号分隔' },
150
- },
151
- required: ['endpoint_id', 'name', 'owner', 'members'],
152
- },
153
- platforms: ['dingtalk'],
154
- tags: ['dingtalk'],
155
- permissions: [platformPermit('chat_owner')],
156
- execute: async (args: Record<string, any>) => {
157
- const endpoint = dingtalk.endpoints.get(args.endpoint_id);
158
- if (!endpoint) throw new Error(`Endpoint ${args.endpoint_id} 不存在`);
159
- const chatId = await endpoint.createChat(args.name, args.owner, args.members.split(','));
160
- return { success: !!chatId, chat_id: chatId, message: chatId ? `群聊创建成功: ${chatId}` : '创建失败' };
161
- },
162
- }, plugin.name));
163
-
164
- disposers.push(toolService.addTool({
165
- name: 'dingtalk_add_chat_members',
166
- description: '向钉钉群聊添加成员',
167
- parameters: {
168
- type: 'object',
169
- properties: {
170
- endpoint_id: { type: 'string', description: 'Endpoint 名称', contextKey: 'endpointId' },
171
- chat_id: { type: 'string', description: '群聊 ID' },
172
- user_ids: { type: 'string', description: '要添加的用户 ID 列表,逗号分隔' },
173
- },
174
- required: ['endpoint_id', 'chat_id', 'user_ids'],
175
- },
176
- platforms: ['dingtalk'],
177
- tags: ['dingtalk'],
178
- permissions: [platformPermit('chat_admin')],
179
- execute: async (args: Record<string, any>) => {
180
- const endpoint = dingtalk.endpoints.get(args.endpoint_id);
181
- if (!endpoint) throw new Error(`Endpoint ${args.endpoint_id} 不存在`);
182
- const success = await endpoint.updateChat(args.chat_id, { add_useridlist: args.user_ids.split(',') });
183
- return { success, message: success ? '成员添加成功' : '添加失败' };
184
- },
185
- }, plugin.name));
186
-
187
- disposers.push(toolService.addTool({
188
- name: 'dingtalk_dept_info',
189
- description: '获取钉钉部门详细信息',
190
- parameters: {
191
- type: 'object',
192
- properties: {
193
- endpoint_id: { type: 'string', description: 'Endpoint 名称', contextKey: 'endpointId' },
194
- dept_id: { type: 'string', description: '部门 ID' },
195
- },
196
- required: ['endpoint_id', 'dept_id'],
197
- },
198
- platforms: ['dingtalk'],
199
- tags: ['dingtalk'],
200
- execute: async (args: Record<string, any>) => {
201
- const endpoint = dingtalk.endpoints.get(args.endpoint_id);
202
- if (!endpoint) throw new Error(`Endpoint ${args.endpoint_id} 不存在`);
203
- return await endpoint.getDepartmentInfo(Number(args.dept_id));
204
- },
205
- }, plugin.name));
206
-
207
- disposers.push(toolService.addTool({
208
- name: 'dingtalk_update_chat',
209
- description: '更新钉钉群聊设置(改名、换群主、增减成员)',
210
- parameters: {
211
- type: 'object',
212
- properties: {
213
- endpoint_id: { type: 'string', description: 'Endpoint 名称', contextKey: 'endpointId' },
214
- chat_id: { type: 'string', description: '群聊 ID' },
215
- name: { type: 'string', description: '新群名(可选)' },
216
- owner: { type: 'string', description: '新群主 userId(可选)' },
217
- add_members: { type: 'string', description: '要添加的成员 userId,逗号分隔(可选)' },
218
- remove_members: { type: 'string', description: '要移除的成员 userId,逗号分隔(可选)' },
219
- },
220
- required: ['endpoint_id', 'chat_id'],
221
- },
222
- platforms: ['dingtalk'],
223
- tags: ['dingtalk'],
224
- execute: async (args: Record<string, any>) => {
225
- const endpoint = dingtalk.endpoints.get(args.endpoint_id);
226
- if (!endpoint) throw new Error(`Endpoint ${args.endpoint_id} 不存在`);
227
- const options: any = {};
228
- if (args.name) options.name = args.name;
229
- if (args.owner) options.owner = args.owner;
230
- if (args.add_members) options.add_useridlist = args.add_members.split(',').map((s: string) => s.trim());
231
- if (args.remove_members) options.del_useridlist = args.remove_members.split(',').map((s: string) => s.trim());
232
- await endpoint.updateChat(args.chat_id, options);
233
- return { success: true, message: '群聊设置已更新' };
234
- },
235
- }, plugin.name));
236
-
237
- return () => disposers.forEach(d => d());
238
- });
49
+ } from './platform-permit.js';
@@ -1,8 +1,7 @@
1
1
  /**
2
2
  * 钉钉 DingTalk platform permit
3
3
  */
4
- import type { Message } from 'zhin.js';
5
- import { registerPlatformPermitChecker } from 'zhin.js';
4
+ import { registerPlatformPermitChecker, type Message } from '@zhin.js/core';
6
5
 
7
6
  const ADAPTER = 'dingtalk';
8
7
 
@@ -0,0 +1,338 @@
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
+ /** Plugin Runtime owner config (`plugins.<instanceKey>` / schema.json). */
10
+ export interface DingTalkAdapterConfig {
11
+ readonly name?: string;
12
+ readonly appKey?: string;
13
+ readonly appSecret?: string;
14
+ readonly webhookPath?: string;
15
+ readonly robotCode?: string;
16
+ readonly apiBaseUrl?: string;
17
+ /** Transitional: legacy root `endpoints[]` with `context: dingtalk`. */
18
+ readonly endpoints?: ReadonlyArray<Partial<ResolvedDingTalkConfig> & {
19
+ readonly context?: string;
20
+ }>;
21
+ }
22
+
23
+ export interface ResolvedDingTalkConfig {
24
+ readonly context: 'dingtalk';
25
+ readonly name: string;
26
+ readonly appKey: string;
27
+ readonly appSecret: string;
28
+ readonly webhookPath: string;
29
+ readonly robotCode?: string;
30
+ readonly apiBaseUrl: string;
31
+ }
32
+
33
+ export interface DingTalkMessage {
34
+ readonly msgtype?: string;
35
+ readonly text?: { readonly content?: string };
36
+ readonly msgId?: string;
37
+ readonly createAt?: number;
38
+ readonly conversationType?: string;
39
+ readonly conversationId?: string;
40
+ readonly senderId?: string;
41
+ readonly senderNick?: string;
42
+ readonly senderCorpId?: string;
43
+ readonly sessionWebhook?: string;
44
+ readonly chatbotCorpId?: string;
45
+ readonly chatbotUserId?: string;
46
+ readonly isAdmin?: boolean;
47
+ readonly senderStaffId?: string;
48
+ readonly atUsers?: ReadonlyArray<{ readonly dingtalkId?: string; readonly staffId?: string }>;
49
+ readonly content?: Record<string, unknown>;
50
+ }
51
+
52
+ export interface DingTalkEvent extends DingTalkMessage {
53
+ readonly [key: string]: unknown;
54
+ }
55
+
56
+ /**
57
+ * 钉钉回调消息 @ 机器人判定:机器人被 @ 时回调带 `isInAtList: true`;
58
+ * 部分回调形态的 `atUserIds` / `atUsers[].dingtalkId` 会包含机器人 robotCode(来自配置)。
59
+ * 两者都不满足则不标注。
60
+ */
61
+ export function isDingtalkBotMentioned(event: DingTalkMessage, robotCode?: string): boolean {
62
+ const extra = event as DingTalkMessage & {
63
+ readonly isInAtList?: unknown;
64
+ readonly atUserIds?: unknown;
65
+ };
66
+ if (extra.isInAtList === true) return true;
67
+ if (!robotCode) return false;
68
+ if (Array.isArray(extra.atUserIds) && extra.atUserIds.some((id) => String(id) === robotCode)) {
69
+ return true;
70
+ }
71
+ return (event.atUsers ?? []).some((user) => user.dingtalkId === robotCode);
72
+ }
73
+
74
+ export interface AccessToken {
75
+ token: string;
76
+ expires_in: number;
77
+ timestamp: number;
78
+ }
79
+
80
+ export interface DingTalkApiResponse {
81
+ readonly errcode: number;
82
+ readonly errmsg?: string;
83
+ readonly access_token?: string;
84
+ readonly expires_in?: number;
85
+ readonly msgId?: string;
86
+ readonly chatid?: string;
87
+ readonly result?: unknown;
88
+ readonly chat_info?: unknown;
89
+ readonly [key: string]: unknown;
90
+ }
91
+
92
+ export interface DingTalkWireSegment {
93
+ readonly type: string;
94
+ readonly data?: Record<string, unknown>;
95
+ }
96
+
97
+ export interface DingTalkSendBody {
98
+ readonly msgtype: string;
99
+ readonly text?: { readonly content: string };
100
+ readonly picture?: { readonly picURL: string };
101
+ readonly markdown?: { readonly title: string; readonly text: string };
102
+ readonly link?: {
103
+ readonly title: string;
104
+ readonly text: string;
105
+ readonly messageUrl?: string;
106
+ readonly picUrl?: string;
107
+ };
108
+ readonly at?: { readonly atUserIds: string[]; readonly isAtAll: boolean };
109
+ readonly robotCode?: string;
110
+ }
111
+
112
+ export function resolveDingTalkConfig(config: DingTalkAdapterConfig = {}): ResolvedDingTalkConfig {
113
+ const entry = config.endpoints?.find((item) => item.context === 'dingtalk');
114
+ const appKey = config.appKey ?? entry?.appKey ?? process.env.DINGTALK_APP_KEY;
115
+ const appSecret = config.appSecret ?? entry?.appSecret ?? process.env.DINGTALK_APP_SECRET;
116
+ if (!appKey || !appSecret) {
117
+ throw new TypeError(
118
+ 'DingTalk adapter requires appKey + appSecret (plugins.<key> or endpoints with context: dingtalk)',
119
+ );
120
+ }
121
+ const name = (typeof config.name === 'string' && config.name)
122
+ || (typeof entry?.name === 'string' && entry.name)
123
+ || process.env.DINGTALK_BOT_NAME
124
+ || 'dingtalk-bot';
125
+ const webhookPath = normalizeWebhookPath(
126
+ config.webhookPath ?? entry?.webhookPath ?? '/dingtalk/webhook',
127
+ );
128
+ const apiBaseUrl = (
129
+ config.apiBaseUrl ?? entry?.apiBaseUrl ?? 'https://oapi.dingtalk.com'
130
+ ).replace(/\/$/, '');
131
+ const robotCode = config.robotCode ?? entry?.robotCode;
132
+ return {
133
+ context: 'dingtalk',
134
+ name,
135
+ appKey,
136
+ appSecret,
137
+ webhookPath,
138
+ ...(robotCode ? { robotCode } : {}),
139
+ apiBaseUrl,
140
+ };
141
+ }
142
+
143
+ export function normalizeWebhookPath(path: string): string {
144
+ const trimmed = path.trim() || '/dingtalk/webhook';
145
+ return trimmed.startsWith('/') ? trimmed : `/${trimmed}`;
146
+ }
147
+
148
+ export function resolveChatType(conversationType?: string): 'group' | 'private' {
149
+ return conversationType === '2' ? 'group' : 'private';
150
+ }
151
+
152
+ export function resolveTarget(msg: DingTalkMessage): string {
153
+ return msg.conversationId || msg.senderId || 'unknown';
154
+ }
155
+
156
+ export function resolveSender(msg: DingTalkMessage): string {
157
+ return msg.senderId || msg.senderStaffId || 'unknown';
158
+ }
159
+
160
+ export function generateMessageId(msg: DingTalkMessage): string {
161
+ return msg.msgId || `${msg.createAt ?? Date.now()}`;
162
+ }
163
+
164
+ /** Build inbound text for MessageGateway.receive. */
165
+ export function formatInboundContent(msg: DingTalkMessage): string {
166
+ if (!msg.msgtype) return '';
167
+ switch (msg.msgtype) {
168
+ case 'text':
169
+ return msg.text?.content || '';
170
+ case 'picture':
171
+ return '[image]';
172
+ case 'file': {
173
+ const name = typeof msg.content?.fileName === 'string' ? msg.content.fileName : '';
174
+ return name ? `[file: ${name}]` : '[file]';
175
+ }
176
+ case 'audio':
177
+ return '[audio]';
178
+ case 'video':
179
+ return '[video]';
180
+ case 'richText': {
181
+ const rich = msg.content?.richText;
182
+ if (Array.isArray(rich)) {
183
+ return rich
184
+ .map((item) => (item && typeof item === 'object' && 'text' in item
185
+ ? String((item as { text?: string }).text || '')
186
+ : ''))
187
+ .join('');
188
+ }
189
+ return '[richText]';
190
+ }
191
+ case 'markdown':
192
+ return typeof msg.content?.text === 'string' ? msg.content.text : '[markdown]';
193
+ default:
194
+ return `[${msg.msgtype}]`;
195
+ }
196
+ }
197
+
198
+ export function verifySignature(
199
+ appSecret: string,
200
+ timestamp: string,
201
+ sign: string,
202
+ ): boolean {
203
+ try {
204
+ const stringToSign = `${timestamp}\n${appSecret}`;
205
+ const hmac = createHmac('sha256', appSecret);
206
+ hmac.update(stringToSign);
207
+ const calculated = hmac.digest('base64');
208
+ const a = Buffer.from(calculated);
209
+ const b = Buffer.from(sign);
210
+ if (a.length !== b.length) return false;
211
+ return timingSafeEqual(a, b);
212
+ } catch {
213
+ return false;
214
+ }
215
+ }
216
+
217
+ /**
218
+ * Wire-encode an already-rendered outbound payload into DingTalk robot body.
219
+ * Segment canonicalization is intentionally not done here.
220
+ */
221
+ export function formatOutboundBody(payload: unknown): DingTalkSendBody {
222
+ if (typeof payload === 'string') {
223
+ return { msgtype: 'text', text: { content: payload } };
224
+ }
225
+
226
+ const items: Array<string | DingTalkWireSegment> = Array.isArray(payload)
227
+ ? payload as Array<string | DingTalkWireSegment>
228
+ : payload && typeof payload === 'object' && 'type' in (payload as object)
229
+ ? [payload as DingTalkWireSegment]
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 { msgtype: 'text', text: { content: text } };
239
+ }
240
+
241
+ const textParts: string[] = [];
242
+ const atUserIds: string[] = [];
243
+ let media: DingTalkSendBody | null = null;
244
+
245
+ for (const item of items) {
246
+ if (typeof item === 'string') {
247
+ textParts.push(item);
248
+ continue;
249
+ }
250
+ const data = item.data ?? {};
251
+ switch (item.type) {
252
+ case 'text':
253
+ textParts.push(String(data.content ?? data.text ?? ''));
254
+ break;
255
+ case 'at': {
256
+ const userId = data.id ?? data.userId;
257
+ if (userId) {
258
+ atUserIds.push(String(userId));
259
+ textParts.push(`@${String(data.name || userId)} `);
260
+ }
261
+ break;
262
+ }
263
+ case 'image':
264
+ if (!media) {
265
+ media = {
266
+ msgtype: 'picture',
267
+ picture: { picURL: String(data.url ?? data.file ?? '') },
268
+ };
269
+ }
270
+ break;
271
+ case 'markdown':
272
+ if (!media) {
273
+ media = {
274
+ msgtype: 'markdown',
275
+ markdown: {
276
+ title: String(data.title || '消息'),
277
+ text: String(data.content ?? data.text ?? ''),
278
+ },
279
+ };
280
+ }
281
+ break;
282
+ case 'link':
283
+ if (!media) {
284
+ media = {
285
+ msgtype: 'link',
286
+ link: {
287
+ title: String(data.title || '链接'),
288
+ text: String(data.text ?? data.content ?? ''),
289
+ messageUrl: typeof data.url === 'string' ? data.url : undefined,
290
+ picUrl: typeof data.picUrl === 'string' ? data.picUrl : undefined,
291
+ },
292
+ };
293
+ }
294
+ break;
295
+ default:
296
+ textParts.push(`[${item.type}]`);
297
+ }
298
+ }
299
+
300
+ if (media) return media;
301
+
302
+ const result: DingTalkSendBody = {
303
+ msgtype: 'text',
304
+ text: { content: textParts.join('') },
305
+ };
306
+ if (atUserIds.length > 0) {
307
+ return { ...result, at: { atUserIds, isAtAll: false } };
308
+ }
309
+ return result;
310
+ }
311
+
312
+ export function headerValue(
313
+ headers: IncomingMessage['headers'],
314
+ name: string,
315
+ ): string {
316
+ const value = headers[name] ?? headers[name.toLowerCase()];
317
+ if (Array.isArray(value)) return value[0] ?? '';
318
+ return value ?? '';
319
+ }
320
+
321
+ export async function readTextBody(
322
+ request: IncomingMessage,
323
+ options: { readonly limit?: number } = {},
324
+ ): Promise<string> {
325
+ const limit = options.limit ?? 1_048_576;
326
+ const chunks: Buffer[] = [];
327
+ let size = 0;
328
+ for await (const chunk of request) {
329
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
330
+ size += buffer.length;
331
+ if (size > limit) {
332
+ request.destroy();
333
+ throw new Error(`Request body exceeds ${limit} bytes`);
334
+ }
335
+ chunks.push(buffer);
336
+ }
337
+ return Buffer.concat(chunks).toString('utf8');
338
+ }