@michengai/dsh-im-connect 1.0.11 → 1.0.13
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 +15 -0
- package/CHANGELOG.zh-CN.md +15 -0
- package/README.md +28 -3
- package/README.zh-CN.md +28 -3
- package/client.js +438 -17
- package/lib/api-base.d.ts +21 -0
- package/lib/api-base.d.ts.map +1 -0
- package/lib/api-base.js +51 -0
- package/lib/api-base.js.map +1 -0
- package/lib/channels/channel-image-download.d.ts +8 -5
- package/lib/channels/channel-image-download.d.ts.map +1 -1
- package/lib/channels/channel-image-download.js +70 -2
- package/lib/channels/channel-image-download.js.map +1 -1
- package/lib/channels/diagnostics.d.ts +1 -1
- package/lib/channels/diagnostics.d.ts.map +1 -1
- package/lib/channels/diagnostics.js +2 -2
- package/lib/channels/diagnostics.js.map +1 -1
- package/lib/channels/discord.d.ts +3 -0
- package/lib/channels/discord.d.ts.map +1 -1
- package/lib/channels/discord.js +56 -7
- package/lib/channels/discord.js.map +1 -1
- package/lib/channels/factory.d.ts.map +1 -1
- package/lib/channels/factory.js +8 -2
- package/lib/channels/factory.js.map +1 -1
- package/lib/channels/file-send.d.ts +1 -1
- package/lib/channels/file-send.d.ts.map +1 -1
- package/lib/channels/file-send.js +2 -2
- package/lib/channels/file-send.js.map +1 -1
- package/lib/channels/meta.d.ts +2 -0
- package/lib/channels/meta.d.ts.map +1 -1
- package/lib/channels/meta.js +2 -0
- package/lib/channels/meta.js.map +1 -1
- package/lib/channels/telegram.d.ts +2 -0
- package/lib/channels/telegram.d.ts.map +1 -1
- package/lib/channels/telegram.js +29 -6
- package/lib/channels/telegram.js.map +1 -1
- package/lib/client.js +523 -21
- package/lib/index.d.ts +2 -0
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +10 -6
- package/lib/index.js.map +1 -1
- package/lib/manager.d.ts +15 -0
- package/lib/manager.d.ts.map +1 -1
- package/lib/manager.js +221 -32
- package/lib/manager.js.map +1 -1
- package/lib/plugin-updater.d.ts +1 -0
- package/lib/plugin-updater.d.ts.map +1 -1
- package/lib/plugin-updater.js +7 -0
- package/lib/plugin-updater.js.map +1 -1
- package/package.json +5 -4
- package/src/api-base.ts +45 -0
- package/src/channels/channel-image-download.ts +83 -5
- package/src/channels/diagnostics.ts +2 -2
- package/src/channels/discord.ts +49 -7
- package/src/channels/factory.ts +8 -2
- package/src/channels/file-send.ts +2 -2
- package/src/channels/meta.ts +4 -0
- package/src/channels/telegram.ts +22 -6
- package/src/index.ts +12 -6
- package/src/manager.ts +214 -31
- package/src/plugin-update-ui.js +36 -5
- package/src/plugin-updater.ts +8 -1
|
@@ -86,16 +86,91 @@ function sameHostRedirect(current: URL, location: string | string[] | undefined)
|
|
|
86
86
|
return next.href
|
|
87
87
|
}
|
|
88
88
|
|
|
89
|
-
|
|
90
|
-
* No ambient proxy/credentials. Same-host redirects are opt-in. IPv4-only intentionally fails closed on IPv6-only hosts.
|
|
91
|
-
*/
|
|
92
|
-
export async function requestChannelBytes(rawUrl: string, options: {
|
|
89
|
+
export interface ChannelByteRequestOptions {
|
|
93
90
|
method?: 'GET' | 'POST'; headers?: Record<string, string>; body?: string
|
|
94
91
|
maxBytes?: number; timeoutMs?: number; signal?: AbortSignal
|
|
95
92
|
additionalTrustedHosts?: readonly string[]
|
|
96
93
|
/** 只跟随同一主机的 HTTPS 跳转,令牌不会被带到别的域名。默认不跟随。 */
|
|
97
94
|
sameHostRedirects?: number
|
|
98
|
-
|
|
95
|
+
/** 自定义 fetcher(用于账号级代理分流,挂载 ProxyAgent) */
|
|
96
|
+
fetcher?: typeof fetch
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* 代理模式下的下载实现:
|
|
101
|
+
* 在 custom/direct 代理分流下由外部注入带 Dispatcher 的 fetcher 执行请求。
|
|
102
|
+
* 此时目标域名的 DNS 解析由代理服务器完成,本地 DNS rebinding 校验不适用;
|
|
103
|
+
* 但仍严格保留并执行:强制 HTTPS、默认 443 端口、禁止裸 IP、禁止凭据、仅限同主机重定向、拦截 text/html 以及流式字节上限防护。
|
|
104
|
+
*/
|
|
105
|
+
async function requestChannelBytesViaFetcher(
|
|
106
|
+
url: URL,
|
|
107
|
+
options: ChannelByteRequestOptions,
|
|
108
|
+
fetcher: typeof fetch,
|
|
109
|
+
): Promise<Buffer> {
|
|
110
|
+
const signal = options.timeoutMs
|
|
111
|
+
? AbortSignal.any([AbortSignal.timeout(options.timeoutMs), ...(options.signal ? [options.signal] : [])])
|
|
112
|
+
: options.signal ?? AbortSignal.timeout(30_000)
|
|
113
|
+
signal.throwIfAborted()
|
|
114
|
+
|
|
115
|
+
const response = await fetcher(url.href, {
|
|
116
|
+
method: options.method ?? 'GET',
|
|
117
|
+
headers: options.headers,
|
|
118
|
+
body: options.body,
|
|
119
|
+
signal,
|
|
120
|
+
redirect: 'manual',
|
|
121
|
+
})
|
|
122
|
+
|
|
123
|
+
const status = response.status
|
|
124
|
+
const redirects = options.sameHostRedirects ?? 0
|
|
125
|
+
if (redirects > 0 && [301, 302, 307, 308].includes(status)) {
|
|
126
|
+
const location = response.headers.get('location')
|
|
127
|
+
await response.body?.cancel().catch(() => undefined)
|
|
128
|
+
const next = sameHostRedirect(url, location ?? undefined)
|
|
129
|
+
if (!next) throw new Error('图片地址不符合安全要求')
|
|
130
|
+
return requestChannelBytes(next, { ...options, sameHostRedirects: redirects - 1, fetcher })
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
if (status !== 200) {
|
|
134
|
+
await response.body?.cancel().catch(() => undefined)
|
|
135
|
+
throw new Error(`图片下载 HTTP ${status}`)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const contentType = String(response.headers.get('content-type') ?? '')
|
|
139
|
+
if (/text\/html/i.test(contentType)) {
|
|
140
|
+
await response.body?.cancel().catch(() => undefined)
|
|
141
|
+
throw new Error('图片地址不符合安全要求')
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const maxBytes = options.maxBytes ?? MAX_CHANNEL_IMAGE_BYTES + 32
|
|
145
|
+
const contentLength = Number(response.headers.get('content-length'))
|
|
146
|
+
if (contentLength > maxBytes) {
|
|
147
|
+
await response.body?.cancel().catch(() => undefined)
|
|
148
|
+
throw new Error('图片超过大小限制')
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
if (!response.body) return Buffer.alloc(0)
|
|
152
|
+
const reader = response.body.getReader()
|
|
153
|
+
const chunks: Buffer[] = []
|
|
154
|
+
let size = 0
|
|
155
|
+
try {
|
|
156
|
+
while (true) {
|
|
157
|
+
const { done, value } = await reader.read()
|
|
158
|
+
if (done) break
|
|
159
|
+
size += value.length
|
|
160
|
+
if (size > maxBytes) throw new Error('图片超过大小限制')
|
|
161
|
+
chunks.push(Buffer.from(value))
|
|
162
|
+
}
|
|
163
|
+
return Buffer.concat(chunks)
|
|
164
|
+
} finally {
|
|
165
|
+
await reader.cancel().catch(() => undefined)
|
|
166
|
+
reader.releaseLock()
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** HTTPS only; 未注入 fetcher 时走本地原生连接查找与 DNS rebinding 防护(直连无环境代理);
|
|
171
|
+
* 传入 fetcher 时通过账号级代理分流。仅限同主机重定向。IPv4-only 模式在纯 IPv6 主机上明确快速失败。
|
|
172
|
+
*/
|
|
173
|
+
export async function requestChannelBytes(rawUrl: string, options: ChannelByteRequestOptions = {}): Promise<Buffer> {
|
|
99
174
|
const additionalHosts = new Set(validateAdditionalImageHosts(options.additionalTrustedHosts))
|
|
100
175
|
options.signal?.throwIfAborted()
|
|
101
176
|
const url = new URL(rawUrl)
|
|
@@ -103,6 +178,9 @@ export async function requestChannelBytes(rawUrl: string, options: {
|
|
|
103
178
|
|| isIP(url.hostname) || url.hostname.includes(':') || url.hostname.endsWith('.')) {
|
|
104
179
|
throw new Error('图片地址不符合安全要求')
|
|
105
180
|
}
|
|
181
|
+
if (options.fetcher) {
|
|
182
|
+
return requestChannelBytesViaFetcher(url, options, options.fetcher)
|
|
183
|
+
}
|
|
106
184
|
return new Promise((resolve, reject) => {
|
|
107
185
|
let settled = false
|
|
108
186
|
let timer: ReturnType<typeof setTimeout> | undefined
|
|
@@ -28,8 +28,8 @@ export async function probe(id: DiagnosticCheck['id'], signal: AbortSignal, run:
|
|
|
28
28
|
}
|
|
29
29
|
|
|
30
30
|
/** 新请求、不跟随重定向、限制回包大小;调用方负责平台业务码与必要字段校验。 */
|
|
31
|
-
export async function diagnosticJson(url: string, signal: AbortSignal, body?: unknown, headers?: Record<string, string
|
|
32
|
-
const response = await
|
|
31
|
+
export async function diagnosticJson(url: string, signal: AbortSignal, body?: unknown, headers?: Record<string, string>, fetcher: typeof fetch = fetch): Promise<Record<string, unknown>> {
|
|
32
|
+
const response = await fetcher(url, { method: body === undefined ? 'GET' : 'POST', headers: { 'content-type': 'application/json', ...headers }, body: body === undefined ? undefined : JSON.stringify(body), signal, redirect: 'error' })
|
|
33
33
|
if (!response.ok) {
|
|
34
34
|
await response.body?.cancel()
|
|
35
35
|
const status = response.status
|
package/src/channels/discord.ts
CHANGED
|
@@ -7,14 +7,18 @@ import { sleepWithSignal, timeoutSignal } from '../engine/abort.js'
|
|
|
7
7
|
import { splitText } from '../engine/split.js'
|
|
8
8
|
import { diagnosticJson, probe, requireDiagnostic } from './diagnostics.js'
|
|
9
9
|
import { fileMedia, imageMedia, requestChannelBytes } from './channel-image-download.js'
|
|
10
|
+
import { Agent, type Dispatcher, ProxyAgent } from 'undici'
|
|
10
11
|
|
|
11
12
|
export interface DiscordConfig {
|
|
12
13
|
token?: string
|
|
13
14
|
stateDir?: string
|
|
14
15
|
host?: { get(name: string): unknown }
|
|
15
16
|
fetchImpl?: typeof fetch
|
|
17
|
+
/** 自定义 WebSocket 工厂;若指定此项,代理分流由外部工厂负责处理。 */
|
|
16
18
|
createWebSocket?: (url: string) => GatewaySocket
|
|
17
19
|
connectTimeoutMs?: number
|
|
20
|
+
proxyMode?: 'inherit' | 'direct' | 'custom'
|
|
21
|
+
proxyUrl?: string
|
|
18
22
|
}
|
|
19
23
|
|
|
20
24
|
export interface GatewaySocketEvent { data?: unknown; code?: number }
|
|
@@ -377,8 +381,35 @@ export async function resolveDiscordRoute(
|
|
|
377
381
|
export function createDiscordChannel(config: DiscordConfig, log: (line: string) => void): ChannelAdapter | undefined {
|
|
378
382
|
const token = config.token?.trim()
|
|
379
383
|
if (!token) return undefined
|
|
380
|
-
const
|
|
381
|
-
|
|
384
|
+
const proxyMode = config.proxyMode ?? 'inherit'
|
|
385
|
+
let parsedProxyUrl: string | undefined
|
|
386
|
+
if (proxyMode === 'custom') {
|
|
387
|
+
let proxyUrl: URL
|
|
388
|
+
try { proxyUrl = new URL(config.proxyUrl ?? '') } catch { throw new Error('Discord 代理地址无效') }
|
|
389
|
+
if (!['http:', 'https:'].includes(proxyUrl.protocol) || !proxyUrl.hostname || proxyUrl.pathname !== '/' || proxyUrl.search || proxyUrl.hash) {
|
|
390
|
+
throw new Error('Discord 代理地址无效')
|
|
391
|
+
}
|
|
392
|
+
parsedProxyUrl = proxyUrl.toString()
|
|
393
|
+
} else if (proxyMode !== 'inherit' && proxyMode !== 'direct') throw new Error('Discord 代理模式无效')
|
|
394
|
+
|
|
395
|
+
let dispatcher: Dispatcher | undefined
|
|
396
|
+
function getDispatcher(): Dispatcher | undefined {
|
|
397
|
+
if (proxyMode === 'inherit') return undefined
|
|
398
|
+
const isAlive = (d: any) => Boolean(d && !d.closed && !d.destroyed)
|
|
399
|
+
if (dispatcher && isAlive(dispatcher)) return dispatcher
|
|
400
|
+
if (proxyMode === 'direct') dispatcher = new Agent()
|
|
401
|
+
else if (proxyMode === 'custom' && parsedProxyUrl) dispatcher = new ProxyAgent(parsedProxyUrl)
|
|
402
|
+
return dispatcher
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
const fetchImpl: typeof fetch = config.fetchImpl ?? ((input, init) => {
|
|
406
|
+
const disp = getDispatcher()
|
|
407
|
+
return fetch(input, disp ? { ...init, dispatcher: disp } as RequestInit : init)
|
|
408
|
+
})
|
|
409
|
+
const createSocket = config.createWebSocket ?? ((url: string) => {
|
|
410
|
+
const disp = getDispatcher()
|
|
411
|
+
return new WebSocket(url, disp ? ({ dispatcher: disp } as any) : undefined)
|
|
412
|
+
})
|
|
382
413
|
const cursorFile = new JsonStateFile<GatewayCursor>(config.stateDir ? `${config.stateDir.replace(/[\\/]$/, '')}/discord-gateway.json` : '', EMPTY_CURSOR)
|
|
383
414
|
const persist = Boolean(config.stateDir)
|
|
384
415
|
let handler: ((msg: ImMessage) => void | Promise<void>) | undefined
|
|
@@ -503,6 +534,7 @@ export function createDiscordChannel(config: DiscordConfig, log: (line: string)
|
|
|
503
534
|
signal,
|
|
504
535
|
maxBytes: kind === 'image' ? 10 * 1024 * 1024 : 20 * 1024 * 1024,
|
|
505
536
|
additionalTrustedHosts: [new URL(url).hostname],
|
|
537
|
+
fetcher: dispatcher ? fetchImpl : undefined,
|
|
506
538
|
})
|
|
507
539
|
const name = attachment.filename?.replace(/\\/g, '/').split('/').pop()
|
|
508
540
|
media.push(kind === 'image' ? { ...imageMedia(bytes), ...(name ? { name } : {}) } : fileMedia(bytes, name))
|
|
@@ -773,12 +805,17 @@ export function createDiscordChannel(config: DiscordConfig, log: (line: string)
|
|
|
773
805
|
choiceLimits: { maxButtons: 25, maxTextLength: 1800 },
|
|
774
806
|
typingIntervalMs: 8_000,
|
|
775
807
|
async start() {
|
|
776
|
-
await this.stop()
|
|
777
808
|
stopped = false
|
|
778
809
|
starting = true
|
|
779
810
|
readyOnce = false
|
|
780
811
|
statusText = '连接中'
|
|
812
|
+
clearTimeout(reconnectTimer)
|
|
813
|
+
clearHeartbeat()
|
|
814
|
+
generation += 1
|
|
815
|
+
lifecycle.abort()
|
|
781
816
|
lifecycle = new AbortController()
|
|
817
|
+
socket?.close(1000, 'restarting')
|
|
818
|
+
socket = undefined
|
|
782
819
|
const saved = persist ? cursorFile.read() : EMPTY_CURSOR
|
|
783
820
|
sessionId = saved.sessionId || ''
|
|
784
821
|
resumeUrl = saved.resumeUrl || ''
|
|
@@ -791,16 +828,18 @@ export function createDiscordChannel(config: DiscordConfig, log: (line: string)
|
|
|
791
828
|
if (!bot?.id || bot.bot !== true) throw new Error('Discord token does not belong to a bot')
|
|
792
829
|
runtimeBotId = String(bot.id)
|
|
793
830
|
gatewayBase = String(gateway?.url ?? '')
|
|
831
|
+
const hadCursor = Boolean(sessionId && resumeUrl)
|
|
794
832
|
try {
|
|
795
|
-
await connectOnce(
|
|
833
|
+
await connectOnce(hadCursor)
|
|
796
834
|
} catch (error) {
|
|
797
|
-
if (fatalGateway(error) || !
|
|
835
|
+
if (fatalGateway(error) || !hadCursor) throw error
|
|
798
836
|
clearCursor()
|
|
799
837
|
await connectOnce(false)
|
|
800
838
|
}
|
|
801
839
|
starting = false
|
|
802
840
|
log('[discord] Gateway 已连接')
|
|
803
841
|
} catch (error) {
|
|
842
|
+
log(`[discord] 启动失败: ${error instanceof Error ? error.message : String(error)}`)
|
|
804
843
|
// 4000/1006 只是这次握手失败。停掉适配器后管理器不会再拉起,重启就会一直停在连接异常。
|
|
805
844
|
if (!recoverableGateway(error)) {
|
|
806
845
|
statusText = '连接失败,请查看本机日志'
|
|
@@ -826,6 +865,9 @@ export function createDiscordChannel(config: DiscordConfig, log: (line: string)
|
|
|
826
865
|
socket?.close(1000, 'stopped')
|
|
827
866
|
socket = undefined
|
|
828
867
|
saveCursor()
|
|
868
|
+
const currentDispatcher = dispatcher
|
|
869
|
+
dispatcher = undefined
|
|
870
|
+
if (currentDispatcher) await Promise.resolve(currentDispatcher.close()).catch(() => (currentDispatcher as any)?.destroy?.())
|
|
829
871
|
},
|
|
830
872
|
canDeliverDeferred() { return !stopped && statusText === '长连接已建立' },
|
|
831
873
|
async send(chatId, text) {
|
|
@@ -937,12 +979,12 @@ export function createDiscordChannel(config: DiscordConfig, log: (line: string)
|
|
|
937
979
|
setMessageHandler(next) { handler = next },
|
|
938
980
|
async diagnose(signal) {
|
|
939
981
|
const identity = await probe('bot', signal, async () => {
|
|
940
|
-
const bot = await diagnosticJson(new URL('users/@me', API).href, signal, undefined, headers)
|
|
982
|
+
const bot = await diagnosticJson(new URL('users/@me', API).href, signal, undefined, headers, fetchImpl)
|
|
941
983
|
requireDiagnostic(bot.id && bot.bot === true)
|
|
942
984
|
})
|
|
943
985
|
if (identity.status !== 'passed') return [identity]
|
|
944
986
|
return [identity, await probe('gateway', signal, async () => {
|
|
945
|
-
const gateway = await diagnosticJson(new URL('gateway/bot', API).href, signal, undefined, headers)
|
|
987
|
+
const gateway = await diagnosticJson(new URL('gateway/bot', API).href, signal, undefined, headers, fetchImpl)
|
|
946
988
|
requireDiagnostic(typeof gateway.url === 'string')
|
|
947
989
|
gatewayUrl(gateway.url)
|
|
948
990
|
})]
|
package/src/channels/factory.ts
CHANGED
|
@@ -22,9 +22,15 @@ export function createChannelAdapter(
|
|
|
22
22
|
? { additionalImageHosts: parseAdditionalImageHosts(config.additionalImageHosts) } : {}
|
|
23
23
|
switch (id) {
|
|
24
24
|
case 'telegram':
|
|
25
|
-
adapter = createTelegramChannel({ token: config.token, stateDir, host: options?.host }, log); break
|
|
25
|
+
adapter = createTelegramChannel({ token: config.token, stateDir, host: options?.host, proxyMode: config.proxyMode as 'inherit' | 'direct' | 'custom' | undefined, proxyUrl: config.proxyUrl }, log); break
|
|
26
26
|
case 'discord':
|
|
27
|
-
adapter = createDiscordChannel({
|
|
27
|
+
adapter = createDiscordChannel({
|
|
28
|
+
token: config.token,
|
|
29
|
+
stateDir,
|
|
30
|
+
host: options?.host,
|
|
31
|
+
proxyMode: config.proxyMode as 'inherit' | 'direct' | 'custom' | undefined,
|
|
32
|
+
proxyUrl: config.proxyUrl,
|
|
33
|
+
}, log); break
|
|
28
34
|
case 'feishu':
|
|
29
35
|
adapter = createFeishuChannel('feishu', { appId: config.appId, appSecret: config.appSecret, host: options?.host }, log); break
|
|
30
36
|
case 'lark':
|
|
@@ -11,8 +11,8 @@ export function fileForm(file: OutgoingFile, field: string): FormData {
|
|
|
11
11
|
}
|
|
12
12
|
|
|
13
13
|
/** 上传响应只提取协议状态,避免令牌或临时 URL 进入错误日志。 */
|
|
14
|
-
export async function fileRequest(url: string, init: RequestInit): Promise<any> {
|
|
15
|
-
const response = await
|
|
14
|
+
export async function fileRequest(url: string, init: RequestInit, fetcher: typeof fetch = fetch): Promise<any> {
|
|
15
|
+
const response = await fetcher(url, { ...init, redirect: 'error', signal: init.signal ?? AbortSignal.timeout(120_000) })
|
|
16
16
|
if (!response.ok) throw new Error(`file-transfer-http-${response.status}`)
|
|
17
17
|
const data = await response.json() as any
|
|
18
18
|
const rejected = (code: unknown) => code !== undefined && code !== 0 && code !== '0'
|
package/src/channels/meta.ts
CHANGED
|
@@ -6,6 +6,8 @@ export interface ChannelField {
|
|
|
6
6
|
key: string
|
|
7
7
|
label: string
|
|
8
8
|
secret?: boolean
|
|
9
|
+
/** 仅用于已绑定账号的设置,不放进新增账号凭据表单。 */
|
|
10
|
+
settingsOnly?: boolean
|
|
9
11
|
}
|
|
10
12
|
|
|
11
13
|
export interface ChannelMeta {
|
|
@@ -95,6 +97,7 @@ export const CHANNEL_META: Record<ChannelId, ChannelMeta> = {
|
|
|
95
97
|
kind: 'credentials',
|
|
96
98
|
fields: [
|
|
97
99
|
{ key: 'token', label: 'Bot Token', secret: true },
|
|
100
|
+
{ key: 'proxyUrl', label: '代理地址', secret: true, settingsOnly: true },
|
|
98
101
|
],
|
|
99
102
|
},
|
|
100
103
|
discord: {
|
|
@@ -104,6 +107,7 @@ export const CHANNEL_META: Record<ChannelId, ChannelMeta> = {
|
|
|
104
107
|
kind: 'credentials',
|
|
105
108
|
fields: [
|
|
106
109
|
{ key: 'token', label: 'Bot Token', secret: true },
|
|
110
|
+
{ key: 'proxyUrl', label: '代理地址', secret: true, settingsOnly: true },
|
|
107
111
|
],
|
|
108
112
|
},
|
|
109
113
|
slack: {
|
package/src/channels/telegram.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { choiceSendError } from '../engine/choice-delivery.js'
|
|
2
|
+
import { Agent, ProxyAgent, type Dispatcher } from 'undici'
|
|
2
3
|
import { DeliveryRejected } from '../engine/deferred-delivery.js'
|
|
3
4
|
import { notice } from '../engine/command-locale.js'
|
|
4
5
|
import { diagnosticJson, DiagnosticError, probe, requireDiagnostic } from './diagnostics.js'
|
|
@@ -12,6 +13,8 @@ export interface TelegramConfig {
|
|
|
12
13
|
token?: string
|
|
13
14
|
stateDir?: string
|
|
14
15
|
host?: { get(name: string): unknown }
|
|
16
|
+
proxyMode?: 'inherit' | 'direct' | 'custom'
|
|
17
|
+
proxyUrl?: string
|
|
15
18
|
}
|
|
16
19
|
|
|
17
20
|
interface TgUpdate {
|
|
@@ -119,6 +122,18 @@ export function toTelegramRichMarkdown(value: string): string | undefined {
|
|
|
119
122
|
export function createTelegramChannel(config: TelegramConfig, log: (line: string) => void): ChannelAdapter | undefined {
|
|
120
123
|
const token = config.token?.trim()
|
|
121
124
|
if (!token) return undefined
|
|
125
|
+
const proxyMode = config.proxyMode ?? 'inherit'
|
|
126
|
+
let dispatcher: Dispatcher | undefined
|
|
127
|
+
if (proxyMode === 'direct') dispatcher = new Agent()
|
|
128
|
+
else if (proxyMode === 'custom') {
|
|
129
|
+
let proxyUrl: URL
|
|
130
|
+
try { proxyUrl = new URL(config.proxyUrl ?? '') } catch { throw new Error('Telegram 代理地址无效') }
|
|
131
|
+
if (!['http:', 'https:'].includes(proxyUrl.protocol) || !proxyUrl.hostname || proxyUrl.pathname !== '/' || proxyUrl.search || proxyUrl.hash) {
|
|
132
|
+
throw new Error('Telegram 代理地址无效')
|
|
133
|
+
}
|
|
134
|
+
dispatcher = new ProxyAgent(proxyUrl.toString())
|
|
135
|
+
} else if (proxyMode !== 'inherit') throw new Error('Telegram 代理模式无效')
|
|
136
|
+
const fetchTelegram: typeof fetch = (input, init) => fetch(input, dispatcher ? { ...init, dispatcher } as RequestInit : init)
|
|
122
137
|
const cursorFile = new JsonStateFile(config.stateDir ? `${config.stateDir.replace(/[\\/]$/, '')}/cursor.json` : '', { offset: 0 })
|
|
123
138
|
const persist = Boolean(config.stateDir)
|
|
124
139
|
|
|
@@ -165,7 +180,7 @@ export function createTelegramChannel(config: TelegramConfig, log: (line: string
|
|
|
165
180
|
}
|
|
166
181
|
|
|
167
182
|
async function api<T>(method: string, body: Record<string, unknown>, timeoutMs = 30_000): Promise<T> {
|
|
168
|
-
const res = await
|
|
183
|
+
const res = await fetchTelegram(`${API}/bot${token}/${method}`, {
|
|
169
184
|
method: 'POST',
|
|
170
185
|
headers: { 'content-type': 'application/json' },
|
|
171
186
|
body: JSON.stringify(body),
|
|
@@ -203,7 +218,7 @@ export function createTelegramChannel(config: TelegramConfig, log: (line: string
|
|
|
203
218
|
|| file.file_path.split('/').some(part => !part || part === '.' || part === '..')
|
|
204
219
|
|| (file.file_size ?? 0) > MAX_CHANNEL_IMAGE_BYTES) throw new Error('图片文件无效或超过大小限制')
|
|
205
220
|
// The bot token must never follow a redirect or a caller-provided download URL.
|
|
206
|
-
const response = await
|
|
221
|
+
const response = await fetchTelegram(`${API}/file/bot${token}/${file.file_path}`, {
|
|
207
222
|
redirect: 'error', signal: timeoutSignal(30_000, lifecycle?.signal),
|
|
208
223
|
})
|
|
209
224
|
if (!response.ok || !response.body) throw new Error('图片下载失败')
|
|
@@ -360,6 +375,7 @@ export function createTelegramChannel(config: TelegramConfig, log: (line: string
|
|
|
360
375
|
await pollTask?.catch(() => undefined)
|
|
361
376
|
pollTask = undefined
|
|
362
377
|
lifecycle = undefined
|
|
378
|
+
if (dispatcher) await dispatcher.close().catch(() => dispatcher?.destroy())
|
|
363
379
|
if (persist) cursorFile.write({ offset })
|
|
364
380
|
},
|
|
365
381
|
canDeliverDeferred() { return !stopped },
|
|
@@ -373,7 +389,7 @@ export function createTelegramChannel(config: TelegramConfig, log: (line: string
|
|
|
373
389
|
if (route.threadId !== undefined) {
|
|
374
390
|
form.append('message_thread_id', String(route.threadId))
|
|
375
391
|
}
|
|
376
|
-
await fileRequest(`${API}/bot${token}/sendDocument`, { method: 'POST', body: form, signal: timeoutSignal(120_000, AbortSignal.any([...(signal ? [signal] : []), ...(lifecycle ? [lifecycle.signal] : [])])) })
|
|
392
|
+
await fileRequest(`${API}/bot${token}/sendDocument`, { method: 'POST', body: form, signal: timeoutSignal(120_000, AbortSignal.any([...(signal ? [signal] : []), ...(lifecycle ? [lifecycle.signal] : [])])) }, fetchTelegram)
|
|
377
393
|
},
|
|
378
394
|
/**
|
|
379
395
|
* 把会话标题写成话题名。只有论坛话题(话题群 / 私聊话题)有这一层级;
|
|
@@ -424,7 +440,7 @@ export function createTelegramChannel(config: TelegramConfig, log: (line: string
|
|
|
424
440
|
await fileRequest(`${API}/bot${token}/setMessageReaction`, {
|
|
425
441
|
method: 'POST', headers: { 'content-type': 'application/json' }, signal,
|
|
426
442
|
body: JSON.stringify({ chat_id: route.chatId, message_id: Number(message.messageId), reaction: [{ type: 'emoji', emoji }] }),
|
|
427
|
-
})
|
|
443
|
+
}, fetchTelegram)
|
|
428
444
|
return emoji
|
|
429
445
|
},
|
|
430
446
|
async removeStatusReaction(message, _reaction, signal) {
|
|
@@ -432,7 +448,7 @@ export function createTelegramChannel(config: TelegramConfig, log: (line: string
|
|
|
432
448
|
await fileRequest(`${API}/bot${token}/setMessageReaction`, {
|
|
433
449
|
method: 'POST', headers: { 'content-type': 'application/json' }, signal,
|
|
434
450
|
body: JSON.stringify({ chat_id: route.chatId, message_id: Number(message.messageId), reaction: [] }),
|
|
435
|
-
})
|
|
451
|
+
}, fetchTelegram)
|
|
436
452
|
},
|
|
437
453
|
async sendAction(chatId) {
|
|
438
454
|
const route = parseTelegramChatId(chatId)
|
|
@@ -513,7 +529,7 @@ export function createTelegramChannel(config: TelegramConfig, log: (line: string
|
|
|
513
529
|
setTopicEditHandler(h) { onTopicEdited = h },
|
|
514
530
|
async diagnose(signal) {
|
|
515
531
|
const query = async (method: string) => {
|
|
516
|
-
const data = await diagnosticJson(`${API}/bot${token}/${method}`, signal, {})
|
|
532
|
+
const data = await diagnosticJson(`${API}/bot${token}/${method}`, signal, {}, undefined, fetchTelegram)
|
|
517
533
|
if (data.ok === false) throw new DiagnosticError(data.error_code === 401 ? 'auth' : 'rejected', undefined, typeof data.error_code === 'number' ? data.error_code : undefined)
|
|
518
534
|
requireDiagnostic(data.ok === true && data.result && typeof data.result === 'object')
|
|
519
535
|
return data.result as Record<string, unknown>
|
package/src/index.ts
CHANGED
|
@@ -31,6 +31,8 @@ export interface PluginConfig {
|
|
|
31
31
|
agentPreset: string
|
|
32
32
|
mergeTimeoutSecs: number
|
|
33
33
|
topicNaming: TopicMode
|
|
34
|
+
updater?: boolean
|
|
35
|
+
onlineUpdate?: boolean
|
|
34
36
|
}
|
|
35
37
|
|
|
36
38
|
export const Config: Schema<PluginConfig> = Schema.object({
|
|
@@ -41,14 +43,12 @@ export const Config: Schema<PluginConfig> = Schema.object({
|
|
|
41
43
|
agentPreset: Schema.string().default('standard'),
|
|
42
44
|
mergeTimeoutSecs: Schema.number().default(5),
|
|
43
45
|
topicNaming: Schema.union(['once', 'follow', 'off']).default('once'),
|
|
46
|
+
updater: Schema.boolean(),
|
|
47
|
+
onlineUpdate: Schema.boolean(),
|
|
44
48
|
})
|
|
45
49
|
|
|
46
50
|
export function apply(ctx: Context, config: PluginConfig): void {
|
|
47
|
-
|
|
48
|
-
endpoint: '/api/michengai/dsh-im-connect/update',
|
|
49
|
-
packageName: '@michengai/dsh-im-connect',
|
|
50
|
-
manifestUrl: new URL('../package.json', import.meta.url),
|
|
51
|
-
}), 'im-connect.plugin-updater')
|
|
51
|
+
const hostUpdateDisabled = config.updater === false || config.onlineUpdate === false
|
|
52
52
|
const permissionPresets = (ctx as Context & { permissionPresets: { defaultPreset: string } }).permissionPresets
|
|
53
53
|
const stateDir = config.stateDir !== ''
|
|
54
54
|
? config.stateDir
|
|
@@ -73,8 +73,14 @@ export function apply(ctx: Context, config: PluginConfig): void {
|
|
|
73
73
|
}
|
|
74
74
|
|
|
75
75
|
const applyStarted = Date.now()
|
|
76
|
-
const manager = new ChannelManager({ ctx, stateDir, log, engineConfig })
|
|
76
|
+
const manager = new ChannelManager({ ctx, stateDir, log, engineConfig, hostUpdateDisabled })
|
|
77
77
|
log(`[boot] ChannelManager 构造 ${Date.now() - applyStarted}ms`)
|
|
78
|
+
ctx.effect(() => registerPluginUpdater(ctx, {
|
|
79
|
+
endpoint: '/api/michengai/dsh-im-connect/update',
|
|
80
|
+
packageName: '@michengai/dsh-im-connect',
|
|
81
|
+
manifestUrl: new URL('../package.json', import.meta.url),
|
|
82
|
+
isEnabled: async () => !hostUpdateDisabled && manager.isUpdateEnabled(),
|
|
83
|
+
}), 'im-connect.plugin-updater')
|
|
78
84
|
ctx.effect(() => {
|
|
79
85
|
manager.registerApi(ctx)
|
|
80
86
|
// 卸载或初始化失败后不再恢复会话;保留一个完整异常链,避免后台拒绝终止宿主。
|