@zhin.js/adapter-dingtalk 4.0.2 → 5.0.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.
- package/CHANGELOG.md +62 -0
- package/README.md +59 -345
- package/adapters/dingtalk.ts +26 -0
- package/agent/tools/add_chat_members.ts +2 -2
- package/agent/tools/create_chat.ts +2 -2
- package/agent/tools/dept_info.ts +2 -2
- package/agent/tools/get_dept_users.ts +2 -2
- package/agent/tools/get_user.ts +2 -2
- package/agent/tools/list_departments.ts +2 -2
- package/agent/tools/send_work_notice.ts +2 -2
- package/agent/tools/update_chat.ts +2 -2
- package/lib/dingtalk-agent-deps.d.ts +26 -0
- package/lib/dingtalk-agent-deps.js +30 -0
- package/lib/endpoint.d.ts +55 -0
- package/lib/endpoint.js +312 -0
- package/lib/index.d.ts +5 -0
- package/lib/index.js +5 -0
- package/lib/platform-permit.d.ts +15 -0
- package/lib/{src/platform-permit.js → platform-permit.js} +1 -2
- package/lib/protocol.d.ts +121 -0
- package/lib/protocol.js +221 -0
- package/lib/webhook.d.ts +13 -0
- package/lib/webhook.js +48 -0
- package/package.json +45 -23
- package/plugin.ts +12 -0
- package/schema.json +56 -0
- package/src/dingtalk-agent-deps.ts +49 -9
- package/src/endpoint.ts +263 -479
- package/src/index.ts +45 -59
- package/src/platform-permit.ts +1 -1
- package/src/protocol.ts +338 -0
- package/src/webhook.ts +76 -0
- package/lib/agent/tools/add_chat_members.js +0 -21
- package/lib/agent/tools/add_chat_members.js.map +0 -1
- package/lib/agent/tools/create_chat.js +0 -22
- package/lib/agent/tools/create_chat.js.map +0 -1
- package/lib/agent/tools/dept_info.js +0 -17
- package/lib/agent/tools/dept_info.js.map +0 -1
- package/lib/agent/tools/get_dept_users.js +0 -18
- package/lib/agent/tools/get_dept_users.js.map +0 -1
- package/lib/agent/tools/get_user.js +0 -17
- package/lib/agent/tools/get_user.js.map +0 -1
- package/lib/agent/tools/list_departments.js +0 -18
- package/lib/agent/tools/list_departments.js.map +0 -1
- package/lib/agent/tools/send_work_notice.js +0 -20
- package/lib/agent/tools/send_work_notice.js.map +0 -1
- package/lib/agent/tools/update_chat.js +0 -31
- package/lib/agent/tools/update_chat.js.map +0 -1
- package/lib/src/adapter.js +0 -40
- package/lib/src/adapter.js.map +0 -1
- package/lib/src/dingtalk-agent-deps.js +0 -10
- package/lib/src/dingtalk-agent-deps.js.map +0 -1
- package/lib/src/endpoint.js +0 -547
- package/lib/src/endpoint.js.map +0 -1
- package/lib/src/index.js +0 -43
- package/lib/src/index.js.map +0 -1
- package/lib/src/platform-permit.js.map +0 -1
- package/lib/src/segment-mapper.js +0 -2
- package/lib/src/segment-mapper.js.map +0 -1
- package/lib/src/types.js +0 -5
- package/lib/src/types.js.map +0 -1
- package/plugin.yml +0 -3
- package/src/adapter.ts +0 -46
- package/src/segment-mapper.ts +0 -1
- package/src/types.ts +0 -56
package/src/index.ts
CHANGED
|
@@ -1,63 +1,49 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
}
|
|
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
22
|
|
|
23
|
-
export
|
|
24
|
-
|
|
25
|
-
|
|
23
|
+
export {
|
|
24
|
+
DingTalkEndpoint,
|
|
25
|
+
type DingTalkEndpointOptions,
|
|
26
|
+
type DingTalkFetch,
|
|
27
|
+
} from './endpoint.js';
|
|
26
28
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
+
export {
|
|
30
|
+
registerDingTalkWebhookRoutes,
|
|
31
|
+
handleDingTalkWebhookRequest,
|
|
32
|
+
type DingTalkWebhookHandler,
|
|
33
|
+
} from './webhook.js';
|
|
29
34
|
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
return adapter;
|
|
38
|
-
},
|
|
39
|
-
dispose: async (adapter: DingTalkAdapter) => {
|
|
40
|
-
await adapter.stop();
|
|
41
|
-
},
|
|
42
|
-
});
|
|
43
|
-
});
|
|
35
|
+
export {
|
|
36
|
+
getDingtalkAgentDeps,
|
|
37
|
+
registerDingtalkAgentEndpoint,
|
|
38
|
+
setDingtalkAgentDeps,
|
|
39
|
+
type DingtalkAgentDeps,
|
|
40
|
+
type DingtalkAgentEndpoint,
|
|
41
|
+
} from './dingtalk-agent-deps.js';
|
|
44
42
|
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
return endpoint;
|
|
53
|
-
},
|
|
54
|
-
getAdapter: () => dingtalk,
|
|
55
|
-
});
|
|
56
|
-
const sceneTools = createSceneManagementTools(
|
|
57
|
-
dingtalk as unknown as ISceneManagement,
|
|
58
|
-
'dingtalk',
|
|
59
|
-
{ permitResolver: dingtalkGroupPermitResolver, registerChecker: false },
|
|
60
|
-
);
|
|
61
|
-
disposers.push(...sceneTools.map(t => toolService.addTool(t, plugin.name)));
|
|
62
|
-
return () => disposers.forEach(d => d());
|
|
63
|
-
});
|
|
43
|
+
export {
|
|
44
|
+
checkDingtalkPlatformPermit,
|
|
45
|
+
dingtalkGroupPermitResolver,
|
|
46
|
+
normalizeDingtalkSenderForPermit,
|
|
47
|
+
platformPermit,
|
|
48
|
+
registerDingtalkPlatformPermitChecker,
|
|
49
|
+
} from './platform-permit.js';
|
package/src/platform-permit.ts
CHANGED
package/src/protocol.ts
ADDED
|
@@ -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
|
+
}
|
package/src/webhook.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DingTalk webhook HTTP: signature → parse → admit.
|
|
3
|
+
*/
|
|
4
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
5
|
+
import type { HttpHost, HttpRouteRegistration } from '@zhin.js/host-http';
|
|
6
|
+
import { formatCompact, getLogger } from '@zhin.js/logger';
|
|
7
|
+
import {
|
|
8
|
+
headerValue,
|
|
9
|
+
readTextBody,
|
|
10
|
+
verifySignature,
|
|
11
|
+
type DingTalkEvent,
|
|
12
|
+
type ResolvedDingTalkConfig,
|
|
13
|
+
} from './protocol.js';
|
|
14
|
+
|
|
15
|
+
const logger = getLogger('dingtalk');
|
|
16
|
+
|
|
17
|
+
export interface DingTalkWebhookHandler {
|
|
18
|
+
readonly config: ResolvedDingTalkConfig;
|
|
19
|
+
readonly isOpen: boolean;
|
|
20
|
+
admit(event: DingTalkEvent): void;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function registerDingTalkWebhookRoutes(
|
|
24
|
+
http: HttpHost,
|
|
25
|
+
handler: DingTalkWebhookHandler,
|
|
26
|
+
): HttpRouteRegistration[] {
|
|
27
|
+
const path = handler.config.webhookPath;
|
|
28
|
+
return [
|
|
29
|
+
http.route('POST', path, async (request, response) => {
|
|
30
|
+
await handleDingTalkWebhookRequest(request, response, handler);
|
|
31
|
+
}, { summary: 'DingTalk robot webhook', tags: ['dingtalk'] }),
|
|
32
|
+
];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export async function handleDingTalkWebhookRequest(
|
|
36
|
+
request: IncomingMessage,
|
|
37
|
+
response: ServerResponse,
|
|
38
|
+
handler: DingTalkWebhookHandler,
|
|
39
|
+
): Promise<void> {
|
|
40
|
+
try {
|
|
41
|
+
// DingTalk outgoing callbacks put timestamp/sign on the URL query;
|
|
42
|
+
// headers are accepted as a fallback for legacy senders.
|
|
43
|
+
const query = new URL(request.url ?? '/', 'http://localhost').searchParams;
|
|
44
|
+
const timestamp = query.get('timestamp') || headerValue(request.headers, 'timestamp');
|
|
45
|
+
const sign = query.get('sign') || headerValue(request.headers, 'sign');
|
|
46
|
+
if (timestamp && sign) {
|
|
47
|
+
if (!verifySignature(handler.config.appSecret, timestamp, sign)) {
|
|
48
|
+
logger.warn(formatCompact({ op: 'webhook', ok: false, error: 'invalid signature' }));
|
|
49
|
+
response.writeHead(403, { 'Content-Type': 'application/json' });
|
|
50
|
+
response.end(JSON.stringify({ code: -1, msg: 'Forbidden' }));
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const rawBody = await readTextBody(request);
|
|
56
|
+
let event: DingTalkEvent;
|
|
57
|
+
try {
|
|
58
|
+
event = JSON.parse(rawBody) as DingTalkEvent;
|
|
59
|
+
} catch {
|
|
60
|
+
response.writeHead(200, { 'Content-Type': 'application/json' });
|
|
61
|
+
response.end(JSON.stringify({ code: 0, msg: 'success' }));
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (event.msgtype && handler.isOpen) {
|
|
66
|
+
handler.admit(event);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
response.writeHead(200, { 'Content-Type': 'application/json' });
|
|
70
|
+
response.end(JSON.stringify({ code: 0, msg: 'success' }));
|
|
71
|
+
} catch (error) {
|
|
72
|
+
logger.error('Webhook error:', error);
|
|
73
|
+
response.writeHead(500, { 'Content-Type': 'application/json' });
|
|
74
|
+
response.end(JSON.stringify({ code: -1, msg: 'Internal Server Error' }));
|
|
75
|
+
}
|
|
76
|
+
}
|
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
import { defineTool } from '@zhin.js/agent/tools';
|
|
2
|
-
import { z } from 'zod';
|
|
3
|
-
import { getDingtalkAgentDeps } from '../../src/dingtalk-agent-deps.js';
|
|
4
|
-
import { platformPermit } from '../../src/platform-permit.js';
|
|
5
|
-
export default defineTool({
|
|
6
|
-
description: '向钉钉群聊添加成员',
|
|
7
|
-
inputSchema: z.object({
|
|
8
|
-
endpoint_id: z.string().describe('Endpoint 名称'),
|
|
9
|
-
chat_id: z.string().describe('群聊 ID'),
|
|
10
|
-
user_ids: z.string().describe('要添加的用户 ID 列表,逗号分隔'),
|
|
11
|
-
}),
|
|
12
|
-
platforms: ['dingtalk'],
|
|
13
|
-
tags: ['dingtalk'],
|
|
14
|
-
permissions: [platformPermit('chat_admin')],
|
|
15
|
-
async execute({ endpoint_id, chat_id, user_ids }) {
|
|
16
|
-
const endpoint = getDingtalkAgentDeps().getEndpoint(endpoint_id);
|
|
17
|
-
const success = await endpoint.updateChat(chat_id, { add_useridlist: user_ids.split(',') });
|
|
18
|
-
return { success, message: success ? '成员添加成功' : '添加失败' };
|
|
19
|
-
},
|
|
20
|
-
});
|
|
21
|
-
//# sourceMappingURL=add_chat_members.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"add_chat_members.js","sourceRoot":"","sources":["../../../agent/tools/add_chat_members.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAClD,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,oBAAoB,EAAE,MAAM,kCAAkC,CAAC;AACxE,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAE9D,eAAe,UAAU,CAA6D;IACpF,WAAW,EAAE,WAAW;IACxB,WAAW,EAAE,CAAC,CAAC,MAAM,CAAC;QACpB,WAAW,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,aAAa,CAAC;QAC/C,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,OAAO,CAAC;QACrC,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,mBAAmB,CAAC;KACnD,CAAC;IACF,SAAS,EAAE,CAAC,UAAU,CAAC;IACvB,IAAI,EAAE,CAAC,UAAU,CAAC;IAClB,WAAW,EAAE,CAAC,cAAc,CAAC,YAAY,CAAC,CAAC;IAC3C,KAAK,CAAC,OAAO,CAAC,EAAE,WAAW,EAAE,OAAO,EAAE,QAAQ,EAAiE;QAC7G,MAAM,QAAQ,GAAG,oBAAoB,EAAE,CAAC,WAAW,CAAC,WAAW,CAAC,CAAC;QACjE,MAAM,OAAO,GAAG,MAAM,QAAQ,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,cAAc,EAAE,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QAC5F,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC;IAC3D,CAAC;CACF,CAAC,CAAC"}
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import { defineTool } from '@zhin.js/agent/tools';
|
|
2
|
-
import { z } from 'zod';
|
|
3
|
-
import { getDingtalkAgentDeps } from '../../src/dingtalk-agent-deps.js';
|
|
4
|
-
import { platformPermit } from '../../src/platform-permit.js';
|
|
5
|
-
export default defineTool({
|
|
6
|
-
description: '创建钉钉群聊',
|
|
7
|
-
inputSchema: z.object({
|
|
8
|
-
endpoint_id: z.string().describe('Endpoint 名称'),
|
|
9
|
-
name: z.string().describe('群名'),
|
|
10
|
-
owner: z.string().describe('群主用户 ID'),
|
|
11
|
-
members: z.string().describe('成员用户 ID 列表,逗号分隔'),
|
|
12
|
-
}),
|
|
13
|
-
platforms: ['dingtalk'],
|
|
14
|
-
tags: ['dingtalk'],
|
|
15
|
-
permissions: [platformPermit('chat_owner')],
|
|
16
|
-
async execute({ endpoint_id, name, owner, members }) {
|
|
17
|
-
const endpoint = getDingtalkAgentDeps().getEndpoint(endpoint_id);
|
|
18
|
-
const chatId = await endpoint.createChat(name, owner, members.split(','));
|
|
19
|
-
return { success: !!chatId, chat_id: chatId, message: chatId ? `群聊创建成功: ${chatId}` : '创建失败' };
|
|
20
|
-
},
|
|
21
|
-
});
|
|
22
|
-
//# sourceMappingURL=create_chat.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"create_chat.js","sourceRoot":"","sources":["../../../agent/tools/create_chat.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAClD,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,oBAAoB,EAAE,MAAM,kCAAkC,CAAC;AACxE,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAE9D,eAAe,UAAU,CAAwE;IAC/F,WAAW,EAAE,QAAQ;IACrB,WAAW,EAAE,CAAC,CAAC,MAAM,CAAC;QACpB,WAAW,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,aAAa,CAAC;QAC/C,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC;QAC/B,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,SAAS,CAAC;QACrC,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,iBAAiB,CAAC;KAChD,CAAC;IACF,SAAS,EAAE,CAAC,UAAU,CAAC;IACvB,IAAI,EAAE,CAAC,UAAU,CAAC;IAClB,WAAW,EAAE,CAAC,cAAc,CAAC,YAAY,CAAC,CAAC;IAC3C,KAAK,CAAC,OAAO,CAAC,EAAE,WAAW,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,EAA4E;QAC3H,MAAM,QAAQ,GAAG,oBAAoB,EAAE,CAAC,WAAW,CAAC,WAAW,CAAC,CAAC;QACjE,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,UAAU,CAAC,IAAI,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC;QAC1E,OAAO,EAAE,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC,CAAC,WAAW,MAAM,EAAE,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC;IAChG,CAAC;CACF,CAAC,CAAC"}
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import { defineTool } from '@zhin.js/agent/tools';
|
|
2
|
-
import { z } from 'zod';
|
|
3
|
-
import { getDingtalkAgentDeps } from '../../src/dingtalk-agent-deps.js';
|
|
4
|
-
export default defineTool({
|
|
5
|
-
description: '获取钉钉部门详细信息',
|
|
6
|
-
inputSchema: z.object({
|
|
7
|
-
endpoint_id: z.string().describe('Endpoint 名称'),
|
|
8
|
-
dept_id: z.string().describe('部门 ID'),
|
|
9
|
-
}),
|
|
10
|
-
platforms: ['dingtalk'],
|
|
11
|
-
tags: ['dingtalk'],
|
|
12
|
-
async execute({ endpoint_id, dept_id }) {
|
|
13
|
-
const endpoint = getDingtalkAgentDeps().getEndpoint(endpoint_id);
|
|
14
|
-
return await endpoint.getDepartmentInfo(Number(dept_id));
|
|
15
|
-
},
|
|
16
|
-
});
|
|
17
|
-
//# sourceMappingURL=dept_info.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"dept_info.js","sourceRoot":"","sources":["../../../agent/tools/dept_info.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAClD,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,oBAAoB,EAAE,MAAM,kCAAkC,CAAC;AACxE,eAAe,UAAU,CAA2C;IAClE,WAAW,EAAE,YAAY;IACzB,WAAW,EAAE,CAAC,CAAC,MAAM,CAAC;QACpB,WAAW,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,aAAa,CAAC;QAC/C,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,OAAO,CAAC;KACtC,CAAC;IACF,SAAS,EAAE,CAAC,UAAU,CAAC;IACvB,IAAI,EAAE,CAAC,UAAU,CAAC;IAClB,KAAK,CAAC,OAAO,CAAC,EAAE,WAAW,EAAE,OAAO,EAA+C;QACjF,MAAM,QAAQ,GAAG,oBAAoB,EAAE,CAAC,WAAW,CAAC,WAAW,CAAC,CAAC;QACjE,OAAO,MAAM,QAAQ,CAAC,iBAAiB,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC;IAC3D,CAAC;CACF,CAAC,CAAC"}
|
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
import { defineTool } from '@zhin.js/agent/tools';
|
|
2
|
-
import { z } from 'zod';
|
|
3
|
-
import { getDingtalkAgentDeps } from '../../src/dingtalk-agent-deps.js';
|
|
4
|
-
export default defineTool({
|
|
5
|
-
description: '获取钉钉部门用户列表',
|
|
6
|
-
inputSchema: z.object({
|
|
7
|
-
endpoint_id: z.string().describe('Endpoint 名称'),
|
|
8
|
-
dept_id: z.string().describe('部门 ID'),
|
|
9
|
-
}),
|
|
10
|
-
platforms: ['dingtalk'],
|
|
11
|
-
tags: ['dingtalk'],
|
|
12
|
-
async execute({ endpoint_id, dept_id }) {
|
|
13
|
-
const endpoint = getDingtalkAgentDeps().getEndpoint(endpoint_id);
|
|
14
|
-
const users = await endpoint.getDepartmentUsers(Number(dept_id));
|
|
15
|
-
return { users, count: users.length };
|
|
16
|
-
},
|
|
17
|
-
});
|
|
18
|
-
//# sourceMappingURL=get_dept_users.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"get_dept_users.js","sourceRoot":"","sources":["../../../agent/tools/get_dept_users.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAClD,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,oBAAoB,EAAE,MAAM,kCAAkC,CAAC;AACxE,eAAe,UAAU,CAA2C;IAClE,WAAW,EAAE,YAAY;IACzB,WAAW,EAAE,CAAC,CAAC,MAAM,CAAC;QACpB,WAAW,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,aAAa,CAAC;QAC/C,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,OAAO,CAAC;KACtC,CAAC;IACF,SAAS,EAAE,CAAC,UAAU,CAAC;IACvB,IAAI,EAAE,CAAC,UAAU,CAAC;IAClB,KAAK,CAAC,OAAO,CAAC,EAAE,WAAW,EAAE,OAAO,EAA+C;QACjF,MAAM,QAAQ,GAAG,oBAAoB,EAAE,CAAC,WAAW,CAAC,WAAW,CAAC,CAAC;QACjE,MAAM,KAAK,GAAG,MAAM,QAAQ,CAAC,kBAAkB,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC;QACjE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC;IACxC,CAAC;CACF,CAAC,CAAC"}
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import { defineTool } from '@zhin.js/agent/tools';
|
|
2
|
-
import { z } from 'zod';
|
|
3
|
-
import { getDingtalkAgentDeps } from '../../src/dingtalk-agent-deps.js';
|
|
4
|
-
export default defineTool({
|
|
5
|
-
description: '获取钉钉用户信息',
|
|
6
|
-
inputSchema: z.object({
|
|
7
|
-
endpoint_id: z.string().describe('Endpoint 名称'),
|
|
8
|
-
user_id: z.string().describe('用户 ID'),
|
|
9
|
-
}),
|
|
10
|
-
platforms: ['dingtalk'],
|
|
11
|
-
tags: ['dingtalk'],
|
|
12
|
-
async execute({ endpoint_id, user_id }) {
|
|
13
|
-
const endpoint = getDingtalkAgentDeps().getEndpoint(endpoint_id);
|
|
14
|
-
return await endpoint.getUserInfo(user_id);
|
|
15
|
-
},
|
|
16
|
-
});
|
|
17
|
-
//# sourceMappingURL=get_user.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"get_user.js","sourceRoot":"","sources":["../../../agent/tools/get_user.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAClD,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,oBAAoB,EAAE,MAAM,kCAAkC,CAAC;AACxE,eAAe,UAAU,CAA2C;IAClE,WAAW,EAAE,UAAU;IACvB,WAAW,EAAE,CAAC,CAAC,MAAM,CAAC;QACpB,WAAW,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,aAAa,CAAC;QAC/C,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,OAAO,CAAC;KACtC,CAAC;IACF,SAAS,EAAE,CAAC,UAAU,CAAC;IACvB,IAAI,EAAE,CAAC,UAAU,CAAC;IAClB,KAAK,CAAC,OAAO,CAAC,EAAE,WAAW,EAAE,OAAO,EAA+C;QACjF,MAAM,QAAQ,GAAG,oBAAoB,EAAE,CAAC,WAAW,CAAC,WAAW,CAAC,CAAC;QACjE,OAAO,MAAM,QAAQ,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;IAC7C,CAAC;CACF,CAAC,CAAC"}
|
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
import { defineTool } from '@zhin.js/agent/tools';
|
|
2
|
-
import { z } from 'zod';
|
|
3
|
-
import { getDingtalkAgentDeps } from '../../src/dingtalk-agent-deps.js';
|
|
4
|
-
export default defineTool({
|
|
5
|
-
description: '获取钉钉部门列表',
|
|
6
|
-
inputSchema: z.object({
|
|
7
|
-
endpoint_id: z.string().describe('Endpoint 名称'),
|
|
8
|
-
dept_id: z.string().optional().describe('父部门 ID,默认 1(根部门)'),
|
|
9
|
-
}),
|
|
10
|
-
platforms: ['dingtalk'],
|
|
11
|
-
tags: ['dingtalk'],
|
|
12
|
-
async execute({ endpoint_id, dept_id }) {
|
|
13
|
-
const endpoint = getDingtalkAgentDeps().getEndpoint(endpoint_id);
|
|
14
|
-
const departments = await endpoint.getDepartmentList(Number(dept_id || '1'));
|
|
15
|
-
return { departments, count: departments.length };
|
|
16
|
-
},
|
|
17
|
-
});
|
|
18
|
-
//# sourceMappingURL=list_departments.js.map
|