@goodandready/dsh-messenger-gateway 0.4.44 → 0.4.46
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 -0
- package/README.ru.md +2 -0
- package/README.zh.md +2 -0
- package/lib/adapters/telegram.js +25 -13
- package/lib/client.js +205 -23
- package/lib/config.js +30 -6
- package/lib/forum-mirror.js +3 -0
- package/lib/gateway.js +20 -0
- package/lib/index.js +171 -147
- package/lib/outbox.js +4 -1
- package/lib/pairing.js +35 -20
- package/lib/personas.js +27 -11
- package/lib/scheduler.js +30 -11
- package/lib/secret-guard.js +2 -0
- package/lib/settings-bridge.js +32 -4
- package/lib/storage-atomic.js +174 -8
- package/lib/voice-prefs.js +31 -21
- package/lib/webapp.js +8 -5
- package/lib/workspace.js +23 -11
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -12,7 +12,7 @@ import {
|
|
|
12
12
|
} from './messenger-api.js'
|
|
13
13
|
import { listHomes } from './homes.js'
|
|
14
14
|
export { plainConfig } from './config.js'
|
|
15
|
-
import { Config, plainConfig, resolveInternalBaseUrl } from './config.js'
|
|
15
|
+
import { Config, plainConfig, resolveInternalBaseUrl, transportSignatureOf } from './config.js'
|
|
16
16
|
import { describeProxy, maskProxyUrl } from './proxy.js'
|
|
17
17
|
import { readSecrets, restoreSecrets } from './secret-guard.js'
|
|
18
18
|
import { setupSettings } from './settings-bridge.js'
|
|
@@ -25,7 +25,7 @@ export const inject = ['agentDefaultModel', 'agents', 'sessions', 'loader', 'set
|
|
|
25
25
|
export const SETTINGS_NAMESPACE = 'dsh-messenger-gateway'
|
|
26
26
|
export { Config }
|
|
27
27
|
|
|
28
|
-
function resolveConfig(raw) {
|
|
28
|
+
export function resolveConfig(raw) {
|
|
29
29
|
// Unwrap once here: everything downstream reads plain values.
|
|
30
30
|
const plain = plainConfig(raw)
|
|
31
31
|
const cfg = plainConfig(Config(plain))
|
|
@@ -36,85 +36,73 @@ function resolveConfig(raw) {
|
|
|
36
36
|
return cfg
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
+
// Fields with role('secret') in the schema (#232): the projection never
|
|
40
|
+
// exposes the value — only a `<field>Configured` flag (plus proxyUrlMasked
|
|
41
|
+
// for the proxy). Keeping this list explicit makes the security surface
|
|
42
|
+
// reviewable.
|
|
43
|
+
const SECRET_FIELDS = new Set([
|
|
44
|
+
'telegram.botToken',
|
|
45
|
+
'telegram.webhookSecret',
|
|
46
|
+
'telegram.proxyUrl',
|
|
47
|
+
'discord.botToken',
|
|
48
|
+
'slack.botToken',
|
|
49
|
+
'webhooks.secret',
|
|
50
|
+
'memory.token',
|
|
51
|
+
])
|
|
52
|
+
|
|
53
|
+
// Fields never exposed to the client (server-internal values).
|
|
54
|
+
const HIDDEN_FIELDS = new Set([
|
|
55
|
+
'media.cacheDir',
|
|
56
|
+
])
|
|
57
|
+
|
|
39
58
|
export function publicConfig(cfg, gw, ctx) {
|
|
40
|
-
const internalBaseURL = gw?.baseUrl?.() || resolveInternalBaseUrl(cfg, ctx)
|
|
41
59
|
const proxy = describeProxy(cfg.telegram?.proxyUrl)
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
proxyLabel: proxy.label || '',
|
|
77
|
-
proxySource: proxy.source || '',
|
|
78
|
-
proxyError: proxy.error || '',
|
|
79
|
-
voiceMode: cfg.telegram.voiceMode,
|
|
80
|
-
quickActions: cfg.telegram.quickActions !== false,
|
|
81
|
-
artifactPreviews: cfg.telegram.artifactPreviews !== false,
|
|
82
|
-
notifyBridge: {
|
|
83
|
-
enabled: Boolean(cfg.telegram.notifyBridge?.enabled),
|
|
84
|
-
events: cfg.telegram.notifyBridge?.events || ['task_done', 'error'],
|
|
85
|
-
home: cfg.telegram.notifyBridge?.home || 'default',
|
|
86
|
-
excludeSessionPrefixes: cfg.telegram.notifyBridge?.excludeSessionPrefixes || ['msgw-'],
|
|
87
|
-
},
|
|
88
|
-
forumMirrorEnabled: Boolean(cfg.telegram.forumMirrorEnabled),
|
|
89
|
-
forumMirrorChatId: cfg.telegram.forumMirrorChatId || '',
|
|
90
|
-
},
|
|
91
|
-
discord: {
|
|
92
|
-
enabled: Boolean(cfg.discord?.enabled),
|
|
93
|
-
botTokenConfigured: Boolean(String(cfg.discord?.botToken || '').trim()),
|
|
94
|
-
webhookConfigured: Boolean(String(cfg.discord?.webhookUrl || '').trim()),
|
|
95
|
-
},
|
|
96
|
-
slack: {
|
|
97
|
-
enabled: Boolean(cfg.slack?.enabled),
|
|
98
|
-
botTokenConfigured: Boolean(String(cfg.slack?.botToken || '').trim()),
|
|
99
|
-
webhookConfigured: Boolean(String(cfg.slack?.webhookUrl || '').trim()),
|
|
100
|
-
},
|
|
101
|
-
media: { maxDocBytes: cfg.media.maxDocBytes, maxTextInjectBytes: cfg.media.maxTextInjectBytes, maxImageBytes: cfg.media.maxImageBytes },
|
|
102
|
-
tts: cfg.tts,
|
|
103
|
-
agent: {
|
|
104
|
-
provider: cfg.agent.provider,
|
|
105
|
-
model: cfg.agent.model,
|
|
106
|
-
cwd: cfg.agent.cwd || '',
|
|
107
|
-
effectiveCwd: resolveEffectiveCwd(cfg.agent.cwd, ctx?.logger),
|
|
108
|
-
defaultCwd: process.cwd(),
|
|
109
|
-
cwdWarning: getCwdWarning(cfg.agent.cwd),
|
|
110
|
-
photoOnlyMode: cfg.agent.photoOnlyMode,
|
|
111
|
-
maxMessageLength: cfg.agent.maxMessageLength,
|
|
112
|
-
turnTimeoutMs: cfg.agent.turnTimeoutMs,
|
|
113
|
-
idleTimeoutMs: cfg.agent.idleTimeoutMs,
|
|
114
|
-
instructionPrefix: cfg.agent.instructionPrefix,
|
|
115
|
-
sessionScope: cfg.agent.sessionScope,
|
|
116
|
-
},
|
|
60
|
+
// Schema-driven projection (#232): start from the resolved config itself —
|
|
61
|
+
// every schema field is projected automatically — then replace secrets
|
|
62
|
+
// with configured-flags and append derived runtime values. The parity test
|
|
63
|
+
// asserts every resolved schema leaf is covered.
|
|
64
|
+
const projected = {}
|
|
65
|
+
for (const [section, value] of Object.entries(cfg)) {
|
|
66
|
+
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
67
|
+
const out = {}
|
|
68
|
+
for (const [key, v] of Object.entries(value)) {
|
|
69
|
+
const path = `${section}.${key}`
|
|
70
|
+
if (HIDDEN_FIELDS.has(path)) continue
|
|
71
|
+
if (SECRET_FIELDS.has(path)) {
|
|
72
|
+
out[`${key}Configured`] = Boolean(String(v ?? '').trim())
|
|
73
|
+
if (path === 'telegram.proxyUrl') out.proxyUrlMasked = maskProxyUrl(v || '')
|
|
74
|
+
continue
|
|
75
|
+
}
|
|
76
|
+
out[key] = v
|
|
77
|
+
}
|
|
78
|
+
projected[section] = out
|
|
79
|
+
} else {
|
|
80
|
+
projected[section] = value
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
const tg = projected.telegram || {}
|
|
84
|
+
// Derived runtime values (not stored config) appended on top of the walk.
|
|
85
|
+
tg.homes = listHomes(cfg.telegram)
|
|
86
|
+
tg.proxyActive = Boolean(proxy.active)
|
|
87
|
+
tg.proxyLabel = proxy.label || ''
|
|
88
|
+
tg.proxySource = proxy.source || ''
|
|
89
|
+
tg.proxyError = proxy.error || ''
|
|
90
|
+
projected.internalBaseURL = gw?.baseUrl?.() || resolveInternalBaseUrl(cfg, ctx)
|
|
91
|
+
projected.discord = {
|
|
92
|
+
...projected.discord,
|
|
93
|
+
webhookConfigured: Boolean(String(cfg.discord?.webhookUrl || '').trim()),
|
|
117
94
|
}
|
|
95
|
+
projected.slack = {
|
|
96
|
+
...projected.slack,
|
|
97
|
+
webhookConfigured: Boolean(String(cfg.slack?.webhookUrl || '').trim()),
|
|
98
|
+
}
|
|
99
|
+
projected.agent = {
|
|
100
|
+
...projected.agent,
|
|
101
|
+
effectiveCwd: resolveEffectiveCwd(cfg.agent?.cwd, ctx?.logger),
|
|
102
|
+
defaultCwd: process.cwd(),
|
|
103
|
+
cwdWarning: getCwdWarning(cfg.agent?.cwd),
|
|
104
|
+
}
|
|
105
|
+
return projected
|
|
118
106
|
}
|
|
119
107
|
|
|
120
108
|
async function readJsonSafe(req, res, maxBytes = 1_048_576) {
|
|
@@ -249,85 +237,116 @@ export function apply(ctx, config) {
|
|
|
249
237
|
})
|
|
250
238
|
}
|
|
251
239
|
|
|
240
|
+
// Gateway hooks are static: they read the CURRENT config at execution time
|
|
241
|
+
// through the settings writer mutex, so they can be created once (#224).
|
|
242
|
+
const gatewayHooks = {
|
|
243
|
+
persistAllowedUserIds: async (ids) => {
|
|
244
|
+
if (!settingsApi?.isReady?.()) return
|
|
245
|
+
await settingsApi.writeExclusive(async (api) => {
|
|
246
|
+
const cur = source()
|
|
247
|
+
await api.replace(Config({
|
|
248
|
+
...cur,
|
|
249
|
+
telegram: { ...cur.telegram, allowedUserIds: ids },
|
|
250
|
+
}))
|
|
251
|
+
})
|
|
252
|
+
},
|
|
253
|
+
persistHome: async ({ chatId, threadId }) => {
|
|
254
|
+
if (!settingsApi?.isReady?.()) throw new Error('settings not ready')
|
|
255
|
+
await settingsApi.writeExclusive(async (api) => {
|
|
256
|
+
const cur = source()
|
|
257
|
+
await api.replace(Config({
|
|
258
|
+
...cur,
|
|
259
|
+
telegram: { ...cur.telegram, homeChatId: chatId, homeThreadId: threadId || 0 },
|
|
260
|
+
}))
|
|
261
|
+
})
|
|
262
|
+
},
|
|
263
|
+
persistHomes: async (nextTelegram) => {
|
|
264
|
+
if (!settingsApi?.isReady?.()) throw new Error('settings not ready')
|
|
265
|
+
await settingsApi.writeExclusive(async (api) => {
|
|
266
|
+
const cur = source()
|
|
267
|
+
await api.replace(Config({
|
|
268
|
+
...cur,
|
|
269
|
+
telegram: { ...cur.telegram, ...nextTelegram },
|
|
270
|
+
}))
|
|
271
|
+
})
|
|
272
|
+
},
|
|
273
|
+
persistAgentModel: async ({ provider, model }) => {
|
|
274
|
+
if (!settingsApi?.isReady?.()) return
|
|
275
|
+
await settingsApi.writeExclusive(async (api) => {
|
|
276
|
+
const cur = source()
|
|
277
|
+
await api.replace(Config({
|
|
278
|
+
...cur,
|
|
279
|
+
agent: { ...cur.agent, provider, model },
|
|
280
|
+
}))
|
|
281
|
+
})
|
|
282
|
+
},
|
|
283
|
+
// Runtime toggles from chat commands (#222): /voice summary and
|
|
284
|
+
// /keyboard on|off now survive config syncs like every other writer.
|
|
285
|
+
persistVoiceSummary: async (on) => {
|
|
286
|
+
if (!settingsApi?.isReady?.()) return
|
|
287
|
+
await settingsApi.writeExclusive(async (api) => {
|
|
288
|
+
const cur = source()
|
|
289
|
+
await api.replace(Config({
|
|
290
|
+
...cur,
|
|
291
|
+
tts: { ...cur.tts, voiceSummary: on },
|
|
292
|
+
}))
|
|
293
|
+
})
|
|
294
|
+
},
|
|
295
|
+
persistQuickActions: async (on) => {
|
|
296
|
+
if (!settingsApi?.isReady?.()) return
|
|
297
|
+
await settingsApi.writeExclusive(async (api) => {
|
|
298
|
+
const cur = source()
|
|
299
|
+
await api.replace(Config({
|
|
300
|
+
...cur,
|
|
301
|
+
telegram: { ...cur.telegram, quickActions: on },
|
|
302
|
+
}))
|
|
303
|
+
})
|
|
304
|
+
},
|
|
305
|
+
}
|
|
306
|
+
|
|
252
307
|
let lastSyncSignature
|
|
308
|
+
let lastTransportSignature
|
|
309
|
+
let syncChain = Promise.resolve()
|
|
310
|
+
const startGateway = (cfg) => {
|
|
311
|
+
gateway = new Gateway(ctx, cfg, gatewayHooks)
|
|
312
|
+
gateway.start().catch((err) => ctx.logger?.warn?.(`dsh-messenger-gateway: ${err.message}`))
|
|
313
|
+
}
|
|
253
314
|
const sync = () => {
|
|
254
315
|
syncWebhookRoute()
|
|
255
316
|
const effective = source()
|
|
256
|
-
// DSH sends several events for one settings write
|
|
257
|
-
// drops live sessions and resets the Telegram polling offset. Restart only
|
|
258
|
-
// when the resolved config actually changed.
|
|
317
|
+
// DSH sends several events for one settings write; skip identical repeats.
|
|
259
318
|
let signature
|
|
260
319
|
try { signature = JSON.stringify(effective) } catch { signature = undefined }
|
|
261
320
|
if (gateway && signature !== undefined && signature === lastSyncSignature) return
|
|
262
321
|
lastSyncSignature = signature
|
|
263
322
|
guardSecrets(effective).catch((err) => ctx.logger?.warn?.(`dsh-messenger-gateway: secret guard failed: ${err?.message || err}`))
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
if (!settingsApi?.isReady?.()) throw new Error('settings not ready')
|
|
289
|
-
await settingsApi.writeExclusive(async (api) => {
|
|
290
|
-
const cur = source()
|
|
291
|
-
await api.replace(Config({
|
|
292
|
-
...cur,
|
|
293
|
-
telegram: { ...cur.telegram, ...nextTelegram },
|
|
294
|
-
}))
|
|
295
|
-
})
|
|
296
|
-
},
|
|
297
|
-
persistAgentModel: async ({ provider, model }) => {
|
|
298
|
-
if (!settingsApi?.isReady?.()) return
|
|
299
|
-
await settingsApi.writeExclusive(async (api) => {
|
|
300
|
-
const cur = source()
|
|
301
|
-
await api.replace(Config({
|
|
302
|
-
...cur,
|
|
303
|
-
agent: { ...cur.agent, provider, model },
|
|
304
|
-
}))
|
|
305
|
-
})
|
|
306
|
-
},
|
|
307
|
-
// Runtime toggles from chat commands (#222): /voice summary and
|
|
308
|
-
// /keyboard on|off now survive config syncs like every other writer.
|
|
309
|
-
persistVoiceSummary: async (on) => {
|
|
310
|
-
if (!settingsApi?.isReady?.()) return
|
|
311
|
-
await settingsApi.writeExclusive(async (api) => {
|
|
312
|
-
const cur = source()
|
|
313
|
-
await api.replace(Config({
|
|
314
|
-
...cur,
|
|
315
|
-
tts: { ...cur.tts, voiceSummary: on },
|
|
316
|
-
}))
|
|
317
|
-
})
|
|
318
|
-
},
|
|
319
|
-
persistQuickActions: async (on) => {
|
|
320
|
-
if (!settingsApi?.isReady?.()) return
|
|
321
|
-
await settingsApi.writeExclusive(async (api) => {
|
|
322
|
-
const cur = source()
|
|
323
|
-
await api.replace(Config({
|
|
324
|
-
...cur,
|
|
325
|
-
telegram: { ...cur.telegram, quickActions: on },
|
|
326
|
-
}))
|
|
327
|
-
})
|
|
328
|
-
},
|
|
323
|
+
// Granular apply (#224): when the transport-critical slice is unchanged,
|
|
324
|
+
// swap the config on the LIVE gateway instead of tearing it down.
|
|
325
|
+
const transportSig = transportSignatureOf(effective)
|
|
326
|
+
if (gateway && transportSig === lastTransportSignature) {
|
|
327
|
+
gateway.applyConfig(effective)
|
|
328
|
+
return
|
|
329
|
+
}
|
|
330
|
+
lastTransportSignature = transportSig
|
|
331
|
+
if (effective.enabled === false) {
|
|
332
|
+
// Serialize even the shutdown path so it cannot interleave with a
|
|
333
|
+
// queued restart (#224).
|
|
334
|
+
const run = syncChain.then(async () => {
|
|
335
|
+
if (gateway) { await gateway.stop(); gateway = undefined }
|
|
336
|
+
})
|
|
337
|
+
syncChain = run.catch((err) => { ctx.logger?.debug?.('dsh-messenger-gateway: sync stop error:', err?.message || err) })
|
|
338
|
+
return
|
|
339
|
+
}
|
|
340
|
+
// Serialize gateway recreation: concurrent sync events queue their
|
|
341
|
+
// stop()/start() cycles instead of racing (#224). The queued run reads
|
|
342
|
+
// source() at execution time, so the last config always wins.
|
|
343
|
+
const run = syncChain.then(async () => {
|
|
344
|
+
const cfg = source()
|
|
345
|
+
if (gateway) { await gateway.stop(); gateway = undefined }
|
|
346
|
+
startGateway(cfg)
|
|
329
347
|
})
|
|
330
|
-
|
|
348
|
+
syncChain = run.catch((err) => { ctx.logger?.debug?.('dsh-messenger-gateway: sync restart error:', err?.message || err) })
|
|
349
|
+
return run
|
|
331
350
|
}
|
|
332
351
|
|
|
333
352
|
const settingsBridge = setupSettings(ctx, {
|
|
@@ -749,6 +768,10 @@ export function apply(ctx, config) {
|
|
|
749
768
|
if (payload.discord && !String(payload.discord.botToken || '').trim()) nextDiscord.botToken = cur.discord?.botToken
|
|
750
769
|
const nextSlack = { ...(cur.slack || {}), ...(payload.slack || {}) }
|
|
751
770
|
if (payload.slack && !String(payload.slack.botToken || '').trim()) nextSlack.botToken = cur.slack?.botToken
|
|
771
|
+
// memory.token is a secret: a payload without it must keep the
|
|
772
|
+
// stored value, so the section merges like every other (#237).
|
|
773
|
+
const nextMemory = { ...(cur.memory || {}), ...(payload.memory || {}) }
|
|
774
|
+
if (payload.memory && !String(payload.memory.token || '').trim()) nextMemory.token = cur.memory?.token
|
|
752
775
|
await api.replace(Config({
|
|
753
776
|
...cur,
|
|
754
777
|
...payload,
|
|
@@ -758,6 +781,7 @@ export function apply(ctx, config) {
|
|
|
758
781
|
tts: { ...cur.tts, ...(payload.tts || {}) },
|
|
759
782
|
agent: { ...cur.agent, ...(payload.agent || {}) },
|
|
760
783
|
media: { ...cur.media, ...(payload.media || {}) },
|
|
784
|
+
memory: nextMemory,
|
|
761
785
|
}))
|
|
762
786
|
})
|
|
763
787
|
sync()
|
package/lib/outbox.js
CHANGED
|
@@ -26,6 +26,7 @@ import { writeJsonAtomic } from './storage-atomic.js'
|
|
|
26
26
|
import { isTopicGoneError } from './telegram-errors.js'
|
|
27
27
|
|
|
28
28
|
const LOCK_STALE_MS = 30_000
|
|
29
|
+
const OUTBOX_SCHEMA_VERSION = 1
|
|
29
30
|
|
|
30
31
|
/**
|
|
31
32
|
* Exclusive lock file scoped to the queue (#218). Returns false when another
|
|
@@ -164,7 +165,9 @@ export function createOutboxQueue(options = {}) {
|
|
|
164
165
|
|
|
165
166
|
async function persist() {
|
|
166
167
|
try {
|
|
167
|
-
|
|
168
|
+
// schemaVersion envelope (#227): future format changes migrate instead
|
|
169
|
+
// of misreading; readers stay tolerant of legacy files without it.
|
|
170
|
+
await writeJsonAtomic(storagePath, { schemaVersion: OUTBOX_SCHEMA_VERSION, pending, dlq })
|
|
168
171
|
} catch (err) {
|
|
169
172
|
if (logger) {
|
|
170
173
|
logger.warn?.(`[outbox] failed to persist queue to disk: ${err.message}`)
|
package/lib/pairing.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { randomBytes
|
|
2
|
-
import {
|
|
3
|
-
import { dirname } from 'node:path'
|
|
1
|
+
import { randomBytes } from 'node:crypto'
|
|
2
|
+
import { writeJsonAtomicSync, readJsonStateSync, StateCorruptError } from './storage-atomic.js'
|
|
4
3
|
|
|
5
4
|
const ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
|
|
5
|
+
const PAIRING_SCHEMA_VERSION = 1
|
|
6
6
|
|
|
7
7
|
export function generatePairingCode(length = 8) {
|
|
8
8
|
const bytes = randomBytes(length)
|
|
@@ -11,35 +11,50 @@ export function generatePairingCode(length = 8) {
|
|
|
11
11
|
return out
|
|
12
12
|
}
|
|
13
13
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
}
|
|
14
|
+
const migratePairing = (raw) => ({
|
|
15
|
+
schemaVersion: PAIRING_SCHEMA_VERSION,
|
|
16
|
+
approved: Array.isArray(raw?.approved) ? raw.approved : [],
|
|
17
|
+
pending: raw?.pending && typeof raw.pending === 'object' ? raw.pending : {},
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
const logLoadFailure = (logger, err) => {
|
|
21
|
+
const detail = err instanceof StateCorruptError
|
|
22
|
+
? `state file corrupted and unrecoverable; access stays fail-closed (empty allowlist); corrupted copy preserved at ${err.corruptBackup || 'an unknown path'}`
|
|
23
|
+
: `read error: ${err?.message || err}`
|
|
24
|
+
const message = `[dsh-messenger-gateway] pairing store ${detail}`
|
|
25
|
+
if (typeof logger?.error === 'function') logger.error(message)
|
|
26
|
+
else logger?.warn?.(message)
|
|
25
27
|
}
|
|
26
28
|
|
|
27
29
|
/** @param {string} filePath @param {any} [opts] */
|
|
28
30
|
export function createPairingStore(filePath, { logger } = {}) {
|
|
29
31
|
const state = { pending: {}, /** @type {number[]} */ approved: [] }
|
|
30
|
-
if (filePath
|
|
32
|
+
if (filePath) {
|
|
31
33
|
try {
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
|
|
34
|
+
const { data, recovered, corruptBackup } = readJsonStateSync(filePath, {
|
|
35
|
+
version: PAIRING_SCHEMA_VERSION,
|
|
36
|
+
migrate: migratePairing,
|
|
37
|
+
})
|
|
38
|
+
if (data) {
|
|
39
|
+
state.approved = (data.approved || []).map(Number).filter(Number.isFinite)
|
|
40
|
+
state.pending = data.pending && typeof data.pending === 'object' ? data.pending : {}
|
|
41
|
+
}
|
|
42
|
+
if (recovered) {
|
|
43
|
+
logger?.warn?.(`[dsh-messenger-gateway] pairing store recovered from .bak after corruption; preserved copy: ${corruptBackup}`)
|
|
44
|
+
}
|
|
35
45
|
} catch (err) {
|
|
36
|
-
|
|
46
|
+
if (err instanceof StateCorruptError || err?.name === 'StateVersionError') logLoadFailure(logger, err)
|
|
47
|
+
else logger?.warn?.('[dsh-messenger-gateway] pairing store read error:', err?.message || err)
|
|
37
48
|
}
|
|
38
49
|
}
|
|
39
50
|
const persist = () => {
|
|
40
51
|
if (!filePath) return
|
|
41
52
|
try {
|
|
42
|
-
writeJsonAtomicSync(filePath, {
|
|
53
|
+
writeJsonAtomicSync(filePath, {
|
|
54
|
+
schemaVersion: PAIRING_SCHEMA_VERSION,
|
|
55
|
+
approved: state.approved,
|
|
56
|
+
pending: state.pending,
|
|
57
|
+
})
|
|
43
58
|
} catch (err) {
|
|
44
59
|
logger?.warn?.('[dsh-messenger-gateway] pairing store persist error:', err?.message || err)
|
|
45
60
|
}
|
package/lib/personas.js
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { writeJsonAtomicSync } from './storage-atomic.js'
|
|
1
|
+
import { writeJsonAtomicSync, readJsonStateSync, StateCorruptError } from './storage-atomic.js'
|
|
3
2
|
|
|
4
3
|
export const BUILTIN_PERSONAS = {
|
|
5
4
|
default: {
|
|
@@ -70,25 +69,42 @@ export function listPersonas() {
|
|
|
70
69
|
return Object.values(BUILTIN_PERSONAS)
|
|
71
70
|
}
|
|
72
71
|
|
|
72
|
+
const PERSONAS_SCHEMA_VERSION = 1
|
|
73
|
+
|
|
74
|
+
// Legacy files either carried {personas, presets} at the top level or a bare
|
|
75
|
+
// persona map; v1 wraps everything under a versioned envelope (#227).
|
|
76
|
+
const migratePersonas = (raw) => {
|
|
77
|
+
if (raw && typeof raw === 'object' && (raw.personas || raw.presets)) {
|
|
78
|
+
return { schemaVersion: PERSONAS_SCHEMA_VERSION, personas: raw.personas || {}, presets: raw.presets || {} }
|
|
79
|
+
}
|
|
80
|
+
return { schemaVersion: PERSONAS_SCHEMA_VERSION, personas: (raw && typeof raw === 'object') ? raw : {}, presets: {} }
|
|
81
|
+
}
|
|
82
|
+
|
|
73
83
|
/** @param {string} filePath @param {any} [opts] */
|
|
74
84
|
export function createPersonaStore(filePath, { logger } = {}) {
|
|
75
85
|
let cache = { personas: {}, presets: {} }
|
|
76
86
|
try {
|
|
77
|
-
const
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
}
|
|
87
|
+
const { data, recovered, corruptBackup } = readJsonStateSync(filePath, {
|
|
88
|
+
version: PERSONAS_SCHEMA_VERSION,
|
|
89
|
+
migrate: migratePersonas,
|
|
90
|
+
})
|
|
91
|
+
if (data) cache = { personas: data.personas || {}, presets: data.presets || {} }
|
|
92
|
+
if (recovered) {
|
|
93
|
+
logger?.warn?.(`[dsh-messenger-gateway] personas store recovered from .bak after corruption; preserved copy: ${corruptBackup}`)
|
|
84
94
|
}
|
|
85
95
|
} catch (err) {
|
|
86
|
-
if (err
|
|
96
|
+
if (err instanceof StateCorruptError || err?.name === 'StateVersionError') {
|
|
97
|
+
const message = `[dsh-messenger-gateway] personas store corrupted; starting empty; corrupted copy preserved at ${err.corruptBackup || filePath}`
|
|
98
|
+
if (typeof logger?.error === 'function') logger.error(message)
|
|
99
|
+
else logger?.warn?.(message)
|
|
100
|
+
} else if (err?.code !== 'ENOENT') {
|
|
101
|
+
logger?.warn?.('[dsh-messenger-gateway] personas load error:', err?.message || err)
|
|
102
|
+
}
|
|
87
103
|
}
|
|
88
104
|
|
|
89
105
|
function save() {
|
|
90
106
|
try {
|
|
91
|
-
writeJsonAtomicSync(filePath, cache)
|
|
107
|
+
writeJsonAtomicSync(filePath, { schemaVersion: PERSONAS_SCHEMA_VERSION, ...cache })
|
|
92
108
|
} catch (err) {
|
|
93
109
|
logger?.warn?.('[dsh-messenger-gateway] personas save error:', err?.message || err)
|
|
94
110
|
}
|
package/lib/scheduler.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { readFile } from 'node:fs/promises'
|
|
2
1
|
import { randomUUID } from 'node:crypto'
|
|
3
|
-
import { writeJsonAtomic } from './storage-atomic.js'
|
|
2
|
+
import { writeJsonAtomic, readJsonStateSync, StateCorruptError } from './storage-atomic.js'
|
|
3
|
+
|
|
4
|
+
const SCHEDULER_SCHEMA_VERSION = 1
|
|
4
5
|
|
|
5
6
|
export function parseRelativeTime(input) {
|
|
6
7
|
if (!input) return null
|
|
@@ -39,18 +40,36 @@ export function createScheduler(filePath, onDue, options = {}) {
|
|
|
39
40
|
let loaded = false
|
|
40
41
|
let timer = null
|
|
41
42
|
|
|
43
|
+
// Legacy files were a bare task array; v1 adds the schema envelope (#227).
|
|
44
|
+
// A `null` tasks value marks a legacy payload that was never a task array:
|
|
45
|
+
// load() reports it with the historic "invalid tasks payload" warning.
|
|
46
|
+
const migrateScheduler = (raw) => ({
|
|
47
|
+
schemaVersion: SCHEDULER_SCHEMA_VERSION,
|
|
48
|
+
tasks: Array.isArray(raw) ? raw : (Array.isArray(raw?.tasks) ? raw.tasks : null),
|
|
49
|
+
})
|
|
50
|
+
|
|
42
51
|
async function load() {
|
|
43
52
|
try {
|
|
44
|
-
const
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
53
|
+
const { data, recovered, corruptBackup } = readJsonStateSync(filePath, {
|
|
54
|
+
version: SCHEDULER_SCHEMA_VERSION,
|
|
55
|
+
migrate: migrateScheduler,
|
|
56
|
+
})
|
|
57
|
+
if (data) {
|
|
58
|
+
if (Array.isArray(data.tasks)) tasks = data.tasks
|
|
59
|
+
else {
|
|
60
|
+
logger?.warn?.(`[dsh-messenger-gateway] scheduler invalid tasks payload in ${filePath}: expected array, got ${typeof data.tasks}; resetting to empty list`)
|
|
61
|
+
tasks = []
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (recovered) {
|
|
65
|
+
logger?.warn?.(`[dsh-messenger-gateway] scheduler recovered from .bak after corruption; preserved copy: ${corruptBackup}`)
|
|
51
66
|
}
|
|
52
67
|
} catch (err) {
|
|
53
|
-
if (err?.
|
|
68
|
+
if (err instanceof StateCorruptError || err?.name === 'StateVersionError') {
|
|
69
|
+
const message = `[dsh-messenger-gateway] scheduler state corrupted; reminders lost unless a preserved copy is restored manually; corrupted file kept at ${err.corruptBackup || filePath}`
|
|
70
|
+
if (typeof logger?.error === 'function') logger.error(message)
|
|
71
|
+
else logger?.warn?.(message)
|
|
72
|
+
} else if (err?.code !== 'ENOENT') {
|
|
54
73
|
logger?.warn?.('[dsh-messenger-gateway] scheduler load error:', err?.message || err)
|
|
55
74
|
}
|
|
56
75
|
tasks = []
|
|
@@ -70,7 +89,7 @@ export function createScheduler(filePath, onDue, options = {}) {
|
|
|
70
89
|
const finishTime = t.firedAt || t.createdAt || 0
|
|
71
90
|
return (now - finishTime) < RETENTION_MS
|
|
72
91
|
})
|
|
73
|
-
await writeJsonAtomic(filePath, tasks)
|
|
92
|
+
await writeJsonAtomic(filePath, { schemaVersion: SCHEDULER_SCHEMA_VERSION, tasks })
|
|
74
93
|
} catch (err) {
|
|
75
94
|
logger?.warn?.('[dsh-messenger-gateway] scheduler save failed:', err?.message || err)
|
|
76
95
|
}
|
package/lib/secret-guard.js
CHANGED
|
@@ -11,9 +11,11 @@
|
|
|
11
11
|
export const SECRET_FIELDS = [
|
|
12
12
|
['telegram', 'botToken'],
|
|
13
13
|
['telegram', 'webhookSecret'],
|
|
14
|
+
['telegram', 'proxyUrl'],
|
|
14
15
|
['discord', 'botToken'],
|
|
15
16
|
['slack', 'botToken'],
|
|
16
17
|
['webhooks', 'secret'],
|
|
18
|
+
['memory', 'token'],
|
|
17
19
|
]
|
|
18
20
|
|
|
19
21
|
function keyOf(section, field) {
|