@michengai/dsh-im-connect 0.1.19 → 0.1.21

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 (67) hide show
  1. package/README.en.md +2 -2
  2. package/README.md +2 -2
  3. package/SECURITY.md +1 -1
  4. package/lib/channels/dingtalk-card.d.ts.map +1 -1
  5. package/lib/channels/dingtalk-card.js +3 -0
  6. package/lib/channels/dingtalk-card.js.map +1 -1
  7. package/lib/channels/dingtalk.d.ts.map +1 -1
  8. package/lib/channels/dingtalk.js +6 -1
  9. package/lib/channels/dingtalk.js.map +1 -1
  10. package/lib/channels/feishu.d.ts +9 -0
  11. package/lib/channels/feishu.d.ts.map +1 -1
  12. package/lib/channels/feishu.js +23 -6
  13. package/lib/channels/feishu.js.map +1 -1
  14. package/lib/channels/qq.d.ts.map +1 -1
  15. package/lib/channels/qq.js +17 -1
  16. package/lib/channels/qq.js.map +1 -1
  17. package/lib/channels/telegram.d.ts.map +1 -1
  18. package/lib/channels/telegram.js +17 -4
  19. package/lib/channels/telegram.js.map +1 -1
  20. package/lib/channels/wecom.d.ts +7 -1
  21. package/lib/channels/wecom.d.ts.map +1 -1
  22. package/lib/channels/wecom.js +44 -11
  23. package/lib/channels/wecom.js.map +1 -1
  24. package/lib/channels/weixin.d.ts +3 -0
  25. package/lib/channels/weixin.d.ts.map +1 -1
  26. package/lib/channels/weixin.js +68 -15
  27. package/lib/channels/weixin.js.map +1 -1
  28. package/lib/engine/abort.d.ts +4 -0
  29. package/lib/engine/abort.d.ts.map +1 -0
  30. package/lib/engine/abort.js +26 -0
  31. package/lib/engine/abort.js.map +1 -0
  32. package/lib/engine/atomic-file.d.ts +5 -0
  33. package/lib/engine/atomic-file.d.ts.map +1 -0
  34. package/lib/engine/atomic-file.js +46 -0
  35. package/lib/engine/atomic-file.js.map +1 -0
  36. package/lib/engine/json-state.d.ts.map +1 -1
  37. package/lib/engine/json-state.js +7 -5
  38. package/lib/engine/json-state.js.map +1 -1
  39. package/lib/engine/secure-file.d.ts.map +1 -1
  40. package/lib/engine/secure-file.js +2 -12
  41. package/lib/engine/secure-file.js.map +1 -1
  42. package/lib/engine/seen-store.d.ts.map +1 -1
  43. package/lib/engine/seen-store.js +4 -4
  44. package/lib/engine/seen-store.js.map +1 -1
  45. package/lib/engine/session-store.d.ts.map +1 -1
  46. package/lib/engine/session-store.js +7 -5
  47. package/lib/engine/session-store.js.map +1 -1
  48. package/lib/manager.d.ts +7 -0
  49. package/lib/manager.d.ts.map +1 -1
  50. package/lib/manager.js +50 -42
  51. package/lib/manager.js.map +1 -1
  52. package/package.json +1 -1
  53. package/src/channels/dingtalk-card.ts +195 -192
  54. package/src/channels/dingtalk.ts +144 -140
  55. package/src/channels/feishu.ts +92 -66
  56. package/src/channels/qq.ts +303 -288
  57. package/src/channels/telegram.ts +170 -158
  58. package/src/channels/wecom.ts +209 -177
  59. package/src/channels/weixin.ts +158 -112
  60. package/src/engine/abort.ts +25 -0
  61. package/src/engine/access.ts +34 -34
  62. package/src/engine/atomic-file.ts +36 -0
  63. package/src/engine/json-state.ts +16 -15
  64. package/src/engine/secure-file.ts +7 -13
  65. package/src/engine/seen-store.ts +39 -39
  66. package/src/engine/session-store.ts +40 -39
  67. package/src/manager.ts +346 -321
@@ -10,27 +10,30 @@
10
10
  * @module dsh-im-gateway/channels/wechat
11
11
  */
12
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'
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
17
  import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto'
18
18
  import { writePrivateFileSync } from '../engine/secure-file.js'
19
-
20
- export interface WeixinChannelConfig {
21
- enabled?: boolean
22
- /** 登录/上下文/媒体落盘目录。 */
23
- stateDir?: string
24
- pollTimeoutSecs?: number
25
- /** 由 Host credentials vault 注入,不写入微信状态文件。 */
26
- botToken?: string
27
- /** 登录态刷新或失效时同步回 Host credentials vault。 */
28
- onBotToken?: (token: string | undefined) => void | Promise<void>
29
- }
19
+ import { isAbortError, sleepWithSignal, timeoutSignal } from '../engine/abort.js'
20
+ import { backupCorruptFileSync } from '../engine/atomic-file.js'
21
+
22
+ export interface WeixinChannelConfig {
23
+ enabled?: boolean
24
+ /** 登录/上下文/媒体落盘目录。 */
25
+ stateDir?: string
26
+ pollTimeoutSecs?: number
27
+ /** 由 Host credentials vault 注入,不写入微信状态文件。 */
28
+ botToken?: string
29
+ /** 登录态刷新或失效时同步回 Host credentials vault。 */
30
+ onBotToken?: (token: string | undefined) => void | Promise<void>
31
+ }
30
32
 
31
33
  const BASE_URL = 'https://ilinkai.weixin.qq.com'
32
34
  /** CDN 基址(官方插件同款)。 */
33
- export const CDN_BASE_URL = 'https://novac2c.cdn.weixin.qq.com/c2c'
35
+ export const CDN_BASE_URL = 'https://novac2c.cdn.weixin.qq.com/c2c'
36
+ export const MAX_WEIXIN_MEDIA_BYTES = 50 * 1024 * 1024
34
37
 
35
38
  /** 消息 item 类型:1=文本 2=图片 3=语音 4=文件 5=视频。 */
36
39
  const ITEM_TEXT = 1
@@ -47,8 +50,8 @@ const UPLOAD_FILE = 3
47
50
  interface WechatState {
48
51
  allowedUserId?: string
49
52
  contextTokens: Record<string, string>
50
- /** 旧版本遗留字段;读取后由 manager 迁移到 credentials vault。 */
51
- botToken?: string
53
+ /** 旧版本遗留字段;读取后由 manager 迁移到 credentials vault。 */
54
+ botToken?: string
52
55
  /** 服务端下发的 base URL(可能变化)。 */
53
56
  baseUrl?: string
54
57
  /** 轮询游标(重启恢复避免消息重复/丢失)。 */
@@ -117,7 +120,7 @@ function guessExt(name: string): string {
117
120
  return m ? `.${m[1]!.toLowerCase()}` : '.bin'
118
121
  }
119
122
 
120
- export function mimeFromExt(ext: string): string {
123
+ export function mimeFromExt(ext: string): string {
121
124
  const map: Record<string, string> = {
122
125
  '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.gif': 'image/gif', '.webp': 'image/webp', '.bmp': 'image/bmp',
123
126
  '.mp4': 'video/mp4', '.mov': 'video/quicktime', '.avi': 'video/x-msvideo', '.mkv': 'video/x-matroska',
@@ -127,20 +130,49 @@ export function mimeFromExt(ext: string): string {
127
130
  '.mp3': 'audio/mpeg', '.wav': 'audio/wav', '.silk': 'audio/silk', '.amr': 'audio/amr',
128
131
  }
129
132
  return map[ext] ?? 'application/octet-stream'
133
+ }
134
+
135
+ /** 为每个入站媒体生成不可复用的安全文件名,避免同名附件互相覆盖。 */
136
+ export function uniqueMediaFileName(prefix: string, ext: string, name?: string): string {
137
+ const safePrefix = prefix.replace(/[^\w-]+/g, '_') || 'media'
138
+ const normalizedName = (name ?? `${safePrefix}${ext}`).replace(/[^\w.\-\u4e00-\u9fa5]+/g, '_')
139
+ const safeName = normalizedName.replace(/^\.+/, '') || `${safePrefix}${ext}`
140
+ const withExt = safeName.endsWith(ext) || safeName.includes('.') ? safeName : `${safeName}${ext}`
141
+ return `${safePrefix}-${Date.now()}-${randomBytes(6).toString('hex')}-${withExt}`
142
+ }
143
+
144
+ export function isStaleWeixinTokenError(error: unknown): boolean {
145
+ const message = error instanceof Error ? error.message : String(error)
146
+ return /(?:ret|errcode)\s*=\s*-14(?:\D|$)/i.test(message)
130
147
  }
131
148
 
132
- /** 为每个入站媒体生成不可复用的安全文件名,避免同名附件互相覆盖。 */
133
- export function uniqueMediaFileName(prefix: string, ext: string, name?: string): string {
134
- const safePrefix = prefix.replace(/[^\w-]+/g, '_') || 'media'
135
- const normalizedName = (name ?? `${safePrefix}${ext}`).replace(/[^\w.\-\u4e00-\u9fa5]+/g, '_')
136
- const safeName = normalizedName.replace(/^\.+/, '') || `${safePrefix}${ext}`
137
- const withExt = safeName.endsWith(ext) || safeName.includes('.') ? safeName : `${safeName}${ext}`
138
- return `${safePrefix}-${Date.now()}-${randomBytes(6).toString('hex')}-${withExt}`
139
- }
140
-
141
- export function isStaleWeixinTokenError(error: unknown): boolean {
142
- const message = error instanceof Error ? error.message : String(error)
143
- return /(?:ret|errcode)\s*=\s*-14(?:\D|$)/i.test(message)
149
+ /** 即使响应未提供可信 content-length,也按实际读取字节数执行硬上限。 */
150
+ export async function readResponseBufferLimited(response: Response, maxBytes: number): Promise<Buffer> {
151
+ const declared = Number(response.headers.get('content-length') ?? '')
152
+ if (Number.isFinite(declared) && declared > maxBytes) throw new Error(`媒体超过 ${maxBytes} 字节上限`)
153
+ if (!response.body) {
154
+ const buf = Buffer.from(await response.arrayBuffer())
155
+ if (buf.length > maxBytes) throw new Error(`媒体超过 ${maxBytes} 字节上限`)
156
+ return buf
157
+ }
158
+ const reader = response.body.getReader()
159
+ const chunks: Buffer[] = []
160
+ let total = 0
161
+ try {
162
+ while (true) {
163
+ const { done, value } = await reader.read()
164
+ if (done) break
165
+ total += value.byteLength
166
+ if (total > maxBytes) {
167
+ await reader.cancel().catch(() => undefined)
168
+ throw new Error(`媒体超过 ${maxBytes} 字节上限`)
169
+ }
170
+ chunks.push(Buffer.from(value))
171
+ }
172
+ } finally {
173
+ reader.releaseLock()
174
+ }
175
+ return Buffer.concat(chunks, total)
144
176
  }
145
177
 
146
178
  /** 从 CDNMedia 取下载 URL(encrypt_query_param 优先,full_url 兜底)。 */
@@ -161,12 +193,15 @@ export function createWeixinChannel(config: WeixinChannelConfig, log: (line: str
161
193
  const loginPath = join(dir, 'wechat-login.txt')
162
194
 
163
195
  let state: WechatState = loadState()
164
- let handler: ((msg: ImMessage) => void | Promise<void>) | undefined
165
- let stopped = false
196
+ let handler: ((msg: ImMessage) => void | Promise<void>) | undefined
197
+ let stopped = false
198
+ let lifecycle: AbortController | undefined
199
+ let pollTask: Promise<void> | undefined
166
200
  let botToken = config.botToken?.trim() ?? ''
167
201
  let statusText = '未登录'
168
202
  /** 当前登录二维码 URL(UI 轮询用)。 */
169
- let currentLoginUrl: string | undefined
203
+ let currentLoginUrl: string | undefined
204
+ let lastFlushed = ''
170
205
 
171
206
  const uin = Buffer.from(String(Math.floor(Math.random() * 0xffffffff)), 'utf8').toString('base64')
172
207
  /** typing_ticket 按用户缓存。 */
@@ -183,17 +218,21 @@ export function createWeixinChannel(config: WeixinChannelConfig, log: (line: str
183
218
  baseUrl: parsed.baseUrl,
184
219
  syncBuf: parsed.syncBuf,
185
220
  }
186
- } catch {
187
- return { contextTokens: {} }
221
+ } catch {
222
+ backupCorruptFileSync(statePath)
223
+ return { contextTokens: {} }
188
224
  }
189
225
  }
190
226
 
191
- function flush(): void {
192
- try {
193
- mkdirSync(dir, { recursive: true })
227
+ function flush(): void {
228
+ try {
229
+ mkdirSync(dir, { recursive: true })
194
230
  // botToken 只允许存在于 credentials vault;兼容读取旧状态但绝不再次落回本文件。
195
231
  const { botToken: _legacyToken, ...publicState } = state
196
- writePrivateFileSync(statePath, `${JSON.stringify(publicState, null, 2)}\n`)
232
+ const serialized = `${JSON.stringify(publicState, null, 2)}\n`
233
+ if (serialized === lastFlushed) return
234
+ writePrivateFileSync(statePath, serialized)
235
+ lastFlushed = serialized
197
236
  } catch (err) {
198
237
  log(`[weixin] 状态落盘失败: ${err instanceof Error ? err.message : String(err)}`)
199
238
  }
@@ -218,7 +257,7 @@ export function createWeixinChannel(config: WeixinChannelConfig, log: (line: str
218
257
  method: 'POST',
219
258
  headers: headers(),
220
259
  body: JSON.stringify(body),
221
- signal: AbortSignal.timeout(timeoutMs),
260
+ signal: timeoutSignal(timeoutMs, lifecycle?.signal),
222
261
  })
223
262
  if (!res.ok) throw new Error(`weixin ${path} http ${res.status}`)
224
263
  const data = (await res.json()) as Json
@@ -238,14 +277,14 @@ export function createWeixinChannel(config: WeixinChannelConfig, log: (line: str
238
277
  qr = await request('/ilink/bot/get_bot_qrcode?bot_type=3', {}, 15_000)
239
278
  } catch (err) {
240
279
  log(`[weixin] 获取二维码失败,5s 后重试: ${err instanceof Error ? err.message : String(err)}`)
241
- await sleep(5000)
280
+ await sleepWithSignal(5000, lifecycle?.signal)
242
281
  continue
243
282
  }
244
283
  const qrcodeId = pickStr(qr, 'qrcode', 'qrcode_id')
245
284
  const qrUrl = pickStr(qr, 'qrcode_img_content', 'qrcode_url', 'url')
246
285
  if (!qrcodeId || !qrUrl) {
247
286
  log('[weixin] 二维码字段缺失,5s 后重试')
248
- await sleep(5000)
287
+ await sleepWithSignal(5000, lifecycle?.signal)
249
288
  continue
250
289
  }
251
290
  statusText = '等待扫码'
@@ -261,19 +300,19 @@ export function createWeixinChannel(config: WeixinChannelConfig, log: (line: str
261
300
  try {
262
301
  st = await request(`/ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(qrcodeId)}`, {}, 40_000, true)
263
302
  } catch {
264
- await sleep(2000)
303
+ await sleepWithSignal(2000, lifecycle?.signal)
265
304
  continue
266
305
  }
267
306
  const status = String(st.status ?? '')
268
307
  if (Number(st.ret ?? 0) === 0 && status === 'confirmed') {
269
308
  const token = pickStr(st, 'bot_token')
270
309
  const userId = pickStr(st, 'ilink_user_id')
271
- if (!token || !userId) throw new Error('weixin confirmed 但缺少 token/user')
272
- botToken = token
273
- state.botToken = undefined
274
- try { await config.onBotToken?.(token) } catch (error) {
275
- log(`[weixin] token 写入凭据服务失败: ${error instanceof Error ? error.message : String(error)}`)
276
- }
310
+ if (!token || !userId) throw new Error('weixin confirmed 但缺少 token/user')
311
+ botToken = token
312
+ state.botToken = undefined
313
+ try { await config.onBotToken?.(token) } catch (error) {
314
+ log(`[weixin] token 写入凭据服务失败: ${error instanceof Error ? error.message : String(error)}`)
315
+ }
277
316
  const newBaseUrl = pickStr(st, 'baseurl', 'base_url')
278
317
  if (newBaseUrl) state.baseUrl = newBaseUrl
279
318
  if (!state.allowedUserId) {
@@ -293,7 +332,7 @@ export function createWeixinChannel(config: WeixinChannelConfig, log: (line: str
293
332
  log('[weixin] 二维码已过期,重新获取')
294
333
  break
295
334
  }
296
- await sleep(2000)
335
+ await sleepWithSignal(2000, lifecycle?.signal)
297
336
  }
298
337
  }
299
338
  return false
@@ -304,9 +343,9 @@ export function createWeixinChannel(config: WeixinChannelConfig, log: (line: str
304
343
  const url = cdnUrlOf(mediaRef)
305
344
  if (!url) return undefined
306
345
  try {
307
- const res = await fetch(url, { signal: AbortSignal.timeout(60_000) })
308
- if (!res.ok) throw new Error(`CDN 下载 HTTP ${res.status}`)
309
- const buf = Buffer.from(await res.arrayBuffer())
346
+ const res = await fetch(url, { signal: timeoutSignal(60_000, lifecycle?.signal) })
347
+ if (!res.ok) throw new Error(`CDN 下载 HTTP ${res.status}`)
348
+ const buf = await readResponseBufferLimited(res, MAX_WEIXIN_MEDIA_BYTES)
310
349
  const plain = aesKey ? decryptAesEcb(buf, aesKey) : buf
311
350
  return { buf: plain, contentType: res.headers.get('content-type') ?? undefined }
312
351
  } catch (err) {
@@ -316,10 +355,10 @@ export function createWeixinChannel(config: WeixinChannelConfig, log: (line: str
316
355
  }
317
356
 
318
357
  /** 保存媒体字节到媒体目录。 */
319
- function saveMediaBuf(buf: Buffer, ext: string, prefix: string, name?: string): string {
320
- mkdirSync(mediaDir, { recursive: true })
321
- const filePath = join(mediaDir, uniqueMediaFileName(prefix, ext, name))
322
- writeFileSync(filePath, buf)
358
+ function saveMediaBuf(buf: Buffer, ext: string, prefix: string, name?: string): string {
359
+ mkdirSync(mediaDir, { recursive: true })
360
+ const filePath = join(mediaDir, uniqueMediaFileName(prefix, ext, name))
361
+ writeFileSync(filePath, buf)
323
362
  return filePath
324
363
  }
325
364
 
@@ -433,8 +472,8 @@ export function createWeixinChannel(config: WeixinChannelConfig, log: (line: str
433
472
 
434
473
  async function pollLoop(): Promise<void> {
435
474
  // 已有保存的登录态 → 跳过扫码直接轮询(重启免扫码)
436
- if (botToken) {
437
- statusText = '已登录(自动恢复)'
475
+ if (botToken) {
476
+ statusText = '已登录(自动恢复)'
438
477
  log('[weixin] 检测到已保存的登录态,跳过扫码直接轮询')
439
478
  } else if (!(await loginLoop())) {
440
479
  return
@@ -453,16 +492,16 @@ export function createWeixinChannel(config: WeixinChannelConfig, log: (line: str
453
492
  if (stopped) return
454
493
  const msg = err instanceof Error ? err.message : String(err)
455
494
  // token 失效(服务端 errcode -14,与官方插件 STALE_TOKEN_ERRCODE 一致)
456
- if (isStaleWeixinTokenError(err)) {
495
+ if (isStaleWeixinTokenError(err)) {
457
496
  staleCount += 1
458
497
  if (staleCount >= 3) {
459
- log('[weixin] 登录态已失效(连续 3 次),清除登录信息,需要重新扫码')
460
- botToken = ''
461
- state.botToken = undefined
462
- state.syncBuf = undefined
463
- try { await config.onBotToken?.(undefined) } catch (error) {
464
- log(`[weixin] 清除失效 token 失败: ${error instanceof Error ? error.message : String(error)}`)
465
- }
498
+ log('[weixin] 登录态已失效(连续 3 次),清除登录信息,需要重新扫码')
499
+ botToken = ''
500
+ state.botToken = undefined
501
+ state.syncBuf = undefined
502
+ try { await config.onBotToken?.(undefined) } catch (error) {
503
+ log(`[weixin] 清除失效 token 失败: ${error instanceof Error ? error.message : String(error)}`)
504
+ }
466
505
  flush()
467
506
  if (!(await loginLoop())) return
468
507
  staleCount = 0
@@ -470,12 +509,12 @@ export function createWeixinChannel(config: WeixinChannelConfig, log: (line: str
470
509
  continue
471
510
  }
472
511
  log(`[weixin] 登录态失效(${staleCount}/3),5 分钟后重试(若持续失效请重新扫码)`)
473
- await sleep(300_000)
512
+ await sleepWithSignal(300_000, lifecycle?.signal)
474
513
  continue
475
514
  }
476
515
  staleCount = 0
477
516
  log(`[weixin] 长轮询失败,5s 后重试: ${msg}`)
478
- await sleep(5000)
517
+ await sleepWithSignal(5000, lifecycle?.signal)
479
518
  continue
480
519
  }
481
520
  staleCount = 0
@@ -598,7 +637,7 @@ export function createWeixinChannel(config: WeixinChannelConfig, log: (line: str
598
637
  method: 'POST',
599
638
  headers: { 'content-type': 'application/octet-stream' },
600
639
  body: new Uint8Array(ciphertext),
601
- signal: AbortSignal.timeout(120_000),
640
+ signal: timeoutSignal(120_000, lifecycle?.signal),
602
641
  })
603
642
  if (upRes.status !== 200) {
604
643
  const errMsg = upRes.headers.get('x-error-message') ?? `HTTP ${upRes.status}`
@@ -663,14 +702,26 @@ export function createWeixinChannel(config: WeixinChannelConfig, log: (line: str
663
702
  id: 'weixin',
664
703
  label: '微信',
665
704
  maxMessageLength: 1200,
666
- async start() {
667
- stopped = false
668
- statusText = '登录中'
669
- void pollLoop()
670
- },
671
- async stop() {
672
- stopped = true
673
- flush()
705
+ async start() {
706
+ lifecycle?.abort()
707
+ lifecycle = new AbortController()
708
+ stopped = false
709
+ statusText = '登录中'
710
+ pollTask = pollLoop().catch((error) => {
711
+ if (stopped || isAbortError(error)) return
712
+ statusText = '连接失败'
713
+ currentLoginUrl = undefined
714
+ log(`[weixin] 轮询循环退出: ${error instanceof Error ? error.message : String(error)}`)
715
+ })
716
+ },
717
+ async stop() {
718
+ stopped = true
719
+ lifecycle?.abort()
720
+ await pollTask?.catch(() => undefined)
721
+ pollTask = undefined
722
+ lifecycle = undefined
723
+ statusText = '已停止'
724
+ flush()
674
725
  },
675
726
  async send(chatId, text) {
676
727
  await sendText(chatId, text)
@@ -697,16 +748,11 @@ export function createWeixinChannel(config: WeixinChannelConfig, log: (line: str
697
748
  }
698
749
  }
699
750
 
700
- function sleep(ms: number): Promise<void> {
701
- return new Promise((resolve) => setTimeout(resolve, ms))
702
- }
703
-
704
-
705
- export function weixinStatePath(stateDir: string): string {
751
+ export function weixinStatePath(stateDir: string): string {
706
752
  return join(stateDir, 'wechat-state.json')
707
753
  }
708
754
 
709
- export function readWeixinAllowedUserId(stateDir: string): string | undefined {
755
+ export function readWeixinAllowedUserId(stateDir: string): string | undefined {
710
756
  try {
711
757
  const parsed = JSON.parse(readFileSync(weixinStatePath(stateDir), 'utf8')) as Partial<WechatState>
712
758
  const id = parsed.allowedUserId?.trim()
@@ -714,46 +760,46 @@ export function readWeixinAllowedUserId(stateDir: string): string | undefined {
714
760
  } catch {
715
761
  return undefined
716
762
  }
717
- }
718
-
719
- /** 读取旧版本明文登录 token,仅供 manager 一次性迁移到 credentials vault。 */
720
- export function readLegacyWeixinBotToken(stateDir: string): string | undefined {
721
- try {
722
- const parsed = JSON.parse(readFileSync(weixinStatePath(stateDir), 'utf8')) as Partial<WechatState>
723
- return parsed.botToken?.trim() || undefined
724
- } catch {
725
- return undefined
726
- }
727
- }
728
-
729
- export function persistWeixinLogin(stateDir: string, data: { allowedUserId?: string; baseUrl?: string }): void {
730
- mkdirSync(stateDir, { recursive: true })
731
- const file = weixinStatePath(stateDir)
763
+ }
764
+
765
+ /** 读取旧版本明文登录 token,仅供 manager 一次性迁移到 credentials vault。 */
766
+ export function readLegacyWeixinBotToken(stateDir: string): string | undefined {
767
+ try {
768
+ const parsed = JSON.parse(readFileSync(weixinStatePath(stateDir), 'utf8')) as Partial<WechatState>
769
+ return parsed.botToken?.trim() || undefined
770
+ } catch {
771
+ return undefined
772
+ }
773
+ }
774
+
775
+ export function persistWeixinLogin(stateDir: string, data: { allowedUserId?: string; baseUrl?: string }): void {
776
+ mkdirSync(stateDir, { recursive: true })
777
+ const file = weixinStatePath(stateDir)
732
778
  let prev: WechatState = { contextTokens: {} }
733
779
  try {
734
780
  const parsed = JSON.parse(readFileSync(file, 'utf8')) as Partial<WechatState>
735
781
  prev = {
736
782
  allowedUserId: parsed.allowedUserId,
737
783
  contextTokens: parsed.contextTokens ?? {},
738
- baseUrl: parsed.baseUrl,
739
- syncBuf: parsed.syncBuf,
784
+ baseUrl: parsed.baseUrl,
785
+ syncBuf: parsed.syncBuf,
740
786
  }
741
787
  } catch { /* 首次写入 */ }
742
788
  const next: WechatState = {
743
789
  ...prev,
744
- allowedUserId: data.allowedUserId || prev.allowedUserId,
745
- baseUrl: data.baseUrl || prev.baseUrl,
746
- }
747
- writePrivateFileSync(file, `${JSON.stringify(next, null, 2)}\n`)
748
- }
790
+ allowedUserId: data.allowedUserId || prev.allowedUserId,
791
+ baseUrl: data.baseUrl || prev.baseUrl,
792
+ }
793
+ writePrivateFileSync(file, `${JSON.stringify(next, null, 2)}\n`)
794
+ }
749
795
 
750
796
  export function clearWeixinLogin(stateDir: string): void {
751
797
  const file = weixinStatePath(stateDir)
752
798
  try {
753
799
  const parsed = JSON.parse(readFileSync(file, 'utf8')) as Partial<WechatState>
754
- writePrivateFileSync(file, `${JSON.stringify({
755
- allowedUserId: parsed.allowedUserId,
756
- contextTokens: parsed.contextTokens ?? {},
757
- }, null, 2)}\n`)
800
+ writePrivateFileSync(file, `${JSON.stringify({
801
+ allowedUserId: parsed.allowedUserId,
802
+ contextTokens: parsed.contextTokens ?? {},
803
+ }, null, 2)}\n`)
758
804
  } catch { /* 无登录态 */ }
759
805
  }
@@ -0,0 +1,25 @@
1
+ export function timeoutSignal(timeoutMs: number, parent?: AbortSignal): AbortSignal {
2
+ const timeout = AbortSignal.timeout(timeoutMs)
3
+ return parent ? AbortSignal.any([parent, timeout]) : timeout
4
+ }
5
+
6
+ export function isAbortError(error: unknown): boolean {
7
+ return error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError')
8
+ }
9
+
10
+ export function sleepWithSignal(ms: number, signal?: AbortSignal): Promise<void> {
11
+ if (!signal) return new Promise((resolve) => setTimeout(resolve, ms))
12
+ if (signal.aborted) return Promise.reject(signal.reason)
13
+ return new Promise((resolve, reject) => {
14
+ const timer = setTimeout(done, ms)
15
+ signal.addEventListener('abort', aborted, { once: true })
16
+ function done() {
17
+ signal!.removeEventListener('abort', aborted)
18
+ resolve()
19
+ }
20
+ function aborted() {
21
+ clearTimeout(timer)
22
+ reject(signal!.reason)
23
+ }
24
+ })
25
+ }
@@ -1,34 +1,34 @@
1
- /** 群聊不用绑定;私聊只有白名单用户可驱动,缺 userId 拒绝。 */
2
- export type AccessDecision = 'allow' | 'deny' | 'ignore'
3
-
4
- export function normalizeUserId(userId?: string): string {
5
- return userId?.trim() ?? ''
6
- }
7
-
8
- export function isUserAllowed(allowlist: Iterable<string>, userId?: string): boolean {
9
- const id = normalizeUserId(userId)
10
- if (!id) return false
11
- for (const item of allowlist) {
12
- if (item === id) return true
13
- }
14
- return false
15
- }
16
-
17
- export function decideAccess(input: {
18
- userAllowed: boolean
19
- kind?: 'dm' | 'group'
20
- addressed?: boolean
21
- }): AccessDecision {
22
- if (input.kind === 'group') {
23
- return input.addressed === false ? 'ignore' : 'allow'
24
- }
25
- return input.userAllowed ? 'allow' : 'deny'
26
- }
27
-
28
- /** 工具授权比普通消息更严:必须已在白名单,且只能在私聊里答复。 */
29
- export function canAnswerToolApproval(input: {
30
- userAllowed: boolean
31
- kind?: 'dm' | 'group'
32
- }): boolean {
33
- return input.userAllowed && input.kind !== 'group'
34
- }
1
+ /** 群聊不用绑定;私聊只有白名单用户可驱动,缺 userId 拒绝。 */
2
+ export type AccessDecision = 'allow' | 'deny' | 'ignore'
3
+
4
+ export function normalizeUserId(userId?: string): string {
5
+ return userId?.trim() ?? ''
6
+ }
7
+
8
+ export function isUserAllowed(allowlist: Iterable<string>, userId?: string): boolean {
9
+ const id = normalizeUserId(userId)
10
+ if (!id) return false
11
+ for (const item of allowlist) {
12
+ if (item === id) return true
13
+ }
14
+ return false
15
+ }
16
+
17
+ export function decideAccess(input: {
18
+ userAllowed: boolean
19
+ kind?: 'dm' | 'group'
20
+ addressed?: boolean
21
+ }): AccessDecision {
22
+ if (input.kind === 'group') {
23
+ return input.addressed === false ? 'ignore' : 'allow'
24
+ }
25
+ return input.userAllowed ? 'allow' : 'deny'
26
+ }
27
+
28
+ /** 工具授权比普通消息更严:必须已在白名单,且只能在私聊里答复。 */
29
+ export function canAnswerToolApproval(input: {
30
+ userAllowed: boolean
31
+ kind?: 'dm' | 'group'
32
+ }): boolean {
33
+ return input.userAllowed && input.kind !== 'group'
34
+ }
@@ -0,0 +1,36 @@
1
+ import { randomBytes } from 'node:crypto'
2
+ import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'
3
+ import { basename, dirname, join } from 'node:path'
4
+
5
+ /** 在目标文件同目录写临时文件,再原子替换,避免进程中断留下半截内容。 */
6
+ export function writeFileAtomicSync(file: string, data: string, mode?: number): void {
7
+ const dir = dirname(file)
8
+ mkdirSync(dir, { recursive: true })
9
+ const temp = join(dir, `.${basename(file)}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`)
10
+ let fd: number | undefined
11
+ try {
12
+ fd = openSync(temp, 'wx', mode)
13
+ writeFileSync(fd, data, 'utf8')
14
+ fsyncSync(fd)
15
+ closeSync(fd)
16
+ fd = undefined
17
+ if (mode !== undefined) {
18
+ try { chmodSync(temp, mode) } catch { /* Windows 或受限文件系统不支持 POSIX mode */ }
19
+ }
20
+ renameSync(temp, file)
21
+ } finally {
22
+ if (fd !== undefined) {
23
+ try { closeSync(fd) } catch { /* 已关闭 */ }
24
+ }
25
+ try { unlinkSync(temp) } catch { /* rename 成功或临时文件尚未创建 */ }
26
+ }
27
+ }
28
+
29
+ /** 在回退为空状态前保留不可解析文件的唯一副本。 */
30
+ export function backupCorruptFileSync(file: string): string | undefined {
31
+ if (!existsSync(file)) return undefined
32
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-')
33
+ const backup = `${file}.corrupt-${stamp}-${process.pid}`
34
+ renameSync(file, backup)
35
+ return backup
36
+ }
@@ -1,20 +1,21 @@
1
- import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
2
- import { dirname } from 'node:path'
3
-
4
- export class JsonStateFile<T extends object> {
5
- constructor(private readonly file: string, private readonly fallback: T) {}
6
-
7
- read(): T {
8
- try {
1
+ import { readFileSync } from 'node:fs'
2
+ import { backupCorruptFileSync, writeFileAtomicSync } from './atomic-file.js'
3
+
4
+ export class JsonStateFile<T extends object> {
5
+ constructor(private readonly file: string, private readonly fallback: T) {}
6
+
7
+ read(): T {
8
+ try {
9
9
  const parsed = JSON.parse(readFileSync(this.file, 'utf8')) as T
10
- return parsed && typeof parsed === 'object' ? parsed : structuredClone(this.fallback)
10
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new TypeError('状态文件顶层必须是对象')
11
+ return parsed
11
12
  } catch {
13
+ backupCorruptFileSync(this.file)
12
14
  return structuredClone(this.fallback)
13
- }
14
- }
15
-
15
+ }
16
+ }
17
+
16
18
  write(value: T): void {
17
- mkdirSync(dirname(this.file), { recursive: true })
18
- writeFileSync(this.file, `${JSON.stringify(value, null, 2)}\n`, 'utf8')
19
+ writeFileAtomicSync(this.file, `${JSON.stringify(value, null, 2)}\n`)
19
20
  }
20
- }
21
+ }
@@ -1,15 +1,9 @@
1
- import { chmodSync, closeSync, openSync, writeFileSync } from 'node:fs'
2
-
3
- /**
4
- * 覆盖写入仅供当前用户读取的本地状态文件。
5
- * POSIX 上 mode/chmod 会强制 0600;Windows 会继续继承用户目录 ACL。
6
- */
1
+ import { writeFileAtomicSync } from './atomic-file.js'
2
+
3
+ /**
4
+ * 覆盖写入仅供当前用户读取的本地状态文件。
5
+ * POSIX 上 mode/chmod 会强制 0600;Windows 会继续继承用户目录 ACL。
6
+ */
7
7
  export function writePrivateFileSync(file: string, data: string): void {
8
- const fd = openSync(file, 'w', 0o600)
9
- try {
10
- writeFileSync(fd, data, 'utf8')
11
- } finally {
12
- closeSync(fd)
13
- }
14
- try { chmodSync(file, 0o600) } catch { /* Windows 或受限文件系统不支持 POSIX mode */ }
8
+ writeFileAtomicSync(file, data, 0o600)
15
9
  }