@michengai/dsh-im-connect 0.1.37 → 0.1.39
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 +17 -1
- package/CHANGELOG.zh-CN.md +17 -1
- package/README.en.md +60 -65
- package/README.md +60 -65
- package/SECURITY.md +7 -2
- package/client.js +31 -298
- package/lib/channels/channel-image-download.d.ts +22 -0
- package/lib/channels/channel-image-download.d.ts.map +1 -0
- package/lib/channels/channel-image-download.js +179 -0
- package/lib/channels/channel-image-download.js.map +1 -0
- package/lib/channels/dingtalk-token-cache.d.ts +18 -0
- package/lib/channels/dingtalk-token-cache.d.ts.map +1 -0
- package/lib/channels/dingtalk-token-cache.js +48 -0
- package/lib/channels/dingtalk-token-cache.js.map +1 -0
- package/lib/channels/dingtalk.d.ts +17 -4
- package/lib/channels/dingtalk.d.ts.map +1 -1
- package/lib/channels/dingtalk.js +111 -18
- package/lib/channels/dingtalk.js.map +1 -1
- package/lib/channels/factory.d.ts.map +1 -1
- package/lib/channels/factory.js +6 -3
- package/lib/channels/factory.js.map +1 -1
- package/lib/channels/feishu.d.ts +30 -2
- package/lib/channels/feishu.d.ts.map +1 -1
- package/lib/channels/feishu.js +141 -26
- package/lib/channels/feishu.js.map +1 -1
- package/lib/channels/image-host-policy.d.ts +4 -0
- package/lib/channels/image-host-policy.d.ts.map +1 -0
- package/lib/channels/image-host-policy.js +24 -0
- package/lib/channels/image-host-policy.js.map +1 -0
- package/lib/channels/qq.d.ts +1 -0
- package/lib/channels/qq.d.ts.map +1 -1
- package/lib/channels/qq.js +89 -18
- package/lib/channels/qq.js.map +1 -1
- package/lib/channels/telegram.d.ts.map +1 -1
- package/lib/channels/telegram.js +121 -16
- package/lib/channels/telegram.js.map +1 -1
- package/lib/channels/wecom.d.ts +8 -2
- package/lib/channels/wecom.d.ts.map +1 -1
- package/lib/channels/wecom.js +60 -11
- package/lib/channels/wecom.js.map +1 -1
- package/lib/channels/weixin.d.ts.map +1 -1
- package/lib/channels/weixin.js +169 -17
- package/lib/channels/weixin.js.map +1 -1
- package/lib/client.js +31 -298
- package/lib/engine/gateway.d.ts +2 -0
- package/lib/engine/gateway.d.ts.map +1 -1
- package/lib/engine/gateway.js +48 -11
- package/lib/engine/gateway.js.map +1 -1
- package/lib/engine/image-input.d.ts +8 -0
- package/lib/engine/image-input.d.ts.map +1 -0
- package/lib/engine/image-input.js +31 -0
- package/lib/engine/image-input.js.map +1 -0
- package/lib/engine/router.d.ts.map +1 -1
- package/lib/engine/router.js +29 -19
- package/lib/engine/router.js.map +1 -1
- package/lib/manager.d.ts +0 -10
- package/lib/manager.d.ts.map +1 -1
- package/lib/manager.js +231 -203
- package/lib/manager.js.map +1 -1
- package/package.json +1 -1
- package/src/channels/channel-image-download.ts +154 -0
- package/src/channels/dingtalk-token-cache.ts +39 -0
- package/src/channels/dingtalk.ts +106 -27
- package/src/channels/factory.ts +6 -3
- package/src/channels/feishu.ts +126 -24
- package/src/channels/image-host-policy.ts +21 -0
- package/src/channels/qq.ts +80 -26
- package/src/channels/telegram.ts +105 -16
- package/src/channels/wecom.ts +57 -12
- package/src/channels/weixin.ts +124 -14
- package/src/engine/gateway.ts +35 -6
- package/src/engine/image-input.ts +26 -0
- package/src/engine/router.ts +28 -18
- package/src/manager.ts +116 -84
package/src/channels/dingtalk.ts
CHANGED
|
@@ -1,13 +1,46 @@
|
|
|
1
|
-
import type { ChannelAdapter, ImMessage, ReplyStream } from '../engine/types.js'
|
|
1
|
+
import type { ChannelAdapter, ImMessage, ImMedia, ReplyStream } from '../engine/types.js'
|
|
2
2
|
import { DingtalkCardClient, openDingtalkCardStream, type CardTarget } from './dingtalk-card.js'
|
|
3
|
+
import { validateAdditionalImageHosts } from './image-host-policy.js'
|
|
4
|
+
import { DingtalkTokenCache } from './dingtalk-token-cache.js'
|
|
3
5
|
import { timeoutSignal } from '../engine/abort.js'
|
|
6
|
+
import { requestChannelBytes, imageMedia, MAX_CHANNEL_IMAGES, channelImageFailureReason, channelImageDownloadHost } from './channel-image-download.js'
|
|
7
|
+
|
|
8
|
+
async function postDingtalk(path: string, body: unknown, signal: AbortSignal, headers: Record<string, string> = {}) {
|
|
9
|
+
const bytes = await requestChannelBytes(`https://api.dingtalk.com/v1.0/${path}`, {
|
|
10
|
+
method: 'POST', headers: { 'content-type': 'application/json', ...headers },
|
|
11
|
+
body: JSON.stringify(body), maxBytes: 64 * 1024, signal,
|
|
12
|
+
})
|
|
13
|
+
return JSON.parse(bytes.toString()) as Record<string, unknown>
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async function downloadDingtalkImage(clientId: string, tokens: DingtalkTokenCache, downloadCode: string, signal: AbortSignal, additionalImageHosts: readonly string[], log: (line: string) => void): Promise<ImMedia> {
|
|
17
|
+
if (typeof downloadCode !== 'string' || !downloadCode.trim()) throw new Error('图片缺少 downloadCode')
|
|
18
|
+
const token = await tokens.get(signal)
|
|
19
|
+
const file = await postDingtalk('robot/messageFiles/download', { robotCode: clientId, downloadCode }, signal, {
|
|
20
|
+
'x-acs-dingtalk-access-token': token,
|
|
21
|
+
})
|
|
22
|
+
if (typeof file.downloadUrl !== 'string' || !file.downloadUrl) throw new Error('钉钉没有返回图片下载地址')
|
|
23
|
+
const mediaUrl = new URL(file.downloadUrl)
|
|
24
|
+
const sourceProtocol = mediaUrl.protocol
|
|
25
|
+
// DingTalk can return an HTTP-signed OSS URL. Upgrade this exact platform
|
|
26
|
+
// origin without altering its opaque path/query; never allow plaintext media.
|
|
27
|
+
if (mediaUrl.protocol === 'http:'
|
|
28
|
+
&& (mediaUrl.hostname === 'wukong-file-im-zjk.oss-cn-zhangjiakou.aliyuncs.com' || additionalImageHosts.includes(mediaUrl.hostname))
|
|
29
|
+
&& !mediaUrl.username && !mediaUrl.password && !mediaUrl.port) mediaUrl.protocol = 'https:'
|
|
30
|
+
log(`[dingtalk] 图片下载 host=${channelImageDownloadHost(mediaUrl.href)} sourceProtocol=${sourceProtocol} protocol=${mediaUrl.protocol} port=${mediaUrl.port || 'default'} userinfo=${Boolean(mediaUrl.username || mediaUrl.password)}`)
|
|
31
|
+
// The temporary media URL must never receive the app secret or access token.
|
|
32
|
+
return imageMedia(await requestChannelBytes(mediaUrl.href, { signal, additionalTrustedHosts: additionalImageHosts }))
|
|
33
|
+
}
|
|
4
34
|
|
|
5
35
|
export interface DingtalkConfig {
|
|
6
36
|
clientId?: string
|
|
7
37
|
clientSecret?: string
|
|
38
|
+
additionalImageHosts?: readonly string[]
|
|
8
39
|
}
|
|
9
40
|
|
|
10
|
-
export
|
|
41
|
+
export interface DingtalkRobotPayload {
|
|
42
|
+
msgtype?: string
|
|
43
|
+
content?: { downloadCode?: string; richText?: Array<{ type?: string; text?: string; downloadCode?: string }> }
|
|
11
44
|
text?: { content?: string }
|
|
12
45
|
senderStaffId?: string
|
|
13
46
|
senderId?: string
|
|
@@ -17,8 +50,12 @@ export function parseDingtalkRobotEvent(payload: {
|
|
|
17
50
|
msgId?: string
|
|
18
51
|
msgid?: string
|
|
19
52
|
msgIdEnc?: string
|
|
20
|
-
}
|
|
21
|
-
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function parseDingtalkRobotEvent(payload: DingtalkRobotPayload): { chatId: string; userId: string; text: string; kind: 'dm' | 'group'; messageId?: string } | undefined {
|
|
56
|
+
const text = payload.msgtype === 'richText' && Array.isArray(payload.content?.richText)
|
|
57
|
+
? payload.content.richText.filter(item => typeof item?.text === 'string').map(item => item.text).join('\n').trim()
|
|
58
|
+
: payload.text?.content?.trim() ?? ''
|
|
22
59
|
const sender = payload.senderStaffId ?? payload.senderId ?? ''
|
|
23
60
|
const group = String(payload.conversationType) === '2'
|
|
24
61
|
const chatId = group ? (payload.conversationId ?? '') : sender
|
|
@@ -32,14 +69,21 @@ export function parseDingtalkRobotEvent(payload: {
|
|
|
32
69
|
messageId,
|
|
33
70
|
}
|
|
34
71
|
}
|
|
35
|
-
export function createDingtalkChannel(config: DingtalkConfig, log: (line: string) => void
|
|
72
|
+
export function createDingtalkChannel(config: DingtalkConfig, log: (line: string) => void, dependencies: {
|
|
73
|
+
downloadImage?: (downloadCode: string) => Promise<ImMedia>
|
|
74
|
+
} = {}): ChannelAdapter | undefined {
|
|
36
75
|
const clientId = config.clientId?.trim()
|
|
37
76
|
const clientSecret = config.clientSecret?.trim()
|
|
38
77
|
if (!clientId || !clientSecret) return undefined
|
|
78
|
+
const additionalImageHosts = validateAdditionalImageHosts(config.additionalImageHosts)
|
|
39
79
|
|
|
40
80
|
let handler: ((msg: ImMessage) => void | Promise<void>) | undefined
|
|
41
81
|
let client: { connect(): Promise<void>; disconnect(): void; registerCallbackListener(topic: string, cb: (res: { data: string }) => unknown): void } | undefined
|
|
42
82
|
let statusText = '未连接'
|
|
83
|
+
let generation = 0
|
|
84
|
+
let lifecycle = new AbortController()
|
|
85
|
+
const tokens = new DingtalkTokenCache(signal => postDingtalk('oauth2/accessToken', { appKey: clientId, appSecret: clientSecret }, signal))
|
|
86
|
+
const receiving = new Map<string, Promise<void>>()
|
|
43
87
|
const webhooks = new Map<string, string>()
|
|
44
88
|
const targets = new Map<string, CardTarget>()
|
|
45
89
|
const cards = new DingtalkCardClient(clientId, clientSecret, log)
|
|
@@ -57,50 +101,85 @@ export function createDingtalkChannel(config: DingtalkConfig, log: (line: string
|
|
|
57
101
|
label: '钉钉',
|
|
58
102
|
maxMessageLength: 4000,
|
|
59
103
|
async start() {
|
|
104
|
+
const startedGeneration = ++generation
|
|
105
|
+
lifecycle.abort()
|
|
106
|
+
lifecycle = new AbortController()
|
|
107
|
+
const signal = lifecycle.signal
|
|
108
|
+
tokens.clear()
|
|
109
|
+
receiving.clear()
|
|
110
|
+
webhooks.clear()
|
|
111
|
+
targets.clear()
|
|
112
|
+
client?.disconnect()
|
|
113
|
+
client = undefined
|
|
60
114
|
try {
|
|
61
115
|
const sdk = await import('dingtalk-stream') as {
|
|
62
116
|
DWClient: new (opts: Record<string, unknown>) => NonNullable<typeof client>
|
|
63
117
|
TOPIC_ROBOT: string
|
|
64
118
|
}
|
|
65
|
-
|
|
119
|
+
if (generation !== startedGeneration) return
|
|
120
|
+
const startedClient = new sdk.DWClient({ clientId, clientSecret, autoReconnect: true })
|
|
121
|
+
client = startedClient
|
|
66
122
|
client.registerCallbackListener(sdk.TOPIC_ROBOT, (res) => {
|
|
67
|
-
let payload:
|
|
68
|
-
text?: { content?: string }
|
|
69
|
-
senderStaffId?: string
|
|
70
|
-
senderId?: string
|
|
71
|
-
conversationId?: string
|
|
72
|
-
conversationType?: string
|
|
73
|
-
sessionWebhook?: string
|
|
74
|
-
}
|
|
123
|
+
let payload: DingtalkRobotPayload
|
|
75
124
|
try { payload = JSON.parse(res.data) as typeof payload } catch { return }
|
|
76
125
|
const parsed = parseDingtalkRobotEvent(payload)
|
|
77
|
-
|
|
78
|
-
|
|
126
|
+
const images = payload.msgtype === 'picture' ? [payload.content?.downloadCode ?? '']
|
|
127
|
+
: payload.msgtype === 'richText' && Array.isArray(payload.content?.richText)
|
|
128
|
+
? payload.content.richText.filter(item => item && (item.type === 'picture' || 'downloadCode' in item)).map(item => item.downloadCode ?? '') : []
|
|
129
|
+
if (!parsed?.chatId || (!parsed.text && !images.length)) return { status: 'SUCCESS' }
|
|
130
|
+
const work = (receiving.get(parsed.chatId) ?? Promise.resolve()).then(async () => {
|
|
131
|
+
if (generation !== startedGeneration) return
|
|
132
|
+
// Advance reply targets only when this message reaches the head of its chat queue.
|
|
133
|
+
if (payload.sessionWebhook) remember(webhooks, parsed.chatId, payload.sessionWebhook)
|
|
79
134
|
remember(targets, parsed.chatId, parsed.kind === 'group'
|
|
80
135
|
? { type: 'group', openConversationId: payload.conversationId ?? parsed.chatId }
|
|
81
136
|
: { type: 'user', userId: parsed.userId })
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
137
|
+
const media: ImMedia[] = []
|
|
138
|
+
try {
|
|
139
|
+
if (images.length > MAX_CHANNEL_IMAGES) throw new Error('图片数量超过限制')
|
|
140
|
+
for (const code of images) {
|
|
141
|
+
if (generation !== startedGeneration) return
|
|
142
|
+
media.push(await (dependencies.downloadImage
|
|
143
|
+
? dependencies.downloadImage(code) : downloadDingtalkImage(clientId, tokens, code, signal, additionalImageHosts, log)))
|
|
144
|
+
}
|
|
145
|
+
} catch (error) {
|
|
146
|
+
if (generation !== startedGeneration) return
|
|
147
|
+
const reason = channelImageFailureReason(error)
|
|
148
|
+
log(`[dingtalk] 图片读取失败: ${reason}`)
|
|
149
|
+
if (!payload.sessionWebhook) throw new Error('没有可回复的图片回调 webhook')
|
|
150
|
+
await requestChannelBytes(payload.sessionWebhook, {
|
|
151
|
+
method: 'POST', headers: { 'content-type': 'application/json' }, maxBytes: 64 * 1024, signal,
|
|
152
|
+
body: JSON.stringify({ msgtype: 'text', text: { content: `图片读取失败:${reason}。请重试;若仍失败请管理员检查网络和机器人文件下载权限。` } }),
|
|
153
|
+
})
|
|
154
|
+
return
|
|
155
|
+
}
|
|
156
|
+
if (generation !== startedGeneration) return
|
|
157
|
+
await handler?.({ ...parsed, media, addressed: true })
|
|
158
|
+
}).catch(error => { log(`[dingtalk] 消息处理或图片错误提示发送失败: ${channelImageFailureReason(error)}`) })
|
|
159
|
+
receiving.set(parsed.chatId, work)
|
|
160
|
+
void work.finally(() => { if (receiving.get(parsed.chatId) === work) receiving.delete(parsed.chatId) })
|
|
92
161
|
return { status: 'SUCCESS' }
|
|
93
162
|
})
|
|
94
|
-
await
|
|
163
|
+
await startedClient.connect()
|
|
164
|
+
if (generation !== startedGeneration) { startedClient.disconnect(); return }
|
|
95
165
|
statusText = 'Stream 已连接'
|
|
96
166
|
log('[dingtalk] Stream 已连接')
|
|
97
167
|
} catch (error) {
|
|
168
|
+
if (generation !== startedGeneration) return
|
|
169
|
+
lifecycle.abort()
|
|
170
|
+
tokens.clear()
|
|
171
|
+
client?.disconnect()
|
|
172
|
+
client = undefined
|
|
98
173
|
const message = error instanceof Error ? error.message : String(error)
|
|
99
174
|
const missing = /Cannot find package ['"]dingtalk-stream['"]/i.test(message)
|
|
100
175
|
throw new Error(missing ? '缺少依赖 dingtalk-stream' : `钉钉连接失败: ${message}`)
|
|
101
176
|
}
|
|
102
177
|
},
|
|
103
178
|
async stop() {
|
|
179
|
+
generation++
|
|
180
|
+
lifecycle.abort()
|
|
181
|
+
tokens.clear()
|
|
182
|
+
receiving.clear()
|
|
104
183
|
client?.disconnect()
|
|
105
184
|
client = undefined
|
|
106
185
|
webhooks.clear()
|
package/src/channels/factory.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { createTelegramChannel } from './telegram.js'
|
|
|
6
6
|
import { createWecomChannel } from './wecom.js'
|
|
7
7
|
import { createWeixinChannel } from './weixin.js'
|
|
8
8
|
import { createQqChannel } from './qq.js'
|
|
9
|
+
import { parseAdditionalImageHosts } from './image-host-policy.js'
|
|
9
10
|
|
|
10
11
|
export function createChannelAdapter(
|
|
11
12
|
id: ChannelId,
|
|
@@ -15,6 +16,8 @@ export function createChannelAdapter(
|
|
|
15
16
|
options?: { accountId?: string; accountLabel?: string; onWeixinBotToken?: (token: string | undefined) => void | Promise<void> },
|
|
16
17
|
): ChannelAdapter | undefined {
|
|
17
18
|
let adapter: ChannelAdapter | undefined
|
|
19
|
+
const imageOptions = ['qq', 'wecom', 'dingtalk'].includes(id)
|
|
20
|
+
? { additionalImageHosts: parseAdditionalImageHosts(config.additionalImageHosts) } : {}
|
|
18
21
|
switch (id) {
|
|
19
22
|
case 'telegram':
|
|
20
23
|
adapter = createTelegramChannel({ token: config.token, stateDir }, log); break
|
|
@@ -25,11 +28,11 @@ export function createChannelAdapter(
|
|
|
25
28
|
case 'weixin':
|
|
26
29
|
adapter = createWeixinChannel({ enabled: true, stateDir, botToken: config.botToken, onBotToken: options?.onWeixinBotToken }, log, stateDir); break
|
|
27
30
|
case 'wecom':
|
|
28
|
-
adapter = createWecomChannel({ botId: config.botId, secret: config.secret }, log); break
|
|
31
|
+
adapter = createWecomChannel({ botId: config.botId, secret: config.secret, ...imageOptions }, log); break
|
|
29
32
|
case 'dingtalk':
|
|
30
|
-
adapter = createDingtalkChannel({ clientId: config.clientId, clientSecret: config.clientSecret }, log); break
|
|
33
|
+
adapter = createDingtalkChannel({ clientId: config.clientId, clientSecret: config.clientSecret, ...imageOptions }, log); break
|
|
31
34
|
case 'qq':
|
|
32
|
-
adapter = createQqChannel({ appId: config.appId, appSecret: config.appSecret }, log); break
|
|
35
|
+
adapter = createQqChannel({ appId: config.appId, appSecret: config.appSecret, ...imageOptions }, log); break
|
|
33
36
|
default:
|
|
34
37
|
return undefined
|
|
35
38
|
}
|
package/src/channels/feishu.ts
CHANGED
|
@@ -1,5 +1,88 @@
|
|
|
1
|
-
import type { ChannelAdapter, ImMessage } from '../engine/types.js'
|
|
1
|
+
import type { ChannelAdapter, ImMedia, ImMessage } from '../engine/types.js'
|
|
2
2
|
import { quietSdkLogger } from '../engine/quiet-logger.js'
|
|
3
|
+
import { KeyedSerialQueue } from '../engine/keyed-queue.js'
|
|
4
|
+
import { timeoutSignal } from '../engine/abort.js'
|
|
5
|
+
import { MAX_CHANNEL_IMAGES } from './channel-image-download.js'
|
|
6
|
+
|
|
7
|
+
interface FeishuContentMessage {
|
|
8
|
+
message_id?: string
|
|
9
|
+
message_type?: string
|
|
10
|
+
content?: string
|
|
11
|
+
}
|
|
12
|
+
interface ResourceClient {
|
|
13
|
+
im: { messageResource: { get(opts: { path: { message_id: string; file_key: string }; params: { type: string } }): Promise<{ getReadableStream(): import('node:stream').Readable; headers?: Record<string, string> }> } }
|
|
14
|
+
}
|
|
15
|
+
const MAX_IMAGE_BYTES = 20 * 1024 * 1024
|
|
16
|
+
// Shared across all images in one message, not renewed for each resource.
|
|
17
|
+
const MAX_MESSAGE_IMAGE_BYTES = MAX_IMAGE_BYTES
|
|
18
|
+
|
|
19
|
+
/** SDK messageResource.get is the receive-side API, not im.image.get. */
|
|
20
|
+
export async function resolveFeishuContent(client: ResourceClient, message: FeishuContentMessage, signal: AbortSignal = AbortSignal.timeout(30_000)): Promise<{ text: string; media: ImMedia[] }> {
|
|
21
|
+
const content = JSON.parse(message.content ?? '{}')
|
|
22
|
+
const keys: string[] = []
|
|
23
|
+
const texts: string[] = []
|
|
24
|
+
if (message.message_type === 'text') texts.push(content.text ?? '')
|
|
25
|
+
else if (message.message_type === 'image') {
|
|
26
|
+
if (!content.image_key) throw new Error('图片资源缺失')
|
|
27
|
+
keys.push(content.image_key)
|
|
28
|
+
} else if (message.message_type === 'post') {
|
|
29
|
+
const post = content.content ? content : content.zh_cn ?? content.en_us ?? Object.values(content)[0]
|
|
30
|
+
if (!post || !Array.isArray(post.content)) throw new Error('富文本内容无效')
|
|
31
|
+
if (post.title) texts.push(post.title)
|
|
32
|
+
for (const row of post.content) {
|
|
33
|
+
for (const item of row) {
|
|
34
|
+
if (item.tag === 'img') {
|
|
35
|
+
if (!item.image_key) throw new Error('图片资源缺失')
|
|
36
|
+
keys.push(item.image_key)
|
|
37
|
+
} else if (typeof item.text === 'string') texts.push(item.text)
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
} else throw new Error('暂不支持该消息类型,请发送文字或图片。')
|
|
41
|
+
if (keys.length > MAX_CHANNEL_IMAGES) throw new Error('图片数量超过上限')
|
|
42
|
+
const media: ImMedia[] = []
|
|
43
|
+
let totalBytes = 0
|
|
44
|
+
for (const key of keys) {
|
|
45
|
+
if (totalBytes >= MAX_MESSAGE_IMAGE_BYTES) throw new Error('图片累计大小超过上限')
|
|
46
|
+
if (!message.message_id) throw new Error('图片消息 ID 缺失')
|
|
47
|
+
signal.throwIfAborted()
|
|
48
|
+
let stream: import('node:stream').Readable | undefined
|
|
49
|
+
let abort: () => void = () => {}
|
|
50
|
+
const aborted = new Promise<never>((_, reject) => {
|
|
51
|
+
abort = () => { stream?.destroy(new Error('图片下载已取消或超时')); reject(new Error('图片下载已取消或超时')) }
|
|
52
|
+
signal.addEventListener('abort', abort, { once: true })
|
|
53
|
+
})
|
|
54
|
+
try {
|
|
55
|
+
const resource = await Promise.race([
|
|
56
|
+
client.im.messageResource.get({ path: { message_id: message.message_id, file_key: key }, params: { type: 'image' } }).then(resource => {
|
|
57
|
+
stream = resource.getReadableStream()
|
|
58
|
+
if (signal.aborted) { stream.destroy(); throw new Error('图片下载已取消或超时') }
|
|
59
|
+
return resource
|
|
60
|
+
}), aborted,
|
|
61
|
+
])
|
|
62
|
+
const consume = async () => {
|
|
63
|
+
const chunks: Buffer[] = []
|
|
64
|
+
let size = 0
|
|
65
|
+
if (Number(resource.headers?.['content-length']) > MAX_IMAGE_BYTES) throw new Error('图片超过 20 MB 上限')
|
|
66
|
+
if (Number(resource.headers?.['content-length']) > MAX_MESSAGE_IMAGE_BYTES - totalBytes) throw new Error('图片累计大小超过上限')
|
|
67
|
+
for await (const chunk of stream!) {
|
|
68
|
+
const bytes = Buffer.from(chunk)
|
|
69
|
+
size += bytes.length
|
|
70
|
+
totalBytes += bytes.length
|
|
71
|
+
if (totalBytes > MAX_MESSAGE_IMAGE_BYTES) throw new Error('图片累计大小超过上限')
|
|
72
|
+
if (size > MAX_IMAGE_BYTES) throw new Error('图片超过 20 MB 上限')
|
|
73
|
+
chunks.push(bytes)
|
|
74
|
+
}
|
|
75
|
+
if (!size) throw new Error('图片为空')
|
|
76
|
+
return { kind: 'image' as const, data: Buffer.concat(chunks), mediaType: resource.headers?.['content-type']?.split(';')[0] }
|
|
77
|
+
}
|
|
78
|
+
media.push(await Promise.race([consume(), aborted]))
|
|
79
|
+
} finally {
|
|
80
|
+
signal.removeEventListener('abort', abort)
|
|
81
|
+
stream?.destroy()
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return { text: texts.join('\n'), media }
|
|
85
|
+
}
|
|
3
86
|
|
|
4
87
|
export interface FeishuConfig {
|
|
5
88
|
appId?: string
|
|
@@ -18,18 +101,19 @@ export function isFeishuBotMentioned(mentions: FeishuMention[] | undefined, botO
|
|
|
18
101
|
return mentions.some((mention) => mention.id?.open_id === botOpenId)
|
|
19
102
|
}
|
|
20
103
|
|
|
21
|
-
export function createFeishuChannel(id: 'feishu' | 'lark', config: FeishuConfig, log: (line: string) => void): ChannelAdapter | undefined {
|
|
104
|
+
export function createFeishuChannel(id: 'feishu' | 'lark', config: FeishuConfig, log: (line: string) => void, loadSdk?: () => Promise<typeof import('@larksuiteoapi/node-sdk')>): ChannelAdapter | undefined {
|
|
22
105
|
const appId = config.appId?.trim()
|
|
23
106
|
const appSecret = config.appSecret?.trim()
|
|
24
107
|
if (!appId || !appSecret) return undefined
|
|
25
108
|
|
|
26
109
|
let handler: ((msg: ImMessage) => void | Promise<void>) | undefined
|
|
27
|
-
let client: {
|
|
110
|
+
let client: ResourceClient & {
|
|
28
111
|
request(opts: { url: string; method: 'GET' }): Promise<unknown>
|
|
29
112
|
im: { message: { create(opts: unknown): Promise<unknown> } }
|
|
30
113
|
} | undefined
|
|
31
114
|
let ws: { close(opts?: { force?: boolean }): void } | undefined
|
|
32
115
|
let statusText = '未连接'
|
|
116
|
+
let lifecycle: AbortController | undefined
|
|
33
117
|
const label = id === 'lark' ? 'Lark' : '飞书'
|
|
34
118
|
|
|
35
119
|
return {
|
|
@@ -37,48 +121,64 @@ export function createFeishuChannel(id: 'feishu' | 'lark', config: FeishuConfig,
|
|
|
37
121
|
label,
|
|
38
122
|
maxMessageLength: 4000,
|
|
39
123
|
async start() {
|
|
124
|
+
lifecycle?.abort()
|
|
125
|
+
const generation = new AbortController()
|
|
126
|
+
lifecycle = generation
|
|
127
|
+
const current = () => lifecycle === generation && !generation.signal.aborted
|
|
128
|
+
const incoming = new KeyedSerialQueue()
|
|
40
129
|
let sdk: typeof import('@larksuiteoapi/node-sdk')
|
|
41
130
|
try {
|
|
42
|
-
sdk = await import('@larksuiteoapi/node-sdk')
|
|
131
|
+
sdk = await (loadSdk ? loadSdk() : import('@larksuiteoapi/node-sdk'))
|
|
43
132
|
} catch {
|
|
44
133
|
throw new Error('缺少依赖 @larksuiteoapi/node-sdk')
|
|
45
134
|
}
|
|
46
135
|
const domain = id === 'lark' || config.domain === 'lark' ? 'https://open.larksuite.com' : undefined
|
|
47
|
-
const logger = quietSdkLogger(log, id)
|
|
136
|
+
const logger = quietSdkLogger(() => log(`[${id}] SDK 请求或连接异常(敏感详情已隐藏)`), id)
|
|
48
137
|
const loggerLevel = sdk.LoggerLevel?.error ?? 1
|
|
49
|
-
|
|
138
|
+
const httpInstance = Object.create(sdk.defaultHttpInstance)
|
|
139
|
+
httpInstance.request = (opts: Record<string, unknown>) => sdk.defaultHttpInstance.request({ ...opts, timeout: 30_000, maxRedirects: 0 })
|
|
140
|
+
client = new sdk.Client({ appId, appSecret, logger, loggerLevel, httpInstance, ...(domain ? { domain } : {}) }) as unknown as typeof client
|
|
50
141
|
const identity = await client!.request({ url: '/open-apis/bot/v3/info', method: 'GET' }) as {
|
|
51
142
|
bot?: { open_id?: string }
|
|
52
143
|
}
|
|
53
144
|
const botOpenId = identity.bot?.open_id?.trim() ?? ''
|
|
54
145
|
if (!botOpenId) throw new Error(`${id}: 无法获取机器人 open_id`)
|
|
55
146
|
const dispatcher = new sdk.EventDispatcher({}).register({
|
|
56
|
-
'im.message.receive_v1': (data: {
|
|
147
|
+
'im.message.receive_v1': async (data: {
|
|
57
148
|
sender?: { sender_id?: { open_id?: string } }
|
|
58
|
-
message?: { chat_id?: string; chat_type?: string; message_type?: string; content?: string; mentions?: FeishuMention[] }
|
|
149
|
+
message?: { message_id?: string; chat_id?: string; chat_type?: string; message_type?: string; content?: string; mentions?: FeishuMention[] }
|
|
59
150
|
}) => {
|
|
60
151
|
const message = data.message
|
|
61
152
|
if (!message) return
|
|
62
153
|
const group = message.chat_type === 'group'
|
|
63
154
|
const addressed = !group || isFeishuBotMentioned(message.mentions, botOpenId)
|
|
64
|
-
if (message.
|
|
65
|
-
|
|
66
|
-
|
|
155
|
+
if (!addressed || !message.chat_id || !current()) return
|
|
156
|
+
const chatId = message.chat_id
|
|
157
|
+
return incoming.run(chatId, async () => {
|
|
158
|
+
if (!current()) return
|
|
159
|
+
let resolved: { text: string; media: ImMedia[] }
|
|
160
|
+
try {
|
|
161
|
+
resolved = await resolveFeishuContent(client!, message, timeoutSignal(30_000, generation.signal))
|
|
162
|
+
} catch {
|
|
163
|
+
if (!current()) return
|
|
164
|
+
log(`[${id}] 图片或消息读取失败`)
|
|
165
|
+
await client?.im.message.create({
|
|
67
166
|
params: { receive_id_type: 'chat_id' },
|
|
68
|
-
data: { receive_id: message.chat_id, msg_type: 'text', content: JSON.stringify({ text: '
|
|
69
|
-
}).catch((
|
|
167
|
+
data: { receive_id: message.chat_id, msg_type: 'text', content: JSON.stringify({ text: '图片或消息读取失败,请重发图片或发送文字。' }) },
|
|
168
|
+
}).catch(() => log(`[${id}] 媒体提示发送失败`))
|
|
169
|
+
return
|
|
70
170
|
}
|
|
71
|
-
return
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
})
|
|
171
|
+
if (!current()) return
|
|
172
|
+
await handler?.({
|
|
173
|
+
chatId,
|
|
174
|
+
userId: data.sender?.sender_id?.open_id,
|
|
175
|
+
text: resolved.text,
|
|
176
|
+
...(resolved.media.length ? { media: resolved.media } : {}),
|
|
177
|
+
messageId: message.message_id,
|
|
178
|
+
kind: group ? 'group' : 'dm',
|
|
179
|
+
addressed,
|
|
180
|
+
})
|
|
181
|
+
}).catch(() => { if (current()) log(`[${id}] 消息处理失败`) })
|
|
82
182
|
},
|
|
83
183
|
})
|
|
84
184
|
const wsClient = new sdk.WSClient({ appId, appSecret, logger, loggerLevel, ...(domain ? { domain } : {}) })
|
|
@@ -88,6 +188,8 @@ export function createFeishuChannel(id: 'feishu' | 'lark', config: FeishuConfig,
|
|
|
88
188
|
log(`[${id}] WebSocket 长连接已启动`)
|
|
89
189
|
},
|
|
90
190
|
async stop() {
|
|
191
|
+
lifecycle?.abort()
|
|
192
|
+
lifecycle = undefined
|
|
91
193
|
ws?.close({ force: true })
|
|
92
194
|
ws = undefined
|
|
93
195
|
statusText = '已停止'
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { isIP } from 'node:net'
|
|
2
|
+
|
|
3
|
+
/** 管理员只能添加精确 DNS 主机名,不接受 URL 或域名后缀规则。 */
|
|
4
|
+
export function validateAdditionalImageHosts(hosts: readonly string[] = []): string[] {
|
|
5
|
+
const invalid = () => new Error('图片扩展主机配置无效')
|
|
6
|
+
if (!Array.isArray(hosts) || hosts.length > 16) throw invalid()
|
|
7
|
+
const result = new Set<string>()
|
|
8
|
+
for (const host of hosts) {
|
|
9
|
+
if (typeof host !== 'string' || host.length > 253
|
|
10
|
+
|| !/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(host)) throw invalid()
|
|
11
|
+
const name = host.toLowerCase()
|
|
12
|
+
if (name === 'localhost' || name.endsWith('.localhost') || isIP(name)) throw invalid()
|
|
13
|
+
result.add(name)
|
|
14
|
+
}
|
|
15
|
+
return [...result]
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function parseAdditionalImageHosts(value?: string): string[] {
|
|
19
|
+
if (value === undefined || value.trim() === '') return []
|
|
20
|
+
return validateAdditionalImageHosts(value.trim().split(/[,\s]+/))
|
|
21
|
+
}
|
package/src/channels/qq.ts
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
1
1
|
/** QQ 开放平台机器人:官方 WebSocket 网关,不是个人 QQ 号。 */
|
|
2
|
-
import type { ChannelAdapter, ImMessage, ReplyStream } from '../engine/types.js'
|
|
2
|
+
import type { ChannelAdapter, ImMedia, ImMessage, ReplyStream } from '../engine/types.js'
|
|
3
3
|
import { timeoutSignal } from '../engine/abort.js'
|
|
4
4
|
|
|
5
|
+
import { validateAdditionalImageHosts } from './image-host-policy.js'
|
|
6
|
+
import { KeyedSerialQueue } from '../engine/keyed-queue.js'
|
|
7
|
+
import { MAX_CHANNEL_IMAGES, channelImageFailureReason, channelImageDownloadHost, requestChannelBytes, imageMedia } from './channel-image-download.js'
|
|
8
|
+
|
|
5
9
|
export interface QqChannelConfig {
|
|
6
10
|
appId?: string
|
|
7
11
|
appSecret?: string
|
|
12
|
+
additionalImageHosts?: readonly string[]
|
|
8
13
|
}
|
|
9
14
|
|
|
10
15
|
interface GatewayPayload {
|
|
@@ -17,7 +22,7 @@ interface GatewayPayload {
|
|
|
17
22
|
interface QQMessage {
|
|
18
23
|
id: string
|
|
19
24
|
content?: string
|
|
20
|
-
attachments?:
|
|
25
|
+
attachments?: Array<{ content_type?: string; url?: string; filename?: string; size?: number }>
|
|
21
26
|
author?: {
|
|
22
27
|
id?: string
|
|
23
28
|
user_openid?: string
|
|
@@ -37,12 +42,15 @@ const TOKEN_URL = 'https://bots.qq.com/app/getAppAccessToken'
|
|
|
37
42
|
const API = 'https://api.sgroup.qq.com'
|
|
38
43
|
const GATEWAY_PATH = '/gateway'
|
|
39
44
|
const GROUP_AND_C2C_INTENT = 1 << 25
|
|
45
|
+
const MAX_MESSAGE_IMAGE_BYTES = 20 * 1024 * 1024
|
|
40
46
|
|
|
41
47
|
export function cleanQqText(text: string): string {
|
|
42
48
|
return text.replace(/<@!?\w+>/g, '').replace(/^\s*@\S+\s+/, '').trim()
|
|
43
49
|
}
|
|
44
50
|
|
|
45
51
|
export function createQqChannel(config: QqChannelConfig, log: (line: string) => void): ChannelAdapter | undefined {
|
|
52
|
+
const additionalImageHosts = validateAdditionalImageHosts(config.additionalImageHosts)
|
|
53
|
+
const trustedMediaHosts = new Set(['multimedia.nt.qq.com', 'multimedia.nt.qq.com.cn', 'gchat.qpic.cn', ...additionalImageHosts])
|
|
46
54
|
const appId = config.appId?.trim()
|
|
47
55
|
const appSecret = config.appSecret?.trim()
|
|
48
56
|
if (!appId || !appSecret) return undefined
|
|
@@ -101,15 +109,19 @@ export function createQqChannel(config: QqChannelConfig, log: (line: string) =>
|
|
|
101
109
|
}
|
|
102
110
|
|
|
103
111
|
async function qqFetch<T>(path: string, init?: RequestInit): Promise<T> {
|
|
104
|
-
const
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
112
|
+
const requestLifecycle = lifecycle
|
|
113
|
+
const request = () => {
|
|
114
|
+
requestLifecycle?.signal.throwIfAborted()
|
|
115
|
+
return fetch(`${API}${path}`, {
|
|
116
|
+
...init,
|
|
117
|
+
headers: {
|
|
118
|
+
Authorization: `QQBot ${accessToken}`,
|
|
119
|
+
'content-type': 'application/json',
|
|
120
|
+
...(init?.headers ?? {}),
|
|
121
|
+
},
|
|
122
|
+
signal: timeoutSignal(30_000, requestLifecycle?.signal),
|
|
123
|
+
})
|
|
124
|
+
}
|
|
113
125
|
await ensureToken()
|
|
114
126
|
let res = await request()
|
|
115
127
|
if (res.status === 401) {
|
|
@@ -149,15 +161,25 @@ export function createQqChannel(config: QqChannelConfig, log: (line: string) =>
|
|
|
149
161
|
socket.onopen = () => {
|
|
150
162
|
if (ws === socket) statusText = '等待网关握手'
|
|
151
163
|
}
|
|
164
|
+
const generation = lifecycle
|
|
165
|
+
const socketLifetime = new AbortController()
|
|
166
|
+
const mediaSignal = generation ? AbortSignal.any([generation.signal, socketLifetime.signal]) : socketLifetime.signal
|
|
167
|
+
const current = () => !stopped && lifecycle === generation && ws === socket
|
|
168
|
+
const incoming = new KeyedSerialQueue()
|
|
152
169
|
socket.onmessage = (ev) => {
|
|
170
|
+
if (!current()) return
|
|
153
171
|
let payload: GatewayPayload
|
|
154
|
-
try {
|
|
155
|
-
|
|
156
|
-
} catch {
|
|
157
|
-
log('[qq] 收到无法解析的网关消息')
|
|
158
|
-
return
|
|
159
|
-
}
|
|
172
|
+
try { payload = JSON.parse(String(ev.data)) as GatewayPayload } catch { log('[qq] 收到无法解析的网关消息'); return }
|
|
173
|
+
// Sequence/handshake/heartbeat handling must never wait behind media I/O.
|
|
160
174
|
if (payload.s !== undefined) seq = payload.s
|
|
175
|
+
const isMessage = payload.op === 0 && ['C2C_MESSAGE_CREATE', 'GROUP_AT_MESSAGE_CREATE'].includes(payload.t ?? '')
|
|
176
|
+
const msg = payload.d as QQMessage | undefined
|
|
177
|
+
const key = payload.t === 'GROUP_AT_MESSAGE_CREATE' ? `g:${msg?.group_openid ?? ''}` : msg?.author?.user_openid ?? msg?.author?.id ?? ''
|
|
178
|
+
const work = isMessage ? incoming.run(key, () => receive(payload)) : receive(payload)
|
|
179
|
+
void work.catch(() => { if (current()) log('[qq] 消息处理失败') })
|
|
180
|
+
}
|
|
181
|
+
const receive = async (payload: GatewayPayload) => {
|
|
182
|
+
if (!current()) return
|
|
161
183
|
switch (payload.op) {
|
|
162
184
|
case 10: {
|
|
163
185
|
const hello = payload.d as { heartbeat_interval: number }
|
|
@@ -199,22 +221,53 @@ export function createQqChannel(config: QqChannelConfig, log: (line: string) =>
|
|
|
199
221
|
? `g:${msg.group_openid ?? ''}`
|
|
200
222
|
: (msg.author.user_openid ?? msg.author.id ?? '')
|
|
201
223
|
if (!chatId || !userId) return
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
224
|
+
remember(chatId, isGroup ? 'group' : 'dm', msg.id)
|
|
225
|
+
const images = (msg.attachments ?? []).filter(a => typeof a.content_type === 'string' && a.content_type.startsWith('image/'))
|
|
226
|
+
const media: ImMedia[] = []
|
|
227
|
+
try {
|
|
228
|
+
if (images.length > MAX_CHANNEL_IMAGES) throw new Error('图片数量超过上限')
|
|
229
|
+
const declaredBytes = images.reduce((sum, image) => sum + (typeof image.size === 'number' && image.size > 0 ? image.size : 0), 0)
|
|
230
|
+
if (declaredBytes > MAX_MESSAGE_IMAGE_BYTES) throw new Error('图片累计大小超过上限')
|
|
231
|
+
let remainingBytes = MAX_MESSAGE_IMAGE_BYTES
|
|
232
|
+
const downloadSignal = timeoutSignal(30_000, mediaSignal)
|
|
233
|
+
for (const image of images) {
|
|
234
|
+
if (!current()) return
|
|
235
|
+
downloadSignal.throwIfAborted()
|
|
236
|
+
if (remainingBytes <= 0) throw new Error('图片累计大小超过上限')
|
|
237
|
+
const rawUrl = image.url ?? ''
|
|
238
|
+
const url = new URL(rawUrl.startsWith('//') ? `https:${rawUrl}`
|
|
239
|
+
: /^[a-z][a-z0-9+.-]*:/i.test(rawUrl) ? rawUrl : `https://${rawUrl}`)
|
|
240
|
+
// Official QQ CDN only; never forward API credentials or follow redirects.
|
|
241
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.port
|
|
242
|
+
|| !trustedMediaHosts.has(url.hostname)) throw new Error('不安全的图片地址')
|
|
243
|
+
// QQ also supplies scheme-less/HTTP CDN links. Upgrade known hosts;
|
|
244
|
+
// never send signed media URLs over plaintext HTTP.
|
|
245
|
+
url.protocol = 'https:'
|
|
246
|
+
if ((image.size ?? 0) > 20 * 1024 * 1024) throw new Error('图片过大')
|
|
247
|
+
const data = await requestChannelBytes(url.href, { signal: downloadSignal, maxBytes: remainingBytes, additionalTrustedHosts: additionalImageHosts })
|
|
248
|
+
downloadSignal.throwIfAborted()
|
|
249
|
+
remainingBytes -= data.length
|
|
250
|
+
if (!data.length) throw new Error('图片为空')
|
|
251
|
+
media.push({ ...imageMedia(data, MAX_MESSAGE_IMAGE_BYTES), name: image.filename })
|
|
209
252
|
}
|
|
253
|
+
} catch (error) {
|
|
254
|
+
if (!current()) return
|
|
255
|
+
const reason = channelImageFailureReason(error)
|
|
256
|
+
log(`[qq] 图片下载失败: ${reason} host=${images.slice(0, MAX_CHANNEL_IMAGES).map(image => channelImageDownloadHost(image.url)).join(',')}`)
|
|
257
|
+
await sendText(chatId, `图片下载失败:${reason}。请重新发送。`).catch(() => log('[qq] 图片提示发送失败'))
|
|
210
258
|
return
|
|
211
259
|
}
|
|
212
|
-
|
|
213
|
-
|
|
260
|
+
if (!current()) return
|
|
261
|
+
if (!text && !media.length) {
|
|
262
|
+
if (msg.attachments?.length) await sendText(chatId, '暂不支持该文件类型,请发送文字或图片。')
|
|
263
|
+
return
|
|
264
|
+
}
|
|
265
|
+
await handler?.({
|
|
214
266
|
chatId,
|
|
215
267
|
userId,
|
|
216
268
|
username: msg.author.username,
|
|
217
269
|
text,
|
|
270
|
+
...(media.length ? { media } : {}),
|
|
218
271
|
kind: isGroup ? 'group' : 'dm',
|
|
219
272
|
addressed: true,
|
|
220
273
|
messageId: msg.id,
|
|
@@ -232,6 +285,7 @@ export function createQqChannel(config: QqChannelConfig, log: (line: string) =>
|
|
|
232
285
|
}
|
|
233
286
|
}
|
|
234
287
|
socket.onclose = (ev) => {
|
|
288
|
+
socketLifetime.abort()
|
|
235
289
|
if (ws !== socket) return
|
|
236
290
|
clearInterval(heartbeat)
|
|
237
291
|
heartbeat = undefined
|