@michengai/dsh-im-connect 0.1.37 → 0.1.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -1
- package/CHANGELOG.zh-CN.md +17 -1
- package/README.en.md +60 -65
- package/README.md +60 -65
- package/SECURITY.md +7 -2
- package/client.js +31 -298
- package/lib/channels/channel-image-download.d.ts +22 -0
- package/lib/channels/channel-image-download.d.ts.map +1 -0
- package/lib/channels/channel-image-download.js +179 -0
- package/lib/channels/channel-image-download.js.map +1 -0
- package/lib/channels/dingtalk-token-cache.d.ts +18 -0
- package/lib/channels/dingtalk-token-cache.d.ts.map +1 -0
- package/lib/channels/dingtalk-token-cache.js +48 -0
- package/lib/channels/dingtalk-token-cache.js.map +1 -0
- package/lib/channels/dingtalk.d.ts +17 -4
- package/lib/channels/dingtalk.d.ts.map +1 -1
- package/lib/channels/dingtalk.js +111 -18
- package/lib/channels/dingtalk.js.map +1 -1
- package/lib/channels/factory.d.ts.map +1 -1
- package/lib/channels/factory.js +6 -3
- package/lib/channels/factory.js.map +1 -1
- package/lib/channels/feishu.d.ts +30 -2
- package/lib/channels/feishu.d.ts.map +1 -1
- package/lib/channels/feishu.js +141 -26
- package/lib/channels/feishu.js.map +1 -1
- package/lib/channels/image-host-policy.d.ts +4 -0
- package/lib/channels/image-host-policy.d.ts.map +1 -0
- package/lib/channels/image-host-policy.js +24 -0
- package/lib/channels/image-host-policy.js.map +1 -0
- package/lib/channels/qq.d.ts +1 -0
- package/lib/channels/qq.d.ts.map +1 -1
- package/lib/channels/qq.js +89 -18
- package/lib/channels/qq.js.map +1 -1
- package/lib/channels/telegram.d.ts.map +1 -1
- package/lib/channels/telegram.js +121 -16
- package/lib/channels/telegram.js.map +1 -1
- package/lib/channels/wecom.d.ts +8 -2
- package/lib/channels/wecom.d.ts.map +1 -1
- package/lib/channels/wecom.js +60 -11
- package/lib/channels/wecom.js.map +1 -1
- package/lib/channels/weixin.d.ts.map +1 -1
- package/lib/channels/weixin.js +169 -17
- package/lib/channels/weixin.js.map +1 -1
- package/lib/client.js +31 -298
- package/lib/engine/gateway.d.ts +2 -0
- package/lib/engine/gateway.d.ts.map +1 -1
- package/lib/engine/gateway.js +48 -11
- package/lib/engine/gateway.js.map +1 -1
- package/lib/engine/image-input.d.ts +8 -0
- package/lib/engine/image-input.d.ts.map +1 -0
- package/lib/engine/image-input.js +31 -0
- package/lib/engine/image-input.js.map +1 -0
- package/lib/engine/router.d.ts.map +1 -1
- package/lib/engine/router.js +29 -19
- package/lib/engine/router.js.map +1 -1
- package/lib/manager.d.ts +0 -10
- package/lib/manager.d.ts.map +1 -1
- package/lib/manager.js +231 -203
- package/lib/manager.js.map +1 -1
- package/package.json +1 -1
- package/src/channels/channel-image-download.ts +154 -0
- package/src/channels/dingtalk-token-cache.ts +39 -0
- package/src/channels/dingtalk.ts +106 -27
- package/src/channels/factory.ts +6 -3
- package/src/channels/feishu.ts +126 -24
- package/src/channels/image-host-policy.ts +21 -0
- package/src/channels/qq.ts +80 -26
- package/src/channels/telegram.ts +105 -16
- package/src/channels/wecom.ts +57 -12
- package/src/channels/weixin.ts +124 -14
- package/src/engine/gateway.ts +35 -6
- package/src/engine/image-input.ts +26 -0
- package/src/engine/router.ts +28 -18
- package/src/manager.ts +116 -84
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises'
|
|
2
|
+
import type { ImMedia } from './types.js'
|
|
3
|
+
|
|
4
|
+
export class ImageInputError extends Error {}
|
|
5
|
+
|
|
6
|
+
/** Safe feedback: never forward raw host errors (paths, tokens, or bytes) to IM. */
|
|
7
|
+
export function imageInputFailure(error: unknown): string {
|
|
8
|
+
if (error instanceof ImageInputError) return error.message
|
|
9
|
+
const reason = (error as { details?: { reason?: string } } | null)?.details?.reason
|
|
10
|
+
if (reason === 'MODEL_DOES_NOT_SUPPORT_IMAGES') return '当前会话模型不支持图片输入,请在 Chat 中切换支持视觉的模型后重新发送。'
|
|
11
|
+
return '图片输入失败,消息未提交。请检查图片格式、大小或当前会话模型后重新发送;详情见本机日志。'
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Encode a channel download for Chat's public prompt API. Host owns validation. */
|
|
15
|
+
export async function imagePromptPart(media: ImMedia): Promise<Record<string, unknown>> {
|
|
16
|
+
const data = media.data ? Buffer.from(media.data) : media.path ? await readFile(media.path).catch(() => { throw new ImageInputError('图片读取失败,请重新发送。') }) : Buffer.alloc(0)
|
|
17
|
+
if (data.length === 0) throw new ImageInputError('图片下载失败或内容为空,请重新发送。')
|
|
18
|
+
let mediaType = media.mediaType
|
|
19
|
+
// Encrypted CDNs may report octet-stream or the adapter may guess from a
|
|
20
|
+
// filename. Actual image bytes take precedence; Host still fully decodes them.
|
|
21
|
+
if (data.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) mediaType = 'image/png'
|
|
22
|
+
else if (data[0] === 255 && data[1] === 216 && data[2] === 255) mediaType = 'image/jpeg'
|
|
23
|
+
else if (['GIF87a', 'GIF89a'].includes(data.subarray(0, 6).toString('ascii'))) mediaType = 'image/gif'
|
|
24
|
+
else if (data.subarray(0, 4).toString('ascii') === 'RIFF' && data.subarray(8, 12).toString('ascii') === 'WEBP') mediaType = 'image/webp'
|
|
25
|
+
return { type: 'image', data: data.toString('base64'), mediaType, ...(media.name ? { name: media.name } : {}) }
|
|
26
|
+
}
|
package/src/engine/router.ts
CHANGED
|
@@ -334,7 +334,10 @@ export class SessionRouter {
|
|
|
334
334
|
try {
|
|
335
335
|
const handle = await this.ctx.agents.resume({
|
|
336
336
|
resumeSessionId: record.sessionId,
|
|
337
|
-
agentOptions:
|
|
337
|
+
agentOptions: {
|
|
338
|
+
...this.resolveAgentOptions(record.channel),
|
|
339
|
+
...(this.resolveConfig(record.channel).reasoningEffort ? { reasoningEffort: this.resolveConfig(record.channel).reasoningEffort } : {}),
|
|
340
|
+
},
|
|
338
341
|
setup: this.presetSetup(record.channel),
|
|
339
342
|
})
|
|
340
343
|
await this.attachWorkspace(record.sessionId, record.channel)
|
|
@@ -355,7 +358,8 @@ export class SessionRouter {
|
|
|
355
358
|
private async createHandle(sessionId: string, channelId: string) {
|
|
356
359
|
const agents = this.ctx.agents
|
|
357
360
|
if (!agents?.create) throw new Error('当前 Host 没有 agents 服务,无法创建 IM 会话')
|
|
358
|
-
//
|
|
361
|
+
// IM 保持普通会话(不设置 subagent origin);Chat prompt 会拒绝子代理所有权。
|
|
362
|
+
// IM 与任务的区分靠 sessionId 的 im: 前缀。
|
|
359
363
|
// 必须带上当前默认模型,否则 deployment:persona 的 {{model}} 组装会失败。
|
|
360
364
|
const config = this.resolveConfig(channelId)
|
|
361
365
|
const agentOptions = this.resolveAgentOptions(channelId)
|
|
@@ -372,7 +376,24 @@ export class SessionRouter {
|
|
|
372
376
|
},
|
|
373
377
|
setup: this.presetSetup(channelId),
|
|
374
378
|
})
|
|
375
|
-
|
|
379
|
+
const handle = await (agents.withoutInitiator ? agents.withoutInitiator(create) : create())
|
|
380
|
+
// Chat's selectionFor() restores the durable pending selection, not this
|
|
381
|
+
// router's assembly hook. Seed NEW sessions so an image-first message uses
|
|
382
|
+
// the account model. Never rewrite a resumed session's current selection.
|
|
383
|
+
const session = handle.agent?.session as { append?: (type: string, data: unknown) => void } | undefined
|
|
384
|
+
if (config.provider && config.model && session?.append) {
|
|
385
|
+
try {
|
|
386
|
+
session.append('model/selection', {
|
|
387
|
+
provider: config.provider,
|
|
388
|
+
model: config.model,
|
|
389
|
+
...(config.reasoningEffort ? { reasoningEffort: config.reasoningEffort } : {}),
|
|
390
|
+
})
|
|
391
|
+
} catch (error) {
|
|
392
|
+
// Older Hosts may not register this event; preserve legacy text input.
|
|
393
|
+
this.log(`[router] 无法记录初始模型选择: ${error instanceof Error ? error.message : String(error)}`)
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
return handle
|
|
376
397
|
}
|
|
377
398
|
|
|
378
399
|
async attachMappedSessions(): Promise<void> {
|
|
@@ -440,21 +461,10 @@ export class SessionRouter {
|
|
|
440
461
|
const permission = config.permissionPreset
|
|
441
462
|
return async (agentCtx: unknown) => {
|
|
442
463
|
if (ctx.agentPresets?.mount) await ctx.agentPresets.mount(agentCtx, preset)
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
current: {
|
|
448
|
-
provider: config.provider,
|
|
449
|
-
model: config.model,
|
|
450
|
-
...(config.reasoningEffort ? { reasoningEffort: config.reasoningEffort } : {}),
|
|
451
|
-
},
|
|
452
|
-
assembled: undefined,
|
|
453
|
-
})
|
|
454
|
-
} catch {
|
|
455
|
-
// Host 未暴露该接口时,仍把 reasoningEffort 放在 agentOptions 里。
|
|
456
|
-
}
|
|
457
|
-
}
|
|
464
|
+
// Account defaults belong in agentOptions (including on legacy Hosts),
|
|
465
|
+
// not a second installModelSelection middleware. Its outer after-next
|
|
466
|
+
// override would defeat Chat's session selection and image admission.
|
|
467
|
+
// New sessions also persist their initial selection in createHandle().
|
|
458
468
|
if (permission) {
|
|
459
469
|
try {
|
|
460
470
|
const agent = (agentCtx as { agent?: { session?: unknown } }).agent
|
package/src/manager.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { createHash, randomUUID } from 'node:crypto'
|
|
|
3
3
|
import { readFileSync } from 'node:fs'
|
|
4
4
|
import { join } from 'node:path'
|
|
5
5
|
import { createChannelAdapter } from './channels/factory.js'
|
|
6
|
+
import { parseAdditionalImageHosts } from './channels/image-host-policy.js'
|
|
6
7
|
import { CHANNEL_META, CHANNEL_ORDER, supportsQr } from './channels/meta.js'
|
|
7
8
|
import { PairingHub } from './channels/qr/hub.js'
|
|
8
9
|
import type { ChannelId } from './engine/session-id.js'
|
|
@@ -37,21 +38,11 @@ class ApiRequestError extends Error {
|
|
|
37
38
|
}
|
|
38
39
|
}
|
|
39
40
|
|
|
40
|
-
/**
|
|
41
|
-
|
|
41
|
+
/** 宿主负责身份认证;插件仍限制写请求格式,避免简单跨站表单与错误载荷。 */
|
|
42
|
+
function validateApiMutation(request: {
|
|
42
43
|
method?: string
|
|
43
44
|
headers: Record<string, string | string[] | undefined>
|
|
44
|
-
remoteAddress?: string
|
|
45
45
|
}): ApiRequestErrorShape | undefined {
|
|
46
|
-
const remote = request.remoteAddress ?? ''
|
|
47
|
-
if (!(remote === '::1' || /^127\./.test(remote) || /^::ffff:127\./i.test(remote))) {
|
|
48
|
-
return { status: 403, error: 'forbidden client address' }
|
|
49
|
-
}
|
|
50
|
-
const hostValue = request.headers.host
|
|
51
|
-
const host = String(Array.isArray(hostValue) ? hostValue[0] ?? '' : hostValue ?? '').toLowerCase()
|
|
52
|
-
if (!/^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(host)) {
|
|
53
|
-
return { status: 403, error: 'forbidden host' }
|
|
54
|
-
}
|
|
55
46
|
const method = (request.method ?? 'GET').toUpperCase()
|
|
56
47
|
if (method === 'GET' || method === 'HEAD') return undefined
|
|
57
48
|
const markerValue = request.headers[API_CLIENT_HEADER]
|
|
@@ -331,6 +322,14 @@ export class ChannelManager {
|
|
|
331
322
|
const hadAnotherIdentity = !existed && Object.entries(this.store.channels)
|
|
332
323
|
.some(([existingId, state]) => existingId !== accountId && this.platformOf(existingId, state) === id)
|
|
333
324
|
const prev = this.store.channels[accountId] ?? {}
|
|
325
|
+
if (['qq', 'wecom', 'dingtalk'].includes(id)) {
|
|
326
|
+
const hosts = Object.hasOwn(incoming, 'additionalImageHosts') ? incoming.additionalImageHosts : prev.config?.additionalImageHosts
|
|
327
|
+
try {
|
|
328
|
+
if (hosts !== undefined) incoming.additionalImageHosts = parseAdditionalImageHosts(hosts).join('\n')
|
|
329
|
+
} catch {
|
|
330
|
+
return { ok: false, error: '图片扩展主机配置无效:请填写精确域名,不要包含通配符、URL、端口或 IP 地址。' }
|
|
331
|
+
}
|
|
332
|
+
}
|
|
334
333
|
const normalized = this.normalizeAccountSettings(id, settings, prev)
|
|
335
334
|
if (!normalized.ok) return normalized
|
|
336
335
|
if (id === 'weixin' && incoming.botToken) {
|
|
@@ -460,7 +459,7 @@ export class ChannelManager {
|
|
|
460
459
|
}).webServer
|
|
461
460
|
if (!webServer) return
|
|
462
461
|
const send = (res: import('node:http').ServerResponse, status: number, body: unknown) => {
|
|
463
|
-
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' })
|
|
462
|
+
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
|
|
464
463
|
res.end(JSON.stringify(body))
|
|
465
464
|
}
|
|
466
465
|
const readJson = async (req: import('node:http').IncomingMessage): Promise<Record<string, unknown>> => {
|
|
@@ -469,25 +468,25 @@ export class ChannelManager {
|
|
|
469
468
|
if (invalidJson) throw new ApiRequestError(400, '请求体不是合法 JSON')
|
|
470
469
|
return body
|
|
471
470
|
}
|
|
472
|
-
const
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
const parts =
|
|
471
|
+
const dispatch = async (
|
|
472
|
+
method: string,
|
|
473
|
+
path: string,
|
|
474
|
+
readBody: () => Promise<Record<string, unknown>>,
|
|
475
|
+
send: (status: number, body: unknown) => void,
|
|
476
|
+
): Promise<void> => {
|
|
477
|
+
const payload = () => ({
|
|
478
|
+
ok: true,
|
|
479
|
+
channels: this.list(),
|
|
480
|
+
groups: this.channelSessions(),
|
|
481
|
+
pending: this.pendingRequests(),
|
|
482
|
+
assistant: this.currentAssistant(),
|
|
483
|
+
})
|
|
484
|
+
try {
|
|
485
|
+
// 路由段统一从插件前缀之后开始,身份认证只由下方入口负责。
|
|
486
|
+
const parts = ('/dsh-im-connect/api' + path).split('/').filter(Boolean)
|
|
488
487
|
if (parts[2] === 'assistant' && parts.length === 3) {
|
|
489
|
-
if (
|
|
490
|
-
send(
|
|
488
|
+
if (method === 'GET') {
|
|
489
|
+
send(200, {
|
|
491
490
|
ok: true,
|
|
492
491
|
assistant: this.currentAssistant(),
|
|
493
492
|
cwd: this.currentWorkspace(),
|
|
@@ -497,166 +496,199 @@ export class ChannelManager {
|
|
|
497
496
|
})
|
|
498
497
|
return
|
|
499
498
|
}
|
|
500
|
-
if (
|
|
501
|
-
const body = await
|
|
499
|
+
if (method === 'POST') {
|
|
500
|
+
const body = await readBody()
|
|
502
501
|
const result = this.setAssistant(body)
|
|
503
|
-
send(
|
|
502
|
+
send(result.ok ? 200 : 400, result)
|
|
504
503
|
return
|
|
505
504
|
}
|
|
506
|
-
send(
|
|
505
|
+
send(405, { ok: false, error: 'method not allowed' })
|
|
507
506
|
return
|
|
508
507
|
}
|
|
509
|
-
if (parts[2] === 'sessions' && parts.length === 4 &&
|
|
508
|
+
if (parts[2] === 'sessions' && parts.length === 4 && method === 'POST') {
|
|
510
509
|
const action = parts[3]
|
|
511
|
-
const body = await
|
|
510
|
+
const body = await readBody()
|
|
512
511
|
const sessionId = String(body.sessionId ?? '')
|
|
513
|
-
if (!sessionId) { send(
|
|
512
|
+
if (!sessionId) { send(400, { ok: false, error: '缺少 sessionId' }); return }
|
|
514
513
|
if (action === 'rename') {
|
|
515
514
|
const title = String(body.title ?? '').trim()
|
|
516
|
-
if (!title) { send(
|
|
515
|
+
if (!title) { send(400, { ok: false, error: '缺少标题' }); return }
|
|
517
516
|
const ok = this.engine.renameSession(sessionId, title)
|
|
518
|
-
send(
|
|
517
|
+
send(ok ? 200 : 404, ok ? { ok: true, groups: this.channelSessions() } : { ok: false, error: '会话不存在' })
|
|
519
518
|
return
|
|
520
519
|
}
|
|
521
520
|
if (action === 'remove') {
|
|
522
521
|
const ok = await this.engine.removeSession(sessionId)
|
|
523
|
-
send(
|
|
522
|
+
send(ok ? 200 : 404, ok ? { ok: true, groups: this.channelSessions() } : { ok: false, error: '会话不存在' })
|
|
524
523
|
return
|
|
525
524
|
}
|
|
526
525
|
if (action === 'ensure') {
|
|
527
526
|
const ok = await this.engine.ensureSession(sessionId)
|
|
528
|
-
send(
|
|
527
|
+
send(ok ? 200 : 404, ok ? { ok: true, sessionId } : { ok: false, error: '会话不存在' })
|
|
529
528
|
return
|
|
530
529
|
}
|
|
531
|
-
send(
|
|
530
|
+
send(404, { ok: false, error: `未知会话操作 ${action}` })
|
|
532
531
|
return
|
|
533
532
|
}
|
|
534
|
-
if (parts[2] === 'channels' && parts.length === 3 &&
|
|
535
|
-
send(
|
|
533
|
+
if (parts[2] === 'channels' && parts.length === 3 && method === 'GET') {
|
|
534
|
+
send(200, payload())
|
|
536
535
|
return
|
|
537
536
|
}
|
|
538
537
|
if (parts[2] === 'channels' && parts.length === 6 && parts[4] === 'qr') {
|
|
539
538
|
const id = parts[3] as ChannelId
|
|
540
539
|
const action = parts[5]
|
|
541
|
-
if (!CHANNEL_META[id]) { send(
|
|
542
|
-
if (!supportsQr(id)) { send(
|
|
543
|
-
if (action === 'status' &&
|
|
544
|
-
send(
|
|
540
|
+
if (!CHANNEL_META[id]) { send(404, { ok: false, error: '未知渠道' }); return }
|
|
541
|
+
if (!supportsQr(id)) { send(400, { ok: false, error: '该渠道不支持扫码绑定' }); return }
|
|
542
|
+
if (action === 'status' && method === 'GET') {
|
|
543
|
+
send(200, { ok: true, pairing: this.pairing.view(id), channel: this.list().find((item) => item.id === id) })
|
|
545
544
|
return
|
|
546
545
|
}
|
|
547
|
-
if (
|
|
548
|
-
const body = await
|
|
546
|
+
if (method !== 'POST') { send(405, { ok: false, error: 'method not allowed' }); return }
|
|
547
|
+
const body = await readBody()
|
|
549
548
|
if (action === 'start') {
|
|
550
549
|
const pairing = await this.pairing.start(id, pairingSettings(body.settings as Record<string, unknown> | undefined))
|
|
551
|
-
send(
|
|
550
|
+
send(pairing.status === 'failed' ? 400 : 200, { ok: pairing.status !== 'failed', pairing, error: pairing.error })
|
|
552
551
|
return
|
|
553
552
|
}
|
|
554
553
|
if (action === 'refresh') {
|
|
555
554
|
const pairing = await this.pairing.refresh(id)
|
|
556
|
-
send(
|
|
555
|
+
send(pairing.status === 'failed' ? 400 : 200, { ok: pairing.status !== 'failed', pairing, error: pairing.error })
|
|
557
556
|
return
|
|
558
557
|
}
|
|
559
558
|
if (action === 'cancel') {
|
|
560
|
-
send(
|
|
559
|
+
send(200, { ok: true, pairing: this.pairing.cancel(id) })
|
|
561
560
|
return
|
|
562
561
|
}
|
|
563
|
-
send(
|
|
562
|
+
send(404, { ok: false, error: `未知扫码操作 ${action}` })
|
|
564
563
|
return
|
|
565
564
|
}
|
|
566
|
-
if (parts[2] === 'channels' && parts.length === 5 &&
|
|
565
|
+
if (parts[2] === 'channels' && parts.length === 5 && method === 'POST') {
|
|
567
566
|
const id = parts[3] as ChannelId
|
|
568
567
|
const action = parts[4]
|
|
569
|
-
const body = await
|
|
568
|
+
const body = await readBody()
|
|
570
569
|
if (action === 'connect') {
|
|
571
570
|
const result = await this.connect(id, body.config as Record<string, string> | undefined, body.settings as Record<string, unknown> | undefined)
|
|
572
|
-
send(
|
|
571
|
+
send(result.ok ? 200 : 400, result.ok ? { ...result, channel: this.list().find((item) => item.id === id) } : result)
|
|
573
572
|
return
|
|
574
573
|
}
|
|
575
574
|
if (action === 'receive') {
|
|
576
575
|
const result = await this.setReceive(id, body.receiveEnabled !== false)
|
|
577
|
-
send(
|
|
576
|
+
send(result.ok ? 200 : 400, result.ok ? { ok: true, channel: this.list().find((item) => item.id === id) } : result)
|
|
578
577
|
return
|
|
579
578
|
}
|
|
580
579
|
if (action === 'disconnect') {
|
|
581
580
|
await this.disconnect(id)
|
|
582
|
-
send(
|
|
581
|
+
send(200, { ok: true, channel: this.list().find((item) => item.id === id) })
|
|
583
582
|
return
|
|
584
583
|
}
|
|
585
584
|
if (action === 'remove') {
|
|
586
585
|
await this.remove(id)
|
|
587
|
-
send(
|
|
586
|
+
send(200, { ok: true, channel: this.list().find((item) => item.id === id) })
|
|
588
587
|
return
|
|
589
588
|
}
|
|
590
589
|
if (action === 'approve' || action === 'deny') {
|
|
591
590
|
const userId = String(body.userId ?? '')
|
|
592
|
-
if (!userId) { send(
|
|
591
|
+
if (!userId) { send(400, { ok: false, error: '缺少 userId' }); return }
|
|
593
592
|
const accountId = this.resolveAccountId(id)
|
|
594
|
-
if (!accountId) { send(
|
|
593
|
+
if (!accountId) { send(404, { ok: false, error: '账号不存在或该渠道包含多个账号' }); return }
|
|
595
594
|
if (action === 'approve') this.approve(accountId, userId)
|
|
596
595
|
else this.deny(accountId, userId)
|
|
597
|
-
send(
|
|
596
|
+
send(200, { ok: true, pending: this.pendingRequests() })
|
|
598
597
|
return
|
|
599
598
|
}
|
|
600
|
-
send(
|
|
599
|
+
send(404, { ok: false, error: `未知操作 ${action}` })
|
|
601
600
|
return
|
|
602
601
|
}
|
|
603
|
-
if (parts[2] === 'accounts' && parts.length === 5 &&
|
|
602
|
+
if (parts[2] === 'accounts' && parts.length === 5 && method === 'POST') {
|
|
604
603
|
const accountId = parts[3]!
|
|
605
604
|
const action = parts[4]!
|
|
606
|
-
const body = await
|
|
607
|
-
if (!this.store.channels[accountId]) { send(
|
|
605
|
+
const body = await readBody()
|
|
606
|
+
if (!this.store.channels[accountId]) { send(404, { ok: false, error: '账号不存在' }); return }
|
|
608
607
|
if (action === 'settings') {
|
|
609
608
|
const result = await this.updateAccount(accountId, body)
|
|
610
|
-
send(
|
|
609
|
+
send(result.ok ? 200 : 400, result)
|
|
611
610
|
return
|
|
612
611
|
}
|
|
613
612
|
if (action === 'receive') {
|
|
614
613
|
const result = await this.setReceive(accountId, body.receiveEnabled !== false)
|
|
615
|
-
send(
|
|
614
|
+
send(result.ok ? 200 : 400, result)
|
|
616
615
|
return
|
|
617
616
|
}
|
|
618
617
|
if (action === 'reconnect') {
|
|
619
618
|
const result = await this.reconnect(accountId)
|
|
620
|
-
send(
|
|
619
|
+
send(result.ok ? 200 : 400, result)
|
|
621
620
|
return
|
|
622
621
|
}
|
|
623
622
|
if (action === 'check') {
|
|
624
623
|
const state = this.store.channels[accountId]!
|
|
625
624
|
state.lastCheckedAt = new Date().toISOString()
|
|
626
625
|
this.flush()
|
|
627
|
-
send(
|
|
626
|
+
send(200, { ok: true, account: this.accountView(accountId, state) })
|
|
628
627
|
return
|
|
629
628
|
}
|
|
630
629
|
if (action === 'remove') {
|
|
631
630
|
await this.remove(accountId)
|
|
632
|
-
send(
|
|
631
|
+
send(200, { ok: true })
|
|
633
632
|
return
|
|
634
633
|
}
|
|
635
634
|
if (action === 'approve' || action === 'deny') {
|
|
636
635
|
const userId = String(body.userId ?? '')
|
|
637
|
-
if (!userId) { send(
|
|
636
|
+
if (!userId) { send(400, { ok: false, error: '缺少 userId' }); return }
|
|
638
637
|
action === 'approve' ? this.approve(accountId, userId) : this.deny(accountId, userId)
|
|
639
|
-
send(
|
|
638
|
+
send(200, { ok: true, pending: this.pendingRequests() })
|
|
640
639
|
return
|
|
641
640
|
}
|
|
642
|
-
send(
|
|
641
|
+
send(404, { ok: false, error: `未知账号操作 ${action}` })
|
|
643
642
|
return
|
|
644
643
|
}
|
|
645
|
-
send(
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
644
|
+
send(404, { ok: false, error: 'not found' })
|
|
645
|
+
} catch (error) {
|
|
646
|
+
// 单个路由异常不能让 HTTP 连接悬死,统一回 500 并落日志。
|
|
647
|
+
if (error instanceof ApiRequestError) {
|
|
648
|
+
send(error.status, { ok: false, error: error.message })
|
|
649
|
+
return
|
|
650
|
+
}
|
|
651
|
+
const detail = error instanceof Error ? error.message : String(error)
|
|
652
|
+
this.log(`[manager] API 处理失败: ${detail}`)
|
|
653
|
+
send(500, { ok: false, error: '操作失败,请查看本机日志' })
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
const basePath = '/api/dsh-im-connect'
|
|
658
|
+
const dispose = webServer.register({
|
|
659
|
+
kind: 'prefix',
|
|
660
|
+
path: basePath,
|
|
661
|
+
handler: async (req, res) => {
|
|
662
|
+
try {
|
|
663
|
+
// 动态读取活动服务,并保留 requestRejection 的 this 绑定。
|
|
664
|
+
const connection = (typeof ctx.get === 'function' ? ctx.get('connection') : undefined) as {
|
|
665
|
+
requestRejection?: (request: { headers: typeof req.headers }) => 401 | 403 | undefined
|
|
666
|
+
} | undefined
|
|
667
|
+
if (typeof connection?.requestRejection !== 'function') {
|
|
668
|
+
send(res, 503, { ok: false, error: '宿主认证服务尚未就绪或版本不支持;请稍后重试或升级宿主。 / Retry or upgrade DSH to enable authenticated management.' })
|
|
669
|
+
return
|
|
670
|
+
}
|
|
671
|
+
const rejection = connection.requestRejection(req)
|
|
672
|
+
if (rejection !== undefined) {
|
|
673
|
+
send(res, rejection, { ok: false, error: rejection === 401 ? '请先登录 DSH / Sign in to DSH first' : '宿主拒绝此 Host 或跨站请求 / Host or cross-site request forbidden' })
|
|
650
674
|
return
|
|
651
675
|
}
|
|
652
|
-
const
|
|
653
|
-
|
|
676
|
+
const requestError = validateApiMutation(req)
|
|
677
|
+
if (requestError) { send(res, requestError.status, { ok: false, error: requestError.error }); return }
|
|
678
|
+
const url = new URL(req.url ?? '/', 'http://localhost')
|
|
679
|
+
if (url.pathname !== basePath && !url.pathname.startsWith(basePath + '/')) {
|
|
680
|
+
send(res, 404, { ok: false, error: 'not found' })
|
|
681
|
+
return
|
|
682
|
+
}
|
|
683
|
+
await dispatch(req.method ?? 'GET', url.pathname.slice(basePath.length), () => readJson(req), (status, body) => send(res, status, body))
|
|
684
|
+
} catch (error) {
|
|
685
|
+
this.log(`[manager] API 认证失败: ${error instanceof Error ? error.message : String(error)}`)
|
|
654
686
|
send(res, 500, { ok: false, error: '操作失败,请查看本机日志' })
|
|
655
687
|
}
|
|
656
688
|
},
|
|
657
689
|
})
|
|
658
690
|
if (typeof dispose === 'function') this.apiDisposers.push(dispose)
|
|
659
|
-
this.log('[manager] API 已注册 /dsh-im-connect
|
|
691
|
+
this.log('[manager] API 已注册 /api/dsh-im-connect')
|
|
660
692
|
}
|
|
661
693
|
|
|
662
694
|
disposeApi(): void {
|