forked from test2/Amnezia-Web-Panel-main
Improve Hysteria for Happ: BBR, password auth, salamander, UDP 443.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -2,8 +2,8 @@
|
||||
Hysteria 2 protocol manager — teddysun/hysteria Docker image.
|
||||
|
||||
Installs Hysteria with Let's Encrypt TLS for an admin-provided domain
|
||||
(certbot standalone on port 80), then runs the UDP QUIC server.
|
||||
Clients use userpass auth; share links are hysteria2:// URIs.
|
||||
(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
|
||||
@@ -34,7 +34,7 @@ class HysteriaManager:
|
||||
IMAGE_NAME = 'teddysun/hysteria:latest'
|
||||
CERTBOT_IMAGE = 'certbot/certbot:latest'
|
||||
BASE_DIR = '/opt/amnezia/hysteria'
|
||||
DEFAULT_PORT = 8998
|
||||
DEFAULT_PORT = 443
|
||||
|
||||
def __init__(self, ssh, protocol='hysteria'):
|
||||
self.ssh = ssh
|
||||
@@ -98,7 +98,7 @@ class HysteriaManager:
|
||||
meta = self._read_metadata() if exists else {}
|
||||
clients = self._read_clients() if exists else []
|
||||
|
||||
# Auto-migrate older bridge/-p installs that break QUIC (client EOF while ping works)
|
||||
# Auto-migrate older installs (bridge NAT / userpass / missing BBR+obfs)
|
||||
if exists:
|
||||
try:
|
||||
name = self._container_name(protocol_type)
|
||||
@@ -106,13 +106,20 @@ class HysteriaManager:
|
||||
f"docker inspect -f '{{{{.HostConfig.NetworkMode}}}}' {name} 2>/dev/null"
|
||||
)
|
||||
mode = (mode or '').strip()
|
||||
if mode and mode != 'host':
|
||||
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 host-network migrate failed: %s', e)
|
||||
logger.warning('Hysteria migrate failed: %s', e)
|
||||
|
||||
return {
|
||||
'container_exists': exists,
|
||||
@@ -177,7 +184,24 @@ class HysteriaManager:
|
||||
def _write_clients(self, clients):
|
||||
self._write_file(self.clients_path, json.dumps(clients, indent=2, ensure_ascii=False))
|
||||
|
||||
def _build_server_yaml(self, port, clients):
|
||||
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)}',
|
||||
'',
|
||||
@@ -186,24 +210,14 @@ class HysteriaManager:
|
||||
' key: /etc/hysteria/private.key',
|
||||
'',
|
||||
'auth:',
|
||||
' type: userpass',
|
||||
' userpass:',
|
||||
]
|
||||
if clients:
|
||||
for c in clients:
|
||||
if c.get('enabled', True) is False:
|
||||
continue
|
||||
user = str(c.get('username') or '').strip().lower()
|
||||
pwd = str(c.get('password') or '').strip()
|
||||
if user and pwd:
|
||||
# YAML double-quote; usernames lowercased (viper maps keys to lower)
|
||||
lines.append(f' "{user}": "{pwd}"')
|
||||
else:
|
||||
# Placeholder so Hysteria starts; first real client replaces this
|
||||
lines.append(f' "__bootstrap__": "{_rand_token(24)}"')
|
||||
lines.extend([
|
||||
' type: password',
|
||||
f' password: "{password}"',
|
||||
'',
|
||||
'obfs:',
|
||||
' type: salamander',
|
||||
' salamander:',
|
||||
f' password: "{obfs_password}"',
|
||||
'',
|
||||
# Larger windows + disable PMTUD: avoids common QUIC EOF behind VPS/Docker NAT
|
||||
'quic:',
|
||||
' initStreamReceiveWindow: 8388608',
|
||||
' maxStreamReceiveWindow: 8388608',
|
||||
@@ -229,18 +243,18 @@ class HysteriaManager:
|
||||
' - name: direct',
|
||||
' type: direct',
|
||||
'',
|
||||
])
|
||||
]
|
||||
return '\n'.join(lines)
|
||||
|
||||
def _write_config_from_clients(self, port=None):
|
||||
meta = self._read_metadata()
|
||||
meta = self._ensure_secrets(self._read_metadata())
|
||||
port = int(port or meta.get('port') or self.DEFAULT_PORT)
|
||||
clients = self._read_clients()
|
||||
self._write_file(self.config_path, self._build_server_yaml(port, clients))
|
||||
# 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_udp_buffers(self):
|
||||
"""Raise kernel UDP buffers — too-small buffers cause quic-go EOF on clients."""
|
||||
def _tune_host_network(self):
|
||||
"""UDP buffers + BBR — reduces quic-go EOF and improves throughput."""
|
||||
script = r"""
|
||||
set +e
|
||||
mkdir -p /etc/sysctl.d
|
||||
@@ -249,12 +263,19 @@ printf '%s\n' \
|
||||
'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)
|
||||
|
||||
@@ -277,9 +298,8 @@ iptables -C INPUT -p udp --dport {port} -j ACCEPT 2>/dev/null || iptables -I INP
|
||||
"""Run with --network host so QUIC/UDP is not broken by Docker NAT (EOF)."""
|
||||
name = self.container_name
|
||||
port = int(port)
|
||||
self._tune_host_udp_buffers()
|
||||
self._tune_host_network()
|
||||
self._open_udp_port(port)
|
||||
# Cert must be readable inside the container (non-root entrypoint possible)
|
||||
self.ssh.run_sudo_command(
|
||||
f"chmod 644 {_q(self.cert_path)} {_q(self.key_path)} 2>/dev/null || true"
|
||||
)
|
||||
@@ -298,7 +318,6 @@ iptables -C INPUT -p udp --dport {port} -j ACCEPT 2>/dev/null || iptables -I INP
|
||||
return True
|
||||
|
||||
def _reload_container(self):
|
||||
# Recreate (not restart) so older bridge/-p installs are migrated to host network
|
||||
meta = self._read_metadata()
|
||||
port = int(meta.get('port') or self.DEFAULT_PORT)
|
||||
try:
|
||||
@@ -345,15 +364,21 @@ chmod 644 {_q(self.cert_path)} {_q(self.key_path)}
|
||||
if code != 0:
|
||||
raise RuntimeError(f'Failed to install certificate files: {err or out}')
|
||||
|
||||
def _build_share_uri(self, host, port, domain, username, password, name):
|
||||
user = str(username or '').strip().lower()
|
||||
userinfo = f"{quote(user, safe='')}:{quote(password, safe='')}"
|
||||
fragment = quote(name or user, safe='')
|
||||
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
|
||||
conn_host = 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"hysteria2://{userinfo}@{conn_host}:{int(port)}/"
|
||||
f"?sni={quote(sni, safe='')}&insecure=0#{fragment}"
|
||||
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 =====================
|
||||
@@ -380,13 +405,16 @@ chmod 644 {_q(self.cert_path)} {_q(self.key_path)}
|
||||
|
||||
self.ssh.run_sudo_command(f"mkdir -p {_q(self.base_dir)}")
|
||||
self._write_clients([])
|
||||
self._write_metadata({
|
||||
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')
|
||||
log.append('Prepared config directory (password auth + salamander + BBR)')
|
||||
|
||||
try:
|
||||
self._issue_certificate(domain, email)
|
||||
@@ -399,7 +427,7 @@ chmod 644 {_q(self.cert_path)} {_q(self.key_path)}
|
||||
except Exception as e:
|
||||
return {'status': 'error', 'message': str(e), 'log': log}
|
||||
|
||||
log.append(f'Started {self.container_name} on UDP {port} (host network)')
|
||||
log.append(f'Started {self.container_name} on UDP {port} (host network, BBR)')
|
||||
return {
|
||||
'status': 'success',
|
||||
'message': 'Hysteria installed',
|
||||
@@ -431,60 +459,58 @@ chmod 644 {_q(self.cert_path)} {_q(self.key_path)}
|
||||
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': c.get('name') or c.get('username'),
|
||||
'email': c.get('username'),
|
||||
'userData': {'clientName': c.get('name') or c.get('username')},
|
||||
'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._read_metadata()
|
||||
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)
|
||||
username = f"u_{client_id}" # lowercase — hysteria userpass keys are case-folded
|
||||
password = _rand_token(20)
|
||||
clients = self._read_clients()
|
||||
clients.append({
|
||||
'id': client_id,
|
||||
'name': name or username,
|
||||
'username': username,
|
||||
'password': password,
|
||||
'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, username, password, name or username)
|
||||
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._read_metadata()
|
||||
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('username'), client.get('password'),
|
||||
client.get('name') or client.get('username'),
|
||||
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)
|
||||
self._write_config_from_clients()
|
||||
self._reload_container()
|
||||
return True
|
||||
|
||||
def toggle_client(self, protocol_type, client_id, enable=True):
|
||||
# Soft-disable: remove from yaml but keep in table with enabled=false
|
||||
clients = self._read_clients()
|
||||
found = False
|
||||
for c in clients:
|
||||
@@ -495,6 +521,4 @@ chmod 644 {_q(self.cert_path)} {_q(self.key_path)}
|
||||
if not found:
|
||||
raise RuntimeError('Client not found')
|
||||
self._write_clients(clients)
|
||||
self._write_config_from_clients()
|
||||
self._reload_container()
|
||||
return True
|
||||
|
||||
Reference in New Issue
Block a user