5 Commits
Author SHA1 Message Date
faumarayandClaude Opus 5.5 ae58bd1f12 windows: a setup program, and an uninstall entry in Settings > Apps
ProxySuite-<version>-windows-x64-setup.exe (NSIS, English and Russian):
it unpacks the release into its temporary folder and runs the release's
own proxy-suite-service.exe install from there, as install.cmd does from
the zip (unpacked straight into Program Files, an upgrade would find its
files in use). It refuses 32-bit Windows and anything before 10 1903, and
offers Windows' OpenSSH Client, unchecked, for the SSH tunnel.

install now writes the entry in Settings > Apps (uninstall.cmd; quietly,
the service's uninstall), and uninstall removes it, with WinDivert's
driver service when it is the suite's own.

The release workflow publishes the setup beside the zip. The app's
icon and GPUI's manifest share one resource (llvm-rc for both); the
build scripts' clones retry, and are kept for the next build.
Tested under Wine: tools/wine-setup-test.sh.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 13:45:09 +03:00
faumarayandClaude Opus 5.5 ae31e499ca windows: the app's whitelist-bypass page, and its icon
A page for whitelist-bypass: on or off; joiners with their state and the
call link to join; creators with theirs, their call link to copy, a new
call, and their login (a cookies export picked from disk, or DION's and
Bitrix's email and password); adding and removing either.

The app carries an icon now (tools/make-icon.py draws it; llvm-rc makes
it the exe's resource 1, where GPUI, Explorer and the Start Menu take it).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 13:21:49 +03:00
faumarayandClaude Opus 5.5 b6e54f963d windows: whitelist-bypass names its files only after plain names
The names were checked only while whitelist-bypass was on, but proxy-ctl
wl names files after them either way: a configuration saved with it off
could name a creator 'C:\...\x' (on Windows a join with an absolute
path replaces the directory) and have the service write or delete a file
of that name as SYSTEM. They are checked on or off now, and every state
file goes through one helper that checks the name again.

Names (of rule sets, groups, profiles, devices, ...) can no longer be
Windows devices either (CON, NUL, COM1, ...): a file named so is the
device.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 13:05:22 +03:00
faumarayandClaude Opus 5.5 610e36a28b windows: whitelist-bypass
Creators and joiners, built from upstream's tag with upstream's patches
(links and passwords from the environment, never argv), run by the
service as whitelist-bypass.nix runs them: joiners while the proxy runs,
as its outbounds, creators while the suite is on, their logins kept in
a working copy they refresh. proxy-ctl wl list|link|auth|join|new|restart
over new API requests (whitelistBypass scope).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 13:01:10 +03:00
faumarayandClaude Opus 5.5 1f4fcf540d windows: the programs carry their C runtime
Statically linked (+crt-static): no vcruntime140.dll, so no Visual C++
Redistributable to install first. LNK4099 (the runtime's own PDBs) ignored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 13:01:10 +03:00
33 changed files with 1596 additions and 46 deletions

No files matched your search

+7 -5
View File
@@ -1,8 +1,8 @@
name: Windows release
# The Windows port (windows/). On a tag windows-v<version> it builds the release zip and
# publishes it as a Gitea release, with the notes in windows/release-notes/<version>.md. Run
# by hand, it only builds: the zip is the run's artifact.
# The Windows port (windows/). On a tag windows-v<version> it builds the setup program and the
# release zip and publishes them as a Gitea release, with the notes in
# windows/release-notes/<version>.md. Run by hand, it only builds: they are the run's artifact.
#
# Two jobs, as upstream's dependency updates: the one that runs fetched code (crates,
# components, wheels, the Nix closure) holds no token that can write. Only the publishing job
@@ -90,7 +90,9 @@ jobs:
set -euo pipefail
version=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)
mkdir -p ../release
cp "dist/ProxySuite-$version-windows-x64.zip" "dist/ProxySuite-$version-windows-x64.zip.sha256" ../release/
for f in "ProxySuite-$version-windows-x64-setup.exe" "ProxySuite-$version-windows-x64.zip"; do
cp "dist/$f" "dist/$f.sha256" ../release/
done
if [ -f "release-notes/$version.md" ]; then cp "release-notes/$version.md" ../release/notes.md; fi
- name: Upload
@@ -150,7 +152,7 @@ jobs:
*) echo "::error::looking up the release for $TAG: HTTP $code: $(cat found.json)"; exit 1 ;;
esac
for f in release/*.zip release/*.sha256; do
for f in release/*.exe release/*.zip release/*.sha256; do
name=$(basename "$f")
for old in $(api "$API/releases/$id/assets" | jq -r --arg n "$name" '.[] | select(.name == $n) | .id'); do
api -X DELETE "$API/releases/$id/assets/$old" >/dev/null
+13
View File
@@ -0,0 +1,13 @@
# The Windows programs carry their C runtime: vcruntime140.dll is not on every Windows (the
# Visual C++ Redistributable brings it), and nothing else should have to be installed first.
# (LNK4099: the static runtime's objects name Microsoft's own PDBs, which are not shipped; it
# is about their debug info only.)
[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static", "-C", "link-arg=/ignore:4099"]
# GPUI's build compiles its manifest with embed-resource, which would take the dev shell's RC
# (MinGW's windres, for the C cross-compiler) and make a COFF object of it; with llvm-rc it makes
# a .res, which the linker merges with the app's icon (crates/ps-gui/build.rs). Two resource
# objects it refuses.
[env]
RC_x86_64_pc_windows_msvc = "llvm-rc"
+22
View File
@@ -5007,6 +5007,7 @@ dependencies = [
"ps-client",
"ps-core",
"ps-ipc",
"rpassword",
"serde_json",
"tokio",
]
@@ -5623,6 +5624,27 @@ dependencies = [
"memchr",
]
[[package]]
name = "rpassword"
version = "7.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2da316a15f47e3d053de9cb2c439650bd8fa4aaeb9365f2e5f27f492ff73c196"
dependencies = [
"libc",
"rtoolbox",
"windows-sys 0.61.2",
]
[[package]]
name = "rtoolbox"
version = "0.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a1efe12a1469752d0e6ff5ebec0b6ef4924cc5c4c71046b0ec730040535819d"
dependencies = [
"libc",
"windows-sys 0.61.2",
]
[[package]]
name = "rust-embed"
version = "8.13.0"
+1
View File
@@ -22,6 +22,7 @@ ipnet = "2"
indexmap = { version = "2", features = ["serde"] }
tokio = { version = "1.54", features = ["rt-multi-thread", "macros", "net", "io-util", "process", "time", "sync", "fs", "signal"] }
clap = { version = "4.6", features = ["derive"] }
rpassword = "7"
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider", "socks", "json", "stream", "http2", "query"] }
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
windows-service = "0.8"
+39 -14
View File
@@ -26,11 +26,12 @@ tray icon) or with `proxy-ctl`, as upstream's is.
| Tor | `tor`: the Tor Project's own Windows build (the Expert Bundle, signed, pinned), with bridges (obfs4, webtunnel, snowflake, meek, conjure) and, with `asOutbound`, an outbound of the proxy |
| AmneziaWG | `amneziaWg` profiles as outbounds, from a `.conf`, an AmneziaVPN `vpn://` link or settings: `"userspace"` (wireproxy-awg, built from upstream's source, AmneziaWG's obfuscation kept, no driver) or `"singBox"` (plain WireGuard). WARP devices take either kind too |
| WARP | `warp` with `asOutbound = "singBox"` or `"userspace"`: each device registered with Cloudflare as wgcf registers (through the local proxy first, then directly, then `generatorUrl`), or a profile given; a sing-box WireGuard endpoint, several grouped as `warp` |
| whitelist-bypass | `whitelistBypass`: [whitelist-bypass](https://github.com/kulikov0/whitelist-bypass)'s headless creators and joiners (WB Stream, Telemost, DION, Bitrix; VK creators), built from upstream's source: a joiner is an outbound of the proxy tunnelled through a video call, a creator the call's free end. `proxy-ctl wl` gives the links and logins |
| SSH tunnel | `sshProxy`: Windows' own OpenSSH as a SOCKS listener (`ssh -D`) for other programs, and, with `asOutbound`, an outbound of the proxy (sing-box's SSH client) |
| TUN | sing-box's TUN (wintun), `proxy-ctl proxy tun on` — **see the caveats** |
| The app | **Proxy Suite** in the Start Menu, and a tray icon from sign-in: the proxy, DPI bypass and Telegram proxy at a glance and a click; outbounds, subscriptions and the routing mode; zapret's presets and sites; tg-ws-proxy's links; the logs; **every option** in its JSON editor, checked by the service before it takes it; the system proxy |
| The app | **Proxy Suite** in the Start Menu, and a tray icon from sign-in: the proxy, DPI bypass and Telegram proxy at a glance and a click; outbounds, subscriptions and the routing mode; zapret's presets and sites; tg-ws-proxy's links; whitelist-bypass's joiners and creators (links, logins); the logs; **every option** in its JSON editor, checked by the service before it takes it; the system proxy |
Not in this release, still to come: AmneziaWG as a system-wide VPN (its driver), Tor's onion service, whitelist-bypass,
Not in this release, still to come: AmneziaWG as a system-wide VPN (its driver), Tor's onion service,
the kill switch, server inbounds, the XRay-only backend, autoProxy, zapret2's extended
detection and z2k strategies. Their options are accepted (they are upstream's), but the
service says, in its status and in the app, that it does not run them yet.
@@ -51,10 +52,12 @@ Needs 64-bit Windows 10 (1903 or later) or 11.
| SSH tunnel | end to end on Linux: an sshd of the test's own, a page through the `ssh -D` listener and through sing-box's SSH outbound, each logging in with the service's copy of the key (`an_ssh_tunnel`) |
| Tor | its Windows `tor.exe` (under Wine) accepts the torrc the service writes, bridges and transports included; on Linux the service runs Tor with it and Tor starts bootstrapping (where Tor's relays are blocked, it needs bridges) |
| AmneziaWG | profiles from `.conf`, `vpn://` links and settings converted exactly as upstream's script converts them (its own encoder's links as test vectors); end to end on Linux: sing-box as a WireGuard server, the service running wireproxy-awg, a page through its listener and through the proxy's outbound (`an_amneziawg_tunnel`) |
| whitelist-bypass | its Windows programs built from upstream's tag with upstream's patches (links and passwords from the environment, never the command line); on Linux the service runs a joiner and a creator with their flags, the link and the login reaching them (`proxy-ctl wl join`, `wl auth`, `wl new`, `wl link`); a real call needs an account on a platform, so none was made |
| WARP | a device registered live with Cloudflare by the service, its profile rendered as a sing-box endpoint and accepted; traffic through it not (this test machine blocks outgoing UDP) |
| zapret's hostlist rules | every preset with sample rules, checked by `winws.exe --dry-run` (a preset without the profile a rule copies is refused, as upstream refuses it) |
| The app | every page against the service running on Linux, in a window on a virtual display (Xvfb, Mesa's software Vulkan), clicked and typed into by a script, screenshots looked at, and the service's configuration checked after each change (`tools/gui-shot.sh`) |
| The app's Windows build | built by the release workflow; its shaders by Microsoft's own `fxc.exe` (under Wine) with GPUI's own arguments; under Wine it starts and gets as far as drawing text |
| The setup program | under Wine (`tools/wine-setup-test.sh`): a silent install puts every file of the release into Program Files and the entry into Settings → Apps, the service runs and answers; the same setup again over the running install upgrades it; the entry's uninstall removes the service, the files and the entry. Its pages (and the Russian ones) not looked at |
| The app's Windows build | built by the release workflow; its shaders by Microsoft's own `fxc.exe` (under Wine) with GPUI's own arguments; its icon and manifest in its resources, no C runtime DLL among its imports; under Wine it starts and gets as far as drawing text |
**Not verified: anything that needs real Windows.** Traffic through sing-box on Windows (Wine
lacks an API it needs), the TUN adapter, WinDivert actually rewriting packets, the Windows
@@ -64,16 +67,27 @@ there), its tray icon, the system proxy and the Start Menu entry.
## Install
1. Unzip `ProxySuite-<version>-windows-x64.zip` anywhere.
2. Run `install.cmd` (it asks for administrator rights). It copies the program to
`C:\Program Files\ProxySuite`, registers the **ProxySuite** service (starts at boot), adds
`proxy-ctl` to PATH, starts it, and opens the app; the app starts at every sign-in, in the
tray (its shield is green while things work, amber when one failed, grey when all is off).
1. Download `ProxySuite-<version>-windows-x64-setup.exe` and run it. It asks for
administrator rights; SmartScreen may warn of an unknown publisher (the programs are not
signed yet): **More info** → **Run anyway**.
2. It installs everything into `C:\Program Files\ProxySuite`, registers the **ProxySuite**
service (starts at boot), adds `proxy-ctl` to PATH, starts it, and opens the app; the app
starts at every sign-in, in the tray (its shield is green while things work, amber when one
failed, grey when all is off). One option, unchecked: Windows' **OpenSSH Client**, for the
SSH tunnel only, where it was removed from Windows (Windows 10 1809 and later have it).
3. Open **Proxy Suite** from the Start Menu or the tray, or in a **new** terminal:
`proxy-ctl status`.
To upgrade, unzip the new release and run its `install.cmd`. To remove, run `uninstall.cmd`;
the configuration and state stay in `%ProgramData%\ProxySuite` until you delete it.
Nothing has to be installed first: the C runtime is linked into the programs, and WinDivert,
wintun, Python, Tor and the rest come with it, as components. For a silent install:
`ProxySuite-<version>-windows-x64-setup.exe /S`.
To upgrade, run the new setup: the settings stay. To remove: **Settings → Apps → Proxy Suite →
Uninstall** (it runs `uninstall.cmd` in that folder); the configuration and state stay in
`%ProgramData%\ProxySuite` until you delete it.
Without the setup program: unzip `ProxySuite-<version>-windows-x64.zip` anywhere and run
`install.cmd` (it asks for administrator rights): the same install, from the same files.
Windows Defender and other antivirus software may flag WinDivert (zapret's driver): it is a
packet-filtering driver, which is what it is for. Remove other DPI-bypass tools first:
@@ -110,6 +124,14 @@ proxy-ctl config get > config.json # set "tgWsProxy": { "enable": true }
proxy-ctl config set config.json
proxy-ctl logs proxy-suite-tg-ws-proxy # its tg:// link and secret
# whitelist-bypass: a joiner here (set "whitelistBypass": { "enable": true,
# "joiners": { "wl": { "platform": "wbstream" } } }), its creator's link from the other end:
proxy-ctl wl join wl "https://..."
proxy-ctl proxy pin wl
# A creator: its login (a cookies export; DION and Bitrix ask for an email and password), its call:
proxy-ctl wl auth laptop cookies.json
proxy-ctl wl link laptop
proxy-ctl logs -f # everything, following
proxy-ctl --help
```
@@ -169,8 +191,9 @@ On Linux with Nix: `nix develop` here (this directory has its own `flake.nix`),
```sh
cargo test # everything but the app; sing-box and xray from the shell
python3 -I tools/parity/links.py # link parsing against upstream's Python
tools/package.sh # the release zip, in dist/
tools/package.sh # the setup program and the zip, in dist/
nix shell nixpkgs#wineWow64Packages.stable -c tools/winws-dry-run.sh dist/ProxySuite-*/components
nix shell nixpkgs#wineWow64Packages.stable -c tools/wine-setup-test.sh dist/ProxySuite-*-setup.exe dist/ProxySuite-*-x64
```
The app on Linux, against the service on Linux:
@@ -185,10 +208,12 @@ Its Windows build compiles GPUI's shaders with Microsoft's `fxc.exe` under Wine
(`tools/fxc-wine.sh`, fetched from the Windows SDK and pinned by hash; it stays on the build
machine), through a small patch to GPUI's Windows backend (`vendor/gpui-pre-windows`).
The Windows programs are cross-compiled with `cargo xwin` (MSVC target), with the toolchain
in `rust-toolchain.toml`. Design notes: [`DESIGN.md`](DESIGN.md).
The Windows programs are cross-compiled with `cargo xwin` (MSVC target, the C runtime linked
in: `.cargo/config.toml`), with the toolchain in `rust-toolchain.toml`. The setup program is
NSIS's (`tools/installer.nsi`, `makensis` from the shell): it unpacks the release and runs its
`proxy-suite-service.exe install`, as `install.cmd` does. Design notes: [`DESIGN.md`](DESIGN.md).
Releases are built by Gitea Actions (`.gitea/workflows/windows-release.yml`): bump `version`
in `Cargo.toml`, add `release-notes/<version>.md`, push a tag `windows-v<version>`. The
workflow tests, packages and publishes the zip and its `.sha256` with the `RELEASE_TOKEN`
workflow tests, packages and publishes the setup program and the zip, each with its `.sha256`, with the `RELEASE_TOKEN`
secret (a token with `write:repository`). Run by hand, it only builds.
+7
View File
@@ -125,6 +125,13 @@
"homepage": "https://github.com/artem-russkikh/wireproxy-awg",
"bundled": true,
"sources": []
},
"whitelist-bypass": {
"version": "0.4.4",
"license": "MIT",
"homepage": "https://github.com/kulikov0/whitelist-bypass",
"bundled": true,
"sources": []
}
}
}
+49
View File
@@ -235,6 +235,39 @@ pub fn set_path(c: &mut Value, path: &[&str], value: Value) {
*cur = value;
}
/// whitelist-bypass's platforms, as its options name them.
pub const WL_PLATFORMS: [&str; 5] = ["wbstream", "telemost", "dion", "bitrix", "vk"];
/// A whitelist-bypass joiner or creator (`role`: "joiners" or "creators") on `platform`. A name
/// is one of either: `proxy-ctl wl` takes them by name alone.
pub fn add_wl(c: &mut Value, role: &str, name: &str, platform: &str) -> Result<()> {
if !matches!(role, "joiners" | "creators") {
bail!("a whitelist-bypass role is joiners or creators");
}
if !ps_core::config::path_name_ok(name) {
bail!("a name takes letters, digits, '.', '_' and '-', and no leading dot");
}
if !WL_PLATFORMS.contains(&platform) {
bail!("no platform '{platform}': {}", WL_PLATFORMS.join(", "));
}
if role == "joiners" && platform == "vk" {
bail!("VK has no joiner, only creators");
}
let wl = &c["whitelistBypass"];
if wl["joiners"].get(name).is_some() || wl["creators"].get(name).is_some() {
bail!("'{name}' is taken");
}
set_path(c, &["whitelistBypass", role, name], json!({ "platform": platform }));
Ok(())
}
pub fn remove_wl(c: &mut Value, role: &str, name: &str) -> Result<()> {
match c.get_mut("whitelistBypass").and_then(|w| w.get_mut(role)).and_then(Value::as_object_mut).and_then(|o| o.remove(name)) {
Some(_) => Ok(()),
None => bail!("no whitelist-bypass {} '{name}'", role.trim_end_matches('s')),
}
}
/// The sites an engine also handles and those it leaves alone: for `zapret-discord-youtube`
/// beside its release's lists, for `zapret2` beside its strategies' own.
pub fn set_zapret_sites(c: &mut Value, engine: &str, domains: &[String], exclude: &[String]) -> Result<()> {
@@ -259,6 +292,22 @@ pub fn set_zapret_sites(c: &mut Value, engine: &str, domains: &[String], exclude
mod tests {
use super::*;
#[test]
fn whitelist_bypass_entries_are_added_once_and_removed() {
let mut c = json!({});
add_wl(&mut c, "joiners", "wl", "wbstream").unwrap();
add_wl(&mut c, "creators", "laptop", "vk").unwrap();
assert_eq!(c["whitelistBypass"]["joiners"]["wl"], json!({ "platform": "wbstream" }));
assert!(add_wl(&mut c, "creators", "wl", "dion").is_err(), "a name is one of either");
assert!(add_wl(&mut c, "joiners", "phone", "vk").is_err(), "VK has no joiner");
assert!(add_wl(&mut c, "joiners", "phone", "zoom").is_err());
assert!(add_wl(&mut c, "joiners", "../x", "wbstream").is_err());
assert!(add_wl(&mut c, "joiners", "CON", "wbstream").is_err());
remove_wl(&mut c, "joiners", "wl").unwrap();
assert!(remove_wl(&mut c, "joiners", "wl").is_err());
assert_eq!(c["whitelistBypass"]["creators"]["laptop"]["platform"], "vk");
}
#[test]
fn outbounds_are_added_once_and_removed() {
let mut c = json!({});
+1 -1
View File
@@ -21,7 +21,7 @@ pub use misc::*;
pub use privilege::privileged_changes;
pub use proxy::*;
pub use tunnels::*;
pub use validate::{Issue, Severity, validate};
pub use validate::{Issue, Severity, path_name_ok, validate};
pub use zapret::*;
use serde::{Deserialize, Serialize};
+33 -7
View File
@@ -50,11 +50,20 @@ fn tag_pattern_ok(tag: &str) -> bool {
/// A name that becomes part of a file path, a Windows service name or an adapter name:
/// letters, digits, `.`, `_` and `-`, not starting with a dot, at most 64 characters.
pub(crate) fn path_name_ok(name: &str) -> bool {
pub fn path_name_ok(name: &str) -> bool {
!name.is_empty()
&& name.len() <= 64
&& !name.starts_with('.')
&& name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
&& !windows_device(name)
}
/// CON, NUL, COM1 and the rest: on Windows a file named so (whatever its extension) is the
/// device.
fn windows_device(name: &str) -> bool {
let stem = name.split('.').next().unwrap_or("").to_ascii_uppercase();
matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL")
|| (stem.len() == 4 && (stem.starts_with("COM") || stem.starts_with("LPT")) && stem.as_bytes()[3].is_ascii_digit())
}
/// A geosite or geoip name: "geolocation-!cn" and "google@cn" among them, never a path
@@ -116,7 +125,6 @@ fn not_ported(cfg: &Config, v: &mut Issues) {
(cfg.amnezia_wg.enable && cfg.amnezia_wg.profiles.values().any(|p| p.as_outbound.is_none()), "amneziaWg.profiles", "AmneziaWG as a system-wide VPN (its driver; as outbounds it is here)"),
(cfg.warp.enable && cfg.warp.as_amnezia_wg, "warp.asAmneziaWg", "WARP as an AmneziaWG profile"),
(cfg.tor.enable && cfg.tor.onion_service.enable, "tor.onionService.enable", "Tor's onion service (it serves the inbounds)"),
(cfg.whitelist_bypass.enable, "whitelistBypass.enable", "whitelist-bypass"),
(cfg.inbounds.enable, "inbounds.enable", "Serving inbounds"),
(cfg.proxy.auto_proxy.enable, "proxy.autoProxy.enable", "autoProxy"),
] {
@@ -478,13 +486,14 @@ fn tunnels(cfg: &Config, v: &mut Issues) {
}
let wl = &cfg.whitelist_bypass;
// Checked on or off: `proxy-ctl wl` names files after them either way.
for name in wl.joiners.keys().chain(wl.creators.keys()) {
if !path_name_ok(name) {
v.error(format!("whitelistBypass.{name}"), "a creator or joiner name takes letters, digits, '.', '_' and '-', and no leading dot");
}
}
if wl.enable {
v.requires(!wl.joiners.is_empty(), proxy_on, "whitelistBypass.joiners", "whitelistBypass.joiners", "proxy.enable = true");
for name in wl.joiners.keys().chain(wl.creators.keys()) {
if !path_name_ok(name) {
v.error(format!("whitelistBypass.{name}"), "a creator or joiner name takes letters, digits, '.', '_' and '-', and no leading dot");
}
}
for (name, j) in &wl.joiners {
if j.platform == crate::config::WlPlatform::Vk {
v.error(format!("whitelistBypass.joiners.{name}.platform"), "VK has no joiner here");
@@ -757,6 +766,23 @@ mod tests {
use super::*;
use crate::config::{Group, Outbound, RoutingRule};
#[test]
fn names_are_plain_file_names_and_never_devices() {
for ok in ["laptop", "wl", "a.b_c-1", "COM", "console", "lpt10", "nul-ish"] {
assert!(path_name_ok(ok), "{ok}");
}
for bad in ["", ".hidden", "a/b", r"a\b", "C:x", "..", "CON", "con.txt", "Nul", "PRN", "aux.json", "COM1", "lpt9.link"] {
assert!(!path_name_ok(bad), "{bad}");
}
}
#[test]
fn whitelist_bypass_names_are_checked_while_it_is_off() {
let mut cfg = Config::default();
cfg.whitelist_bypass.creators.insert(r"C:\Windows\x".into(), serde_json::from_value(serde_json::json!({ "platform": "wbstream" })).unwrap());
assert!(errors(&cfg).iter().any(|e| e.starts_with("whitelistBypass.")), "{:?}", errors(&cfg));
}
fn errors(cfg: &Config) -> Vec<String> {
validate(cfg)
.into_iter()
+1
View File
@@ -17,6 +17,7 @@ anyhow.workspace = true
serde_json.workspace = true
tokio.workspace = true
clap.workspace = true
rpassword.workspace = true
[dev-dependencies]
serde_json.workspace = true
+129 -2
View File
@@ -54,6 +54,11 @@ enum Cmd {
#[command(subcommand)]
verb: TgVerb,
},
/// whitelist-bypass creators and joiners.
Wl {
#[command(subcommand)]
verb: Option<WlVerb>,
},
/// The backend programs: what is installed, and installing them (administrator).
Components {
#[command(subcommand)]
@@ -67,6 +72,23 @@ enum TgVerb {
Link,
}
#[derive(Subcommand)]
enum WlVerb {
/// Creators and joiners, and their state.
List,
/// The call a creator made, for its joiner.
Link { creator: String },
/// A creator's login: a cookies export (a file, or - for stdin); DION and Bitrix ask for
/// an email and password without one.
Auth { creator: String, file: Option<String> },
/// The call link a joiner joins (or - for stdin).
Join { joiner: String, link: String },
/// Start a new call, if the platform closed the old one.
New { creator: String },
/// Restart all of them, or the one named.
Restart { name: Option<String> },
}
#[derive(Subcommand)]
enum ZapretVerb {
Status,
@@ -245,9 +267,13 @@ fn read_arg(value: &str) -> Result<String> {
}
}
/// A file's text, or stdin's for -.
fn read_arg_file(file: &str) -> Result<String> {
if file == "-" { read_arg("-") } else { std::fs::read_to_string(file).with_context(|| format!("reading {file}")) }
}
fn read_file_arg(file: &str) -> Result<Value> {
let text = if file == "-" { read_arg("-")? } else { std::fs::read_to_string(file).with_context(|| format!("reading {file}"))? };
serde_json::from_str(&text).with_context(|| format!("{file} is not JSON"))
serde_json::from_str(&read_arg_file(file)?).with_context(|| format!("{file} is not JSON"))
}
async fn status(ctl: &Ctl) -> Result<()> {
@@ -549,6 +575,106 @@ async fn zapret(ctl: &Ctl, verb: Option<ZapretVerb>) -> Result<()> {
Ok(())
}
/// A login for the DION and Bitrix creators, which log in on their own from it.
fn password_login(platform: &str, name: &str) -> Result<String> {
let fields: &[&str] = match platform {
"dion" => &["email", "password"],
"bitrix" => &["email", "password", "portal"],
_ => bail!("{platform} logs in only in a browser: export its cookies from the desktop Creator, then: proxy-ctl wl auth {name} <file>"),
};
let mut login = serde_json::Map::new();
for field in fields {
let value = if *field == "password" {
rpassword::prompt_password("Password: ")?
} else {
eprint!("{}{}: ", field[..1].to_uppercase(), &field[1..]);
let mut line = String::new();
std::io::stdin().read_line(&mut line)?;
line.trim().to_owned()
};
let value = match *field {
"portal" => {
let portal = value.trim_end_matches('/');
if portal.contains("://") { portal.to_owned() } else { format!("https://{portal}") }
}
_ => value,
};
login.insert((*field).to_owned(), Value::String(value));
}
Ok(Value::Object(login).to_string())
}
async fn wl(ctl: &Ctl, verb: Option<WlVerb>) -> Result<()> {
let say = |r: &Value| println!("{}: {}", r["unit"].as_str().unwrap_or("?"), r["state"].as_str().unwrap_or("?"));
match verb.unwrap_or(WlVerb::List) {
WlVerb::List => {
let r = ctl.call(Request::WlList).await?;
if ctl.json {
ctl.print(&r);
return Ok(());
}
let list = r.as_array().cloned().unwrap_or_default();
if list.is_empty() {
println!("No whitelist-bypass creators or joiners configured.");
return Ok(());
}
println!(" {:<16} {:<8} {:<10} STATUS", "NAME", "ROLE", "PLATFORM");
for w in list {
let f = |k: &str| w[k].as_str().unwrap_or("").to_owned();
println!(" {:<16} {:<8} {:<10} {}", f("name"), f("role"), f("platform"), f("state"));
}
}
WlVerb::Link { creator } => {
let r = ctl.call(Request::WlLink { name: creator }).await?;
println!("{}", r["link"].as_str().unwrap_or(""));
}
WlVerb::Auth { creator, file } => {
let login = match file {
Some(f) => {
let text = read_arg_file(&f)?;
serde_json::from_str::<Value>(&text).context("not a cookies export, not valid JSON")?;
text
}
None => {
let list = ctl.call(Request::WlList).await?;
let platform = list
.as_array()
.into_iter()
.flatten()
.find(|w| w["name"] == creator.as_str() && w["role"] == "creator")
.and_then(|w| w["platform"].as_str().map(str::to_owned))
.with_context(|| format!("no whitelist-bypass creator '{creator}'"))?;
password_login(&platform, &creator)?
}
};
say(&ctl.call(Request::WlAuth { name: creator, login }).await?);
}
WlVerb::Join { joiner, link } => {
let link = read_arg(&link)?;
say(&ctl.call(Request::WlJoin { name: joiner, link: link.trim().to_owned() }).await?);
}
WlVerb::New { creator } => {
say(&ctl.call(Request::WlNew { name: creator.clone() }).await?);
println!("Its joiner needs the new call: proxy-ctl wl link {creator}");
}
WlVerb::Restart { name } => {
let list = ctl.call(Request::WlList).await?;
let units: Vec<String> = list
.as_array()
.into_iter()
.flatten()
.filter(|w| name.as_deref().is_none_or(|n| w["name"] == n))
.map(|w| format!("proxy-suite-wb-{}-{}", w["role"].as_str().unwrap_or(""), w["name"].as_str().unwrap_or("")))
.collect();
if units.is_empty() {
bail!("no such whitelist-bypass creator or joiner");
}
ctl.call(Request::Restart { units }).await?;
}
}
Ok(())
}
async fn components(ctl: &Ctl, verb: Option<ComponentsVerb>) -> Result<()> {
match verb.unwrap_or(ComponentsVerb::List) {
ComponentsVerb::List => {
@@ -601,6 +727,7 @@ async fn real_main() -> Result<()> {
Cmd::Proxy(p) => proxy(&ctl, p.verb).await?,
Cmd::Zapret { verb } => zapret(&ctl, verb).await?,
Cmd::Components { verb } => components(&ctl, verb).await?,
Cmd::Wl { verb } => wl(&ctl, verb).await?,
Cmd::Tg { verb: TgVerb::Link } => {
let r = ctl.call(Request::TgLinks).await?;
for l in r["links"].as_array().into_iter().flatten().filter_map(Value::as_str) {
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

+34
View File
@@ -0,0 +1,34 @@
//! The Windows build carries the app's icon as its resource 1, where GPUI loads its windows'
//! icon from (and Explorer, the Start Menu and Settings > Apps show it). The resource compiler
//! is LLVM's (`llvm-rc`, in the dev shell), or `rc.exe` on Windows; `PS_GUI_RC` names another.
//! (Not `RC`: the dev shell sets that to MinGW's windres, which takes other arguments.) Without
//! one the app builds with Windows' default icon, and says so; tools/package.sh refuses that.
use std::path::PathBuf;
use std::process::Command;
fn main() {
let icon = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap()).join("assets/proxy-suite.ico");
println!("cargo:rerun-if-changed={}", icon.display());
println!("cargo:rerun-if-env-changed=PS_GUI_RC");
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return;
}
let out = PathBuf::from(std::env::var("OUT_DIR").unwrap());
let rc = out.join("app.rc");
let res = out.join("app.res");
// The resource script's strings are C strings: backslashes doubled.
std::fs::write(&rc, format!("1 ICON \"{}\"\n", icon.display().to_string().replace('\\', "\\\\"))).unwrap();
let compiler = std::env::var("PS_GUI_RC").unwrap_or_else(|_| if cfg!(windows) { "rc.exe".into() } else { "llvm-rc".into() });
let mut command = Command::new(&compiler);
command.arg("/nologo");
if compiler.contains("llvm-rc") {
// Nothing to preprocess, so no C compiler needed for it.
command.arg("/no-preprocess");
}
match command.arg("/fo").arg(&res).arg(&rc).status() {
Ok(s) if s.success() => println!("cargo:rustc-link-arg-bins={}", res.display()),
Ok(s) => println!("cargo:warning=the app's icon: {compiler} failed ({s}); building without it"),
Err(e) => println!("cargo:warning=the app's icon: no {compiler} ({e}); building without it"),
}
}
+1 -1
View File
@@ -5,7 +5,7 @@ use std::borrow::Cow;
use gpui_kit::*;
gpui_kit::assets::icon_assets!(Extra, [Shield, Send, Package, Pin, PinOff, RefreshCw, Save, Trash, Plus, Copy, Download, Link, Gauge, Power]);
gpui_kit::assets::icon_assets!(Extra, [Shield, Send, Package, Pin, PinOff, RefreshCw, Save, Trash, Plus, Copy, Download, Link, Gauge, Power, Video, FileUp]);
pub struct AppAssets;
+12 -2
View File
@@ -8,6 +8,7 @@ mod outbounds;
mod overview;
mod settings;
mod telegram;
mod whitelist;
mod widgets;
use gpui_kit::component::notification::Notification;
@@ -23,6 +24,7 @@ pub enum Page {
Overview,
Dpi,
Telegram,
Whitelist,
Outbounds,
Logs,
Settings,
@@ -30,13 +32,14 @@ pub enum Page {
}
impl Page {
const ALL: [Page; 7] = [Page::Overview, Page::Dpi, Page::Telegram, Page::Outbounds, Page::Logs, Page::Settings, Page::Components];
const ALL: [Page; 8] = [Page::Overview, Page::Dpi, Page::Telegram, Page::Whitelist, Page::Outbounds, Page::Logs, Page::Settings, Page::Components];
fn title(self) -> &'static str {
match self {
Page::Overview => "Overview",
Page::Dpi => "DPI bypass",
Page::Telegram => "Telegram proxy",
Page::Whitelist => "Whitelist bypass",
Page::Outbounds => "Outbounds",
Page::Logs => "Logs",
Page::Settings => "Settings",
@@ -49,6 +52,7 @@ impl Page {
Page::Overview => IconName::LayoutDashboard,
Page::Dpi => IconName::Shield,
Page::Telegram => IconName::Send,
Page::Whitelist => IconName::Video,
Page::Outbounds => IconName::Globe,
Page::Logs => IconName::SquareTerminal,
Page::Settings => IconName::Settings,
@@ -63,6 +67,8 @@ pub struct AppView {
dpi: Entity<dpi::DpiPage>,
telegram: Entity<telegram::TelegramPage>,
outbounds: Entity<outbounds::OutboundsPage>,
/// Made when first shown.
whitelist: Option<Entity<whitelist::WhitelistPage>>,
/// Made when first shown: following the logs starts then.
logs: Option<Entity<logs::LogsPage>>,
/// Made when first shown, as it loads the configuration into its editor then.
@@ -86,7 +92,7 @@ impl AppView {
let dpi = cx.new(|cx| dpi::DpiPage::new(model.clone(), window, cx));
let telegram = cx.new(|cx| telegram::TelegramPage::new(model.clone(), window, cx));
let outbounds = cx.new(|cx| outbounds::OutboundsPage::new(model.clone(), window, cx));
Self { model, page: Page::Overview, dpi, telegram, outbounds, logs: None, settings: None, components: None, _subscriptions: subscriptions }
Self { model, page: Page::Overview, dpi, telegram, outbounds, whitelist: None, logs: None, settings: None, components: None, _subscriptions: subscriptions }
}
fn sidebar(&self, cx: &mut Context<Self>) -> impl IntoElement {
@@ -114,6 +120,10 @@ impl Render for AppView {
Page::Overview => overview::render(&self.model, window, cx).into_any_element(),
Page::Dpi => self.dpi.clone().into_any_element(),
Page::Telegram => self.telegram.clone().into_any_element(),
Page::Whitelist => {
let model = self.model.clone();
self.whitelist.get_or_insert_with(|| cx.new(|cx| whitelist::WhitelistPage::new(model, window, cx))).clone().into_any_element()
}
Page::Outbounds => self.outbounds.clone().into_any_element(),
Page::Logs => {
let model = self.model.clone();
+318
View File
@@ -0,0 +1,318 @@
//! whitelist-bypass: its joiners (outbounds of the proxy, through a video call) and creators
//! (the calls' other ends), their state; a joiner's call link given, a creator's shown, its
//! login given (a cookies export, or DION's and Bitrix's email and password); which there are.
use std::collections::BTreeMap;
use gpui_kit::assets::IconName;
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::input::{Input, InputState};
use gpui_kit::component::notification::Notification;
use gpui_kit::component::radio::RadioGroup;
use gpui_kit::component::switch::Switch;
use gpui_kit::component::*;
use gpui_kit::*;
use ps_client::edits;
use ps_ipc::Request;
use serde_json::Value;
use super::widgets::{card, hint, page, state_tag};
use crate::model::Model;
const PLATFORMS: [(&str, &str); 5] = [("wbstream", "WB Stream"), ("telemost", "Telemost"), ("dion", "DION"), ("bitrix", "Bitrix24"), ("vk", "VK (creators only)")];
/// A creator's login by email and password, for the platforms that take one.
struct PasswordLogin {
email: Entity<InputState>,
password: Entity<InputState>,
/// Bitrix only: the portal's address.
portal: Option<Entity<InputState>>,
}
pub struct WhitelistPage {
model: Entity<Model>,
name: Entity<InputState>,
platform: usize,
/// Each joiner's link input, by name.
joins: BTreeMap<String, Entity<InputState>>,
/// DION's and Bitrix's creators' login inputs, by name.
logins: BTreeMap<String, PasswordLogin>,
/// Each creator's call link, or why there is none, once asked for.
links: BTreeMap<String, Result<String, String>>,
_subscriptions: Vec<Subscription>,
}
impl WhitelistPage {
pub fn new(model: Entity<Model>, window: &mut Window, cx: &mut Context<Self>) -> Self {
let name = cx.new(|cx| InputState::new(window, cx).placeholder("laptop"));
let subscriptions = vec![cx.observe_in(&model, window, |this, _, window, cx| this.sync(window, cx))];
let mut this = Self { model, name, platform: 0, joins: BTreeMap::new(), logins: BTreeMap::new(), links: BTreeMap::new(), _subscriptions: subscriptions };
this.sync(window, cx);
this
}
/// Inputs for the creators and joiners there are now.
fn sync(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let w = self.model.read(cx).config()["whitelistBypass"].clone();
let joiners: Vec<String> = w["joiners"].as_object().map(|o| o.keys().cloned().collect()).unwrap_or_default();
self.joins.retain(|n, _| joiners.contains(n));
for n in joiners {
self.joins.entry(n).or_insert_with(|| cx.new(|cx| InputState::new(window, cx).placeholder("the creator's call link")));
}
let creators: Vec<(String, String)> =
w["creators"].as_object().map(|o| o.iter().map(|(n, c)| (n.clone(), c["platform"].as_str().unwrap_or("").to_owned())).collect()).unwrap_or_default();
self.logins.retain(|n, _| creators.iter().any(|(c, p)| c == n && matches!(p.as_str(), "dion" | "bitrix")));
for (n, platform) in creators {
if matches!(platform.as_str(), "dion" | "bitrix") && !self.logins.contains_key(&n) {
let login = PasswordLogin {
email: cx.new(|cx| InputState::new(window, cx).placeholder("email")),
password: cx.new(|cx| InputState::new(window, cx).placeholder("password").masked(true)),
portal: (platform == "bitrix").then(|| cx.new(|cx| InputState::new(window, cx).placeholder("portal.bitrix24.ru"))),
};
self.logins.insert(n, login);
}
}
}
fn add(&mut self, role: &'static str, window: &mut Window, cx: &mut Context<Self>) {
let name = self.name.read(cx).value().trim().to_owned();
let platform = PLATFORMS[self.platform].0;
// Checked here first, for a message at once.
if let Err(e) = edits::add_wl(&mut Value::Null, role, &name, platform) {
window.push_notification(Notification::error(format!("{e:#}")), cx);
return;
}
self.name.update(cx, |s, cx| s.set_value("", window, cx));
let what = format!("{} '{name}' added", if role == "joiners" { "Joiner" } else { "Creator" });
self.model.update(cx, |m, cx| m.edit(what, move |c| edits::add_wl(c, role, &name, platform), cx));
}
fn join(&mut self, name: String, window: &mut Window, cx: &mut Context<Self>) {
let Some(input) = self.joins.get(&name) else { return };
let link = input.read(cx).value().trim().to_owned();
if link.is_empty() {
window.push_notification(Notification::error("Paste the link the creator's side gave (its proxy-ctl wl link)"), cx);
return;
}
input.update(cx, |s, cx| s.set_value("", window, cx));
self.model.update(cx, |m, cx| m.request(format!("'{name}' joins the call"), Request::WlJoin { name, link }, cx));
}
fn link(&mut self, name: String, cx: &mut Context<Self>) {
let job = self.model.read(cx).bridge().call(Request::WlLink { name: name.clone() });
cx.spawn(async move |this, cx| {
let r = job.await.map(|v| v["link"].as_str().unwrap_or("").to_owned()).map_err(|e| format!("{e:#}"));
this.update(cx, |this, cx| {
this.links.insert(name, r);
cx.notify();
})
.ok();
})
.detach();
}
/// A cookies export, chosen: read here, as the signed-in user, and handed to the service.
fn cookies(&mut self, name: String, cx: &mut Context<Self>) {
let paths = cx.prompt_for_paths(PathPromptOptions { files: true, directories: false, multiple: false, prompt: Some("Log in".into()) });
let model = self.model.clone();
cx.spawn(async move |_, cx| {
let Ok(Ok(Some(paths))) = paths.await else { return };
let Some(path) = paths.into_iter().next() else { return };
let login = std::fs::read_to_string(&path);
model.update(cx, |m, cx| match login {
Ok(login) => m.request(format!("'{name}' has its login"), Request::WlAuth { name, login }, cx),
Err(e) => m.track(format!("Reading {}", path.display()), async move { Err(e.into()) }, cx),
});
})
.detach();
}
fn password_login(&mut self, name: String, window: &mut Window, cx: &mut Context<Self>) {
let Some(l) = self.logins.get(&name) else { return };
let mut login = serde_json::Map::new();
login.insert("email".into(), l.email.read(cx).value().trim().into());
login.insert("password".into(), l.password.read(cx).value().to_string().into());
if let Some(p) = &l.portal {
let portal = p.read(cx).value().trim().trim_end_matches('/').to_owned();
login.insert("portal".into(), if portal.contains("://") { portal } else { format!("https://{portal}") }.into());
}
if login.values().any(|v| v.as_str().is_none_or(str::is_empty) || v == "https://") {
window.push_notification(Notification::error("Fill in every field"), cx);
return;
}
l.password.update(cx, |s, cx| s.set_value("", window, cx));
let login = Value::Object(login).to_string();
self.model.update(cx, |m, cx| m.request(format!("'{name}' has its login"), Request::WlAuth { name, login }, cx));
}
fn remove(&mut self, role: &'static str, name: String, cx: &mut Context<Self>) {
self.model.update(cx, |m, cx| m.edit(format!("'{name}' removed"), move |c| edits::remove_wl(c, role, &name), cx));
}
}
/// A unit's state from the service's status, "off" when whitelist-bypass is.
fn unit_state(status: &Value, unit: &str, on: bool) -> String {
if !on {
return "off".into();
}
status["units"].as_array().into_iter().flatten().find(|u| u["name"] == unit).and_then(|u| u["state"].as_str()).unwrap_or("waiting").to_owned()
}
fn platform_label(p: &str) -> &str {
PLATFORMS.iter().find(|(id, _)| *id == p).map_or(p, |(_, label)| label.trim_end_matches(" (creators only)"))
}
impl Render for WhitelistPage {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let m = self.model.read(cx);
let w = m.config()["whitelistBypass"].clone();
let status = m.status().clone();
let body = page("Whitelist bypass", cx);
if m.config().is_null() {
return body.child(hint("Waiting for the service…", cx));
}
let on = w["enable"] == true;
let model = self.model.clone();
let enable = Switch::new("wl-enable").checked(on).on_change(move |on, _, cx| {
let on = *on;
model.update(cx, |m, cx| {
m.edit(
if on { "Whitelist bypass is on" } else { "Whitelist bypass is off" },
move |c| {
edits::set_path(c, &["whitelistBypass", "enable"], on.into());
Ok(())
},
cx,
)
})
});
let about = card("whitelist-bypass", Some(enable.into_any_element()), cx).child(hint(
"For networks that let only a whitelist through, video calls among it: a joiner here tunnels the proxy's traffic through a call that a creator, on a machine with normal internet, holds open. Pin the joiner's outbound (Outbounds) to send traffic through it.",
cx,
));
let mut joiners = card("Joiners", None, cx).child(hint("Each is an outbound of the proxy, named as here. It joins the call whose link its creator gives.", cx));
let joiner_list: Vec<(String, String)> =
w["joiners"].as_object().map(|o| o.iter().map(|(n, j)| (n.clone(), j["platform"].as_str().unwrap_or("").to_owned())).collect()).unwrap_or_default();
if joiner_list.is_empty() {
joiners = joiners.child(hint("None yet: add one below.", cx));
}
for (i, (name, platform)) in joiner_list.into_iter().enumerate() {
let Some(input) = self.joins.get(&name) else { continue };
let state = unit_state(&status, &format!("proxy-suite-wb-joiner-{name}"), on);
let (n1, n2) = (name.clone(), name.clone());
joiners = joiners.child(
div()
.v_flex()
.gap_2()
.py_2()
.border_t_1()
.border_color(cx.theme().border)
.child(
div()
.h_flex()
.gap_3()
.items_center()
.child(div().font_medium().child(name.clone()))
.child(div().text_sm().text_color(cx.theme().muted_foreground).child(platform_label(&platform).to_owned()))
.child(state_tag(&state))
.child(div().flex_1())
.child(Button::new(("wl-remove-joiner", i)).small().ghost().icon(IconName::Trash).on_click(cx.listener(move |this, _, _, cx| this.remove("joiners", n1.clone(), cx)))),
)
.child(
div()
.h_flex()
.gap_2()
.child(div().flex_1().min_w_0().child(Input::new(input)))
.child(Button::new(("wl-join", i)).small().primary().label("Join").on_click(cx.listener(move |this, _, window, cx| this.join(n2.clone(), window, cx)))),
),
);
}
let mut creators = card("Creators", None, cx).child(hint(
"On the machine with normal internet. Each logs in to its platform (a cookies export from the desktop Creator app or a browser; DION and Bitrix take an email and password), starts a call and keeps it: give its link to the joiner.",
cx,
));
let creator_list: Vec<(String, String)> =
w["creators"].as_object().map(|o| o.iter().map(|(n, c)| (n.clone(), c["platform"].as_str().unwrap_or("").to_owned())).collect()).unwrap_or_default();
if creator_list.is_empty() {
creators = creators.child(hint("None here.", cx));
}
for (i, (name, platform)) in creator_list.into_iter().enumerate() {
let state = unit_state(&status, &format!("proxy-suite-wb-creator-{name}"), on);
let (n1, n2, n3, n4, n5) = (name.clone(), name.clone(), name.clone(), name.clone(), name.clone());
let mut row = div()
.v_flex()
.gap_2()
.py_2()
.border_t_1()
.border_color(cx.theme().border)
.child(
div()
.h_flex()
.gap_3()
.items_center()
.child(div().font_medium().child(name.clone()))
.child(div().text_sm().text_color(cx.theme().muted_foreground).child(platform_label(&platform).to_owned()))
.child(state_tag(&state))
.child(div().flex_1())
.child(Button::new(("wl-link", i)).small().icon(IconName::Link).label("Call link").on_click(cx.listener(move |this, _, _, cx| this.link(n1.clone(), cx))))
.child(Button::new(("wl-new", i)).small().icon(IconName::RefreshCw).label("New call").on_click(cx.listener(move |this, _, _, cx| {
this.links.remove(&n2);
let name = n2.clone();
this.model.update(cx, |m, cx| m.request(format!("'{name}' starts a new call"), Request::WlNew { name }, cx));
})))
.child(Button::new(("wl-cookies", i)).small().icon(IconName::FileUp).label("Cookies file…").on_click(cx.listener(move |this, _, _, cx| this.cookies(n3.clone(), cx))))
.child(Button::new(("wl-remove-creator", i)).small().ghost().icon(IconName::Trash).on_click(cx.listener(move |this, _, _, cx| this.remove("creators", n4.clone(), cx)))),
);
match self.links.get(&name) {
Some(Ok(link)) => {
let copy = link.clone();
row = row.child(
div()
.h_flex()
.gap_2()
.items_center()
.child(div().flex_1().min_w_0().truncate().text_sm().font_family("monospace").child(link.clone()))
.child(Button::new(("wl-copy", i)).small().icon(IconName::Copy).label("Copy").on_click(move |_, window, cx| {
cx.write_to_clipboard(ClipboardItem::new_string(copy.clone()));
window.push_notification(Notification::success("Copied"), cx);
})),
);
}
Some(Err(e)) => row = row.child(hint(e.clone(), cx)),
None => {}
}
if let Some(l) = self.logins.get(&name) {
let mut fields = div().h_flex().gap_2().child(div().flex_1().min_w_0().child(Input::new(&l.email))).child(div().flex_1().min_w_0().child(Input::new(&l.password)));
if let Some(p) = &l.portal {
fields = fields.child(div().flex_1().min_w_0().child(Input::new(p)));
}
row = row.child(fields.child(Button::new(("wl-login", i)).small().primary().label("Log in").on_click(cx.listener(move |this, _, window, cx| this.password_login(n5.clone(), window, cx)))));
}
creators = creators.child(row);
}
let platforms = RadioGroup::horizontal("wl-platform")
.children(PLATFORMS.map(|(_, label)| label))
.selected_index(Some(self.platform))
.on_change(cx.listener(|this, ix: &usize, _, cx| {
this.platform = *ix;
cx.notify();
}));
let add = card("Add", None, cx)
.child(div().v_flex().gap_1().child(div().text_sm().child("Name (letters, digits, '.', '_', '-')")).child(Input::new(&self.name)))
.child(platforms)
.child(
div()
.h_flex()
.gap_2()
.child(Button::new("wl-add-joiner").small().icon(IconName::Plus).label("Add a joiner").on_click(cx.listener(|this, _, window, cx| this.add("joiners", window, cx))))
.child(Button::new("wl-add-creator").small().icon(IconName::Plus).label("Add a creator").on_click(cx.listener(|this, _, window, cx| this.add("creators", window, cx)))),
)
.child(hint("Their other options (linkFile, cookiesFile, upstream, resources) are in Settings, under whitelistBypass.", cx));
body.child(about).child(joiners).child(creators).child(add)
}
}
+11
View File
@@ -65,6 +65,17 @@ pub enum Request {
TgLinks,
/// Fetch and install components (all wanted, or the named ones).
ComponentsInstall { names: Vec<String> },
/// whitelist-bypass's creators and joiners, and their state.
WlList,
/// The call a creator made and keeps rejoining.
WlLink { name: String },
/// A creator's login: a cookies export, or (DION, Bitrix) the JSON of its email, password
/// and portal.
WlAuth { name: String, login: String },
/// The call link a joiner joins.
WlJoin { name: String, link: String },
/// Drops the call a creator rejoins: it makes a new one.
WlNew { name: String },
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+101
View File
@@ -135,10 +135,27 @@ fn scope_of(req: &Request) -> Option<Scope> {
// Backend logs name the sites visited (at info), and errors may quote what was dialled.
Request::RenderedConfig | Request::Logs { .. } | Request::TgLinks => Some(Scope::Secrets),
Request::Restart { .. } | Request::Start { .. } | Request::Stop { .. } => Some(Scope::Services),
Request::WlList | Request::WlLink { .. } | Request::WlAuth { .. } | Request::WlJoin { .. } | Request::WlNew { .. } => Some(Scope::WhitelistBypass),
_ => None,
}
}
/// Re-applies whitelist-bypass, so a unit that waited starts, and restarts `unit` on what
/// was just left for it.
async fn wl_restart(s: &mut service::Service, unit: &str) -> Response {
let started = |s: &service::Service| s.sup.status().into_iter().find(|u| u.name == unit).map(|u| u.since);
let before = started(s);
if let Err(e) = s.apply_wl().await {
return Response::err(format!("{e:#}"));
}
// Unless the apply (re)started it on a new spec, or it does not run (off, or its proxy is).
let after = started(s);
if after.is_some() && after == before {
s.sup.restart(unit);
}
Response::ok(json!({ "unit": unit, "state": s.sup.state_of(unit).as_str() }))
}
fn has_secrets(cfg: &Config, peer: &Peer) -> bool {
allowed(cfg, peer, Some(Scope::Secrets)).is_ok()
}
@@ -476,6 +493,90 @@ pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response {
}
}
Request::WlList => {
let s = shared.lock().await;
let wl = &s.cfg().whitelist_bypass;
let state = |unit: String| if wl.enable { s.sup.state_of(&unit).as_str() } else { "off" };
let mut list: Vec<Value> = wl
.creators
.iter()
.map(|(name, c)| json!({ "name": name, "role": "creator", "platform": c.platform.as_str(), "state": state(format!("{}{name}", crate::wl::CREATOR_PREFIX)) }))
.collect();
list.extend(wl.joiners.iter().map(|(name, j)| {
json!({ "name": name, "role": "joiner", "platform": j.platform.as_str(), "state": state(format!("{}{name}", crate::wl::JOINER_PREFIX)) })
}));
Response::ok(json!(list))
}
Request::WlLink { name } => {
let s = shared.lock().await;
if !s.cfg().whitelist_bypass.creators.contains_key(&name) {
return Response::err(format!("no whitelist-bypass creator '{name}'"));
}
match crate::wl::last_link(s.paths(), &name) {
Some(link) => Response::ok(json!({ "link": link })),
None => Response::err(format!("{name} has no call yet: see proxy-ctl logs {}{name}", crate::wl::CREATOR_PREFIX)),
}
}
Request::WlAuth { name, login } => {
let mut s = shared.lock().await;
if !s.cfg().whitelist_bypass.creators.contains_key(&name) {
return Response::err(format!("no whitelist-bypass creator '{name}'"));
}
if login.len() > 1 << 20 || serde_json::from_str::<Value>(&login).is_err() {
return Response::err("not a cookies export (or a login): not valid JSON");
}
let file = match crate::wl::state_file(s.paths(), &name, ".cookies.json") {
Ok(f) => f,
Err(e) => return Response::err(format!("{e:#}")),
};
if let Err(e) = crate::wl::write_private(&file, login.as_bytes()) {
return Response::err(format!("{e:#}"));
}
wl_restart(&mut s, &format!("{}{name}", crate::wl::CREATOR_PREFIX)).await
}
Request::WlJoin { name, link } => {
let mut s = shared.lock().await;
if !s.cfg().whitelist_bypass.joiners.contains_key(&name) {
return Response::err(format!("no whitelist-bypass joiner '{name}'"));
}
let link = link.trim();
let link = match crate::wl::clean_link(link) {
Ok(l) if l == link => l,
_ => return Response::err("a call link is one word: a room id, a slug or a URL"),
};
let file = match crate::wl::state_file(s.paths(), &name, ".join") {
Ok(f) => f,
Err(e) => return Response::err(format!("{e:#}")),
};
if let Err(e) = crate::wl::write_private(&file, format!("{link}\n").as_bytes()) {
return Response::err(format!("{e:#}"));
}
wl_restart(&mut s, &format!("{}{name}", crate::wl::JOINER_PREFIX)).await
}
Request::WlNew { name } => {
let mut s = shared.lock().await;
let Some(c) = s.cfg().whitelist_bypass.creators.get(&name) else {
return Response::err(format!("no whitelist-bypass creator '{name}'"));
};
if c.link_file.is_some() {
return Response::err(format!("{name} rejoins the call its linkFile sets: change that instead"));
}
let file = match crate::wl::state_file(s.paths(), &name, ".link") {
Ok(f) => f,
Err(e) => return Response::err(format!("{e:#}")),
};
if let Err(e) = std::fs::remove_file(&file)
&& e.kind() != std::io::ErrorKind::NotFound
{
return Response::err(format!("removing {}: {e}", file.display()));
}
wl_restart(&mut s, &format!("{}{name}", crate::wl::CREATOR_PREFIX)).await
}
Request::ComponentsInstall { names } => {
// Programs the service runs as SYSTEM: an administrator's call, whatever the scopes.
if !peer.admin {
+1
View File
@@ -21,6 +21,7 @@ mod units;
mod warp;
#[cfg(windows)]
mod winsvc;
mod wl;
mod zapret;
use std::path::PathBuf;
+60 -2
View File
@@ -1,6 +1,6 @@
//! The service's state and what it does with it: render, write, check, (re)start, fetch.
use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, SystemTime};
@@ -37,6 +37,8 @@ pub struct Service {
pub last_error: Option<String>,
pub last_fetch: BTreeMap<String, SystemTime>,
tcp_timestamps_on: bool,
/// What whitelist-bypass's units waited for at the last apply, said when it first did.
wl_waiting: BTreeSet<String>,
}
fn digest(data: &[u8]) -> String {
@@ -59,6 +61,7 @@ impl Service {
last_error: None,
last_fetch: BTreeMap::new(),
tcp_timestamps_on: false,
wl_waiting: BTreeSet::new(),
store,
})
}
@@ -99,6 +102,17 @@ impl Service {
{
direct.push(p.to_string_lossy().into_owned());
}
// The joiners' calls, and the creators' unless they go through the proxy.
if cfg.whitelist_bypass.enable {
let wl = &cfg.whitelist_bypass;
let joiners = wl.joiners.values().map(|j| format!("headless-{}-joiner", j.platform.as_str()));
let creators = wl.creators.values().filter(|c| c.upstream == ps_core::config::Upstream::Direct).map(|c| format!("headless-{}-creator", c.platform.as_str()));
for name in joiners.chain(creators).collect::<BTreeSet<_>>() {
if let Some(p) = self.comps.find("whitelist-bypass", &name) {
direct.push(p.to_string_lossy().into_owned());
}
}
}
// Tor's own connections, unless it is to go through the proxy (upstream = "proxy").
if cfg.tor.enable
&& cfg.tor.upstream == ps_core::config::Upstream::Direct
@@ -163,8 +177,52 @@ impl Service {
if let Err(e) = &awg {
self.sup.note(SOCKS_UNIT, format!("proxy-suite: AmneziaWG: {e:#}"));
}
let wl = self.apply_wl().await;
if let Err(e) = &wl {
self.sup.note(SOCKS_UNIT, format!("proxy-suite: whitelist-bypass: {e:#}"));
}
let proxy = self.apply_proxy().await;
zapret.and(tg).and(ssh).and(tor).and(awg).and(proxy)
zapret.and(tg).and(ssh).and(tor).and(awg).and(wl).and(proxy)
}
/// whitelist-bypass: the joiners while the proxy they serve runs, the creators while it
/// is on; the ones no longer wanted stopped, and what the rest wait for said once.
pub async fn apply_wl(&mut self) -> Result<()> {
let cfg = self.cfg().clone();
let mut wanted_cfg = cfg.clone();
let on = cfg.enable && cfg.whitelist_bypass.enable;
if !self.proxy_wanted() {
wanted_cfg.whitelist_bypass.joiners.clear();
}
let (units, waiting) = if on {
let auth = &cfg.proxy.listener.auth;
let password = match (&auth.password, &auth.password_file) {
(Some(p), _) => Some(p.clone()),
(None, Some(f)) => Some(std::fs::read_to_string(f).with_context(|| format!("reading {f}"))?.lines().next().unwrap_or("").to_owned()),
(None, None) => None,
};
let login = auth.username.clone().zip(password);
let hop = (self.store.secrets.hop_user.clone(), self.store.secrets.hop_password.clone());
let program = |name: &str| self.comps.program("whitelist-bypass", name);
crate::wl::units(&wanted_cfg, self.paths(), &program, (&hop.0, &hop.1), login)
} else {
(Vec::new(), Vec::new())
};
let waiting: BTreeSet<String> = waiting.into_iter().collect();
for w in waiting.difference(&self.wl_waiting) {
self.sup.note(SOCKS_UNIT, format!("proxy-suite: {w}"));
}
self.wl_waiting = waiting;
let wanted: Vec<String> = units.iter().map(|u| u.name.clone()).collect();
for name in self.sup.names() {
if (name.starts_with(crate::wl::JOINER_PREFIX) || name.starts_with(crate::wl::CREATOR_PREFIX)) && !wanted.contains(&name) {
self.sup.stop(&name).await;
}
}
for unit in units {
self.sup.ensure(unit);
}
Ok(())
}
/// The wireproxy tunnels behind "userspace" AmneziaWG outbounds and WARP devices, while
+99
View File
@@ -144,6 +144,9 @@ pub fn install() -> Result<()> {
Ok(false) => {}
Err(e) => println!("warning: the app's Start Menu entry and start at sign-in: {e:#}"),
}
if let Err(e) = apps::add(&to) {
println!("warning: the entry in Settings → Apps: {e:#}");
}
println!("Open a new terminal and try: proxy-ctl status");
Ok(())
}
@@ -163,8 +166,10 @@ pub fn uninstall() -> Result<()> {
} else {
println!("{DISPLAY} was not installed.");
}
remove_windivert(&manager);
let dir = install_dir();
desktop::remove();
apps::remove();
let _ = path::remove(&dir);
if dir.exists() {
// This program may be one of the files: they go a moment after it exits. Raw, as cmd
@@ -185,6 +190,100 @@ pub fn uninstall() -> Result<()> {
Ok(())
}
/// The WinDivert driver zapret loaded from this suite's components, if it is still registered
/// (WinDivert removes its own service as it loads, but one stopped hard can stay): stopped and
/// deleted, as Flowseal's service.bat removes it. One from elsewhere is left alone.
fn remove_windivert(manager: &ServiceManager) {
let ours = crate::paths::Paths::platform_default().root.to_string_lossy().to_lowercase();
for name in ["WinDivert", "WinDivert14"] {
let Ok(service) = manager.open_service(name, ServiceAccess::QUERY_CONFIG | ServiceAccess::QUERY_STATUS | ServiceAccess::STOP | ServiceAccess::DELETE) else {
continue;
};
let Ok(config) = service.query_config() else { continue };
if config.executable_path.to_string_lossy().to_lowercase().contains(&ours) {
let _ = service.stop();
if service.delete().is_ok() {
println!("WinDivert's driver ({name}) is removed.");
}
}
}
}
/// The entry in Settings → Apps (and Control Panel's Programs and Features): its Uninstall runs
/// uninstall.cmd, which asks for administrator rights; `QuietUninstallString` (winget, scripts
/// that run elevated) the service's own `uninstall`.
mod apps {
use std::path::Path;
use anyhow::{Result, bail};
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
use windows_sys::Win32::System::Registry::{
HKEY, HKEY_LOCAL_MACHINE, KEY_WRITE, REG_DWORD, REG_OPTION_NON_VOLATILE, REG_SZ, RegCloseKey, RegCreateKeyExW, RegDeleteTreeW,
RegSetValueExW,
};
const KEY: &str = r"Software\Microsoft\Windows\CurrentVersion\Uninstall\ProxySuite";
fn wide(s: &str) -> Vec<u16> {
s.encode_utf16().chain(Some(0)).collect()
}
fn size_kib(dir: &Path) -> u64 {
fn walk(dir: &Path) -> u64 {
std::fs::read_dir(dir).into_iter().flatten().flatten().map(|e| match e.file_type() {
Ok(t) if t.is_dir() => walk(&e.path()),
Ok(t) if t.is_file() => e.metadata().map_or(0, |m| m.len()),
_ => 0,
}).sum()
}
walk(dir) / 1024
}
pub fn add(dir: &Path) -> Result<()> {
let system = std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".into());
let d = dir.display();
let text = [
("DisplayName", super::DISPLAY.to_owned()),
("DisplayVersion", env!("CARGO_PKG_VERSION").to_owned()),
("Publisher", "Proxy Suite".to_owned()),
("URLInfoAbout", "https://git.faumaray.com/faumaray/proxy-suite-flake".to_owned()),
("InstallLocation", d.to_string()),
("DisplayIcon", format!("{d}\\proxy-suite.exe")),
// cmd's /c takes the whole line in one more pair of quotes.
("UninstallString", format!("\"{system}\\System32\\cmd.exe\" /c \"\"{d}\\uninstall.cmd\"\"")),
("QuietUninstallString", format!("\"{d}\\proxy-suite-service.exe\" uninstall")),
];
let numbers = [("NoModify", 1u32), ("NoRepair", 1), ("EstimatedSize", size_kib(dir).min(u32::MAX as u64) as u32)];
// SAFETY: NUL-terminated names and data, lengths as given; the key is closed below.
unsafe {
let mut key: HKEY = std::ptr::null_mut();
if RegCreateKeyExW(HKEY_LOCAL_MACHINE, wide(KEY).as_ptr(), 0, std::ptr::null(), REG_OPTION_NON_VOLATILE, KEY_WRITE, std::ptr::null(), &mut key, std::ptr::null_mut()) != ERROR_SUCCESS {
bail!("cannot create the uninstall key");
}
let mut failed = false;
for (name, value) in &text {
let data = wide(value);
failed |= RegSetValueExW(key, wide(name).as_ptr(), 0, REG_SZ, data.as_ptr().cast(), (data.len() * 2) as u32) != ERROR_SUCCESS;
}
for (name, value) in &numbers {
failed |= RegSetValueExW(key, wide(name).as_ptr(), 0, REG_DWORD, (value as *const u32).cast(), 4) != ERROR_SUCCESS;
}
RegCloseKey(key);
if failed {
bail!("cannot write the uninstall key");
}
}
Ok(())
}
pub fn remove() {
// SAFETY: a NUL-terminated name.
unsafe {
RegDeleteTreeW(HKEY_LOCAL_MACHINE, wide(KEY).as_ptr());
}
}
}
/// The desktop app: a Start Menu entry for everyone, and started at each sign-in into the tray;
/// closed before its files are replaced or removed.
mod desktop {
+221
View File
@@ -0,0 +1,221 @@
//! whitelist-bypass, as upstream's whitelist-bypass.nix runs it: joiners, each a SOCKS listener
//! on loopback (with the hop login) behind its outbound, tunnelled through a video call; and
//! creators, the free ends of those calls. Links, logins and passwords reach them through the
//! environment (the build makes those the flags' defaults), never their command lines.
//!
//! A joiner waits for its call's link (`proxy-ctl wl join`, or `linkFile`); a creator for a login
//! (`proxy-ctl wl auth`, or `cookiesFile`), which it keeps refreshing in its own working copy.
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail};
use ps_core::config::{Config, Upstream, WlCreator, WlResources};
use ps_core::derived::ports;
use crate::paths::{Paths, write_atomic};
use crate::units::UnitSpec;
pub const JOINER_PREFIX: &str = "proxy-suite-wb-joiner-";
pub const CREATOR_PREFIX: &str = "proxy-suite-wb-creator-";
/// What `proxy-ctl wl` leaves for the units: links (`<name>.join`), logins
/// (`<name>.cookies.json`), and the creators' calls (`<name>.link`, last line the current).
pub fn state_dir(paths: &Paths) -> PathBuf {
paths.root.join("whitelist-bypass")
}
/// The creators' working logins, which they rewrite as they refresh them.
fn sessions_dir(paths: &Paths) -> PathBuf {
paths.root.join("whitelist-bypass-sessions")
}
/// `name`'s file in `dir`: a plain name there, checked here again whatever let it through (on
/// Windows, joining an absolute path replaces the directory).
fn named(dir: &Path, name: &str, suffix: &str) -> Result<PathBuf> {
if !ps_core::config::path_name_ok(name) {
bail!("'{name}' is not a creator or joiner name");
}
Ok(dir.join(format!("{name}{suffix}")))
}
/// `name`'s file in the state directory: `.join`, `.cookies.json` or `.link`.
pub fn state_file(paths: &Paths, name: &str, suffix: &str) -> Result<PathBuf> {
named(&state_dir(paths), name, suffix)
}
fn resources(r: WlResources) -> &'static str {
match r {
WlResources::Moderate => "moderate",
WlResources::Default => "default",
WlResources::Unlimited => "unlimited",
}
}
/// A link as the units take it: whitespace gone, one line.
pub fn clean_link(text: &str) -> Result<String> {
let link: String = text.chars().filter(|c| !c.is_whitespace()).collect();
if link.is_empty() {
bail!("an empty link");
}
if link.len() > 4096 || link.chars().any(char::is_control) {
bail!("that is not a call link");
}
Ok(link)
}
/// The units, and what each that cannot run yet waits for. `program` finds one of the
/// component's programs by name.
pub fn units(
cfg: &Config,
paths: &Paths,
program: &dyn Fn(&str) -> Result<PathBuf>,
hop: (&str, &str),
proxy_login: Option<(String, String)>,
) -> (Vec<UnitSpec>, Vec<String>) {
let w = &cfg.whitelist_bypass;
let mut units = Vec::new();
let mut waiting = Vec::new();
for (i, (tag, j)) in w.joiners.iter().enumerate() {
let port = ports::WL_JOINER_BASE + i as u16;
// The link `wl join` gave wins over linkFile.
let link = state_file(paths, tag, ".join")
.and_then(|f| Ok(std::fs::read_to_string(f)?))
.ok()
.or_else(|| j.link_file.as_ref().and_then(|f| std::fs::read_to_string(f).ok()))
.and_then(|t| clean_link(&t).ok());
let Some(link) = link else {
waiting.push(format!("whitelist-bypass joiner '{tag}' waits for its call's link: proxy-ctl wl join {tag} <link>"));
continue;
};
let program = match program(&format!("headless-{}-joiner", j.platform.as_str())) {
Ok(p) => p,
Err(e) => {
waiting.push(format!("whitelist-bypass joiner '{tag}': {e:#}"));
continue;
}
};
let args = vec!["--socks-port".into(), port.to_string(), "--socks-user".into(), hop.0.to_owned()];
units.push(UnitSpec {
name: format!("{JOINER_PREFIX}{tag}"),
program,
generation: format!("{args:?}{link}"),
args,
env: vec![("WB_LINK".into(), link), ("WB_SOCKS_PASS".into(), hop.1.to_owned())],
cwd: None,
});
}
for (name, c) in &w.creators {
match creator(cfg, paths, program, name, c, proxy_login.clone()) {
Ok(Some(unit)) => units.push(unit),
Ok(None) => waiting.push(format!("whitelist-bypass creator '{name}' waits for a login: proxy-ctl wl auth {name} <cookies.json>")),
Err(e) => waiting.push(format!("whitelist-bypass creator '{name}': {e:#}")),
}
}
(units, waiting)
}
/// The call a creator made and keeps rejoining: the last line it wrote.
pub fn last_link(paths: &Paths, name: &str) -> Option<String> {
let text = std::fs::read_to_string(state_file(paths, name, ".link").ok()?).ok()?;
text.lines().map(str::trim).rfind(|l| !l.is_empty()).map(str::to_owned)
}
/// Writes a file only the service reads: a link, a login.
pub fn write_private(file: &Path, data: &[u8]) -> Result<()> {
if let Some(dir) = file.parent() {
std::fs::create_dir_all(dir)?;
}
write_atomic(file, data).with_context(|| format!("writing {}", file.display()))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(file, std::fs::Permissions::from_mode(0o600))?;
}
Ok(())
}
fn creator(
cfg: &Config,
paths: &Paths,
program: &dyn Fn(&str) -> Result<PathBuf>,
name: &str,
c: &WlCreator,
proxy_login: Option<(String, String)>,
) -> Result<Option<UnitSpec>> {
let program = program(&format!("headless-{}-creator", c.platform.as_str()))?;
let sessions = sessions_dir(paths);
std::fs::create_dir_all(state_dir(paths))?;
std::fs::create_dir_all(&sessions)?;
let given = state_file(paths, name, ".cookies.json")?;
let cookies = named(&sessions, name, ".cookies.json")?;
// A login `wl auth` left replaces the working copy, then goes.
if given.is_file() {
write_private(&cookies, &std::fs::read(&given)?)?;
std::fs::remove_file(&given)?;
} else if !cookies.is_file()
&& let Some(f) = &c.cookies_file
{
write_private(&cookies, &std::fs::read(f).with_context(|| format!("reading {f}"))?)?;
}
if !cookies.is_file() {
return Ok(None);
}
let links = state_file(paths, name, ".link")?;
// linkFile's call, or the last one it made (empty: it makes one).
let link = match &c.link_file {
Some(f) => clean_link(&std::fs::read_to_string(f).with_context(|| format!("reading {f}"))?)?,
None => last_link(paths, name).unwrap_or_default(),
};
let mut args: Vec<String> = vec![
"--cookies".into(),
cookies.display().to_string(),
"--write-file".into(),
links.display().to_string(),
"--resources".into(),
resources(c.resources).into(),
];
let mut env = vec![("WB_LINK".to_owned(), link)];
if c.upstream == Upstream::Proxy {
// From the parsed address, as Tor's: the listener's own, or loopback for a wildcard.
let l = &cfg.proxy.listener;
let host = match l.address.parse::<std::net::IpAddr>().context("proxy.listener.address is not an IP address")? {
ip if ip.is_unspecified() => "127.0.0.1".to_owned(),
std::net::IpAddr::V6(v6) => format!("[{v6}]"),
v4 => v4.to_string(),
};
args.extend(["--upstream-socks".into(), format!("{host}:{}", l.port)]);
if let Some((user, password)) = proxy_login {
args.extend(["--upstream-user".into(), user]);
env.push(("WB_UPSTREAM_PASS".into(), password));
}
}
Ok(Some(UnitSpec {
name: format!("{CREATOR_PREFIX}{name}"),
program,
generation: format!("{args:?}{}", env[0].1),
args,
env,
cwd: None,
}))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn links_are_one_clean_line() {
assert_eq!(clean_link(" https://stream.wb.ru/room/abc \n").unwrap(), "https://stream.wb.ru/room/abc");
assert!(clean_link(" \n").is_err());
assert!(clean_link("a\u{7}b").is_err());
}
#[test]
fn files_are_only_plain_names_in_the_state_directory() {
let paths = Paths::new("state");
assert_eq!(state_file(&paths, "laptop", ".link").unwrap(), std::path::Path::new("state/whitelist-bypass/laptop.link"));
for bad in [r"C:\Windows\System32\x", "/etc/x", "../x", "..", "a/b", r"a\b", "CON", "nul", "COM1", ""] {
assert!(state_file(&paths, bad, ".link").is_err(), "{bad}");
}
}
}
+2
View File
@@ -56,6 +56,8 @@
openssh
# wireproxy-awg and whitelist-bypass, built from source (Go cross-compiles).
go
# The setup program (tools/installer.nsi).
nsis
];
buildInputs = guiLibs;
LD_LIBRARY_PATH = pkgs.lib.makeLibraryPath guiLibs;
+10 -3
View File
@@ -1,4 +1,4 @@
The desktop app: Proxy Suite now has a window and a tray icon, besides `proxy-ctl`.
The desktop app: Proxy Suite now has a window and a tray icon, besides `proxy-ctl`; and a setup program.
**Not yet run on real Windows.** It was built and tested on Linux, and under Wine where Wine can (it cannot draw the app's text: its DirectWrite does not match fonts). See "What has been verified" in the README, and please report what happens on yours.
@@ -6,10 +6,12 @@ The desktop app: Proxy Suite now has a window and a tray icon, besides `proxy-ct
- **Overview:** the local proxy, the DPI bypass and the Telegram proxy, their states and switches; what the service warns of.
- **DPI bypass:** zapret with Flowseal's presets (the preset, game traffic) or zapret2 (learning, IPv6); your own sites to handle or leave alone.
- **Telegram proxy:** on or off, its tg:// links to open in Telegram or copy to a phone, other devices allowed or not, port and fake-TLS domain.
- **Whitelist bypass:** joiners and creators, added or removed; a joiner's call link given, a creator's call link copied, its login given (a cookies file, or DION's and Bitrix's email and password).
- **Outbounds:** add one from a link; pin, test delays, leave out, remove; the routing mode; subscriptions.
- **Logs:** every service's, live.
- **Settings:** every option, as JSON, checked by the service before it is saved.
- **Components:** what is installed, at which version.
- **Icon:** the app has one now (window, taskbar, Start Menu, Settings → Apps).
- **Tray:** a shield, green while things work, amber when one failed, grey when all is off; its menu switches the proxy, the DPI bypass and the Telegram proxy.
- **System proxy:** the app can point Windows' proxy setting (browsers, most programs) at the local proxy while it runs, and puts yours back after.
@@ -20,16 +22,21 @@ The desktop app: Proxy Suite now has a window and a tray icon, besides `proxy-ct
- The SSH tunnel (`sshProxy`): Windows' own OpenSSH as a SOCKS listener for other programs, and, with `asOutbound`, an outbound of the proxy. Needs Windows' "OpenSSH Client" (there by default since Windows 10 1809).
- Tor (`tor`): the Tor Project's own Windows build, with bridges (obfs4, webtunnel, snowflake, meek, conjure) and, with `asOutbound`, an outbound of the proxy.
- AmneziaWG as outbounds (`amneziaWg`): profiles from a `.conf`, an AmneziaVPN `vpn://` link or settings; `"userspace"` runs wireproxy-awg (AmneziaWG's obfuscation kept, no driver), `"singBox"` plain WireGuard. WARP devices can be either.
- whitelist-bypass (`whitelistBypass`): its creators and joiners, built from upstream's source; a joiner is an outbound of the proxy through a video call (WB Stream, Telemost, DION, Bitrix), a creator the call's other end. `proxy-ctl wl join|auth|link|new`.
- WARP (`warp`, as a sing-box outbound): devices registered with Cloudflare as wgcf registers them (through the local proxy first, where its API is blocked), or profiles given; several grouped as `warp`.
- What is not on Windows yet (the kill switch, AmneziaWG, WARP, Tor, the SSH tunnel, …) is no longer accepted silently: the service warns while it is configured, and the app shows it.
- The service names zapret's presets and gives tg-ws-proxy's links (`proxy-ctl zapret presets`, `proxy-ctl tg link`).
- A setup program (`…-setup.exe`, English and Russian), with an uninstaller in Settings → Apps; `install.cmd` from the zip makes that entry too. Uninstalling removes WinDivert's driver service too, when it is the suite's.
- The programs carry their C runtime: no Visual C++ Redistributable needed.
- Built and published by Gitea Actions.
### Install
Download `ProxySuite-0.2.0-pre.1-windows-x64.zip`; its SHA-256 is in the `.sha256` file next to it. Unzip, run `install.cmd` as administrator, then open **Proxy Suite** from the Start Menu. Needs 64-bit Windows 10 (1903 or later) or 11.
Download `ProxySuite-0.2.0-pre.1-windows-x64-setup.exe` and run it (its SHA-256 is in the `.sha256` file next to it); SmartScreen may warn of an unknown publisher, the programs are not signed yet (**More info** → **Run anyway**). It installs everything, starts the service and the app, and adds Proxy Suite to **Settings → Apps**, where its **Uninstall** is. Nothing has to be installed first: the programs carry their C runtime now. Needs 64-bit Windows 10 (1903 or later) or 11.
The zip is still there, the same files with `install.cmd`.
### Not yet
AmneziaWG as a system-wide VPN, Tor's onion service, whitelist-bypass, the kill switch, server inbounds, the XRay-only backend, zapret2's extended detection and the z2k strategies.
AmneziaWG as a system-wide VPN, Tor's onion service, the kill switch, server inbounds, the XRay-only backend, zapret2's extended detection and the z2k strategies.
### Note
Unlike upstream, the signed-in user may change every setting by default (`userControl`), except the ones that could run programs or read files as SYSTEM: those always need an administrator. On a shared computer, restrict `userControl.scopes`.
+2 -1
View File
@@ -5,6 +5,7 @@
#
# tools/build-tg-ws-proxy.sh OUT_DIR (needs curl, git, unzip, pip)
set -euo pipefail
. "$(dirname "$0")/lib.sh"
OUT=$(realpath -m "${1:?output directory}")
cd "$(dirname "$0")"
PY_VERSION=3.12.10
@@ -25,7 +26,7 @@ pip download -q --require-hashes --no-deps --only-binary=:all: --platform win_am
mkdir -p "$OUT/python/Lib/site-packages"
for w in "$WORK"/wheels/*.whl; do unzip -q -o "$w" -d "$OUT/python/Lib/site-packages"; done
git -c advice.detachedHead=false clone -q --depth 1 --branch "$TG_TAG" https://github.com/Flowseal/tg-ws-proxy "$WORK/src"
clone_tag https://github.com/Flowseal/tg-ws-proxy "$TG_TAG" "$WORK/src"
[ "$(git -C "$WORK/src" rev-parse HEAD)" = "$TG_COMMIT" ] || { echo "tag $TG_TAG moved off $TG_COMMIT"; exit 1; }
cp -r "$WORK/src/proxy" "$WORK/src/utils" "$WORK/src/LICENSE" "$OUT/app/"
+48
View File
@@ -0,0 +1,48 @@
#!/usr/bin/env bash
# whitelist-bypass's headless ends for Windows (creators and joiners: a tunnel through the media
# servers of video calls), built from upstream's tag as upstream's pkgs/whitelist-bypass.nix
# builds them: the call link, the local proxy's password and a joiner's SOCKS password read
# from the environment by default, never the command line (any local user reads that).
#
# tools/build-whitelist-bypass.sh OUT_DIR [GOOS] (needs git, go, sed; GOOS: windows)
set -euo pipefail
. "$(dirname "$0")/lib.sh"
OUT=$(realpath -m "${1:?output directory}")
GOOS=${2:-windows}
VERSION=0.4.4
COMMIT=7c19a7ec40900940fe0c43ea1db7768ee632393d
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
clone_tag https://github.com/kulikov0/whitelist-bypass "v$VERSION" "$WORK/src"
[ "$(git -C "$WORK/src" rev-parse HEAD)" = "$COMMIT" ] || { echo "tag v$VERSION moved off $COMMIT"; exit 1; }
cd "$WORK/src"
# upstream's postPatch: flag.String("NAME", "", …) defaults to os.Getenv("VAR").
env_default() {
local file="headless/$1/main.go"
grep -q "flag.String(\"$2\", \"\"," "$file" || { echo "$file has no flag $2 to patch"; exit 1; }
sed -i "s|flag.String(\"$2\", \"\",|flag.String(\"$2\", os.Getenv(\"$3\"),|" "$file"
}
for p in vk telemost wbstream dion bitrix; do env_default "$p" upstream-pass WB_UPSTREAM_PASS; done
for p in bitrix dion dion-joiner wbstream wbstream-joiner; do env_default "$p" room WB_LINK; done
for p in telemost-joiner wbstream-joiner dion-joiner bitrix-joiner; do env_default "$p" socks-pass WB_SOCKS_PASS; done
env_default bitrix-joiner link WB_LINK
env_default telemost tm-link WB_LINK
env_default telemost-joiner tm-link WB_LINK
env_default vk vk-link WB_LINK
export GOTOOLCHAIN=local CGO_ENABLED=0 GOOS GOARCH=amd64
ext=
[ "$GOOS" = windows ] && ext=.exe
rm -rf "$OUT" && mkdir -p "$OUT"
# Upstream's names (build-headless.sh): headless-<platform>-creator and -joiner.
for p in vk telemost wbstream dion bitrix; do
go build -trimpath -ldflags "-s -w" -o "$OUT/headless-$p-creator$ext" "./headless/$p"
done
for p in telemost wbstream dion bitrix; do
go build -trimpath -ldflags "-s -w" -o "$OUT/headless-$p-joiner$ext" "./headless/$p-joiner"
done
cp LICENSE "$OUT/"
echo "$VERSION" >"$OUT/.version"
echo "whitelist-bypass $VERSION ($GOOS) in $OUT"
+2 -1
View File
@@ -6,6 +6,7 @@
#
# tools/build-wireproxy-awg.sh OUT_DIR [GOOS] (needs git, go, patch; GOOS: windows)
set -euo pipefail
. "$(dirname "$0")/lib.sh"
OUT=$(realpath -m "${1:?output directory}")
GOOS=${2:-windows}
cd "$(dirname "$0")"
@@ -15,7 +16,7 @@ PATCHES=$(realpath ../../pkgs/patches)
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
git -c advice.detachedHead=false clone -q --depth 1 --branch "v$VERSION" https://github.com/artem-russkikh/wireproxy-awg "$WORK/src"
clone_tag https://github.com/artem-russkikh/wireproxy-awg "v$VERSION" "$WORK/src"
[ "$(git -C "$WORK/src" rev-parse HEAD)" = "$COMMIT" ] || { echo "tag v$VERSION moved off $COMMIT"; exit 1; }
cd "$WORK/src"
patch -s -p1 <"$PATCHES/wireproxy-awg-fwmark.patch"
+2 -1
View File
@@ -6,7 +6,7 @@
#
# Before the shot, SHOT_STEPS does what it lists, in order, each followed by a moment for the
# app to answer: "click:X,Y" (screen points), "type:TEXT" (no spaces), "key:NAME" (xdotool's
# names, e.g. ctrl+a), "wait:SECONDS".
# names, e.g. ctrl+a), "scroll:X,Y" (ten steps down, there), "wait:SECONDS".
set -euo pipefail
OUT=$(realpath -m "${1:?the screenshot, a .png}"); shift
WAIT=6
@@ -36,6 +36,7 @@ x() { DISPLAY=":$n" "$XDOTOOL/bin/xdotool" "$@"; }
for step in ${SHOT_STEPS:-}; do
case $step in
click:*) p=${step#click:}; x mousemove "${p%,*}" "${p#*,}" click 1 ;;
scroll:*) p=${step#scroll:}; x mousemove "${p%,*}" "${p#*,}" click --repeat 10 5 ;;
type:*) x type --delay 40 "${step#type:}" ;;
key:*) x key "${step#key:}" ;;
wait:*) sleep "${step#wait:}" ;;
+126
View File
@@ -0,0 +1,126 @@
; Proxy Suite's setup program. It unpacks the release into its temporary folder and runs the
; release's own `proxy-suite-service.exe install` from there, as install.cmd does from the zip:
; that stops what runs, copies the release into Program Files, registers the service, PATH, the
; Start Menu entry, the app at sign-in and the entry in Settings > Apps, and starts it all.
; Unpacked straight into Program Files instead, an upgrade would find its files in use.
; The uninstaller is that entry's: uninstall.cmd, which the release carries.
;
; makensis -INPUTCHARSET UTF8 -DVERSION=0.2.0-pre.1 -DVERSION4=0.2.0.0 -DRELEASE=<release dir>
; -DICON=crates/ps-gui/assets/proxy-suite.ico -DOUT=<setup.exe> tools/installer.nsi
;
; Everything the programs need is in the release: the C runtime is linked in, WinDivert, wintun,
; Python and the rest are components. Windows' OpenSSH Client (the SSH tunnel) is Windows' own:
; offered, unchecked, for a Windows that had it removed.
Unicode true
ManifestDPIAware true
RequestExecutionLevel admin
; Solid, with a dictionary that keeps the build's memory modest: the release is ~600 MB of
; programs, many alike (whitelist-bypass's nine).
SetCompressor /SOLID /FINAL lzma
SetCompressorDictSize 32
!include MUI2.nsh
!include LogicLib.nsh
!include x64.nsh
!include WinVer.nsh
Name "Proxy Suite"
OutFile "${OUT}"
InstallDir "$PROGRAMFILES64\ProxySuite"
BrandingText "Proxy Suite ${VERSION}"
ShowInstDetails show
VIProductVersion "${VERSION4}"
VIAddVersionKey /LANG=0 "ProductName" "Proxy Suite"
VIAddVersionKey /LANG=0 "ProductVersion" "${VERSION}"
VIAddVersionKey /LANG=0 "FileVersion" "${VERSION}"
VIAddVersionKey /LANG=0 "FileDescription" "Proxy Suite setup"
VIAddVersionKey /LANG=0 "LegalCopyright" "MIT License"
!define MUI_ICON "${ICON}"
!define MUI_ABORTWARNING
!define MUI_FINISHPAGE_TITLE "$(FinishTitle)"
!define MUI_FINISHPAGE_TEXT "$(FinishText)"
!define MUI_FINISHPAGE_NOAUTOCLOSE
!insertmacro MUI_PAGE_WELCOME
!insertmacro MUI_PAGE_LICENSE "${RELEASE}/LICENSE"
!insertmacro MUI_PAGE_COMPONENTS
!insertmacro MUI_PAGE_INSTFILES
!insertmacro MUI_PAGE_FINISH
; The first is the default; Windows' own language picks among them.
!insertmacro MUI_LANGUAGE "English"
!insertmacro MUI_LANGUAGE "Russian"
LangString NeedX64 ${LANG_ENGLISH} "Proxy Suite needs 64-bit Windows."
LangString NeedX64 ${LANG_RUSSIAN} "Для Proxy Suite нужна 64-битная Windows."
LangString NeedBuild ${LANG_ENGLISH} "Proxy Suite needs Windows 10 version 1903 or later, or Windows 11."
LangString NeedBuild ${LANG_RUSSIAN} "Для Proxy Suite нужна Windows 10 версии 1903 или новее либо Windows 11."
LangString Failed ${LANG_ENGLISH} "Setup did not finish: the details are in the list above. Nothing that was installed before is lost."
LangString Failed ${LANG_RUSSIAN} "Установка не завершена: подробности в списке выше. Установленное ранее не потеряно."
LangString MainName ${LANG_ENGLISH} "Proxy Suite"
LangString MainName ${LANG_RUSSIAN} "Proxy Suite"
LangString MainDesc ${LANG_ENGLISH} "The service, the app, proxy-ctl and every component (sing-box, XRay, zapret, zapret2, Tor, tg-ws-proxy, wireproxy-awg, whitelist-bypass), into Program Files. Settings already made are kept."
LangString MainDesc ${LANG_RUSSIAN} "Служба, приложение, proxy-ctl и все компоненты (sing-box, XRay, zapret, zapret2, Tor, tg-ws-proxy, wireproxy-awg, whitelist-bypass) в Program Files. Сделанные ранее настройки сохраняются."
LangString SshName ${LANG_ENGLISH} "Windows OpenSSH Client"
LangString SshName ${LANG_RUSSIAN} "Клиент OpenSSH Windows"
LangString SshDesc ${LANG_ENGLISH} "For the SSH tunnel only. Windows 10 1809 and later have it already; this adds it from Windows Update where it was removed."
LangString SshDesc ${LANG_RUSSIAN} "Нужен только для SSH-туннеля. В Windows 10 1809 и новее он уже есть; здесь он добавляется из Центра обновления, если его удалили."
LangString SshThere ${LANG_ENGLISH} "The OpenSSH Client is there already."
LangString SshThere ${LANG_RUSSIAN} "Клиент OpenSSH уже установлен."
LangString SshFailed ${LANG_ENGLISH} "The OpenSSH Client could not be added (is Windows Update reachable?). Everything else works without it; add it later in Settings > System > Optional features."
LangString SshFailed ${LANG_RUSSIAN} "Не удалось добавить клиент OpenSSH (доступен ли Центр обновления?). Всё остальное работает без него; его можно добавить позже: Параметры > Система > Дополнительные компоненты."
LangString FinishTitle ${LANG_ENGLISH} "Proxy Suite is installed"
LangString FinishTitle ${LANG_RUSSIAN} "Proxy Suite установлен"
LangString FinishText ${LANG_ENGLISH} "Its service runs, and the app is in the tray (the shield) and the Start Menu; it starts at every sign-in.$\r$\n$\r$\nIn a new terminal: proxy-ctl status.$\r$\n$\r$\nTo remove it: Settings > Apps > Proxy Suite."
LangString FinishText ${LANG_RUSSIAN} "Служба запущена, приложение в трее (щит) и в меню «Пуск»; оно запускается при каждом входе в систему.$\r$\n$\r$\nВ новом терминале: proxy-ctl status.$\r$\n$\r$\nУдаление: Параметры > Приложения > Proxy Suite."
Function .onInit
${IfNot} ${RunningX64}
MessageBox MB_ICONSTOP "$(NeedX64)" /SD IDOK
Abort
${EndIf}
${IfNot} ${AtLeastBuild} 18362
MessageBox MB_ICONSTOP "$(NeedBuild)" /SD IDOK
Abort
${EndIf}
InitPluginsDir
FunctionEnd
Section "$(MainName)" SecMain
SectionIn RO
SetOutPath "$PLUGINSDIR\release"
File /r "${RELEASE}/*"
DetailPrint "proxy-suite-service install"
nsExec::ExecToLog '"$PLUGINSDIR\release\proxy-suite-service.exe" install'
Pop $0
; Out of the folder, so that it goes with $PLUGINSDIR when setup ends.
SetOutPath "$TEMP"
${If} $0 != 0
DetailPrint "$(Failed)"
MessageBox MB_ICONSTOP "$(Failed)" /SD IDOK
SetErrorLevel 2
Abort
${EndIf}
SectionEnd
Section /o "$(SshName)" SecSsh
; This setup runs as a 32-bit program: Sysnative is the real System32.
${If} ${FileExists} "$WINDIR\Sysnative\OpenSSH\ssh.exe"
DetailPrint "$(SshThere)"
${Else}
nsExec::ExecToLog '"$WINDIR\Sysnative\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -NonInteractive -Command "Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0 | Out-Null; if (-not (Test-Path $$env:SystemRoot\System32\OpenSSH\ssh.exe)) { exit 1 }"'
Pop $0
${If} $0 != 0
DetailPrint "$(SshFailed)"
MessageBox MB_ICONEXCLAMATION "$(SshFailed)" /SD IDOK
${EndIf}
${EndIf}
SectionEnd
!insertmacro MUI_FUNCTION_DESCRIPTION_BEGIN
!insertmacro MUI_DESCRIPTION_TEXT ${SecMain} "$(MainDesc)"
!insertmacro MUI_DESCRIPTION_TEXT ${SecSsh} "$(SshDesc)"
!insertmacro MUI_FUNCTION_DESCRIPTION_END
+30
View File
@@ -0,0 +1,30 @@
# Shared by tools/build-*.sh (sourced).
# clone_tag URL TAG DIR: a shallow clone of TAG into DIR, tried three times: a transfer that
# stalls (GitHub's sometimes do) is given up after a minute, a connection that hangs by curl's
# own timeout; a slow one is waited for. With SRC_CACHE set, a clone made is kept there and
# the next build copies it rather than fetching it again (the scripts check its commit either
# way).
clone_tag() {
local url=$1 tag=$2 dir=$3 try cached=""
if [ -n "${SRC_CACHE:-}" ]; then
cached="$SRC_CACHE/$(basename "$url")@$tag"
if [ -d "$cached/.git" ]; then
# Its files as its commit has them, whatever happened to the copy since.
rm -rf "$dir" && cp -a "$cached" "$dir" && git -C "$dir" reset -q --hard && git -C "$dir" clean -qfdx && return 0
fi
fi
for try in 1 2 3; do
rm -rf "$dir"
if git -c advice.detachedHead=false -c http.lowSpeedLimit=1000 -c http.lowSpeedTime=60 \
clone -q --depth 1 --branch "$tag" "$url" "$dir"; then
if [ -n "$cached" ]; then
mkdir -p "$SRC_CACHE" && rm -rf "$cached.tmp" && cp -a "$dir" "$cached.tmp" && mv "$cached.tmp" "$cached"
fi
return 0
fi
echo "cloning $url ($tag) failed, try $try of 3" >&2
sleep 5
done
return 1
}
+109
View File
@@ -0,0 +1,109 @@
#!/usr/bin/env python3
"""The app's icon, crates/ps-gui/assets/proxy-suite.ico: a shield with a check mark (the tray's
shield, in the app's blue), drawn here at every size Windows asks for, antialiased, with no
image library. The .ico it writes is committed; run this again only to change it.
python3 -I tools/make-icon.py
"""
import math
import pathlib
import struct
import zlib
BLUE = (37, 99, 235)
WHITE = (255, 255, 255)
SIZES = [16, 20, 24, 32, 40, 48, 64, 256]
SAMPLES = 4 # per axis, per pixel
def cubic(p0, p1, p2, p3, steps=24):
out = []
for i in range(1, steps + 1):
t = i / steps
u = 1 - t
out.append(tuple(u**3 * a + 3 * u * u * t * b + 3 * u * t * t * c + t**3 * d for a, b, c, d in zip(p0, p1, p2, p3)))
return out
# Lucide's shield, on its 24-unit grid, as a polygon.
SHIELD = [(12.0, 2.2)]
SHIELD += cubic((12.0, 2.2), (14.6, 4.4), (17.2, 5.1), (19.8, 5.1))
SHIELD += [(19.8, 13.0)]
SHIELD += cubic((19.8, 13.0), (19.8, 18.2), (16.4, 20.6), (12.0, 22.0))
SHIELD += cubic((12.0, 22.0), (7.6, 20.6), (4.2, 18.2), (4.2, 13.0))
SHIELD += [(4.2, 5.1)]
SHIELD += cubic((4.2, 5.1), (6.8, 5.1), (9.4, 4.4), (12.0, 2.2))
CHECK = [(8.3, 12.3), (11.0, 15.0), (15.9, 9.6)]
CHECK_HALF_WIDTH = 1.15
def inside(poly, x, y):
hit = False
for (x1, y1), (x2, y2) in zip(poly, poly[1:] + poly[:1]):
if (y1 > y) != (y2 > y) and x < x1 + (y - y1) * (x2 - x1) / (y2 - y1):
hit = not hit
return hit
def near_check(x, y):
for (x1, y1), (x2, y2) in zip(CHECK, CHECK[1:]):
dx, dy = x2 - x1, y2 - y1
t = max(0.0, min(1.0, ((x - x1) * dx + (y - y1) * dy) / (dx * dx + dy * dy)))
if math.hypot(x - (x1 + t * dx), y - (y1 + t * dy)) <= CHECK_HALF_WIDTH:
return True
return False
def render(size):
"""RGBA rows, top first."""
rows = []
scale = 24 / size
for py in range(size):
row = bytearray()
for px in range(size):
shield = check = 0
for sy in range(SAMPLES):
for sx in range(SAMPLES):
x = (px + (sx + 0.5) / SAMPLES) * scale
y = (py + (sy + 0.5) / SAMPLES) * scale
if inside(SHIELD, x, y):
shield += 1
check += near_check(x, y)
n = SAMPLES * SAMPLES
alpha = shield / n
if shield:
w = check / shield
colour = [round(b * (1 - w) + f * w) for b, f in zip(BLUE, WHITE)]
else:
colour = [0, 0, 0]
row += bytes(colour + [round(alpha * 255)])
rows.append(bytes(row))
return rows
def png(size, rows):
def chunk(kind, data):
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data))
raw = b"".join(b"\x00" + r for r in rows)
ihdr = struct.pack(">IIBBBBB", size, size, 8, 6, 0, 0, 0)
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(raw, 9)) + chunk(b"IEND", b"")
def main():
images = [png(s, render(s)) for s in SIZES]
header = struct.pack("<HHH", 0, 1, len(images))
offset = 6 + 16 * len(images)
entries = b""
for s, data in zip(SIZES, images):
entries += struct.pack("<BBBBHHII", s % 256, s % 256, 0, 0, 1, 32, len(data), offset)
offset += len(data)
out = pathlib.Path(__file__).resolve().parent.parent / "crates/ps-gui/assets/proxy-suite.ico"
out.parent.mkdir(exist_ok=True)
out.write_bytes(header + entries + b"".join(images))
print(f"{out}: {out.stat().st_size} bytes, sizes {SIZES}")
if __name__ == "__main__":
main()
+20 -6
View File
@@ -1,22 +1,26 @@
#!/usr/bin/env bash
# The release: ProxySuite-<version>-windows-x64.zip in dist/, with the programs (the service,
# proxy-ctl, the app), every component (fetched and verified), the install scripts, the README
# and the licenses.
# The release, in dist/: ProxySuite-<version>-windows-x64-setup.exe, the setup program, and
# ProxySuite-<version>-windows-x64.zip, the same unpacked with install.cmd. Both hold the
# programs (the service, proxy-ctl, the app), every component (fetched and verified), the
# install scripts, the README and the licenses.
#
# nix develop --command tools/package.sh (needs curl, git, unzip, zip, pip, go; nix
# for the app's shader compiler, tools/fxc-wine.sh)
# nix develop --command tools/package.sh (needs curl, git, unzip, zip, pip, go, makensis;
# nix for the app's shader compiler, tools/fxc-wine.sh)
set -euo pipefail
cd "$(dirname "$0")/.."
VERSION=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)
NAME=ProxySuite-$VERSION-windows-x64
DIST=dist/$NAME
CACHE=${CACHE:-${XDG_CACHE_HOME:-$HOME/.cache}/proxy-suite-windows}
# The sources tools/build-*.sh clone, kept for the next build.
export SRC_CACHE=$CACHE/src
rm -rf "$DIST" "dist/$NAME.zip"
mkdir -p "$DIST/components"
echo "== components"
tools/build-tg-ws-proxy.sh "$DIST/components/tg-ws-proxy"
tools/build-wireproxy-awg.sh "$DIST/components/wireproxy-awg" windows
tools/build-whitelist-bypass.sh "$DIST/components/whitelist-bypass" windows
cargo build -q --release -p ps-service
target/release/proxy-suite-service stage-components --to "$DIST/components" --cache "$CACHE"
rm -rf "$DIST"/components/*.old "$DIST"/components/*.staging
@@ -29,6 +33,8 @@ GPUI_FXC_PATH="$PWD/tools/fxc-wine.sh" cargo xwin build -q --release -p ps-gui -
for exe in proxy-suite-service proxy-ctl proxy-suite; do
cp "target/x86_64-pc-windows-msvc/release/$exe.exe" "$DIST/"
done
# Its build only warns without its icon (cargo -q shows no warning): the release has it.
llvm-readobj --coff-resources "$DIST/proxy-suite.exe" | grep 'Type: ICON' >/dev/null || { echo "proxy-suite.exe has no icon"; exit 1; }
cp ../LICENSE README.md "$DIST/"
cp tools/install.cmd tools/uninstall.cmd "$DIST/"
@@ -52,6 +58,7 @@ echo "== THIRD-PARTY.md"
echo "- **zapret2** (winws2.exe, its Lua) and **nfqws2-keenetic** (its strategies, lists, blobs): MIT, https://github.com/bol-van/zapret2, https://github.com/nfqws/nfqws2-keenetic"
echo "- **wintun** (inside sing-box): WireGuard's prebuilt-binary license, https://www.wintun.net"
echo "- **amneziawg-go** (inside wireproxy-awg, with the suite's patch): MIT, https://github.com/amnezia-vpn/amneziawg-go"
echo "- **Go modules** (inside wireproxy-awg and whitelist-bypass, e.g. Pion's WebRTC): as each project's go.mod pins them, under their own licenses (MIT, BSD-3-Clause, Apache-2.0)"
echo "- **lyrebird** and **conjure** (Tor's pluggable transports, in the Expert Bundle): their licenses are in components/tor/docs"
echo "- **CPython $( sed 's/.*+py//' "$DIST/components/tg-ws-proxy/.version" )** (tg-ws-proxy): PSF License, https://www.python.org"
echo "- **The programs themselves** (proxy-suite-service, proxy-ctl, proxy-suite) are built from"
@@ -71,4 +78,11 @@ echo "== THIRD-PARTY.md"
echo "== zip"
(cd dist && zip -qr "$NAME.zip" "$NAME")
(cd dist && sha256sum "$NAME.zip" | tee "$NAME.zip.sha256")
du -h "dist/$NAME.zip"
echo "== setup"
# Windows' file version takes four numbers: 0.2.0-pre.1 is 0.2.0.0.
VERSION4=$(sed 's/-.*//' <<<"$VERSION").0
rm -f "dist/$NAME-setup.exe"
makensis -V2 -INPUTCHARSET UTF8 -DVERSION="$VERSION" -DVERSION4="$VERSION4" -DRELEASE="$PWD/$DIST" -DICON="$PWD/crates/ps-gui/assets/proxy-suite.ico" -DOUT="$PWD/dist/$NAME-setup.exe" tools/installer.nsi
(cd dist && sha256sum "$NAME-setup.exe" | tee "$NAME-setup.exe.sha256")
du -h "dist/$NAME.zip" "dist/$NAME-setup.exe"
+85
View File
@@ -0,0 +1,85 @@
#!/usr/bin/env bash
# The setup program under Wine: a silent install into Program Files (every file, the
# components' manifests among them), the entry in Settings > Apps, the service registered and
# answering over its pipe; the same setup again over the running install (an upgrade); then the
# entry's quiet uninstall, after which the service, the files and the entry are gone.
#
# nix shell nixpkgs#wineWow64Packages.stable -c tools/wine-setup-test.sh dist/ProxySuite-<version>-windows-x64-setup.exe [RELEASE_DIR]
#
# RELEASE_DIR (the unpacked release the setup was made of): its files are compared with the
# installed ones.
set -euo pipefail
SETUP=$(realpath "${1:?the setup program}")
REL=${2:+$(realpath "$2")}
WORK=$(mktemp -d)
export WINEPREFIX=${WINEPREFIX:-$WORK/prefix} WINEDEBUG=-all
trap 'wineserver -k 2>/dev/null || true; rm -rf "$WORK"' EXIT
wineboot -i >/dev/null 2>&1 || true
for key in Tcpip Tcpip6; do
wine reg add "HKLM\\SYSTEM\\CurrentControlSet\\Services\\$key\\Parameters\\Interfaces" /f >/dev/null 2>&1
done
PF="$WINEPREFIX/drive_c/Program Files/ProxySuite"
KEY='HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall\ProxySuite'
fail() { echo "FAIL: $*"; exit 1; }
state() { local st; st=$(wine sc query ProxySuite 2>/dev/null || true); st=${st//$'\r'/}; grep STATE <<<"$st" | grep -o '[A-Z_]*$' || echo NONE; }
# Wine's manager often fails the first start right after a create (wine-install-test.sh says
# more); a second start works.
running() {
local s last=""
for _ in $(seq 60); do
s=$(state)
[ "$s" = "$last" ] || echo " $s"
last=$s
[ "$s" = RUNNING ] && return 0
[ "$s" = STOPPED ] && { wine sc start ProxySuite >/dev/null 2>&1 || true; }
sleep 3
done
return 1
}
echo "== setup /S"
wine "$SETUP" /S && rc=0 || rc=$?
echo " exit code $rc"
[ "$rc" = 0 ] || fail "setup exited with $rc"
[ -f "$PF/proxy-suite-service.exe" ] || fail "nothing in Program Files"
ls "$PF" | sed 's/^/ /'
if [ -n "$REL" ]; then
# Every file of the release, dotfiles too (the components' .files.json and .version).
missing=$(cd "$REL" && find . -type f | while read -r f; do [ -f "$PF/$f" ] || echo "$f"; done)
[ -z "$missing" ] || fail "not installed: $missing"
echo " every file of the release is there ($(cd "$REL" && find . -type f | wc -l))"
fi
ls "$PF"/components/*/.files.json >/dev/null || fail "no component manifests"
echo "== Settings > Apps"
entry=$(wine reg query "$KEY" 2>/dev/null | tr -d '\r') || fail "no uninstall entry"
sed 's/^/ /' <<<"$entry"
for v in DisplayName DisplayVersion UninstallString QuietUninstallString InstallLocation EstimatedSize; do
grep -q "$v" <<<"$entry" || fail "the entry has no $v"
done
echo "== the service"
running || fail "the service is $(state)"
for _ in $(seq 30); do wine "$PF/proxy-ctl.exe" status >/dev/null 2>&1 && break; sleep 1; done
wine "$PF/proxy-ctl.exe" components | tr -d '\r' | sed 's/^/ /' || fail "no answer over the pipe"
echo "== setup /S again, over the running install"
wine "$SETUP" /S && rc=0 || rc=$?
[ "$rc" = 0 ] || fail "the upgrade exited with $rc"
running || fail "after the upgrade the service is $(state)"
for _ in $(seq 30); do wine "$PF/proxy-ctl.exe" status >/dev/null 2>&1 && break; sleep 1; done
wine "$PF/proxy-ctl.exe" status >/dev/null 2>&1 || fail "no answer after the upgrade"
echo " upgraded, running, answering"
echo "== the entry's quiet uninstall"
quiet=$(wine reg query "$KEY" /v QuietUninstallString | tr -d '\r' | sed -n 's/.*REG_SZ *//p')
echo " $quiet"
# Its command line, as Windows would run it: the quoted program, then its argument.
prog=${quiet#\"}; prog=${prog%%\"*}
wine "$prog" uninstall
sleep 6
[ "$(state)" = NONE ] || fail "the service is still there: $(state)"
wine reg query "$KEY" >/dev/null 2>&1 && fail "the entry is still there"
[ ! -e "$PF" ] || fail "Program Files\\ProxySuite is still there: $(ls "$PF")"
echo "OK: installed, upgraded and removed by the setup program and its entry"