6 Commits

Author SHA1 Message Date
Андрей Бобырев
b6525bc0ae stable 1.2.5: token field + channel buttons in version card
Ports the channel UI to stable so users who installed the open stable
version can paste their subscriber token (save_token) and switch to
beta/dev straight from Настройки → Версия и обновления. Adds
gh_token_present/save_gh_token helpers and stable/beta/dev quick buttons.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-05-31 01:57:19 +03:00
Андрей Бобырев
d072c8227f feat: private dev/beta channels via subscriber token (repo split)
Closed channels (beta, dev) now live in a separate PRIVATE repository
andrey271192/PCA_Phobos-dev. Access is gated by a read-only subscriber
GH_TOKEN (distributed via Boosty) instead of a shared hash key — the
token both authenticates the private raw fetch AND acts as the gate, so
there is a single secret and the code is genuinely hidden (public repo
holds stable/main only).

install.sh: CHANNEL=beta|dev -> private repo, requires GH_TOKEN, persists
it to $PANEL_DIR/.gh_token + writes .channel. stable stays public/no-token.
update.sh: per-ref repo routing (repo_for), gh_curl injects the token for
private channels, token read from env or saved .gh_token, --check/--versions
reflect public vs private, stable path unchanged and tokenless.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-05-31 01:12:32 +03:00
Андрей Бобырев
7b941dc532 docs: README channels — stable open, beta/dev key-gated (Boosty)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-05-31 00:59:45 +03:00
Андрей Бобырев
8c1654ecaa feat: 3-channel model (stable open / beta + dev key-gated)
Channels:
  stable -> branch main  (open, no key)
  beta   -> branch beta  (release candidate, key-gated)
  dev    -> branch dev    (active development, key-gated)

beta and dev require PHOBOS_KEY (subscriber key distributed via Boosty);
only the sha256 hash is embedded in install.sh / update.sh. stable stays
open. install.sh honours CHANNEL=stable|beta|dev; phobos-update accepts
stable|beta|dev|<tag> and gates the closed channels. --check now lists all
three channels with a [закрыт ключом] marker.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-05-31 00:58:06 +03:00
phobos
dc83d90a35 v1.2.4: install stable by default; beta opt-in via CHANNEL=beta (documented) 2026-05-31 00:38:50 +03:00
phobos
e0ea54e83a v1.2.3: debounce server DOWN alerts (3 cycles + retry) fix flapping; update.sh aborts on missing version + --check/--versions + beta channel; panel Check button 2026-05-30 23:52:47 +03:00
5 changed files with 213 additions and 36 deletions

View File

@@ -77,9 +77,21 @@ bash <(curl -fsSL https://raw.githubusercontent.com/andrey271192/PCA_Phobos/main
| `OBF_PORTS` | `2083,5443,993` | Порты обфускатора |
| `TG_TOKEN`/`TG_CHAT` | пусто | Telegram-уведомления |
| `ALLOW_PLAIN_WG` | пусто | `=1` открыть порт 51820 для iOS WireGuard (без обфускации) |
| `CHANNEL` | `stable` | канал: `stable` (открытый) · `beta`/`dev` (под ключом `PHOBOS_KEY`) |
После установки панель напечатает адрес, логин, пароль и **API key** — сохрани их.
> **Каналы:**
> - **stable** — стабильная (ветка `main`), ставится **без ключа**, по умолчанию.
> - **beta** — кандидат в релиз (тест), **под ключом** подписчика.
> - **dev** — активная разработка (нестабильно), **под ключом** подписчика.
>
> Ключ `PHOBOS_KEY` выдаётся по подписке [Boosty](https://boosty.to/andrey27). Закрытый канал:
> ```bash
> PHOBOS_KEY=ваш_ключ CHANNEL=dev bash <(curl -fsSL https://raw.githubusercontent.com/andrey271192/PCA_Phobos/main/install.sh)
> ```
> Переключение после установки: `phobos-update stable` (без ключа) · `PHOBOS_KEY=... phobos-update beta|dev` · статус: `phobos-update --check`.
### Вторичный сервер (для failover / балансировки)
```bash

View File

@@ -1 +1 @@
1.2.2
1.2.5

97
app.py
View File

@@ -479,6 +479,7 @@ def kick_client_by_id(client_id):
prev_session_keys = None
prev_server_status = {}
_down_streak = {}
_last_fanout = 0
server_stats_cache = {}
server_handshakes_cache = {}
@@ -503,12 +504,19 @@ def get_local_stats():
def get_remote_stats(server):
import urllib.request
url = f"http://{server['ip']}:8444/api/health"
req = urllib.request.Request(url, headers={"X-API-Key": server.get("api_key", "")})
data = None
for _attempt in range(2): # retry once: smooths transient timeouts (1-worker agent)
try:
data = json.loads(urllib.request.urlopen(req, timeout=6).read())
break
except Exception:
data = None
try:
import urllib.request
url = f"http://{server['ip']}:8444/api/health"
req = urllib.request.Request(url, headers={"X-API-Key": server.get("api_key", "")})
resp = urllib.request.urlopen(req, timeout=3)
data = json.loads(resp.read())
if data is None:
raise Exception("no response")
# cache handshakes so page renders never block on remote HTTP
server_handshakes_cache[server.get("ip", "")] = data.get("handshakes", {}) or {}
# Filter peers: only count known client public keys
@@ -653,6 +661,28 @@ def panel_version():
return "unknown"
GH_TOKEN_FILE = "/opt/phobos-panel/.gh_token"
def gh_token_present():
try:
return os.path.exists(GH_TOKEN_FILE) and os.path.getsize(GH_TOKEN_FILE) > 0
except Exception:
return False
def save_gh_token(tok):
tok = (tok or "").strip()
if not tok:
return False
fd = os.open(GH_TOKEN_FILE, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
try:
os.write(fd, tok.encode())
finally:
os.close(fd)
return True
def run_update(arg):
import subprocess
try:
@@ -777,7 +807,7 @@ def push_config_to_router(client_id):
def session_monitor():
global prev_session_keys, prev_server_status, server_stats_cache, _last_fanout
global prev_session_keys, prev_server_status, server_stats_cache, _last_fanout, _down_streak
while True:
try:
s = load_settings()
@@ -814,19 +844,24 @@ def session_monitor():
local_stats = get_local_stats()
server_stats_cache[SERVER_IP] = local_stats
DOWN_CONFIRM = 3 # consecutive failed cycles before declaring a server DOWN
for srv in servers:
ip = srv["ip"]
stats = get_remote_stats(srv)
server_stats_cache[ip] = stats
raw = stats.get("status", "down")
streak = _down_streak.get(ip, 0)
streak = streak + 1 if raw == "down" else 0
_down_streak[ip] = streak
# update cache on OK, or only once a DOWN is confirmed (keep last-good on transient)
if raw == "ok" or streak >= DOWN_CONFIRM:
server_stats_cache[ip] = stats
eff = "down" if streak >= DOWN_CONFIRM else "ok"
was_up = prev_server_status.get(ip, "ok")
now_status = stats["status"]
if was_up == "ok" and now_status == "down":
if was_up == "ok" and eff == "down":
tg_send(f"🔴 <b>Server {ip}</b> DOWN!")
elif was_up == "down" and now_status == "ok":
elif was_up == "down" and eff == "ok":
tg_send(f"🟢 <b>Server {ip}</b> back ONLINE")
prev_server_status[ip] = now_status
prev_server_status[ip] = eff
# periodic config fan-out to secondaries (covers CLI-created clients
# and config drift; gated ~5 min, skips down servers)
@@ -1371,9 +1406,19 @@ def labels_page():
def settings_page():
s = load_settings()
msg = ""
if request.method == "POST" and request.form.get("action") in ("update", "rollback"):
if request.form.get("action") == "update":
if request.method == "POST" and request.form.get("action") in ("update", "rollback", "check", "save_token"):
_act = request.form.get("action")
_tok = request.form.get("gh_token", "").strip()
if _tok:
save_gh_token(_tok)
if _act == "save_token":
_out = tr("Токен подписчика сохранён. Теперь можно переключаться на beta/dev.",
"Subscriber token saved. You can now switch to beta/dev.") if _tok else \
tr("Поле токена пустое.", "Token field is empty.")
elif _act == "update":
_out = run_update(request.form.get("target", "").strip() or "main")
elif _act == "check":
_out = run_update("--check")
else:
_out = run_update("--rollback")
s = load_settings()
@@ -1412,11 +1457,31 @@ def settings_page():
<div class="card">
<h2>{tr("Версия и обновления","Version & updates")} {hlp("Скачивает свежие файлы PCA-слоя (панель + скрипты) с GitHub и перезапускает панель. Ключи WireGuard, server.env и клиенты НЕ трогаются. Пусто или main = последняя версия; можно указать тег (например v1.1.0). Откат восстанавливает предыдущую версию из автоматического бэкапа.", "Fetches the latest PCA files (panel + scripts) from GitHub and restarts the panel. WireGuard keys, server.env and clients are NOT touched. Empty or main = latest; you can pass a tag (e.g. v1.1.0). Rollback restores the previous version from an automatic backup.")}</h2>
<p>{tr("Установленная версия","Installed version")}: <b style="color:#a5b4fc">{panel_version()}</b></p>
<p style="font-size:.85em;color:#94a3b8;margin:4px 0 8px">{tr("Каналы","Channels")}:
<b style="color:#22c55e">stable</b> — {tr("стабильная","stable")} ·
<b style="color:#eab308">beta</b> — {tr("тест","testing")} ·
<b style="color:#f97316">dev</b> — {tr("разработка","development")}.
{tr("stable — без токена. Для beta/dev вставь токен подписчика (по подписке Boosty), сохрани — и жми канал.","stable needs no token. For beta/dev paste your subscriber token (Boosty), save it, then click the channel.")}</p>
<form method="post" class="form-row" style="margin-bottom:8px">
<input type="hidden" name="action" value="save_token">
<input type="password" name="gh_token" placeholder="{tr('токен подписчика (для beta/dev)','subscriber token (for beta/dev)')}" style="width:240px" autocomplete="off">
<button class="btn btn-sm" style="background:#475569" type="submit">{tr("Сохранить токен","Save token")}</button>
<span style="font-size:.82em;color:{'#22c55e' if gh_token_present() else '#f59e0b'}">{(tr("✓ токен сохранён","✓ token saved") if gh_token_present() else tr("токен не задан — beta/dev недоступны","no token — beta/dev locked"))}</span>
</form>
<div class="form-row" style="gap:6px;margin-bottom:8px">
<form method="post" style="display:inline"><input type="hidden" name="action" value="update"><input type="hidden" name="target" value="stable"><button class="btn btn-sm" style="background:#16a34a" type="submit" onclick="return confirm('{tr("Перейти на стабильную?","Switch to stable?")}')">stable</button></form>
<form method="post" style="display:inline"><input type="hidden" name="action" value="update"><input type="hidden" name="target" value="beta"><button class="btn btn-sm" style="background:#ca8a04" type="submit" onclick="return confirm('{tr("Перейти на beta?","Switch to beta?")}')">beta</button></form>
<form method="post" style="display:inline"><input type="hidden" name="action" value="update"><input type="hidden" name="target" value="dev"><button class="btn btn-sm" style="background:#ea580c" type="submit" onclick="return confirm('{tr("Перейти на dev (нестабильно)?","Switch to dev (unstable)?")}')">dev</button></form>
</div>
<form method="post" class="form-row">
<input type="hidden" name="action" value="update">
<input type="text" name="target" placeholder="main / v1.1.0" style="width:150px">
<input type="text" name="target" placeholder="stable / beta / dev / v1.2.4" style="width:170px">
<button class="btn btn-primary" type="submit" onclick="return confirm('{tr("Обновить панель и скрипты?","Update panel and scripts?")}')">{tr("Обновить","Update")}</button>
</form>
<form method="post" style="display:inline">
<input type="hidden" name="action" value="check">
<button class="btn btn-sm" style="background:#0ea5e9" type="submit">{tr("Проверить обновления","Check for updates")}</button>
</form>
<form method="post" style="margin-top:8px">
<input type="hidden" name="action" value="rollback">
<button class="btn btn-danger btn-sm" type="submit" onclick="return confirm('{tr("Откатить на предыдущую версию?","Roll back to the previous version?")}')">{tr("Откатить на предыдущую","Rollback")}</button>

View File

@@ -25,11 +25,31 @@ PANEL_PASS="${PANEL_PASS:-OcAdmin2026!}"
TG_TOKEN="${TG_TOKEN:-}"
TG_CHAT="${TG_CHAT:-}"
OBF_PORTS="${OBF_PORTS:-2083,5443,993}"
PCA_BRANCH="${PCA_BRANCH:-main}"
GH_TOKEN="${GH_TOKEN:-}" # set for private-repo installs; empty for public
# Каналы: stable (открытый, публичный repo) · beta (тест) · dev (разработка).
# beta и dev живут в ПРИВАТНОМ repo PCA_Phobos-dev — доступ по токену подписчика
# (GH_TOKEN, read-only, выдаётся по подписке Boosty). stable — без токена.
GH_TOKEN="${GH_TOKEN:-}"
PUB_REPO="andrey271192/PCA_Phobos"
DEV_REPO="andrey271192/PCA_Phobos-dev"
CHANNEL="${CHANNEL:-stable}"
case "$CHANNEL" in
beta) REPO="$DEV_REPO"; PCA_BRANCH="${PCA_BRANCH:-beta}";;
dev) REPO="$DEV_REPO"; PCA_BRANCH="${PCA_BRANCH:-dev}";;
stable|main|"") REPO="$PUB_REPO"; PCA_BRANCH="${PCA_BRANCH:-main}";;
*) REPO="$PUB_REPO"; PCA_BRANCH="${PCA_BRANCH:-$CHANNEL}";;
esac
if [ "$REPO" = "$DEV_REPO" ] && [ -z "$GH_TOKEN" ]; then
echo "Канал '$CHANNEL' закрыт — это $([ "$CHANNEL" = dev ] && echo 'разработка (нестабильно)' || echo 'бета (тест)'), приватный репозиторий."
echo "Нужен read-only токен подписчика:"
echo " GH_TOKEN=ваш_токен CHANNEL=$CHANNEL bash <(curl -fsSL https://raw.githubusercontent.com/$PUB_REPO/main/install.sh)"
echo "Токен выдаётся по подписке: https://boosty.to/andrey27"
echo "Стабильная версия ставится без токена (CHANNEL=stable, по умолчанию)."
exit 1
fi
[ "$REPO" = "$DEV_REPO" ] && echo "Токен принят — закрытый канал '$CHANNEL' (приватный repo)."
PHOBOS_DIR="/opt/Phobos"
PANEL_DIR="/opt/phobos-panel"
RAW="https://raw.githubusercontent.com/andrey271192/PCA_Phobos/${PCA_BRANCH}"
RAW="https://raw.githubusercontent.com/${REPO}/${PCA_BRANCH}"
[ "$EUID" -eq 0 ] || { echo "Run as root"; exit 1; }
@@ -240,6 +260,13 @@ if [ -f "$PHOBOS_DIR/server/phobos-router-watchdog.py" ]; then
fi
sleep 2
# persist channel + subscriber token so phobos-update can reach private channels
mkdir -p "$PANEL_DIR"
echo "$CHANNEL" > "$PANEL_DIR/.channel" 2>/dev/null || true
if [ "$REPO" = "$DEV_REPO" ] && [ -n "$GH_TOKEN" ]; then
( umask 077; printf %s "$GH_TOKEN" > "$PANEL_DIR/.gh_token" )
fi
echo ""
echo "============================================"
echo " Installation complete"

105
update.sh
View File

@@ -2,24 +2,47 @@
# ============================================================
# PCA Phobos — updater / rollback
#
# phobos-update # обновить до последней версии (main)
# phobos-update v1.1.0 # обновить до конкретной версии (git tag)
# phobos-update # обновить до стабильной (канал stable / main)
# phobos-update stable # стабильный канал (публичный, без токена)
# GH_TOKEN=... phobos-update beta # бета-канал (приватный, по токену подписчика)
# GH_TOKEN=... phobos-update dev # канал разработки (приватный, по токену)
# phobos-update v1.2.4 # конкретная версия (git tag)
# phobos-update --rollback # откатить на предыдущую версию (из бэкапа)
# phobos-update --version # показать установленную и последнюю версию
# phobos-update --check # установленная + версии всех каналов
# phobos-update --list # список бэкапов для отката
#
# Обновляет ТОЛЬКО PCA-слой (панель + скрипты онбординга/служебные).
# НЕ трогает ключи WireGuard, server.env, клиентов — они сохраняются.
# Перед каждым обновлением делает бэкап; откат восстанавливает его.
# Каналы:
# stable -> публичный репозиторий andrey271192/PCA_Phobos (открыт)
# beta / dev -> приватный andrey271192/PCA_Phobos-dev (только подписчики)
# Для beta/dev нужен read-only токен подписчика: env GH_TOKEN или файл
# $PANEL_DIR/.gh_token (сохраняется при установке закрытого канала).
#
# Обновляет ТОЛЬКО PCA-слой (панель + скрипты). НЕ трогает ключи WireGuard,
# server.env, клиентов. Перед каждым обновлением — бэкап; откат восстанавливает.
# ============================================================
set -e
PHOBOS_DIR=/opt/Phobos
PANEL_DIR=/opt/phobos-panel
REPO=andrey271192/PCA_Phobos
RAW="https://raw.githubusercontent.com/$REPO"
PUB_REPO=andrey271192/PCA_Phobos
DEV_REPO=andrey271192/PCA_Phobos-dev
BACKUPS="$PHOBOS_DIR/updates"
VERFILE="$PANEL_DIR/.version"
CUR=$(cat "$VERFILE" 2>/dev/null || echo "unknown")
# Токен подписчика для приватных каналов: env > сохранённый файл
GH_TOKEN="${GH_TOKEN:-$(cat "$PANEL_DIR/.gh_token" 2>/dev/null || true)}"
# repo for a ref/channel: beta/dev/*-beta/*-dev -> private, остальное -> public
repo_for() { case "$1" in beta|dev|*-beta|*-dev) echo "$DEV_REPO";; *) echo "$PUB_REPO";; esac; }
is_private() { case "$1" in beta|dev|*-beta|*-dev) return 0;; *) return 1;; esac; }
# curl with token header only when ref is a private channel
gh_curl() { # $1=ref, rest=curl args
local ref="$1"; shift
if is_private "$ref" && [ -n "$GH_TOKEN" ]; then
curl -H "Authorization: token $GH_TOKEN" "$@"
else
curl "$@"
fi
}
managed_files() {
cat <<LIST
@@ -35,7 +58,13 @@ $PHOBOS_DIR/server/update.sh|update.sh
LIST
}
latest_version() { curl -fsSL -m10 "$RAW/main/VERSION" 2>/dev/null | tr -d ' \r\n'; }
# fetch VERSION of a channel (public repos / or private if token present)
chan_version() { # $1 = ref(channel)
local repo; repo=$(repo_for "$1"); local repo_ref="$1"
if is_private "$1" && [ -z "$GH_TOKEN" ]; then echo ""; return; fi
gh_curl "$1" -fsSL -m8 "https://raw.githubusercontent.com/$repo/$1/VERSION" 2>/dev/null | tr -d ' \r\n'
}
latest_version() { curl -fsSL -m10 "https://raw.githubusercontent.com/$PUB_REPO/main/VERSION" 2>/dev/null | tr -d ' \r\n'; }
do_backup() {
local dir="$BACKUPS/${CUR}-$(date +%Y%m%d-%H%M%S)"
@@ -48,10 +77,12 @@ do_backup() {
}
apply_ref() {
local ref="$1"
local ref="$1"; local repo; repo=$(repo_for "$ref")
local repo_ref="$ref"
local RAW="https://raw.githubusercontent.com/$repo/$ref"
managed_files | while IFS='|' read -r lp rp; do
local tmp; tmp=$(mktemp)
if curl -fsSL -m25 "$RAW/$ref/$rp" -o "$tmp" && [ -s "$tmp" ]; then
if gh_curl "$ref" -fsSL -m25 "$RAW/$rp" -o "$tmp" && [ -s "$tmp" ]; then
mkdir -p "$(dirname "$lp")"; mv "$tmp" "$lp"
case "$lp" in *.sh|*.py) chmod +x "$lp" 2>/dev/null || true;; esac
else
@@ -60,10 +91,33 @@ apply_ref() {
done
}
ref_exists() {
local repo; repo=$(repo_for "$1"); local repo_ref="$1"
gh_curl "$1" -fsSL -m12 "https://raw.githubusercontent.com/$repo/$1/app.py" -o /dev/null 2>/dev/null
}
case "${1:-}" in
--version|-v)
echo "Установлено: $CUR"
echo "Доступно: $(latest_version)"
--version|-v|--check)
echo "Установлено: $CUR"
echo "Стабильная: $(latest_version) [открытый]"
b=$(chan_version beta); d=$(chan_version dev)
if [ -n "$GH_TOKEN" ]; then
[ -n "$b" ] && echo "Бета (beta): $b [приватный, токен ок]"
[ -n "$d" ] && echo "Разработка(dev):$d [приватный, токен ок]"
else
echo "Бета (beta): — [приватный: нужен GH_TOKEN подписчика]"
echo "Разработка(dev):— [приватный: нужен GH_TOKEN подписчика]"
fi
;;
--versions|--tags)
echo "Стабильные версии (публичные теги):"
curl -fsSL -m10 "https://api.github.com/repos/$PUB_REPO/tags?per_page=100" 2>/dev/null \
| grep -oE '"name": *"[^"]+"' | sed 's/.*"name": *"\(.*\)"/ \1/' || echo " (нет данных)"
if [ -n "$GH_TOKEN" ]; then
echo "Закрытые версии (приватные теги, beta/dev):"
curl -fsSL -m10 -H "Authorization: token $GH_TOKEN" "https://api.github.com/repos/$DEV_REPO/tags?per_page=100" 2>/dev/null \
| grep -oE '"name": *"[^"]+"' | sed 's/.*"name": *"\(.*\)"/ \1/' || echo " (нет данных)"
fi
;;
--list)
echo "Бэкапы (для отката):"
@@ -82,8 +136,27 @@ case "${1:-}" in
echo "Откат выполнен -> $fromver"
;;
*)
ref="${1:-main}"; [ "$ref" = "latest" ] && ref="main"
target=$(curl -fsSL -m10 "$RAW/$ref/VERSION" 2>/dev/null | tr -d ' \r\n'); [ -z "$target" ] && target="$ref"
ref="${1:-main}"
case "$ref" in latest|stable) ref="main";; esac
# Каналы beta/dev — приватный репозиторий, нужен токен подписчика
if is_private "$ref" && [ -z "$GH_TOKEN" ]; then
echo "Канал '$ref' закрыт (бета/разработка) — приватный репозиторий."
echo "Нужен read-only токен подписчика:"
echo " GH_TOKEN=ваш_токен phobos-update $ref"
echo "Токен — по подписке: https://boosty.to/andrey27 . Стабильная (без токена): phobos-update stable"
exit 1
fi
if ! ref_exists "$ref"; then
echo "Версия/ветка '$ref' не найдена (или токен неверный). Обновление отменено (текущая $CUR не тронута)."
echo "Доступные: phobos-update --versions · стабильная: $(latest_version)"
exit 1
fi
# сохранить токен для будущих обновлений приватного канала
if is_private "$ref" && [ -n "$GH_TOKEN" ]; then
( umask 077; printf %s "$GH_TOKEN" > "$PANEL_DIR/.gh_token" )
fi
repo_ref="$ref"
target=$(gh_curl "$ref" -fsSL -m10 "https://raw.githubusercontent.com/$(repo_for "$ref")/$ref/VERSION" 2>/dev/null | tr -d ' \r\n'); [ -z "$target" ] && target="$ref"
echo "Текущая: $CUR -> целевая: $target ($ref)"
b=$(do_backup); echo "Бэкап: $b"
apply_ref "$ref"