Files
mnemazine/scripts/mnemazine-telegram-bot.mjs
T
zarubinvibeandЗарубин Филипп 3b7c85bae5 feat(telegram): intake bot + Mini App + guided installer (#2)
* feat(telegram): bot intake → inbox + daily VPS pull sync

- mnemazine-telegram-bot.mjs: zero-dep long-poll bot, writes text/photo/doc/voice/audio/video into staging inbox; chat_id allowlist; --selftest
- mnemazine-telegram-sync.sh: daily rsync pull VPS buffer → local inbox, then npm run run
- launchd plist template for daily 09:00 schedule

* feat(telegram): Mini App — status/send/run-now + reverse-channel poller

- webapp/index.html: Telegram Mini App (theme-aware, minimal); buffer status, send-to-inbox, run-now
- mnemazine-webapp-server.mjs: localhost API, initData HMAC verify + user allowlist, /api/{status,send,run}; --selftest
- run-now reverse channel: API touches .run-now; poll.sh consumes flag, Mac pulls+runs
- poll.sh: 5-min launchd tick — manual flag or daily 09:00 window; writes .last-run for app
- sync.sh: drop exec so markers persist; plist → StartInterval 300

* docs: Telegram intake architecture (bot + Mini App), EN+RU, no secrets

Generic scheme — host/secrets/domain abstracted. Linked from both READMEs.

* feat(setup): guided step-by-step installer for fresh devices

- setup.sh: staged wizard, numbered-menu questions, gates each stage
- checks prereqs and says exactly what to install before continuing
- missing capability → 'Друг, значит этого тебе не оставим' + continue
- asks inbox location (repo vs Desktop); optional Telegram bot incl. VPS deploy
- MNEMAZINE_SETUP_DRYRUN=1 walks stages without installing/deploying
- README EN+RU point to it

* fix(telegram): C1/C2 — secrets out of git, two-phase move (no data loss)

Phase 0+1.1 of audit fix plan:
- poll.sh/sync.sh: drop hardcoded VPS host/key → placeholders + gitignored .mnemazine/config.env (fail-fast on placeholder)
- sync.sh: two-phase move — pull to staging, promote, run protocol, delete on VPS ONLY after success (closes --remove-source-files data-loss window); deletes only files it took
- config.env.example template; .mnemazine/config.env gitignored
- selftest chat_id fixture 1 → 1 (was real personal id)

* fix(telegram): C3/C4 — kill stored-XSS + initData replay window

- webapp: render inbox file names via textContent/createElement (was innerHTML — file names come from untrusted Telegram uploads); add strict CSP meta
- webapp-server: verifyInitData now rejects stale auth_date (default 24h TTL, MNEMAZINE_INITDATA_TTL); closes forever-valid captured initData
- selftest: assert stale initData rejected (C7 — test from the threat, not current behavior)

* fix(telegram): C5 reliability — stop storm, TTY-guard, fail-closed, DoS caps

Phase 2:
- poll.sh: write daily marker BEFORE sync (no 5-min storm on failure); mkdir single-flight lock (macOS has no flock) with 60-min stale steal; re-queue manual run-now on failure. plist: RunAtLoad
- setup.sh: read EOF/TTY guard (no infinite loop under curl|bash/CI); gate install.sh exit code (stage actually gates)
- bot: advance/persist offset only AFTER successful handle (at-least-once, no dropped message); fail-closed allowlist (empty = reject + log id, not accept-all); cap download size 30MB; sanitize file extension (no traversal)
- webapp-server: cap request body 64KB (413); 500 returns generic error, detail to stderr only

* feat(telegram): C6 vault-patterns — run audit, config.env boundary, idempotent setup

Phase 3:
- /api/run: flag now carries {at, by} audit (kept as coalescing flag, not a full job queue — single user/button; YAGNI)
- 3.2 fenceUntrusted already covered: digest/synthesize fence note bodies at the LLM boundary (mnemazine-llm.mjs); inbox stays raw by design
- setup.sh: writes .mnemazine/config.env (chmod 600) from entered VPS details so poll/sync read the boundary; idempotent pm2 (start||restart) for rerun-safe deploy

* feat(telegram): Phase 4 polish — confirm run, auto-refresh, access log, throttle

- frontend: tg.showConfirm before run (no accidental token-spend); auto-refresh status every 15s while visible + on visibilitychange
- server: structured access log (stderr {ts,user,method,path}); light per-user 1/sec write throttle (429)

---------

Co-authored-by: Зарубин Филипп <289370046+zarubinphil@users.noreply.github.com>
2026-06-19 13:03:46 +03:00

158 lines
6.8 KiB
JavaScript
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env node
// Mnemazine Telegram intake bot.
// Long-polls getUpdates, writes each message into a staging inbox dir as a
// file the Mnemazine protocol can pick up. Native fetch only, zero deps.
//
// Env:
// TELEGRAM_BOT_TOKEN (required) bot token from @BotFather
// MNEMAZINE_INBOX (optional) target dir, default ./inbox
// ALLOWED_CHAT_IDS (optional) comma-separated chat ids; if set, others ignored
//
// On a host (VPS) it runs under pm2; the Mac pulls the staging dir daily.
// ponytail: long-poll, not webhook — no TLS/public-port setup, Telegram buffers ~24h.
import fs from 'node:fs/promises'
import path from 'node:path'
const SELFTEST = process.argv.includes('--selftest')
const TOKEN = process.env.TELEGRAM_BOT_TOKEN
if (!TOKEN && !SELFTEST) {
console.error('FATAL: TELEGRAM_BOT_TOKEN not set')
process.exit(1)
}
const API = `https://api.telegram.org/bot${TOKEN}`
const FILE_API = `https://api.telegram.org/file/bot${TOKEN}`
let INBOX = path.resolve(process.env.MNEMAZINE_INBOX || path.join(process.cwd(), 'inbox'))
const OFFSET_FILE = path.join(INBOX, '.telegram-offset')
const ALLOWED = (process.env.ALLOWED_CHAT_IDS || '')
.split(',').map(s => s.trim()).filter(Boolean)
const api = async (method, params) => {
const res = await fetch(`${API}/${method}`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(params || {}),
})
const json = await res.json()
if (!json.ok) throw new Error(`${method}: ${json.description}`)
return json.result
}
const sanitize = name => (name || 'file').replace(/[^\w.\-а-яёА-ЯЁ]+/gu, '_').slice(0, 80)
async function downloadFile(fileId, suggestedName) {
const f = await api('getFile', { file_id: fileId })
const url = `${FILE_API}/${f.file_path}`
const res = await fetch(url)
if (!res.ok) throw new Error(`download ${fileId}: HTTP ${res.status}`)
// Cap download size to avoid OOM on a hostile/huge file (Telegram tops ~20 MB).
const MAX_FILE = 30 * 1024 * 1024
const len = Number(res.headers.get('content-length') || 0)
if (len > MAX_FILE) throw new Error(`download ${fileId}: too large (${len} bytes)`)
const buf = Buffer.from(await res.arrayBuffer())
if (buf.length > MAX_FILE) throw new Error(`download ${fileId}: too large (${buf.length} bytes)`)
const rawExt = path.extname(f.file_path) || path.extname(suggestedName || '') || ''
const ext = rawExt.replace(/[^.\w]/g, '').slice(0, 12) // no path separators / traversal
const base = suggestedName ? sanitize(path.basename(suggestedName, path.extname(suggestedName))) : sanitize(path.basename(f.file_path, ext))
const stamp = new Date().toISOString().slice(0, 10)
const target = path.join(INBOX, `tg_${stamp}_${base}${ext}`)
await fs.writeFile(target, buf)
return path.basename(target)
}
async function writeText(msg, text) {
const stamp = new Date().toISOString().slice(0, 10)
const from = msg.from?.username || msg.from?.first_name || msg.chat?.id
const body = [
'---',
`source: telegram`,
`from: ${from}`,
`chat_id: ${msg.chat?.id}`,
`date: ${new Date((msg.date || 0) * 1000).toISOString()}`,
'---',
'',
text,
'',
].join('\n')
const target = path.join(INBOX, `tg_${stamp}_${msg.message_id}.md`)
await fs.writeFile(target, body, 'utf8')
return path.basename(target)
}
async function handle(msg) {
const chatId = String(msg.chat?.id ?? '')
console.log(`[msg] chat_id=${chatId} from=${msg.from?.username || msg.from?.first_name || '?'}`)
// Fail-closed: an empty allowlist rejects everyone (still logs the id so you
// can configure it), rather than accepting any stranger who finds the bot.
if (!ALLOWED.length) {
console.log(`[reject] ALLOWED_CHAT_IDS empty — set it to "${chatId}" then restart to accept`)
return
}
if (!ALLOWED.includes(chatId)) {
console.log(`[skip] chat_id ${chatId} not in ALLOWED_CHAT_IDS`)
return
}
const saved = []
if (msg.photo?.length) saved.push(await downloadFile(msg.photo[msg.photo.length - 1].file_id))
if (msg.document) saved.push(await downloadFile(msg.document.file_id, msg.document.file_name))
if (msg.voice) saved.push(await downloadFile(msg.voice.file_id, `voice_${msg.message_id}.ogg`))
if (msg.audio) saved.push(await downloadFile(msg.audio.file_id, msg.audio.file_name || `audio_${msg.message_id}.mp3`))
if (msg.video) saved.push(await downloadFile(msg.video.file_id, `video_${msg.message_id}.mp4`))
if (msg.video_note) saved.push(await downloadFile(msg.video_note.file_id, `videonote_${msg.message_id}.mp4`))
const text = msg.text || msg.caption
if (text) saved.push(await writeText(msg, text))
if (!saved.length) console.log('[skip] no usable content (sticker/location/etc)')
else { console.log(`[saved] ${saved.join(', ')}`); try { await api('sendMessage', { chat_id: chatId, text: `✓ в inbox: ${saved.length}` }) } catch {} }
}
async function selftest() {
const assert = (c, m) => { if (!c) throw new Error(`selftest: ${m}`) }
assert(sanitize('a/b c?.PNG') === 'a_b_c_.PNG', `sanitize got "${sanitize('a/b c?.PNG')}"`)
assert(sanitize('Файл №1.pdf') === 'Файл_1.pdf', `cyrillic got "${sanitize('Файл №1.pdf')}"`)
assert(sanitize('') === 'file', 'empty name fallback')
const tmp = path.join(process.cwd(), '.mnemazine', 'tg-selftest')
await fs.mkdir(tmp, { recursive: true })
const orig = INBOX; INBOX = tmp
const name = await writeText({ message_id: 7, chat: { id: 42 }, from: { username: 'u' }, date: 0 }, 'hello')
const written = await fs.readFile(path.join(tmp, name), 'utf8')
INBOX = orig
assert(written.includes('source: telegram') && written.includes('hello'), 'writeText frontmatter/body')
await fs.rm(tmp, { recursive: true, force: true })
console.log('selftest ok')
}
async function loadOffset() {
try { return Number(await fs.readFile(OFFSET_FILE, 'utf8')) || 0 } catch { return 0 }
}
async function main() {
await fs.mkdir(INBOX, { recursive: true })
let offset = await loadOffset()
console.log(`Mnemazine TG bot up. inbox=${INBOX} allowlist=${ALLOWED.length ? ALLOWED.join(',') : 'OPEN(bootstrap)'}`)
for (;;) {
try {
const updates = await api('getUpdates', { offset, timeout: 50, allowed_updates: ['message'] })
for (const u of updates) {
if (u.message) {
// At-least-once: only advance/persist the offset AFTER a successful
// handle. On failure, stop the batch so the next poll re-fetches it.
try { await handle(u.message) }
catch (e) { console.error(`[err] msg ${u.message.message_id}: ${e.message} — will retry`); break }
}
offset = u.update_id + 1
await fs.writeFile(OFFSET_FILE, String(offset), 'utf8')
}
} catch (e) {
console.error(`[poll] ${e.message}`)
await new Promise(r => setTimeout(r, 5000))
}
}
}
if (SELFTEST) selftest().catch(e => { console.error(e.message); process.exit(1) })
else main()