@goodandready/dsh-messenger-gateway 0.4.37 → 0.4.39

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
@@ -149,6 +149,13 @@ In addition to Telegram, outbound messages can be dispatched to Discord and Slac
149
149
  - `telegram.proxyUrl` is a secret: the settings API returns only a masked value and an empty field keeps the configured proxy
150
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
151
  - Mini App artifacts are chat-scoped: a Telegram user sees only artifacts produced in their own chat; allowlisted admins see all
152
+ - Mini App sign-in is hardened: `auth_date` required, 1h acceptance window, one-time `query_id` (replays rejected); `initData` in URL query is not accepted — the Mini App must send it via the `Authorization: tma` header
153
+ - HITL approvals are fail-closed by default: in `mutations` sensitivity every tool that is not recognizably read-only (including network, send and MCP tools) asks for confirmation; a chat without a target refuses unconfirmed actions
154
+ - `telegram.apiRoot` with plain `http` is only accepted for loopback hosts (a local Bot API server); the webhook URL is logged without its secret path
155
+ - `webhooks.enabled: false` removes the messenger write routes entirely; GET `/update` and `/messenger` require trusted callers
156
+ - `webAppEnabled: false` takes the whole Mini App surface down (dashboard and every `/api/*` answer 404) and clears the menu button
157
+ - Inline keyboard `replyMarkup` sent via `/messenger/send` is schema-validated (button text/actions, sizes) before delivery
158
+ - All state files (pairing, outbox, voice prefs) are written with `0600` permissions inside `0700` directories
152
159
  - `sessionList`: `true` (default) — enables `/sessions` and `/resume` commands in chat
153
160
  - `sessionTitleFromChat`: `false` (default) — name each new session after its originating chat (`TG · @user`, `TG · Group › topic N`) instead of generic generated titles
154
161
  - `voiceMode`: `mirror` / `always` / `off` — when to speak replies (also `/voice`)
@@ -28,7 +28,7 @@ export default function createAdapters(deps) {
28
28
  apiRoot: tg.apiRoot,
29
29
  quickActions: tg.quickActions !== false,
30
30
  artifactPreviews: tg.artifactPreviews !== false,
31
- webAppUrl: tg.webAppUrl || (tg.webhookUrl && String(tg.webhookUrl).startsWith('http') ? `${new URL(tg.webhookUrl).origin}/dsh-messenger-gateway/webapp` : ''),
31
+ webAppUrl: tg.webAppEnabled === false ? '' : (tg.webAppUrl || (tg.webhookUrl && String(tg.webhookUrl).startsWith('http') ? `${new URL(tg.webhookUrl).origin}/dsh-messenger-gateway/webapp` : '')),
32
32
  mediaGroupDebounceMs: tg.mediaGroupDebounceMs,
33
33
  media: config.media,
34
34
  onMessage,
@@ -244,7 +244,10 @@ export class TelegramAdapter {
244
244
  secret_token: this.webhookSecret,
245
245
  }
246
246
  await this.call('setWebhook', params)
247
- this.logger?.info?.(`dsh-messenger-gateway: telegram webhook set → ${this.webhookUrl}`)
247
+ // The webhook URL carries the secret token path: log only the origin (#205)
248
+ let webhookLogTarget = this.webhookUrl
249
+ try { webhookLogTarget = `${new URL(this.webhookUrl).origin}/***` } catch { /* keep raw */ }
250
+ this.logger?.info?.(`dsh-messenger-gateway: telegram webhook set → ${webhookLogTarget}`)
248
251
  return
249
252
  }
250
253
  try {
@@ -85,23 +85,44 @@ export function formatApprovalCard(req, locale = "en") {
85
85
  return t("ask.confirm_title", { tool: escapeHtml(tool), reason: reason + detail }, locale, { escape: false })
86
86
  }
87
87
 
88
- export async function answerApproval(gw, chatKeyValue, req, next) {
88
+ // Read-only allowlist for the "mutations" sensitivity (#203): everything NOT
89
+ // matching this allowlist (unknown tools, MCP tools, network and send tools)
90
+ // requires explicit user confirmation. Anything that mutates, sends, or
91
+ // executes can never be in the safe set regardless of its name.
92
+ const SAFE_READ_ONLY_TOOLS = new Set([
93
+ "read_file", "read_many_files", "list_files", "list_dir",
94
+ "glob", "grep", "doc_search", "view", "show",
95
+ ])
96
+ const SAFE_READ_ONLY_PREFIX = /^(read|list|get|view|show|describe)[_-]/i
97
+ const UNSAFE_HINT = /(write|replace|edit|delete|remove|create|patch|send|post|put|exec|run|deploy|install|apply|curl|wget|fetch|http|schedule|email)/i
98
+
99
+ /** True when a tool is recognizably read-only and safe to run unconfirmed. */
100
+ export function isSafeReadOnlyTool(toolName) {
101
+ if (!toolName) return false
102
+ const t = String(toolName)
103
+ if (UNSAFE_HINT.test(t)) return false
104
+ return SAFE_READ_ONLY_TOOLS.has(t) || SAFE_READ_ONLY_PREFIX.test(t)
105
+ }
106
+
107
+ export async function answerApproval(gw, chatKeyValue, req, _next) {
89
108
  try {
90
109
  const tg = gw.tg ? gw.tg() : (gw.config?.telegram || {})
91
110
  if (tg.approvalsEnabled === false || tg.approvalsSensitivity === "disabled") {
92
111
  return "allowed-once"
93
112
  }
94
113
  const tool = req.toolName || "tool"
95
- const sensitivity = tg.approvalsSensitivity || "mutations"
96
- if (sensitivity === "mutations" && !isSensitiveTool(tool)) {
97
- return "allowed-once"
98
- }
99
114
 
115
+ // Fail-closed (#203): without a messenger target we cannot ask the user,
116
+ // so an unconfirmed action is refused instead of silently executed.
100
117
  const chat = gw.chats.get(chatKeyValue)
101
- if (!chat?.target) return next()
118
+ if (!chat?.target) return "rejected"
102
119
  if (chat.sessionAllowlist?.has(tool)) {
103
120
  return "allowed-once"
104
121
  }
122
+ const sensitivity = tg.approvalsSensitivity || "mutations"
123
+ if (sensitivity === "mutations" && isSafeReadOnlyTool(tool)) {
124
+ return "allowed-once"
125
+ }
105
126
  const locale = gw.resolveLocale ? gw.resolveLocale(chat.target) : "en"
106
127
  const text = formatApprovalCard(req, locale)
107
128
  const buttons = [
package/lib/index.js CHANGED
@@ -132,11 +132,16 @@ async function readJsonSafe(req, res, maxBytes = 1_048_576) {
132
132
  }
133
133
  }
134
134
 
135
- function registerMessengerRoute(ctx, getGw, path, action, source) {
135
+ export function registerMessengerRoute(ctx, getGw, path, action, source) {
136
136
  ctx.effect(() => (ctx.get?.('webServer') || ctx.webServer).register({
137
137
  kind: 'exact', path,
138
138
  handler: async (req, res) => {
139
139
  if (req.method !== 'POST') return writeJson(res, 405, { ok: false, error: 'POST only' })
140
+ // The global switch takes precedence (#206): with webhooks disabled the
141
+ // messenger write routes disappear entirely (404, like unknown paths).
142
+ if (source?.()?.webhooks?.enabled === false) {
143
+ return writeJson(res, 404, { ok: false, error: 'webhooks disabled' })
144
+ }
140
145
  if (!isAuthorizedMessengerRequest(req, source?.()?.webhooks, ctx, { trustProxy: source?.()?.security?.trustProxy === true })) {
141
146
  return writeJson(res, 403, { ok: false, error: 'forbidden' })
142
147
  }
@@ -615,6 +620,7 @@ export function apply(ctx, config) {
615
620
  kind: 'exact', path: '/dsh-messenger-gateway/messenger',
616
621
  handler: async (req, res) => {
617
622
  if (req.method !== 'GET') return writeJson(res, 405, { ok: false, error: 'GET only' })
623
+ if (!isTrustedSettingsRequest(req, source().webhooks?.secret, ctx, { trustProxy: source().security?.trustProxy === true })) return writeJson(res, 403, { ok: false, error: 'forbidden' })
618
624
  writeJson(res, 200, { ok: true, schema: messengerApiSchema })
619
625
  },
620
626
  }), 'dsh-messenger-gateway: messenger schema')
@@ -781,14 +787,22 @@ export function apply(ctx, config) {
781
787
  ctx.effect(() => {
782
788
  const ws = getWebServer()
783
789
  if (!ws?.register) return
790
+ const webappHandler = createWebAppHandler({
791
+ getGateway: getGw,
792
+ getConfig: source,
793
+ ctx,
794
+ })
784
795
  return ws.register({
785
796
  kind: 'prefix',
786
797
  path: '/dsh-messenger-gateway/webapp',
787
- handler: createWebAppHandler({
788
- getGateway: getGw,
789
- getConfig: source,
790
- ctx,
791
- }),
798
+ handler: async (req, res) => {
799
+ // webAppEnabled=false must take the whole Mini App surface down —
800
+ // HTML dashboard and every /api/* endpoint answer 404 (#207).
801
+ if (source().telegram?.webAppEnabled === false) {
802
+ return writeJson(res, 404, { ok: false, error: 'webapp disabled' })
803
+ }
804
+ return webappHandler(req, res)
805
+ },
792
806
  })
793
807
  }, 'dsh-messenger-gateway: webapp dashboard')
794
808
 
@@ -796,6 +810,14 @@ export function apply(ctx, config) {
796
810
  manifestPath,
797
811
  packageName: '@goodandready/dsh-messenger-gateway',
798
812
  endpoint: '/dsh-messenger-gateway/update',
813
+ // Read endpoints answer version/profile data: gate them like other
814
+ // admin reads (#206).
815
+ isTrustedRequest: (req) => isTrustedSettingsRequest(
816
+ req,
817
+ source().webhooks?.secret,
818
+ ctx,
819
+ { trustProxy: source().security?.trustProxy === true },
820
+ ),
799
821
  }), 'dsh-messenger-gateway: plugin updater')
800
822
 
801
823
  // Cordis never delivers a 'dispose' event to `ctx.on`, so this cleanup never
@@ -147,6 +147,83 @@ export function normalizeFiles(files) {
147
147
  })
148
148
  }
149
149
 
150
+ // Telegram inline keyboard constraints: rows of buttons, each button with a
151
+ // text label and exactly one action; callback_data <= 64 bytes. Rejects
152
+ // phishing-shaped markup (script urls, oversized payloads, unknown fields)
153
+ // before it reaches the Telegram API (#206).
154
+ export function sanitizeReplyMarkup(markup) {
155
+ if (markup === undefined || markup === null) return undefined
156
+ if (typeof markup !== 'object' || Array.isArray(markup)) {
157
+ const err = /** @type {any} */ (new Error('replyMarkup must be an object'))
158
+ err.status = 400
159
+ throw err
160
+ }
161
+ const rows = markup.inline_keyboard
162
+ if (!Array.isArray(rows) || rows.length === 0 || rows.length > 100) {
163
+ const err = /** @type {any} */ (new Error('replyMarkup.inline_keyboard must be a non-empty array of at most 100 rows'))
164
+ err.status = 400
165
+ throw err
166
+ }
167
+ let total = 0
168
+ const clean = rows.map((row) => {
169
+ if (!Array.isArray(row) || row.length === 0 || row.length > 8) {
170
+ const err = /** @type {any} */ (new Error('each inline_keyboard row must contain 1..8 buttons'))
171
+ err.status = 400
172
+ throw err
173
+ }
174
+ return row.map((button) => {
175
+ total += 1
176
+ if (total > 100) {
177
+ const err = /** @type {any} */ (new Error('inline_keyboard must contain at most 100 buttons'))
178
+ err.status = 400
179
+ throw err
180
+ }
181
+ const text = typeof button?.text === 'string' ? button.text : ''
182
+ if (!text || text.length > 64) {
183
+ const err = /** @type {any} */ (new Error('button.text must be 1..64 characters'))
184
+ err.status = 400
185
+ throw err
186
+ }
187
+ const out = { text }
188
+ const kinds = ['url', 'callback_data', 'web_app']
189
+ const present = kinds.filter((k) => button[k] !== undefined)
190
+ if (present.length !== 1) {
191
+ const err = /** @type {any} */ (new Error('button must define exactly one of url, callback_data, web_app'))
192
+ err.status = 400
193
+ throw err
194
+ }
195
+ const kind = present[0]
196
+ if (kind === 'url') {
197
+ const url = String(button.url)
198
+ if (!/^https?:\/\//i.test(url) && !url.startsWith('tg://')) {
199
+ const err = /** @type {any} */ (new Error('button.url must be http(s) or tg://'))
200
+ err.status = 400
201
+ throw err
202
+ }
203
+ out.url = url
204
+ } else if (kind === 'callback_data') {
205
+ const data = String(button.callback_data)
206
+ if (!data || Buffer.byteLength(data, 'utf8') > 64) {
207
+ const err = /** @type {any} */ (new Error('button.callback_data must be 1..64 bytes'))
208
+ err.status = 400
209
+ throw err
210
+ }
211
+ out.callback_data = data
212
+ } else {
213
+ const webAppUrl = String(button.web_app?.url || '')
214
+ if (!/^https:\/\//i.test(webAppUrl)) {
215
+ const err = /** @type {any} */ (new Error('button.web_app.url must be https'))
216
+ err.status = 400
217
+ throw err
218
+ }
219
+ out.web_app = { url: webAppUrl }
220
+ }
221
+ return out
222
+ })
223
+ })
224
+ return { inline_keyboard: clean }
225
+ }
226
+
150
227
  export function normalizeSendBody(payload) {
151
228
  const text = typeof payload?.text === 'string' ? payload.text.trim() : ''
152
229
  const files = normalizeFiles(payload?.files)
@@ -158,7 +235,8 @@ export function normalizeSendBody(payload) {
158
235
  const body = {}
159
236
  if (text) body.text = text
160
237
  if (files.length) body.files = files
161
- if (payload?.replyMarkup) body.replyMarkup = payload.replyMarkup
238
+ const markup = sanitizeReplyMarkup(payload?.replyMarkup)
239
+ if (markup) body.replyMarkup = markup
162
240
  return body
163
241
  }
164
242
 
package/lib/pairing.js CHANGED
@@ -13,10 +13,10 @@ export function generatePairingCode(length = 8) {
13
13
 
14
14
  function writeJsonAtomicSync(filePath, data) {
15
15
  const dir = dirname(filePath)
16
- mkdirSync(dir, { recursive: true })
16
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
17
17
  const tmpPath = `${filePath}.${randomUUID().slice(0, 8)}.tmp`
18
18
  try {
19
- writeFileSync(tmpPath, JSON.stringify(data, null, 2), 'utf8')
19
+ writeFileSync(tmpPath, JSON.stringify(data, null, 2), { encoding: 'utf8', mode: 0o600 })
20
20
  renameSync(tmpPath, filePath)
21
21
  } catch (err) {
22
22
  try { unlinkSync(tmpPath) } catch { /* safe best-effort temp file cleanup */ }
package/lib/proxy.js CHANGED
@@ -613,6 +613,15 @@ export function normalizeApiRoot(rawUrl) {
613
613
  if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
614
614
  throw new Error(`Unsupported apiRoot protocol "${parsed.protocol}". Must be http: or https:`)
615
615
  }
616
+ // Plain-text http would carry the bot token in the URL path (#205): only
617
+ // loopback hosts (a local Bot API server) may use it.
618
+ if (parsed.protocol === 'http:') {
619
+ const host = parsed.hostname.toLowerCase()
620
+ const loopback = host === 'localhost' || host === '127.0.0.1' || host === '::1' || host === '[::1]'
621
+ if (!loopback) {
622
+ throw new Error(`apiRoot "${trimmed}" uses plain http for a non-loopback host; the bot token would travel unencrypted. Use https or a loopback address.`)
623
+ }
624
+ }
616
625
  return trimmed.replace(/\/+$/, '')
617
626
  }
618
627
 
@@ -3,17 +3,23 @@ import { writeFileSync, renameSync, mkdirSync, unlinkSync } from 'node:fs'
3
3
  import { dirname } from 'node:path'
4
4
  import { randomUUID } from 'node:crypto'
5
5
 
6
+ // State files carry message texts, approved user ids and pairing data: they
7
+ // must not be world-readable (#204). Directories are created 0o700 so the
8
+ // contents stay private even when the parent is shared.
9
+ const FILE_MODE = 0o600
10
+ const DIR_MODE = 0o700
11
+
6
12
  /**
7
13
  * Write JSON atomically via temporary file and rename.
8
14
  * Guarantees that readers never observe partially written files.
9
15
  */
10
16
  export async function writeJsonAtomic(filePath, data) {
11
17
  const dir = dirname(filePath)
12
- await mkdir(dir, { recursive: true })
18
+ await mkdir(dir, { recursive: true, mode: DIR_MODE })
13
19
  const tmpPath = `${filePath}.${randomUUID().slice(0, 8)}.tmp`
14
20
  const serialized = JSON.stringify(data, null, 2)
15
21
  try {
16
- await writeFile(tmpPath, serialized, 'utf8')
22
+ await writeFile(tmpPath, serialized, { encoding: 'utf8', mode: FILE_MODE })
17
23
  await rename(tmpPath, filePath)
18
24
  } catch (err) {
19
25
  await unlink(tmpPath).catch((e) => { void e })
@@ -26,13 +32,13 @@ export async function writeJsonAtomic(filePath, data) {
26
32
  */
27
33
  export function writeJsonAtomicSync(filePath, data) {
28
34
  const dir = dirname(filePath)
29
- mkdirSync(dir, { recursive: true })
35
+ mkdirSync(dir, { recursive: true, mode: DIR_MODE })
30
36
  const tmpPath = `${filePath}.${randomUUID().slice(0, 8)}.tmp`
31
37
  try {
32
- writeFileSync(tmpPath, JSON.stringify(data, null, 2), 'utf8')
38
+ writeFileSync(tmpPath, JSON.stringify(data, null, 2), { encoding: 'utf8', mode: FILE_MODE })
33
39
  renameSync(tmpPath, filePath)
34
40
  } catch (err) {
35
41
  try { unlinkSync(tmpPath) } catch { /* ignore */ }
36
42
  throw err
37
43
  }
38
- }
44
+ }
package/lib/updater.js CHANGED
@@ -251,6 +251,12 @@ export function registerPluginUpdater(ctx, options) {
251
251
  try {
252
252
  const target = runtime()
253
253
  if (request.method === 'GET' || request.method === 'HEAD') {
254
+ // Version/profile discovery is gated like other admin reads (#206)
255
+ if (typeof options.isTrustedRequest === 'function' && !options.isTrustedRequest(request)) {
256
+ response.writeHead(403, { 'content-type': 'application/json; charset=utf-8' })
257
+ response.end(JSON.stringify({ ok: false, error: 'forbidden' }))
258
+ return
259
+ }
254
260
  const payload = await getUpdateStatus(options, target)
255
261
  response.writeHead(200, {
256
262
  'content-type': 'application/json; charset=utf-8',
@@ -4,10 +4,10 @@ import { randomUUID } from "node:crypto"
4
4
 
5
5
  function writeJsonAtomicSync(filePath, data) {
6
6
  const dir = dirname(filePath)
7
- mkdirSync(dir, { recursive: true })
7
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
8
8
  const tmpPath = `${filePath}.${randomUUID().slice(0, 8)}.tmp`
9
9
  try {
10
- writeFileSync(tmpPath, JSON.stringify(data, null, 2), "utf8")
10
+ writeFileSync(tmpPath, JSON.stringify(data, null, 2), { encoding: "utf8", mode: 0o600 })
11
11
  renameSync(tmpPath, filePath)
12
12
  } catch (err) {
13
13
  try { unlinkSync(tmpPath) } catch { /* safe best-effort temp file cleanup */ }
package/lib/webapp.js CHANGED
@@ -1,17 +1,34 @@
1
1
  import { createHmac } from 'node:crypto'
2
2
  import { timingSafeCompare, isTrustedSettingsRequest, readBody, writeJson } from './http.js'
3
3
 
4
+ // Replay guard (#202): a query_id can be redeemed only once. Telegram issues a
5
+ // fresh query_id on every Mini App opening, so legitimate re-openings are not
6
+ // affected; a stolen initData string becomes useless after the first use.
7
+ const seenQueryIds = new Map()
8
+ function checkAndRememberQueryId(queryId) {
9
+ if (!queryId) return null
10
+ const now = Date.now()
11
+ for (const [k, ts] of seenQueryIds) {
12
+ if (now - ts > 26 * 3600_000) seenQueryIds.delete(k)
13
+ }
14
+ if (seenQueryIds.has(queryId)) return 'replayed_query_id'
15
+ seenQueryIds.set(queryId, now)
16
+ return null
17
+ }
18
+
4
19
  /**
5
20
  * Validates Telegram WebApp initData string using HMAC-SHA256 according to Telegram specification:
6
21
  * https://core.telegram.org/bots/webapps#validating-data-received-via-the-mini-app
7
22
  *
23
+ * Hardened (#202): auth_date is REQUIRED, the default acceptance window is
24
+ * 1 hour, and a query_id can be redeemed only once.
25
+ *
8
26
  * @param {string} rawInitData - URL-encoded query string received from Telegram.WebApp.initData
9
27
  * @param {string} botToken - Telegram Bot Token
10
- * @param {number} [maxAgeSec=86400] - Maximum allowed age of initData in seconds (default 24h)
11
- * @returns {{ ok: boolean, user?: object, authDate?: number, queryId?: string, chatType?: string, error?: string }}
28
+ * @param {number} [maxAgeSec=3600] - Maximum allowed age of initData in seconds (default 1h)
29
+ * @returns {{ ok: boolean, user?: object, authDate?: number, queryId?: string, chatType?: string, chatInstance?: string, data?: Record<string, string>, error?: string }}
12
30
  */
13
- /** @returns {any} TMA auth result */
14
- export function validateTelegramWebAppData(rawInitData, botToken, maxAgeSec = 86400) {
31
+ export function validateTelegramWebAppData(rawInitData, botToken, maxAgeSec = 3600) {
15
32
  if (!rawInitData || typeof rawInitData !== 'string') {
16
33
  return { ok: false, error: 'empty_init_data' }
17
34
  }
@@ -38,13 +55,21 @@ export function validateTelegramWebAppData(rawInitData, botToken, maxAgeSec = 86
38
55
 
39
56
  const authDateStr = params.get('auth_date')
40
57
  const authDate = Number(authDateStr) || 0
41
- if (authDate > 0 && maxAgeSec > 0) {
58
+ if (!authDate) {
59
+ return { ok: false, error: 'missing_auth_date' }
60
+ }
61
+ if (maxAgeSec > 0) {
42
62
  const nowSec = Math.floor(Date.now() / 1000)
43
63
  if (Math.abs(nowSec - authDate) > maxAgeSec) {
44
64
  return { ok: false, error: 'expired', authDate }
45
65
  }
46
66
  }
47
67
 
68
+ const replayError = checkAndRememberQueryId(params.get('query_id'))
69
+ if (replayError) {
70
+ return { ok: false, error: replayError }
71
+ }
72
+
48
73
  let user = null
49
74
  const userStr = params.get('user')
50
75
  if (userStr) {
@@ -614,9 +639,9 @@ export function createWebAppHandler(options = {}) {
614
639
  initData = authHeader.slice(4).trim()
615
640
  } else if (req.headers['x-telegram-init-data']) {
616
641
  initData = String(req.headers['x-telegram-init-data']).trim()
617
- } else if (url.searchParams.get('initData')) {
618
- initData = url.searchParams.get('initData')
619
642
  }
643
+ // initData in the URL query is no longer accepted (#202): it leaks into
644
+ // browser history, Referer headers and access logs.
620
645
 
621
646
  if (initData) {
622
647
  const val = validateTelegramWebAppData(initData, botToken)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodandready/dsh-messenger-gateway",
3
- "version": "0.4.37",
3
+ "version": "0.4.39",
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",