Fix
This commit is contained in:
+579
-31
@@ -6,12 +6,13 @@ Passwords are generated; no password input or interactive login is requested.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import copy
|
||||
import datetime as dt
|
||||
import getpass
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import shlex
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
@@ -625,29 +626,563 @@ def xray_reset_traffic():
|
||||
print("Traffic reset.")
|
||||
|
||||
|
||||
def edit_json(path):
|
||||
data = request("GET", path)
|
||||
fd, name = tempfile.mkstemp(prefix="dragoncore-", suffix=".json")
|
||||
try:
|
||||
os.fchmod(fd, 0o600)
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as out:
|
||||
json.dump(data, out, indent=2, ensure_ascii=False)
|
||||
out.write("\n")
|
||||
before = Path(name).read_bytes()
|
||||
editor = shlex.split(os.environ.get("EDITOR") or (shutil.which("nano") or shutil.which("vi") or ""))
|
||||
if not editor or subprocess.run([*editor, name]).returncode:
|
||||
raise CLIError("No working editor (install nano or set EDITOR); changes discarded")
|
||||
after = Path(name).read_bytes()
|
||||
if after == before:
|
||||
print("No changes.")
|
||||
def setting_value(label, current, kind="text"):
|
||||
"""Prompt for one typed setting; blank retains the current value."""
|
||||
shown = ", ".join(map(str, current)) if isinstance(current, list) else current
|
||||
if kind == "secret":
|
||||
value = getpass.getpass(f"{label} (blank keeps current): ").strip()
|
||||
return value or current
|
||||
if kind == "bool":
|
||||
raw = ask(label + " (yes/no)", "yes" if current else "no").lower()
|
||||
if raw not in ("yes", "no", "y", "n"):
|
||||
raise CLIError("Enter yes or no")
|
||||
return raw in ("yes", "y")
|
||||
if kind.startswith("choose:"):
|
||||
allowed = kind.partition(":")[2].split("/")
|
||||
value = ask(label + " (" + "/".join(allowed) + ")", current).lower()
|
||||
if value not in allowed:
|
||||
raise CLIError("Choose " + ", ".join(allowed))
|
||||
return value
|
||||
if kind == "int":
|
||||
return number(label, current or 0, -1, 1000000000)
|
||||
if kind in ("list", "intlist"):
|
||||
raw = input(f"{label} (comma separated, - clears) [{shown or ''}]: ").strip()
|
||||
if not raw:
|
||||
return current or []
|
||||
items = [] if raw == "-" else [item.strip() for item in raw.split(",") if item.strip()]
|
||||
if kind == "intlist":
|
||||
try:
|
||||
return [int(item) for item in items]
|
||||
except ValueError as exc:
|
||||
raise CLIError("Enter numbers separated by commas") from exc
|
||||
return items
|
||||
raw = ask(label, shown or "")
|
||||
return raw if raw != "-" else ""
|
||||
|
||||
|
||||
def save_settings(path, document):
|
||||
report = request("POST", path, document)
|
||||
print("Setting applied.")
|
||||
if isinstance(report, dict):
|
||||
for warning in report.get("warnings") or []:
|
||||
print_wrapped("Warning: " + str(warning))
|
||||
|
||||
|
||||
def edit_field(path, field, parent_keys=()):
|
||||
key, label, kind = field
|
||||
document = request("GET", path)
|
||||
parent = document
|
||||
for parent_key in parent_keys:
|
||||
parent = parent[parent_key]
|
||||
current = parent.get(key)
|
||||
if current is None:
|
||||
current = False if kind == "bool" else ([] if kind in ("list", "intlist") else (0 if kind == "int" else ""))
|
||||
value = setting_value(label, current, kind)
|
||||
if value == current:
|
||||
print("No changes.")
|
||||
return
|
||||
parent[key] = value
|
||||
save_settings(path, document)
|
||||
|
||||
|
||||
def field_menu(title, path, fields, parent_keys=()):
|
||||
menu(title, {str(index): (label, lambda f=field: edit_field(path, f, parent_keys))
|
||||
for index, field in enumerate(fields, 1) for label in (field[1],)})
|
||||
|
||||
|
||||
SSH_FIELDS = (
|
||||
("listen", "Primary SSH/HTTP listener", "text"),
|
||||
("extra_listen", "Extra public listeners", "list"),
|
||||
("local_ssh_listen", "Local SSH listener", "text"),
|
||||
("host_key_file", "SSH host key file", "text"),
|
||||
("banner", "SSH banner text", "text"),
|
||||
("banner_file", "SSH banner file", "text"),
|
||||
("quiet", "Quiet mode", "bool"),
|
||||
("user_count", "Show user count", "bool"),
|
||||
("pam_auth_enabled", "PAM account login", "bool"),
|
||||
("ssh_idle_timeout", "SSH idle timeout", "text"),
|
||||
("max_total_connections", "Global connection cap", "int"),
|
||||
("default_limit_mbps_up", "Default upload Mbps", "int"),
|
||||
("default_limit_mbps_down", "Default download Mbps", "int"),
|
||||
("proxy_auto_restart_interval", "Listener restart interval", "text"),
|
||||
("proxy_auto_restart_grace", "Listener restart grace", "text"),
|
||||
)
|
||||
|
||||
BLOCKS = {
|
||||
"dnstt": ("DNSTT", {"domain": "", "udp_listen": "0.0.0.0:5300"}, (
|
||||
("domain", "DNS tunnel domain", "text"), ("domains", "Accepted domains", "list"),
|
||||
("udp_listen", "UDP listener", "text"), ("privkey_file", "Private key file", "text"),
|
||||
("fake_dns_enabled", "Local fake DNS", "bool"), ("fake_dns_listen", "Fake DNS listener", "text"),
|
||||
("fake_dns_domain", "Fake DNS domain", "text"), ("fake_dns_workers", "Fake DNS workers", "int"),
|
||||
("dns_response_workers", "DNS response workers", "int"), ("max_sessions", "Max sessions", "int"),
|
||||
("max_streams", "Max streams", "int"), ("pending_responses", "Pending responses", "int"),
|
||||
("stream_buffer", "Stream buffer bytes", "int"), ("udp_read_buffer", "UDP read buffer", "int"),
|
||||
("udp_write_buffer", "UDP write buffer", "int"), ("log_connections", "Log connections", "bool"),
|
||||
("disable_stats_log", "Mute stats logs", "bool"), ("disable_console_log", "Mute console logs", "bool"),
|
||||
("auto_restart_interval", "Restart interval", "text"), ("auto_restart_grace", "Restart grace", "text"),
|
||||
)),
|
||||
"bhttp": ("BHTTP", {"listen": ["0.0.0.0:8880"], "shared_ports": False}, (
|
||||
("listen", "TCP listeners", "list"), ("shared_ports", "Share SSH/TLS ports", "bool"),
|
||||
("session_timeout", "Session timeout", "text"), ("max_v2_lanes", "Max V2 lanes", "int"),
|
||||
("max_sessions", "Max sessions", "int"), ("max_connections", "Max connections", "int"),
|
||||
("disable_console_log", "Mute console logs", "bool"), ("log_connections", "Log connections", "bool"),
|
||||
("auto_restart_interval", "Restart interval", "text"), ("auto_restart_grace", "Restart grace", "text"),
|
||||
)),
|
||||
"btun": ("BTUN", {"tcp_listen": "0.0.0.0:7300", "udp_listen": "", "manage_routing": True}, (
|
||||
("tcp_listen", "TCP listener", "text"), ("udp_listen", "UDP listener", "text"),
|
||||
("shared_ports", "Share SSH/TLS ports", "bool"), ("tun_name", "TUN interface", "text"),
|
||||
("subnet", "Private subnet CIDR", "text"), ("gateway", "Gateway CIDR", "text"),
|
||||
("mtu", "TUN MTU", "int"), ("manage_routing", "Manage routing/NAT", "bool"),
|
||||
("wan_interface", "WAN interface", "text"), ("handshake_timeout", "Handshake timeout", "text"),
|
||||
("idle_timeout", "Idle timeout", "text"), ("max_packet_size", "Max packet bytes", "int"),
|
||||
("max_cover_bytes", "Max cover bytes", "int"), ("max_sessions", "Max sessions", "int"),
|
||||
("disable_console_log", "Mute console logs", "bool"), ("log_connections", "Log connections", "bool"),
|
||||
("auto_restart_interval", "Restart interval", "text"), ("auto_restart_grace", "Restart grace", "text"),
|
||||
)),
|
||||
"hcr": ("HCR", {"listen": ["0.0.0.0:8181"], "shared_ports": False}, (
|
||||
("listen", "TCP listeners", "list"), ("shared_ports", "Share SSH/TLS ports", "bool"),
|
||||
("max_connections", "Max connections", "int"), ("max_sessions", "Max sessions", "int"),
|
||||
("max_source_sessions", "Max sessions per IP", "int"),
|
||||
("download_poll_timeout", "Download poll timeout", "text"),
|
||||
("max_download_frame", "Max frame bytes", "int"),
|
||||
("idle_session_timeout", "Idle session timeout", "text"),
|
||||
("disable_console_log", "Mute console logs", "bool"), ("log_connections", "Log connections", "bool"),
|
||||
("auto_restart_interval", "Restart interval", "text"), ("auto_restart_grace", "Restart grace", "text"),
|
||||
)),
|
||||
"udpgw": ("UDPGW", {"listen": "0.0.0.0:7400"}, (
|
||||
("listen", "TCP listener", "text"), ("max_frame", "Max frame bytes", "int"),
|
||||
("debug", "Debug logging", "bool"), ("hexdump", "Hexdump bytes", "int"),
|
||||
("write_chan", "Write queue size", "int"), ("udp_bind", "UDP bind IP", "text"),
|
||||
("udp_rbuf", "UDP read buffer", "int"), ("udp_wbuf", "UDP write buffer", "int"),
|
||||
("map_ttl", "Mapping TTL", "text"), ("reap_every", "Reap interval", "text"),
|
||||
("idle_timeout", "Idle timeout", "text"), ("max_client_conns", "Max connections per client", "int"),
|
||||
("max_map_entries", "Max mappings per client", "int"), ("max_clients", "Max clients", "int"),
|
||||
("auto_restart_interval", "Restart interval", "text"), ("auto_restart_grace", "Restart grace", "text"),
|
||||
)),
|
||||
"xray": ("XRAY SERVICE", {"enabled": True, "mode": "native", "native": True}, (
|
||||
("enabled", "Enable Xray", "bool"), ("mode", "Runtime mode", "choose:native/external"),
|
||||
("native_ip_strategy", "IP strategy", "choose:auto/force_ipv4"),
|
||||
("bin_path", "External Xray binary", "text"),
|
||||
("config_file", "External config file", "text"),
|
||||
("native_config_file", "Native config file", "text"),
|
||||
("api_server", "Stats API address", "text"),
|
||||
("online_window_seconds", "Online window seconds", "int"),
|
||||
("stats_poll_seconds", "Stats poll seconds", "int"),
|
||||
)),
|
||||
}
|
||||
|
||||
|
||||
def toggle_block(block):
|
||||
document = request("GET", "/api/server/config")
|
||||
if document.get(block) is not None:
|
||||
if confirm("Disable " + BLOCKS[block][0] + " and disconnect its sessions?"):
|
||||
document[block] = None
|
||||
save_settings("/api/server/config", document)
|
||||
return
|
||||
value = copy.deepcopy(BLOCKS[block][1])
|
||||
if block == "dnstt":
|
||||
value["domain"] = ask("DNS tunnel domain")
|
||||
if not value["domain"]:
|
||||
raise CLIError("A DNSTT domain is required")
|
||||
key = request("POST", "/api/dnstt/genkey", {})
|
||||
value["privkey_file"] = key["privkey_file"]
|
||||
print_wrapped("DNSTT public key: " + key["pubkey"])
|
||||
document[block] = value
|
||||
save_settings("/api/server/config", document)
|
||||
|
||||
|
||||
def block_field(block, field):
|
||||
document = request("GET", "/api/server/config")
|
||||
current = document.get(block)
|
||||
if current is None:
|
||||
raise CLIError("Enable " + BLOCKS[block][0] + " first")
|
||||
key, label, kind = field
|
||||
old = current.get(key)
|
||||
if old is None:
|
||||
old = False if kind == "bool" else ([] if kind == "list" else (0 if kind == "int" else ""))
|
||||
value = setting_value(label, old, kind)
|
||||
if value == old:
|
||||
print("No changes.")
|
||||
return
|
||||
current[key] = value
|
||||
if block == "xray" and key == "mode":
|
||||
current["native"] = value == "native"
|
||||
save_settings("/api/server/config", document)
|
||||
|
||||
|
||||
def block_menu(block):
|
||||
title, _, fields = BLOCKS[block]
|
||||
options = {"1": ("Enable / disable", lambda: toggle_block(block))}
|
||||
options.update({str(index): (label, lambda f=field: block_field(block, f))
|
||||
for index, field in enumerate(fields, 2) for label in (field[1],)})
|
||||
if block == "xray":
|
||||
options[str(len(fields) + 2)] = ("Native emulator tuning", xray_tuning_menu)
|
||||
menu(title + " SETTINGS", options)
|
||||
|
||||
|
||||
def xray_tuning_field(field):
|
||||
document = request("GET", "/api/server/config")
|
||||
xray = document.get("xray")
|
||||
if xray is None:
|
||||
raise CLIError("Enable Xray first")
|
||||
tuning = xray.setdefault("native_tuning", {})
|
||||
key, label, kind = field
|
||||
old = tuning.get(key, False if kind == "bool" else 0)
|
||||
value = setting_value(label, old, kind)
|
||||
if value == old:
|
||||
print("No changes.")
|
||||
return
|
||||
tuning[key] = value
|
||||
save_settings("/api/server/config", document)
|
||||
|
||||
|
||||
def xray_tuning_menu():
|
||||
fields = (("runtime_gomaxprocs", "Runtime CPU threads (0 = auto)", "int"),
|
||||
("mux_global_sessions", "Mux session budget", "int"),
|
||||
("trace_packets", "Packet tracing", "bool"))
|
||||
menu("XRAY TUNING", {str(i): (field[1], lambda f=field: xray_tuning_field(f))
|
||||
for i, field in enumerate(fields, 1)})
|
||||
|
||||
|
||||
def certificate_list():
|
||||
certs = (request("GET", "/api/tls/certs") or {}).get("certs") or []
|
||||
for index, cert in enumerate(certs, 1):
|
||||
print_wrapped(f"{index}. {cert['name']} — {cert.get('days_left', '?')} days left"
|
||||
f" {'valid' if cert.get('key_ok') else 'check certificate/key'}")
|
||||
if not certs:
|
||||
print("No certificates. Generate one in Connection modes.")
|
||||
return certs
|
||||
|
||||
|
||||
def select_certificate():
|
||||
certs = certificate_list()
|
||||
if not certs:
|
||||
raise CLIError("Create a certificate first")
|
||||
index = number("Certificate number", 1, 1, len(certs)) - 1
|
||||
cert = certs[index]
|
||||
if not cert.get("key_ok"):
|
||||
raise CLIError("Certificate or matching key is unavailable")
|
||||
return cert["cert_file"], cert["key_file"]
|
||||
|
||||
|
||||
def tls_listener_add():
|
||||
cfg = request("GET", "/api/server/config")
|
||||
listen = ask("TLS listener (IP:port)", "0.0.0.0:443")
|
||||
cert, key = select_certificate()
|
||||
cfg.setdefault("tls_forwarders", []).append({"listen": listen, "cert_file": cert, "key_file": key})
|
||||
save_settings("/api/server/config", cfg)
|
||||
|
||||
|
||||
def tls_listener_edit(index):
|
||||
cfg = request("GET", "/api/server/config")
|
||||
listeners = cfg.get("tls_forwarders") or []
|
||||
if index >= len(listeners):
|
||||
raise CLIError("TLS listener was removed")
|
||||
entry = listeners[index]
|
||||
options = {"1": ("Change listen address", lambda: tls_listener_field(index, "listen")),
|
||||
"2": ("Select certificate", lambda: tls_listener_field(index, "certificate")),
|
||||
"3": ("Remove listener", lambda: tls_listener_field(index, "remove"))}
|
||||
print_wrapped(f"Listener: {entry['listen']} Certificate: {entry['cert_file']}")
|
||||
menu("TLS LISTENER", options)
|
||||
|
||||
|
||||
def tls_listener_field(index, field):
|
||||
cfg = request("GET", "/api/server/config")
|
||||
listeners = cfg.get("tls_forwarders") or []
|
||||
if index >= len(listeners):
|
||||
raise CLIError("TLS listener was removed")
|
||||
if field == "remove":
|
||||
if not confirm("Remove this TLS listener?"):
|
||||
return
|
||||
updated = json.loads(after)
|
||||
if not confirm("Apply these configuration changes through the API?"):
|
||||
listeners.pop(index)
|
||||
elif field == "certificate":
|
||||
listeners[index]["cert_file"], listeners[index]["key_file"] = select_certificate()
|
||||
else:
|
||||
listeners[index]["listen"] = ask("TLS listener (IP:port)", listeners[index]["listen"])
|
||||
cfg["tls_forwarders"] = listeners
|
||||
save_settings("/api/server/config", cfg)
|
||||
|
||||
|
||||
def tls_listener_menu():
|
||||
def options():
|
||||
listeners = (request("GET", "/api/server/config") or {}).get("tls_forwarders") or []
|
||||
result = {"1": ("Add TLS listener", tls_listener_add)}
|
||||
result.update({str(index + 2): (listener.get("listen", "TLS listener"),
|
||||
lambda i=index: tls_listener_edit(i))
|
||||
for index, listener in enumerate(listeners)})
|
||||
return result
|
||||
menu("TLS LISTENERS", options)
|
||||
|
||||
|
||||
def server_settings_menu():
|
||||
menu("SERVER SETTINGS", {
|
||||
"1": ("SSH and public listeners", lambda: field_menu("SSH SETTINGS", "/api/server/config", SSH_FIELDS)),
|
||||
"2": ("TLS listeners", tls_listener_menu),
|
||||
"3": ("DNSTT", lambda: block_menu("dnstt")),
|
||||
"4": ("BHTTP", lambda: block_menu("bhttp")),
|
||||
"5": ("BTUN", lambda: block_menu("btun")),
|
||||
"6": ("HCR", lambda: block_menu("hcr")),
|
||||
"7": ("UDPGW", lambda: block_menu("udpgw")),
|
||||
"8": ("Xray service", lambda: block_menu("xray")),
|
||||
})
|
||||
|
||||
|
||||
def tree_node(document, trail):
|
||||
node = document
|
||||
for part in trail:
|
||||
node = node[part]
|
||||
return node
|
||||
|
||||
|
||||
def tree_value(path, trail):
|
||||
document = request("GET", path)
|
||||
parent = tree_node(document, trail[:-1])
|
||||
old = parent[trail[-1]]
|
||||
if old is None:
|
||||
raise CLIError("This empty field has no type; use another setting first")
|
||||
kind = "bool" if isinstance(old, bool) else "int" if isinstance(old, int) else "text"
|
||||
value = setting_value(str(trail[-1]), old, kind)
|
||||
if value == old:
|
||||
print("No changes.")
|
||||
return
|
||||
parent[trail[-1]] = value
|
||||
save_settings(path, document)
|
||||
|
||||
|
||||
def tree_browse(path, trail=()):
|
||||
"""Navigate existing Xray settings without displaying or editing raw JSON."""
|
||||
def options():
|
||||
node = tree_node(request("GET", path), trail)
|
||||
if not isinstance(node, (dict, list)):
|
||||
raise CLIError("Choose a setting from its parent menu")
|
||||
items = list(node.keys()) if isinstance(node, dict) else list(range(len(node)))
|
||||
result = {}
|
||||
for index, key in enumerate(items, 1):
|
||||
value = node[key]
|
||||
if str(key).lower() in ("password", "secret", "token", "api_key", "admin_key"):
|
||||
result[str(index)] = (str(key) + ": [hidden]",
|
||||
lambda: print("Configure credentials through the authenticated API."))
|
||||
continue
|
||||
if key == "clients" and trail and trail[-1] == "settings":
|
||||
result[str(index)] = ("Clients (use Xray accounts menu)",
|
||||
lambda: print("Use Xray accounts to manage clients."))
|
||||
continue
|
||||
label = str(key) + (" ›" if isinstance(value, (dict, list)) else
|
||||
": " + ("yes" if value is True else "no" if value is False else str(value)[:24]))
|
||||
next_trail = (*trail, key)
|
||||
result[str(index)] = (label, lambda t=next_trail, v=value:
|
||||
tree_browse(path, t) if isinstance(v, (dict, list)) else tree_value(path, t))
|
||||
return result
|
||||
menu("XRAY " + (str(trail[-1]).upper() if trail else "FIELDS"), options)
|
||||
|
||||
|
||||
def xray_inbound_add():
|
||||
cfg = request("GET", "/api/xray/config")
|
||||
inbounds = cfg.setdefault("inbounds", [])
|
||||
tag = ask("New inbound tag")
|
||||
if not tag or any(inbound.get("tag") == tag for inbound in inbounds):
|
||||
raise CLIError("Enter a unique inbound tag")
|
||||
protocol = setting_value("Protocol", "vless", "choose:vless/vmess")
|
||||
used = {item.get("port") for item in inbounds}
|
||||
suggested_port = next(p for p in range(10086, 65536) if p not in used)
|
||||
port = number("Standalone port", suggested_port, 1, 65535)
|
||||
listen = ask("Listen IP", "0.0.0.0")
|
||||
transport = setting_value("Transport", "tcp", "choose:tcp/ws/xhttp")
|
||||
stream = {"network": transport, "security": "none"}
|
||||
if transport != "tcp":
|
||||
path = ask("URL path (blank = /c1)") or "/c1"
|
||||
if not path.startswith("/"):
|
||||
path = "/" + path
|
||||
if path == "/":
|
||||
raise CLIError("A non-root URL path is required")
|
||||
stream["wsSettings" if transport == "ws" else "xhttpSettings"] = {"path": path}
|
||||
client_id = str(uuid.uuid4())
|
||||
inbound = {"tag": tag, "protocol": protocol, "listen": listen, "port": port,
|
||||
"settings": {"clients": [{"id": client_id, "email": tag + "@dragoncore.local"}]},
|
||||
"streamSettings": stream}
|
||||
if protocol == "vless":
|
||||
inbound["settings"]["decryption"] = "none"
|
||||
inbounds.append(inbound)
|
||||
save_settings("/api/xray/config", cfg)
|
||||
print("Generated client UUID:", client_id)
|
||||
|
||||
|
||||
def xray_inbound_field(tag, field):
|
||||
cfg = request("GET", "/api/xray/config")
|
||||
inbound = next((item for item in cfg.get("inbounds") or [] if item.get("tag") == tag), None)
|
||||
if inbound is None:
|
||||
raise CLIError("Inbound was removed")
|
||||
if field == "remove":
|
||||
if not confirm(f"Remove inbound {tag} and its clients?"):
|
||||
return
|
||||
request("POST", path, updated)
|
||||
print("Configuration saved.")
|
||||
finally:
|
||||
os.unlink(name)
|
||||
cfg["inbounds"].remove(inbound)
|
||||
elif field == "port":
|
||||
if inbound.get("dragoncoreSharedPort"):
|
||||
raise CLIError("Shared inbounds use the public SSH/TLS ports")
|
||||
inbound["port"] = number("Port", inbound.get("port") or 10086, 1, 65535)
|
||||
elif field == "listen":
|
||||
inbound["listen"] = ask("Listen IP", inbound.get("listen") or "0.0.0.0")
|
||||
elif field == "path":
|
||||
stream = inbound.setdefault("streamSettings", {})
|
||||
network = stream.get("network")
|
||||
if network not in ("ws", "xhttp"):
|
||||
raise CLIError("Choose WS or XHTTP transport first")
|
||||
key = "wsSettings" if network == "ws" else "xhttpSettings"
|
||||
old = stream.get(key, {}).get("path", "")
|
||||
value = ask("URL path", old)
|
||||
if not value.startswith("/"):
|
||||
value = "/" + value
|
||||
if value == "/":
|
||||
raise CLIError("A non-root URL path is required")
|
||||
stream.setdefault(key, {})["path"] = value
|
||||
elif field == "transport":
|
||||
if inbound.get("dragoncoreSharedPort"):
|
||||
raise CLIError("Use Share SSH/TLS ports to change this inbound")
|
||||
stream = inbound.setdefault("streamSettings", {})
|
||||
network = setting_value("Transport", stream.get("network", "tcp"), "choose:tcp/ws/xhttp")
|
||||
stream["network"] = network
|
||||
if network in ("ws", "xhttp"):
|
||||
key = "wsSettings" if network == "ws" else "xhttpSettings"
|
||||
value = ask("URL path (blank = /c1)", stream.get(key, {}).get("path", "")) or "/c1"
|
||||
if not value.startswith("/"):
|
||||
value = "/" + value
|
||||
stream.setdefault(key, {})["path"] = value
|
||||
print_wrapped("Existing clients must update their connection transport.")
|
||||
save_settings("/api/xray/config", cfg)
|
||||
|
||||
|
||||
def xray_inbound_settings(tag):
|
||||
menu("INBOUND " + tag.upper(), {
|
||||
"1": ("Listen IP", lambda: xray_inbound_field(tag, "listen")),
|
||||
"2": ("Standalone port", lambda: xray_inbound_field(tag, "port")),
|
||||
"3": ("Transport (TCP/WS/XHTTP)", lambda: xray_inbound_field(tag, "transport")),
|
||||
"4": ("WS/XHTTP path", lambda: xray_inbound_field(tag, "path")),
|
||||
"5": ("Remove inbound", lambda: xray_inbound_field(tag, "remove")),
|
||||
})
|
||||
|
||||
|
||||
def xray_inbound_settings_menu():
|
||||
def options():
|
||||
inbounds = (request("GET", "/api/xray/config") or {}).get("inbounds") or []
|
||||
result = {"1": ("Create standalone inbound", xray_inbound_add),
|
||||
"2": ("Share SSH/TLS ports (WS/XHTTP)", xray_shared_port)}
|
||||
result.update({str(index + 3): (f"{item.get('tag')} ({item.get('protocol')})",
|
||||
lambda tag=item.get("tag"): xray_inbound_settings(tag))
|
||||
for index, item in enumerate(inbounds)})
|
||||
return result
|
||||
menu("XRAY INBOUNDS", options)
|
||||
|
||||
|
||||
def xray_settings_menu():
|
||||
menu("XRAY SETTINGS", {
|
||||
"1": ("Inbounds and transports", xray_inbound_settings_menu),
|
||||
"2": ("Native / external service", lambda: block_menu("xray")),
|
||||
"3": ("Other Xray fields", lambda: tree_browse("/api/xray/config")),
|
||||
})
|
||||
|
||||
|
||||
BOT_FIELDS = (
|
||||
("enabled", "Bot enabled", "bool"),
|
||||
("mp_confirm_mode", "Payment confirmation", "choose:polling/webhook"),
|
||||
("mp_poll_interval", "Payment poll interval", "text"),
|
||||
("pix_expiration_minutes", "PIX expiry minutes", "int"),
|
||||
("trial_enabled", "Trial accounts enabled", "bool"),
|
||||
("trial_hours", "Trial duration hours", "int"),
|
||||
("trial_max_connections", "Trial connection limit", "int"),
|
||||
("trial_kind", "Trial kind", "choose:ssh/xray"),
|
||||
("trial_inbound_tag", "Trial Xray inbound", "text"),
|
||||
("admin_telegram_ids", "Bot admin Telegram IDs", "intlist"),
|
||||
("currency", "Currency", "text"),
|
||||
("public_host", "SSH public hostname", "text"),
|
||||
("xray_public_host", "Xray public hostname", "text"),
|
||||
("telegram_token", "Telegram bot token", "secret"),
|
||||
("mp_access_token", "Mercado Pago access token", "secret"),
|
||||
("mp_webhook_secret", "Payment webhook secret", "secret"),
|
||||
)
|
||||
|
||||
|
||||
def bot_text_setting(key, label):
|
||||
settings = request("GET", "/api/bot/settings") or {}
|
||||
print_wrapped(f"Current {label}: {settings.get(key, '') or '(empty)'}")
|
||||
if key == "app_url":
|
||||
value = setting_value(label, settings.get(key, ""))
|
||||
else:
|
||||
print("Enter new text, finish with a line containing only a dot.")
|
||||
print("An empty first line keeps the current text; a single - clears it.")
|
||||
first = input("First line: ")
|
||||
if not first:
|
||||
return
|
||||
if first == "-":
|
||||
value = ""
|
||||
else:
|
||||
lines = [first]
|
||||
while (line := input()) != ".":
|
||||
lines.append(line)
|
||||
value = "\n".join(lines)
|
||||
if value == settings.get(key, ""):
|
||||
print("No changes.")
|
||||
return
|
||||
save_settings("/api/bot/settings", {key: value})
|
||||
|
||||
|
||||
def bot_text_menu():
|
||||
fields = (("welcome_text", "Welcome message"), ("contact_text", "Contact message"),
|
||||
("app_text", "App description"), ("app_url", "App URL"))
|
||||
menu("BOT TEXT", {str(i): (label, lambda k=key, l=label: bot_text_setting(k, l))
|
||||
for i, (key, label) in enumerate(fields, 1)})
|
||||
|
||||
|
||||
def bot_settings_menu():
|
||||
menu("TELEGRAM BOT", {
|
||||
"1": ("Bot and payment settings", lambda: field_menu("BOT SETTINGS", "/api/bot/config", BOT_FIELDS)),
|
||||
"2": ("Messages and app link", bot_text_menu),
|
||||
})
|
||||
|
||||
|
||||
def managed_server_summary():
|
||||
servers = request("GET", "/api/servers") or []
|
||||
for row in servers:
|
||||
print_wrapped(f"{row.get('id')} {row.get('name')} {row.get('base_url')}"
|
||||
f" {'active' if row.get('is_active') else 'disabled'}"
|
||||
f" SSH={'yes' if row.get('enable_ssh') else 'no'}"
|
||||
f" Xray={'yes' if row.get('enable_xray') else 'no'}")
|
||||
return servers
|
||||
|
||||
|
||||
def managed_server_field(server_id, field):
|
||||
server = next((row for row in request("GET", "/api/servers") or []
|
||||
if str(row.get("id")) == str(server_id)), None)
|
||||
if server is None or server.get("is_local"):
|
||||
raise CLIError("Select an existing remote server")
|
||||
kind = "bool" if field in ("is_active", "enable_ssh", "enable_xray") else "text"
|
||||
value = setting_value(field.replace("_", " ").title(), server.get(field, ""), kind)
|
||||
if value == server.get(field):
|
||||
print("No changes.")
|
||||
return
|
||||
server[field] = value
|
||||
payload = {key: server.get(key) for key in ("id", "name", "base_url", "admin_username",
|
||||
"enable_ssh", "enable_xray", "is_active")}
|
||||
# An empty credential preserves the encrypted credential already stored by the API.
|
||||
payload["admin_key"] = ""
|
||||
save_settings("/api/servers", payload)
|
||||
|
||||
|
||||
def managed_server_edit(server_id):
|
||||
fields = (("name", "Server name"), ("base_url", "API URL"),
|
||||
("admin_username", "Remote admin username"), ("is_active", "Active"),
|
||||
("enable_ssh", "Allow SSH accounts"), ("enable_xray", "Allow Xray clients"))
|
||||
menu("MANAGED SERVER", {str(i): (label, lambda f=field: managed_server_field(server_id, f))
|
||||
for i, (field, label) in enumerate(fields, 1)})
|
||||
|
||||
|
||||
def managed_servers_menu():
|
||||
servers = [server for server in managed_server_summary() if not server.get("is_local")]
|
||||
if not servers:
|
||||
print("No remote servers configured. Add a remote server using the authenticated API.")
|
||||
return
|
||||
menu("MANAGED SERVERS", {str(i): (f"{server.get('name')} ({server.get('id')})",
|
||||
lambda sid=server.get("id"): managed_server_edit(sid))
|
||||
for i, server in enumerate(servers, 1)})
|
||||
|
||||
|
||||
def set_banner():
|
||||
@@ -771,8 +1306,8 @@ def connection_menu():
|
||||
menu("CONNECTION MODES", {
|
||||
"1": ("Ports and transports", connection_status),
|
||||
"2": ("DNSTT / BHTTP / HCR / BTUN statistics", protocol_stats),
|
||||
"3": ("Edit listeners and protocol settings", lambda: edit_json("/api/server/config")),
|
||||
"4": ("TLS certificates", lambda: print(json.dumps(request("GET", "/api/tls/certs"), indent=2))),
|
||||
"3": ("Listeners and protocol settings", server_settings_menu),
|
||||
"4": ("TLS certificates", certificate_list),
|
||||
"5": ("DNSTT public key", lambda: print(json.dumps(request("GET", "/api/dnstt/pubkey"), indent=2))),
|
||||
"6": ("Protocol logs", protocol_logs),
|
||||
"7": ("Generate self-signed TLS certificate", generate_tls_certificate),
|
||||
@@ -855,14 +1390,27 @@ _menu_calls = 0
|
||||
def menu(title, options):
|
||||
global _menu_calls
|
||||
_menu_calls += 1
|
||||
page = 0
|
||||
while True:
|
||||
clear_screen()
|
||||
vps = collect_vps_status() if title == "MAIN MENU" else None
|
||||
print(render_menu(title, options, vps))
|
||||
current_options = options() if callable(options) else options
|
||||
page_size = 9 if terminal_columns() <= 48 else 16
|
||||
entries = list(current_options.items())
|
||||
pages = max(1, (len(entries) + page_size - 1) // page_size)
|
||||
page = min(page, pages - 1)
|
||||
visible = dict(entries[page * page_size:(page + 1) * page_size])
|
||||
heading = title + (f" ({page + 1}/{pages})" if pages > 1 else "")
|
||||
print(render_menu(heading, visible, vps))
|
||||
if pages > 1:
|
||||
print(" n Next page p Previous page")
|
||||
choice = input("Choose: ").strip().lstrip("0") or "0"
|
||||
if choice.lower() in ("n", "p") and pages > 1:
|
||||
page = min(pages - 1, page + 1) if choice.lower() == "n" else max(0, page - 1)
|
||||
continue
|
||||
if choice == "0":
|
||||
return
|
||||
entry = options.get(choice)
|
||||
entry = visible.get(choice)
|
||||
if not entry:
|
||||
print("Invalid option.")
|
||||
else:
|
||||
@@ -905,7 +1453,7 @@ def xray_menu():
|
||||
"4": ("Reset client traffic", xray_reset_traffic),
|
||||
"5": ("Delete client", xray_delete),
|
||||
"6": ("Status", lambda: print(json.dumps(request("GET", "/api/xray/status"), indent=2))),
|
||||
"7": ("Edit Xray JSON", lambda: edit_json("/api/xray/config")),
|
||||
"7": ("Xray settings menu", xray_settings_menu),
|
||||
"8": ("Start Xray", lambda: xray_action("start")),
|
||||
"9": ("Stop Xray", lambda: xray_action("stop") if confirm("Stop Xray connections?") else None),
|
||||
"10": ("Restart Xray", lambda: xray_action("restart")),
|
||||
@@ -918,10 +1466,10 @@ def config_menu():
|
||||
menu("CONFIGURATION", {"1": ("Set SSH banner", set_banner),
|
||||
"2": ("Change SSH listener ports", set_ssh_ports),
|
||||
"3": ("Default bandwidth / connection limits", set_ssh_limits),
|
||||
"4": ("All SSH / DNSTT / BHTTP / BTUN / HCR settings", lambda: edit_json("/api/server/config")),
|
||||
"5": ("Xray JSON", lambda: edit_json("/api/xray/config")),
|
||||
"6": ("Telegram bot configuration", lambda: print(json.dumps(request("GET", "/api/bot/config"), indent=2))),
|
||||
"7": ("Managed servers", lambda: print(json.dumps(request("GET", "/api/servers"), indent=2)))})
|
||||
"4": ("All server and protocol settings", server_settings_menu),
|
||||
"5": ("Xray settings", xray_settings_menu),
|
||||
"6": ("Telegram bot settings", bot_settings_menu),
|
||||
"7": ("Managed servers", managed_servers_menu)})
|
||||
|
||||
|
||||
def api_menu():
|
||||
|
||||
Reference in New Issue
Block a user