Files
mnemazine/docs/telegram-intake.md
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

4.5 KiB

Telegram intake (bot + Mini App)

Send anything to a Telegram bot — text, photo, document, voice, audio, video — and it lands in the Mnemazine inbox/. A small Mini App shows the buffer, lets you drop a quick note, and triggers a protocol run on demand. The daily auto-run still happens on schedule.

The protocol itself runs on your machine (local OCR engines, local LLM binary). The bot runs on an always-on host so it keeps receiving while your machine is asleep; your machine pulls the buffer and processes it. The host is only a transit buffer, never a second store.

Architecture

  Telegram ──message──▶ Bot (always-on host)
                          │ long-poll getUpdates (no webhook/TLS)
                          ▼
                    host staging inbox  ◀── Mini App: POST /api/send
                          │                  Mini App: POST /api/run → .run-now flag
                          │
        your machine ─────┤ pull, every ~5 min:
                          │   • .run-now flag present?  → run
                          │   • daily window reached?   → run
                          ▼
                  rsync --remove-source-files  (move; host stays thin)
                          ▼
                    local inbox/  ──▶  npm run run  (the protocol)
                          ▼
                        vault/        ──writes .last-run──▶ Mini App status

Reverse channel without a public machine: the host never reaches your machine. Your machine polls a flag the host sets. "Run now" in the Mini App just writes that flag; the next poll consumes it.

Components

Piece Where What
scripts/mnemazine-telegram-bot.mjs host Long-poll bot. Writes each message into the staging inbox. Zero deps.
scripts/mnemazine-webapp-server.mjs host Mini App API (/api/status, /api/send, /api/run). Verifies Telegram initData, enforces an allowlist. Zero deps.
webapp/index.html host (static) The Mini App UI. Theme-aware, single file.
scripts/mnemazine-telegram-poll.sh your machine ~5-min tick: consume run-now flag / daily window → pull + run.
scripts/mnemazine-telegram-sync.sh your machine rsync pull (move) + npm run run.
scripts/com.mnemazine.telegram-sync.plist.template your machine launchd agent (macOS) for the poll tick.

Setup

1. Bot on the host

TELEGRAM_BOT_TOKEN=<from @BotFather> \
MNEMAZINE_INBOX=/path/to/staging-inbox \
node scripts/mnemazine-telegram-bot.mjs

First message logs your chat_id. Lock the bot to yourself:

ALLOWED_CHAT_IDS=<your_chat_id>   # comma-separated for more

Restart with that env set. Unset = bootstrap mode (accepts, logs the id to set).

2. Mini App on the host

Serve webapp/index.html over HTTPS (Telegram requires TLS) and proxy /api/ to the API server:

TELEGRAM_BOT_TOKEN=<token> \
MNEMAZINE_INBOX=/path/to/staging-inbox \
ALLOWED_CHAT_IDS=<your_chat_id> \
PORT=8787 \
node scripts/mnemazine-webapp-server.mjs

Reverse-proxy example (any TLS-terminating front works):

location /mini/mnemazine/api/ { proxy_pass http://127.0.0.1:8787/api/; }
location /mini/mnemazine/     { alias /path/to/webapp/; index index.html; }

The page fetches api/... relative to its own path, so it works under any sub-path. Point the bot's menu button at the page URL:

curl -X POST "https://api.telegram.org/bot<token>/setChatMenuButton" \
  -H 'content-type: application/json' \
  -d '{"menu_button":{"type":"web_app","text":"Mnemazine",
       "web_app":{"url":"https://<your-host>/mini/mnemazine/"}}}'

3. Poller on your machine

# render the launchd template and load it (macOS)
sed 's#__REPO__#'"$PWD"'#g' \
  scripts/com.mnemazine.telegram-sync.plist.template \
  > ~/Library/LaunchAgents/com.mnemazine.telegram-sync.plist
launchctl load ~/Library/LaunchAgents/com.mnemazine.telegram-sync.plist

Override host/key/paths via MNEMAZINE_VPS, MNEMAZINE_VPS_KEY, MNEMAZINE_REMOTE_INBOX, MNEMAZINE_ROOT (see the script headers). On Linux, use a 5-minute cron entry calling mnemazine-telegram-poll.sh instead.

Security

  • The token is a secret — keep it in env / a secret store, never in git.
  • initData is HMAC-verified with the bot token; only allowlisted user ids pass.
  • The bot ignores messages from anyone outside ALLOWED_CHAT_IDS.

Self-tests

node scripts/mnemazine-telegram-bot.mjs --selftest
node scripts/mnemazine-webapp-server.mjs --selftest