@michengai/dsh-im-connect 0.1.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.
Files changed (162) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +39 -0
  3. package/client.js +1479 -0
  4. package/cordis.patch.yml +4 -0
  5. package/lib/channels/dingtalk-card.d.ts +24 -0
  6. package/lib/channels/dingtalk-card.d.ts.map +1 -0
  7. package/lib/channels/dingtalk-card.js +182 -0
  8. package/lib/channels/dingtalk-card.js.map +1 -0
  9. package/lib/channels/dingtalk.d.ts +7 -0
  10. package/lib/channels/dingtalk.d.ts.map +1 -0
  11. package/lib/channels/dingtalk.js +107 -0
  12. package/lib/channels/dingtalk.js.map +1 -0
  13. package/lib/channels/factory.d.ts +4 -0
  14. package/lib/channels/factory.d.ts.map +1 -0
  15. package/lib/channels/factory.js +24 -0
  16. package/lib/channels/factory.js.map +1 -0
  17. package/lib/channels/feishu.d.ts +8 -0
  18. package/lib/channels/feishu.d.ts.map +1 -0
  19. package/lib/channels/feishu.js +73 -0
  20. package/lib/channels/feishu.js.map +1 -0
  21. package/lib/channels/meta.d.ts +20 -0
  22. package/lib/channels/meta.d.ts.map +1 -0
  23. package/lib/channels/meta.js +69 -0
  24. package/lib/channels/meta.js.map +1 -0
  25. package/lib/channels/qr/dingtalk.d.ts +12 -0
  26. package/lib/channels/qr/dingtalk.d.ts.map +1 -0
  27. package/lib/channels/qr/dingtalk.js +69 -0
  28. package/lib/channels/qr/dingtalk.js.map +1 -0
  29. package/lib/channels/qr/feishu.d.ts +14 -0
  30. package/lib/channels/qr/feishu.d.ts.map +1 -0
  31. package/lib/channels/qr/feishu.js +87 -0
  32. package/lib/channels/qr/feishu.js.map +1 -0
  33. package/lib/channels/qr/hub.d.ts +22 -0
  34. package/lib/channels/qr/hub.d.ts.map +1 -0
  35. package/lib/channels/qr/hub.js +193 -0
  36. package/lib/channels/qr/hub.js.map +1 -0
  37. package/lib/channels/qr/render.d.ts +3 -0
  38. package/lib/channels/qr/render.d.ts.map +1 -0
  39. package/lib/channels/qr/render.js +9 -0
  40. package/lib/channels/qr/render.js.map +1 -0
  41. package/lib/channels/qr/shared.d.ts +39 -0
  42. package/lib/channels/qr/shared.d.ts.map +1 -0
  43. package/lib/channels/qr/shared.js +51 -0
  44. package/lib/channels/qr/shared.js.map +1 -0
  45. package/lib/channels/qr/wecom.d.ts +10 -0
  46. package/lib/channels/qr/wecom.d.ts.map +1 -0
  47. package/lib/channels/qr/wecom.js +81 -0
  48. package/lib/channels/qr/wecom.js.map +1 -0
  49. package/lib/channels/qr/weixin.d.ts +10 -0
  50. package/lib/channels/qr/weixin.d.ts.map +1 -0
  51. package/lib/channels/qr/weixin.js +77 -0
  52. package/lib/channels/qr/weixin.js.map +1 -0
  53. package/lib/channels/telegram.d.ts +7 -0
  54. package/lib/channels/telegram.d.ts.map +1 -0
  55. package/lib/channels/telegram.js +133 -0
  56. package/lib/channels/telegram.js.map +1 -0
  57. package/lib/channels/wecom.d.ts +28 -0
  58. package/lib/channels/wecom.d.ts.map +1 -0
  59. package/lib/channels/wecom.js +168 -0
  60. package/lib/channels/wecom.js.map +1 -0
  61. package/lib/channels/weixin.d.ts +41 -0
  62. package/lib/channels/weixin.d.ts.map +1 -0
  63. package/lib/channels/weixin.js +678 -0
  64. package/lib/channels/weixin.js.map +1 -0
  65. package/lib/client.js +1479 -0
  66. package/lib/engine/access.d.ts +11 -0
  67. package/lib/engine/access.d.ts.map +1 -0
  68. package/lib/engine/access.js +11 -0
  69. package/lib/engine/access.js.map +1 -0
  70. package/lib/engine/agent-options.d.ts +25 -0
  71. package/lib/engine/agent-options.d.ts.map +1 -0
  72. package/lib/engine/agent-options.js +19 -0
  73. package/lib/engine/agent-options.js.map +1 -0
  74. package/lib/engine/approval.d.ts +9 -0
  75. package/lib/engine/approval.d.ts.map +1 -0
  76. package/lib/engine/approval.js +38 -0
  77. package/lib/engine/approval.js.map +1 -0
  78. package/lib/engine/assistant-settings.d.ts +17 -0
  79. package/lib/engine/assistant-settings.d.ts.map +1 -0
  80. package/lib/engine/assistant-settings.js +35 -0
  81. package/lib/engine/assistant-settings.js.map +1 -0
  82. package/lib/engine/credentials.d.ts +17 -0
  83. package/lib/engine/credentials.d.ts.map +1 -0
  84. package/lib/engine/credentials.js +51 -0
  85. package/lib/engine/credentials.js.map +1 -0
  86. package/lib/engine/gateway.d.ts +46 -0
  87. package/lib/engine/gateway.d.ts.map +1 -0
  88. package/lib/engine/gateway.js +333 -0
  89. package/lib/engine/gateway.js.map +1 -0
  90. package/lib/engine/json-state.d.ts +8 -0
  91. package/lib/engine/json-state.d.ts.map +1 -0
  92. package/lib/engine/json-state.js +24 -0
  93. package/lib/engine/json-state.js.map +1 -0
  94. package/lib/engine/merge.d.ts +21 -0
  95. package/lib/engine/merge.d.ts.map +1 -0
  96. package/lib/engine/merge.js +55 -0
  97. package/lib/engine/merge.js.map +1 -0
  98. package/lib/engine/router.d.ts +88 -0
  99. package/lib/engine/router.d.ts.map +1 -0
  100. package/lib/engine/router.js +309 -0
  101. package/lib/engine/router.js.map +1 -0
  102. package/lib/engine/seen-store.d.ts +12 -0
  103. package/lib/engine/seen-store.d.ts.map +1 -0
  104. package/lib/engine/seen-store.js +38 -0
  105. package/lib/engine/seen-store.js.map +1 -0
  106. package/lib/engine/session-id.d.ts +30 -0
  107. package/lib/engine/session-id.d.ts.map +1 -0
  108. package/lib/engine/session-id.js +53 -0
  109. package/lib/engine/session-id.js.map +1 -0
  110. package/lib/engine/session-store.d.ts +13 -0
  111. package/lib/engine/session-store.d.ts.map +1 -0
  112. package/lib/engine/session-store.js +38 -0
  113. package/lib/engine/session-store.js.map +1 -0
  114. package/lib/engine/split.d.ts +2 -0
  115. package/lib/engine/split.d.ts.map +1 -0
  116. package/lib/engine/split.js +41 -0
  117. package/lib/engine/split.js.map +1 -0
  118. package/lib/engine/types.d.ts +52 -0
  119. package/lib/engine/types.d.ts.map +1 -0
  120. package/lib/engine/types.js +2 -0
  121. package/lib/engine/types.js.map +1 -0
  122. package/lib/index.d.ts +22 -0
  123. package/lib/index.d.ts.map +1 -0
  124. package/lib/index.js +53 -0
  125. package/lib/index.js.map +1 -0
  126. package/lib/manager.d.ts +103 -0
  127. package/lib/manager.d.ts.map +1 -0
  128. package/lib/manager.js +543 -0
  129. package/lib/manager.js.map +1 -0
  130. package/package.json +63 -0
  131. package/src/channels/dingtalk-card.ts +191 -0
  132. package/src/channels/dingtalk.ts +113 -0
  133. package/src/channels/factory.ts +32 -0
  134. package/src/channels/feishu.ts +77 -0
  135. package/src/channels/meta.ts +89 -0
  136. package/src/channels/qr/dingtalk.ts +71 -0
  137. package/src/channels/qr/feishu.ts +90 -0
  138. package/src/channels/qr/hub.ts +206 -0
  139. package/src/channels/qr/render.ts +7 -0
  140. package/src/channels/qr/shared.ts +80 -0
  141. package/src/channels/qr/wecom.ts +78 -0
  142. package/src/channels/qr/weixin.ts +78 -0
  143. package/src/channels/telegram.ts +145 -0
  144. package/src/channels/wecom.ts +182 -0
  145. package/src/channels/weixin.ts +712 -0
  146. package/src/engine/access.ts +17 -0
  147. package/src/engine/agent-options.ts +24 -0
  148. package/src/engine/approval.ts +45 -0
  149. package/src/engine/assistant-settings.ts +41 -0
  150. package/src/engine/credentials.ts +64 -0
  151. package/src/engine/gateway.ts +330 -0
  152. package/src/engine/json-state.ts +20 -0
  153. package/src/engine/merge.ts +60 -0
  154. package/src/engine/router.ts +333 -0
  155. package/src/engine/seen-store.ts +36 -0
  156. package/src/engine/session-id.ts +65 -0
  157. package/src/engine/session-store.ts +45 -0
  158. package/src/engine/split.ts +29 -0
  159. package/src/engine/types.ts +55 -0
  160. package/src/index.ts +81 -0
  161. package/src/manager.ts +571 -0
  162. package/src/optional-modules.d.ts +13 -0
@@ -0,0 +1,712 @@
1
+ /**
2
+ * 微信渠道适配器:腾讯官方 iLink Bot 协议(ilinkai.weixin.qq.com)。
3
+ * 与 OpenClaw 官方插件 @tencent-weixin/openclaw-weixin 同协议:
4
+ * - 扫码登录 → 长轮询收消息 → context_token 回复
5
+ * - 媒体收发:图片/语音/文件/视频,CDN AES-128-ECB 加密上传/下载
6
+ * - "正在输入"状态(getconfig → sendtyping)
7
+ *
8
+ * ⚠️ 仅私聊、一个账号一个 poller;建议使用专用小号。
9
+ * 使用本渠道即表示同意《微信ClawBot功能使用条款》(腾讯官方产品,非逆向方案)。
10
+ * @module dsh-im-gateway/channels/wechat
11
+ */
12
+
13
+ import type { ChannelAdapter, ImMedia, ImMessage } from '../engine/types.js'
14
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
15
+ import { readFile } from 'node:fs/promises'
16
+ import { join, basename } from 'node:path'
17
+ import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto'
18
+
19
+ export interface WeixinChannelConfig {
20
+ enabled?: boolean
21
+ /** 登录/上下文/媒体落盘目录。 */
22
+ stateDir?: string
23
+ pollTimeoutSecs?: number
24
+ }
25
+
26
+ const BASE_URL = 'https://ilinkai.weixin.qq.com'
27
+ /** CDN 基址(官方插件同款)。 */
28
+ export const CDN_BASE_URL = 'https://novac2c.cdn.weixin.qq.com/c2c'
29
+
30
+ /** 消息 item 类型:1=文本 2=图片 3=语音 4=文件 5=视频。 */
31
+ const ITEM_TEXT = 1
32
+ const ITEM_IMAGE = 2
33
+ const ITEM_VOICE = 3
34
+ const ITEM_FILE = 4
35
+ const ITEM_VIDEO = 5
36
+
37
+ /** 上传媒体类型:1=图片 2=视频 3=文件。 */
38
+ const UPLOAD_IMAGE = 1
39
+ const UPLOAD_VIDEO = 2
40
+ const UPLOAD_FILE = 3
41
+
42
+ interface WechatState {
43
+ allowedUserId?: string
44
+ contextTokens: Record<string, string>
45
+ /** 登录 bot_token(持久化后重启免扫码)。 */
46
+ botToken?: string
47
+ /** 服务端下发的 base URL(可能变化)。 */
48
+ baseUrl?: string
49
+ /** 轮询游标(重启恢复避免消息重复/丢失)。 */
50
+ syncBuf?: string
51
+ }
52
+
53
+ type Json = Record<string, unknown>
54
+
55
+ // ── AES-128-ECB(CDN 加解密,与官方插件一致)─────────────────────
56
+
57
+ /** PKCS7 填充后的密文大小。 */
58
+ export function aesEcbPaddedSize(plaintextSize: number): number {
59
+ return Math.ceil((plaintextSize + 1) / 16) * 16
60
+ }
61
+
62
+ export function encryptAesEcb(plaintext: Buffer, key: Buffer): Buffer {
63
+ const cipher = createCipheriv('aes-128-ecb', key, null)
64
+ return Buffer.concat([cipher.update(plaintext), cipher.final()])
65
+ }
66
+
67
+ export function decryptAesEcb(ciphertext: Buffer, key: Buffer): Buffer {
68
+ const decipher = createDecipheriv('aes-128-ecb', key, null)
69
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()])
70
+ }
71
+
72
+ /**
73
+ * 解析 CDNMedia.aes_key 为 16 字节原始 key。
74
+ * 野外有两种编码:base64(16 原始字节)(图片)或 base64(hex 字符串)(文件/语音/视频)。
75
+ */
76
+ export function parseAesKey(aesKeyBase64: string, label = 'aes'): Buffer {
77
+ const decoded = Buffer.from(aesKeyBase64, 'base64')
78
+ if (decoded.length === 16) return decoded
79
+ if (decoded.length === 32 && /^[0-9a-fA-F]{32}$/.test(decoded.toString('ascii'))) {
80
+ return Buffer.from(decoded.toString('ascii'), 'hex')
81
+ }
82
+ throw new Error(`${label}: aes_key 无法解析(base64 解码后 ${decoded.length} 字节,应为 16 字节或 32 字符 hex)`)
83
+ }
84
+
85
+ /** 构建 CDN 下载 URL。 */
86
+ export function buildCdnDownloadUrl(encryptedQueryParam: string, cdnBaseUrl = CDN_BASE_URL): string {
87
+ return `${cdnBaseUrl}/download?encrypted_query_param=${encodeURIComponent(encryptedQueryParam)}`
88
+ }
89
+
90
+ // ── 工具函数 ────────────────────────────────────────────────────
91
+
92
+ function pickStr(obj: Json, ...keys: string[]): string | undefined {
93
+ for (const k of keys) {
94
+ const v = obj[k]
95
+ if (v !== undefined && v !== null && v !== '') return String(v)
96
+ }
97
+ return undefined
98
+ }
99
+
100
+ function normalizeId(v: unknown): string | undefined {
101
+ if (typeof v === 'string') return v || undefined
102
+ if (typeof v === 'number' && Number.isFinite(v)) return String(Math.trunc(v))
103
+ if (v && typeof v === 'object') {
104
+ const inner = pickStr(v as Json, 'id', 'value', 'str')
105
+ if (inner !== undefined) return normalizeId(inner)
106
+ }
107
+ return undefined
108
+ }
109
+
110
+ function guessExt(name: string): string {
111
+ const m = name.match(/\.([a-zA-Z0-9]+)$/)
112
+ return m ? `.${m[1]!.toLowerCase()}` : '.bin'
113
+ }
114
+
115
+ export function mimeFromExt(ext: string): string {
116
+ const map: Record<string, string> = {
117
+ '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.gif': 'image/gif', '.webp': 'image/webp', '.bmp': 'image/bmp',
118
+ '.mp4': 'video/mp4', '.mov': 'video/quicktime', '.avi': 'video/x-msvideo', '.mkv': 'video/x-matroska',
119
+ '.pdf': 'application/pdf', '.doc': 'application/msword', '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
120
+ '.xls': 'application/vnd.ms-excel', '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
121
+ '.zip': 'application/zip', '.txt': 'text/plain', '.md': 'text/markdown', '.json': 'application/json',
122
+ '.mp3': 'audio/mpeg', '.wav': 'audio/wav', '.silk': 'audio/silk', '.amr': 'audio/amr',
123
+ }
124
+ return map[ext] ?? 'application/octet-stream'
125
+ }
126
+
127
+ /** 从 CDNMedia 取下载 URL(encrypt_query_param 优先,full_url 兜底)。 */
128
+ function cdnUrlOf(mediaRef: Json | undefined): string | undefined {
129
+ if (!mediaRef) return undefined
130
+ const param = pickStr(mediaRef, 'encrypt_query_param')
131
+ if (param) return buildCdnDownloadUrl(param)
132
+ return pickStr(mediaRef, 'full_url')
133
+ }
134
+
135
+ // ── 渠道工厂 ────────────────────────────────────────────────────
136
+
137
+ export function createWeixinChannel(config: WeixinChannelConfig, log: (line: string) => void, stateDir: string): ChannelAdapter | undefined {
138
+ if (!config.enabled) return undefined
139
+ const dir = config.stateDir ?? stateDir
140
+ const mediaDir = join(dir, 'media')
141
+ const statePath = join(dir, 'wechat-state.json')
142
+ const loginPath = join(dir, 'wechat-login.txt')
143
+
144
+ let state: WechatState = loadState()
145
+ let handler: ((msg: ImMessage) => void | Promise<void>) | undefined
146
+ let stopped = false
147
+ let botToken = ''
148
+ let statusText = '未登录'
149
+ /** 当前登录二维码 URL(UI 轮询用)。 */
150
+ let currentLoginUrl: string | undefined
151
+
152
+ const uin = Buffer.from(String(Math.floor(Math.random() * 0xffffffff)), 'utf8').toString('base64')
153
+ /** typing_ticket 按用户缓存。 */
154
+ const typingTickets = new Map<string, { ticket: string; nextFetchAt: number }>()
155
+
156
+ function loadState(): WechatState {
157
+ try {
158
+ const raw = readFileSync(statePath, 'utf8')
159
+ const parsed = JSON.parse(raw) as Partial<WechatState>
160
+ return {
161
+ allowedUserId: parsed.allowedUserId,
162
+ contextTokens: parsed.contextTokens ?? {},
163
+ botToken: parsed.botToken,
164
+ baseUrl: parsed.baseUrl,
165
+ syncBuf: parsed.syncBuf,
166
+ }
167
+ } catch {
168
+ return { contextTokens: {} }
169
+ }
170
+ }
171
+
172
+ function flush(): void {
173
+ try {
174
+ mkdirSync(dir, { recursive: true })
175
+ writeFileSync(statePath, JSON.stringify(state, null, 2))
176
+ } catch (err) {
177
+ log(`[weixin] 状态落盘失败: ${err instanceof Error ? err.message : String(err)}`)
178
+ }
179
+ }
180
+
181
+ function headers(): Record<string, string> {
182
+ const h: Record<string, string> = {
183
+ 'content-type': 'application/json',
184
+ 'iLink-App-ClientVersion': '1',
185
+ 'X-WECHAT-UIN': uin,
186
+ }
187
+ if (botToken) {
188
+ h['Authorization'] = `Bearer ${botToken}`
189
+ h['AuthorizationType'] = 'ilink_bot_token'
190
+ }
191
+ return h
192
+ }
193
+
194
+ async function request(path: string, body: unknown, timeoutMs: number, tolerateRet1 = false): Promise<Json> {
195
+ const baseUrl = state.baseUrl && state.baseUrl.trim() !== '' ? state.baseUrl : BASE_URL
196
+ const res = await fetch(`${baseUrl}${path}`, {
197
+ method: 'POST',
198
+ headers: headers(),
199
+ body: JSON.stringify(body),
200
+ signal: AbortSignal.timeout(timeoutMs),
201
+ })
202
+ if (!res.ok) throw new Error(`weixin ${path} http ${res.status}`)
203
+ const data = (await res.json()) as Json
204
+ const ret = Number(data.ret ?? 0)
205
+ const errcode = Number(data.errcode ?? 0)
206
+ if (tolerateRet1 && ret === 1 && errcode === 0) return data
207
+ if (ret !== 0 || errcode !== 0) {
208
+ throw new Error(`weixin ${path} ret=${ret} errcode=${errcode} ${String(data.errmsg ?? '')}`)
209
+ }
210
+ return data
211
+ }
212
+
213
+ async function loginLoop(): Promise<boolean> {
214
+ while (!stopped) {
215
+ let qr: Json
216
+ try {
217
+ qr = await request('/ilink/bot/get_bot_qrcode?bot_type=3', {}, 15_000)
218
+ } catch (err) {
219
+ log(`[weixin] 获取二维码失败,5s 后重试: ${err instanceof Error ? err.message : String(err)}`)
220
+ await sleep(5000)
221
+ continue
222
+ }
223
+ const qrcodeId = pickStr(qr, 'qrcode', 'qrcode_id')
224
+ const qrUrl = pickStr(qr, 'qrcode_img_content', 'qrcode_url', 'url')
225
+ if (!qrcodeId || !qrUrl) {
226
+ log('[weixin] 二维码字段缺失,5s 后重试')
227
+ await sleep(5000)
228
+ continue
229
+ }
230
+ statusText = '等待扫码'
231
+ currentLoginUrl = qrUrl
232
+ log(`[weixin] 请用微信扫码登录: ${qrUrl}`)
233
+ try {
234
+ mkdirSync(dir, { recursive: true })
235
+ writeFileSync(loginPath, `${qrUrl}\n`)
236
+ } catch { /* 忽略 */ }
237
+
238
+ while (!stopped) {
239
+ let st: Json
240
+ try {
241
+ st = await request(`/ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(qrcodeId)}`, {}, 40_000, true)
242
+ } catch {
243
+ await sleep(2000)
244
+ continue
245
+ }
246
+ const status = String(st.status ?? '')
247
+ if (Number(st.ret ?? 0) === 0 && status === 'confirmed') {
248
+ const token = pickStr(st, 'bot_token')
249
+ const userId = pickStr(st, 'ilink_user_id')
250
+ if (!token || !userId) throw new Error('weixin confirmed 但缺少 token/user')
251
+ botToken = token
252
+ // 持久化登录态:重启后免扫码
253
+ state.botToken = token
254
+ const newBaseUrl = pickStr(st, 'baseurl', 'base_url')
255
+ if (newBaseUrl) state.baseUrl = newBaseUrl
256
+ if (!state.allowedUserId) {
257
+ state.allowedUserId = userId
258
+ log(`[weixin] 已绑定白名单用户 ${userId}(仅该用户可驱动)`)
259
+ } else if (state.allowedUserId !== userId) {
260
+ log(`[weixin] 扫码用户 ${userId} 不在白名单(白名单=${state.allowedUserId})`)
261
+ return false
262
+ }
263
+ flush()
264
+ statusText = '已登录'
265
+ currentLoginUrl = undefined
266
+ log('[weixin] 登录完成(登录态已保存,重启无需重复扫码)')
267
+ return true
268
+ }
269
+ if (status === 'expired') {
270
+ log('[weixin] 二维码已过期,重新获取')
271
+ break
272
+ }
273
+ await sleep(2000)
274
+ }
275
+ }
276
+ return false
277
+ }
278
+
279
+ /** 下载 + 解密 CDN 媒体。 */
280
+ async function downloadCdn(mediaRef: Json | undefined, aesKey: Buffer | undefined): Promise<{ buf: Buffer; contentType?: string } | undefined> {
281
+ const url = cdnUrlOf(mediaRef)
282
+ if (!url) return undefined
283
+ try {
284
+ const res = await fetch(url, { signal: AbortSignal.timeout(60_000) })
285
+ if (!res.ok) throw new Error(`CDN 下载 HTTP ${res.status}`)
286
+ const buf = Buffer.from(await res.arrayBuffer())
287
+ const plain = aesKey ? decryptAesEcb(buf, aesKey) : buf
288
+ return { buf: plain, contentType: res.headers.get('content-type') ?? undefined }
289
+ } catch (err) {
290
+ log(`[weixin] 媒体下载失败: ${err instanceof Error ? err.message : String(err)}`)
291
+ return undefined
292
+ }
293
+ }
294
+
295
+ /** 保存媒体字节到媒体目录。 */
296
+ function saveMediaBuf(buf: Buffer, ext: string, prefix: string, name?: string): string {
297
+ mkdirSync(mediaDir, { recursive: true })
298
+ const fileName = name ? name.replace(/[^\w.\-\u4e00-\u9fa5]+/g, '_') : `${prefix}-${Date.now()}${ext}`
299
+ const filePath = join(mediaDir, fileName.endsWith(ext) || fileName.includes('.') ? fileName : `${fileName}${ext}`)
300
+ writeFileSync(filePath, buf)
301
+ return filePath
302
+ }
303
+
304
+ /** 从 media 引用取 AES key(image_item.aeskey hex 优先,media.aes_key base64 兜底)。 */
305
+ function aesKeyOf(mediaRef: Json | undefined, hexKey: string | undefined, label: string): Buffer | undefined {
306
+ if (hexKey) return Buffer.from(hexKey, 'hex')
307
+ if (mediaRef) {
308
+ const b64 = pickStr(mediaRef, 'aes_key')
309
+ if (b64) return parseAesKey(b64, label)
310
+ }
311
+ return undefined
312
+ }
313
+
314
+ // ── 媒体下载项(每条媒体一个惰性任务)────────────────────────
315
+
316
+ async function downloadImageItem(item: Json): Promise<ImMedia> {
317
+ const img = item.image_item as Json | undefined
318
+ const mediaRef = img?.media as Json | undefined
319
+ const aesKey = aesKeyOf(mediaRef, img ? pickStr(img, 'aeskey') : undefined, 'wechat-image')
320
+ const dl = await downloadCdn(mediaRef, aesKey)
321
+ if (!dl) return { kind: 'image', name: 'image' }
322
+ // 从 CDN Content-Type 推断真实图片类型(避免 saveImage 校验失败)
323
+ const ct = dl.contentType?.split(';')[0]?.trim().toLowerCase() ?? ''
324
+ const ext = ct === 'image/png' ? '.png' : ct === 'image/gif' ? '.gif' : ct === 'image/webp' ? '.webp' : '.jpg'
325
+ const mediaType = ct.startsWith('image/') ? ct : 'image/jpeg'
326
+ const saved = saveMediaBuf(dl.buf, ext, 'image', `image${ext}`)
327
+ return { kind: 'image', path: saved, mediaType, name: basename(saved) }
328
+ }
329
+
330
+ async function downloadVoiceItem(item: Json): Promise<ImMedia> {
331
+ const voice = item.voice_item as Json | undefined
332
+ const mediaRef = voice?.media as Json | undefined
333
+ const aesKey = aesKeyOf(mediaRef, undefined, 'wechat-voice')
334
+ const dl = await downloadCdn(mediaRef, aesKey)
335
+ if (!dl) return { kind: 'file', name: 'voice.silk' }
336
+ const saved = saveMediaBuf(dl.buf, '.silk', 'voice', 'voice.silk')
337
+ return { kind: 'file', path: saved, mediaType: 'audio/silk', name: basename(saved) }
338
+ }
339
+
340
+ async function downloadFileItem(item: Json): Promise<ImMedia> {
341
+ const fileItem = item.file_item as Json | undefined
342
+ const mediaRef = fileItem?.media as Json | undefined
343
+ const aesKey = aesKeyOf(mediaRef, undefined, 'wechat-file')
344
+ const dl = await downloadCdn(mediaRef, aesKey)
345
+ const fileName = fileItem ? pickStr(fileItem, 'file_name') ?? 'file.bin' : 'file.bin'
346
+ if (!dl) return { kind: 'file', name: fileName }
347
+ const ext = guessExt(fileName)
348
+ const saved = saveMediaBuf(dl.buf, ext, 'file', fileName)
349
+ return { kind: 'file', path: saved, name: fileName, mediaType: mimeFromExt(ext) }
350
+ }
351
+
352
+ async function downloadVideoItem(item: Json): Promise<ImMedia> {
353
+ const videoItem = item.video_item as Json | undefined
354
+ const mediaRef = videoItem?.media as Json | undefined
355
+ const aesKey = aesKeyOf(mediaRef, undefined, 'wechat-video')
356
+ const dl = await downloadCdn(mediaRef, aesKey)
357
+ if (!dl) return { kind: 'video', name: 'video.mp4' }
358
+ const saved = saveMediaBuf(dl.buf, '.mp4', 'video', 'video.mp4')
359
+ return { kind: 'video', path: saved, mediaType: 'video/mp4', name: basename(saved) }
360
+ }
361
+
362
+ // ── 入站解析 ─────────────────────────────────────────────────
363
+
364
+ /** 解析入站消息:文本 + 媒体(异步下载任务列表)。 */
365
+ function parseInbound(raw: unknown): { fromUserId: string; contextToken?: string; text: string; media: Array<Promise<ImMedia>>; messageId: string } | null {
366
+ if (!raw || typeof raw !== 'object') return null
367
+ let m = raw as Json
368
+ if (m.message && typeof m.message === 'object') m = { ...m, ...(m.message as Json) }
369
+ if (m.message_type !== undefined && Number(m.message_type) !== 1) return null
370
+ const fromUserId = pickStr(m, 'from_user_id', 'from_user')
371
+ if (!fromUserId) return null
372
+
373
+ const parts: string[] = []
374
+ const media: Array<Promise<ImMedia>> = []
375
+ if (typeof m.text === 'string') parts.push(m.text)
376
+ if (Array.isArray(m.item_list)) {
377
+ for (const rawItem of m.item_list) {
378
+ const it = rawItem as Json
379
+ const type = Number(it.type ?? 0)
380
+ try {
381
+ if (type === ITEM_TEXT) {
382
+ const textItem = it.text_item as Json | undefined
383
+ const t = textItem ? pickStr(textItem, 'text') : undefined
384
+ if (t) parts.push(t)
385
+ } else if (type === ITEM_IMAGE) {
386
+ media.push(Promise.resolve().then(() => downloadImageItem(it)))
387
+ } else if (type === ITEM_VOICE) {
388
+ const voiceItem = it.voice_item as Json | undefined
389
+ const asr = voiceItem ? pickStr(voiceItem, 'text') : undefined
390
+ if (asr) {
391
+ // 官方服务端转文字:直接拼进文本
392
+ parts.push(`[语音] ${asr}`)
393
+ } else {
394
+ media.push(Promise.resolve().then(() => downloadVoiceItem(it)))
395
+ }
396
+ } else if (type === ITEM_FILE) {
397
+ media.push(Promise.resolve().then(() => downloadFileItem(it)))
398
+ } else if (type === ITEM_VIDEO) {
399
+ media.push(Promise.resolve().then(() => downloadVideoItem(it)))
400
+ }
401
+ } catch (err) {
402
+ log(`[weixin] 媒体解析失败: ${err instanceof Error ? err.message : String(err)}`)
403
+ }
404
+ }
405
+ }
406
+ const text = parts.join('').trim()
407
+ const messageId = String(normalizeId(m.message_id) ?? normalizeId(m.msg_id) ?? `${fromUserId}:${String(m.create_time_ms ?? m.create_time ?? 0)}`)
408
+ const contextToken = pickStr(m, 'context_token')
409
+ return { fromUserId, contextToken, text, media, messageId }
410
+ }
411
+
412
+ async function pollLoop(): Promise<void> {
413
+ // 已有保存的登录态 → 跳过扫码直接轮询(重启免扫码)
414
+ if (state.botToken) {
415
+ botToken = state.botToken
416
+ statusText = '已登录(自动恢复)'
417
+ log('[weixin] 检测到已保存的登录态,跳过扫码直接轮询')
418
+ } else if (!(await loginLoop())) {
419
+ return
420
+ }
421
+ let cursor = state.syncBuf ?? ''
422
+ let staleCount = 0
423
+ while (!stopped) {
424
+ let data: Json
425
+ try {
426
+ data = await request(
427
+ '/ilink/bot/getupdates',
428
+ { get_updates_buf: cursor, base_info: { channel_version: '1.0.0' } },
429
+ (config.pollTimeoutSecs ?? 70) * 1000 + 5000,
430
+ )
431
+ } catch (err) {
432
+ if (stopped) return
433
+ const msg = err instanceof Error ? err.message : String(err)
434
+ // token 失效(服务端 errcode -14,与官方插件 STALE_TOKEN_ERRCODE 一致)
435
+ if (msg.includes('ret=-14') || msg.includes('errcode=-14') || msg.includes('-14')) {
436
+ staleCount += 1
437
+ if (staleCount >= 3) {
438
+ log('[weixin] 登录态已失效(连续 3 次),清除登录信息,需要重新扫码')
439
+ state.botToken = undefined
440
+ state.syncBuf = undefined
441
+ flush()
442
+ if (!(await loginLoop())) return
443
+ staleCount = 0
444
+ cursor = state.syncBuf ?? ''
445
+ continue
446
+ }
447
+ log(`[weixin] 登录态失效(${staleCount}/3),5 分钟后重试(若持续失效请重新扫码)`)
448
+ await sleep(300_000)
449
+ continue
450
+ }
451
+ staleCount = 0
452
+ log(`[weixin] 长轮询失败,5s 后重试: ${msg}`)
453
+ await sleep(5000)
454
+ continue
455
+ }
456
+ staleCount = 0
457
+ const nextCursor = pickStr(data, 'get_updates_buf', 'cursor', 'sync_buf') ?? cursor
458
+ if (nextCursor !== cursor) {
459
+ cursor = nextCursor
460
+ state.syncBuf = cursor
461
+ }
462
+ const rawList = data.msgs ?? data.messages ?? data.updates
463
+ if (Array.isArray(rawList)) {
464
+ for (const raw of rawList) {
465
+ try {
466
+ const parsed = parseInbound(raw)
467
+ if (!parsed) continue
468
+ if (parsed.contextToken) state.contextTokens[parsed.fromUserId] = parsed.contextToken
469
+ if (state.allowedUserId && parsed.fromUserId !== state.allowedUserId) continue
470
+ const media = await Promise.all(parsed.media)
471
+ if (parsed.text === '' && media.length === 0) continue
472
+ void handler?.({
473
+ chatId: parsed.fromUserId,
474
+ userId: parsed.fromUserId,
475
+ text: parsed.text,
476
+ media,
477
+ context: { contextToken: parsed.contextToken },
478
+ })
479
+ } catch { /* 单条失败跳过 */ }
480
+ }
481
+ }
482
+ flush()
483
+ }
484
+ }
485
+
486
+ // ── 出站:文本 / 媒体 / typing ────────────────────────────────
487
+
488
+ async function sendRaw(toUserId: string, item: Json, clientId: string): Promise<void> {
489
+ const contextToken = state.contextTokens[toUserId]
490
+ await request(
491
+ '/ilink/bot/sendmessage',
492
+ {
493
+ msg: {
494
+ from_user_id: '',
495
+ to_user_id: toUserId,
496
+ client_id: clientId,
497
+ message_type: 2,
498
+ message_state: 2,
499
+ context_token: contextToken ?? '',
500
+ item_list: [item],
501
+ },
502
+ base_info: { channel_version: '1.0.0' },
503
+ },
504
+ 15_000,
505
+ )
506
+ }
507
+
508
+ async function sendText(toUserId: string, text: string): Promise<void> {
509
+ await sendRaw(toUserId, { type: ITEM_TEXT, text_item: { text } }, `dsh-im-connect:${Date.now()}:${Math.floor(Math.random() * 1e6)}`)
510
+ }
511
+
512
+ /** typing:getconfig 拿 ticket(按用户缓存),sendtyping 发状态。 */
513
+ async function sendTypingStatus(toUserId: string, status: 1 | 2): Promise<void> {
514
+ try {
515
+ let cached = typingTickets.get(toUserId)
516
+ if (!cached || Date.now() >= cached.nextFetchAt) {
517
+ const resp = await request(
518
+ '/ilink/bot/getconfig',
519
+ { ilink_user_id: toUserId, context_token: state.contextTokens[toUserId] ?? '', base_info: { channel_version: '1.0.0' } },
520
+ 15_000,
521
+ )
522
+ const ticket = pickStr(resp, 'typing_ticket')
523
+ if (!ticket) return
524
+ cached = { ticket, nextFetchAt: Date.now() + 5 * 60_000 }
525
+ typingTickets.set(toUserId, cached)
526
+ }
527
+ await request(
528
+ '/ilink/bot/sendtyping',
529
+ { ilink_user_id: toUserId, typing_ticket: cached.ticket, status, base_info: { channel_version: '1.0.0' } },
530
+ 10_000,
531
+ )
532
+ } catch (err) {
533
+ log(`[weixin] typing 发送失败(忽略): ${err instanceof Error ? err.message : String(err)}`)
534
+ }
535
+ }
536
+
537
+ /** 上传本地文件到 CDN(与官方插件流程一致),返回组装媒体项所需参数。 */
538
+ async function uploadToCdn(filePath: string, toUserId: string, mediaType: number): Promise<{ downloadParam: string; aeskeyHex: string; rawsize: number; filesizeCiphertext: number }> {
539
+ const plaintext = await readFile(filePath)
540
+ const rawsize = plaintext.length
541
+ const rawfilemd5 = createHash('md5').update(plaintext).digest('hex')
542
+ const filesize = aesEcbPaddedSize(rawsize)
543
+ const filekey = randomBytes(16).toString('hex')
544
+ const aeskey = randomBytes(16)
545
+
546
+ const resp = await request(
547
+ '/ilink/bot/getuploadurl',
548
+ {
549
+ filekey,
550
+ media_type: mediaType,
551
+ to_user_id: toUserId,
552
+ rawsize,
553
+ rawfilemd5,
554
+ filesize,
555
+ no_need_thumb: true,
556
+ aeskey: aeskey.toString('hex'),
557
+ },
558
+ 20_000,
559
+ )
560
+ const uploadFullUrl = pickStr(resp, 'upload_full_url')?.trim()
561
+ const uploadParam = pickStr(resp, 'upload_param')
562
+ if (!uploadFullUrl && !uploadParam) throw new Error('getuploadurl 未返回上传地址')
563
+
564
+ const cdnUrl = uploadFullUrl ?? `${CDN_BASE_URL}/upload?encrypted_query_param=${encodeURIComponent(uploadParam!)}&filekey=${encodeURIComponent(filekey)}`
565
+ const ciphertext = encryptAesEcb(plaintext, aeskey)
566
+ const upRes = await fetch(cdnUrl, {
567
+ method: 'POST',
568
+ headers: { 'content-type': 'application/octet-stream' },
569
+ body: new Uint8Array(ciphertext),
570
+ signal: AbortSignal.timeout(120_000),
571
+ })
572
+ if (upRes.status !== 200) {
573
+ const errMsg = upRes.headers.get('x-error-message') ?? `HTTP ${upRes.status}`
574
+ throw new Error(`CDN 上传失败: ${errMsg}`)
575
+ }
576
+ const downloadParam = upRes.headers.get('x-encrypted-param')
577
+ if (!downloadParam) throw new Error('CDN 上传响应缺少 x-encrypted-param')
578
+ return { downloadParam, aeskeyHex: aeskey.toString('hex'), rawsize, filesizeCiphertext: filesize }
579
+ }
580
+
581
+ /** 发送媒体文件(按 MIME 路由 图片/视频/文件),caption 作为前导文本。 */
582
+ async function sendMediaFile(toUserId: string, filePath: string, caption?: string): Promise<void> {
583
+ const mime = mimeFromExt(guessExt(filePath))
584
+ const now = Date.now()
585
+ let item: Json
586
+ if (mime.startsWith('image/')) {
587
+ const up = await uploadToCdn(filePath, toUserId, UPLOAD_IMAGE)
588
+ item = {
589
+ type: ITEM_IMAGE,
590
+ image_item: {
591
+ media: {
592
+ encrypt_query_param: up.downloadParam,
593
+ aes_key: Buffer.from(up.aeskeyHex).toString('base64'),
594
+ encrypt_type: 1,
595
+ },
596
+ mid_size: up.filesizeCiphertext,
597
+ },
598
+ }
599
+ } else if (mime.startsWith('video/')) {
600
+ const up = await uploadToCdn(filePath, toUserId, UPLOAD_VIDEO)
601
+ item = {
602
+ type: ITEM_VIDEO,
603
+ video_item: {
604
+ media: {
605
+ encrypt_query_param: up.downloadParam,
606
+ aes_key: Buffer.from(up.aeskeyHex).toString('base64'),
607
+ encrypt_type: 1,
608
+ },
609
+ video_size: up.filesizeCiphertext,
610
+ },
611
+ }
612
+ } else {
613
+ const up = await uploadToCdn(filePath, toUserId, UPLOAD_FILE)
614
+ item = {
615
+ type: ITEM_FILE,
616
+ file_item: {
617
+ media: {
618
+ encrypt_query_param: up.downloadParam,
619
+ aes_key: Buffer.from(up.aeskeyHex).toString('base64'),
620
+ encrypt_type: 1,
621
+ },
622
+ file_name: basename(filePath),
623
+ len: String(up.rawsize),
624
+ },
625
+ }
626
+ }
627
+ if (caption) await sendText(toUserId, caption)
628
+ await sendRaw(toUserId, item, `dsh-im-connect:${now}`)
629
+ }
630
+
631
+ return {
632
+ id: 'weixin',
633
+ label: '微信',
634
+ maxMessageLength: 1200,
635
+ async start() {
636
+ stopped = false
637
+ statusText = '登录中'
638
+ void pollLoop()
639
+ },
640
+ async stop() {
641
+ stopped = true
642
+ flush()
643
+ },
644
+ async send(chatId, text) {
645
+ await sendText(chatId, text)
646
+ },
647
+ async sendAction(chatId) {
648
+ await sendTypingStatus(chatId, 1)
649
+ },
650
+ async sendMedia(chatId, filePath, caption) {
651
+ await sendMediaFile(chatId, filePath, caption)
652
+ },
653
+ loginUrl() {
654
+ return currentLoginUrl
655
+ },
656
+ authorizes(userId: string) {
657
+ // 已绑定扫码白名单:仅放行该用户(其余在轮询层已过滤)
658
+ if (state.allowedUserId) return state.allowedUserId === userId
659
+ // 尚未登录/未绑定白名单:交给网关全局白名单决定
660
+ return undefined
661
+ },
662
+ setMessageHandler(h) {
663
+ handler = h
664
+ },
665
+ status() {
666
+ return statusText
667
+ },
668
+ }
669
+ }
670
+
671
+ function sleep(ms: number): Promise<void> {
672
+ return new Promise((resolve) => setTimeout(resolve, ms))
673
+ }
674
+
675
+
676
+ export function weixinStatePath(stateDir: string): string {
677
+ return join(stateDir, 'wechat-state.json')
678
+ }
679
+
680
+ export function persistWeixinLogin(stateDir: string, data: { botToken: string; allowedUserId?: string; baseUrl?: string }): void {
681
+ mkdirSync(stateDir, { recursive: true })
682
+ const file = weixinStatePath(stateDir)
683
+ let prev: WechatState = { contextTokens: {} }
684
+ try {
685
+ const parsed = JSON.parse(readFileSync(file, 'utf8')) as Partial<WechatState>
686
+ prev = {
687
+ allowedUserId: parsed.allowedUserId,
688
+ contextTokens: parsed.contextTokens ?? {},
689
+ botToken: parsed.botToken,
690
+ baseUrl: parsed.baseUrl,
691
+ syncBuf: parsed.syncBuf,
692
+ }
693
+ } catch { /* 首次写入 */ }
694
+ const next: WechatState = {
695
+ ...prev,
696
+ botToken: data.botToken,
697
+ allowedUserId: data.allowedUserId || prev.allowedUserId,
698
+ baseUrl: data.baseUrl || prev.baseUrl,
699
+ }
700
+ writeFileSync(file, `${JSON.stringify(next, null, 2)}\n`, 'utf8')
701
+ }
702
+
703
+ export function clearWeixinLogin(stateDir: string): void {
704
+ const file = weixinStatePath(stateDir)
705
+ try {
706
+ const parsed = JSON.parse(readFileSync(file, 'utf8')) as Partial<WechatState>
707
+ writeFileSync(file, `${JSON.stringify({
708
+ allowedUserId: parsed.allowedUserId,
709
+ contextTokens: parsed.contextTokens ?? {},
710
+ }, null, 2)}\n`, 'utf8')
711
+ } catch { /* 无登录态 */ }
712
+ }