@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.
- package/README.en.md +2 -2
- package/README.md +2 -2
- package/SECURITY.md +1 -1
- package/lib/channels/dingtalk-card.d.ts.map +1 -1
- package/lib/channels/dingtalk-card.js +3 -0
- package/lib/channels/dingtalk-card.js.map +1 -1
- package/lib/channels/dingtalk.d.ts.map +1 -1
- package/lib/channels/dingtalk.js +6 -1
- package/lib/channels/dingtalk.js.map +1 -1
- package/lib/channels/feishu.d.ts +9 -0
- package/lib/channels/feishu.d.ts.map +1 -1
- package/lib/channels/feishu.js +23 -6
- package/lib/channels/feishu.js.map +1 -1
- package/lib/channels/qq.d.ts.map +1 -1
- package/lib/channels/qq.js +17 -1
- package/lib/channels/qq.js.map +1 -1
- package/lib/channels/telegram.d.ts.map +1 -1
- package/lib/channels/telegram.js +17 -4
- package/lib/channels/telegram.js.map +1 -1
- package/lib/channels/wecom.d.ts +7 -1
- package/lib/channels/wecom.d.ts.map +1 -1
- package/lib/channels/wecom.js +44 -11
- package/lib/channels/wecom.js.map +1 -1
- package/lib/channels/weixin.d.ts +3 -0
- package/lib/channels/weixin.d.ts.map +1 -1
- package/lib/channels/weixin.js +68 -15
- package/lib/channels/weixin.js.map +1 -1
- package/lib/engine/abort.d.ts +4 -0
- package/lib/engine/abort.d.ts.map +1 -0
- package/lib/engine/abort.js +26 -0
- package/lib/engine/abort.js.map +1 -0
- package/lib/engine/atomic-file.d.ts +5 -0
- package/lib/engine/atomic-file.d.ts.map +1 -0
- package/lib/engine/atomic-file.js +46 -0
- package/lib/engine/atomic-file.js.map +1 -0
- package/lib/engine/json-state.d.ts.map +1 -1
- package/lib/engine/json-state.js +7 -5
- package/lib/engine/json-state.js.map +1 -1
- package/lib/engine/secure-file.d.ts.map +1 -1
- package/lib/engine/secure-file.js +2 -12
- package/lib/engine/secure-file.js.map +1 -1
- package/lib/engine/seen-store.d.ts.map +1 -1
- package/lib/engine/seen-store.js +4 -4
- package/lib/engine/seen-store.js.map +1 -1
- package/lib/engine/session-store.d.ts.map +1 -1
- package/lib/engine/session-store.js +7 -5
- package/lib/engine/session-store.js.map +1 -1
- package/lib/manager.d.ts +7 -0
- package/lib/manager.d.ts.map +1 -1
- package/lib/manager.js +50 -42
- package/lib/manager.js.map +1 -1
- package/package.json +1 -1
- package/src/channels/dingtalk-card.ts +195 -192
- package/src/channels/dingtalk.ts +144 -140
- package/src/channels/feishu.ts +92 -66
- package/src/channels/qq.ts +303 -288
- package/src/channels/telegram.ts +170 -158
- package/src/channels/wecom.ts +209 -177
- package/src/channels/weixin.ts +158 -112
- package/src/engine/abort.ts +25 -0
- package/src/engine/access.ts +34 -34
- package/src/engine/atomic-file.ts +36 -0
- package/src/engine/json-state.ts +16 -15
- package/src/engine/secure-file.ts +7 -13
- package/src/engine/seen-store.ts +39 -39
- package/src/engine/session-store.ts +40 -39
- package/src/manager.ts +346 -321
package/src/manager.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Context } from '@deepseek-ai/cordis'
|
|
2
|
-
import {
|
|
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,57 +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
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
const
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
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 覆盖唯一副本。 */
|
|
57
110
|
export function backupCorruptConfig(file: string): string | undefined {
|
|
58
|
-
|
|
59
|
-
const stamp = new Date().toISOString().replace(/[:.]/g, '-')
|
|
60
|
-
const backup = `${file}.corrupt-${stamp}-${process.pid}`
|
|
61
|
-
renameSync(file, backup)
|
|
62
|
-
return backup
|
|
111
|
+
return backupCorruptFileSync(file)
|
|
63
112
|
}
|
|
64
113
|
|
|
65
114
|
export interface ChannelState {
|
|
@@ -88,26 +137,26 @@ interface PendingRequest {
|
|
|
88
137
|
time: number
|
|
89
138
|
}
|
|
90
139
|
|
|
91
|
-
interface Persisted {
|
|
140
|
+
interface Persisted {
|
|
92
141
|
channels: Record<string, ChannelState>
|
|
93
142
|
allowlist: Record<string, string[]>
|
|
94
143
|
pending: Record<string, PendingRequest[]>
|
|
95
144
|
assistant?: AssistantModel
|
|
96
145
|
cwd?: string
|
|
97
|
-
permission?: PermissionPreset
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
export interface PermissionOptionView {
|
|
101
|
-
value: string
|
|
102
|
-
name: string
|
|
103
|
-
description?: string
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
interface PermissionPresetService {
|
|
107
|
-
readonly names: readonly string[]
|
|
108
|
-
readonly defaultPreset: string
|
|
109
|
-
optionOf(name: string): PermissionOptionView
|
|
110
|
-
}
|
|
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
|
+
}
|
|
111
160
|
|
|
112
161
|
export class ChannelManager {
|
|
113
162
|
private readonly file: string
|
|
@@ -120,8 +169,8 @@ export class ChannelManager {
|
|
|
120
169
|
private readonly ctx: Context
|
|
121
170
|
private readonly engineConfig: EngineConfig
|
|
122
171
|
private store: Persisted = { channels: {}, allowlist: {}, pending: {} }
|
|
123
|
-
private readonly running = new Map<string, ChannelAdapter>()
|
|
124
|
-
private readonly channelOperations = new KeyedSerialQueue()
|
|
172
|
+
private readonly running = new Map<string, ChannelAdapter>()
|
|
173
|
+
private readonly channelOperations = new KeyedSerialQueue()
|
|
125
174
|
private apiDisposers: Array<() => void> = []
|
|
126
175
|
// dispose 后阻止 initEnabled/startOne 再拉起渠道,避免插件重载时新旧双实例并存
|
|
127
176
|
private disposed = false
|
|
@@ -201,18 +250,18 @@ export class ChannelManager {
|
|
|
201
250
|
}
|
|
202
251
|
}
|
|
203
252
|
|
|
204
|
-
async connect(id: ChannelId, config?: Record<string, string>): Promise<{ ok: boolean; error?: string }> {
|
|
205
|
-
if (!CHANNEL_META[id]) return { ok: false, error: '未知渠道' }
|
|
206
|
-
return this.channelOperations.run(id, () => this.connectNow(id, config))
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
private async connectNow(id: ChannelId, config?: Record<string, string>): Promise<{ ok: boolean; error?: string }> {
|
|
210
|
-
const incoming = { ...(config ?? {}) }
|
|
211
|
-
if (id === 'weixin' && incoming.botToken) {
|
|
212
|
-
await this.vault.set(credentialRef('weixin', 'botToken'), incoming.botToken)
|
|
213
|
-
persistWeixinLogin(join(this.stateDir, 'weixin'), {
|
|
214
|
-
allowedUserId: incoming.allowedUserId,
|
|
215
|
-
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,
|
|
216
265
|
})
|
|
217
266
|
delete incoming.botToken
|
|
218
267
|
incoming.bound = '1'
|
|
@@ -222,22 +271,22 @@ export class ChannelManager {
|
|
|
222
271
|
this.store.channels[id] = { ...prev, enabled: true, receiveEnabled: true, config: nextConfig }
|
|
223
272
|
this.flush()
|
|
224
273
|
this.seedAllowedUser(id, incoming.allowedUserId || incoming.ownerOpenId || nextConfig.allowedUserId || nextConfig.ownerOpenId)
|
|
225
|
-
try {
|
|
226
|
-
await this.startOne(id)
|
|
227
|
-
return { ok: true }
|
|
228
|
-
} catch (error) {
|
|
229
|
-
this.log(`[manager] ${id} 连接失败: ${error instanceof Error ? error.message : String(error)}`)
|
|
230
|
-
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: '渠道连接失败,请查看本机日志' }
|
|
231
280
|
}
|
|
232
281
|
}
|
|
233
282
|
|
|
234
|
-
async setReceive(id: ChannelId, receiveEnabled: boolean): Promise<{ ok: boolean; error?: string }> {
|
|
235
|
-
if (!CHANNEL_META[id]) return { ok: false, error: '未知渠道' }
|
|
236
|
-
return this.channelOperations.run(id, () => this.setReceiveNow(id, receiveEnabled))
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
private async setReceiveNow(id: ChannelId, receiveEnabled: boolean): Promise<{ ok: boolean; error?: string }> {
|
|
240
|
-
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]
|
|
241
290
|
if (!state?.enabled) return { ok: false, error: '渠道未配置' }
|
|
242
291
|
state.receiveEnabled = receiveEnabled
|
|
243
292
|
this.flush()
|
|
@@ -246,13 +295,13 @@ export class ChannelManager {
|
|
|
246
295
|
return { ok: true }
|
|
247
296
|
}
|
|
248
297
|
|
|
249
|
-
async disconnect(id: ChannelId): Promise<void> {
|
|
250
|
-
if (!CHANNEL_META[id]) return
|
|
251
|
-
await this.channelOperations.run(id, () => this.disconnectNow(id))
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
private async disconnectNow(id: ChannelId): Promise<void> {
|
|
255
|
-
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]
|
|
256
305
|
if (state) {
|
|
257
306
|
state.enabled = false
|
|
258
307
|
state.receiveEnabled = false
|
|
@@ -262,20 +311,20 @@ export class ChannelManager {
|
|
|
262
311
|
await this.stopOne(id)
|
|
263
312
|
}
|
|
264
313
|
|
|
265
|
-
async remove(id: ChannelId): Promise<void> {
|
|
266
|
-
if (!CHANNEL_META[id]) return
|
|
267
|
-
await this.channelOperations.run(id, () => this.removeNow(id))
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
private async removeNow(id: ChannelId): Promise<void> {
|
|
271
|
-
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)
|
|
272
321
|
this.pairing.cancel(id)
|
|
273
322
|
delete this.store.channels[id]
|
|
274
323
|
delete this.store.allowlist[id]
|
|
275
324
|
delete this.store.pending[id]
|
|
276
325
|
this.flush()
|
|
277
|
-
if (id === 'weixin') clearWeixinLogin(join(this.stateDir, 'weixin'))
|
|
278
|
-
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)
|
|
279
328
|
for (const field of CHANNEL_META[id].fields.filter((item) => item.secret)) {
|
|
280
329
|
await this.vault.unset(credentialRef(id, field.key)).catch(() => undefined)
|
|
281
330
|
}
|
|
@@ -285,17 +334,17 @@ export class ChannelManager {
|
|
|
285
334
|
return this.engine.attachMappedSessions()
|
|
286
335
|
}
|
|
287
336
|
|
|
288
|
-
async initEnabled(): Promise<void> {
|
|
289
|
-
const started = Date.now()
|
|
290
|
-
await this.migrateLegacyWeixinToken().catch((error) => {
|
|
291
|
-
this.log(`[manager] 迁移旧版微信 token 失败,已保留原文件: ${error instanceof Error ? error.message : String(error)}`)
|
|
292
|
-
})
|
|
293
|
-
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) {
|
|
294
343
|
if (this.disposed) return
|
|
295
344
|
const state = this.store.channels[id]
|
|
296
345
|
if (state?.enabled && state.receiveEnabled !== false) {
|
|
297
346
|
const one = Date.now()
|
|
298
|
-
await this.channelOperations.run(id, () => this.startOne(id)).catch((error) => {
|
|
347
|
+
await this.channelOperations.run(id, () => this.startOne(id)).catch((error) => {
|
|
299
348
|
this.log(`[manager] 启动 ${id} 失败: ${error instanceof Error ? error.message : String(error)}`)
|
|
300
349
|
})
|
|
301
350
|
this.log(`[boot] 渠道 ${id} 启动 ${Date.now() - one}ms`)
|
|
@@ -319,35 +368,12 @@ export class ChannelManager {
|
|
|
319
368
|
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' })
|
|
320
369
|
res.end(JSON.stringify(body))
|
|
321
370
|
}
|
|
322
|
-
const
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
// 超限后停止累计但不掐断连接,等 end 后统一按 413 拒绝,防止内存被撑爆
|
|
329
|
-
req.on('data', (chunk) => {
|
|
330
|
-
if (oversized) return
|
|
331
|
-
bytes += Buffer.isBuffer(chunk) ? chunk.length : Buffer.byteLength(String(chunk))
|
|
332
|
-
if (bytes > MAX_BODY_BYTES) { oversized = true; return }
|
|
333
|
-
raw += chunk
|
|
334
|
-
})
|
|
335
|
-
req.on('error', () => resolve({ body: {}, oversized, invalidJson: true }))
|
|
336
|
-
req.on('end', () => {
|
|
337
|
-
if (oversized) { resolve({ body: {}, oversized, invalidJson: false }); return }
|
|
338
|
-
try {
|
|
339
|
-
const parsed = raw ? JSON.parse(raw) as unknown : {}
|
|
340
|
-
const valid = parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)
|
|
341
|
-
resolve({ body: valid ? parsed as Record<string, unknown> : {}, oversized: false, invalidJson: !valid })
|
|
342
|
-
} catch { resolve({ body: {}, oversized: false, invalidJson: true }) }
|
|
343
|
-
})
|
|
344
|
-
})
|
|
345
|
-
const readJson = async (req: import('node:http').IncomingMessage): Promise<Record<string, unknown>> => {
|
|
346
|
-
const { body, oversized, invalidJson } = await readBody(req)
|
|
347
|
-
if (oversized) throw new ApiRequestError(413, '请求体超过 1MB 上限')
|
|
348
|
-
if (invalidJson) throw new ApiRequestError(400, '请求体不是合法 JSON')
|
|
349
|
-
return body
|
|
350
|
-
}
|
|
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
|
+
}
|
|
351
377
|
const payload = () => ({
|
|
352
378
|
ok: true,
|
|
353
379
|
channels: this.list(),
|
|
@@ -357,37 +383,37 @@ export class ChannelManager {
|
|
|
357
383
|
})
|
|
358
384
|
const dispose = webServer.register({
|
|
359
385
|
kind: 'prefix',
|
|
360
|
-
path: '/dsh-im-connect/api',
|
|
361
|
-
handler: async (req, res) => {
|
|
362
|
-
try {
|
|
363
|
-
const requestError = validateApiRequest({ method: req.method, headers: req.headers, remoteAddress: req.socket.remoteAddress })
|
|
364
|
-
if (requestError) { send(res, requestError.status, { ok: false, error: requestError.error }); return }
|
|
365
|
-
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'}`)
|
|
366
392
|
const parts = url.pathname.split('/').filter(Boolean)
|
|
367
393
|
if (parts[2] === 'assistant' && parts.length === 3) {
|
|
368
394
|
if (req.method === 'GET') {
|
|
369
|
-
send(res, 200, {
|
|
370
|
-
ok: true,
|
|
371
|
-
assistant: this.currentAssistant(),
|
|
372
|
-
cwd: this.currentWorkspace(),
|
|
373
|
-
permission: this.currentPermission(),
|
|
374
|
-
permissions: this.permissionOptions(),
|
|
375
|
-
providers: await this.listModelCatalog(),
|
|
376
|
-
})
|
|
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
|
+
})
|
|
377
403
|
return
|
|
378
|
-
}
|
|
379
|
-
if (req.method === 'POST') {
|
|
380
|
-
const body = await readJson(req)
|
|
381
|
-
const result = this.setAssistant(body)
|
|
404
|
+
}
|
|
405
|
+
if (req.method === 'POST') {
|
|
406
|
+
const body = await readJson(req)
|
|
407
|
+
const result = this.setAssistant(body)
|
|
382
408
|
send(res, result.ok ? 200 : 400, result)
|
|
383
409
|
return
|
|
384
410
|
}
|
|
385
411
|
send(res, 405, { ok: false, error: 'method not allowed' })
|
|
386
412
|
return
|
|
387
413
|
}
|
|
388
|
-
if (parts[2] === 'sessions' && parts.length === 4 && req.method === 'POST') {
|
|
389
|
-
const action = parts[3]
|
|
390
|
-
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)
|
|
391
417
|
const sessionId = String(body.sessionId ?? '')
|
|
392
418
|
if (!sessionId) { send(res, 400, { ok: false, error: '缺少 sessionId' }); return }
|
|
393
419
|
if (action === 'rename') {
|
|
@@ -424,7 +450,7 @@ export class ChannelManager {
|
|
|
424
450
|
return
|
|
425
451
|
}
|
|
426
452
|
if (req.method !== 'POST') { send(res, 405, { ok: false, error: 'method not allowed' }); return }
|
|
427
|
-
await readJson(req)
|
|
453
|
+
await readJson(req)
|
|
428
454
|
if (action === 'start') {
|
|
429
455
|
const pairing = await this.pairing.start(id)
|
|
430
456
|
send(res, pairing.status === 'failed' ? 400 : 200, { ok: pairing.status !== 'failed', pairing, error: pairing.error })
|
|
@@ -443,9 +469,9 @@ export class ChannelManager {
|
|
|
443
469
|
return
|
|
444
470
|
}
|
|
445
471
|
if (parts[2] === 'channels' && parts.length === 5 && req.method === 'POST') {
|
|
446
|
-
const id = parts[3] as ChannelId
|
|
447
|
-
const action = parts[4]
|
|
448
|
-
const body = await readJson(req)
|
|
472
|
+
const id = parts[3] as ChannelId
|
|
473
|
+
const action = parts[4]
|
|
474
|
+
const body = await readJson(req)
|
|
449
475
|
if (action === 'connect') {
|
|
450
476
|
const result = await this.connect(id, body.config as Record<string, string> | undefined)
|
|
451
477
|
send(res, result.ok ? 200 : 400, result.ok ? { ok: true, channel: this.list().find((item) => item.id === id) } : result)
|
|
@@ -478,15 +504,15 @@ export class ChannelManager {
|
|
|
478
504
|
return
|
|
479
505
|
}
|
|
480
506
|
send(res, 404, { ok: false, error: 'not found' })
|
|
481
|
-
} catch (error) {
|
|
482
|
-
// 单个路由异常不能让 HTTP 连接悬死,统一回 500 并落日志
|
|
483
|
-
if (error instanceof ApiRequestError) {
|
|
484
|
-
send(res, error.status, { ok: false, error: error.message })
|
|
485
|
-
return
|
|
486
|
-
}
|
|
487
|
-
const detail = error instanceof Error ? error.message : String(error)
|
|
488
|
-
this.log(`[manager] API 处理失败: ${detail}`)
|
|
489
|
-
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: '操作失败,请查看本机日志' })
|
|
490
516
|
}
|
|
491
517
|
},
|
|
492
518
|
})
|
|
@@ -494,13 +520,13 @@ export class ChannelManager {
|
|
|
494
520
|
this.log('[manager] API 已注册 /dsh-im-connect/api')
|
|
495
521
|
}
|
|
496
522
|
|
|
497
|
-
disposeApi(): void {
|
|
523
|
+
disposeApi(): void {
|
|
498
524
|
this.disposed = true
|
|
499
525
|
for (const dispose of this.apiDisposers) dispose()
|
|
500
526
|
this.apiDisposers = []
|
|
501
527
|
this.pairing.dispose()
|
|
502
|
-
const activeIds = new Set([...this.running.keys(), ...this.channelOperations.keys()])
|
|
503
|
-
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))
|
|
504
530
|
this.engine.dispose()
|
|
505
531
|
}
|
|
506
532
|
|
|
@@ -529,8 +555,8 @@ export class ChannelManager {
|
|
|
529
555
|
this.applyWorkspace(cwd)
|
|
530
556
|
this.log(`[manager] 工作区已设为 ${cwd}`)
|
|
531
557
|
}
|
|
532
|
-
if (hasPermission) {
|
|
533
|
-
const permission = normalizePermission(input.permission, this.permissionPresets().names)
|
|
558
|
+
if (hasPermission) {
|
|
559
|
+
const permission = normalizePermission(input.permission, this.permissionPresets().names)
|
|
534
560
|
if (!permission) return { ok: false, error: '请选择权限' }
|
|
535
561
|
this.store.permission = permission
|
|
536
562
|
this.applyPermission(permission)
|
|
@@ -560,102 +586,102 @@ export class ChannelManager {
|
|
|
560
586
|
this.engine?.setCwd(next)
|
|
561
587
|
}
|
|
562
588
|
|
|
563
|
-
currentPermission(): PermissionPreset {
|
|
564
|
-
const official = this.permissionPresets()
|
|
565
|
-
return normalizePermission(this.store.permission ?? this.engineConfig.permissionPreset, official.names) ?? official.defaultPreset
|
|
566
|
-
}
|
|
567
|
-
|
|
568
|
-
private applyPermission(permission?: PermissionPreset): void {
|
|
569
|
-
const next = normalizePermission(permission, this.permissionPresets().names)
|
|
570
|
-
if (!next) return
|
|
571
|
-
this.engineConfig.permissionPreset = next
|
|
572
|
-
this.engine?.setPermission(next)
|
|
573
|
-
}
|
|
574
|
-
|
|
575
|
-
permissionOptions(): PermissionOptionView[] {
|
|
576
|
-
const official = this.permissionPresets()
|
|
577
|
-
return official.names.map((name) => official.optionOf(name))
|
|
578
|
-
}
|
|
579
|
-
|
|
580
|
-
private permissionPresets(): PermissionPresetService {
|
|
581
|
-
return (this.ctx as Context & { permissionPresets: PermissionPresetService }).permissionPresets
|
|
582
|
-
}
|
|
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
|
+
}
|
|
600
|
+
|
|
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
|
+
}
|
|
583
609
|
|
|
584
|
-
private async listModelCatalog(): Promise<Array<{
|
|
585
|
-
id: string
|
|
586
|
-
name: string
|
|
587
|
-
models: Array<{
|
|
588
|
-
id: string
|
|
589
|
-
name: string
|
|
590
|
-
description?: string
|
|
591
|
-
reasoning?: {
|
|
592
|
-
efforts: Array<{ id: string; name: string; description?: string }>
|
|
593
|
-
defaultEffort?: string
|
|
594
|
-
}
|
|
595
|
-
}>
|
|
596
|
-
}>> {
|
|
597
|
-
const llm = (this.ctx as Context & {
|
|
598
|
-
get?(name: string): {
|
|
599
|
-
listProviders?: () => Array<{ id: string; name?: string }>
|
|
600
|
-
listModels?: (provider: string) => Promise<Array<{ id: string; name?: string; description?: string }>>
|
|
601
|
-
resolveModelInfo?: (provider: string, model: string) => Promise<{
|
|
602
|
-
description?: string
|
|
603
|
-
reasoning?: {
|
|
604
|
-
efforts: ReadonlyArray<{ id: string; name: string; description?: string }>
|
|
605
|
-
defaultEffort?: string
|
|
606
|
-
}
|
|
607
|
-
}>
|
|
608
|
-
} | undefined
|
|
609
|
-
}).get?.('llm')
|
|
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')
|
|
610
636
|
const providers = llm?.listProviders?.() ?? []
|
|
611
637
|
const out: Array<{ id: string; name: string; models: Array<{ id: string; name: string }> }> = []
|
|
612
638
|
for (const item of providers) {
|
|
613
|
-
const models = llm?.listModels ? await llm.listModels(item.id).catch(() => []) : []
|
|
614
|
-
out.push({
|
|
615
|
-
id: item.id,
|
|
616
|
-
name: item.name || item.id,
|
|
617
|
-
models: await Promise.all(models.map(async (model: { id: string; name?: string; description?: string }) => {
|
|
618
|
-
const resolved = llm?.resolveModelInfo === undefined
|
|
619
|
-
? undefined
|
|
620
|
-
: await llm.resolveModelInfo(item.id, model.id).catch(() => undefined)
|
|
621
|
-
const reasoning = resolved?.reasoning === undefined
|
|
622
|
-
? undefined
|
|
623
|
-
: {
|
|
624
|
-
efforts: resolved.reasoning.efforts.map((effort: { id: string; name: string; description?: string }) => ({
|
|
625
|
-
id: effort.id,
|
|
626
|
-
name: effort.name,
|
|
627
|
-
...(effort.description === undefined ? {} : { description: effort.description }),
|
|
628
|
-
})),
|
|
629
|
-
...(resolved.reasoning.defaultEffort === undefined ? {} : { defaultEffort: resolved.reasoning.defaultEffort }),
|
|
630
|
-
}
|
|
631
|
-
return {
|
|
632
|
-
id: model.id,
|
|
633
|
-
name: model.name || model.id,
|
|
634
|
-
...(resolved?.description ?? model.description) === undefined
|
|
635
|
-
? {}
|
|
636
|
-
: { description: resolved?.description ?? model.description },
|
|
637
|
-
...(reasoning === undefined ? {} : { reasoning }),
|
|
638
|
-
}
|
|
639
|
-
})),
|
|
640
|
-
})
|
|
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
|
+
})
|
|
641
667
|
}
|
|
642
668
|
return out
|
|
643
669
|
}
|
|
644
670
|
|
|
645
|
-
private async startOne(id: ChannelId): Promise<void> {
|
|
646
|
-
await this.stopOne(id)
|
|
647
|
-
if (this.disposed) return
|
|
648
|
-
const state = this.store.channels[id]
|
|
649
|
-
if (id === 'weixin') await this.migrateLegacyWeixinToken()
|
|
650
|
-
const resolved = await this.resolveSecrets(id, state?.config ?? {})
|
|
651
|
-
if (this.disposed) return
|
|
652
|
-
const adapter = createChannelAdapter(id, resolved, this.log, join(this.stateDir, id), {
|
|
653
|
-
onWeixinBotToken: async (token) => {
|
|
654
|
-
const ref = credentialRef('weixin', 'botToken')
|
|
655
|
-
if (token) await this.vault.set(ref, token)
|
|
656
|
-
else await this.vault.unset(ref)
|
|
657
|
-
},
|
|
658
|
-
})
|
|
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
|
+
})
|
|
659
685
|
if (!adapter) throw new Error('凭据不足,无法启动渠道')
|
|
660
686
|
if (id === 'weixin') {
|
|
661
687
|
this.seedAllowedUser(id, readWeixinAllowedUserId(join(this.stateDir, 'weixin')) || resolved.allowedUserId)
|
|
@@ -667,26 +693,26 @@ export class ChannelManager {
|
|
|
667
693
|
const START_TIMEOUT_MS = 30_000
|
|
668
694
|
let startTimer: ReturnType<typeof setTimeout> | undefined
|
|
669
695
|
try {
|
|
670
|
-
await Promise.race([
|
|
696
|
+
await Promise.race([
|
|
671
697
|
adapter.start(),
|
|
672
698
|
new Promise<never>((_, reject) => {
|
|
673
699
|
startTimer = setTimeout(() => reject(new Error('渠道启动超时')), START_TIMEOUT_MS)
|
|
674
700
|
}),
|
|
675
|
-
])
|
|
676
|
-
if (this.disposed) {
|
|
677
|
-
this.engine.unregister(id)
|
|
678
|
-
this.running.delete(id)
|
|
679
|
-
await Promise.resolve(adapter.stop()).catch(() => undefined)
|
|
680
|
-
return
|
|
681
|
-
}
|
|
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
|
+
}
|
|
682
708
|
} catch (error) {
|
|
683
709
|
this.engine.unregister(id)
|
|
684
710
|
this.running.delete(id)
|
|
685
711
|
await Promise.resolve(adapter.stop()).catch(() => undefined)
|
|
686
|
-
const message = error instanceof Error ? error.message : String(error)
|
|
687
|
-
if (state) {
|
|
688
|
-
state.lastError = '连接失败,请查看本机日志'
|
|
689
|
-
this.flush()
|
|
712
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
713
|
+
if (state) {
|
|
714
|
+
state.lastError = '连接失败,请查看本机日志'
|
|
715
|
+
this.flush()
|
|
690
716
|
}
|
|
691
717
|
throw error
|
|
692
718
|
} finally {
|
|
@@ -721,36 +747,36 @@ export class ChannelManager {
|
|
|
721
747
|
return out
|
|
722
748
|
}
|
|
723
749
|
|
|
724
|
-
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>> {
|
|
725
751
|
const secrets = new Set((CHANNEL_META[id].fields.filter((field) => field.secret)).map((field) => field.key))
|
|
726
752
|
const out = { ...config }
|
|
727
|
-
for (const key of secrets) {
|
|
753
|
+
for (const key of secrets) {
|
|
728
754
|
const ref = out[`${key}Ref`] || credentialRef(id, key)
|
|
729
755
|
const value = await this.vault.resolve(ref)
|
|
730
756
|
if (value) out[key] = value
|
|
731
|
-
}
|
|
732
|
-
if (id === 'weixin') {
|
|
733
|
-
const token = await this.vault.resolve(credentialRef('weixin', 'botToken'))
|
|
734
|
-
if (token) out.botToken = token
|
|
735
|
-
}
|
|
736
|
-
return out
|
|
737
|
-
}
|
|
738
|
-
|
|
739
|
-
private async migrateLegacyWeixinToken(): Promise<void> {
|
|
740
|
-
const dir = join(this.stateDir, 'weixin')
|
|
741
|
-
const token = readLegacyWeixinBotToken(dir)
|
|
742
|
-
if (!token) return
|
|
743
|
-
await this.vault.set(credentialRef('weixin', 'botToken'), token)
|
|
744
|
-
// 只有 vault 写入成功后才重写旧文件,避免迁移失败导致登录态丢失。
|
|
745
|
-
persistWeixinLogin(dir, {})
|
|
746
|
-
this.log('[manager] 已把旧版微信明文 token 迁移到凭据服务')
|
|
747
|
-
}
|
|
748
|
-
|
|
749
|
-
private load(): void {
|
|
750
|
-
try {
|
|
751
|
-
const value = JSON.parse(readFileSync(this.file, 'utf8')) as unknown
|
|
752
|
-
if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new TypeError('channels.json 顶层必须是对象')
|
|
753
|
-
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>
|
|
754
780
|
this.store = {
|
|
755
781
|
channels: parsed.channels ?? {},
|
|
756
782
|
allowlist: parsed.allowlist ?? {},
|
|
@@ -759,15 +785,15 @@ export class ChannelManager {
|
|
|
759
785
|
cwd: normalizeWorkspacePath(parsed.cwd),
|
|
760
786
|
permission: normalizePermission(parsed.permission),
|
|
761
787
|
}
|
|
762
|
-
} catch (error) {
|
|
763
|
-
try {
|
|
764
|
-
const backup = backupCorruptConfig(this.file)
|
|
765
|
-
if (backup) this.log(`[manager] channels.json 损坏,已备份到 ${backup}: ${error instanceof Error ? error.message : String(error)}`)
|
|
766
|
-
} catch (backupError) {
|
|
767
|
-
this.log(`[manager] channels.json 无法读取且备份失败,拒绝覆盖原文件: ${backupError instanceof Error ? backupError.message : String(backupError)}`)
|
|
768
|
-
throw backupError
|
|
769
|
-
}
|
|
770
|
-
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: {} }
|
|
771
797
|
}
|
|
772
798
|
}
|
|
773
799
|
|
|
@@ -812,9 +838,8 @@ export class ChannelManager {
|
|
|
812
838
|
}
|
|
813
839
|
}
|
|
814
840
|
|
|
815
|
-
private flush(): void {
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
}
|
|
841
|
+
private flush(): void {
|
|
842
|
+
writeFileAtomicSync(this.file, `${JSON.stringify(this.store, null, 2)}\n`)
|
|
843
|
+
}
|
|
844
|
+
}
|
|
820
845
|
|