feat: better inbounds user management

This commit is contained in:
FUFSoB committed 2026-10-14 21:41:49 +05:00
1 parent 2f8414455d
commit 9f7ad91f39
47 files changed
+6767 -78

No files matched your search

+3
View File
@@ -240,6 +240,9 @@ def render_server_config(listener: dict, state: dict) -> str:
awg = listener["amneziaWg"]
peers = []
for user in listener["users"]:
# Switched off by the manager: no peer, but the keys and address stay in the state.
if user.get("active") is False:
continue
entry = state["users"][user["name"]]
peer: dict[str, Any] = {
"publicKey": entry["publicKey"],
+5 -7
View File
@@ -5,8 +5,7 @@ import argparse
import json
import sys
import inbound_runtime
from proxy_inbound import build_inbounds
from inbound_apply import render
def main() -> None:
@@ -42,14 +41,13 @@ def main() -> None:
sys.exit(1)
try:
spec, runtime, warnings = inbound_runtime.merge(spec, check_ports=True)
for warning in warnings:
print(f"proxy-suite: warning: {warning}", file=sys.stderr)
result = build_inbounds(spec, server_address, args.onion_address)
template = None
if args.template and spec.get("runtime"):
with open(args.template, encoding="utf-8") as handle:
template = json.load(handle)
result.update(inbound_runtime.routing(spec, runtime, template["routing"]["rules"]))
result, warnings = render(spec, server_address, args.onion_address, template, check_ports=True)
for warning in warnings:
print(f"proxy-suite: warning: {warning}", file=sys.stderr)
except (ValueError, OSError) as exc:
print(f"error: {exc}", file=sys.stderr)
sys.exit(1)
+473
View File
@@ -0,0 +1,473 @@
#!/usr/bin/env python3
"""Apply a change to the inbounds without restarting them, where XRay's API can.
The inbounds' start script keeps what it rendered (build-inbound.py's output) and with
what, in its runtime directory. This renders the spec again the same way and compares:
- users who came, went or changed on a listener that is otherwise the same: removed and
added through the API (rmu, adu), and the connections of those removed cut (ss -K for
TCP, a short drop in proxy-suite's nftables table for UDP), since XRay keeps them;
- the routing rules (runtime users' serverSource rules): replaced whole (adrules);
- their serverSource outbounds and addresses: added and removed (ado, rmo, ip addr);
- the share links and subscriptions: written again by the module's own writer;
- AmneziaWG listeners whose peers changed: their interfaces synced (awg syncconf), which
leaves the other peers' sessions alone.
Anything else (a listener added, removed or changed, a Shadowsocks listener going between
one user and many, socks or http accounts) needs the restart it always needed, and so does
an API call that fails. One apply at a time (a lock in the runtime directory).
"""
from __future__ import annotations
import argparse
import copy
import fcntl
import json
import os
import subprocess
import sys
import tempfile
import inbound_runtime
from proxy_inbound import build_inbounds
# The inbound's user list, by XRay protocol; a Shadowsocks inbound has one only with more
# than one user. The others (socks, http, a single-user Shadowsocks, AmneziaWG's) change
# only with a restart.
USER_LISTS = {"vless": "clients", "vmess": "clients", "trojan": "clients", "hysteria": "clients", "shadowsocks": "clients"}
# Inbounds that speak UDP to their clients: a cut user's sessions there are dropped for a
# while instead (QUIC has no socket to kill).
UDP_CUT_SECONDS = 90
def render(spec: dict, server_address: str, onion_address: str = "", template: dict | None = None,
check_ports: bool | set = False, now: float | None = None) -> tuple[dict, list[str]]:
"""What build-inbound.py prints: the inbounds, links and subscriptions, and with
inbounds.runtime and the template its routing additions. check_ports: whether a runtime
listener's port must be free, or the ports the running XRay holds, which count as free."""
merged, runtime, warnings = inbound_runtime.merge(spec, check_ports=check_ports, now=now)
result = build_inbounds(merged, server_address, onion_address)
if template is not None and merged.get("runtime"):
result.update(inbound_runtime.routing(merged, runtime, template["routing"]["rules"]))
return result, warnings
# --- the comparison -------------------------------------------------------------------
def split_users(inbound: dict) -> tuple[dict, dict[str, dict]]:
"""The inbound without its users, and its users by email. One whose users cannot be
told apart from the rest comes whole, with none."""
key = USER_LISTS.get(inbound.get("protocol", ""))
settings = inbound.get("settings") or {}
if key is None or not isinstance(settings.get(key), list):
return inbound, {}
shape = copy.deepcopy(inbound)
users = {client.get("email"): client for client in shape["settings"].pop(key)}
if None in users or len(users) != len(settings[key]):
return inbound, {}
return shape, users
def plan(old: dict, new: dict) -> dict:
"""What it takes to go from the old rendering to the new one: {"restart": [reasons],
"users": {tag: {"remove": [emails], "add": [clients]}}, "rules": rules | None,
"outbounds": {"remove": [tags], "add": [outbounds]}, "addresses": {"remove", "add"},
"outputs": bool}. A non-empty "restart" means the rest does not apply."""
result: dict = {"restart": [], "users": {}, "rules": None, "outbounds": {"remove": [], "add": []},
"addresses": {"remove": [], "add": []}, "outputs": False}
old_inbounds = {ib.get("tag"): ib for ib in old.get("inbounds") or []}
new_inbounds = {ib.get("tag"): ib for ib in new.get("inbounds") or []}
if set(old_inbounds) != set(new_inbounds):
added = sorted(set(new_inbounds) - set(old_inbounds))
gone = sorted(set(old_inbounds) - set(new_inbounds))
result["restart"].append(
"listeners " + ", ".join(filter(None, [added and f"added: {', '.join(added)}", gone and f"gone: {', '.join(gone)}"]))
)
return result
for tag, inbound in new_inbounds.items():
old_shape, old_users = split_users(old_inbounds[tag])
new_shape, new_users = split_users(inbound)
if old_shape != new_shape:
result["restart"].append(f"listener '{tag}' changed")
continue
remove = sorted(e for e in old_users if e not in new_users or old_users[e] != new_users[e])
add = [new_users[e] for e in sorted(new_users) if e not in old_users or old_users[e] != new_users[e]]
if remove or add:
result["users"][tag] = {"remove": remove, "add": add}
if result["restart"]:
return result
if (old.get("rules") or []) != (new.get("rules") or []):
result["rules"] = new.get("rules") or []
old_outbounds = {ob["tag"]: ob for ob in old.get("selfOutbounds") or []}
new_outbounds = {ob["tag"]: ob for ob in new.get("selfOutbounds") or []}
result["outbounds"]["remove"] = sorted(t for t in old_outbounds if old_outbounds[t] != new_outbounds.get(t))
result["outbounds"]["add"] = [new_outbounds[t] for t in sorted(new_outbounds) if new_outbounds[t] != old_outbounds.get(t)]
def addresses(rendering):
return {(family, entry[key]) for entry in rendering.get("selfAddresses") or []
for family, key in (("4", "ipv4"), ("6", "ipv6")) if entry.get(key)}
old_addresses, new_addresses = addresses(old), addresses(new)
result["addresses"]["remove"] = sorted(old_addresses - new_addresses)
result["addresses"]["add"] = sorted(new_addresses - old_addresses)
result["outputs"] = (old.get("links"), old.get("subscriptions")) != (new.get("links"), new.get("subscriptions"))
return result
def is_noop(steps: dict) -> bool:
return not (steps["restart"] or steps["users"] or steps["rules"] is not None or steps["outbounds"]["remove"]
or steps["outbounds"]["add"] or steps["addresses"]["remove"] or steps["addresses"]["add"]
or steps["outputs"])
def udp_inbound(inbound: dict) -> bool:
stream = inbound.get("streamSettings") or {}
alpn = ((stream.get("tlsSettings") or {}).get("alpn")) or []
return inbound.get("protocol") == "hysteria" or (stream.get("network") == "xhttp" and alpn == ["h3"])
# --- doing it -------------------------------------------------------------------------
class ApplyError(RuntimeError):
pass
class Tools:
"""The binaries and names the module hands over (apply.json), and how to call them."""
def __init__(self, config: dict, dry_run: bool = False):
self.config = config
self.dry_run = dry_run
self.log: list[str] = []
def run(self, argv: list[str], what: str, stdin: str | None = None, check: bool = True) -> str:
self.log.append(" ".join(argv))
if self.dry_run:
return ""
env = dict(os.environ)
env.update(self.config.get("env") or {})
try:
done = subprocess.run(argv, input=stdin, capture_output=True, text=True, env=env, timeout=30)
except (OSError, subprocess.TimeoutExpired) as exc:
raise ApplyError(f"{what}: {exc}") from None
if check and done.returncode != 0:
raise ApplyError(f"{what}: {(done.stderr or done.stdout).strip() or f'exit {done.returncode}'}")
return done.stdout
def xray_api(self, command: str, *args: str, what: str) -> str:
# The server first: Go's flags end at the first argument that is none (rmu's emails).
return self.run([self.config["xray"], "api", command, f"--server={self.config['api']}", *args], what)
def xray_api_file(self, command: str, value: dict, what: str) -> str:
with tempfile.NamedTemporaryFile("w", suffix=".json", dir=self.config.get("tmpDir"), delete=True) as handle:
json.dump(value, handle)
handle.flush()
return self.run([self.config["xray"], "api", command, f"--server={self.config['api']}", handle.name], what)
def online_ips(tools: Tools, email: str) -> list[str]:
"""Where a user is connected from now, as XRay counts it (loopback never is)."""
try:
out = tools.xray_api("statsonlineiplist", "-email", email, what=f"online addresses of {email}")
return sorted((json.loads(out or "{}").get("ips") or {}).keys())
except (ApplyError, ValueError):
return []
def cut(tools: Tools, ips: list[str], tcp_ports: set[int], udp_ports: set[int]) -> None:
"""Close what these addresses hold open on these ports: TCP sockets killed, UDP dropped
for a while. Other users behind the same address reconnect once."""
ss = tools.config.get("ss")
if ss:
for ip in ips:
# A prefix: a bare IPv6 address would read as address and port to ss.
prefix = f"{ip}/128" if ":" in ip else f"{ip}/32"
for port in sorted(tcp_ports):
tools.run([ss, "-K", "-n", "-t", "state", "established", f"( sport = :{port} )", "dst", prefix],
f"closing {ip}'s connections to {port}", check=False)
nft, table = tools.config.get("nft"), tools.config.get("nftTable")
if nft and table and udp_ports and ips:
lines = []
for ip in ips:
family = "6" if ":" in ip else "4"
for port in sorted(udp_ports):
lines.append(f"add element inet {table} cut{family} {{ {ip} . {port} timeout {UDP_CUT_SECONDS}s }}")
tools.run([nft, "-f", "-"], "dropping UDP of the users cut off", stdin="\n".join(lines) + "\n", check=False)
def run_steps(tools: Tools, steps: dict, new: dict, template: dict | None) -> list[str]:
"""Carry out a plan without "restart". What was done, line by line."""
done = []
by_tag = {ib["tag"]: ib for ib in new.get("inbounds") or []}
# Where the users going away are connected from, before XRay forgets them.
leaving: dict[str, list[str]] = {}
for change in steps["users"].values():
for email in change["remove"]:
if email not in leaving:
leaving[email] = online_ips(tools, email)
tcp_ports: dict[str, set[int]] = {}
udp_ports: dict[str, set[int]] = {}
for tag, change in sorted(steps["users"].items()):
inbound = by_tag[tag]
if change["remove"]:
tools.xray_api("rmu", f"-tag={tag}", *change["remove"], what=f"removing users from {tag}")
ports = udp_ports if udp_inbound(inbound) else tcp_ports
for email in change["remove"]:
ports.setdefault(email, set()).add(int(inbound["port"]))
done.append(f"{tag}: -{','.join(change['remove'])}")
if change["add"]:
key = USER_LISTS[inbound["protocol"]]
partial = copy.deepcopy(inbound)
partial["settings"][key] = change["add"]
tools.xray_api_file("adu", {"inbounds": [partial]}, f"adding users to {tag}")
done.append(f"{tag}: +{','.join(c['email'] for c in change['add'])}")
# A user whose secret or level changed was removed and added: their old sessions go too.
for email, ips in sorted(leaving.items()):
if ips:
cut(tools, ips, tcp_ports.get(email, set()), udp_ports.get(email, set()))
done.append(f"cut {email} ({', '.join(ips)})")
for tag in steps["outbounds"]["remove"]:
tools.xray_api("rmo", tag, what=f"removing outbound {tag}")
if steps["outbounds"]["add"]:
tools.xray_api_file("ado", {"outbounds": steps["outbounds"]["add"]}, "adding serverSource outbounds")
if steps["outbounds"]["remove"] or steps["outbounds"]["add"]:
done.append("serverSource outbounds")
if steps["rules"] is not None:
routing = {key: value for key, value in ((template or {}).get("routing") or {}).items() if key != "rules"}
routing["rules"] = steps["rules"]
tools.xray_api_file("adrules", {"routing": routing}, "replacing the routing rules")
done.append("routing rules")
ip, interface = tools.config.get("ip"), tools.config.get("selfInterface")
if ip and interface:
for family, address in steps["addresses"]["remove"]:
prefix = "32" if family == "4" else "128"
tools.run([ip, f"-{family}", "addr", "del", f"{address}/{prefix}", "dev", interface],
f"removing {address}", check=False)
for family, address in steps["addresses"]["add"]:
prefix = "32" if family == "4" else "128"
extra = ["nodad"] if family == "6" else []
tools.run([ip, f"-{family}", "addr", "add", f"{address}/{prefix}", "dev", interface, *extra],
f"adding {address}")
if steps["addresses"]["remove"] or steps["addresses"]["add"]:
done.append("serverSource addresses")
return done
def sync_config(runtime_dir: str, steps: dict, new: dict) -> None:
"""The running XRay's config.json, as it now runs: what proxy-ctl and people read. In
place, so its owner, mode and ACLs stay."""
path = os.path.join(runtime_dir, "config.json")
config = load_json(path)
if not isinstance(config, dict):
return
by_tag = {ib["tag"]: ib for ib in new.get("inbounds") or []}
for inbound in config.get("inbounds") or []:
tag = inbound.get("tag")
if tag in steps["users"]:
key = USER_LISTS[inbound["protocol"]]
inbound.setdefault("settings", {})[key] = copy.deepcopy(by_tag[tag]["settings"][key])
if steps["rules"] is not None:
config.setdefault("routing", {})["rules"] = steps["rules"]
gone = set(steps["outbounds"]["remove"])
if gone or steps["outbounds"]["add"]:
config["outbounds"] = [ob for ob in config.get("outbounds") or [] if ob.get("tag") not in gone]
config["outbounds"] += copy.deepcopy(steps["outbounds"]["add"])
fd = os.open(path, os.O_WRONLY | os.O_TRUNC | os.O_NOFOLLOW)
with os.fdopen(fd, "w", encoding="utf-8") as handle:
json.dump(config, handle)
def write_outputs(tools: Tools, rendered_path: str) -> None:
script = tools.config.get("outputsScript")
if script:
tools.run([script, rendered_path], "writing the share links and subscriptions")
def save_rendering(runtime_dir: str, rendered: dict) -> str:
path = os.path.join(runtime_dir, "rendered.json")
tmp = path + ".tmp"
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as handle:
json.dump(rendered, handle)
os.replace(tmp, path)
return path
def load_json(path: str):
try:
with open(path, encoding="utf-8") as handle:
return json.load(handle)
except (OSError, ValueError):
return None
def restart(tools: Tools, units: list[str], reason: str) -> list[str]:
systemctl = tools.config["systemctl"]
tools.run([systemctl, "try-restart", *units], f"restarting {', '.join(units)}")
return [f"restarted {', '.join(units)}: {reason}"]
def apply_xray(tools: Tools, spec: dict) -> list[str]:
"""The XRay side; restarts the inbounds when the API cannot do it."""
config = tools.config
runtime_dir = config["runtimeDir"]
unit = config["unit"]
old = load_json(os.path.join(runtime_dir, "rendered.json"))
args = load_json(os.path.join(runtime_dir, "render-args.json"))
if not isinstance(old, dict) or not isinstance(args, dict):
return restart(tools, [unit], "nothing rendered to compare with")
template = load_json(config["template"]) if config.get("template") else None
try:
server_address = args.get("serverAddress") or spec.get("serverAddress") or ""
# As the start script checks them, but the ports XRay holds now are its own.
held = {int(ib["port"]) for ib in old.get("inbounds") or [] if isinstance(ib.get("port"), int)}
new, warnings = render(spec, server_address, args.get("onionAddress", ""), template, check_ports=held or True)
except (ValueError, OSError) as exc:
return restart(tools, [unit], f"cannot render: {exc}")
for warning in warnings:
print(f"proxy-suite: warning: {warning}", file=sys.stderr)
steps = plan(old, new)
if steps["restart"]:
return restart(tools, [unit], "; ".join(steps["restart"]))
if is_noop(steps):
return []
try:
done = run_steps(tools, steps, new, template)
except ApplyError as exc:
return restart(tools, [unit], f"the API failed: {exc}")
path = save_rendering(runtime_dir, new)
try:
sync_config(runtime_dir, steps, new)
except (OSError, ValueError, KeyError) as exc:
print(f"proxy-suite: config.json not updated: {exc}", file=sys.stderr)
if steps["outputs"]:
try:
write_outputs(tools, path)
done.append("links and subscriptions")
except ApplyError as exc:
print(f"proxy-suite: {exc}", file=sys.stderr)
return done
# --- AmneziaWG ------------------------------------------------------------------------
STRIPPED_INTERFACE_KEYS = {"address", "dns", "mtu", "table", "preup", "postup", "predown", "postdown", "saveconfig"}
def strip_config(text: str) -> str:
"""awg-quick strip: what `awg setconf` takes, without awg-quick's own keys."""
lines, section = [], ""
for line in text.splitlines():
stripped = line.strip()
if stripped.startswith("["):
section = stripped.lower()
elif section == "[interface]" and "=" in stripped:
if stripped.split("=", 1)[0].strip().lower() in STRIPPED_INTERFACE_KEYS:
continue
lines.append(line)
return "\n".join(lines) + "\n"
def interface_part(text: str) -> str:
out, section = [], ""
for line in strip_config(text).splitlines():
if line.strip().startswith("["):
section = line.strip().lower()
if section == "[interface]":
out.append(line.strip())
return "\n".join(out)
def apply_awg(tools: Tools, spec: dict) -> list[str]:
"""Write the AmneziaWG listeners' configs again and sync the interfaces whose peers
changed. A change to an interface itself restarts their unit."""
config = tools.config
awg = config.get("awg")
if not awg or not any(listener.get("type") == "amneziawg" for listener in spec["listeners"]):
return []
import awg_inbound
awg_dir = config["awgRuntimeDir"]
if not os.path.isdir(awg_dir):
return restart(tools, [config["awgUnit"]], "the AmneziaWG listeners are not running")
before = {}
for listener in spec["listeners"]:
if listener.get("type") == "amneziawg":
path = os.path.join(awg_dir, f"{listener['amneziaWg']['interfaceName']}.conf")
try:
with open(path, encoding="utf-8") as handle:
before[listener["amneziaWg"]["interfaceName"]] = handle.read()
except OSError:
before[listener["amneziaWg"]["interfaceName"]] = None
merged, _, _ = inbound_runtime.merge(spec)
if tools.dry_run:
return []
prepared = awg_inbound.prepare(merged, awg, awg_dir)
if {entry["interface"] for entry in prepared} != set(before):
return restart(tools, [config["awgUnit"]], "AmneziaWG listeners added or removed")
done = []
for entry in prepared:
with open(entry["config"], encoding="utf-8") as handle:
text = handle.read()
old = before.get(entry["interface"])
if old == text:
continue
if old is None or interface_part(old) != interface_part(text):
return done + restart(tools, [config["awgUnit"]], f"interface {entry['interface']} changed")
stripped = entry["config"] + ".stripped"
fd = os.open(stripped, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as handle:
handle.write(strip_config(text))
try:
tools.run([awg, "syncconf", entry["interface"], stripped], f"syncing {entry['interface']}")
except ApplyError as exc:
return done + restart(tools, [config["awgUnit"]], str(exc))
finally:
os.unlink(stripped)
done.append(f"{entry['interface']}: peers synced")
return done
# --- entry ----------------------------------------------------------------------------
def apply(config: dict, spec: dict, dry_run: bool = False) -> list[str]:
"""Both sides, under the apply lock. With the inbounds stopped (no runtime directory)
there is nothing to change in place: try-restart, which leaves them stopped."""
tools = Tools(config, dry_run)
if not os.path.isdir(config["runtimeDir"]):
return apply_awg(tools, spec) + restart(tools, [config["unit"]], "the inbounds are not running")
lock_path = os.path.join(config["runtimeDir"], "apply.lock")
fd = os.open(lock_path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
try:
fcntl.flock(fd, fcntl.LOCK_EX)
return apply_awg(tools, spec) + apply_xray(tools, spec)
finally:
os.close(fd)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
parser.add_argument("--config", required=True, help="apply.json, from the module")
parser.add_argument("--spec", required=True)
parser.add_argument("--dry-run", action="store_true")
args = parser.parse_args(argv)
with open(args.config, encoding="utf-8") as handle:
config = json.load(handle)
with open(args.spec, encoding="utf-8") as handle:
spec = json.load(handle)
try:
for line in apply(config, spec, args.dry_run):
print(line)
except (ApplyError, OSError) as exc:
print(f"error: {exc}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
File diff suppressed because it is too large. Load diff
+194
View File
@@ -0,0 +1,194 @@
#!/usr/bin/env python3
"""The inbound manager's nftables table: banned addresses, cut-off UDP, and speed limits.
- ban4/ban6: an address on a port, for a while (an address past a user's ipLimit).
- cut4/cut6: the same, for the UDP sessions of a user just switched off (inbound_apply.py).
- up/down: speed limits of XRay users, by socket mark. The patched XRay marks the sockets
its exits dial for a user of level N with MARK_BASE + N (pkgs/patches/
xray-user-level-mark.patch); the mark goes to the connection, whose packets toward the
site (original direction, leaving this host) are policed against the user's "up" limit
and those back (reply direction, arriving) against "down". Through the local proxy the
connection is on loopback, where both directions arrive and leave: each is policed once.
- awg_up/awg_down: AmneziaWG peers, by interface and tunnel address.
Limits police (drop past the rate), which TCP and QUIC back off from. The table is
replaced whole when it is missing (nftables flushed it); the limits are swapped in one
transaction; the bans' sets are left alone.
"""
from __future__ import annotations
import json
import subprocess
TABLE = "proxy_suite_inbound_limits"
MARK_BASE = 0x04000000
MARK_MASK = 0xFFFF0000
# What the exits' sockopt.mark carries: the patch's flag, and the base the levels are added to.
LEVEL_MARK_FLAG = 0x40000000
EXIT_MARK = LEVEL_MARK_FLAG | MARK_BASE
MAX_SLOTS = 0xFFFF
def ruleset(table: str = TABLE) -> str:
"""The table from nothing: an existing one of that name goes first."""
mark = f"ct mark & 0x{MARK_MASK:08x} == 0x{MARK_BASE:08x}"
return f"""table inet {table}
delete table inet {table}
table inet {table} {{
set ban4 {{ type ipv4_addr . inet_service; flags timeout; }}
set ban6 {{ type ipv6_addr . inet_service; flags timeout; }}
set cut4 {{ type ipv4_addr . inet_service; flags timeout; }}
set cut6 {{ type ipv6_addr . inet_service; flags timeout; }}
map up {{ type mark : limit; }}
map down {{ type mark : limit; }}
map awg_up4 {{ type ifname . ipv4_addr : limit; }}
map awg_down4 {{ type ifname . ipv4_addr : limit; }}
map awg_up6 {{ type ifname . ipv6_addr : limit; }}
map awg_down6 {{ type ifname . ipv6_addr : limit; }}
chain input {{
type filter hook input priority filter - 5; policy accept;
ip saddr . th dport @ban4 drop
ip6 saddr . th dport @ban6 drop
meta l4proto udp ip saddr . th dport @cut4 drop
meta l4proto udp ip6 saddr . th dport @cut6 drop
ct direction reply {mark} limit name ct mark map @down drop
}}
chain output {{
type filter hook output priority filter - 5; policy accept;
ct state new meta mark & 0x{MARK_MASK:08x} == 0x{MARK_BASE:08x} ct mark set meta mark
ct direction original {mark} limit name ct mark map @up drop
}}
chain awg_in {{
type filter hook prerouting priority filter - 5; policy accept;
limit name iifname . ip saddr map @awg_up4 drop
limit name iifname . ip6 saddr map @awg_up6 drop
}}
chain awg_out {{
type filter hook postrouting priority filter - 5; policy accept;
limit name oifname . ip daddr map @awg_down4 drop
limit name oifname . ip6 daddr map @awg_down6 drop
}}
}}
"""
def _limit(name: str, bits: int) -> str:
rate = max(bits // 8, 1)
# Room for a TCP window or two: a burst too small holds a fast link far below its rate.
burst = max(rate // 4, 65536)
return f"{name} {{ rate over {rate} bytes/second burst {burst} bytes }}"
def limits_script(table: str, existing: list[str], users: dict[int, dict], peers: list[dict]) -> str:
"""One transaction that empties the maps, drops the old limits and adds the new ones.
users: {slot: {"up": bit/s|None, "down": bit/s|None}}; peers: [{"interface", "address",
"up", "down"}]."""
lines = [f"flush map inet {table} {m}" for m in ("up", "down", "awg_up4", "awg_down4", "awg_up6", "awg_down6")]
lines += [f"delete limit inet {table} {name}" for name in sorted(existing)]
for slot, speed in sorted(users.items()):
for direction in ("up", "down"):
if speed.get(direction):
name = f"u{slot}_{direction}"
lines.append(f"add limit inet {table} {_limit(name, speed[direction])}")
lines.append(f'add element inet {table} {direction} {{ 0x{MARK_BASE + slot:08x} : "{name}" }}')
for index, peer in enumerate(peers):
family = "6" if ":" in peer["address"] else "4"
for direction in ("up", "down"):
if peer.get(direction):
name = f"p{index}_{direction}"
lines.append(f"add limit inet {table} {_limit(name, peer[direction])}")
lines.append(
f'add element inet {table} awg_{direction}{family} {{ "{peer["interface"]}" . {peer["address"]} : "{name}" }}'
)
return "\n".join(lines) + "\n"
class Netfilter:
"""nft, for the manager. Off (nft None) on hosts it cannot run on: nothing happens."""
def __init__(self, nft: str | None, table: str = TABLE):
self.nft = nft
self.table = table
self.installed: tuple | None = None
@property
def enabled(self) -> bool:
return bool(self.nft)
def _run(self, *args: str, stdin: str | None = None) -> str:
done = subprocess.run([self.nft, *args], input=stdin, capture_output=True, text=True, timeout=30)
if done.returncode != 0:
raise RuntimeError(done.stderr.strip() or f"nft exited with {done.returncode}")
return done.stdout
def present(self) -> bool:
try:
self._run("list", "table", "inet", self.table)
return True
except RuntimeError:
return False
def ensure(self) -> bool:
"""Make the table if it is gone. True when it was (the limits must go in again)."""
if not self.enabled or self.present():
return False
self._run("-f", "-", stdin=ruleset(self.table))
self.installed = None
return True
def objects(self) -> list[str]:
out = self._run("-j", "list", "table", "inet", self.table)
names = []
for item in json.loads(out).get("nftables", []):
if "limit" in item and isinstance(item["limit"], dict) and "name" in item["limit"]:
names.append(item["limit"]["name"])
return names
def sync_limits(self, users: dict[int, dict], peers: list[dict]) -> bool:
"""Install these limits unless they are what is in. True when it changed them."""
if not self.enabled:
return False
wanted = (tuple(sorted((slot, s.get("up"), s.get("down")) for slot, s in users.items())),
tuple(sorted((p["interface"], p["address"], p.get("up"), p.get("down")) for p in peers)))
if wanted == self.installed and self.present():
return False
self.ensure()
self._run("-f", "-", stdin=limits_script(self.table, self.objects(), users, peers))
self.installed = wanted
return True
def ban(self, ip: str, ports: list[int], seconds: int) -> None:
if not self.enabled or not ports:
return
family = "6" if ":" in ip else "4"
elements = ", ".join(f"{ip} . {port} timeout {int(seconds)}s" for port in sorted(set(ports)))
self._run("add", "element", "inet", self.table, f"ban{family}", "{ " + elements + " }")
def bans(self) -> list[dict]:
"""[{"ip", "port", "expires"}]: seconds left."""
if not self.enabled or not self.present():
return []
result = []
for family in ("4", "6"):
out = self._run("-j", "list", "set", "inet", self.table, f"ban{family}")
for item in json.loads(out).get("nftables", []):
for element in (item.get("set") or {}).get("elem") or []:
value = element.get("elem", element) if isinstance(element, dict) else element
expires = value.get("expires") if isinstance(value, dict) else None
concat = (value.get("val") if isinstance(value, dict) else value) or {}
parts = concat.get("concat") if isinstance(concat, dict) else None
if parts and len(parts) == 2:
result.append({"ip": str(parts[0]), "port": int(parts[1]), "expires": expires})
return result
def unban(self, ip: str) -> int:
"""Lift every ban of this address; how many there were."""
found = [ban for ban in self.bans() if ban["ip"] == ip]
if found:
family = "6" if ":" in ip else "4"
elements = ", ".join(f"{ip} . {ban['port']}" for ban in found)
self._run("delete", "element", "inet", self.table, f"ban{family}", "{ " + elements + " }")
return len(found)
+538
View File
@@ -0,0 +1,538 @@
#!/usr/bin/env python3
"""Per-user policies of the inbound manager (services.proxy-suite.inbounds.manager).
A policy says whether a user may connect and how much: switched on or off by hand, an
expiry time (or a term that starts with the first connection), a traffic allowance that may renew every day, week or month, how many
addresses may use it at once, and a speed limit. Declared users take theirs from
`inbounds.users.<name>.policy`; the manager's policy file overrides those field by field,
and holds the runtime users' whole. Only the manager (root) writes that file.
The manager's state file keeps what the policies are measured against: when each user's
traffic period began, and the speed slot (XRay user level) a limited user's sockets are
marked with. Traffic comes from the collector's file (proxy-suite-inbound-stats), whose
daily totals are summed from the period's first day, less what that day had carried before
the period began.
Whoever renders the inbounds (build-inbound.py, awg_inbound.py) asks statuses() which users
are active and at which level; this module never writes there.
"""
from __future__ import annotations
import calendar
import copy
import datetime
import fcntl
import json
import math
import os
import re
import secrets
import time
PERIODS = ("daily", "weekly", "monthly")
DEFAULT_POLICY = {
"enabled": True,
"expiresAt": None,
"expiresAfter": None,
"trafficLimit": None,
"trafficPeriod": None,
"ipLimit": None,
"speedLimit": None,
"meta": {},
}
FIELDS = tuple(DEFAULT_POLICY)
MAX_META_KEYS = 32
MAX_META_VALUE = 1024
STATE_VERSION = 1
MAX_TIME = 253402214400 # 9999-12-31
class PolicyError(ValueError):
"""A policy value that cannot be used."""
# --- parsing --------------------------------------------------------------------------
_SIZE = re.compile(r"\s*([0-9]+(?:\.[0-9]+)?)\s*([KMGTP]?)(?:I?B)?\s*", re.IGNORECASE)
_RATE = re.compile(r"\s*([0-9]+(?:\.[0-9]+)?)\s*([KMG]?)(?:BIT|BPS|BIT/S|B/S)?\s*", re.IGNORECASE)
_RELATIVE = re.compile(r"\s*\+\s*([0-9]+)\s*([mhdw])\s*", re.IGNORECASE)
_DURATION = re.compile(r"\s*\+?\s*([0-9]+)\s*([mhdw])\s*", re.IGNORECASE)
SIZE_UNITS = {"": 1, "K": 1024, "M": 1024**2, "G": 1024**3, "T": 1024**4, "P": 1024**5}
RATE_UNITS = {"": 1, "K": 1000, "M": 1000**2, "G": 1000**3}
RELATIVE_UNITS = {"m": 60, "h": 3600, "d": 86400, "w": 7 * 86400}
def parse_size(value) -> int | None:
"""Bytes, from an int or "50G", "1.5T", "512MiB": binary units, as clients show them.
None, "", "none", "unlimited" and 0 mean no limit."""
if value is None or value == 0:
return None
if type(value) is int:
if value < 0:
raise PolicyError(f"size {value} is negative")
return value
if not isinstance(value, str):
raise PolicyError(f"size {json.dumps(value)} is neither a number nor a string")
if value.strip().lower() in ("", "none", "unlimited", "0"):
return None
match = _SIZE.fullmatch(value)
if not match:
raise PolicyError(f"size {json.dumps(value)}: a number with K, M, G or T")
return int(float(match.group(1)) * SIZE_UNITS[match.group(2).upper()])
def parse_rate(value) -> int | None:
"""Bits per second, from an int or "10M", "500k", "1G": decimal units, as ISPs sell them."""
if value is None or value == 0:
return None
if type(value) is int:
if value < 0:
raise PolicyError(f"rate {value} is negative")
return value
if not isinstance(value, str):
raise PolicyError(f"rate {json.dumps(value)} is neither a number nor a string")
if value.strip().lower() in ("", "none", "unlimited", "0"):
return None
match = _RATE.fullmatch(value)
if not match:
raise PolicyError(f"rate {json.dumps(value)}: bits per second, a number with k, M or G")
return int(float(match.group(1)) * RATE_UNITS[match.group(2).upper()])
def parse_speed(value) -> dict | None:
"""{"up": bit/s|None, "down": bit/s|None}, from one rate for both ("20M"), "down/up"
("20M/5M"), or such an object. None: no limit."""
if value is None:
return None
if isinstance(value, dict):
unknown = set(value) - {"up", "down"}
if unknown:
raise PolicyError(f"speedLimit: unknown keys {sorted(unknown)}")
speed = {"up": parse_rate(value.get("up")), "down": parse_rate(value.get("down"))}
elif isinstance(value, str) and "/" in value:
down, up = value.split("/", 1)
speed = {"up": parse_rate(up), "down": parse_rate(down)}
else:
rate = parse_rate(value)
speed = {"up": rate, "down": rate}
return speed if speed["up"] or speed["down"] else None
def parse_duration(value) -> int | None:
"""Seconds, from an int or "30d", "+12h" (m, h, d, w). None, "", "none" and 0: none."""
if value is None or value == 0:
return None
if type(value) is int:
if value < 0:
raise PolicyError(f"duration {value} is negative")
return value
if not isinstance(value, str):
raise PolicyError(f"duration {json.dumps(value)} is neither a number nor a string")
text = value.strip()
if text.lower() in ("", "none", "0"):
return None
if text.isdigit():
return int(text)
match = _DURATION.fullmatch(text)
if not match:
raise PolicyError(f"duration {json.dumps(value)}: a number with m, h, d or w, such as 30d")
return int(match.group(1)) * RELATIVE_UNITS[match.group(2).lower()] or None
def _local_midnight(day: datetime.date) -> int:
return int(time.mktime(day.timetuple()))
def parse_time(value, now: float | None = None) -> int | None:
"""A Unix time from an int, "2026-12-31" (the end of that day, local time),
"2026-12-31T18:00" (local), an ISO time with its zone, or "+30d" from now (m, h, d, w).
None, "", "never": no expiry."""
if value is None:
return None
if type(value) is int:
return value
if not isinstance(value, str):
raise PolicyError(f"time {json.dumps(value)} is neither a number nor a string")
text = value.strip()
if text.lower() in ("", "never", "none"):
return None
if text.isdigit():
return int(text)
relative = _RELATIVE.fullmatch(text)
if relative:
base = time.time() if now is None else now
return int(base) + int(relative.group(1)) * RELATIVE_UNITS[relative.group(2).lower()]
try:
if re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}", text):
return _local_midnight(datetime.date.fromisoformat(text) + datetime.timedelta(days=1))
moment = datetime.datetime.fromisoformat(text)
except ValueError:
raise PolicyError(f"time {json.dumps(value)}: a date, an ISO time, a Unix time or +<n>d") from None
return int(moment.timestamp())
# --- policies -------------------------------------------------------------------------
def _check_meta(value) -> dict:
if not isinstance(value, dict):
raise PolicyError("meta must be an object of strings")
if len(value) > MAX_META_KEYS:
raise PolicyError(f"meta holds at most {MAX_META_KEYS} keys")
for key, item in value.items():
if not isinstance(key, str) or not re.fullmatch(r"[A-Za-z0-9_.-]{1,64}", key):
raise PolicyError(f"meta key {json.dumps(key)}: letters, digits, dot, dash and underscore, up to 64")
if not isinstance(item, str) or len(item) > MAX_META_VALUE:
raise PolicyError(f"meta.{key} must be a string of at most {MAX_META_VALUE} characters")
return dict(value)
def normalize(fields: dict, now: float | None = None) -> dict:
"""Policy fields as the file keeps them, from what a person or a bot gave: sizes,
rates and times in any form parse_* takes. Only the fields given."""
if not isinstance(fields, dict):
raise PolicyError("a policy is an object")
unknown = set(fields) - set(FIELDS)
if unknown:
raise PolicyError(f"unknown policy fields: {', '.join(sorted(unknown))}")
out: dict = {}
for key, value in fields.items():
if key == "enabled":
if type(value) is not bool:
raise PolicyError("enabled must be true or false")
out[key] = value
elif key == "expiresAt":
# 0 is no expiry, as 0 is no limit in the other fields: not 1970.
out[key] = None if value in (0, "0") else parse_time(value, now)
if out[key] is not None and not 0 < out[key] < MAX_TIME:
raise PolicyError(f"time {json.dumps(value)} is out of range")
elif key == "expiresAfter":
out[key] = parse_duration(value)
if out[key] is not None and out[key] >= MAX_TIME:
raise PolicyError(f"duration {json.dumps(value)} is out of range")
elif key == "trafficLimit":
out[key] = parse_size(value)
elif key == "trafficPeriod":
if value in (None, "", "none", "never"):
out[key] = None
elif value in PERIODS:
out[key] = value
else:
raise PolicyError(f"trafficPeriod must be one of {', '.join(PERIODS)} or none")
elif key == "ipLimit":
if value in (None, 0, ""):
out[key] = None
elif type(value) is int and value > 0:
out[key] = value
elif isinstance(value, str) and value.isdigit():
out[key] = int(value) or None
else:
raise PolicyError("ipLimit must be a positive number, or 0 for none")
elif key == "speedLimit":
out[key] = parse_speed(value)
elif key == "meta":
out[key] = _check_meta(value)
return out
def check_stored(entry: dict) -> dict:
"""A stored policy, already normalized: the same check, which must change nothing."""
normalized = normalize(entry)
if normalized != entry:
raise PolicyError("not in its stored form")
return entry
def effective(declared: dict | None, stored: dict | None) -> dict:
"""The defaults, then the declared policy, then the stored one, field by field."""
policy = copy.deepcopy(DEFAULT_POLICY)
for layer in (declared or {}, stored or {}):
for key in FIELDS:
if key in layer:
policy[key] = copy.deepcopy(layer[key])
return policy
def declared_policies(spec: dict) -> dict[str, dict]:
"""The declared users' `policy` options, normalized; a bad one is left out (the module's
assertions catch it at build time)."""
policies = {}
for name, user in (spec.get("users") or {}).items():
declared = {k: v for k, v in (user.get("policy") or {}).items() if v is not None}
try:
policies[name] = normalize(declared)
except PolicyError:
continue
return policies
# --- files ----------------------------------------------------------------------------
def read_json(path: str, default):
try:
with open(path, encoding="utf-8") as handle:
value = json.load(handle)
except FileNotFoundError:
return copy.deepcopy(default)
except (OSError, ValueError):
return copy.deepcopy(default)
return value if isinstance(value, type(default)) else copy.deepcopy(default)
def write_json(path: str, value, mode: int = 0o600) -> None:
"""Atomically, through a new file of its own next to it."""
directory = os.path.dirname(path) or "."
os.makedirs(directory, mode=0o700, exist_ok=True)
tmp = os.path.join(directory, f".{os.path.basename(path)}.{secrets.token_hex(6)}")
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, mode)
try:
with os.fdopen(fd, "w", encoding="utf-8") as handle:
handle.write(json.dumps(value, indent=2, sort_keys=True) + "\n")
handle.flush()
os.fsync(handle.fileno())
os.replace(tmp, path)
except BaseException:
try:
os.unlink(tmp)
except OSError:
pass
raise
class Locked:
"""flock on <path>.lock, for a read-modify-write of path."""
def __init__(self, path: str):
self.path = path + ".lock"
self.fd = -1
def __enter__(self):
os.makedirs(os.path.dirname(self.path) or ".", mode=0o700, exist_ok=True)
self.fd = os.open(self.path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
fcntl.flock(self.fd, fcntl.LOCK_EX)
return self
def __exit__(self, *_):
os.close(self.fd)
def load_policies(path: str) -> dict[str, dict]:
"""The policy file: {name: stored fields}; entries that do not hold up are left out."""
raw = read_json(path, {})
policies = {}
for name, entry in (raw.get("users") or {}).items() if isinstance(raw.get("users"), dict) else []:
try:
policies[name] = check_stored(entry)
except PolicyError:
continue
return policies
def _count(value) -> bool:
return type(value) is int and value >= 0
def check_user_state(entry) -> dict:
"""A user's entry in the state file, as start_period() and roll_period() make it: the
renderers read it at every start, so a bad one (an import, a hand edit) must not get in."""
if not isinstance(entry, dict):
raise PolicyError("a user's state is an object")
for key in ("periodStart", "baselineUp", "baselineDown"):
if key in entry and not _count(entry[key]):
raise PolicyError(f"{key} must be a whole number")
# A date the calendar functions still take (the year 9999).
if entry.get("periodStart", 0) >= MAX_TIME:
raise PolicyError("periodStart is too far ahead")
if "anchorDay" in entry and not (type(entry["anchorDay"]) is int and 1 <= entry["anchorDay"] <= 31):
raise PolicyError("anchorDay must be a day of the month")
if "notified" in entry and not isinstance(entry["notified"], dict):
raise PolicyError("notified must be an object")
return entry
def load_state(path: str) -> dict:
"""The state file; entries that do not hold up are left out, as the policy file's are."""
state = read_json(path, {})
state.setdefault("version", STATE_VERSION)
for key in ("users", "slots", "bans", "seen", "subscriptions"):
if not isinstance(state.get(key), dict):
state[key] = {}
for name, entry in list(state["users"].items()):
try:
check_user_state(entry)
except PolicyError:
del state["users"][name]
for name, slot in list(state["slots"].items()):
if not (type(slot) is int and slot > 0):
del state["slots"][name]
for name, first in list(state["seen"].items()):
if not isinstance(first, dict):
del state["seen"][name]
# Salts of the users whose subscription URL was moved on (proxy_inbound.subscription_token).
for name, salt in list(state["subscriptions"].items()):
if not is_subscription_salt(salt):
del state["subscriptions"][name]
return state
def is_subscription_salt(value) -> bool:
return isinstance(value, str) and re.fullmatch(r"[0-9a-f]{32}", value) is not None
def read_stats(path: str) -> dict:
return read_json(path, {})
# --- traffic --------------------------------------------------------------------------
def day_key(ts: float) -> str:
"""The collector's day: its `date +%F`, in local time."""
return time.strftime("%Y-%m-%d", time.localtime(ts))
def _counters(entry) -> tuple[int, int]:
"""(up, down) of one day's counters; nothing from a malformed entry, which must not stop
the renderers that ask statuses()."""
if not isinstance(entry, dict):
return 0, 0
def number(value) -> int:
# jq may write a large sum as a float.
return int(value) if type(value) in (int, float) and math.isfinite(value) and value >= 0 else 0
return number(entry.get("up", 0)), number(entry.get("down", 0))
def day_traffic(stats: dict, day: str, name: str) -> tuple[int, int]:
buckets = (stats.get("days") or {}).get(day)
users = buckets.get("user") if isinstance(buckets, dict) else None
return _counters(users.get(name) if isinstance(users, dict) else None)
def day_total(stats: dict, day: str, name: str) -> int:
return sum(day_traffic(stats, day, name))
def period_traffic(stats: dict, user_state: dict, name: str) -> tuple[int, int]:
"""(up, down) since the period began: every day from its first, less what that day had
before it (the baselines). A user the manager has not measured yet has used nothing:
their count begins when it first sees them, not with whatever the file kept before."""
start = user_state.get("periodStart")
if not start:
return 0, 0
first = day_key(start)
up = down = 0
days = stats.get("days")
for day, buckets in (days.items() if isinstance(days, dict) else []):
if not isinstance(day, str) or day < first or not isinstance(buckets, dict):
continue
users = buckets.get("user")
day_up, day_down = _counters(users.get(name) if isinstance(users, dict) else None)
up += day_up
down += day_down
return (max(up - int(user_state.get("baselineUp", 0) or 0), 0),
max(down - int(user_state.get("baselineDown", 0) or 0), 0))
def used_bytes(stats: dict, user_state: dict, name: str) -> int:
return sum(period_traffic(stats, user_state, name))
def _add_period(day: datetime.date, period: str, anchor_day: int) -> datetime.date:
if period == "daily":
return day + datetime.timedelta(days=1)
if period == "weekly":
return day + datetime.timedelta(days=7)
year, month = (day.year + 1, 1) if day.month == 12 else (day.year, day.month + 1)
return datetime.date(year, month, min(anchor_day, calendar.monthrange(year, month)[1]))
def period_end(policy: dict, user_state: dict) -> int | None:
"""When the current period ends and the traffic starts over, or None."""
period = policy.get("trafficPeriod")
start = user_state.get("periodStart")
if period not in PERIODS or not start:
return None
first = datetime.date.fromtimestamp(start)
anchor = int(user_state.get("anchorDay") or first.day)
return _local_midnight(_add_period(first, period, anchor))
def start_period(stats: dict, name: str, now: float) -> dict:
"""A period that begins now: the day so far is the baseline. A renewing period begins
at midnight, so a monthly one renews on this day of the month."""
up, down = day_traffic(stats, day_key(now), name)
return {
"periodStart": int(now),
"baselineUp": up,
"baselineDown": down,
"anchorDay": datetime.date.fromtimestamp(now).day,
}
def roll_period(policy: dict, user_state: dict, now: float) -> bool:
"""Move a renewing period on past now, from boundary to boundary (midnights, so nothing
of the day before counts). True when it moved."""
moved = False
while True:
end = period_end(policy, user_state)
if end is None or end > now:
return moved
user_state["periodStart"] = end
user_state["baselineUp"] = user_state["baselineDown"] = 0
moved = True
# --- status ---------------------------------------------------------------------------
def on_hold(policy: dict) -> bool:
"""A term that starts with the first connection, and has not: expiresAfter without
expiresAt. An expiresAt set by hand wins over it."""
return policy.get("expiresAt") is None and bool(policy.get("expiresAfter"))
def status(policy: dict, used: int, now: float) -> dict:
"""{"active", "reasons"}: why a user may not connect now, if they may not. A user on
hold may: their term begins when they do."""
reasons = []
if not policy.get("enabled", True):
reasons.append("disabled")
expires = policy.get("expiresAt")
if expires is not None and now >= expires:
reasons.append("expired")
limit = policy.get("trafficLimit")
if limit is not None and used >= limit:
reasons.append("traffic")
return {"active": not reasons, "reasons": reasons}
def user_names(spec: dict, runtime_users) -> list[str]:
return sorted(set(spec.get("users") or {}) | set(runtime_users))
def statuses(spec: dict, runtime_users, now: float | None = None) -> dict[str, dict]:
"""Each user's {"active", "level", "reasons"}, for the renderers. Empty without the
manager: everyone active, nobody limited, as before it."""
manager = spec.get("manager")
if not manager:
return {}
now = time.time() if now is None else now
declared = declared_policies(spec)
stored = load_policies(manager["policyFile"])
state = load_state(manager["stateFile"])
stats = read_stats(manager["statsFile"])
result = {}
for name in user_names(spec, runtime_users):
policy = effective(declared.get(name), stored.get(name))
user_state = copy.deepcopy(state["users"].get(name) or {})
roll_period(policy, user_state, now)
view = status(policy, used_bytes(stats, user_state, name), now)
slot = state["slots"].get(name)
limited = bool(policy.get("speedLimit")) and manager.get("speedLimits", False)
view["level"] = int(slot) if limited and isinstance(slot, int) and slot > 0 else 0
result[name] = view
return result
+58 -9
View File
@@ -37,6 +37,8 @@ import time
import urllib.parse
import uuid
import inbound_policy
# User names and listener tags: they become file names, XRay emails and tags, and URL parts.
NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,31}")
MAX_ENTRY_BYTES = 65536
@@ -841,17 +843,55 @@ def number_users(spec: dict, names: list[str], state_users: dict, warnings: list
return numbered
def merge_state(spec: dict, state: dict, check_ports: bool = False) -> tuple[dict, dict, list[str]]:
# Listener types whose XRay inbound runs with no client at all, so a user switched off by
# the manager leaves it in place, ready to take them back without a restart. A Shadowsocks
# listener has a client list only with more than one user (render_xray_inbound).
EMPTY_CLIENTS_TYPES = ("vless", "vmess", "trojan", "hysteria2")
def _runs_without_clients(listener: dict) -> bool:
if listener.get("type") in EMPTY_CLIENTS_TYPES:
return True
return listener.get("type") == "shadowsocks" and len(listener["users"]) > 1
def apply_statuses(merged: dict, statuses: dict, warnings: list[str]) -> None:
"""The manager's view of each user (inbound_policy.statuses): "active" and "level" on
every listener's users. A listener whose users are all switched off stays when it runs
without clients, and is left out otherwise, as one without users is."""
kept = []
for listener in merged["listeners"]:
for user in listener["users"]:
view = statuses.get(user["name"]) or {}
user["active"] = view.get("active", True)
user["level"] = view.get("level", 0)
if (
listener["users"]
and listener.get("type") not in (None, "amneziawg")
and not any(user["active"] for user in listener["users"])
and not _runs_without_clients(listener)
):
warnings.append(f"listener '{listener['tag']}' has no active users; not started")
continue
kept.append(listener)
merged["listeners"] = kept
def merge_state(spec: dict, state: dict, check_ports: bool | set = False, statuses: dict | None = None) -> tuple[dict, dict, list[str]]:
"""The spec with the runtime entries merged in, what was made of them, and warnings.
The result's "runtime" key holds {"listeners": [runtime tags kept], "users": [runtime
names kept], "selfSources": [...], "problems": {("user"|"listener", name): [why]}}.
statuses: the manager's, by user name (inbound_policy.statuses); None leaves everyone
active, at level 0.
"""
runtime = spec.get("runtime")
merged = copy.deepcopy(spec)
result = {"listeners": [], "users": [], "selfSources": [], "problems": {}}
if not runtime:
return merged, result, []
warnings: list[str] = []
apply_statuses(merged, statuses or {}, warnings)
return merged, result, warnings
warnings: list[str] = []
problems: dict = result["problems"]
@@ -948,7 +988,11 @@ def merge_state(spec: dict, state: dict, check_ports: bool = False) -> tuple[dic
why = [f"cannot be checked: {exc}"]
if listener["port"] in declared_ports or listener["port"] in used_ports:
why.append(f"port {listener['port']} is taken by another listener")
if not why and check_ports and not port_free(listener["listen"], listener["port"], _protocols(listener)):
# check_ports may name the ports the running XRay holds already (inbound_apply.py):
# those are its own, not taken.
held = check_ports if isinstance(check_ports, (set, frozenset)) else set()
if (not why and check_ports and listener["port"] not in held
and not port_free(listener["listen"], listener["port"], _protocols(listener))):
why.append(f"port {listener['port']} is in use on this host")
if why:
for message in why:
@@ -1005,16 +1049,21 @@ def merge_state(spec: dict, state: dict, check_ports: bool = False) -> tuple[dic
}
result["users"] = sorted(users)
result["selfSources"] = number_users(spec, sorted(on_xray), state["users"], warnings)
apply_statuses(merged, statuses or {}, warnings)
result["listeners"] = [tag for tag in result["listeners"] if any(l["tag"] == tag for l in merged["listeners"])]
return merged, result, warnings
def merge(spec: dict, check_ports: bool = False) -> tuple[dict, dict, list[str]]:
"""merge_state() on the spool the spec names, as the services read it at start."""
def merge(spec: dict, check_ports: bool | set = False, now: float | None = None) -> tuple[dict, dict, list[str]]:
"""merge_state() on the spool the spec names, as the services read it at start, with
the manager's statuses when it is on."""
runtime = spec.get("runtime")
if not runtime:
return spec, {"listeners": [], "users": [], "selfSources": [], "problems": {}}, []
state, warnings = load_spool(runtime["spool"])
merged, result, more = merge_state(spec, state, check_ports)
state, warnings = load_spool(runtime["spool"]) if runtime else ({"users": {}, "listeners": {}}, [])
statuses = inbound_policy.statuses(spec, state["users"], now) if spec.get("manager") else None
merged, result, more = merge_state(spec, state, check_ports, statuses)
if spec.get("manager"):
# Users whose subscription URL the manager moved on (proxy_inbound.subscription_token).
merged["subscriptionSalts"] = inbound_policy.load_state(spec["manager"]["stateFile"])["subscriptions"]
return merged, result, warnings + more
+543
View File
@@ -0,0 +1,543 @@
#!/usr/bin/env python3
"""A user's subscription in the shape their client asks for (inbounds.manager).
The manager serves one URL per user. Most clients (v2rayN, v2rayNG, Happ, Hiddify,
Streisand, Shadowrocket, NekoBox) read base64 of the share links, which stays the answer to
anything not recognized. Clash and mihomo clients get a config of proxies and groups, the
sing-box apps a sing-box config, and a browser a page with the subscription's state, a QR
code and buttons that open it in an app. `?format=` picks one by hand.
Everything comes from rendered.json (proxy_inbound.build_inbounds): each link's client
outbound is already parsed there, as sing-box JSON where sing-box can dial it and XRay's
where only XRay can (XHTTP, ECH). The configs leave those out; the links keep them.
"""
from __future__ import annotations
import base64
import datetime
import hashlib
import html
import json
import re
import urllib.parse
FORMATS = ("base64", "links", "clash", "sing-box", "html")
# The configs' own groups and exits, which no server may be named as.
RESERVED = {"proxy", "auto", "direct", "block", "reject", "dns"}
# By the start of the User-Agent: Hiddify says "like ClashMeta v2ray sing-box" further on,
# and reads the links best.
_CLASH_AGENTS = re.compile(r"(clash|mihomo|stash|flclash|koala-clash)", re.IGNORECASE)
_SING_BOX_AGENTS = re.compile(r"(SF[AIMT]/|sing-box)", re.IGNORECASE)
def pick_format(query_format: str | None, user_agent: str, accept: str) -> str:
"""The format to answer in: the query's, or one the client is known to read."""
if query_format in FORMATS:
return query_format
if _CLASH_AGENTS.match(user_agent):
return "clash"
if _SING_BOX_AGENTS.match(user_agent):
return "sing-box"
if user_agent.startswith("Mozilla/") and "text/html" in accept:
return "html"
return "base64"
def entries(rendered: dict, user: str) -> list[dict]:
"""The user's links as subscriptions carry them: no AmneziaWG configs, which clients
reading these do not speak. Each with a name of its own, the listener's tag and variant."""
result = []
seen: set[str] = set()
for link in rendered.get("links") or []:
if link.get("user") != user or link.get("config") is not None:
continue
name = link.get("tag", "proxy") + (f"-{link['variant']}" if link.get("variant") else "")
base, index = name, 2
if name.lower() in RESERVED:
name = f"{base}-{index}"
index += 1
while name in seen:
name, index = f"{base}-{index}", index + 1
seen.add(name)
result.append({**link, "name": name})
return result
# --- sing-box -------------------------------------------------------------------------
def sing_box_outbounds(items: list[dict]) -> list[dict]:
"""Outbounds sing-box dials, named for the config: XRay-only ones are left out."""
outbounds = []
for item in items:
outbound = item.get("outbound")
if isinstance(outbound, dict) and "type" in outbound:
outbounds.append({**outbound, "tag": item["name"]})
return outbounds
def sing_box_config(items: list[dict]) -> dict:
"""A whole client config for the sing-box apps (1.12 and later): TUN, the user's
servers under a selector whose default picks the fastest, private networks direct."""
outbounds = sing_box_outbounds(items)
names = [o["tag"] for o in outbounds]
groups = []
if names:
groups = [
{"type": "selector", "tag": "proxy", "outbounds": ["auto", *names], "default": "auto"},
{"type": "urltest", "tag": "auto", "outbounds": names, "interval": "10m"},
]
return {
"log": {"level": "warn"},
"dns": {
"servers": [
{"type": "https", "tag": "remote", "server": "1.1.1.1", "detour": "proxy" if names else "direct"},
{"type": "local", "tag": "local"},
],
"final": "remote",
},
"inbounds": [
{
"type": "tun",
"tag": "tun-in",
"address": ["172.19.0.1/30", "fdfe:dcba:9876::1/126"],
"auto_route": True,
"strict_route": True,
}
],
"outbounds": [*groups, *outbounds, {"type": "direct", "tag": "direct"}],
"route": {
"rules": [
{"action": "sniff"},
{"protocol": "dns", "action": "hijack-dns"},
{"ip_is_private": True, "outbound": "direct"},
],
"final": "proxy" if names else "direct",
"auto_detect_interface": True,
"default_domain_resolver": "local",
},
}
# --- Clash and mihomo -----------------------------------------------------------------
def _clash_tls(proxy: dict, tls: dict, sni_key: str) -> None:
if not tls.get("enabled"):
return
proxy["tls"] = True
if tls.get("server_name"):
proxy[sni_key] = tls["server_name"]
if tls.get("insecure"):
proxy["skip-cert-verify"] = True
if tls.get("alpn"):
proxy["alpn"] = list(tls["alpn"])
fingerprint = (tls.get("utls") or {}).get("fingerprint")
if fingerprint:
proxy["client-fingerprint"] = fingerprint
reality = tls.get("reality") or {}
if reality.get("enabled"):
proxy["reality-opts"] = {"public-key": reality.get("public_key", ""), "short-id": reality.get("short_id", "")}
proxy.setdefault("client-fingerprint", "chrome")
def _clash_transport(proxy: dict, transport: dict | None) -> bool:
"""mihomo's network and its options; False for a transport it lacks."""
if not transport:
proxy["network"] = "tcp"
return True
kind = transport.get("type")
if kind in ("ws", "httpupgrade"):
proxy["network"] = "ws"
opts: dict = {"path": transport.get("path") or "/"}
host = (transport.get("headers") or {}).get("Host") or transport.get("host")
if host:
opts["headers"] = {"Host": host}
if kind == "httpupgrade":
opts["v2ray-http-upgrade"] = True
proxy["ws-opts"] = opts
elif kind == "grpc":
proxy["network"] = "grpc"
proxy["grpc-opts"] = {"grpc-service-name": transport.get("service_name", "")}
elif kind == "http":
proxy["network"] = "h2"
proxy["h2-opts"] = {"host": list(transport.get("host") or []), "path": transport.get("path") or "/"}
else:
return False
return True
def clash_proxy(name: str, outbound: dict) -> dict | None:
"""A mihomo proxy from a sing-box outbound; None for what it cannot dial the same way."""
kind = outbound.get("type")
proxy: dict = {"name": name, "server": outbound.get("server"), "port": outbound.get("server_port")}
tls = outbound.get("tls") or {}
if kind in ("vless", "vmess"):
proxy.update(type=kind, uuid=outbound.get("uuid"), udp=True)
if kind == "vless":
if outbound.get("flow"):
proxy["flow"] = outbound["flow"]
if outbound.get("packet_encoding"):
proxy["packet-encoding"] = outbound["packet_encoding"]
else:
proxy.update({"alterId": outbound.get("alter_id", 0), "cipher": outbound.get("security") or "auto"})
_clash_tls(proxy, tls, "servername")
elif kind == "trojan":
proxy.update(type="trojan", password=outbound.get("password"), udp=True)
_clash_tls(proxy, tls, "sni")
elif kind == "shadowsocks":
if outbound.get("plugin"):
return None
proxy.update(type="ss", cipher=outbound.get("method"), password=outbound.get("password"), udp=True)
elif kind == "hysteria2":
proxy.update(type="hysteria2", password=outbound.get("password"))
if tls.get("server_name"):
proxy["sni"] = tls["server_name"]
if tls.get("insecure"):
proxy["skip-cert-verify"] = True
if tls.get("alpn"):
proxy["alpn"] = list(tls["alpn"])
obfs = outbound.get("obfs") or {}
if obfs.get("type"):
proxy.update({"obfs": obfs["type"], "obfs-password": obfs.get("password", "")})
if outbound.get("server_ports"):
proxy["ports"] = ",".join(p.replace(":", "-") for p in outbound["server_ports"])
return proxy
elif kind in ("socks", "http"):
proxy["type"] = "socks5" if kind == "socks" else "http"
for key in ("username", "password"):
if outbound.get(key):
proxy[key] = outbound[key]
_clash_tls(proxy, tls, "sni")
return proxy
else:
return None
if kind in ("vless", "vmess", "trojan") and not _clash_transport(proxy, outbound.get("transport")):
return None
return proxy
def clash_config(items: list[dict]) -> dict:
"""A mihomo config: the user's servers, a group that picks the fastest and one to choose
by hand, private networks direct."""
proxies = []
for item in items:
outbound = item.get("outbound")
if isinstance(outbound, dict) and "type" in outbound:
proxy = clash_proxy(item["name"], outbound)
if proxy is not None:
proxies.append(proxy)
names = [p["name"] for p in proxies]
groups = [
{"name": "PROXY", "type": "select", "proxies": ["auto", *names] if names else ["DIRECT"]},
{"name": "auto", "type": "url-test", "proxies": names or ["DIRECT"],
"url": "https://www.gstatic.com/generate_204", "interval": 600},
]
return {
"mixed-port": 7890,
"mode": "rule",
"log-level": "warning",
"proxies": proxies,
"proxy-groups": groups,
"rules": [
"IP-CIDR,10.0.0.0/8,DIRECT,no-resolve",
"IP-CIDR,172.16.0.0/12,DIRECT,no-resolve",
"IP-CIDR,192.168.0.0/16,DIRECT,no-resolve",
"IP-CIDR,127.0.0.0/8,DIRECT,no-resolve",
"MATCH,PROXY",
],
}
# --- the page -------------------------------------------------------------------------
TEXT = {
"en": {
"active": "Active", "hold": "Starts with the first connection", "off": "Switched off",
"disabled": "switched off", "expired": "expired", "traffic": "out of traffic",
"used": "Traffic", "of": "of", "unlimited": "unlimited", "renews": "renews",
"expires": "Expires", "never": "never", "term": "for {} from the first connection",
"sub": "Subscription", "copy": "Copy", "copied": "Copied", "open": "Add to an app",
"more": "Other apps", "links": "Connections", "support": "Support", "user": "User",
"hint": "Keep this page to yourself: its address is your access.",
},
"ru": {
"active": "Активна", "hold": "Начнётся с первого подключения", "off": "Отключена",
"disabled": "отключена", "expired": "срок истёк", "traffic": "трафик исчерпан",
"used": "Трафик", "of": "из", "unlimited": "без лимита", "renews": "обновится",
"expires": "Действует до", "never": "бессрочно", "term": "{} с первого подключения",
"sub": "Подписка", "copy": "Копировать", "copied": "Скопировано", "open": "Добавить в приложение",
"more": "Другие приложения", "links": "Подключения", "support": "Поддержка", "user": "Пользователь",
"hint": "Не показывайте эту страницу никому: её адрес и есть ваш доступ.",
},
}
ANDROID, IOS, MACOS, WINDOWS, LINUX = "android", "ios", "macos", "windows", "linux"
EVERYWHERE = frozenset({ANDROID, IOS, MACOS, WINDOWS, LINUX})
# Each opens the subscription in that app, on the systems the app takes the link on; {url} is
# quoted, {raw} is not. clash:// is taken by Clash Meta, FlClash, Clash Verge Rev, Clash Party
# and Stash; v2rayN and Throne take no link, only the URL pasted.
APPS = [
("Happ", "happ://add/{raw}", EVERYWHERE),
("Hiddify", "hiddify://import/{raw}#{name}", EVERYWHERE),
("v2rayNG", "v2rayng://install-config?url={url}#{name}", {ANDROID}),
("Streisand", "streisand://import/{raw}#{name}", {IOS, MACOS}),
("Karing", "karing://install-config?url={url}&name={name}", {ANDROID, IOS, MACOS, WINDOWS}),
("sing-box", "sing-box://import-remote-profile?url={url}#{name}", {ANDROID, IOS, MACOS}),
("Clash / mihomo", "clash://install-config?url={url}&name={name}", EVERYWHERE),
# proxy-suite-gui (gui.enable): asks before it runs `proxy subs add`.
("Proxy Suite", "proxy-suite://install-config?url={url}&name={name}", {LINUX}),
]
# In this order: Android's User-Agent says Linux too, and a Chromebook runs Android apps.
_PLATFORMS = [
(ANDROID, re.compile(r"Android|CrOS")),
(IOS, re.compile(r"iPhone|iPad|iPod")),
(WINDOWS, re.compile(r"Windows")),
(MACOS, re.compile(r"Macintosh|Mac OS X")),
(LINUX, re.compile(r"Linux|X11")),
]
def platform(user_agent: str) -> str | None:
"""The system a browser runs on, as APPS names them; None when it does not say."""
return next((name for name, pattern in _PLATFORMS if pattern.search(user_agent or "")), None)
def language(accept_language: str) -> str:
for part in (accept_language or "").split(","):
tag = part.split(";")[0].strip().lower()
if tag.startswith("ru"):
return "ru"
if tag.startswith("en"):
return "en"
return "en"
def human_bytes(value: int) -> str:
size = float(value)
for unit in ("B", "KiB", "MiB", "GiB", "TiB"):
if size < 1024 or unit == "TiB":
return f"{size:.0f} {unit}" if unit == "B" else f"{size:.1f} {unit}"
size /= 1024
return f"{value} B"
def human_span(seconds: int) -> str:
for unit, size in (("w", 604800), ("d", 86400), ("h", 3600), ("m", 60)):
if seconds % size == 0:
return f"{seconds // size}{unit}"
return f"{seconds}s"
_STYLE = """
:root{--bg:#f6f7f9;--card:#fff;--fg:#1c1f24;--muted:#646b75;--line:#e1e4e8;--accent:#2563eb;--ok:#15803d;--warn:#b45309;--bad:#b91c1c}
@media (prefers-color-scheme:dark){:root{--bg:#111316;--card:#1b1e23;--fg:#e8eaed;--muted:#9aa1ab;--line:#2c3036;--accent:#6ea0ff;--ok:#4ade80;--warn:#fbbf24;--bad:#f87171}}
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.5 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
main{max-width:560px;margin:0 auto;padding:24px 16px 48px}h1{font-size:22px;margin:0 0 4px}
.card{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:16px;margin-top:16px}
.status{font-weight:600}.ok{color:var(--ok)}.warn{color:var(--warn)}.bad{color:var(--bad)}
.row{display:flex;justify-content:space-between;gap:12px;padding:6px 0;border-bottom:1px solid var(--line)}.row:last-child{border:0}
.muted{color:var(--muted);font-size:14px}.bar{display:block;width:100%;height:6px;border-radius:3px;overflow:hidden;margin-top:6px}
.bar .track{fill:var(--line)}.bar .fill{fill:var(--accent)}
.qr{display:flex;justify-content:center;margin:8px 0}.qr svg{width:220px;height:220px;background:#fff;border-radius:8px}
code{display:block;word-break:break-all;font-size:13px;background:var(--bg);border:1px solid var(--line);border-radius:8px;padding:8px;margin:8px 0}
button,a.app{font:inherit;font-size:14px;border:1px solid var(--line);background:var(--bg);color:var(--fg);border-radius:8px;padding:6px 12px;cursor:pointer;text-decoration:none;display:inline-block;margin:4px 4px 0 0}
button:hover,a.app:hover{border-color:var(--accent)}
summary{cursor:pointer;color:var(--muted);font-size:14px;margin-top:12px}h2{font-size:16px;margin:0 0 8px}h2.next{margin-top:16px}
"""
# The QR code is drawn by the browser: a request costs the server no encoder run, and the page
# takes no image from elsewhere, for the people opening it may not reach much. qrMatrix(text):
# the modules, rows of booleans, of the smallest QR code (byte mode, error correction M) that
# holds text, mask chosen by the standard's penalty; null past version 40. A test decodes its
# output with zbar.
_QR_SCRIPT = """
function qrMatrix(text){
var ECC=[0,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],
BLK=[0,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49];
var bytes=new TextEncoder().encode(text),ver,size,raw,i,j,x,y;
function rawModules(v){var r=(16*v+128)*v+64;if(v>=2){var n=Math.floor(v/7)+2;r-=(25*n-10)*n-55;if(v>=7)r-=36}return r}
for(ver=1;;ver++){if(ver>40)return null;raw=Math.floor(rawModules(ver)/8);if(4+(ver<10?8:16)+8*bytes.length<=(raw-ECC[ver]*BLK[ver])*8)break}
size=ver*4+17;var cap=raw-ECC[ver]*BLK[ver],bits=[];
function put(v,n){for(var k=n-1;k>=0;k--)bits.push(v>>>k&1)}
put(4,4);put(bytes.length,ver<10?8:16);for(i=0;i<bytes.length;i++)put(bytes[i],8);
put(0,Math.min(4,cap*8-bits.length));put(0,(8-bits.length%8)%8);
for(var pad=0xEC;bits.length<cap*8;pad^=0xEC^0x11)put(pad,8);
var data=[];for(i=0;i<bits.length;i+=8){for(x=0,j=0;j<8;j++)x=x<<1|bits[i+j];data.push(x)}
function mul(a,b){for(var z=0,k=7;k>=0;k--){z=(z<<1)^((z>>>7)*0x11D);z^=(b>>>k&1)*a}return z}
var deg=ECC[ver],gen=[],root=1;for(i=0;i<deg;i++)gen.push(0);gen[deg-1]=1;
for(i=0;i<deg;i++){for(j=0;j<deg;j++){gen[j]=mul(gen[j],root);if(j+1<deg)gen[j]^=gen[j+1]}root=mul(root,2)}
var nb=BLK[ver],nshort=nb-raw%nb,slen=Math.floor(raw/nb),blocks=[],eccs=[],at=0;
for(i=0;i<nb;i++){var d=data.slice(at,at+=slen-deg+(i<nshort?0:1)),rem=gen.map(function(){return 0});
for(j=0;j<d.length;j++){var f=d[j]^rem.shift();rem.push(0);for(var k=0;k<deg;k++)rem[k]^=mul(gen[k],f)}
blocks.push(d);eccs.push(rem)}
var words=[];for(i=0;i<=slen-deg;i++)for(j=0;j<nb;j++)if(i<blocks[j].length)words.push(blocks[j][i]);
for(i=0;i<deg;i++)for(j=0;j<nb;j++)words.push(eccs[j][i]);
var m=[],fn=[];for(y=0;y<size;y++){m.push([]);fn.push([]);for(x=0;x<size;x++){m[y].push(false);fn[y].push(false)}}
function set(x,y,dark){m[y][x]=dark;fn[y][x]=true}
for(i=0;i<size;i++){set(6,i,i%2==0);set(i,6,i%2==0)}
[[3,3],[size-4,3],[3,size-4]].forEach(function(c){for(var dy=-4;dy<=4;dy++)for(var dx=-4;dx<=4;dx++){
var q=Math.max(Math.abs(dx),Math.abs(dy)),xx=c[0]+dx,yy=c[1]+dy;if(xx>=0&&xx<size&&yy>=0&&yy<size)set(xx,yy,q!=2&&q!=4)}});
var pos=[];if(ver>1){var na=Math.floor(ver/7)+2,step=Math.floor((ver*8+na*3+5)/(na*4-4))*2;pos=[6];for(x=size-7;pos.length<na;x-=step)pos.splice(1,0,x)}
for(i=0;i<pos.length;i++)for(j=0;j<pos.length;j++){if(i==0&&j==0||i==0&&j==pos.length-1||i==pos.length-1&&j==0)continue;
for(var ay=-2;ay<=2;ay++)for(var ax=-2;ax<=2;ax++)set(pos[i]+ax,pos[j]+ay,Math.max(Math.abs(ax),Math.abs(ay))!=1)}
function format(mask){var v=mask,r=v;for(var k=0;k<10;k++)r=(r<<1)^((r>>>9)*0x537);v=(v<<10|r)^0x5412;
function b(k){return (v>>>k&1)==1}
for(k=0;k<=5;k++)set(8,k,b(k));set(8,7,b(6));set(8,8,b(7));set(7,8,b(8));for(k=9;k<15;k++)set(14-k,8,b(k));
for(k=0;k<8;k++)set(size-1-k,8,b(k));for(k=8;k<15;k++)set(8,size-15+k,b(k));set(8,size-8,true)}
format(0);
if(ver>=7){var r=ver;for(i=0;i<12;i++)r=(r<<1)^((r>>>11)*0x1F25);var vb=ver<<12|r;
for(i=0;i<18;i++){var bit=(vb>>>i&1)==1,a=size-11+i%3,c=Math.floor(i/3);set(a,c,bit);set(c,a,bit)}}
for(i=0,x=size-1;x>=1;x-=2){if(x==6)x=5;for(var v=0;v<size;v++)for(j=0;j<2;j++){
var xx=x-j;y=(x+1&2)==0?size-1-v:v;if(!fn[y][xx]&&i<words.length*8){m[y][xx]=(words[i>>>3]>>>7-(i&7)&1)==1;i++}}}
var masks=[function(x,y){return (x+y)%2==0},function(x,y){return y%2==0},function(x,y){return x%3==0},
function(x,y){return (x+y)%3==0},function(x,y){return (Math.floor(x/3)+Math.floor(y/2))%2==0},
function(x,y){return x*y%2+x*y%3==0},function(x,y){return (x*y%2+x*y%3)%2==0},function(x,y){return ((x+y)%2+x*y%3)%2==0}];
function flip(k){for(var y=0;y<size;y++)for(var x=0;x<size;x++)if(!fn[y][x]&&masks[k](x,y))m[y][x]=!m[y][x]}
function line(get){var p=0,dark=0,run=0,last=null,seq='';for(var k=0;k<size;k++){var d=get(k);dark+=d;seq+=d?'1':'0';
if(d===last)run++;else{if(run>=5)p+=run-2;run=1;last=d}}if(run>=5)p+=run-2;
for(k=seq.indexOf('1011101');k>=0;k=seq.indexOf('1011101',k+1))
if(seq.substr(k-4,4)=='0000'||seq.substr(k+7,4)=='0000'||k<4||k+11>size)p+=40;return p}
function score(){var p=0,dark=0;for(var a=0;a<size;a++){p+=line(function(k){return m[a][k]?1:0});p+=line(function(k){return m[k][a]?1:0})}
for(var y=0;y<size;y++)for(var x=0;x<size;x++){dark+=m[y][x];if(x<size-1&&y<size-1&&m[y][x]==m[y][x+1]&&m[y][x]==m[y+1][x]&&m[y][x]==m[y+1][x+1])p+=3}
return p+10*Math.max(0,Math.ceil(Math.abs(dark*20-size*size*10)/(size*size))-1)}
var best=0,low=Infinity;for(k=0;k<8;k++){flip(k);format(k);var s=score();if(s<low){low=s;best=k}flip(k)}
flip(best);format(best);return m}
"""
_SCRIPT = _QR_SCRIPT + """
document.querySelectorAll('[data-qr]').forEach(function(e){var m=qrMatrix(e.getAttribute('data-qr'));if(!m)return;
var n=m.length+8,ns='http://www.w3.org/2000/svg',s=document.createElementNS(ns,'svg'),p=document.createElementNS(ns,'path'),d='';
for(var y=0;y<m.length;y++)for(var x=0;x<m.length;x++)if(m[y][x])d+='M'+(x+4)+' '+(y+4)+'h1v1h-1z';
s.setAttribute('viewBox','0 0 '+n+' '+n);s.setAttribute('shape-rendering','crispEdges');p.setAttribute('d',d);p.setAttribute('fill','#000');
s.appendChild(p);e.appendChild(s)});
document.querySelectorAll('button[data-copy]').forEach(function(b){b.addEventListener('click',function(){
var t=b.getAttribute('data-copy'),l=b.textContent;function done(){b.textContent=b.getAttribute('data-done');setTimeout(function(){b.textContent=l},1500)}
if(navigator.clipboard){navigator.clipboard.writeText(t).then(done)}else{var a=document.createElement('textarea');a.value=t;document.body.appendChild(a);a.select();document.execCommand('copy');a.remove();done()}})});
"""
def _csp_hash(source: str) -> str:
return "'sha256-" + base64.b64encode(hashlib.sha256(source.encode("utf-8")).digest()).decode("ascii") + "'"
# Every answer: the address is the secret, not to be sent on, indexed, sniffed into something
# else or read by other sites' pages.
HEADERS = {
"Cache-Control": "no-store",
"Referrer-Policy": "no-referrer",
"X-Robots-Tag": "noindex, nofollow",
"X-Content-Type-Options": "nosniff",
"Cross-Origin-Resource-Policy": "same-origin",
}
# The page, besides: nothing runs or styles it but its own script and stylesheet, by their
# hashes; no style attribute, no frame, no form, no other origin.
PAGE_HEADERS = {
"Content-Security-Policy": f"default-src 'none'; script-src {_csp_hash(_SCRIPT)}; style-src {_csp_hash(_STYLE)}; "
"base-uri 'none'; form-action 'none'; frame-ancestors 'none'; "
"require-trusted-types-for 'script'",
"Cross-Origin-Opener-Policy": "same-origin",
}
def html_page(row: dict, items: list[dict], sub_url: str, title: str, settings: dict, lang: str,
user_agent: str = "") -> str:
"""The page a browser gets: the state of the subscription, its QR code and links. The apps
for the browser's system come first, the rest folded away: the page may be open on a laptop
to set up a phone."""
t = TEXT[lang]
esc = html.escape
if not row.get("active"):
state = f'<span class="status bad">{esc(t["off"])}</span>'
reasons = ", ".join(t.get(r, r) for r in row.get("reasons") or [])
if reasons:
state += f' <span class="muted">({esc(reasons)})</span>'
elif row.get("onHold"):
state = f'<span class="status warn">{esc(t["hold"])}</span>'
else:
state = f'<span class="status ok">{esc(t["active"])}</span>'
traffic = row.get("traffic") or {}
used, limit = traffic.get("used") or 0, traffic.get("limit")
usage = esc(human_bytes(used)) + (f' {esc(t["of"])} {esc(human_bytes(limit))}' if limit else f' <span class="muted">({esc(t["unlimited"])})</span>')
if limit and traffic.get("periodEnd"):
renew = datetime.datetime.fromtimestamp(traffic["periodEnd"]).strftime("%Y-%m-%d")
usage += f' <span class="muted">· {esc(t["renews"])} {esc(renew)}</span>'
# An SVG's width attribute, not a style one: the CSP lets no style attribute through.
bar = (f'<svg class="bar" viewBox="0 0 100 1" preserveAspectRatio="none"><rect class="track" width="100" height="1"/>'
f'<rect class="fill" width="{min(100, int(used * 100 / limit))}" height="1"/></svg>') if limit else ""
if row.get("onHold"):
expires = esc(t["term"].format(human_span((row.get("policy") or {}).get("expiresAfter") or 0)))
elif row.get("expiresAt"):
expires = esc(datetime.datetime.fromtimestamp(row["expiresAt"]).strftime("%Y-%m-%d %H:%M"))
else:
expires = esc(t["never"])
name = urllib.parse.quote(title, safe="")
system = platform(user_agent)
buttons = {
label: f'<a class="app" href="{esc(pattern.format(url=urllib.parse.quote(sub_url, safe=""), raw=sub_url, name=name))}">{esc(label)}</a>'
for label, pattern, _ in APPS
}
mine = [label for label, _, systems in APPS if system in systems]
others = [label for label, _, _ in APPS if label not in mine]
if mine:
apps = "".join(buttons[label] for label in mine)
if others:
apps += f'<details><summary>{esc(t["more"])}</summary>{"".join(buttons[label] for label in others)}</details>'
else:
apps = "".join(buttons.values())
links = "".join(
f'<div class="row"><span>{esc(item["name"])}</span>'
f'<button data-copy="{esc(item["link"])}" data-done="{esc(t["copied"])}">{esc(t["copy"])}</button></div>'
for item in items
)
# Whose it is, unless the title (profileTitle's {user}) says so already.
user = ""
if row.get("name") and row["name"] not in title:
user = f'<div class="muted">{esc(t["user"])}: {esc(row["name"])}</div>'
support = ""
if settings.get("supportUrl"):
support = f'<p class="muted"><a href="{esc(settings["supportUrl"])}">{esc(t["support"])}</a></p>'
return f"""<!doctype html>
<html lang="{lang}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="robots" content="noindex,nofollow"><meta name="referrer" content="no-referrer">
<title>{esc(title)}</title><style>{_STYLE}</style></head>
<body><main>
<h1>{esc(title)}</h1>{user}<div>{state}</div>
<div class="card">
<div class="row"><span>{esc(t["used"])}</span><span>{usage}</span></div>{bar}
<div class="row"><span>{esc(t["expires"])}</span><span>{expires}</span></div>
</div>
<div class="card"><h2>{esc(t["sub"])}</h2>
<div class="qr" data-qr="{esc(sub_url)}"></div>
<code>{esc(sub_url)}</code>
<button data-copy="{esc(sub_url)}" data-done="{esc(t["copied"])}">{esc(t["copy"])}</button>
<h2 class="next">{esc(t["open"])}</h2>{apps}
</div>
{f'<div class="card"><h2>{esc(t["links"])}</h2>{links}</div>' if links else ''}
<p class="muted">{esc(t["hint"])}</p>{support}
</main><script>{_SCRIPT}</script></body></html>
"""
# --- the answer -----------------------------------------------------------------------
def render(fmt: str, rendered: dict, user: str, body_b64: str, row: dict | None, sub_url: str, title: str,
settings: dict, accept_language: str = "", user_agent: str = "") -> tuple[bytes, str]:
"""(body, Content-Type) of a subscription in one format."""
items = entries(rendered, user)
if fmt == "links":
return base64.b64decode(body_b64) + b"\n", "text/plain; charset=utf-8"
if fmt == "sing-box":
return (json.dumps(sing_box_config(items), indent=2) + "\n").encode("utf-8"), "application/json; charset=utf-8"
if fmt == "clash":
# JSON is YAML: no YAML library needed, and mihomo reads it as such.
return (json.dumps(clash_config(items), indent=2, ensure_ascii=False) + "\n").encode("utf-8"), "text/yaml; charset=utf-8"
if fmt == "html" and row is not None:
page = html_page(row, items, sub_url, title, settings, language(accept_language), user_agent)
return page.encode("utf-8"), "text/html; charset=utf-8"
return body_b64.encode("ascii"), "text/plain; charset=utf-8"
+45 -9
View File
@@ -10,6 +10,7 @@ without changing the spec or the link generator.
import base64
import hashlib
import hmac
import json
import os
import secrets
@@ -73,7 +74,11 @@ def _salamander(listener: dict) -> str | None:
return _resolve(
salamander.get("password"), salamander.get("passwordFile"), "salamander password", listener["tag"]
)
path = listener["salamanderStateFile"]
return _kept_secret(listener["salamanderStateFile"], lambda: secrets.token_urlsafe(24))
def _kept_secret(path: str, generate) -> str:
"""The secret kept in path, or one generated now and kept there for the next start."""
try:
stored = _read_secret(path)
except FileNotFoundError:
@@ -81,7 +86,7 @@ def _salamander(listener: dict) -> str | None:
if stored:
return stored
os.makedirs(os.path.dirname(path), mode=0o700, exist_ok=True)
generated = secrets.token_urlsafe(24)
generated = generate()
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as handle:
handle.write(generated + "\n")
@@ -100,8 +105,13 @@ def _share_port(listener: dict) -> int:
def _clients(listener: dict, tag: str) -> list[dict]:
"""The users XRay accepts: those the manager has switched off are left out (their links
stay), and a speed-limited one carries its slot as its level, which the patched XRay
marks its sockets with (pkgs/patches/xray-user-level-mark.patch)."""
clients = []
for index, user in enumerate(listener["users"]):
if user.get("active") is False:
continue
secret = _user_secret(user, listener["type"], tag)
email = user.get("name") or f"{tag}-{index}"
if listener["type"] in UUID_TYPES:
@@ -112,6 +122,8 @@ def _clients(listener: dict, tag: str) -> list[dict]:
client = {"auth": secret, "email": email}
else:
client = {"password": secret, "email": email}
if user.get("level"):
client["level"] = user["level"]
clients.append(client)
return clients
@@ -119,6 +131,8 @@ def _clients(listener: dict, tag: str) -> list[dict]:
def _accounts(listener: dict, tag: str) -> list[dict]:
accounts = []
for index, user in enumerate(listener["users"]):
if user.get("active") is False:
continue
secret = _user_secret(user, listener["type"], tag)
accounts.append({"user": user.get("name") or f"{tag}-{index}", "pass": secret})
return accounts
@@ -226,6 +240,8 @@ def render_xray_inbound(listener: dict) -> dict:
if len(users) == 1:
settings["password"] = _user_secret(users[0], listener_type, tag)
settings["email"] = users[0].get("name") or f"{tag}-0"
if users[0].get("level"):
settings["level"] = users[0]["level"]
keys = [(settings["email"], settings["password"])]
else:
# Multi-user is 2022-blake3-aes only: the server key, then one key per user.
@@ -558,15 +574,33 @@ def client_outbound(link: str, tag: str) -> dict | None:
return None
def subscription_token(name: str, secrets: list[str]) -> str:
def subscription_token(name: str, secrets: list[str], key: str | None = None, salt: str = "") -> str:
"""Name of a user's subscription file, and so the secret part of its URL.
Derived from the user's own credentials rather than stored: there is no
second secret to manage, it stays put for as long as they do, and rotating
the user's uuid rotates the URL with it.
Derived from the user's own credentials rather than stored: it stays put for
as long as they do, and rotating the user's uuid rotates the URL with it.
key (inbounds.subscriptions.keyFile, or the one generated) makes it an HMAC under
a secret only this server holds: whoever learns one of a user's links cannot work
the URL out from it. salt (the manager's, `proxy-ctl inbounds users rotate-sub`) moves one
user's URL on without new credentials. Neither: the plain hash of before.
"""
material = "\n".join(["proxy-suite-subscription", name, *sorted(set(secrets))])
return hashlib.sha256(material.encode("utf-8")).hexdigest()[:32]
material = "\n".join(["proxy-suite-subscription", name, *sorted(set(secrets)), *([salt] if salt else [])])
if key is None:
return hashlib.sha256(material.encode("utf-8")).hexdigest()[:32]
return hmac.new(key.encode("utf-8"), material.encode("utf-8"), hashlib.sha256).hexdigest()[:32]
def _subscription_key(spec: dict) -> str | None:
"""The config's key file; else the one generated on first start (subscriptions.keyFile
null); else none (false)."""
path = spec.get("subscriptionKeyFile")
if not path:
state = spec.get("subscriptionKeyStateFile")
return _kept_secret(state, lambda: secrets.token_hex(32)) if state else None
key = _read_secret(path)
if not key:
raise ValueError(f"subscription key file '{path}' is empty")
return key
def build_inbounds(spec: dict, server_address: str, onion_address: str = "") -> dict:
@@ -628,10 +662,12 @@ def build_inbounds(spec: dict, server_address: str, onion_address: str = "") ->
"outbound": None,
}
)
key = _subscription_key(spec) if by_user else None
salts = spec.get("subscriptionSalts") or {}
subscriptions = [
{
"user": name,
"token": subscription_token(name, entry["secrets"]),
"token": subscription_token(name, entry["secrets"], key, salts.get(name, "")),
"body": base64.b64encode("\n".join(entry["links"]).encode("utf-8")).decode("ascii"),
}
for name, entry in by_user.items()
+41
View File
@@ -707,6 +707,47 @@ class BuildInboundsTests(unittest.TestCase):
self.assertNotEqual(token, next(s["token"] for s in rotated if s["user"] == "fufsob"))
# No links, nothing to subscribe to.
self.assertEqual(build_inbounds(spec(share=False), "vpn.example.com")["subscriptions"], [])
# Under a key only the server holds, the credentials alone do not give the token away.
with tempfile.TemporaryDirectory() as tmp:
key_file = os.path.join(tmp, "key")
with open(key_file, "w", encoding="utf-8") as handle:
handle.write("k" * 64 + "\n")
keyed = {s["user"]: s["token"] for s in build_inbounds({**spec(), "subscriptionKeyFile": key_file},
"vpn.example.com")["subscriptions"]}
self.assertRegex(keyed["fufsob"], "^[0-9a-f]{32}$")
self.assertNotEqual(keyed["fufsob"], token)
self.assertEqual(keyed["fufsob"], subscription_token("fufsob", ["uuid-fufsob"], "k" * 64))
self.assertNotEqual(keyed["fufsob"], subscription_token("fufsob", ["uuid-fufsob"], "other"))
# The manager's salt moves one user's on, the rest stay.
salted = {s["user"]: s["token"] for s in build_inbounds(
{**spec(), "subscriptionKeyFile": key_file, "subscriptionSalts": {"fufsob": "ab" * 16}},
"vpn.example.com")["subscriptions"]}
self.assertNotEqual(salted["fufsob"], keyed["fufsob"])
self.assertEqual(salted["teri"], keyed["teri"])
# Without a key too: a salt is a secret of the server's.
self.assertNotEqual(subscription_token("fufsob", ["uuid-fufsob"], salt="ab" * 16), token)
# No key file: one generated on first start, kept, and used from then on.
state = os.path.join(tmp, "state", "subscription-key")
generated = {s["user"]: s["token"] for s in build_inbounds(
{**spec(), "subscriptionKeyStateFile": state}, "vpn.example.com")["subscriptions"]}
with open(state, encoding="utf-8") as handle:
kept = handle.read().strip()
self.assertRegex(kept, "^[0-9a-f]{64}$")
self.assertEqual(os.stat(state).st_mode & 0o777, 0o600)
self.assertEqual(generated["fufsob"], subscription_token("fufsob", ["uuid-fufsob"], kept))
self.assertEqual(generated, {s["user"]: s["token"] for s in build_inbounds(
{**spec(), "subscriptionKeyStateFile": state}, "vpn.example.com")["subscriptions"]})
# The config's key wins over it.
self.assertEqual(keyed, {s["user"]: s["token"] for s in build_inbounds(
{**spec(), "subscriptionKeyFile": key_file, "subscriptionKeyStateFile": state},
"vpn.example.com")["subscriptions"]})
# A key file that is empty or not there stops the rendering, as a secret's would.
with open(key_file, "w", encoding="utf-8") as handle:
handle.write("\n")
with self.assertRaises(ValueError):
build_inbounds({**spec(), "subscriptionKeyFile": key_file}, "vpn.example.com")
with self.assertRaises(OSError):
build_inbounds({**spec(), "subscriptionKeyFile": os.path.join(tmp, "none")}, "vpn.example.com")
def test_share_port_overrides_the_bound_port(self):
spec = {
+223
View File
@@ -0,0 +1,223 @@
#!/usr/bin/env python3
import copy
import json
import os
import secrets
import subprocess
import tempfile
import time
import unittest
import inbound_apply as ap
UUID_A = "b831381d-6324-4d53-ad4f-8cda48b30811"
UUID_B = "11111111-2222-3333-4444-555555555555"
def vless(tag, clients, port=443, **extra):
inbound = {"tag": tag, "listen": "::", "port": port, "protocol": "vless",
"settings": {"clients": clients, "decryption": "none"},
"streamSettings": {"network": "raw", "security": "none"}}
inbound.update(extra)
return inbound
def client(email, uuid=UUID_A, **extra):
return {"id": uuid, "email": email, **extra}
def rendering(*inbounds, **extra):
return {"inbounds": list(inbounds), "links": [], "subscriptions": [], **extra}
class Plan(unittest.TestCase):
def test_nothing_changed(self):
old = rendering(vless("a", [client("u")]))
steps = ap.plan(old, copy.deepcopy(old))
self.assertTrue(ap.is_noop(steps))
def test_users_come_and_go(self):
old = rendering(vless("a", [client("u"), client("v", UUID_B)]))
new = rendering(vless("a", [client("v", UUID_B, level=3), client("w")]))
steps = ap.plan(old, new)
self.assertEqual(steps["restart"], [])
self.assertEqual(steps["users"]["a"]["remove"], ["u", "v"])
self.assertEqual([c["email"] for c in steps["users"]["a"]["add"]], ["v", "w"])
def test_a_changed_listener_restarts(self):
old = rendering(vless("a", [client("u")]))
new = rendering(vless("a", [client("u")], port=8443))
self.assertEqual(ap.plan(old, new)["restart"], ["listener 'a' changed"])
def test_listeners_added_or_gone_restart(self):
old = rendering(vless("a", [client("u")]))
new = rendering(vless("a", [client("u")]), vless("b", [client("u")], port=8443))
self.assertEqual(ap.plan(old, new)["restart"], ["listeners added: b"])
self.assertEqual(ap.plan(new, old)["restart"], ["listeners gone: b"])
def test_accounts_and_single_user_shadowsocks_restart(self):
socks = {"tag": "s", "protocol": "socks", "port": 1080, "settings": {"accounts": [{"user": "u", "pass": "1"}]}}
changed = copy.deepcopy(socks)
changed["settings"]["accounts"].append({"user": "v", "pass": "2"})
self.assertTrue(ap.plan(rendering(socks), rendering(changed))["restart"])
single = {"tag": "ss", "protocol": "shadowsocks", "port": 8388,
"settings": {"method": "aes-128-gcm", "password": "x", "email": "u"}}
other = copy.deepcopy(single)
other["settings"]["level"] = 2
self.assertTrue(ap.plan(rendering(single), rendering(other))["restart"])
def test_routing_outbounds_addresses_and_outputs(self):
old = rendering(vless("a", []), rules=[{"ruleTag": "x"}],
selfOutbounds=[{"tag": "direct-self4-1", "sendThrough": "10.0.0.1"}],
selfAddresses=[{"ipv4": "10.0.0.1", "ipv6": None}])
new = rendering(vless("a", []), rules=[{"ruleTag": "x"}, {"ruleTag": "y"}],
selfOutbounds=[{"tag": "direct-self4-2", "sendThrough": "10.0.0.2"}],
selfAddresses=[{"ipv4": "10.0.0.2", "ipv6": "fd00::2"}])
new["links"] = [{"link": "vless://..."}]
steps = ap.plan(old, new)
self.assertEqual(steps["rules"], [{"ruleTag": "x"}, {"ruleTag": "y"}])
self.assertEqual(steps["outbounds"]["remove"], ["direct-self4-1"])
self.assertEqual([o["tag"] for o in steps["outbounds"]["add"]], ["direct-self4-2"])
self.assertEqual(steps["addresses"]["remove"], [("4", "10.0.0.1")])
self.assertEqual(steps["addresses"]["add"], [("4", "10.0.0.2"), ("6", "fd00::2")])
self.assertTrue(steps["outputs"])
def test_udp_inbounds(self):
self.assertTrue(ap.udp_inbound({"protocol": "hysteria"}))
self.assertTrue(ap.udp_inbound({"protocol": "vless", "streamSettings": {"network": "xhttp", "tlsSettings": {"alpn": ["h3"]}}}))
self.assertFalse(ap.udp_inbound(vless("a", [])))
class Steps(unittest.TestCase):
def test_the_commands(self):
config = {"xray": "xray", "api": "unix:///run/api.sock", "ss": "ss", "nft": "nft", "nftTable": "t",
"ip": "ip", "selfInterface": "ps-self"}
tools = ap.Tools(config, dry_run=True)
new = rendering(vless("a", [client("w")]), {"tag": "h", "protocol": "hysteria", "port": 443, "settings": {"clients": []}})
steps = {"restart": [], "users": {"a": {"remove": ["u"], "add": [client("w")]}, "h": {"remove": ["u"], "add": []}},
"rules": None, "outbounds": {"remove": [], "add": []},
"addresses": {"remove": [("4", "10.0.0.1")], "add": [("6", "fd00::2")]}, "outputs": False}
done = ap.run_steps(tools, steps, new, None)
self.assertIn("a: -u", done)
self.assertIn("a: +w", done)
log = "\n".join(tools.log)
self.assertIn("xray api statsonlineiplist --server=unix:///run/api.sock -email u", log)
self.assertIn("xray api rmu --server=unix:///run/api.sock -tag=a u", log)
self.assertIn("xray api adu --server=unix:///run/api.sock", log)
self.assertIn("ip -4 addr del 10.0.0.1/32 dev ps-self", log)
self.assertIn("ip -6 addr add fd00::2/128 dev ps-self nodad", log)
class SyncConfig(unittest.TestCase):
def test_config_json_follows_in_place(self):
with tempfile.TemporaryDirectory() as directory:
path = os.path.join(directory, "config.json")
running = {"inbounds": [vless("a", [client("u")]), vless("b", [client("u")], port=8443)],
"routing": {"rules": [{"ruleTag": "x"}]},
"outbounds": [{"tag": "direct"}, {"tag": "direct-self4-1"}]}
with open(path, "w", encoding="utf-8") as handle:
json.dump(running, handle)
os.chmod(path, 0o440 | 0o200)
inode = os.stat(path).st_ino
new = rendering(vless("a", [client("w")]), vless("b", [client("u")], port=8443))
steps = {"users": {"a": {"remove": ["u"], "add": [client("w")]}}, "rules": [{"ruleTag": "y"}],
"outbounds": {"remove": ["direct-self4-1"], "add": [{"tag": "direct-self4-2"}]}}
ap.sync_config(directory, steps, new)
with open(path, encoding="utf-8") as handle:
synced = json.load(handle)
self.assertEqual(os.stat(path).st_ino, inode)
self.assertEqual([c["email"] for c in synced["inbounds"][0]["settings"]["clients"]], ["w"])
self.assertEqual([c["email"] for c in synced["inbounds"][1]["settings"]["clients"]], ["u"])
self.assertEqual(synced["routing"]["rules"], [{"ruleTag": "y"}])
self.assertEqual([o["tag"] for o in synced["outbounds"]], ["direct", "direct-self4-2"])
class Stopped(unittest.TestCase):
def test_stopped_inbounds_are_left_to_try_restart(self):
config = {"runtimeDir": "/nonexistent/proxy-suite-inbounds", "unit": "proxy-suite-inbounds.service",
"systemctl": "systemctl"}
done = ap.apply(config, {"listeners": []}, dry_run=True)
self.assertEqual(done, ["restarted proxy-suite-inbounds.service: the inbounds are not running"])
class AmneziaWG(unittest.TestCase):
CONFIG = "[Interface]\nPrivateKey = k\nAddress = 10.66.0.1/24\nListenPort = 51820\nMTU = 1380\nTable = off\nJc = 4\n\n[Peer]\nPublicKey = p\nAllowedIPs = 10.66.0.2/32\n"
def test_strip(self):
stripped = ap.strip_config(self.CONFIG)
self.assertNotIn("Address", stripped)
self.assertNotIn("MTU", stripped)
self.assertIn("Jc = 4", stripped)
self.assertIn("AllowedIPs = 10.66.0.2/32", stripped)
def test_interface_part_ignores_peers(self):
other = self.CONFIG.replace("10.66.0.2/32", "10.66.0.3/32")
self.assertEqual(ap.interface_part(self.CONFIG), ap.interface_part(other))
self.assertNotEqual(ap.interface_part(self.CONFIG), ap.interface_part(self.CONFIG.replace("Jc = 4", "Jc = 5")))
@unittest.skipUnless(os.environ.get("XRAY"), "XRAY is not set: no live XRay to talk to")
class LiveXray(unittest.TestCase):
"""The API steps against a running XRay: users added and removed, rules replaced."""
def setUp(self):
self.dir = tempfile.TemporaryDirectory()
self.socket = f"@proxy-suite-test-{secrets.token_hex(4)}"
self.api = f"unix-abstract:{self.socket[1:]}"
template = {"routing": {"domainStrategy": "AsIs", "rules": [{"ruleTag": "inbound-stats-api", "inboundTag": ["api-in"], "outboundTag": "api"}]}}
config = {
"log": {"loglevel": "warning"},
"api": {"tag": "api", "services": ["StatsService", "HandlerService", "RoutingService"]},
"stats": {},
"inbounds": [
{"tag": "api-in", "protocol": "dokodemo-door", "listen": self.socket,
"settings": {"address": "127.0.0.1", "network": "unix"}},
vless("a", [client("u")], port=0, listen="127.0.0.1"),
],
"outbounds": [{"tag": "direct", "protocol": "freedom"}, {"tag": "api", "protocol": "freedom"}],
"routing": template["routing"],
}
self.template = template
# Port 0 is no port to XRay: take a free one.
import socket
with socket.socket() as probe:
probe.bind(("127.0.0.1", 0))
config["inbounds"][1]["port"] = probe.getsockname()[1]
self.inbound = config["inbounds"][1]
path = os.path.join(self.dir.name, "config.json")
with open(path, "w", encoding="utf-8") as handle:
json.dump(config, handle)
self.xray = subprocess.Popen([os.environ["XRAY"], "run", "-c", path], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
self.tools = ap.Tools({"xray": os.environ["XRAY"], "api": self.api, "tmpDir": self.dir.name})
for _ in range(50):
try:
self.tools.xray_api("lsi", what="waiting")
break
except ap.ApplyError:
time.sleep(0.1)
def tearDown(self):
self.xray.terminate()
self.xray.wait()
self.dir.cleanup()
def users(self):
out = self.tools.xray_api("inbounduser", "-tag=a", what="listing")
return sorted(u["email"] for u in json.loads(out or "{}").get("users") or [])
def test_users_and_rules(self):
old = rendering(self.inbound)
new_inbound = copy.deepcopy(self.inbound)
new_inbound["settings"]["clients"] = [client("v", UUID_B, level=4)]
new = rendering(new_inbound, rules=self.template["routing"]["rules"] + [{"ruleTag": "extra", "user": ["v"], "outboundTag": "direct"}])
steps = ap.plan(old, new)
self.assertEqual(steps["restart"], [])
ap.run_steps(self.tools, steps, new, self.template)
self.assertEqual(self.users(), ["v"])
rules = json.loads(self.tools.xray_api("lsrules", what="rules"))["rules"]
self.assertEqual([r["ruleTag"] for r in rules], ["inbound-stats-api", "extra"])
if __name__ == "__main__":
unittest.main()
+628
View File
@@ -0,0 +1,628 @@
#!/usr/bin/env python3
import base64
import copy
import http.client
import importlib.util
import json
import os
import socket
import tempfile
import threading
import time
import unittest
import uuid
from unittest import mock
import inbound_apply
import inbound_manager as im
import inbound_subscription
import inbound_policy as policy
import inbound_runtime as rt
# The runtime tests' spec, spool and all.
_spec = importlib.util.spec_from_file_location("runtime_tests", os.path.join(os.path.dirname(__file__), "test-inbound-runtime.py"))
runtime_tests = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(runtime_tests)
class FakeNetfilter:
enabled = True
def __init__(self):
self.banned = []
self.limits = None
def ensure(self):
return False
def ban(self, ip, ports, seconds):
self.banned.append((ip, sorted(ports), seconds))
def bans(self):
return [{"ip": ip, "port": port, "expires": seconds} for ip, ports, seconds in self.banned for port in ports]
def unban(self, ip):
found = [b for b in self.banned if b[0] == ip]
self.banned = [b for b in self.banned if b[0] != ip]
return len(found)
def sync_limits(self, users, peers):
self.limits = (users, peers)
return True
class Clock:
def __init__(self, now):
self.now = now
def __call__(self):
return self.now
class ManagerTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
base = self.tmp.name
self.spool = os.path.join(base, "spool")
os.makedirs(self.spool)
self.runtime_dir = os.path.join(base, "run")
os.makedirs(self.runtime_dir)
self.spec = runtime_tests.make_spec(self.spool)
self.config = {
"policyFile": os.path.join(base, "policy.json"),
"stateFile": os.path.join(base, "state.json"),
"statsFile": os.path.join(base, "stats.json"),
"speedLimits": True,
"slots": 4,
"apply": {"runtimeDir": self.runtime_dir},
"subscriptions": {"baseUrl": "https://vpn.example.com/sub", "profileTitle": "VPN {user}", "updateInterval": 12},
"ipLimit": {"banSeconds": 300},
}
self.spec["manager"] = {k: self.config[k] for k in ("policyFile", "stateFile", "statsFile", "speedLimits")}
self.clock = Clock(time.time())
self.netfilter = FakeNetfilter()
self.webhooks = im.Webhooks([])
self.applies = []
patcher = mock.patch.object(inbound_apply, "apply", side_effect=lambda config, spec: self.applies.append(spec) or [])
patcher.start()
self.addCleanup(patcher.stop)
self.cut = mock.patch.object(inbound_apply, "cut").start()
self.addCleanup(mock.patch.stopall)
self.manager = im.Manager(self.config, self.spec, clock=self.clock, netfilter=self.netfilter, webhooks=self.webhooks)
def tearDown(self):
self.tmp.cleanup()
def events(self, kind=None):
return [(e["event"], e["user"]) for e in self.webhooks.sent if kind is None or e["event"] == kind]
def write_stats(self, stats):
policy.write_json(self.config["statsFile"], stats)
def write_rendered(self, rendered):
with open(os.path.join(self.runtime_dir, "rendered.json"), "w", encoding="utf-8") as handle:
json.dump(rendered, handle)
# --- users and policies -----------------------------------------------------------
def test_create_a_user_with_a_policy(self):
row = self.manager.create_user({"name": "alice", "listeners": ["vless-in"],
"policy": {"trafficLimit": "10G", "expiresAt": "+30d", "speedLimit": "20M/5M"}})
self.assertEqual(row["source"], "runtime")
self.assertEqual(row["listeners"], ["vless-in"])
self.assertEqual(row["policy"]["trafficLimit"], 10 * 1024**3)
self.assertEqual(row["expiresAt"], int(self.clock.now) + 30 * 86400)
self.assertEqual(row["level"], 1)
self.assertTrue(row["active"])
self.assertEqual(len(self.applies), 1)
self.assertIn(("user.created", "alice"), self.events())
with self.assertRaises(im.ApiError) as raised:
self.manager.create_user({"name": "alice"})
self.assertEqual(raised.exception.status, 409)
def test_bad_policy_is_refused_before_anything_is_written(self):
with self.assertRaises(im.ApiError) as raised:
self.manager.create_user({"name": "zed", "policy": {"trafficLimit": "lots"}})
self.assertEqual(raised.exception.status, 400)
self.assertNotIn("zed", rt.load_spool(self.spool)[0]["users"])
def test_declared_users_get_policies_too(self):
row = self.manager.set_policy("bob", {"enabled": False})
self.assertFalse(row["active"])
self.assertEqual(row["reasons"], ["disabled"])
self.assertEqual(row["stored"], {"enabled": False})
row = self.manager.set_policy("bob", {}, unset=["enabled"])
self.assertTrue(row["active"])
self.assertEqual(policy.load_policies(self.config["policyFile"]), {})
def test_disabling_reaches_the_renderers(self):
self.manager.set_policy("bob", {"enabled": False})
merged, _, _ = rt.merge(self.spec)
vless = next(l for l in merged["listeners"] if l["tag"] == "vless-in")
bob = next(u for u in vless["users"] if u["name"] == "bob")
self.assertFalse(bob["active"])
def test_extend_from_the_later_of_now_and_the_expiry(self):
now = int(self.clock.now)
self.manager.set_policy("bob", {"expiresAt": now + 86400})
row = self.manager.extend("bob", by="30d")
self.assertEqual(row["expiresAt"], now + 31 * 86400)
self.manager.set_policy("bob", {"expiresAt": now - 86400})
self.assertEqual(self.manager.extend("bob", by="1d")["expiresAt"], now + 86400)
with self.assertRaises(im.ApiError):
self.manager.extend("bob")
def test_extend_with_a_reset_starts_the_traffic_over(self):
today = policy.day_key(self.clock.now)
self.manager.create_user({"name": "alice", "policy": {"trafficLimit": 100}})
self.manager.tick()
self.write_stats({"days": {today: {"user": {"alice": {"up": 60, "down": 60}}}}})
self.manager.tick()
self.assertEqual(self.manager.overview("alice")[0]["reasons"], ["traffic"])
row = self.manager.extend("alice", by="30d", reset=True)
self.assertTrue(row["active"])
self.assertEqual(row["traffic"]["used"], 0)
self.assertEqual(row["expiresAt"], int(self.clock.now) + 30 * 86400)
self.assertIn(("user.reset", "alice"), self.events())
def test_on_hold_starts_with_the_first_connection(self):
today = policy.day_key(self.clock.now)
row = self.manager.create_user({"name": "alice", "policy": {"expiresAfter": "30d"}})
self.assertTrue(row["active"])
self.assertTrue(row["onHold"])
self.assertIsNone(row["expiresAt"])
# Extended while on hold: the term grows, nothing starts.
row = self.manager.extend("alice", by="5d")
self.assertEqual(row["policy"]["expiresAfter"], 35 * 86400)
self.assertTrue(row["onHold"])
self.manager.tick()
self.clock.now += 3 * 86400
self.manager.tick()
self.assertTrue(self.manager.overview("alice")[0]["onHold"])
self.assertEqual(self.events("user.activated"), [])
self.write_stats({"days": {today: {"user": {"alice": {"up": 1, "down": 2}}}}})
self.manager.tick()
row = self.manager.overview("alice")[0]
self.assertFalse(row["onHold"])
self.assertEqual(row["expiresAt"], int(self.clock.now) + 35 * 86400)
self.assertEqual(self.events("user.activated"), [("user.activated", "alice")])
self.manager.tick()
self.assertEqual(len(self.events("user.activated")), 1)
def test_on_hold_starts_when_seen_online(self):
self.manager.create_user({"name": "alice", "policy": {"expiresAfter": "1d", "trafficLimit": "1G"}})
self.manager.create_user({"name": "zed", "policy": {"expiresAfter": policy.MAX_TIME - 1, "trafficLimit": "1G"}})
self.write_stats({"online": [{"email": name, "ips": [{"ip": "198.51.100.1"}]} for name in ("alice", "zed")]})
self.manager.tick()
self.assertEqual(self.manager.overview("alice")[0]["expiresAt"], int(self.clock.now) + 86400)
# A term past the year 9999 ends just before it: the rest of the policy stays.
zed = self.manager.overview("zed")[0]
self.assertEqual(zed["expiresAt"], policy.MAX_TIME - 1)
self.assertEqual(zed["policy"]["trafficLimit"], 1024**3)
def test_expired_runtime_users_are_deleted_after_a_while(self):
self.config["deleteExpiredAfter"] = "7d"
now = int(self.clock.now)
self.manager.create_user({"name": "alice", "policy": {"expiresAt": now + 86400}})
self.manager.create_user({"name": "carol"})
self.manager.set_policy("bob", {"expiresAt": now + 86400})
self.clock.now += 7 * 86400
self.manager.tick()
self.assertIn("alice", self.manager.names())
self.clock.now += 86400 + 1
self.manager.tick()
names = self.manager.names()
self.assertNotIn("alice", names)
# Declared in the config: kept. Never expires: kept.
self.assertIn("bob", names)
self.assertIn("carol", names)
deleted = [e for e in self.webhooks.sent if e["event"] == "user.deleted"]
self.assertEqual([(e["user"], e["data"]) for e in deleted], [("alice", {"reason": "expired"})])
def test_delete_forgets_the_policy(self):
self.manager.create_user({"name": "alice", "policy": {"ipLimit": 2}})
self.manager.delete_user("alice")
self.assertNotIn("alice", policy.load_policies(self.config["policyFile"]))
with self.assertRaises(im.ApiError) as raised:
self.manager.delete_user("bob")
self.assertEqual(raised.exception.status, 409)
def test_set_listeners(self):
self.manager.create_user({"name": "alice", "listeners": ["vless-in"]})
self.assertEqual(self.manager.set_listeners("alice", [])["listeners"], [])
self.assertEqual(self.manager.set_listeners("alice", ["vless-in"])["listeners"], ["vless-in"])
# A single-user shadowsocks listener takes no second user.
with self.assertRaises(im.ApiError) as raised:
self.manager.set_listeners("alice", ["ss-in"])
self.assertEqual(raised.exception.status, 409)
def test_slots_run_out(self):
for name in ("a1", "a2", "a3", "a4"):
self.manager.create_user({"name": name, "policy": {"speedLimit": "1M"}})
with self.assertRaises(im.ApiError):
self.manager.create_user({"name": "a5", "policy": {"speedLimit": "1M"}})
# Refused whole: no user without the slot their policy needs.
self.assertNotIn("a5", rt.load_spool(self.spool)[0]["users"])
self.manager.create_user({"name": "a5"})
with self.assertRaises(im.ApiError):
self.manager.set_policy("a5", {"speedLimit": "1M"})
self.assertNotIn("a5", self.manager.stored_policies())
# A slot comes back when its user's limit goes.
self.manager.set_policy("a1", {"speedLimit": None})
self.manager.tick()
self.assertNotIn("a1", self.manager.state()["slots"])
self.manager.set_policy("a5", {"speedLimit": "1M"})
self.assertIn("a5", self.manager.state()["slots"])
# --- the tick ---------------------------------------------------------------------
def test_traffic_runs_out_and_comes_back_with_the_period(self):
today = policy.day_key(self.clock.now)
self.manager.create_user({"name": "alice", "policy": {"trafficLimit": 1000, "trafficPeriod": "daily"}})
self.manager.tick()
self.write_stats({"days": {today: {"user": {"alice": {"up": 300, "down": 600}}}}})
self.manager.tick()
self.assertIn(("user.traffic", "alice"), self.events())
self.assertTrue(self.manager.overview("alice")[0]["active"])
self.write_stats({"days": {today: {"user": {"alice": {"up": 400, "down": 700}}}}})
applies = len(self.applies)
self.manager.tick()
row = self.manager.overview("alice")[0]
self.assertFalse(row["active"])
self.assertEqual(row["reasons"], ["traffic"])
self.assertEqual(len(self.applies), applies + 1)
self.assertIn(("user.disabled", "alice"), self.events())
self.assertEqual([e for e in self.events("user.traffic")], [("user.traffic", "alice")] * 2)
# The next day: a new period.
self.clock.now += 86400
self.manager.tick()
self.assertTrue(self.manager.overview("alice")[0]["active"])
self.assertIn(("user.enabled", "alice"), self.events())
def test_expiry_warnings_and_expiry(self):
self.manager.create_user({"name": "alice", "policy": {"expiresAt": int(self.clock.now) + 2 * 86400}})
self.manager.tick()
self.assertEqual(self.events("user.expiring"), [("user.expiring", "alice")])
self.manager.tick()
self.assertEqual(len(self.events("user.expiring")), 1)
self.clock.now += 2 * 86400 + 1
self.manager.tick()
self.assertEqual(self.manager.overview("alice")[0]["reasons"], ["expired"])
self.assertIn(("user.disabled", "alice"), self.events())
def test_ip_limit_bans_the_newest(self):
self.manager.create_user({"name": "alice", "listeners": ["vless-in"], "policy": {"ipLimit": 1}})
self.write_rendered({"inbounds": [
{"tag": "vless-in", "listen": "::", "port": 443, "protocol": "vless", "settings": {"clients": [{"email": "alice"}]}},
{"tag": "behind", "listen": "127.0.0.1", "port": 9000, "protocol": "vless", "settings": {"clients": [{"email": "alice"}]}},
]})
self.write_stats({"online": [{"email": "alice", "ips": [{"ip": "198.51.100.1"}]}]})
self.manager.tick()
self.assertEqual(self.netfilter.banned, [])
self.clock.now += 10
self.write_stats({"online": [{"email": "alice", "ips": [{"ip": "198.51.100.1"}, {"ip": "203.0.113.9"}]}]})
self.manager.tick()
self.assertEqual(self.netfilter.banned, [("203.0.113.9", [443], 300)])
self.assertTrue(self.cut.called)
self.assertEqual(self.events("user.ip-limit"), [("user.ip-limit", "alice")])
def test_speed_limits_follow_activity(self):
self.manager.create_user({"name": "alice", "policy": {"speedLimit": "8M/2M"}})
users, _ = self.netfilter.limits
self.assertEqual(users, {1: {"up": 2_000_000, "down": 8_000_000}})
self.manager.set_policy("alice", {"enabled": False})
self.assertEqual(self.netfilter.limits[0], {})
# --- subscriptions ----------------------------------------------------------------
def test_subscription_headers(self):
today = policy.day_key(self.clock.now)
self.manager.create_user({"name": "alice", "policy": {"trafficLimit": 5000, "expiresAt": 2_000_000_000}})
self.manager.tick()
self.write_stats({"days": {today: {"user": {"alice": {"up": 10, "down": 20}}}}})
self.write_rendered({"subscriptions": [{"user": "alice", "token": "a" * 32, "body": "Ym9keQ=="}]})
body, headers = self.manager.subscription("a" * 32)
self.assertEqual(body, b"Ym9keQ==")
self.assertEqual(headers["subscription-userinfo"], "upload=10; download=20; total=5000; expire=2000000000")
self.assertEqual(base64.b64decode(headers["profile-title"][len("base64:"):]).decode(), "VPN alice")
self.assertEqual(headers["Content-Type"], "text/plain; charset=utf-8")
self.assertEqual(headers["profile-update-interval"], "12")
self.assertIsNone(self.manager.subscription("b" * 32))
self.assertEqual(self.manager.overview("alice")[0]["subscription"]["url"], "https://vpn.example.com/sub/" + "a" * 32)
def test_subscription_formats(self):
self.manager.create_user({"name": "alice", "policy": {"expiresAfter": "30d"}})
link = "trojan://pass@vpn.example.com:8443?security=tls&sni=vpn.example.com#tr"
self.write_rendered({
"subscriptions": [{"user": "alice", "token": "a" * 32, "body": base64.b64encode(link.encode()).decode()}],
"links": [{"tag": "tr", "user": "alice", "link": link,
"outbound": {"type": "trojan", "tag": "tr", "server": "vpn.example.com", "server_port": 8443,
"password": "pass", "tls": {"enabled": True, "server_name": "vpn.example.com"}}}],
})
body, headers = self.manager.subscription("a" * 32, user_agent="ClashMetaForAndroid/2.11")
self.assertEqual(json.loads(body)["proxies"][0]["name"], "tr")
self.assertIn("subscription-userinfo", headers)
body, headers = self.manager.subscription("a" * 32, user_agent="Mozilla/5.0", accept="text/html",
accept_language="ru")
self.assertEqual(headers["Content-Type"], "text/html; charset=utf-8")
self.assertEqual(headers["Referrer-Policy"], "no-referrer")
self.assertEqual(headers["Content-Security-Policy"], inbound_subscription.PAGE_HEADERS["Content-Security-Policy"])
self.assertNotIn("content-disposition", headers)
page = body.decode()
self.assertIn("Начнётся с первого подключения", page)
# baseUrl wins over the address asked at: it is what clients are given.
self.assertIn("https://vpn.example.com/sub/" + "a" * 32, page)
body, headers = self.manager.subscription("a" * 32, fmt="links")
self.assertEqual(body.decode().strip(), link)
# Every format: not cached, sniffed, sent on or indexed; the page's CSP on the page only.
self.assertEqual({k: headers[k] for k in inbound_subscription.HEADERS}, inbound_subscription.HEADERS)
self.assertNotIn("Content-Security-Policy", headers)
def test_rotate_subscription(self):
self.manager.create_user({"name": "alice", "listeners": ["vless-in"]})
merged, _, _ = rt.merge(self.spec)
self.assertEqual(merged["subscriptionSalts"], {})
status, _ = im.handle_api(self.manager, "POST", "/api/v1/users/alice/rotate-subscription", {}, None)
self.assertEqual(status, 200)
salt = policy.load_state(self.config["stateFile"])["subscriptions"]["alice"]
self.assertTrue(policy.is_subscription_salt(salt))
# The renderers take it (proxy_inbound.subscription_token), on the apply it asked for.
self.assertEqual(rt.merge(self.spec)[0]["subscriptionSalts"], {"alice": salt})
self.assertEqual(self.applies[-1], self.spec)
self.assertEqual(self.webhooks.sent[-1]["data"], {"subscription": "rotated"})
self.manager.rotate_subscription("alice")
self.assertNotEqual(policy.load_state(self.config["stateFile"])["subscriptions"]["alice"], salt)
with self.assertRaises(im.ApiError) as raised:
self.manager.rotate_subscription("nobody")
self.assertEqual(raised.exception.status, 404)
# It travels with an export; a deleted user's goes with them.
bundle = self.manager.export()
self.assertIn("alice", bundle["state"]["subscriptions"])
self.manager.delete_user("alice")
self.assertNotIn("alice", policy.load_state(self.config["stateFile"])["subscriptions"])
self.manager.import_bundle(bundle)
self.assertEqual(policy.load_state(self.config["stateFile"])["subscriptions"]["alice"],
bundle["state"]["subscriptions"]["alice"])
with self.assertRaises(im.ApiError):
self.manager.import_bundle({**bundle, "state": {"subscriptions": {"alice": "../x"}}})
# A salt that does not hold up is left out.
state = policy.load_state(self.config["stateFile"])
state["subscriptions"]["bob"] = "short"
policy.write_json(self.config["stateFile"], state)
self.assertNotIn("bob", policy.load_state(self.config["stateFile"])["subscriptions"])
def test_misses_are_logged_sparingly(self):
clock = Clock(1000.0)
misses = im.Misses(every=60, clock=clock)
with mock.patch.object(im, "_log") as log:
for _ in range(5):
misses.note("203.0.113.7")
misses.note("198.51.100.1")
clock.now += 61
misses.note("203.0.113.7")
self.assertEqual([c.args[0] for c in log.call_args_list], [
"subscription: unknown token from 203.0.113.7",
"subscription: unknown token from 198.51.100.1",
"subscription: unknown token from 203.0.113.7 (4 more since the last line)",
])
# --- export and import ------------------------------------------------------------
def test_export_and_import_into_an_empty_server(self):
self.manager.create_user({"name": "alice", "listeners": ["vless-in"], "policy": {"trafficLimit": "1G"}})
self.write_stats({"days": {"2026-10-01": {"user": {"alice": {"up": 1, "down": 2}}}}})
awg_state = os.path.join(self.tmp.name, "awg.json")
self.spec["listeners"][2]["amneziaWg"] = {"stateFile": awg_state, "interfaceName": "awgi-awg", "subnet": "10.66.0.0/24"}
server_key = base64.b64encode(b"S" * 32).decode()
policy.write_json(awg_state, {"version": 1, "server": {"publicKey": server_key}, "users": {"bob": {"offset": 2}}})
bundle = json.loads(json.dumps(self.manager.export()))
self.assertEqual(sorted(bundle["runtime"]["users"]), ["alice"])
self.assertEqual(bundle["amneziaWg"]["awg"]["server"]["publicKey"], server_key)
other = tempfile.TemporaryDirectory()
self.addCleanup(other.cleanup)
spool = os.path.join(other.name, "spool")
os.makedirs(spool)
spec = runtime_tests.make_spec(spool)
spec["listeners"][2]["amneziaWg"] = {"stateFile": os.path.join(other.name, "awg.json"), "interfaceName": "awgi-awg", "subnet": "10.66.0.0/24"}
config = copy.deepcopy(self.config)
for key in ("policyFile", "stateFile", "statsFile"):
config[key] = os.path.join(other.name, os.path.basename(config[key]))
spec["manager"] = {k: config[k] for k in ("policyFile", "stateFile", "statsFile", "speedLimits")}
target = im.Manager(config, spec, clock=self.clock, netfilter=FakeNetfilter(), webhooks=im.Webhooks([]))
report = target.import_bundle(bundle)
self.assertEqual(report["users"], ["alice"])
self.assertEqual(report["amneziaWg"], ["awg"])
row = target.overview("alice")[0]
self.assertEqual(row["policy"]["trafficLimit"], 1024**3)
self.assertEqual(rt.load_spool(spool)[0]["users"]["alice"]["uuid"], rt.load_spool(self.spool)[0]["users"]["alice"]["uuid"])
self.assertEqual(policy.read_stats(config["statsFile"])["days"]["2026-10-01"]["user"]["alice"], {"up": 1, "down": 2})
with self.assertRaises(im.ApiError) as raised:
target.import_bundle(bundle)
self.assertEqual(raised.exception.status, 409)
self.assertEqual(target.import_bundle(bundle, replace=True)["users"], ["alice"])
def test_the_generated_subscription_key_travels(self):
key_path = os.path.join(self.tmp.name, "inbounds", "subscription-key")
self.spec["subscriptionKeyStateFile"] = key_path
self.assertIsNone(self.manager.export()["subscriptionKey"])
os.makedirs(os.path.dirname(key_path))
with open(key_path, "w", encoding="utf-8") as handle:
handle.write("e" * 64 + "\n")
bundle = self.manager.export()
self.assertEqual(bundle["subscriptionKey"], "e" * 64)
# A key the config names is the config's: not exported.
named = im.Manager(self.config, {**self.spec, "subscriptionKeyFile": "/run/secrets/k"}, netfilter=FakeNetfilter())
self.assertIsNone(named.export()["subscriptionKey"])
other = tempfile.TemporaryDirectory()
self.addCleanup(other.cleanup)
target_path = os.path.join(other.name, "inbounds", "subscription-key")
target = im.Manager(self.config, {**self.spec, "subscriptionKeyStateFile": target_path},
clock=self.clock, netfilter=FakeNetfilter(), webhooks=im.Webhooks([]))
report = {"skipped": []}
target._import_subscription_key(bundle["subscriptionKey"], False, report)
self.assertTrue(report["subscriptionKey"])
with open(target_path, encoding="utf-8") as handle:
self.assertEqual(handle.read().strip(), "e" * 64)
self.assertEqual(os.stat(target_path).st_mode & 0o777, 0o600)
# One of its own already: kept, unless replace.
report = {"skipped": []}
target._import_subscription_key("f" * 64, False, report)
self.assertIn("kept this server's", report["skipped"][0])
target._import_subscription_key("f" * 64, True, report)
with open(target_path, encoding="utf-8") as handle:
self.assertEqual(handle.read().strip(), "f" * 64)
# None to keep it in: said so.
report = {"skipped": []}
im.Manager(self.config, {**self.spec, "subscriptionKeyStateFile": None},
netfilter=FakeNetfilter())._import_subscription_key("f" * 64, False, report)
self.assertIn("keyFile is false", report["skipped"][0])
with self.assertRaises(im.ApiError):
self.manager.import_bundle({**bundle, "subscriptionKey": "short\nline"})
def test_import_refuses_garbage(self):
for bad in (None, {}, {"format": "x"}, {"format": im.BUNDLE_FORMAT, "version": 99}):
with self.assertRaises(im.ApiError):
self.manager.import_bundle(bad)
bundle = self.manager.export()
bundle["runtime"]["users"]["evil"] = {"order": 1, "uuid": "nope", "password": "x"}
with self.assertRaises(im.ApiError) as raised:
self.manager.import_bundle(bundle)
self.assertEqual(raised.exception.status, 400)
def test_import_refuses_what_would_escape_or_break_its_files(self):
clean = self.manager.export()
awg_state = os.path.join(self.tmp.name, "awg.json")
self.spec["listeners"][2]["amneziaWg"] = {"stateFile": awg_state, "interfaceName": "awgi-awg", "subnet": "10.66.0.0/24"}
key = base64.b64encode(b"k" * 32).decode()
bad_parts = [
# A tag is a directory under the Salamander state: not a way out of it.
("salamander", {"../../escape": "password"}),
("salamander", {"hy2": "two\nlines"}),
# A key with a line break would add a line (PostUp = ...) to what awg-quick runs.
("amneziaWg", {"awg": {"version": 1, "server": {"privateKey": key + "\nPostUp = touch /x"}, "users": {}}}),
("amneziaWg", {"awg": {"version": 1, "server": {}, "users": {"bob": {"offset": 2, "presharedKey": "short"}}}}),
# A state of another version: its keys would be made anew.
("amneziaWg", {"awg": {"server": {"privateKey": key}, "users": {}}}),
# The renderers and the collector read these at every start and run.
("state", {"users": {"alice": {"periodStart": "yesterday"}}, "slots": {}}),
("stats", {"days": {"2026-10-01": {"user": {"alice": {"up": "lots"}}}}}),
]
for section, value in bad_parts:
bundle = copy.deepcopy(clean)
bundle[section] = value
with self.subTest(section=section, value=value), self.assertRaises(im.ApiError) as raised:
self.manager.import_bundle(bundle)
self.assertEqual(raised.exception.status, 400)
self.assertFalse(os.path.exists(os.path.join(self.tmp.name, "escape")))
self.assertFalse(os.path.exists(awg_state))
def test_import_takes_declared_names_outside_the_runtime_pattern(self):
# Declared tags and user names are any string; only a path made of one is checked.
awg_state = os.path.join(self.tmp.name, "awg.json")
salamander_file = os.path.join(self.tmp.name, "declared-salamander")
self.spec["listeners"][2]["amneziaWg"] = {"stateFile": awg_state, "interfaceName": "awgi-awg", "subnet": "10.66.0.0/24"}
self.spec["listeners"][0]["salamanderStateFile"] = salamander_file
tag = self.spec["listeners"][0]["tag"]
bundle = self.manager.export()
bundle["amneziaWg"] = {"awg": {"version": 1, "server": {}, "users": {"bob smith": {"offset": 3}}}}
bundle["salamander"] = {tag: "secret-password"}
report = self.manager.import_bundle(bundle)
self.assertEqual(report["amneziaWg"], ["awg"])
self.assertEqual(report["salamander"], [tag])
with open(salamander_file, encoding="utf-8") as handle:
self.assertEqual(handle.read(), "secret-password\n")
def test_import_refuses_a_runtime_user_named_as_a_declared_one(self):
bundle = self.manager.export()
declared = sorted(self.spec["users"])[0]
bundle["runtime"]["users"][declared] = {"order": 900, "uuid": str(uuid.uuid4()), "password": "x" * 16}
with self.assertRaises(im.ApiError) as raised:
self.manager.import_bundle(bundle)
self.assertEqual(raised.exception.status, 409)
self.assertNotIn(declared, rt.load_spool(self.spool)[0]["users"])
def test_a_malformed_state_entry_is_left_out(self):
policy.write_json(self.config["stateFile"], {"users": {"alice": {"periodStart": "x"}, "bob": {"periodStart": 5}},
"slots": {"alice": "1", "bob": 2}})
state = policy.load_state(self.config["stateFile"])
self.assertEqual(state["users"], {"bob": {"periodStart": 5}})
self.assertEqual(state["slots"], {"bob": 2})
class Api(ManagerTest):
def test_routes(self):
status, value = im.handle_api(self.manager, "POST", "/api/v1/users", {}, {"name": "alice", "policy": {"ipLimit": 2}})
self.assertEqual(status, 201)
self.assertEqual(value["policy"]["ipLimit"], 2)
status, value = im.handle_api(self.manager, "PATCH", "/api/v1/users/alice", {}, {"trafficLimit": "1G", "unset": ["ipLimit"]})
self.assertIsNone(value["policy"]["ipLimit"])
status, value = im.handle_api(self.manager, "POST", "/api/v1/users/alice/disable", {}, None)
self.assertFalse(value["active"])
with self.assertRaises(im.ApiError) as raised:
im.handle_api(self.manager, "PUT", "/api/v1/users/alice", {}, {})
self.assertEqual(raised.exception.status, 405)
with self.assertRaises(im.ApiError) as raised:
im.handle_api(self.manager, "GET", "/api/v1/users/nobody", {}, None)
self.assertEqual(raised.exception.status, 404)
def request(self, path, method="GET", body=None, headers=None, sock=None):
connection = http.client.HTTPConnection("localhost")
connection.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
connection.sock.connect(sock)
payload = body if isinstance(body, bytes) or body is None else json.dumps(body).encode()
connection.request(method, path, body=payload, headers=headers or {})
response = connection.getresponse()
return response.status, dict(response.getheaders()), response.read()
def test_over_the_sockets(self):
api_socket = os.path.join(self.tmp.name, "api.sock")
sub_socket = os.path.join(self.tmp.name, "sub.sock")
misses = mock.Mock()
servers = [im.unix_server(api_socket, im._handler(self.manager, "api", []), None, 0o600),
im.unix_server(sub_socket, im._handler(self.manager, "sub", [], misses), None, 0o600)]
for server in servers:
threading.Thread(target=server.serve_forever, daemon=True).start()
self.addCleanup(server.shutdown)
status, _, body = self.request("/api/v1/users", "POST", {"name": "alice"}, sock=api_socket)
self.assertEqual(status, 201, body)
status, _, body = self.request("/api/v1/users/alice", sock=api_socket)
self.assertEqual(json.loads(body)["name"], "alice")
status, _, body = self.request("/api/v1/users", "POST", b"x", sock=api_socket)
self.assertEqual(status, 400)
# The subscription socket answers subscriptions only.
self.write_rendered({"subscriptions": [{"user": "alice", "token": "c" * 32, "body": "eA=="}]})
status, headers, body = self.request("/sub/" + "c" * 32, sock=sub_socket)
self.assertEqual((status, body), (200, b"eA=="))
self.assertIn("subscription-userinfo", {k.lower() for k in headers})
status, headers, _ = self.request("/api/v1/users", sock=sub_socket)
self.assertEqual(status, 404)
self.assertEqual(headers.get("X-Content-Type-Options"), "nosniff")
# A miss is noted by the address the web server says it came from, when that is one.
self.request("/sub/" + "d" * 32, sock=sub_socket, headers={"X-Real-IP": "203.0.113.7"})
self.request("/sub/" + "d" * 32, sock=sub_socket, headers={"X-Forwarded-For": "10.0.0.1, 198.51.100.1"})
self.request("/sub/" + "d" * 32, sock=sub_socket, headers={"X-Real-IP": "forged words"})
self.assertEqual([c.args[0] for c in misses.note.call_args_list][-3:], ["203.0.113.7", "198.51.100.1", "unix"])
# The format from the query or the client; a page that names the address it was asked at.
status, headers, body = self.request("/sub/" + "c" * 32 + "?format=sing-box", sock=sub_socket)
self.assertEqual(json.loads(body)["route"]["final"], "direct")
del self.config["subscriptions"]["baseUrl"]
status, headers, body = self.request("/sub/" + "c" * 32, sock=sub_socket, headers={
"User-Agent": "Mozilla/5.0", "Accept": "text/html", "Host": "vpn.example.org", "X-Forwarded-Proto": "https"})
self.assertEqual(status, 200)
self.assertIn("https://vpn.example.org/sub/" + "c" * 32, body.decode())
status, headers, body = self.request("/sub/" + "c" * 32, sock=sub_socket, headers={
"User-Agent": "Mozilla/5.0", "Accept": "text/html", "Host": "evil\"><script>"})
self.assertNotIn("evil", body.decode())
def test_tokens(self):
path = os.path.join(self.tmp.name, "tokens")
with open(path, "w", encoding="utf-8") as handle:
handle.write("# bots\nbot:s3cret\nplain\n")
self.assertEqual(im.read_tokens(path), [b"s3cret", b"plain"])
if __name__ == "__main__":
unittest.main()
+244
View File
@@ -0,0 +1,244 @@
#!/usr/bin/env python3
import datetime
import json
import os
import tempfile
import time
import unittest
import inbound_policy as policy
import inbound_runtime as rt
from proxy_inbound import render_xray_inbound
def midnight(year, month, day):
return int(time.mktime(datetime.date(year, month, day).timetuple()))
class Parsing(unittest.TestCase):
def test_sizes_are_binary(self):
self.assertEqual(policy.parse_size("50G"), 50 * 1024**3)
self.assertEqual(policy.parse_size("1.5T"), int(1.5 * 1024**4))
self.assertEqual(policy.parse_size("512MiB"), 512 * 1024**2)
self.assertEqual(policy.parse_size(1000), 1000)
for none in (None, 0, "", "none", "unlimited", "0"):
self.assertIsNone(policy.parse_size(none))
for bad in ("lots", "-5G", -1, 1.5, "5X"):
with self.assertRaises(policy.PolicyError):
policy.parse_size(bad)
def test_rates_are_decimal_bits(self):
self.assertEqual(policy.parse_rate("10M"), 10_000_000)
self.assertEqual(policy.parse_rate("500k"), 500_000)
self.assertEqual(policy.parse_rate("1Gbit"), 1_000_000_000)
self.assertIsNone(policy.parse_rate("0"))
def test_speed_forms(self):
self.assertEqual(policy.parse_speed("20M"), {"up": 20_000_000, "down": 20_000_000})
self.assertEqual(policy.parse_speed("20M/5M"), {"up": 5_000_000, "down": 20_000_000})
self.assertEqual(policy.parse_speed({"down": "8M"}), {"up": None, "down": 8_000_000})
self.assertIsNone(policy.parse_speed("0/0"))
with self.assertRaises(policy.PolicyError):
policy.parse_speed({"sideways": "1M"})
def test_times(self):
now = 1_800_000_000
self.assertEqual(policy.parse_time("+30d", now), now + 30 * 86400)
self.assertEqual(policy.parse_time("+2h", now), now + 7200)
# A date is the end of that day.
self.assertEqual(policy.parse_time("2026-12-31"), midnight(2027, 1, 1))
self.assertEqual(policy.parse_time("2026-12-31T00:00:00+00:00"), 1798675200)
self.assertEqual(policy.parse_time(str(now)), now)
self.assertIsNone(policy.parse_time("never"))
with self.assertRaises(policy.PolicyError):
policy.parse_time("next tuesday")
class Policies(unittest.TestCase):
def test_normalize_and_store_round_trip(self):
fields = policy.normalize(
{"trafficLimit": "10G", "speedLimit": "10M/2M", "ipLimit": "2", "trafficPeriod": "monthly",
"meta": {"telegram": "42"}, "enabled": False, "expiresAt": "+1d"},
now=1_800_000_000,
)
self.assertEqual(fields["trafficLimit"], 10 * 1024**3)
self.assertEqual(fields["ipLimit"], 2)
self.assertEqual(fields["expiresAt"], 1_800_086_400)
self.assertEqual(policy.check_stored(fields), fields)
self.assertIsNone(policy.normalize({"expiresAt": 0})["expiresAt"])
def test_unknown_and_bad_fields(self):
for bad in ({"colour": "red"}, {"enabled": "yes"}, {"trafficPeriod": "yearly"}, {"ipLimit": -1},
{"meta": {"a b": "x"}}, {"meta": {"k": 5}}):
with self.assertRaises(policy.PolicyError, msg=bad):
policy.normalize(bad)
def test_stored_overrides_declared_field_by_field(self):
declared = {"trafficLimit": 100, "ipLimit": 3}
stored = {"ipLimit": None, "enabled": False}
merged = policy.effective(declared, stored)
self.assertEqual(merged["trafficLimit"], 100)
self.assertIsNone(merged["ipLimit"])
self.assertFalse(merged["enabled"])
def test_declared_nulls_do_not_override(self):
spec = {"users": {"phone": {"policy": {"trafficLimit": None, "ipLimit": 2, "expiresAt": None}}}}
self.assertEqual(policy.declared_policies(spec), {"phone": {"ipLimit": 2}})
class Traffic(unittest.TestCase):
STATS = {
"days": {
"2026-10-01": {"user": {"a": {"up": 10, "down": 90}, "b": {"up": 1, "down": 1}}},
"2026-10-02": {"user": {"a": {"up": 5, "down": 5}}},
}
}
def test_usage_from_period_start_less_baseline(self):
start = midnight(2026, 10, 1) + 3600
self.assertEqual(policy.used_bytes(self.STATS, {"periodStart": start, "baselineUp": 10, "baselineDown": 30}, "a"), 70)
self.assertEqual(policy.period_traffic(self.STATS, {"periodStart": start, "baselineDown": 30}, "a"), (15, 65))
self.assertEqual(policy.used_bytes(self.STATS, {"periodStart": midnight(2026, 10, 2)}, "a"), 10)
# Not measured yet: the history before the manager saw the user does not count.
self.assertEqual(policy.used_bytes(self.STATS, {}, "a"), 0)
self.assertEqual(policy.used_bytes(self.STATS, {"periodStart": 1, "baselineUp": 500, "baselineDown": 500}, "a"), 0)
def test_start_period_takes_the_day_so_far(self):
now = midnight(2026, 10, 1) + 7200
state = policy.start_period(self.STATS, "a", now)
self.assertEqual((state["baselineUp"], state["baselineDown"]), (10, 90))
self.assertEqual(policy.used_bytes(self.STATS, state, "a"), 10)
def test_monthly_periods_renew_at_midnight_on_the_anchor_day(self):
state = {"periodStart": midnight(2026, 1, 31) + 5000, "baselineUp": 7, "anchorDay": 31}
pol = {"trafficPeriod": "monthly"}
self.assertEqual(policy.period_end(pol, state), midnight(2026, 2, 28))
self.assertTrue(policy.roll_period(pol, state, midnight(2026, 3, 5)))
# Feb 28, then Mar 31 is still ahead: the anchor day survives the short month.
self.assertEqual(state["periodStart"], midnight(2026, 2, 28))
self.assertEqual(state["baselineUp"], 0)
self.assertEqual(policy.period_end(pol, state), midnight(2026, 3, 31))
self.assertFalse(policy.roll_period(pol, state, midnight(2026, 3, 6)))
def test_no_period_never_rolls(self):
state = {"periodStart": 1, "baselineUp": 3}
self.assertFalse(policy.roll_period({"trafficPeriod": None}, state, time.time()))
self.assertEqual(state["baselineUp"], 3)
def test_durations(self):
self.assertEqual(policy.parse_duration("30d"), 30 * 86400)
self.assertEqual(policy.parse_duration("+12h"), 12 * 3600)
self.assertEqual(policy.parse_duration(90), 90)
for none in (None, 0, "", "none", "0d"):
self.assertIsNone(policy.parse_duration(none))
for bad in ("30 days", "-1d", -5, 1.5):
with self.assertRaises(policy.PolicyError):
policy.parse_duration(bad)
self.assertEqual(policy.normalize({"expiresAfter": "1w"}), {"expiresAfter": 7 * 86400})
policy.check_stored({"expiresAfter": 604800})
def test_on_hold_until_an_expiry_is_set(self):
self.assertTrue(policy.on_hold(policy.effective({"expiresAfter": 86400}, None)))
# A term started, or an expiry given by hand: no longer on hold.
self.assertFalse(policy.on_hold(policy.effective({"expiresAfter": 86400}, {"expiresAt": 2_000_000_000})))
self.assertFalse(policy.on_hold(policy.effective(None, None)))
self.assertTrue(policy.status(policy.effective({"expiresAfter": 86400}, None), 0, 2_000_000_000)["active"])
def test_status_reasons(self):
now = 2_000_000_000
self.assertEqual(policy.status(policy.effective(None, None), 10**12, now), {"active": True, "reasons": []})
pol = policy.effective({"trafficLimit": 100, "expiresAt": now - 1}, {"enabled": False})
self.assertEqual(policy.status(pol, 100, now)["reasons"], ["disabled", "expired", "traffic"])
self.assertTrue(policy.status(policy.effective({"trafficLimit": 100}, None), 99, now)["active"])
class Statuses(unittest.TestCase):
def setUp(self):
self.dir = tempfile.TemporaryDirectory()
base = self.dir.name
self.manager = {
"policyFile": os.path.join(base, "policy.json"),
"stateFile": os.path.join(base, "state.json"),
"statsFile": os.path.join(base, "stats.json"),
"speedLimits": True,
}
def tearDown(self):
self.dir.cleanup()
def write(self, key, value):
with open(self.manager[key], "w", encoding="utf-8") as handle:
json.dump(value, handle)
def test_without_the_manager_nothing_changes(self):
self.assertEqual(policy.statuses({"users": {"a": {}}}, []), {})
def test_statuses_from_the_files(self):
now = time.time()
today = policy.day_key(now)
self.write("policyFile", {"users": {"rt": {"trafficLimit": 50}, "phone": {"speedLimit": {"up": 1000, "down": 1000}}}})
self.write("stateFile", {"users": {"rt": {"periodStart": int(now) - 60}}, "slots": {"phone": 3, "rt": 4}})
self.write("statsFile", {"days": {today: {"user": {"rt": {"up": 30, "down": 30}}}}})
spec = {"manager": self.manager, "users": {"phone": {"policy": {"expiresAt": None}}}}
views = policy.statuses(spec, ["rt"], now)
self.assertEqual(views["rt"], {"active": False, "reasons": ["traffic"], "level": 0})
self.assertEqual(views["phone"], {"active": True, "reasons": [], "level": 3})
def test_a_broken_policy_file_is_no_policy(self):
with open(self.manager["policyFile"], "w", encoding="utf-8") as handle:
handle.write("{nope")
spec = {"manager": self.manager, "users": {"a": {}}}
self.assertTrue(policy.statuses(spec, [])["a"]["active"])
def listener(tag, kind, users, **extra):
base = {"tag": tag, "type": kind, "port": 443, "listen": "::", "via": "direct", "users": users,
"flow": None, "fallbacks": [], "transport": {"type": "raw", "path": "/"},
"tls": {"enable": False}, "reality": {"enable": False}, "hysteria": {}}
base.update(extra)
return base
def user(name, **fields):
return {"name": name, "uuid": "b831381d-6324-4d53-ad4f-8cda48b30811", "password": "pw-" + name, **fields}
class MergeWithStatuses(unittest.TestCase):
def spec(self):
return {
"runtime": None,
"users": {},
"listeners": [
listener("vl", "vless", [user("a"), user("b")]),
listener("sk", "socks", [user("a")]),
listener("ss", "shadowsocks", [user("b")], method="aes-128-gcm"),
],
}
def test_inactive_users_leave_xray_but_listeners_that_can_stay_do(self):
statuses = {"a": {"active": False, "level": 0}, "b": {"active": True, "level": 7}}
merged, _, warnings = rt.merge_state(self.spec(), {"users": {}, "listeners": {}}, statuses=statuses)
tags = [l["tag"] for l in merged["listeners"]]
self.assertEqual(tags, ["vl", "ss"])
self.assertIn("listener 'sk' has no active users; not started", warnings)
inbound = render_xray_inbound(merged["listeners"][0])
self.assertEqual([(c["email"], c.get("level")) for c in inbound["settings"]["clients"]], [("b", 7)])
ss = render_xray_inbound(merged["listeners"][1])
self.assertEqual(ss["settings"]["level"], 7)
def test_a_vless_listener_with_everyone_off_runs_empty(self):
statuses = {"a": {"active": False}, "b": {"active": False}}
merged, _, _ = rt.merge_state(self.spec(), {"users": {}, "listeners": {}}, statuses=statuses)
vl = next(l for l in merged["listeners"] if l["tag"] == "vl")
self.assertEqual(render_xray_inbound(vl)["settings"]["clients"], [])
def test_no_statuses_keeps_everyone(self):
merged, _, warnings = rt.merge_state(self.spec(), {"users": {}, "listeners": {}})
self.assertEqual(len(merged["listeners"]), 3)
self.assertEqual(warnings, [])
self.assertTrue(all(u["active"] for l in merged["listeners"] for u in l["users"]))
if __name__ == "__main__":
unittest.main()
+272
View File
@@ -0,0 +1,272 @@
#!/usr/bin/env python3
import base64
import json
import os
import re
import subprocess
import tempfile
import unittest
import inbound_subscription as sub
import proxy_inbound
UUID = "11111111-2222-3333-4444-555555555555"
LINKS = {
"reality": f"vless://{UUID}@vpn.example.com:443?type=tcp&security=reality&sni=www.microsoft.com&fp=chrome"
"&pbk=jNXHt1yRo0vDuchQlIP6Z0ZvjT3KtzVI-T4E7RoLJS0&sid=0123abcd&flow=xtls-rprx-vision#reality",
"ws": f"vless://{UUID}@vpn.example.com:443?type=ws&security=tls&sni=vpn.example.com&path=%2Fws"
"&host=vpn.example.com&fp=chrome&alpn=h2%2Chttp%2F1.1#ws",
"grpc": f"vless://{UUID}@vpn.example.com:443?type=grpc&security=tls&sni=vpn.example.com&serviceName=gs#grpc",
"xhttp": f"vless://{UUID}@vpn.example.com:443?type=xhttp&security=tls&sni=vpn.example.com&path=%2Fx#xh",
"trojan": "trojan://pass@vpn.example.com:8443?security=tls&sni=vpn.example.com&type=httpupgrade&path=%2Fhu#tr",
"hy2": "hysteria2://pw@vpn.example.com:443?sni=vpn.example.com&obfs=salamander&obfs-password=xx&mport=20000-20010#hy2",
}
def rendered_for(user="alice"):
links = [{"tag": tag, "user": user, "link": link, "outbound": proxy_inbound.client_outbound(link, tag)}
for tag, link in LINKS.items()]
links.append({"tag": "reality", "user": user, "link": LINKS["reality"], "variant": "onion",
"outbound": proxy_inbound.client_outbound(LINKS["reality"], "reality")})
links.append({"tag": "awg", "user": user, "link": "vpn://x", "config": "[Interface]", "outbound": None})
links.append({"tag": "ws", "user": "bob", "link": LINKS["ws"], "outbound": None})
body = base64.b64encode("\n".join(LINKS.values()).encode()).decode()
return {"links": links, "subscriptions": [{"user": user, "token": "a" * 32, "body": body}]}
ROW = {"name": "alice", "active": True, "reasons": [], "onHold": False, "expiresAt": 2_000_000_000,
"policy": {"expiresAfter": None},
"traffic": {"up": 1, "down": 1023, "used": 1024, "limit": 4096, "periodEnd": 1_900_000_000}}
class Formats(unittest.TestCase):
def test_pick_by_client(self):
cases = {
"ClashMetaForAndroid/2.11.2.Meta": "clash",
"clash-verge/v2.0.0": "clash",
"FlClash/v0.8": "clash",
"mihomo/1.19": "clash",
"Stash/2.4.6 Clash/1.9.0": "clash",
"SFA/1.11.4 (Android 14; sing-box 1.11.4)": "sing-box",
"SFI/1.12.0": "sing-box",
"sing-box 1.12.0": "sing-box",
# Hiddify names Clash and sing-box after "like": the links serve it best.
"HiddifyNext/2.5.7 (android) like ClashMeta v2ray sing-box": "base64",
"v2rayNG/1.9.1": "base64",
"Happ/1.0": "base64",
"": "base64",
}
for agent, expected in cases.items():
self.assertEqual(sub.pick_format(None, agent, "*/*"), expected, agent)
browser = "Mozilla/5.0 (X11; Linux x86_64) Firefox/131.0"
self.assertEqual(sub.pick_format(None, browser, "text/html,application/xhtml+xml"), "html")
# A client that says Mozilla but wants no page.
self.assertEqual(sub.pick_format(None, browser, "*/*"), "base64")
self.assertEqual(sub.pick_format("clash", "v2rayNG/1.9", ""), "clash")
self.assertEqual(sub.pick_format("nonsense", "v2rayNG/1.9", ""), "base64")
def test_entries_are_the_users_links_named_apart(self):
names = [e["name"] for e in sub.entries(rendered_for(), "alice")]
self.assertEqual(names, ["reality", "ws", "grpc", "xhttp", "trojan", "hy2", "reality-onion"])
def test_names_stay_clear_of_the_groups(self):
rendered = {"links": [{"tag": tag, "user": "u", "link": LINKS["ws"], "outbound": None}
for tag in ("proxy", "AUTO", "direct", "proxy")]}
self.assertEqual([e["name"] for e in sub.entries(rendered, "u")], ["proxy-2", "AUTO-2", "direct-2", "proxy-3"])
def test_sing_box_config(self):
config = sub.sing_box_config(sub.entries(rendered_for(), "alice"))
tags = [o["tag"] for o in config["outbounds"]]
# XHTTP only XRay dials: left out of the config.
self.assertNotIn("xhttp", tags)
self.assertEqual(tags[:2], ["proxy", "auto"])
self.assertEqual(config["outbounds"][0]["outbounds"][0], "auto")
self.assertIn("reality-onion", config["outbounds"][1]["outbounds"])
self.assertEqual(config["route"]["final"], "proxy")
empty = sub.sing_box_config([])
self.assertEqual(empty["route"]["final"], "direct")
self.assertEqual([o["tag"] for o in empty["outbounds"]], ["direct"])
sing_box = os.environ.get("SING_BOX")
if sing_box:
for value in (config, empty):
with tempfile.NamedTemporaryFile("w", suffix=".json") as handle:
json.dump(value, handle)
handle.flush()
done = subprocess.run([sing_box, "check", "-c", handle.name], capture_output=True, text=True)
self.assertEqual(done.returncode, 0, done.stderr)
def test_clash_proxies(self):
config = sub.clash_config(sub.entries(rendered_for(), "alice"))
proxies = {p["name"]: p for p in config["proxies"]}
self.assertNotIn("xhttp", proxies)
reality = proxies["reality"]
self.assertEqual((reality["type"], reality["server"], reality["port"], reality["uuid"]),
("vless", "vpn.example.com", 443, UUID))
self.assertEqual(reality["flow"], "xtls-rprx-vision")
self.assertEqual(reality["servername"], "www.microsoft.com")
self.assertEqual(reality["reality-opts"], {"public-key": "jNXHt1yRo0vDuchQlIP6Z0ZvjT3KtzVI-T4E7RoLJS0",
"short-id": "0123abcd"})
self.assertEqual(reality["client-fingerprint"], "chrome")
self.assertEqual(reality["network"], "tcp")
self.assertEqual(proxies["ws"]["ws-opts"], {"path": "/ws", "headers": {"Host": "vpn.example.com"}})
self.assertEqual(proxies["ws"]["alpn"], ["h2", "http/1.1"])
self.assertEqual(proxies["grpc"]["grpc-opts"], {"grpc-service-name": "gs"})
trojan = proxies["trojan"]
self.assertEqual((trojan["type"], trojan["sni"], trojan["network"]), ("trojan", "vpn.example.com", "ws"))
self.assertTrue(trojan["ws-opts"]["v2ray-http-upgrade"])
hy2 = proxies["hy2"]
self.assertEqual((hy2["type"], hy2["obfs"], hy2["obfs-password"], hy2["ports"]),
("hysteria2", "salamander", "xx", "20000-20010"))
groups = {g["name"]: g for g in config["proxy-groups"]}
self.assertEqual(groups["PROXY"]["proxies"][0], "auto")
self.assertEqual(config["rules"][-1], "MATCH,PROXY")
self.assertEqual(sub.clash_proxy("x", {"type": "shadowsocks", "method": "aes-128-gcm", "password": "p",
"server": "h", "server_port": 1, "plugin": "obfs-local"}), None)
self.assertEqual(sub.clash_proxy("x", {"type": "shadowsocks", "method": "aes-128-gcm", "password": "p",
"server": "h", "server_port": 1})["cipher"], "aes-128-gcm")
def test_render(self):
rendered = rendered_for()
body_b64 = rendered["subscriptions"][0]["body"]
args = (rendered, "alice", body_b64, ROW, "https://vpn.example.com/sub/" + "a" * 32, "VPN alice", {})
body, kind = sub.render("base64", *args)
self.assertEqual((body, kind), (body_b64.encode(), "text/plain; charset=utf-8"))
body, _ = sub.render("links", *args)
self.assertEqual(body.decode().split("\n")[0], LINKS["reality"])
body, kind = sub.render("clash", *args)
self.assertEqual(kind, "text/yaml; charset=utf-8")
self.assertIn("proxies", json.loads(body))
body, kind = sub.render("sing-box", *args)
self.assertEqual(json.loads(body)["route"]["final"], "proxy")
def test_page(self):
rendered = rendered_for()
url = "https://vpn.example.com/sub/" + "a" * 32
row = {**ROW, "name": "<b>alice</b>"}
page = sub.html_page(row, sub.entries(rendered, "alice"), url, "VPN <b>", {"supportUrl": "https://t.me/x"}, "en")
self.assertIn("VPN &lt;b&gt;", page)
self.assertNotIn("<b>", page)
self.assertIn("User: &lt;b&gt;alice&lt;/b&gt;", page)
# Named in the title already: not again.
self.assertNotIn("Пользователь", sub.html_page(ROW, [], url, "VPN alice", {}, "ru"))
self.assertIn("Пользователь: alice", sub.html_page(ROW, [], url, "Stage", {}, "ru"))
self.assertIn("Active", page)
self.assertIn("1.0 KiB of 4.0 KiB", page)
self.assertIn('<rect class="fill" width="25"', page)
self.assertIn(f'data-qr="{url}"', page)
self.assertIn("happ://add/" + url, page)
self.assertIn("v2rayng://install-config?url=https%3A%2F%2Fvpn.example.com", page)
self.assertIn("https://t.me/x", page)
# Share links are attributes, escaped: & stays &amp;.
self.assertIn("type=tcp&amp;security=reality", page)
held = sub.html_page({**ROW, "onHold": True, "expiresAt": None, "policy": {"expiresAfter": 30 * 86400}},
[], url, "VPN", {}, "ru")
self.assertIn("Начнётся с первого подключения", held)
self.assertIn("30d с первого подключения", held)
off = sub.html_page({**ROW, "active": False, "reasons": ["expired", "traffic"]}, [], url, "VPN", {}, "en")
self.assertIn("expired, out of traffic", off)
self.assertEqual(sub.language("ru-RU,ru;q=0.9,en;q=0.8"), "ru")
self.assertEqual(sub.language("de-DE,en;q=0.5"), "en")
self.assertEqual(sub.language(""), "en")
def test_apps_for_the_system(self):
url = "https://vpn.example.com/sub/" + "a" * 32
agents = {
"android": "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 Chrome/130.0 Mobile Safari/537.36",
"ios": "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 Mobile/15E148",
"macos": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 Version/18.0 Safari/605.1.15",
"windows": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/130.0 Safari/537.36",
"linux": "Mozilla/5.0 (X11; Linux x86_64; rv:131.0) Gecko/20100101 Firefox/131.0",
}
for system, agent in agents.items():
self.assertEqual(sub.platform(agent), system)
self.assertEqual(sub.platform("Mozilla/5.0 (X11; CrOS x86_64 15917.0.0) Chrome/130.0"), "android")
self.assertIsNone(sub.platform(""))
def shown(agent):
"""(labels up front, labels folded away) on the page for this browser."""
page = sub.html_page(ROW, [], url, "VPN", {}, "en", user_agent=agent)
apps = page.split("Add to an app</h2>", 1)[1].split("</div>", 1)[0]
first, _, folded = apps.partition("<details>")
label = lambda part: re.findall(r'<a class="app" href="[^"]*">([^<]*)</a>', part)
return label(first), label(folded)
first, folded = shown(agents["android"])
self.assertIn("v2rayNG", first)
self.assertIn("Streisand", folded)
self.assertNotIn("Proxy Suite", first)
first, folded = shown(agents["linux"])
self.assertEqual(first, ["Happ", "Hiddify", "Clash / mihomo", "Proxy Suite"])
self.assertIn("v2rayNG", folded)
# Nothing said: every app, none folded away.
first, folded = shown("")
self.assertEqual((len(first), folded), (len(sub.APPS), []))
self.assertIn('proxy-suite://install-config?url=https%3A%2F%2Fvpn.example.com%2Fsub%2F' + "a" * 32 + "&amp;name=VPN",
sub.html_page(ROW, [], url, "VPN", {}, "ru", user_agent=agents["linux"]))
self.assertIn("Другие приложения", sub.html_page(ROW, [], url, "VPN", {}, "ru", user_agent=agents["linux"]))
def test_page_policy(self):
"""The CSP lets the page's own script and stylesheet run, by their hashes, and nothing
else: no style attribute, no other script or stylesheet."""
page = sub.html_page({**ROW, "active": False, "reasons": ["expired"]},
sub.entries(rendered_for(), "alice"), "https://vpn.example.com/sub/x", "VPN", {}, "en")
csp = dict(part.strip().split(" ", 1) for part in sub.PAGE_HEADERS["Content-Security-Policy"].split(";"))
scripts = re.findall(r"<script>(.*?)</script>", page, re.S)
styles = re.findall(r"<style>(.*?)</style>", page, re.S)
self.assertEqual((len(scripts), len(styles)), (1, 1))
self.assertEqual(csp["script-src"], sub._csp_hash(scripts[0]))
self.assertEqual(csp["style-src"], sub._csp_hash(styles[0]))
self.assertEqual(csp["default-src"], "'none'")
self.assertNotIn("unsafe", sub.PAGE_HEADERS["Content-Security-Policy"])
self.assertNotIn(" style=", page)
self.assertEqual(page.count("<script"), 1)
def test_qr_code(self):
"""The browser's QR encoder, run by node, read back by zbar: each length up to version
40, multibyte text, and every mask."""
node, zbarimg = os.environ.get("NODE"), os.environ.get("ZBARIMG")
if not (node and zbarimg):
self.skipTest("needs NODE and ZBARIMG")
driver = """
const fs = require('fs');
const [source, text, mask, out] = process.argv.slice(2);
let code = fs.readFileSync(source, 'utf8');
if (mask !== '') code = code.replace('flip(best);format(best);return m', `flip(${mask});format(${mask});return m`);
const qrMatrix = new Function(code + ';return qrMatrix')();
const m = qrMatrix(text), quiet = 4, scale = 3, n = (m.length + 2 * quiet) * scale;
const rows = [];
for (let y = 0; y < n; y++) {
const row = [];
for (let x = 0; x < n; x++) {
const my = Math.floor(y / scale) - quiet, mx = Math.floor(x / scale) - quiet;
row.push(my >= 0 && mx >= 0 && my < m.length && mx < m.length && m[my][mx] ? 1 : 0);
}
rows.push(row.join(' '));
}
fs.writeFileSync(out, `P1\\n${n} ${n}\\n${rows.join('\\n')}\\n`);
console.log(m.length);
"""
self.assertIn("flip(best);format(best);return m", sub._QR_SCRIPT)
cases = [("https://vpn.example.com/sub/" + "0123456789abcdef" * 2, ""), ("https://vpn.example.com/sub/привет", "")]
cases += [("".join(chr(0x21 + (i * 7 + n) % 90) for i in range(n)), "") for n in (1, 14, 15, 84, 154, 213, 400, 1000, 2331)]
cases += [("https://vpn.example.com/sub/" + "a" * 32, str(mask)) for mask in range(8)]
with tempfile.TemporaryDirectory() as tmp:
source, script, image = (os.path.join(tmp, name) for name in ("qr.js", "driver.js", "qr.pbm"))
with open(source, "w", encoding="utf-8") as handle:
handle.write(sub._QR_SCRIPT)
with open(script, "w", encoding="utf-8") as handle:
handle.write(driver)
sizes = set()
for text, mask in cases:
with self.subTest(length=len(text), mask=mask):
drawn = subprocess.run([node, script, source, text, mask, image], capture_output=True, text=True, check=True)
sizes.add(int(drawn.stdout))
read = subprocess.run([zbarimg, "-q", "--raw", image], capture_output=True)
self.assertEqual(read.stdout.decode("utf-8").rstrip("\n"), text)
# Versions 1 and 40, and some between.
self.assertTrue({21, 177} <= sizes and len(sizes) >= 8, sizes)
if __name__ == "__main__":
unittest.main()