@goodandready/dsh-messenger-gateway 0.4.38 → 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
@@ -151,6 +151,10 @@ In addition to Telegram, outbound messages can be dispatched to Discord and Slac
151
151
  - Mini App artifacts are chat-scoped: a Telegram user sees only artifacts produced in their own chat; allowlisted admins see all
152
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
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
154
158
  - All state files (pairing, outbox, voice prefs) are written with `0600` permissions inside `0700` directories
155
159
  - `sessionList`: `true` (default) — enables `/sessions` and `/resume` commands in chat
156
160
  - `sessionTitleFromChat`: `false` (default) — name each new session after its originating chat (`TG · @user`, `TG · Group › topic N`) instead of generic generated titles
@@ -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 {
File without changes
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
File without changes
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
 
File without changes
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',
File without changes
package/lib/webapp.js CHANGED
File without changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodandready/dsh-messenger-gateway",
3
- "version": "0.4.38",
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",