feat: share-variants

This commit is contained in:
fufsob committed 2026-10-03 16:24:11 +00:00
1 parent 194742c956
commit 1fc6c27489
13 files changed
+593 -25

No files matched your search

+3 -2
View File
@@ -223,8 +223,9 @@ Changes and secrets need root or the userControl group.
apps run <profile> -- <cmd> [args] run a command through a profile
inbounds [list] server inbounds
inbounds link <tag> [user] [--onion] [--qr|--json]
share link or client JSON; --onion: via the onion service
inbounds link <tag> [user] [--onion|--variant=<name>] [--qr|--json]
share link or client JSON; --onion: via the onion
service; --variant: one of the listener's shareVariants
inbounds link <tag> [user] --config [--qr]
AmneziaWG client .conf or its QR code
inbounds link <tag> --server-json the server's inbound JSON
+115
View File
@@ -82,7 +82,17 @@ Part of the [proxy-suite options reference](./index.md).
- [serverPassword](#services-proxy-suite-inbounds-listeners-name-serverpassword)
- [serverPasswordFile](#services-proxy-suite-inbounds-listeners-name-serverpasswordfile)
- [shareAddress](#services-proxy-suite-inbounds-listeners-name-shareaddress)
- [shareFingerprint](#services-proxy-suite-inbounds-listeners-name-sharefingerprint)
- [sharePort](#services-proxy-suite-inbounds-listeners-name-shareport)
- [shareVariants](#services-proxy-suite-inbounds-listeners-name-sharevariants)
- item
- [address](#services-proxy-suite-inbounds-listeners-name-sharevariants-address)
- [alpn](#services-proxy-suite-inbounds-listeners-name-sharevariants-alpn)
- [fingerprint](#services-proxy-suite-inbounds-listeners-name-sharevariants-fingerprint)
- [mode](#services-proxy-suite-inbounds-listeners-name-sharevariants-mode)
- [name](#services-proxy-suite-inbounds-listeners-name-sharevariants-name)
- [portHopping](#services-proxy-suite-inbounds-listeners-name-sharevariants-porthopping)
- [serverName](#services-proxy-suite-inbounds-listeners-name-sharevariants-servername)
- [tls](#services-proxy-suite-inbounds-listeners-name-tls)
- [enable](#services-proxy-suite-inbounds-listeners-name-tls-enable)
- [alpn](#services-proxy-suite-inbounds-listeners-name-tls-alpn)
@@ -810,6 +820,18 @@ they then send as SNI\. Links of listeners behind its fallbacks use it too\.
**Default:** `null`\
**Example:** `"cdn.example.com"`
<a id="services-proxy-suite-inbounds-listeners-name-sharefingerprint"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.shareFingerprint
Browser whose TLS ClientHello clients imitate (` fp ` in vless and trojan share links,
with tls or reality)\. A network that blocks one browser’s handshakes to a server can
let another’s through\. ` null ` leaves it out, and the client picks: XRay-based clients
(v2rayNG, v2rayN) imitate Chrome then, sing-box-based ones send Go’s own handshake\.
**Type:** null or one of “chrome”, “firefox”, “safari”, “ios”, “android”, “edge”, “360”, “qq”, “random”, “randomized”\
**Default:** `"chrome"`\
**Example:** `"firefox"`
<a id="services-proxy-suite-inbounds-listeners-name-shareport"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.sharePort
@@ -819,6 +841,99 @@ Port in share links, if something in front owns the public port\. ` null `: ` po
**Default:** `null`\
**Example:** `443`
<a id="services-proxy-suite-inbounds-listeners-name-sharevariants"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.shareVariants
More links per user to this same listener, each changing only what the client sends:
its TLS fingerprint, ALPN, xhttp mode, the name it dials and sends as SNI, or
hysteria2’s port hopping\. They follow the listener’s own link in subscriptions,
labelled “\<tag> \<name>”, so a client can test them side by side and show which of
them a network lets through\. vless, trojan and hysteria2 listeners\.
A variant only connects if the listener accepts what it changes: the ALPNs its TLS
offers, any xhttp mode unless ` transport.mode ` fixes one, names that reach it\.
**Type:** list of (submodule)\
**Default:** `[ ]`\
**Example:**
```nix
[
{ name = "firefox"; fingerprint = "firefox"; }
{ name = "h1"; alpn = [ "http/1.1" ]; }
{ name = "stream-one"; mode = "stream-one"; }
]
```
<a id="services-proxy-suite-inbounds-listeners-name-sharevariants-address"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.shareVariants\.\*\.address
Address the link dials, instead of the listener’s\. The SNI stays the listener’s unless
` serverName ` changes it too\.
**Type:** null or string\
**Default:** `null`\
**Example:** `"img.example.com"`
<a id="services-proxy-suite-inbounds-listeners-name-sharevariants-alpn"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.shareVariants\.\*\.alpn
ALPN in the link, instead of ` tls.alpn `: what the client offers, and so which HTTP
version an xhttp client speaks\. ` [ ] ` leaves it out, for the client’s default\. ` null `:
the listener’s\.
**Type:** null or (list of (one of “h3”, “h2”, “http/1\.1”))\
**Default:** `null`\
**Example:** `[ "http/1.1" ]`
<a id="services-proxy-suite-inbounds-listeners-name-sharevariants-fingerprint"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.shareVariants\.\*\.fingerprint
Browser whose TLS ClientHello the client imitates (` fp `), instead of the listener’s ` shareFingerprint `\.
**Type:** null or one of “chrome”, “firefox”, “safari”, “ios”, “android”, “edge”, “360”, “qq”, “random”, “randomized”\
**Default:** `null`\
**Example:** `"firefox"`
<a id="services-proxy-suite-inbounds-listeners-name-sharevariants-mode"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.shareVariants\.\*\.mode
xhttp mode in the link, instead of ` transport.mode `\. An xhttp listener without a mode of its own takes every one\.
**Type:** null or one of “auto”, “packet-up”, “stream-up”, “stream-one”\
**Default:** `null`\
**Example:** `"stream-one"`
<a id="services-proxy-suite-inbounds-listeners-name-sharevariants-name"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.shareVariants\.\*\.name
Names the variant: in its links’ labels, after the listener’s tag, and as ` variant ` in
` links.json ` (` proxy-ctl inbounds link <tag> --variant=<name> `)\. Not “onion”, which
the onion service’s links use\.
**Type:** string matching the pattern \[A-Za-z0-9]\[A-Za-z0-9\._-]\*\
**Example:** `"firefox"`
<a id="services-proxy-suite-inbounds-listeners-name-sharevariants-porthopping"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.shareVariants\.\*\.portHopping
hysteria2: ` false ` leaves the hop range out, so the client stays on ` port `\. ` null `: as the listener\.
**Type:** null or boolean\
**Default:** `null`\
**Example:** `false`
<a id="services-proxy-suite-inbounds-listeners-name-sharevariants-servername"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.shareVariants\.\*\.serverName
SNI in the link, instead of the listener’s\. Whatever routes by SNI in front of the
listener must send this name to it as well\.
**Type:** null or string\
**Default:** `null`\
**Example:** `"img.example.com"`
<a id="services-proxy-suite-inbounds-listeners-name-tls"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.tls
+2
View File
@@ -135,6 +135,8 @@ let
port
sharePort
shareAddress
shareFingerprint
shareVariants
acceptProxyProtocol
users
flow
@@ -309,6 +309,92 @@ let
};
};
# Browsers whose TLS ClientHello a client can imitate (uTLS), as share links name them.
fingerprintType = types.enum [
"chrome"
"firefox"
"safari"
"ios"
"android"
"edge"
"360"
"qq"
"random"
"randomized"
];
# One more link per user to a listener, with only what the client sends changed.
shareVariantType = types.submodule {
options = {
name = mkOption {
type = types.strMatching "[A-Za-z0-9][A-Za-z0-9._-]*";
description = ''
Names the variant: in its links' labels, after the listener's tag, and as `variant` in
`links.json` (`proxy-ctl inbounds link <tag> --variant=<name>`). Not "onion", which
the onion service's links use.
'';
example = "firefox";
};
fingerprint = mkOption {
type = types.nullOr fingerprintType;
default = null;
description = "Browser whose TLS ClientHello the client imitates (`fp`), instead of the listener's `shareFingerprint`.";
example = "firefox";
};
alpn = mkOption {
type = types.nullOr (
types.listOf (
types.enum [
"h3"
"h2"
"http/1.1"
]
)
);
default = null;
description = ''
ALPN in the link, instead of `tls.alpn`: what the client offers, and so which HTTP
version an xhttp client speaks. `[ ]` leaves it out, for the client's default. `null`:
the listener's.
'';
example = [ "http/1.1" ];
};
mode = mkOption {
type = types.nullOr (
types.enum [
"auto"
"packet-up"
"stream-up"
"stream-one"
]
);
default = null;
description = "xhttp mode in the link, instead of `transport.mode`. An xhttp listener without a mode of its own takes every one.";
example = "stream-one";
};
address = nullStr ''
Address the link dials, instead of the listener's. The SNI stays the listener's unless
`serverName` changes it too.
'' "img.example.com";
serverName = nullStr ''
SNI in the link, instead of the listener's. Whatever routes by SNI in front of the
listener must send this name to it as well.
'' "img.example.com";
portHopping = mkOption {
type = types.nullOr types.bool;
default = null;
description = "hysteria2: `false` leaves the hop range out, so the client stays on `port`. `null`: as the listener.";
example = false;
};
};
};
inboundType = types.submodule (
{ name, ... }:
{
@@ -376,6 +462,40 @@ let
'';
};
shareFingerprint = mkOption {
type = types.nullOr fingerprintType;
default = "chrome";
description = ''
Browser whose TLS ClientHello clients imitate (`fp` in vless and trojan share links,
with tls or reality). A network that blocks one browser's handshakes to a server can
let another's through. `null` leaves it out, and the client picks: XRay-based clients
(v2rayNG, v2rayN) imitate Chrome then, sing-box-based ones send Go's own handshake.
'';
example = "firefox";
};
shareVariants = mkOption {
type = types.listOf shareVariantType;
default = [ ];
description = ''
More links per user to this same listener, each changing only what the client sends:
its TLS fingerprint, ALPN, xhttp mode, the name it dials and sends as SNI, or
hysteria2's port hopping. They follow the listener's own link in subscriptions,
labelled "<tag> <name>", so a client can test them side by side and show which of
them a network lets through. vless, trojan and hysteria2 listeners.
A variant only connects if the listener accepts what it changes: the ALPNs its TLS
offers, any xhttp mode unless `transport.mode` fixes one, names that reach it.
'';
example = lib.literalExpression ''
[
{ name = "firefox"; fingerprint = "firefox"; }
{ name = "h1"; alpn = [ "http/1.1" ]; }
{ name = "stream-one"; mode = "stream-one"; }
]
'';
};
via = nullStr "Where this listener's traffic exits, as in `inbounds.routing.via`. `null`: use that default." "nl-vps";
order = mkOption {
@@ -791,6 +791,40 @@ let
(mkAssertion (
!proxyInboundsEnabled || l.hysteria.portHopping == null || hostKind == "nixos"
) "${prefix}: hysteria.portHopping needs a NixOS host")
# Share variants rewrite a link's query, which vmess (a JSON blob) and the others lack.
(mkAssertion (
!proxyInboundsEnabled
|| l.shareVariants == [ ]
|| builtins.elem l.type [
"vless"
"trojan"
"hysteria2"
]
) "${prefix}: shareVariants are for vless, trojan and hysteria2 listeners")
(mkAssertion (
!proxyInboundsEnabled
|| (
let
names = map (v: v.name) l.shareVariants;
in
lib.length (lib.unique names) == lib.length names && !builtins.elem "onion" names
)
) "${prefix}: shareVariants need names of their own, and not \"onion\"")
(mkAssertion (
!proxyInboundsEnabled || lib.all (v: v.mode == null || l.transport.type == "xhttp") l.shareVariants
) "${prefix}: a share variant's mode is for xhttp listeners only")
(mkAssertion (
!proxyInboundsEnabled || lib.all (v: v.portHopping == null || l.type == "hysteria2") l.shareVariants
) "${prefix}: a share variant's portHopping is for hysteria2 listeners only")
(mkAssertion (
!proxyInboundsEnabled
|| lib.all (
v:
(v.fingerprint == null && v.alpn == null && v.serverName == null)
|| tlsTerminated
|| l.reality.enable
) l.shareVariants
) "${prefix}: a share variant's fingerprint, alpn and serverName need tls or reality")
# A PROXY header opens a TCP stream; raw JSON listeners set their own sockopt.
(mkAssertion
(
+36 -8
View File
@@ -144,8 +144,9 @@ Changes and secrets need root or the userControl group.
apps run <profile> -- <cmd> [args] run a command through a profile
inbounds [list] server inbounds
inbounds link <tag> [user] [--onion] [--qr|--json]
share link or client JSON; --onion: via the onion service
inbounds link <tag> [user] [--onion|--variant=<name>] [--qr|--json]
share link or client JSON; --onion: via the onion
service; --variant: one of the listener's shareVariants
inbounds link <tag> [user] --config [--qr]
AmneziaWG client .conf or its QR code
inbounds link <tag> --server-json the server's inbound JSON
@@ -199,6 +200,7 @@ INBOUND_ADD_FLAGS = {
"--method": "shadowsocks cipher",
"--share-port": "port in share links",
"--share-address": "address in share links",
"--fingerprint": "browser fingerprint in share links (fp)",
"--order": "position in links and subscriptions",
"--masquerade": "hysteria2: site shown to anything else",
"--salamander": "hysteria2: Salamander obfuscation",
@@ -870,6 +872,7 @@ COMPLETE = {
"flags": {
"--qr": "print a QR code",
"--onion": "the link through the onion service",
"--variant=": "one of the listener's share variants: --variant=<name>",
"--json": "the client's outbound JSON",
"--config": "an AmneziaWG client's .conf",
"--server-json": "the server's inbound JSON",
@@ -1370,9 +1373,25 @@ class _UnixHTTPConnection(http.client.HTTPConnection):
self._path = path
def connect(self):
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.settimeout(self.timeout)
self.sock.connect(self._path)
# A Unix socket whose listen queue is full refuses at once with EAGAIN, timeout or
# not: a burst of callers (a whole outbounds test) is waited out, not read as no API.
deadline = time.monotonic() + (self.timeout or 0)
while True:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.settimeout(self.timeout)
try:
sock.connect(self._path)
except BlockingIOError:
sock.close()
if time.monotonic() >= deadline:
raise
time.sleep(0.05)
continue
except BaseException:
sock.close()
raise
self.sock = sock
return
def _clash_via_broker(broker, method, path, body, timeout):
@@ -1532,6 +1551,9 @@ def _clash_broker_server(path):
class Server(socketserver.ThreadingMixIn, socketserver.UnixStreamServer):
daemon_threads = True
slots = threading.BoundedSemaphore(CLASH_BROKER_MAX_CLIENTS)
# socketserver listens with a queue of 5: the rest of a burst that arrives while
# this thread checks a caller's groups was refused before it could be accepted.
request_queue_size = CLASH_BROKER_MAX_CLIENTS
def verify_request(self, request, client_address):
# Someone in no userControl group is closed on before sending a byte.
@@ -4570,7 +4592,8 @@ def _inbound_server_json(tag):
def _inbound_link_for(tag, user="", *_, field="link", variant=""):
"""variant "onion": the link to the listener through the onion service."""
"""variant "onion": the link to the listener through the onion service; any other: the
listener's share variant of that name."""
matches = [
x
for x in _inbound_links()
@@ -4579,6 +4602,8 @@ def _inbound_link_for(tag, user="", *_, field="link", variant=""):
if not matches:
if variant == "onion":
die(f"No onion link for {tag}: is it in tor.onionService.listeners, and has Tor written its address?")
if variant:
die(f"No share variant '{variant}' for {tag}: see its shareVariants, or `proxy-ctl inbounds list`.")
die(f"Unknown inbound, or no share link for it: {tag}")
if len(matches) > 1:
sys.stdout.flush()
@@ -4884,15 +4909,18 @@ def cmd_inbounds(verb="list", *args):
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 "")
kind = _s(x.get("type")) + (f" ({_s(x.get('variant'))})" if x.get("variant") else "")
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:
usage("inbounds link <tag> [user] [--onion] [--qr|--json|--config|--server-json]")
usage("inbounds link <tag> [user] [--onion|--variant=<name>] [--qr|--json|--config|--server-json]")
qr = verb == "qr" or "--qr" in args
variant = "onion" if "--onion" in args else ""
for a in args:
if a.startswith("--variant="):
variant = a[len("--variant=") :]
if "--server-json" in args:
_inbound_server_json(rest[0])
elif "--json" in args:
+6 -4
View File
@@ -429,14 +429,15 @@ def inbound_rows(_):
# No presence column: XRay keys the online map by user alone (no inbound dimension),
# 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.
# A listener behind the onion service has a second row, for its .onion link, and one per
# share variant.
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 {}),
**({"type": f"{ctl._s(x.get('type') or '')} ({ctl._s(x.get('variant'))})"} if x.get("variant") else {}),
"source": sources.get(ctl._s(x.get("tag")), "nix"),
}
for x in ctl._inbound_links()
@@ -543,8 +544,9 @@ def _natural(value):
def _link(row, *extra):
onion = ["--onion"] if row.get("variant") == "onion" else []
return ["inbounds", "link", row["tag"], *([row["user"]] if row["user"] else []), *onion, *extra]
variant = row.get("variant") or ""
which = ["--onion"] if variant == "onion" else ([f"--variant={variant}"] if variant else [])
return ["inbounds", "link", row["tag"], *([row["user"]] if row["user"] else []), *which, *extra]
def _amneziawg(row):
+113
View File
@@ -11,6 +11,7 @@ import stat
import sys
import tempfile
import threading
import time
import unittest
import urllib.parse
from unittest import mock
@@ -217,6 +218,99 @@ class ClashBrokerTest(EnvTest):
self.assertEqual(ask("GET", "/proxies"), (0, None))
self.assertEqual(len(seen), 3)
def test_a_full_listen_queue_is_waited_out(self):
# Nothing accepts at first, and the queue holds one: a Unix socket refuses the next
# connect at once (EAGAIN), which the client must retry rather than read as no API.
path = self.path("busy.sock")
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.addCleanup(server.close)
server.bind(path)
server.listen(0)
queued = [socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) for _ in range(4)]
for s in queued:
self.addCleanup(s.close)
s.setblocking(False)
try:
s.connect(path)
except BlockingIOError:
pass
def drain():
time.sleep(0.3)
server.settimeout(5)
for _ in range(len(queued) + 1):
try:
server.accept()[0].close()
except OSError:
return
threading.Thread(target=drain, daemon=True).start()
conn = ctl._UnixHTTPConnection(path, 5)
self.addCleanup(conn.close)
conn.connect()
self.assertIsNotNone(conn.sock)
# With no one ever accepting, it still gives up once its timeout has passed.
stuck = self.path("stuck.sock")
never = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.addCleanup(never.close)
never.bind(stuck)
never.listen(0)
fillers = [socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) for _ in range(4)]
for s in fillers:
self.addCleanup(s.close)
s.setblocking(False)
try:
s.connect(stuck)
except BlockingIOError:
pass
start = time.monotonic()
with self.assertRaises(BlockingIOError):
ctl._UnixHTTPConnection(stuck, 0.3).connect()
self.assertLess(time.monotonic() - start, 3)
@unittest.skipIf(os.geteuid() == 0, "root holds every scope")
def test_a_burst_of_delay_tests_all_get_answers(self):
import grp
import http.server
from concurrent.futures import ThreadPoolExecutor
try:
group = grp.getgrgid(os.getgid()).gr_name
except KeyError:
self.skipTest("no name for this group")
class Api(http.server.BaseHTTPRequestHandler):
def do_GET(self):
time.sleep(0.2) # a delay test takes a while
raw = json.dumps({"delay": 1}).encode()
self.send_response(200)
self.send_header("Content-Length", str(len(raw)))
self.end_headers()
self.wfile.write(raw)
def log_message(self, *_):
pass
api = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Api)
self.addCleanup(api.server_close)
threading.Thread(target=api.serve_forever, daemon=True).start()
self.addCleanup(api.shutdown)
self.write("clash-secret", "s3cret\n")
os.environ.update(
CLASH_API=f"http://127.0.0.1:{api.server_address[1]}",
OUTBOUND_INVENTORY_FILE=self.path("outbounds.json"),
USER_CONTROL_GROUPS=json.dumps({group: ["outbounds"]}),
)
sock = self.path("api.sock")
broker = ctl._clash_broker_server(sock)
self.addCleanup(broker.server_close)
threading.Thread(target=broker.serve_forever, daemon=True).start()
self.addCleanup(broker.shutdown)
# As `proxy outbounds test` asks: every outbound's delay at once.
with ThreadPoolExecutor(max_workers=32) as pool:
statuses = list(pool.map(lambda i: ctl._clash_via_broker(sock, "GET", f"/proxies/o{i}/delay?url=x", None, 5)[0], range(32)))
self.assertEqual(statuses, [200] * 32)
class WarpDevicesTest(EnvTest):
def test_every_device_or_the_one_named(self):
@@ -1681,6 +1775,25 @@ class ShareTest(EnvTest):
self.patch("svc_state", lambda unit: "active")
self.assertRegex(ok(ctl.cmd_inbounds, "list"), r"(?m)^ in +u +vless \(onion\) +443 +active$")
def test_inbound_share_variant_link(self):
self.write(
"inbounds/links.json",
[
{"tag": "in", "user": "u", "type": "vless", "port": 443, "link": "vless://x@h:443?fp=chrome", "outbound": {"server": "h"}},
{"tag": "in", "user": "u", "type": "vless", "port": 443, "link": "vless://x@h:443?fp=firefox",
"outbound": {"server": "h", "fp": "firefox"}, "variant": "firefox"},
],
)
# The listener's own link unless --variant names one of its variants.
self.assertEqual(ok(ctl.cmd_inbounds, "link", "in", "u"), "vless://x@h:443?fp=chrome\n")
self.assertEqual(ok(ctl.cmd_inbounds, "link", "in", "--variant=firefox"), "vless://x@h:443?fp=firefox\n")
self.assertEqual(json.loads(ok(ctl.cmd_inbounds, "link", "in", "u", "--variant=firefox", "--json"))["fp"], "firefox")
status, _, err = run(ctl.cmd_inbounds, "link", "in", "--variant=safari")
self.assertNotEqual(status, 0)
self.assertIn("No share variant 'safari'", err)
self.patch("svc_state", lambda unit: "active")
self.assertRegex(ok(ctl.cmd_inbounds, "list"), r"(?m)^ in +u +vless \(firefox\) +443 +active$")
@unittest.skipIf(os.geteuid() == 0, "root reads anything")
def test_unreadable(self):
os.chmod(self.share, 0)
+7
View File
@@ -166,6 +166,13 @@ class ModelTest(unittest.TestCase):
self.assertFalse(model._amneziawg(onion))
self.assertEqual(model.TOGGLES["proxy-suite-tor"], ["tor"])
def test_share_variant_rows_link_to_their_variant(self):
links = [{"tag": "xh", "user": "alice", "type": "vless", "port": 443, "variant": "h1"}]
with mock.patch.object(ctl, "_inbound_links", lambda: links):
(row,) = model.inbound_rows({})
self.assertEqual((row["key"], row["type"]), ("xh/alice/h1", "vless (h1)"))
self.assertEqual(model._link(row, "--json"), ["inbounds", "link", "xh", "alice", "--variant=h1", "--json"])
def test_whitelist_bypass_rows(self):
"""A creator or joiner is a unit on the services tab: toggled, restarted, and its call handled there."""
tab = model.TABS[0]
+8 -2
View File
@@ -47,6 +47,8 @@ TYPES = UUID_TYPES + PASSWORD_TYPES
TRANSPORTS = ("raw", "ws", "grpc", "httpupgrade", "xhttp")
XHTTP_MODES = ("auto", "packet-up", "stream-up", "stream-one")
ALPNS = ("h3", "h2", "http/1.1")
# As the shareFingerprint option takes them (options/types/inbounds.nix).
FINGERPRINTS = ("chrome", "firefox", "safari", "ios", "android", "edge", "360", "qq", "random", "randomized")
# Shadowsocks 2022 keys, by method: bytes of base64 key.
SS2022_KEY_BYTES = {
"2022-blake3-aes-128-gcm": 16,
@@ -203,6 +205,7 @@ LISTENER_SCHEMA = {
"port": _is_port,
"sharePort": _nullable(_is_port),
"shareAddress": _nullable(_nonspace),
"shareFingerprint": _nullable(_one_of(*FINGERPRINTS)),
"address": _nonspace,
"acceptProxyProtocol": _is_bool,
"via": _nullable(_nonspace),
@@ -538,6 +541,8 @@ def _render_listener(tag: str, entry: dict, runtime: dict) -> dict:
tls["serverName"] = certificate.get("serverName")
hysteria = filled.setdefault("hysteria", {})
hysteria["portHopping"] = None
# Declared listeners only: the module's assertions are what check them.
filled["shareVariants"] = []
hysteria.setdefault("salamander", {})["passwordFile"] = None
filled["serverPasswordFile"] = None
filled["xrayJson"] = None
@@ -1044,7 +1049,8 @@ def listener_from_flags(kind: str, args: argparse.Namespace) -> dict:
"""A listener entry from `add <tag> <type> [flags]`."""
entry: dict = {"type": kind}
for flag, key in (("port", "port"), ("listen", "address"), ("via", "via"), ("share_port", "sharePort"),
("share_address", "shareAddress"), ("order", "order"), ("method", "method")):
("share_address", "shareAddress"), ("fingerprint", "shareFingerprint"), ("order", "order"),
("method", "method")):
if getattr(args, flag) is not None:
entry[key] = getattr(args, flag)
if args.flow:
@@ -1232,7 +1238,7 @@ def main(argv: list[str] | None = None) -> int:
add.add_argument("tag")
add.add_argument("source", help="a listener type, a JSON file, or - for JSON on stdin")
for flag, kind in (("--port", int), ("--listen", str), ("--via", str), ("--share-port", int), ("--share-address", str),
("--order", int), ("--method", str), ("--flow", str), ("--transport", str), ("--path", str),
("--fingerprint", str), ("--order", int), ("--method", str), ("--flow", str), ("--transport", str), ("--path", str),
("--host", str), ("--mode", str), ("--service-name", str), ("--tls", str), ("--alpn", str),
("--sni", str), ("--reality", str), ("--reality-dest", str), ("--short-id", str),
("--masquerade", str)):
+56 -8
View File
@@ -274,7 +274,10 @@ def _link_transport_params(listener: dict) -> dict:
return params
def _link_security_params(listener: dict, server_address: str) -> dict:
def _link_security_params(listener: dict, server_address: str, fingerprint: str | None) -> dict:
"""The link's security: the TLS or REALITY of the listener it dials (`listener`, the
front of one behind a fallback), with the browser fingerprint the link's own listener
names, if any."""
reality = listener["reality"]
tls = listener["tls"]
if reality["enable"]:
@@ -289,8 +292,9 @@ def _link_security_params(listener: dict, server_address: str) -> dict:
"security": "reality",
"pbk": reality["publicKey"],
"sni": server_names[0] if server_names else server_address,
"fp": "chrome",
}
if fingerprint:
params["fp"] = fingerprint
if short_ids and short_ids[0]:
params["sid"] = short_ids[0]
return params
@@ -298,8 +302,9 @@ def _link_security_params(listener: dict, server_address: str) -> dict:
params = {
"security": "tls",
"sni": tls.get("serverName") or server_address,
"fp": "chrome",
}
if fingerprint:
params["fp"] = fingerprint
# A client left to its own ALPN offers h2 and http/1.1, and so never
# reaches an HTTP/3-only listener at all.
if tls.get("alpn"):
@@ -333,13 +338,32 @@ def _vmess_link(
return "vmess://" + _b64(json.dumps(blob, separators=(",", ":")))
def _apply_variant(params: dict, variant: dict, listener_type: str) -> None:
"""Rewrite a link's query for a share variant: only what the client sends changes."""
if variant.get("fingerprint") is not None and params.get("security") in ("tls", "reality"):
params["fp"] = variant["fingerprint"]
if variant.get("alpn") is not None:
if variant["alpn"]:
params["alpn"] = ",".join(variant["alpn"])
else:
params.pop("alpn", None)
if variant.get("mode") is not None and params.get("type") == "xhttp":
params["mode"] = variant["mode"]
if variant.get("serverName") is not None and "sni" in params:
params["sni"] = variant["serverName"]
if listener_type == "hysteria2" and variant.get("portHopping") is False:
params.pop("mport", None)
def build_share_link(
listener: dict, server_address: str, user_index: int = 0, onion_address: str = ""
listener: dict, server_address: str, user_index: int = 0, onion_address: str = "", variant: dict | None = None
) -> str:
"""Build the client-facing share URL for a listener.
With an onion address the link dials that instead, through the client's Tor; the TLS
and REALITY names stay those of server_address, which the listener still answers to.
A share variant (listener["shareVariants"]) changes what the client sends: fingerprint,
ALPN, xhttp mode, the address it dials and the SNI, hysteria2's port hopping.
"""
tag = listener["tag"]
listener_type = listener["type"]
@@ -358,9 +382,13 @@ def build_share_link(
user = users[user_index]
secret = _user_secret(user, listener_type, tag)
user_name = user.get("name") or f"{tag}-{user_index}"
label = f"{tag} ({user_name}, onion)" if onion_address else f"{tag} ({user_name})"
variant = variant or {}
if variant:
label = f"{tag} {variant['name']} ({user_name})"
else:
label = f"{tag} ({user_name}, onion)" if onion_address else f"{tag} ({user_name})"
fragment = urllib.parse.quote(label, safe="")
endpoint_address = onion_address or server_address
endpoint_address = onion_address or variant.get("address") or server_address
host = f"[{endpoint_address}]" if ":" in endpoint_address else endpoint_address
endpoint = f"{host}:{_share_port(front)}"
@@ -397,13 +425,15 @@ def build_share_link(
hopping = (listener.get("hysteria") or {}).get("portHopping")
if hopping:
params["mport"] = hopping
_apply_variant(params, variant, listener_type)
query = urllib.parse.urlencode(params, quote_via=urllib.parse.quote)
return f"hysteria2://{urllib.parse.quote(secret, safe='')}@{endpoint}?{query}#{fragment}"
params = _link_transport_params(listener)
params.update(_link_security_params(front, server_address))
params.update(_link_security_params(front, server_address, listener.get("shareFingerprint")))
if listener_type == "vless" and listener.get("flow"):
params["flow"] = listener["flow"]
_apply_variant(params, variant, listener_type)
query = urllib.parse.urlencode(params, quote_via=urllib.parse.quote)
return f"{listener_type}://{secret}@{endpoint}?{query}#{fragment}"
@@ -475,12 +505,27 @@ def build_listener(
if share_links and onion_address
else []
)
variant_links = (
[
(
variant["name"],
[
build_share_link(listener, server_address, index, variant=variant)
for index in range(len(listener["users"]))
],
)
for variant in listener.get("shareVariants") or []
]
if share_links
else []
)
return {
"tag": tag,
"type": listener["type"],
"port": _share_port(listener.get("front") or listener),
"inbound": inbound,
"links": links,
"variantLinks": variant_links,
"onionLinks": onion_links,
}
@@ -513,7 +558,8 @@ def build_inbounds(spec: dict, server_address: str, onion_address: str = "") ->
A subscription gathers one user's links from every listener -- users are
matched by name -- as base64 of the newline-joined links, which is what
v2rayNG, Hiddify and NekoBox import. Listeners in spec["onionListeners"] get a
v2rayNG, Hiddify and NekoBox import. A listener's share variants follow its own
link, each with "variant": its name. Listeners in spec["onionListeners"] get a
second link per user to onion_address, with "variant": "onion", in both.
"""
inbounds = []
@@ -524,6 +570,8 @@ def build_inbounds(spec: dict, server_address: str, onion_address: str = "") ->
rendered = build_listener(listener, server_address, spec.get("shareLinks", True), onion)
inbounds.append(rendered["inbound"])
variants = [(rendered["links"], {})]
for name, variant_links in rendered.get("variantLinks") or []:
variants.append((variant_links, {"variant": name}))
if rendered.get("onionLinks"):
variants.append((rendered["onionLinks"], {"variant": "onion"}))
for variant_links, extra in variants:
+89
View File
@@ -18,6 +18,7 @@ def listener(**overrides):
"type": "vless",
"port": 443,
"sharePort": None,
"shareFingerprint": "chrome",
"acceptProxyProtocol": False,
"listen": "::",
"via": "direct",
@@ -489,6 +490,25 @@ class RoundTripTests(unittest.TestCase):
self.assertEqual([m["type"] for m in masks], ["udphop", "salamander"])
self.assertEqual(masks[0]["settings"]["remotePorts"], "20000-30000")
def test_share_fingerprint_names_the_browser_or_leaves_it_to_the_client(self):
tls = {"enable": True, "certificateFile": "/c", "keyFile": "/k", "serverName": None}
self.assertEqual(link_params(build_share_link(listener(tls=tls), "vpn.example.com"))["fp"], "chrome")
firefox = build_share_link(listener(tls=tls, shareFingerprint="firefox"), "vpn.example.com")
self.assertEqual(link_params(firefox)["fp"], "firefox")
self.assertEqual(build_outbound(firefox, "fp", backend="xray")["streamSettings"]["tlsSettings"]["fingerprint"], "firefox")
self.assertNotIn("fp", link_params(build_share_link(listener(tls=tls, shareFingerprint=None), "vpn.example.com")))
# REALITY's too; without TLS there is no handshake to shape.
self.assertEqual(link_params(build_share_link(listener(reality=reality(), shareFingerprint="safari"), "vpn.example.com"))["fp"], "safari")
self.assertNotIn("fp", link_params(build_share_link(listener(shareFingerprint="safari"), "vpn.example.com")))
# A variant's own fingerprint wins, and one is added where the listener names none.
variant = {"name": "ff", "fingerprint": "firefox"}
self.assertEqual(link_params(build_share_link(listener(tls=tls, shareFingerprint="safari"), "vpn.example.com", variant=variant))["fp"], "firefox")
self.assertEqual(link_params(build_share_link(listener(tls=tls, shareFingerprint=None), "vpn.example.com", variant=variant))["fp"], "firefox")
self.assertEqual(
link_params(build_share_link(listener(tls=tls, shareFingerprint="safari"), "vpn.example.com", variant={"name": "plain"}))["fp"],
"safari",
)
def test_share_address_is_dialled_and_the_default_sni(self):
tls = {"enable": True, "certificateFile": "/c", "keyFile": "/k", "serverName": None}
front = listener(shareAddress="cdn.example.com", tls=tls, flow="xtls-rprx-vision")
@@ -794,6 +814,75 @@ class BuildInboundsTests(unittest.TestCase):
self.assertEqual([e for e in without["links"] if e.get("variant")], [])
self.assertEqual(without["inbounds"], result["inbounds"])
def test_share_variants_change_only_what_the_client_sends(self):
tls = {"enable": True, "certificateFile": "/c", "keyFile": "/k", "serverName": "x.example.com", "alpn": ["h2"]}
users = [{"name": "alice", "uuid": "uuid-1", "uuidFile": None, "password": "pw", "passwordFile": None}]
xhttp = {"type": "xhttp", "path": "/x", "host": None, "mode": None, "serviceName": "", "trustedXForwardedFor": []}
variants = [
{"name": "firefox", "fingerprint": "firefox"},
{"name": "h1", "alpn": ["http/1.1"]},
{"name": "any-alpn", "alpn": []},
{"name": "stream-one", "mode": "stream-one"},
{"name": "fresh", "address": "img.example.com", "serverName": "img.example.com"},
]
spec = {
"serverAddress": "vpn.example.com",
"shareLinks": True,
"listeners": [
listener(tag="xh", users=users, port=10005, sharePort=443, tls=tls, transport=xhttp, shareVariants=variants),
listener(
tag="hy2",
type="hysteria2",
users=users,
tls=dict(tls, alpn=None),
hysteria={"masquerade": None, "portHopping": "20000-20010"},
shareVariants=[{"name": "no-hop", "portHopping": False}],
),
],
}
result = build_inbounds(spec, "vpn.example.com")
# The listeners render as without variants: they change links only.
self.assertEqual(
result["inbounds"],
build_inbounds({**spec, "listeners": [dict(l, shareVariants=[]) for l in spec["listeners"]]}, "vpn.example.com")["inbounds"],
)
by_variant = {(e["tag"], e.get("variant", "")): e for e in result["links"]}
self.assertEqual(
[(e["tag"], e.get("variant", "")) for e in result["links"]],
[("xh", ""), ("xh", "firefox"), ("xh", "h1"), ("xh", "any-alpn"), ("xh", "stream-one"), ("xh", "fresh"), ("hy2", ""), ("hy2", "no-hop")],
)
base = link_params(by_variant[("xh", "")]["link"])
self.assertEqual((base["fp"], base["alpn"], base.get("mode")), ("chrome", "h2", None))
def params(variant):
entry = by_variant[("xh", variant)]
self.assertIn(f"xh {variant} (alice)", urllib.parse.unquote(urllib.parse.urlsplit(entry["link"]).fragment))
return link_params(entry["link"])
self.assertEqual(params("firefox"), dict(base, fp="firefox"))
self.assertEqual(params("h1"), dict(base, alpn="http/1.1"))
self.assertEqual(params("any-alpn"), {k: v for k, v in base.items() if k != "alpn"})
self.assertEqual(params("stream-one"), dict(base, mode="stream-one"))
self.assertEqual(params("fresh"), dict(base, sni="img.example.com"))
self.assertTrue(by_variant[("xh", "fresh")]["link"].startswith("vless://uuid-1@img.example.com:443?"))
# Each reads back into a client config that sends what it says.
stream = by_variant[("xh", "firefox")]["outbound"]["streamSettings"]
self.assertEqual(stream["tlsSettings"]["fingerprint"], "firefox")
self.assertEqual(by_variant[("xh", "h1")]["outbound"]["streamSettings"]["tlsSettings"]["alpn"], ["http/1.1"])
self.assertEqual(by_variant[("xh", "stream-one")]["outbound"]["streamSettings"]["xhttpSettings"]["mode"], "stream-one")
hop = link_params(by_variant[("hy2", "")]["link"])
self.assertEqual(hop["mport"], "20000-20010")
self.assertEqual(link_params(by_variant[("hy2", "no-hop")]["link"]), {k: v for k, v in hop.items() if k != "mport"})
self.assertNotIn("server_ports", by_variant[("hy2", "no-hop")]["outbound"])
# One subscription, every link in that order, and the same token as without variants.
body = base64.b64decode(result["subscriptions"][0]["body"]).decode().split("\n")
self.assertEqual(body, [e["link"] for e in result["links"]])
plain = build_inbounds({**spec, "listeners": [dict(l, shareVariants=[]) for l in spec["listeners"]]}, "vpn.example.com")
self.assertEqual(result["subscriptions"][0]["token"], plain["subscriptions"][0]["token"])
if __name__ == "__main__":
unittest.main()
+4 -1
View File
@@ -230,7 +230,7 @@ class RuntimeTest(unittest.TestCase):
def test_reality_listener_gets_generated_keys(self):
args = rt.main.__globals__["argparse"].Namespace(
port=20001, listen=None, via=None, share_port=None, share_address=None, order=None, method=None,
port=20001, listen=None, via=None, share_port=None, share_address=None, fingerprint="firefox", order=None, method=None,
flow="vision", transport=None, path=None, host=None, mode=None, service_name=None, tls=None, alpn=None,
sni=None, reality="www.example.com,example.com", reality_dest=None, short_id=None, masquerade=None,
salamander=False, user=["bob"],
@@ -238,6 +238,7 @@ class RuntimeTest(unittest.TestCase):
entry = rt.listener_from_flags("vless", args)
self.assertEqual(entry["reality"]["dest"], "www.example.com:443")
self.assertEqual(entry["flow"], "xtls-rprx-vision")
self.assertEqual(entry["shareFingerprint"], "firefox")
rt.cmd_add(self.spec, self.spool, "friends", entry, self.xray)
saved = self.state()["listeners"]["friends"]
self.assertEqual((saved["reality"]["privateKey"], saved["reality"]["publicKey"]), ("private-x", "public-x"))
@@ -245,6 +246,7 @@ class RuntimeTest(unittest.TestCase):
merged, result, _ = rt.merge(self.spec)
friends = next(l for l in merged["listeners"] if l["tag"] == "friends")
self.assertEqual(friends["listen"], "::")
self.assertEqual(friends["shareFingerprint"], "firefox")
self.assertEqual(friends["via"], "proxy")
self.assertTrue(friends["runtime"])
self.assertEqual(result["listeners"], ["friends"])
@@ -259,6 +261,7 @@ class RuntimeTest(unittest.TestCase):
({"type": "vless", "port": 20001, "tls": {"certificateFile": "/etc/shadow"}}, "not something a runtime entry can set"),
({"type": "vless", "port": 20001, "xrayJson": {}}, "not something a runtime entry can set"),
({"type": "amneziawg", "port": 20001}, "type: invalid value"),
({"type": "vless", "port": 20001, "shareFingerprint": "netscape"}, "shareFingerprint: invalid value"),
({"type": "hysteria2", "port": 20001, "hysteria": {"portHopping": "1-2"}}, "not something"),
({"type": "vless", "port": 20001, "fallbacks": [{"dest": 22}]}, "not in inbounds.runtime.fallbackDests"),
({"type": "vless", "port": 20001, "fallbacks": [{"listener": "vless-in"}]}, "must be another runtime listener"),