diff --git a/.gitignore b/.gitignore index 55b9118..48e6473 100644 --- a/.gitignore +++ b/.gitignore @@ -12,6 +12,7 @@ __pycache__/ .mnemazine/quarantine/ .mnemazine/backlog/ .mnemazine/owner-context.txt +.mnemazine/config.env .mnemazine/rebuild/ .mnemazine/reprocess-video-inbox/ inbox/* diff --git a/.mnemazine/config.env.example b/.mnemazine/config.env.example new file mode 100644 index 0000000..26a8bb7 --- /dev/null +++ b/.mnemazine/config.env.example @@ -0,0 +1,5 @@ +# Mnemazine local config — copy to .mnemazine/config.env (gitignored) and fill in. +# Never commit real host/key values. Sourced by the Telegram sync/poll scripts. +MNEMAZINE_VPS="root@YOUR_VPS_HOST" +MNEMAZINE_VPS_KEY="$HOME/.ssh/id_rsa" +MNEMAZINE_REMOTE_INBOX="/var/www/mnemazine-inbox" diff --git a/README.md b/README.md index d318604..95a29c5 100644 --- a/README.md +++ b/README.md @@ -61,9 +61,16 @@ Clone the project into the only folder you need: ```bash git clone https://github.com/zarubinphil/Mnemazine.git "$HOME/Desktop/Mnemazine" cd "$HOME/Desktop/Mnemazine" -bash install.sh +bash setup.sh # guided, step-by-step (asks where the inbox goes, optional Telegram bot) +# or: bash install.sh # non-interactive skeleton only ``` +`setup.sh` walks a fresh device through setup in clear stages: it checks +prerequisites, tells you exactly what to install when something is missing, +asks where to put the `inbox/` (inside the repo or on the Desktop), and can +deploy the Telegram bot to a VPS. Preview a run without touching anything: +`MNEMAZINE_SETUP_DRYRUN=1 bash setup.sh`. + After installation, open this folder as an Obsidian vault: ```text @@ -256,6 +263,7 @@ That matters because a real memory must be reproducible. A note should be able t - [Token Economics](docs/token-economics.md) - [Website Ingestion](docs/site-ingestion.md) - [YouTube Ingestion](docs/youtube-ingestion.md) +- [Telegram Intake (bot + Mini App)](docs/telegram-intake.md) - [Obsidian Vault](docs/obsidian.md) - [Apple Vision OCR](docs/apple-vision.md) - [Graphify](docs/graphify.md) diff --git a/README.ru.md b/README.ru.md index d6caeb9..102587b 100644 --- a/README.ru.md +++ b/README.ru.md @@ -61,9 +61,15 @@ Mnemazine экономит токены, вынося работу из повт ```bash git clone https://github.com/zarubinphil/Mnemazine.git "$HOME/Desktop/Mnemazine" cd "$HOME/Desktop/Mnemazine" -bash install.sh +bash setup.sh # пошагово, с вопросами (куда класть inbox, опц. Telegram-бот) +# или: bash install.sh # без вопросов, только каркас ``` +`setup.sh` проводит новое устройство по этапам: проверяет окружение, чётко +говорит что доустановить если чего-то нет, спрашивает куда класть `inbox/` +(в репозитории или на рабочий стол), может задеплоить Telegram-бота на VPS. +Прогон вхолостую без изменений: `MNEMAZINE_SETUP_DRYRUN=1 bash setup.sh`. + После установки откройте эту папку как Obsidian-vault: ```text @@ -256,6 +262,7 @@ Mnemazine — это не «второй мозг» как лозунг про - [Экономика токенов](docs/token-economics.ru.md) - [Парсинг сайтов](docs/site-ingestion.ru.md) - [Парсинг YouTube](docs/youtube-ingestion.ru.md) +- [Приём через Telegram (бот + Mini App)](docs/telegram-intake.ru.md) - [Obsidian-vault](docs/obsidian.ru.md) - [Apple Vision OCR](docs/apple-vision.ru.md) - [Graphify](docs/graphify.ru.md) diff --git a/docs/telegram-intake.md b/docs/telegram-intake.md new file mode 100644 index 0000000..d5f38a0 --- /dev/null +++ b/docs/telegram-intake.md @@ -0,0 +1,121 @@ +# 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 + +```bash +TELEGRAM_BOT_TOKEN= \ +MNEMAZINE_INBOX=/path/to/staging-inbox \ +node scripts/mnemazine-telegram-bot.mjs +``` + +First message logs your `chat_id`. Lock the bot to yourself: + +```bash +ALLOWED_CHAT_IDS= # 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: + +```bash +TELEGRAM_BOT_TOKEN= \ +MNEMAZINE_INBOX=/path/to/staging-inbox \ +ALLOWED_CHAT_IDS= \ +PORT=8787 \ +node scripts/mnemazine-webapp-server.mjs +``` + +Reverse-proxy example (any TLS-terminating front works): + +```nginx +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: + +```bash +curl -X POST "https://api.telegram.org/bot/setChatMenuButton" \ + -H 'content-type: application/json' \ + -d '{"menu_button":{"type":"web_app","text":"Mnemazine", + "web_app":{"url":"https:///mini/mnemazine/"}}}' +``` + +### 3. Poller on your machine + +```bash +# 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 + +```bash +node scripts/mnemazine-telegram-bot.mjs --selftest +node scripts/mnemazine-webapp-server.mjs --selftest +``` diff --git a/docs/telegram-intake.ru.md b/docs/telegram-intake.ru.md new file mode 100644 index 0000000..54314eb --- /dev/null +++ b/docs/telegram-intake.ru.md @@ -0,0 +1,121 @@ +# Приём через Telegram (бот + Mini App) + +Шлёшь что угодно в Telegram-бота — текст, фото, документ, голос, аудио, видео — +и оно попадает в `inbox/` Mnemazine. Маленькая Mini App показывает буфер, +даёт быстро бросить заметку и запустить прогон протокола по требованию. +Ежедневный авто-прогон работает как и раньше. + +Сам протокол идёт **на твоей машине** (локальные OCR-движки, локальный +LLM-бинарь). Бот живёт на всегда-онлайн хосте, чтобы принимать пока машина +спит; машина сама забирает буфер и обрабатывает. Хост — только транзитный +буфер, не второе хранилище. + +## Архитектура + +``` + Telegram ──сообщение──▶ Бот (всегда-онлайн хост) + │ long-poll getUpdates (без webhook/TLS) + ▼ + staging-inbox хоста ◀── Mini App: POST /api/send + │ Mini App: POST /api/run → флаг .run-now + │ + твоя машина ────────┤ pull, каждые ~5 мин: + │ • есть флаг .run-now? → прогон + │ • наступило окно дня? → прогон + ▼ + rsync --remove-source-files (move; хост остаётся тонким) + ▼ + локальный inbox/ ──▶ npm run run (протокол) + ▼ + vault/ ──пишет .last-run──▶ статус Mini App +``` + +Обратный канал без публичной машины: хост не достучится до машины. Машина +сама поллит флаг, который ставит хост. Кнопка «Прогнать сейчас» в Mini App +просто пишет флаг; ближайший poll его забирает. + +## Компоненты + +| Часть | Где | Что | +|---|---|---| +| `scripts/mnemazine-telegram-bot.mjs` | хост | Long-poll бот. Пишет каждое сообщение в staging-inbox. Ноль зависимостей. | +| `scripts/mnemazine-webapp-server.mjs` | хост | API Mini App (`/api/status`, `/api/send`, `/api/run`). Верифицирует `initData`, держит allowlist. Ноль зависимостей. | +| `webapp/index.html` | хост (статика) | UI Mini App. Тема-aware, один файл. | +| `scripts/mnemazine-telegram-poll.sh` | твоя машина | Тик ~5 мин: флаг run-now / дневное окно → pull + прогон. | +| `scripts/mnemazine-telegram-sync.sh` | твоя машина | rsync pull (move) + `npm run run`. | +| `scripts/com.mnemazine.telegram-sync.plist.template` | твоя машина | launchd-агент (macOS) для тика. | + +## Установка + +### 1. Бот на хосте + +```bash +TELEGRAM_BOT_TOKEN=<от @BotFather> \ +MNEMAZINE_INBOX=/path/to/staging-inbox \ +node scripts/mnemazine-telegram-bot.mjs +``` + +Первое сообщение логирует твой `chat_id`. Закрой бота на себя: + +```bash +ALLOWED_CHAT_IDS=<твой_chat_id> # через запятую для нескольких +``` + +Перезапусти с этим env. Пусто = bootstrap-режим (принимает, логирует id для настройки). + +### 2. Mini App на хосте + +Раздавай `webapp/index.html` по **HTTPS** (Telegram требует TLS) и проксируй +`/api/` на API-сервер: + +```bash +TELEGRAM_BOT_TOKEN=<токен> \ +MNEMAZINE_INBOX=/path/to/staging-inbox \ +ALLOWED_CHAT_IDS=<твой_chat_id> \ +PORT=8787 \ +node scripts/mnemazine-webapp-server.mjs +``` + +Пример reverse-proxy (любой TLS-фронт подойдёт): + +```nginx +location /mini/mnemazine/api/ { proxy_pass http://127.0.0.1:8787/api/; } +location /mini/mnemazine/ { alias /path/to/webapp/; index index.html; } +``` + +Страница тянет `api/...` относительно своего пути — работает под любым +суб-путём. Наведи кнопку-меню бота на URL страницы: + +```bash +curl -X POST "https://api.telegram.org/bot<токен>/setChatMenuButton" \ + -H 'content-type: application/json' \ + -d '{"menu_button":{"type":"web_app","text":"Mnemazine", + "web_app":{"url":"https://<твой-хост>/mini/mnemazine/"}}}' +``` + +### 3. Поллер на твоей машине + +```bash +# отрендерить launchd-шаблон и загрузить (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 +``` + +Хост/ключ/пути переопределяются через `MNEMAZINE_VPS`, `MNEMAZINE_VPS_KEY`, +`MNEMAZINE_REMOTE_INBOX`, `MNEMAZINE_ROOT` (см. шапки скриптов). На Linux — +cron на 5 минут, вызывающий `mnemazine-telegram-poll.sh`. + +## Безопасность + +- Токен — секрет: env / секрет-стор, никогда не в git. +- `initData` HMAC-верифицируется токеном бота; проходят только id из allowlist. +- Бот игнорирует сообщения от всех вне `ALLOWED_CHAT_IDS`. + +## Селф-тесты + +```bash +node scripts/mnemazine-telegram-bot.mjs --selftest +node scripts/mnemazine-webapp-server.mjs --selftest +``` diff --git a/scripts/com.mnemazine.telegram-sync.plist.template b/scripts/com.mnemazine.telegram-sync.plist.template new file mode 100644 index 0000000..5fb3d50 --- /dev/null +++ b/scripts/com.mnemazine.telegram-sync.plist.template @@ -0,0 +1,26 @@ + + + + + Label + com.mnemazine.telegram-sync + ProgramArguments + + /bin/bash + __REPO__/scripts/mnemazine-telegram-poll.sh + + StartInterval + 300 + RunAtLoad + + StandardOutPath + __REPO__/.mnemazine/telegram-sync.log + StandardErrorPath + __REPO__/.mnemazine/telegram-sync.err.log + + diff --git a/scripts/mnemazine-telegram-bot.mjs b/scripts/mnemazine-telegram-bot.mjs new file mode 100755 index 0000000..7a6de97 --- /dev/null +++ b/scripts/mnemazine-telegram-bot.mjs @@ -0,0 +1,157 @@ +#!/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() diff --git a/scripts/mnemazine-telegram-poll.sh b/scripts/mnemazine-telegram-poll.sh new file mode 100755 index 0000000..d095b68 --- /dev/null +++ b/scripts/mnemazine-telegram-poll.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +# Runs every ~5 min via launchd. Decides whether to run the Mnemazine protocol: +# - manual: mini app touched .run-now on the VPS (consumed atomically here) +# - daily: first eligible tick at/after 09:00 local that hasn't run today +# Reverse channel VPS->Mac without a public Mac: Mac polls a flag the VPS sets. +set -euo pipefail + +REPO="${MNEMAZINE_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}" +# Live host/key/paths live in a gitignored config, never hardcoded here. +[ -f "$REPO/.mnemazine/config.env" ] && . "$REPO/.mnemazine/config.env" +VPS="${MNEMAZINE_VPS:-root@YOUR_VPS_HOST}" +KEY="${MNEMAZINE_VPS_KEY:-$HOME/.ssh/id_rsa}" +REMOTE_INBOX="${MNEMAZINE_REMOTE_INBOX:-/var/www/mnemazine-inbox}" + +# ponytail: fail fast if still on the placeholder — beats a confusing ssh error. +if [ "$VPS" = "root@YOUR_VPS_HOST" ]; then + echo "Set MNEMAZINE_VPS (and MNEMAZINE_VPS_KEY) in $REPO/.mnemazine/config.env" >&2 + exit 1 +fi +SSH="ssh -i $KEY -o StrictHostKeyChecking=no -o ConnectTimeout=10" +MARKER="$REPO/.mnemazine/.last-daily" +mkdir -p "$REPO/.mnemazine" + +# Single-flight lock. macOS has no flock, so use an atomic mkdir lock dir. +# Steal a stale lock (>60 min) left by a killed run. +LOCK="$REPO/.mnemazine/poll.lock" +[ -d "$LOCK" ] && find "$LOCK" -maxdepth 0 -mmin +60 -exec rmdir {} \; 2>/dev/null +if ! mkdir "$LOCK" 2>/dev/null; then exit 0; fi # previous tick still running +trap 'rmdir "$LOCK" 2>/dev/null' EXIT + +run=0; manual=0 +# Consume run-now flag atomically: print + delete in one ssh. +flag="$($SSH "$VPS" "f=$REMOTE_INBOX/.run-now; if [ -f \"\$f\" ]; then cat \"\$f\"; rm -f \"\$f\"; fi" 2>/dev/null || true)" +[ -n "$flag" ] && { run=1; manual=1; } + +today="$(date +%F)" +if [ "$(cat "$MARKER" 2>/dev/null || true)" != "$today" ] && [ "$(date +%H)" -ge 9 ]; then + run=1 + # Mark the daily attempt BEFORE syncing: a failed run must not re-fire every + # 5 min for the rest of the day (storm). One attempt per day. + echo "$today" > "$MARKER" +fi + +[ "$run" -eq 0 ] && exit 0 + +if bash "$REPO/scripts/mnemazine-telegram-sync.sh"; then + $SSH "$VPS" "echo $(date -u +%FT%TZ) > $REMOTE_INBOX/.last-run" 2>/dev/null || true +else + # A manual run-now we already consumed shouldn't vanish on failure — re-queue it. + [ "$manual" = "1" ] && $SSH "$VPS" "echo retry > $REMOTE_INBOX/.run-now" 2>/dev/null || true + exit 1 +fi diff --git a/scripts/mnemazine-telegram-sync.sh b/scripts/mnemazine-telegram-sync.sh new file mode 100755 index 0000000..9e61fb7 --- /dev/null +++ b/scripts/mnemazine-telegram-sync.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash +# Daily: pull buffered Telegram messages from the VPS into the local inbox, +# then run the Mnemazine protocol. Mac initiates (VPS can't reach Mac behind NAT). +# ponytail: rsync --remove-source-files = move; local protocol archives originals, +# so the VPS stays a thin transit buffer, not a second store. +set -euo pipefail + +REPO="${MNEMAZINE_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}" +# Live host/key/paths live in a gitignored config, never hardcoded here. +[ -f "$REPO/.mnemazine/config.env" ] && . "$REPO/.mnemazine/config.env" +VPS="${MNEMAZINE_VPS:-root@YOUR_VPS_HOST}" +KEY="${MNEMAZINE_VPS_KEY:-$HOME/.ssh/id_rsa}" +REMOTE_INBOX="${MNEMAZINE_REMOTE_INBOX:-/var/www/mnemazine-inbox/}" +LOCAL_INBOX="$REPO/inbox/" +STAGING="$REPO/inbox/.staging/" + +if [ "$VPS" = "root@YOUR_VPS_HOST" ]; then + echo "Set MNEMAZINE_VPS (and MNEMAZINE_VPS_KEY) in $REPO/.mnemazine/config.env" >&2 + exit 1 +fi + +mkdir -p "$LOCAL_INBOX" "$STAGING" +SSH_E="ssh -i $KEY -o StrictHostKeyChecking=no" + +# Two-phase move (C2: never delete the only copy before processing succeeds). +# 1) pull into staging WITHOUT deleting on the VPS, resumable on partial transfer. +rsync -avz --partial --exclude '.*' -e "$SSH_E" "$VPS:$REMOTE_INBOX" "$STAGING" + +# 2) promote staged files into the live inbox (atomic rename, same filesystem). +# Record exactly which files we took, so we delete only those on the VPS later +# (messages that arrive during the run stay buffered, not deleted). +pulled=() +shopt -s dotglob nullglob +for f in "$STAGING"*; do + base="$(basename "$f")" + case "$base" in .*) continue ;; esac # skip dotfiles defensively + mv -f "$f" "$LOCAL_INBOX$base" + pulled+=("$base") +done +shopt -u dotglob nullglob + +# 3) run the protocol; only AFTER it succeeds delete the taken files on the VPS. +cd "$REPO" +if npm run run; then + if [ "${#pulled[@]}" -gt 0 ]; then + printf '%s\n' "${pulled[@]}" | $SSH_E "$VPS" "cd ${REMOTE_INBOX%/} && xargs -d '\n' -r rm -f --" + fi +else + echo "protocol run failed — files are in local inbox, VPS copies kept for safety" >&2 + exit 1 +fi diff --git a/scripts/mnemazine-webapp-server.mjs b/scripts/mnemazine-webapp-server.mjs new file mode 100755 index 0000000..2075ff2 --- /dev/null +++ b/scripts/mnemazine-webapp-server.mjs @@ -0,0 +1,156 @@ +#!/usr/bin/env node +// Mnemazine Telegram Mini App backend. Localhost HTTP API behind nginx TLS. +// Endpoints (all require valid Telegram WebApp initData for an allowed user): +// GET /api/status -> { count, recent:[{name,at}], lastRun } +// POST /api/send {text} -> writes a note into the inbox +// POST /api/run -> touches .run-now flag; Mac poller picks it up +// Native http + crypto only, zero deps. +// +// Env: TELEGRAM_BOT_TOKEN (required), MNEMAZINE_INBOX, ALLOWED_CHAT_IDS, PORT (8787) + +import http from 'node:http' +import crypto from 'node:crypto' +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 INBOX = path.resolve(process.env.MNEMAZINE_INBOX || path.join(process.cwd(), 'inbox')) +const RUN_FLAG = path.join(INBOX, '.run-now') +const RUN_MARKER = path.join(INBOX, '.last-run') +const PORT = Number(process.env.PORT || 8787) +const ALLOWED = (process.env.ALLOWED_CHAT_IDS || '').split(',').map(s => s.trim()).filter(Boolean) +const throttle = new Map() // user.id -> last write ms + +// Verify Telegram WebApp initData. Returns the user object or null. +// https://core.telegram.org/bots/webapps#validating-data-received-via-the-mini-app +function verifyInitData(initData, token) { + const params = new URLSearchParams(initData) + const hash = params.get('hash') + if (!hash) return null + params.delete('hash') + const dataCheckString = [...params.entries()] + .map(([k, v]) => `${k}=${v}`) + .sort() + .join('\n') + const secret = crypto.createHmac('sha256', 'WebAppData').update(token).digest() + const calc = crypto.createHmac('sha256', secret).update(dataCheckString).digest('hex') + // timing-safe compare + if (calc.length !== hash.length || !crypto.timingSafeEqual(Buffer.from(calc), Buffer.from(hash))) return null + // Reject stale initData — a leaked/captured one must not work forever (replay). + const ttl = Number(process.env.MNEMAZINE_INITDATA_TTL || 86400) + if (ttl > 0) { + const authDate = Number(params.get('auth_date')) + if (!authDate || (Date.now() / 1000) - authDate > ttl) return null + } + try { return JSON.parse(params.get('user') || 'null') } catch { return null } +} + +const json = (res, code, obj) => { + res.writeHead(code, { 'content-type': 'application/json' }) + res.end(JSON.stringify(obj)) +} + +const MAX_BODY = 65536 // 64 KB — notes are small; cap guards against OOM. +async function readBody(req) { + const chunks = [] + let total = 0 + for await (const c of req) { + total += c.length + if (total > MAX_BODY) { const e = new Error('payload too large'); e.code = 413; throw e } + chunks.push(c) + } + return Buffer.concat(chunks).toString('utf8') +} + +async function status() { + const names = (await fs.readdir(INBOX).catch(() => [])).filter(n => !n.startsWith('.')) + const recent = [] + for (const n of names.slice(-10).reverse()) { + const st = await fs.stat(path.join(INBOX, n)).catch(() => null) + if (st) recent.push({ name: n, at: st.mtime.toISOString() }) + } + const lastRun = await fs.readFile(RUN_MARKER, 'utf8').catch(() => null) + return { count: names.length, recent, lastRun: lastRun?.trim() || null } +} + +async function send(text) { + await fs.mkdir(INBOX, { recursive: true }) + const stamp = new Date().toISOString() + const day = stamp.slice(0, 10) + const body = ['---', 'source: telegram-webapp', `date: ${stamp}`, '---', '', text, ''].join('\n') + const name = `tg_${day}_webapp_${Date.now()}.md` + await fs.writeFile(path.join(INBOX, name), body, 'utf8') + return name +} + +const server = http.createServer(async (req, res) => { + try { + const url = new URL(req.url, 'http://localhost') + if (!url.pathname.startsWith('/api/')) return json(res, 404, { error: 'not found' }) + + const initData = req.headers['x-telegram-initdata'] || '' + const user = verifyInitData(String(initData), TOKEN) + if (!user) return json(res, 401, { error: 'bad initData' }) + if (ALLOWED.length && !ALLOWED.includes(String(user.id))) return json(res, 403, { error: 'forbidden' }) + + // Structured access log (stderr): who hit what, for audit. + console.error(JSON.stringify({ ts: new Date().toISOString(), user: user.id, method: req.method, path: url.pathname })) + + // Light per-user throttle on writes (1/sec) — coarse anti-flood, not a quota. + if (req.method === 'POST') { + const last = throttle.get(user.id) || 0 + const now = Date.now() + if (now - last < 1000) return json(res, 429, { error: 'slow down' }) + throttle.set(user.id, now) + } + + if (req.method === 'GET' && url.pathname === '/api/status') return json(res, 200, await status()) + if (req.method === 'POST' && url.pathname === '/api/send') { + const { text } = JSON.parse(await readBody(req) || '{}') + if (!text || !text.trim()) return json(res, 400, { error: 'empty text' }) + return json(res, 200, { ok: true, saved: await send(text.trim()) }) + } + if (req.method === 'POST' && url.pathname === '/api/run') { + await fs.mkdir(INBOX, { recursive: true }) + // Coalescing trigger (many taps → one run) with a who/when audit trail. + // ponytail: a flag, not a job queue — single user, single button. + await fs.writeFile(RUN_FLAG, JSON.stringify({ at: new Date().toISOString(), by: user.id }), 'utf8') + return json(res, 200, { ok: true, queued: true }) + } + return json(res, 404, { error: 'not found' }) + } catch (e) { + if (e.code === 413) return json(res, 413, { error: 'payload too large' }) + console.error(`[500] ${e.stack || e.message}`) // detail to stderr, not the client + return json(res, 500, { error: 'internal error' }) + } +}) + +async function selftest() { + const assert = (c, m) => { if (!c) throw new Error(`selftest: ${m}`) } + // build a valid initData and verify round-trips; tampered fails. + const tok = 'test:token' + const user = JSON.stringify({ id: 1, first_name: 'F' }) + const sign = params => { + const dcs = [...params.entries()].map(([k, v]) => `${k}=${v}`).sort().join('\n') + const secret = crypto.createHmac('sha256', 'WebAppData').update(tok).digest() + return crypto.createHmac('sha256', secret).update(dcs).digest('hex') + } + const fresh = String(Math.floor(Date.now() / 1000)) + const p = new URLSearchParams({ auth_date: fresh, user }); p.set('hash', sign(new URLSearchParams({ auth_date: fresh, user }))) + const ok = verifyInitData(p.toString(), tok) + assert(ok && ok.id === 1, 'valid fresh initData accepted') + assert(verifyInitData(p.toString(), 'wrong:token') === null, 'wrong token rejected') + const bad = new URLSearchParams(p); bad.set('auth_date', String(Number(fresh) + 1)) + assert(verifyInitData(bad.toString(), tok) === null, 'tampered payload rejected') + assert(verifyInitData('', tok) === null, 'empty rejected') + // C7: test from the threat — a correctly-signed but OLD initData must be refused. + const staleDate = String(Math.floor(Date.now() / 1000) - 100000) + const stale = new URLSearchParams({ auth_date: staleDate, user }); stale.set('hash', sign(new URLSearchParams({ auth_date: staleDate, user }))) + assert(verifyInitData(stale.toString(), tok) === null, 'stale (replay) initData rejected') + console.log('selftest ok') +} + +if (SELFTEST) selftest().catch(e => { console.error(e.message); process.exit(1) }) +else server.listen(PORT, '127.0.0.1', () => console.log(`Mnemazine webapp API on 127.0.0.1:${PORT} inbox=${INBOX} allow=${ALLOWED.join(',') || 'ANY'}`)) diff --git a/setup.sh b/setup.sh new file mode 100755 index 0000000..4629001 --- /dev/null +++ b/setup.sh @@ -0,0 +1,185 @@ +#!/usr/bin/env bash +# Mnemazine guided installer. Walks a fresh device through setup in clear stages. +# Questions are numbered menus (terminal "dropdown"). Each stage gates the next. +# When a capability is missing we say so plainly and move on — never silently skip. +# +# Dry run (walk stages + questions, install/deploy nothing): +# MNEMAZINE_SETUP_DRYRUN=1 bash setup.sh +set -uo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +DRY="${MNEMAZINE_SETUP_DRYRUN:-0}" + +# ---- ui helpers ------------------------------------------------------------- +b() { printf '\033[1m%s\033[0m\n' "$*"; } +ok() { printf ' \033[32m✓\033[0m %s\n' "$*"; } +no() { printf ' \033[31m✗\033[0m %s\n' "$*"; } +note() { printf ' • %s\n' "$*"; } +stage() { printf '\n\033[1m\033[36m── Этап %s ──\033[0m %s\n' "$1" "$2"; } +miss() { printf '\n \033[33mДруг, значит %s тебе не оставим.\033[0m %s\n' "$1" "${2:-}"; } +halt() { printf '\n\033[1mУстанови вот это, потом запусти setup.sh снова — перейдём к следующему этапу.\033[0m\n'; exit 1; } + +# ask_choice "Question?" "opt1" "opt2" ... -> sets REPLY_IDX (1-based) and REPLY_VAL +ask_choice() { + local q="$1"; shift + local opts=("$@") i + printf '\n%s\n' "$q" + for i in "${!opts[@]}"; do printf ' %d) %s\n' $((i+1)) "${opts[$i]}"; done + local sel + while true; do + printf 'Выбери [1-%d]: ' "${#opts[@]}" + if ! read -r sel; then + printf '\nНет TTY (ввод закрыт). Запусти setup.sh интерактивно или используй install.sh без вопросов.\n' >&2 + exit 1 + fi + if [[ "$sel" =~ ^[0-9]+$ ]] && [ "$sel" -ge 1 ] && [ "$sel" -le "${#opts[@]}" ]; then + REPLY_IDX="$sel"; REPLY_VAL="${opts[$((sel-1))]}"; return 0 + fi + no "Не понял. Введи число от 1 до ${#opts[@]}." + done +} + +ask_text() { # ask_text "prompt" [silent] -> REPLY_TXT + local p="$1" silent="${2:-}" + if [ "$silent" = "secret" ]; then printf '%s: ' "$p"; read -rs REPLY_TXT || { printf '\nНет TTY.\n' >&2; exit 1; }; printf '\n' + else printf '%s: ' "$p"; read -r REPLY_TXT || { printf '\nНет TTY.\n' >&2; exit 1; }; fi +} + +run() { # run a command unless dry-run + if [ "$DRY" = "1" ]; then printf ' [dry] %s\n' "$*"; return 0; fi + "$@" +} + +b "Mnemazine — установка по шагам." +note "Каждый этап завершается прежде чем начнётся следующий." +[ "$DRY" = "1" ] && note "DRY RUN — ничего не ставится и не деплоится." + +# ---- Stage 1: base environment (hard gate) --------------------------------- +stage 1 "Базовое окружение (обязательно)" +fail=0 +if command -v git >/dev/null 2>&1; then ok "git"; else no "git нет"; note "macOS: xcode-select --install · Linux: apt install git"; fail=1; fi +if command -v node >/dev/null 2>&1; then + ver="$(node -p 'process.versions.node.split(".")[0]' 2>/dev/null || echo 0)" + if [ "$ver" -ge 20 ]; then ok "node $(node -v)"; else no "node слишком старый ($(node -v)), нужен >=20"; note "https://nodejs.org или nvm install 20"; fail=1; fi +else no "node нет (нужен >=20)"; note "https://nodejs.org или: brew install node"; fail=1; fi +[ "$fail" = "1" ] && halt +ok "База готова." + +# ---- Stage 2: local engines (optional, degrade gracefully) ----------------- +stage 2 "Локальные движки распознавания (по желанию — экономят токены)" +have_py=0; have_ff=0; have_whisper=0; have_swift=0 +command -v python3 >/dev/null 2>&1 && { ok "python3 (markitdown: PDF/DOCX/PPTX/XLSX/HTML)"; have_py=1; } || miss "разбор офис-файлов локально" "поставь python3 — иначе их распознает LLM в deep-режиме." +command -v ffmpeg >/dev/null 2>&1 && { ok "ffmpeg (видео-кадры/аудио)"; have_ff=1; } || miss "локальную обработку видео/аудио" "brew install ffmpeg / apt install ffmpeg." +command -v whisper >/dev/null 2>&1 && { ok "whisper (транскрипт речи)"; have_whisper=1; } || miss "локальный транскрипт речи" "pip install openai-whisper — иначе только субтитры/LLM." +if [ "$(uname)" = "Darwin" ]; then + command -v swiftc >/dev/null 2>&1 && { ok "swiftc (Apple Vision OCR картинок)"; have_swift=1; } || miss "Apple Vision OCR" "xcode-select --install — картинки распознает LLM." +else + miss "Apple Vision OCR" "доступен только на macOS — на этом устройстве картинки распознает LLM." +fi +note "Это не блокеры. Каркас поставится и без них." + +# ---- Stage 3: inbox location (required question) --------------------------- +stage 3 "Куда класть inbox?" +ask_choice "Входящие материалы будут падать сюда:" \ + "Внутри репозитория — $ROOT/inbox" \ + "На рабочий стол — $HOME/Desktop/Mnemazine-inbox" +if [ "$REPLY_IDX" = "1" ]; then INBOX="$ROOT/inbox"; else INBOX="$HOME/Desktop/Mnemazine-inbox"; fi +ok "Inbox: $INBOX" + +# ---- Stage 4: LLM provider (deep mode) ------------------------------------- +stage 4 "LLM-провайдер для deep-режима (атомизация/обогащение/проверка)" +has_claude=0; has_codex=0 +command -v claude >/dev/null 2>&1 && has_claude=1 +command -v codex >/dev/null 2>&1 && has_codex=1 +if [ "$has_claude" = "1" ] || [ "$has_codex" = "1" ]; then + opts=(); [ "$has_claude" = "1" ] && opts+=("Claude CLI"); [ "$has_codex" = "1" ] && opts+=("Codex CLI"); opts+=("Без deep — только локальный разбор") + ask_choice "Найдены провайдеры. Чем работать?" "${opts[@]}" + case "$REPLY_VAL" in + "Claude CLI") LLM=claude ;; "Codex CLI") LLM=codex ;; *) LLM="" ;; + esac + [ -n "$LLM" ] && ok "Провайдер: $LLM" || ok "Deep выключен (conservative, 0 токенов)." +else + LLM="" + miss "deep-режим (атомизация/обогащение через LLM)" "не найден ни claude, ни codex CLI. Каркас и локальный разбор работают." +fi + +# ---- Stage 5: Telegram bot -------------------------------------------------- +stage 5 "Telegram-бот для приёма входящих" +BOT_TOKEN=""; BOT_MODE="none" +ask_choice "Подключить Telegram-бота? (шлёшь боту — падает в inbox)" "Да" "Нет" +if [ "$REPLY_IDX" = "1" ]; then + ask_text "Вставь токен бота от @BotFather" secret; BOT_TOKEN="$REPLY_TXT" + if [ -z "$BOT_TOKEN" ]; then + miss "Telegram-бота" "токен пустой — пропускаем." + else + ok "Токен принят (в git не пишем)." + b "Бот должен идти через VPS (всегда-онлайн, принимает пока твоё устройство спит)." + ask_choice "Есть VPS для бота?" "Да, есть VPS" "Нет VPS" + if [ "$REPLY_IDX" = "1" ]; then + ask_text "VPS (user@host)"; BOT_VPS="$REPLY_TXT" + ask_text "Путь к SSH-ключу (Enter = ~/.ssh/id_rsa)"; BOT_KEY="${REPLY_TXT:-$HOME/.ssh/id_rsa}" + if [ "$DRY" != "1" ] && ! ssh -i "$BOT_KEY" -o StrictHostKeyChecking=no -o ConnectTimeout=10 "$BOT_VPS" 'command -v node >/dev/null && command -v pm2 >/dev/null' 2>/dev/null; then + miss "бота через VPS" "VPS недоступен или нет node+pm2 (ssh-in: 'npm i -g pm2'). Запусти бота локально вручную позже." + BOT_MODE="manual" + else + BOT_MODE="vps"; ok "VPS на связи (node+pm2 есть)." + fi + else + miss "бота через VPS" "Без VPS постоянного приёма нет. Можешь запускать бота локально, пока устройство включено." + BOT_MODE="manual" + fi + fi +else + note "Бот пропущен." +fi + +# ---- Stage 6: build the skeleton ------------------------------------------- +stage 6 "Ставлю каркас Mnemazine" +ok "Запускаю install.sh (vault, папки, venv, OCR-сборка)…" +if ! MNEMAZINE_ROOT="$ROOT" MNEMAZINE_INBOX="$INBOX" run bash "$ROOT/install.sh"; then + no "install.sh завершился с ошибкой — каркас не собран." + halt +fi + +# deploy bot if VPS path chosen +if [ "$BOT_MODE" = "vps" ]; then + stage 6.1 "Деплой бота на VPS" + REMOTE_INBOX="/var/www/mnemazine-inbox" + # Persist the host/key boundary so poll/sync scripts read it (never hardcoded). + if [ "$DRY" != "1" ]; then + mkdir -p "$ROOT/.mnemazine" + umask 177 + cat > "$ROOT/.mnemazine/config.env" < /var/www/mnemazine-bot/mnemazine-telegram-bot.mjs' + # Idempotent: start, or restart if the process already exists (rerun-safe). + ssh -i "$BOT_KEY" -o StrictHostKeyChecking=no "$BOT_VPS" "cd /var/www/mnemazine-bot && TELEGRAM_BOT_TOKEN='$BOT_TOKEN' MNEMAZINE_INBOX=$REMOTE_INBOX pm2 start mnemazine-telegram-bot.mjs --name mnemazine-bot --update-env 2>/dev/null || TELEGRAM_BOT_TOKEN='$BOT_TOKEN' MNEMAZINE_INBOX=$REMOTE_INBOX pm2 restart mnemazine-bot --update-env; pm2 save" + ok "Бот запущен на VPS (bootstrap-режим)." + note "Напиши боту сообщение, затем на VPS: pm2 logs mnemazine-bot — увидишь свой chat_id." + note "Закрой доступ: перезапусти с ALLOWED_CHAT_IDS= (см. docs/telegram-intake.md)." + fi +elif [ "$BOT_MODE" = "manual" ]; then + stage 6.1 "Бот локально (вручную)" + note "Запусти когда нужно:" + note "TELEGRAM_BOT_TOKEN=<токен> MNEMAZINE_INBOX=$INBOX node $ROOT/scripts/mnemazine-telegram-bot.mjs" +fi + +# ---- Stage 7: done ---------------------------------------------------------- +stage 7 "Готово" +ok "Каркас: $ROOT" +ok "Inbox: $INBOX" +[ -n "$LLM" ] && ok "Deep-провайдер: $LLM" || note "Deep выключен — включишь позже через MNEMAZINE_LLM." +note "Открой папку vault в Obsidian." +note "Прогон: cd $ROOT && npm run run (deep: npm run run -- --deep)" +[ "$BOT_MODE" = "vps" ] && note "Mini App + ежедневный pull: см. docs/telegram-intake.md (этапы 2-3)." +b "Всё. Пользуйся." diff --git a/webapp/index.html b/webapp/index.html new file mode 100644 index 0000000..4d3b0e7 --- /dev/null +++ b/webapp/index.html @@ -0,0 +1,136 @@ + + + + + + +Mnemazine + + + + +

Mnemazine

+ +
+
—в буфере
+
последний прогон: —
+
    +
    + +
    + + +
    + + + +
    + + + +