@goodandready/dsh-messenger-gateway 0.4.33 → 0.4.35
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 +4 -2
- package/README.ru.md +4 -1
- package/README.zh.md +8 -0
- package/lib/adapters/discord.js +1 -1
- package/lib/adapters/telegram-inbound.js +1 -1
- package/lib/adapters/telegram.js +5 -6
- package/lib/artifacts.js +1 -1
- package/lib/ask.js +1 -1
- package/lib/client.js +0 -13
- package/lib/config.js +6 -3
- package/lib/file-manager.js +16 -3
- package/lib/forum-mirror.js +1 -1
- package/lib/gateway-callbacks.js +1 -2
- package/lib/gateway-commands.js +8 -2
- package/lib/gateway-turn.js +6 -6
- package/lib/gateway.js +5 -5
- package/lib/http.js +52 -12
- package/lib/index.js +9 -8
- package/lib/memory-brain.js +6 -1
- package/lib/messenger-api.js +17 -17
- package/lib/pairing.js +3 -2
- package/lib/personas.js +1 -0
- package/lib/proxy.js +5 -3
- package/lib/session-ops.js +1 -1
- package/lib/telegram-errors.js +0 -0
- package/lib/tts.js +1 -0
- package/lib/voice-prefs.js +1 -0
- package/lib/webapp.js +2 -1
- package/lib/workspace.js +2 -1
- package/package.json +12 -3
package/README.md
CHANGED
|
@@ -48,7 +48,7 @@ Talk to your Harness agent from Telegram: text, voice, photos, documents, inline
|
|
|
48
48
|
- Configurable proxy support: HTTP, HTTPS, SOCKS5, and SOCKS5h (`telegram.proxyUrl`)
|
|
49
49
|
- Custom Bot API root URL (`telegram.apiRoot`) for reverse proxies and local Bot API servers
|
|
50
50
|
- Multi-transport support: Telegram, Discord (Webhooks & Bot API), and Slack (Webhooks & Bot API)
|
|
51
|
-
- Allowlist + pairing codes (
|
|
51
|
+
- Allowlist + pairing codes (fail-closed by default: a fresh install admits nobody until paired; `allowlistMode: open` is an explicit opt-in)
|
|
52
52
|
- Conversation switching directly from chat (`/sessions` and `/resume <n|id>`)
|
|
53
53
|
- Per-user or per-chat sessions (`sessionScope`)
|
|
54
54
|
- Forum topics as separate sessions
|
|
@@ -143,7 +143,9 @@ In addition to Telegram, outbound messages can be dispatched to Discord and Slac
|
|
|
143
143
|
## Configuration notes
|
|
144
144
|
|
|
145
145
|
- `sessionScope`: `user` (default) or `chat` — how group chats isolate sessions
|
|
146
|
-
- `allowlistMode`: `
|
|
146
|
+
- `allowlistMode`: `closed` (default) or `open` — **closed** refuses every unknown user (fail-closed): a fresh install admits nobody until the admin approves a pairing code (`/start` → approve in the settings card); **open** admits all users when the allowlist is empty — enable it explicitly only for public assistant bots, the settings card and `/status` surface the exposure
|
|
147
|
+
- `security.trustProxy`: `false` (default) — loopback-trusted requests must carry a pinned `localhost` / `127.0.0.1` / `[::1]` Host (DNS rebinding defense). Enable only behind a trusted local reverse proxy that rewrites the Host header
|
|
148
|
+
- `/get` and `/files` require allowlisted users and never serve hidden (dot) files
|
|
147
149
|
- `sessionList`: `true` (default) — enables `/sessions` and `/resume` commands in chat
|
|
148
150
|
- `sessionTitleFromChat`: `false` (default) — name each new session after its originating chat (`TG · @user`, `TG · Group › topic N`) instead of generic generated titles
|
|
149
151
|
- `voiceMode`: `mirror` / `always` / `off` — when to speak replies (also `/voice`)
|
package/README.ru.md
CHANGED
|
@@ -95,8 +95,11 @@ graph LR
|
|
|
95
95
|
* Исключен риск перезаписи чужих файлов или доступа к системным ресурсам.
|
|
96
96
|
|
|
97
97
|
### 5. 🔐 Безопасность и 6-значные коды сопряжения (`pairing.js`)
|
|
98
|
+
* **Закрытый режим по умолчанию (`allowlistMode: closed`, fail-closed)**: новая установка не отвечает никому, пока администратор не одобрит код сопряжения; режим `open` (пропускать всех при пустом списке) включается явно — только для публичных ботов-ассистентов;
|
|
98
99
|
* Защита от несанкционированного доступа: новые пользователи должны ввести одноразовый 6-значный код, сгенерированный в Web UI;
|
|
99
|
-
* Белые списки разрешенных ID (`
|
|
100
|
+
* Белые списки разрешенных ID (`allowedUserIds`);
|
|
101
|
+
* Команды `/get` и `/files` доступны только пользователям из белого списка и никогда не отдают скрытые файлы (dotfiles, например `.env`);
|
|
102
|
+
* Loopback-запросы доверяются только с закреплёнными Host (`localhost` / `127.0.0.1` / `[::1]`) — защита от DNS rebinding; для доверенного локального reverse-proxy есть явный флаг `security.trustProxy`.
|
|
100
103
|
|
|
101
104
|
### 6. 🤖 Команды бота (`commands.js`)
|
|
102
105
|
* `/start` — приветствие и запуск сопряжения;
|
package/README.zh.md
CHANGED
|
@@ -81,6 +81,14 @@ dsh plugin --profile web add @goodandready/dsh-messenger-gateway
|
|
|
81
81
|
|
|
82
82
|
---
|
|
83
83
|
|
|
84
|
+
## 🔐 安全默认值
|
|
85
|
+
|
|
86
|
+
- **默认关闭白名单模式(`allowlistMode: closed`,fail-closed)**:全新安装不会响应任何用户,直到管理员批准配对码;`open` 模式(空列表时放行所有人)必须显式开启,仅适用于公共助手机器人;
|
|
87
|
+
- `/get` 与 `/files` 命令仅对白名单用户可用,且永远不会返回隐藏文件(dotfiles,如 `.env`);
|
|
88
|
+
- 本地回环请求只接受固定的 Host(`localhost` / `127.0.0.1` / `[::1]`)— 防 DNS Rebinding;如需在受信任的本地反向代理后使用,可显式开启 `security.trustProxy`。
|
|
89
|
+
|
|
90
|
+
---
|
|
91
|
+
|
|
84
92
|
## 📄 开源协议
|
|
85
93
|
|
|
86
94
|
MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
|
package/lib/adapters/discord.js
CHANGED
|
@@ -64,7 +64,7 @@ export class DiscordAdapter {
|
|
|
64
64
|
this.stopped = true
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
-
async sendTo(channelId, payload,
|
|
67
|
+
async sendTo(channelId, payload, _opts = {}) {
|
|
68
68
|
if (this.stopped) throw new Error('discord adapter stopped')
|
|
69
69
|
const body = typeof payload === 'string' ? { text: payload } : (payload || {})
|
|
70
70
|
const text = String(body.text || '')
|
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
IMAGE_EXT_TO_MIME, VIDEO_EXT_TO_MIME, classifyDocument,
|
|
4
4
|
extOf, TELEGRAM_MAX_DOC_BYTES,
|
|
5
5
|
} from '../media.js'
|
|
6
|
-
import { TEXT_INJECT_EXTS,
|
|
6
|
+
import { TEXT_INJECT_EXTS, } from '../documents.js'
|
|
7
7
|
|
|
8
8
|
export async function extractTelegramInboundMedia(adapter, msg, initialText, maxDocBytes = TELEGRAM_MAX_DOC_BYTES, maxTextInjectBytes = 100 * 1024) {
|
|
9
9
|
let text = initialText || ''
|
package/lib/adapters/telegram.js
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import { readFile } from 'node:fs/promises'
|
|
2
2
|
import {
|
|
3
|
-
|
|
3
|
+
cacheName,
|
|
4
4
|
extOf, saveToCache, safeName, TELEGRAM_MAX_DOC_BYTES,
|
|
5
5
|
} from '../media.js'
|
|
6
|
-
import { TEXT_INJECT_EXTS } from '../documents.js'
|
|
7
6
|
import { splitText } from '../text.js'
|
|
8
7
|
import { prepareTelegramText } from '../telegram-format.js'
|
|
9
8
|
import { normalizeTelegramCommands } from '../commands.js'
|
|
@@ -40,7 +39,7 @@ export class TelegramAdapter {
|
|
|
40
39
|
this.name = 'telegram'
|
|
41
40
|
this.token = String(opts.botToken || '').trim()
|
|
42
41
|
this.allowedUserIds = (opts.allowedUserIds || []).map(Number).filter((n) => Number.isFinite(n))
|
|
43
|
-
this.allowlistMode = opts.allowlistMode === '
|
|
42
|
+
this.allowlistMode = opts.allowlistMode === 'open' ? 'open' : 'closed'
|
|
44
43
|
this.timeoutSeconds = Number(opts.timeoutSeconds) || 50
|
|
45
44
|
this.pollIntervalMs = Number(opts.pollIntervalMs) || 500
|
|
46
45
|
this.media = opts.media || {}
|
|
@@ -363,7 +362,7 @@ export class TelegramAdapter {
|
|
|
363
362
|
editMessage: async (text, replyMarkup) => {
|
|
364
363
|
const { text: formatted, parseMode } = this.formatOutgoingText(text)
|
|
365
364
|
const params = { chat_id: chatId, message_id: messageId, text: formatted, reply_markup: replyMarkup }
|
|
366
|
-
if (parseMode) params.parse_mode = parseMode
|
|
365
|
+
if (parseMode) /** @type {any} */ (params).parse_mode = parseMode
|
|
367
366
|
try {
|
|
368
367
|
return await this.call('editMessageText', params)
|
|
369
368
|
} catch (err) {
|
|
@@ -687,7 +686,7 @@ export class TelegramAdapter {
|
|
|
687
686
|
const { text: formatted, parseMode } = this.formatOutgoingText(String(text || ''), payload)
|
|
688
687
|
const chunk = splitText(formatted, TELEGRAM_MAX)[0] || '…'
|
|
689
688
|
const params = { chat_id: chatId, message_id: messageId, text: chunk }
|
|
690
|
-
if (parseMode) params.parse_mode = parseMode
|
|
689
|
+
if (parseMode) /** @type {any} */ (params).parse_mode = parseMode
|
|
691
690
|
try {
|
|
692
691
|
await this.call('editMessageText', params)
|
|
693
692
|
} catch (err) {
|
|
@@ -760,7 +759,7 @@ export class TelegramAdapter {
|
|
|
760
759
|
reply_markup: i === 0 ? effectiveMarkup : undefined,
|
|
761
760
|
...telegramThreadParams(threadId),
|
|
762
761
|
}
|
|
763
|
-
if (parseMode) params.parse_mode = parseMode
|
|
762
|
+
if (parseMode) /** @type {any} */ (params).parse_mode = parseMode
|
|
764
763
|
try {
|
|
765
764
|
await this.sendWithRetry('sendMessage', params)
|
|
766
765
|
} catch (err) {
|
package/lib/artifacts.js
CHANGED
|
@@ -404,7 +404,7 @@ export function processDiagramsAndTables(rawText, options = {}) {
|
|
|
404
404
|
}
|
|
405
405
|
|
|
406
406
|
export async function processDiagramsAndTablesAsync(rawText, options = {}) {
|
|
407
|
-
const { artifactPreviews = true, artifactStore = null, chatId = null
|
|
407
|
+
const { artifactPreviews = true, artifactStore = null, chatId = null } = options
|
|
408
408
|
const createdArtifacts = []
|
|
409
409
|
let text = String(rawText || "")
|
|
410
410
|
const files = []
|
package/lib/ask.js
CHANGED
|
@@ -12,7 +12,7 @@ export function makeAskToken() {
|
|
|
12
12
|
export function buildCallbackData(token, buttonId) {
|
|
13
13
|
const data = `${token}:${buttonId}`
|
|
14
14
|
if (data.length > TELEGRAM_CALLBACK_DATA_MAX) {
|
|
15
|
-
const err = new Error(`callback_data too long (${data.length} > ${TELEGRAM_CALLBACK_DATA_MAX})`)
|
|
15
|
+
const err = /** @type {any} */ (new Error(`callback_data too long (${data.length} > ${TELEGRAM_CALLBACK_DATA_MAX})`))
|
|
16
16
|
err.status = 400
|
|
17
17
|
throw err
|
|
18
18
|
}
|
package/lib/client.js
CHANGED
|
@@ -334,19 +334,6 @@ window.__ModuleLoader__.load({
|
|
|
334
334
|
'badge.api_degraded': 'Telegram API 异常 ({count} 次连续错误)',
|
|
335
335
|
}
|
|
336
336
|
|
|
337
|
-
function useActiveLocale(ctx) {
|
|
338
|
-
const loc = ctx?.get?.('locale') || ctx?.locale
|
|
339
|
-
return React.useSyncExternalStore(
|
|
340
|
-
React.useMemo(() => (cb) => (loc ? loc.subscribe(cb) : () => {}), [loc]),
|
|
341
|
-
React.useCallback(() => {
|
|
342
|
-
if (loc) {
|
|
343
|
-
const active = loc.getSnapshot?.()?.active
|
|
344
|
-
if (typeof active === 'string' && active) return active
|
|
345
|
-
}
|
|
346
|
-
return typeof navigator !== 'undefined' ? String(navigator.language || '').slice(0, 2) : 'en'
|
|
347
|
-
}, [loc]),
|
|
348
|
-
)
|
|
349
|
-
}
|
|
350
337
|
|
|
351
338
|
function makeT(locale) {
|
|
352
339
|
const DICT = String(locale || '').startsWith('zh') ? zh : en
|
package/lib/config.js
CHANGED
|
@@ -18,12 +18,15 @@ export const PluginConfig = z.object({
|
|
|
18
18
|
enabled: z.boolean().volatile().default(true),
|
|
19
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'),
|
|
20
20
|
defaultLocale: z.union([z.const('en'), z.const('zh')]).volatile().default('en').description('Default language for bot messages and notifications (en, zh)'),
|
|
21
|
+
security: z.object({
|
|
22
|
+
trustProxy: z.boolean().default(false).description('Enable ONLY behind a trusted local reverse proxy: allows non-loopback Host/Origin headers (e.g. your-domain.local) on loopback requests. Default off — loopback trust requires pinned localhost/127.0.0.1/[::1] Host names (DNS rebinding defense)'),
|
|
23
|
+
}).volatile().default({}),
|
|
21
24
|
telegram: z.object({
|
|
22
25
|
enabled: z.boolean().default(false),
|
|
23
26
|
botToken: z.string().role('secret').default(''),
|
|
24
27
|
allowedUserIds: z.array(z.number()).default([]),
|
|
25
|
-
allowlistMode: z.union([z.const('open'), z.const('closed')]).default('
|
|
26
|
-
.description('Allowlist mode: open admits
|
|
28
|
+
allowlistMode: z.union([z.const('open'), z.const('closed')]).default('closed')
|
|
29
|
+
.description('Allowlist mode: closed (default, fail-closed) refuses unknown users until they are allowlisted or paired; open admits ALL users when the list is empty — enable explicitly only for public assistant bots'),
|
|
27
30
|
pollTimeoutSeconds: z.number().default(50),
|
|
28
31
|
pollIntervalMs: z.number().default(500),
|
|
29
32
|
commands: z.array(z.object({
|
|
@@ -34,7 +37,7 @@ export const PluginConfig = z.object({
|
|
|
34
37
|
homeChatId: z.union([z.number(), z.string()]).default('').description('Legacy default home chatId'),
|
|
35
38
|
homeThreadId: z.number().default(0),
|
|
36
39
|
homes: z.array(HomeEntry).default([]).description('Named homes (forum topics / channels)'),
|
|
37
|
-
pairingEnabled: z.boolean().default(true).description('Issue pairing codes to unknown users
|
|
40
|
+
pairingEnabled: z.boolean().default(true).description('Issue pairing codes to unknown users so the admin can approve them into the allowlist (the bootstrap path for the default closed mode)'),
|
|
38
41
|
streaming: z.boolean().default(false).description('If true, edit one Telegram message while tokens arrive; default off'),
|
|
39
42
|
streamEditIntervalMs: z.number().default(1200),
|
|
40
43
|
progressEnabled: z.boolean().default(true),
|
package/lib/file-manager.js
CHANGED
|
@@ -30,7 +30,7 @@ export function resolveSafePath(baseCwd, userPath = '.') {
|
|
|
30
30
|
const isDrivePath = /^[a-zA-Z]:/.test(cleanUser)
|
|
31
31
|
const rel = relative(base, target)
|
|
32
32
|
if (isAbsolute(cleanUser) || isDrivePath || rel.startsWith('..') || isAbsolute(rel) || (rel && resolve(base, rel) !== target)) {
|
|
33
|
-
const err = new Error('Access denied: path traversal out of workspace')
|
|
33
|
+
const err = /** @type {any} */ (new Error('Access denied: path traversal out of workspace'))
|
|
34
34
|
err.code = 'ERR_PATH_TRAVERSAL'
|
|
35
35
|
throw err
|
|
36
36
|
}
|
|
@@ -40,7 +40,7 @@ export function resolveSafePath(baseCwd, userPath = '.') {
|
|
|
40
40
|
try {
|
|
41
41
|
const realTarget = realpathSync(target)
|
|
42
42
|
if (!isSubpath(realBase, realTarget)) {
|
|
43
|
-
const err = new Error('Access denied: symlink resolves out of workspace')
|
|
43
|
+
const err = /** @type {any} */ (new Error('Access denied: symlink resolves out of workspace'))
|
|
44
44
|
err.code = 'ERR_PATH_TRAVERSAL'
|
|
45
45
|
throw err
|
|
46
46
|
}
|
|
@@ -52,7 +52,7 @@ export function resolveSafePath(baseCwd, userPath = '.') {
|
|
|
52
52
|
try {
|
|
53
53
|
const realCurr = realpathSync(curr)
|
|
54
54
|
if (!isSubpath(realBase, realCurr)) {
|
|
55
|
-
const err = new Error('Access denied: symlink ancestor resolves out of workspace')
|
|
55
|
+
const err = /** @type {any} */ (new Error('Access denied: symlink ancestor resolves out of workspace'))
|
|
56
56
|
err.code = 'ERR_PATH_TRAVERSAL'
|
|
57
57
|
throw err
|
|
58
58
|
}
|
|
@@ -86,6 +86,13 @@ export function resolveInside(base, candidate = '.') {
|
|
|
86
86
|
return resolveSafePath(base, candidate).target
|
|
87
87
|
}
|
|
88
88
|
|
|
89
|
+
// Hidden (dot) files are never served through the bot: they routinely carry
|
|
90
|
+
// secrets (.env, .npmrc, deploy keys). Any path segment starting with "." is
|
|
91
|
+
// rejected for /get and single-file /files lookups; listings already skip them.
|
|
92
|
+
function hasHiddenSegment(relativePath) {
|
|
93
|
+
return String(relativePath || '').split(/[\\/]/).some((segment) => segment.startsWith('.'))
|
|
94
|
+
}
|
|
95
|
+
|
|
89
96
|
export async function listFiles(baseCwd, subPath = '.', opts = {}) {
|
|
90
97
|
const { maxEntries = 50, showHidden = false } = opts
|
|
91
98
|
const target = resolveInside(baseCwd, subPath)
|
|
@@ -99,6 +106,9 @@ export async function listFiles(baseCwd, subPath = '.', opts = {}) {
|
|
|
99
106
|
}
|
|
100
107
|
|
|
101
108
|
if (!st.isDirectory()) {
|
|
109
|
+
if (hasHiddenSegment(relativePath)) {
|
|
110
|
+
return { ok: false, error: 'Hidden files are not accessible via the bot.' }
|
|
111
|
+
}
|
|
102
112
|
return {
|
|
103
113
|
ok: true,
|
|
104
114
|
isDirectory: false,
|
|
@@ -179,6 +189,9 @@ export async function listFiles(baseCwd, subPath = '.', opts = {}) {
|
|
|
179
189
|
export async function getFileForDownload(baseCwd, relativePath, maxBytes = 50 * 1024 * 1024) {
|
|
180
190
|
const target = resolveInside(baseCwd, relativePath)
|
|
181
191
|
const { relativePath: safeRel } = resolveSafePath(baseCwd, relativePath)
|
|
192
|
+
if (hasHiddenSegment(safeRel)) {
|
|
193
|
+
return { ok: false, error: 'Hidden files are not accessible via the bot.' }
|
|
194
|
+
}
|
|
182
195
|
let st
|
|
183
196
|
try {
|
|
184
197
|
st = await stat(target)
|
package/lib/forum-mirror.js
CHANGED
|
@@ -115,7 +115,7 @@ export async function mirrorSessionToForumTopic(gw, session) {
|
|
|
115
115
|
gw.ctx?.logger?.warn?.(`Failed to mirror session ${sessionId} to forum topic: ${err?.message || err}`)
|
|
116
116
|
}
|
|
117
117
|
}
|
|
118
|
-
export async function relayTurnToForumMirror(gw, session,
|
|
118
|
+
export async function relayTurnToForumMirror(gw, session, _event) {
|
|
119
119
|
if (!session || !session.id) return
|
|
120
120
|
const sessionId = String(session.id)
|
|
121
121
|
const threadInfo = gw.sessionToThread.get(sessionId)
|
package/lib/gateway-callbacks.js
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
|
-
import { escapeHtml } from './telegram-format.js'
|
|
2
1
|
import { t } from './locales/index.js'
|
|
3
2
|
import {
|
|
4
3
|
parseCallbackData, parseAskCallback, targetMatchesAsk,
|
|
5
4
|
releaseCallbacks, buildMultiSelectKeyboard, indexCallbacks, REMOVE_KEYBOARD
|
|
6
5
|
} from './ask.js'
|
|
7
6
|
import {
|
|
8
|
-
listModelCatalog, buildProvidersKeyboard, buildModelsKeyboard,
|
|
7
|
+
listModelCatalog, buildProvidersKeyboard, buildModelsKeyboard,
|
|
9
8
|
getStoredModelSelection
|
|
10
9
|
} from './models.js'
|
|
11
10
|
|
package/lib/gateway-commands.js
CHANGED
|
@@ -133,7 +133,7 @@ export async function handleGatewayCommand(gw, key, text, input) {
|
|
|
133
133
|
if (!res.updated) {
|
|
134
134
|
return reply(t('update.already_latest', { version: res.currentVersion }, locale))
|
|
135
135
|
}
|
|
136
|
-
return reply(t('update.success', { version: res.updatedVersion }, locale))
|
|
136
|
+
return reply(t('update.success', { version: /** @type {any} */ (res).updatedVersion }, locale))
|
|
137
137
|
} catch (err) {
|
|
138
138
|
return reply(t('update.failed', { error: err.message }, locale))
|
|
139
139
|
}
|
|
@@ -481,6 +481,9 @@ export async function handleGatewayCommand(gw, key, text, input) {
|
|
|
481
481
|
}
|
|
482
482
|
|
|
483
483
|
if (cmd === '/files') {
|
|
484
|
+
if (!gw.isUserAllowed(userId)) {
|
|
485
|
+
return reply(t('msg.not_allowed', {}, locale))
|
|
486
|
+
}
|
|
484
487
|
const subPath = parts.slice(1).join(' ').trim() || '.'
|
|
485
488
|
const agentCwd = (gw.resolveEffectiveCwdFor ? gw.resolveEffectiveCwdFor(chatId, threadId) : resolveEffectiveCwd(gw.config.agent?.cwd, gw.ctx?.logger))
|
|
486
489
|
const res = await handleFilesCommand(agentCwd, subPath)
|
|
@@ -488,6 +491,9 @@ export async function handleGatewayCommand(gw, key, text, input) {
|
|
|
488
491
|
}
|
|
489
492
|
|
|
490
493
|
if (cmd === '/get') {
|
|
494
|
+
if (!gw.isUserAllowed(userId)) {
|
|
495
|
+
return reply(t('msg.not_allowed', {}, locale))
|
|
496
|
+
}
|
|
491
497
|
const targetRel = parts.slice(1).join(' ').trim()
|
|
492
498
|
const agentCwd = (gw.resolveEffectiveCwdFor ? gw.resolveEffectiveCwdFor(chatId, threadId) : resolveEffectiveCwd(gw.config.agent?.cwd, gw.ctx?.logger))
|
|
493
499
|
const maxDocBytes = Number(gw.config.media?.maxDocBytes) || 50 * 1024 * 1024
|
|
@@ -827,7 +833,7 @@ export async function handleGatewayCommand(gw, key, text, input) {
|
|
|
827
833
|
].join('\n'))
|
|
828
834
|
}
|
|
829
835
|
const dueAt = Date.now() + delayMs
|
|
830
|
-
|
|
836
|
+
await gw.scheduler.schedule({
|
|
831
837
|
platform: platform || 'telegram',
|
|
832
838
|
chatId,
|
|
833
839
|
threadId: threadId || 0,
|
package/lib/gateway-turn.js
CHANGED
|
@@ -2,17 +2,17 @@ import { readFile } from 'node:fs/promises'
|
|
|
2
2
|
import { createUserMessage } from '@deepseek-ai/dsh-llm'
|
|
3
3
|
import { ensureContentArray } from './content-guard.js'
|
|
4
4
|
import { getPersona } from './personas.js'
|
|
5
|
-
import { MESSENGER_RELAY_INSTRUCTION,
|
|
5
|
+
import { MESSENGER_RELAY_INSTRUCTION, splitText } from './text.js'
|
|
6
6
|
import { formatInboundDocument, documentOnlyHint, parseDocument } from './documents.js'
|
|
7
7
|
import { t } from './locales/index.js'
|
|
8
|
-
import {
|
|
8
|
+
import { processDiagramsAndTablesAsync } from './artifacts.js'
|
|
9
9
|
import { prepareTtsText, toTelegramVoiceFile } from './tts.js'
|
|
10
10
|
import { shouldSpeakReply } from './voice-prefs.js'
|
|
11
11
|
import { speakText, transcribeVoice } from './integrations.js'
|
|
12
12
|
import { attachInboundPhoto, photoOnlyHint } from './photos.js'
|
|
13
13
|
import { buildOutboundFiles, stripImageUrls } from './outbound.js'
|
|
14
14
|
import {
|
|
15
|
-
buildStreamPreview, formatProgressLine, createEditScheduler, startTypingHeartbeat,
|
|
15
|
+
buildStreamPreview, formatProgressLine, createEditScheduler, startTypingHeartbeat, formatReasoningFinal
|
|
16
16
|
} from './stream.js'
|
|
17
17
|
import { escapeHtml } from './telegram-format.js'
|
|
18
18
|
import { formatCostFooter, normalizeUsage, extractSessionStats, calculateEstimatedCostUsd, checkBudgetThreshold } from './cost-tracker.js'
|
|
@@ -279,10 +279,10 @@ export async function runGatewayTurn(gw, chat, input, signal) {
|
|
|
279
279
|
|
|
280
280
|
|
|
281
281
|
const content = await gw.buildUserContent(input, signal)
|
|
282
|
-
chat.agent.followup(createUserMessage({
|
|
282
|
+
chat.agent.followup(createUserMessage(/** @type {any} */ ({
|
|
283
283
|
content: ensureContentArray(content),
|
|
284
284
|
source: { kind: 'user', plugin: PLUGIN, form: 'relay', origin: 'telegram' },
|
|
285
|
-
}))
|
|
285
|
+
})))
|
|
286
286
|
const turnTimeoutMs = Number(gw.config.agent?.turnTimeoutMs) || 600_000
|
|
287
287
|
await whenIdleWithTimeout(chat.agent, turnTimeoutMs, signal)
|
|
288
288
|
if (signal.aborted) {
|
|
@@ -310,7 +310,7 @@ export async function runGatewayTurn(gw, chat, input, signal) {
|
|
|
310
310
|
chatId: input.chatId,
|
|
311
311
|
webAppUrl: gw.resolveWebAppUrl?.() || '',
|
|
312
312
|
})
|
|
313
|
-
|
|
313
|
+
let answer = processed.text
|
|
314
314
|
if (collector.reason?.kind === 'error') {
|
|
315
315
|
const err = collector.reason.error
|
|
316
316
|
const msg = t('msg.agent_error', { code: err?.code || 'error', message: err?.message || 'unknown' }, gw.resolveLocale(input))
|
package/lib/gateway.js
CHANGED
|
@@ -203,7 +203,7 @@ export class Gateway {
|
|
|
203
203
|
|
|
204
204
|
isUserAllowed(userId) {
|
|
205
205
|
const ids = this.effectiveAllowedIds()
|
|
206
|
-
const mode = this.tg()?.allowlistMode || '
|
|
206
|
+
const mode = this.tg()?.allowlistMode || 'closed'
|
|
207
207
|
if (mode === 'closed') {
|
|
208
208
|
return ids.length > 0 && ids.includes(Number(userId))
|
|
209
209
|
}
|
|
@@ -306,7 +306,7 @@ export class Gateway {
|
|
|
306
306
|
this.adapterList = this.adapterList.filter((item) => item !== adapter)
|
|
307
307
|
if (this.tgAdapter === adapter) this.tgAdapter = undefined
|
|
308
308
|
}
|
|
309
|
-
if ((this.tg()?.allowlistMode || '
|
|
309
|
+
if ((this.tg()?.allowlistMode || 'closed') === 'open' && this.effectiveAllowedIds().length === 0) {
|
|
310
310
|
this.ctx.logger?.warn?.('[dsh-messenger-gateway] telegram allowlist is empty in "open" mode: the bot will accept messages from any Telegram user.')
|
|
311
311
|
}
|
|
312
312
|
for (const adapter of adapters) {
|
|
@@ -457,7 +457,7 @@ export class Gateway {
|
|
|
457
457
|
}
|
|
458
458
|
|
|
459
459
|
async handleMessage(input) {
|
|
460
|
-
const {
|
|
460
|
+
const { text, reply } = input
|
|
461
461
|
const key = this.sessionKeyFor(input)
|
|
462
462
|
const body = String(text || '').trim()
|
|
463
463
|
let attachments = [...(input.attachments || [])]
|
|
@@ -544,10 +544,10 @@ export class Gateway {
|
|
|
544
544
|
text: steerText,
|
|
545
545
|
steer: true,
|
|
546
546
|
}, undefined)
|
|
547
|
-
chat.agent.followup(createUserMessage({
|
|
547
|
+
chat.agent.followup(createUserMessage(/** @type {any} */ ({
|
|
548
548
|
content: ensureContentArray(content),
|
|
549
549
|
source: { kind: 'user', plugin: PLUGIN, form: 'steer', origin: 'telegram' },
|
|
550
|
-
}))
|
|
550
|
+
})))
|
|
551
551
|
chat.lastUsed = Date.now()
|
|
552
552
|
try { await reply(t('msg.steer_added', {}, this.resolveLocale(input))) } catch (err) { this.recordApiFailure('reply.steer_added', err) }
|
|
553
553
|
return
|
package/lib/http.js
CHANGED
|
@@ -3,7 +3,7 @@ import { timingSafeEqual } from 'node:crypto'
|
|
|
3
3
|
export async function readBody(req, maxBytes = 1_048_576) {
|
|
4
4
|
const cl = Number(req?.headers?.['content-length'])
|
|
5
5
|
if (Number.isFinite(cl) && cl > maxBytes) {
|
|
6
|
-
const err = new Error(`Payload Too Large: content-length ${cl} exceeds ${maxBytes}`)
|
|
6
|
+
const err = /** @type {any} */ (new Error(`Payload Too Large: content-length ${cl} exceeds ${maxBytes}`))
|
|
7
7
|
err.status = 413
|
|
8
8
|
err.statusCode = 413
|
|
9
9
|
throw err
|
|
@@ -13,7 +13,7 @@ export async function readBody(req, maxBytes = 1_048_576) {
|
|
|
13
13
|
for await (const chunk of req) {
|
|
14
14
|
total += chunk.length
|
|
15
15
|
if (total > maxBytes) {
|
|
16
|
-
const err = new Error(`Payload Too Large: exceeded ${maxBytes} bytes`)
|
|
16
|
+
const err = /** @type {any} */ (new Error(`Payload Too Large: exceeded ${maxBytes} bytes`))
|
|
17
17
|
err.status = 413
|
|
18
18
|
err.statusCode = 413
|
|
19
19
|
throw err
|
|
@@ -88,9 +88,33 @@ export function getConnection(ctx) {
|
|
|
88
88
|
}
|
|
89
89
|
}
|
|
90
90
|
|
|
91
|
-
|
|
91
|
+
// Loopback hostnames allowed in the Host/Origin/Referer headers for requests
|
|
92
|
+
// trusted by loopback remote address. DNS rebinding serves evil.com from
|
|
93
|
+
// 127.0.0.1: Host and Origin would match each other but the hostname is not in
|
|
94
|
+
// this pin-list, so the request is rejected (#198). Ports are ignored — the
|
|
95
|
+
// profile port is not known to the auth layer.
|
|
96
|
+
const LOOPBACK_HOSTNAMES = new Set(['localhost', '127.0.0.1', '::1', '::ffff:127.0.0.1'])
|
|
97
|
+
|
|
98
|
+
export function isPinnedLoopbackHost(hostHeader) {
|
|
99
|
+
const raw = String(hostHeader || '').toLowerCase().trim()
|
|
100
|
+
if (!raw) return false
|
|
101
|
+
let name = raw
|
|
102
|
+
if (name.startsWith('[')) {
|
|
103
|
+
const end = name.indexOf(']')
|
|
104
|
+
if (end === -1) return false
|
|
105
|
+
name = name.slice(1, end)
|
|
106
|
+
} else {
|
|
107
|
+
const colon = name.indexOf(':')
|
|
108
|
+
if (colon !== -1) name = name.slice(0, colon)
|
|
109
|
+
}
|
|
110
|
+
return LOOPBACK_HOSTNAMES.has(name)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export function isTrustedSettingsRequest(req, expectedSecret, ctx = null, { trustProxy = false } = {}) {
|
|
92
114
|
const remote = req?.socket?.remoteAddress
|
|
93
|
-
|
|
115
|
+
// Never trust x-forwarded-host: it is fully attacker-controlled unless the
|
|
116
|
+
// operator explicitly enables trustProxy behind a local reverse proxy.
|
|
117
|
+
const host = String(req?.headers?.host || '')
|
|
94
118
|
if (!host) return false
|
|
95
119
|
|
|
96
120
|
const site = String(req?.headers?.['sec-fetch-site'] || '').toLowerCase()
|
|
@@ -115,14 +139,17 @@ export function isTrustedSettingsRequest(req, expectedSecret, ctx = null) {
|
|
|
115
139
|
return false
|
|
116
140
|
}
|
|
117
141
|
|
|
118
|
-
// 2. Local loopback remote address (CLI, tests, local host processes)
|
|
142
|
+
// 2. Local loopback remote address (CLI, tests, local host processes):
|
|
143
|
+
// Host and Origin must be pinned loopback hostnames (DNS rebinding defense).
|
|
119
144
|
if (remote !== undefined && isLoopback(remote)) {
|
|
145
|
+
if (!trustProxy && !isPinnedLoopbackHost(host)) return false
|
|
120
146
|
const origin = String(req?.headers?.origin || '')
|
|
121
147
|
if (origin) {
|
|
122
148
|
try {
|
|
123
149
|
const url = new URL(origin)
|
|
124
150
|
if (url.protocol !== 'http:' && url.protocol !== 'https:') return false
|
|
125
|
-
if (
|
|
151
|
+
if (!trustProxy && !isPinnedLoopbackHost(url.host)) return false
|
|
152
|
+
if (trustProxy && url.host.toLowerCase() !== host.toLowerCase() && !isLoopback(url.hostname)) return false
|
|
126
153
|
} catch {
|
|
127
154
|
return false
|
|
128
155
|
}
|
|
@@ -132,7 +159,8 @@ export function isTrustedSettingsRequest(req, expectedSecret, ctx = null) {
|
|
|
132
159
|
try {
|
|
133
160
|
const url = new URL(referer)
|
|
134
161
|
if (url.protocol !== 'http:' && url.protocol !== 'https:') return false
|
|
135
|
-
if (
|
|
162
|
+
if (!trustProxy && !isPinnedLoopbackHost(url.host)) return false
|
|
163
|
+
if (trustProxy && url.host.toLowerCase() !== host.toLowerCase() && !isLoopback(url.hostname)) return false
|
|
136
164
|
} catch {
|
|
137
165
|
return false
|
|
138
166
|
}
|
|
@@ -147,7 +175,7 @@ export function isTrustedSettingsRequest(req, expectedSecret, ctx = null) {
|
|
|
147
175
|
try {
|
|
148
176
|
const url = new URL(origin)
|
|
149
177
|
if (url.protocol !== 'http:' && url.protocol !== 'https:') return false
|
|
150
|
-
return url.host
|
|
178
|
+
return isPinnedLoopbackHost(url.host) && isPinnedLoopbackHost(host)
|
|
151
179
|
} catch {
|
|
152
180
|
return false
|
|
153
181
|
}
|
|
@@ -157,7 +185,7 @@ export function isTrustedSettingsRequest(req, expectedSecret, ctx = null) {
|
|
|
157
185
|
try {
|
|
158
186
|
const url = new URL(referer)
|
|
159
187
|
if (url.protocol !== 'http:' && url.protocol !== 'https:') return false
|
|
160
|
-
return url.host
|
|
188
|
+
return isPinnedLoopbackHost(url.host) && isPinnedLoopbackHost(host)
|
|
161
189
|
} catch {
|
|
162
190
|
return false
|
|
163
191
|
}
|
|
@@ -212,7 +240,7 @@ export function isTrustedSettingsRequest(req, expectedSecret, ctx = null) {
|
|
|
212
240
|
return false
|
|
213
241
|
}
|
|
214
242
|
|
|
215
|
-
export function isAuthorizedMessengerRequest(req, webhooksConfig, ctx = null) {
|
|
243
|
+
export function isAuthorizedMessengerRequest(req, webhooksConfig, ctx = null, { trustProxy = false } = {}) {
|
|
216
244
|
const site = String(req?.headers?.['sec-fetch-site'] || '').toLowerCase()
|
|
217
245
|
if (site === 'cross-site') return false
|
|
218
246
|
|
|
@@ -227,7 +255,7 @@ export function isAuthorizedMessengerRequest(req, webhooksConfig, ctx = null) {
|
|
|
227
255
|
}
|
|
228
256
|
}
|
|
229
257
|
|
|
230
|
-
const host = String(req?.headers?.host ||
|
|
258
|
+
const host = String(req?.headers?.host || '')
|
|
231
259
|
const hostName = host.split(':')[0].toLowerCase().replace(/^\[|\]$/g, '')
|
|
232
260
|
const remote = req?.socket?.remoteAddress
|
|
233
261
|
|
|
@@ -236,6 +264,18 @@ export function isAuthorizedMessengerRequest(req, webhooksConfig, ctx = null) {
|
|
|
236
264
|
}
|
|
237
265
|
|
|
238
266
|
if (remote !== undefined && isLoopback(remote)) {
|
|
267
|
+
// DNS rebinding defense (#198): the Host header must be a pinned loopback
|
|
268
|
+
// name; a matched attacker domain resolving to 127.0.0.1 is rejected.
|
|
269
|
+
if (!trustProxy && !isPinnedLoopbackHost(host)) return false
|
|
270
|
+
const origin = String(req?.headers?.origin || '')
|
|
271
|
+
if (origin) {
|
|
272
|
+
try {
|
|
273
|
+
const url = new URL(origin)
|
|
274
|
+
if (!trustProxy && !isPinnedLoopbackHost(url.host)) return false
|
|
275
|
+
} catch {
|
|
276
|
+
return false
|
|
277
|
+
}
|
|
278
|
+
}
|
|
239
279
|
return true
|
|
240
280
|
}
|
|
241
281
|
|
|
@@ -244,7 +284,7 @@ export function isAuthorizedMessengerRequest(req, webhooksConfig, ctx = null) {
|
|
|
244
284
|
if (origin) {
|
|
245
285
|
try {
|
|
246
286
|
const url = new URL(origin)
|
|
247
|
-
return url.host
|
|
287
|
+
return isPinnedLoopbackHost(url.host) && isPinnedLoopbackHost(host)
|
|
248
288
|
} catch {
|
|
249
289
|
return false
|
|
250
290
|
}
|
package/lib/index.js
CHANGED
|
@@ -136,7 +136,7 @@ function registerMessengerRoute(ctx, getGw, path, action, source) {
|
|
|
136
136
|
kind: 'exact', path,
|
|
137
137
|
handler: async (req, res) => {
|
|
138
138
|
if (req.method !== 'POST') return writeJson(res, 405, { ok: false, error: 'POST only' })
|
|
139
|
-
if (!isAuthorizedMessengerRequest(req, source?.()?.webhooks, ctx)) {
|
|
139
|
+
if (!isAuthorizedMessengerRequest(req, source?.()?.webhooks, ctx, { trustProxy: source?.()?.security?.trustProxy === true })) {
|
|
140
140
|
return writeJson(res, 403, { ok: false, error: 'forbidden' })
|
|
141
141
|
}
|
|
142
142
|
let payload
|
|
@@ -168,7 +168,6 @@ export function apply(ctx, config) {
|
|
|
168
168
|
let gateway
|
|
169
169
|
let source = () => entry
|
|
170
170
|
let settingsApi
|
|
171
|
-
const turnStarts = new Map()
|
|
172
171
|
const getWebServer = () => ctx.get?.('webServer') || ctx.webServer
|
|
173
172
|
|
|
174
173
|
// Секреты (botToken и т. п.) не отдаются браузеру, а карточка сохраняет секции
|
|
@@ -559,7 +558,7 @@ export function apply(ctx, config) {
|
|
|
559
558
|
kind: 'exact', path: '/dsh-messenger-gateway/status',
|
|
560
559
|
handler: async (req, res) => {
|
|
561
560
|
if (req.method !== 'GET') return writeJson(res, 405, { ok: false, error: 'GET only' })
|
|
562
|
-
if (!isTrustedSettingsRequest(req, source().webhooks?.secret, ctx)) return writeJson(res, 403, { ok: false, error: 'forbidden' })
|
|
561
|
+
if (!isTrustedSettingsRequest(req, source().webhooks?.secret, ctx, { trustProxy: source().security?.trustProxy === true })) return writeJson(res, 403, { ok: false, error: 'forbidden' })
|
|
563
562
|
const gw = getGw()
|
|
564
563
|
const botInfo = gw?.getBotInfo?.() || {}
|
|
565
564
|
const uptimeSec = gw?.stats?.startedAt ? Math.max(0, Math.round((Date.now() - gw.stats.startedAt) / 1000)) : 0
|
|
@@ -567,6 +566,8 @@ export function apply(ctx, config) {
|
|
|
567
566
|
writeJson(res, 200, {
|
|
568
567
|
ok: true,
|
|
569
568
|
running: Boolean(gw),
|
|
569
|
+
allowlistMode: source().telegram?.allowlistMode || 'closed',
|
|
570
|
+
allowlistCount: (source().telegram?.allowedUserIds || []).length,
|
|
570
571
|
adapters: gw?.messenger.adapters() || [],
|
|
571
572
|
activeChats: gw?.messenger.activeChats() || 0,
|
|
572
573
|
ttsEnabled: Boolean(source().tts?.enabled),
|
|
@@ -598,7 +599,7 @@ export function apply(ctx, config) {
|
|
|
598
599
|
kind: 'exact', path: '/dsh-messenger-gateway/smoke',
|
|
599
600
|
handler: async (req, res) => {
|
|
600
601
|
if (req.method !== 'POST') return writeJson(res, 405, { ok: false, error: 'POST only' })
|
|
601
|
-
if (!isTrustedSettingsRequest(req, source().webhooks?.secret, ctx)) return writeJson(res, 403, { ok: false, error: 'forbidden' })
|
|
602
|
+
if (!isTrustedSettingsRequest(req, source().webhooks?.secret, ctx, { trustProxy: source().security?.trustProxy === true })) return writeJson(res, 403, { ok: false, error: 'forbidden' })
|
|
602
603
|
const gw = getGw()
|
|
603
604
|
if (!gw) return writeJson(res, 503, { ok: false, error: 'gateway not running' })
|
|
604
605
|
const parsed = await readJsonSafe(req, res, 65536)
|
|
@@ -674,7 +675,7 @@ export function apply(ctx, config) {
|
|
|
674
675
|
kind: 'exact', path: '/dsh-messenger-gateway/config',
|
|
675
676
|
handler: async (req, res) => {
|
|
676
677
|
if (req.method !== 'GET' && req.method !== 'PUT') return writeJson(res, 405, { ok: false, error: 'GET or PUT' })
|
|
677
|
-
if (!isTrustedSettingsRequest(req, source().webhooks?.secret, ctx)) return writeJson(res, 403, { ok: false, error: 'forbidden' })
|
|
678
|
+
if (!isTrustedSettingsRequest(req, source().webhooks?.secret, ctx, { trustProxy: source().security?.trustProxy === true })) return writeJson(res, 403, { ok: false, error: 'forbidden' })
|
|
678
679
|
if (req.method === 'GET') return writeJson(res, 200, { ok: true, config: publicConfig(source(), getGw(), ctx) })
|
|
679
680
|
if (!settingsApi?.isReady?.()) return writeJson(res, 503, { ok: false, error: 'settings not ready' })
|
|
680
681
|
const parsedConfig = await readJsonSafe(req, res, 1_048_576)
|
|
@@ -717,7 +718,7 @@ export function apply(ctx, config) {
|
|
|
717
718
|
kind: 'exact', path: '/dsh-messenger-gateway/pairing',
|
|
718
719
|
handler: async (req, res) => {
|
|
719
720
|
if (req.method !== 'GET') return writeJson(res, 405, { ok: false, error: 'GET only' })
|
|
720
|
-
if (!isTrustedSettingsRequest(req, source().webhooks?.secret, ctx)) return writeJson(res, 403, { ok: false, error: 'forbidden' })
|
|
721
|
+
if (!isTrustedSettingsRequest(req, source().webhooks?.secret, ctx, { trustProxy: source().security?.trustProxy === true })) return writeJson(res, 403, { ok: false, error: 'forbidden' })
|
|
721
722
|
const gw = getGw()
|
|
722
723
|
if (!gw) return writeJson(res, 503, { ok: false, error: 'gateway not running' })
|
|
723
724
|
writeJson(res, 200, {
|
|
@@ -732,7 +733,7 @@ export function apply(ctx, config) {
|
|
|
732
733
|
kind: 'exact', path: '/dsh-messenger-gateway/pairing/approve',
|
|
733
734
|
handler: async (req, res) => {
|
|
734
735
|
if (req.method !== 'POST') return writeJson(res, 405, { ok: false, error: 'POST only' })
|
|
735
|
-
if (!isTrustedSettingsRequest(req, source().webhooks?.secret, ctx)) return writeJson(res, 403, { ok: false, error: 'forbidden' })
|
|
736
|
+
if (!isTrustedSettingsRequest(req, source().webhooks?.secret, ctx, { trustProxy: source().security?.trustProxy === true })) return writeJson(res, 403, { ok: false, error: 'forbidden' })
|
|
736
737
|
const gw = getGw()
|
|
737
738
|
if (!gw) return writeJson(res, 503, { ok: false, error: 'gateway not running' })
|
|
738
739
|
const parsed = await readJsonSafe(req, res, 65536)
|
|
@@ -746,7 +747,7 @@ export function apply(ctx, config) {
|
|
|
746
747
|
kind: 'exact', path: '/dsh-messenger-gateway/pairing/reject',
|
|
747
748
|
handler: async (req, res) => {
|
|
748
749
|
if (req.method !== 'POST') return writeJson(res, 405, { ok: false, error: 'POST only' })
|
|
749
|
-
if (!isTrustedSettingsRequest(req, source().webhooks?.secret, ctx)) return writeJson(res, 403, { ok: false, error: 'forbidden' })
|
|
750
|
+
if (!isTrustedSettingsRequest(req, source().webhooks?.secret, ctx, { trustProxy: source().security?.trustProxy === true })) return writeJson(res, 403, { ok: false, error: 'forbidden' })
|
|
750
751
|
const gw = getGw()
|
|
751
752
|
if (!gw) return writeJson(res, 503, { ok: false, error: 'gateway not running' })
|
|
752
753
|
const parsed = await readJsonSafe(req, res, 65536)
|
package/lib/memory-brain.js
CHANGED
|
@@ -149,6 +149,7 @@ export async function callMemoryMcp(rawConfig, toolName, args, signal) {
|
|
|
149
149
|
}
|
|
150
150
|
}
|
|
151
151
|
|
|
152
|
+
/** @param {any} opts */
|
|
152
153
|
export async function listUserMemories({ config, userId, limit = 20, signal }) {
|
|
153
154
|
if (!userId) return { ok: false, error: 'missing_user_id', items: [] }
|
|
154
155
|
const scope = `user:${userId}`
|
|
@@ -160,6 +161,7 @@ export async function listUserMemories({ config, userId, limit = 20, signal }) {
|
|
|
160
161
|
return { ok: true, items, raw: res.text }
|
|
161
162
|
}
|
|
162
163
|
|
|
164
|
+
/** @param {any} opts */
|
|
163
165
|
export async function recallUserMemories({ config, userId, query = '', budget, signal }) {
|
|
164
166
|
if (!userId) return ''
|
|
165
167
|
const scope = `user:${userId}`
|
|
@@ -184,6 +186,7 @@ export async function recallUserMemories({ config, userId, query = '', budget, s
|
|
|
184
186
|
return formatMemoryContext(res.text, userId)
|
|
185
187
|
}
|
|
186
188
|
|
|
189
|
+
/** @param {any} opts */
|
|
187
190
|
export async function rememberUserFact({ config, userId, content, category = 'preference', signal }) {
|
|
188
191
|
if (!userId) return { ok: false, error: 'missing_user_id' }
|
|
189
192
|
const text = String(content || '').trim()
|
|
@@ -211,6 +214,7 @@ export async function rememberUserFact({ config, userId, content, category = 'pr
|
|
|
211
214
|
return { ok: true, memoryId, text: res.text }
|
|
212
215
|
}
|
|
213
216
|
|
|
217
|
+
/** @param {any} opts */
|
|
214
218
|
export async function forgetUserMemory({ config, userId, memoryId, signal }) {
|
|
215
219
|
if (!userId) return { ok: false, error: 'missing_user_id' }
|
|
216
220
|
const target = String(memoryId || '').trim()
|
|
@@ -248,7 +252,8 @@ export async function forgetUserMemory({ config, userId, memoryId, signal }) {
|
|
|
248
252
|
return res
|
|
249
253
|
}
|
|
250
254
|
|
|
251
|
-
|
|
255
|
+
/** @param {any} opts */
|
|
256
|
+
export async function recordTurnMemory({ config, userId, userText, assistantText: _assistantText, signal, logger }) {
|
|
252
257
|
const extracted = extractConversationalPreferences(userText)
|
|
253
258
|
if (!extracted) return { ok: true, skipped: true }
|
|
254
259
|
|
package/lib/messenger-api.js
CHANGED
|
@@ -41,7 +41,7 @@ export function parseMessengerBody(raw) {
|
|
|
41
41
|
try {
|
|
42
42
|
return JSON.parse(String(raw || '{}') || '{}')
|
|
43
43
|
} catch {
|
|
44
|
-
const err = new Error('invalid json')
|
|
44
|
+
const err = /** @type {any} */ (new Error('invalid json'))
|
|
45
45
|
err.status = 400
|
|
46
46
|
throw err
|
|
47
47
|
}
|
|
@@ -49,13 +49,13 @@ export function parseMessengerBody(raw) {
|
|
|
49
49
|
|
|
50
50
|
export function validateTarget(target) {
|
|
51
51
|
if (!target || typeof target !== 'object') {
|
|
52
|
-
const err = new Error('target is required')
|
|
52
|
+
const err = /** @type {any} */ (new Error('target is required'))
|
|
53
53
|
err.status = 400
|
|
54
54
|
throw err
|
|
55
55
|
}
|
|
56
56
|
const platform = String(target.platform || '').trim()
|
|
57
57
|
if (!platform) {
|
|
58
|
-
const err = new Error('target.platform is required')
|
|
58
|
+
const err = /** @type {any} */ (new Error('target.platform is required'))
|
|
59
59
|
err.status = 400
|
|
60
60
|
throw err
|
|
61
61
|
}
|
|
@@ -74,13 +74,13 @@ export function validateTarget(target) {
|
|
|
74
74
|
export function normalizeButtons(buttons) {
|
|
75
75
|
if (buttons === undefined || buttons === null) return []
|
|
76
76
|
if (!Array.isArray(buttons)) {
|
|
77
|
-
const err = new Error('buttons must be a 2d array')
|
|
77
|
+
const err = /** @type {any} */ (new Error('buttons must be a 2d array'))
|
|
78
78
|
err.status = 400
|
|
79
79
|
throw err
|
|
80
80
|
}
|
|
81
81
|
return buttons.map((row, ri) => {
|
|
82
82
|
if (!Array.isArray(row)) {
|
|
83
|
-
const err = new Error(`buttons[${ri}] must be an array`)
|
|
83
|
+
const err = /** @type {any} */ (new Error(`buttons[${ri}] must be an array`))
|
|
84
84
|
err.status = 400
|
|
85
85
|
throw err
|
|
86
86
|
}
|
|
@@ -88,7 +88,7 @@ export function normalizeButtons(buttons) {
|
|
|
88
88
|
const id = String(btn?.id ?? btn?.buttonId ?? '').trim()
|
|
89
89
|
const text = String(btn?.text ?? '').trim()
|
|
90
90
|
if (!id || !text) {
|
|
91
|
-
const err = new Error(`buttons[${ri}][${bi}] requires id and text`)
|
|
91
|
+
const err = /** @type {any} */ (new Error(`buttons[${ri}][${bi}] requires id and text`))
|
|
92
92
|
err.status = 400
|
|
93
93
|
throw err
|
|
94
94
|
}
|
|
@@ -100,13 +100,13 @@ export function normalizeButtons(buttons) {
|
|
|
100
100
|
export function normalizeFiles(files) {
|
|
101
101
|
if (!files) return []
|
|
102
102
|
if (!Array.isArray(files)) {
|
|
103
|
-
const err = new Error('files must be an array')
|
|
103
|
+
const err = /** @type {any} */ (new Error('files must be an array'))
|
|
104
104
|
err.status = 400
|
|
105
105
|
throw err
|
|
106
106
|
}
|
|
107
107
|
return files.map((file, i) => {
|
|
108
108
|
if (!file || typeof file !== 'object') {
|
|
109
|
-
const err = new Error(`files[${i}] must be an object`)
|
|
109
|
+
const err = /** @type {any} */ (new Error(`files[${i}] must be an object`))
|
|
110
110
|
err.status = 400
|
|
111
111
|
throw err
|
|
112
112
|
}
|
|
@@ -122,7 +122,7 @@ export function normalizeFiles(files) {
|
|
|
122
122
|
buf = Buffer.from(file.bytes, 'utf8')
|
|
123
123
|
}
|
|
124
124
|
if (!buf) {
|
|
125
|
-
const err = new Error(`files[${i}].bytes must be a Buffer, Uint8Array, or array of bytes`)
|
|
125
|
+
const err = /** @type {any} */ (new Error(`files[${i}].bytes must be a Buffer, Uint8Array, or array of bytes`))
|
|
126
126
|
err.status = 400
|
|
127
127
|
throw err
|
|
128
128
|
}
|
|
@@ -141,7 +141,7 @@ export function normalizeFiles(files) {
|
|
|
141
141
|
name: file.name || 'file',
|
|
142
142
|
}
|
|
143
143
|
}
|
|
144
|
-
const err = new Error(`files[${i}] needs bytes or dataBase64`)
|
|
144
|
+
const err = /** @type {any} */ (new Error(`files[${i}] needs bytes or dataBase64`))
|
|
145
145
|
err.status = 400
|
|
146
146
|
throw err
|
|
147
147
|
})
|
|
@@ -151,7 +151,7 @@ export function normalizeSendBody(payload) {
|
|
|
151
151
|
const text = typeof payload?.text === 'string' ? payload.text.trim() : ''
|
|
152
152
|
const files = normalizeFiles(payload?.files)
|
|
153
153
|
if (!text && !files.length) {
|
|
154
|
-
const err = new Error('text or files required')
|
|
154
|
+
const err = /** @type {any} */ (new Error('text or files required'))
|
|
155
155
|
err.status = 400
|
|
156
156
|
throw err
|
|
157
157
|
}
|
|
@@ -165,7 +165,7 @@ export function normalizeSendBody(payload) {
|
|
|
165
165
|
export function normalizeAskBody(payload) {
|
|
166
166
|
const text = String(payload?.text || '').trim()
|
|
167
167
|
if (!text) {
|
|
168
|
-
const err = new Error('text is required for ask')
|
|
168
|
+
const err = /** @type {any} */ (new Error('text is required for ask'))
|
|
169
169
|
err.status = 400
|
|
170
170
|
throw err
|
|
171
171
|
}
|
|
@@ -173,7 +173,7 @@ export function normalizeAskBody(payload) {
|
|
|
173
173
|
if (mode === 'multi' || (Array.isArray(payload?.options) && payload.options.length > 0)) {
|
|
174
174
|
const rawOptions = Array.isArray(payload?.options) ? payload.options : (Array.isArray(payload?.buttons) ? payload.buttons : [])
|
|
175
175
|
if (!rawOptions.length || (Array.isArray(rawOptions[0]) && !rawOptions.some((r) => r.length > 0))) {
|
|
176
|
-
const err = new Error('ask requires at least one option')
|
|
176
|
+
const err = /** @type {any} */ (new Error('ask requires at least one option'))
|
|
177
177
|
err.status = 400
|
|
178
178
|
throw err
|
|
179
179
|
}
|
|
@@ -189,7 +189,7 @@ export function normalizeAskBody(payload) {
|
|
|
189
189
|
}
|
|
190
190
|
const buttons = normalizeButtons(payload?.buttons)
|
|
191
191
|
if (!buttons.length || !buttons.some((row) => row.length > 0)) {
|
|
192
|
-
const err = new Error('ask requires at least one button')
|
|
192
|
+
const err = /** @type {any} */ (new Error('ask requires at least one button'))
|
|
193
193
|
err.status = 400
|
|
194
194
|
throw err
|
|
195
195
|
}
|
|
@@ -199,7 +199,7 @@ export function normalizeAskBody(payload) {
|
|
|
199
199
|
export function normalizeProgressBody(payload) {
|
|
200
200
|
const text = String(payload?.text || '').trim()
|
|
201
201
|
if (!text) {
|
|
202
|
-
const err = new Error('text is required for progress')
|
|
202
|
+
const err = /** @type {any} */ (new Error('text is required for progress'))
|
|
203
203
|
err.status = 400
|
|
204
204
|
throw err
|
|
205
205
|
}
|
|
@@ -223,7 +223,7 @@ export function httpStatusForError(err) {
|
|
|
223
223
|
|
|
224
224
|
export async function dispatchMessenger(gw, action, payload) {
|
|
225
225
|
if (!gw) {
|
|
226
|
-
const err = new Error('gateway not running')
|
|
226
|
+
const err = /** @type {any} */ (new Error('gateway not running'))
|
|
227
227
|
err.status = 503
|
|
228
228
|
throw err
|
|
229
229
|
}
|
|
@@ -240,7 +240,7 @@ export async function dispatchMessenger(gw, action, payload) {
|
|
|
240
240
|
const result = await gw.messenger.ask(target, normalizeAskBody(payload), resolveAskTimeoutMs(payload?.timeoutMs))
|
|
241
241
|
return { ok: true, result }
|
|
242
242
|
}
|
|
243
|
-
const err = new Error(`unknown messenger action: ${action}`)
|
|
243
|
+
const err = /** @type {any} */ (new Error(`unknown messenger action: ${action}`))
|
|
244
244
|
err.status = 400
|
|
245
245
|
throw err
|
|
246
246
|
}
|
package/lib/pairing.js
CHANGED
|
@@ -24,6 +24,7 @@ function writeJsonAtomicSync(filePath, data) {
|
|
|
24
24
|
}
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
+
/** @param {string} filePath @param {any} [opts] */
|
|
27
28
|
export function createPairingStore(filePath, { logger } = {}) {
|
|
28
29
|
const state = { pending: {}, /** @type {number[]} */ approved: [] }
|
|
29
30
|
if (filePath && existsSync(filePath)) {
|
|
@@ -79,12 +80,12 @@ export function createPairingStore(filePath, { logger } = {}) {
|
|
|
79
80
|
}
|
|
80
81
|
const recent = Object.values(state.pending).find((r) => Number(r.userId) === uid && Date.now() - Number(r.createdAt || 0) < 600_000)
|
|
81
82
|
if (recent) {
|
|
82
|
-
const err = new Error('pairing rate limited')
|
|
83
|
+
const err = /** @type {any} */ (new Error('pairing rate limited'))
|
|
83
84
|
err.code = 'RATE_LIMIT'
|
|
84
85
|
throw err
|
|
85
86
|
}
|
|
86
87
|
if (Object.keys(state.pending).length >= 20) {
|
|
87
|
-
const err = new Error('too many pending pairing codes')
|
|
88
|
+
const err = /** @type {any} */ (new Error('too many pending pairing codes'))
|
|
88
89
|
err.code = 'FULL'
|
|
89
90
|
throw err
|
|
90
91
|
}
|
package/lib/personas.js
CHANGED
package/lib/proxy.js
CHANGED
|
@@ -382,7 +382,9 @@ async function openTunnel(spec, host, port, options) {
|
|
|
382
382
|
: connectViaHttpProxy(spec, host, port, options)
|
|
383
383
|
}
|
|
384
384
|
|
|
385
|
-
|
|
385
|
+
/** @param {any} [opts] */
|
|
386
|
+
function wrapTls(socket, servername, opts = {}) {
|
|
387
|
+
const { signal } = opts
|
|
386
388
|
return new Promise((resolve, reject) => {
|
|
387
389
|
const cleanup = () => {
|
|
388
390
|
if (signal && typeof signal.removeEventListener === 'function') signal.removeEventListener('abort', onAbort)
|
|
@@ -554,8 +556,8 @@ function requestOverTunnel({ spec, url, method, headers, body, signal, timeoutMs
|
|
|
554
556
|
reject(abortReason(signal))
|
|
555
557
|
return
|
|
556
558
|
}
|
|
557
|
-
const agent = new ProxyTunnelAgent({ spec, timeoutMs, logger })
|
|
558
|
-
req = mod.request({
|
|
559
|
+
const agent = /** @type {any} */ (new ProxyTunnelAgent({ spec, timeoutMs, logger }))
|
|
560
|
+
req = /** @type {any} */ (mod).request({
|
|
559
561
|
protocol: url.protocol,
|
|
560
562
|
host: url.hostname,
|
|
561
563
|
hostname: url.hostname,
|
package/lib/session-ops.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export function exportSessionToMarkdown(session,
|
|
1
|
+
export function exportSessionToMarkdown(session, _opts = {}) {
|
|
2
2
|
if (!session) return { filename: 'session-export.md', content: '# Empty session\n', buffer: Buffer.from('# Empty session\n') }
|
|
3
3
|
|
|
4
4
|
const id = session.id || 'unknown'
|
package/lib/telegram-errors.js
CHANGED
|
File without changes
|
package/lib/tts.js
CHANGED
|
@@ -97,6 +97,7 @@ export async function convertToOggOpus(audioBytes, inputMime = 'audio/mpeg') {
|
|
|
97
97
|
* Build a Telegram voice-note file from dsh-tts output.
|
|
98
98
|
* Prefer OGG/Opus; if conversion fails and binary missing, fall back to audio (not voice-note).
|
|
99
99
|
*/
|
|
100
|
+
/** @param {any} spoken @param {any} [opts] */
|
|
100
101
|
export async function toTelegramVoiceFile(spoken, { logger } = {}) {
|
|
101
102
|
if (!spoken?.audio?.length) return null
|
|
102
103
|
if (isOggOpusMime(spoken.mime)) {
|
package/lib/voice-prefs.js
CHANGED
package/lib/webapp.js
CHANGED
|
@@ -10,6 +10,7 @@ import { timingSafeCompare, isTrustedSettingsRequest, readBody, writeJson } from
|
|
|
10
10
|
* @param {number} [maxAgeSec=86400] - Maximum allowed age of initData in seconds (default 24h)
|
|
11
11
|
* @returns {{ ok: boolean, user?: object, authDate?: number, queryId?: string, chatType?: string, error?: string }}
|
|
12
12
|
*/
|
|
13
|
+
/** @returns {any} TMA auth result */
|
|
13
14
|
export function validateTelegramWebAppData(rawInitData, botToken, maxAgeSec = 86400) {
|
|
14
15
|
if (!rawInitData || typeof rawInitData !== 'string') {
|
|
15
16
|
return { ok: false, error: 'empty_init_data' }
|
|
@@ -603,7 +604,7 @@ export function createWebAppHandler(options = {}) {
|
|
|
603
604
|
|
|
604
605
|
// Helper: authenticate request via Telegram WebApp initData or trusted loopback/session
|
|
605
606
|
function authenticate() {
|
|
606
|
-
if (isTrustedSettingsRequest(req, cfg.webhooks?.secret, ctx)) {
|
|
607
|
+
if (isTrustedSettingsRequest(req, cfg.webhooks?.secret, ctx, { trustProxy: cfg.security?.trustProxy === true })) {
|
|
607
608
|
return { ok: true, trusted: true, user: { id: 0, first_name: 'DSH Admin' } }
|
|
608
609
|
}
|
|
609
610
|
|
package/lib/workspace.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { resolve,
|
|
1
|
+
import { resolve, basename } from 'node:path'
|
|
2
2
|
import { statSync, realpathSync, existsSync } from 'node:fs'
|
|
3
3
|
import { readFile } from 'node:fs/promises'
|
|
4
4
|
import { readFileSync } from 'node:fs'
|
|
@@ -170,6 +170,7 @@ export function inspectGitWorkspace(dirPath) {
|
|
|
170
170
|
return { isGit: false, isWorktree: false }
|
|
171
171
|
}
|
|
172
172
|
|
|
173
|
+
/** @param {string} filePath @param {any} [opts] */
|
|
173
174
|
export function createTopicWorkspaceStore(filePath, { logger } = {}) {
|
|
174
175
|
let cache = { workspaces: {} }
|
|
175
176
|
try {
|
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.35",
|
|
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",
|
|
@@ -36,6 +36,9 @@
|
|
|
36
36
|
"test": "node --test test/*.test.mjs",
|
|
37
37
|
"test:load": "node scripts/verify-dsh-load.mjs",
|
|
38
38
|
"test:all": "npm test && npm run test:load && npm run pack:check",
|
|
39
|
+
"test:coverage": "node --test --experimental-test-coverage test/*.test.mjs",
|
|
40
|
+
"lint": "eslint .",
|
|
41
|
+
"typecheck": "tsc --noEmit",
|
|
39
42
|
"smoke:http": "node scripts/smoke-http.mjs",
|
|
40
43
|
"pack:check": "node scripts/pack-check.mjs"
|
|
41
44
|
},
|
|
@@ -60,8 +63,8 @@
|
|
|
60
63
|
"@deepseek-ai/dsh-llm": "^0.1.7-rc.2 || ^0.2.0-rc.1",
|
|
61
64
|
"@deepseek-ai/dsh-session": "^0.1.7-rc.2 || ^0.2.0-rc.1",
|
|
62
65
|
"@deepseek-ai/dsh-settings": "^0.1.7-rc.2 || ^0.2.0-rc.1",
|
|
63
|
-
"@deepseek-ai/
|
|
64
|
-
"@deepseek-ai/
|
|
66
|
+
"@deepseek-ai/dsh-tools": "^0.1.7-rc.2 || ^0.2.0-rc.1",
|
|
67
|
+
"@deepseek-ai/schemastery": "^3.18.2"
|
|
65
68
|
},
|
|
66
69
|
"publishConfig": {
|
|
67
70
|
"access": "public"
|
|
@@ -72,5 +75,11 @@
|
|
|
72
75
|
"overrides": {
|
|
73
76
|
"zod": "^4.6.6",
|
|
74
77
|
"fast-uri": "^3.1.9"
|
|
78
|
+
},
|
|
79
|
+
"devDependencies": {
|
|
80
|
+
"@types/node": "^24.19.2",
|
|
81
|
+
"eslint": "^9.39.5",
|
|
82
|
+
"globals": "^15.15.0",
|
|
83
|
+
"typescript": "^5.9.3"
|
|
75
84
|
}
|
|
76
85
|
}
|