@goodandready/dsh-messenger-gateway 0.4.16 → 0.4.18
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/client.js +1 -1
- package/lib/config.js +17 -9
- package/lib/gateway.js +27 -3
- package/lib/http.js +55 -5
- package/lib/index.js +44 -3
- 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/client.js
CHANGED
|
@@ -612,7 +612,7 @@ window.__ModuleLoader__.load({
|
|
|
612
612
|
|
|
613
613
|
const loadStatus = React.useCallback(async () => {
|
|
614
614
|
try {
|
|
615
|
-
const res = await fetch(`${ROUTE_PREFIX}/status`, { cache: 'no-store', signal: timeoutSignal(10000) })
|
|
615
|
+
const res = await fetch(`${ROUTE_PREFIX}/status`, { credentials: 'same-origin', cache: 'no-store', signal: timeoutSignal(10000) })
|
|
616
616
|
const data = await res.json().catch(() => ({}))
|
|
617
617
|
if (res.ok && data.ok) {
|
|
618
618
|
setStatus(data)
|
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/http.js
CHANGED
|
@@ -36,6 +36,44 @@ export function isLoopback(value) {
|
|
|
36
36
|
|| address.startsWith('::ffff:127.')
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
+
function isPrivateIPv4(address) {
|
|
40
|
+
const parts = address.split('.')
|
|
41
|
+
if (parts.length !== 4) return false
|
|
42
|
+
for (const p of parts) {
|
|
43
|
+
if (!/^\d{1,3}$/.test(p)) return false
|
|
44
|
+
const n = Number(p)
|
|
45
|
+
if (n < 0 || n > 255) return false
|
|
46
|
+
}
|
|
47
|
+
const o0 = Number(parts[0])
|
|
48
|
+
const o1 = Number(parts[1])
|
|
49
|
+
if (o0 === 10) return true
|
|
50
|
+
if (o0 === 192 && o1 === 168) return true
|
|
51
|
+
if (o0 === 172 && o1 >= 16 && o1 <= 31) return true
|
|
52
|
+
if (o0 === 169 && o1 === 254) return true
|
|
53
|
+
return false
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function isPrivateAddress(value) {
|
|
57
|
+
let address = String(value || '').toLowerCase().replace(/^\[|\]$/g, '')
|
|
58
|
+
if (address.startsWith('::ffff:')) {
|
|
59
|
+
address = address.slice('::ffff:'.length)
|
|
60
|
+
}
|
|
61
|
+
if (isLoopback(address)) return true
|
|
62
|
+
if (isPrivateIPv4(address)) return true
|
|
63
|
+
|
|
64
|
+
if (address.includes(':')) {
|
|
65
|
+
const firstHextet = address.split(':')[0]
|
|
66
|
+
const num = Number.parseInt(firstHextet, 16)
|
|
67
|
+
if (!Number.isNaN(num)) {
|
|
68
|
+
if ((num & 0xfe00) === 0xfc00) return true // fc00::/7 ULA (RFC 4193)
|
|
69
|
+
if ((num & 0xffc0) === 0xfe80) return true // fe80::/10 Link-Local (RFC 4291)
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return false
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export const isLoopbackOrLan = isPrivateAddress
|
|
76
|
+
|
|
39
77
|
export function isTrustedSettingsRequest(req, expectedSecret) {
|
|
40
78
|
const remote = req?.socket?.remoteAddress
|
|
41
79
|
const host = String(req?.headers?.host || '')
|
|
@@ -55,7 +93,14 @@ export function isTrustedSettingsRequest(req, expectedSecret) {
|
|
|
55
93
|
}
|
|
56
94
|
}
|
|
57
95
|
|
|
58
|
-
|
|
96
|
+
// Reject non-private / WAN requests without secret
|
|
97
|
+
if (remote !== undefined && !isPrivateAddress(remote)) {
|
|
98
|
+
return false
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// If host is loopback (localhost/127.0.0.1/::1), remote address must also be loopback
|
|
102
|
+
const hostName = host.split(':')[0].toLowerCase().replace(/^\[|\]$/g, '')
|
|
103
|
+
if (isLoopback(hostName) && remote !== undefined && !isLoopback(remote)) {
|
|
59
104
|
return false
|
|
60
105
|
}
|
|
61
106
|
|
|
@@ -82,7 +127,9 @@ export function isTrustedSettingsRequest(req, expectedSecret) {
|
|
|
82
127
|
}
|
|
83
128
|
|
|
84
129
|
if (site === 'same-origin') {
|
|
85
|
-
|
|
130
|
+
if (remote === undefined || isLoopback(remote)) {
|
|
131
|
+
return true
|
|
132
|
+
}
|
|
86
133
|
}
|
|
87
134
|
|
|
88
135
|
return isLoopback(remote)
|
|
@@ -93,8 +140,6 @@ export function isAuthorizedMessengerRequest(req, webhooksConfig) {
|
|
|
93
140
|
if (site === 'cross-site') return false
|
|
94
141
|
|
|
95
142
|
const secret = String(webhooksConfig?.secret || '').trim()
|
|
96
|
-
if (isTrustedSettingsRequest(req, secret)) return true
|
|
97
|
-
if (isLoopback(req?.socket?.remoteAddress)) return true
|
|
98
143
|
if (secret) {
|
|
99
144
|
const authHeader = req?.headers?.authorization || ''
|
|
100
145
|
const bearer = authHeader.startsWith('Bearer ') ? authHeader.slice(7).trim() : ''
|
|
@@ -105,7 +150,12 @@ export function isAuthorizedMessengerRequest(req, webhooksConfig) {
|
|
|
105
150
|
}
|
|
106
151
|
}
|
|
107
152
|
|
|
108
|
-
|
|
153
|
+
const remote = req?.socket?.remoteAddress
|
|
154
|
+
if (remote !== undefined && !isLoopback(remote)) {
|
|
155
|
+
return false
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
return isTrustedSettingsRequest(req, secret) || isLoopback(remote)
|
|
109
159
|
}
|
|
110
160
|
|
|
111
161
|
export function timingSafeCompare(a, b) {
|
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) => {
|
|
@@ -418,6 +458,7 @@ export function apply(ctx, config) {
|
|
|
418
458
|
kind: 'exact', path: '/dsh-messenger-gateway/status',
|
|
419
459
|
handler: async (req, res) => {
|
|
420
460
|
if (req.method !== 'GET') return writeJson(res, 405, { ok: false, error: 'GET only' })
|
|
461
|
+
if (!isTrustedSettingsRequest(req, source().webhooks?.secret)) return writeJson(res, 403, { ok: false, error: 'forbidden' })
|
|
421
462
|
const gw = getGw()
|
|
422
463
|
const botInfo = gw?.getBotInfo?.() || {}
|
|
423
464
|
const uptimeSec = gw?.stats?.startedAt ? Math.max(0, Math.round((Date.now() - gw.stats.startedAt) / 1000)) : 0
|
|
@@ -531,9 +572,9 @@ export function apply(ctx, config) {
|
|
|
531
572
|
ctx.effect(() => getWebServer().register({
|
|
532
573
|
kind: 'exact', path: '/dsh-messenger-gateway/config',
|
|
533
574
|
handler: async (req, res) => {
|
|
534
|
-
if (req.method
|
|
535
|
-
if (req.method !== 'PUT') return writeJson(res, 405, { ok: false, error: 'GET or PUT' })
|
|
575
|
+
if (req.method !== 'GET' && req.method !== 'PUT') return writeJson(res, 405, { ok: false, error: 'GET or PUT' })
|
|
536
576
|
if (!isTrustedSettingsRequest(req, source().webhooks?.secret)) return writeJson(res, 403, { ok: false, error: 'forbidden' })
|
|
577
|
+
if (req.method === 'GET') return writeJson(res, 200, { ok: true, config: publicConfig(source(), getGw(), ctx) })
|
|
537
578
|
if (!settingsApi?.isReady?.()) return writeJson(res, 503, { ok: false, error: 'settings not ready' })
|
|
538
579
|
const parsedConfig = await readJsonSafe(req, res, 1_048_576)
|
|
539
580
|
if (!parsedConfig.ok) return
|