@michengai/dsh-im-connect 0.1.20 → 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 (66) 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.map +1 -1
  49. package/lib/manager.js +4 -9
  50. package/lib/manager.js.map +1 -1
  51. package/package.json +1 -1
  52. package/src/channels/dingtalk-card.ts +195 -192
  53. package/src/channels/dingtalk.ts +144 -140
  54. package/src/channels/feishu.ts +92 -66
  55. package/src/channels/qq.ts +303 -288
  56. package/src/channels/telegram.ts +170 -158
  57. package/src/channels/wecom.ts +209 -177
  58. package/src/channels/weixin.ts +158 -112
  59. package/src/engine/abort.ts +25 -0
  60. package/src/engine/access.ts +34 -34
  61. package/src/engine/atomic-file.ts +36 -0
  62. package/src/engine/json-state.ts +16 -15
  63. package/src/engine/secure-file.ts +7 -13
  64. package/src/engine/seen-store.ts +39 -39
  65. package/src/engine/session-store.ts +40 -39
  66. package/src/manager.ts +346 -350
package/src/manager.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Context } from '@deepseek-ai/cordis'
2
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
2
+ import { readFileSync } from 'node:fs'
3
3
  import { join } from 'node:path'
4
4
  import { createChannelAdapter } from './channels/factory.js'
5
5
  import { CHANNEL_META, CHANNEL_ORDER, supportsQr } from './channels/meta.js'
@@ -9,109 +9,106 @@ import { SessionMapStore } from './engine/session-store.js'
9
9
  import { createFileVault, createServiceVault, credentialRef, type CredentialService, type CredentialVault } from './engine/credentials.js'
10
10
  import { ImEngine } from './engine/gateway.js'
11
11
  import { SeenStore } from './engine/seen-store.js'
12
- import { clearWeixinLogin, persistWeixinLogin, readLegacyWeixinBotToken, readWeixinAllowedUserId } from './channels/weixin.js'
12
+ import { clearWeixinLogin, persistWeixinLogin, readLegacyWeixinBotToken, readWeixinAllowedUserId } from './channels/weixin.js'
13
13
  import { normalizeAssistantModel, normalizePermission, normalizeWorkspacePath, type AssistantModel, type PermissionPreset } from './engine/assistant-settings.js'
14
- import type { ChannelAdapter, EngineConfig, ImMessage } from './engine/types.js'
14
+ import type { ChannelAdapter, EngineConfig, ImMessage } from './engine/types.js'
15
15
  import { KeyedSerialQueue } from './engine/keyed-queue.js'
16
-
17
- export const API_CLIENT_HEADER = 'x-dsh-im-connect-client'
18
- const MAX_API_BODY_BYTES = 1024 * 1024
19
-
20
- interface ApiBodyReadResult {
21
- body: Record<string, unknown>
22
- oversized: boolean
23
- invalidJson: boolean
24
- }
25
-
26
- interface ApiRequestErrorShape {
27
- status: number
28
- error: string
29
- }
30
-
31
- class ApiRequestError extends Error {
32
- constructor(readonly status: number, message: string) {
33
- super(message)
34
- }
35
- }
36
-
37
- /** 管理面只接受回环 Host;写请求再用自定义头 + JSON 阻断简单跨站请求。 */
38
- export function validateApiRequest(request: {
39
- method?: string
40
- headers: Record<string, string | string[] | undefined>
41
- remoteAddress?: string
42
- }): ApiRequestErrorShape | undefined {
43
- const remote = request.remoteAddress ?? ''
44
- if (!(remote === '::1' || /^127\./.test(remote) || /^::ffff:127\./i.test(remote))) {
45
- return { status: 403, error: 'forbidden client address' }
46
- }
47
- const hostValue = request.headers.host
48
- const host = String(Array.isArray(hostValue) ? hostValue[0] ?? '' : hostValue ?? '').toLowerCase()
49
- if (!/^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(host)) {
50
- return { status: 403, error: 'forbidden host' }
51
- }
52
- const method = (request.method ?? 'GET').toUpperCase()
53
- if (method === 'GET' || method === 'HEAD') return undefined
54
- const markerValue = request.headers[API_CLIENT_HEADER]
55
- const marker = Array.isArray(markerValue) ? markerValue[0] : markerValue
56
- if (marker !== '1') return { status: 403, error: 'forbidden mutation request' }
57
- const typeValue = request.headers['content-type']
58
- const contentType = String(Array.isArray(typeValue) ? typeValue[0] ?? '' : typeValue ?? '').split(';', 1)[0]!.trim().toLowerCase()
59
- if (contentType !== 'application/json') return { status: 415, error: 'content-type must be application/json' }
60
- return undefined
61
- }
62
-
63
- /** 累计原始字节后一次性解码,避免 UTF-8 多字节字符跨 data chunk 时被替换字符破坏。 */
64
- export function readApiJsonBody(
65
- req: import('node:stream').Readable,
66
- maxBodyBytes = MAX_API_BODY_BYTES,
67
- ): Promise<ApiBodyReadResult> {
68
- return new Promise((resolve) => {
69
- const chunks: Buffer[] = []
70
- let bytes = 0
71
- let oversized = false
72
- let settled = false
73
- const finish = (result: ApiBodyReadResult): void => {
74
- if (settled) return
75
- settled = true
76
- resolve(result)
77
- }
78
- // 超限后停止累计但不掐断连接,等 end 后统一按 413 拒绝,防止内存被撑爆
79
- req.on('data', (chunk: Buffer | string) => {
80
- if (oversized) return
81
- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
82
- bytes += buffer.length
83
- if (bytes > maxBodyBytes) {
84
- oversized = true
85
- chunks.length = 0
86
- return
87
- }
88
- chunks.push(buffer)
89
- })
90
- req.on('error', () => finish({ body: {}, oversized, invalidJson: true }))
91
- req.on('end', () => {
92
- if (oversized) {
93
- finish({ body: {}, oversized: true, invalidJson: false })
94
- return
95
- }
96
- try {
97
- const raw = Buffer.concat(chunks, bytes).toString('utf8')
98
- const parsed = raw ? JSON.parse(raw) as unknown : {}
99
- const valid = parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)
100
- finish({ body: valid ? parsed as Record<string, unknown> : {}, oversized: false, invalidJson: !valid })
101
- } catch {
102
- finish({ body: {}, oversized: false, invalidJson: true })
103
- }
104
- })
105
- })
106
- }
107
-
108
- /** 把不可解析的配置移走后再回到空配置,避免下一次 flush 覆盖唯一副本。 */
16
+ import { backupCorruptFileSync, writeFileAtomicSync } from './engine/atomic-file.js'
17
+
18
+ export const API_CLIENT_HEADER = 'x-dsh-im-connect-client'
19
+ const MAX_API_BODY_BYTES = 1024 * 1024
20
+
21
+ interface ApiBodyReadResult {
22
+ body: Record<string, unknown>
23
+ oversized: boolean
24
+ invalidJson: boolean
25
+ }
26
+
27
+ interface ApiRequestErrorShape {
28
+ status: number
29
+ error: string
30
+ }
31
+
32
+ class ApiRequestError extends Error {
33
+ constructor(readonly status: number, message: string) {
34
+ super(message)
35
+ }
36
+ }
37
+
38
+ /** 管理面只接受回环 Host;写请求再用自定义头 + JSON 阻断简单跨站请求。 */
39
+ export function validateApiRequest(request: {
40
+ method?: string
41
+ headers: Record<string, string | string[] | undefined>
42
+ remoteAddress?: string
43
+ }): ApiRequestErrorShape | undefined {
44
+ const remote = request.remoteAddress ?? ''
45
+ if (!(remote === '::1' || /^127\./.test(remote) || /^::ffff:127\./i.test(remote))) {
46
+ return { status: 403, error: 'forbidden client address' }
47
+ }
48
+ const hostValue = request.headers.host
49
+ const host = String(Array.isArray(hostValue) ? hostValue[0] ?? '' : hostValue ?? '').toLowerCase()
50
+ if (!/^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(host)) {
51
+ return { status: 403, error: 'forbidden host' }
52
+ }
53
+ const method = (request.method ?? 'GET').toUpperCase()
54
+ if (method === 'GET' || method === 'HEAD') return undefined
55
+ const markerValue = request.headers[API_CLIENT_HEADER]
56
+ const marker = Array.isArray(markerValue) ? markerValue[0] : markerValue
57
+ if (marker !== '1') return { status: 403, error: 'forbidden mutation request' }
58
+ const typeValue = request.headers['content-type']
59
+ const contentType = String(Array.isArray(typeValue) ? typeValue[0] ?? '' : typeValue ?? '').split(';', 1)[0]!.trim().toLowerCase()
60
+ if (contentType !== 'application/json') return { status: 415, error: 'content-type must be application/json' }
61
+ return undefined
62
+ }
63
+
64
+ /** 累计原始字节后一次性解码,避免 UTF-8 多字节字符跨 data chunk 时被替换字符破坏。 */
65
+ export function readApiJsonBody(
66
+ req: import('node:stream').Readable,
67
+ maxBodyBytes = MAX_API_BODY_BYTES,
68
+ ): Promise<ApiBodyReadResult> {
69
+ return new Promise((resolve) => {
70
+ const chunks: Buffer[] = []
71
+ let bytes = 0
72
+ let oversized = false
73
+ let settled = false
74
+ const finish = (result: ApiBodyReadResult): void => {
75
+ if (settled) return
76
+ settled = true
77
+ resolve(result)
78
+ }
79
+ // 超限后停止累计但不掐断连接,等 end 后统一按 413 拒绝,防止内存被撑爆
80
+ req.on('data', (chunk: Buffer | string) => {
81
+ if (oversized) return
82
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
83
+ bytes += buffer.length
84
+ if (bytes > maxBodyBytes) {
85
+ oversized = true
86
+ chunks.length = 0
87
+ return
88
+ }
89
+ chunks.push(buffer)
90
+ })
91
+ req.on('error', () => finish({ body: {}, oversized, invalidJson: true }))
92
+ req.on('end', () => {
93
+ if (oversized) {
94
+ finish({ body: {}, oversized: true, invalidJson: false })
95
+ return
96
+ }
97
+ try {
98
+ const raw = Buffer.concat(chunks, bytes).toString('utf8')
99
+ const parsed = raw ? JSON.parse(raw) as unknown : {}
100
+ const valid = parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)
101
+ finish({ body: valid ? parsed as Record<string, unknown> : {}, oversized: false, invalidJson: !valid })
102
+ } catch {
103
+ finish({ body: {}, oversized: false, invalidJson: true })
104
+ }
105
+ })
106
+ })
107
+ }
108
+
109
+ /** 把不可解析的配置移走后再回到空配置,避免下一次 flush 覆盖唯一副本。 */
109
110
  export function backupCorruptConfig(file: string): string | undefined {
110
- if (!existsSync(file)) return undefined
111
- const stamp = new Date().toISOString().replace(/[:.]/g, '-')
112
- const backup = `${file}.corrupt-${stamp}-${process.pid}`
113
- renameSync(file, backup)
114
- return backup
111
+ return backupCorruptFileSync(file)
115
112
  }
116
113
 
117
114
  export interface ChannelState {
@@ -140,26 +137,26 @@ interface PendingRequest {
140
137
  time: number
141
138
  }
142
139
 
143
- interface Persisted {
140
+ interface Persisted {
144
141
  channels: Record<string, ChannelState>
145
142
  allowlist: Record<string, string[]>
146
143
  pending: Record<string, PendingRequest[]>
147
144
  assistant?: AssistantModel
148
145
  cwd?: string
149
- permission?: PermissionPreset
150
- }
151
-
152
- export interface PermissionOptionView {
153
- value: string
154
- name: string
155
- description?: string
156
- }
157
-
158
- interface PermissionPresetService {
159
- readonly names: readonly string[]
160
- readonly defaultPreset: string
161
- optionOf(name: string): PermissionOptionView
162
- }
146
+ permission?: PermissionPreset
147
+ }
148
+
149
+ export interface PermissionOptionView {
150
+ value: string
151
+ name: string
152
+ description?: string
153
+ }
154
+
155
+ interface PermissionPresetService {
156
+ readonly names: readonly string[]
157
+ readonly defaultPreset: string
158
+ optionOf(name: string): PermissionOptionView
159
+ }
163
160
 
164
161
  export class ChannelManager {
165
162
  private readonly file: string
@@ -172,8 +169,8 @@ export class ChannelManager {
172
169
  private readonly ctx: Context
173
170
  private readonly engineConfig: EngineConfig
174
171
  private store: Persisted = { channels: {}, allowlist: {}, pending: {} }
175
- private readonly running = new Map<string, ChannelAdapter>()
176
- private readonly channelOperations = new KeyedSerialQueue()
172
+ private readonly running = new Map<string, ChannelAdapter>()
173
+ private readonly channelOperations = new KeyedSerialQueue()
177
174
  private apiDisposers: Array<() => void> = []
178
175
  // dispose 后阻止 initEnabled/startOne 再拉起渠道,避免插件重载时新旧双实例并存
179
176
  private disposed = false
@@ -253,18 +250,18 @@ export class ChannelManager {
253
250
  }
254
251
  }
255
252
 
256
- async connect(id: ChannelId, config?: Record<string, string>): Promise<{ ok: boolean; error?: string }> {
257
- if (!CHANNEL_META[id]) return { ok: false, error: '未知渠道' }
258
- return this.channelOperations.run(id, () => this.connectNow(id, config))
259
- }
260
-
261
- private async connectNow(id: ChannelId, config?: Record<string, string>): Promise<{ ok: boolean; error?: string }> {
262
- const incoming = { ...(config ?? {}) }
263
- if (id === 'weixin' && incoming.botToken) {
264
- await this.vault.set(credentialRef('weixin', 'botToken'), incoming.botToken)
265
- persistWeixinLogin(join(this.stateDir, 'weixin'), {
266
- allowedUserId: incoming.allowedUserId,
267
- baseUrl: incoming.baseUrl,
253
+ async connect(id: ChannelId, config?: Record<string, string>): Promise<{ ok: boolean; error?: string }> {
254
+ if (!CHANNEL_META[id]) return { ok: false, error: '未知渠道' }
255
+ return this.channelOperations.run(id, () => this.connectNow(id, config))
256
+ }
257
+
258
+ private async connectNow(id: ChannelId, config?: Record<string, string>): Promise<{ ok: boolean; error?: string }> {
259
+ const incoming = { ...(config ?? {}) }
260
+ if (id === 'weixin' && incoming.botToken) {
261
+ await this.vault.set(credentialRef('weixin', 'botToken'), incoming.botToken)
262
+ persistWeixinLogin(join(this.stateDir, 'weixin'), {
263
+ allowedUserId: incoming.allowedUserId,
264
+ baseUrl: incoming.baseUrl,
268
265
  })
269
266
  delete incoming.botToken
270
267
  incoming.bound = '1'
@@ -274,22 +271,22 @@ export class ChannelManager {
274
271
  this.store.channels[id] = { ...prev, enabled: true, receiveEnabled: true, config: nextConfig }
275
272
  this.flush()
276
273
  this.seedAllowedUser(id, incoming.allowedUserId || incoming.ownerOpenId || nextConfig.allowedUserId || nextConfig.ownerOpenId)
277
- try {
278
- await this.startOne(id)
279
- return { ok: true }
280
- } catch (error) {
281
- this.log(`[manager] ${id} 连接失败: ${error instanceof Error ? error.message : String(error)}`)
282
- return { ok: false, error: '渠道连接失败,请查看本机日志' }
274
+ try {
275
+ await this.startOne(id)
276
+ return { ok: true }
277
+ } catch (error) {
278
+ this.log(`[manager] ${id} 连接失败: ${error instanceof Error ? error.message : String(error)}`)
279
+ return { ok: false, error: '渠道连接失败,请查看本机日志' }
283
280
  }
284
281
  }
285
282
 
286
- async setReceive(id: ChannelId, receiveEnabled: boolean): Promise<{ ok: boolean; error?: string }> {
287
- if (!CHANNEL_META[id]) return { ok: false, error: '未知渠道' }
288
- return this.channelOperations.run(id, () => this.setReceiveNow(id, receiveEnabled))
289
- }
290
-
291
- private async setReceiveNow(id: ChannelId, receiveEnabled: boolean): Promise<{ ok: boolean; error?: string }> {
292
- const state = this.store.channels[id]
283
+ async setReceive(id: ChannelId, receiveEnabled: boolean): Promise<{ ok: boolean; error?: string }> {
284
+ if (!CHANNEL_META[id]) return { ok: false, error: '未知渠道' }
285
+ return this.channelOperations.run(id, () => this.setReceiveNow(id, receiveEnabled))
286
+ }
287
+
288
+ private async setReceiveNow(id: ChannelId, receiveEnabled: boolean): Promise<{ ok: boolean; error?: string }> {
289
+ const state = this.store.channels[id]
293
290
  if (!state?.enabled) return { ok: false, error: '渠道未配置' }
294
291
  state.receiveEnabled = receiveEnabled
295
292
  this.flush()
@@ -298,13 +295,13 @@ export class ChannelManager {
298
295
  return { ok: true }
299
296
  }
300
297
 
301
- async disconnect(id: ChannelId): Promise<void> {
302
- if (!CHANNEL_META[id]) return
303
- await this.channelOperations.run(id, () => this.disconnectNow(id))
304
- }
305
-
306
- private async disconnectNow(id: ChannelId): Promise<void> {
307
- const state = this.store.channels[id]
298
+ async disconnect(id: ChannelId): Promise<void> {
299
+ if (!CHANNEL_META[id]) return
300
+ await this.channelOperations.run(id, () => this.disconnectNow(id))
301
+ }
302
+
303
+ private async disconnectNow(id: ChannelId): Promise<void> {
304
+ const state = this.store.channels[id]
308
305
  if (state) {
309
306
  state.enabled = false
310
307
  state.receiveEnabled = false
@@ -314,20 +311,20 @@ export class ChannelManager {
314
311
  await this.stopOne(id)
315
312
  }
316
313
 
317
- async remove(id: ChannelId): Promise<void> {
318
- if (!CHANNEL_META[id]) return
319
- await this.channelOperations.run(id, () => this.removeNow(id))
320
- }
321
-
322
- private async removeNow(id: ChannelId): Promise<void> {
323
- await this.stopOne(id)
314
+ async remove(id: ChannelId): Promise<void> {
315
+ if (!CHANNEL_META[id]) return
316
+ await this.channelOperations.run(id, () => this.removeNow(id))
317
+ }
318
+
319
+ private async removeNow(id: ChannelId): Promise<void> {
320
+ await this.stopOne(id)
324
321
  this.pairing.cancel(id)
325
322
  delete this.store.channels[id]
326
323
  delete this.store.allowlist[id]
327
324
  delete this.store.pending[id]
328
325
  this.flush()
329
- if (id === 'weixin') clearWeixinLogin(join(this.stateDir, 'weixin'))
330
- if (id === 'weixin') await this.vault.unset(credentialRef('weixin', 'botToken')).catch(() => undefined)
326
+ if (id === 'weixin') clearWeixinLogin(join(this.stateDir, 'weixin'))
327
+ if (id === 'weixin') await this.vault.unset(credentialRef('weixin', 'botToken')).catch(() => undefined)
331
328
  for (const field of CHANNEL_META[id].fields.filter((item) => item.secret)) {
332
329
  await this.vault.unset(credentialRef(id, field.key)).catch(() => undefined)
333
330
  }
@@ -337,17 +334,17 @@ export class ChannelManager {
337
334
  return this.engine.attachMappedSessions()
338
335
  }
339
336
 
340
- async initEnabled(): Promise<void> {
341
- const started = Date.now()
342
- await this.migrateLegacyWeixinToken().catch((error) => {
343
- this.log(`[manager] 迁移旧版微信 token 失败,已保留原文件: ${error instanceof Error ? error.message : String(error)}`)
344
- })
345
- for (const id of CHANNEL_ORDER) {
337
+ async initEnabled(): Promise<void> {
338
+ const started = Date.now()
339
+ await this.migrateLegacyWeixinToken().catch((error) => {
340
+ this.log(`[manager] 迁移旧版微信 token 失败,已保留原文件: ${error instanceof Error ? error.message : String(error)}`)
341
+ })
342
+ for (const id of CHANNEL_ORDER) {
346
343
  if (this.disposed) return
347
344
  const state = this.store.channels[id]
348
345
  if (state?.enabled && state.receiveEnabled !== false) {
349
346
  const one = Date.now()
350
- await this.channelOperations.run(id, () => this.startOne(id)).catch((error) => {
347
+ await this.channelOperations.run(id, () => this.startOne(id)).catch((error) => {
351
348
  this.log(`[manager] 启动 ${id} 失败: ${error instanceof Error ? error.message : String(error)}`)
352
349
  })
353
350
  this.log(`[boot] 渠道 ${id} 启动 ${Date.now() - one}ms`)
@@ -371,12 +368,12 @@ export class ChannelManager {
371
368
  res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' })
372
369
  res.end(JSON.stringify(body))
373
370
  }
374
- const readJson = async (req: import('node:http').IncomingMessage): Promise<Record<string, unknown>> => {
375
- const { body, oversized, invalidJson } = await readApiJsonBody(req)
376
- if (oversized) throw new ApiRequestError(413, '请求体超过 1MB 上限')
377
- if (invalidJson) throw new ApiRequestError(400, '请求体不是合法 JSON')
378
- return body
379
- }
371
+ const readJson = async (req: import('node:http').IncomingMessage): Promise<Record<string, unknown>> => {
372
+ const { body, oversized, invalidJson } = await readApiJsonBody(req)
373
+ if (oversized) throw new ApiRequestError(413, '请求体超过 1MB 上限')
374
+ if (invalidJson) throw new ApiRequestError(400, '请求体不是合法 JSON')
375
+ return body
376
+ }
380
377
  const payload = () => ({
381
378
  ok: true,
382
379
  channels: this.list(),
@@ -386,37 +383,37 @@ export class ChannelManager {
386
383
  })
387
384
  const dispose = webServer.register({
388
385
  kind: 'prefix',
389
- path: '/dsh-im-connect/api',
390
- handler: async (req, res) => {
391
- try {
392
- const requestError = validateApiRequest({ method: req.method, headers: req.headers, remoteAddress: req.socket.remoteAddress })
393
- if (requestError) { send(res, requestError.status, { ok: false, error: requestError.error }); return }
394
- const url = new URL(req.url ?? '/', `http://${req.headers.host ?? '127.0.0.1'}`)
386
+ path: '/dsh-im-connect/api',
387
+ handler: async (req, res) => {
388
+ try {
389
+ const requestError = validateApiRequest({ method: req.method, headers: req.headers, remoteAddress: req.socket.remoteAddress })
390
+ if (requestError) { send(res, requestError.status, { ok: false, error: requestError.error }); return }
391
+ const url = new URL(req.url ?? '/', `http://${req.headers.host ?? '127.0.0.1'}`)
395
392
  const parts = url.pathname.split('/').filter(Boolean)
396
393
  if (parts[2] === 'assistant' && parts.length === 3) {
397
394
  if (req.method === 'GET') {
398
- send(res, 200, {
399
- ok: true,
400
- assistant: this.currentAssistant(),
401
- cwd: this.currentWorkspace(),
402
- permission: this.currentPermission(),
403
- permissions: this.permissionOptions(),
404
- providers: await this.listModelCatalog(),
405
- })
395
+ send(res, 200, {
396
+ ok: true,
397
+ assistant: this.currentAssistant(),
398
+ cwd: this.currentWorkspace(),
399
+ permission: this.currentPermission(),
400
+ permissions: this.permissionOptions(),
401
+ providers: await this.listModelCatalog(),
402
+ })
406
403
  return
407
- }
408
- if (req.method === 'POST') {
409
- const body = await readJson(req)
410
- const result = this.setAssistant(body)
404
+ }
405
+ if (req.method === 'POST') {
406
+ const body = await readJson(req)
407
+ const result = this.setAssistant(body)
411
408
  send(res, result.ok ? 200 : 400, result)
412
409
  return
413
410
  }
414
411
  send(res, 405, { ok: false, error: 'method not allowed' })
415
412
  return
416
413
  }
417
- if (parts[2] === 'sessions' && parts.length === 4 && req.method === 'POST') {
418
- const action = parts[3]
419
- const body = await readJson(req)
414
+ if (parts[2] === 'sessions' && parts.length === 4 && req.method === 'POST') {
415
+ const action = parts[3]
416
+ const body = await readJson(req)
420
417
  const sessionId = String(body.sessionId ?? '')
421
418
  if (!sessionId) { send(res, 400, { ok: false, error: '缺少 sessionId' }); return }
422
419
  if (action === 'rename') {
@@ -453,7 +450,7 @@ export class ChannelManager {
453
450
  return
454
451
  }
455
452
  if (req.method !== 'POST') { send(res, 405, { ok: false, error: 'method not allowed' }); return }
456
- await readJson(req)
453
+ await readJson(req)
457
454
  if (action === 'start') {
458
455
  const pairing = await this.pairing.start(id)
459
456
  send(res, pairing.status === 'failed' ? 400 : 200, { ok: pairing.status !== 'failed', pairing, error: pairing.error })
@@ -472,9 +469,9 @@ export class ChannelManager {
472
469
  return
473
470
  }
474
471
  if (parts[2] === 'channels' && parts.length === 5 && req.method === 'POST') {
475
- const id = parts[3] as ChannelId
476
- const action = parts[4]
477
- const body = await readJson(req)
472
+ const id = parts[3] as ChannelId
473
+ const action = parts[4]
474
+ const body = await readJson(req)
478
475
  if (action === 'connect') {
479
476
  const result = await this.connect(id, body.config as Record<string, string> | undefined)
480
477
  send(res, result.ok ? 200 : 400, result.ok ? { ok: true, channel: this.list().find((item) => item.id === id) } : result)
@@ -507,15 +504,15 @@ export class ChannelManager {
507
504
  return
508
505
  }
509
506
  send(res, 404, { ok: false, error: 'not found' })
510
- } catch (error) {
511
- // 单个路由异常不能让 HTTP 连接悬死,统一回 500 并落日志
512
- if (error instanceof ApiRequestError) {
513
- send(res, error.status, { ok: false, error: error.message })
514
- return
515
- }
516
- const detail = error instanceof Error ? error.message : String(error)
517
- this.log(`[manager] API 处理失败: ${detail}`)
518
- send(res, 500, { ok: false, error: '操作失败,请查看本机日志' })
507
+ } catch (error) {
508
+ // 单个路由异常不能让 HTTP 连接悬死,统一回 500 并落日志
509
+ if (error instanceof ApiRequestError) {
510
+ send(res, error.status, { ok: false, error: error.message })
511
+ return
512
+ }
513
+ const detail = error instanceof Error ? error.message : String(error)
514
+ this.log(`[manager] API 处理失败: ${detail}`)
515
+ send(res, 500, { ok: false, error: '操作失败,请查看本机日志' })
519
516
  }
520
517
  },
521
518
  })
@@ -523,13 +520,13 @@ export class ChannelManager {
523
520
  this.log('[manager] API 已注册 /dsh-im-connect/api')
524
521
  }
525
522
 
526
- disposeApi(): void {
523
+ disposeApi(): void {
527
524
  this.disposed = true
528
525
  for (const dispose of this.apiDisposers) dispose()
529
526
  this.apiDisposers = []
530
527
  this.pairing.dispose()
531
- const activeIds = new Set([...this.running.keys(), ...this.channelOperations.keys()])
532
- for (const id of activeIds) void this.channelOperations.run(id, () => this.stopOne(id as ChannelId))
528
+ const activeIds = new Set([...this.running.keys(), ...this.channelOperations.keys()])
529
+ for (const id of activeIds) void this.channelOperations.run(id, () => this.stopOne(id as ChannelId))
533
530
  this.engine.dispose()
534
531
  }
535
532
 
@@ -558,8 +555,8 @@ export class ChannelManager {
558
555
  this.applyWorkspace(cwd)
559
556
  this.log(`[manager] 工作区已设为 ${cwd}`)
560
557
  }
561
- if (hasPermission) {
562
- const permission = normalizePermission(input.permission, this.permissionPresets().names)
558
+ if (hasPermission) {
559
+ const permission = normalizePermission(input.permission, this.permissionPresets().names)
563
560
  if (!permission) return { ok: false, error: '请选择权限' }
564
561
  this.store.permission = permission
565
562
  this.applyPermission(permission)
@@ -589,102 +586,102 @@ export class ChannelManager {
589
586
  this.engine?.setCwd(next)
590
587
  }
591
588
 
592
- currentPermission(): PermissionPreset {
593
- const official = this.permissionPresets()
594
- return normalizePermission(this.store.permission ?? this.engineConfig.permissionPreset, official.names) ?? official.defaultPreset
595
- }
596
-
597
- private applyPermission(permission?: PermissionPreset): void {
598
- const next = normalizePermission(permission, this.permissionPresets().names)
599
- if (!next) return
600
- this.engineConfig.permissionPreset = next
601
- this.engine?.setPermission(next)
602
- }
603
-
604
- permissionOptions(): PermissionOptionView[] {
605
- const official = this.permissionPresets()
606
- return official.names.map((name) => official.optionOf(name))
607
- }
608
-
609
- private permissionPresets(): PermissionPresetService {
610
- return (this.ctx as Context & { permissionPresets: PermissionPresetService }).permissionPresets
611
- }
589
+ currentPermission(): PermissionPreset {
590
+ const official = this.permissionPresets()
591
+ return normalizePermission(this.store.permission ?? this.engineConfig.permissionPreset, official.names) ?? official.defaultPreset
592
+ }
593
+
594
+ private applyPermission(permission?: PermissionPreset): void {
595
+ const next = normalizePermission(permission, this.permissionPresets().names)
596
+ if (!next) return
597
+ this.engineConfig.permissionPreset = next
598
+ this.engine?.setPermission(next)
599
+ }
612
600
 
613
- private async listModelCatalog(): Promise<Array<{
614
- id: string
615
- name: string
616
- models: Array<{
617
- id: string
618
- name: string
619
- description?: string
620
- reasoning?: {
621
- efforts: Array<{ id: string; name: string; description?: string }>
622
- defaultEffort?: string
623
- }
624
- }>
625
- }>> {
626
- const llm = (this.ctx as Context & {
627
- get?(name: string): {
628
- listProviders?: () => Array<{ id: string; name?: string }>
629
- listModels?: (provider: string) => Promise<Array<{ id: string; name?: string; description?: string }>>
630
- resolveModelInfo?: (provider: string, model: string) => Promise<{
631
- description?: string
632
- reasoning?: {
633
- efforts: ReadonlyArray<{ id: string; name: string; description?: string }>
634
- defaultEffort?: string
635
- }
636
- }>
637
- } | undefined
638
- }).get?.('llm')
601
+ permissionOptions(): PermissionOptionView[] {
602
+ const official = this.permissionPresets()
603
+ return official.names.map((name) => official.optionOf(name))
604
+ }
605
+
606
+ private permissionPresets(): PermissionPresetService {
607
+ return (this.ctx as Context & { permissionPresets: PermissionPresetService }).permissionPresets
608
+ }
609
+
610
+ private async listModelCatalog(): Promise<Array<{
611
+ id: string
612
+ name: string
613
+ models: Array<{
614
+ id: string
615
+ name: string
616
+ description?: string
617
+ reasoning?: {
618
+ efforts: Array<{ id: string; name: string; description?: string }>
619
+ defaultEffort?: string
620
+ }
621
+ }>
622
+ }>> {
623
+ const llm = (this.ctx as Context & {
624
+ get?(name: string): {
625
+ listProviders?: () => Array<{ id: string; name?: string }>
626
+ listModels?: (provider: string) => Promise<Array<{ id: string; name?: string; description?: string }>>
627
+ resolveModelInfo?: (provider: string, model: string) => Promise<{
628
+ description?: string
629
+ reasoning?: {
630
+ efforts: ReadonlyArray<{ id: string; name: string; description?: string }>
631
+ defaultEffort?: string
632
+ }
633
+ }>
634
+ } | undefined
635
+ }).get?.('llm')
639
636
  const providers = llm?.listProviders?.() ?? []
640
637
  const out: Array<{ id: string; name: string; models: Array<{ id: string; name: string }> }> = []
641
638
  for (const item of providers) {
642
- const models = llm?.listModels ? await llm.listModels(item.id).catch(() => []) : []
643
- out.push({
644
- id: item.id,
645
- name: item.name || item.id,
646
- models: await Promise.all(models.map(async (model: { id: string; name?: string; description?: string }) => {
647
- const resolved = llm?.resolveModelInfo === undefined
648
- ? undefined
649
- : await llm.resolveModelInfo(item.id, model.id).catch(() => undefined)
650
- const reasoning = resolved?.reasoning === undefined
651
- ? undefined
652
- : {
653
- efforts: resolved.reasoning.efforts.map((effort: { id: string; name: string; description?: string }) => ({
654
- id: effort.id,
655
- name: effort.name,
656
- ...(effort.description === undefined ? {} : { description: effort.description }),
657
- })),
658
- ...(resolved.reasoning.defaultEffort === undefined ? {} : { defaultEffort: resolved.reasoning.defaultEffort }),
659
- }
660
- return {
661
- id: model.id,
662
- name: model.name || model.id,
663
- ...(resolved?.description ?? model.description) === undefined
664
- ? {}
665
- : { description: resolved?.description ?? model.description },
666
- ...(reasoning === undefined ? {} : { reasoning }),
667
- }
668
- })),
669
- })
639
+ const models = llm?.listModels ? await llm.listModels(item.id).catch(() => []) : []
640
+ out.push({
641
+ id: item.id,
642
+ name: item.name || item.id,
643
+ models: await Promise.all(models.map(async (model: { id: string; name?: string; description?: string }) => {
644
+ const resolved = llm?.resolveModelInfo === undefined
645
+ ? undefined
646
+ : await llm.resolveModelInfo(item.id, model.id).catch(() => undefined)
647
+ const reasoning = resolved?.reasoning === undefined
648
+ ? undefined
649
+ : {
650
+ efforts: resolved.reasoning.efforts.map((effort: { id: string; name: string; description?: string }) => ({
651
+ id: effort.id,
652
+ name: effort.name,
653
+ ...(effort.description === undefined ? {} : { description: effort.description }),
654
+ })),
655
+ ...(resolved.reasoning.defaultEffort === undefined ? {} : { defaultEffort: resolved.reasoning.defaultEffort }),
656
+ }
657
+ return {
658
+ id: model.id,
659
+ name: model.name || model.id,
660
+ ...(resolved?.description ?? model.description) === undefined
661
+ ? {}
662
+ : { description: resolved?.description ?? model.description },
663
+ ...(reasoning === undefined ? {} : { reasoning }),
664
+ }
665
+ })),
666
+ })
670
667
  }
671
668
  return out
672
669
  }
673
670
 
674
- private async startOne(id: ChannelId): Promise<void> {
675
- await this.stopOne(id)
676
- if (this.disposed) return
677
- const state = this.store.channels[id]
678
- if (id === 'weixin') await this.migrateLegacyWeixinToken()
679
- const resolved = await this.resolveSecrets(id, state?.config ?? {})
680
- if (this.disposed) return
681
- const adapter = createChannelAdapter(id, resolved, this.log, join(this.stateDir, id), {
682
- onWeixinBotToken: async (token) => {
683
- const ref = credentialRef('weixin', 'botToken')
684
- if (token) await this.vault.set(ref, token)
685
- else await this.vault.unset(ref)
686
- },
687
- })
671
+ private async startOne(id: ChannelId): Promise<void> {
672
+ await this.stopOne(id)
673
+ if (this.disposed) return
674
+ const state = this.store.channels[id]
675
+ if (id === 'weixin') await this.migrateLegacyWeixinToken()
676
+ const resolved = await this.resolveSecrets(id, state?.config ?? {})
677
+ if (this.disposed) return
678
+ const adapter = createChannelAdapter(id, resolved, this.log, join(this.stateDir, id), {
679
+ onWeixinBotToken: async (token) => {
680
+ const ref = credentialRef('weixin', 'botToken')
681
+ if (token) await this.vault.set(ref, token)
682
+ else await this.vault.unset(ref)
683
+ },
684
+ })
688
685
  if (!adapter) throw new Error('凭据不足,无法启动渠道')
689
686
  if (id === 'weixin') {
690
687
  this.seedAllowedUser(id, readWeixinAllowedUserId(join(this.stateDir, 'weixin')) || resolved.allowedUserId)
@@ -696,26 +693,26 @@ export class ChannelManager {
696
693
  const START_TIMEOUT_MS = 30_000
697
694
  let startTimer: ReturnType<typeof setTimeout> | undefined
698
695
  try {
699
- await Promise.race([
696
+ await Promise.race([
700
697
  adapter.start(),
701
698
  new Promise<never>((_, reject) => {
702
699
  startTimer = setTimeout(() => reject(new Error('渠道启动超时')), START_TIMEOUT_MS)
703
700
  }),
704
- ])
705
- if (this.disposed) {
706
- this.engine.unregister(id)
707
- this.running.delete(id)
708
- await Promise.resolve(adapter.stop()).catch(() => undefined)
709
- return
710
- }
701
+ ])
702
+ if (this.disposed) {
703
+ this.engine.unregister(id)
704
+ this.running.delete(id)
705
+ await Promise.resolve(adapter.stop()).catch(() => undefined)
706
+ return
707
+ }
711
708
  } catch (error) {
712
709
  this.engine.unregister(id)
713
710
  this.running.delete(id)
714
711
  await Promise.resolve(adapter.stop()).catch(() => undefined)
715
- const message = error instanceof Error ? error.message : String(error)
716
- if (state) {
717
- state.lastError = '连接失败,请查看本机日志'
718
- this.flush()
712
+ const message = error instanceof Error ? error.message : String(error)
713
+ if (state) {
714
+ state.lastError = '连接失败,请查看本机日志'
715
+ this.flush()
719
716
  }
720
717
  throw error
721
718
  } finally {
@@ -750,36 +747,36 @@ export class ChannelManager {
750
747
  return out
751
748
  }
752
749
 
753
- private async resolveSecrets(id: ChannelId, config: Record<string, string>): Promise<Record<string, string>> {
750
+ private async resolveSecrets(id: ChannelId, config: Record<string, string>): Promise<Record<string, string>> {
754
751
  const secrets = new Set((CHANNEL_META[id].fields.filter((field) => field.secret)).map((field) => field.key))
755
752
  const out = { ...config }
756
- for (const key of secrets) {
753
+ for (const key of secrets) {
757
754
  const ref = out[`${key}Ref`] || credentialRef(id, key)
758
755
  const value = await this.vault.resolve(ref)
759
756
  if (value) out[key] = value
760
- }
761
- if (id === 'weixin') {
762
- const token = await this.vault.resolve(credentialRef('weixin', 'botToken'))
763
- if (token) out.botToken = token
764
- }
765
- return out
766
- }
767
-
768
- private async migrateLegacyWeixinToken(): Promise<void> {
769
- const dir = join(this.stateDir, 'weixin')
770
- const token = readLegacyWeixinBotToken(dir)
771
- if (!token) return
772
- await this.vault.set(credentialRef('weixin', 'botToken'), token)
773
- // 只有 vault 写入成功后才重写旧文件,避免迁移失败导致登录态丢失。
774
- persistWeixinLogin(dir, {})
775
- this.log('[manager] 已把旧版微信明文 token 迁移到凭据服务')
776
- }
777
-
778
- private load(): void {
779
- try {
780
- const value = JSON.parse(readFileSync(this.file, 'utf8')) as unknown
781
- if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new TypeError('channels.json 顶层必须是对象')
782
- const parsed = value as Partial<Persisted>
757
+ }
758
+ if (id === 'weixin') {
759
+ const token = await this.vault.resolve(credentialRef('weixin', 'botToken'))
760
+ if (token) out.botToken = token
761
+ }
762
+ return out
763
+ }
764
+
765
+ private async migrateLegacyWeixinToken(): Promise<void> {
766
+ const dir = join(this.stateDir, 'weixin')
767
+ const token = readLegacyWeixinBotToken(dir)
768
+ if (!token) return
769
+ await this.vault.set(credentialRef('weixin', 'botToken'), token)
770
+ // 只有 vault 写入成功后才重写旧文件,避免迁移失败导致登录态丢失。
771
+ persistWeixinLogin(dir, {})
772
+ this.log('[manager] 已把旧版微信明文 token 迁移到凭据服务')
773
+ }
774
+
775
+ private load(): void {
776
+ try {
777
+ const value = JSON.parse(readFileSync(this.file, 'utf8')) as unknown
778
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new TypeError('channels.json 顶层必须是对象')
779
+ const parsed = value as Partial<Persisted>
783
780
  this.store = {
784
781
  channels: parsed.channels ?? {},
785
782
  allowlist: parsed.allowlist ?? {},
@@ -788,15 +785,15 @@ export class ChannelManager {
788
785
  cwd: normalizeWorkspacePath(parsed.cwd),
789
786
  permission: normalizePermission(parsed.permission),
790
787
  }
791
- } catch (error) {
792
- try {
793
- const backup = backupCorruptConfig(this.file)
794
- if (backup) this.log(`[manager] channels.json 损坏,已备份到 ${backup}: ${error instanceof Error ? error.message : String(error)}`)
795
- } catch (backupError) {
796
- this.log(`[manager] channels.json 无法读取且备份失败,拒绝覆盖原文件: ${backupError instanceof Error ? backupError.message : String(backupError)}`)
797
- throw backupError
798
- }
799
- this.store = { channels: {}, allowlist: {}, pending: {} }
788
+ } catch (error) {
789
+ try {
790
+ const backup = backupCorruptConfig(this.file)
791
+ if (backup) this.log(`[manager] channels.json 损坏,已备份到 ${backup}: ${error instanceof Error ? error.message : String(error)}`)
792
+ } catch (backupError) {
793
+ this.log(`[manager] channels.json 无法读取且备份失败,拒绝覆盖原文件: ${backupError instanceof Error ? backupError.message : String(backupError)}`)
794
+ throw backupError
795
+ }
796
+ this.store = { channels: {}, allowlist: {}, pending: {} }
800
797
  }
801
798
  }
802
799
 
@@ -841,9 +838,8 @@ export class ChannelManager {
841
838
  }
842
839
  }
843
840
 
844
- private flush(): void {
845
- mkdirSync(this.stateDir, { recursive: true })
846
- writeFileSync(this.file, `${JSON.stringify(this.store, null, 2)}\n`, 'utf8')
847
- }
848
- }
841
+ private flush(): void {
842
+ writeFileAtomicSync(this.file, `${JSON.stringify(this.store, null, 2)}\n`)
843
+ }
844
+ }
849
845