diff --git a/ops/brovops/app.py b/ops/brovops/app.py index 83eece7..3b23590 100644 --- a/ops/brovops/app.py +++ b/ops/brovops/app.py @@ -437,37 +437,50 @@ async def main(): log.warning("TELEGRAM_TOKEN not set: API only") await asyncio.Event().wait() proxy = CFG["proxy"] or None - builder = (Application.builder().token(CFG["token"]) - .request(HTTPXRequest(proxy=proxy, connect_timeout=10, read_timeout=20, write_timeout=20, - pool_timeout=10, connection_pool_size=8)) - .get_updates_request(PollRequest(proxy=proxy, connect_timeout=10, read_timeout=40, - write_timeout=10, pool_timeout=10))) - tg = builder.build() - async def on_error(update, ctx): - log.error("handler failed", exc_info=ctx.error) - tg.add_error_handler(on_error) - tg.add_handler(CommandHandler("start", cmd_start)) - tg.add_handler(CommandHandler("today", cmd_today)) - tg.add_handler(CommandHandler("tasks", cmd_tasks)) - tg.add_handler(CommandHandler("subs", cmd_subs)) - tg.add_handler(CommandHandler("routines", cmd_routines)) - tg.add_handler(CommandHandler("stop", cmd_stop)) - tg.add_handler(CallbackQueryHandler(on_button)) - tg.add_handler(MessageHandler(filters.VOICE | filters.AUDIO, on_voice)) - tg.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, on_text)) - # A Telegram/proxy outage must not kill the API, calendar and reminders. Keep the - # process alive and retry Telegram; systemd restart is still reserved for the polling - # watchdog, which catches a connection that looked established but stopped updating. + + def build_tg() -> Application: + builder = (Application.builder().token(CFG["token"]) + .request(HTTPXRequest(proxy=proxy, connect_timeout=10, read_timeout=20, write_timeout=20, + pool_timeout=10, connection_pool_size=8)) + .get_updates_request(PollRequest(proxy=proxy, connect_timeout=10, read_timeout=40, + write_timeout=10, pool_timeout=10))) + tg = builder.build() + + async def on_error(update, ctx): + log.error("handler failed", exc_info=ctx.error) + tg.add_error_handler(on_error) + tg.add_handler(CommandHandler("start", cmd_start)) + tg.add_handler(CommandHandler("today", cmd_today)) + tg.add_handler(CommandHandler("tasks", cmd_tasks)) + tg.add_handler(CommandHandler("subs", cmd_subs)) + tg.add_handler(CommandHandler("routines", cmd_routines)) + tg.add_handler(CommandHandler("stop", cmd_stop)) + tg.add_handler(CallbackQueryHandler(on_button)) + tg.add_handler(MessageHandler(filters.VOICE | filters.AUDIO, on_voice)) + tg.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, on_text)) + return tg + + # A Telegram/proxy outage must not kill the API, calendar and reminders. Every retry + # builds a FRESH Application: 06.11.2026 a proxy hiccup poisoned the shared httpx pool + # (PoolTimeout on every get_me) and reusing the same tg object looped forever — the API + # answered, the bot stayed dead for 2.5 days. If a fresh app still can't start 10 times + # (~5 minutes), exit and let systemd bring up a clean process. + fails = 0 while True: try: - async with tg: + async with build_tg() as tg: await tg.start() await tg.updater.start_polling(drop_pending_updates=False, timeout=25) + fails = 0 asyncio.create_task(reminder_loop(tg.bot)) asyncio.create_task(poll_watchdog()) await asyncio.Event().wait() except Exception: - log.exception("Telegram unavailable; API remains active, retrying in 30 s") + fails += 1 + log.exception("Telegram unavailable (attempt %d); API remains active, retrying in 30 s", fails) + if fails >= 10: + log.error("Telegram still broken after %d fresh attempts — restarting", fails) + os._exit(1) await asyncio.sleep(30) diff --git a/ops/deploy/brov-ops-proxy.service b/ops/deploy/brov-ops-proxy.service index 486d5dd..df78632 100644 --- a/ops/deploy/brov-ops-proxy.service +++ b/ops/deploy/brov-ops-proxy.service @@ -1,12 +1,12 @@ [Unit] -Description=BroV Ops proxy core (mihomo, proxy mode only: Telegram + Claude for brov-ops) +Description=BroV Ops proxy core (Xray, HTTP proxy on 127.0.0.1:7890: Telegram + Kimi for brov-ops) After=network-online.target Wants=network-online.target [Service] User=brovops Group=brovops -ExecStart=/usr/local/bin/mihomo -d /etc/brov-ops/proxy -f /etc/brov-ops/proxy/config.yaml +ExecStart=/opt/brov-ops/xray run -config /etc/brov-ops/proxy/xray.json Restart=always RestartSec=5 NoNewPrivileges=yes diff --git a/ops/deploy/gen-xray.py b/ops/deploy/gen-xray.py new file mode 100644 index 0000000..a47713d --- /dev/null +++ b/ops/deploy/gen-xray.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""Build /etc/brov-ops/proxy/xray.json from a nodes file of vless:// links. + +Usage: gen-xray.py + +The nodes file holds one vless:// link per line (comments and blanks skipped). +Subscription contents are accepted too: base64 blob that decodes to vless:// lines. +Only REALITY+tcp VLESS nodes are used (that is what brov-ops' proxy runs on). +The first node becomes the outbound; extra nodes go into a round-robin balancer. +""" +import base64 +import json +import sys +from urllib.parse import parse_qs, urlparse + + +def links(path: str) -> list[str]: + raw = open(path, encoding="utf-8").read().strip() + if "vless://" not in raw: # maybe a base64 subscription blob + try: + raw = base64.b64decode(raw).decode("utf-8") + except Exception: + pass + return [ln.strip() for ln in raw.splitlines() if ln.strip().startswith("vless://")] + + +def outbound(link: str, tag: str) -> dict: + u = urlparse(link) + q = {k: v[0] for k, v in parse_qs(u.query).items()} + if q.get("security") != "reality" or q.get("type", "tcp") != "tcp": + raise ValueError(f"пропускаю не-REALITY узел: {link[:40]}…") + return { + "tag": tag, + "protocol": "vless", + "settings": {"vnext": [{ + "address": u.hostname, + "port": u.port or 443, + "users": [{"id": u.username, "encryption": q.get("encryption", "none"), + **({"flow": q["flow"]} if q.get("flow") else {})}], + }]}, + "streamSettings": { + "network": "tcp", + "security": "reality", + "realitySettings": { + "serverName": q.get("sni", ""), + "fingerprint": q.get("fp", "chrome"), + "publicKey": q["pbk"], + "shortId": q.get("sid", ""), + }, + }, + } + + +def main() -> None: + nodes_path, out_path = sys.argv[1], sys.argv[2] + found = links(nodes_path) + if not found: + raise SystemExit("✗ в файле узлов нет ни одной vless:// ссылки") + outbounds, tags = [], [] + for i, link in enumerate(found): + try: + ob = outbound(link, f"node{i}") + except (ValueError, KeyError) as e: + print(f"⚠ {e}", file=sys.stderr) + continue + outbounds.append(ob) + tags.append(ob["tag"]) + if not outbounds: + raise SystemExit("✗ ни одного рабочего REALITY-узла") + cfg = { + "log": {"loglevel": "warning"}, + "inbounds": [{"listen": "127.0.0.1", "port": 7890, "protocol": "http", + "settings": {"timeout": 0}}], + "outbounds": outbounds, + } + if len(tags) > 1: + cfg["routing"] = {"balancers": [{"tag": "out", "selector": tags}]} + with open(out_path, "w", encoding="utf-8") as f: + json.dump(cfg, f, indent=1, ensure_ascii=False) + f.write("\n") + print(f"✓ xray.json: {len(tags)} узл(а)") + + +if __name__ == "__main__": + main() diff --git a/ops/deploy/install.sh b/ops/deploy/install.sh index 41c9b89..81b22d1 100644 --- a/ops/deploy/install.sh +++ b/ops/deploy/install.sh @@ -3,8 +3,8 @@ # sudo sh ops/deploy/install.sh # # Puts the service in /opt/brov-ops (user brovops), data in /var/lib/brov-ops, settings in -# /etc/brov-ops (root, 600). Telegram and Claude go through a local proxy core (mihomo in -# proxy mode on 127.0.0.1:7890 — only this service uses it, the VM itself is not tunnelled). +# /etc/brov-ops (root, 600). Telegram and Kimi go through a local proxy core (Xray in +# HTTP-proxy mode on 127.0.0.1:7890 — only this service uses it, the VM is not tunnelled). # # Secrets on the first run: the VLESS subscription URL and the Telegram bot token are taken # from ~/.brovops-sub and ~/.brovops-token of the user running sudo (moved into @@ -16,14 +16,14 @@ set -e HERE=$(cd "$(dirname "$0")/.." && pwd) ETC=/etc/brov-ops PROXY_DIR=$ETC/proxy -MIHOMO_VERSION=v1.19.32 -MIHOMO_GZ_SHA=8451100836c9eda194331c2babfad490b2faf30cebc1a04b0e76fd8ac2d35d10 -MIHOMO_BIN_SHA=3122d100e8177501776109f1a6253a694611627cf4d7c7ec82705855cf8626a8 +XRAY_VERSION=26.10.31 +XRAY_ZIP_SHA=e4bd9119f50ae7c41658b1abd0679ae06f98bd864a2907ff33f2f2cf7081b214 +XRAY_BIN_SHA=cc4b84d3069569f297a61f04b914f2bb37e9d202fd7b84cb50def1fc30fd40e1 PROXY=http://127.0.0.1:7890 echo "→ Пакеты" apt-get update -qq -apt-get install -y -qq python3-venv python3-pip ffmpeg curl ca-certificates openssl >/dev/null +apt-get install -y -qq python3-venv python3-pip ffmpeg curl ca-certificates openssl unzip >/dev/null id brovops >/dev/null 2>&1 || useradd --system --create-home --home-dir /home/brovops --shell /usr/sbin/nologin brovops install -d -m 755 /opt/brov-ops @@ -31,13 +31,15 @@ install -d -m 750 -o brovops -g brovops /var/lib/brov-ops install -d -m 750 -o root -g brovops $ETC install -d -m 700 -o brovops -g brovops $PROXY_DIR -echo "→ Прокси-ядро (mihomo $MIHOMO_VERSION)" -if [ "$(sha256sum /usr/local/bin/mihomo 2>/dev/null | cut -d' ' -f1)" != "$MIHOMO_BIN_SHA" ]; then +echo "→ Прокси-ядро (Xray $XRAY_VERSION)" +# Xray, не mihomo: 05.11.2026 mihomo не смог в REALITY handshake против Xray-сервера +# (REALITY authentication failed), а Xray-клиент ходит стабильно. Версия и суммы pinned. +if [ "$(sha256sum /opt/brov-ops/xray 2>/dev/null | cut -d' ' -f1)" != "$XRAY_BIN_SHA" ]; then TMP=$(mktemp -d) - curl -fsSL -o "$TMP/m.gz" "https://github.com/MetaCubeX/mihomo/releases/download/$MIHOMO_VERSION/mihomo-linux-amd64-$MIHOMO_VERSION.gz" - [ "$(sha256sum "$TMP/m.gz" | cut -d' ' -f1)" = "$MIHOMO_GZ_SHA" ] || { echo "✗ архив mihomo не совпал с контрольной суммой"; exit 1; } - gunzip -c "$TMP/m.gz" > "$TMP/mihomo" - install -m 755 "$TMP/mihomo" /usr/local/bin/mihomo + curl -fsSL -o "$TMP/x.zip" "https://github.com/XTLS/Xray-core/releases/download/v$XRAY_VERSION/Xray-linux-64.zip" + [ "$(sha256sum "$TMP/x.zip" | cut -d' ' -f1)" = "$XRAY_ZIP_SHA" ] || { echo "✗ архив Xray не совпал с контрольной суммой"; exit 1; } + unzip -q -o "$TMP/x.zip" -d "$TMP" + install -m 755 "$TMP/xray" /opt/brov-ops/xray rm -rf "$TMP" fi USER_HOME=$(getent passwd "${SUDO_USER:-root}" | cut -d: -f6) @@ -54,51 +56,30 @@ ask_secret() { # prompt → stdout, input not echoed # Server list: the subscription content as a file (~/.brovops-nodes — when the subscription # page itself is blocked from here) and/or the subscription URL (~/.brovops-sub). NODES=$(take_file nodes); [ -n "$NODES" ] && printf '%s\n' "$NODES" > $PROXY_DIR/nodes.txt -SUBURL=$(take_file sub); [ -n "$SUBURL" ] && printf '%s\n' "$SUBURL" > $PROXY_DIR/vless.sub +SUBURL=$(take_file sub) +if [ -n "$SUBURL" ]; then + case "$SUBURL" in + vless://*) printf '%s\n' "$SUBURL" > $PROXY_DIR/nodes.txt ;; # a single key, not a subscription + *) printf '%s\n' "$SUBURL" > $PROXY_DIR/vless.sub ;; + esac +fi if [ ! -s $PROXY_DIR/nodes.txt ] && [ ! -s $PROXY_DIR/vless.sub ]; then ask_secret "Ссылка подписки VLESS (ввод скрыт): " > $PROXY_DIR/vless.sub [ -s $PROXY_DIR/vless.sub ] || { echo "✗ нет ни подписки, ни списка серверов"; exit 1; } fi -PROVIDERS=""; USE="" -if [ -s $PROXY_DIR/nodes.txt ]; then - PROVIDERS="$PROVIDERS - nodes: - type: file - path: ./nodes.txt - health-check: {enable: true, url: \"https://www.gstatic.com/generate_204\", interval: 300}" - USE="nodes" +# Xray не умеет подписки сам: скачиваем список узлов один раз при установке и генерируем +# статичный xray.json из vless:// ссылок (REALITY). Обновление узлов — правка nodes.txt +# и повторный запуск gen-xray.py + systemctl restart brov-ops-proxy. +if [ ! -s $PROXY_DIR/nodes.txt ] && [ -s $PROXY_DIR/vless.sub ]; then + curl -fsSL -m 30 -o $PROXY_DIR/nodes.txt "$(head -n1 $PROXY_DIR/vless.sub | tr -d '\r\n ')" \ + || { echo "✗ подписка не скачалась — положи узлы файлом ~/.brovops-nodes"; exit 1; } fi -if [ -s $PROXY_DIR/vless.sub ]; then - SUB=$(head -n1 $PROXY_DIR/vless.sub | tr -d '\r\n ') - PROVIDERS="$PROVIDERS - vless: - type: http - url: \"$SUB\" - path: ./vless.yaml - interval: 43200 - proxy: DIRECT - health-check: {enable: true, url: \"https://www.gstatic.com/generate_204\", interval: 300}" - USE="${USE:+$USE, }vless" -fi -umask 077 -cat > $PROXY_DIR/config.yaml </dev/null systemctl restart brov-ops-proxy @@ -108,24 +89,33 @@ curl -s -m 8 -o /dev/null -w " Telegram через прокси: HTTP %{http_co echo "→ Код и Python-окружение" cp -r "$HERE/brovops" "$HERE/requirements.txt" /opt/brov-ops/ [ -x /opt/brov-ops/venv/bin/python ] || python3 -m venv /opt/brov-ops/venv -HTTPS_PROXY=$PROXY /opt/brov-ops/venv/bin/pip install -q --upgrade pip -HTTPS_PROXY=$PROXY /opt/brov-ops/venv/bin/pip install -q -r /opt/brov-ops/requirements.txt +/opt/brov-ops/venv/bin/pip install -q --upgrade pip +/opt/brov-ops/venv/bin/pip install -q -r /opt/brov-ops/requirements.txt -echo "→ Claude Code" -CLAUDE=/home/brovops/.local/bin/claude -if [ ! -x $CLAUDE ]; then - sudo -u brovops -H env HTTPS_PROXY=$PROXY HTTP_PROXY=$PROXY sh -c 'curl -fsSL https://claude.ai/install.sh | bash' >/dev/null +echo "→ Kimi Code" +KIMI=/home/brovops/.kimi-code/bin/kimi +if [ ! -x $KIMI ]; then + # Kimi and PyPI are reachable directly; only Telegram requires the local proxy. + sudo -u brovops -H sh -c 'curl -fsSL https://code.kimi.com/kimi-code/install.sh | bash' >/dev/null fi -[ -x $CLAUDE ] && echo " ✓ $($CLAUDE --version 2>/dev/null)" || echo " ⚠ Claude Code не установился" +[ -x $KIMI ] && echo " ✓ $($KIMI --version 2>/dev/null)" || echo " ⚠ Kimi Code не установился" echo "→ Настройки" if [ ! -f $ETC/config.env ]; then - # Whisper "small" needs ~1 GB on top of Claude: on a small VM take "base". + # Whisper "small" needs ~1 GB on top of Kimi: on a small VM take "base". MEM_MB=$(awk '/MemTotal/ {print int($2/1024)}' /proc/meminfo) WHISPER=small; [ "$MEM_MB" -lt 3500 ] && WHISPER=base - sed -e "s|^API_TOKEN=.*|API_TOKEN=$(openssl rand -hex 24)|" -e "s|^CLAUDE_BIN=.*|CLAUDE_BIN=$CLAUDE|" \ + sed -e "s|^API_TOKEN=.*|API_TOKEN=$(openssl rand -hex 24)|" -e "s|^KIMI_BIN=.*|KIMI_BIN=$KIMI|" \ -e "s|^WHISPER_MODEL=.*|WHISPER_MODEL=$WHISPER|" "$HERE/deploy/config.env.example" > $ETC/config.env +else + # Migrate an existing installation without touching tokens, owner or other settings. + # Old global proxy variables were for Claude; Telegram has its own TELEGRAM_PROXY. + sed -i -e "s|^CLAUDE_BIN=.*|KIMI_BIN=$KIMI|" -e "s|^CLAUDE_MODEL=.*|KIMI_MODEL=|" \ + -e '/^HTTPS_PROXY=/d' -e '/^HTTP_PROXY=/d' $ETC/config.env fi +grep -q "^KIMI_BIN=" $ETC/config.env || echo "KIMI_BIN=$KIMI" >> $ETC/config.env +grep -q "^KIMI_MODEL=" $ETC/config.env || echo "KIMI_MODEL=" >> $ETC/config.env +grep -q "^KIMI_PROXY=" $ETC/config.env || echo "KIMI_PROXY=" >> $ETC/config.env if ! grep -q "^TELEGRAM_TOKEN=." $ETC/config.env; then TOK=$(take_file token) [ -n "$TOK" ] || TOK=$(ask_secret "Токен бота от @BotFather (ввод скрыт): ") @@ -148,9 +138,9 @@ systemctl is-active --quiet brov-ops && echo "✓ brov-ops работает" || cat <