Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ff7cc5c592 | ||
|
|
2808a49fa5 |
+2
-1
@@ -5,6 +5,7 @@ FROM python:3.12-slim
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
APP_PORT=5000 \
|
||||
PANEL_IN_DOCKER=1 \
|
||||
PIP_DISABLE_PIP_VERSION_CHECK=1
|
||||
|
||||
WORKDIR /app
|
||||
@@ -21,6 +22,6 @@ COPY . .
|
||||
EXPOSE 5000
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
|
||||
CMD curl -fsS "http://127.0.0.1:${APP_PORT}/docs" >/dev/null || exit 1
|
||||
CMD curl -fsS "http://127.0.0.1:${APP_PORT}/health" >/dev/null || exit 1
|
||||
|
||||
CMD ["python3", "app.py"]
|
||||
|
||||
@@ -228,6 +228,12 @@ GitHub Actions workflows in `.github/workflows/`:
|
||||
|
||||
## 📋 Fix / changelog (this fork)
|
||||
|
||||
### v2.5.6
|
||||
* **Fix 404 after in-panel update (no tunnel)** — safer Docker restart, validate update before restart, friendly 404 page with panel link.
|
||||
|
||||
### v2.5.5
|
||||
* **Fix 404 after panel update** — correct tunnel/local port when `APP_PORT` is set (Docker), health check before reload, auto-restart quick tunnels after reboot, reliable archive download URLs.
|
||||
|
||||
### v2.5.4
|
||||
* **Move connections between servers** — on a server page, select configs and move them to another server (recreates peers, keeps user links).
|
||||
|
||||
|
||||
@@ -29,7 +29,8 @@ from fastapi.responses import JSONResponse, RedirectResponse, HTMLResponse, Stre
|
||||
from starlette.background import BackgroundTask
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from fastapi import FastAPI, Request, Query, UploadFile, File
|
||||
from fastapi import FastAPI, Request, Query, UploadFile, File, HTTPException
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
from starlette.middleware.sessions import SessionMiddleware
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional, List, Dict
|
||||
@@ -102,7 +103,7 @@ else:
|
||||
application_path = os.path.dirname(__file__)
|
||||
|
||||
DATA_FILE = os.path.join(application_path, 'data.json') # legacy JSON; used only for one-shot import / export
|
||||
CURRENT_VERSION = "v2.5.4"
|
||||
CURRENT_VERSION = "v2.5.6"
|
||||
RELEASES_REPO_URL = repo_url()
|
||||
RELEASES_API_LATEST = api_latest_url()
|
||||
BIN_DIR = os.environ.get('TUNNEL_BIN_DIR', os.path.join(application_path, 'bin'))
|
||||
@@ -224,12 +225,46 @@ def tpl(request, template, **kwargs):
|
||||
return templates.TemplateResponse(template, ctx)
|
||||
|
||||
|
||||
def get_panel_listen_port(data: Optional[dict] = None) -> int:
|
||||
try:
|
||||
env_port = int(os.environ.get('APP_PORT', '0') or '0')
|
||||
except ValueError:
|
||||
env_port = 0
|
||||
if env_port:
|
||||
return env_port
|
||||
if data is None:
|
||||
data = load_data()
|
||||
ssl_conf = data.get('settings', {}).get('ssl', {}) or {}
|
||||
try:
|
||||
return int(ssl_conf.get('panel_port', 5000) or 5000)
|
||||
except (TypeError, ValueError):
|
||||
return 5000
|
||||
|
||||
|
||||
def panel_ssl_active(data: Optional[dict] = None) -> bool:
|
||||
if data is None:
|
||||
data = load_data()
|
||||
ssl_conf = data.get('settings', {}).get('ssl', {}) or {}
|
||||
if not ssl_conf.get('enabled'):
|
||||
return False
|
||||
# Docker/compose usually terminates TLS outside the app and serves plain HTTP inside.
|
||||
if os.environ.get('APP_PORT'):
|
||||
return False
|
||||
cert_path = ssl_conf.get('cert_path')
|
||||
key_path = ssl_conf.get('key_path')
|
||||
if ssl_conf.get('cert_text') or ssl_conf.get('key_text'):
|
||||
return True
|
||||
return bool(
|
||||
cert_path and key_path
|
||||
and os.path.exists(cert_path) and os.path.exists(key_path)
|
||||
)
|
||||
|
||||
|
||||
def get_panel_local_url(request: Optional[Request] = None):
|
||||
data = load_data()
|
||||
ssl_conf = data.get('settings', {}).get('ssl', {})
|
||||
scheme = 'https' if ssl_conf.get('enabled') else 'http'
|
||||
scheme = 'https' if panel_ssl_active(data) else 'http'
|
||||
host = '127.0.0.1'
|
||||
port = ssl_conf.get('panel_port', 5000) or 5000
|
||||
port = get_panel_listen_port(data)
|
||||
if request:
|
||||
scheme = request.url.scheme or scheme
|
||||
host = request.url.hostname or host
|
||||
@@ -239,12 +274,59 @@ def get_panel_local_url(request: Optional[Request] = None):
|
||||
|
||||
def get_panel_tunnel_target_url():
|
||||
data = load_data()
|
||||
ssl_conf = data.get('settings', {}).get('ssl', {})
|
||||
scheme = 'https' if ssl_conf.get('enabled') else 'http'
|
||||
port = ssl_conf.get('panel_port', 5000) or 5000
|
||||
scheme = 'https' if panel_ssl_active(data) else 'http'
|
||||
port = get_panel_listen_port(data)
|
||||
return f"{scheme}://127.0.0.1:{port}"
|
||||
|
||||
|
||||
def get_panel_public_url(request: Optional[Request] = None) -> str:
|
||||
if request is not None:
|
||||
forwarded_proto = (request.headers.get('x-forwarded-proto') or '').split(',')[0].strip()
|
||||
scheme = forwarded_proto or request.url.scheme or 'http'
|
||||
host = (
|
||||
(request.headers.get('x-forwarded-host') or '').split(',')[0].strip()
|
||||
or request.headers.get('host')
|
||||
or request.url.netloc
|
||||
)
|
||||
if host:
|
||||
return f"{scheme}://{host}/"
|
||||
return get_panel_local_url(request).rstrip('/') + '/'
|
||||
|
||||
|
||||
def enrich_update_result(request: Request, result: dict) -> dict:
|
||||
result['panel_url'] = get_panel_public_url(request)
|
||||
return result
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def custom_http_exception_handler(request: Request, exc: StarletteHTTPException):
|
||||
if exc.status_code != 404:
|
||||
detail = exc.detail if isinstance(exc.detail, str) else 'Error'
|
||||
if request.url.path.startswith('/api/'):
|
||||
return JSONResponse({'error': detail}, status_code=exc.status_code)
|
||||
return HTMLResponse(f'<h1>{exc.status_code}</h1><p>{detail}</p>', status_code=exc.status_code)
|
||||
if request.url.path.startswith('/api/') or 'application/json' in (request.headers.get('accept') or '').lower():
|
||||
return JSONResponse({'error': 'Not found'}, status_code=404)
|
||||
home = get_panel_public_url(request)
|
||||
return HTMLResponse(
|
||||
f'''<!DOCTYPE html><html><head><meta charset="utf-8"><title>Amnezia Panel</title></head>
|
||||
<body style="font-family:sans-serif;max-width:520px;margin:3rem auto;padding:0 1rem;">
|
||||
<h1>Страница не найдена</h1>
|
||||
<p>Адрес <code>{request.url.path}</code> не существует в панели.</p>
|
||||
<p>Если вы только что обновили панель, подождите 10–30 секунд и откройте:</p>
|
||||
<p><a href="{home}">{home}</a></p>
|
||||
<p><a href="/health">/health</a> — проверка, что панель запущена.</p>
|
||||
</body></html>''',
|
||||
status_code=404,
|
||||
)
|
||||
|
||||
|
||||
@app.get('/health', include_in_schema=False)
|
||||
@app.get('/api/health', include_in_schema=False)
|
||||
async def health_check():
|
||||
return {'status': 'ok', 'version': CURRENT_VERSION}
|
||||
|
||||
|
||||
def get_warp_cli_binary():
|
||||
found = shutil.which(WARP_CLI_COMMAND)
|
||||
if found:
|
||||
@@ -2436,6 +2518,24 @@ async def startup():
|
||||
logger.info("Starting Telegram bot from saved settings...")
|
||||
tg_bot.launch_bot(tg_cfg['token'], load_data, generate_vpn_link, save_data)
|
||||
|
||||
# Reattach quick tunnels after panel restart so public URLs keep working.
|
||||
try:
|
||||
tunnel_state = await asyncio.to_thread(load_tunnel_state)
|
||||
local_url = get_panel_tunnel_target_url()
|
||||
for provider in ('cloudflare', 'ngrok'):
|
||||
state = tunnel_state.get(provider) or {}
|
||||
if not (state.get('public_url') or state.get('pid') or state.get('started_at')):
|
||||
continue
|
||||
if state.get('pid') and pid_is_running(state.get('pid')):
|
||||
continue
|
||||
try:
|
||||
await asyncio.to_thread(start_tunnel, provider, local_url)
|
||||
logger.info('Restarted %s tunnel after panel boot -> %s', provider, local_url)
|
||||
except Exception as exc:
|
||||
logger.warning('Could not restart %s tunnel after panel boot: %s', provider, exc)
|
||||
except Exception as exc:
|
||||
logger.warning('Tunnel auto-restart skipped: %s', exc)
|
||||
|
||||
|
||||
def _scrape_server_traffic(server, sid, my_conns):
|
||||
server_updates = []
|
||||
@@ -5843,11 +5943,11 @@ async def api_my_connection_config(request: Request, connection_id: str):
|
||||
return JSONResponse({'error': str(e)}, status_code=500)
|
||||
|
||||
|
||||
@app.get('/settings', tags=["System Templates"])
|
||||
@app.get('/settings', response_class=HTMLResponse, tags=["System Templates"])
|
||||
async def settings_page(request: Request):
|
||||
user = _check_admin(request)
|
||||
if not user:
|
||||
return RedirectResponse('/login')
|
||||
return RedirectResponse('/login', status_code=302)
|
||||
data = load_data()
|
||||
from managers.xui_servers import list_xui_servers, public_server_view, ensure_xui_servers
|
||||
settings = data.setdefault('settings', {})
|
||||
@@ -5951,8 +6051,8 @@ async def api_apply_update(request: Request, req: ApplyUpdateRequest):
|
||||
return JSONResponse({'error': result.get('message') or 'Update failed', **result}, status_code=status_code)
|
||||
|
||||
if result.get('restart'):
|
||||
UpdateManager.schedule_restart(1.5)
|
||||
return result
|
||||
UpdateManager.schedule_restart(application_path, 1.5)
|
||||
return enrich_update_result(request, result)
|
||||
|
||||
|
||||
@app.post('/api/settings/upgrade_panel', tags=["Settings"])
|
||||
@@ -5989,10 +6089,10 @@ async def api_upgrade_panel(request: Request):
|
||||
if result.get('status') != 'success':
|
||||
return JSONResponse({'error': result.get('message') or 'Update failed', **result}, status_code=500)
|
||||
if result.get('restart'):
|
||||
UpdateManager.schedule_restart(1.5)
|
||||
UpdateManager.schedule_restart(application_path, 1.5)
|
||||
result['up_to_date'] = False
|
||||
result['previous_version'] = CURRENT_VERSION
|
||||
return result
|
||||
return enrich_update_result(request, result)
|
||||
|
||||
|
||||
@app.get('/api/settings/tunnels/status', tags=["Settings"])
|
||||
@@ -6564,10 +6664,10 @@ if __name__ == '__main__':
|
||||
uvicorn_kwargs = {
|
||||
"app": app,
|
||||
"host": "0.0.0.0",
|
||||
"port": env_port or ssl_conf.get('panel_port', 5000) or 5000,
|
||||
"port": env_port or get_panel_listen_port(data),
|
||||
}
|
||||
|
||||
if ssl_conf.get('enabled') and cert_file and key_file:
|
||||
if panel_ssl_active(data) and cert_file and key_file:
|
||||
if os.path.exists(cert_file) and os.path.exists(key_file):
|
||||
logger.info(f"Starting panel with HTTPS enabled on domain: {ssl_conf.get('domain')} at port {uvicorn_kwargs['port']}")
|
||||
uvicorn_kwargs["ssl_certfile"] = cert_file
|
||||
|
||||
+1
-1
@@ -37,7 +37,7 @@ services:
|
||||
- amnezia_data:/app/data
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:5000/docs >/dev/null || exit 1"]
|
||||
test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:5000/health >/dev/null || exit 1"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
@@ -278,12 +279,33 @@ class UpdateManager:
|
||||
}
|
||||
|
||||
def _archive_urls(self, tag: str) -> list[str]:
|
||||
urls: list[str] = []
|
||||
api_base = api_latest_url().rsplit('/releases/latest', 1)[0]
|
||||
for endpoint in (f'{api_base}/releases/tags/{tag}', api_latest_url()):
|
||||
try:
|
||||
req = urllib.request.Request(
|
||||
endpoint,
|
||||
headers={'Accept': 'application/json', 'User-Agent': 'Amnezia-Web-Panel-Updater'},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
payload = json.loads(resp.read().decode('utf-8', errors='replace') or '{}')
|
||||
zipball = (payload.get('zipball_url') or '').strip()
|
||||
if zipball:
|
||||
urls.append(zipball)
|
||||
except Exception:
|
||||
pass
|
||||
base = repo_url()
|
||||
return [
|
||||
urls.extend([
|
||||
f'{base}/archive/{tag}.zip',
|
||||
f'{base}/archive/{tag.lstrip("v")}.zip',
|
||||
f'{api_latest_url().rsplit("/releases/latest", 1)[0]}/archive/{tag}.zip',
|
||||
]
|
||||
f'{api_base}/archive/{tag}.zip',
|
||||
])
|
||||
seen = set()
|
||||
ordered: list[str] = []
|
||||
for url in urls:
|
||||
if url and url not in seen:
|
||||
seen.add(url)
|
||||
ordered.append(url)
|
||||
return ordered
|
||||
|
||||
def _download_archive(self, tag: str, dest_path: str) -> None:
|
||||
last_err = 'unknown error'
|
||||
@@ -311,6 +333,15 @@ class UpdateManager:
|
||||
return only
|
||||
return extract_dir
|
||||
|
||||
def _verify_tree(self, root: str) -> Optional[str]:
|
||||
app_py = os.path.join(root, 'app.py')
|
||||
if not os.path.isfile(app_py):
|
||||
return 'Release archive is missing app.py'
|
||||
code, _, err = _run([sys.executable, '-m', 'py_compile', app_py], root, timeout=60)
|
||||
if code != 0:
|
||||
return f'Updated app.py failed validation: {err or code}'
|
||||
return None
|
||||
|
||||
def _sync_tree(self, src_root: str) -> None:
|
||||
for root, dirs, files in os.walk(src_root):
|
||||
dirs[:] = [d for d in dirs if d not in ARCHIVE_SKIP_DIRS]
|
||||
@@ -336,6 +367,9 @@ class UpdateManager:
|
||||
src_root = self._extract_zip_root(extract_dir)
|
||||
if not os.path.isdir(src_root):
|
||||
return {'status': 'error', 'message': 'Invalid release archive layout'}
|
||||
verify_err = self._verify_tree(src_root)
|
||||
if verify_err:
|
||||
return {'status': 'error', 'message': verify_err, 'method': 'archive'}
|
||||
self._sync_tree(src_root)
|
||||
except Exception as e:
|
||||
return {'status': 'error', 'message': str(e), 'method': 'archive'}
|
||||
@@ -383,15 +417,36 @@ class UpdateManager:
|
||||
return {'status': 'error', 'message': hint, 'mode': mode}
|
||||
|
||||
@staticmethod
|
||||
def schedule_restart(delay_sec: float = 1.5) -> None:
|
||||
def schedule_restart(app_root: str, delay_sec: float = 1.5) -> None:
|
||||
in_docker = os.path.exists('/.dockerenv') or os.environ.get('PANEL_IN_DOCKER') == '1'
|
||||
|
||||
def _restart():
|
||||
time.sleep(max(0.5, float(delay_sec)))
|
||||
cwd = os.path.abspath(app_root or os.getcwd())
|
||||
argv = [sys.executable] + sys.argv
|
||||
logger.info('Restarting panel after update: %s (cwd=%s, docker=%s)', argv, cwd, in_docker)
|
||||
if in_docker:
|
||||
# Let Docker restart policy bring the container back with updated /app files.
|
||||
os._exit(0)
|
||||
try:
|
||||
argv = [sys.executable] + sys.argv
|
||||
logger.info('Restarting panel after update: %s', argv)
|
||||
os.chdir(cwd)
|
||||
proc = subprocess.Popen(
|
||||
argv,
|
||||
cwd=cwd,
|
||||
start_new_session=True,
|
||||
close_fds=(os.name != 'nt'),
|
||||
)
|
||||
time.sleep(2.0)
|
||||
if proc.poll() is None:
|
||||
logger.info('New panel process started (pid=%s), stopping old process', proc.pid)
|
||||
os._exit(0)
|
||||
except Exception:
|
||||
logger.exception('subprocess restart failed; trying execv')
|
||||
try:
|
||||
os.chdir(cwd)
|
||||
os.execv(sys.executable, argv)
|
||||
except Exception:
|
||||
logger.exception('Failed to restart after update; exiting')
|
||||
os._exit(0)
|
||||
logger.exception('Failed to restart after update')
|
||||
os._exit(1)
|
||||
|
||||
threading.Thread(target=_restart, name='panel-update-restart', daemon=False).start()
|
||||
|
||||
+37
-8
@@ -1718,6 +1718,24 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function waitForPanelRestart(timeoutMs = 120000, panelUrl) {
|
||||
const base = String(panelUrl || window.location.origin || '').replace(/\/$/, '');
|
||||
const started = Date.now();
|
||||
while (Date.now() - started < timeoutMs) {
|
||||
try {
|
||||
const res = await fetch(`${base}/api/health`, { cache: 'no-store' });
|
||||
if (res.ok) {
|
||||
window.location.href = base + '/';
|
||||
return true;
|
||||
}
|
||||
} catch (_) {}
|
||||
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||
}
|
||||
const hint = base ? ` ${base}` : '';
|
||||
showToast("{{ _('update_restart_timeout')|default('Panel did not come back in time. Refresh the page manually.') }}" + hint, 'error');
|
||||
return false;
|
||||
}
|
||||
|
||||
async function applyPanelUpdate() {
|
||||
const applyBtn = document.getElementById('applyUpdateBtn');
|
||||
const applyText = document.getElementById('applyUpdateBtnText');
|
||||
@@ -1733,18 +1751,24 @@
|
||||
applyBtn.disabled = true;
|
||||
applyText.textContent = "{{ _('applying_update')|default('Updating…') }}";
|
||||
applySpinner.classList.remove('hidden');
|
||||
let restarting = false;
|
||||
try {
|
||||
const data = await apiCall('/api/settings/apply_update', 'POST', {
|
||||
target_version: target,
|
||||
allow_dirty: true,
|
||||
});
|
||||
showToast(data.message || "{{ _('update_restarting')|default('Updated. Restarting…') }}", 'success');
|
||||
setTimeout(() => { window.location.reload(); }, 3500);
|
||||
restarting = true;
|
||||
applyText.textContent = "{{ _('update_waiting_restart')|default('Waiting for panel…') }}";
|
||||
await waitForPanelRestart(120000, data.panel_url);
|
||||
} catch (err) {
|
||||
showToast(_('error') + ': ' + err.message, 'error');
|
||||
applyBtn.disabled = false;
|
||||
applyText.textContent = "⬆ {{ _('apply_update')|default('Install update') }}";
|
||||
applySpinner.classList.add('hidden');
|
||||
} finally {
|
||||
if (!restarting) {
|
||||
applyBtn.disabled = false;
|
||||
applyText.textContent = "⬆ {{ _('apply_update')|default('Install update') }}";
|
||||
applySpinner.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1761,6 +1785,7 @@
|
||||
btn.disabled = true;
|
||||
spinner.classList.remove('hidden');
|
||||
text.textContent = "{{ _('upgrade_panel_working')|default('Updating panel…') }}";
|
||||
let restarting = false;
|
||||
try {
|
||||
const data = await apiCall('/api/settings/upgrade_panel', 'POST', {});
|
||||
if (data.up_to_date) {
|
||||
@@ -1769,14 +1794,18 @@
|
||||
return;
|
||||
}
|
||||
showToast(data.message || "{{ _('update_restarting')|default('Updated. Restarting…') }}", 'success');
|
||||
setTimeout(() => { window.location.reload(); }, 4000);
|
||||
restarting = true;
|
||||
text.textContent = "{{ _('update_waiting_restart')|default('Waiting for panel…') }}";
|
||||
await waitForPanelRestart(120000, data.panel_url);
|
||||
} catch (err) {
|
||||
showToast(_('error') + ': ' + err.message, 'error');
|
||||
await checkForUpdates(true);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
spinner.classList.add('hidden');
|
||||
text.textContent = "⬆ {{ _('upgrade_panel')|default('Update panel') }}";
|
||||
if (!restarting) {
|
||||
btn.disabled = false;
|
||||
spinner.classList.add('hidden');
|
||||
text.textContent = "⬆ {{ _('upgrade_panel')|default('Update panel') }}";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -505,6 +505,8 @@
|
||||
"applying_update": "Updating…",
|
||||
"apply_update_confirm": "Install update from git.evilfox.cc and restart the panel?",
|
||||
"update_restarting": "Updated. Restarting panel…",
|
||||
"update_waiting_restart": "Waiting for panel to restart…",
|
||||
"update_restart_timeout": "Panel did not come back in time. Refresh the page manually.",
|
||||
"update_no_target": "No target version. Check for updates first.",
|
||||
"auto_update_hint": "Auto-update pulls the release tag from git.evilfox.cc (git checkout required).",
|
||||
"auto_update_ready": "Git auto-update is available for this install.",
|
||||
|
||||
@@ -505,6 +505,8 @@
|
||||
"applying_update": "Обновление…",
|
||||
"apply_update_confirm": "Установить обновление с git.evilfox.cc и перезапустить панель?",
|
||||
"update_restarting": "Обновлено. Перезапуск панели…",
|
||||
"update_waiting_restart": "Ожидание перезапуска панели…",
|
||||
"update_restart_timeout": "Панель не ответила вовремя. Обновите страницу вручную.",
|
||||
"update_no_target": "Нет целевой версии. Сначала проверьте обновления.",
|
||||
"auto_update_hint": "Автообновление тянет тег релиза с git.evilfox.cc (нужен git clone панели).",
|
||||
"auto_update_ready": "Для этой установки доступно автообновление через git.",
|
||||
|
||||
Reference in New Issue
Block a user