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:
@@ -0,0 +1,26 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- Mnemazine Telegram poller. Runs every 5 min: pulls + runs the protocol when
|
||||
the mini app queued a run (.run-now) or the daily window is due.
|
||||
Install: replace __REPO__ with your checkout path, then
|
||||
cp scripts/com.mnemazine.telegram-sync.plist.template \
|
||||
~/Library/LaunchAgents/com.mnemazine.telegram-sync.plist
|
||||
launchctl load ~/Library/LaunchAgents/com.mnemazine.telegram-sync.plist -->
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Label</key>
|
||||
<string>com.mnemazine.telegram-sync</string>
|
||||
<key>ProgramArguments</key>
|
||||
<array>
|
||||
<string>/bin/bash</string>
|
||||
<string>__REPO__/scripts/mnemazine-telegram-poll.sh</string>
|
||||
</array>
|
||||
<key>StartInterval</key>
|
||||
<integer>300</integer>
|
||||
<key>RunAtLoad</key>
|
||||
<true/>
|
||||
<key>StandardOutPath</key>
|
||||
<string>__REPO__/.mnemazine/telegram-sync.log</string>
|
||||
<key>StandardErrorPath</key>
|
||||
<string>__REPO__/.mnemazine/telegram-sync.err.log</string>
|
||||
</dict>
|
||||
</plist>
|
||||
Executable
+157
@@ -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()
|
||||
Executable
+52
@@ -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
|
||||
Executable
+51
@@ -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
|
||||
Executable
+156
@@ -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'}`))
|
||||
Reference in New Issue
Block a user