feat(wl): runtime auth

This commit is contained in:
fufsob committed 2026-09-25 04:57:30 +00:00
1 parent f3e9140f62
commit ba5f960b2e
10 files changed
+222 -34

No files matched your search

+3
View File
@@ -204,6 +204,9 @@ Secrets and changes need root, or the userControl group.
tg [status|on|off] Telegram WebSocket proxy
wl [list] whitelist-bypass creators and joiners
wl link <creator> [--qr] the call link its joiner takes
wl auth <creator> [file|-] replace its login: cookies, or asked (DION, Bitrix)
wl join <joiner> <link|-> the call it joins, over its linkFile
wl new <creator> drop its call for a new one
wl on|off|toggle|restart [name] one creator or joiner, or all of them
apps [list] per-app routing profiles
+2 -1
View File
@@ -56,9 +56,10 @@ What userControl\.group may do; empty allows every scope\.
- “autoProxy”: read what autoProxy learned, and ` proxy auto learn|forget|relearn|clear `\.
- “zapret”: edit zapret2’s learned hosts, and ` zapret cutoff probe `\.
- “stats”: ` inbounds stats `\.
- “whitelistBypass”: the whitelist-bypass creators and joiners: ` wl on|off|toggle|restart `, their calls (` wl link `), and their logins and links (` wl auth|join|new `)\.
*Type:*
list of (one of “services”, “perApp”, “routing”, “outbounds”, “secrets”, “autoProxy”, “zapret”, “stats”)
list of (one of “services”, “perApp”, “routing”, “outbounds”, “secrets”, “autoProxy”, “zapret”, “stats”, “whitelistBypass”)
*Default:*
+20 -5
View File
@@ -83,11 +83,18 @@ attribute set of (submodule)
Runtime path to the platform’s cookies, as the upstream desktop Creator exports them\.
Copied into the state directory on first start only: DION and Bitrix rotate their
refresh token into that copy, and a stale one would kill the session\. Delete
` <stateDir>/whitelist-bypass/<name>.cookies.json ` to take a new export\.
refresh token into that copy, and a stale one would kill the session\.
` proxy-ctl wl auth <name> ` replaces that copy at runtime, with a new export or, for
DION and Bitrix, an email and password\. Null leaves the creator off until then\.
*Type:*
string
null or string
*Default:*
```nix
null
```
*Example:*
@@ -100,7 +107,7 @@ string
Runtime path to the call to rejoin\. Null rejoins the last call written to
` <stateDir>/whitelist-bypass/<name>.link `, and creates one on first start: the link
stays the same across restarts, so the joiner needs it only once\.
stays the same across restarts, so the joiner needs it only once\. ` proxy-ctl wl new <name> ` drops it for a new call, when the platform has closed the old one\.
*Type:*
null or string
@@ -195,9 +202,17 @@ attribute set of (submodule)
Runtime path to the call link the creator printed (or wrote to its state directory):
a WB Stream room id, a Telemost link, a DION event slug or a Bitrix conference link\.
` proxy-ctl wl join <name> <link> ` sets one at runtime, which wins over this\. Null
leaves the joiner off until then\.
*Type:*
string
null or string
*Default:*
```nix
null
```
*Example:*
@@ -24,6 +24,7 @@ in
"autoProxy"
"zapret"
"stats"
"whitelistBypass"
]
);
default = [ ];
@@ -37,6 +38,7 @@ in
- "autoProxy": read what autoProxy learned, and `proxy auto learn|forget|relearn|clear`.
- "zapret": edit zapret2's learned hosts, and `zapret cutoff probe`.
- "stats": `inbounds stats`.
- "whitelistBypass": the whitelist-bypass creators and joiners: `wl on|off|toggle|restart`, their calls (`wl link`), and their logins and links (`wl auth|join|new`).
'';
example = [
"services"
@@ -17,10 +17,13 @@ let
};
linkFile = mkOption {
type = types.str;
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to the call link the creator printed (or wrote to its state directory):
a WB Stream room id, a Telemost link, a DION event slug or a Bitrix conference link.
`proxy-ctl wl join <name> <link>` sets one at runtime, which wins over this. Null
leaves the joiner off until then.
'';
example = "/run/secrets/whitelist-bypass-link";
};
@@ -45,12 +48,14 @@ let
};
cookiesFile = mkOption {
type = types.str;
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to the platform's cookies, as the upstream desktop Creator exports them.
Copied into the state directory on first start only: DION and Bitrix rotate their
refresh token into that copy, and a stale one would kill the session. Delete
`<stateDir>/whitelist-bypass/<name>.cookies.json` to take a new export.
refresh token into that copy, and a stale one would kill the session.
`proxy-ctl wl auth <name>` replaces that copy at runtime, with a new export or, for
DION and Bitrix, an email and password. Null leaves the creator off until then.
'';
example = "/run/secrets/whitelist-bypass-cookies-wbstream.json";
};
@@ -61,7 +66,8 @@ let
description = ''
Runtime path to the call to rejoin. Null rejoins the last call written to
`<stateDir>/whitelist-bypass/<name>.link`, and creates one on first start: the link
stays the same across restarts, so the joiner needs it only once.
stays the same across restarts, so the joiner needs it only once. `proxy-ctl wl new
<name>` drops it for a new call, when the platform has closed the old one.
'';
example = "/run/secrets/whitelist-bypass-link";
};
+2
View File
@@ -80,6 +80,8 @@ in
inherit name;
inherit (c) platform;
role = "creator";
# Set in the configuration: `wl new` cannot drop it.
fixedLink = c.linkFile != null;
}) cfg.whitelistBypass.creators
++ lib.mapAttrsToList (name: j: {
inherit name;
+1
View File
@@ -14,6 +14,7 @@ let
"proxy-suite-autoproxy-learn." = "autoProxy";
"proxy-suite-zapret2-cutoff." = "zapret";
"proxy-suite-inbound-stats." = "stats";
"proxy-suite-wb-" = "whitelistBypass";
};
in
{
+41 -15
View File
@@ -9,7 +9,7 @@
let
w = derived.whitelistBypassCfg;
inherit (derived.constants) unprivilegedServiceConfig;
inherit (derived.constants) unprivilegedServiceConfig privileged serviceUser;
inherit (derived.localProxy) auth;
# Every flag that takes the call, joiner and creator alike.
@@ -32,6 +32,18 @@ let
else
null;
# Logins, calls and the links joiners take at runtime (`proxy-ctl wl auth|join|new`); the
# whitelistBypass scope's group writes them too. tmpfiles makes it before any unit has run,
# so a creator or joiner that waits on a file there can be given one.
groupAccess = privileged && derived.userControlAllows "whitelistBypass";
stateDir = "${derived.constants.stateDir}/whitelist-bypass";
stateMode = if groupAccess then "0770" else "0700";
stateGroup = if groupAccess then cfg.userControl.group else serviceUser;
# A runtime file the unit cannot start without, when nothing in the configuration stands in.
waitFor = file: {
unitConfig.ConditionPathExists = "%S/proxy-suite/whitelist-bypass/${file}";
};
# Restart=always must not trip the start limit while the network or the platform is down.
mkUnit = description: serviceConfig: {
inherit description;
@@ -44,22 +56,29 @@ let
// {
Restart = "always";
RestartSec = 5;
StateDirectory = "proxy-suite/whitelist-bypass";
StateDirectoryMode = stateMode;
}
// lib.optionalAttrs groupAccess { Group = stateGroup; }
// serviceConfig;
};
# The link `wl join` gave it wins over linkFile.
mkJoiner =
j:
lib.nameValuePair "proxy-suite-wb-joiner-${j.tag}" (
mkUnit "proxy-suite - whitelist-bypass joiner ${j.tag}" {
ExecStart = pkgs.writeShellScript "proxy-suite-wb-joiner-${j.tag}" ''
set -euo pipefail
link=$(tr -d '[:space:]' < "$CREDENTIALS_DIRECTORY/link")
join="$STATE_DIRECTORY/${j.tag}.join"
${lib.optionalString (j.linkFile != null) ''[ -e "$join" ] || join="$CREDENTIALS_DIRECTORY/link"''}
link=$(tr -d '[:space:]' < "$join")
exec ${w.package}/bin/headless-${j.platform}-joiner \
${joinerLinkFlag.${j.platform}} "$link" --socks-port ${toString j.port}
'';
LoadCredential = [ "link:${j.linkFile}" ];
LoadCredential = lib.optional (j.linkFile != null) "link:${j.linkFile}";
}
// lib.optionalAttrs (j.linkFile == null) (waitFor "${j.tag}.join")
);
mkCreator =
@@ -72,7 +91,9 @@ let
set -euo pipefail
cookies="$STATE_DIRECTORY/${name}.cookies.json"
links="$STATE_DIRECTORY/${name}.link"
[ -e "$cookies" ] || install -m 600 "$CREDENTIALS_DIRECTORY/cookies" "$cookies"
${lib.optionalString (c.cookiesFile != null) ''
[ -e "$cookies" ] || install -m 600 "$CREDENTIALS_DIRECTORY/cookies" "$cookies"
''}
args=(--cookies "$cookies" --write-file "$links" --resources ${c.resources})
${
if c.linkFile != null then
@@ -88,21 +109,26 @@ let
''}
exec ${w.package}/bin/headless-${c.platform}-creator "''${args[@]}"
'';
StateDirectory = "proxy-suite/whitelist-bypass";
StateDirectoryMode = "0700";
LoadCredential = [
"cookies:${c.cookiesFile}"
]
++ lib.optional (c.linkFile != null) "link:${c.linkFile}"
++ lib.optional withProxyAuth "proxy-password:${passwordSource}";
LoadCredential =
lib.optional (c.cookiesFile != null) "cookies:${c.cookiesFile}"
++ lib.optional (c.linkFile != null) "link:${c.linkFile}"
++ lib.optional withProxyAuth "proxy-password:${passwordSource}";
};
in
lib.nameValuePair "proxy-suite-wb-creator-${name}" (
unit // lib.optionalAttrs viaProxy { after = unit.after ++ [ "proxy-suite-socks.service" ]; }
unit
// lib.optionalAttrs viaProxy { after = unit.after ++ [ "proxy-suite-socks.service" ]; }
# Without a login it has nothing to run on until `proxy-ctl wl auth` writes one.
// lib.optionalAttrs (c.cookiesFile == null) (waitFor "${name}.cookies.json")
);
in
{
services.proxy-suite.internal.services = lib.listToAttrs (
map mkJoiner derived.whitelistBypassJoiners ++ lib.mapAttrsToList mkCreator w.creators
);
services.proxy-suite.internal = {
services = lib.listToAttrs (
map mkJoiner derived.whitelistBypassJoiners ++ lib.mapAttrsToList mkCreator w.creators
);
tmpfiles = [
"d ${stateDir} ${stateMode} ${if privileged then "${serviceUser} ${stateGroup}" else "- -"} -"
];
};
}
+114 -8
View File
@@ -5,6 +5,7 @@ Configuration arrives through the environment the Nix wrapper sets.
import base64
import datetime
import getpass
import http.client
import importlib
import json
@@ -117,6 +118,9 @@ Secrets and changes need root, or the userControl group.
tg [status|on|off] Telegram WebSocket proxy
wl [list] whitelist-bypass creators and joiners
wl link <creator> [--qr] the call link its joiner takes
wl auth <creator> [file|-] replace its login: cookies, or asked (DION, Bitrix)
wl join <joiner> <link|-> the call it joins, over its linkFile
wl new <creator> drop its call for a new one
wl on|off|toggle|restart [name] one creator or joiner, or all of them
apps [list] per-app routing profiles
@@ -626,6 +630,9 @@ COMPLETE = {
"words": {
"list": "creators and joiners and their state",
"link": "the call link a creator's joiner takes",
"auth": "replace a creator's login",
"join": "set the call a joiner joins",
"new": "drop a creator's call for a new one",
"on": "start one, or all",
"off": "stop one, or all",
"toggle": "start it if stopped, stop it if running",
@@ -633,6 +640,9 @@ COMPLETE = {
}
},
"wl link": {"args": lambda: _names(w["name"] for w in _wl() if w["role"] == "creator"), "flags": {"--qr": "print a QR code"}},
"wl auth": {"args": lambda: _names(w["name"] for w in _wl() if w["role"] == "creator")},
"wl join": {"args": lambda: _names(w["name"] for w in _wl() if w["role"] == "joiner")},
"wl new": {"args": lambda: _names(w["name"] for w in _wl() if w["role"] == "creator" and not w.get("fixedLink"))},
**{f"wl {verb}": {"args": lambda: {w["name"]: w["role"] for w in _wl()}} for verb in ("on", "off", "toggle", "restart")},
"apps": {"words": {"list": "per-app routing profiles", "run": "run a command through a profile"}},
"apps run": {"args": lambda: {_s(p["name"]): _s(p.get("route") or "") for p in read_json(env("PER_APP_ROUTING_PROFILES_FILE"))}},
@@ -2868,23 +2878,114 @@ def _wl_unit(w):
return f"proxy-suite-wb-{w['role']}-{w['name']}"
def _wl_path(name, suffix):
return os.path.join(state_dir(), "whitelist-bypass", name + suffix)
def _wl_link(name):
"""The call a creator made and keeps rejoining: the last line it wrote."""
path = os.path.join(state_dir(), "whitelist-bypass", f"{name}.link")
path = _wl_path(name, ".link")
try:
links = [line.strip() for line in lines(read_text(path)) if line.strip()]
except FileNotFoundError:
links = []
except PermissionError:
die(f"Cannot read {path} - re-run with sudo.")
denied(path)
if not links:
die(f"{name} has no call yet: {journal_hint(_wl_unit({'role': 'creator', 'name': name}))}")
return links[-1]
def _wl_input(source, what):
"""The text of source: a file, or - for stdin."""
try:
return sys.stdin.read() if source == "-" else read_text(source)
except OSError as e:
die(f"Cannot read the {what} from {source}: {e.strerror}")
# DION and Bitrix creators log in on their own from these, and save the session back.
WL_PASSWORD_LOGIN = {"dion": ("email", "password"), "bitrix": ("email", "password", "portal")}
def _wl_login(w, source):
"""The creator's login: a cookies export from source (a file or -), or asked for."""
if source:
text = _wl_input(source, "cookies")
try:
json.loads(text)
except ValueError as e:
die(f"Not a cookies export, not valid JSON: {e}")
return text
fields = WL_PASSWORD_LOGIN.get(w["platform"])
if not fields:
die(f"{w['platform']} logs in only in a browser: export its cookies from the desktop Creator, then: proxy-ctl wl auth {w['name']} <file>")
login = {k: getpass.getpass("Password: ") if k == "password" else input(f"{k.capitalize()}: ").strip() for k in fields}
if "portal" in login:
portal = login["portal"].rstrip("/")
login["portal"] = portal if "://" in portal else f"https://{portal}"
return json.dumps(login)
def _wl_write(w, suffix, text):
"""Replaces a file the unit reads from its state directory, and restarts it on it.
The file takes the directory's group, and its owner too when root writes it: the
daemon reads it, and DION and Bitrix creators rotate their tokens into it.
"""
path = _wl_path(w["name"], suffix)
tmp = ""
try:
os.makedirs(os.path.dirname(path), 0o700, exist_ok=True)
st = os.stat(os.path.dirname(path))
fd, tmp = tempfile.mkstemp(prefix=os.path.basename(path) + ".", dir=os.path.dirname(path))
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write(text)
os.chown(tmp, st.st_uid if os.geteuid() == 0 else -1, st.st_gid)
os.chmod(tmp, 0o600 | (st.st_mode & 0o060))
os.replace(tmp, path)
except OSError:
if tmp:
try:
os.unlink(tmp)
except OSError:
pass
denied(path, "write")
must("restart", _wl_unit(w))
def _wl_join(w, source):
link = (_wl_input(source, "link") if source == "-" else source).strip()
if not link or re.search(r"\s", link):
die("A call link is one word: a room id, a slug or a URL.")
_wl_write(w, ".join", f"{link}\n")
def _wl_new(w):
"""Drops the call a creator rejoins: it makes a new one when it starts."""
if w.get("fixedLink"):
die(f"{w['name']} rejoins the call its linkFile sets: change that instead.")
path = _wl_path(w["name"], ".link")
try:
os.unlink(path)
except FileNotFoundError:
pass
except OSError:
denied(path, "remove")
must("restart", _wl_unit(w))
print(f"Its joiner needs the new call: proxy-ctl wl link {w['name']}")
def _wl_one(named, role, shape):
"""The one creator or joiner a verb takes."""
if not named or len(named) > 1 or named[0]["role"] != role:
usage(f"wl {shape}")
return named[0]
def cmd_wl(verb="list", *args):
entries = _wl()
named = [w for w in entries if w["name"] == args[0]] if args else entries
named = [w for w in entries if w["name"] == args[0]] if args else []
if args and not named:
die(f"Unknown whitelist-bypass creator or joiner: {args[0]}")
if verb in ("list", "status"):
@@ -2895,15 +2996,20 @@ def cmd_wl(verb="list", *args):
for w in entries:
print(f" {w['name']:<16} {w['role']:<8} {w['platform']:<10} {svc_state(_wl_unit(w)) or 'unknown'}")
elif verb == "link":
if not args or named[0]["role"] != "creator":
usage("wl link <creator> [--qr]")
_emit(_wl_link(args[0]), "--qr" in args)
_emit(_wl_link(_wl_one(named, "creator", "link <creator> [--qr]")["name"]), "--qr" in args)
elif verb == "auth" and len(args) <= 2:
w = _wl_one(named, "creator", "auth <creator> [file|-]")
_wl_write(w, ".cookies.json", _wl_login(w, args[1] if len(args) > 1 else ""))
elif verb == "join" and len(args) == 2:
_wl_join(_wl_one(named, "joiner", "join <joiner> <link|->"), args[1])
elif verb == "new" and len(args) == 1:
_wl_new(_wl_one(named, "creator", "new <creator>"))
elif verb in ("on", "off", "toggle", "restart"):
for w in named:
for w in named or entries:
action = {"on": "start", "off": "stop", "restart": "restart"}[_flip(_wl_unit(w), verb)]
must(action, _wl_unit(w))
else:
usage("wl [list] | link <creator> [--qr] | on|off|toggle|restart [name]")
usage("wl [list] | link <creator> [--qr] | auth <creator> [file|-] | join <joiner> <link|-> | new <creator> | on|off|toggle|restart [name]")
# --- apps ---------------------------------------------------------------------
+26
View File
@@ -405,6 +405,32 @@ class ServiceManagerTest(EnvTest):
self.assertEqual(ok(ctl.cmd_wl, "link", "phone"), "dion://new\n")
self.assertNotEqual(run(ctl.cmd_wl, "link", "wl")[0], 0) # a joiner has no link to give
self.assertEqual(set(ctl._complete_tree("wl", "link")), {"phone", "--qr"})
# auth: a cookies export, or DION's email and password; either restarts the creator.
# The directory's group bits carry over: the whitelistBypass scope's group shares it.
seen.clear()
os.chmod(os.path.join(self.dir, "whitelist-bypass"), 0o770)
cookies = os.path.join(self.dir, "whitelist-bypass", "phone.cookies.json")
ok(ctl.cmd_wl, "auth", "phone", self.write("export.json", [{"name": "a", "value": "b"}]))
self.assertEqual(json.loads(ctl.read_text(cookies)), [{"name": "a", "value": "b"}])
self.assertEqual(os.stat(cookies).st_mode & 0o777, 0o660)
self.enterContext(mock.patch("builtins.input", lambda prompt: " me@x "))
self.enterContext(mock.patch("getpass.getpass", lambda prompt: "pw"))
ok(ctl.cmd_wl, "auth", "phone")
self.assertEqual(json.loads(ctl.read_text(cookies)), {"email": "me@x", "password": "pw"})
self.assertEqual([argv[1:3] for argv in seen], [["restart", "proxy-suite-wb-creator-phone"]] * 2)
self.assertNotEqual(run(ctl.cmd_wl, "auth", "phone", self.write("bad.json", "{"))[0], 0)
self.assertNotEqual(run(ctl.cmd_wl, "auth", "wl")[0], 0) # a joiner has no login
# join: the call a joiner takes; new: a creator drops its call, unless configured.
seen.clear()
ok(ctl.cmd_wl, "join", "wl", " dion://new ")
self.assertEqual(ctl.read_text(os.path.join(self.dir, "whitelist-bypass", "wl.join")), "dion://new\n")
self.assertNotEqual(run(ctl.cmd_wl, "join", "wl", "a b")[0], 0)
self.assertNotEqual(run(ctl.cmd_wl, "join", "phone", "x")[0], 0) # a creator makes its call
ok(ctl.cmd_wl, "new", "phone")
self.assertFalse(os.path.exists(os.path.join(self.dir, "whitelist-bypass", "phone.link")))
self.assertEqual([argv[1:3] for argv in seen], [["restart", "proxy-suite-wb-joiner-wl"], ["restart", "proxy-suite-wb-creator-phone"]])
os.environ["WL_FILE"] = self.write("wl.json", [{"name": "phone", "role": "creator", "platform": "dion", "fixedLink": True}])
self.assertNotEqual(run(ctl.cmd_wl, "new", "phone")[0], 0)
def test_toggle_completes(self):
for path in ("ssh", "zapret", "proxy", "proxy tun", "tor"):