@goodandready/dsh-messenger-gateway 0.4.15 → 0.4.17

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.
@@ -0,0 +1,52 @@
1
+ // Защита секретов плагина от «пустой перезаписи» из карточки настроек.
2
+ //
3
+ // DSH отдаёт браузеру describe({ redactSecrets: true }) — поля с
4
+ // role('secret') (botToken, webhookSecret, secret вебхуков) в клиент не
5
+ // попадают. Карточка плагина сохраняет секцию целиком, поэтому при каждом
6
+ // сохранении (например, при смене прокси) в конфиг уезжает пустой токен и бот
7
+ // отключается. Здесь мы запоминаем последние непустые значения и возвращаем их
8
+ // обратно, если запись их обнулила. Явная смена значения (непустое новое)
9
+ // всегда выигрывает — так же ведёт себя и PUT /config в lib/index.js.
10
+
11
+ export const SECRET_FIELDS = [
12
+ ['telegram', 'botToken'],
13
+ ['telegram', 'webhookSecret'],
14
+ ['discord', 'botToken'],
15
+ ['slack', 'botToken'],
16
+ ['webhooks', 'secret'],
17
+ ]
18
+
19
+ function keyOf(section, field) {
20
+ return `${section}.${field}`
21
+ }
22
+
23
+ /** Снимок непустых секретов конфига: { 'telegram.botToken': '123:ABC' }. */
24
+ export function readSecrets(config) {
25
+ const out = {}
26
+ for (const [section, field] of SECRET_FIELDS) {
27
+ const value = String(config?.[section]?.[field] ?? '')
28
+ out[keyOf(section, field)] = value
29
+ }
30
+ return out
31
+ }
32
+
33
+ /**
34
+ * Возвращает копию конфига с восстановленными секретами.
35
+ * @param previous снимок из readSecrets() до записи
36
+ * @param config разобранный конфиг после записи
37
+ * @returns {{ config: object, restored: string[] }} — restored пуст, если чинить нечего
38
+ */
39
+ export function restoreSecrets(previous, config) {
40
+ const restored = []
41
+ const next = structuredClone(config ?? {})
42
+ for (const [section, field] of SECRET_FIELDS) {
43
+ const key = keyOf(section, field)
44
+ const before = String(previous?.[key] ?? '')
45
+ const after = String(next?.[section]?.[field] ?? '')
46
+ if (before && !after) {
47
+ next[section] = { ...(next[section] || {}), [field]: before }
48
+ restored.push(key)
49
+ }
50
+ }
51
+ return { config: next, restored }
52
+ }
File without changes
@@ -7,6 +7,69 @@ export function escapeHtml(text) {
7
7
 
8
8
  const PH = '\uE000'
9
9
 
10
+ // Telegram HTML поддерживает только этот набор тегов; всё остальное (<script>,
11
+ // атрибуты, произвольные теги) обязано остаться текстом. Командные ответы самого
12
+ // плагина написаны HTML-тегами (<b>, <code>, ...), а конвейер рассчитан на
13
+ // Markdown и экранирует весь вход — из-за этого в чате были видны литеральные
14
+ // теги. Поэтому теги из белого списка вынимаем в слоты до экранирования и
15
+ // возвращаем уже как разметку.
16
+ const SAFE_TAG_NAMES = 'b|strong|i|em|u|s|strike|del|code|pre|tg-spoiler|blockquote'
17
+ const SAFE_TAG_RE = new RegExp(`<(/?)(${SAFE_TAG_NAMES})>`, 'gi')
18
+ const SAFE_ANCHOR_RE = /<a\s+href="([^"]{1,512})"\s*>/gi
19
+
20
+ const ENTITIES = {
21
+ '&lt;': '<',
22
+ '&gt;': '>',
23
+ '&quot;': '"',
24
+ '&#39;': "'",
25
+ '&apos;': "'",
26
+ '&nbsp;': '\u00a0',
27
+ }
28
+
29
+ /**
30
+ * Однопроходное раскрытие типовых HTML-сущностей: плагин пишет `&lt;role&gt;`
31
+ * там, где нужен текст `<role>`, а Markdown-конвейер ждёт обычный текст.
32
+ * `&amp;` раскрывается последним, поэтому `&amp;lt;` остаётся `&lt;`.
33
+ */
34
+ export function decodeHtmlEntities(text) {
35
+ return String(text ?? '').replace(/&(lt|gt|quot|#39|apos|nbsp);|&amp;/g, (match) => ENTITIES[match] ?? '&')
36
+ }
37
+
38
+ const SAFE_TAG_ANY_RE = new RegExp(`<a\\s+href="([^"]{1,512})"\\s*>|<(/?)(${SAFE_TAG_NAMES}|a)>`, 'gi')
39
+
40
+ /**
41
+ * Вынимает в слоты только сбалансированные теги из белого списка. Незакрытый
42
+ * `</b>` или тег с атрибутами (`<b onclick=...>`) остаются текстом и будут
43
+ * экранированы — иначе Telegram отвергнет сообщение как невалидную разметку.
44
+ */
45
+ function protectSafeTags(text, stash) {
46
+ const open = []
47
+ return text.replace(SAFE_TAG_ANY_RE, (match, href, closing, rawName) => {
48
+ const tag = String(rawName || 'a').toLowerCase()
49
+ if (href !== undefined) {
50
+ if (!isSafeUrl(href)) return match
51
+ open.push(tag)
52
+ return stash(match)
53
+ }
54
+ if (closing) {
55
+ const index = open.lastIndexOf(tag)
56
+ if (index === -1) return match
57
+ open.splice(index, 1)
58
+ return stash(match)
59
+ }
60
+ open.push(tag)
61
+ return stash(match)
62
+ })
63
+ }
64
+
65
+ /** Для режима plain: убрать разметку и раскрыть сущности, оставив чистый текст. */
66
+ export function stripSafeTags(text) {
67
+ return decodeHtmlEntities(text)
68
+ .replace(SAFE_ANCHOR_RE, '')
69
+ .replace(/<\/a>/gi, '')
70
+ .replace(SAFE_TAG_RE, '')
71
+ }
72
+
10
73
  const SAFE_SCHEMES = new Set(['https:', 'http:', 'tg:'])
11
74
 
12
75
  export function isSafeUrl(rawUrl) {
@@ -138,8 +201,10 @@ export function markdownToTelegramHtml(markdown) {
138
201
  return `${PH}${id}${PH}`
139
202
  }
140
203
 
204
+ text = decodeHtmlEntities(text)
141
205
  text = text.replace(/```([\s\S]*?)```/g, (_, code) => stash(`<pre><code>${escapeHtml(code.replace(/^\n/, '').replace(/\n$/, ''))}</code></pre>`))
142
206
  text = text.replace(/`([^`\n]+)`/g, (_, code) => stash(`<code>${escapeHtml(code)}</code>`))
207
+ text = protectSafeTags(text, stash)
143
208
  text = convertTables(text, stash)
144
209
  text = convertDetails(text, stash)
145
210
  text = convertTaskLists(text, stash)
@@ -157,6 +222,7 @@ export function markdownToTelegramHtml(markdown) {
157
222
 
158
223
  export function prepareTelegramText(text, format = 'html') {
159
224
  const raw = String(text ?? '')
160
- if (!raw || format === 'plain') return { text: raw, parseMode: undefined }
225
+ if (!raw) return { text: raw, parseMode: undefined }
226
+ if (format === 'plain') return { text: stripSafeTags(raw), parseMode: undefined }
161
227
  return { text: markdownToTelegramHtml(raw), parseMode: 'HTML' }
162
228
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodandready/dsh-messenger-gateway",
3
- "version": "0.4.15",
3
+ "version": "0.4.17",
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",