This commit is contained in:
Penguinehis
2026-09-29 12:11:40 -03:00
parent 81d71999b4
commit 6afe9bd2c3
3 changed files with 665 additions and 34 deletions
+3 -3
View File
@@ -15,7 +15,7 @@ sudo menu
The installer installs required packages, Go, PostgreSQL, Xray, the `sshpanel` systemd service, and the `menu` command. It generates service credentials and writes configuration under `/opt/sshpanel`. It needs network access for system packages, Go, and Xray. An extracted source archive can be installed with `sudo bash install.sh` from its root. If `/usr/local/bin/menu` already exists, the installer saves a timestamped backup before replacing it. Use a fresh server because installation creates new database and configuration credentials.
Run `sudo menu` for the command menu. `sudo dragoncore` is an alias. The header shows CPU, RAM, disk, uptime, network traffic, SSH and Xray activity, and service status. Each menu redraw clears the visible terminal; after a command prints results, press Enter to return to the menu. The menu adjusts to narrow terminals; `sudo menu --mobile` forces the compact layout, or set `DRAGONCORE_COLUMNS=36`. A terminal editor such as `nano` or `$EDITOR` is used for advanced JSON settings.
Run `sudo menu` for the command menu. `sudo dragoncore` is an alias. The header shows CPU, RAM, disk, uptime, network traffic, SSH and Xray activity, and service status. Each menu redraw clears the visible terminal; after a command prints results, press Enter to return to the menu. The menu adjusts to narrow terminals; `sudo menu --mobile` forces the compact layout, or set `DRAGONCORE_COLUMNS=36`. Long menus have `n`/`p` page navigation. Configuration uses guided fields instead of opening a JSON editor.
| Command | Purpose |
| --- | --- |
@@ -48,7 +48,7 @@ The CLI generates SSH account passwords and Xray UUIDs when creating them. It do
- **Xray:** manage inbounds and clients, generate UUIDs, adjust limits and quotas, reset traffic, edit JSON, control the service, and configure shared listener ports.
- **Connection modes:** inspect SSH/TLS, DNSTT, BHTTP, BTUN, HCR, UDPGW, and Xray status, settings, and available logs; manage TLS certificates and DNSTT keys.
- **VPS and traffic:** CPU, RAM, storage, uptime, per-interface traffic, daily/monthly totals, system logs, and update status.
- **Configuration and service:** banner and listener settings, full server JSON, bot configuration display, managed servers display, start/stop/restart controls, and API password rotation.
- **Configuration and service:** guided SSH, TLS, DNSTT, BHTTP, BTUN, HCR, UDPGW, Xray, and bot settings; managed server overview and settings; service controls and API password rotation. Existing remote server credentials can be retained while editing. Adding a remote server requires its credential through the authenticated API.
## HTTP API
@@ -121,7 +121,7 @@ curl -X POST http://127.0.0.1:9090/api/users/create \
| POST | `/api/resellers/create` | Admin | Create/update reseller account |
| DELETE | `/api/resellers/delete?username=name` | Admin | Delete reseller account |
Managed server JSON uses `id` (for updates), `name`, `base_url`, `admin_username`, `admin_key`, `enable_ssh`, `enable_xray`, and `is_active`. Configuration POST expects the server configuration JSON; read it with GET, modify the desired fields, and POST the resulting document. The CLI provides guided settings and a JSON editor for advanced options. Reseller routes remain available to the bot and other API integrations, while reseller management stays outside the CLI.
Managed server JSON uses `id` (for updates), `name`, `base_url`, `admin_username`, `admin_key`, `enable_ssh`, `enable_xray`, and `is_active`. Configuration POST expects the server configuration JSON; read it with GET, modify the desired fields, and POST the resulting document. The CLI reads that document internally, changes the selected field, and saves it through the API. It presents menus instead of a JSON editor. Reseller routes remain available to the bot and other API integrations, while reseller management stays outside the CLI.
Reseller create/update JSON uses `username`, `password`, `max_users`, `expires_at` (RFC3339 or empty), and `is_active`. A new reseller requires a password in the API request; omitting it on an update leaves the existing password intact. The CLI never asks its operator for one.
+579 -31
View File
@@ -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():
+83
View File
@@ -1,4 +1,5 @@
import importlib.util
import copy
import io
from pathlib import Path
import tempfile
@@ -90,6 +91,88 @@ class TokenManagementTest(unittest.TestCase):
self.assertEqual(ask.call_count, 3)
self.assertEqual(output.getvalue().count("\033[2J\033[H"), 3)
def test_menu_refreshes_dynamic_options_after_a_change(self):
calls = []
def options():
calls.append(True)
return {"1": ("New" if len(calls) > 1 else "Old", lambda: None)}
with patch("builtins.input", side_effect=["1", "0"]), redirect_stdout(io.StringIO()) as output:
cli.menu("TEST", options)
self.assertEqual(len(calls), 2)
self.assertIn("New", output.getvalue())
def test_server_setting_updates_one_field_and_keeps_other_blocks(self):
config = {"listen": "0.0.0.0:80", "extra_listen": [],
"users": [{"username": "alice"}], "bhttp": {"shared_ports": True}}
writes = []
def fake_request(method, path, data=None):
if method == "GET":
return copy.deepcopy(config)
writes.append((path, data))
return {"warnings": []}
with patch.object(cli, "request", side_effect=fake_request), \
patch.object(cli, "ask", return_value="0.0.0.0:8080"), \
redirect_stdout(io.StringIO()):
cli.edit_field("/api/server/config", cli.SSH_FIELDS[0])
self.assertEqual(writes[0][1]["listen"], "0.0.0.0:8080")
self.assertEqual(writes[0][1]["users"], config["users"])
self.assertEqual(writes[0][1]["bhttp"], config["bhttp"])
def test_protocol_can_be_enabled_through_menu_fields(self):
config = {"listen": "0.0.0.0:80", "hcr": None}
with patch.object(cli, "request", side_effect=[copy.deepcopy(config), {"ok": True}]) as request, \
redirect_stdout(io.StringIO()):
cli.toggle_block("hcr")
payload = request.call_args.args[2]
self.assertEqual(payload["hcr"]["listen"], ["0.0.0.0:8181"])
def test_bot_setting_keeps_existing_token_flags(self):
bot = {"enabled": True, "has_telegram_token": True, "telegram_token": "",
"trial_hours": 1, "mp_confirm_mode": "polling"}
with patch.object(cli, "request", side_effect=[copy.deepcopy(bot), {"ok": True}]) as request, \
patch.object(cli, "number", return_value=24), redirect_stdout(io.StringIO()):
cli.edit_field("/api/bot/config", ("trial_hours", "Trial hours", "int"))
self.assertEqual(request.call_args.args[2]["trial_hours"], 24)
self.assertTrue(request.call_args.args[2]["has_telegram_token"])
def test_new_xray_inbound_uses_next_available_port(self):
config = {"inbounds": [{"tag": "vless-in", "port": 10086}]}
with patch.object(cli, "request", side_effect=[copy.deepcopy(config), None]) as request, \
patch.object(cli, "ask", side_effect=["new-in", "vless", "0.0.0.0", "tcp"]), \
patch.object(cli, "number", side_effect=lambda label, default, *_: default), \
redirect_stdout(io.StringIO()):
cli.xray_inbound_add()
inbound = request.call_args.args[2]["inbounds"][1]
self.assertEqual(inbound["port"], 10087)
self.assertEqual(inbound["streamSettings"]["network"], "tcp")
self.assertTrue(inbound["settings"]["clients"][0]["id"])
def test_configuration_entries_open_guided_menus(self):
with patch.object(cli, "menu") as open_menu:
cli.config_menu()
config = open_menu.call_args.args[1]
self.assertIs(config["4"][1], cli.server_settings_menu)
self.assertIs(config["5"][1], cli.xray_settings_menu)
self.assertIs(config["6"][1], cli.bot_settings_menu)
cli.connection_menu()
self.assertIs(open_menu.call_args.args[1]["3"][1], cli.server_settings_menu)
cli.xray_menu()
self.assertIs(open_menu.call_args.args[1]["7"][1], cli.xray_settings_menu)
def test_guided_config_labels_fit_mobile_width(self):
options = {str(i): (field[1], lambda: None) for i, field in enumerate(cli.SSH_FIELDS, 1)}
self.assertLessEqual(max(map(len, cli.render_menu("SSH SETTINGS", options, columns=40).splitlines())), 40)
def test_long_mobile_settings_menu_has_pages(self):
chosen = []
options = {str(i): (f"Setting {i}", lambda value=i: chosen.append(value)) for i in range(1, 21)}
with patch.object(cli, "terminal_columns", return_value=40), \
patch("builtins.input", side_effect=["n", "11", "0"]), \
redirect_stdout(io.StringIO()) as output:
cli.menu("SETTINGS", options)
self.assertEqual(chosen, [11])
self.assertIn("(2/3)", output.getvalue())
def test_user_list_fits_phone_terminal(self):
users = [{"username": "account-with-a-long-name", "active_conns": 2,
"max_connections": 5, "total_bytes": 1234567,