feat: json exports/imports

This commit is contained in:
fufsob committed 2026-09-15 04:53:39 +00:00
1 parent d7108abf0c
commit aa19042ee5
18 files changed
+778 -42

No files matched your search

+8 -2
View File
@@ -112,10 +112,12 @@ A group without a verb shows its status or list.
proxy [status|on|off] local proxy backend
proxy outbounds [list] outbounds, where each came from, and the pick
proxy outbounds add <tag> <url> add an outbound at runtime
proxy outbounds add <tag> <url|json|-> add an outbound at runtime: a URL, or sing-box/XRay JSON (-: stdin)
proxy outbounds rm <tag> remove a runtime outbound
proxy outbounds test [tag...] [--ping] [--delay] [--download]
TCP ping, real delay, download speed (default: ping, delay)
proxy outbounds link <tag> [--qr|--json|--config]
its URL, QR code, backend JSON, or a client config for it (sudo)
proxy pin [tag] always use this outbound (no tag: pick from a menu)
proxy unpin let the configured selection pick again
proxy mode [default|whitelist|blacklist|all-proxy|all-bypass]
@@ -123,6 +125,8 @@ A group without a verb shows its status or list.
proxy subs [list|update] subscription caches; update refetches them
proxy subs add <tag> <url> add a subscription at runtime
proxy subs rm <tag> remove a runtime subscription
proxy subs link <tag> [--qr] its URL (sudo)
proxy config [--raw] client config to import elsewhere; --raw: as running (sudo)
proxy tun [status|on|off] global TUN mode
proxy tproxy [status|on|off] global TProxy mode
proxy auto [list] what autoProxy routed, and via which exit (sudo, or userControl)
@@ -151,7 +155,9 @@ A group without a verb shows its status or list.
apps run <profile> -- <cmd> [args] run a command through a profile
inbounds [list] server inbounds
inbounds link <tag> [user] [--qr] client share link
inbounds link <tag> [user] [--qr|--json]
client share link, or the client's outbound JSON
inbounds link <tag> --server-json the server's inbound JSON (sudo)
inbounds sub [user] [--qr] subscription users, or one user's URL
inbounds stats [days] traffic per user (sudo, or userControl)
```
@@ -131,7 +131,7 @@ let
TAG="''${TAG%.json}"
case "$KEEP" in
*"|$TAG|"*) ;;
*) rm -f "$CACHE" ;;
*) rm -f "$CACHE" "''${CACHE%.json}.links" ;;
esac
done
@@ -99,14 +99,53 @@ let
ob=$(_proxy_suite_parse_url "$tag" "$url") || return 1
OUTBOUNDS_JSON=$(${jq} --argjson ob "$ob" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
'';
# Raw JSON gets the tag and the routing mark a Nix-declared one gets (rawOutboundJson).
singBoxMark = lib.optionalString (routingMark != null) " | .routing_mark = ${toString routingMark}";
xrayMark = lib.optionalString (
routingMark != null
) " | .streamSettings.sockopt.mark = ${toString routingMark}";
jsonAddBlock =
if hybridEnabled then
''
case "$kind" in
xray) _proxy_suite_add_xray_sidecar_ob "$ob" "$tag" ;;
sing-box) _proxy_suite_add_sing_box_ob "$(${jq} -c '.${singBoxMark}' <<< "$ob")" ;;
*) echo "proxy-suite: outbound '$tag' is neither sing-box nor XRay JSON" >&2; return 1 ;;
esac
''
else
let
want = if pureXrayEnabled then "xray" else "sing-box";
in
''
if [ "$kind" != ${want} ]; then
echo "proxy-suite: outbound '$tag' is not ${want} JSON" >&2
return 1
fi
OUTBOUNDS_JSON=$(${jq} --argjson ob "$ob" '. + [$ob${
if pureXrayEnabled then xrayMark else singBoxMark
}]' <<< "$OUTBOUNDS_JSON")
'';
in
''
OUTBOUND_SOURCES_JSON='{}'
# What proxy-ctl shares back: tag -> the URL it was given, sub tag -> its URL.
OUTBOUND_URLS_JSON='{}'
SUBSCRIPTION_URLS_JSON='{}'
_proxy_suite_record_tag_source() {
OUTBOUND_SOURCES_JSON=$(${jq} --arg t "$1" --arg s "$2" '.[$t] = $s' <<< "$OUTBOUND_SOURCES_JSON")
}
# $1 sub tag, $2 file holding its URL, $3 its links file (absent for a cache
# written before links existed: those entries share as JSON until the next update).
_proxy_suite_record_subscription_share() {
SUBSCRIPTION_URLS_JSON=$(${jq} --arg t "$1" --rawfile u "$2" '.[$t] = ($u | rtrimstr("\n"))' <<< "$SUBSCRIPTION_URLS_JSON")
if [ -s "$3" ]; then
OUTBOUND_URLS_JSON=$(${jq} --slurpfile l "$3" '. + $l[0]' <<< "$OUTBOUND_URLS_JSON") || true
fi
}
# $1 source label, $2 array length before the add, $3 after. Subscriptions
# append an unknown number of outbounds, so they label them by range.
_proxy_suite_record_outbound_source() {
@@ -142,18 +181,28 @@ let
local tag="$1" url="$2" source="$3" pref="''${4:-auto}" ob
${addBlock}
_proxy_suite_record_tag_source "$tag" "$source"
OUTBOUND_URLS_JSON=$(${jq} --arg t "$tag" --arg u "$url" '.[$t] = $u' <<< "$OUTBOUND_URLS_JSON")
}
# Every runtime outbound, as "<tag>\t<url file>" lines. proxy-ctl refuses
# $1 tag, $2 file holding one sing-box or XRay outbound, $3 source label.
_proxy_suite_add_json_outbound() {
local tag="$1" source="$3" ob kind
ob=$(${jq} -ce --arg t "$tag" 'select(type == "object") | .tag = $t' "$2" 2>/dev/null) || return 1
kind=$(${jq} -r 'if has("protocol") then "xray" elif has("type") then "sing-box" else "" end' <<< "$ob")
${jsonAddBlock}
_proxy_suite_record_tag_source "$tag" "$source"
}
# Every runtime outbound, as "<tag>\t<file>" lines: <tag>.url or <tag>.json. proxy-ctl refuses
# the reserved names, but the spool is group-writable, so check again here:
# a second outbound tagged "proxy" would quietly shadow the real one.
_proxy_suite_runtime_outbounds() {
local f tag
[ -d "${runtimeOutboundsDir}" ] || return 0
for f in "${runtimeOutboundsDir}"/*.url; do
for f in "${runtimeOutboundsDir}"/*.url "${runtimeOutboundsDir}"/*.json; do
[ -e "$f" ] || continue
tag="''${f##*/}"
tag="''${tag%.url}"
tag="''${tag%.*}"
case "$tag" in
proxy | direct | block)
echo "proxy-suite: warning: ignoring runtime outbound '$tag': reserved name" >&2
@@ -356,8 +405,10 @@ let
# outbounds added at runtime
while IFS=$'\t' read -r RUNTIME_OB_TAG RUNTIME_OB_SRC; do
[ -n "$RUNTIME_OB_TAG" ] || continue
_proxy_suite_add_url_outbound "$RUNTIME_OB_TAG" "$(cat "$RUNTIME_OB_SRC")" runtime \
|| echo "proxy-suite: warning: ignoring runtime outbound '$RUNTIME_OB_TAG'" >&2
case "$RUNTIME_OB_SRC" in
*.json) _proxy_suite_add_json_outbound "$RUNTIME_OB_TAG" "$RUNTIME_OB_SRC" runtime ;;
*) _proxy_suite_add_url_outbound "$RUNTIME_OB_TAG" "$(cat "$RUNTIME_OB_SRC")" runtime ;;
esac || echo "proxy-suite: warning: ignoring runtime outbound '$RUNTIME_OB_TAG'" >&2
done < <(_proxy_suite_runtime_outbounds)
'';
@@ -66,17 +66,22 @@ let
fi
}
# $1 tag, $2 file holding the subscription URL. Writes the cache atomically.
# $1 tag, $2 file holding the subscription URL. Writes the cache atomically,
# and next to it <tag>.links: each entry's original URI, for proxy-ctl to share.
_proxy_suite_fetch_subscription() {
local tag="$1" src="$2" cache="$SUB_CACHE_DIR/$1.json"
local tag="$1" src="$2" cache="$SUB_CACHE_DIR/$1.json" links="$SUB_CACHE_DIR/$1.links"
mkdir -p "$SUB_CACHE_DIR"
if printf '%s' "$(cat "$src")" \
| PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${fetchSubscriptionPy} \
${subscriptionBackendArg} --tag-prefix "$tag" > "$cache.tmp"; then
_proxy_suite_commit_subscription_cache "$cache.tmp" "$cache" "$tag"
return
${subscriptionBackendArg} --tag-prefix "$tag" --links-out "$links.tmp" > "$cache.tmp"; then
if _proxy_suite_commit_subscription_cache "$cache.tmp" "$cache" "$tag"; then
mv "$links.tmp" "$links"
return 0
fi
rm -f "$links.tmp"
return 1
fi
rm -f "$cache.tmp"
rm -f "$cache.tmp" "$links.tmp"
echo "proxy-suite: failed to update subscription '$tag'" >&2
return 1
}
@@ -138,6 +143,7 @@ let
${mergeBlock}
after=$(${jq} 'length' <<< "$OUTBOUNDS_JSON")
_proxy_suite_record_outbound_source "sub:$tag" "$before" "$after"
_proxy_suite_record_subscription_share "$tag" "$src" "$SUB_CACHE_DIR/$tag.links"
}
'';
@@ -270,6 +270,21 @@ let
}
mv "$ENDPOINTS_TMP" "$RUNTIME_DIR/outbound-endpoints.json"
# proxy-ctl's share links: the URL each outbound was given, and its backend JSON.
# Credentials, so root only, whatever userControl allows.
SHARE_TMP="$RUNTIME_DIR/outbound-share.json.tmp"
(umask 077 && ${jq} -c --argjson sidecar "''${XRAY_OUTBOUNDS_JSON:-[]}" --arg collapsed "''${PROXY_TAG:-}" \
--argjson urls "$OUTBOUND_URLS_JSON" --argjson subs "$SUBSCRIPTION_URLS_JSON" '
($sidecar | map({key: .tag, value: .}) | from_entries) as $real
| {outbounds: ([.[] | select(.type != "selector" and .type != "urltest")
| (.tag | ltrimstr("proxy-suite-ob-") | if . == "proxy" then $collapsed else . end) as $tag
| {key: $tag, value: {url: $urls[$tag], outbound: (($real[$tag] // $real[.tag] // .) | .tag = $tag)}}]
| from_entries),
subscriptions: $subs}
' <<< "$OUTBOUNDS_JSON" > "$SHARE_TMP")
chmod 600 "$SHARE_TMP"
mv "$SHARE_TMP" "$RUNTIME_DIR/outbound-share.json"
${lib.optionalString (!pureXrayEnabled) ''
# Delay and download: a loopback listener pinned to a selector over every real
# exit, switched one outbound at a time through the Clash API.
+22 -1
View File
@@ -109,7 +109,7 @@
printf '%s\n' '#!/bin/sh'
printf '%s\n' 'if [ "$1" = start ] && [ "$2" = proxy-suite-outbound-reload.service ]; then'
printf '%s\n' ' ls "$RUNTIME_OUTBOUNDS_DIR" > "$OUTBOUND_INVENTORY_FILE.spool"'
printf '%s\n' ' jq --rawfile spool "$OUTBOUND_INVENTORY_FILE.spool" '"'"'($spool | split("\n") | map(select(endswith(".url")) | rtrimstr(".url"))) as $new | .tags = (.tags + $new | unique) | .sources = reduce $new[] as $t (.sources; .[$t] = "runtime")'"'"' "$OUTBOUND_INVENTORY_FILE" > "$OUTBOUND_INVENTORY_FILE.tmp"'
printf '%s\n' ' jq --rawfile spool "$OUTBOUND_INVENTORY_FILE.spool" '"'"'($spool | split("\n") | map(select(endswith(".url") or endswith(".json")) | sub("\\.(url|json)$"; ""))) as $new | .tags = (.tags + $new | unique) | .sources = reduce $new[] as $t (.sources; .[$t] = "runtime")'"'"' "$OUTBOUND_INVENTORY_FILE" > "$OUTBOUND_INVENTORY_FILE.tmp"'
printf '%s\n' ' mv "$OUTBOUND_INVENTORY_FILE.tmp" "$OUTBOUND_INVENTORY_FILE"'
printf '%s\n' 'fi'
printf '%s\n' 'exit 0'
@@ -184,6 +184,18 @@
run proxy outbounds rm spool-one | grep -q 'Removed outbound: spool-one'
[ ! -e obd/spool-one.url ]
# JSON, as `link --json` prints it, lands as <tag>.json without its own tag; stdin too.
run proxy outbounds add from-json '{"type":"trojan","tag":"x","server":"t.test","server_port":443,"password":"p"}' \
| grep -q 'Added outbound: from-json'
[ "$(jq -r 'has("tag"), .server' obd/from-json.json | paste -sd,)" = "false,t.test" ]
printf '%s' '{"protocol":"vless","settings":{}}' | run proxy outbounds add from-stdin - | grep -q 'Added outbound: from-stdin'
! run proxy outbounds add from-json '{"type":"trojan"}' 2>/dev/null
! run proxy outbounds add bad-json '{"server":"t.test"}' 2>/dev/null
! run proxy outbounds add bad-json '{nope' 2>/dev/null
[ ! -e obd/bad-json.json ]
run proxy outbounds rm from-json | grep -q 'Removed outbound: from-json'
[ ! -e obd/from-json.json ]
# Subscriptions use the same spool machinery, verified by cache file.
printf '%s\n' '[{},{}]' > cache/extra.json
run proxy subs add extra https://example.com/sub | grep -q 'Added subscription: extra (2 proxies)'
@@ -413,6 +425,15 @@
touch "$out"
'';
# proxy_export: the running config made portable, and sing-box still accepts it.
proxy-export-unit =
pkgs.runCommand "proxy-suite-proxy-export-unit-check" { nativeBuildInputs = [ pkgs.python3 ]; } ''
export SING_BOX=${pkgs.sing-box}/bin/sing-box
export PYTHONDONTWRITEBYTECODE=1 PYTHONPATH=${../../pkgs/proxy-ctl}
python ${../../pkgs/proxy-ctl}/test_proxy_export.py
touch "$out"
'';
# proxy-tui driven headless: keys turn into the right proxy-ctl argv.
proxy-tui-unit =
pkgs.runCommand "proxy-suite-proxy-tui-unit-check"
+3
View File
@@ -80,9 +80,11 @@ let
lib.mapAttrsToList (name: value: "--set ${name} ${lib.escapeShellArg value}") wrapperEnv
);
# The modules both front-ends import: proxy_ctl for reads, proxy_model for the tabs and the tray menu.
# proxy_export: what `proxy-ctl proxy config` imports.
pythonModules = pkgs.runCommand "proxy-suite-python-modules" { } ''
install -Dm644 ${./proxy-ctl/proxy_ctl.py} "$out/proxy_ctl.py"
install -Dm644 ${./proxy-ctl/proxy_model.py} "$out/proxy_model.py"
install -Dm644 ${./proxy-ctl/proxy_export.py} "$out/proxy_export.py"
'';
# A separate package: the Textual closure stays off hosts that don't enable it.
# It imports proxy_ctl for reads and runs proxy-ctl for every change.
@@ -225,6 +227,7 @@ let
[ -x "$probe_curl" ]
wrapProgram "$out/bin/proxy-ctl" \
--set PROBE_CURL "$probe_curl" \
--set PROXY_CTL_MODULES ${pythonModules} \
--prefix PATH : "${
lib.makeBinPath [
# curl-impersonate's curl_chrome* wrappers are `#!/usr/bin/env bash`.
+183 -20
View File
@@ -53,10 +53,12 @@ A group without a verb shows its status or list.
proxy [status|on|off] local proxy backend
proxy outbounds [list] outbounds, where each came from, and the pick
proxy outbounds add <tag> <url> add an outbound at runtime
proxy outbounds add <tag> <url|json|-> add an outbound at runtime: a URL, or sing-box/XRay JSON (-: stdin)
proxy outbounds rm <tag> remove a runtime outbound
proxy outbounds test [tag...] [--ping] [--delay] [--download]
TCP ping, real delay, download speed (default: ping, delay)
proxy outbounds link <tag> [--qr|--json|--config]
its URL, QR code, backend JSON, or a client config for it (sudo)
proxy pin [tag] always use this outbound (no tag: pick from a menu)
proxy unpin let the configured selection pick again
proxy mode [default|whitelist|blacklist|all-proxy|all-bypass]
@@ -64,6 +66,8 @@ A group without a verb shows its status or list.
proxy subs [list|update] subscription caches; update refetches them
proxy subs add <tag> <url> add a subscription at runtime
proxy subs rm <tag> remove a runtime subscription
proxy subs link <tag> [--qr] its URL (sudo)
proxy config [--raw] client config to import elsewhere; --raw: as running (sudo)
proxy tun [status|on|off] global TUN mode
proxy tproxy [status|on|off] global TProxy mode
proxy auto [list] what autoProxy routed, and via which exit (sudo, or userControl)
@@ -92,7 +96,9 @@ A group without a verb shows its status or list.
apps run <profile> -- <cmd> [args] run a command through a profile
inbounds [list] server inbounds
inbounds link <tag> [user] [--qr] client share link
inbounds link <tag> [user] [--qr|--json]
client share link, or the client's outbound JSON
inbounds link <tag> --server-json the server's inbound JSON (sudo)
inbounds sub [user] [--qr] subscription users, or one user's URL
inbounds stats [days] traffic per user (sudo, or userControl)
"""
@@ -317,16 +323,23 @@ COMPLETE = {
"tun": "global TUN mode",
"tproxy": "global TProxy mode",
"auto": "what autoProxy routed",
"config": "client config to import elsewhere",
}
},
"proxy config": {"flags": {"--raw": "the config as it runs here"}},
"proxy outbounds": {
"words": {
"list": "outbounds, where each came from, and the pick",
"add": "add an outbound at runtime",
"add": "add an outbound at runtime: a URL or JSON",
"rm": "remove a runtime outbound",
"test": "TCP ping, real delay, download speed",
"link": "its URL, QR code, JSON or client config",
}
},
"proxy outbounds link": {
"args": _outbound_choices,
"flags": {"--qr": "print a QR code", "--json": "backend JSON", "--config": "client config for this server"},
},
"proxy outbounds rm": {"args": lambda: _names(_runtime_tags("outbound"))},
"proxy outbounds test": {
"args": _outbound_choices,
@@ -345,8 +358,10 @@ COMPLETE = {
"update": "refetch the subscriptions",
"add": "add a subscription at runtime",
"rm": "remove a runtime subscription",
"link": "its URL",
}
},
"proxy subs link": {"args": lambda: _names(_sub_tags() + _runtime_tags("subscription")), "flags": {"--qr": "print a QR code"}},
"proxy subs rm": {"args": lambda: _names(_runtime_tags("subscription"))},
"proxy tun": {"words": TOGGLE},
"proxy tproxy": {"words": TOGGLE},
@@ -407,7 +422,10 @@ COMPLETE = {
"stats": "traffic per user",
}
},
"inbounds link": {"args": _inbound_link_choices, "flags": {"--qr": "print a QR code"}},
"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"},
},
"inbounds sub": {
"args": lambda: _names(_s(x["user"]) for x in read_json(env("INBOUNDS_SUBS_FILE"))),
"flags": {"--qr": "print a QR code"},
@@ -689,6 +707,8 @@ def cmd_proxy(verb="status", *args):
must("stop", "proxy-suite-socks")
elif verb == "outbounds":
cmd_outbounds(*args)
elif verb == "config":
_config_export(*args)
elif verb == "pin":
cmd_pin(*args)
elif verb == "unpin":
@@ -706,7 +726,7 @@ def cmd_proxy(verb="status", *args):
elif verb in ("probe", "learn", "queue", "learned"):
cmd_proxy_auto(verb, *args)
else:
usage("proxy [status|on|off|outbounds|pin|unpin|mode|subs|tun|tproxy|auto]")
usage("proxy [status|on|off|outbounds|pin|unpin|mode|subs|tun|tproxy|auto|config]")
def cmd_outbounds(verb="list", *args):
@@ -718,8 +738,10 @@ def cmd_outbounds(verb="list", *args):
_runtime_entry_rm("outbound", *args)
elif verb == "test":
cmd_outbounds_test(*args)
elif verb == "link":
_outbound_link(*args)
else:
usage("proxy outbounds [list|add <tag> <url>|rm <tag>|test [tag...]]")
usage("proxy outbounds [list|add <tag> <url|json|->|rm <tag>|test [tag...]|link <tag>]")
def _outbound_inventory():
@@ -946,6 +968,92 @@ def _outbounds_list():
print(f" {mark}{tag:<34} {rep(tag)}{_s(sources.get(tag) or '-')}")
# --- sharing ------------------------------------------------------------------
#
# The socks start script writes outbound-share.json, root only: the URL each outbound
# was given (none for one declared as JSON, WARP or SSH) and its backend JSON. A URL is
# never rebuilt from JSON. `proxy config` turns the running config into one another
# device can import (proxy_export).
def _read_root_json(path, what):
if not os.path.isfile(path):
die(f"No {what} yet - is proxy-suite-socks running?")
if not readable(path):
die(f"Cannot read {path} - re-run with sudo.")
return read_json(path)
def _share_args(args, flags, noun):
rest = [a for a in args if not a.startswith("-")]
given = [a for a in args if a.startswith("-")]
for flag in given:
if flag not in flags:
die(f"Unknown option: {flag}")
if len(rest) != 1 or len(given) > 1:
usage(f"{noun} link <tag> [{'|'.join(flags)}]")
return rest[0], given[0] if given else ""
def _json_text(value):
return json.dumps(value, indent=2, ensure_ascii=False)
def _outbound_link(*args):
tag, flag = _share_args(args, ("--qr", "--json", "--config"), "proxy outbounds")
if flag == "--config":
_config_export(only=tag)
return
entry = (_read_root_json(_runtime_file("outbound-share.json"), "outbounds").get("outbounds") or {}).get(tag)
if entry is None:
die(f"Unknown outbound: {tag}")
if flag == "--json":
print(_json_text(_proxy_export().portable_outbound(entry.get("outbound") or {})))
elif not entry.get("url"):
die(f"{tag} has no URL (it was not given as one) - use --json.")
else:
_emit(_s(entry["url"]), flag == "--qr")
def _subscription_link(*args):
tag, flag = _share_args(args, ("--qr",), "proxy subs")
url = (_read_root_json(_runtime_file("outbound-share.json"), "subscriptions").get("subscriptions") or {}).get(tag)
if not url:
die(f"Unknown subscription: {tag}")
_emit(_s(url), flag == "--qr")
def _proxy_export():
# Not PYTHONPATH: that would reach every command `apps run` starts.
sys.path.append(env("PROXY_CTL_MODULES", os.path.dirname(os.path.abspath(__file__))))
import proxy_export
return proxy_export
def _config_export(*args, only=None):
proxy_export = _proxy_export()
for arg in args:
if arg != "--raw":
usage("proxy config [--raw]")
cfg = _read_root_json(_runtime_file("config.json"), "running config")
if "--raw" in args:
sidecar = _runtime_file("xray-sidecar.json")
print(_json_text({"sing-box": cfg, "xray": read_json(sidecar)} if os.path.isfile(sidecar) else cfg))
return
if only is not None and only not in _outbound_tags():
die(f"Unknown outbound: {only}")
try:
cfg, warnings = proxy_export.portable(cfg, only)
except ValueError as e:
die(f"Cannot export: {e}")
print(_json_text(cfg))
sys.stdout.flush()
for warning in warnings:
print(f"warning: {warning}", file=sys.stderr)
def cmd_pin(tag="", *_):
if not tag:
if not (os.isatty(0) and os.isatty(1)):
@@ -978,8 +1086,9 @@ def cmd_unpin(*_):
# --- runtime outbounds and subscriptions --------------------------------------
#
# One URL per file in a spool directory the userControl group may write. The
# backend reads them at start, which the reload unit triggers.
# One entry per file in a spool directory the userControl group may write: <tag>.url,
# or for an outbound <tag>.json, one sing-box or XRay outbound as `link --json` prints
# it. The backend reads them at start, which the reload unit triggers.
def _runtime_dir(kind):
@@ -997,7 +1106,29 @@ def _runtime_tags(kind):
names = os.listdir(_runtime_dir(kind))
except OSError:
return []
return sorted(n[: -len(".url")] for n in names if n.endswith(".url"))
exts = (".url", ".json") if kind == "outbound" else (".url",)
return sorted(os.path.splitext(n)[0] for n in names if n.endswith(exts))
def _runtime_path(kind, tag):
"""The file behind a runtime entry, or its .url spelling when there is none."""
for ext in (".url", ".json") if kind == "outbound" else (".url",):
path = os.path.join(_runtime_dir(kind), tag + ext)
if os.path.exists(path):
return path
return os.path.join(_runtime_dir(kind), f"{tag}.url")
def _runtime_json_outbound(text):
"""One outbound object from `text`, the tag left to the entry's name."""
try:
ob = json.loads(text)
except ValueError as e:
die(f"Not a URL, and not valid JSON: {e}")
if not isinstance(ob, dict) or not ("type" in ob or "protocol" in ob):
die('JSON must be one outbound object: sing-box ("type") or XRay ("protocol").')
ob.pop("tag", None)
return json.dumps(ob, ensure_ascii=False)
def _check_runtime_tag(kind, tag):
@@ -1015,12 +1146,20 @@ def _check_runtime_tag(kind, tag):
def _runtime_entry_add(kind, tag="", url="", *_):
what = "<url|json|->" if kind == "outbound" else "<url>"
if not tag or not url:
usage(f"proxy {_runtime_noun(kind)} add <tag> <url>")
usage(f"proxy {_runtime_noun(kind)} add <tag> {what}")
_check_runtime_tag(kind, tag)
if re.search(r"\s", url):
if kind == "outbound" and url == "-":
url = sys.stdin.read()
ext = ".url"
if kind == "outbound" and url.lstrip().startswith("{"):
url, ext = _runtime_json_outbound(url), ".json"
elif re.search(r"\s", url.strip()):
die("A URL cannot contain whitespace.")
path = os.path.join(_runtime_dir(kind), f"{tag}.url")
else:
url = url.strip()
path = os.path.join(_runtime_dir(kind), tag + ext)
old = os.umask(0o027)
try:
with open(path, "w", encoding="utf-8") as f:
@@ -1036,7 +1175,7 @@ def _runtime_entry_add(kind, tag="", url="", *_):
def _runtime_entry_rm(kind, tag="", *_):
if not tag:
usage(f"proxy {_runtime_noun(kind)} rm <tag>")
path = os.path.join(_runtime_dir(kind), f"{tag}.url")
path = _runtime_path(kind, tag)
if not os.path.exists(path):
die(f"No runtime {kind} named '{tag}'. Ones declared in the NixOS configuration are removed there.")
try:
@@ -1059,7 +1198,7 @@ def _subscription_cache(tag):
def _runtime_entry_verify(kind, tag):
"""Only the backend parses the URL, so confirm the entry actually came up."""
"""Only the backend parses the entry, so confirm it actually came up."""
if kind == "outbound":
if tag in _outbound_tags():
print(f"Added outbound: {tag}")
@@ -1135,13 +1274,15 @@ def cmd_subscription(verb="list", *args):
_runtime_entry_add("subscription", *args)
elif verb in ("rm", "remove", "del"):
_runtime_entry_rm("subscription", *args)
elif verb == "link":
_subscription_link(*args)
elif verb == "update":
if not svc_exists("proxy-suite-subscription-update"):
die("The proxy is not enabled in this configuration.")
must("start", "proxy-suite-subscription-update")
print("Subscription update triggered. Follow with: proxy-ctl logs proxy-suite-subscription-update")
else:
usage("proxy subs [list|update|add <tag> <url>|rm <tag>]")
usage("proxy subs [list|update|add <tag> <url>|rm <tag>|link <tag>]")
# --- proxy auto: reachability probe -------------------------------------------
@@ -2212,7 +2353,20 @@ def _inbound_links():
return read_json(path)
def _inbound_link_for(tag, user="", *_):
def _inbound_server_json(tag):
"""The XRay inbound as the server runs it, secrets and all."""
path = os.path.join(os.path.dirname(env("INBOUNDS_LINKS_FILE", "/run/proxy-suite-inbounds/links.json")), "config.json")
if not os.path.isfile(path):
die("No inbound config yet - is proxy-suite-inbounds running?")
if not readable(path):
die(f"Cannot read {path} - re-run with sudo.")
inbound = next((x for x in read_json(path).get("inbounds") or [] if x.get("tag") == tag), None)
if inbound is None:
die(f"Unknown inbound: {tag}")
print(_json_text(inbound))
def _inbound_link_for(tag, user="", *_, field="link"):
matches = [x for x in _inbound_links() if x.get("tag") == tag and (not user or x.get("user") == user)]
if not matches:
die(f"Unknown inbound, or no share link for it: {tag}")
@@ -2222,7 +2376,11 @@ def _inbound_link_for(tag, user="", *_):
for x in matches:
print(f" {_s(x.get('user'))}", file=sys.stderr)
sys.exit(1)
return _s(matches[0].get("link"))
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]
def _human_bytes(b):
@@ -2326,10 +2484,15 @@ def cmd_inbounds(verb="list", *args):
for x in _inbound_links():
print(row.format(*(_s(x.get(k)) for k in ("tag", "user", "type", "port")), state))
elif verb in ("link", "qr"):
rest = [a for a in args if a != "--qr"]
rest = [a for a in args if not a.startswith("--")]
if not rest:
usage("inbounds link <tag> [user] [--qr]")
_emit(_inbound_link_for(*rest), verb == "qr" or "--qr" in args)
usage("inbounds link <tag> [user] [--qr|--json|--server-json]")
if "--server-json" in args:
_inbound_server_json(rest[0])
elif "--json" in args:
print(_json_text(_inbound_link_for(*rest, field="outbound")))
else:
_emit(_inbound_link_for(*rest), verb == "qr" or "--qr" in args)
elif verb == "stats":
_inbound_stats(args[0] if args else "7")
elif verb == "sub":
+184
View File
@@ -0,0 +1,184 @@
"""The running backend config, made into a client config another device can import.
Pure functions: a config dict in, (config, warnings) out. What only makes sense on
this host goes: tproxy/tun and probe listeners, routing marks, the Clash API, loopback
hops (the hybrid XRay sidecar, the WARP tunnel, the SSH listener), and rule-sets that
live in local state. Geodata rule-sets are pointed at their upstream downloads.
"""
import copy
import re
LOOPBACK = re.compile(r"^(127\.|::1$|localhost$)")
GROUPS = ("selector", "urltest")
SING_BOX_SYSTEM = ("direct", "block", "dns", *GROUPS)
XRAY_SYSTEM = ("freedom", "blackhole", "dns")
GEODATA_PATH = re.compile(r"/share/sing-box/rule-set/(geosite|geoip)-([^/]+)\.srs$")
# ponytail: guessed from the file name, so wrong for custom geodata packages; take the
# URL from an option if someone ships one.
GEODATA_URL = "https://raw.githubusercontent.com/SagerNet/sing-{kind}/rule-set/{kind}-{name}.srs"
XRAY_SOCKS_PORT = 10808
XRAY_HTTP_PORT = 10809
def _server(ob):
settings = ob.get("settings") or {}
for key in ("vnext", "servers"):
if settings.get(key):
return settings[key][0].get("address", "")
return ob.get("server") or settings.get("address") or ""
def _loopback(ob):
return bool(LOOPBACK.match(str(_server(ob))))
def portable_outbound(ob):
"""One outbound without what ties it to this host: routing marks and interfaces."""
ob = copy.deepcopy(ob)
ob.pop("routing_mark", None)
ob.pop("bind_interface", None)
sockopt = (ob.get("streamSettings") or {}).get("sockopt") or {}
sockopt.pop("mark", None)
sockopt.pop("interface", None)
return ob
def _backend_tag(tags, only, prefix=""):
"""The tag `only` has in the backend: as given, prefixed by the XRay wrapper, or the
outbound collapsed into "proxy"."""
for tag in (only, prefix + only, "proxy"):
if tag in tags:
return tag
raise ValueError(f"no outbound {only} in the running config")
def portable_sing_box(cfg, only=None):
cfg = copy.deepcopy(cfg)
warnings = []
obs = cfg.get("outbounds") or []
exits = [o for o in obs if o.get("type") not in SING_BOX_SYSTEM]
keep = _backend_tag({o["tag"] for o in exits}, only) if only else None
dropped = set()
for o in exits:
if keep and o["tag"] != keep:
dropped.add(o["tag"])
elif _loopback(o):
dropped.add(o["tag"])
warnings.append(f"left out {o['tag']}: this host reaches it through a local hop")
dropped |= {o["tag"] for o in obs if o["tag"].startswith("proxy-suite-test")}
obs = [portable_outbound(o) for o in obs if o["tag"] not in dropped]
for o in obs:
if o.get("type") in GROUPS:
o["outbounds"] = [t for t in o.get("outbounds") or [] if t not in dropped]
if o.get("default") in dropped:
o.pop("default")
tags = {o["tag"] for o in obs}
if not any(o.get("type") not in SING_BOX_SYSTEM for o in obs):
raise ValueError("no outbound here can be used from another device")
target = "proxy" if "proxy" in tags else keep or next(o["tag"] for o in obs if o.get("type") not in SING_BOX_SYSTEM)
# A group left empty (every exit it had was dropped) routes through what remains.
for o in obs:
if o.get("type") in GROUPS and not o["outbounds"]:
o["outbounds"] = [target if target != o["tag"] else "direct"]
cfg["outbounds"] = obs
inbound = next((i for i in cfg.get("inbounds") or [] if i.get("tag") == "mixed-in"), {})
cfg["inbounds"] = [{"type": "mixed", "tag": "mixed-in", "listen": "127.0.0.1", "listen_port": inbound.get("listen_port", 2080)}]
route = cfg.setdefault("route", {})
rule_sets, gone = [], set()
for rs in route.get("rule_set") or []:
match = GEODATA_PATH.search(rs.get("path") or "") if rs.get("type") == "local" else None
if match:
kind, name = match.groups()
rule_sets.append({"type": "remote", "tag": rs["tag"], "format": "binary",
"url": GEODATA_URL.format(kind=kind, name=name), "download_detour": target})
elif rs.get("type") == "local":
gone.add(rs["tag"])
else:
rule_sets.append(rs)
route["rule_set"] = rule_sets
def usable(rule):
return not set(rule.get("inbound") or []) - {"mixed-in"} and not set(rule.get("rule_set") or []) & gone
def retarget(rule, key):
if rule.get(key) in dropped:
rule[key] = target
return rule
route["rules"] = [retarget(r, "outbound") for r in route.get("rules") or [] if usable(r)]
if route.get("final") in dropped:
route["final"] = target
route.pop("default_mark", None)
route.pop("default_interface", None)
route["auto_detect_interface"] = True
dns = cfg.get("dns") or {}
for server in dns.get("servers") or []:
retarget(server, "detour")
if "rules" in dns:
dns["rules"] = [r for r in dns["rules"] if usable(r)]
experimental = cfg.get("experimental") or {}
experimental.pop("clash_api", None)
if not experimental:
cfg.pop("experimental", None)
return cfg, warnings
def portable_xray(cfg, only=None):
cfg = copy.deepcopy(cfg)
warnings = []
obs = cfg.get("outbounds") or []
exits = [o for o in obs if o.get("protocol") not in XRAY_SYSTEM]
keep = _backend_tag({o["tag"] for o in exits}, only, "proxy-suite-ob-") if only else None
dropped = set()
for o in exits:
if keep and o["tag"] != keep:
dropped.add(o["tag"])
elif _loopback(o):
dropped.add(o["tag"])
warnings.append(f"left out {o['tag']}: this host reaches it through a local hop")
obs = [portable_outbound(o) for o in obs if o["tag"] not in dropped]
remaining = [o["tag"] for o in obs if o.get("protocol") not in XRAY_SYSTEM]
if not remaining:
raise ValueError("no outbound here can be used from another device")
cfg["outbounds"] = obs
mixed = next((i for i in cfg.get("inbounds") or [] if i.get("tag") == "mixed-in"), {})
sniffing = mixed.get("sniffing") or {"enabled": True, "destOverride": ["http", "tls", "quic"]}
cfg["inbounds"] = [
{"tag": "mixed-in", "protocol": "socks", "listen": "127.0.0.1", "port": XRAY_SOCKS_PORT,
"settings": {"auth": "noauth", "udp": True}, "sniffing": sniffing},
{"tag": "http-in", "protocol": "http", "listen": "127.0.0.1", "port": XRAY_HTTP_PORT, "sniffing": sniffing},
]
routing = cfg.setdefault("routing", {})
balanced = bool(routing.get("balancers"))
rules = []
for rule in routing.get("rules") or []:
if set(rule.get("inboundTag") or []) - {"mixed-in"}:
continue
if rule.get("outboundTag") in dropped:
if balanced:
rule.pop("outboundTag")
rule["balancerTag"] = "proxy"
else:
rule["outboundTag"] = keep or remaining[0]
rules.append(rule)
routing["rules"] = rules
for key in ("api", "stats", "policy"):
cfg.pop(key, None)
return cfg, warnings
def portable(cfg, only=None):
"""sing-box or XRay, by the config's own shape."""
if any("protocol" in o for o in cfg.get("outbounds") or []):
return portable_xray(cfg, only)
return portable_sing_box(cfg, only)
+13 -1
View File
@@ -352,8 +352,15 @@ TABS = [
Action("u", "unpin: let the selection pick", lambda r, *_: ["proxy", "unpin"], when=lambda r: r["mark"] == "★"),
Action("t", "test it", lambda r, *_: ["proxy", "outbounds", "test", r["tag"]], when=ROW, mode="dialog"),
Action("T", "test all", lambda r, *_: ["proxy", "outbounds", "test"], mode="dialog"),
Action("n", "add a runtime outbound…", lambda r, t, _: ["proxy", "outbounds", "add", *t.split(None, 1)], prompt="<tag> <url>"),
Action("n", "add a runtime outbound…", lambda r, t, _: ["proxy", "outbounds", "add", *t.split(None, 1)], prompt="<tag> <url or JSON>"),
Action("d", "remove it", lambda r, *_: ["proxy", "outbounds", "rm", r["tag"]], when=lambda r: r["runtime"], confirm=True),
# Credentials: proxy-ctl refuses these without root, and the dialog says so.
Action("l", "its URL", lambda r, *_: ["proxy", "outbounds", "link", r["tag"]], when=ROW, mode="dialog"),
Action("c", "copy its URL", lambda r, *_: ["proxy", "outbounds", "link", r["tag"]], when=ROW, mode="copy"),
Action("Q", "its URL as QR", lambda r, *_: ["proxy", "outbounds", "link", r["tag"], "--qr"], when=ROW, mode="dialog"),
Action("J", "its JSON", lambda r, *_: ["proxy", "outbounds", "link", r["tag"], "--json"], when=ROW, mode="dialog"),
Action("F", "client config for it alone", lambda r, *_: ["proxy", "outbounds", "link", r["tag"], "--config"], when=ROW, mode="dialog"),
Action("X", "client config with every outbound and rule", lambda r, *_: ["proxy", "config"], mode="dialog"),
],
),
Tab(
@@ -368,6 +375,9 @@ TABS = [
Action("l", "follow the update's logs", lambda r, *_: ["logs", "proxy-suite-subscription-update"], mode="suspend"),
Action("n", "add a runtime subscription…", lambda r, t, _: ["proxy", "subs", "add", *t.split(None, 1)], prompt="<tag> <url>"),
Action("d", "remove it", lambda r, *_: ["proxy", "subs", "rm", r["tag"]], when=lambda r: r["source"] == "runtime", confirm=True),
Action("k", "its URL", lambda r, *_: ["proxy", "subs", "link", r["tag"]], when=ROW, mode="dialog"),
Action("y", "copy its URL", lambda r, *_: ["proxy", "subs", "link", r["tag"]], when=ROW, mode="copy"),
Action("Q", "its URL as QR", lambda r, *_: ["proxy", "subs", "link", r["tag"], "--qr"], when=ROW, mode="dialog"),
],
),
Tab(
@@ -419,6 +429,8 @@ 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("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"),
],
),
+55
View File
@@ -540,6 +540,61 @@ class OutboundTestTest(EnvTest):
self.assertIn("enable userControl, or run with sudo", err)
class ShareTest(EnvTest):
def setUp(self):
super().setUp()
os.environ["OUTBOUND_INVENTORY_FILE"] = self.write("outbounds.json", {"tags": ["vps", "warp"], "sources": {}})
os.environ["INBOUNDS_ENABLED"] = "1"
os.environ["INBOUNDS_LINKS_FILE"] = self.write(
"inbounds/links.json", [{"tag": "in", "user": "u", "link": "vless://x@h:443", "outbound": {"type": "vless"}}]
)
self.write("inbounds/config.json", {"inbounds": [{"tag": "in", "protocol": "vless"}]})
self.share = self.write(
"outbound-share.json",
{
"outbounds": {
"vps": {"url": "vless://x@vps.test:443", "outbound": {"type": "vless", "tag": "vps", "server": "vps.test"}},
"warp": {"url": None, "outbound": {"type": "socks", "tag": "warp", "server": "127.0.0.1"}},
},
"subscriptions": {"community": "https://sub.test/t"},
},
)
self.write(
"config.json",
{"outbounds": [{"type": "vless", "tag": "vps", "server": "vps.test"}, {"type": "socks", "tag": "warp", "server": "127.0.0.1"},
{"type": "direct", "tag": "direct"}], "route": {"final": "vps"}},
)
def test_outbound_link(self):
self.assertEqual(ok(ctl.cmd_outbounds, "link", "vps"), "vless://x@vps.test:443\n")
self.assertEqual(json.loads(ok(ctl.cmd_outbounds, "link", "warp", "--json"))["server"], "127.0.0.1")
status, _, err = run(ctl.cmd_outbounds, "link", "warp")
self.assertNotEqual(status, 0)
self.assertIn("use --json", err)
self.assertNotEqual(run(ctl.cmd_outbounds, "link", "nope")[0], 0)
self.assertNotEqual(run(ctl.cmd_outbounds, "link", "vps", "--bogus")[0], 0)
self.assertEqual(ok(ctl.cmd_subscription, "link", "community"), "https://sub.test/t\n")
def test_config(self):
status, out, err = run(ctl.cmd_proxy, "config")
self.assertEqual(status, 0, err)
self.assertEqual([o["tag"] for o in json.loads(out)["outbounds"]], ["vps", "direct"])
self.assertIn("left out warp", err)
self.assertIn('"tag": "warp"', ok(ctl.cmd_proxy, "config", "--raw"))
self.assertNotEqual(run(ctl.cmd_outbounds, "link", "nope", "--config")[0], 0)
def test_inbound_json(self):
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")
@unittest.skipIf(os.geteuid() == 0, "root reads anything")
def test_unreadable(self):
os.chmod(self.share, 0)
status, _, err = run(ctl.cmd_outbounds, "link", "vps")
self.assertNotEqual(status, 0)
self.assertIn("re-run with sudo", err)
class BadExitTest(EnvTest):
def test_shown_from_state(self):
os.environ.update(
+169
View File
@@ -0,0 +1,169 @@
#!/usr/bin/env python3
"""proxy_export: host-only parts leave, the routing stays, and sing-box accepts the result."""
import json
import os
import subprocess
import tempfile
import unittest
import proxy_export as export
GEOSITE = "/nix/store/x-sing-geosite/share/sing-box/rule-set/geosite-google.srs"
def sing_box_config():
"""The socks unit's config on hybrid sing-box, with autoProxy, the test listener and local auth."""
return {
"log": {"level": "warn"},
"dns": {
"servers": [
{"tag": "remote", "type": "tls", "server": "1.1.1.1", "server_port": 853, "detour": "proxy"},
{"tag": "local", "type": "udp", "server": "77.88.8.8", "server_port": 53},
],
"rules": [{"rule_set": ["geosite-google"], "server": "remote"}],
"final": "remote",
},
"inbounds": [
{"type": "direct", "tag": "xray-dns-in", "listen": "127.0.0.1", "listen_port": 5353},
{"type": "mixed", "tag": "mixed-in", "listen": "0.0.0.0", "listen_port": 1080, "users": [{"username": "u", "password": "p"}]},
{"type": "tproxy", "tag": "tproxy-in", "listen": "127.0.0.1", "listen_port": 7894},
{"type": "mixed", "tag": "probe-in-1", "listen": "127.0.0.1", "listen_port": 20001},
],
"outbounds": [
{"type": "vless", "tag": "vps", "server": "vps.example.com", "server_port": 443, "uuid": "a4a0b7a8-7b35-4bb4-9a9b-2b7b33e9b7a1", "routing_mark": 1},
{"type": "trojan", "tag": "sub-de", "server": "de.example.com", "server_port": 443, "password": "x", "routing_mark": 1},
{"type": "socks", "tag": "xhttp-vps", "server": "127.0.0.1", "server_port": 30001},
{"type": "socks", "tag": "warp", "server": "127.0.0.1", "server_port": 40000},
{"type": "urltest", "tag": "proxy", "outbounds": ["vps", "sub-de", "xhttp-vps", "warp"]},
{"type": "selector", "tag": "proxy-suite-test", "outbounds": ["vps", "sub-de"]},
{"type": "direct", "tag": "direct", "routing_mark": 1},
{"type": "block", "tag": "block"},
],
"route": {
"default_domain_resolver": "local",
"rule_set": [
{"type": "local", "tag": "geosite-google", "format": "binary", "path": GEOSITE},
{"type": "local", "tag": "autoproxy-1", "format": "source", "path": "/var/lib/proxy-suite/autoproxy/rs-1.json"},
],
"rules": [
{"inbound": ["probe-in-1"], "outbound": "sub-de"},
{"inbound": ["xray-dns-in"], "network": ["tcp", "udp"], "action": "hijack-dns"},
{"domain_suffix": ["x.test"], "outbound": "xhttp-vps"},
{"rule_set": ["geosite-google"], "outbound": "proxy"},
{"rule_set": ["autoproxy-1"], "outbound": "sub-de"},
{"inbound": ["mixed-in"], "ip_is_private": True, "action": "reject"},
],
"final": "direct",
},
"experimental": {"clash_api": {"external_controller": "127.0.0.1:9090"}},
}
def xray_config():
return {
"log": {"loglevel": "warning"},
"inbounds": [
{"tag": "mixed-in", "protocol": "socks", "listen": "0.0.0.0", "port": 1080, "settings": {"auth": "password", "accounts": [{"user": "u", "pass": "p"}]}},
{"tag": "tproxy-in", "protocol": "tunnel", "listen": "127.0.0.1", "port": 7894},
],
"outbounds": [
{"protocol": "vless", "tag": "proxy-suite-ob-vps", "settings": {"vnext": [{"address": "vps.example.com", "port": 443}]}, "streamSettings": {"sockopt": {"mark": 1}}},
{"protocol": "vless", "tag": "proxy-suite-ob-de", "settings": {"vnext": [{"address": "de.example.com", "port": 443}]}},
{"protocol": "socks", "tag": "proxy-suite-ob-warp", "settings": {"address": "127.0.0.1", "port": 40000}},
{"protocol": "freedom", "tag": "direct", "streamSettings": {"sockopt": {"mark": 1}}},
{"protocol": "blackhole", "tag": "block"},
],
"routing": {
"rules": [
{"type": "field", "inboundTag": ["tproxy-in"], "outboundTag": "direct"},
{"type": "field", "domain": ["geosite:google"], "outboundTag": "proxy-suite-ob-warp"},
{"type": "field", "network": "tcp,udp", "balancerTag": "proxy"},
],
"balancers": [{"tag": "proxy", "selector": ["proxy-suite-ob-"], "strategy": {"type": "leastPing"}}],
},
}
class SingBoxTest(unittest.TestCase):
def test_host_parts_leave(self):
cfg, warnings = export.portable(sing_box_config())
self.assertEqual(cfg["inbounds"], [{"type": "mixed", "tag": "mixed-in", "listen": "127.0.0.1", "listen_port": 1080}])
tags = [o["tag"] for o in cfg["outbounds"]]
self.assertEqual(tags, ["vps", "sub-de", "proxy", "direct", "block"])
self.assertEqual(cfg["outbounds"][2]["outbounds"], ["vps", "sub-de"])
self.assertFalse(any("routing_mark" in o for o in cfg["outbounds"]))
self.assertEqual(sorted(warnings), ["left out warp: this host reaches it through a local hop", "left out xhttp-vps: this host reaches it through a local hop"])
self.assertNotIn("experimental", cfg)
self.assertTrue(cfg["route"]["auto_detect_interface"])
def test_routing_stays(self):
route = export.portable(sing_box_config())[0]["route"]
self.assertEqual(
route["rules"],
[
{"domain_suffix": ["x.test"], "outbound": "proxy"},
{"rule_set": ["geosite-google"], "outbound": "proxy"},
{"inbound": ["mixed-in"], "ip_is_private": True, "action": "reject"},
],
)
self.assertEqual(
route["rule_set"],
[{"type": "remote", "tag": "geosite-google", "format": "binary", "download_detour": "proxy",
"url": "https://raw.githubusercontent.com/SagerNet/sing-geosite/rule-set/geosite-google.srs"}],
)
def test_one_server(self):
cfg, _ = export.portable(sing_box_config(), only="sub-de")
self.assertEqual([o["tag"] for o in cfg["outbounds"]], ["sub-de", "proxy", "direct", "block"])
self.assertEqual(cfg["outbounds"][1]["outbounds"], ["sub-de"])
with self.assertRaises(ValueError):
export.portable(sing_box_config(), only="nope")
def test_collapsed_proxy(self):
base = sing_box_config()
base["outbounds"] = [{**base["outbounds"][0], "tag": "proxy"}, base["outbounds"][1], *base["outbounds"][6:]]
base["route"]["rules"] = []
cfg, _ = export.portable(base, only="vps")
self.assertEqual([o["tag"] for o in cfg["outbounds"]], ["proxy", "direct", "block"])
def test_nothing_portable(self):
base = sing_box_config()
base["outbounds"] = base["outbounds"][2:4] + base["outbounds"][6:]
with self.assertRaises(ValueError):
export.portable(base)
@unittest.skipUnless(os.environ.get("SING_BOX"), "SING_BOX not set")
def test_sing_box_accepts_it(self):
cfg, _ = export.portable(sing_box_config())
# Remote rule-sets are fetched at start, not by check.
with tempfile.NamedTemporaryFile("w", suffix=".json") as f:
json.dump(cfg, f)
f.flush()
result = subprocess.run([os.environ["SING_BOX"], "check", "-c", f.name], capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stderr)
class XrayTest(unittest.TestCase):
def test_host_parts_leave(self):
cfg, warnings = export.portable(xray_config())
self.assertEqual([i["tag"] for i in cfg["inbounds"]], ["mixed-in", "http-in"])
self.assertEqual(cfg["inbounds"][0]["settings"], {"auth": "noauth", "udp": True})
self.assertEqual([o["tag"] for o in cfg["outbounds"]], ["proxy-suite-ob-vps", "proxy-suite-ob-de", "direct", "block"])
self.assertEqual(cfg["outbounds"][0]["streamSettings"]["sockopt"], {})
self.assertEqual(warnings, ["left out proxy-suite-ob-warp: this host reaches it through a local hop"])
self.assertEqual(
cfg["routing"]["rules"],
[
{"type": "field", "domain": ["geosite:google"], "balancerTag": "proxy"},
{"type": "field", "network": "tcp,udp", "balancerTag": "proxy"},
],
)
def test_one_server(self):
cfg, _ = export.portable(xray_config(), only="de")
self.assertEqual([o["tag"] for o in cfg["outbounds"]], ["proxy-suite-ob-de", "direct", "block"])
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -89,7 +89,7 @@ class ModelTest(unittest.TestCase):
rows, summary = model.load_tab(tab, {})
self.assertEqual([(r["tag"], r["mark"]) for r in rows], [("a", "▸"), ("b", "★")])
self.assertIn("Pinned: b", summary)
self.assertEqual([a.key for a in model.applicable(tab, rows[1])], ["u", "t", "T", "n"])
self.assertEqual([a.key for a in model.applicable(tab, rows[1])], ["u", "t", "T", "n", "l", "c", "Q", "J", "F", "X"])
broken = model.Tab("x", "X", model.ROW, [], lambda _: ctl.die("backend gone"))
self.assertEqual(model.load_tab(broken, {}), ([], "✗ backend gone"))
+9 -2
View File
@@ -20,6 +20,9 @@ def main() -> None:
)
ap.add_argument("--backend", choices=["sing-box", "xray", "hybrid"], default="sing-box")
ap.add_argument("--routing-mark", type=int, default=None, dest="routing_mark")
ap.add_argument(
"--links-out", default=None, dest="links_out", help="Also write {tag: original URI} here, for sharing."
)
args = ap.parse_args()
url = sys.stdin.read().strip()
@@ -34,17 +37,21 @@ def main() -> None:
sys.exit(1)
lines = decode_subscription(raw)
links: dict[str, str] = {}
if args.backend == "hybrid":
outbounds = parse_hybrid_subscription(lines, args.tag_prefix, args.routing_mark)
outbounds = parse_hybrid_subscription(lines, args.tag_prefix, args.routing_mark, links)
has_outbounds = bool(outbounds["singBox"] or outbounds["xray"])
else:
outbounds = parse_subscription(lines, args.tag_prefix, args.routing_mark, args.backend)
outbounds = parse_subscription(lines, args.tag_prefix, args.routing_mark, args.backend, links)
has_outbounds = bool(outbounds)
if not has_outbounds:
print("error: subscription contained no parseable proxy URIs", file=sys.stderr)
sys.exit(1)
if args.links_out:
with open(args.links_out, "w", encoding="utf-8") as handle:
json.dump(links, handle)
print(json.dumps(outbounds))
+14
View File
@@ -13,6 +13,8 @@ import hashlib
import json
import urllib.parse
from proxy_parsing import build_outbound
UUID_TYPES = ("vless", "vmess")
PASSWORD_TYPES = ("trojan", "shadowsocks", "socks", "http")
UDP_TYPES = ("shadowsocks", "socks")
@@ -313,6 +315,17 @@ def build_listener(listener: dict, server_address: str, share_links: bool) -> di
return {"tag": tag, "type": listener["type"], "port": _share_port(listener), "inbound": inbound, "links": links}
def client_outbound(link: str, tag: str) -> dict | None:
"""What a client dials for this link: sing-box JSON, or XRay's where sing-box has
no such transport (XHTTP, ECH). None when neither parser reads the link (socks://)."""
for backend in ("sing-box", "xray"):
try:
return build_outbound(link, tag, backend=backend)
except ValueError:
pass
return None
def subscription_token(name: str, secrets: list[str]) -> str:
"""Name of a user's subscription file, and so the secret part of its URL.
@@ -348,6 +361,7 @@ def build_inbounds(spec: dict, server_address: str) -> dict:
"type": rendered.get("type", ""),
"port": rendered.get("port", 0),
"link": link,
"outbound": client_outbound(link, rendered["tag"]),
}
)
entry = by_user.setdefault(name, {"links": [], "secrets": []})
+13 -2
View File
@@ -276,8 +276,13 @@ def _subscription_tag(line: str, tag_prefix: str, index: int, seen_tags: set[str
def parse_subscription(
lines: list[str], tag_prefix: str, routing_mark: int | None, backend: str = "sing-box"
lines: list[str],
tag_prefix: str,
routing_mark: int | None,
backend: str = "sing-box",
links: dict[str, str] | None = None,
) -> list[dict]:
"""links, when given, collects tag -> the line it came from, to share it back."""
outbounds = []
seen_tags: set[str] = set()
@@ -296,12 +301,14 @@ def parse_subscription(
seen_tags.add(tag)
outbounds.append(outbound)
if links is not None:
links[tag] = line
return outbounds
def parse_hybrid_subscription(
lines: list[str], tag_prefix: str, routing_mark: int | None = None
lines: list[str], tag_prefix: str, routing_mark: int | None = None, links: dict[str, str] | None = None
) -> dict[str, list[dict]]:
outbounds: dict[str, list[dict]] = {"singBox": [], "xray": []}
seen_tags: set[str] = set()
@@ -317,6 +324,8 @@ def parse_hybrid_subscription(
outbound = build_outbound(line, tag, routing_mark, "sing-box")
outbounds["singBox"].append(outbound)
seen_tags.add(tag)
if links is not None:
links[tag] = line
continue
except Exception as sing_box_exc:
sing_box_error = sing_box_exc
@@ -333,5 +342,7 @@ def parse_hybrid_subscription(
outbounds["xray"].append(outbound)
seen_tags.add(tag)
if links is not None:
links[tag] = line
return outbounds
+11 -1
View File
@@ -7,7 +7,7 @@ import tempfile
import unittest
import urllib.parse
from proxy_inbound import build_inbounds, build_share_link, render_xray_inbound, subscription_token
from proxy_inbound import build_inbounds, build_share_link, client_outbound, render_xray_inbound, subscription_token
from proxy_parsing import build_outbound
@@ -357,6 +357,16 @@ class BuildInboundsTests(unittest.TestCase):
self.assertEqual([ib["tag"] for ib in result["inbounds"]], ["a", "b"])
self.assertEqual([entry["tag"] for entry in result["links"]], ["a", "b"])
self.assertEqual(result["links"][1]["port"], 8443)
self.assertEqual(result["links"][0]["outbound"]["type"], "vless")
# v2rayN's socks:// is a link, but not one the outbound parsers take.
self.assertIsNone(result["links"][1]["outbound"])
def test_client_outbound_falls_back_to_xray(self):
link = build_share_link(
listener(transport={"type": "xhttp", "path": "/p", "host": None, "mode": "auto", "serviceName": ""}),
"vpn.example.com",
)
self.assertEqual(client_outbound(link, "x")["protocol"], "vless")
def test_xhttp_mode_reaches_the_inbound_and_the_link(self):
spec = listener(
+9
View File
@@ -61,6 +61,15 @@ class FetchSubscriptionTests(unittest.TestCase):
obs = run_fetcher(payload, tag_prefix="mysub")
self.assertTrue(obs[0]["tag"].startswith("mysub-"))
def test_links_map_tags_to_lines(self):
lines = [VLESS_URI, INVALID_URI, VLESS_XHTTP_URI]
links: dict[str, str] = {}
obs = parse_subscription(lines, "sub", None, "sing-box", links)
self.assertEqual(links, {obs[0]["tag"]: VLESS_URI})
links = {}
hybrid = parse_hybrid_subscription(lines, "sub", None, links)
self.assertEqual(links, {hybrid["singBox"][0]["tag"]: VLESS_URI, hybrid["xray"][0]["tag"]: VLESS_XHTTP_URI})
def test_remark_used_in_tag(self):
uri_with_remark = VLESS_URI + "#My Server DE"
payload = _make_b64_payload(uri_with_remark)