feat: awg inbounds
This commit is contained in:
31 files changed
+2876
-133
No files matched your search
+44
-13
@@ -102,6 +102,8 @@ Secrets and changes need root, or the userControl group.
|
||||
inbounds [list] server inbounds
|
||||
inbounds link <tag> [user] [--qr|--json]
|
||||
client share link, or the client's outbound JSON
|
||||
inbounds link <tag> [user] --config [--qr]
|
||||
an AmneziaWG client's .conf, or its QR code
|
||||
inbounds link <tag> --server-json the server's inbound JSON
|
||||
inbounds sub [user] [--qr] subscription users, or one user's URL
|
||||
inbounds stats [days] [--by user|inbound|outbound]
|
||||
@@ -494,7 +496,12 @@ COMPLETE = {
|
||||
"inbounds stats": {"flags": {"--by": "user, inbound or outbound"}},
|
||||
"inbounds link": {
|
||||
"args": _inbound_link_choices,
|
||||
"flags": {"--qr": "print a QR code", "--json": "the client's outbound JSON", "--server-json": "the server's inbound JSON"},
|
||||
"flags": {
|
||||
"--qr": "print a QR code",
|
||||
"--json": "the client's outbound JSON",
|
||||
"--config": "an AmneziaWG client's .conf",
|
||||
"--server-json": "the server's inbound JSON",
|
||||
},
|
||||
},
|
||||
"inbounds sub": {
|
||||
"args": lambda: _names(_s(x["user"]) for x in read_json(env("INBOUNDS_SUBS_FILE"))),
|
||||
@@ -2536,11 +2543,16 @@ def _inbound_link_for(tag, user="", *_, field="link"):
|
||||
for x in matches:
|
||||
print(f" {_s(x.get('user'))}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
entry = matches[0]
|
||||
if field == "link":
|
||||
return _s(matches[0].get("link"))
|
||||
if matches[0].get(field) is None:
|
||||
die(f"No client JSON for {tag}: proxy-suite cannot parse its link.")
|
||||
return matches[0][field]
|
||||
return _s(entry.get("link"))
|
||||
if entry.get(field) is not None:
|
||||
return entry[field]
|
||||
if field == "config":
|
||||
die(f"No client config for {tag}: only AmneziaWG listeners have one - use the link.")
|
||||
if entry.get("type") == "amneziawg":
|
||||
die(f"No client JSON for {tag}: AmneziaWG clients take a config - use --config.")
|
||||
die(f"No client JSON for {tag}: proxy-suite cannot parse its link.")
|
||||
|
||||
|
||||
def _human_bytes(b):
|
||||
@@ -2608,6 +2620,9 @@ def _inbound_stats(*args):
|
||||
print(total.format(name, _human_bytes(down), _human_bytes(up)))
|
||||
|
||||
|
||||
AWG_ONLINE_SECONDS = 180
|
||||
|
||||
|
||||
def _inbound_presence():
|
||||
"""user -> (state, addresses): "online", "seen <time>" or "never seen"; dies when the stats API is silent."""
|
||||
status, out = _run(
|
||||
@@ -2621,12 +2636,24 @@ def _inbound_presence():
|
||||
online = {_s(u.get("email")): u.get("ips") or [] for u in json.loads(out or "{}").get("users") or []}
|
||||
except (ValueError, AttributeError):
|
||||
die("Unexpected answer from the inbounds' stats API.")
|
||||
# As the timer last wrote it: the API already told who is online now.
|
||||
path = env("INBOUNDS_STATS_FILE", f"{state_dir()}/inbound-stats.json")
|
||||
seen = (read_json(path).get("seen") or {}) if readable(path) else {}
|
||||
# Users nobody has seen yet, when the links say who exists.
|
||||
path = env("INBOUNDS_LINKS_FILE")
|
||||
known = {_s(x.get("user")) for x in read_json(path) if x.get("user")} if readable(path) else set()
|
||||
links = read_json(path) if readable(path) else []
|
||||
known = {_s(x.get("user")) for x in links if x.get("user")}
|
||||
# AmneziaWG peers are only known by their last handshake, which the collector reads;
|
||||
# the XRay API already told who else is online now.
|
||||
if any(x.get("type") == "amneziawg" for x in links):
|
||||
systemctl("--no-ask-password", "start", "proxy-suite-inbound-stats.service", quiet=True)
|
||||
path = env("INBOUNDS_STATS_FILE", f"{state_dir()}/inbound-stats.json")
|
||||
stats = read_json(path) if readable(path) else {}
|
||||
seen = stats.get("seen") or {}
|
||||
now = time.time()
|
||||
for user, peer in (stats.get("awgPeers") or {}).items():
|
||||
handshake = (peer or {}).get("handshake") or 0
|
||||
endpoint = _s((peer or {}).get("endpoint") or "")
|
||||
# A live peer handshakes every two minutes.
|
||||
if handshake and now - handshake < AWG_ONLINE_SECONDS and endpoint:
|
||||
online.setdefault(_s(user), []).append({"ip": endpoint.rsplit(":", 1)[0].strip("[]")})
|
||||
|
||||
def when(ts):
|
||||
return datetime.datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M")
|
||||
@@ -2652,8 +2679,9 @@ def _inbound_online():
|
||||
print(row.format(user, state, addresses))
|
||||
sys.stdout.flush()
|
||||
print(
|
||||
"A user counts as online while a connection is open. Behind a web server that needs the "
|
||||
"listener's transport.trustedXForwardedFor, or everyone reads as never seen.",
|
||||
"A user counts as online while a connection is open, or for AmneziaWG within three minutes "
|
||||
"of a handshake. Behind a web server that needs the listener's transport.trustedXForwardedFor, "
|
||||
"or everyone reads as never seen.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
|
||||
@@ -2707,13 +2735,16 @@ def cmd_inbounds(verb="list", *args):
|
||||
elif verb in ("link", "qr"):
|
||||
rest = [a for a in args if not a.startswith("--")]
|
||||
if not rest:
|
||||
usage("inbounds link <tag> [user] [--qr|--json|--server-json]")
|
||||
usage("inbounds link <tag> [user] [--qr|--json|--config|--server-json]")
|
||||
qr = verb == "qr" or "--qr" in args
|
||||
if "--server-json" in args:
|
||||
_inbound_server_json(rest[0])
|
||||
elif "--json" in args:
|
||||
print(_json_text(_inbound_link_for(*rest, field="outbound")))
|
||||
elif "--config" in args:
|
||||
_emit(_inbound_link_for(*rest, field="config").rstrip("\n"), qr)
|
||||
else:
|
||||
_emit(_inbound_link_for(*rest), verb == "qr" or "--qr" in args)
|
||||
_emit(_inbound_link_for(*rest), qr)
|
||||
elif verb == "stats":
|
||||
_inbound_stats(*args)
|
||||
elif verb == "online":
|
||||
|
||||
@@ -352,6 +352,11 @@ def _link(row, *extra):
|
||||
return ["inbounds", "link", row["tag"], *([row["user"]] if row["user"] else []), *extra]
|
||||
|
||||
|
||||
def _amneziawg(row):
|
||||
# AmneziaWG clients take a .conf (or its vpn:// link), not an outbound JSON.
|
||||
return row["type"] == "amneziawg"
|
||||
|
||||
|
||||
def _kind(*kinds):
|
||||
return lambda row: row["kind"] in kinds
|
||||
|
||||
@@ -512,7 +517,9 @@ TABS = [
|
||||
# Without subscriptions.baseUrl there is only a file path, with a hint after it: nothing to encode or copy.
|
||||
Action("S", "subscription URL as QR", lambda r, *_: ["inbounds", "sub", r["user"], "--qr"], when=_sub_url, mode="dialog"),
|
||||
Action("y", "copy subscription URL", lambda r, *_: ["inbounds", "sub", r["user"]], when=_sub_url, mode="copy"),
|
||||
Action("J", "client's outbound JSON", lambda r, *_: _link(r, "--json"), when=ROW, mode="dialog"),
|
||||
Action("J", "client's outbound JSON", lambda r, *_: _link(r, "--json"), when=lambda r: not _amneziawg(r), mode="dialog"),
|
||||
Action("w", "client config", lambda r, *_: _link(r, "--config"), when=_amneziawg, mode="dialog"),
|
||||
Action("W", "client config as QR", lambda r, *_: _link(r, "--config", "--qr"), when=_amneziawg, mode="dialog"),
|
||||
Action("V", "server's inbound JSON", lambda r, *_: ["inbounds", "link", r["tag"], "--server-json"], when=ROW, mode="dialog"),
|
||||
Action("t", "traffic per user", lambda r, *_: ["inbounds", "stats"], mode="dialog"),
|
||||
Action("I", "traffic per inbound", lambda r, *_: ["inbounds", "stats", "--by", "inbound"], mode="dialog"),
|
||||
|
||||
@@ -474,6 +474,35 @@ class InboundsTest(EnvTest):
|
||||
self.patch("_run", lambda *a, **kw: (1, ""))
|
||||
self.assertNotEqual(run(ctl._inbound_online)[0], 0)
|
||||
|
||||
def test_online_amneziawg(self):
|
||||
answer = {"users": [{"email": "fufsob", "ips": [{"ip": "203.0.113.7", "lastSeen": 1789471207}]}]}
|
||||
self.patch("_run", lambda *a, **kw: (0, json.dumps(answer)))
|
||||
started = []
|
||||
self.patch("systemctl", lambda *a, **kw: started.append(a))
|
||||
now = 1789471300
|
||||
self.patch("time", mock.Mock(time=lambda: now))
|
||||
os.environ["INBOUNDS_STATS_FILE"] = self.write(
|
||||
"stats.json",
|
||||
{
|
||||
"seen": {"phone": now - 600, "laptop": now - 30},
|
||||
"awgPeers": {
|
||||
"phone": {"tag": "awg", "handshake": now - 600, "endpoint": "198.51.100.2:5000"},
|
||||
"laptop": {"tag": "awg", "handshake": now - 30, "endpoint": "[2001:db8::5]:51820"},
|
||||
"tablet": {"tag": "awg", "handshake": 0, "endpoint": None},
|
||||
},
|
||||
},
|
||||
)
|
||||
os.environ["INBOUNDS_LINKS_FILE"] = self.write(
|
||||
"links.json", [{"tag": "a", "user": "fufsob", "type": "vless"}, {"tag": "awg", "user": "tablet", "type": "amneziawg"}]
|
||||
)
|
||||
out = ok(ctl._inbound_online)
|
||||
# The collector reads the handshakes first.
|
||||
self.assertEqual(started, [("--no-ask-password", "start", "proxy-suite-inbound-stats.service")])
|
||||
self.assertRegex(out, r"(?m)^ fufsob +online +203\.0\.113\.7$")
|
||||
self.assertRegex(out, r"(?m)^ laptop +online +2001:db8::5$")
|
||||
self.assertRegex(out, r"(?m)^ phone +seen ")
|
||||
self.assertRegex(out, r"(?m)^ tablet +never seen")
|
||||
|
||||
def test_subscriptions(self):
|
||||
os.environ["INBOUNDS_SUBS_FILE"] = self.write("subs.json", [{"user": "fufsob", "token": "aaa"}, {"user": "teri", "token": "bbb"}])
|
||||
os.environ["INBOUNDS_SUB_BASE_URL"] = "https://vpn.example/sub/"
|
||||
@@ -688,6 +717,28 @@ class ShareTest(EnvTest):
|
||||
self.assertEqual(json.loads(ok(ctl.cmd_inbounds, "link", "in", "--json")), {"type": "vless"})
|
||||
self.assertEqual(json.loads(ok(ctl.cmd_inbounds, "link", "in", "--server-json"))["protocol"], "vless")
|
||||
|
||||
def test_inbound_amneziawg_config(self):
|
||||
config = "[Interface]\nPrivateKey = k\n\n[Peer]\nEndpoint = h:51820\n"
|
||||
self.write(
|
||||
"inbounds/links.json",
|
||||
[
|
||||
{"tag": "in", "user": "u", "type": "vless", "link": "vless://x@h:443", "outbound": {"type": "vless"}},
|
||||
{"tag": "awg", "user": "u", "type": "amneziawg", "link": "vpn://abc", "config": config, "outbound": None},
|
||||
],
|
||||
)
|
||||
emitted = []
|
||||
self.patch("_run", lambda cmd, **kw: (emitted.append((cmd, kw.get("stdin"))), (0, ""))[1])
|
||||
self.assertEqual(ok(ctl.cmd_inbounds, "link", "awg", "u"), "vpn://abc\n")
|
||||
self.assertEqual(ok(ctl.cmd_inbounds, "link", "awg", "--config"), config)
|
||||
ok(ctl.cmd_inbounds, "link", "awg", "u", "--config", "--qr")
|
||||
self.assertEqual(emitted[-1], (["qrencode", "-t", "ANSIUTF8"], config.rstrip("\n")))
|
||||
status, _, err = run(ctl.cmd_inbounds, "link", "awg", "--json")
|
||||
self.assertNotEqual(status, 0)
|
||||
self.assertIn("use --config", err)
|
||||
status, _, err = run(ctl.cmd_inbounds, "link", "in", "--config")
|
||||
self.assertNotEqual(status, 0)
|
||||
self.assertIn("only AmneziaWG", err)
|
||||
|
||||
@unittest.skipIf(os.geteuid() == 0, "root reads anything")
|
||||
def test_unreadable(self):
|
||||
os.chmod(self.share, 0)
|
||||
|
||||
@@ -79,6 +79,16 @@ class ModelTest(unittest.TestCase):
|
||||
self.assertEqual(model.toggle_argv(row), ["awg", "on", "warp"]) # a global profile named warp
|
||||
self.assertIn("ctrl+r", keys())
|
||||
|
||||
def test_inbound_amneziawg_actions(self):
|
||||
tab = next(t for t in model.TABS if t.id == "inbounds")
|
||||
actions = {a.key: a for a in tab.actions}
|
||||
awg = {"key": "awg/u", "tag": "awg", "user": "u", "type": "amneziawg", "port": "51820"}
|
||||
vless = {"key": "in/u", "tag": "in", "user": "u", "type": "vless", "port": "443"}
|
||||
self.assertEqual(actions["w"].argv(awg), ["inbounds", "link", "awg", "u", "--config"])
|
||||
self.assertEqual(actions["W"].argv(awg), ["inbounds", "link", "awg", "u", "--config", "--qr"])
|
||||
self.assertTrue(actions["w"].when(awg) and actions["W"].when(awg) and actions["J"].when(vless))
|
||||
self.assertFalse(actions["w"].when(vless) or actions["W"].when(vless) or actions["J"].when(awg))
|
||||
|
||||
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."""
|
||||
|
||||
Reference in new issue
Block a user