@goodandready/dsh-messenger-gateway 0.4.34 → 0.4.36

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 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 (with configurable `allowlistMode`: `open` | `closed`)
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,12 @@ 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`: `open` (default) or `closed` — in `closed` mode, an empty allowlist admits nobody (fail-closed)
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
149
+ - `telegram.proxyUrl` is a secret: the settings API returns only a masked value and an empty field keeps the configured proxy
150
+ - Inbound archives are extraction-capped (per-entry and per-archive budget verified against actual bytes — a lying ZIP header cannot balloon the heap)
151
+ - Mini App artifacts are chat-scoped: a Telegram user sees only artifacts produced in their own chat; allowlisted admins see all
147
152
  - `sessionList`: `true` (default) — enables `/sessions` and `/resume` commands in chat
148
153
  - `sessionTitleFromChat`: `false` (default) — name each new session after its originating chat (`TG · @user`, `TG · Group › topic N`) instead of generic generated titles
149
154
  - `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 (`allowedUsers`, `allowedChats`).
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)
@@ -39,7 +39,7 @@ export class TelegramAdapter {
39
39
  this.name = 'telegram'
40
40
  this.token = String(opts.botToken || '').trim()
41
41
  this.allowedUserIds = (opts.allowedUserIds || []).map(Number).filter((n) => Number.isFinite(n))
42
- this.allowlistMode = opts.allowlistMode === 'closed' ? 'closed' : 'open'
42
+ this.allowlistMode = opts.allowlistMode === 'open' ? 'open' : 'closed'
43
43
  this.timeoutSeconds = Number(opts.timeoutSeconds) || 50
44
44
  this.pollIntervalMs = Number(opts.pollIntervalMs) || 500
45
45
  this.media = opts.media || {}
package/lib/client.js CHANGED
@@ -111,7 +111,7 @@ window.__ModuleLoader__.load({
111
111
  webhookSecretConfigured: 'Secret set',
112
112
  webhookSecretRequired: 'Secret required',
113
113
  proxyUrl: 'Proxy URL (HTTP, HTTPS, SOCKS5)',
114
- proxyUrlHint: 'Optional proxy for Telegram API requests (e.g. socks5://127.0.0.1:1080 or http://127.0.0.1:8080).',
114
+ proxyUrlHint: 'Optional proxy for Telegram API requests (e.g. socks5://127.0.0.1:1080 or http://127.0.0.1:8080). Leave empty to keep the configured proxy.',
115
115
  apiRoot: 'Custom Telegram Bot API Base URL',
116
116
  apiRootHint: 'Custom API root for reverse proxies or local Bot API servers. Default: https://api.telegram.org',
117
117
  workingDir: 'Working directory (agent.cwd)',
@@ -265,7 +265,7 @@ window.__ModuleLoader__.load({
265
265
  webhookSecretConfigured: '密钥已设置',
266
266
  webhookSecretRequired: '必须设置密钥',
267
267
  proxyUrl: '代理地址 (HTTP, HTTPS, SOCKS5)',
268
- proxyUrlHint: 'Telegram API 请求的可选代理(例如 socks5://127.0.0.1:1080 或 http://127.0.0.1:8080)。',
268
+ proxyUrlHint: 'Telegram API 请求的可选代理(例如 socks5://127.0.0.1:1080 或 http://127.0.0.1:8080)。留空保持当前代理。',
269
269
  apiRoot: '自定义 Telegram Bot API 地址',
270
270
  apiRootHint: '用于反向代理或本地 Bot API 服务器的自定义根地址。默认:https://api.telegram.org',
271
271
  workingDir: '工作目录 (agent.cwd)',
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('open')
26
- .description('Allowlist mode: open admits all users when list is empty; closed refuses unknown users when list is empty'),
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 when allowlist is non-empty'),
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),
@@ -54,7 +57,7 @@ export const PluginConfig = z.object({
54
57
  webhookUrl: z.string().default(''),
55
58
  webhookSecret: z.string().role('secret').default(''),
56
59
  webhookPath: z.string().default('/dsh-messenger-gateway/telegram/webhook'),
57
- 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'),
60
+ proxyUrl: z.string().role('secret').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'),
58
61
  apiRoot: z.string().default('').description('Custom Telegram Bot API root URL (default: https://api.telegram.org)'),
59
62
  voiceMode: z.union([z.const('mirror'), z.const('always'), z.const('off')]).default('mirror')
60
63
  .description('mirror: TTS when inbound was voice; always/off override (per-user /voice wins)'),
package/lib/documents.js CHANGED
@@ -107,7 +107,9 @@ export function extractDocxText(buffer) {
107
107
  let xmlStr = ''
108
108
  try {
109
109
  if (compMethod === 8) {
110
- xmlStr = inflateRawSync(compData).toString('utf8')
110
+ // word/document.xml for a real docx stays far below this cap; a
111
+ // bomb stream is cut off instead of ballooning the heap (#199).
112
+ xmlStr = inflateRawSync(compData, { maxOutputLength: 16 * 1024 * 1024 }).toString('utf8')
111
113
  } else {
112
114
  xmlStr = compData.toString('utf8')
113
115
  }
@@ -179,6 +181,7 @@ export function extractZipEntries(buffer, opts = {}) {
179
181
  const entries = []
180
182
  let pos = cdOffset
181
183
  let totalUncompressed = 0
184
+ let extractedBytes = 0
182
185
 
183
186
  for (let idx = 0; idx < totalEntries && idx < maxEntries; idx++) {
184
187
  if (pos + 46 > buffer.length) break
@@ -221,13 +224,22 @@ export function extractZipEntries(buffer, opts = {}) {
221
224
  const compData = buffer.subarray(dataStart, dataStart + compSize)
222
225
 
223
226
  let content = null
224
- const canExtract = uncompSize <= maxFileBytes && (TEXT_INJECT_EXTS.has(ext) || !ext)
227
+ // The declared uncompressed size is attacker-controlled: treat it only as a
228
+ // fast-path skip, cap every inflate with maxOutputLength (#199), and count
229
+ // the ACTUAL bytes against the archive-wide budget.
230
+ const canExtract = uncompSize <= maxFileBytes
231
+ && extractedBytes < maxUncompressedBytes
232
+ && (TEXT_INJECT_EXTS.has(ext) || !ext)
225
233
  if (canExtract) {
226
234
  try {
227
235
  if (compMethod === 8) {
228
- content = inflateRawSync(compData).toString("utf8")
236
+ const budget = Math.max(1, Math.min(maxFileBytes, maxUncompressedBytes - extractedBytes))
237
+ const inflated = inflateRawSync(compData, { maxOutputLength: budget })
238
+ extractedBytes += inflated.length
239
+ content = inflated.toString("utf8")
229
240
  } else if (compMethod === 0) {
230
241
  content = compData.toString("utf8")
242
+ extractedBytes += content.length
231
243
  }
232
244
  } catch {
233
245
  content = null
@@ -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)
@@ -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
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 || 'open'
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 || 'open') === 'open' && this.effectiveAllowedIds().length === 0) {
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) {
package/lib/http.js CHANGED
@@ -88,9 +88,33 @@ export function getConnection(ctx) {
88
88
  }
89
89
  }
90
90
 
91
- export function isTrustedSettingsRequest(req, expectedSecret, ctx = null) {
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
- const host = String(req?.headers?.host || req?.headers?.['x-forwarded-host'] || '')
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 (url.host.toLowerCase() !== host.toLowerCase() && !isLoopback(url.hostname)) return false
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 (url.host.toLowerCase() !== host.toLowerCase() && !isLoopback(url.hostname)) return false
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.toLowerCase() === host.toLowerCase() || isLoopback(url.hostname)
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.toLowerCase() === host.toLowerCase() || isLoopback(url.hostname)
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 || req?.headers?.['x-forwarded-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.toLowerCase() === host.toLowerCase() || isLoopback(url.hostname)
287
+ return isPinnedLoopbackHost(url.host) && isPinnedLoopbackHost(host)
248
288
  } catch {
249
289
  return false
250
290
  }
package/lib/index.js CHANGED
@@ -13,7 +13,7 @@ import {
13
13
  import { listHomes } from './homes.js'
14
14
  export { plainConfig } from './config.js'
15
15
  import { Config, plainConfig, resolveInternalBaseUrl } from './config.js'
16
- import { describeProxy } from './proxy.js'
16
+ import { describeProxy, maskProxyUrl } from './proxy.js'
17
17
  import { readSecrets, restoreSecrets } from './secret-guard.js'
18
18
  import { setupSettings } from './settings-bridge.js'
19
19
  import { resolveEffectiveCwd, getCwdWarning } from './workspace.js'
@@ -36,7 +36,7 @@ function resolveConfig(raw) {
36
36
  return cfg
37
37
  }
38
38
 
39
- function publicConfig(cfg, gw, ctx) {
39
+ export function publicConfig(cfg, gw, ctx) {
40
40
  const internalBaseURL = gw?.baseUrl?.() || resolveInternalBaseUrl(cfg, ctx)
41
41
  const proxy = describeProxy(cfg.telegram?.proxyUrl)
42
42
  return {
@@ -69,7 +69,8 @@ function publicConfig(cfg, gw, ctx) {
69
69
  webhookPath: cfg.telegram.webhookPath,
70
70
  webhookSecretConfigured: Boolean(String(cfg.telegram.webhookSecret || '').trim()),
71
71
  botTokenConfigured: Boolean(String(cfg.telegram.botToken || '').trim()),
72
- proxyUrl: cfg.telegram.proxyUrl || '',
72
+ proxyUrlConfigured: Boolean(String(cfg.telegram.proxyUrl || '').trim()),
73
+ proxyUrlMasked: maskProxyUrl(cfg.telegram.proxyUrl || ''),
73
74
  apiRoot: cfg.telegram.apiRoot || '',
74
75
  proxyActive: Boolean(proxy.active),
75
76
  proxyLabel: proxy.label || '',
@@ -136,7 +137,7 @@ function registerMessengerRoute(ctx, getGw, path, action, source) {
136
137
  kind: 'exact', path,
137
138
  handler: async (req, res) => {
138
139
  if (req.method !== 'POST') return writeJson(res, 405, { ok: false, error: 'POST only' })
139
- if (!isAuthorizedMessengerRequest(req, source?.()?.webhooks, ctx)) {
140
+ if (!isAuthorizedMessengerRequest(req, source?.()?.webhooks, ctx, { trustProxy: source?.()?.security?.trustProxy === true })) {
140
141
  return writeJson(res, 403, { ok: false, error: 'forbidden' })
141
142
  }
142
143
  let payload
@@ -558,7 +559,7 @@ export function apply(ctx, config) {
558
559
  kind: 'exact', path: '/dsh-messenger-gateway/status',
559
560
  handler: async (req, res) => {
560
561
  if (req.method !== 'GET') return writeJson(res, 405, { ok: false, error: 'GET only' })
561
- if (!isTrustedSettingsRequest(req, source().webhooks?.secret, ctx)) return writeJson(res, 403, { ok: false, error: 'forbidden' })
562
+ if (!isTrustedSettingsRequest(req, source().webhooks?.secret, ctx, { trustProxy: source().security?.trustProxy === true })) return writeJson(res, 403, { ok: false, error: 'forbidden' })
562
563
  const gw = getGw()
563
564
  const botInfo = gw?.getBotInfo?.() || {}
564
565
  const uptimeSec = gw?.stats?.startedAt ? Math.max(0, Math.round((Date.now() - gw.stats.startedAt) / 1000)) : 0
@@ -566,6 +567,8 @@ export function apply(ctx, config) {
566
567
  writeJson(res, 200, {
567
568
  ok: true,
568
569
  running: Boolean(gw),
570
+ allowlistMode: source().telegram?.allowlistMode || 'closed',
571
+ allowlistCount: (source().telegram?.allowedUserIds || []).length,
569
572
  adapters: gw?.messenger.adapters() || [],
570
573
  activeChats: gw?.messenger.activeChats() || 0,
571
574
  ttsEnabled: Boolean(source().tts?.enabled),
@@ -597,7 +600,7 @@ export function apply(ctx, config) {
597
600
  kind: 'exact', path: '/dsh-messenger-gateway/smoke',
598
601
  handler: async (req, res) => {
599
602
  if (req.method !== 'POST') return writeJson(res, 405, { ok: false, error: 'POST only' })
600
- if (!isTrustedSettingsRequest(req, source().webhooks?.secret, ctx)) return writeJson(res, 403, { ok: false, error: 'forbidden' })
603
+ if (!isTrustedSettingsRequest(req, source().webhooks?.secret, ctx, { trustProxy: source().security?.trustProxy === true })) return writeJson(res, 403, { ok: false, error: 'forbidden' })
601
604
  const gw = getGw()
602
605
  if (!gw) return writeJson(res, 503, { ok: false, error: 'gateway not running' })
603
606
  const parsed = await readJsonSafe(req, res, 65536)
@@ -673,7 +676,7 @@ export function apply(ctx, config) {
673
676
  kind: 'exact', path: '/dsh-messenger-gateway/config',
674
677
  handler: async (req, res) => {
675
678
  if (req.method !== 'GET' && req.method !== 'PUT') return writeJson(res, 405, { ok: false, error: 'GET or PUT' })
676
- if (!isTrustedSettingsRequest(req, source().webhooks?.secret, ctx)) return writeJson(res, 403, { ok: false, error: 'forbidden' })
679
+ if (!isTrustedSettingsRequest(req, source().webhooks?.secret, ctx, { trustProxy: source().security?.trustProxy === true })) return writeJson(res, 403, { ok: false, error: 'forbidden' })
677
680
  if (req.method === 'GET') return writeJson(res, 200, { ok: true, config: publicConfig(source(), getGw(), ctx) })
678
681
  if (!settingsApi?.isReady?.()) return writeJson(res, 503, { ok: false, error: 'settings not ready' })
679
682
  const parsedConfig = await readJsonSafe(req, res, 1_048_576)
@@ -684,6 +687,14 @@ export function apply(ctx, config) {
684
687
  const cur = source()
685
688
  const nextTg = { ...cur.telegram, ...(payload.telegram || {}) }
686
689
  if (payload.telegram && !String(payload.telegram.botToken || '').trim()) nextTg.botToken = cur.telegram.botToken
690
+ // proxyUrl is a secret: empty value or an echoed mask means "keep the
691
+ // stored proxy" (#200)
692
+ if (payload.telegram && Object.prototype.hasOwnProperty.call(payload.telegram, 'proxyUrl')) {
693
+ const incoming = String(payload.telegram.proxyUrl || '').trim()
694
+ if (!incoming || incoming.includes(':***@') || incoming === maskProxyUrl(cur.telegram.proxyUrl || '')) {
695
+ nextTg.proxyUrl = cur.telegram.proxyUrl
696
+ }
697
+ }
687
698
  if (payload.telegram && Object.prototype.hasOwnProperty.call(payload.telegram, 'webhookSecret') && !String(payload.telegram.webhookSecret || '').trim()) {
688
699
  nextTg.webhookSecret = cur.telegram.webhookSecret
689
700
  }
@@ -716,7 +727,7 @@ export function apply(ctx, config) {
716
727
  kind: 'exact', path: '/dsh-messenger-gateway/pairing',
717
728
  handler: async (req, res) => {
718
729
  if (req.method !== 'GET') return writeJson(res, 405, { ok: false, error: 'GET only' })
719
- if (!isTrustedSettingsRequest(req, source().webhooks?.secret, ctx)) return writeJson(res, 403, { ok: false, error: 'forbidden' })
730
+ if (!isTrustedSettingsRequest(req, source().webhooks?.secret, ctx, { trustProxy: source().security?.trustProxy === true })) return writeJson(res, 403, { ok: false, error: 'forbidden' })
720
731
  const gw = getGw()
721
732
  if (!gw) return writeJson(res, 503, { ok: false, error: 'gateway not running' })
722
733
  writeJson(res, 200, {
@@ -731,7 +742,7 @@ export function apply(ctx, config) {
731
742
  kind: 'exact', path: '/dsh-messenger-gateway/pairing/approve',
732
743
  handler: async (req, res) => {
733
744
  if (req.method !== 'POST') return writeJson(res, 405, { ok: false, error: 'POST only' })
734
- if (!isTrustedSettingsRequest(req, source().webhooks?.secret, ctx)) return writeJson(res, 403, { ok: false, error: 'forbidden' })
745
+ if (!isTrustedSettingsRequest(req, source().webhooks?.secret, ctx, { trustProxy: source().security?.trustProxy === true })) return writeJson(res, 403, { ok: false, error: 'forbidden' })
735
746
  const gw = getGw()
736
747
  if (!gw) return writeJson(res, 503, { ok: false, error: 'gateway not running' })
737
748
  const parsed = await readJsonSafe(req, res, 65536)
@@ -745,7 +756,7 @@ export function apply(ctx, config) {
745
756
  kind: 'exact', path: '/dsh-messenger-gateway/pairing/reject',
746
757
  handler: async (req, res) => {
747
758
  if (req.method !== 'POST') return writeJson(res, 405, { ok: false, error: 'POST only' })
748
- if (!isTrustedSettingsRequest(req, source().webhooks?.secret, ctx)) return writeJson(res, 403, { ok: false, error: 'forbidden' })
759
+ if (!isTrustedSettingsRequest(req, source().webhooks?.secret, ctx, { trustProxy: source().security?.trustProxy === true })) return writeJson(res, 403, { ok: false, error: 'forbidden' })
749
760
  const gw = getGw()
750
761
  if (!gw) return writeJson(res, 503, { ok: false, error: 'gateway not running' })
751
762
  const parsed = await readJsonSafe(req, res, 65536)
package/lib/webapp.js CHANGED
@@ -604,7 +604,7 @@ export function createWebAppHandler(options = {}) {
604
604
 
605
605
  // Helper: authenticate request via Telegram WebApp initData or trusted loopback/session
606
606
  function authenticate() {
607
- if (isTrustedSettingsRequest(req, cfg.webhooks?.secret, ctx)) {
607
+ if (isTrustedSettingsRequest(req, cfg.webhooks?.secret, ctx, { trustProxy: cfg.security?.trustProxy === true })) {
608
608
  return { ok: true, trusted: true, user: { id: 0, first_name: 'DSH Admin' } }
609
609
  }
610
610
 
@@ -621,11 +621,12 @@ export function createWebAppHandler(options = {}) {
621
621
  if (initData) {
622
622
  const val = validateTelegramWebAppData(initData, botToken)
623
623
  if (val.ok) {
624
- if (Array.isArray(tgCfg.allowedUserIds) && tgCfg.allowedUserIds.length > 0) {
625
- const uid = Number(val.user?.id)
626
- if (!tgCfg.allowedUserIds.includes(uid)) {
627
- return { ok: false, error: 'user_not_allowed' }
628
- }
624
+ // Gateway-aware allowlist check (#201): honors allowlistMode — in the
625
+ // default closed mode an empty allowlist admits nobody (fail-closed),
626
+ // previously a non-empty check only.
627
+ const uid = Number(val.user?.id)
628
+ if (gw?.isUserAllowed && !gw.isUserAllowed(uid)) {
629
+ return { ok: false, error: 'user_not_allowed' }
629
630
  }
630
631
  return { ok: true, user: val.user, initData: val }
631
632
  }
@@ -678,7 +679,15 @@ export function createWebAppHandler(options = {}) {
678
679
  if (!auth.ok) return writeJson(res, 401, { ok: false, error: auth.error })
679
680
 
680
681
  const limit = Number(url.searchParams.get('limit')) || 30
681
- const artifacts = gw?.artifactStore ? gw.artifactStore.list(limit) : []
682
+ const uid = Number(auth.user?.id || 0)
683
+ // Allowlist membership (not open-mode admission) defines an admin:
684
+ // in open mode everyone authenticates, so chat scoping stays meaningful.
685
+ const isAdmin = Array.isArray(tgCfg.allowedUserIds) && tgCfg.allowedUserIds.includes(uid)
686
+ const all = gw?.artifactStore ? gw.artifactStore.list(limit) : []
687
+ // Chat isolation (#201): an authenticated Mini App user sees only
688
+ // artifacts produced in their own private chat (chatId === userId);
689
+ // allowlisted admins see the whole store.
690
+ const artifacts = all.filter((a) => isAdmin || (uid && String(a.chatId || '') === String(uid)))
682
691
  return writeJson(res, 200, { ok: true, artifacts })
683
692
  }
684
693
 
@@ -691,6 +700,11 @@ export function createWebAppHandler(options = {}) {
691
700
 
692
701
  const artifact = gw?.artifactStore?.get(id)
693
702
  if (!artifact) return writeJson(res, 404, { ok: false, error: 'not found' })
703
+ const uid = Number(auth.user?.id || 0)
704
+ const isAdmin = Array.isArray(tgCfg.allowedUserIds) && tgCfg.allowedUserIds.includes(uid)
705
+ if (!isAdmin && String(artifact.chatId || '') !== String(uid)) {
706
+ return writeJson(res, 403, { ok: false, error: 'forbidden' })
707
+ }
694
708
 
695
709
  return writeJson(res, 200, { ok: true, artifact })
696
710
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodandready/dsh-messenger-gateway",
3
- "version": "0.4.34",
3
+ "version": "0.4.36",
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",