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>
This commit is contained in:
2026-06-19 13:03:46 +03:00
committed by GitHub
co-authored by Зарубин Филипп
parent 80376437b2
commit 3b7c85bae5
13 changed files with 1028 additions and 2 deletions
+136
View File
@@ -0,0 +1,136 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self' https://telegram.org; style-src 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; base-uri 'none'">
<title>Mnemazine</title>
<script src="https://telegram.org/js/telegram-web-app.js"></script>
<style>
:root {
--bg: var(--tg-theme-bg-color, #fff);
--text: var(--tg-theme-text-color, #111);
--hint: var(--tg-theme-hint-color, #888);
--card: var(--tg-theme-secondary-bg-color, #f4f4f5);
--accent: var(--tg-theme-button-color, #2481cc);
--accent-text: var(--tg-theme-button-text-color, #fff);
--radius: 16px;
}
* { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
body {
margin: 0; font: 16px/1.45 -apple-system, system-ui, sans-serif;
background: var(--bg); color: var(--text);
padding: 16px calc(16px + env(safe-area-inset-right)) calc(16px + env(safe-area-inset-bottom)) calc(16px + env(safe-area-inset-left));
}
h1 { font-size: 22px; font-weight: 600; letter-spacing: -0.02em; margin: 4px 0 18px; }
.card { background: var(--card); border-radius: var(--radius); padding: 16px; margin-bottom: 14px; }
.stat { display: flex; align-items: baseline; gap: 8px; }
.stat b { font-size: 34px; font-weight: 650; letter-spacing: -0.03em; }
.hint { color: var(--hint); font-size: 13px; }
ul { list-style: none; margin: 12px 0 0; padding: 0; }
li { font-size: 14px; padding: 7px 0; border-top: 1px solid color-mix(in srgb, var(--hint) 20%, transparent); display: flex; justify-content: space-between; gap: 10px; }
li span:last-child { color: var(--hint); flex: none; }
li:first-child { border-top: none; }
textarea {
width: 100%; min-height: 90px; resize: vertical; border: none; border-radius: 12px;
padding: 12px; font: inherit; background: var(--bg); color: var(--text);
outline: 1px solid color-mix(in srgb, var(--hint) 25%, transparent);
}
button {
width: 100%; border: none; border-radius: 12px; padding: 14px; margin-top: 10px;
font: inherit; font-weight: 600; background: var(--accent); color: var(--accent-text);
cursor: pointer; transition: opacity .15s, transform .05s;
}
button:active { transform: scale(.985); }
button:disabled { opacity: .5; }
button.ghost { background: transparent; color: var(--accent); outline: 1px solid color-mix(in srgb, var(--accent) 45%, transparent); }
.toast { position: fixed; left: 50%; bottom: 24px; transform: translateX(-50%); background: var(--text); color: var(--bg); padding: 10px 18px; border-radius: 20px; font-size: 14px; opacity: 0; transition: opacity .2s; pointer-events: none; }
.toast.show { opacity: .94; }
</style>
</head>
<body>
<h1>Mnemazine</h1>
<div class="card">
<div class="stat"><b id="count">—</b><span class="hint">в буфере</span></div>
<div class="hint" id="lastrun" style="margin-top:6px">последний прогон: —</div>
<ul id="recent"></ul>
</div>
<div class="card">
<textarea id="text" placeholder="Заметка, ссылка, мысль — в inbox Mnemazine…"></textarea>
<button id="send">В inbox</button>
</div>
<button class="ghost" id="run">Прогнать протокол сейчас</button>
<div class="toast" id="toast"></div>
<script>
const tg = window.Telegram?.WebApp
tg?.ready(); tg?.expand()
const initData = tg?.initData || ''
const $ = id => document.getElementById(id)
function toast(msg) { const t = $('toast'); t.textContent = msg; t.classList.add('show'); setTimeout(() => t.classList.remove('show'), 1800) }
async function api(path, opts = {}) {
const res = await fetch('api/' + path, {
...opts,
headers: { 'content-type': 'application/json', 'x-telegram-initdata': initData, ...(opts.headers || {}) },
})
if (!res.ok) throw new Error((await res.json().catch(() => ({}))).error || res.status)
return res.json()
}
function fmt(iso) { try { return new Date(iso).toLocaleString('ru-RU', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' }) } catch { return iso } }
async function refresh() {
try {
const s = await api('status')
$('count').textContent = s.count
$('lastrun').textContent = 'последний прогон: ' + (s.lastRun ? fmt(s.lastRun) : 'ещё не было')
// Build DOM with textContent — file names come from untrusted Telegram
// uploads; innerHTML here would be a stored-XSS sink.
const ul = $('recent'); ul.replaceChildren()
if (!s.recent.length) {
const li = document.createElement('li'); li.className = 'hint'; li.textContent = 'пусто'; ul.append(li)
} else for (const r of s.recent) {
const li = document.createElement('li')
const name = document.createElement('span'); name.textContent = r.name.replace(/^tg_/, '').replace(/\.md$/, '')
const at = document.createElement('span'); at.textContent = fmt(r.at)
li.append(name, at); ul.append(li)
}
} catch (e) { toast('Ошибка: ' + e.message) }
}
$('send').onclick = async () => {
const text = $('text').value.trim()
if (!text) return toast('Пусто')
$('send').disabled = true
try { await api('send', { method: 'POST', body: JSON.stringify({ text }) }); $('text').value = ''; toast('✓ в inbox'); refresh() }
catch (e) { toast('Ошибка: ' + e.message) }
finally { $('send').disabled = false }
}
async function doRun() {
tg?.HapticFeedback?.impactOccurred('medium')
$('run').disabled = true
try { await api('run', { method: 'POST' }); toast('✓ протокол поставлен в очередь') }
catch (e) { toast('Ошибка: ' + e.message) }
finally { setTimeout(() => $('run').disabled = false, 1500) }
}
$('run').onclick = () => {
// Confirm before kicking off a real (token-spending) protocol run.
if (tg?.showConfirm) tg.showConfirm('Запустить прогон протокола сейчас?', ok => { if (ok) doRun() })
else if (confirm('Запустить прогон протокола сейчас?')) doRun()
}
refresh()
// Keep status fresh while the app is open and visible.
setInterval(() => { if (document.visibilityState === 'visible') refresh() }, 15000)
document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') refresh() })
</script>
</body>
</html>