@goodandready/dsh-messenger-gateway 0.4.16 → 0.4.17
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.md +1 -1
- package/README.ru.md +1 -1
- package/lib/adapters/telegram-inbound.js +7 -3
- package/lib/adapters/telegram.js +38 -23
- package/lib/config.js +17 -9
- package/lib/gateway.js +27 -3
- package/lib/index.js +41 -1
- package/lib/proxy.js +639 -33
- package/lib/secret-guard.js +52 -0
- package/lib/telegram-errors.js +0 -0
- package/lib/telegram-format.js +67 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -142,7 +142,7 @@ In addition to Telegram, outbound messages can be dispatched to Discord and Slac
|
|
|
142
142
|
- `voiceMode`: `mirror` / `always` / `off` — when to speak replies (also `/voice`)
|
|
143
143
|
- `tts.enabled` / `tts.maxChars` — TTS gate and length cap
|
|
144
144
|
- `notifyBridge` — forward non-messenger web session events to a home
|
|
145
|
-
- `telegram.proxyUrl`: optional HTTP, HTTPS
|
|
145
|
+
- `telegram.proxyUrl`: optional HTTP, HTTPS or SOCKS5 proxy URL (`socks5://user:pass@127.0.0.1:1080`, `http://127.0.0.1:8080`); `socks://` and `socks5h://` are aliases. Leave it empty to use `TELEGRAM_PROXY` / `DSH_MESSENGER_TELEGRAM_PROXY` / `HTTPS_PROXY` / `ALL_PROXY` from the environment, use `off`/`none`/`direct` to disable proxying entirely, and `NO_PROXY`/`no_proxy` rules are honoured. The tunnel is implemented with `node:net`/`node:tls` (no extra dependencies) and keeps normal TLS certificate verification for `api.telegram.org`
|
|
146
146
|
- `telegram.apiRoot`: optional custom Telegram Bot API base URL (default: `https://api.telegram.org`), for local Bot API servers or reverse proxies
|
|
147
147
|
- Bot token is a DSH secret field — never commit it
|
|
148
148
|
|
package/README.ru.md
CHANGED
|
@@ -106,7 +106,7 @@ graph LR
|
|
|
106
106
|
* `/help` — список возможностей.
|
|
107
107
|
|
|
108
108
|
### 7. 🌐 Поддержка прокси и кастомного Bot API (`proxy.js`)
|
|
109
|
-
* Маршрутизация запросов к Telegram через прокси: HTTP, HTTPS, SOCKS5 и SOCKS5h (`telegram.proxyUrl`);
|
|
109
|
+
* Маршрутизация запросов к Telegram через прокси: HTTP, HTTPS, SOCKS5 и SOCKS5h (`telegram.proxyUrl`, поддерживаются логин/пароль, `socks://` и `socks5h://` — синонимы). Пустое поле → берётся из окружения (`TELEGRAM_PROXY`, `DSH_MESSENGER_TELEGRAM_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`); `off`/`none`/`direct` отключают прокси, правила `NO_PROXY` соблюдаются. Туннель реализован на `node:net`/`node:tls` без внешних зависимостей, TLS-сертификат `api.telegram.org` проверяется как обычно;
|
|
110
110
|
* Поддержка пользовательского базового адреса API (`telegram.apiRoot`) для локальных серверов Telegram Bot API или обратных прокси (reverse proxy).
|
|
111
111
|
|
|
112
112
|
---
|
|
@@ -100,8 +100,9 @@ export async function extractTelegramInboundMedia(adapter, msg, initialText, max
|
|
|
100
100
|
}
|
|
101
101
|
|
|
102
102
|
export async function probeTelegramHealth(adapter, timeoutMs = 10000) {
|
|
103
|
+
const proxyLabel = adapter?.proxy?.active ? (adapter.proxy.label || '') : ''
|
|
103
104
|
if (!adapter.token) {
|
|
104
|
-
return { ok: false, error: 'Telegram bot token is empty' }
|
|
105
|
+
return { ok: false, error: 'Telegram bot token is empty', proxy: proxyLabel }
|
|
105
106
|
}
|
|
106
107
|
const start = Date.now()
|
|
107
108
|
try {
|
|
@@ -112,14 +113,15 @@ export async function probeTelegramHealth(adapter, timeoutMs = 10000) {
|
|
|
112
113
|
body: JSON.stringify({}),
|
|
113
114
|
signal: AbortSignal.timeout(Math.max(1000, Number(timeoutMs) || 10000)),
|
|
114
115
|
}
|
|
115
|
-
|
|
116
|
-
const res = await
|
|
116
|
+
const apiFetch = typeof adapter.apiFetch === 'function' ? adapter.apiFetch : fetch
|
|
117
|
+
const res = await apiFetch(`${apiRoot}/bot${adapter.token}/getMe`, fetchOpts)
|
|
117
118
|
const latencyMs = Date.now() - start
|
|
118
119
|
const json = await res.json().catch(() => ({}))
|
|
119
120
|
if (!res.ok || json.ok === false) {
|
|
120
121
|
return {
|
|
121
122
|
ok: false,
|
|
122
123
|
latencyMs,
|
|
124
|
+
proxy: proxyLabel,
|
|
123
125
|
error: json.description || `HTTP ${res.status}`,
|
|
124
126
|
}
|
|
125
127
|
}
|
|
@@ -129,6 +131,7 @@ export async function probeTelegramHealth(adapter, timeoutMs = 10000) {
|
|
|
129
131
|
return {
|
|
130
132
|
ok: true,
|
|
131
133
|
latencyMs,
|
|
134
|
+
proxy: proxyLabel,
|
|
132
135
|
botId: adapter.botId,
|
|
133
136
|
botUsername: adapter.botUsername,
|
|
134
137
|
firstName: me.first_name || '',
|
|
@@ -137,6 +140,7 @@ export async function probeTelegramHealth(adapter, timeoutMs = 10000) {
|
|
|
137
140
|
return {
|
|
138
141
|
ok: false,
|
|
139
142
|
latencyMs: Date.now() - start,
|
|
143
|
+
proxy: proxyLabel,
|
|
140
144
|
error: err instanceof Error ? err.message : String(err),
|
|
141
145
|
}
|
|
142
146
|
}
|
package/lib/adapters/telegram.js
CHANGED
|
@@ -13,10 +13,25 @@ import {
|
|
|
13
13
|
} from '../groups.js'
|
|
14
14
|
import { isResendSafeNetworkError, isPollingConflict, isTopicGoneError, computePollBackoffMs } from '../telegram-errors.js'
|
|
15
15
|
import { extractTelegramInboundMedia, probeTelegramHealth } from './telegram-inbound.js'
|
|
16
|
-
import {
|
|
16
|
+
import { createProxiedFetch, describeProxy, normalizeApiRoot } from '../proxy.js'
|
|
17
17
|
|
|
18
18
|
const TELEGRAM_MAX = 4096
|
|
19
19
|
|
|
20
|
+
// Telegram повторно отдаёт апдейты, которые не были подтверждены более высоким
|
|
21
|
+
// offset (перезапуск адаптера, конфликт двух getUpdates, повторная доставка).
|
|
22
|
+
// Держим id обработанных апдейтов на уровне модуля — тогда даже при нескольких
|
|
23
|
+
// циклах опроса команда не будет выполнена дважды.
|
|
24
|
+
const PROCESSED_UPDATE_LIMIT = 1000
|
|
25
|
+
const processedUpdateIds = new Set()
|
|
26
|
+
|
|
27
|
+
function rememberUpdate(id) {
|
|
28
|
+
processedUpdateIds.add(id)
|
|
29
|
+
if (processedUpdateIds.size > PROCESSED_UPDATE_LIMIT) {
|
|
30
|
+
const oldest = processedUpdateIds.values().next().value
|
|
31
|
+
processedUpdateIds.delete(oldest)
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
20
35
|
import { buildQuickActionsKeyboard, REMOVE_REPLY_KEYBOARD } from '../commands.js'
|
|
21
36
|
export { buildQuickActionsKeyboard, REMOVE_REPLY_KEYBOARD }
|
|
22
37
|
|
|
@@ -57,15 +72,17 @@ export class TelegramAdapter {
|
|
|
57
72
|
this.botUsername = ''
|
|
58
73
|
this.apiRoot = normalizeApiRoot(opts.apiRoot)
|
|
59
74
|
this.proxyUrl = String(opts.proxyUrl || '').trim()
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
this.
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
this.
|
|
75
|
+
// Прокси для Bot API: http(s)-CONNECT и SOCKS5 (в т.ч. с логином/паролем),
|
|
76
|
+
// без внешних зависимостей. Пустая настройка → значение из окружения
|
|
77
|
+
// (TELEGRAM_PROXY / DSH_MESSENGER_TELEGRAM_PROXY / HTTPS_PROXY / ALL_PROXY).
|
|
78
|
+
this.proxy = describeProxy(this.proxyUrl)
|
|
79
|
+
try {
|
|
80
|
+
this.apiFetch = createProxiedFetch(this.proxyUrl, { logger: this.logger }) || fetch
|
|
81
|
+
if (this.proxy.active) this.logger?.info?.(`dsh-messenger-gateway: telegram via proxy ${this.proxy.label}`)
|
|
82
|
+
} catch (err) {
|
|
83
|
+
this.proxy = { ...this.proxy, active: false, error: err.message }
|
|
84
|
+
this.apiFetch = fetch
|
|
85
|
+
this.logger?.error?.(`dsh-messenger-gateway: telegram proxy is invalid, using direct connection: ${err.message}`)
|
|
69
86
|
}
|
|
70
87
|
}
|
|
71
88
|
|
|
@@ -82,8 +99,7 @@ export class TelegramAdapter {
|
|
|
82
99
|
keepalive: true,
|
|
83
100
|
signal: AbortSignal.timeout(timeoutMs),
|
|
84
101
|
}
|
|
85
|
-
|
|
86
|
-
const res = await fetch(`${this.apiRoot}/bot${this.token}/${method}`, fetchOpts)
|
|
102
|
+
const res = await this.apiFetch(`${this.apiRoot}/bot${this.token}/${method}`, fetchOpts)
|
|
87
103
|
const json = await res.json().catch(() => ({}))
|
|
88
104
|
if (!res.ok || json.ok === false) throw new Error(`telegram ${method}: ${json.description || res.status}`)
|
|
89
105
|
return json.result
|
|
@@ -97,8 +113,7 @@ export class TelegramAdapter {
|
|
|
97
113
|
keepalive: true,
|
|
98
114
|
signal: AbortSignal.timeout(timeoutMs),
|
|
99
115
|
}
|
|
100
|
-
|
|
101
|
-
const res = await fetch(`${this.apiRoot}/bot${this.token}/${method}`, fetchOpts)
|
|
116
|
+
const res = await this.apiFetch(`${this.apiRoot}/bot${this.token}/${method}`, fetchOpts)
|
|
102
117
|
const json = await res.json().catch(() => ({}))
|
|
103
118
|
if (!res.ok || json.ok === false) throw new Error(`telegram ${method}: ${json.description || res.status}`)
|
|
104
119
|
return json.result
|
|
@@ -130,8 +145,7 @@ export class TelegramAdapter {
|
|
|
130
145
|
keepalive: true,
|
|
131
146
|
signal: AbortSignal.timeout(timeoutMs),
|
|
132
147
|
}
|
|
133
|
-
|
|
134
|
-
const res = await fetch(`${this.apiRoot}/file/bot${this.token}/${filePath}`, fetchOpts)
|
|
148
|
+
const res = await this.apiFetch(`${this.apiRoot}/file/bot${this.token}/${filePath}`, fetchOpts)
|
|
135
149
|
if (!res.ok) throw new Error(`telegram download HTTP ${res.status}`)
|
|
136
150
|
return new Uint8Array(await res.arrayBuffer())
|
|
137
151
|
}
|
|
@@ -190,6 +204,7 @@ export class TelegramAdapter {
|
|
|
190
204
|
} catch (err) {
|
|
191
205
|
this.logger?.warn?.(`dsh-messenger-gateway: telegram setMyCommands: ${err.message}`)
|
|
192
206
|
}
|
|
207
|
+
if (this.stopped) return
|
|
193
208
|
if (this.transport === 'webhook') {
|
|
194
209
|
if (!this.webhookUrl) throw new Error('telegram webhookUrl is required for webhook transport')
|
|
195
210
|
if (!this.webhookSecret) throw new Error('telegram webhookSecret is required for webhook transport')
|
|
@@ -213,6 +228,8 @@ export class TelegramAdapter {
|
|
|
213
228
|
} catch (err) {
|
|
214
229
|
this.logger?.debug?.('telegram deleteWebhook failed (safe to ignore):', err?.message || err)
|
|
215
230
|
}
|
|
231
|
+
// start() мог быть прерван stop() за время сетевых вызовов выше.
|
|
232
|
+
if (this.stopped) return
|
|
216
233
|
this.poll()
|
|
217
234
|
}
|
|
218
235
|
|
|
@@ -222,13 +239,6 @@ export class TelegramAdapter {
|
|
|
222
239
|
if (this.statusIndicator) this.setStatusIndicator(this.statusOffline).catch((err) => {
|
|
223
240
|
this.logger?.debug?.('telegram setStatusIndicator offline failed:', err?.message || err)
|
|
224
241
|
})
|
|
225
|
-
if (this.ownDispatcher) {
|
|
226
|
-
try {
|
|
227
|
-
this.ownDispatcher.close?.().catch?.(() => {})
|
|
228
|
-
} catch (err) {
|
|
229
|
-
this.logger?.debug?.('telegram dispatcher close error:', err?.message || err)
|
|
230
|
-
}
|
|
231
|
-
}
|
|
232
242
|
}
|
|
233
243
|
|
|
234
244
|
schedulePoll(delayMs) {
|
|
@@ -251,6 +261,11 @@ export class TelegramAdapter {
|
|
|
251
261
|
this.pollErrorCount = 0
|
|
252
262
|
for (const update of updates || []) {
|
|
253
263
|
this.offset = Math.max(this.offset, update.update_id + 1)
|
|
264
|
+
if (processedUpdateIds.has(update.update_id)) {
|
|
265
|
+
this.logger?.debug?.(`telegram: skipping already handled update ${update.update_id}`)
|
|
266
|
+
continue
|
|
267
|
+
}
|
|
268
|
+
rememberUpdate(update.update_id)
|
|
254
269
|
await this.dispatchUpdate(update)
|
|
255
270
|
}
|
|
256
271
|
} catch (e) {
|
package/lib/config.js
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
import z from '@deepseek-ai/schemastery'
|
|
2
2
|
|
|
3
|
+
// DSH persists plugin settings (into the profile patch) only for schema paths it
|
|
4
|
+
// can treat as live-editable: every write goes through `volatileForm(schema)` in
|
|
5
|
+
// @deepseek-ai/dsh-settings and is rejected with
|
|
6
|
+
// `Config field "<path>" is not volatile` otherwise. Only `enabled` and
|
|
7
|
+
// `internalBaseURL` were volatile, so the settings card could not save anything
|
|
8
|
+
// else. The configurable sections are declared volatile as a whole — the card
|
|
9
|
+
// edits them as live values and the gateway restarts its adapters on change.
|
|
10
|
+
|
|
3
11
|
const HomeEntry = z.object({
|
|
4
12
|
name: z.string().default('default'),
|
|
5
13
|
chatId: z.union([z.number(), z.string()]),
|
|
@@ -9,7 +17,7 @@ const HomeEntry = z.object({
|
|
|
9
17
|
export const PluginConfig = z.object({
|
|
10
18
|
enabled: z.boolean().volatile().default(true),
|
|
11
19
|
internalBaseURL: z.string().volatile().default('').description('Internal base URL for host services; if omitted, resolved dynamically from webServer port or falls back to http://127.0.0.1:3080'),
|
|
12
|
-
defaultLocale: z.union([z.const('en'), z.const('zh')]).default('en').description('Default language for bot messages and notifications (en, zh)'),
|
|
20
|
+
defaultLocale: z.union([z.const('en'), z.const('zh')]).volatile().default('en').description('Default language for bot messages and notifications (en, zh)'),
|
|
13
21
|
telegram: z.object({
|
|
14
22
|
enabled: z.boolean().default(false),
|
|
15
23
|
botToken: z.string().role('secret').default(''),
|
|
@@ -39,7 +47,7 @@ export const PluginConfig = z.object({
|
|
|
39
47
|
webhookUrl: z.string().default(''),
|
|
40
48
|
webhookSecret: z.string().role('secret').default(''),
|
|
41
49
|
webhookPath: z.string().default('/dsh-messenger-gateway/telegram/webhook'),
|
|
42
|
-
proxyUrl: z.string().default('').description('Proxy
|
|
50
|
+
proxyUrl: z.string().default('').description('Proxy for Telegram Bot API calls: http(s)://[user:pass@]host:port or socks5://[user:pass@]host:port (socks5h/socks are aliases). Empty = take from the environment (TELEGRAM_PROXY/HTTPS_PROXY/ALL_PROXY); off/none/direct = never use a proxy'),
|
|
43
51
|
apiRoot: z.string().default('').description('Custom Telegram Bot API root URL (default: https://api.telegram.org)'),
|
|
44
52
|
voiceMode: z.union([z.const('mirror'), z.const('always'), z.const('off')]).default('mirror')
|
|
45
53
|
.description('mirror: TTS when inbound was voice; always/off override (per-user /voice wins)'),
|
|
@@ -64,32 +72,32 @@ export const PluginConfig = z.object({
|
|
|
64
72
|
}).default({ enabled: false }),
|
|
65
73
|
forumMirrorChatId: z.union([z.number(), z.string()]).default(''),
|
|
66
74
|
forumMirrorEnabled: z.boolean().default(false),
|
|
67
|
-
}),
|
|
75
|
+
}).volatile(),
|
|
68
76
|
discord: z.object({
|
|
69
77
|
enabled: z.boolean().default(false),
|
|
70
78
|
botToken: z.string().role('secret').default(''),
|
|
71
79
|
webhookUrl: z.string().default(''),
|
|
72
|
-
}).default({ enabled: false }),
|
|
80
|
+
}).default({ enabled: false }).volatile(),
|
|
73
81
|
slack: z.object({
|
|
74
82
|
enabled: z.boolean().default(false),
|
|
75
83
|
botToken: z.string().role('secret').default(''),
|
|
76
84
|
webhookUrl: z.string().default(''),
|
|
77
|
-
}).default({ enabled: false }),
|
|
85
|
+
}).default({ enabled: false }).volatile(),
|
|
78
86
|
webhooks: z.object({
|
|
79
87
|
enabled: z.boolean().default(true),
|
|
80
88
|
secret: z.string().role('secret').default(''),
|
|
81
|
-
}).default({ enabled: true }),
|
|
89
|
+
}).default({ enabled: true }).volatile(),
|
|
82
90
|
media: z.object({
|
|
83
91
|
cacheDir: z.string().default(''),
|
|
84
92
|
maxDocBytes: z.number().default(20 * 1024 * 1024),
|
|
85
93
|
maxTextInjectBytes: z.number().default(100 * 1024),
|
|
86
94
|
maxImageBytes: z.number().default(20 * 1024 * 1024),
|
|
87
|
-
}),
|
|
95
|
+
}).volatile(),
|
|
88
96
|
tts: z.object({
|
|
89
97
|
enabled: z.boolean().default(false),
|
|
90
98
|
maxChars: z.number().default(4000),
|
|
91
99
|
voiceSummary: z.boolean().default(false).description('Speak concise TL;DR summary while full text is sent to chat'),
|
|
92
|
-
}),
|
|
100
|
+
}).volatile(),
|
|
93
101
|
agent: z.object({
|
|
94
102
|
provider: z.string().default(''),
|
|
95
103
|
model: z.string().default(''),
|
|
@@ -101,7 +109,7 @@ export const PluginConfig = z.object({
|
|
|
101
109
|
photoOnlyMode: z.union([z.const('prompt'), z.const('run')]).default('prompt'),
|
|
102
110
|
sessionScope: z.union([z.const('chat'), z.const('user')]).default('user')
|
|
103
111
|
.description('In groups: user = per-user session; chat = shared session for the chat/topic'),
|
|
104
|
-
}),
|
|
112
|
+
}).volatile(),
|
|
105
113
|
})
|
|
106
114
|
|
|
107
115
|
export const Config = PluginConfig
|
package/lib/gateway.js
CHANGED
|
@@ -44,6 +44,8 @@ export class Gateway {
|
|
|
44
44
|
this.pendingAsks = new Map()
|
|
45
45
|
this.adapters = new Map()
|
|
46
46
|
this.adapterList = []
|
|
47
|
+
// true после stop(): start() обязан прекратить работу, если его обогнали.
|
|
48
|
+
this.stopped = false
|
|
47
49
|
this.disposeListener = undefined
|
|
48
50
|
this.idleTimer = undefined
|
|
49
51
|
this.callbackIndex = new Map()
|
|
@@ -218,6 +220,7 @@ export class Gateway {
|
|
|
218
220
|
}
|
|
219
221
|
|
|
220
222
|
async start() {
|
|
223
|
+
this.stopped = false
|
|
221
224
|
const onHost = (session, event) => this.handleHostEvent(session, event)
|
|
222
225
|
const unsubs = [
|
|
223
226
|
this.ctx.on('session/event', onHost),
|
|
@@ -241,22 +244,41 @@ export class Gateway {
|
|
|
241
244
|
isUserAllowed: (id) => this.isUserAllowed(id),
|
|
242
245
|
logger: this.ctx.logger,
|
|
243
246
|
})
|
|
247
|
+
const dropAdapter = (adapter) => {
|
|
248
|
+
this.adapters.delete(adapter.name)
|
|
249
|
+
this.adapterList = this.adapterList.filter((item) => item !== adapter)
|
|
250
|
+
if (this.tgAdapter === adapter) this.tgAdapter = undefined
|
|
251
|
+
}
|
|
244
252
|
for (const adapter of adapters) {
|
|
253
|
+
// Регистрируем адаптер ДО `await adapter.start()`: старт адаптера — это
|
|
254
|
+
// сетевые вызовы (getMe/setMyCommands/deleteWebhook), и если за это время
|
|
255
|
+
// придёт stop() (перезагрузка настроек вызывает sync() -> stop()+start()),
|
|
256
|
+
// незарегистрированный адаптер не будет остановлен, а его цикл getUpdates
|
|
257
|
+
// останется жить вечно. Несколько таких «утекших» поллеров забирают одни и
|
|
258
|
+
// те же апдейты у Telegram — бот отвечает на команду по 2–N раз.
|
|
259
|
+
this.adapterList.push(adapter)
|
|
260
|
+
this.adapters.set(adapter.name, adapter)
|
|
261
|
+
if (adapter.name === 'telegram') this.tgAdapter = adapter
|
|
245
262
|
try {
|
|
246
263
|
await adapter.start()
|
|
247
|
-
this.
|
|
248
|
-
|
|
249
|
-
|
|
264
|
+
if (this.stopped) {
|
|
265
|
+
try { adapter.stop() } catch (e) { this.logger?.debug?.('adapter stop error:', e?.message || e) }
|
|
266
|
+
dropAdapter(adapter)
|
|
267
|
+
return
|
|
268
|
+
}
|
|
250
269
|
this.ctx.logger?.info?.(`dsh-messenger-gateway: ${adapter.name} started`)
|
|
251
270
|
} catch (err) {
|
|
271
|
+
dropAdapter(adapter)
|
|
252
272
|
this.ctx.logger?.warn?.(`dsh-messenger-gateway: ${adapter.name}: ${err.message}`)
|
|
253
273
|
}
|
|
254
274
|
}
|
|
275
|
+
if (this.stopped) return
|
|
255
276
|
if (this.adapters.has('telegram')) {
|
|
256
277
|
await this.syncTelegramCommands().catch((err) => {
|
|
257
278
|
this.ctx.logger?.warn?.(`Initial syncTelegramCommands: ${err?.message || err}`)
|
|
258
279
|
})
|
|
259
280
|
}
|
|
281
|
+
if (this.stopped) return
|
|
260
282
|
const rawIdle = Number(this.config.agent?.idleTimeoutMs)
|
|
261
283
|
const idleMs = Number.isFinite(rawIdle) && rawIdle > 0 ? rawIdle : 86_400_000
|
|
262
284
|
this.idleTimer = setInterval(() => this.reapIdle(), Math.min(idleMs, 60_000))
|
|
@@ -265,12 +287,14 @@ export class Gateway {
|
|
|
265
287
|
}
|
|
266
288
|
|
|
267
289
|
stop() {
|
|
290
|
+
this.stopped = true
|
|
268
291
|
if (this.scheduler) this.scheduler.stop()
|
|
269
292
|
if (this.disposeListener) this.disposeListener()
|
|
270
293
|
if (this.idleTimer) clearInterval(this.idleTimer)
|
|
271
294
|
for (const a of this.adapterList) { try { a.stop() } catch (e) { this.logger?.debug?.('adapter stop error:', e?.message || e) } }
|
|
272
295
|
this.adapterList = []
|
|
273
296
|
this.adapters.clear()
|
|
297
|
+
this.tgAdapter = undefined
|
|
274
298
|
for (const chat of this.chats.values()) chat.dispose().catch((e) => this.logger?.debug?.('dispose error:', e?.message || e))
|
|
275
299
|
this.chats.clear()
|
|
276
300
|
this.sessionToChat.clear()
|
package/lib/index.js
CHANGED
|
@@ -12,6 +12,8 @@ import {
|
|
|
12
12
|
import { listHomes } from './homes.js'
|
|
13
13
|
export { plainConfig } from './config.js'
|
|
14
14
|
import { Config, plainConfig, resolveInternalBaseUrl } from './config.js'
|
|
15
|
+
import { describeProxy } from './proxy.js'
|
|
16
|
+
import { readSecrets, restoreSecrets } from './secret-guard.js'
|
|
15
17
|
import { setupSettings } from './settings-bridge.js'
|
|
16
18
|
|
|
17
19
|
export const name = '@goodandready/dsh-messenger-gateway'
|
|
@@ -33,6 +35,7 @@ function resolveConfig(raw) {
|
|
|
33
35
|
|
|
34
36
|
function publicConfig(cfg, gw, ctx) {
|
|
35
37
|
const internalBaseURL = gw?.baseUrl?.() || resolveInternalBaseUrl(cfg, ctx)
|
|
38
|
+
const proxy = describeProxy(cfg.telegram?.proxyUrl)
|
|
36
39
|
return {
|
|
37
40
|
enabled: cfg.enabled,
|
|
38
41
|
internalBaseURL,
|
|
@@ -60,6 +63,10 @@ function publicConfig(cfg, gw, ctx) {
|
|
|
60
63
|
botTokenConfigured: Boolean(String(cfg.telegram.botToken || '').trim()),
|
|
61
64
|
proxyUrl: cfg.telegram.proxyUrl || '',
|
|
62
65
|
apiRoot: cfg.telegram.apiRoot || '',
|
|
66
|
+
proxyActive: Boolean(proxy.active),
|
|
67
|
+
proxyLabel: proxy.label || '',
|
|
68
|
+
proxySource: proxy.source || '',
|
|
69
|
+
proxyError: proxy.error || '',
|
|
63
70
|
voiceMode: cfg.telegram.voiceMode,
|
|
64
71
|
quickActions: cfg.telegram.quickActions !== false,
|
|
65
72
|
artifactPreviews: cfg.telegram.artifactPreviews !== false,
|
|
@@ -152,6 +159,30 @@ export function apply(ctx, config) {
|
|
|
152
159
|
const turnStarts = new Map()
|
|
153
160
|
const getWebServer = () => ctx.get?.('webServer') || ctx.webServer
|
|
154
161
|
|
|
162
|
+
// Секреты (botToken и т. п.) не отдаются браузеру, а карточка сохраняет секции
|
|
163
|
+
// целиком — без этой защиты каждое сохранение (например, смена прокси) затирало
|
|
164
|
+
// бы токен пустым значением. См. lib/secret-guard.js.
|
|
165
|
+
let knownSecrets
|
|
166
|
+
const guardSecrets = async (cfg) => {
|
|
167
|
+
const current = readSecrets(cfg)
|
|
168
|
+
if (knownSecrets === undefined) {
|
|
169
|
+
knownSecrets = current
|
|
170
|
+
return
|
|
171
|
+
}
|
|
172
|
+
const { config: fixed, restored } = restoreSecrets(knownSecrets, cfg)
|
|
173
|
+
if (!restored.length) {
|
|
174
|
+
knownSecrets = current
|
|
175
|
+
return
|
|
176
|
+
}
|
|
177
|
+
knownSecrets = readSecrets(fixed)
|
|
178
|
+
ctx.logger?.warn?.(`dsh-messenger-gateway: settings write cleared secret fields (${restored.join(', ')}); restoring the previous values`)
|
|
179
|
+
try {
|
|
180
|
+
await settingsApi.replace(Config(fixed))
|
|
181
|
+
} catch (err) {
|
|
182
|
+
ctx.logger?.warn?.(`dsh-messenger-gateway: could not restore secret fields: ${err?.message || err}`)
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
155
186
|
let webhookRouteDispose = null
|
|
156
187
|
let currentWebhookPath = ''
|
|
157
188
|
|
|
@@ -201,10 +232,19 @@ export function apply(ctx, config) {
|
|
|
201
232
|
})
|
|
202
233
|
}
|
|
203
234
|
|
|
235
|
+
let lastSyncSignature
|
|
204
236
|
const sync = () => {
|
|
205
237
|
syncWebhookRoute()
|
|
206
|
-
if (gateway) { gateway.stop(); gateway = undefined }
|
|
207
238
|
const effective = source()
|
|
239
|
+
// DSH sends several events for one settings write, and restarting the gateway
|
|
240
|
+
// drops live sessions and resets the Telegram polling offset. Restart only
|
|
241
|
+
// when the resolved config actually changed.
|
|
242
|
+
let signature
|
|
243
|
+
try { signature = JSON.stringify(effective) } catch { signature = undefined }
|
|
244
|
+
if (gateway && signature !== undefined && signature === lastSyncSignature) return
|
|
245
|
+
lastSyncSignature = signature
|
|
246
|
+
guardSecrets(effective).catch((err) => ctx.logger?.warn?.(`dsh-messenger-gateway: secret guard failed: ${err?.message || err}`))
|
|
247
|
+
if (gateway) { gateway.stop(); gateway = undefined }
|
|
208
248
|
if (effective.enabled === false) return
|
|
209
249
|
gateway = new Gateway(ctx, effective, {
|
|
210
250
|
persistAllowedUserIds: async (ids) => {
|
package/lib/proxy.js
CHANGED
|
@@ -1,24 +1,604 @@
|
|
|
1
|
-
|
|
1
|
+
// Outbound proxy support for Telegram Bot API calls (HTTP/HTTPS CONNECT and SOCKS5).
|
|
2
|
+
//
|
|
3
|
+
// Telegram is blocked in some networks, so the gateway needs to reach
|
|
4
|
+
// api.telegram.org through a proxy. This module is dependency-free: it tunnels a
|
|
5
|
+
// raw TCP socket to the target through the configured proxy and then lets the
|
|
6
|
+
// regular node:https stack (with normal certificate verification) talk over it
|
|
7
|
+
// via a minimal custom agent.
|
|
8
|
+
//
|
|
9
|
+
// Supported proxy URLs:
|
|
10
|
+
// http://[user:pass@]host:port
|
|
11
|
+
// https://[user:pass@]host:port
|
|
12
|
+
// socks5://[user:pass@]host:port (socks5h:// and socks:// are aliases)
|
|
13
|
+
//
|
|
14
|
+
// Configuration precedence (first non-empty wins): plugin setting -> environment
|
|
15
|
+
// (DSH_MESSENGER_TELEGRAM_PROXY, TELEGRAM_PROXY, HTTPS_PROXY, ALL_PROXY, HTTP_PROXY).
|
|
16
|
+
// Setting the value to off/none/direct disables the setting and the environment.
|
|
2
17
|
|
|
3
|
-
|
|
18
|
+
import http from 'node:http'
|
|
19
|
+
import https from 'node:https'
|
|
20
|
+
import net from 'node:net'
|
|
21
|
+
import tls from 'node:tls'
|
|
4
22
|
|
|
5
|
-
const
|
|
23
|
+
const ENV_KEYS = [
|
|
24
|
+
'DSH_MESSENGER_TELEGRAM_PROXY',
|
|
25
|
+
'TELEGRAM_PROXY',
|
|
26
|
+
'HTTPS_PROXY',
|
|
27
|
+
'https_proxy',
|
|
28
|
+
'ALL_PROXY',
|
|
29
|
+
'all_proxy',
|
|
30
|
+
'HTTP_PROXY',
|
|
31
|
+
'http_proxy',
|
|
32
|
+
]
|
|
6
33
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
34
|
+
const DISABLED_VALUES = new Set(['off', 'none', 'no', 'direct', 'false', '0', '-'])
|
|
35
|
+
|
|
36
|
+
const PROXY_KINDS = {
|
|
37
|
+
'http:': { kind: 'http', protocol: 'http', defaultPort: 80 },
|
|
38
|
+
'https:': { kind: 'https', protocol: 'https', defaultPort: 443 },
|
|
39
|
+
'socks:': { kind: 'socks5', protocol: 'socks5', defaultPort: 1080 },
|
|
40
|
+
'socks5:': { kind: 'socks5', protocol: 'socks5', defaultPort: 1080 },
|
|
41
|
+
'socks5h:': { kind: 'socks5', protocol: 'socks5', defaultPort: 1080 },
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function decodePart(value) {
|
|
45
|
+
if (!value) return ''
|
|
11
46
|
try {
|
|
12
|
-
|
|
47
|
+
return decodeURIComponent(value)
|
|
48
|
+
} catch {
|
|
49
|
+
return value
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function bareHost(hostname) {
|
|
54
|
+
return String(hostname || '').replace(/^\[|\]$/g, '')
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Parse a proxy URL into a spec object; returns null when no proxy is configured. */
|
|
58
|
+
export function parseProxySpec(raw) {
|
|
59
|
+
const value = String(raw ?? '').trim()
|
|
60
|
+
if (!value) return null
|
|
61
|
+
if (DISABLED_VALUES.has(value.toLowerCase())) return null
|
|
62
|
+
const candidate = /^[a-z][a-z0-9+.-]*:\/\//i.test(value) ? value : `http://${value}`
|
|
63
|
+
let url
|
|
64
|
+
try {
|
|
65
|
+
url = new URL(candidate)
|
|
66
|
+
} catch {
|
|
67
|
+
throw new Error(`invalid proxy URL: ${value}`)
|
|
68
|
+
}
|
|
69
|
+
const entry = PROXY_KINDS[url.protocol.toLowerCase()]
|
|
70
|
+
if (!entry) {
|
|
71
|
+
throw new Error(`unsupported proxy protocol "${url.protocol}" (use http://, https:// or socks5://)`)
|
|
72
|
+
}
|
|
73
|
+
const host = bareHost(url.hostname)
|
|
74
|
+
if (!host) throw new Error(`invalid proxy URL: ${value}`)
|
|
75
|
+
const spec = {
|
|
76
|
+
kind: entry.kind,
|
|
77
|
+
protocol: entry.protocol,
|
|
78
|
+
host,
|
|
79
|
+
port: Number(url.port) || entry.defaultPort,
|
|
80
|
+
username: decodePart(url.username),
|
|
81
|
+
password: decodePart(url.password),
|
|
82
|
+
raw: value,
|
|
83
|
+
}
|
|
84
|
+
spec.label = maskProxyUrl(spec)
|
|
85
|
+
return spec
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Credential-safe proxy label for logs and the settings UI. */
|
|
89
|
+
export function maskProxyUrl(specOrUrl) {
|
|
90
|
+
const spec = typeof specOrUrl === 'string' ? parseProxySpec(specOrUrl) : specOrUrl
|
|
91
|
+
if (!spec) return ''
|
|
92
|
+
const auth = (spec.username || spec.password) ? `${encodeURIComponent(spec.username)}:***@` : ''
|
|
93
|
+
return `${spec.protocol}://${auth}${spec.host}:${spec.port}`
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Resolve the effective proxy URL: explicit plugin setting first, environment
|
|
98
|
+
* second. Returns '' when no proxy should be used.
|
|
99
|
+
*/
|
|
100
|
+
export function resolveProxySetting(configured, env = process.env) {
|
|
101
|
+
const explicit = String(configured ?? '').trim()
|
|
102
|
+
if (explicit) {
|
|
103
|
+
if (DISABLED_VALUES.has(explicit.toLowerCase())) return ''
|
|
104
|
+
return explicit
|
|
105
|
+
}
|
|
106
|
+
for (const key of ENV_KEYS) {
|
|
107
|
+
const value = String(env?.[key] ?? '').trim()
|
|
108
|
+
if (!value) continue
|
|
109
|
+
if (DISABLED_VALUES.has(value.toLowerCase())) return ''
|
|
110
|
+
return value
|
|
111
|
+
}
|
|
112
|
+
return ''
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** True when no_proxy/NO_PROXY says the host must be reached directly. */
|
|
116
|
+
export function shouldBypassProxy(host, env = process.env) {
|
|
117
|
+
const rules = String((env?.no_proxy || env?.NO_PROXY) ?? '').trim()
|
|
118
|
+
if (!rules) return false
|
|
119
|
+
const target = String(host || '').toLowerCase()
|
|
120
|
+
for (const rawRule of rules.split(',')) {
|
|
121
|
+
const rule = rawRule.trim().toLowerCase()
|
|
122
|
+
if (!rule) continue
|
|
123
|
+
if (rule === '*') return true
|
|
124
|
+
const bare = rule.startsWith('.') ? rule.slice(1) : rule
|
|
125
|
+
if (target === bare || target.endsWith(`.${bare}`)) return true
|
|
126
|
+
}
|
|
127
|
+
return false
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function basicAuthHeader(spec) {
|
|
131
|
+
if (!spec.username && !spec.password) return undefined
|
|
132
|
+
return `Basic ${Buffer.from(`${spec.username}:${spec.password}`).toString('base64')}`
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function isAborted(signal) {
|
|
136
|
+
return Boolean(signal?.aborted)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function abortReason(signal, fallback = 'proxy request aborted') {
|
|
140
|
+
const reason = signal?.reason
|
|
141
|
+
if (reason instanceof Error) return reason
|
|
142
|
+
if (reason !== undefined) return new Error(String(reason))
|
|
143
|
+
return new Error(fallback)
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Tunnel to host:port through an http(s) proxy using the CONNECT method. */
|
|
147
|
+
function connectViaHttpProxy(spec, host, port, { signal, timeoutMs }) {
|
|
148
|
+
return new Promise((resolve, reject) => {
|
|
149
|
+
const mod = spec.kind === 'https' ? https : http
|
|
150
|
+
const headers = { host: `${host}:${port}` }
|
|
151
|
+
const auth = basicAuthHeader(spec)
|
|
152
|
+
if (auth) headers['proxy-authorization'] = auth
|
|
153
|
+
const options = {
|
|
154
|
+
host: spec.host,
|
|
155
|
+
port: spec.port,
|
|
156
|
+
method: 'CONNECT',
|
|
157
|
+
path: `${host}:${port}`,
|
|
158
|
+
headers,
|
|
159
|
+
agent: false,
|
|
160
|
+
}
|
|
161
|
+
if (spec.kind === 'https') options.servername = spec.host
|
|
162
|
+
|
|
163
|
+
let settled = false
|
|
164
|
+
const req = mod.request(options)
|
|
165
|
+
const cleanup = () => {
|
|
166
|
+
if (signal && typeof signal.removeEventListener === 'function') signal.removeEventListener('abort', onAbort)
|
|
167
|
+
}
|
|
168
|
+
const fail = (err) => {
|
|
169
|
+
if (settled) return
|
|
170
|
+
settled = true
|
|
171
|
+
cleanup()
|
|
172
|
+
reject(err)
|
|
173
|
+
}
|
|
174
|
+
const onAbort = () => {
|
|
175
|
+
req.destroy(abortReason(signal))
|
|
176
|
+
fail(abortReason(signal))
|
|
177
|
+
}
|
|
178
|
+
req.setTimeout(Math.max(1000, Number(timeoutMs) || 20000), () => {
|
|
179
|
+
req.destroy(new Error(`proxy CONNECT timeout after ${timeoutMs}ms`))
|
|
180
|
+
})
|
|
181
|
+
req.on('error', (err) => fail(err))
|
|
182
|
+
req.on('response', (res) => {
|
|
183
|
+
res.resume()
|
|
184
|
+
fail(new Error(`proxy CONNECT rejected (HTTP ${res.statusCode}${res.statusCode === 407 ? ' proxy authentication required' : ''})`))
|
|
185
|
+
})
|
|
186
|
+
req.on('connect', (res, socket, head) => {
|
|
187
|
+
if (settled) {
|
|
188
|
+
socket.destroy()
|
|
189
|
+
return
|
|
190
|
+
}
|
|
191
|
+
if (res.statusCode !== 200) {
|
|
192
|
+
socket.destroy()
|
|
193
|
+
fail(new Error(`proxy CONNECT rejected (HTTP ${res.statusCode}${res.statusCode === 407 ? ' proxy authentication required' : ''})`))
|
|
194
|
+
return
|
|
195
|
+
}
|
|
196
|
+
settled = true
|
|
197
|
+
cleanup()
|
|
198
|
+
socket.setNoDelay(true)
|
|
199
|
+
if (head && head.length) socket.unshift(head)
|
|
200
|
+
resolve(socket)
|
|
201
|
+
})
|
|
202
|
+
if (signal) {
|
|
203
|
+
if (isAborted(signal)) {
|
|
204
|
+
onAbort()
|
|
205
|
+
return
|
|
206
|
+
}
|
|
207
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
208
|
+
}
|
|
209
|
+
req.end()
|
|
210
|
+
})
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Small exact-length reader used for the SOCKS5 handshake. */
|
|
214
|
+
class SocketReader {
|
|
215
|
+
constructor(socket) {
|
|
216
|
+
this.socket = socket
|
|
217
|
+
this.buffer = Buffer.alloc(0)
|
|
218
|
+
this.error = null
|
|
219
|
+
this.closed = false
|
|
220
|
+
this.waiters = []
|
|
221
|
+
this.onData = (chunk) => {
|
|
222
|
+
this.buffer = Buffer.concat([this.buffer, chunk])
|
|
223
|
+
this.wake()
|
|
224
|
+
}
|
|
225
|
+
this.onError = (err) => {
|
|
226
|
+
this.error = err
|
|
227
|
+
this.wake()
|
|
228
|
+
}
|
|
229
|
+
this.onClose = () => {
|
|
230
|
+
this.closed = true
|
|
231
|
+
this.wake()
|
|
232
|
+
}
|
|
233
|
+
socket.on('data', this.onData)
|
|
234
|
+
socket.on('error', this.onError)
|
|
235
|
+
socket.on('close', this.onClose)
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
wake() {
|
|
239
|
+
const waiters = this.waiters
|
|
240
|
+
this.waiters = []
|
|
241
|
+
for (const resolve of waiters) resolve()
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
async read(size) {
|
|
245
|
+
while (this.buffer.length < size) {
|
|
246
|
+
if (this.error) throw this.error
|
|
247
|
+
if (this.closed) throw new Error('proxy closed the connection during SOCKS5 handshake')
|
|
248
|
+
await new Promise((resolve) => this.waiters.push(resolve))
|
|
249
|
+
}
|
|
250
|
+
const out = this.buffer.subarray(0, size)
|
|
251
|
+
this.buffer = this.buffer.subarray(size)
|
|
252
|
+
return out
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
detach() {
|
|
256
|
+
this.socket.removeListener('data', this.onData)
|
|
257
|
+
this.socket.removeListener('error', this.onError)
|
|
258
|
+
this.socket.removeListener('close', this.onClose)
|
|
259
|
+
const rest = this.buffer
|
|
260
|
+
this.buffer = Buffer.alloc(0)
|
|
261
|
+
return rest
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function socksErrorMessage(code) {
|
|
266
|
+
const map = {
|
|
267
|
+
0x01: 'general SOCKS server failure',
|
|
268
|
+
0x02: 'connection not allowed by ruleset',
|
|
269
|
+
0x03: 'network unreachable',
|
|
270
|
+
0x04: 'host unreachable',
|
|
271
|
+
0x05: 'connection refused',
|
|
272
|
+
0x06: 'TTL expired',
|
|
273
|
+
0x07: 'command not supported',
|
|
274
|
+
0x08: 'address type not supported',
|
|
275
|
+
}
|
|
276
|
+
return map[code] || `error 0x${Number(code).toString(16)}`
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function encodeSocksTarget(host, port) {
|
|
280
|
+
const portBuf = Buffer.alloc(2)
|
|
281
|
+
portBuf.writeUInt16BE(port, 0)
|
|
282
|
+
if (net.isIPv4(host)) {
|
|
283
|
+
return Buffer.concat([Buffer.from([0x01]), Buffer.from(host.split('.').map(Number)), portBuf])
|
|
284
|
+
}
|
|
285
|
+
if (net.isIPv6(host)) {
|
|
286
|
+
return Buffer.concat([Buffer.from([0x04]), expandIpv6(host), portBuf])
|
|
287
|
+
}
|
|
288
|
+
const name = Buffer.from(host, 'utf8')
|
|
289
|
+
if (name.length > 255) throw new Error(`SOCKS5 target host too long: ${host}`)
|
|
290
|
+
return Buffer.concat([Buffer.from([0x03, name.length]), name, portBuf])
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function expandIpv6(host) {
|
|
294
|
+
const [head, tail] = host.split('::')
|
|
295
|
+
const headParts = head ? head.split(':').filter(Boolean) : []
|
|
296
|
+
const tailParts = tail !== undefined && tail ? tail.split(':').filter(Boolean) : []
|
|
297
|
+
const missing = 8 - headParts.length - tailParts.length
|
|
298
|
+
const parts = [...headParts, ...Array(Math.max(0, missing)).fill('0'), ...tailParts]
|
|
299
|
+
const buf = Buffer.alloc(16)
|
|
300
|
+
parts.slice(0, 8).forEach((part, index) => buf.writeUInt16BE(parseInt(part || '0', 16) || 0, index * 2))
|
|
301
|
+
return buf
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function writeAll(socket, buffer) {
|
|
305
|
+
return new Promise((resolve, reject) => {
|
|
306
|
+
const onError = (err) => {
|
|
307
|
+
socket.removeListener('error', onError)
|
|
308
|
+
reject(err)
|
|
309
|
+
}
|
|
310
|
+
socket.once('error', onError)
|
|
311
|
+
socket.write(buffer, () => {
|
|
312
|
+
socket.removeListener('error', onError)
|
|
313
|
+
resolve()
|
|
314
|
+
})
|
|
315
|
+
})
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** Tunnel to host:port through a SOCKS5 proxy (remote DNS resolution). */
|
|
319
|
+
async function connectViaSocks5(spec, host, port, { signal, timeoutMs }) {
|
|
320
|
+
const socket = net.connect({ host: spec.host, port: spec.port })
|
|
321
|
+
socket.setNoDelay(true)
|
|
322
|
+
const reader = new SocketReader(socket)
|
|
323
|
+
const cleanup = () => {
|
|
324
|
+
if (signal && typeof signal.removeEventListener === 'function') signal.removeEventListener('abort', onAbort)
|
|
325
|
+
}
|
|
326
|
+
const onAbort = () => {
|
|
327
|
+
socket.destroy(abortReason(signal))
|
|
328
|
+
}
|
|
329
|
+
const timer = setTimeout(
|
|
330
|
+
() => socket.destroy(new Error(`SOCKS5 handshake timeout after ${timeoutMs}ms`)),
|
|
331
|
+
Math.max(1000, Number(timeoutMs) || 20000),
|
|
332
|
+
)
|
|
333
|
+
if (signal) {
|
|
334
|
+
if (isAborted(signal)) onAbort()
|
|
335
|
+
else signal.addEventListener('abort', onAbort, { once: true })
|
|
336
|
+
}
|
|
337
|
+
try {
|
|
338
|
+
await new Promise((resolve, reject) => {
|
|
339
|
+
socket.once('connect', resolve)
|
|
340
|
+
socket.once('error', reject)
|
|
341
|
+
})
|
|
342
|
+
const useAuth = Boolean(spec.username || spec.password)
|
|
343
|
+
await writeAll(socket, useAuth ? Buffer.from([0x05, 0x02, 0x00, 0x02]) : Buffer.from([0x05, 0x01, 0x00]))
|
|
344
|
+
const greeting = await reader.read(2)
|
|
345
|
+
if (greeting[0] !== 0x05) throw new Error(`SOCKS5 proxy reply has unsupported version 0x${greeting[0].toString(16)}`)
|
|
346
|
+
if (greeting[1] === 0xff) throw new Error('SOCKS5 proxy refused all authentication methods')
|
|
347
|
+
if (greeting[1] === 0x02) {
|
|
348
|
+
if (!useAuth) throw new Error('SOCKS5 proxy requires username/password authentication')
|
|
349
|
+
const user = Buffer.from(spec.username, 'utf8')
|
|
350
|
+
const pass = Buffer.from(spec.password, 'utf8')
|
|
351
|
+
await writeAll(socket, Buffer.concat([Buffer.from([0x01, user.length]), user, Buffer.from([pass.length]), pass]))
|
|
352
|
+
const authReply = await reader.read(2)
|
|
353
|
+
if (authReply[1] !== 0x00) throw new Error('SOCKS5 proxy rejected the supplied username/password')
|
|
354
|
+
} else if (greeting[1] !== 0x00) {
|
|
355
|
+
throw new Error(`SOCKS5 proxy selected unsupported authentication method 0x${greeting[1].toString(16)}`)
|
|
356
|
+
}
|
|
357
|
+
await writeAll(socket, Buffer.concat([Buffer.from([0x05, 0x01, 0x00]), encodeSocksTarget(host, port)]))
|
|
358
|
+
const replyHead = await reader.read(4)
|
|
359
|
+
if (replyHead[0] !== 0x05) throw new Error('SOCKS5 proxy returned a malformed reply')
|
|
360
|
+
if (replyHead[1] !== 0x00) {
|
|
361
|
+
throw new Error(`SOCKS5 proxy could not connect to ${host}:${port} (${socksErrorMessage(replyHead[1])})`)
|
|
362
|
+
}
|
|
363
|
+
const atyp = replyHead[3]
|
|
364
|
+
const addrLength = atyp === 0x01 ? 4 : atyp === 0x04 ? 16 : (await reader.read(1))[0]
|
|
365
|
+
await reader.read(addrLength + 2)
|
|
366
|
+
const leftover = reader.detach()
|
|
367
|
+
if (leftover.length) socket.unshift(leftover)
|
|
368
|
+
return socket
|
|
13
369
|
} catch (err) {
|
|
14
|
-
|
|
370
|
+
reader.detach()
|
|
371
|
+
socket.destroy()
|
|
372
|
+
throw err
|
|
373
|
+
} finally {
|
|
374
|
+
clearTimeout(timer)
|
|
375
|
+
cleanup()
|
|
15
376
|
}
|
|
16
|
-
|
|
17
|
-
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
async function openTunnel(spec, host, port, options) {
|
|
380
|
+
return spec.kind === 'socks5'
|
|
381
|
+
? connectViaSocks5(spec, host, port, options)
|
|
382
|
+
: connectViaHttpProxy(spec, host, port, options)
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
function wrapTls(socket, servername, { signal } = {}) {
|
|
386
|
+
return new Promise((resolve, reject) => {
|
|
387
|
+
const cleanup = () => {
|
|
388
|
+
if (signal && typeof signal.removeEventListener === 'function') signal.removeEventListener('abort', onAbort)
|
|
389
|
+
}
|
|
390
|
+
const onAbort = () => {
|
|
391
|
+
socket.destroy(abortReason(signal))
|
|
392
|
+
reject(abortReason(signal))
|
|
393
|
+
}
|
|
394
|
+
const tlsSocket = tls.connect({ socket, servername, ALPNProtocols: ['http/1.1'], minVersion: 'TLSv1.2' }, () => {
|
|
395
|
+
cleanup()
|
|
396
|
+
resolve(tlsSocket)
|
|
397
|
+
})
|
|
398
|
+
tlsSocket.once('error', (err) => {
|
|
399
|
+
cleanup()
|
|
400
|
+
reject(err)
|
|
401
|
+
})
|
|
402
|
+
if (signal) {
|
|
403
|
+
if (isAborted(signal)) {
|
|
404
|
+
onAbort()
|
|
405
|
+
return
|
|
406
|
+
}
|
|
407
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
408
|
+
}
|
|
409
|
+
})
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* Minimal http.Agent-compatible object: every request gets a fresh tunnel, so
|
|
414
|
+
* there is no socket pool to maintain. Node calls addRequest() and receives the
|
|
415
|
+
* connected socket back through req.onSocket().
|
|
416
|
+
*/
|
|
417
|
+
class ProxyTunnelAgent {
|
|
418
|
+
constructor({ spec, timeoutMs, logger }) {
|
|
419
|
+
this.spec = spec
|
|
420
|
+
this.timeoutMs = timeoutMs
|
|
421
|
+
this.logger = logger
|
|
422
|
+
this.protocol = 'https:'
|
|
423
|
+
this.defaultPort = 443
|
|
424
|
+
this.keepAlive = false
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
getName() {
|
|
428
|
+
return `dsh-telegram-proxy:${this.spec.label}`
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
keepSocketAlive() {
|
|
432
|
+
return false
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
reuseSocket(socket) {
|
|
436
|
+
try { socket?.destroy() } catch { /* ignore */ }
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
destroy() {
|
|
440
|
+
/* nothing pooled */
|
|
18
441
|
}
|
|
19
|
-
|
|
442
|
+
|
|
443
|
+
addRequest(req, options = {}) {
|
|
444
|
+
const targetHost = options.host || options.hostname
|
|
445
|
+
const targetPort = Number(options.port) || (options.protocol === 'https:' ? 443 : 80)
|
|
446
|
+
const signal = options.__dshAbortSignal
|
|
447
|
+
const servername = options.servername || targetHost
|
|
448
|
+
openTunnel(this.spec, targetHost, targetPort, { signal, timeoutMs: this.timeoutMs })
|
|
449
|
+
.then(async (raw) => {
|
|
450
|
+
try {
|
|
451
|
+
if (signal?.aborted) throw abortReason(signal)
|
|
452
|
+
return options.protocol === 'https:' ? await wrapTls(raw, servername, { signal }) : raw
|
|
453
|
+
} catch (err) {
|
|
454
|
+
raw.destroy()
|
|
455
|
+
throw err
|
|
456
|
+
}
|
|
457
|
+
})
|
|
458
|
+
.then((socket) => {
|
|
459
|
+
if (req.destroyed) {
|
|
460
|
+
socket.destroy()
|
|
461
|
+
return
|
|
462
|
+
}
|
|
463
|
+
req.onSocket(socket)
|
|
464
|
+
})
|
|
465
|
+
.catch((err) => {
|
|
466
|
+
this.logger?.debug?.(`telegram proxy tunnel failed (${this.spec.label}): ${err?.message || err}`)
|
|
467
|
+
failRequest(req, err)
|
|
468
|
+
})
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
// A ClientRequest that never received a socket does not surface destroy(err):
|
|
473
|
+
// Node only emits 'error' once the request owns a socket. Report the failure
|
|
474
|
+
// explicitly so the awaiting fetch() rejects instead of hanging.
|
|
475
|
+
function failRequest(req, err) {
|
|
476
|
+
try { req.destroy() } catch { /* ignore */ }
|
|
477
|
+
try { req.emit('error', err) } catch { /* ignore */ }
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
function headersToObject(headers) {
|
|
481
|
+
if (!headers) return {}
|
|
482
|
+
if (typeof headers.forEach === 'function' && typeof headers.get === 'function') {
|
|
483
|
+
const out = {}
|
|
484
|
+
headers.forEach((value, key) => { out[key] = value })
|
|
485
|
+
return out
|
|
486
|
+
}
|
|
487
|
+
if (Array.isArray(headers)) return Object.fromEntries(headers)
|
|
488
|
+
return { ...headers }
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
async function serializeBody(body) {
|
|
492
|
+
if (body === undefined || body === null) return { buffer: null, contentType: undefined }
|
|
493
|
+
if (typeof body === 'string') return { buffer: Buffer.from(body, 'utf8'), contentType: undefined }
|
|
494
|
+
if (Buffer.isBuffer(body)) return { buffer: body, contentType: undefined }
|
|
495
|
+
if (body instanceof Uint8Array) return { buffer: Buffer.from(body), contentType: undefined }
|
|
496
|
+
if (body instanceof ArrayBuffer) return { buffer: Buffer.from(body), contentType: undefined }
|
|
497
|
+
if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) {
|
|
498
|
+
return { buffer: Buffer.from(body.toString(), 'utf8'), contentType: 'application/x-www-form-urlencoded;charset=UTF-8' }
|
|
499
|
+
}
|
|
500
|
+
if (typeof FormData !== 'undefined' && typeof Request !== 'undefined' && body instanceof FormData) {
|
|
501
|
+
// Let the platform multipart encoder build the body, then read it back.
|
|
502
|
+
const prepared = new Request('http://dsh-messenger-gateway.invalid/', { method: 'POST', body })
|
|
503
|
+
const buffer = Buffer.from(await prepared.arrayBuffer())
|
|
504
|
+
return { buffer, contentType: prepared.headers.get('content-type') || undefined }
|
|
505
|
+
}
|
|
506
|
+
return { buffer: Buffer.from(String(body), 'utf8'), contentType: undefined }
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
function makeResponse(res, buffer, url) {
|
|
510
|
+
const headers = res.headers || {}
|
|
511
|
+
return {
|
|
512
|
+
ok: Number(res.statusCode) >= 200 && Number(res.statusCode) < 300,
|
|
513
|
+
status: Number(res.statusCode),
|
|
514
|
+
statusText: String(res.statusMessage || ''),
|
|
515
|
+
url,
|
|
516
|
+
headers: {
|
|
517
|
+
get: (name) => {
|
|
518
|
+
const value = headers[String(name).toLowerCase()]
|
|
519
|
+
return value === undefined ? null : String(value)
|
|
520
|
+
},
|
|
521
|
+
has: (name) => headers[String(name).toLowerCase()] !== undefined,
|
|
522
|
+
forEach: (cb) => {
|
|
523
|
+
for (const [key, value] of Object.entries(headers)) cb(String(value), key)
|
|
524
|
+
},
|
|
525
|
+
entries: () => Object.entries(headers)[Symbol.iterator](),
|
|
526
|
+
},
|
|
527
|
+
async text() { return buffer.toString('utf8') },
|
|
528
|
+
async json() { return JSON.parse(buffer.toString('utf8')) },
|
|
529
|
+
async arrayBuffer() {
|
|
530
|
+
return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength)
|
|
531
|
+
},
|
|
532
|
+
async blob() { return new Blob([buffer]) },
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
function requestOverTunnel({ spec, url, method, headers, body, signal, timeoutMs, logger }) {
|
|
537
|
+
return new Promise((resolve, reject) => {
|
|
538
|
+
const mod = url.protocol === 'https:' ? https : http
|
|
539
|
+
const onAbort = () => {
|
|
540
|
+
const reason = abortReason(signal)
|
|
541
|
+
failRequest(req, reason)
|
|
542
|
+
reject(reason)
|
|
543
|
+
}
|
|
544
|
+
let req
|
|
545
|
+
serializeBody(body).then((payload) => {
|
|
546
|
+
const outgoing = { ...headers }
|
|
547
|
+
delete outgoing['content-length']
|
|
548
|
+
delete outgoing['Content-Length']
|
|
549
|
+
if (payload.contentType && !outgoing['content-type'] && !outgoing['Content-Type']) {
|
|
550
|
+
outgoing['content-type'] = payload.contentType
|
|
551
|
+
}
|
|
552
|
+
if (!outgoing.host && !outgoing.Host) outgoing.host = url.host
|
|
553
|
+
if (signal?.aborted) {
|
|
554
|
+
reject(abortReason(signal))
|
|
555
|
+
return
|
|
556
|
+
}
|
|
557
|
+
const agent = new ProxyTunnelAgent({ spec, timeoutMs, logger })
|
|
558
|
+
req = mod.request({
|
|
559
|
+
protocol: url.protocol,
|
|
560
|
+
host: url.hostname,
|
|
561
|
+
hostname: url.hostname,
|
|
562
|
+
port: Number(url.port) || (url.protocol === 'https:' ? 443 : 80),
|
|
563
|
+
path: `${url.pathname}${url.search}`,
|
|
564
|
+
method: String(method || 'GET').toUpperCase(),
|
|
565
|
+
headers: outgoing,
|
|
566
|
+
servername: url.hostname,
|
|
567
|
+
agent,
|
|
568
|
+
__dshAbortSignal: signal,
|
|
569
|
+
}, (res) => {
|
|
570
|
+
const chunks = []
|
|
571
|
+
res.on('data', (chunk) => chunks.push(chunk))
|
|
572
|
+
res.on('end', () => {
|
|
573
|
+
if (signal && typeof signal.removeEventListener === 'function') signal.removeEventListener('abort', onAbort)
|
|
574
|
+
resolve(makeResponse(res, Buffer.concat(chunks), url.href))
|
|
575
|
+
})
|
|
576
|
+
res.on('error', (err) => {
|
|
577
|
+
if (signal && typeof signal.removeEventListener === 'function') signal.removeEventListener('abort', onAbort)
|
|
578
|
+
reject(err)
|
|
579
|
+
})
|
|
580
|
+
})
|
|
581
|
+
req.on('error', (err) => {
|
|
582
|
+
if (signal && typeof signal.removeEventListener === 'function') signal.removeEventListener('abort', onAbort)
|
|
583
|
+
reject(err)
|
|
584
|
+
})
|
|
585
|
+
if (signal) signal.addEventListener('abort', onAbort, { once: true })
|
|
586
|
+
req.end(payload.buffer ?? undefined)
|
|
587
|
+
}, reject)
|
|
588
|
+
})
|
|
20
589
|
}
|
|
21
590
|
|
|
591
|
+
/** Canonical proxy URL (compat with the upstream `normalizeProxyUrl`). */
|
|
592
|
+
export function normalizeProxyUrl(raw) {
|
|
593
|
+
const spec = parseProxySpec(raw)
|
|
594
|
+
if (!spec) return ''
|
|
595
|
+
const auth = (spec.username || spec.password)
|
|
596
|
+
? `${encodeURIComponent(spec.username)}:${encodeURIComponent(spec.password)}@`
|
|
597
|
+
: ''
|
|
598
|
+
return `${spec.protocol}://${auth}${spec.host}:${spec.port}`
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/** Custom Telegram Bot API root (upstream name for the api base URL). */
|
|
22
602
|
export function normalizeApiRoot(rawUrl) {
|
|
23
603
|
const trimmed = String(rawUrl || '').trim()
|
|
24
604
|
if (!trimmed) return 'https://api.telegram.org'
|
|
@@ -34,30 +614,56 @@ export function normalizeApiRoot(rawUrl) {
|
|
|
34
614
|
return trimmed.replace(/\/+$/, '')
|
|
35
615
|
}
|
|
36
616
|
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
const
|
|
49
|
-
|
|
50
|
-
|
|
617
|
+
/**
|
|
618
|
+
* Build a fetch()-compatible function that routes every request through the
|
|
619
|
+
* proxy. Returns null when no proxy is configured (callers keep global fetch).
|
|
620
|
+
* Throws on malformed proxy URLs so the failure is visible in the plugin log.
|
|
621
|
+
*/
|
|
622
|
+
export function createProxiedFetch(configuredProxy, options = {}) {
|
|
623
|
+
const env = options.env || process.env
|
|
624
|
+
const resolved = resolveProxySetting(configuredProxy, env)
|
|
625
|
+
if (!resolved) return null
|
|
626
|
+
const spec = parseProxySpec(resolved)
|
|
627
|
+
if (!spec) return null
|
|
628
|
+
const timeoutMs = Number(options.timeoutMs) || 20_000
|
|
629
|
+
const logger = options.logger
|
|
630
|
+
const proxied = async (input, init = {}) => {
|
|
631
|
+
const href = typeof input === 'string' ? input : (input instanceof URL ? input.href : input?.url)
|
|
632
|
+
const url = new URL(href)
|
|
633
|
+
if (shouldBypassProxy(url.hostname, env)) return fetch(input, init)
|
|
634
|
+
return requestOverTunnel({
|
|
635
|
+
spec,
|
|
636
|
+
url,
|
|
637
|
+
method: init.method || 'GET',
|
|
638
|
+
headers: headersToObject(init.headers),
|
|
639
|
+
body: init.body,
|
|
640
|
+
signal: init.signal,
|
|
641
|
+
timeoutMs,
|
|
642
|
+
logger,
|
|
643
|
+
})
|
|
51
644
|
}
|
|
645
|
+
proxied.proxy = spec
|
|
646
|
+
proxied.label = spec.label
|
|
647
|
+
proxied.raw = resolved
|
|
648
|
+
return proxied
|
|
649
|
+
}
|
|
52
650
|
|
|
651
|
+
/** Human readable proxy state for logs and the settings UI diagnostics. */
|
|
652
|
+
export function describeProxy(configuredProxy, env = process.env) {
|
|
653
|
+
const explicit = String(configuredProxy ?? '').trim()
|
|
53
654
|
try {
|
|
54
|
-
const
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
|
|
655
|
+
const resolved = resolveProxySetting(configuredProxy, env)
|
|
656
|
+
if (!resolved) return { configured: explicit, source: explicit ? 'settings' : 'env', active: false, label: '' }
|
|
657
|
+
const spec = parseProxySpec(resolved)
|
|
658
|
+
if (!spec) return { configured: explicit, active: false, label: '' }
|
|
659
|
+
return {
|
|
660
|
+
configured: explicit,
|
|
661
|
+
source: explicit ? 'settings' : 'env',
|
|
662
|
+
active: true,
|
|
663
|
+
label: spec.label,
|
|
664
|
+
kind: spec.kind,
|
|
665
|
+
}
|
|
60
666
|
} catch (err) {
|
|
61
|
-
|
|
667
|
+
return { configured: explicit, active: false, error: err.message, label: '' }
|
|
62
668
|
}
|
|
63
669
|
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// Защита секретов плагина от «пустой перезаписи» из карточки настроек.
|
|
2
|
+
//
|
|
3
|
+
// DSH отдаёт браузеру describe({ redactSecrets: true }) — поля с
|
|
4
|
+
// role('secret') (botToken, webhookSecret, secret вебхуков) в клиент не
|
|
5
|
+
// попадают. Карточка плагина сохраняет секцию целиком, поэтому при каждом
|
|
6
|
+
// сохранении (например, при смене прокси) в конфиг уезжает пустой токен и бот
|
|
7
|
+
// отключается. Здесь мы запоминаем последние непустые значения и возвращаем их
|
|
8
|
+
// обратно, если запись их обнулила. Явная смена значения (непустое новое)
|
|
9
|
+
// всегда выигрывает — так же ведёт себя и PUT /config в lib/index.js.
|
|
10
|
+
|
|
11
|
+
export const SECRET_FIELDS = [
|
|
12
|
+
['telegram', 'botToken'],
|
|
13
|
+
['telegram', 'webhookSecret'],
|
|
14
|
+
['discord', 'botToken'],
|
|
15
|
+
['slack', 'botToken'],
|
|
16
|
+
['webhooks', 'secret'],
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
function keyOf(section, field) {
|
|
20
|
+
return `${section}.${field}`
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Снимок непустых секретов конфига: { 'telegram.botToken': '123:ABC' }. */
|
|
24
|
+
export function readSecrets(config) {
|
|
25
|
+
const out = {}
|
|
26
|
+
for (const [section, field] of SECRET_FIELDS) {
|
|
27
|
+
const value = String(config?.[section]?.[field] ?? '')
|
|
28
|
+
out[keyOf(section, field)] = value
|
|
29
|
+
}
|
|
30
|
+
return out
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Возвращает копию конфига с восстановленными секретами.
|
|
35
|
+
* @param previous снимок из readSecrets() до записи
|
|
36
|
+
* @param config разобранный конфиг после записи
|
|
37
|
+
* @returns {{ config: object, restored: string[] }} — restored пуст, если чинить нечего
|
|
38
|
+
*/
|
|
39
|
+
export function restoreSecrets(previous, config) {
|
|
40
|
+
const restored = []
|
|
41
|
+
const next = structuredClone(config ?? {})
|
|
42
|
+
for (const [section, field] of SECRET_FIELDS) {
|
|
43
|
+
const key = keyOf(section, field)
|
|
44
|
+
const before = String(previous?.[key] ?? '')
|
|
45
|
+
const after = String(next?.[section]?.[field] ?? '')
|
|
46
|
+
if (before && !after) {
|
|
47
|
+
next[section] = { ...(next[section] || {}), [field]: before }
|
|
48
|
+
restored.push(key)
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return { config: next, restored }
|
|
52
|
+
}
|
package/lib/telegram-errors.js
CHANGED
|
File without changes
|
package/lib/telegram-format.js
CHANGED
|
@@ -7,6 +7,69 @@ export function escapeHtml(text) {
|
|
|
7
7
|
|
|
8
8
|
const PH = '\uE000'
|
|
9
9
|
|
|
10
|
+
// Telegram HTML поддерживает только этот набор тегов; всё остальное (<script>,
|
|
11
|
+
// атрибуты, произвольные теги) обязано остаться текстом. Командные ответы самого
|
|
12
|
+
// плагина написаны HTML-тегами (<b>, <code>, ...), а конвейер рассчитан на
|
|
13
|
+
// Markdown и экранирует весь вход — из-за этого в чате были видны литеральные
|
|
14
|
+
// теги. Поэтому теги из белого списка вынимаем в слоты до экранирования и
|
|
15
|
+
// возвращаем уже как разметку.
|
|
16
|
+
const SAFE_TAG_NAMES = 'b|strong|i|em|u|s|strike|del|code|pre|tg-spoiler|blockquote'
|
|
17
|
+
const SAFE_TAG_RE = new RegExp(`<(/?)(${SAFE_TAG_NAMES})>`, 'gi')
|
|
18
|
+
const SAFE_ANCHOR_RE = /<a\s+href="([^"]{1,512})"\s*>/gi
|
|
19
|
+
|
|
20
|
+
const ENTITIES = {
|
|
21
|
+
'<': '<',
|
|
22
|
+
'>': '>',
|
|
23
|
+
'"': '"',
|
|
24
|
+
''': "'",
|
|
25
|
+
''': "'",
|
|
26
|
+
' ': '\u00a0',
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Однопроходное раскрытие типовых HTML-сущностей: плагин пишет `<role>`
|
|
31
|
+
* там, где нужен текст `<role>`, а Markdown-конвейер ждёт обычный текст.
|
|
32
|
+
* `&` раскрывается последним, поэтому `&lt;` остаётся `<`.
|
|
33
|
+
*/
|
|
34
|
+
export function decodeHtmlEntities(text) {
|
|
35
|
+
return String(text ?? '').replace(/&(lt|gt|quot|#39|apos|nbsp);|&/g, (match) => ENTITIES[match] ?? '&')
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const SAFE_TAG_ANY_RE = new RegExp(`<a\\s+href="([^"]{1,512})"\\s*>|<(/?)(${SAFE_TAG_NAMES}|a)>`, 'gi')
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Вынимает в слоты только сбалансированные теги из белого списка. Незакрытый
|
|
42
|
+
* `</b>` или тег с атрибутами (`<b onclick=...>`) остаются текстом и будут
|
|
43
|
+
* экранированы — иначе Telegram отвергнет сообщение как невалидную разметку.
|
|
44
|
+
*/
|
|
45
|
+
function protectSafeTags(text, stash) {
|
|
46
|
+
const open = []
|
|
47
|
+
return text.replace(SAFE_TAG_ANY_RE, (match, href, closing, rawName) => {
|
|
48
|
+
const tag = String(rawName || 'a').toLowerCase()
|
|
49
|
+
if (href !== undefined) {
|
|
50
|
+
if (!isSafeUrl(href)) return match
|
|
51
|
+
open.push(tag)
|
|
52
|
+
return stash(match)
|
|
53
|
+
}
|
|
54
|
+
if (closing) {
|
|
55
|
+
const index = open.lastIndexOf(tag)
|
|
56
|
+
if (index === -1) return match
|
|
57
|
+
open.splice(index, 1)
|
|
58
|
+
return stash(match)
|
|
59
|
+
}
|
|
60
|
+
open.push(tag)
|
|
61
|
+
return stash(match)
|
|
62
|
+
})
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Для режима plain: убрать разметку и раскрыть сущности, оставив чистый текст. */
|
|
66
|
+
export function stripSafeTags(text) {
|
|
67
|
+
return decodeHtmlEntities(text)
|
|
68
|
+
.replace(SAFE_ANCHOR_RE, '')
|
|
69
|
+
.replace(/<\/a>/gi, '')
|
|
70
|
+
.replace(SAFE_TAG_RE, '')
|
|
71
|
+
}
|
|
72
|
+
|
|
10
73
|
const SAFE_SCHEMES = new Set(['https:', 'http:', 'tg:'])
|
|
11
74
|
|
|
12
75
|
export function isSafeUrl(rawUrl) {
|
|
@@ -138,8 +201,10 @@ export function markdownToTelegramHtml(markdown) {
|
|
|
138
201
|
return `${PH}${id}${PH}`
|
|
139
202
|
}
|
|
140
203
|
|
|
204
|
+
text = decodeHtmlEntities(text)
|
|
141
205
|
text = text.replace(/```([\s\S]*?)```/g, (_, code) => stash(`<pre><code>${escapeHtml(code.replace(/^\n/, '').replace(/\n$/, ''))}</code></pre>`))
|
|
142
206
|
text = text.replace(/`([^`\n]+)`/g, (_, code) => stash(`<code>${escapeHtml(code)}</code>`))
|
|
207
|
+
text = protectSafeTags(text, stash)
|
|
143
208
|
text = convertTables(text, stash)
|
|
144
209
|
text = convertDetails(text, stash)
|
|
145
210
|
text = convertTaskLists(text, stash)
|
|
@@ -157,6 +222,7 @@ export function markdownToTelegramHtml(markdown) {
|
|
|
157
222
|
|
|
158
223
|
export function prepareTelegramText(text, format = 'html') {
|
|
159
224
|
const raw = String(text ?? '')
|
|
160
|
-
if (!raw
|
|
225
|
+
if (!raw) return { text: raw, parseMode: undefined }
|
|
226
|
+
if (format === 'plain') return { text: stripSafeTags(raw), parseMode: undefined }
|
|
161
227
|
return { text: markdownToTelegramHtml(raw), parseMode: 'HTML' }
|
|
162
228
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@goodandready/dsh-messenger-gateway",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.17",
|
|
4
4
|
"description": "Telegram messenger bridge for DeepSeek Harness: sessions, steer, homes, inline asks, notify bridge, and optional TTS voice notes.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|