Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
80160d0ef4 | ||
|
|
ac76a0e540 | ||
|
|
bf7bd16fcd | ||
|
|
24e793d943 | ||
|
|
415cfea5eb | ||
|
|
04a32fb168 | ||
|
|
183071f588 | ||
|
|
ed5c54cf96 | ||
|
|
a9a0eea61d | ||
|
|
64aa1850a0 | ||
|
|
b71c31605d |
@@ -1,6 +1,6 @@
|
||||
# Amnezia Web Panel
|
||||
|
||||
A modern, high-performance web interface for managing **AmneziaWG**, **Classic WireGuard**, **Xray (XTLS-Reality)**, **Telemt (Telegram MTProxy)**, **Cloudflare WARP**, **AmneziaDNS**, **AdGuard Home**, **SOCKS5**, and **NGINX + Let's Encrypt** services on remote Ubuntu servers — from a single dashboard. Designed to provide a premium user experience with robust administrative capabilities.
|
||||
A modern, high-performance web interface for managing **AmneziaWG**, **Classic WireGuard**, **Xray (XTLS-Reality)**, **Hysteria 2**, **NaiveProxy**, **Telemt (Telegram MTProxy)**, **Cloudflare WARP**, **AmneziaDNS**, **AdGuard Home**, **SOCKS5**, and **NGINX + Let's Encrypt** services on remote Ubuntu servers — from a single dashboard. Designed to provide a premium user experience with robust administrative capabilities.
|
||||
|
||||
> ### 🔄 Compatibility with Official Amnezia Client
|
||||
>
|
||||
@@ -62,6 +62,8 @@ Configuration panel for system parameters and preferences:
|
||||
* **AmneziaWG (AWG / AWG 2.0 / AWG Legacy)**: Advanced WireGuard-based protocol with S3/S4 obfuscation to bypass deep packet inspection (DPI). Three coexisting variants — modern AWG 2.0 with full junk-packet masking, and a legacy variant for older clients.
|
||||
* **Classic WireGuard**: Standard, high-performance WireGuard protocol for unmatched speed and broad device compatibility with traffic monitoring support.
|
||||
* **Xray (XTLS-Reality)**: Stealthy protocol that masks VPN traffic as standard HTTPS browsing. Pinned to **Xray-core v26.x**; transparently reads both the **panel layout** (`meta.json` + `clientsTable.json`) and the **native Amnezia client layout** (`xray_*.key` files + `clientsTable`), so a node first installed via the official mobile/desktop app can be attached to the panel without re-installation.
|
||||
* **Hysteria 2**: QUIC/HTTP3 proxy from [apernet/hysteria](https://github.com/apernet/hysteria) via `tobyxdd/hysteria:v2` — Let's Encrypt TLS, salamander obfuscation, password auth, `hy2://` share links. Per-server SSL domain/email defaults, renew from settings; install requires free TCP **80** and **443**.
|
||||
* **NaiveProxy** (stable): HTTPS/HTTP2 camouflage proxy via [klzgrad/naiveproxy](https://github.com/klzgrad/naiveproxy) (Caddy + [klzgrad/forwardproxy](https://github.com/klzgrad/forwardproxy) naïve fork). ACME TLS on the domain, per-client basic auth, `naive+https://` share links. Requires free TCP **80** and **443**. **Use Karing** as the client — do **not** use v2rayN; other clients are untested.
|
||||
* **Telemt (Telegram MTProxy)**: High-performance Telegram MTProxy with TLS emulation and comprehensive management (quotas, IP limits, real-time session tracking). Robust install path that auto-configures Docker's official apt/yum repository when needed.
|
||||
* **Cloudflare WARP**: Add and manage WARP-powered connectivity from the panel for routing and network flexibility.
|
||||
* **🛠 Services**:
|
||||
@@ -71,13 +73,19 @@ Configuration panel for system parameters and preferences:
|
||||
* **NGINX + Let's Encrypt**: Reverse-proxy and HTTPS automation with certificate management for secure public endpoints.
|
||||
* **⚙️ Core Server Management**:
|
||||
* **Add / Edit / Delete / Reorder** server entries — drag-and-drop reorder updates `server_id` references in saved connections automatically.
|
||||
* **Per-server SSL defaults**: optional domain + Let's Encrypt email on each server, pre-filled when installing Hysteria or NGINX.
|
||||
* **Live ping indicator** next to each server name — non-blocking TCP-connect probe to the SSH port, runs on the asyncio loop in parallel for all servers.
|
||||
* **Clear server** wipes every Amnezia-related container, image and `/opt/amnezia` directory in a single sudo script — works for any current or future `amnezia-*` protocol.
|
||||
* **Reboot** the server directly from the UI.
|
||||
* Strictly concurrent protocol status polling — all supported protocols/services checked in parallel for immediate feedback.
|
||||
* **Asynchronous Processing**: Resilient, non-blocking background architecture prevents the UI panel from freezing, even if remote endpoints hang.
|
||||
* **🔁 Cascade (double VPN)**:
|
||||
* Route clients through an **entry** AmneziaWG/WireGuard server to an **exit** server (country-block bypass).
|
||||
* Approach inspired by [ryderams/amneziawg-cascade](https://github.com/ryderams/amneziawg-cascade) (AWG2 entry→exit); applied via panel SSH — **no remote curl|bash** script download.
|
||||
* Handshake wait + optional egress verify (curl --interface → ifconfig.me); exit return route persisted like ryderams vps2.
|
||||
* Users keep using the **ENTRY** client config only — do not share the exit cascade peer.
|
||||
* **🧩 Marketplace & Templates**:
|
||||
* Market templates provide quick presets for installing and configuring supported protocols and services.
|
||||
* Market templates provide quick presets for installing and configuring supported protocols and services (including **Hysteria 2**).
|
||||
* Multi-protocol management lets you run and control multiple protocol instances on the same server.
|
||||
* **🌐 Internationalization (i18n)**:
|
||||
* Full support for **English**, **Russian**, **French**, **Chinese**, and **Persian**.
|
||||
@@ -219,16 +227,53 @@ GitHub Actions workflows in `.github/workflows/`:
|
||||
|
||||
## 📋 Fix / changelog (this fork)
|
||||
|
||||
### v2.2.1
|
||||
* **Cascade egress verify fix**: bind curl to ENTRY `awg0`/`wg0` IP (client-subnet policy route), not cascade peer Address.
|
||||
* Soft-warn (no rollback) when policy route via `cascade` is OK but public-IP echo services fail.
|
||||
|
||||
### v2.2.0
|
||||
* **Cascade (double VPN) restored** — stable entry→exit tunnel for AmneziaWG / WireGuard.
|
||||
* Inspired by [ryderams/amneziawg-cascade](https://github.com/ryderams/amneziawg-cascade); logic runs over panel SSH (**no remote curl|bash**).
|
||||
* Safety: require exit **handshake** when enabled; optional **egress verify**; subnet conflict check; exit `/32` return route with start.sh markers.
|
||||
* UI on the server page with per-step settings (pin exit route, MSS clamp, verify egress, …). Defaults prefer **awg2**.
|
||||
|
||||
### v2.1.0
|
||||
* **NaiveProxy — stable**: production-ready install (Caddy + klzgrad/forwardproxy), share links always include `:443`.
|
||||
* **Client notes (important)**:
|
||||
* **Do not use v2rayN** with NaiveProxy (broken DNS/IPv6 behaviour → latency −1 ms even when the server is fine).
|
||||
* **Karing** — confirmed working.
|
||||
* Other clients — untested / use at your own risk.
|
||||
* Share-link and config UI hints updated accordingly.
|
||||
|
||||
### v2.0.0-beta
|
||||
* **NaiveProxy** (Beta): install [klzgrad/naiveproxy](https://github.com/klzgrad/naiveproxy) server via Caddy + naïve [forwardproxy](https://github.com/klzgrad/forwardproxy) — domain TLS (ACME), per-client basic auth, `naive+https://` share links.
|
||||
* Marketplace / server page / users / invites / Telegram / backups include NaiveProxy.
|
||||
* Install warns that free TCP **80** and **443** are required; uses per-server SSL domain/email defaults when set.
|
||||
* Official prebuilt Caddy on amd64; xcaddy build path for other arches.
|
||||
* Version line bumped to **2.0 Beta** (`v2.0.0-beta`).
|
||||
|
||||
### v1.8.0
|
||||
* **Hysteria 2** fully wired in marketplace, server page, users/invites, Telegram bot, and backups.
|
||||
* **Per-server SSL defaults**: set domain + Let's Encrypt email when adding/editing a server; values pre-fill Hysteria (and NGINX) install forms.
|
||||
* **SSL renew**: change domain or use “Renew SSL” in Hysteria settings to re-issue the certificate (needs free TCP 80).
|
||||
* **Install warning**: free TCP ports **80** and **443** required for stable Let's Encrypt / HTTPS-QUIC operation.
|
||||
* Official image `tobyxdd/hysteria:v2`, salamander obfs, password auth, `hy2://` share links, selectable UDP listen port.
|
||||
|
||||
### v1.7.0
|
||||
* **Clearer create flow**: pick **server first**, then **protocol** (WireGuard, AmneziaWG 2.0, …) — invites, guest access, and user connections no longer dump everything into one messy list.
|
||||
* Protocol titles are human-readable and ordered (AWG 2.0 → AWG → Legacy → WireGuard → Xray → Telemt → Hysteria).
|
||||
* 3x-ui is a separate “server” choice; VLESS inbounds still load from that panel’s API.
|
||||
* **Hysteria 2** manager restored ([apernet/hysteria](https://github.com/apernet/hysteria)) — see **v1.8.0** for full panel integration.
|
||||
|
||||
### v1.6.0
|
||||
* **3x-ui multi-panel**: register several 3x-ui servers in Settings; pick a panel and load VLESS inbounds over its API when creating users/invites (share link comes from 3x-ui).
|
||||
* **Docker / CI**: refreshed `Dockerfile` + compose, `.env.example`, CI checks, GHCR image workflow.
|
||||
* **Cascade removed** for now (pending redesign — showed active while internet often did not work).
|
||||
* **Cascade** was temporarily removed in this release (redesigned and restored in **v2.2.0**).
|
||||
* **WG/AWG backups**: ZIP export of client `.conf` + restore with loading feedback.
|
||||
* **API performance**: in-memory data cache, faster server check/stats.
|
||||
* **Share / guest**: one-tap “Copy key”.
|
||||
* **User expiration**: countdown can start on first config use; UTC-safe comparisons.
|
||||
* **UI**: shared SVG icon system.
|
||||
* **Removed earlier**: Hysteria 2.
|
||||
|
||||
## 🔧 Project Details
|
||||
|
||||
@@ -290,6 +335,8 @@ web-panel/
|
||||
│ ├── awg_manager.py # AmneziaWG / AWG 2.0 / AWG Legacy
|
||||
│ ├── wireguard_manager.py # Classic WireGuard
|
||||
│ ├── xray_manager.py # Xray-core (VLESS-Reality)
|
||||
│ ├── hysteria_manager.py # Hysteria 2 (apernet/hysteria)
|
||||
│ ├── naiveproxy_manager.py # NaiveProxy (Caddy + klzgrad/forwardproxy)
|
||||
│ ├── telemt_manager.py # Telegram MTProxy
|
||||
│ ├── dns_manager.py # AmneziaDNS (Unbound)
|
||||
│ ├── adguard_manager.py # AdGuard Home
|
||||
|
||||
@@ -46,6 +46,7 @@ from managers.awg_manager import AWGManager
|
||||
from managers.xray_manager import XrayManager
|
||||
from managers.wireguard_manager import WireGuardManager
|
||||
from managers.backup_manager import BackupManager
|
||||
from managers.cascade_manager import CascadeManager, normalize_settings, DEFAULT_SETTINGS as CASCADE_DEFAULT_SETTINGS
|
||||
import telegram_bot as tg_bot
|
||||
|
||||
# Configure logging
|
||||
@@ -101,7 +102,9 @@ 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 = "v1.6.0"
|
||||
CURRENT_VERSION = "v2.2.1"
|
||||
RELEASES_REPO_URL = "https://git.evilfox.cc/test2/Amnezia-Web-Panel-main"
|
||||
RELEASES_API_LATEST = "https://git.evilfox.cc/api/v1/repos/test2/Amnezia-Web-Panel-main/releases/latest"
|
||||
BIN_DIR = os.environ.get('TUNNEL_BIN_DIR', os.path.join(application_path, 'bin'))
|
||||
TUNNEL_STATE_FILE = os.environ.get('TUNNEL_STATE_FILE', os.path.join(application_path, 'tunnels_state.json'))
|
||||
|
||||
@@ -841,8 +844,8 @@ async def wait_for_tunnel_url(provider: str, seconds: int = 20):
|
||||
return get_tunnel_status(provider)
|
||||
|
||||
|
||||
BASE_PROTOCOLS = ['awg', 'awg2', 'awg_legacy', 'xray', 'telemt', 'dns', 'wireguard', 'socks5', 'adguard', 'nginx']
|
||||
MULTI_INSTANCE_PROTOCOLS = {'awg', 'awg2', 'awg_legacy', 'xray', 'telemt', 'socks5'}
|
||||
BASE_PROTOCOLS = ['awg', 'awg2', 'awg_legacy', 'xray', 'telemt', 'hysteria', 'naiveproxy', 'dns', 'wireguard', 'socks5', 'adguard', 'nginx']
|
||||
MULTI_INSTANCE_PROTOCOLS = {'awg', 'awg2', 'awg_legacy', 'xray', 'telemt', 'hysteria', 'socks5'}
|
||||
|
||||
|
||||
def protocol_base(protocol: str) -> str:
|
||||
@@ -882,6 +885,8 @@ def protocol_display_name(protocol: str) -> str:
|
||||
'awg_legacy': 'AmneziaWG Legacy',
|
||||
'xray': 'Xray',
|
||||
'telemt': 'Telemt',
|
||||
'hysteria': 'Hysteria 2',
|
||||
'naiveproxy': 'NaiveProxy',
|
||||
'dns': 'AmneziaDNS',
|
||||
'wireguard': 'WireGuard',
|
||||
'socks5': 'SOCKS5',
|
||||
@@ -901,6 +906,8 @@ def protocol_container_name(protocol: str) -> Optional[str]:
|
||||
'awg_legacy': 'amnezia-awg-legacy',
|
||||
'xray': 'amnezia-xray',
|
||||
'telemt': 'telemt',
|
||||
'hysteria': 'amnezia-hysteria',
|
||||
'naiveproxy': 'amnezia-naiveproxy',
|
||||
'dns': 'amnezia-dns',
|
||||
'wireguard': 'amnezia-wireguard',
|
||||
'socks5': 'amnezia-socks5proxy',
|
||||
@@ -940,6 +947,12 @@ def get_protocol_manager(ssh, protocol: str):
|
||||
elif base == 'nginx':
|
||||
from managers.nginx_manager import NginxManager
|
||||
return NginxManager(ssh, protocol)
|
||||
elif base == 'hysteria':
|
||||
from managers.hysteria_manager import HysteriaManager
|
||||
return HysteriaManager(ssh, protocol)
|
||||
elif base == 'naiveproxy':
|
||||
from managers.naiveproxy_manager import NaiveProxyManager
|
||||
return NaiveProxyManager(ssh, protocol)
|
||||
from managers.awg_manager import AWGManager
|
||||
return AWGManager(ssh)
|
||||
|
||||
@@ -1001,7 +1014,7 @@ def _manager_call(manager, method, protocol, *args, **kwargs):
|
||||
|
||||
|
||||
# Protocols that own VPN clients (can list/link connections)
|
||||
CLIENT_VPN_BASES = {'awg', 'awg2', 'awg_legacy', 'xray', 'telemt', 'wireguard', 'xui'}
|
||||
CLIENT_VPN_BASES = {'awg', 'awg2', 'awg_legacy', 'xray', 'telemt', 'wireguard', 'hysteria', 'naiveproxy', 'xui'}
|
||||
|
||||
|
||||
def generate_vpn_link(config_text):
|
||||
@@ -1663,6 +1676,8 @@ class AddServerRequest(BaseModel):
|
||||
password: str = ''
|
||||
private_key: str = ''
|
||||
name: str = ''
|
||||
ssl_domain: str = ''
|
||||
ssl_email: str = ''
|
||||
|
||||
|
||||
class EditServerRequest(BaseModel):
|
||||
@@ -1675,6 +1690,8 @@ class EditServerRequest(BaseModel):
|
||||
# fields can be omitted to keep current auth unchanged.
|
||||
password: Optional[str] = None
|
||||
private_key: Optional[str] = None
|
||||
ssl_domain: Optional[str] = None
|
||||
ssl_email: Optional[str] = None
|
||||
|
||||
|
||||
class ReorderServersRequest(BaseModel):
|
||||
@@ -1704,6 +1721,12 @@ class InstallProtocolRequest(BaseModel):
|
||||
# NGINX
|
||||
nginx_domain: Optional[str] = None
|
||||
nginx_email: Optional[str] = None
|
||||
# Hysteria
|
||||
hysteria_domain: Optional[str] = None
|
||||
hysteria_email: Optional[str] = None
|
||||
# NaiveProxy
|
||||
naiveproxy_domain: Optional[str] = None
|
||||
naiveproxy_email: Optional[str] = None
|
||||
|
||||
|
||||
class Socks5SettingsRequest(BaseModel):
|
||||
@@ -1713,6 +1736,32 @@ class Socks5SettingsRequest(BaseModel):
|
||||
password: Optional[str] = None
|
||||
|
||||
|
||||
class HysteriaSettingsRequest(BaseModel):
|
||||
protocol: str = 'hysteria'
|
||||
port: Optional[int] = None
|
||||
domain: Optional[str] = None
|
||||
email: Optional[str] = None
|
||||
renew_ssl: bool = False
|
||||
|
||||
class CascadeSetupRequest(BaseModel):
|
||||
entry_protocol: str = 'awg2'
|
||||
exit_server_id: Optional[int] = None
|
||||
exit_protocol: str = 'awg2'
|
||||
enabled: bool = True
|
||||
# Per-step cascade tuning
|
||||
pin_exit_route: Optional[bool] = True
|
||||
remove_eth_masquerade: Optional[bool] = True
|
||||
force_forward: Optional[bool] = True
|
||||
mss_clamp: Optional[bool] = True
|
||||
wait_handshake: Optional[bool] = True
|
||||
handshake_timeout_sec: Optional[int] = 25
|
||||
allowed_ips: Optional[str] = '0.0.0.0/0'
|
||||
keep_exit_dns: Optional[bool] = False
|
||||
vpn_subnet_override: Optional[str] = ''
|
||||
table_id: Optional[int] = 200
|
||||
rule_priority: Optional[int] = 100
|
||||
verify_egress: Optional[bool] = True
|
||||
|
||||
class ProtocolRequest(BaseModel):
|
||||
protocol: str = 'awg'
|
||||
|
||||
@@ -2431,6 +2480,13 @@ async def api_add_server(request: Request, req: AddServerRequest):
|
||||
'private_key': req.private_key, 'server_info': server_info,
|
||||
'protocols': {},
|
||||
}
|
||||
ssl_domain = (req.ssl_domain or '').strip().lower()
|
||||
ssl_email = (req.ssl_email or '').strip()
|
||||
if ssl_domain:
|
||||
server_info['ssl_domain'] = ssl_domain
|
||||
if ssl_email:
|
||||
server_info['ssl_email'] = ssl_email
|
||||
server['server_info'] = server_info
|
||||
data = load_data()
|
||||
data['servers'].append(server)
|
||||
save_data(data)
|
||||
@@ -2491,9 +2547,27 @@ async def api_edit_server(request: Request, server_id: int, req: EditServerReque
|
||||
server['username'] = new_user
|
||||
server['password'] = new_pass
|
||||
server['private_key'] = new_key
|
||||
server['server_info'] = server_info
|
||||
# Merge SSH probe info with preserved SSL domain defaults
|
||||
info = dict(server.get('server_info') or {})
|
||||
if isinstance(server_info, dict):
|
||||
for k, v in server_info.items():
|
||||
if k not in ('ssl_domain', 'ssl_email'):
|
||||
info[k] = v
|
||||
if req.ssl_domain is not None:
|
||||
domain = (req.ssl_domain or '').strip().lower()
|
||||
if domain:
|
||||
info['ssl_domain'] = domain
|
||||
else:
|
||||
info.pop('ssl_domain', None)
|
||||
if req.ssl_email is not None:
|
||||
email = (req.ssl_email or '').strip()
|
||||
if email:
|
||||
info['ssl_email'] = email
|
||||
else:
|
||||
info.pop('ssl_email', None)
|
||||
server['server_info'] = info
|
||||
save_data(data)
|
||||
return {'status': 'success', 'server_info': server_info}
|
||||
return {'status': 'success', 'server_info': info}
|
||||
except Exception as e:
|
||||
logger.exception("Error editing server")
|
||||
return JSONResponse({'error': str(e)}, status_code=500)
|
||||
@@ -2799,6 +2873,18 @@ async def api_check_server(request: Request, server_id: int):
|
||||
for key in ('domain', 'email', 'site_url'):
|
||||
if db_proto.get(key) not in (None, ''):
|
||||
merged[key] = db_proto[key]
|
||||
if protocol_base(proto) == 'hysteria':
|
||||
for key in ('domain', 'email'):
|
||||
if db_proto.get(key) not in (None, '') and not merged.get(key):
|
||||
merged[key] = db_proto[key]
|
||||
if db_proto.get('port') and not merged.get('port'):
|
||||
merged['port'] = db_proto['port']
|
||||
if protocol_base(proto) == 'naiveproxy':
|
||||
for key in ('domain', 'email'):
|
||||
if db_proto.get(key) not in (None, '') and not merged.get(key):
|
||||
merged[key] = db_proto[key]
|
||||
if db_proto.get('port') and not merged.get('port'):
|
||||
merged['port'] = db_proto['port']
|
||||
return merged
|
||||
|
||||
def should_preserve_saved_protocol(proto, result=None, err=None):
|
||||
@@ -2950,6 +3036,20 @@ async def api_install_protocol(request: Request, server_id: int, req: InstallPro
|
||||
domain=req.nginx_domain,
|
||||
email=req.nginx_email,
|
||||
)
|
||||
elif install_base == 'hysteria':
|
||||
result = manager.install_protocol(
|
||||
protocol_type=install_protocol,
|
||||
port=req.port,
|
||||
domain=req.hysteria_domain,
|
||||
email=req.hysteria_email,
|
||||
)
|
||||
elif install_base == 'naiveproxy':
|
||||
result = manager.install_protocol(
|
||||
protocol_type=install_protocol,
|
||||
port=req.port,
|
||||
domain=req.naiveproxy_domain,
|
||||
email=req.naiveproxy_email,
|
||||
)
|
||||
else:
|
||||
result = manager.install_protocol(install_protocol, port=req.port)
|
||||
|
||||
@@ -2976,6 +3076,29 @@ async def api_install_protocol(request: Request, server_id: int, req: InstallPro
|
||||
proto_record['domain'] = result.get('domain')
|
||||
proto_record['email'] = result.get('email')
|
||||
proto_record['site_url'] = result.get('site_url')
|
||||
if install_base == 'hysteria':
|
||||
# Remember domain/email as server defaults for next installs / renewals
|
||||
info = server.setdefault('server_info', {})
|
||||
if req.hysteria_domain:
|
||||
info['ssl_domain'] = (req.hysteria_domain or '').strip().lower()
|
||||
if req.hysteria_email:
|
||||
info['ssl_email'] = (req.hysteria_email or '').strip()
|
||||
save_data(data)
|
||||
proto_record['domain'] = result.get('domain')
|
||||
proto_record['email'] = result.get('email')
|
||||
if result.get('port'):
|
||||
proto_record['port'] = str(result['port'])
|
||||
if install_base == 'naiveproxy':
|
||||
info = server.setdefault('server_info', {})
|
||||
if req.naiveproxy_domain:
|
||||
info['ssl_domain'] = (req.naiveproxy_domain or '').strip().lower()
|
||||
if req.naiveproxy_email:
|
||||
info['ssl_email'] = (req.naiveproxy_email or '').strip()
|
||||
save_data(data)
|
||||
proto_record['domain'] = result.get('domain')
|
||||
proto_record['email'] = result.get('email')
|
||||
if result.get('port'):
|
||||
proto_record['port'] = str(result['port'])
|
||||
proto_record['base_protocol'] = install_base
|
||||
proto_record['instance'] = protocol_instance(install_protocol)
|
||||
proto_record['display_name'] = protocol_display_name(install_protocol)
|
||||
@@ -3051,6 +3174,320 @@ async def api_socks5_update_credentials(request: Request, server_id: int, req: S
|
||||
return JSONResponse({'error': str(e)}, status_code=500)
|
||||
|
||||
|
||||
@app.get('/api/servers/{server_id}/hysteria/settings', tags=["Protocols"])
|
||||
async def api_hysteria_get_settings(request: Request, server_id: int, protocol: str = 'hysteria'):
|
||||
"""Return current Hysteria domain/port for the settings modal."""
|
||||
if not _check_admin(request):
|
||||
return JSONResponse({'error': 'Forbidden'}, status_code=403)
|
||||
try:
|
||||
data = load_data()
|
||||
if server_id >= len(data['servers']):
|
||||
return JSONResponse({'error': 'Server not found'}, status_code=404)
|
||||
if not is_valid_protocol(protocol) or protocol_base(protocol) != 'hysteria':
|
||||
return JSONResponse({'error': 'Invalid protocol'}, status_code=400)
|
||||
server = data['servers'][server_id]
|
||||
ssh = get_ssh(server)
|
||||
ssh.connect()
|
||||
manager = get_protocol_manager(ssh, protocol)
|
||||
settings = manager.get_settings()
|
||||
ssh.disconnect()
|
||||
saved = (server.get('protocols') or {}).get(protocol) or {}
|
||||
if not settings.get('port') and saved.get('port'):
|
||||
settings['port'] = int(saved['port'])
|
||||
return {'status': 'success', **settings}
|
||||
except Exception as e:
|
||||
logger.exception("Error reading Hysteria settings")
|
||||
return JSONResponse({'error': str(e)}, status_code=500)
|
||||
|
||||
|
||||
@app.post('/api/servers/{server_id}/hysteria/settings', tags=["Protocols"])
|
||||
async def api_hysteria_update_settings(request: Request, server_id: int, req: HysteriaSettingsRequest):
|
||||
"""Change Hysteria UDP listen port and recreate the container."""
|
||||
if not _check_admin(request):
|
||||
return JSONResponse({'error': 'Forbidden'}, status_code=403)
|
||||
try:
|
||||
data = load_data()
|
||||
if server_id >= len(data['servers']):
|
||||
return JSONResponse({'error': 'Server not found'}, status_code=404)
|
||||
protocol = req.protocol if is_valid_protocol(req.protocol) and protocol_base(req.protocol) == 'hysteria' else 'hysteria'
|
||||
server = data['servers'][server_id]
|
||||
ssh = get_ssh(server)
|
||||
ssh.connect()
|
||||
manager = get_protocol_manager(ssh, protocol)
|
||||
result = manager.update_settings(
|
||||
port=req.port,
|
||||
domain=req.domain,
|
||||
email=req.email,
|
||||
renew_ssl=bool(req.renew_ssl),
|
||||
)
|
||||
ssh.disconnect()
|
||||
if result.get('status') == 'error':
|
||||
return JSONResponse(
|
||||
{'error': result.get('message') or 'Failed to update settings', **{k: v for k, v in result.items() if k != 'status'}},
|
||||
status_code=400,
|
||||
)
|
||||
if result.get('port') or result.get('domain'):
|
||||
srv_proto = server.setdefault('protocols', {}).setdefault(protocol, {})
|
||||
if result.get('port'):
|
||||
srv_proto['port'] = str(result['port'])
|
||||
srv_proto['installed'] = True
|
||||
srv_proto['base_protocol'] = protocol_base(protocol)
|
||||
srv_proto['instance'] = protocol_instance(protocol)
|
||||
srv_proto['display_name'] = protocol_display_name(protocol)
|
||||
srv_proto['container_name'] = protocol_container_name(protocol)
|
||||
if result.get('domain'):
|
||||
srv_proto['domain'] = result['domain']
|
||||
# Keep server-level SSL defaults in sync
|
||||
info = server.setdefault('server_info', {})
|
||||
if result.get('domain'):
|
||||
info['ssl_domain'] = result['domain']
|
||||
if result.get('email'):
|
||||
info['ssl_email'] = result['email']
|
||||
save_data(data)
|
||||
return result
|
||||
except Exception as e:
|
||||
logger.exception("Error updating Hysteria settings")
|
||||
return JSONResponse({'error': str(e)}, status_code=500)
|
||||
|
||||
|
||||
@app.post('/api/servers/{server_id}/cascade', tags=["Protocols"])
|
||||
async def api_cascade_get(request: Request, server_id: int):
|
||||
"""Return saved cascade settings and live tunnel status for this (entry) server."""
|
||||
if not _check_admin(request):
|
||||
return JSONResponse({'error': 'Forbidden'}, status_code=403)
|
||||
try:
|
||||
data = await asyncio.to_thread(load_data)
|
||||
if server_id >= len(data['servers']):
|
||||
return JSONResponse({'error': 'Server not found'}, status_code=404)
|
||||
server = data['servers'][server_id]
|
||||
cascade = dict(server.get('cascade') or {})
|
||||
live = {'enabled': False, 'up': False}
|
||||
entry_proto = cascade.get('entry_protocol') or ''
|
||||
if cascade.get('enabled') and entry_proto and CascadeManager.is_wg_family(entry_proto):
|
||||
def _status():
|
||||
ssh = get_ssh(server)
|
||||
ssh.connect()
|
||||
try:
|
||||
return CascadeManager(ssh).status(entry_proto)
|
||||
finally:
|
||||
ssh.disconnect()
|
||||
live = await asyncio.to_thread(_status)
|
||||
return {
|
||||
'cascade': cascade,
|
||||
'live': live,
|
||||
'defaults': CASCADE_DEFAULT_SETTINGS,
|
||||
'servers': [
|
||||
{
|
||||
'id': i,
|
||||
'name': s.get('name') or s.get('host'),
|
||||
'host': s.get('host'),
|
||||
'protocols': list((s.get('protocols') or {}).keys()),
|
||||
}
|
||||
for i, s in enumerate(data['servers']) if i != server_id
|
||||
],
|
||||
}
|
||||
except Exception as e:
|
||||
logger.exception("Error reading cascade status")
|
||||
return JSONResponse({'error': str(e)}, status_code=500)
|
||||
|
||||
|
||||
@app.post('/api/servers/{server_id}/cascade/setup', tags=["Protocols"])
|
||||
async def api_cascade_setup(request: Request, server_id: int, req: CascadeSetupRequest):
|
||||
"""Enable or disable double-VPN cascade: clients → this entry → exit server."""
|
||||
if not _check_admin(request):
|
||||
return JSONResponse({'error': 'Forbidden'}, status_code=403)
|
||||
if not CascadeManager.is_wg_family(req.entry_protocol):
|
||||
return JSONResponse({'error': 'Cascade supports WireGuard / AmneziaWG only'}, status_code=400)
|
||||
if req.enabled and not CascadeManager.is_wg_family(req.exit_protocol):
|
||||
return JSONResponse({'error': 'Cascade supports WireGuard / AmneziaWG only'}, status_code=400)
|
||||
|
||||
try:
|
||||
data = await asyncio.to_thread(load_data)
|
||||
if server_id >= len(data['servers']):
|
||||
return JSONResponse({'error': 'Server not found'}, status_code=404)
|
||||
entry = data['servers'][server_id]
|
||||
settings = normalize_settings({
|
||||
'pin_exit_route': req.pin_exit_route,
|
||||
'remove_eth_masquerade': req.remove_eth_masquerade,
|
||||
'force_forward': req.force_forward,
|
||||
'mss_clamp': req.mss_clamp,
|
||||
'wait_handshake': req.wait_handshake,
|
||||
'handshake_timeout_sec': req.handshake_timeout_sec,
|
||||
'allowed_ips': req.allowed_ips,
|
||||
'keep_exit_dns': req.keep_exit_dns,
|
||||
'vpn_subnet_override': req.vpn_subnet_override,
|
||||
'table_id': req.table_id,
|
||||
'rule_priority': req.rule_priority,
|
||||
'verify_egress': req.verify_egress,
|
||||
})
|
||||
if not req.enabled:
|
||||
def _disable():
|
||||
ssh = get_ssh(entry)
|
||||
ssh.connect()
|
||||
try:
|
||||
return CascadeManager(ssh).disable(
|
||||
req.entry_protocol,
|
||||
settings=dict((entry.get('cascade') or {}).get('settings') or settings),
|
||||
)
|
||||
finally:
|
||||
ssh.disconnect()
|
||||
|
||||
result = await asyncio.to_thread(_disable)
|
||||
if result.get('status') == 'error':
|
||||
return JSONResponse({'error': result.get('message', 'Failed to disable cascade')}, status_code=500)
|
||||
prev = dict(entry.get('cascade') or {})
|
||||
entry['cascade'] = {
|
||||
'enabled': False,
|
||||
'entry_protocol': req.entry_protocol or prev.get('entry_protocol'),
|
||||
'exit_server_id': prev.get('exit_server_id'),
|
||||
'exit_protocol': prev.get('exit_protocol') or req.exit_protocol,
|
||||
'settings': settings,
|
||||
'updated_at': datetime.now().isoformat(timespec='seconds'),
|
||||
}
|
||||
async with DATA_LOCK:
|
||||
await asyncio.to_thread(save_data, data)
|
||||
return {'status': 'success', 'cascade': entry['cascade']}
|
||||
|
||||
if req.exit_server_id is None:
|
||||
return JSONResponse({'error': 'exit_server_id is required'}, status_code=400)
|
||||
if req.exit_server_id < 0 or req.exit_server_id >= len(data['servers']):
|
||||
return JSONResponse({'error': 'Exit server not found'}, status_code=404)
|
||||
if req.exit_server_id == server_id:
|
||||
return JSONResponse({'error': 'Entry and exit servers must be different'}, status_code=400)
|
||||
|
||||
exit_srv = data['servers'][req.exit_server_id]
|
||||
|
||||
def _enable():
|
||||
exit_ssh = get_ssh(exit_srv)
|
||||
exit_ssh.connect()
|
||||
try:
|
||||
exit_mgr = get_protocol_manager(exit_ssh, req.exit_protocol)
|
||||
clients = _manager_call(exit_mgr, 'get_clients', req.exit_protocol) or []
|
||||
cascade_name = f"cascade-from-{(entry.get('name') or entry.get('host') or 'entry')[:40]}"
|
||||
cascade_name = re.sub(r'[^\w.\-]+', '_', cascade_name).strip('._') or 'cascade-entry'
|
||||
existing = None
|
||||
for c in clients:
|
||||
ud = c.get('userData') or {}
|
||||
if ud.get('clientName') == cascade_name or ud.get('cascade_entry_server_id') == server_id:
|
||||
existing = c
|
||||
break
|
||||
|
||||
if existing:
|
||||
client_id = existing.get('clientId')
|
||||
conf = _manager_call(
|
||||
exit_mgr, 'get_client_config', req.exit_protocol,
|
||||
client_id, exit_srv['host'],
|
||||
(exit_srv.get('protocols') or {}).get(req.exit_protocol, {}).get('port', '55424'),
|
||||
)
|
||||
else:
|
||||
add_res = _manager_call(
|
||||
exit_mgr, 'add_client', req.exit_protocol, cascade_name,
|
||||
exit_srv['host'],
|
||||
(exit_srv.get('protocols') or {}).get(req.exit_protocol, {}).get('port', '55424'),
|
||||
)
|
||||
if not add_res.get('client_id'):
|
||||
raise RuntimeError(add_res.get('message') or 'Failed to create cascade peer on exit')
|
||||
client_id = add_res['client_id']
|
||||
conf = add_res.get('config')
|
||||
if not conf:
|
||||
conf = _manager_call(
|
||||
exit_mgr, 'get_client_config', req.exit_protocol,
|
||||
client_id, exit_srv['host'],
|
||||
(exit_srv.get('protocols') or {}).get(req.exit_protocol, {}).get('port', '55424'),
|
||||
)
|
||||
try:
|
||||
table = exit_mgr._get_clients_table(req.exit_protocol) if hasattr(exit_mgr, '_get_clients_table') else []
|
||||
for row in table:
|
||||
if row.get('clientId') == client_id:
|
||||
row.setdefault('userData', {})['cascade_entry_server_id'] = server_id
|
||||
if hasattr(exit_mgr, '_save_clients_table'):
|
||||
exit_mgr._save_clients_table(req.exit_protocol, table)
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
exit_ssh.disconnect()
|
||||
|
||||
entry_ssh = get_ssh(entry)
|
||||
entry_ssh.connect()
|
||||
try:
|
||||
applied = CascadeManager(entry_ssh).apply(
|
||||
req.entry_protocol,
|
||||
conf,
|
||||
exit_srv.get('host') or '',
|
||||
settings=settings,
|
||||
)
|
||||
finally:
|
||||
entry_ssh.disconnect()
|
||||
|
||||
if applied.get('status') != 'success':
|
||||
raise RuntimeError(applied.get('message') or 'Failed to apply cascade on entry')
|
||||
|
||||
if settings.get('wait_handshake') and not applied.get('handshake'):
|
||||
try:
|
||||
entry_ssh2 = get_ssh(entry)
|
||||
entry_ssh2.connect()
|
||||
try:
|
||||
CascadeManager(entry_ssh2).disable(req.entry_protocol, settings=settings)
|
||||
finally:
|
||||
entry_ssh2.disconnect()
|
||||
except Exception:
|
||||
pass
|
||||
raise RuntimeError(
|
||||
applied.get('message')
|
||||
or 'Cascade apply reported success but exit handshake is missing'
|
||||
)
|
||||
|
||||
peer_ip = applied.get('cascade_peer_ip') or ''
|
||||
if not peer_ip and conf:
|
||||
peer_ip = CascadeManager._extract_address_ip(conf)
|
||||
if peer_ip and hasattr(CascadeManager, 'ensure_exit_return_route'):
|
||||
exit_ssh2 = get_ssh(exit_srv)
|
||||
exit_ssh2.connect()
|
||||
try:
|
||||
route_res = CascadeManager(exit_ssh2).ensure_exit_return_route(
|
||||
req.exit_protocol, peer_ip
|
||||
)
|
||||
applied['exit_return_route'] = route_res
|
||||
finally:
|
||||
exit_ssh2.disconnect()
|
||||
|
||||
return {
|
||||
'client_id': client_id,
|
||||
'client_name': cascade_name,
|
||||
'applied': applied,
|
||||
}
|
||||
|
||||
info = await asyncio.to_thread(_enable)
|
||||
applied = info.get('applied') or {}
|
||||
entry['cascade'] = {
|
||||
'enabled': True,
|
||||
'entry_protocol': req.entry_protocol,
|
||||
'exit_server_id': req.exit_server_id,
|
||||
'exit_protocol': req.exit_protocol,
|
||||
'exit_client_id': info['client_id'],
|
||||
'exit_client_name': info['client_name'],
|
||||
'settings': settings,
|
||||
'up': bool(applied.get('up')),
|
||||
'handshake': bool(applied.get('handshake')),
|
||||
'updated_at': datetime.now().isoformat(timespec='seconds'),
|
||||
'last_error': None,
|
||||
'diagnostics': applied.get('diagnostics') or '',
|
||||
}
|
||||
async with DATA_LOCK:
|
||||
await asyncio.to_thread(save_data, data)
|
||||
return {
|
||||
'status': 'success',
|
||||
'cascade': entry['cascade'],
|
||||
'applied': applied,
|
||||
'warning': applied.get('warning'),
|
||||
}
|
||||
except Exception as e:
|
||||
logger.exception("Error setting up cascade")
|
||||
return JSONResponse({'error': str(e)}, status_code=500)
|
||||
|
||||
|
||||
|
||||
@app.post('/api/servers/{server_id}/uninstall', tags=["Protocols"])
|
||||
async def api_uninstall_protocol(request: Request, server_id: int, req: ProtocolRequest):
|
||||
if not _check_admin(request):
|
||||
@@ -3084,6 +3521,8 @@ CONTAINER_NAMES = {
|
||||
'awg_legacy': 'amnezia-awg-legacy',
|
||||
'xray': 'amnezia-xray',
|
||||
'telemt': 'telemt',
|
||||
'hysteria': 'amnezia-hysteria',
|
||||
'naiveproxy': 'amnezia-naiveproxy',
|
||||
'dns': 'amnezia-dns',
|
||||
'wireguard': 'amnezia-wireguard',
|
||||
'socks5': 'amnezia-socks5proxy',
|
||||
@@ -3390,13 +3829,39 @@ async def api_container_toggle(request: Request, server_id: int, req: ProtocolRe
|
||||
ssh.run_sudo_command(f"docker stop {container}")
|
||||
action = 'stopped'
|
||||
else:
|
||||
ssh.run_sudo_command(f"docker start {container}")
|
||||
if protocol_base(req.protocol) == 'hysteria':
|
||||
from managers.hysteria_manager import HysteriaManager
|
||||
mgr = HysteriaManager(ssh, req.protocol)
|
||||
meta = mgr._read_metadata()
|
||||
port = int(meta.get('port') or mgr.DEFAULT_PORT)
|
||||
mgr._write_config_from_clients(port)
|
||||
mgr._start_container(port)
|
||||
else:
|
||||
ssh.run_sudo_command(f"docker start {container}")
|
||||
action = 'started'
|
||||
error = ''
|
||||
recent_logs = ''
|
||||
if protocol_base(req.protocol) == 'hysteria':
|
||||
from managers.hysteria_manager import HysteriaManager
|
||||
mgr = HysteriaManager(ssh, req.protocol)
|
||||
diag = mgr.get_container_diagnostics(req.protocol)
|
||||
error = diag.get('error_summary') or ''
|
||||
recent_logs = diag.get('recent_logs') or ''
|
||||
if action == 'started' and not diag.get('running'):
|
||||
ssh.disconnect()
|
||||
return JSONResponse({
|
||||
'error': error or 'Hysteria failed to start',
|
||||
'action': action,
|
||||
'container': container,
|
||||
'recent_logs': recent_logs,
|
||||
}, status_code=400)
|
||||
ssh.disconnect()
|
||||
return {
|
||||
'status': 'success',
|
||||
'action': action,
|
||||
'container': container,
|
||||
'error': error,
|
||||
'recent_logs': recent_logs,
|
||||
}
|
||||
except Exception as e:
|
||||
logger.exception("Error toggling container")
|
||||
@@ -3418,7 +3883,22 @@ async def api_container_logs(request: Request, server_id: int, req: ContainerLog
|
||||
container = protocol_container_name(req.protocol)
|
||||
ssh = get_ssh(server)
|
||||
ssh.connect()
|
||||
# Generic docker logs for all protocols
|
||||
if protocol_base(req.protocol) == 'hysteria':
|
||||
from managers.hysteria_manager import HysteriaManager
|
||||
mgr = HysteriaManager(ssh, req.protocol)
|
||||
logs = mgr.get_logs(req.protocol, tail=req.tail or 200)
|
||||
diag = mgr.get_container_diagnostics(req.protocol)
|
||||
ssh.disconnect()
|
||||
return {
|
||||
'status': 'success',
|
||||
'protocol': req.protocol,
|
||||
'container': container,
|
||||
'logs': logs,
|
||||
'running': bool(diag.get('running')),
|
||||
'error': diag.get('error_summary') or '',
|
||||
'exit_code': diag.get('exit_code'),
|
||||
'container_status': diag.get('status') or '',
|
||||
}
|
||||
tail = max(20, min(int(req.tail or 200), 2000))
|
||||
out, err, _ = ssh.run_sudo_command(
|
||||
f"docker logs --tail {tail} --timestamps {shlex.quote(container)} 2>&1",
|
||||
@@ -3539,6 +4019,14 @@ async def api_server_config(request: Request, server_id: int, req: ProtocolReque
|
||||
from managers.nginx_manager import NginxManager
|
||||
mgr = NginxManager(ssh, req.protocol)
|
||||
config = mgr._get_server_config(req.protocol)
|
||||
elif protocol_base(req.protocol) == 'hysteria':
|
||||
from managers.hysteria_manager import HysteriaManager
|
||||
mgr = HysteriaManager(ssh, req.protocol)
|
||||
config = mgr.get_server_config(req.protocol)
|
||||
elif protocol_base(req.protocol) == 'naiveproxy':
|
||||
from managers.naiveproxy_manager import NaiveProxyManager
|
||||
mgr = NaiveProxyManager(ssh, req.protocol)
|
||||
config = mgr.get_server_config(req.protocol)
|
||||
else:
|
||||
mgr = AWGManager(ssh)
|
||||
config = mgr._get_server_config(req.protocol)
|
||||
@@ -3583,6 +4071,14 @@ async def api_server_config_save(request: Request, server_id: int, req: ServerCo
|
||||
from managers.nginx_manager import NginxManager
|
||||
mgr = NginxManager(ssh, req.protocol)
|
||||
mgr.save_server_config(req.protocol, req.config)
|
||||
elif protocol_base(req.protocol) == 'hysteria':
|
||||
from managers.hysteria_manager import HysteriaManager
|
||||
mgr = HysteriaManager(ssh, req.protocol)
|
||||
mgr.save_server_config(req.protocol, req.config)
|
||||
elif protocol_base(req.protocol) == 'naiveproxy':
|
||||
from managers.naiveproxy_manager import NaiveProxyManager
|
||||
mgr = NaiveProxyManager(ssh, req.protocol)
|
||||
mgr.save_server_config(req.protocol, req.config)
|
||||
else:
|
||||
mgr = AWGManager(ssh)
|
||||
mgr.save_server_config(req.protocol, req.config)
|
||||
@@ -5253,6 +5749,39 @@ async def api_get_settings(request: Request):
|
||||
return data.get('settings', {})
|
||||
|
||||
|
||||
@app.get('/api/settings/check_updates', tags=["Settings"])
|
||||
async def api_check_updates(request: Request):
|
||||
"""Proxy latest release lookup to avoid browser CORS blocks on git.evilfox.cc."""
|
||||
if not _check_admin(request):
|
||||
return JSONResponse({'error': 'Forbidden'}, status_code=403)
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=15.0, follow_redirects=True) as client:
|
||||
resp = await client.get(
|
||||
RELEASES_API_LATEST,
|
||||
headers={'Accept': 'application/json'},
|
||||
)
|
||||
if resp.status_code >= 400:
|
||||
return JSONResponse(
|
||||
{'error': f'Release API returned HTTP {resp.status_code}'},
|
||||
status_code=502,
|
||||
)
|
||||
data = resp.json() if resp.content else {}
|
||||
latest = (data.get('tag_name') or data.get('name') or '').strip()
|
||||
html_url = (data.get('html_url') or f'{RELEASES_REPO_URL}/releases').strip()
|
||||
current = CURRENT_VERSION
|
||||
update_available = bool(latest) and latest != current
|
||||
return {
|
||||
'current_version': current,
|
||||
'latest_version': latest,
|
||||
'update_available': update_available,
|
||||
'html_url': html_url,
|
||||
'releases_url': f'{RELEASES_REPO_URL}/releases',
|
||||
}
|
||||
except Exception as e:
|
||||
logger.exception('Error checking for updates')
|
||||
return JSONResponse({'error': str(e)}, status_code=502)
|
||||
|
||||
|
||||
@app.get('/api/settings/tunnels/status', tags=["Settings"])
|
||||
async def api_tunnels_status(request: Request):
|
||||
if not _check_admin(request):
|
||||
|
||||
@@ -62,6 +62,14 @@ class BackupManager:
|
||||
remote_dir = inst_path('/opt/amnezia/telemt')
|
||||
paths['host'] = [remote_dir]
|
||||
paths['container'] = [remote_dir]
|
||||
elif base == 'hysteria':
|
||||
remote_dir = inst_path('/opt/amnezia/hysteria')
|
||||
paths['host'] = [remote_dir]
|
||||
paths['container'] = ['/etc/hysteria']
|
||||
elif base == 'naiveproxy':
|
||||
remote_dir = inst_path('/opt/amnezia/naiveproxy')
|
||||
paths['host'] = [remote_dir]
|
||||
paths['container'] = ['/etc/caddy']
|
||||
elif base == 'dns':
|
||||
paths['host'] = ['/opt/amnezia/dns']
|
||||
paths['container'] = ['/opt/amnezia/dns']
|
||||
|
||||
@@ -0,0 +1,733 @@
|
||||
"""Cascade (double-VPN) between two panel-managed WireGuard/AWG servers.
|
||||
|
||||
Traffic path:
|
||||
Clients → Entry server (accessible) → Exit server (blocked / target) → Internet
|
||||
|
||||
Implemented inside the entry Docker container as a second AWG/WG interface
|
||||
(`cascade.conf`) with source-based routing for the VPN client subnet.
|
||||
|
||||
Inspired by ryderams/amneziawg-cascade (AWG2 entry→exit), but executed via the
|
||||
panel SSH session — no remote curl|bash script download.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import re
|
||||
import shlex
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
|
||||
WG_FAMILY = {'awg', 'awg2', 'awg_legacy', 'wireguard'}
|
||||
CASCADE_MARKER = '# amnezia-web-panel-cascade'
|
||||
EXIT_ROUTE_BEGIN = '# BEGIN awg-cascade-vps2'
|
||||
EXIT_ROUTE_END = '# END awg-cascade-vps2'
|
||||
|
||||
DEFAULT_SETTINGS = {
|
||||
'pin_exit_route': True,
|
||||
'remove_eth_masquerade': True,
|
||||
'force_forward': True,
|
||||
'mss_clamp': True,
|
||||
'wait_handshake': True,
|
||||
'handshake_timeout_sec': 25,
|
||||
'allowed_ips': '0.0.0.0/0',
|
||||
'keep_exit_dns': False,
|
||||
'vpn_subnet_override': '',
|
||||
'table_id': 200,
|
||||
'rule_priority': 100,
|
||||
'verify_egress': True,
|
||||
}
|
||||
|
||||
|
||||
def normalize_settings(raw: Optional[dict]) -> dict:
|
||||
settings = dict(DEFAULT_SETTINGS)
|
||||
if isinstance(raw, dict):
|
||||
for key, default in DEFAULT_SETTINGS.items():
|
||||
if key not in raw or raw[key] is None:
|
||||
continue
|
||||
if isinstance(default, bool):
|
||||
settings[key] = bool(raw[key])
|
||||
elif isinstance(default, int):
|
||||
try:
|
||||
settings[key] = int(raw[key])
|
||||
except (TypeError, ValueError):
|
||||
settings[key] = default
|
||||
else:
|
||||
settings[key] = str(raw[key]).strip()
|
||||
settings['handshake_timeout_sec'] = max(5, min(120, int(settings['handshake_timeout_sec'])))
|
||||
settings['table_id'] = max(1, min(252, int(settings['table_id'])))
|
||||
settings['rule_priority'] = max(1, min(32765, int(settings['rule_priority'])))
|
||||
if not settings.get('allowed_ips'):
|
||||
settings['allowed_ips'] = DEFAULT_SETTINGS['allowed_ips']
|
||||
return settings
|
||||
|
||||
|
||||
class CascadeManager:
|
||||
def __init__(self, ssh_manager):
|
||||
self.ssh = ssh_manager
|
||||
|
||||
@staticmethod
|
||||
def proto_base(protocol: str) -> str:
|
||||
return str(protocol or '').split('__', 1)[0]
|
||||
|
||||
@staticmethod
|
||||
def is_wg_family(protocol: str) -> bool:
|
||||
return CascadeManager.proto_base(protocol) in WG_FAMILY
|
||||
|
||||
@staticmethod
|
||||
def _container_name(protocol: str) -> str:
|
||||
base = CascadeManager.proto_base(protocol)
|
||||
match = re.search(r'__(\d+)$', str(protocol or ''))
|
||||
idx = int(match.group(1)) if match else 1
|
||||
names = {
|
||||
'awg': 'amnezia-awg',
|
||||
'awg2': 'amnezia-awg2',
|
||||
'awg_legacy': 'amnezia-awg-legacy',
|
||||
'wireguard': 'amnezia-wireguard',
|
||||
}
|
||||
name = names.get(base)
|
||||
if not name:
|
||||
return ''
|
||||
return name if idx <= 1 else f'{name}-{idx}'
|
||||
|
||||
@staticmethod
|
||||
def _wg_binary(protocol: str) -> str:
|
||||
return 'wg' if CascadeManager.proto_base(protocol) in ('awg_legacy', 'wireguard') else 'awg'
|
||||
|
||||
@staticmethod
|
||||
def _quick_binary(protocol: str) -> str:
|
||||
return 'wg-quick' if CascadeManager.proto_base(protocol) in ('awg_legacy', 'wireguard') else 'awg-quick'
|
||||
|
||||
@staticmethod
|
||||
def _conf_dir(protocol: str) -> str:
|
||||
return '/opt/amnezia/wireguard' if CascadeManager.proto_base(protocol) == 'wireguard' else '/opt/amnezia/awg'
|
||||
|
||||
@classmethod
|
||||
def _cascade_conf(cls, protocol: str) -> str:
|
||||
return f'{cls._conf_dir(protocol)}/cascade.conf'
|
||||
|
||||
@classmethod
|
||||
def _cascade_up(cls, protocol: str) -> str:
|
||||
return f'{cls._conf_dir(protocol)}/cascade-up.sh'
|
||||
|
||||
@staticmethod
|
||||
def _server_conf(protocol: str) -> str:
|
||||
base = CascadeManager.proto_base(protocol)
|
||||
if base == 'wireguard':
|
||||
return '/opt/amnezia/wireguard/wg0.conf'
|
||||
if base == 'awg_legacy':
|
||||
return '/opt/amnezia/awg/wg0.conf'
|
||||
return '/opt/amnezia/awg/awg0.conf'
|
||||
|
||||
@staticmethod
|
||||
def _server_iface(protocol: str) -> str:
|
||||
base = CascadeManager.proto_base(protocol)
|
||||
if base in ('wireguard', 'awg_legacy'):
|
||||
return 'wg0'
|
||||
return 'awg0'
|
||||
|
||||
@staticmethod
|
||||
def _extract_endpoint_host(config_text: str) -> str:
|
||||
for line in (config_text or '').splitlines():
|
||||
if line.strip().lower().startswith('endpoint'):
|
||||
rhs = line.split('=', 1)[-1].strip()
|
||||
return rhs.rsplit(':', 1)[0].strip().strip('[]')
|
||||
return ''
|
||||
|
||||
@staticmethod
|
||||
def _extract_address_cidr(config_text: str) -> str:
|
||||
for line in (config_text or '').splitlines():
|
||||
stripped = line.strip()
|
||||
if stripped.lower().startswith('address'):
|
||||
rhs = stripped.split('=', 1)[-1].strip()
|
||||
return rhs.split(',')[0].strip()
|
||||
return ''
|
||||
|
||||
@staticmethod
|
||||
def _extract_address_ip(config_text: str) -> str:
|
||||
cidr = CascadeManager._extract_address_cidr(config_text)
|
||||
if not cidr:
|
||||
return ''
|
||||
return cidr.split('/', 1)[0].strip()
|
||||
|
||||
@staticmethod
|
||||
def prepare_exit_client_config(
|
||||
raw_config: str,
|
||||
endpoint_host: str,
|
||||
*,
|
||||
keep_dns: bool = False,
|
||||
allowed_ips: str = '0.0.0.0/0',
|
||||
) -> str:
|
||||
"""Adapt a normal client config for use as an entry→exit cascade tunnel."""
|
||||
effective_allowed = (allowed_ips or '').strip() or '0.0.0.0/0'
|
||||
if effective_allowed in ('0.0.0.0/0, ::/0', '::/0, 0.0.0.0/0'):
|
||||
effective_allowed = '0.0.0.0/0'
|
||||
|
||||
lines = []
|
||||
in_interface = False
|
||||
in_peer = False
|
||||
has_table = False
|
||||
has_mtu = False
|
||||
for raw in (raw_config or '').splitlines():
|
||||
stripped = raw.strip()
|
||||
lower = stripped.lower()
|
||||
if stripped.startswith('[') and stripped.endswith(']'):
|
||||
in_interface = stripped.lower() == '[interface]'
|
||||
in_peer = stripped.lower() == '[peer]'
|
||||
lines.append(stripped)
|
||||
continue
|
||||
if in_interface and lower.startswith('dns') and not keep_dns:
|
||||
continue
|
||||
if in_interface and lower.startswith('table'):
|
||||
has_table = True
|
||||
lines.append('Table = off')
|
||||
continue
|
||||
if in_interface and lower.startswith('mtu'):
|
||||
has_mtu = True
|
||||
lines.append(stripped)
|
||||
continue
|
||||
if lower.startswith('endpoint'):
|
||||
port = '51820'
|
||||
if '=' in stripped:
|
||||
rhs = stripped.split('=', 1)[1].strip()
|
||||
if ':' in rhs:
|
||||
port = rhs.rsplit(':', 1)[-1]
|
||||
host = (endpoint_host or '').strip()
|
||||
if host:
|
||||
lines.append(f'Endpoint = {host}:{port}')
|
||||
else:
|
||||
lines.append(stripped)
|
||||
continue
|
||||
if in_peer and lower.startswith('allowedips'):
|
||||
lines.append(f'AllowedIPs = {effective_allowed}')
|
||||
continue
|
||||
lines.append(stripped)
|
||||
|
||||
out = []
|
||||
inserted_iface = False
|
||||
for line in lines:
|
||||
out.append(line)
|
||||
if not inserted_iface and line.strip().lower() == '[interface]':
|
||||
if not has_table:
|
||||
out.append('Table = off')
|
||||
if not has_mtu:
|
||||
out.append('MTU = 1280')
|
||||
inserted_iface = True
|
||||
return '\n'.join(out).strip() + '\n'
|
||||
|
||||
@staticmethod
|
||||
def _subnet_contains_ip(subnet: str, ip: str) -> bool:
|
||||
try:
|
||||
net = ipaddress.ip_network(subnet, strict=False)
|
||||
return ipaddress.ip_address(ip) in net
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
def status(self, entry_protocol: str) -> dict:
|
||||
container = self._container_name(entry_protocol)
|
||||
if not container:
|
||||
return {'enabled': False, 'up': False, 'handshake': False, 'error': 'Unsupported protocol'}
|
||||
conf = self._cascade_conf(entry_protocol)
|
||||
wg_bin = self._wg_binary(entry_protocol)
|
||||
out, _, _ = self.ssh.run_sudo_command(
|
||||
f"docker exec {shlex.quote(container)} bash -lc "
|
||||
f"'echo HAS=$(test -f {shlex.quote(conf)} && echo 1 || echo 0); "
|
||||
f"echo IFACES=$({wg_bin} show interfaces 2>/dev/null); "
|
||||
f"echo HANDSHAKE=$({wg_bin} show cascade latest-handshakes 2>/dev/null | awk \"{{print \\$2}}\" | head -1); "
|
||||
f"echo TRANSFER=$({wg_bin} show cascade transfer 2>/dev/null | head -1); "
|
||||
f"ip rule show 2>/dev/null | head -20; "
|
||||
f"ip route show table 200 2>/dev/null | head -10'"
|
||||
)
|
||||
text = out or ''
|
||||
has_conf = 'HAS=1' in text
|
||||
ifaces_line = ''
|
||||
handshake_ts = 0
|
||||
for line in text.splitlines():
|
||||
if line.startswith('IFACES='):
|
||||
ifaces_line = line.split('=', 1)[1].strip()
|
||||
if line.startswith('HANDSHAKE='):
|
||||
try:
|
||||
handshake_ts = int(line.split('=', 1)[1].strip() or '0')
|
||||
except ValueError:
|
||||
handshake_ts = 0
|
||||
up = 'cascade' in ifaces_line.split()
|
||||
handshake_ok = handshake_ts > 0
|
||||
return {
|
||||
'enabled': has_conf,
|
||||
'up': up,
|
||||
'handshake': handshake_ok,
|
||||
'handshake_ts': handshake_ts,
|
||||
'raw': text.strip()[:3000],
|
||||
}
|
||||
|
||||
def _vpn_server_iface(self, entry_protocol: str) -> str:
|
||||
base = self.proto_base(entry_protocol)
|
||||
if base in ('awg_legacy', 'wireguard'):
|
||||
return 'wg0'
|
||||
return 'awg0'
|
||||
|
||||
def _vpn_server_ip(self, entry_protocol: str, container: str) -> str:
|
||||
"""IPv4 on awg0/wg0 — traffic from this IP is policy-routed through cascade."""
|
||||
iface = self._vpn_server_iface(entry_protocol)
|
||||
out, _, _ = self.ssh.run_sudo_command(
|
||||
f"docker exec {shlex.quote(container)} sh -c "
|
||||
f"{shlex.quote(f'ip -o -4 addr show dev {iface} 2>/dev/null')}",
|
||||
timeout=15,
|
||||
)
|
||||
for line in (out or '').splitlines():
|
||||
m = re.search(r'\binet\s+(\d+\.\d+\.\d+\.\d+)/\d+', line)
|
||||
if m:
|
||||
return m.group(1)
|
||||
return ''
|
||||
|
||||
@staticmethod
|
||||
def _parse_public_ipv4(text: str) -> str:
|
||||
raw = (text or '').strip()
|
||||
if not raw:
|
||||
return ''
|
||||
for line in reversed(raw.splitlines()):
|
||||
line = line.strip()
|
||||
if re.fullmatch(r'\d+\.\d+\.\d+\.\d+', line):
|
||||
return line
|
||||
m = re.search(r'\b(\d{1,3}(?:\.\d{1,3}){3})\b', raw)
|
||||
return m.group(1) if m else ''
|
||||
|
||||
def _verify_egress(self, container: str, entry_protocol: str, subnet: str) -> dict:
|
||||
"""Confirm client-subnet traffic exits via cascade (ryderams-style).
|
||||
|
||||
Bind curl to the VPN server IP on awg0/wg0 (NOT the cascade peer Address).
|
||||
Policy routing only applies to the client subnet — cascade Address must
|
||||
not be used as --interface.
|
||||
"""
|
||||
server_ip = self._vpn_server_ip(entry_protocol, container)
|
||||
iface = self._vpn_server_iface(entry_protocol)
|
||||
if not server_ip:
|
||||
return {
|
||||
'ok': False,
|
||||
'skipped': False,
|
||||
'detail': f'Could not read IPv4 on {iface} for egress verify',
|
||||
'bind': '',
|
||||
}
|
||||
|
||||
route_out, _, _ = self.ssh.run_sudo_command(
|
||||
f"docker exec {shlex.quote(container)} sh -c "
|
||||
f"{shlex.quote(f'ip route get 1.1.1.1 from {server_ip} 2>/dev/null | head -1')}",
|
||||
timeout=15,
|
||||
)
|
||||
route_line = (route_out or '').strip()
|
||||
route_via_cascade = bool(re.search(r'\bdev\s+cascade\b', route_line))
|
||||
|
||||
if not route_via_cascade:
|
||||
return {
|
||||
'ok': False,
|
||||
'skipped': False,
|
||||
'detail': (
|
||||
f'Policy route from {server_ip} does not use cascade iface. '
|
||||
f'Got: {route_line or "empty"}'
|
||||
),
|
||||
'bind': server_ip,
|
||||
'route': route_line,
|
||||
'subnet': subnet,
|
||||
}
|
||||
|
||||
has_curl, _, _ = self.ssh.run_sudo_command(
|
||||
f"docker exec {shlex.quote(container)} sh -c "
|
||||
f"{shlex.quote('command -v curl >/dev/null 2>&1 && echo YES')}",
|
||||
timeout=15,
|
||||
)
|
||||
if 'YES' not in (has_curl or ''):
|
||||
return {
|
||||
'ok': True,
|
||||
'skipped': True,
|
||||
'warning': True,
|
||||
'detail': 'curl not installed in container — egress IP check skipped (policy route OK)',
|
||||
'bind': server_ip,
|
||||
'route': route_line,
|
||||
}
|
||||
|
||||
urls = (
|
||||
'https://api.ipify.org',
|
||||
'https://icanhazip.com',
|
||||
'https://ifconfig.me/ip',
|
||||
'http://api.ipify.org',
|
||||
'http://icanhazip.com',
|
||||
)
|
||||
binds = [server_ip, 'cascade']
|
||||
last_detail = 'empty response'
|
||||
for bind in binds:
|
||||
for url in urls:
|
||||
inner = (
|
||||
f'curl --interface {shlex.quote(bind)} -4 -sS --max-time 12 '
|
||||
f'{shlex.quote(url)} 2>&1 || true'
|
||||
)
|
||||
egress_out, _, _ = self.ssh.run_sudo_command(
|
||||
f"docker exec {shlex.quote(container)} sh -c {shlex.quote(inner)}",
|
||||
timeout=25,
|
||||
)
|
||||
egress_ip = self._parse_public_ipv4(egress_out or '')
|
||||
if egress_ip:
|
||||
return {
|
||||
'ok': True,
|
||||
'skipped': False,
|
||||
'egress_ip': egress_ip,
|
||||
'bind': bind,
|
||||
'url': url,
|
||||
'route': route_line,
|
||||
'detail': f'{egress_ip} via {bind}',
|
||||
}
|
||||
last_detail = ((egress_out or '') or 'empty response').strip()[:300]
|
||||
|
||||
# Handshake + policy route OK; echo services often fail from VPS — keep cascade up.
|
||||
return {
|
||||
'ok': True,
|
||||
'skipped': False,
|
||||
'warning': True,
|
||||
'detail': (
|
||||
f'Policy route OK via cascade, but public-IP curl failed '
|
||||
f'(bind {server_ip}). Last: {last_detail or "empty response"}'
|
||||
),
|
||||
'bind': server_ip,
|
||||
'route': route_line,
|
||||
'subnet': subnet,
|
||||
}
|
||||
|
||||
def _vpn_subnet(self, entry_protocol: str, container: str, override: str = '') -> str:
|
||||
if override and re.match(r'^\d+\.\d+\.\d+\.\d+/\d+$', override.strip()):
|
||||
return override.strip()
|
||||
conf = self._server_conf(entry_protocol)
|
||||
out, _, _ = self.ssh.run_sudo_command(
|
||||
f"docker exec {shlex.quote(container)} bash -lc "
|
||||
f"\"grep -E '^Address' {shlex.quote(conf)} | head -1 | cut -d= -f2 | tr -d ' '\""
|
||||
)
|
||||
addr = (out or '').strip()
|
||||
if not addr:
|
||||
return '10.8.1.0/24'
|
||||
if '/' in addr:
|
||||
ip, cidr = addr.split('/', 1)
|
||||
parts = ip.split('.')
|
||||
if len(parts) == 4 and cidr.isdigit() and int(cidr) >= 24:
|
||||
return f"{parts[0]}.{parts[1]}.{parts[2]}.0/{cidr}"
|
||||
return addr
|
||||
parts = addr.split('.')
|
||||
if len(parts) == 4:
|
||||
return f"{parts[0]}.{parts[1]}.{parts[2]}.0/24"
|
||||
return '10.8.1.0/24'
|
||||
|
||||
def ensure_exit_return_route(self, protocol: str, peer_ip: str) -> dict:
|
||||
"""Add /32 return route for the cascade peer on the exit container (ryderams vps2)."""
|
||||
peer_ip = (peer_ip or '').strip().split('/', 1)[0]
|
||||
if not re.match(r'^\d+\.\d+\.\d+\.\d+$', peer_ip):
|
||||
return {'status': 'error', 'message': 'Invalid cascade peer IP'}
|
||||
container = self._container_name(protocol)
|
||||
if not container:
|
||||
return {'status': 'error', 'message': 'Unsupported exit protocol'}
|
||||
iface = self._server_iface(protocol)
|
||||
route_cmd = f'ip route replace {peer_ip}/32 dev {iface}'
|
||||
script = f"""#!/bin/bash
|
||||
set -e
|
||||
START=/opt/amnezia/start.sh
|
||||
{route_cmd} 2>/dev/null || true
|
||||
[ -f "$START" ] || {{ echo CASCADE_EXIT_ROUTE_OK; exit 0; }}
|
||||
if grep -q '{EXIT_ROUTE_BEGIN}' "$START" 2>/dev/null; then
|
||||
tmp=$(mktemp)
|
||||
awk -v b='{EXIT_ROUTE_BEGIN}' -v e='{EXIT_ROUTE_END}' '
|
||||
$0==b {{skip=1; next}}
|
||||
$0==e {{skip=0; next}}
|
||||
!skip {{print}}
|
||||
' "$START" > "$tmp" && mv "$tmp" "$START"
|
||||
fi
|
||||
printf '\\n%s\\n%s\\n%s\\n' '{EXIT_ROUTE_BEGIN}' '{route_cmd} || true' '{EXIT_ROUTE_END}' >> "$START"
|
||||
echo CASCADE_EXIT_ROUTE_OK
|
||||
"""
|
||||
self.ssh.upload_file(script, '/tmp/_amnz_cascade_exit_route.sh')
|
||||
out, err, code = self.ssh.run_sudo_command(
|
||||
f"docker cp /tmp/_amnz_cascade_exit_route.sh {shlex.quote(container)}:/tmp/_exit_route.sh && "
|
||||
f"docker exec {shlex.quote(container)} bash /tmp/_exit_route.sh && "
|
||||
f"docker exec {shlex.quote(container)} rm -f /tmp/_exit_route.sh",
|
||||
timeout=60,
|
||||
)
|
||||
self.ssh.run_command('rm -f /tmp/_amnz_cascade_exit_route.sh')
|
||||
if code != 0 or 'CASCADE_EXIT_ROUTE_OK' not in (out or ''):
|
||||
return {
|
||||
'status': 'error',
|
||||
'message': ((err or out) or 'Failed to set exit return route').strip()[:400],
|
||||
}
|
||||
return {'status': 'success', 'peer_ip': peer_ip, 'iface': iface}
|
||||
|
||||
def apply(
|
||||
self,
|
||||
entry_protocol: str,
|
||||
exit_client_config: str,
|
||||
exit_host: str,
|
||||
settings: Optional[dict] = None,
|
||||
) -> dict:
|
||||
opts = normalize_settings(settings)
|
||||
container = self._container_name(entry_protocol)
|
||||
if not container:
|
||||
return {'status': 'error', 'message': 'Unsupported entry protocol'}
|
||||
|
||||
exists, _, code = self.ssh.run_sudo_command(
|
||||
f"docker inspect -f '{{{{.State.Running}}}}' {shlex.quote(container)} 2>/dev/null"
|
||||
)
|
||||
if code != 0 or exists.strip().lower() != 'true':
|
||||
return {'status': 'error', 'message': f'Entry container {container} is not running'}
|
||||
|
||||
cascade_conf_path = self._cascade_conf(entry_protocol)
|
||||
cascade_up_path = self._cascade_up(entry_protocol)
|
||||
cascade_conf = self.prepare_exit_client_config(
|
||||
exit_client_config,
|
||||
exit_host,
|
||||
keep_dns=bool(opts['keep_exit_dns']),
|
||||
allowed_ips=str(opts['allowed_ips']),
|
||||
)
|
||||
endpoint_host = self._extract_endpoint_host(cascade_conf) or exit_host
|
||||
cascade_addr_cidr = self._extract_address_cidr(cascade_conf)
|
||||
cascade_peer_ip = self._extract_address_ip(cascade_conf)
|
||||
subnet = self._vpn_subnet(entry_protocol, container, opts.get('vpn_subnet_override') or '')
|
||||
|
||||
if cascade_peer_ip and self._subnet_contains_ip(subnet, cascade_peer_ip):
|
||||
return {
|
||||
'status': 'error',
|
||||
'message': (
|
||||
f'Cascade tunnel Address {cascade_addr_cidr or cascade_peer_ip} is inside '
|
||||
f'entry client subnet {subnet}. Use a different VPN subnet on the exit server '
|
||||
f'(e.g. 10.99.0.0/24) as in ryderams/amneziawg-cascade.'
|
||||
),
|
||||
}
|
||||
|
||||
wg_bin = self._wg_binary(entry_protocol)
|
||||
quick_bin = self._quick_binary(entry_protocol)
|
||||
conf_dir = self._conf_dir(entry_protocol)
|
||||
table_id = int(opts['table_id'])
|
||||
prio = int(opts['rule_priority'])
|
||||
hs_timeout = int(opts['handshake_timeout_sec'])
|
||||
|
||||
pin_block = ''
|
||||
if opts['pin_exit_route']:
|
||||
pin_block = f"""
|
||||
EXIT_IP="$EXIT_HOST"
|
||||
if ! printf '%s' "$EXIT_IP" | grep -Eq '^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$'; then
|
||||
EXIT_IP=$(getent ahostsv4 "$EXIT_HOST" 2>/dev/null | awk '{{print $1; exit}}')
|
||||
if [ -z "$EXIT_IP" ]; then
|
||||
EXIT_IP=$(python3 - <<'PY' 2>/dev/null || true
|
||||
import socket
|
||||
print(socket.gethostbyname("{endpoint_host}"))
|
||||
PY
|
||||
)
|
||||
fi
|
||||
fi
|
||||
GW=$(ip route | awk '/default/ {{print $3; exit}}')
|
||||
DEV=$(ip route | awk '/default/ {{print $5; exit}}')
|
||||
if [ -n "$EXIT_IP" ] && [ -n "$GW" ] && [ -n "$DEV" ]; then
|
||||
ip route replace "$EXIT_IP/32" via "$GW" dev "$DEV" 2>/dev/null || true
|
||||
fi
|
||||
"""
|
||||
|
||||
remove_masq = ''
|
||||
if opts['remove_eth_masquerade']:
|
||||
remove_masq = f"""
|
||||
for ETH in eth0 eth1 eth2 ens3 ens5 enp0s3 enp1s0; do
|
||||
while iptables -t nat -D POSTROUTING -s "$SUBNET" -o "$ETH" -j MASQUERADE 2>/dev/null; do :; done
|
||||
done
|
||||
"""
|
||||
|
||||
forward_block = ''
|
||||
if opts['force_forward']:
|
||||
forward_block = f"""
|
||||
sysctl -w net.ipv4.ip_forward=1 >/dev/null 2>&1 || true
|
||||
for SRC_IF in awg0 wg0; do
|
||||
iptables -C FORWARD -i "$SRC_IF" -o "$IFACE" -j ACCEPT 2>/dev/null \\
|
||||
|| iptables -I FORWARD 1 -i "$SRC_IF" -o "$IFACE" -j ACCEPT 2>/dev/null || true
|
||||
iptables -C FORWARD -i "$IFACE" -o "$SRC_IF" -j ACCEPT 2>/dev/null \\
|
||||
|| iptables -I FORWARD 1 -i "$IFACE" -o "$SRC_IF" -j ACCEPT 2>/dev/null || true
|
||||
done
|
||||
iptables -C FORWARD -i "$IFACE" -m state --state RELATED,ESTABLISHED -j ACCEPT 2>/dev/null \\
|
||||
|| iptables -I FORWARD 1 -i "$IFACE" -m state --state RELATED,ESTABLISHED -j ACCEPT
|
||||
"""
|
||||
|
||||
mss_block = ''
|
||||
if opts['mss_clamp']:
|
||||
mss_block = """
|
||||
iptables -t mangle -C FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu 2>/dev/null \\
|
||||
|| iptables -t mangle -A FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu
|
||||
"""
|
||||
|
||||
handshake_block = ''
|
||||
if opts['wait_handshake']:
|
||||
handshake_block = f"""
|
||||
OK=0
|
||||
for i in $(seq 1 {hs_timeout}); do
|
||||
HS=$({shlex.quote(wg_bin)} show "$IFACE" latest-handshakes 2>/dev/null | awk '{{print $2}}' | head -1)
|
||||
if [ -n "$HS" ] && [ "$HS" != "0" ]; then OK=1; break; fi
|
||||
sleep 1
|
||||
done
|
||||
if [ "$OK" != "1" ]; then
|
||||
echo "CASCADE_NO_HANDSHAKE" >&2
|
||||
echo "Tunnel interface is up but exit peer did not handshake. Check exit server / UDP port / keys." >&2
|
||||
exit 42
|
||||
fi
|
||||
"""
|
||||
|
||||
up_script = f"""#!/bin/bash
|
||||
{CASCADE_MARKER}
|
||||
set -e
|
||||
CONF={shlex.quote(cascade_conf_path)}
|
||||
QUICK={shlex.quote(quick_bin)}
|
||||
SUBNET={shlex.quote(subnet)}
|
||||
EXIT_HOST={shlex.quote(endpoint_host)}
|
||||
IFACE=cascade
|
||||
TABLE={table_id}
|
||||
PRIO={prio}
|
||||
|
||||
"$QUICK" down "$CONF" 2>/dev/null || true
|
||||
ip link delete "$IFACE" 2>/dev/null || true
|
||||
ip rule del from "$SUBNET" table "$TABLE" 2>/dev/null || true
|
||||
ip route flush table "$TABLE" 2>/dev/null || true
|
||||
|
||||
{pin_block}
|
||||
|
||||
"$QUICK" up "$CONF"
|
||||
|
||||
ip route replace default dev "$IFACE" table "$TABLE" 2>/dev/null || ip route add default dev "$IFACE" table "$TABLE"
|
||||
ip rule del from "$SUBNET" table "$TABLE" 2>/dev/null || true
|
||||
ip rule add from "$SUBNET" table "$TABLE" priority "$PRIO"
|
||||
|
||||
{remove_masq}
|
||||
{forward_block}
|
||||
iptables -t nat -C POSTROUTING -s "$SUBNET" -o "$IFACE" -j MASQUERADE 2>/dev/null \\
|
||||
|| iptables -t nat -A POSTROUTING -s "$SUBNET" -o "$IFACE" -j MASQUERADE
|
||||
{mss_block}
|
||||
{handshake_block}
|
||||
|
||||
echo CASCADE_UP_OK
|
||||
"""
|
||||
|
||||
self.ssh.run_sudo_command(f"docker exec {shlex.quote(container)} mkdir -p {shlex.quote(conf_dir)}")
|
||||
self.ssh.upload_file(cascade_conf, '/tmp/_amnz_cascade.conf')
|
||||
self.ssh.upload_file(up_script, '/tmp/_amnz_cascade_up.sh')
|
||||
self.ssh.run_sudo_command(
|
||||
f"docker cp /tmp/_amnz_cascade.conf {shlex.quote(container)}:{shlex.quote(cascade_conf_path)} && "
|
||||
f"docker cp /tmp/_amnz_cascade_up.sh {shlex.quote(container)}:{shlex.quote(cascade_up_path)} && "
|
||||
f"docker exec {shlex.quote(container)} chmod 644 {shlex.quote(cascade_conf_path)} && "
|
||||
f"docker exec {shlex.quote(container)} chmod +x {shlex.quote(cascade_up_path)}"
|
||||
)
|
||||
self.ssh.run_command('rm -f /tmp/_amnz_cascade.conf /tmp/_amnz_cascade_up.sh')
|
||||
|
||||
self._ensure_start_hook(container, cascade_up_path)
|
||||
|
||||
out, err, code = self.ssh.run_sudo_command(
|
||||
f"docker exec {shlex.quote(container)} bash {shlex.quote(cascade_up_path)}",
|
||||
timeout=max(90, hs_timeout + 40),
|
||||
)
|
||||
combined = ((out or '') + '\n' + (err or '')).strip()
|
||||
if code != 0 or 'CASCADE_UP_OK' not in (out or ''):
|
||||
msg = combined
|
||||
if 'CASCADE_NO_HANDSHAKE' in combined:
|
||||
msg = (
|
||||
'Туннель к серверу выхода поднят, но handshake не прошёл. '
|
||||
'Проверьте, что на выходе открыт UDP-порт, протокол совпадает, '
|
||||
'и входной сервер может достучаться до IP выхода.'
|
||||
)
|
||||
return {
|
||||
'status': 'error',
|
||||
'message': (msg or 'Failed to bring cascade interface up').strip()[:900],
|
||||
'log': combined[:2000],
|
||||
}
|
||||
|
||||
st = self.status(entry_protocol)
|
||||
handshake_ok = bool(st.get('handshake'))
|
||||
|
||||
egress_info = {}
|
||||
if opts.get('verify_egress', True) and handshake_ok:
|
||||
egress_info = self._verify_egress(container, entry_protocol, subnet)
|
||||
if not egress_info.get('ok'):
|
||||
try:
|
||||
self.disable(entry_protocol, settings=opts)
|
||||
except Exception:
|
||||
pass
|
||||
bind = egress_info.get('bind') or 'awg0'
|
||||
detail = egress_info.get('detail') or 'empty response'
|
||||
route = egress_info.get('route') or ''
|
||||
return {
|
||||
'status': 'error',
|
||||
'message': (
|
||||
'Cascade handshake OK but egress verify failed '
|
||||
f'(curl --interface {bind} via client subnet {subnet}). '
|
||||
f'Detail: {detail}'
|
||||
+ (f' Route: {route}' if route else '')
|
||||
),
|
||||
'handshake': True,
|
||||
'up': bool(st.get('up')),
|
||||
'egress': egress_info,
|
||||
'log': combined[:1500],
|
||||
}
|
||||
|
||||
return {
|
||||
'status': 'success',
|
||||
'subnet': subnet,
|
||||
'endpoint': endpoint_host,
|
||||
'container': container,
|
||||
'cascade_peer_ip': cascade_peer_ip,
|
||||
'cascade_address': cascade_addr_cidr,
|
||||
'up': bool(st.get('up')),
|
||||
'handshake': handshake_ok,
|
||||
'egress': egress_info or None,
|
||||
'warning': (egress_info or {}).get('detail') if (egress_info or {}).get('warning') else None,
|
||||
'settings': opts,
|
||||
'applied_at': datetime.now().isoformat(timespec='seconds'),
|
||||
'diagnostics': st.get('raw', '')[:1500],
|
||||
}
|
||||
|
||||
def _ensure_start_hook(self, container: str, cascade_up_path: str) -> None:
|
||||
marker = CASCADE_MARKER
|
||||
installer = f"""#!/bin/bash
|
||||
set -e
|
||||
START=/opt/amnezia/start.sh
|
||||
[ -f "$START" ] || exit 0
|
||||
grep -q '{marker}' "$START" 2>/dev/null && exit 0
|
||||
printf '\\n%s\\n' '{marker}' >> "$START"
|
||||
printf '%s\\n' 'if [ -x {cascade_up_path} ]; then bash {cascade_up_path} || true; fi' >> "$START"
|
||||
"""
|
||||
self.ssh.upload_file(installer, '/tmp/_amnz_cascade_hook.sh')
|
||||
self.ssh.run_sudo_command(
|
||||
f"docker cp /tmp/_amnz_cascade_hook.sh {shlex.quote(container)}:/tmp/_hook.sh && "
|
||||
f"docker exec {shlex.quote(container)} bash /tmp/_hook.sh && "
|
||||
f"docker exec {shlex.quote(container)} rm -f /tmp/_hook.sh"
|
||||
)
|
||||
self.ssh.run_command('rm -f /tmp/_amnz_cascade_hook.sh')
|
||||
|
||||
def disable(self, entry_protocol: str, settings: Optional[dict] = None) -> dict:
|
||||
opts = normalize_settings(settings)
|
||||
container = self._container_name(entry_protocol)
|
||||
if not container:
|
||||
return {'status': 'error', 'message': 'Unsupported entry protocol'}
|
||||
conf = self._cascade_conf(entry_protocol)
|
||||
up = self._cascade_up(entry_protocol)
|
||||
quick_bin = self._quick_binary(entry_protocol)
|
||||
table_id = int(opts['table_id'])
|
||||
script = f"""#!/bin/bash
|
||||
set +e
|
||||
QUICK={shlex.quote(quick_bin)}
|
||||
CONF={shlex.quote(conf)}
|
||||
UP={shlex.quote(up)}
|
||||
TABLE={table_id}
|
||||
"$QUICK" down "$CONF" 2>/dev/null
|
||||
ip link delete cascade 2>/dev/null
|
||||
ip rule del table "$TABLE" 2>/dev/null
|
||||
ip rule del table "$TABLE" 2>/dev/null
|
||||
ip route flush table "$TABLE" 2>/dev/null
|
||||
rm -f "$CONF" "$UP"
|
||||
echo CASCADE_DOWN_OK
|
||||
"""
|
||||
self.ssh.upload_file(script, '/tmp/_amnz_cascade_down.sh')
|
||||
out, err, code = self.ssh.run_sudo_command(
|
||||
f"docker cp /tmp/_amnz_cascade_down.sh {shlex.quote(container)}:/tmp/_cascade_down.sh && "
|
||||
f"docker exec {shlex.quote(container)} bash /tmp/_cascade_down.sh && "
|
||||
f"docker exec {shlex.quote(container)} rm -f /tmp/_cascade_down.sh",
|
||||
timeout=60,
|
||||
)
|
||||
self.ssh.run_command('rm -f /tmp/_amnz_cascade_down.sh')
|
||||
if code != 0 and 'CASCADE_DOWN_OK' not in (out or ''):
|
||||
return {'status': 'success', 'message': (err or out or 'Cascade cleared (best effort)').strip()[:400]}
|
||||
return {'status': 'success'}
|
||||
@@ -0,0 +1,744 @@
|
||||
"""
|
||||
Hysteria 2 protocol manager — official tobyxdd/hysteria image (apernet/hysteria).
|
||||
|
||||
Installs Hysteria with Let's Encrypt TLS for an admin-provided domain
|
||||
(certbot standalone on port 80), host networking, BBR, and salamander obfs.
|
||||
Clients use password auth (Happ/INCY-compatible); share links are hy2:// URIs.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import secrets
|
||||
import shlex
|
||||
import string
|
||||
import time
|
||||
from urllib.parse import quote
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _q(value):
|
||||
return shlex.quote(str(value))
|
||||
|
||||
|
||||
def _rand_token(length=16):
|
||||
alphabet = string.ascii_lowercase + string.digits
|
||||
return ''.join(secrets.choice(alphabet) for _ in range(length))
|
||||
|
||||
|
||||
class HysteriaManager:
|
||||
PROTOCOL = 'hysteria'
|
||||
CONTAINER_NAME = 'amnezia-hysteria'
|
||||
IMAGE_NAME = 'tobyxdd/hysteria:v2'
|
||||
CERTBOT_IMAGE = 'certbot/certbot:latest'
|
||||
BASE_DIR = '/opt/amnezia/hysteria'
|
||||
DEFAULT_PORT = 8998
|
||||
|
||||
def __init__(self, ssh, protocol='hysteria'):
|
||||
self.ssh = ssh
|
||||
self.protocol = protocol or self.PROTOCOL
|
||||
self.instance = self._instance_index(self.protocol)
|
||||
self.container_name = self._container_name(self.protocol)
|
||||
self.base_dir = self._base_dir(self.protocol)
|
||||
self.config_path = f'{self.base_dir}/server.yaml'
|
||||
self.clients_path = f'{self.base_dir}/clients.json'
|
||||
self.meta_path = f'{self.base_dir}/metadata.json'
|
||||
self.cert_path = f'{self.base_dir}/cert.crt'
|
||||
self.key_path = f'{self.base_dir}/private.key'
|
||||
self.letsencrypt_dir = f'{self.base_dir}/letsencrypt'
|
||||
|
||||
def _instance_index(self, protocol=None):
|
||||
parts = str(protocol or self.protocol or '').split('__', 1)
|
||||
if len(parts) == 2:
|
||||
try:
|
||||
return max(1, int(parts[1]))
|
||||
except ValueError:
|
||||
return 1
|
||||
return 1
|
||||
|
||||
def _container_name(self, protocol=None):
|
||||
idx = self._instance_index(protocol or self.protocol)
|
||||
return self.CONTAINER_NAME if idx <= 1 else f'{self.CONTAINER_NAME}-{idx}'
|
||||
|
||||
def _base_dir(self, protocol=None):
|
||||
idx = self._instance_index(protocol or self.protocol)
|
||||
return self.BASE_DIR if idx <= 1 else f'{self.BASE_DIR}-{idx}'
|
||||
|
||||
# ===================== STATUS =====================
|
||||
|
||||
def check_docker_installed(self):
|
||||
out, _, code = self.ssh.run_command("docker --version 2>/dev/null")
|
||||
if code != 0:
|
||||
return False
|
||||
out2, _, _ = self.ssh.run_command(
|
||||
"systemctl is-active docker 2>/dev/null || service docker status 2>/dev/null"
|
||||
)
|
||||
return 'active' in out2 or 'running' in out2.lower()
|
||||
|
||||
def check_protocol_installed(self, protocol_type=None):
|
||||
name = self._container_name(protocol_type or self.protocol)
|
||||
out, _, _ = self.ssh.run_sudo_command(
|
||||
f"docker ps -a --filter name=^{name}$ --format '{{{{.Names}}}}'"
|
||||
)
|
||||
return name in out.strip().split('\n')
|
||||
|
||||
def check_container_running(self, protocol_type=None):
|
||||
name = self._container_name(protocol_type or self.protocol)
|
||||
out, _, _ = self.ssh.run_sudo_command(
|
||||
f"docker ps --filter name=^{name}$ --format '{{{{.Status}}}}'"
|
||||
)
|
||||
return 'Up' in out
|
||||
|
||||
def get_logs(self, protocol_type=None, tail=200):
|
||||
"""Return recent docker logs for the Hysteria container."""
|
||||
name = self._container_name(protocol_type or self.protocol)
|
||||
tail = max(20, min(int(tail or 200), 2000))
|
||||
out, err, code = self.ssh.run_sudo_command(
|
||||
f"docker logs --tail {tail} --timestamps {name} 2>&1",
|
||||
timeout=30,
|
||||
)
|
||||
text = (out or err or '').strip()
|
||||
if code != 0 and not text:
|
||||
text = f'(no logs: exit {code})'
|
||||
return text
|
||||
|
||||
def get_container_diagnostics(self, protocol_type=None):
|
||||
"""Inspect why the container is stopped / unhealthy."""
|
||||
name = self._container_name(protocol_type or self.protocol)
|
||||
fmt = (
|
||||
'{{.State.Status}}|{{.State.Running}}|{{.State.ExitCode}}|'
|
||||
'{{.State.OOMKilled}}|{{.State.Error}}|{{.State.FinishedAt}}|'
|
||||
'{{.State.StartedAt}}'
|
||||
)
|
||||
out, _, code = self.ssh.run_sudo_command(
|
||||
f"docker inspect -f '{fmt}' {name} 2>/dev/null"
|
||||
)
|
||||
diag = {
|
||||
'status': 'unknown',
|
||||
'running': False,
|
||||
'exit_code': None,
|
||||
'oom_killed': False,
|
||||
'error': '',
|
||||
'finished_at': '',
|
||||
'started_at': '',
|
||||
'recent_logs': '',
|
||||
'error_summary': '',
|
||||
}
|
||||
if code != 0 or not (out or '').strip():
|
||||
diag['status'] = 'missing'
|
||||
diag['error_summary'] = 'Container not found'
|
||||
return diag
|
||||
|
||||
parts = (out or '').strip().split('|')
|
||||
while len(parts) < 7:
|
||||
parts.append('')
|
||||
status, running, exit_code, oom, err, finished, started = parts[:7]
|
||||
diag['status'] = status or 'unknown'
|
||||
diag['running'] = str(running).lower() == 'true'
|
||||
try:
|
||||
diag['exit_code'] = int(exit_code)
|
||||
except Exception:
|
||||
diag['exit_code'] = None
|
||||
diag['oom_killed'] = str(oom).lower() == 'true'
|
||||
diag['error'] = (err or '').strip()
|
||||
diag['finished_at'] = (finished or '').strip()
|
||||
diag['started_at'] = (started or '').strip()
|
||||
diag['recent_logs'] = self.get_logs(protocol_type, tail=40)
|
||||
|
||||
# Build human-readable summary for the UI badge
|
||||
if diag['running']:
|
||||
diag['error_summary'] = ''
|
||||
elif diag['oom_killed']:
|
||||
diag['error_summary'] = 'OOM killed (out of memory)'
|
||||
elif diag['error']:
|
||||
diag['error_summary'] = diag['error']
|
||||
elif diag['exit_code'] not in (None, 0):
|
||||
# Prefer bind/port conflicts over generic FATAL lines
|
||||
bind_line = ''
|
||||
last = ''
|
||||
for raw in reversed((diag['recent_logs'] or '').splitlines()):
|
||||
line = self._strip_ansi(raw).strip()
|
||||
if not line:
|
||||
continue
|
||||
# strip docker --timestamps prefix
|
||||
m_ts = re.match(r'^\d{4}-\d{2}-\d{2}T\S+\s+(.*)$', line)
|
||||
if m_ts:
|
||||
line = m_ts.group(1).strip()
|
||||
low = line.lower()
|
||||
if 'address already in use' in low and not bind_line:
|
||||
bind_line = line
|
||||
if ('FATAL' in line or 'failed to load' in low) and not last:
|
||||
last = line
|
||||
if not last:
|
||||
last = line
|
||||
pick = bind_line or last
|
||||
if pick and 'address already in use' in pick.lower():
|
||||
m = re.search(r'listen udp :(\d+)', pick, re.I) or re.search(r':(\d+):\s*bind', pick)
|
||||
p = m.group(1) if m else '?'
|
||||
if p == '?':
|
||||
m2 = re.search(r'udp\s*:(\d+)', pick, re.I)
|
||||
p = m2.group(1) if m2 else '?'
|
||||
diag['error_summary'] = (
|
||||
f'UDP port {p} already in use — change port below (try 8998 or 8443)'
|
||||
)
|
||||
diag['port_busy'] = True
|
||||
elif pick:
|
||||
short = re.sub(r'\s+', ' ', pick)[:160]
|
||||
diag['error_summary'] = f"exit {diag['exit_code']}: {short}"
|
||||
else:
|
||||
diag['error_summary'] = f"exited with code {diag['exit_code']}"
|
||||
elif diag['status'] and diag['status'] != 'running':
|
||||
diag['error_summary'] = f"status: {diag['status']}"
|
||||
return diag
|
||||
|
||||
def get_server_status(self, protocol_type=None):
|
||||
protocol_type = protocol_type or self.protocol
|
||||
exists = self.check_protocol_installed(protocol_type)
|
||||
running = self.check_container_running(protocol_type)
|
||||
meta = self._read_metadata() if exists else {}
|
||||
clients = self._read_clients() if exists else []
|
||||
diag = {}
|
||||
|
||||
# Auto-migrate older installs (bridge NAT / userpass / missing BBR+obfs)
|
||||
if exists:
|
||||
try:
|
||||
name = self._container_name(protocol_type)
|
||||
mode, _, _ = self.ssh.run_sudo_command(
|
||||
f"docker inspect -f '{{{{.HostConfig.NetworkMode}}}}' {name} 2>/dev/null"
|
||||
)
|
||||
mode = (mode or '').strip()
|
||||
cfg = self._read_file(self.config_path)
|
||||
needs_cfg = (
|
||||
'type: userpass' in cfg
|
||||
or 'type: salamander' not in cfg
|
||||
or 'type: password' not in cfg
|
||||
)
|
||||
if (mode and mode != 'host') or needs_cfg:
|
||||
port = int(meta.get('port') or self.DEFAULT_PORT)
|
||||
self._write_config_from_clients(port)
|
||||
self._start_container(port)
|
||||
running = self.check_container_running(protocol_type)
|
||||
meta = self._read_metadata()
|
||||
except Exception as e:
|
||||
logger.warning('Hysteria migrate failed: %s', e)
|
||||
diag = {'error_summary': f'migrate failed: {e}'}
|
||||
|
||||
if exists:
|
||||
try:
|
||||
diag = self.get_container_diagnostics(protocol_type)
|
||||
running = bool(diag.get('running'))
|
||||
except Exception as e:
|
||||
logger.warning('Hysteria diagnostics failed: %s', e)
|
||||
diag = {'error_summary': str(e)}
|
||||
|
||||
return {
|
||||
'container_exists': exists,
|
||||
'container_running': running,
|
||||
'port': int(meta.get('port') or self.DEFAULT_PORT),
|
||||
'domain': meta.get('domain'),
|
||||
'email': meta.get('email'),
|
||||
'clients_count': len(clients),
|
||||
'protocol': protocol_type,
|
||||
'base_protocol': self.PROTOCOL,
|
||||
'instance': self._instance_index(protocol_type),
|
||||
'container_name': self._container_name(protocol_type),
|
||||
'error': diag.get('error_summary') or '',
|
||||
'exit_code': diag.get('exit_code'),
|
||||
'container_status': diag.get('status') or '',
|
||||
'recent_logs': diag.get('recent_logs') or '',
|
||||
'port_busy': bool(diag.get('port_busy')),
|
||||
}
|
||||
|
||||
# ===================== HELPERS =====================
|
||||
|
||||
def _validate_domain(self, domain):
|
||||
domain = (domain or '').strip().lower()
|
||||
if not domain or len(domain) > 253:
|
||||
raise ValueError('Domain is required for Hysteria SSL')
|
||||
if not re.match(r'^(?!-)[a-z0-9.-]+(?<!-)$', domain) or '.' not in domain:
|
||||
raise ValueError('Invalid domain name')
|
||||
return domain
|
||||
|
||||
def _validate_email(self, email):
|
||||
email = (email or '').strip()
|
||||
if not email or '@' not in email:
|
||||
raise ValueError("Valid Let's Encrypt email is required")
|
||||
return email
|
||||
|
||||
def _read_file(self, path):
|
||||
out, _, code = self.ssh.run_sudo_command(f"cat {_q(path)} 2>/dev/null")
|
||||
return out if code == 0 else ''
|
||||
|
||||
def _write_file(self, path, content):
|
||||
parent = path.rsplit('/', 1)[0]
|
||||
self.ssh.run_sudo_command(f"mkdir -p {_q(parent)}")
|
||||
self.ssh.upload_file_sudo(content, path)
|
||||
|
||||
def _read_metadata(self):
|
||||
raw = self._read_file(self.meta_path)
|
||||
if not raw.strip():
|
||||
return {}
|
||||
try:
|
||||
return json.loads(raw)
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
def _write_metadata(self, meta):
|
||||
self._write_file(self.meta_path, json.dumps(meta, indent=2, ensure_ascii=False))
|
||||
|
||||
def _read_clients(self):
|
||||
raw = self._read_file(self.clients_path)
|
||||
if not raw.strip():
|
||||
return []
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
return data if isinstance(data, list) else []
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
def _write_clients(self, clients):
|
||||
self._write_file(self.clients_path, json.dumps(clients, indent=2, ensure_ascii=False))
|
||||
|
||||
def _ensure_secrets(self, meta):
|
||||
"""Password auth (Happ/INCY-friendly) + salamander obfs secrets."""
|
||||
changed = False
|
||||
if not meta.get('password'):
|
||||
meta['password'] = _rand_token(24)
|
||||
changed = True
|
||||
if not meta.get('obfs_password'):
|
||||
meta['obfs_password'] = _rand_token(16)
|
||||
changed = True
|
||||
if changed:
|
||||
self._write_metadata(meta)
|
||||
return meta
|
||||
|
||||
def _build_server_yaml(self, port, clients, meta=None):
|
||||
meta = self._ensure_secrets(meta if meta is not None else self._read_metadata())
|
||||
password = meta['password']
|
||||
obfs_password = meta['obfs_password']
|
||||
# password auth — Happ / sing-box / INCY expect a single auth string, not userpass
|
||||
lines = [
|
||||
f'listen: :{int(port)}',
|
||||
'',
|
||||
'tls:',
|
||||
' cert: /etc/hysteria/cert.crt',
|
||||
' key: /etc/hysteria/private.key',
|
||||
'',
|
||||
'auth:',
|
||||
' type: password',
|
||||
f' password: "{password}"',
|
||||
'',
|
||||
'obfs:',
|
||||
' type: salamander',
|
||||
' salamander:',
|
||||
f' password: "{obfs_password}"',
|
||||
'',
|
||||
'quic:',
|
||||
' initStreamReceiveWindow: 8388608',
|
||||
' maxStreamReceiveWindow: 8388608',
|
||||
' initConnReceiveWindow: 20971520',
|
||||
' maxConnReceiveWindow: 20971520',
|
||||
' maxIdleTimeout: 60s',
|
||||
' maxIncomingStreams: 1024',
|
||||
' disablePathMTUDiscovery: true',
|
||||
'',
|
||||
'ignoreClientBandwidth: true',
|
||||
'',
|
||||
'bandwidth:',
|
||||
' up: 1 gbps',
|
||||
' down: 1 gbps',
|
||||
'',
|
||||
'masquerade:',
|
||||
' type: proxy',
|
||||
' proxy:',
|
||||
' url: https://www.bing.com',
|
||||
' rewriteHost: true',
|
||||
'',
|
||||
'outbounds:',
|
||||
' - name: direct',
|
||||
' type: direct',
|
||||
'',
|
||||
]
|
||||
return '\n'.join(lines)
|
||||
|
||||
def _write_config_from_clients(self, port=None):
|
||||
meta = self._ensure_secrets(self._read_metadata())
|
||||
port = int(port or meta.get('port') or self.DEFAULT_PORT)
|
||||
# clients list is panel-side only (shared password); still rewrite yaml for port/obfs/secrets
|
||||
self._write_file(self.config_path, self._build_server_yaml(port, self._read_clients(), meta))
|
||||
return port
|
||||
|
||||
def _tune_host_network(self):
|
||||
"""UDP buffers + BBR — reduces quic-go EOF and improves throughput."""
|
||||
script = r"""
|
||||
set +e
|
||||
mkdir -p /etc/sysctl.d
|
||||
printf '%s\n' \
|
||||
'net.core.rmem_max=16777216' \
|
||||
'net.core.wmem_max=16777216' \
|
||||
'net.core.rmem_default=16777216' \
|
||||
'net.core.wmem_default=16777216' \
|
||||
'net.core.default_qdisc=fq' \
|
||||
'net.ipv4.tcp_congestion_control=bbr' \
|
||||
'net.ipv4.ip_forward=1' \
|
||||
> /etc/sysctl.d/99-amnezia-hysteria.conf
|
||||
modprobe tcp_bbr >/dev/null 2>&1 || true
|
||||
sysctl -p /etc/sysctl.d/99-amnezia-hysteria.conf >/dev/null 2>&1 || true
|
||||
sysctl -w net.core.rmem_max=16777216 >/dev/null 2>&1 || true
|
||||
sysctl -w net.core.wmem_max=16777216 >/dev/null 2>&1 || true
|
||||
sysctl -w net.core.rmem_default=16777216 >/dev/null 2>&1 || true
|
||||
sysctl -w net.core.wmem_default=16777216 >/dev/null 2>&1 || true
|
||||
sysctl -w net.core.default_qdisc=fq >/dev/null 2>&1 || true
|
||||
sysctl -w net.ipv4.tcp_congestion_control=bbr >/dev/null 2>&1 || true
|
||||
sysctl -w net.ipv4.ip_forward=1 >/dev/null 2>&1 || true
|
||||
"""
|
||||
self.ssh.run_sudo_command(f"sh -c {_q(script)}", timeout=30)
|
||||
|
||||
def _strip_ansi(self, text):
|
||||
return re.sub(r'\x1b\[[0-9;]*m', '', text or '')
|
||||
|
||||
def _udp_port_busy(self, port):
|
||||
"""Return (busy: bool, detail: str) for host UDP port (after our container is removed)."""
|
||||
port = int(port)
|
||||
out, _, _ = self.ssh.run_sudo_command(
|
||||
f"ss -ulnp 'sport = :{port}' 2>/dev/null || "
|
||||
f"ss -uln | grep -E ':{port}([[:space:]]|$)' || true"
|
||||
)
|
||||
detail = (out or '').strip()
|
||||
return bool(detail), detail[:240]
|
||||
|
||||
def _open_udp_port(self, port):
|
||||
port = int(port)
|
||||
script = f"""
|
||||
set +e
|
||||
if command -v ufw >/dev/null 2>&1; then
|
||||
ufw allow {port}/udp >/dev/null 2>&1 || true
|
||||
fi
|
||||
if command -v firewall-cmd >/dev/null 2>&1; then
|
||||
firewall-cmd --permanent --add-port={port}/udp >/dev/null 2>&1 || true
|
||||
firewall-cmd --reload >/dev/null 2>&1 || true
|
||||
fi
|
||||
iptables -C INPUT -p udp --dport {port} -j ACCEPT 2>/dev/null || iptables -I INPUT -p udp --dport {port} -j ACCEPT 2>/dev/null || true
|
||||
"""
|
||||
self.ssh.run_sudo_command(f"sh -c {_q(script)}", timeout=30)
|
||||
|
||||
def _start_container(self, port):
|
||||
"""Run with --network host so QUIC/UDP is not broken by Docker NAT (EOF)."""
|
||||
name = self.container_name
|
||||
port = int(port)
|
||||
if port == 80:
|
||||
raise RuntimeError('Port 80 is reserved for Let\'s Encrypt validation')
|
||||
self._tune_host_network()
|
||||
self._open_udp_port(port)
|
||||
self.ssh.run_sudo_command(
|
||||
f"chmod 644 {_q(self.cert_path)} {_q(self.key_path)} 2>/dev/null || true"
|
||||
)
|
||||
self.ssh.run_sudo_command(f"docker rm -fv {name} 2>/dev/null || true")
|
||||
busy, detail = self._udp_port_busy(port)
|
||||
if busy:
|
||||
raise RuntimeError(
|
||||
f'UDP port {port} is already in use — choose another port in Hysteria settings. '
|
||||
f'({self._strip_ansi(detail)})'
|
||||
)
|
||||
run_cmd = (
|
||||
f"docker run -d --restart always "
|
||||
f"--name {name} "
|
||||
f"--network host "
|
||||
f"--cap-add=NET_ADMIN "
|
||||
f"-v {_q(self.base_dir)}:/etc/hysteria "
|
||||
f"{self.IMAGE_NAME} "
|
||||
f"-c /etc/hysteria/server.yaml server"
|
||||
)
|
||||
_, err, code = self.ssh.run_sudo_command(run_cmd, timeout=60)
|
||||
if code != 0:
|
||||
raise RuntimeError(f'Failed to start Hysteria: {err}')
|
||||
# Confirm it stayed up (catch immediate bind failures)
|
||||
time.sleep(1.2)
|
||||
if not self.check_container_running(self.protocol):
|
||||
diag = self.get_container_diagnostics(self.protocol)
|
||||
raise RuntimeError(
|
||||
diag.get('error_summary')
|
||||
or 'Hysteria container exited immediately — check logs / port'
|
||||
)
|
||||
return True
|
||||
|
||||
def get_settings(self):
|
||||
meta = self._ensure_secrets(self._read_metadata())
|
||||
port = int(meta.get('port') or self.DEFAULT_PORT)
|
||||
return {
|
||||
'port': port,
|
||||
'suggested_port': 8998 if port in (443, 80) else port,
|
||||
'domain': meta.get('domain') or '',
|
||||
'email': meta.get('email') or '',
|
||||
'protocol': self.protocol,
|
||||
}
|
||||
|
||||
def update_settings(self, port=None, domain=None, email=None, renew_ssl=False):
|
||||
"""Change listen UDP port and/or re-issue Let's Encrypt for domain."""
|
||||
meta = self._ensure_secrets(self._read_metadata())
|
||||
if port is None:
|
||||
port = meta.get('port') or self.DEFAULT_PORT
|
||||
port = int(port)
|
||||
if port < 1 or port > 65535:
|
||||
return {'status': 'error', 'message': 'Invalid port'}
|
||||
if port == 80:
|
||||
return {'status': 'error', 'message': 'Port 80 is reserved for Let\'s Encrypt validation'}
|
||||
|
||||
old_domain = (meta.get('domain') or '').strip().lower()
|
||||
domain_changed = False
|
||||
try:
|
||||
if domain is not None and str(domain).strip():
|
||||
new_domain = self._validate_domain(domain)
|
||||
domain_changed = new_domain != old_domain
|
||||
meta['domain'] = new_domain
|
||||
if email is not None and str(email).strip():
|
||||
meta['email'] = self._validate_email(email)
|
||||
except ValueError as e:
|
||||
return {'status': 'error', 'message': str(e)}
|
||||
|
||||
if renew_ssl or domain_changed:
|
||||
# Domain change or explicit renew → re-issue certificate (needs free TCP 80)
|
||||
try:
|
||||
d = meta.get('domain') or ''
|
||||
e = meta.get('email') or ''
|
||||
if not d or not e:
|
||||
return {
|
||||
'status': 'error',
|
||||
'message': 'Domain and email are required to issue SSL',
|
||||
}
|
||||
self._issue_certificate(d, e)
|
||||
except Exception as exc:
|
||||
return {'status': 'error', 'message': str(exc)}
|
||||
|
||||
meta['port'] = port
|
||||
self._write_metadata(meta)
|
||||
self._write_config_from_clients(port)
|
||||
try:
|
||||
self._start_container(port)
|
||||
except Exception as e:
|
||||
return {
|
||||
'status': 'error',
|
||||
'message': str(e),
|
||||
'port': str(port),
|
||||
'domain': meta.get('domain'),
|
||||
'email': meta.get('email'),
|
||||
}
|
||||
msg = 'Hysteria settings updated'
|
||||
if renew_ssl or domain_changed:
|
||||
msg = 'SSL certificate issued and Hysteria settings updated'
|
||||
return {
|
||||
'status': 'success',
|
||||
'port': str(port),
|
||||
'domain': meta.get('domain'),
|
||||
'email': meta.get('email'),
|
||||
'message': msg,
|
||||
}
|
||||
|
||||
def _reload_container(self):
|
||||
meta = self._read_metadata()
|
||||
port = int(meta.get('port') or self.DEFAULT_PORT)
|
||||
try:
|
||||
self._start_container(port)
|
||||
except Exception as e:
|
||||
logger.warning('Hysteria container reload failed: %s', e)
|
||||
|
||||
def _issue_certificate(self, domain, email):
|
||||
"""Issue Let's Encrypt cert via certbot standalone (needs free TCP 80)."""
|
||||
self.ssh.run_sudo_command(f"mkdir -p {_q(self.letsencrypt_dir)}")
|
||||
self.ssh.run_sudo_command(f"docker pull {self.CERTBOT_IMAGE}", timeout=180)
|
||||
|
||||
# Stop anything briefly occupying 80 if it's our leftover certbot
|
||||
self.ssh.run_sudo_command(
|
||||
"docker rm -fv amnezia-hysteria-certbot 2>/dev/null || true"
|
||||
)
|
||||
|
||||
cmd = (
|
||||
f"docker run --rm --name amnezia-hysteria-certbot "
|
||||
f"-p 80:80 "
|
||||
f"-v {_q(self.letsencrypt_dir)}:/etc/letsencrypt "
|
||||
f"{self.CERTBOT_IMAGE} certonly --standalone "
|
||||
f"--non-interactive --agree-tos --no-eff-email "
|
||||
f"--email {_q(email)} -d {_q(domain)}"
|
||||
)
|
||||
out, err, code = self.ssh.run_sudo_command(cmd, timeout=300)
|
||||
if code != 0:
|
||||
raise RuntimeError(
|
||||
f"Let's Encrypt failed for {domain}. "
|
||||
f"Point A-record to this server and free TCP port 80. {err or out}"
|
||||
)
|
||||
|
||||
# Copy live certs into paths expected by the server config
|
||||
copy_script = f"""
|
||||
set -e
|
||||
LIVE={_q(self.letsencrypt_dir)}/live/{_q(domain)}
|
||||
test -s "$LIVE/fullchain.pem"
|
||||
test -s "$LIVE/privkey.pem"
|
||||
cp -f "$LIVE/fullchain.pem" {_q(self.cert_path)}
|
||||
cp -f "$LIVE/privkey.pem" {_q(self.key_path)}
|
||||
chmod 644 {_q(self.cert_path)} {_q(self.key_path)}
|
||||
"""
|
||||
out, err, code = self.ssh.run_sudo_command(f"sh -c {_q(copy_script)}", timeout=30)
|
||||
if code != 0:
|
||||
raise RuntimeError(f'Failed to install certificate files: {err or out}')
|
||||
|
||||
def _build_share_uri(self, host, port, domain, name, meta=None):
|
||||
"""Happ/INCY-compatible hy2 link: password auth + salamander + IP host + SNI."""
|
||||
meta = self._ensure_secrets(meta if meta is not None else self._read_metadata())
|
||||
password = meta['password']
|
||||
obfs_password = meta['obfs_password']
|
||||
sni = domain or host
|
||||
# Prefer raw IP in URI — domain may be CDN/DNS filtered for UDP while ICMP still works
|
||||
conn_host = host or domain
|
||||
fragment = quote(name or 'hysteria', safe='')
|
||||
return (
|
||||
f"hy2://{quote(password, safe='')}@{conn_host}:{int(port)}/"
|
||||
f"?sni={quote(sni, safe='')}"
|
||||
f"&obfs=salamander"
|
||||
f"&obfs-password={quote(obfs_password, safe='')}"
|
||||
f"&insecure=0#{fragment}"
|
||||
)
|
||||
|
||||
# ===================== INSTALL / REMOVE =====================
|
||||
|
||||
def install_protocol(self, protocol_type=None, port=None, domain=None, email=None):
|
||||
protocol_type = protocol_type or self.protocol
|
||||
if not self.check_docker_installed():
|
||||
return {'status': 'error', 'message': 'Docker not installed'}
|
||||
|
||||
domain = self._validate_domain(domain)
|
||||
email = self._validate_email(email)
|
||||
port = int(port or self.DEFAULT_PORT)
|
||||
if port == 80:
|
||||
return {'status': 'error', 'message': 'Port 80 is reserved for Let\'s Encrypt validation'}
|
||||
|
||||
log = []
|
||||
self.ssh.run_sudo_command(f"docker pull {self.IMAGE_NAME}", timeout=180)
|
||||
log.append(f'Pulled {self.IMAGE_NAME}')
|
||||
|
||||
if self.check_protocol_installed(protocol_type):
|
||||
name = self._container_name(protocol_type)
|
||||
self.ssh.run_sudo_command(f"docker rm -fv {name} 2>/dev/null || true")
|
||||
log.append('Removed previous container')
|
||||
|
||||
self.ssh.run_sudo_command(f"mkdir -p {_q(self.base_dir)}")
|
||||
self._write_clients([])
|
||||
meta = {
|
||||
'domain': domain,
|
||||
'email': email,
|
||||
'port': port,
|
||||
'password': _rand_token(24),
|
||||
'obfs_password': _rand_token(16),
|
||||
}
|
||||
self._write_metadata(meta)
|
||||
self._write_config_from_clients(port)
|
||||
log.append('Prepared config directory (password auth + salamander + BBR)')
|
||||
|
||||
try:
|
||||
self._issue_certificate(domain, email)
|
||||
log.append(f"Issued Let's Encrypt certificate for {domain}")
|
||||
except Exception as e:
|
||||
return {'status': 'error', 'message': str(e), 'log': log}
|
||||
|
||||
try:
|
||||
self._start_container(port)
|
||||
except Exception as e:
|
||||
return {'status': 'error', 'message': str(e), 'log': log}
|
||||
|
||||
log.append(f'Started {self.container_name} on UDP {port} (host network, BBR)')
|
||||
return {
|
||||
'status': 'success',
|
||||
'message': 'Hysteria installed',
|
||||
'log': log,
|
||||
'port': str(port),
|
||||
'domain': domain,
|
||||
'email': email,
|
||||
}
|
||||
|
||||
def remove_container(self, protocol_type=None):
|
||||
protocol_type = protocol_type or self.protocol
|
||||
name = self._container_name(protocol_type)
|
||||
base = self._base_dir(protocol_type)
|
||||
self.ssh.run_sudo_command(f"docker rm -fv {name} 2>/dev/null || true")
|
||||
self.ssh.run_sudo_command(f"rm -rf {_q(base)}")
|
||||
return True
|
||||
|
||||
def get_server_config(self, protocol_type=None):
|
||||
return self._read_file(self.config_path)
|
||||
|
||||
def save_server_config(self, protocol_type=None, config_text=''):
|
||||
self._write_file(self.config_path, config_text or '')
|
||||
self._reload_container()
|
||||
return True
|
||||
|
||||
# ===================== CLIENTS =====================
|
||||
|
||||
def get_clients(self, protocol_type=None):
|
||||
clients = self._read_clients()
|
||||
result = []
|
||||
for c in clients:
|
||||
cname = c.get('name') or c.get('id')
|
||||
result.append({
|
||||
'clientId': c.get('id'),
|
||||
'client_id': c.get('id'),
|
||||
'id': c.get('id'),
|
||||
'name': cname,
|
||||
'email': cname,
|
||||
'enabled': c.get('enabled', True),
|
||||
'userData': {'clientName': cname, 'enabled': c.get('enabled', True)},
|
||||
})
|
||||
return result
|
||||
|
||||
def add_client(self, protocol_type, name, host, port=None):
|
||||
meta = self._ensure_secrets(self._read_metadata())
|
||||
domain = meta.get('domain') or host
|
||||
port = int(port or meta.get('port') or self.DEFAULT_PORT)
|
||||
client_id = secrets.token_hex(8)
|
||||
clients = self._read_clients()
|
||||
clients.append({
|
||||
'id': client_id,
|
||||
'name': name or f'client-{client_id[:6]}',
|
||||
'enabled': True,
|
||||
})
|
||||
self._write_clients(clients)
|
||||
# Shared password auth — refresh yaml only if secrets/port changed
|
||||
self._write_config_from_clients(port)
|
||||
self._reload_container()
|
||||
config = self._build_share_uri(host, port, domain, name or client_id, meta)
|
||||
return {'client_id': client_id, 'config': config}
|
||||
|
||||
def get_client_config(self, protocol_type, client_id, host, port=None):
|
||||
meta = self._ensure_secrets(self._read_metadata())
|
||||
domain = meta.get('domain') or host
|
||||
port = int(port or meta.get('port') or self.DEFAULT_PORT)
|
||||
clients = self._read_clients()
|
||||
client = next((c for c in clients if c.get('id') == client_id), None)
|
||||
if not client:
|
||||
raise RuntimeError('Client not found')
|
||||
if client.get('enabled', True) is False:
|
||||
raise RuntimeError('Client is disabled')
|
||||
return self._build_share_uri(
|
||||
host, port, domain,
|
||||
client.get('name') or client_id,
|
||||
meta,
|
||||
)
|
||||
|
||||
def remove_client(self, protocol_type, client_id):
|
||||
clients = [c for c in self._read_clients() if c.get('id') != client_id]
|
||||
self._write_clients(clients)
|
||||
return True
|
||||
|
||||
def toggle_client(self, protocol_type, client_id, enable=True):
|
||||
clients = self._read_clients()
|
||||
found = False
|
||||
for c in clients:
|
||||
if c.get('id') == client_id:
|
||||
c['enabled'] = bool(enable)
|
||||
found = True
|
||||
break
|
||||
if not found:
|
||||
raise RuntimeError('Client not found')
|
||||
self._write_clients(clients)
|
||||
return True
|
||||
@@ -0,0 +1,604 @@
|
||||
"""
|
||||
NaiveProxy manager — Caddy + klzgrad/forwardproxy (naive fork).
|
||||
|
||||
Server side is the naïve Caddy forward_proxy from:
|
||||
https://github.com/klzgrad/naiveproxy
|
||||
https://github.com/klzgrad/forwardproxy
|
||||
|
||||
Uses the official prebuilt Caddy binary on amd64, or builds via xcaddy on other
|
||||
arches. Clients authenticate with HTTP basic auth; share links are
|
||||
naive+https://user:pass@domain URIs (NekoRay / sing-box compatible).
|
||||
Requires free TCP 80 (ACME) and 443 (HTTPS / HTTP2 proxy).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import secrets
|
||||
import shlex
|
||||
import string
|
||||
import time
|
||||
from urllib.parse import quote
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _q(value):
|
||||
return shlex.quote(str(value))
|
||||
|
||||
|
||||
def _rand_token(length=16):
|
||||
alphabet = string.ascii_lowercase + string.digits
|
||||
return ''.join(secrets.choice(alphabet) for _ in range(length))
|
||||
|
||||
|
||||
class NaiveProxyManager:
|
||||
PROTOCOL = 'naiveproxy'
|
||||
CONTAINER_NAME = 'amnezia-naiveproxy'
|
||||
IMAGE_NAME = 'amnezia-naiveproxy:local'
|
||||
BASE_DIR = '/opt/amnezia/naiveproxy'
|
||||
DEFAULT_PORT = 443
|
||||
# Official Caddy+forwardproxy naive build (linux amd64)
|
||||
CADDY_RELEASE = 'v2.11.2-naive'
|
||||
CADDY_URL = (
|
||||
'https://github.com/klzgrad/forwardproxy/releases/download/'
|
||||
f'{CADDY_RELEASE}/caddy-forwardproxy-naive.tar.xz'
|
||||
)
|
||||
|
||||
def __init__(self, ssh, protocol='naiveproxy'):
|
||||
self.ssh = ssh
|
||||
self.protocol = protocol or self.PROTOCOL
|
||||
self.container_name = self.CONTAINER_NAME
|
||||
self.base_dir = self.BASE_DIR
|
||||
self.caddyfile_path = f'{self.base_dir}/Caddyfile'
|
||||
self.clients_path = f'{self.base_dir}/clients.json'
|
||||
self.meta_path = f'{self.base_dir}/metadata.json'
|
||||
self.html_dir = f'{self.base_dir}/html'
|
||||
self.bin_dir = f'{self.base_dir}/bin'
|
||||
self.data_dir = f'{self.base_dir}/caddy-data'
|
||||
self.config_dir = f'{self.base_dir}/caddy-config'
|
||||
|
||||
# ===================== STATUS =====================
|
||||
|
||||
def check_docker_installed(self):
|
||||
out, _, code = self.ssh.run_command("docker --version 2>/dev/null")
|
||||
if code != 0:
|
||||
return False
|
||||
out2, _, _ = self.ssh.run_command(
|
||||
"systemctl is-active docker 2>/dev/null || service docker status 2>/dev/null"
|
||||
)
|
||||
return 'active' in out2 or 'running' in out2.lower()
|
||||
|
||||
def check_protocol_installed(self, protocol_type=None):
|
||||
out, _, _ = self.ssh.run_sudo_command(
|
||||
f"docker ps -a --filter name=^{self.CONTAINER_NAME}$ --format '{{{{.Names}}}}'"
|
||||
)
|
||||
return self.CONTAINER_NAME in out.strip().split('\n')
|
||||
|
||||
def check_container_running(self, protocol_type=None):
|
||||
out, _, _ = self.ssh.run_sudo_command(
|
||||
f"docker ps --filter name=^{self.CONTAINER_NAME}$ --format '{{{{.Status}}}}'"
|
||||
)
|
||||
return 'Up' in out
|
||||
|
||||
def get_logs(self, protocol_type=None, tail=200):
|
||||
tail = max(20, min(int(tail or 200), 2000))
|
||||
out, err, code = self.ssh.run_sudo_command(
|
||||
f"docker logs --tail {tail} --timestamps {self.CONTAINER_NAME} 2>&1",
|
||||
timeout=30,
|
||||
)
|
||||
text = (out or err or '').strip()
|
||||
if code != 0 and not text:
|
||||
text = f'(no logs: exit {code})'
|
||||
return text
|
||||
|
||||
def get_container_diagnostics(self, protocol_type=None):
|
||||
fmt = (
|
||||
'{{.State.Status}}|{{.State.Running}}|{{.State.ExitCode}}|'
|
||||
'{{.State.OOMKilled}}|{{.State.Error}}|{{.State.FinishedAt}}|'
|
||||
'{{.State.StartedAt}}'
|
||||
)
|
||||
out, _, code = self.ssh.run_sudo_command(
|
||||
f"docker inspect -f '{fmt}' {self.CONTAINER_NAME} 2>/dev/null"
|
||||
)
|
||||
diag = {
|
||||
'status': 'unknown',
|
||||
'running': False,
|
||||
'exit_code': None,
|
||||
'error_summary': '',
|
||||
'recent_logs': '',
|
||||
}
|
||||
if code == 0 and out.strip():
|
||||
parts = out.strip().split('|')
|
||||
while len(parts) < 7:
|
||||
parts.append('')
|
||||
diag['status'] = parts[0]
|
||||
diag['running'] = parts[1].lower() == 'true'
|
||||
try:
|
||||
diag['exit_code'] = int(parts[2])
|
||||
except ValueError:
|
||||
diag['exit_code'] = parts[2]
|
||||
if parts[3].lower() == 'true':
|
||||
diag['error_summary'] = 'OOM killed'
|
||||
elif parts[4]:
|
||||
diag['error_summary'] = parts[4]
|
||||
elif not diag['running'] and diag['exit_code'] not in (0, '0', None, ''):
|
||||
diag['error_summary'] = f'Exited with code {diag["exit_code"]}'
|
||||
diag['recent_logs'] = self.get_logs(protocol_type, tail=80)
|
||||
if not diag['error_summary'] and not diag['running']:
|
||||
logs = diag['recent_logs'].lower()
|
||||
if 'address already in use' in logs or 'bind:' in logs:
|
||||
diag['error_summary'] = (
|
||||
'TCP 80/443 already in use — free them or stop conflicting services'
|
||||
)
|
||||
return diag
|
||||
|
||||
def get_server_status(self, protocol_type=None):
|
||||
protocol_type = protocol_type or self.protocol
|
||||
exists = self.check_protocol_installed(protocol_type)
|
||||
running = self.check_container_running(protocol_type) if exists else False
|
||||
meta = self._read_metadata() if exists else {}
|
||||
clients = self._read_clients() if exists else []
|
||||
port = int(meta.get('port') or self.DEFAULT_PORT)
|
||||
return {
|
||||
'container_exists': exists,
|
||||
'container_running': running,
|
||||
'port': port,
|
||||
'domain': meta.get('domain') or '',
|
||||
'email': meta.get('email') or '',
|
||||
'clients_count': len(clients),
|
||||
'protocol': protocol_type,
|
||||
'base_protocol': self.PROTOCOL,
|
||||
'instance': 1,
|
||||
'container_name': self.CONTAINER_NAME,
|
||||
}
|
||||
|
||||
# ===================== IO HELPERS =====================
|
||||
|
||||
def _validate_domain(self, domain):
|
||||
domain = (domain or '').strip().lower()
|
||||
if not domain or len(domain) > 253:
|
||||
raise ValueError('Domain is required')
|
||||
if not re.match(r'^(?!-)[a-z0-9.-]+(?<!-)$', domain) or '.' not in domain:
|
||||
raise ValueError('Invalid domain name')
|
||||
return domain
|
||||
|
||||
def _validate_email(self, email):
|
||||
email = (email or '').strip()
|
||||
if not email or '@' not in email:
|
||||
raise ValueError('Valid Let\'s Encrypt email is required')
|
||||
return email
|
||||
|
||||
def _read_file(self, path):
|
||||
out, _, code = self.ssh.run_sudo_command(f"cat {_q(path)} 2>/dev/null")
|
||||
return out if code == 0 else ''
|
||||
|
||||
def _write_file(self, path, content):
|
||||
# Write via base64 to avoid shell escaping issues
|
||||
import base64
|
||||
b64 = base64.b64encode((content or '').encode('utf-8')).decode('ascii')
|
||||
script = (
|
||||
f"mkdir -p $(dirname {_q(path)}) && "
|
||||
f"echo {_q(b64)} | base64 -d > {_q(path)}"
|
||||
)
|
||||
out, err, code = self.ssh.run_sudo_command(f"sh -c {_q(script)}", timeout=30)
|
||||
if code != 0:
|
||||
raise RuntimeError(f'Failed to write {path}: {err or out}')
|
||||
|
||||
def _read_metadata(self):
|
||||
raw = self._read_file(self.meta_path).strip()
|
||||
if not raw:
|
||||
return {}
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
return data if isinstance(data, dict) else {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
def _write_metadata(self, meta):
|
||||
self._write_file(self.meta_path, json.dumps(meta, indent=2, ensure_ascii=False))
|
||||
|
||||
def _read_clients(self):
|
||||
raw = self._read_file(self.clients_path).strip()
|
||||
if not raw:
|
||||
return []
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
return data if isinstance(data, list) else []
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
def _write_clients(self, clients):
|
||||
self._write_file(self.clients_path, json.dumps(clients, indent=2, ensure_ascii=False))
|
||||
|
||||
def _caddy_auth_lines(self, clients):
|
||||
lines = []
|
||||
for c in clients:
|
||||
if c.get('enabled', True) is False:
|
||||
continue
|
||||
user = (c.get('username') or '').strip()
|
||||
password = (c.get('password') or '').strip()
|
||||
if not user or not password:
|
||||
continue
|
||||
# Credentials are alphanumeric from our generator — safe in Caddyfile
|
||||
lines.append(f' basic_auth {user} {password}')
|
||||
return lines
|
||||
|
||||
def _build_caddyfile(self, domain, email, clients, probe_path):
|
||||
auth_lines = self._caddy_auth_lines(clients)
|
||||
if not auth_lines:
|
||||
# Keep a non-shared bootstrap user so the proxy is never open
|
||||
auth_lines = [f' basic_auth bootstrap {_rand_token(24)}']
|
||||
auth_block = '\n'.join(auth_lines)
|
||||
# probe_resistance looks like a fake domain to browsers
|
||||
probe = (probe_path or _rand_token(12)).strip('/')
|
||||
if '.' not in probe:
|
||||
probe = f'{probe}.com'
|
||||
return f"""{{
|
||||
order forward_proxy before file_server
|
||||
admin off
|
||||
log {{
|
||||
exclude http.log.error
|
||||
}}
|
||||
}}
|
||||
:443, {domain} {{
|
||||
tls {email}
|
||||
encode
|
||||
forward_proxy {{
|
||||
{auth_block}
|
||||
hide_ip
|
||||
hide_via
|
||||
probe_resistance {probe}
|
||||
}}
|
||||
file_server {{
|
||||
root /var/www/html
|
||||
}}
|
||||
}}
|
||||
"""
|
||||
|
||||
def _write_config_from_clients(self):
|
||||
meta = self._read_metadata()
|
||||
domain = meta.get('domain') or ''
|
||||
email = meta.get('email') or ''
|
||||
if not domain or not email:
|
||||
raise RuntimeError('Domain and email are required in metadata')
|
||||
clients = self._read_clients()
|
||||
probe = meta.get('probe_resistance') or _rand_token(12)
|
||||
if not meta.get('probe_resistance'):
|
||||
meta['probe_resistance'] = probe
|
||||
self._write_metadata(meta)
|
||||
text = self._build_caddyfile(domain, email, clients, probe)
|
||||
self._write_file(self.caddyfile_path, text)
|
||||
|
||||
def _ensure_placeholder_site(self):
|
||||
index = f'{self.html_dir}/index.html'
|
||||
existing = self._read_file(index)
|
||||
if existing.strip():
|
||||
return
|
||||
html = (
|
||||
'<!DOCTYPE html><html><head><meta charset="utf-8">'
|
||||
'<title>Welcome</title></head><body><h1>It works</h1></body></html>\n'
|
||||
)
|
||||
self._write_file(index, html)
|
||||
|
||||
def _host_arch(self):
|
||||
out, _, _ = self.ssh.run_command("uname -m")
|
||||
return (out or '').strip().lower()
|
||||
|
||||
def _prepare_caddy_binary(self, log):
|
||||
"""Download official amd64 build or compile with xcaddy for other arches."""
|
||||
self.ssh.run_sudo_command(f"mkdir -p {_q(self.bin_dir)}")
|
||||
arch = self._host_arch()
|
||||
caddy_path = f'{self.bin_dir}/caddy'
|
||||
|
||||
if arch in ('x86_64', 'amd64'):
|
||||
script = f"""
|
||||
set -e
|
||||
cd {_q(self.bin_dir)}
|
||||
curl -fsSL -o caddy-forwardproxy-naive.tar.xz {_q(self.CADDY_URL)}
|
||||
tar -xf caddy-forwardproxy-naive.tar.xz
|
||||
if [ -f caddy-forwardproxy-naive/caddy ]; then
|
||||
cp -f caddy-forwardproxy-naive/caddy ./caddy
|
||||
elif [ -f caddy ]; then
|
||||
true
|
||||
else
|
||||
echo "caddy binary not found in archive" >&2
|
||||
exit 1
|
||||
fi
|
||||
chmod +x ./caddy
|
||||
./caddy version
|
||||
"""
|
||||
out, err, code = self.ssh.run_sudo_command(f"bash -lc {_q(script)}", timeout=300)
|
||||
if code != 0:
|
||||
raise RuntimeError(f'Failed to download NaiveProxy Caddy: {err or out}')
|
||||
log.append(f'Downloaded official Caddy+forwardproxy ({self.CADDY_RELEASE})')
|
||||
return caddy_path
|
||||
|
||||
# arm64 / other: build with xcaddy inside golang image
|
||||
build_script = f"""
|
||||
set -e
|
||||
docker pull golang:1.22-bookworm
|
||||
docker run --rm -v {_q(self.bin_dir)}:/out -w /tmp golang:1.22-bookworm bash -lc '
|
||||
set -e
|
||||
go install github.com/caddyserver/xcaddy/cmd/xcaddy@latest
|
||||
/go/bin/xcaddy build --with github.com/caddyserver/forwardproxy=github.com/klzgrad/forwardproxy@naive
|
||||
cp -f caddy /out/caddy
|
||||
chmod +x /out/caddy
|
||||
'
|
||||
{_q(caddy_path)} version
|
||||
"""
|
||||
out, err, code = self.ssh.run_sudo_command(f"bash -lc {_q(build_script)}", timeout=900)
|
||||
if code != 0:
|
||||
raise RuntimeError(f'Failed to build NaiveProxy Caddy for {arch}: {err or out}')
|
||||
log.append(f'Built Caddy+forwardproxy via xcaddy for {arch}')
|
||||
return caddy_path
|
||||
|
||||
def _build_docker_image(self, log):
|
||||
dockerfile = f"""FROM debian:bookworm-slim
|
||||
RUN apt-get update \\
|
||||
&& apt-get install -y --no-install-recommends ca-certificates \\
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
COPY caddy /usr/bin/caddy
|
||||
RUN chmod +x /usr/bin/caddy
|
||||
WORKDIR /etc/caddy
|
||||
EXPOSE 80 443
|
||||
CMD ["caddy", "run", "--config", "/etc/caddy/Caddyfile", "--adapter", "caddyfile"]
|
||||
"""
|
||||
self._write_file(f'{self.bin_dir}/Dockerfile', dockerfile)
|
||||
out, err, code = self.ssh.run_sudo_command(
|
||||
f"docker build -t {self.IMAGE_NAME} {_q(self.bin_dir)}",
|
||||
timeout=300,
|
||||
)
|
||||
if code != 0:
|
||||
raise RuntimeError(f'Failed to build Docker image: {err or out}')
|
||||
log.append(f'Built image {self.IMAGE_NAME}')
|
||||
|
||||
def _start_container(self):
|
||||
self.ssh.run_sudo_command(
|
||||
f"docker rm -fv {self.CONTAINER_NAME} 2>/dev/null || true"
|
||||
)
|
||||
self.ssh.run_sudo_command(f"mkdir -p {_q(self.data_dir)} {_q(self.config_dir)} {_q(self.html_dir)}")
|
||||
run_cmd = (
|
||||
f"docker run -d --name {self.CONTAINER_NAME} --restart unless-stopped "
|
||||
f"--network host "
|
||||
f"-v {_q(self.base_dir)}:/etc/caddy "
|
||||
f"-v {_q(self.html_dir)}:/var/www/html "
|
||||
f"-v {_q(self.data_dir)}:/data "
|
||||
f"-v {_q(self.config_dir)}:/config "
|
||||
f"-e XDG_DATA_HOME=/data "
|
||||
f"-e XDG_CONFIG_HOME=/config "
|
||||
f"{self.IMAGE_NAME}"
|
||||
)
|
||||
_, err, code = self.ssh.run_sudo_command(run_cmd, timeout=60)
|
||||
if code != 0:
|
||||
raise RuntimeError(f'Failed to start NaiveProxy: {err}')
|
||||
time.sleep(2.0)
|
||||
if not self.check_container_running():
|
||||
diag = self.get_container_diagnostics()
|
||||
raise RuntimeError(
|
||||
diag.get('error_summary')
|
||||
or 'NaiveProxy container exited — free TCP 80/443 and check logs'
|
||||
)
|
||||
return True
|
||||
|
||||
def _reload_container(self):
|
||||
try:
|
||||
self._write_config_from_clients()
|
||||
# Prefer graceful reload; fall back to recreate
|
||||
out, _, code = self.ssh.run_sudo_command(
|
||||
f"docker exec {self.CONTAINER_NAME} caddy reload "
|
||||
f"--config /etc/caddy/Caddyfile --adapter caddyfile 2>&1",
|
||||
timeout=30,
|
||||
)
|
||||
if code != 0:
|
||||
logger.warning('Caddy reload failed (%s), recreating container', out)
|
||||
self._start_container()
|
||||
except Exception as e:
|
||||
logger.warning('NaiveProxy reload failed: %s', e)
|
||||
self._start_container()
|
||||
|
||||
def _build_share_uri(self, domain, username, password, name, port=443):
|
||||
"""v2rayN / NekoRay / sing-box compatible share link.
|
||||
|
||||
Always include an explicit port — without `:443` v2rayN often treats
|
||||
the port as empty/80 and shows «Свойство Порт недопустимо» / SSL errors.
|
||||
"""
|
||||
# Keep credentials unescaped when alphanumeric (our generator); quote otherwise.
|
||||
user = quote(username or '', safe='')
|
||||
pw = quote(password or '', safe='')
|
||||
host = (domain or '').strip().lower()
|
||||
port = int(port or 443)
|
||||
if port < 1 or port > 65535:
|
||||
port = 443
|
||||
# Remark: ASCII-safe, no spaces that break some importers
|
||||
remark = re.sub(r'[^\w.\-]+', '-', (name or 'naiveproxy').strip())[:48] or 'naiveproxy'
|
||||
return f'naive+https://{user}:{pw}@{host}:{port}#{remark}'
|
||||
|
||||
# ===================== INSTALL / REMOVE =====================
|
||||
|
||||
def install_protocol(self, protocol_type=None, port=None, domain=None, email=None):
|
||||
protocol_type = protocol_type or self.protocol
|
||||
if not self.check_docker_installed():
|
||||
return {'status': 'error', 'message': 'Docker not installed'}
|
||||
|
||||
try:
|
||||
domain = self._validate_domain(domain)
|
||||
email = self._validate_email(email)
|
||||
except ValueError as e:
|
||||
return {'status': 'error', 'message': str(e)}
|
||||
|
||||
port = int(port or self.DEFAULT_PORT)
|
||||
if port not in (443,):
|
||||
# Caddy ACME + naive typically bind :443; keep simple for beta
|
||||
port = 443
|
||||
|
||||
log = []
|
||||
self.ssh.run_sudo_command(f"mkdir -p {_q(self.base_dir)} {_q(self.html_dir)} {_q(self.bin_dir)}")
|
||||
|
||||
if self.check_protocol_installed(protocol_type):
|
||||
self.ssh.run_sudo_command(f"docker rm -fv {self.CONTAINER_NAME} 2>/dev/null || true")
|
||||
log.append('Removed previous container')
|
||||
|
||||
try:
|
||||
self._prepare_caddy_binary(log)
|
||||
self._build_docker_image(log)
|
||||
except Exception as e:
|
||||
return {'status': 'error', 'message': str(e), 'log': log}
|
||||
|
||||
self._write_clients([])
|
||||
meta = {
|
||||
'domain': domain,
|
||||
'email': email,
|
||||
'port': port,
|
||||
'probe_resistance': _rand_token(12),
|
||||
'caddy_release': self.CADDY_RELEASE,
|
||||
}
|
||||
self._write_metadata(meta)
|
||||
self._ensure_placeholder_site()
|
||||
try:
|
||||
self._write_config_from_clients()
|
||||
except Exception as e:
|
||||
return {'status': 'error', 'message': str(e), 'log': log}
|
||||
log.append('Wrote Caddyfile (forward_proxy + ACME TLS)')
|
||||
|
||||
try:
|
||||
self._start_container()
|
||||
except Exception as e:
|
||||
return {'status': 'error', 'message': str(e), 'log': log}
|
||||
|
||||
log.append(
|
||||
f'Started {self.CONTAINER_NAME} on TCP 443 (host network). '
|
||||
'Ports 80 and 443 must stay free for ACME and HTTPS.'
|
||||
)
|
||||
return {
|
||||
'status': 'success',
|
||||
'message': 'NaiveProxy installed',
|
||||
'log': log,
|
||||
'port': str(port),
|
||||
'domain': domain,
|
||||
'email': email,
|
||||
}
|
||||
|
||||
def remove_container(self, protocol_type=None):
|
||||
self.ssh.run_sudo_command(f"docker rm -fv {self.CONTAINER_NAME} 2>/dev/null || true")
|
||||
self.ssh.run_sudo_command(f"rm -rf {_q(self.base_dir)}")
|
||||
return True
|
||||
|
||||
def get_server_config(self, protocol_type=None):
|
||||
return self._read_file(self.caddyfile_path)
|
||||
|
||||
def save_server_config(self, protocol_type=None, config_text=''):
|
||||
self._write_file(self.caddyfile_path, config_text or '')
|
||||
self._reload_container()
|
||||
return True
|
||||
|
||||
def get_settings(self):
|
||||
meta = self._read_metadata()
|
||||
return {
|
||||
'port': int(meta.get('port') or self.DEFAULT_PORT),
|
||||
'domain': meta.get('domain') or '',
|
||||
'email': meta.get('email') or '',
|
||||
'protocol': self.protocol,
|
||||
}
|
||||
|
||||
def update_settings(self, domain=None, email=None):
|
||||
meta = self._read_metadata()
|
||||
try:
|
||||
if domain is not None and str(domain).strip():
|
||||
meta['domain'] = self._validate_domain(domain)
|
||||
if email is not None and str(email).strip():
|
||||
meta['email'] = self._validate_email(email)
|
||||
except ValueError as e:
|
||||
return {'status': 'error', 'message': str(e)}
|
||||
if not meta.get('domain') or not meta.get('email'):
|
||||
return {'status': 'error', 'message': 'Domain and email are required'}
|
||||
meta['port'] = int(meta.get('port') or self.DEFAULT_PORT)
|
||||
self._write_metadata(meta)
|
||||
try:
|
||||
self._write_config_from_clients()
|
||||
self._start_container()
|
||||
except Exception as e:
|
||||
return {'status': 'error', 'message': str(e), **self.get_settings()}
|
||||
return {'status': 'success', 'message': 'NaiveProxy settings updated', **self.get_settings()}
|
||||
|
||||
# ===================== CLIENTS =====================
|
||||
|
||||
def get_clients(self, protocol_type=None):
|
||||
clients = self._read_clients()
|
||||
result = []
|
||||
for c in clients:
|
||||
cname = c.get('name') or c.get('username') or c.get('id')
|
||||
result.append({
|
||||
'clientId': c.get('id'),
|
||||
'client_id': c.get('id'),
|
||||
'id': c.get('id'),
|
||||
'name': cname,
|
||||
'email': cname,
|
||||
'enabled': c.get('enabled', True),
|
||||
'userData': {
|
||||
'clientName': cname,
|
||||
'enabled': c.get('enabled', True),
|
||||
'username': c.get('username'),
|
||||
},
|
||||
})
|
||||
return result
|
||||
|
||||
def add_client(self, protocol_type, name, host, port=None):
|
||||
meta = self._read_metadata()
|
||||
domain = meta.get('domain') or host
|
||||
port = int(port or meta.get('port') or self.DEFAULT_PORT)
|
||||
client_id = secrets.token_hex(8)
|
||||
username = f'u{client_id[:8]}'
|
||||
password = _rand_token(20)
|
||||
clients = self._read_clients()
|
||||
clients.append({
|
||||
'id': client_id,
|
||||
'name': name or f'client-{client_id[:6]}',
|
||||
'username': username,
|
||||
'password': password,
|
||||
'enabled': True,
|
||||
})
|
||||
self._write_clients(clients)
|
||||
self._reload_container()
|
||||
config = self._build_share_uri(domain, username, password, name or client_id, port)
|
||||
return {'client_id': client_id, 'config': config}
|
||||
|
||||
def get_client_config(self, protocol_type, client_id, host, port=None):
|
||||
meta = self._read_metadata()
|
||||
domain = meta.get('domain') or host
|
||||
port = int(port or meta.get('port') or self.DEFAULT_PORT)
|
||||
clients = self._read_clients()
|
||||
client = next((c for c in clients if c.get('id') == client_id), None)
|
||||
if not client:
|
||||
raise RuntimeError('Client not found')
|
||||
if client.get('enabled', True) is False:
|
||||
raise RuntimeError('Client is disabled')
|
||||
return self._build_share_uri(
|
||||
domain,
|
||||
client.get('username'),
|
||||
client.get('password'),
|
||||
client.get('name') or client_id,
|
||||
port,
|
||||
)
|
||||
|
||||
def remove_client(self, protocol_type, client_id):
|
||||
clients = [c for c in self._read_clients() if c.get('id') != client_id]
|
||||
self._write_clients(clients)
|
||||
self._reload_container()
|
||||
return True
|
||||
|
||||
def toggle_client(self, protocol_type, client_id, enable=True):
|
||||
clients = self._read_clients()
|
||||
found = False
|
||||
for c in clients:
|
||||
if c.get('id') == client_id:
|
||||
c['enabled'] = bool(enable)
|
||||
found = True
|
||||
break
|
||||
if not found:
|
||||
raise RuntimeError('Client not found')
|
||||
self._write_clients(clients)
|
||||
self._reload_container()
|
||||
return True
|
||||
@@ -944,6 +944,11 @@ a:hover {
|
||||
color: #38bdf8;
|
||||
}
|
||||
|
||||
.protocol-hysteria .protocol-icon {
|
||||
background: linear-gradient(135deg, rgba(14, 165, 233, 0.2), rgba(99, 102, 241, 0.1));
|
||||
color: #38bdf8;
|
||||
}
|
||||
|
||||
.protocol-dns .protocol-icon {
|
||||
background: linear-gradient(135deg, rgba(34, 197, 94, 0.2), rgba(16, 185, 129, 0.1));
|
||||
color: var(--success);
|
||||
|
||||
+11
-3
@@ -24,7 +24,7 @@ _bot_task: Optional[asyncio.Task] = None
|
||||
_callback_refs = {}
|
||||
_pending_inputs = {}
|
||||
|
||||
CLIENT_PROTOCOLS = {"awg", "awg2", "awg_legacy", "xray", "telemt", "wireguard"}
|
||||
CLIENT_PROTOCOLS = {"awg", "awg2", "awg_legacy", "xray", "telemt", "hysteria", "naiveproxy", "wireguard"}
|
||||
SERVICE_PROTOCOLS = {"dns", "adguard", "socks5", "nginx"}
|
||||
|
||||
|
||||
@@ -137,6 +137,8 @@ def _protocol_display_name(protocol: str) -> str:
|
||||
"awg_legacy": "AmneziaWG Legacy",
|
||||
"xray": "Xray",
|
||||
"telemt": "Telemt",
|
||||
"hysteria": "Hysteria 2",
|
||||
"naiveproxy": "NaiveProxy",
|
||||
"dns": "AmneziaDNS",
|
||||
"wireguard": "WireGuard",
|
||||
"socks5": "SOCKS5",
|
||||
@@ -338,6 +340,8 @@ def _get_ssh_and_manager(server: dict, proto: str):
|
||||
from managers.awg_manager import AWGManager
|
||||
from managers.xray_manager import XrayManager
|
||||
from managers.telemt_manager import TelemtManager
|
||||
from managers.hysteria_manager import HysteriaManager
|
||||
from managers.naiveproxy_manager import NaiveProxyManager
|
||||
from managers.wireguard_manager import WireGuardManager
|
||||
from managers.dns_manager import DNSManager
|
||||
from managers.socks5_manager import Socks5Manager
|
||||
@@ -356,6 +360,10 @@ def _get_ssh_and_manager(server: dict, proto: str):
|
||||
manager = XrayManager(ssh, proto)
|
||||
elif base == "telemt":
|
||||
manager = TelemtManager(ssh, proto)
|
||||
elif base == "hysteria":
|
||||
manager = HysteriaManager(ssh, proto)
|
||||
elif base == "naiveproxy":
|
||||
manager = NaiveProxyManager(ssh, proto)
|
||||
elif base == "wireguard":
|
||||
manager = WireGuardManager(ssh)
|
||||
elif base == "dns":
|
||||
@@ -561,7 +569,7 @@ async def _send_config_by_client(api: TelegramAPI, chat_id: int, server: dict, p
|
||||
server_name = server.get("name") or server.get("host", "Unknown")
|
||||
await api.send_message(chat_id, f"✅ <b>{_e(conn_name)}</b>\n🌐 Server: <b>{_e(server_name)}</b>\n🔌 Protocol: <b>{_e(proto.upper())}</b>")
|
||||
|
||||
is_link_proto = _proto_base(proto) in ("xray", "telemt")
|
||||
is_link_proto = _proto_base(proto) in ("xray", "telemt", "hysteria", "naiveproxy")
|
||||
if is_link_proto:
|
||||
await api.send_message(chat_id, f"🔗 <b>Connection link</b> (tap to copy):\n<code>{_e(config)}</code>")
|
||||
else:
|
||||
@@ -918,7 +926,7 @@ async def _admin_create_client(api: TelegramAPI, chat_id: int, message_id: int,
|
||||
|
||||
async def _send_config_text(api: TelegramAPI, chat_id: int, server: dict, proto: str, conn_name: str, config: str, generate_vpn_link_fn: Callable):
|
||||
await api.send_message(chat_id, f"✅ <b>{_e(conn_name)}</b>\n🌐 Server: <b>{_e(server.get('name') or server.get('host'))}</b>\n🔌 Protocol: <b>{_e(proto.upper())}</b>")
|
||||
if _proto_base(proto) in ("xray", "telemt"):
|
||||
if _proto_base(proto) in ("xray", "telemt", "hysteria", "naiveproxy"):
|
||||
await api.send_message(chat_id, f"🔗 <b>Connection link</b>:\n<code>{_e(config)}</code>")
|
||||
else:
|
||||
await api.send_message(chat_id, f"<b>📄 Configuration:</b>\n<pre>{_e(config)}</pre>")
|
||||
|
||||
@@ -105,6 +105,9 @@
|
||||
if (p === 'awg_legacy') return 'AWG Legacy';
|
||||
if (p === 'xray') return 'Xray';
|
||||
if (p === 'xui') return '3x-ui VLESS';
|
||||
if (p === 'hysteria') return 'Hysteria 2';
|
||||
if (p === 'naiveproxy') return 'NaiveProxy';
|
||||
if (p === 'telemt') return 'Telemt';
|
||||
return (p || '').toUpperCase();
|
||||
}
|
||||
|
||||
|
||||
@@ -19,6 +19,8 @@
|
||||
<div class="card card-hover server-card" id="server-{{ loop.index0 }}" data-idx="{{ loop.index0 }}"
|
||||
data-name="{{ server.name }}" data-host="{{ server.host }}" data-port="{{ server.ssh_port }}"
|
||||
data-username="{{ server.username }}" data-auth="{{ 'key' if server.private_key else 'password' }}"
|
||||
data-ssl-domain="{{ (server.server_info or {}).get('ssl_domain', '') }}"
|
||||
data-ssl-email="{{ (server.server_info or {}).get('ssl_email', '') }}"
|
||||
draggable="true">
|
||||
<div class="server-meta">
|
||||
<div class="server-icon">{{ icon('server') }}</div>
|
||||
@@ -137,6 +139,16 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group" style="margin-top: var(--space-md)">
|
||||
<label class="form-label">{{ _('server_ssl_domain') }}</label>
|
||||
<input class="form-input" type="text" id="editServerSslDomain" placeholder="vpn.example.com">
|
||||
<div class="form-hint">{{ _('server_ssl_hint') }}</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">{{ _('server_ssl_email') }}</label>
|
||||
<input class="form-input" type="email" id="editServerSslEmail" placeholder="admin@example.com">
|
||||
</div>
|
||||
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" onclick="closeModal('editServerModal')">{{ _('cancel')
|
||||
}}</button>
|
||||
@@ -202,6 +214,16 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group" style="margin-top: var(--space-md)">
|
||||
<label class="form-label">{{ _('server_ssl_domain') }}</label>
|
||||
<input class="form-input" type="text" id="serverSslDomain" placeholder="vpn.example.com">
|
||||
<div class="form-hint">{{ _('server_ssl_hint') }}</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">{{ _('server_ssl_email') }}</label>
|
||||
<input class="form-input" type="email" id="serverSslEmail" placeholder="admin@example.com">
|
||||
</div>
|
||||
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" onclick="closeModal('addServerModal')">{{ _('cancel')
|
||||
}}</button>
|
||||
@@ -244,6 +266,8 @@
|
||||
username: document.getElementById('serverUser').value,
|
||||
password: document.getElementById('serverPassword').value,
|
||||
private_key: document.getElementById('serverKey').value,
|
||||
ssl_domain: document.getElementById('serverSslDomain').value.trim(),
|
||||
ssl_email: document.getElementById('serverSslEmail').value.trim(),
|
||||
};
|
||||
|
||||
const result = await apiCall('/api/servers/add', 'POST', data);
|
||||
@@ -292,6 +316,8 @@
|
||||
document.getElementById('editServerUser').value = card.dataset.username || '';
|
||||
document.getElementById('editServerPassword').value = '';
|
||||
document.getElementById('editServerKey').value = '';
|
||||
document.getElementById('editServerSslDomain').value = card.dataset.sslDomain || '';
|
||||
document.getElementById('editServerSslEmail').value = card.dataset.sslEmail || '';
|
||||
|
||||
// Pre-select the tab matching the server's current auth method.
|
||||
const authIsKey = card.dataset.auth === 'key';
|
||||
@@ -321,6 +347,8 @@
|
||||
// Empty -> null means "leave unchanged" on the backend.
|
||||
password: document.getElementById('editServerPassword').value || null,
|
||||
private_key: document.getElementById('editServerKey').value || null,
|
||||
ssl_domain: document.getElementById('editServerSslDomain').value.trim(),
|
||||
ssl_email: document.getElementById('editServerSslEmail').value.trim(),
|
||||
};
|
||||
await apiCall(`/api/servers/${idx}/edit`, 'POST', body);
|
||||
showToast(_('server_saved'), 'success');
|
||||
|
||||
+115
-29
@@ -127,17 +127,22 @@
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label class="form-label">{{ _('server_label') }}</label>
|
||||
<select class="form-select" id="inviteServer" onchange="onInviteServerChange()">
|
||||
{% if xui_configured %}
|
||||
<option value="xui">3x-ui</option>
|
||||
{% endif %}
|
||||
{% for s in servers %}
|
||||
<option value="{{ loop.index0 }}">{{ s.name or s.host }} ({{ s.host }})</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
<div class="form-hint">{{ _('server_then_protocol_hint') }}</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group" id="inviteProtoGroup">
|
||||
<label class="form-label">{{ _('protocol_label') }}</label>
|
||||
<select class="form-select" id="inviteProtocol" onchange="updateInviteProtoFields()">
|
||||
<option value="xui">3x-ui VLESS</option>
|
||||
{% for s in servers %}
|
||||
{% set server_idx = loop.index0 %}
|
||||
{% for key, info in (s.protocols or {}).items() %}
|
||||
{% if info.installed and key.split('__')[0] in ['awg','awg2','awg_legacy','xray','wireguard','telemt'] %}
|
||||
<option value="{{ key }}|{{ server_idx }}">{{ s.name or s.host }} — {{ key }}</option>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
{% endfor %}
|
||||
<!-- filled by JS from selected server -->
|
||||
</select>
|
||||
</div>
|
||||
|
||||
@@ -187,9 +192,30 @@
|
||||
|
||||
<script>
|
||||
const invitesData = {{ invites | tojson }};
|
||||
const serversData = {{ servers | tojson }};
|
||||
const xuiConfigured = {{ 'true' if xui_configured else 'false' }};
|
||||
const xuiDefaultInbound = {{ xui_default_inbound | int }};
|
||||
const xuiDefaultPanelId = {{ (xui_default_panel_id or '') | tojson }};
|
||||
const VPN_PROTO_ORDER = ['awg2', 'awg', 'awg_legacy', 'wireguard', 'xray', 'telemt', 'hysteria', 'naiveproxy'];
|
||||
const PROTO_TITLES = {
|
||||
awg2: 'AmneziaWG 2.0',
|
||||
awg: 'AmneziaWG',
|
||||
awg_legacy: 'AWG Legacy',
|
||||
wireguard: 'WireGuard',
|
||||
xray: 'Xray (VLESS-Reality)',
|
||||
telemt: 'Telemt',
|
||||
hysteria: 'Hysteria 2',
|
||||
naiveproxy: 'NaiveProxy',
|
||||
xui: '3x-ui VLESS',
|
||||
};
|
||||
|
||||
function protoTitle(key) {
|
||||
const raw = String(key || '');
|
||||
const base = raw.split('__')[0];
|
||||
const title = PROTO_TITLES[base] || base.toUpperCase();
|
||||
const m = raw.match(/__(\d+)$/);
|
||||
return m ? `${title} #${m[1]}` : title;
|
||||
}
|
||||
|
||||
function inviteUrl(token) {
|
||||
return `${window.location.origin}/invite/${token}`;
|
||||
@@ -200,6 +226,57 @@
|
||||
showToast(_('copied'), 'success');
|
||||
}
|
||||
|
||||
function fillInviteProtocols(preferProtocol) {
|
||||
const serverVal = document.getElementById('inviteServer').value;
|
||||
const sel = document.getElementById('inviteProtocol');
|
||||
sel.innerHTML = '';
|
||||
|
||||
if (serverVal === 'xui') {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = 'xui';
|
||||
opt.textContent = PROTO_TITLES.xui;
|
||||
sel.appendChild(opt);
|
||||
updateInviteProtoFields();
|
||||
return;
|
||||
}
|
||||
|
||||
const server = serversData[parseInt(serverVal, 10)];
|
||||
const protocols = (server && server.protocols) || {};
|
||||
const installed = Object.keys(protocols).filter(k => {
|
||||
const info = protocols[k] || {};
|
||||
if (!info.installed) return false;
|
||||
return VPN_PROTO_ORDER.includes(k.split('__')[0]);
|
||||
});
|
||||
installed.sort((a, b) => {
|
||||
const ia = VPN_PROTO_ORDER.indexOf(a.split('__')[0]);
|
||||
const ib = VPN_PROTO_ORDER.indexOf(b.split('__')[0]);
|
||||
return (ia < 0 ? 99 : ia) - (ib < 0 ? 99 : ib) || a.localeCompare(b);
|
||||
});
|
||||
|
||||
if (!installed.length) {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = '';
|
||||
opt.textContent = _('no_protocols');
|
||||
opt.disabled = true;
|
||||
sel.appendChild(opt);
|
||||
updateInviteProtoFields();
|
||||
return;
|
||||
}
|
||||
|
||||
installed.forEach(key => {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = key;
|
||||
opt.textContent = protoTitle(key);
|
||||
if (preferProtocol && preferProtocol === key) opt.selected = true;
|
||||
sel.appendChild(opt);
|
||||
});
|
||||
updateInviteProtoFields();
|
||||
}
|
||||
|
||||
function onInviteServerChange() {
|
||||
fillInviteProtocols();
|
||||
}
|
||||
|
||||
function updateInviteProtoFields() {
|
||||
const v = document.getElementById('inviteProtocol').value;
|
||||
document.getElementById('inviteInboundGroup').style.display = (v === 'xui') ? '' : 'none';
|
||||
@@ -237,25 +314,26 @@
|
||||
}
|
||||
}
|
||||
|
||||
function parseProtocolValue() {
|
||||
const raw = document.getElementById('inviteProtocol').value;
|
||||
if (raw === 'xui') return { protocol: 'xui', server_id: 0 };
|
||||
if (raw.includes('|')) {
|
||||
const [protocol, sid] = raw.split('|');
|
||||
return { protocol, server_id: parseInt(sid || '0') };
|
||||
function parseInviteSelection() {
|
||||
const serverVal = document.getElementById('inviteServer').value;
|
||||
const protocol = document.getElementById('inviteProtocol').value;
|
||||
if (serverVal === 'xui' || protocol === 'xui') {
|
||||
return { protocol: 'xui', server_id: 0 };
|
||||
}
|
||||
return { protocol: raw, server_id: 0 };
|
||||
return { protocol, server_id: parseInt(serverVal || '0', 10) || 0 };
|
||||
}
|
||||
|
||||
function setProtocolSelect(protocol, serverId) {
|
||||
const sel = document.getElementById('inviteProtocol');
|
||||
if (protocol === 'xui') sel.value = 'xui';
|
||||
else {
|
||||
const want = `${protocol}|${serverId || 0}`;
|
||||
if ([...sel.options].some(o => o.value === want)) sel.value = want;
|
||||
else sel.value = 'xui';
|
||||
function setInviteSelection(protocol, serverId) {
|
||||
const serverSel = document.getElementById('inviteServer');
|
||||
if (protocol === 'xui') {
|
||||
if ([...serverSel.options].some(o => o.value === 'xui')) serverSel.value = 'xui';
|
||||
fillInviteProtocols('xui');
|
||||
return;
|
||||
}
|
||||
updateInviteProtoFields();
|
||||
const sid = String(serverId || 0);
|
||||
if ([...serverSel.options].some(o => o.value === sid)) serverSel.value = sid;
|
||||
else if (serverSel.options.length) serverSel.selectedIndex = xuiConfigured ? 1 : 0;
|
||||
fillInviteProtocols(protocol);
|
||||
}
|
||||
|
||||
function openCreateInvite() {
|
||||
@@ -269,12 +347,17 @@
|
||||
document.getElementById('inviteNote').value = '';
|
||||
document.getElementById('inviteClearPwdWrap').style.display = 'none';
|
||||
document.getElementById('inviteResetUsedWrap').style.display = 'none';
|
||||
setProtocolSelect('xui', 0);
|
||||
const serverSel = document.getElementById('inviteServer');
|
||||
if (xuiConfigured && [...serverSel.options].some(o => o.value === 'xui')) serverSel.value = 'xui';
|
||||
else if (serverSel.options.length) serverSel.selectedIndex = 0;
|
||||
fillInviteProtocols();
|
||||
if (xuiDefaultPanelId) {
|
||||
const p = document.getElementById('inviteXuiPanel');
|
||||
if (p && [...p.options].some(o => o.value === xuiDefaultPanelId)) p.value = xuiDefaultPanelId;
|
||||
}
|
||||
loadInviteInbounds(xuiDefaultInbound);
|
||||
if (document.getElementById('inviteProtocol').value === 'xui') {
|
||||
loadInviteInbounds(xuiDefaultInbound);
|
||||
}
|
||||
openModal('inviteModal');
|
||||
}
|
||||
|
||||
@@ -293,12 +376,14 @@
|
||||
document.getElementById('inviteClearPassword').checked = false;
|
||||
document.getElementById('inviteResetUsedWrap').style.display = 'block';
|
||||
document.getElementById('inviteResetUsed').checked = false;
|
||||
setProtocolSelect(inv.protocol || 'xui', inv.server_id || 0);
|
||||
setInviteSelection(inv.protocol || 'xui', inv.server_id || 0);
|
||||
const panelSel = document.getElementById('inviteXuiPanel');
|
||||
if (panelSel && inv.xui_panel_id && [...panelSel.options].some(o => o.value === inv.xui_panel_id)) {
|
||||
panelSel.value = inv.xui_panel_id;
|
||||
}
|
||||
loadInviteInbounds(inv.xui_inbound_id || xuiDefaultInbound);
|
||||
if ((inv.protocol || '') === 'xui') {
|
||||
loadInviteInbounds(inv.xui_inbound_id || xuiDefaultInbound);
|
||||
}
|
||||
openModal('inviteModal');
|
||||
}
|
||||
|
||||
@@ -309,7 +394,8 @@
|
||||
spinner.classList.remove('hidden');
|
||||
try {
|
||||
const editId = document.getElementById('inviteEditId').value;
|
||||
const proto = parseProtocolValue();
|
||||
const proto = parseInviteSelection();
|
||||
if (!proto.protocol) throw new Error(_('no_protocols'));
|
||||
const inbound = parseInt(document.getElementById('inviteInboundId').value || '0');
|
||||
if (proto.protocol === 'xui' && !inbound) throw new Error(_('invite_inbound_required'));
|
||||
|
||||
|
||||
@@ -118,10 +118,11 @@
|
||||
document.getElementById('configText').textContent = result.config;
|
||||
document.getElementById('vpnLinkText').textContent = currentVpnLink;
|
||||
|
||||
// Telemt uses share links, not vpn:// Amnezia format
|
||||
// Telemt / Hysteria / NaiveProxy use share links, not vpn:// Amnezia format
|
||||
const vpnTab = document.querySelectorAll('.config-tab')[1];
|
||||
const vpnPanel = document.getElementById('panel-vpn');
|
||||
if (proto === 'telemt') {
|
||||
const base = String(proto || '').split('__')[0];
|
||||
if (proto === 'telemt' || base === 'hysteria' || base === 'naiveproxy') {
|
||||
vpnTab.style.display = 'none';
|
||||
} else {
|
||||
vpnTab.style.display = '';
|
||||
|
||||
+691
-10
@@ -1,4 +1,4 @@
|
||||
{% extends "base.html" %}
|
||||
{% extends "base.html" %}
|
||||
{% from "macros/icons.html" import icon %}
|
||||
|
||||
{% block title_extra %} — {{ server.name }}{% endblock %}
|
||||
@@ -157,6 +157,153 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Cascade (double VPN) -->
|
||||
<section class="card" id="cascadeSection" style="margin-bottom: var(--space-xl);">
|
||||
<div class="card-header" style="align-items:flex-start; flex-wrap:wrap; gap:var(--space-sm);">
|
||||
<div>
|
||||
<h2 class="card-title" style="margin:0;">{{ _('cascade_title') }}</h2>
|
||||
<p class="form-hint" style="margin:var(--space-xs) 0 0;">{{ _('cascade_desc') }}</p>
|
||||
</div>
|
||||
<span class="badge badge-warn" id="cascadeStatusBadge">{{ _('cascade_off') }}</span>
|
||||
</div>
|
||||
<div style="padding: 0 var(--space-md) var(--space-md);">
|
||||
<div class="grid" style="display:grid; grid-template-columns:1fr 1fr; gap:var(--space-md);">
|
||||
<div class="form-group">
|
||||
<label class="form-label">{{ _('cascade_entry_protocol') }}</label>
|
||||
<select class="form-select" id="cascadeEntryProtocol">
|
||||
<option value="awg2" selected>AmneziaWG 2.0</option>
|
||||
<option value="awg">AmneziaWG</option>
|
||||
<option value="awg_legacy">AWG Legacy</option>
|
||||
<option value="wireguard">WireGuard</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">{{ _('cascade_exit_server') }}</label>
|
||||
<select class="form-select" id="cascadeExitServer" onchange="fillCascadeExitProtocols()">
|
||||
<option value="">{{ _('cascade_exit_server_none') }}</option>
|
||||
{% for s in all_servers %}
|
||||
{% if loop.index0 != server_id %}
|
||||
<option value="{{ loop.index0 }}"
|
||||
data-protocols="{% for k in (s.protocols or {}).keys() %}{{ k }}{% if not loop.last %},{% endif %}{% endfor %}">
|
||||
{{ s.name or s.host }} ({{ s.host }})
|
||||
</option>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">{{ _('cascade_exit_protocol') }}</label>
|
||||
<select class="form-select" id="cascadeExitProtocol">
|
||||
<option value="awg2" selected>AmneziaWG 2.0</option>
|
||||
<option value="awg">AmneziaWG</option>
|
||||
<option value="awg_legacy">AWG Legacy</option>
|
||||
<option value="wireguard">WireGuard</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-hint" style="margin-bottom:var(--space-sm);">{{ _('cascade_hint') }}</div>
|
||||
<div class="form-hint" style="margin-bottom:var(--space-sm);">{{ _('cascade_client_note') }}</div>
|
||||
<div class="form-hint" style="margin-bottom:var(--space-md);">{{ _('cascade_security_note') }}</div>
|
||||
|
||||
<details id="cascadeSettingsPanel" open style="margin-bottom:var(--space-md); border:1px solid var(--border); border-radius:var(--radius-md); padding:var(--space-sm) var(--space-md);">
|
||||
<summary style="cursor:pointer; font-weight:600; margin-bottom:var(--space-sm);">{{ _('cascade_settings_title') }}</summary>
|
||||
<p class="form-hint" style="margin:0 0 var(--space-md);">{{ _('cascade_settings_desc') }}</p>
|
||||
<div class="grid" style="display:grid; grid-template-columns:1fr 1fr; gap:var(--space-sm) var(--space-md);">
|
||||
<label class="form-check" style="display:flex; gap:var(--space-sm); align-items:flex-start;">
|
||||
<input type="checkbox" id="cascadePinExitRoute" checked>
|
||||
<span>
|
||||
<strong>{{ _('cascade_opt_pin_exit') }}</strong>
|
||||
<span class="form-hint" style="display:block;">{{ _('cascade_opt_pin_exit_hint') }}</span>
|
||||
</span>
|
||||
</label>
|
||||
<label class="form-check" style="display:flex; gap:var(--space-sm); align-items:flex-start;">
|
||||
<input type="checkbox" id="cascadeRemoveEthMasq" checked>
|
||||
<span>
|
||||
<strong>{{ _('cascade_opt_remove_eth_masq') }}</strong>
|
||||
<span class="form-hint" style="display:block;">{{ _('cascade_opt_remove_eth_masq_hint') }}</span>
|
||||
</span>
|
||||
</label>
|
||||
<label class="form-check" style="display:flex; gap:var(--space-sm); align-items:flex-start;">
|
||||
<input type="checkbox" id="cascadeForceForward" checked>
|
||||
<span>
|
||||
<strong>{{ _('cascade_opt_force_forward') }}</strong>
|
||||
<span class="form-hint" style="display:block;">{{ _('cascade_opt_force_forward_hint') }}</span>
|
||||
</span>
|
||||
</label>
|
||||
<label class="form-check" style="display:flex; gap:var(--space-sm); align-items:flex-start;">
|
||||
<input type="checkbox" id="cascadeMssClamp" checked>
|
||||
<span>
|
||||
<strong>{{ _('cascade_opt_mss_clamp') }}</strong>
|
||||
<span class="form-hint" style="display:block;">{{ _('cascade_opt_mss_clamp_hint') }}</span>
|
||||
</span>
|
||||
</label>
|
||||
<label class="form-check" style="display:flex; gap:var(--space-sm); align-items:flex-start;">
|
||||
<input type="checkbox" id="cascadeWaitHandshake" checked>
|
||||
<span>
|
||||
<strong>{{ _('cascade_opt_wait_handshake') }}</strong>
|
||||
<span class="form-hint" style="display:block;">{{ _('cascade_opt_wait_handshake_hint') }}</span>
|
||||
</span>
|
||||
</label>
|
||||
<label class="form-check" style="display:flex; gap:var(--space-sm); align-items:flex-start;">
|
||||
<input type="checkbox" id="cascadeVerifyEgress" checked>
|
||||
<span>
|
||||
<strong>{{ _('cascade_verify_egress') }}</strong>
|
||||
<span class="form-hint" style="display:block;">{{ _('cascade_verify_egress_hint') }}</span>
|
||||
</span>
|
||||
</label>
|
||||
<label class="form-check" style="display:flex; gap:var(--space-sm); align-items:flex-start;">
|
||||
<input type="checkbox" id="cascadeKeepExitDns">
|
||||
<span>
|
||||
<strong>{{ _('cascade_opt_keep_dns') }}</strong>
|
||||
<span class="form-hint" style="display:block;">{{ _('cascade_opt_keep_dns_hint') }}</span>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="grid" style="display:grid; grid-template-columns:1fr 1fr 1fr; gap:var(--space-md); margin-top:var(--space-md);">
|
||||
<div class="form-group" style="margin:0;">
|
||||
<label class="form-label" for="cascadeHandshakeTimeout">{{ _('cascade_opt_handshake_timeout') }}</label>
|
||||
<input type="number" class="form-input" id="cascadeHandshakeTimeout" min="5" max="120" value="25">
|
||||
</div>
|
||||
<div class="form-group" style="margin:0;">
|
||||
<label class="form-label" for="cascadeTableId">{{ _('cascade_opt_table_id') }}</label>
|
||||
<input type="number" class="form-input" id="cascadeTableId" min="1" max="252" value="200">
|
||||
</div>
|
||||
<div class="form-group" style="margin:0;">
|
||||
<label class="form-label" for="cascadeRulePriority">{{ _('cascade_opt_rule_priority') }}</label>
|
||||
<input type="number" class="form-input" id="cascadeRulePriority" min="1" max="32765" value="100">
|
||||
</div>
|
||||
</div>
|
||||
<div class="grid" style="display:grid; grid-template-columns:1fr 1fr; gap:var(--space-md); margin-top:var(--space-md);">
|
||||
<div class="form-group" style="margin:0;">
|
||||
<label class="form-label" for="cascadeAllowedIps">{{ _('cascade_opt_allowed_ips') }}</label>
|
||||
<input type="text" class="form-input" id="cascadeAllowedIps" value="0.0.0.0/0">
|
||||
<span class="form-hint">{{ _('cascade_opt_allowed_ips_hint') }}</span>
|
||||
</div>
|
||||
<div class="form-group" style="margin:0;">
|
||||
<label class="form-label" for="cascadeVpnSubnet">{{ _('cascade_opt_vpn_subnet') }}</label>
|
||||
<input type="text" class="form-input" id="cascadeVpnSubnet" placeholder="10.8.1.0/24" value="">
|
||||
<span class="form-hint">{{ _('cascade_opt_vpn_subnet_hint') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<div id="cascadeDiagBox" class="hidden" style="margin-bottom:var(--space-md); padding:var(--space-sm) var(--space-md); background:var(--bg-muted, rgba(0,0,0,.04)); border-radius:var(--radius-md); font-family:ui-monospace,monospace; font-size:12px; white-space:pre-wrap; max-height:160px; overflow:auto;"></div>
|
||||
|
||||
<div class="flex gap-sm" style="flex-wrap:wrap;">
|
||||
<button type="button" class="btn btn-primary" id="cascadeEnableBtn" onclick="enableCascade()">
|
||||
{{ _('cascade_enable') }}
|
||||
</button>
|
||||
<button type="button" class="btn btn-secondary" id="cascadeDisableBtn" onclick="disableCascade()">
|
||||
{{ _('cascade_disable') }}
|
||||
</button>
|
||||
<button type="button" class="btn btn-secondary" onclick="loadCascade()">{{ _('refresh') }}</button>
|
||||
</div>
|
||||
<div id="cascadeBusy" class="hidden" style="display:none; align-items:center; gap:var(--space-sm); margin-top:var(--space-md);">
|
||||
<div class="spinner" style="width:18px;height:18px;border-width:2px;"></div>
|
||||
<span id="cascadeBusyText">{{ _('cascade_working') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<!-- Installed Applications Section -->
|
||||
|
||||
<div class="apps-loading" id="installedAppsLoading">
|
||||
@@ -295,6 +442,55 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Hysteria Card -->
|
||||
<div class="card card-hover protocol-card protocol-hysteria" id="proto-hysteria">
|
||||
<div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:var(--space-sm);">
|
||||
<div class="protocol-icon">{{ icon('refresh') }}</div>
|
||||
<div class="flex gap-sm" id="hysteria-ctrl" style="display:none!important;"></div>
|
||||
</div>
|
||||
<div class="protocol-name">Hysteria 2</div>
|
||||
<div class="protocol-desc">
|
||||
{{ _('hysteria_desc') }}
|
||||
</div>
|
||||
<div class="protocol-status" id="hysteria-status">
|
||||
<span class="badge badge-warn"><span class="badge-dot"></span> {{ _('not_checked') }}</span>
|
||||
</div>
|
||||
<div id="hysteria-info" class="hidden">
|
||||
<div class="protocol-info" id="hysteria-info-grid"></div>
|
||||
</div>
|
||||
<div class="flex gap-sm" id="hysteria-actions">
|
||||
<button class="btn btn-primary btn-sm" onclick="openInstallModal('hysteria')" id="hysteria-install-btn"
|
||||
style="flex:1">
|
||||
{{ _('install') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- NaiveProxy Card -->
|
||||
<div class="card card-hover protocol-card protocol-naiveproxy" id="proto-naiveproxy">
|
||||
<div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:var(--space-sm);">
|
||||
<div class="protocol-icon">{{ icon('link') }}</div>
|
||||
<div class="flex gap-sm" id="naiveproxy-ctrl" style="display:none!important;"></div>
|
||||
</div>
|
||||
<div class="protocol-name">NaiveProxy <span
|
||||
style="font-size:0.65rem; background:var(--success, #16a34a); color:#fff; padding:2px 6px; border-radius:8px; vertical-align:middle;">STABLE</span></div>
|
||||
<div class="protocol-desc">
|
||||
{{ _('naiveproxy_desc') }}
|
||||
</div>
|
||||
<div class="protocol-status" id="naiveproxy-status">
|
||||
<span class="badge badge-warn"><span class="badge-dot"></span> {{ _('not_checked') }}</span>
|
||||
</div>
|
||||
<div id="naiveproxy-info" class="hidden">
|
||||
<div class="protocol-info" id="naiveproxy-info-grid"></div>
|
||||
</div>
|
||||
<div class="flex gap-sm" id="naiveproxy-actions">
|
||||
<button class="btn btn-primary btn-sm" onclick="openInstallModal('naiveproxy')" id="naiveproxy-install-btn"
|
||||
style="flex:1">
|
||||
{{ _('install') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- WireGuard Card -->
|
||||
<div class="card card-hover protocol-card protocol-wireguard" id="proto-wireguard">
|
||||
<div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:var(--space-sm);">
|
||||
@@ -657,6 +853,47 @@
|
||||
<div class="form-hint">{{ _('nginx_install_hint') }}</div>
|
||||
</div>
|
||||
|
||||
<div id="hysteriaOptions"
|
||||
style="display:none; padding: var(--space-md); background: rgba(0,0,0,0.03); border-radius: var(--radius-md); margin-bottom: var(--space-md);">
|
||||
<div class="form-hint" style="margin-bottom: var(--space-md); padding: var(--space-sm) var(--space-md); border-radius: var(--radius-sm); background: rgba(234,179,8,0.12); border: 1px solid rgba(234,179,8,0.35); color: var(--text);">
|
||||
{{ _('hysteria_ports_warning') }}
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">{{ _('port') }} (UDP) *</label>
|
||||
<input class="form-input" type="number" id="installHysteriaPort" value="8998" min="1" max="65535">
|
||||
<div class="form-hint">{{ _('hysteria_port_hint') }}</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">{{ _('hysteria_domain') }}</label>
|
||||
<input class="form-input" type="text" id="installHysteriaDomain" placeholder="vpn.example.com" oninput="updateHysteriaDnsHint()">
|
||||
<div class="form-hint" id="hysteriaDnsHint"></div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">{{ _('hysteria_email') }}</label>
|
||||
<input class="form-input" type="email" id="installHysteriaEmail" placeholder="admin@example.com">
|
||||
</div>
|
||||
<div class="form-hint">{{ _('hysteria_install_hint') }}</div>
|
||||
</div>
|
||||
|
||||
<div id="naiveproxyOptions"
|
||||
style="display:none; padding: var(--space-md); background: rgba(0,0,0,0.03); border-radius: var(--radius-md); margin-bottom: var(--space-md);">
|
||||
<div class="form-hint" style="margin-bottom: var(--space-md); padding: var(--space-sm) var(--space-md); border-radius: var(--radius-sm); background: rgba(234,179,8,0.12); border: 1px solid rgba(234,179,8,0.35); color: var(--text);">
|
||||
{{ _('naiveproxy_ports_warning') }}
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">{{ _('naiveproxy_domain') }}</label>
|
||||
<input class="form-input" type="text" id="installNaiveproxyDomain" placeholder="vpn.example.com" oninput="updateNaiveproxyDnsHint()">
|
||||
<div class="form-hint" id="naiveproxyDnsHint"></div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">{{ _('naiveproxy_email') }}</label>
|
||||
<input class="form-input" type="email" id="installNaiveproxyEmail" placeholder="admin@example.com">
|
||||
</div>
|
||||
<div class="form-hint">{{ _('naiveproxy_install_hint') }}</div>
|
||||
<div class="form-hint" style="margin-top: var(--space-sm);">{{ _('naiveproxy_port_hint') }}</div>
|
||||
<div class="form-hint" style="margin-top: var(--space-sm); padding: var(--space-sm) var(--space-md); border-radius: var(--radius-sm); background: rgba(234,179,8,0.12); border: 1px solid rgba(234,179,8,0.35);">{{ _('naiveproxy_client_hint') }}</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-footer">
|
||||
<button class="btn btn-secondary" onclick="closeModal('installModal')">{{ _('cancel') }}</button>
|
||||
<button class="btn btn-primary" onclick="installProtocol()" id="installBtn">
|
||||
@@ -711,6 +948,45 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== Hysteria Settings Modal ===== -->
|
||||
<div class="modal-backdrop" id="hysteriaSettingsModal">
|
||||
<div class="modal">
|
||||
<div class="modal-header">
|
||||
<h2 class="modal-title" id="hysteriaSettingsTitle">{{ _('hysteria_settings_title') }}</h2>
|
||||
<button class="modal-close" onclick="closeModal('hysteriaSettingsModal')">×</button>
|
||||
</div>
|
||||
<input type="hidden" id="hysteriaSetProto" value="hysteria" />
|
||||
<div class="form-hint" style="margin-bottom: var(--space-md); padding: var(--space-sm) var(--space-md); border-radius: var(--radius-sm); background: rgba(234,179,8,0.12); border: 1px solid rgba(234,179,8,0.35);">
|
||||
{{ _('hysteria_ports_warning') }}
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">{{ _('hysteria_domain') }}</label>
|
||||
<input class="form-input" type="text" id="hysteriaSetDomain" placeholder="vpn.example.com">
|
||||
<div class="form-hint">{{ _('hysteria_ssl_change_hint') }}</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">{{ _('hysteria_email') }}</label>
|
||||
<input class="form-input" type="email" id="hysteriaSetEmail" placeholder="admin@example.com">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">{{ _('port') }} (UDP)</label>
|
||||
<input class="form-input" type="number" id="hysteriaSetPort" min="1" max="65535" value="8998">
|
||||
<div class="form-hint">{{ _('hysteria_port_change_hint') }}</div>
|
||||
</div>
|
||||
<div class="modal-footer" style="flex-wrap: wrap; gap: var(--space-sm);">
|
||||
<button class="btn btn-secondary" onclick="closeModal('hysteriaSettingsModal')">{{ _('cancel') }}</button>
|
||||
<button class="btn btn-secondary" onclick="renewHysteriaSsl()" id="hysteriaRenewBtn">
|
||||
<span id="hysteriaRenewBtnText">{{ _('hysteria_renew_ssl') }}</span>
|
||||
<div class="spinner hidden" id="hysteriaRenewSpinner"></div>
|
||||
</button>
|
||||
<button class="btn btn-primary" onclick="saveHysteriaSettings()" id="hysteriaSaveBtn">
|
||||
<span id="hysteriaSaveBtnText">{{ _('save') }}</span>
|
||||
<div class="spinner hidden" id="hysteriaSaveSpinner"></div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== NGINX Site Modal ===== -->
|
||||
<div class="modal-backdrop" id="siteConfigModal">
|
||||
<div class="modal" style="max-width:680px;">
|
||||
@@ -859,6 +1135,7 @@
|
||||
<div class="config-panel active" id="panel-conf">
|
||||
<div class="config-display">
|
||||
<div class="config-text" id="configText"></div>
|
||||
<div class="form-hint hidden" id="configClientHint" style="margin-top: var(--space-sm);"></div>
|
||||
<div class="config-actions">
|
||||
<button class="btn btn-secondary btn-sm" onclick="copyToClipboard(currentConfig)" style="flex:1">
|
||||
{{ _('copy') }}
|
||||
@@ -961,12 +1238,16 @@
|
||||
<script>
|
||||
const SERVER_ID = {{ server_id }};
|
||||
const SERVER_HOST = "{{ server.host }}";
|
||||
const SERVER_SSL_DOMAIN = {{ ((server.server_info or {}).get('ssl_domain') or '') | tojson }};
|
||||
const SERVER_SSL_EMAIL = {{ ((server.server_info or {}).get('ssl_email') or '') | tojson }};
|
||||
const MARKETPLACE_APPS = [
|
||||
{ proto: 'awg2', category: 'protocols', icon: 'sparkles', title: 'AmneziaWG 2.0', descKey: 'awg_desc', badge: 'NEW' },
|
||||
{ proto: 'awg', category: 'protocols', icon: 'shield', title: 'AmneziaWG', descKey: 'awg_desc' },
|
||||
{ proto: 'awg_legacy', category: 'protocols', icon: 'radio', title: 'AmneziaWG Legacy', descKey: 'awg_legacy_desc' },
|
||||
{ proto: 'xray', category: 'protocols', icon: 'zap', title: 'Xray (VLESS-Reality)', descKey: 'xray_desc' },
|
||||
{ proto: 'telemt', category: 'protocols', icon: 'plane', title: 'Telemt (Telegram Proxy)', descKey: 'telemt_desc' },
|
||||
{ proto: 'hysteria', category: 'protocols', icon: 'refresh', title: 'Hysteria 2', descKey: 'hysteria_desc' },
|
||||
{ proto: 'naiveproxy', category: 'protocols', icon: 'link', title: 'NaiveProxy', descKey: 'naiveproxy_desc', badge: 'STABLE' },
|
||||
{ proto: 'wireguard', category: 'protocols', icon: 'lock', title: 'WireGuard', descKey: 'wireguard_desc' },
|
||||
{ proto: 'dns', category: 'services', icon: 'search', title: 'AmneziaDNS', descKey: 'dns_desc' },
|
||||
{ proto: 'adguard', category: 'services', icon: 'shield-check', title: 'AdGuard Home', descKey: 'adguard_desc' },
|
||||
@@ -1002,7 +1283,7 @@
|
||||
}
|
||||
|
||||
function isMultiInstanceBase(proto) {
|
||||
return ['awg', 'awg2', 'awg_legacy', 'xray', 'telemt', 'socks5'].includes(protoBase(proto));
|
||||
return ['awg', 'awg2', 'awg_legacy', 'xray', 'telemt', 'hysteria', 'socks5'].includes(protoBase(proto));
|
||||
}
|
||||
|
||||
function nextSuggestedPort(base, fallback) {
|
||||
@@ -1207,6 +1488,8 @@
|
||||
case 'awg_legacy': title = 'AmneziaWG Legacy'; break;
|
||||
case 'xray': title = 'Xray'; break;
|
||||
case 'telemt': title = 'Telemt'; break;
|
||||
case 'hysteria': title = 'Hysteria 2'; break;
|
||||
case 'naiveproxy': title = 'NaiveProxy'; break;
|
||||
case 'wireguard': title = 'WireGuard'; break;
|
||||
case 'dns': title = 'AmneziaDNS'; break;
|
||||
case 'socks5': title = 'SOCKS5 Proxy'; break;
|
||||
@@ -1266,7 +1549,7 @@
|
||||
|
||||
for (const [proto, info] of orderedProtocolEntries(data.protocols)) {
|
||||
updateProtocolCard(proto, info);
|
||||
const isVPN = ['awg', 'awg2', 'awg_legacy', 'xray', 'telemt', 'wireguard'].includes(protoBase(proto));
|
||||
const isVPN = ['awg', 'awg2', 'awg_legacy', 'xray', 'telemt', 'hysteria', 'naiveproxy', 'wireguard'].includes(protoBase(proto));
|
||||
if (info.container_running && isVPN) {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = proto;
|
||||
@@ -1293,6 +1576,7 @@
|
||||
}
|
||||
updateStatusCounts(data.protocols || {});
|
||||
showToast(_('server_check_complete'), 'success');
|
||||
loadCascade();
|
||||
} catch (err) {
|
||||
showToast(_('error') + ': ' + err.message, 'error');
|
||||
const statusDiv = document.getElementById('serverStatus');
|
||||
@@ -1494,7 +1778,13 @@
|
||||
if (isService) {
|
||||
grid = buildServiceInfoGrid(proto, info);
|
||||
} else if (info.port) {
|
||||
grid += `<div class="protocol-info-item"><span class="protocol-info-label">${_('port')}</span><span class="protocol-info-value">${info.port}/${(['xray', 'telemt'].includes(protoBase(proto))) ? 'TCP' : 'UDP'}</span></div>`;
|
||||
grid += `<div class="protocol-info-item"><span class="protocol-info-label">${_('port')}</span><span class="protocol-info-value">${info.port}/${(['xray', 'telemt', 'naiveproxy'].includes(protoBase(proto))) ? 'TCP' : 'UDP'}</span></div>`;
|
||||
if (protoBase(proto) === 'hysteria' && info.domain) {
|
||||
grid += `<div class="protocol-info-item"><span class="protocol-info-label">${_('hysteria_domain')}</span><span class="protocol-info-value">${info.domain}</span></div>`;
|
||||
}
|
||||
if (protoBase(proto) === 'naiveproxy' && info.domain) {
|
||||
grid += `<div class="protocol-info-item"><span class="protocol-info-label">${_('naiveproxy_domain')}</span><span class="protocol-info-value">${info.domain}</span></div>`;
|
||||
}
|
||||
}
|
||||
if (!isService && info.clients_count !== undefined) {
|
||||
grid += `<div class="protocol-info-item"><span class="protocol-info-label">${_('connections')}</span><span class="protocol-info-value">${info.clients_count}</span></div>`;
|
||||
@@ -1529,6 +1819,21 @@
|
||||
<button class="btn btn-secondary btn-sm" onclick="showProtocolBackups('${proto}')" style="flex:1">${_('backup')}</button>
|
||||
<button class="btn btn-danger btn-sm" onclick="uninstallProtocol('${proto}')">${_('uninstall')}</button>
|
||||
`;
|
||||
} else if (protoBase(proto) === 'hysteria') {
|
||||
actionsEl.innerHTML = `
|
||||
<button class="btn btn-secondary btn-sm" onclick="selectProtocolForConns('${proto}')" style="flex:1">${_('connections')}</button>
|
||||
<button class="btn btn-secondary btn-sm" onclick="openHysteriaSettings('${proto}')">${_('hysteria_change_port')}</button>
|
||||
<button class="btn btn-secondary btn-sm" onclick="showProtocolBackups('${proto}')">${_('backup')}</button>
|
||||
<button class="btn btn-danger btn-sm" onclick="uninstallProtocol('${proto}')">${_('uninstall')}</button>
|
||||
`;
|
||||
showConnectionsSection();
|
||||
} else if (protoBase(proto) === 'naiveproxy') {
|
||||
actionsEl.innerHTML = `
|
||||
<button class="btn btn-secondary btn-sm" onclick="selectProtocolForConns('${proto}')" style="flex:1">${_('connections')}</button>
|
||||
<button class="btn btn-secondary btn-sm" onclick="showProtocolBackups('${proto}')">${_('backup')}</button>
|
||||
<button class="btn btn-danger btn-sm" onclick="uninstallProtocol('${proto}')">${_('uninstall')}</button>
|
||||
`;
|
||||
showConnectionsSection();
|
||||
} else {
|
||||
actionsEl.innerHTML = `
|
||||
<button class="btn btn-secondary btn-sm" onclick="selectProtocolForConns('${proto}')" style="flex:1">${_('connections')}</button>
|
||||
@@ -1565,6 +1870,7 @@
|
||||
} else if (info.container_exists) {
|
||||
installedProtocols[proto] = true;
|
||||
const errText = String(info.error || '').trim();
|
||||
const portBusy = !!info.port_busy || /address already in use|UDP port \d+ already in use|already in use/i.test(errText);
|
||||
statusEl.innerHTML = errText
|
||||
? `<span class="badge badge-danger" style="max-width:100%; white-space:normal; text-align:left; line-height:1.35;"><span class="badge-dot"></span> ${_('stop')}: ${escapeHtml(errText.slice(0, 120))}</span>`
|
||||
: `<span class="badge badge-danger"><span class="badge-dot"></span> ${_('stop')}</span>`;
|
||||
@@ -1583,6 +1889,25 @@
|
||||
if (errText) {
|
||||
grid += `<div class="protocol-info-item" style="grid-column:1/-1;"><span class="protocol-info-label">${_('error')}</span><span class="protocol-info-value" style="color:var(--danger); word-break:break-word;">${escapeHtml(errText)}</span></div>`;
|
||||
}
|
||||
if (protoBase(proto) === 'hysteria') {
|
||||
const curPort = parseInt(info.port, 10) || 443;
|
||||
const suggest = (curPort === 443 || portBusy) ? 8998 : curPort;
|
||||
grid += `
|
||||
<div class="protocol-info-item" style="grid-column:1/-1; display:block; padding-top:8px;">
|
||||
<span class="protocol-info-label" style="display:block; margin-bottom:6px;">${_('hysteria_change_port')} (UDP)</span>
|
||||
<div style="display:flex; gap:8px; flex-wrap:wrap; align-items:center;">
|
||||
<input class="form-input" type="number" id="hysteriaInlinePort-${protoDomKey(proto)}"
|
||||
value="${suggest}" min="1" max="65535" style="width:120px; flex:0 0 auto;">
|
||||
<button class="btn btn-primary btn-sm" type="button"
|
||||
onclick="applyHysteriaPort('${proto}', document.getElementById('hysteriaInlinePort-${protoDomKey(proto)}').value)">
|
||||
${_('save')} & ${_('start_btn')}
|
||||
</button>
|
||||
<button class="btn btn-secondary btn-sm" type="button" onclick="openHysteriaSettings('${proto}')">${_('hysteria_settings_title')}</button>
|
||||
</div>
|
||||
<div class="form-hint" style="margin-top:6px;">${_('hysteria_port_change_hint')}</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
infoGrid.innerHTML = grid;
|
||||
}
|
||||
if (isService) {
|
||||
@@ -1592,6 +1917,13 @@
|
||||
<button class="btn btn-secondary btn-sm" onclick="showProtocolBackups('${proto}')">${_('backup')}</button>
|
||||
<button class="btn btn-danger btn-sm" onclick="uninstallProtocol('${proto}')">${_('uninstall')}</button>
|
||||
`;
|
||||
} else if (protoBase(proto) === 'hysteria') {
|
||||
actionsEl.innerHTML = `
|
||||
<button class="btn btn-primary btn-sm" onclick="openHysteriaSettings('${proto}')" style="flex:1">${_('hysteria_change_port')}</button>
|
||||
<button class="btn btn-secondary btn-sm" onclick="showContainerLogs('${proto}')">${_('logs_btn')}</button>
|
||||
<button class="btn btn-secondary btn-sm" onclick="openInstallModal('${proto}')">${_('reinstall')}</button>
|
||||
<button class="btn btn-danger btn-sm" onclick="uninstallProtocol('${proto}')">${_('uninstall')}</button>
|
||||
`;
|
||||
} else {
|
||||
actionsEl.innerHTML = `
|
||||
<button class="btn btn-primary btn-sm" onclick="openInstallModal('${proto}')" style="flex:1">${_('reinstall')}</button>
|
||||
@@ -1872,6 +2204,22 @@
|
||||
hint.innerHTML = `${_('nginx_dns_hint')} <code>A ${domain} ${SERVER_HOST}</code>`;
|
||||
}
|
||||
|
||||
function updateHysteriaDnsHint() {
|
||||
const input = document.getElementById('installHysteriaDomain');
|
||||
const hint = document.getElementById('hysteriaDnsHint');
|
||||
if (!input || !hint) return;
|
||||
const domain = (input.value || '').trim() || 'vpn.example.com';
|
||||
hint.innerHTML = `${_('hysteria_dns_hint')} <code>A ${domain} ${SERVER_HOST}</code>`;
|
||||
}
|
||||
|
||||
function updateNaiveproxyDnsHint() {
|
||||
const input = document.getElementById('installNaiveproxyDomain');
|
||||
const hint = document.getElementById('naiveproxyDnsHint');
|
||||
if (!input || !hint) return;
|
||||
const domain = (input.value || '').trim() || 'vpn.example.com';
|
||||
hint.innerHTML = `${_('naiveproxy_dns_hint')} <code>A ${domain} ${SERVER_HOST}</code>`;
|
||||
}
|
||||
|
||||
function openInstallModal(proto, installAnother = false) {
|
||||
const base = protoBase(proto);
|
||||
currentInstallProto = installAnother ? base : proto;
|
||||
@@ -1887,11 +2235,15 @@
|
||||
const socks5Opts = document.getElementById('socks5Options');
|
||||
const adguardOpts = document.getElementById('adguardOptions');
|
||||
const nginxOpts = document.getElementById('nginxOptions');
|
||||
const hysteriaOpts = document.getElementById('hysteriaOptions');
|
||||
const naiveproxyOpts = document.getElementById('naiveproxyOptions');
|
||||
|
||||
telemtOpts.style.display = 'none';
|
||||
socks5Opts.style.display = 'none';
|
||||
adguardOpts.style.display = 'none';
|
||||
nginxOpts.style.display = 'none';
|
||||
hysteriaOpts.style.display = 'none';
|
||||
if (naiveproxyOpts) naiveproxyOpts.style.display = 'none';
|
||||
if (portGroup) portGroup.style.display = '';
|
||||
|
||||
if (base === 'dns') {
|
||||
@@ -1928,7 +2280,37 @@
|
||||
portInput.disabled = false;
|
||||
portHint.textContent = _('nginx_port_hint');
|
||||
nginxOpts.style.display = 'block';
|
||||
const nxDomain = document.getElementById('installNginxDomain');
|
||||
const nxEmail = document.getElementById('installNginxEmail');
|
||||
if (nxDomain && !nxDomain.value && SERVER_SSL_DOMAIN) nxDomain.value = SERVER_SSL_DOMAIN;
|
||||
if (nxEmail && !nxEmail.value && SERVER_SSL_EMAIL) nxEmail.value = SERVER_SSL_EMAIL;
|
||||
updateNginxDnsHint();
|
||||
} else if (base === 'hysteria') {
|
||||
if (portGroup) portGroup.style.display = 'none';
|
||||
const suggested = currentInstallAnother ? nextSuggestedPort(currentInstallProto, 8998) : '8998';
|
||||
portInput.value = suggested;
|
||||
portInput.disabled = false;
|
||||
hysteriaOpts.style.display = 'block';
|
||||
const hyPort = document.getElementById('installHysteriaPort');
|
||||
if (hyPort) {
|
||||
hyPort.value = suggested;
|
||||
hyPort.oninput = () => { portInput.value = hyPort.value; };
|
||||
}
|
||||
const hyDomain = document.getElementById('installHysteriaDomain');
|
||||
const hyEmail = document.getElementById('installHysteriaEmail');
|
||||
if (hyDomain && !hyDomain.value && SERVER_SSL_DOMAIN) hyDomain.value = SERVER_SSL_DOMAIN;
|
||||
if (hyEmail && !hyEmail.value && SERVER_SSL_EMAIL) hyEmail.value = SERVER_SSL_EMAIL;
|
||||
updateHysteriaDnsHint();
|
||||
} else if (base === 'naiveproxy') {
|
||||
if (portGroup) portGroup.style.display = 'none';
|
||||
portInput.value = '443';
|
||||
portInput.disabled = false;
|
||||
if (naiveproxyOpts) naiveproxyOpts.style.display = 'block';
|
||||
const npDomain = document.getElementById('installNaiveproxyDomain');
|
||||
const npEmail = document.getElementById('installNaiveproxyEmail');
|
||||
if (npDomain && !npDomain.value && SERVER_SSL_DOMAIN) npDomain.value = SERVER_SSL_DOMAIN;
|
||||
if (npEmail && !npEmail.value && SERVER_SSL_EMAIL) npEmail.value = SERVER_SSL_EMAIL;
|
||||
updateNaiveproxyDnsHint();
|
||||
} else {
|
||||
portLabel.textContent = _('port') + ' (UDP)';
|
||||
portInput.value = currentInstallAnother ? nextSuggestedPort(currentInstallProto, 55424) : '55424';
|
||||
@@ -1995,6 +2377,17 @@
|
||||
} else if (protoBase(currentInstallProto) === 'nginx') {
|
||||
params.nginx_domain = document.getElementById('installNginxDomain').value.trim();
|
||||
params.nginx_email = document.getElementById('installNginxEmail').value.trim();
|
||||
} else if (protoBase(currentInstallProto) === 'hysteria') {
|
||||
const hyPortEl = document.getElementById('installHysteriaPort');
|
||||
if (hyPortEl && hyPortEl.value) {
|
||||
params.port = hyPortEl.value;
|
||||
}
|
||||
params.hysteria_domain = document.getElementById('installHysteriaDomain').value.trim();
|
||||
params.hysteria_email = document.getElementById('installHysteriaEmail').value.trim();
|
||||
} else if (protoBase(currentInstallProto) === 'naiveproxy') {
|
||||
params.port = '443';
|
||||
params.naiveproxy_domain = document.getElementById('installNaiveproxyDomain').value.trim();
|
||||
params.naiveproxy_email = document.getElementById('installNaiveproxyEmail').value.trim();
|
||||
}
|
||||
const result = await apiCall(`/api/servers/${SERVER_ID}/install`, 'POST', params);
|
||||
clearInterval(progressInterval);
|
||||
@@ -2210,6 +2603,107 @@
|
||||
}
|
||||
}
|
||||
|
||||
// ========== Hysteria Settings (port) ==========
|
||||
async function applyHysteriaPort(proto, portValue) {
|
||||
const port = parseInt(portValue, 10);
|
||||
if (!port || port < 1 || port > 65535) {
|
||||
showToast(_('error') + ': invalid port', 'error');
|
||||
return;
|
||||
}
|
||||
if (port === 80) {
|
||||
showToast(_('error') + ': port 80 reserved', 'error');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
showToast(_('saving') || 'Saving...', 'info');
|
||||
const res = await apiCall(`/api/servers/${SERVER_ID}/hysteria/settings`, 'POST', {
|
||||
protocol: proto || 'hysteria', port,
|
||||
});
|
||||
showToast(res.message || _('hysteria_settings_saved'), 'success');
|
||||
setTimeout(() => checkServer(), 800);
|
||||
} catch (err) {
|
||||
showToast(_('error') + ': ' + err.message, 'error');
|
||||
openHysteriaSettings(proto);
|
||||
}
|
||||
}
|
||||
|
||||
async function openHysteriaSettings(proto = 'hysteria') {
|
||||
const live = currentProtocolStatus[proto] || {};
|
||||
const livePort = live.port || 443;
|
||||
const suggest = (parseInt(livePort, 10) === 443) ? 8998 : (livePort || 8998);
|
||||
document.getElementById('hysteriaSetProto').value = proto;
|
||||
document.getElementById('hysteriaSettingsTitle').textContent =
|
||||
`${_('hysteria_settings_title')} — ${getProtoTitle(proto)}`;
|
||||
document.getElementById('hysteriaSetDomain').value = live.domain || SERVER_SSL_DOMAIN || '';
|
||||
document.getElementById('hysteriaSetEmail').value = live.email || SERVER_SSL_EMAIL || '';
|
||||
document.getElementById('hysteriaSetPort').value = suggest;
|
||||
openModal('hysteriaSettingsModal');
|
||||
try {
|
||||
const data = await apiCall(`/api/servers/${SERVER_ID}/hysteria/settings?protocol=${encodeURIComponent(proto)}`);
|
||||
if (data.domain) document.getElementById('hysteriaSetDomain').value = data.domain;
|
||||
if (data.email) document.getElementById('hysteriaSetEmail').value = data.email;
|
||||
const p = parseInt(data.port, 10);
|
||||
if (p && p !== 443) document.getElementById('hysteriaSetPort').value = p;
|
||||
else if (p === 443) document.getElementById('hysteriaSetPort').value = 8998;
|
||||
} catch (_) { /* modal already open with local values */ }
|
||||
}
|
||||
|
||||
async function saveHysteriaSettings(opts = {}) {
|
||||
const btn = document.getElementById('hysteriaSaveBtn');
|
||||
const text = document.getElementById('hysteriaSaveBtnText');
|
||||
const spinner = document.getElementById('hysteriaSaveSpinner');
|
||||
const renewBtn = document.getElementById('hysteriaRenewBtn');
|
||||
const renewText = document.getElementById('hysteriaRenewBtnText');
|
||||
const renewSpinner = document.getElementById('hysteriaRenewSpinner');
|
||||
const proto = document.getElementById('hysteriaSetProto').value || 'hysteria';
|
||||
const port = parseInt(document.getElementById('hysteriaSetPort').value, 10);
|
||||
const domain = document.getElementById('hysteriaSetDomain').value.trim();
|
||||
const email = document.getElementById('hysteriaSetEmail').value.trim();
|
||||
const renewSsl = !!opts.renew_ssl;
|
||||
if (!port || port < 1 || port > 65535) {
|
||||
showToast(_('error') + ': invalid port', 'error');
|
||||
return;
|
||||
}
|
||||
if (port === 80) {
|
||||
showToast(_('error') + ': port 80 reserved', 'error');
|
||||
return;
|
||||
}
|
||||
if ((renewSsl || domain) && (!domain || !email)) {
|
||||
showToast(_('error') + ': ' + _('hysteria_ssl_required'), 'error');
|
||||
return;
|
||||
}
|
||||
btn.disabled = true;
|
||||
if (renewBtn) renewBtn.disabled = true;
|
||||
if (renewSsl) {
|
||||
renewText.textContent = _('saving') || 'Saving...';
|
||||
renewSpinner.classList.remove('hidden');
|
||||
} else {
|
||||
text.textContent = _('saving') || 'Saving...';
|
||||
spinner.classList.remove('hidden');
|
||||
}
|
||||
try {
|
||||
const res = await apiCall(`/api/servers/${SERVER_ID}/hysteria/settings`, 'POST', {
|
||||
protocol: proto, port, domain, email, renew_ssl: renewSsl,
|
||||
});
|
||||
showToast(res.message || _('hysteria_settings_saved'), 'success');
|
||||
closeModal('hysteriaSettingsModal');
|
||||
setTimeout(() => checkServer(), 800);
|
||||
} catch (err) {
|
||||
showToast(_('error') + ': ' + err.message, 'error');
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
if (renewBtn) renewBtn.disabled = false;
|
||||
text.textContent = _('save');
|
||||
spinner.classList.add('hidden');
|
||||
if (renewText) renewText.textContent = _('hysteria_renew_ssl');
|
||||
if (renewSpinner) renewSpinner.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
async function renewHysteriaSsl() {
|
||||
return saveHysteriaSettings({ renew_ssl: true });
|
||||
}
|
||||
|
||||
// ========== SOCKS5 Settings ==========
|
||||
async function openSocks5Settings(proto = 'socks5') {
|
||||
currentSocks5Proto = proto || 'socks5';
|
||||
@@ -2294,7 +2788,7 @@
|
||||
const sent = userData.dataSent || '';
|
||||
const initial = name.charAt(0).toUpperCase();
|
||||
const enabled = (client.enabled !== undefined) ? client.enabled : (userData.enabled !== false);
|
||||
const hasPrivKey = !!userData.clientPrivateKey || proto === 'xray' || proto === 'telemt';
|
||||
const hasPrivKey = !!userData.clientPrivateKey || proto === 'xray' || proto === 'telemt' || protoBase(proto) === 'hysteria' || protoBase(proto) === 'naiveproxy';
|
||||
const assignedUser = client.assigned_user || '';
|
||||
|
||||
let metaHtml = '';
|
||||
@@ -2332,7 +2826,7 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="client-actions">
|
||||
<button class="btn btn-secondary btn-sm btn-icon" onclick="showConnectionConfig('${escapeJs(client.clientId)}', '${escapeJs(name)}', ${!!userData.clientPrivateKey || proto === 'xray' || proto === 'telemt'})" title="${_('config')}">${uiIcon('file')}</button>
|
||||
<button class="btn btn-secondary btn-sm btn-icon" onclick="showConnectionConfig('${escapeJs(client.clientId)}', '${escapeJs(name)}', ${!!userData.clientPrivateKey || proto === 'xray' || proto === 'telemt' || protoBase(proto) === 'hysteria' || protoBase(proto) === 'naiveproxy'})" title="${_('config')}">${uiIcon('file')}</button>
|
||||
${proto === 'telemt' ? `<button class="btn btn-secondary btn-sm btn-icon" onclick="editConnection('${escapeJs(client.clientId)}')" title="${_('edit')}">${uiIcon('pencil')}</button>` : ''}
|
||||
<button class="btn btn-secondary btn-sm btn-icon" onclick="toggleConnection('${escapeJs(client.clientId)}', ${!enabled})" title="${toggleTitle}">${toggleIcon}</button>
|
||||
<button class="btn btn-danger btn-sm btn-icon" onclick="removeConnection('${escapeJs(client.clientId)}')" title="${_('delete')}">${uiIcon('trash')}</button>
|
||||
@@ -2384,8 +2878,8 @@
|
||||
document.getElementById('configModalTitle').textContent = `${_('config')} — ${connName}`;
|
||||
document.getElementById('configText').textContent = result.config;
|
||||
document.getElementById('vpnLinkText').textContent = currentVpnLink;
|
||||
document.getElementById('panel-vpn').style.display = (proto === 'telemt' ? 'none' : '');
|
||||
document.querySelectorAll('.config-tab')[1].style.display = (proto === 'telemt' ? 'none' : '');
|
||||
document.getElementById('panel-vpn').style.display = (proto === 'telemt' || protoBase(proto) === 'hysteria' || protoBase(proto) === 'naiveproxy' ? 'none' : '');
|
||||
document.querySelectorAll('.config-tab')[1].style.display = (proto === 'telemt' || protoBase(proto) === 'hysteria' || protoBase(proto) === 'naiveproxy' ? 'none' : '');
|
||||
switchConfigTab('conf');
|
||||
openModal('configModal');
|
||||
generateQR(result.config);
|
||||
@@ -2463,9 +2957,9 @@
|
||||
const proto = document.getElementById('connProtoSelect').value;
|
||||
|
||||
// Restore tabs visibility first
|
||||
document.getElementById('panel-vpn').style.display = (proto === 'telemt' ? 'none' : '');
|
||||
document.getElementById('panel-vpn').style.display = (proto === 'telemt' || protoBase(proto) === 'hysteria' || protoBase(proto) === 'naiveproxy' ? 'none' : '');
|
||||
document.getElementById('panel-qr').style.display = '';
|
||||
document.querySelectorAll('.config-tab')[1].style.display = (proto === 'telemt' ? 'none' : '');
|
||||
document.querySelectorAll('.config-tab')[1].style.display = (proto === 'telemt' || protoBase(proto) === 'hysteria' || protoBase(proto) === 'naiveproxy' ? 'none' : '');
|
||||
document.querySelectorAll('.config-tab')[2].style.display = '';
|
||||
|
||||
// Client was created via native Amnezia app — private key is not stored server-side
|
||||
@@ -2497,6 +2991,16 @@
|
||||
document.getElementById('configModalTitle').textContent = `${_('config')} — ${connName}`;
|
||||
document.getElementById('configText').textContent = result.config;
|
||||
document.getElementById('vpnLinkText').textContent = currentVpnLink;
|
||||
const hintEl = document.getElementById('configClientHint');
|
||||
if (hintEl) {
|
||||
if (protoBase(proto) === 'naiveproxy') {
|
||||
hintEl.textContent = _('naiveproxy_client_hint');
|
||||
hintEl.classList.remove('hidden');
|
||||
} else {
|
||||
hintEl.textContent = '';
|
||||
hintEl.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
switchConfigTab('conf');
|
||||
openModal('configModal');
|
||||
generateQR(result.config);
|
||||
@@ -2609,8 +3113,185 @@
|
||||
}
|
||||
|
||||
|
||||
|
||||
// ========== Cascade (double VPN) ==========
|
||||
const CASCADE_PROTOS = ['awg2', 'awg', 'awg_legacy', 'wireguard'];
|
||||
|
||||
function fillCascadeExitProtocols() {
|
||||
const sel = document.getElementById('cascadeExitServer');
|
||||
const opt = sel.options[sel.selectedIndex];
|
||||
const protoSel = document.getElementById('cascadeExitProtocol');
|
||||
const raw = (opt && opt.dataset.protocols) ? opt.dataset.protocols.split(',').filter(Boolean) : [];
|
||||
const available = raw.filter(p => CASCADE_PROTOS.includes(protoBase(p)));
|
||||
const prev = protoSel.value;
|
||||
protoSel.innerHTML = '';
|
||||
const list = available.length ? available : CASCADE_PROTOS;
|
||||
list.forEach(p => {
|
||||
const o = document.createElement('option');
|
||||
o.value = p;
|
||||
o.textContent = getProtoTitle(p);
|
||||
protoSel.appendChild(o);
|
||||
});
|
||||
if (list.includes(prev)) protoSel.value = prev;
|
||||
else if (list.includes('awg2')) protoSel.value = 'awg2';
|
||||
}
|
||||
|
||||
function setCascadeBusy(on, text) {
|
||||
const busy = document.getElementById('cascadeBusy');
|
||||
const busyText = document.getElementById('cascadeBusyText');
|
||||
const en = document.getElementById('cascadeEnableBtn');
|
||||
const dis = document.getElementById('cascadeDisableBtn');
|
||||
if (busyText && text) busyText.textContent = text;
|
||||
if (busy) {
|
||||
busy.classList.toggle('hidden', !on);
|
||||
busy.style.display = on ? 'flex' : 'none';
|
||||
}
|
||||
if (en) en.disabled = !!on;
|
||||
if (dis) dis.disabled = !!on;
|
||||
}
|
||||
|
||||
function cascadeBool(id, fallback) {
|
||||
const el = document.getElementById(id);
|
||||
return el ? !!el.checked : !!fallback;
|
||||
}
|
||||
|
||||
function cascadeNum(id, fallback) {
|
||||
const el = document.getElementById(id);
|
||||
const n = el ? parseInt(el.value, 10) : NaN;
|
||||
return Number.isFinite(n) ? n : fallback;
|
||||
}
|
||||
|
||||
function collectCascadeSettings() {
|
||||
return {
|
||||
pin_exit_route: cascadeBool('cascadePinExitRoute', true),
|
||||
remove_eth_masquerade: cascadeBool('cascadeRemoveEthMasq', true),
|
||||
force_forward: cascadeBool('cascadeForceForward', true),
|
||||
mss_clamp: cascadeBool('cascadeMssClamp', true),
|
||||
wait_handshake: cascadeBool('cascadeWaitHandshake', true),
|
||||
verify_egress: cascadeBool('cascadeVerifyEgress', true),
|
||||
keep_exit_dns: cascadeBool('cascadeKeepExitDns', false),
|
||||
handshake_timeout_sec: cascadeNum('cascadeHandshakeTimeout', 25),
|
||||
table_id: cascadeNum('cascadeTableId', 200),
|
||||
rule_priority: cascadeNum('cascadeRulePriority', 100),
|
||||
allowed_ips: (document.getElementById('cascadeAllowedIps') || {}).value || '0.0.0.0/0',
|
||||
vpn_subnet_override: (document.getElementById('cascadeVpnSubnet') || {}).value || '',
|
||||
};
|
||||
}
|
||||
|
||||
function applyCascadeSettingsToForm(settings, defaults) {
|
||||
const s = Object.assign({}, defaults || {}, settings || {});
|
||||
const setCheck = (id, val) => { const el = document.getElementById(id); if (el) el.checked = !!val; };
|
||||
const setVal = (id, val) => { const el = document.getElementById(id); if (el && val !== undefined && val !== null) el.value = val; };
|
||||
setCheck('cascadePinExitRoute', s.pin_exit_route !== false);
|
||||
setCheck('cascadeRemoveEthMasq', s.remove_eth_masquerade !== false);
|
||||
setCheck('cascadeForceForward', s.force_forward !== false);
|
||||
setCheck('cascadeMssClamp', s.mss_clamp !== false);
|
||||
setCheck('cascadeWaitHandshake', s.wait_handshake !== false);
|
||||
setCheck('cascadeVerifyEgress', s.verify_egress !== false);
|
||||
setCheck('cascadeKeepExitDns', !!s.keep_exit_dns);
|
||||
setVal('cascadeHandshakeTimeout', s.handshake_timeout_sec ?? 25);
|
||||
setVal('cascadeTableId', s.table_id ?? 200);
|
||||
setVal('cascadeRulePriority', s.rule_priority ?? 100);
|
||||
setVal('cascadeAllowedIps', s.allowed_ips || '0.0.0.0/0');
|
||||
setVal('cascadeVpnSubnet', s.vpn_subnet_override || '');
|
||||
}
|
||||
|
||||
function updateCascadeDiag(cascade, live) {
|
||||
const box = document.getElementById('cascadeDiagBox');
|
||||
if (!box) return;
|
||||
const parts = [];
|
||||
if (cascade && cascade.enabled) {
|
||||
parts.push('handshake: ' + ((live && live.handshake) || cascade.handshake ? 'ok' : 'NONE'));
|
||||
if (cascade.diagnostics) parts.push(String(cascade.diagnostics).trim());
|
||||
else if (live && live.raw) parts.push(String(live.raw).trim());
|
||||
if (cascade.last_error) parts.push('error: ' + cascade.last_error);
|
||||
}
|
||||
const text = parts.filter(Boolean).join('\n\n');
|
||||
box.textContent = text;
|
||||
box.classList.toggle('hidden', !text);
|
||||
}
|
||||
|
||||
function updateCascadeBadge(cascade, live) {
|
||||
const badge = document.getElementById('cascadeStatusBadge');
|
||||
if (!badge) return;
|
||||
const enabled = !!(cascade && cascade.enabled);
|
||||
const up = !!(live && live.up);
|
||||
const hs = !!(live && live.handshake) || !!(cascade && cascade.handshake);
|
||||
badge.className = 'badge ' + (enabled && up && hs ? 'badge-success' : (enabled ? 'badge-warn' : 'badge-warn'));
|
||||
if (!enabled) badge.textContent = _('cascade_off');
|
||||
else if (up && hs) badge.textContent = _('cascade_on');
|
||||
else if (up && !hs) badge.textContent = _('cascade_no_handshake');
|
||||
else badge.textContent = _('cascade_configured_down');
|
||||
updateCascadeDiag(cascade, live);
|
||||
}
|
||||
|
||||
async function loadCascade() {
|
||||
try {
|
||||
const res = await apiCall(`/api/servers/${SERVER_ID}/cascade`, 'POST', {});
|
||||
const c = res.cascade || {};
|
||||
if (c.entry_protocol) document.getElementById('cascadeEntryProtocol').value = c.entry_protocol;
|
||||
if (c.exit_server_id !== undefined && c.exit_server_id !== null && c.exit_server_id !== '') {
|
||||
document.getElementById('cascadeExitServer').value = String(c.exit_server_id);
|
||||
fillCascadeExitProtocols();
|
||||
}
|
||||
if (c.exit_protocol) {
|
||||
const exitProto = document.getElementById('cascadeExitProtocol');
|
||||
if ([...exitProto.options].some(o => o.value === c.exit_protocol)) {
|
||||
exitProto.value = c.exit_protocol;
|
||||
}
|
||||
}
|
||||
applyCascadeSettingsToForm(c.settings || {}, res.defaults || {});
|
||||
updateCascadeBadge(c, res.live || {});
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async function setupCascade(enable) {
|
||||
const entryProtocol = document.getElementById('cascadeEntryProtocol').value;
|
||||
const exitServerId = document.getElementById('cascadeExitServer').value;
|
||||
const exitProtocol = document.getElementById('cascadeExitProtocol').value;
|
||||
if (enable && exitServerId === '') {
|
||||
showToast(_('cascade_exit_required'), 'error');
|
||||
return;
|
||||
}
|
||||
if (enable && !confirm(_('cascade_enable_confirm'))) return;
|
||||
if (!enable && !confirm(_('cascade_disable_confirm'))) return;
|
||||
|
||||
setCascadeBusy(true, enable ? _('cascade_working') : _('cascade_disabling'));
|
||||
showToast(enable ? _('cascade_working') : _('cascade_disabling'), 'info');
|
||||
try {
|
||||
const settings = collectCascadeSettings();
|
||||
const res = await apiCall(`/api/servers/${SERVER_ID}/cascade/setup`, 'POST', {
|
||||
enabled: !!enable,
|
||||
entry_protocol: entryProtocol,
|
||||
exit_server_id: parseInt(exitServerId || '0', 10),
|
||||
exit_protocol: exitProtocol,
|
||||
...settings,
|
||||
});
|
||||
updateCascadeBadge(res.cascade || {}, {
|
||||
up: !!(res.cascade && res.cascade.up),
|
||||
handshake: !!(res.cascade && res.cascade.handshake),
|
||||
});
|
||||
showToast(enable ? _('cascade_enabled') : _('cascade_disabled'), 'success');
|
||||
if (enable && res.warning) {
|
||||
showToast(res.warning, 'info');
|
||||
}
|
||||
await loadCascade();
|
||||
} catch (err) {
|
||||
showToast(_('error') + ': ' + err.message, 'error');
|
||||
} finally {
|
||||
setCascadeBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
function enableCascade() { return setupCascade(true); }
|
||||
function disableCascade() { return setupCascade(false); }
|
||||
|
||||
// ========== Init ==========
|
||||
applyInstalledAppsVisibility();
|
||||
fillCascadeExitProtocols();
|
||||
loadCascade();
|
||||
checkServer();
|
||||
loadServerStats();
|
||||
</script>
|
||||
|
||||
+94
-28
@@ -110,21 +110,26 @@
|
||||
<div id="guestCreateFields"
|
||||
style="{% if not settings.guest.allow_create %}display:none;{% endif %} background: var(--bg-primary); padding: var(--space-md); border-radius: var(--radius-md);">
|
||||
<div class="form-group">
|
||||
<label class="form-label">{{ _('protocol_label') }}</label>
|
||||
<select class="form-select" id="guest_create_protocol" onchange="updateGuestCreateFields()">
|
||||
<option value="xui" {% if settings.guest.create_protocol == 'xui' %}selected{% endif %}>3x-ui VLESS</option>
|
||||
{% for s in servers %}
|
||||
{% set server_idx = loop.index0 %}
|
||||
{% for key, info in (s.protocols or {}).items() %}
|
||||
{% if info.installed and key.split('__')[0] in ['awg','awg2','awg_legacy','xray','wireguard','telemt'] %}
|
||||
<option value="{{ key }}|{{ server_idx }}"
|
||||
{% if settings.guest.create_protocol == key and settings.guest.create_server_id == server_idx %}selected{% endif %}>
|
||||
{{ s.name or s.host }} — {{ key }}
|
||||
</option>
|
||||
<label class="form-label">{{ _('server_label') }}</label>
|
||||
<select class="form-select" id="guest_create_server" onchange="fillGuestProtocols()">
|
||||
{% if xui_servers %}
|
||||
<option value="xui" {% if settings.guest.create_protocol == 'xui' %}selected{% endif %}>3x-ui</option>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
{% for s in servers %}
|
||||
<option value="{{ loop.index0 }}"
|
||||
{% if settings.guest.create_protocol != 'xui' and settings.guest.create_server_id == loop.index0 %}selected{% endif %}>
|
||||
{{ s.name or s.host }} ({{ s.host }})
|
||||
</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
<div class="form-hint">{{ _('server_then_protocol_hint') }}</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">{{ _('protocol_label') }}</label>
|
||||
<select class="form-select" id="guest_create_protocol" onchange="updateGuestCreateFields()">
|
||||
<!-- filled by JS -->
|
||||
</select>
|
||||
<input type="hidden" id="guest_create_protocol_pref" value="{{ settings.guest.create_protocol or '' }}">
|
||||
</div>
|
||||
<div class="form-group" id="guestInboundGroup" style="{% if settings.guest.create_protocol != 'xui' %}display:none;{% endif %}">
|
||||
<label class="form-label">{{ _('xui_server_select_label') }}</label>
|
||||
@@ -597,7 +602,7 @@
|
||||
<span id="checkUpdateBtnText">🔄 {{ _('check_updates') }}</span>
|
||||
<div class="spinner hidden" id="checkUpdateSpinner" style="width:14px; height:14px;"></div>
|
||||
</button>
|
||||
<a href="https://github.com/PRVTPRO/Amnezia-Web-Panel/releases" target="_blank" class="btn btn-primary hidden" id="downloadUpdateBtn" style="flex:1; text-decoration: none; justify-content: center;">
|
||||
<a href="https://git.evilfox.cc/test2/Amnezia-Web-Panel-main/releases" target="_blank" class="btn btn-primary hidden" id="downloadUpdateBtn" style="flex:1; text-decoration: none; justify-content: center;">
|
||||
⬇️ {{ _('download_update') }}
|
||||
</a>
|
||||
</div>
|
||||
@@ -1275,13 +1280,14 @@
|
||||
|
||||
let createProtocol = 'xui';
|
||||
let createServerId = 0;
|
||||
const guestProtoRaw = document.getElementById('guest_create_protocol').value;
|
||||
if (guestProtoRaw === 'xui') {
|
||||
const guestServerVal = document.getElementById('guest_create_server')?.value || 'xui';
|
||||
const guestProtoVal = document.getElementById('guest_create_protocol')?.value || '';
|
||||
if (guestServerVal === 'xui' || guestProtoVal === 'xui') {
|
||||
createProtocol = 'xui';
|
||||
} else if (guestProtoRaw.includes('|')) {
|
||||
const parts = guestProtoRaw.split('|');
|
||||
createProtocol = parts[0];
|
||||
createServerId = parseInt(parts[1] || '0');
|
||||
createServerId = 0;
|
||||
} else {
|
||||
createProtocol = guestProtoVal;
|
||||
createServerId = parseInt(guestServerVal || '0', 10) || 0;
|
||||
}
|
||||
|
||||
const guest = {
|
||||
@@ -1314,6 +1320,70 @@
|
||||
}
|
||||
}
|
||||
|
||||
const guestServersData = {{ servers | default([]) | tojson }};
|
||||
const VPN_PROTO_ORDER = ['awg2', 'awg', 'awg_legacy', 'wireguard', 'xray', 'telemt', 'hysteria', 'naiveproxy'];
|
||||
const PROTO_TITLES = {
|
||||
awg2: 'AmneziaWG 2.0',
|
||||
awg: 'AmneziaWG',
|
||||
awg_legacy: 'AWG Legacy',
|
||||
wireguard: 'WireGuard',
|
||||
xray: 'Xray (VLESS-Reality)',
|
||||
telemt: 'Telemt',
|
||||
hysteria: 'Hysteria 2',
|
||||
naiveproxy: 'NaiveProxy',
|
||||
xui: '3x-ui VLESS',
|
||||
};
|
||||
function protoTitle(key) {
|
||||
const raw = String(key || '');
|
||||
const base = raw.split('__')[0];
|
||||
const title = PROTO_TITLES[base] || base.toUpperCase();
|
||||
const m = raw.match(/__(\d+)$/);
|
||||
return m ? `${title} #${m[1]}` : title;
|
||||
}
|
||||
|
||||
function fillGuestProtocols() {
|
||||
const serverSel = document.getElementById('guest_create_server');
|
||||
const protoSel = document.getElementById('guest_create_protocol');
|
||||
if (!serverSel || !protoSel) return;
|
||||
const prefer = document.getElementById('guest_create_protocol_pref')?.value || protoSel.value || '';
|
||||
const serverVal = serverSel.value;
|
||||
protoSel.innerHTML = '';
|
||||
if (serverVal === 'xui') {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = 'xui';
|
||||
opt.textContent = PROTO_TITLES.xui;
|
||||
protoSel.appendChild(opt);
|
||||
updateGuestCreateFields();
|
||||
return;
|
||||
}
|
||||
const server = guestServersData[parseInt(serverVal, 10)];
|
||||
const protocols = (server && server.protocols) || {};
|
||||
const installed = Object.keys(protocols).filter(k => {
|
||||
const info = protocols[k] || {};
|
||||
return !!info.installed && VPN_PROTO_ORDER.includes(k.split('__')[0]);
|
||||
}).sort((a, b) => {
|
||||
const ia = VPN_PROTO_ORDER.indexOf(a.split('__')[0]);
|
||||
const ib = VPN_PROTO_ORDER.indexOf(b.split('__')[0]);
|
||||
return (ia < 0 ? 99 : ia) - (ib < 0 ? 99 : ib) || a.localeCompare(b);
|
||||
});
|
||||
if (!installed.length) {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = '';
|
||||
opt.disabled = true;
|
||||
opt.textContent = _('no_protocols');
|
||||
protoSel.appendChild(opt);
|
||||
} else {
|
||||
installed.forEach(key => {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = key;
|
||||
opt.textContent = protoTitle(key);
|
||||
if (prefer && prefer === key) opt.selected = true;
|
||||
protoSel.appendChild(opt);
|
||||
});
|
||||
}
|
||||
updateGuestCreateFields();
|
||||
}
|
||||
|
||||
function updateGuestCreateFields() {
|
||||
const v = document.getElementById('guest_create_protocol')?.value;
|
||||
const group = document.getElementById('guestInboundGroup');
|
||||
@@ -1321,6 +1391,7 @@
|
||||
if (v === 'xui') loadGuestInbounds();
|
||||
}
|
||||
|
||||
fillGuestProtocols();
|
||||
if (document.getElementById('guest_create_protocol')?.value === 'xui') {
|
||||
loadGuestInbounds();
|
||||
}
|
||||
@@ -1425,19 +1496,14 @@
|
||||
downloadBtn.classList.add('hidden');
|
||||
|
||||
try {
|
||||
const response = await fetch('https://api.github.com/repos/PRVTPRO/Amnezia-Web-Panel/releases/latest');
|
||||
if (!response.ok) throw new Error('API Error');
|
||||
const data = await response.json();
|
||||
|
||||
const latestVersion = data.tag_name;
|
||||
const currentVersion = '{{ current_version }}';
|
||||
|
||||
const data = await apiCall('/api/settings/check_updates');
|
||||
const latestVersion = data.latest_version || '';
|
||||
statusDiv.classList.remove('hidden');
|
||||
|
||||
if (latestVersion !== currentVersion && latestVersion) {
|
||||
if (data.update_available && latestVersion) {
|
||||
statusDiv.innerHTML = `<span style="color: var(--success); font-weight: bold;">{{ _('update_available')|default('Update available') }}: ${latestVersion}</span>`;
|
||||
statusDiv.style.border = '1px solid var(--success)';
|
||||
downloadBtn.href = data.html_url;
|
||||
downloadBtn.href = data.html_url || data.releases_url || 'https://git.evilfox.cc/test2/Amnezia-Web-Panel-main/releases';
|
||||
downloadBtn.classList.remove('hidden');
|
||||
} else {
|
||||
statusDiv.innerHTML = `<span style="color: var(--text-muted);">{{ _('up_to_date')|default('Up to date') }}</span>`;
|
||||
|
||||
+60
-20
@@ -143,9 +143,10 @@
|
||||
<select class="form-select" id="newUserServer">
|
||||
<option value="">{{ _('no_create_conn') }}</option>
|
||||
{% for s in servers %}
|
||||
<option value="{{ loop.index0 }}">{{ s.name }} ({{ s.host }})</option>
|
||||
<option value="{{ loop.index0 }}">{{ s.name or s.host }} ({{ s.host }})</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
<div class="form-hint">{{ _('server_then_protocol_hint') }}</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group" id="newUserProtoGroup" style="display:none;">
|
||||
@@ -293,10 +294,14 @@
|
||||
<div class="form-group" id="ucServerGroup">
|
||||
<label class="form-label">{{ _('server_label') }}</label>
|
||||
<select class="form-select" id="ucServer">
|
||||
{% if xui_servers %}
|
||||
<option value="xui">3x-ui</option>
|
||||
{% endif %}
|
||||
{% for s in servers %}
|
||||
<option value="{{ loop.index0 }}">{{ s.name }} ({{ s.host }})</option>
|
||||
<option value="{{ loop.index0 }}">{{ s.name or s.host }} ({{ s.host }})</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
<div class="form-hint">{{ _('server_then_protocol_hint') }}</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group" id="ucProtoGroup">
|
||||
@@ -626,30 +631,57 @@
|
||||
const select = document.getElementById(selectId);
|
||||
const group = groupId ? document.getElementById(groupId) : null;
|
||||
select.innerHTML = '';
|
||||
const vpnBases = new Set(['awg', 'awg2', 'awg_legacy', 'xray', 'telemt', 'wireguard']);
|
||||
const vpnOrder = ['awg2', 'awg', 'awg_legacy', 'wireguard', 'xray', 'telemt', 'hysteria', 'naiveproxy'];
|
||||
const titles = {
|
||||
awg2: 'AmneziaWG 2.0',
|
||||
awg: 'AmneziaWG',
|
||||
awg_legacy: 'AWG Legacy',
|
||||
wireguard: 'WireGuard',
|
||||
xray: 'Xray (VLESS-Reality)',
|
||||
telemt: 'Telemt',
|
||||
hysteria: 'Hysteria 2',
|
||||
naiveproxy: 'NaiveProxy',
|
||||
xui: '3x-ui VLESS',
|
||||
};
|
||||
const protoTitle = (key) => {
|
||||
const base = String(key || '').split('__')[0];
|
||||
const title = titles[base] || base.toUpperCase();
|
||||
const m = String(key || '').match(/__(\d+)$/);
|
||||
return m ? `${title} #${m[1]}` : title;
|
||||
};
|
||||
let count = 0;
|
||||
|
||||
// Special source: 3x-ui (server picker value "xui")
|
||||
if (String(serverId) === 'xui') {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = 'xui';
|
||||
opt.textContent = titles.xui;
|
||||
select.appendChild(opt);
|
||||
count = 1;
|
||||
if (group) group.style.display = '';
|
||||
if (selectId === 'ucProtocol') updateXuiInboundVisibility();
|
||||
return;
|
||||
}
|
||||
|
||||
const server = (serverId !== '' && serversData[serverId]) ? serversData[serverId] : null;
|
||||
const protocols = (server && server.protocols) || {};
|
||||
const installed = Object.keys(protocols).filter(key => {
|
||||
const info = protocols[key] || {};
|
||||
if (!info.installed) return false;
|
||||
return vpnOrder.includes(key.split('__')[0]);
|
||||
}).sort((a, b) => {
|
||||
const ia = vpnOrder.indexOf(a.split('__')[0]);
|
||||
const ib = vpnOrder.indexOf(b.split('__')[0]);
|
||||
return (ia < 0 ? 99 : ia) - (ib < 0 ? 99 : ib) || a.localeCompare(b);
|
||||
});
|
||||
|
||||
for (const [key, info] of Object.entries(protocols)) {
|
||||
if (!info.installed) continue;
|
||||
const base = key.split('__')[0];
|
||||
if (!vpnBases.has(base)) continue;
|
||||
installed.forEach(key => {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = key;
|
||||
opt.textContent = key === 'awg' ? 'AmneziaWG' : (key === 'awg2' ? 'AmneziaWG 2.0' : (key === 'awg_legacy' ? 'AWG Legacy' : (key === 'xray' ? 'Xray' : (key === 'wireguard' ? 'WireGuard' : (key === 'telemt' ? 'Telemt' : key.toUpperCase())))));
|
||||
opt.textContent = protoTitle(key);
|
||||
select.appendChild(opt);
|
||||
count++;
|
||||
}
|
||||
|
||||
if (xuiConfigured && selectId === 'ucProtocol') {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = 'xui';
|
||||
opt.textContent = '3x-ui VLESS';
|
||||
select.appendChild(opt);
|
||||
count++;
|
||||
}
|
||||
});
|
||||
|
||||
if (count > 0) {
|
||||
if (group) group.style.display = '';
|
||||
@@ -724,9 +756,12 @@
|
||||
|
||||
document.getElementById('ucServer').addEventListener('change', (e) => {
|
||||
updateProtocols(e.target.value, 'ucProtocol');
|
||||
if (document.getElementById('ucMode').value === 'existing') {
|
||||
const mode = document.getElementById('ucMode').value;
|
||||
if (mode === 'existing' && e.target.value !== 'xui') {
|
||||
fetchExistingClients();
|
||||
}
|
||||
updateTelemtOptions('ucProtocol', 'ucTelemtOptions');
|
||||
updateXuiInboundVisibility();
|
||||
});
|
||||
|
||||
document.getElementById('ucProtocol').addEventListener('change', (e) => {
|
||||
@@ -898,13 +933,18 @@
|
||||
spinner.classList.remove('hidden');
|
||||
|
||||
try {
|
||||
const serverRaw = document.getElementById('ucServer').value;
|
||||
const protocol = document.getElementById('ucProtocol').value;
|
||||
const body = {
|
||||
server_id: parseInt(document.getElementById('ucServer').value) || 0,
|
||||
protocol: document.getElementById('ucProtocol').value,
|
||||
server_id: serverRaw === 'xui' ? 0 : (parseInt(serverRaw, 10) || 0),
|
||||
protocol: protocol,
|
||||
name: document.getElementById('ucName').value || 'VPN Connection',
|
||||
};
|
||||
|
||||
if (mode === 'existing') {
|
||||
if (serverRaw === 'xui' || protocol === 'xui') {
|
||||
throw new Error(_('link_existing_xui_unsupported') || 'Link existing is only for Amnezia server protocols');
|
||||
}
|
||||
const clientId = document.getElementById('ucExistingClient').value;
|
||||
if (!clientId) throw new Error(_('select_connection'));
|
||||
body.client_id = clientId;
|
||||
|
||||
+623
-552
File diff suppressed because it is too large
Load Diff
+566
-496
File diff suppressed because it is too large
Load Diff
+566
-496
File diff suppressed because it is too large
Load Diff
+623
-552
File diff suppressed because it is too large
Load Diff
+566
-496
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user