feat: runtime users and inbounds

This commit is contained in:
fufsob committed 2026-09-29 08:11:29 +00:00
1 parent a4752049ef
commit 9bbffe24b4
36 files changed
+2932 -83

No files matched your search

+167 -3
View File
@@ -138,6 +138,21 @@ Changes and secrets need root or the userControl group.
inbounds sub [user] [--qr] subscription users, or one user's URL
inbounds stats [days] [--by user|inbound|outbound]
traffic by user, listener or exit
inbounds users [list] users: order, serverSource address, listeners
(the rest below needs inbounds.runtime)
inbounds users add <name> [--order N] [--listener <tag>]...
add a user at runtime, with generated secrets
inbounds users rm <name> remove a runtime user
inbounds users order <name> <N> a runtime user's order (serverSource number)
inbounds bind|unbind <user> <tag> put a user on a listener, or take it off
(a runtime user, or a runtime listener)
inbounds add <tag> <type> [--port N] [--via V] [--transport T] [--path P] [--host H]
[--reality SNI[,SNI]] [--tls <cert>] [--alpn a,b] [--flow vision] [--method M]
[--listen A] [--user U]... [more: see inbounds add --help]
add a listener at runtime
inbounds add <tag> <file.json|-> add one from JSON shaped like inbounds.listeners.<tag>
inbounds rm <tag> remove a runtime listener
inbounds show <tag> a runtime listener's JSON
inbounds online who is online, and when others were last seen
"""
@@ -149,6 +164,33 @@ ROUTE_MODE_LABELS = {
"all-bypass": "All Bypass (override)",
}
# `inbounds add`: the listener types and flags scripts/inbound_runtime.py takes.
INBOUND_TYPES = ("vless", "vmess", "trojan", "hysteria2", "shadowsocks", "socks", "http")
INBOUND_ADD_FLAGS = {
"--port": "port, from inbounds.runtime.ports",
"--listen": "listening address (default ::)",
"--via": "where its traffic exits",
"--transport": "raw, ws, grpc, httpupgrade or xhttp",
"--path": "ws, httpupgrade or xhttp path",
"--host": "expected Host header",
"--mode": "xhttp mode",
"--service-name": "gRPC service name",
"--reality": "REALITY server names, comma-separated",
"--reality-dest": "REALITY dest host:port",
"--short-id": "REALITY short ID",
"--tls": "a certificate from inbounds.runtime.tlsCertificates",
"--alpn": "ALPN, comma-separated",
"--sni": "SNI in share links",
"--flow": "vless flow (vision)",
"--method": "shadowsocks cipher",
"--share-port": "port in share links",
"--share-address": "address in share links",
"--order": "position in links and subscriptions",
"--masquerade": "hysteria2: site shown to anything else",
"--salamander": "hysteria2: Salamander obfuscation",
"--user": "a user it accepts",
}
# A hostname: it lands in root-owned files and then in URLs.
HOSTNAME = re.compile(r"[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
@@ -690,9 +732,31 @@ COMPLETE = {
"sub": "subscription users, or one user's URL",
"stats": "traffic per user, listener or exit",
"online": "who is connected now",
"users": "users, and adding them at runtime",
"bind": "put a user on a listener",
"unbind": "take a user off a listener",
"add": "add a listener at runtime",
"rm": "remove a runtime listener",
"show": "a runtime listener's JSON",
}
},
"inbounds stats": {"flags": {"--by": "user, inbound or outbound"}},
"inbounds users": {
"words": {
"list": "users, their order, address and listeners",
"add": "add a user at runtime",
"rm": "remove a runtime user",
"order": "set a runtime user's order",
}
},
"inbounds users add": {"flags": {"--order": "its serverSource number", "--listener": "a listener to put it on"}},
"inbounds users rm": {"args": lambda: _inbound_runtime_names("users", "runtime")},
"inbounds users order": {"args": lambda: _inbound_runtime_names("users", "runtime")},
"inbounds bind": {"args": lambda: {**_inbound_runtime_names("users"), **_inbound_runtime_names("listeners")}, "repeat": True},
"inbounds unbind": {"args": lambda: {**_inbound_runtime_names("users"), **_inbound_runtime_names("listeners")}, "repeat": True},
"inbounds add": {"args": lambda: {t: "" for t in INBOUND_TYPES}, "repeat": True, "flags": INBOUND_ADD_FLAGS},
"inbounds rm": {"args": lambda: _inbound_runtime_names("listeners", "runtime")},
"inbounds show": {"args": lambda: _inbound_runtime_names("listeners", "runtime")},
"inbounds link": {
"args": _inbound_link_choices,
"flags": {
@@ -3720,15 +3784,115 @@ def _inbound_subscriptions(*args):
print("Set inbounds.subscriptions.baseUrl to get a URL instead of a path.", file=sys.stderr)
# --- runtime inbound users and listeners ---------------------------------------
#
# inbounds.runtime: users/<name>.json and listeners/<tag>.json in a spool the "inbounds" scope
# may write. scripts/inbound_runtime.py checks and writes them, with what the spec allows;
# the reload unit restarts the inbounds, which merge them in when they start.
def _inbound_runtime(*args, stdin=None, quiet=False, listing=False):
"""scripts/inbound_runtime.py with the spec: its output, or its complaint as ours.
listing: a read, which works without inbounds.runtime (the declared users and listeners).
"""
if not (listing and env("INBOUNDS_ENABLED") == "1") and env("INBOUNDS_RUNTIME_ENABLED") != "1":
die("Runtime inbound users and listeners are not enabled in this configuration (inbounds.runtime.enable).")
argv = [sys.executable, env("INBOUNDS_RUNTIME_TOOL"), "--spec", env("INBOUNDS_SPEC_FILE"), "--xray", env("INBOUNDS_XRAY", "xray"), *args]
try:
p = subprocess.run(argv, input=stdin, capture_output=True, text=True)
except OSError as e:
die(f"Cannot run {argv[1]}: {e}")
if p.returncode and not quiet:
message = p.stderr.strip() or f"{argv[1]} exited with {p.returncode}"
die(f"{message} - {ask_group()}." if p.returncode == 77 else message)
if not quiet and p.stderr:
sys.stderr.write(p.stderr)
return p.returncode, p.stdout
def _inbound_runtime_rows(kind):
"""Users or listeners, declared and runtime, as the tool lists them; [] when it cannot."""
if env("INBOUNDS_ENABLED") != "1":
return []
status, out = _inbound_runtime(kind, "--json", quiet=True, listing=True)
try:
rows = json.loads(out) if not status else []
except ValueError:
rows = []
return rows if isinstance(rows, list) else []
def _inbound_runtime_names(kind, source=""):
key = "name" if kind == "users" else "tag"
return {_s(r[key]): _s(r.get("source") or "") for r in _inbound_runtime_rows(kind) if not source or r.get("source") == source}
def _inbound_runtime_change(*args, stdin=None):
"""A change to the spool, then the reload that applies it, then what it left out."""
_, out = _inbound_runtime(*args, stdin=stdin)
sys.stdout.write(out)
if systemctl("start", "proxy-suite-inbounds-reload.service")[0]:
die("Saved, but applying it failed - see: proxy-ctl logs proxy-suite-inbounds-reload")
p = subprocess.run(
[sys.executable, env("INBOUNDS_RUNTIME_TOOL"), "--spec", env("INBOUNDS_SPEC_FILE"), "check"],
capture_output=True,
text=True,
)
for line in lines(p.stderr):
print(f"warning: {line}", file=sys.stderr)
def _inbound_users(verb="list", *args):
if verb in ("list", "--json"):
sys.stdout.write(_inbound_runtime("users", *(["--json"] if "--json" in (verb, *args) else []), listing=True)[1])
elif verb == "add" and args:
_inbound_runtime_change("users", "add", *args)
elif verb == "rm" and len(args) == 1:
_inbound_runtime_change("users", "rm", *args)
elif verb == "order" and len(args) == 2:
_inbound_runtime_change("users", "order", *args)
else:
usage("inbounds users [list] | add <name> [--order N] [--listener <tag>]... | rm <name> | order <name> <N>")
def cmd_inbounds(verb="list", *args):
require_enabled("INBOUNDS_ENABLED", "inbounds")
if verb == "users":
_inbound_users(*args)
return
if verb in ("bind", "unbind"):
if len(args) != 2:
usage(f"inbounds {verb} <user> <tag>")
_inbound_runtime_change(verb, *args)
return
if verb == "add":
if "--help" in args or "-h" in args:
sys.stdout.write(_inbound_runtime("add", "--help")[1])
return
if len(args) < 2:
usage("inbounds add <tag> <type> [flags] | <tag> <file.json|->")
_inbound_runtime_change("add", *args, stdin=sys.stdin.read() if args[1:2] == ("-",) else None)
return
if verb == "rm":
if len(args) != 1:
usage("inbounds rm <tag>")
_inbound_runtime_change("rm", *args)
return
if verb == "show":
if len(args) != 1:
usage("inbounds show <tag>")
sys.stdout.write(_inbound_runtime("show", *args)[1])
return
if verb == "list":
state = svc_state("proxy-suite-inbounds")
row = " {:<24} {:<16} {:<14} {:<8} {}"
print(row.format("TAG", "USER", "TYPE", "PORT", "STATE"))
# Which listeners were added at runtime, when they can be.
sources = _inbound_runtime_names("listeners") if env("INBOUNDS_RUNTIME_ENABLED") == "1" else {}
row = " {:<24} {:<16} {:<14} {:<8} {:<8}" + (" {}" if sources else "")
print(row.format("TAG", "USER", "TYPE", "PORT", "STATE", "SOURCE").rstrip())
for x in _inbound_links():
kind = _s(x.get("type")) + (" (onion)" if x.get("variant") == "onion" else "")
print(row.format(_s(x.get("tag")), _s(x.get("user")), kind, _s(x.get("port")), state))
tag = _s(x.get("tag"))
print(row.format(tag, _s(x.get("user")), kind, _s(x.get("port")), state, sources.get(tag, "nix")).rstrip())
elif verb in ("link", "qr"):
rest = [a for a in args if not a.startswith("--")]
if not rest:
+64 -1
View File
@@ -28,7 +28,7 @@ def _die(message, status=1):
# Clash API calls and systemctl spawns that several readers repeat within one load.
MEMOIZED = ("_outbound_current", "_outbound_inventory", "_autoproxy_state", "_timer_next_run", "svc_state", "_wl")
MEMOIZED = ("_outbound_current", "_outbound_inventory", "_autoproxy_state", "_timer_next_run", "svc_state", "_wl", "_inbound_runtime_rows")
# proxy_ctl as the CLI has it, before the patching below: its own tests put these back.
CLI_FUNCTIONS = {name: getattr(ctl, name) for name in ("die", *MEMOIZED)}
@@ -396,17 +396,50 @@ def inbound_rows(_):
# so a per-listener row could only repeat the same verdict once per listener. The
# "who is online" action shows it once per user, which is the shape the data has.
# A listener behind the onion service has a second row, for its .onion link.
sources = ctl._inbound_runtime_names("listeners")
return [
{
# The TUI titles its menu with the key: no trailing "/" for the plain link.
"key": "/".join(ctl._s(x.get(k)) for k in ("tag", "user", "variant") if x.get(k)),
**{k: ctl._s(x.get(k) or "") for k in ("tag", "user", "type", "port", "variant")},
**({"type": f"{ctl._s(x.get('type') or '')} (onion)"} if x.get("variant") == "onion" else {}),
"source": sources.get(ctl._s(x.get("tag")), "nix"),
}
for x in ctl._inbound_links()
]
def inbound_user_rows(_):
"""Inbound users as `inbounds users` lists them: the declared ones, and with
inbounds.runtime the runtime ones too."""
return [
{
"key": ctl._s(u.get("name")),
"name": ctl._s(u.get("name")),
"order": ctl._s(u.get("order") if u.get("order") is not None else ""),
"address": ctl._s(u.get("address") or ""),
"source": ctl._s(u.get("source") or ""),
"listeners": ",".join(ctl._s(t) for t in u.get("listeners") or []),
"problems": "; ".join(ctl._s(p) for p in u.get("problems") or []),
}
for u in ctl._inbound_runtime_rows("users")
]
def _inbounds_runtime():
return ctl.env("INBOUNDS_RUNTIME_ENABLED") == "1"
def _runtime_row(row):
return row.get("source") == "runtime"
def _user_add_argv(text):
words = shlex.split(text)
order = ["--order", words[1]] if len(words) > 1 else []
return ["inbounds", "users", "add", *words[:1], *order, *(a for t in words[2:] for a in ("--listener", t))]
def app_rows(_):
return [
{"key": ctl._s(p.get("name")), "profile": ctl._s(p.get("name")), "route": ctl._s(p.get("route"))}
@@ -753,6 +786,36 @@ TABS = [
Action("I", "traffic per inbound", lambda r, *_: ["inbounds", "stats", "--by", "inbound"], mode="dialog"),
Action("O", "traffic per exit", lambda r, *_: ["inbounds", "stats", "--by", "outbound"], mode="dialog"),
Action("n", "who is online", lambda r, *_: ["inbounds", "online"], mode="dialog"),
Action(
"a",
"add a listener…",
lambda r, t, _: ["inbounds", "add", *shlex.split(t)],
prompt="<tag> <type> [--port N] [--reality SNI] [--tls <cert>] [--user U]... - e.g. friends vless --port 20001 --reality www.microsoft.com",
offered=_inbounds_runtime,
),
Action("d", "remove this listener", lambda r, *_: ["inbounds", "rm", r["tag"]], when=_runtime_row, confirm=True, offered=_inbounds_runtime),
Action("b", "bind a user to it…", lambda r, t, _: ["inbounds", "bind", t.strip(), r["tag"]], when=ROW, prompt="<user>", offered=_inbounds_runtime),
Action("u", "unbind a user from it…", lambda r, t, _: ["inbounds", "unbind", t.strip(), r["tag"]], when=ROW, prompt="<user>", offered=_inbounds_runtime),
],
),
Tab(
"inbound-users",
"Users",
_enabled("INBOUNDS_ENABLED"),
[("name", "User"), ("order", "Order"), ("address", "Address"), ("source", "Source"), ("listeners", "Listeners"), ("problems", "Problems")],
inbound_user_rows,
summary=lambda: (
"Runtime users get generated secrets; a change restarts the inbounds, which drops every connection once."
if _inbounds_runtime()
else "Users from the configuration. inbounds.runtime would let you add and bind them here."
),
actions=[
Action("n", "add a user…", lambda r, t, _: _user_add_argv(t), prompt="<name> [order] [listener]... - e.g. alice 7 vless-in", offered=_inbounds_runtime),
Action("d", "remove this user", lambda r, *_: ["inbounds", "users", "rm", r["name"]], when=_runtime_row, confirm=True, offered=_inbounds_runtime),
Action("e", "set its order…", lambda r, t, _: ["inbounds", "users", "order", r["name"], t.strip()], when=_runtime_row, prompt="<order>", offered=_inbounds_runtime),
Action("b", "bind it to a listener…", lambda r, t, _: ["inbounds", "bind", r["name"], t.strip()], when=ROW, prompt="<listener>", offered=_inbounds_runtime),
Action("u", "unbind it from a listener…", lambda r, t, _: ["inbounds", "unbind", r["name"], t.strip()], when=ROW, prompt="<listener>", offered=_inbounds_runtime),
Action("t", "traffic per user", lambda r, *_: ["inbounds", "stats"], mode="dialog"),
],
),
Tab(
+97
View File
@@ -1157,6 +1157,103 @@ class OutboundTestTest(EnvTest):
self.assertIn("proxy-suite group, or re-run with sudo", err)
class InboundRuntimeTest(EnvTest):
"""inbounds.runtime through proxy-ctl: the tool does the work, proxy-ctl reloads after."""
def setUp(self):
super().setUp()
tool = os.environ.get("INBOUNDS_RUNTIME_TOOL")
if not tool:
self.skipTest("INBOUNDS_RUNTIME_TOOL is not set")
spool = self.path("inbounds.d")
os.makedirs(spool)
spec = {
"serverAddress": "vpn.example.com",
"shareLinks": True,
"users": {"bob": {"order": 1, "uuid": "11111111-1111-4111-8111-111111111111"}, "idle": {"order": None}},
"serverSource": {"ipv4": None, "ipv6": None, "declared": []},
"listeners": [
{"tag": "vless-in", "type": "vless", "port": 443, "order": 1000, "via": "proxy", "listen": "::",
"users": [{"name": "bob", "uuid": "11111111-1111-4111-8111-111111111111"}]},
],
"runtime": {
"spool": spool,
"ports": ["20000-20010"],
"vias": ["proxy", "block"],
"defaultVia": "proxy",
"fallbackDests": [],
"tlsCertificates": {},
"listenerDefaults": {
"address": "::", "acceptProxyProtocol": False, "fallbacks": [], "flow": None, "order": 1000, "port": 443,
"method": "2022-blake3-aes-128-gcm", "serverPassword": None, "sharePort": None, "shareAddress": None,
"hysteria": {"masquerade": None, "salamander": {"enable": False, "password": None}},
"reality": {"enable": False, "dest": "www.microsoft.com:443", "serverNames": [], "privateKey": None,
"publicKey": None, "shortIds": [""], "xver": 0},
"tls": {"enable": False, "alpn": None, "serverName": None},
"transport": {"type": "raw", "path": "/", "host": None, "mode": None, "serviceName": "", "trustedXForwardedFor": []},
},
},
}
os.environ.update(
INBOUNDS_ENABLED="1",
INBOUNDS_RUNTIME_ENABLED="1",
INBOUNDS_SPEC_FILE=self.write("spec.json", spec),
)
self.started = []
def systemctl(*args, **kw):
self.started.append(args)
return 0, ""
self.patch("systemctl", systemctl)
def test_users_and_listeners(self):
out = ok(ctl.cmd_inbounds, "users", "add", "alice", "--listener", "vless-in")
self.assertEqual(out, "Added user alice (order 2) on vless-in\n")
self.assertEqual(self.started, [("start", "proxy-suite-inbounds-reload.service")])
out = ok(ctl.cmd_inbounds, "add", "friends", "vless", "--port", "20001", "--user", "alice")
self.assertIn("Added listener friends", out)
rows = {r["name"]: r for r in json.loads(ok(ctl.cmd_inbounds, "users", "--json"))}
self.assertEqual(rows["alice"]["listeners"], ["friends", "vless-in"])
self.assertEqual(rows["bob"]["source"], "nix")
self.assertEqual(ctl._inbound_runtime_names("listeners", "runtime"), {"friends": "runtime"})
status, _, err = run(ctl.cmd_inbounds, "bind", "bob", "vless-in")
self.assertEqual(status, 1)
self.assertIn("declared in the configuration", err)
# A refusal changes nothing, so nothing is reloaded.
self.assertEqual(len(self.started), 2)
ok(ctl.cmd_inbounds, "rm", "friends")
self.assertIn("vless-in", ok(ctl.cmd_inbounds, "users"))
def test_bad_listener_is_refused(self):
status, _, err = run(ctl.cmd_inbounds, "add", "far", "vless", "--port", "30000")
self.assertEqual(status, 1)
self.assertIn("not in inbounds.runtime.ports", err)
self.assertEqual(self.started, [])
def test_off(self):
os.environ["INBOUNDS_RUNTIME_ENABLED"] = "0"
spec = ctl.read_json(os.environ["INBOUNDS_SPEC_FILE"])
spec["runtime"] = None
os.environ["INBOUNDS_SPEC_FILE"] = self.write("spec-off.json", spec)
status, _, err = run(ctl.cmd_inbounds, "users", "add", "alice")
self.assertEqual(status, 1)
self.assertIn("inbounds.runtime.enable", err)
# The declared users are still listed, on a listener or not.
rows = {r["name"]: r for r in ctl._inbound_runtime_rows("users")}
self.assertEqual(rows["bob"]["listeners"], ["vless-in"])
self.assertEqual(rows["idle"]["listeners"], [])
self.assertIn("idle", ok(ctl.cmd_inbounds, "users"))
os.environ["INBOUNDS_ENABLED"] = "0"
self.assertEqual(ctl._inbound_runtime_rows("users"), [])
def test_completion(self):
ok(ctl.cmd_inbounds, "users", "add", "alice")
self.assertIn("alice", ctl._complete_tree("inbounds", "users", "rm", ""))
self.assertNotIn("bob", ctl._complete_tree("inbounds", "users", "rm", ""))
self.assertIn("--reality", ctl._complete_tree("inbounds", "add", "x", "vless", ""))
class ShareTest(EnvTest):
def setUp(self):
super().setUp()
+31
View File
@@ -103,6 +103,37 @@ class ModelTest(unittest.TestCase):
self.assertTrue(actions["k"].when(awg) and actions["K"].when(awg) and actions["J"].when(vless))
self.assertFalse(actions["k"].when(vless) or actions["K"].when(vless) or actions["J"].when(awg))
def test_runtime_inbound_users_and_listeners(self):
users = next(t for t in model.TABS if t.id == "inbound-users")
inbounds = next(t for t in model.TABS if t.id == "inbounds")
with mock.patch.dict(os.environ, {"INBOUNDS_ENABLED": "1", "INBOUNDS_RUNTIME_ENABLED": "0"}):
# Listed from the configuration; nothing to change them with.
self.assertTrue(users.available({}))
self.assertEqual([a.key for a in users.actions if model.offered(a)], ["t"])
self.assertNotIn("a", [a.key for a in inbounds.actions if model.offered(a)])
with mock.patch.dict(os.environ, {"INBOUNDS_ENABLED": "0"}):
self.assertFalse(users.available({}))
with mock.patch.dict(os.environ, {"INBOUNDS_ENABLED": "1", "INBOUNDS_RUNTIME_ENABLED": "1"}):
self.assertTrue(users.available({}))
rows = [{"name": "bob", "source": "nix", "order": 1, "address": "10.78.0.1", "listeners": ["in"], "problems": []},
{"name": "alice", "source": "runtime", "order": 4, "address": "", "listeners": [], "problems": ["no listeners"]}]
with mock.patch.object(ctl, "_inbound_runtime_rows", lambda kind: rows):
bob, alice = model.inbound_user_rows({})
self.assertEqual((bob["listeners"], alice["problems"]), ("in", "no listeners"))
actions = {a.key: a for a in users.actions}
self.assertEqual(actions["n"].argv(None, "carol 7 in ws", {}),
["inbounds", "users", "add", "carol", "--order", "7", "--listener", "in", "--listener", "ws"])
self.assertEqual(actions["n"].argv(None, "carol", {}), ["inbounds", "users", "add", "carol"])
self.assertEqual([a.key for a in model.applicable(users, bob)], ["n", "b", "u", "t"])
self.assertEqual(actions["e"].argv(alice, " 9 ", {}), ["inbounds", "users", "order", "alice", "9"])
self.assertEqual(actions["b"].argv(alice, "in", {}), ["inbounds", "bind", "alice", "in"])
actions = {a.key: a for a in inbounds.actions}
row = {"key": "friends/alice", "tag": "friends", "user": "alice", "type": "vless", "port": "20001", "source": "runtime"}
self.assertEqual(actions["a"].argv(None, "friends vless --port 20001", {}), ["inbounds", "add", "friends", "vless", "--port", "20001"])
self.assertEqual(actions["d"].argv(row), ["inbounds", "rm", "friends"])
self.assertFalse(actions["d"].when({**row, "source": "nix"}))
self.assertEqual(actions["b"].argv(row, "bob", {}), ["inbounds", "bind", "bob", "friends"])
def test_inbound_rows_carry_no_presence(self):
"""XRay keys the online map by user, not by inbound, so a per-listener row
could only repeat one verdict per listener; it must not claim to have one."""