feat: better inbounds user management

This commit is contained in:
FUFSoB committed 2026-10-14 21:41:49 +05:00
1 parent 2f8414455d
commit 9f7ad91f39
47 files changed
+6767 -78

No files matched your search

+24 -1
View File
@@ -24,7 +24,7 @@ Bundles [sing-box](https://github.com/SagerNet/sing-box), [XRay](https://github.
- AmneziaWG 1.x–3.x from `.conf`, `vpn://` or Nix
- Cloudflare WARP, Tor (with bridges and an onion service), an SSH tunnel and a Telegram proxy
- Tunnels through video-call servers, to get past mobile internet whitelists
- Server inbounds (XRay protocols, hysteria2, AmneziaWG) with share links, QR codes, subscriptions and traffic stats
- Server inbounds (XRay protocols, hysteria2, AmneziaWG) with share links, QR codes, subscriptions in each client's format (links, Clash, sing-box, a web page) and traffic stats; users with expiry, traffic, device and speed limits
- A desktop GUI with a tray icon, the `proxy-ctl` CLI and the `proxy-tui` terminal UI
## Setup
@@ -279,5 +279,28 @@ Changes and secrets need root or the userControl group.
inbounds rm <tag> remove a runtime listener
inbounds show <tag> a runtime listener's JSON
inbounds online who is online, and when others were last seen
With inbounds.manager (users' policies; the API proxy-ctl and bots use):
inbounds users [list] [--json] users, whether they may connect, traffic, expiry
inbounds users show <name> [--json] one user: policy, traffic, online, subscription
inbounds users add <name> [...] [policy flags]
add a runtime user with a policy
inbounds users set <name> [--expires 2026-12-31|+30d] [--on-hold 30d] [--traffic 50G]
[--period monthly] [--ips 2] [--speed 20M/5M] [--enable|--disable] [--meta key=value]...
change a user's policy (declared users too);
--on-hold: a term that starts on the first connection
inbounds users unset <name> <expires|hold|traffic|period|ips|speed|meta|enabled>...
back to the config's value, or none
inbounds users enable|disable <name> switch a user on or off
inbounds users reset <name> start their traffic over
inbounds users extend <name> 30d [--reset]
move the expiry on (from now, or from it if later;
on hold: a longer term); --reset: traffic anew too
inbounds users extend <name> --until <time> [--reset]
inbounds users rotate-sub <name> a new subscription URL, the old one stops answering
inbounds bans [rm <address>] addresses banned past a user's ipLimit
inbounds export [file] [--no-stats] users, policies, keys and traffic, to move them
inbounds import <file|-> [--replace] take them in on this server
inbounds events [N] what the manager did and told its webhooks
```
<!-- proxy-ctl-help:end -->
+366
View File
@@ -113,10 +113,41 @@ Part of the [proxy-suite options reference](./index.md).
- [users](#services-proxy-suite-inbounds-listeners-name-users)
- [via](#services-proxy-suite-inbounds-listeners-name-via)
- [xrayJson](#services-proxy-suite-inbounds-listeners-name-xrayjson)
- manager
- [enable](#services-proxy-suite-inbounds-manager-enable)
- api
- [group](#services-proxy-suite-inbounds-manager-api-group)
- [listen](#services-proxy-suite-inbounds-manager-api-listen)
- [tokensFile](#services-proxy-suite-inbounds-manager-api-tokensfile)
- [deleteExpiredAfter](#services-proxy-suite-inbounds-manager-deleteexpiredafter)
- [interval](#services-proxy-suite-inbounds-manager-interval)
- ipLimit
- [banTime](#services-proxy-suite-inbounds-manager-iplimit-bantime)
- notify
- [expiryDays](#services-proxy-suite-inbounds-manager-notify-expirydays)
- [trafficPercent](#services-proxy-suite-inbounds-manager-notify-trafficpercent)
- speedLimits
- [enable](#services-proxy-suite-inbounds-manager-speedlimits-enable)
- [slots](#services-proxy-suite-inbounds-manager-speedlimits-slots)
- subscriptions
- [enable](#services-proxy-suite-inbounds-manager-subscriptions-enable)
- [group](#services-proxy-suite-inbounds-manager-subscriptions-group)
- [listen](#services-proxy-suite-inbounds-manager-subscriptions-listen)
- [profileTitle](#services-proxy-suite-inbounds-manager-subscriptions-profiletitle)
- [supportUrl](#services-proxy-suite-inbounds-manager-subscriptions-supporturl)
- [updateInterval](#services-proxy-suite-inbounds-manager-subscriptions-updateinterval)
- [webPageUrl](#services-proxy-suite-inbounds-manager-subscriptions-webpageurl)
- [webhooks](#services-proxy-suite-inbounds-manager-webhooks)
- item
- [events](#services-proxy-suite-inbounds-manager-webhooks-events)
- [secretFile](#services-proxy-suite-inbounds-manager-webhooks-secretfile)
- [url](#services-proxy-suite-inbounds-manager-webhooks-url)
- [openFirewall](#services-proxy-suite-inbounds-openfirewall)
- routing
- [blockPorts](#services-proxy-suite-inbounds-routing-blockports)
- [blockPrivate](#services-proxy-suite-inbounds-routing-blockprivate)
- [blockRu](#services-proxy-suite-inbounds-routing-blockru)
- [blockTorrent](#services-proxy-suite-inbounds-routing-blocktorrent)
- proxy
- [domains](#services-proxy-suite-inbounds-routing-proxy-domains)
- [geoips](#services-proxy-suite-inbounds-routing-proxy-geoips)
@@ -146,12 +177,21 @@ Part of the [proxy-suite options reference](./index.md).
- [enable](#services-proxy-suite-inbounds-subscriptions-enable)
- [baseUrl](#services-proxy-suite-inbounds-subscriptions-baseurl)
- [group](#services-proxy-suite-inbounds-subscriptions-group)
- [keyFile](#services-proxy-suite-inbounds-subscriptions-keyfile)
- [users](#services-proxy-suite-inbounds-users)
- `<name>`
- [address](#services-proxy-suite-inbounds-users-name-address)
- [order](#services-proxy-suite-inbounds-users-name-order)
- [password](#services-proxy-suite-inbounds-users-name-password)
- [passwordFile](#services-proxy-suite-inbounds-users-name-passwordfile)
- policy
- [enabled](#services-proxy-suite-inbounds-users-name-policy-enabled)
- [expiresAfter](#services-proxy-suite-inbounds-users-name-policy-expiresafter)
- [expiresAt](#services-proxy-suite-inbounds-users-name-policy-expiresat)
- [ipLimit](#services-proxy-suite-inbounds-users-name-policy-iplimit)
- [speedLimit](#services-proxy-suite-inbounds-users-name-policy-speedlimit)
- [trafficLimit](#services-proxy-suite-inbounds-users-name-policy-trafficlimit)
- [trafficPeriod](#services-proxy-suite-inbounds-users-name-policy-trafficperiod)
- [presharedKeyFile](#services-proxy-suite-inbounds-users-name-presharedkeyfile)
- [privateKeyFile](#services-proxy-suite-inbounds-users-name-privatekeyfile)
- [publicKey](#services-proxy-suite-inbounds-users-name-publickey)
@@ -1132,6 +1172,219 @@ Raw XRay inbound JSON (ends up in the Nix store)\. Its tag is replaced; a missin
**Default:** `null`\
**Example:** `{ protocol = "dokodemo-door"; settings = { port = 8080; }; }`
<a id="services-proxy-suite-inbounds-manager-enable"></a>
## services\.proxy-suite\.inbounds\.manager\.enable
The inbound manager, a daemon that keeps the users’ policies (` inbounds.users.<name>.policy `,
and what it is told at runtime): who is switched off, whose time ran out, who used up
their traffic, how many addresses and how much speed each may have\. It applies them to
the running inbounds without a restart, answers an HTTP+JSON API for proxy-ctl and bots,
serves subscriptions with the traffic and expiry clients show, and calls webhooks\.
Users and listeners added through it need ` inbounds.runtime `\.
**Type:** boolean\
**Default:** `false`
<a id="services-proxy-suite-inbounds-manager-api-group"></a>
## services\.proxy-suite\.inbounds\.manager\.api\.group
Group that may use the API socket, /run/proxy-suite-inbounds-manager/api\.sock: all of
it, every user’s secrets included\. ` null `: ` userControl.group ` when it has the
“inbounds” scope, root only otherwise\.
**Type:** null or string\
**Default:** `null`\
**Example:** `"vpn-admins"`
<a id="services-proxy-suite-inbounds-manager-api-listen"></a>
## services\.proxy-suite\.inbounds\.manager\.api\.listen
Address and port the API also listens on over TCP, for a bot on another host\. Plain
HTTP: put it on loopback behind a TLS proxy\. Needs ` tokensFile `; the firewall is not
opened for it\.
**Type:** null or string matching the pattern (\[\[]\[0-9A-Fa-f:\.]+\[]]|\[0-9\.]+|localhost):\[0-9]{1,5}\
**Default:** `null`\
**Example:** `"127.0.0.1:9180"`
<a id="services-proxy-suite-inbounds-manager-api-tokensfile"></a>
## services\.proxy-suite\.inbounds\.manager\.api\.tokensFile
File with the bearer tokens the TCP API takes, one per line, “name:token” or the token
alone\. Read at start\.
**Type:** null or string\
**Default:** `null`\
**Example:** `"/run/secrets/inbounds-manager-tokens"`
<a id="services-proxy-suite-inbounds-manager-deleteexpiredafter"></a>
## services\.proxy-suite\.inbounds\.manager\.deleteExpiredAfter
Delete runtime users this long after their ` expiresAt `, as ` proxy-ctl inbounds users rm `
would: their secrets, policy and subscription go\. A number with m, h, d or w\. Users
declared in the config stay\. ` null `: never\.
**Type:** null or string matching the pattern \[0-9]+\[mhdw]\
**Default:** `null`\
**Example:** `"30d"`
<a id="services-proxy-suite-inbounds-manager-interval"></a>
## services\.proxy-suite\.inbounds\.manager\.interval
Seconds between two rounds of counting traffic and checking the policies\.
**Type:** integer between 5 and 3600 (both inclusive)\
**Default:** `30`
<a id="services-proxy-suite-inbounds-manager-iplimit-bantime"></a>
## services\.proxy-suite\.inbounds\.manager\.ipLimit\.banTime
Seconds an address past a user’s ` ipLimit ` is banned for\.
**Type:** positive integer, meaning >0\
**Default:** `600`
<a id="services-proxy-suite-inbounds-manager-notify-expirydays"></a>
## services\.proxy-suite\.inbounds\.manager\.notify\.expiryDays
Days before the expiry that send a user\.expiring event\.
**Type:** list of (positive integer, meaning >0)\
**Default:** `[ 3 1 ]`
<a id="services-proxy-suite-inbounds-manager-notify-trafficpercent"></a>
## services\.proxy-suite\.inbounds\.manager\.notify\.trafficPercent
Shares of the traffic allowance used that send a user\.traffic event, once per period\.
**Type:** list of integer between 1 and 100 (both inclusive)\
**Default:** `[ 80 100 ]`
<a id="services-proxy-suite-inbounds-manager-speedlimits-enable"></a>
## services\.proxy-suite\.inbounds\.manager\.speedLimits\.enable
Speed limits (` policy.speedLimit `)\. XRay marks the sockets its exits dial for a limited
user with the user’s slot, which proxy-suite’s XRay build carries a patch for
(pkgs/patches/xray-user-level-mark\.patch), and nftables polices each mark’s
traffic both ways\. AmneziaWG peers are policed by their tunnel address\. Needs root\.
**Type:** boolean\
**Default:** `false`
<a id="services-proxy-suite-inbounds-manager-speedlimits-slots"></a>
## services\.proxy-suite\.inbounds\.manager\.speedLimits\.slots
How many users may have a speed limit at once: an XRay user level each\.
**Type:** integer between 1 and 65535 (both inclusive)\
**Default:** `512`
<a id="services-proxy-suite-inbounds-manager-subscriptions-enable"></a>
## services\.proxy-suite\.inbounds\.manager\.subscriptions\.enable
Serve each user’s subscription from /run/proxy-suite-inbounds-manager/sub\.sock, with the
headers clients read their traffic, allowance and expiry from (subscription-userinfo),
a title and an update interval\. The token is the last part of the path, the same
as the static files’ (` inbounds.subscriptions `), so their URLs keep working:
```nix
services.nginx.virtualHosts."vpn.example.com".locations."/sub/".proxyPass =
"http://unix:/run/proxy-suite-inbounds-manager/sub.sock:";
```
**Type:** boolean\
**Default:** `config.services.proxy-suite.inbounds.shareLinks`
<a id="services-proxy-suite-inbounds-manager-subscriptions-group"></a>
## services\.proxy-suite\.inbounds\.manager\.subscriptions\.group
Group of the web server that connects to the subscription socket\.
**Type:** string\
**Default:** `config.services.proxy-suite.inbounds.subscriptions.group`
<a id="services-proxy-suite-inbounds-manager-subscriptions-listen"></a>
## services\.proxy-suite\.inbounds\.manager\.subscriptions\.listen
Address and port the subscriptions are also served on over TCP, for a web server that cannot reach the socket\.
**Type:** null or string matching the pattern (\[\[]\[0-9A-Fa-f:\.]+\[]]|\[0-9\.]+|localhost):\[0-9]{1,5}\
**Default:** `null`\
**Example:** `"127.0.0.1:9181"`
<a id="services-proxy-suite-inbounds-manager-subscriptions-profiletitle"></a>
## services\.proxy-suite\.inbounds\.manager\.subscriptions\.profileTitle
The profile’s name in clients; {user} is the user’s\.
**Type:** string\
**Default:** `"{user}"`\
**Example:** `"My VPN ({user})"`
<a id="services-proxy-suite-inbounds-manager-subscriptions-supporturl"></a>
## services\.proxy-suite\.inbounds\.manager\.subscriptions\.supportUrl
Where clients send users for help (support-url), such as a Telegram link\.
**Type:** null or string\
**Default:** `null`\
**Example:** `"https://t.me/my_vpn_support"`
<a id="services-proxy-suite-inbounds-manager-subscriptions-updateinterval"></a>
## services\.proxy-suite\.inbounds\.manager\.subscriptions\.updateInterval
Hours between clients’ updates of the subscription (profile-update-interval)\.
**Type:** null or (positive integer, meaning >0)\
**Default:** `12`
<a id="services-proxy-suite-inbounds-manager-subscriptions-webpageurl"></a>
## services\.proxy-suite\.inbounds\.manager\.subscriptions\.webPageUrl
The service’s page (profile-web-page-url)\.
**Type:** null or string\
**Default:** `null`
<a id="services-proxy-suite-inbounds-manager-webhooks"></a>
## services\.proxy-suite\.inbounds\.manager\.webhooks
Where to tell about users created, deleted, updated, switched off (with why) and back
on, their traffic reset, their term started on their first connection (user\.activated), thresholds of their allowance, coming expiries and addresses
banned past their ipLimit\. Retried a few times; a hook that stays down misses them\.
**Type:** list of (submodule)\
**Default:** `[ ]`\
**Example:**
```nix
[ { url = "http://127.0.0.1:8088/proxy-suite"; secretFile = "/run/secrets/hook"; } ]
```
<a id="services-proxy-suite-inbounds-manager-webhooks-events"></a>
## services\.proxy-suite\.inbounds\.manager\.webhooks\.\*\.events
Events to send\. Empty: all of them\.
**Type:** list of (one of “user\.created”, “user\.deleted”, “user\.updated”, “user\.enabled”, “user\.disabled”, “user\.reset”, “user\.activated”, “user\.traffic”, “user\.expiring”, “user\.ip-limit”)\
**Default:** `[ ]`
<a id="services-proxy-suite-inbounds-manager-webhooks-secretfile"></a>
## services\.proxy-suite\.inbounds\.manager\.webhooks\.\*\.secretFile
File with a secret: each body is signed, X-Proxy-Suite-Signature: sha256=\<HMAC-SHA256 hex>\.
**Type:** null or string\
**Default:** `null`
<a id="services-proxy-suite-inbounds-manager-webhooks-url"></a>
## services\.proxy-suite\.inbounds\.manager\.webhooks\.\*\.url
URL the events are POSTed to as JSON: {event, user, at, data}\.
**Type:** string
<a id="services-proxy-suite-inbounds-openfirewall"></a>
## services\.proxy-suite\.inbounds\.openFirewall
@@ -1140,6 +1393,17 @@ Open the firewall for every listener not on loopback\.
**Type:** boolean\
**Default:** `true`
<a id="services-proxy-suite-inbounds-routing-blockports"></a>
## services\.proxy-suite\.inbounds\.routing\.blockPorts
Destination ports clients may not reach, TCP and UDP: single ports and “from-to”
ranges\. Port 25 by default: mail sent straight to other servers, which spam goes
out by and hosters close\. Mail clients’ own ports (465, 587) stay open\.
**Type:** list of (16 bit unsigned integer; between 0 and 65535 (both inclusive) or string matching the pattern \[0-9]±\[0-9]+)\
**Default:** `[ 25 ]`\
**Example:** `[ 25 "6881-6889" ]`
<a id="services-proxy-suite-inbounds-routing-blockprivate"></a>
## services\.proxy-suite\.inbounds\.routing\.blockPrivate
@@ -1159,6 +1423,17 @@ Block Russian destinations (geosite “category-ru”, geoip “ru”)\.
**Type:** boolean\
**Default:** `true`
<a id="services-proxy-suite-inbounds-routing-blocktorrent"></a>
## services\.proxy-suite\.inbounds\.routing\.blockTorrent
Block BitTorrent: connections XRay’s sniffing recognizes by the peers’ handshake, and µTP\.
Not trackers or DHT, nor what a client encrypts (MSE): it makes downloading slow, not
impossible\. Hosters act on the copyright notices torrents bring\. Listeners given as raw
XRay JSON need sniffing on for it\.
**Type:** boolean\
**Default:** `true`
<a id="services-proxy-suite-inbounds-routing-proxy-domains"></a>
## services\.proxy-suite\.inbounds\.routing\.proxy\.domains
@@ -1427,6 +1702,25 @@ Group of the web server that serves the subscription files\.
**Default:** `"nginx"`\
**Example:** `"caddy"`
<a id="services-proxy-suite-inbounds-subscriptions-keyfile"></a>
## services\.proxy-suite\.inbounds\.subscriptions\.keyFile
The key the subscription tokens are an HMAC under\. Changing it changes every user’s
URL\.
- ` null `: generated on first start and kept in the state directory
(inbounds/subscription-key), where ` proxy-ctl inbounds export ` takes it from\.
- a file with a secret, such as ` openssl rand -hex 32 `: that one, read at start and
at each runtime change\.
- ` false `: no key\. A token is a hash of the user’s name and credentials alone, as
before there was a key: whoever learns one of a user’s links can work out their
subscription URL, and from it every other link of theirs\. For a server that gave
URLs out before\.
**Type:** null or value false (singular enum) or string\
**Default:** `null`\
**Example:** `"/run/secrets/inbounds-subscription-key"`
<a id="services-proxy-suite-inbounds-users"></a>
## services\.proxy-suite\.inbounds\.users
@@ -1489,6 +1783,78 @@ File with the password\.
**Default:** `null`\
**Example:** `"/run/secrets/proxy-inbound-password"`
<a id="services-proxy-suite-inbounds-users-name-policy-enabled"></a>
## services\.proxy-suite\.inbounds\.users\.\<name>\.policy\.enabled
Whether the user may connect\. Needs ` inbounds.manager `, as every ` policy ` field does\.
**Type:** boolean\
**Default:** `true`
<a id="services-proxy-suite-inbounds-users-name-policy-expiresafter"></a>
## services\.proxy-suite\.inbounds\.users\.\<name>\.policy\.expiresAfter
A term that starts with the user’s first connection, for access sold ahead: seconds,
or a number with m, h, d or w\. Until they connect the user is on hold, and when
they do ` expiresAt ` is set to that much later\. An ` expiresAt ` given wins\.
**Type:** null or positive integer, meaning >0, or string matching the pattern \[0-9]+\[mhdw]\
**Default:** `null`\
**Example:** `"30d"`
<a id="services-proxy-suite-inbounds-users-name-policy-expiresat"></a>
## services\.proxy-suite\.inbounds\.users\.\<name>\.policy\.expiresAt
When the user’s access ends: a date (the end of that day, local time), an ISO time,
or a Unix time\. Their connections are cut then, and their subscription still says
when it ended\.
**Type:** null or unsigned integer, meaning >=0, or string matching the pattern \[0-9]{4}-\[0-9]{2}-\[0-9]{2}(\[T ]\[0-9:\.]+(\[±]\[0-9:]+|Z)?)?\
**Default:** `null`\
**Example:** `"2026-12-31"`
<a id="services-proxy-suite-inbounds-users-name-policy-iplimit"></a>
## services\.proxy-suite\.inbounds\.users\.\<name>\.policy\.ipLimit
How many addresses may use the user at once\. The ones past it that came last are
banned for ` inbounds.manager.ipLimit.banTime ` from the user’s ports\. Not on
AmneziaWG, whose peer has one address anyway, nor behind a PROXY-protocol front\.
**Type:** null or (positive integer, meaning >0)\
**Default:** `null`\
**Example:** `2`
<a id="services-proxy-suite-inbounds-users-name-policy-speedlimit"></a>
## services\.proxy-suite\.inbounds\.users\.\<name>\.policy\.speedLimit
Speed limit in bits per second, decimal (k, M, G): one rate for both ways, or
“down/up”\. Needs ` inbounds.manager.speedLimits.enable `\. On socks and http listeners
it does not apply\.
**Type:** null or string matching the pattern \[0-9]+(\\\.\[0-9]+)?\[kKMG]?(/\[0-9]+(\\\.\[0-9]+)?\[kKMG]?)?\
**Default:** `null`\
**Example:** `"20M/5M"`
<a id="services-proxy-suite-inbounds-users-name-policy-trafficlimit"></a>
## services\.proxy-suite\.inbounds\.users\.\<name>\.policy\.trafficLimit
Traffic allowance, up and down together: bytes, or with K, M, G, T (binary units, as
clients show them)\. Past it the user is switched off until the period renews or the
traffic is reset\.
**Type:** null or unsigned integer, meaning >=0, or string matching the pattern \[0-9]+(\\\.\[0-9]+)?\[KMGTP]?(i?B)?\
**Default:** `null`\
**Example:** `"50G"`
<a id="services-proxy-suite-inbounds-users-name-policy-trafficperiod"></a>
## services\.proxy-suite\.inbounds\.users\.\<name>\.policy\.trafficPeriod
How often the allowance renews, at local midnight: daily, weekly, or monthly on the
day the count began\. ` null `: never; only a reset starts it over\.
**Type:** null or one of “daily”, “weekly”, “monthly”\
**Default:** `null`
<a id="services-proxy-suite-inbounds-users-name-presharedkeyfile"></a>
## services\.proxy-suite\.inbounds\.users\.\<name>\.presharedKeyFile
+42
View File
@@ -91,11 +91,52 @@ services.proxy-suite = {
accessLog = false;
enable = false;
listeners = { };
manager = {
api = {
group = null;
listen = null;
tokensFile = null;
};
deleteExpiredAfter = null;
enable = false;
interval = 30;
ipLimit = {
banTime = 600;
};
notify = {
expiryDays = [
3
1
];
trafficPercent = [
80
100
];
};
speedLimits = {
enable = false;
slots = 512;
};
subscriptions = {
enable = config.services.proxy-suite.inbounds.shareLinks;
group = config.services.proxy-suite.inbounds.subscriptions.group;
listen = null;
profileTitle = "{user}";
supportUrl = null;
updateInterval = 12;
webPageUrl = null;
};
webhooks = [ ];
};
openFirewall = true;
package = ‹proxy-suite's xray (pkgs/xray.nix)›;
routing = {
blockPorts = [
25
];
blockPrivate = true;
blockRu = true;
blockTorrent = true;
proxy = {
domains = [ ];
geoips = [ ];
@@ -125,6 +166,7 @@ services.proxy-suite = {
baseUrl = null;
enable = false;
group = "nginx";
keyFile = null;
};
users = { };
};
+4 -2
View File
@@ -4,6 +4,8 @@
enable = true;
baseUrl = "https://vpn.example.com/sub";
};
services.nginx.virtualHosts."vpn.example.com".locations."/sub/".alias =
"/run/proxy-suite-inbounds/subscriptions/";
services.nginx.virtualHosts."vpn.example.com".locations."/sub/" = {
alias = "/run/proxy-suite-inbounds/subscriptions/";
extraConfig = "access_log off;"; # the token is the URL's secret
};
}
+17
View File
@@ -0,0 +1,17 @@
{ config, lib, pkgs, ... }:
{
services.proxy-suite.inbounds = {
manager = {
enable = true;
speedLimits.enable = true; # nftables, and proxy-suite's XRay patch
};
# Declared users take a policy in the config; runtime ones get theirs from proxy-ctl or the API.
users.phone.policy = {
expiresAt = "2026-12-31";
trafficLimit = "100G";
trafficPeriod = "monthly";
ipLimit = 2;
speedLimit = "50M/10M"; # down/up, bits per second
};
};
}
+6
View File
@@ -101,6 +101,12 @@ outbound, a subscription URL a subscription. An AmneziaWG `vpn://` link or a who
becomes a global profile, or an outbound when pasted onto the Outbounds tab. See
[Use an AmneziaWG config](./amneziawg.md).
The app also opens `proxy-suite://install-config?url=<subscription URL>` links, which the
subscription page of a proxy-suite server offers on Linux: it shows the `proxy subs add` it
would run and waits for you to confirm it. The link's `name` becomes the subscription's tag
(`VPN alice` as `VPN-alice`, with `-2` after it when taken); without one, it is named after
the URL's host.
Adding a rule, an outbound, a group, a listener or a user opens a form with one field per
parameter. Optional fields are marked, and the values the field knows (outbounds, users,
listeners, strategies) are offered: in the TUI, → completes one, and in the app, a list beside
+181 -2
View File
@@ -101,12 +101,22 @@ services.proxy-suite.inbounds.subscriptions = {
enable = true;
baseUrl = "https://vpn.example.com/sub";
};
services.nginx.virtualHosts."vpn.example.com".locations."/sub/".alias =
"/run/proxy-suite-inbounds/subscriptions/";
services.nginx.virtualHosts."vpn.example.com".locations."/sub/" = {
alias = "/run/proxy-suite-inbounds/subscriptions/";
extraConfig = "access_log off;"; # the token is the URL's secret
};
```
Then `proxy-ctl inbounds sub phone --qr` prints that user's subscription.
The token at the end of the URL is all that guards a subscription. It is an HMAC under a key
generated on first start (/var/lib/proxy-suite/inbounds/subscription-key, carried by
`proxy-ctl inbounds export`), or under `subscriptions.keyFile` when you keep your own. A
server that handed out URLs before there was a key keeps them with
`subscriptions.keyFile = false`: its tokens stay a hash of the user's name and
credentials, which anyone who has one of the user's links can work out, and with it the rest
of their links. Turning the key on later changes every user's URL.
## Add users and listeners at runtime
With `inbounds.runtime`, users and listeners can be added with `proxy-ctl`, the TUI or the app,
@@ -144,10 +154,179 @@ up is refused, and anything that stops working later (a certificate removed from
say) is left out with a warning in `proxy-ctl logs proxy-suite-inbounds` while the rest runs.
Without root, members of `userControl.group` need the `inbounds` scope.
## Policies: expiry, traffic, devices, speed
`inbounds.manager` runs a daemon that keeps each user's policy and applies it to the running
inbounds without a restart: users switched off, out of time or out of traffic leave XRay
through its API (their open connections are cut), the others keep theirs.
```nix
services.proxy-suite.inbounds = {
manager = {
enable = true;
speedLimits.enable = true; # nftables, and proxy-suite's XRay patch
};
# Declared users take a policy in the config; runtime ones get theirs from proxy-ctl or the API.
users.phone.policy = {
expiresAt = "2026-12-31";
trafficLimit = "100G";
trafficPeriod = "monthly";
ipLimit = 2;
speedLimit = "50M/10M"; # down/up, bits per second
};
};
```
```sh
proxy-ctl inbounds users add alice --listener vless-reality --expires +30d --traffic 50G --period monthly --ips 2
proxy-ctl inbounds users # status, traffic used of the allowance, expiry
proxy-ctl inbounds users show alice
proxy-ctl inbounds users set alice --speed 20M/5M
proxy-ctl inbounds users extend alice 30d # from the expiry, or from now if it passed
proxy-ctl inbounds users extend alice 30d --reset # a renewal: the traffic starts over too
proxy-ctl inbounds users add bob --listener vless-reality --on-hold 30d --traffic 50G
proxy-ctl inbounds users reset alice # start the traffic over
proxy-ctl inbounds users rotate-sub alice # a new subscription URL; the old one stops answering
proxy-ctl inbounds users disable alice
proxy-ctl inbounds bans # addresses past an ipLimit, banned for a while
```
What a policy holds:
- `expiresAt`: past it the user is switched off, and their subscription still says when.
- `expiresAfter` (`--on-hold`): a term that starts with the first connection, for access sold
ahead. Until the user connects they are on hold; then `expiresAt` is set that much later
(event user.activated). `extend` lengthens the term while on hold. An `expiresAt` given wins.
- `trafficLimit`, `trafficPeriod`: up and down together, counted from the day the user came
or was reset; a period renews at local midnight, monthly on that day of the month.
- `ipLimit`: past it, the addresses that came last are banned from the user's ports for
`manager.ipLimit.banTime`. Not on AmneziaWG (a peer has one address anyway), nor behind
a PROXY-protocol front.
- `speedLimit`: XRay marks the sockets its exits dial for the user with their slot, and
nftables polices that mark both ways; AmneziaWG peers by their tunnel address.
- `meta`: strings for a bot of yours, such as a Telegram ID.
Runtime users expired long ago can go by themselves: `manager.deleteExpiredAfter = "30d"`
deletes each that long after its expiry (event user.deleted, with the reason). Declared users
stay.
Subscriptions served by the manager carry the traffic, the allowance and the expiry
(`subscription-userinfo`), which v2rayN, Hiddify, Happ and Streisand show, plus a title and
an update interval. The same URL answers each client in what it reads:
- Clash and mihomo apps (Clash Meta, Clash Verge, FlClash, Stash): a mihomo config, the
user's servers in a group that picks the fastest and one to choose by hand.
- The sing-box apps (SFA, SFI, SFM): a sing-box config with TUN.
- A browser: a page with the state, traffic and expiry, a QR code, buttons that add the
subscription to an app, and each link to copy. In Russian when the browser asks for it.
The buttons for the browser's system come first (Android, iOS, macOS, Windows, Linux), the
rest under "Other apps": Happ, Hiddify, v2rayNG, Streisand, Karing, sing-box, Clash (Clash
Meta, FlClash, Clash Verge Rev, Clash Party, Stash) and, on Linux, proxy-suite's own desktop
app (`gui.enable`), which asks before it adds the subscription.
- Everything else, Hiddify included: base64 of the links, as before.
`?format=base64|links|clash|sing-box|html` picks one by hand. Listeners only XRay dials
(XHTTP, ECH) are left out of the Clash and sing-box configs, and AmneziaWG out of all of them.
The page's QR code, drawn by the browser, is of `inbounds.subscriptions.baseUrl`; without it,
of the address the browser asked for, as the web server passes it on in `Host` and
`X-Forwarded-Proto`. Set `baseUrl`: then no header decides what the page offers. The page
runs nothing but its own script and stylesheet (a CSP with their hashes), and no answer is
cached, sent on as a referrer or indexed.
Point the web server at the manager's socket instead of the static files; the tokens and so
the URLs stay the same. Keep the tokens out of its access log, and slow down whoever guesses:
```nix
services.nginx.appendHttpConfig = "limit_req_zone $binary_remote_addr zone=sub:1m rate=30r/m;";
services.nginx.virtualHosts."vpn.example.com".locations."/sub/" = {
proxyPass = "http://unix:/run/proxy-suite-inbounds-manager/sub.sock:";
recommendedProxySettings = true; # Host, X-Forwarded-Proto, X-Real-IP
extraConfig = ''
access_log off;
limit_req zone=sub burst=20 nodelay;
'';
};
```
A token that is not there gets a 404 and a line in the manager's journal, at most one a minute
per address (X-Real-IP from the web server), with how many came since:
`subscription: unknown token from 203.0.113.7 (12 more since the last line)`. A fail2ban
filter on it bans whoever keeps guessing.
`proxy-ctl inbounds users rotate-sub <name>` gives a user a new URL with their credentials
left as they are, for a URL that got out; their clients need the new one. It stays with the
user through an export and import.
Worth knowing:
- A user switched off by the manager loses their open connections too: TCP ones are closed
(`ss -K`), UDP ones (Hysteria2, XHTTP over HTTP/3) dropped for a while. Others behind the
same address reconnect once. Without the manager, removing a runtime user cuts its TCP
connections only.
- Giving a user a speed limit, or taking it away, changes their XRay level: their
connections drop once.
- An exit whose own JSON or URL sets `sockopt.mark` keeps it, and its users are not
speed-limited there. Socks and http listeners take no speed limit either.
### The API
The manager answers HTTP+JSON on `/run/proxy-suite-inbounds-manager/api.sock` (root, and
`userControl.group` with the "inbounds" scope, or `manager.api.group`), and with
`manager.api.listen` and bearer tokens over TCP, for a bot elsewhere (behind TLS):
```sh
curl --unix-socket /run/proxy-suite-inbounds-manager/api.sock http://x/api/v1/users
curl --unix-socket /run/proxy-suite-inbounds-manager/api.sock http://x/api/v1/users \
-d '{"name": "bob", "listeners": ["vless-reality"], "policy": {"expiresAt": "+30d", "trafficLimit": "50G"}}'
```
| Call | What |
| --- | --- |
| `GET /api/v1/users`, `GET /api/v1/users/<name>` | users: policy, status and why, traffic, online addresses, subscription |
| `POST /api/v1/users` | `{name, listeners, order?, policy?}`: a runtime user, secrets generated |
| `PATCH /api/v1/users/<name>` | policy fields, and `unset: [fields]` to drop runtime ones |
| `DELETE /api/v1/users/<name>` | a runtime user, and their policy |
| `POST /api/v1/users/<name>/enable`, `/disable`, `/reset-traffic` | |
| `POST /api/v1/users/<name>/extend` | `{by: "30d"}` or `{until: "2027-01-31"}`, and `resetTraffic: true` to start the traffic over |
| `POST /api/v1/users/<name>/rotate-subscription` | a new subscription URL; the old one stops answering |
| `PUT /api/v1/users/<name>/listeners` | `{listeners: [...]}` |
| `GET /api/v1/users/<name>/links` | share links and client configs |
| `GET /api/v1/listeners`, `/online`, `/bans`; `DELETE /api/v1/bans/<address>` | |
| `GET /api/v1/export`, `POST /api/v1/import` | see below |
| `GET /api/v1/events` | the latest events |
Sizes take K, M, G, T (binary), speeds k, M, G bits per second, times a date, an ISO time,
a Unix time or `+30d`. Errors come as `{"error": "..."}` with a 4xx status.
`manager.webhooks` POST each event as JSON (`{event, user, at, data}`), signed with
`X-Proxy-Suite-Signature: sha256=<HMAC>` when given a secret: user.created, user.deleted,
user.updated, user.enabled, user.disabled (with the reasons), user.reset, user.activated
(a term on hold started), user.traffic (80 % and 100 % of the allowance), user.expiring
(3 days and 1 day before) and user.ip-limit.
### Moving to another server
```sh
proxy-ctl inbounds export users.json # on the old one: 0600, it holds every secret
proxy-ctl inbounds import users.json # on the new one, with the same listeners
```
The export holds the runtime users and listeners (their UUIDs, passwords and REALITY keys),
the policies and what they are measured against, the AmneziaWG listeners' keys and
addresses, the Salamander passwords proxy-suite generated, and the traffic counted. Secrets
the config names by file (sops and the like) are not in it. Runtime users and listeners
already on the new server are refused and policies already there kept, unless `--replace`;
an AmneziaWG listener that has a key already keeps it unless `--replace`, which its existing
clients need.
## Good to know
- Clients cannot reach this host's LAN or Russian sites by default
(`inbounds.routing.blockPrivate`, `blockRu`).
- Nor, by default, BitTorrent or port 25 (`routing.blockTorrent`, `routing.blockPorts`):
copyright notices and spam are what hosters close servers over. XRay's sniffing catches
the peers' handshake, not trackers, DHT or encrypted connections: torrents get slow, not
impossible. Should a complaint come anyway, `inbounds.accessLog` logs who went where.
- Through "direct", clients reach this host itself only on the listeners' ports and
`inbounds.serverPorts` (80/443 with subscriptions), whatever it listens on. Its addresses
are read when the inbounds start: restart them after the address changes.
@@ -129,16 +129,29 @@ in
}
];
stats = { };
# Handler and Routing: users, rules and outbounds changed in place (scripts/inbound_apply.py).
api = {
tag = "api";
services = [ "StatsService" ];
services = [
"StatsService"
"HandlerService"
"RoutingService"
];
};
policy = {
levels."0" = {
statsUserUplink = true;
statsUserDownlink = true;
statsUserOnline = true;
};
# Level 0, and with speed limits one more per slot: a limited user's level, which the
# exits mark its sockets with. A level XRay has no policy for would count no stats.
levels =
let
level = {
statsUserUplink = true;
statsUserDownlink = true;
statsUserOnline = true;
};
slots =
if derived.proxyInboundsSpeedLimits then derived.proxyInboundsManagerCfg.speedLimits.slots else 0;
in
lib.genAttrs (map toString (lib.range 0 slots)) (_: level);
system = {
statsInboundUplink = true;
statsInboundDownlink = true;
+24
View File
@@ -114,6 +114,18 @@ let
# appear here only as paths; the script reads them at runtime.
proxyInboundsSpec = {
runtime = if derived.proxyInboundsRuntimeEnabled then runtimeSpec else null;
# inbounds.manager, for inbound_policy.py: where the policies and what they are measured
# against are. null: every user active, at level 0, as without it.
manager =
if derived.proxyInboundsManagerEnabled then
{
policyFile = "${derived.constants.inboundsManagerDir}/policy.json";
stateFile = "${derived.constants.inboundsManagerDir}/state.json";
statsFile = derived.constants.inboundStatsFile;
speedLimits = derived.proxyInboundsSpeedLimits;
}
else
null;
# Every declared user, on a listener or not, and their serverSource numbers: what
# `proxy-ctl inbounds users` lists, and what runtime users go around. Secrets as paths.
users = derived.proxyInboundsCfg.users;
@@ -126,6 +138,18 @@ let
};
serverAddress = derived.proxyInboundsCfg.serverAddress;
shareLinks = derived.proxyInboundsCfg.shareLinks;
# The config's key (a path), or where the generated one is kept (null: the renderer makes
# it on first start), or neither (false).
subscriptionKeyFile =
let
keyFile = derived.proxyInboundsCfg.subscriptions.keyFile;
in
if builtins.isString keyFile then keyFile else null;
subscriptionKeyStateFile =
if derived.proxyInboundsCfg.subscriptions.keyFile == null then
"${cfg.host.stateDir}/inbounds/subscription-key"
else
null;
# Listeners the onion service carries, which get a second set of links to it.
onionListeners = map (ib: ib.tag) derived.torOnionInbounds;
inherit (inboundRules) sniffDomainsExcluded;
+17
View File
@@ -323,6 +323,11 @@ let
# inbounds.runtime: listeners added with proxy-ctl may exit by these, so everything built
# per exit (rules, outbounds, the local proxy, name resolution) is there for them too.
proxyInboundsRuntimeEnabled = proxyInboundsEnabled && proxyInboundsCfg.runtime.enable;
# inbounds.manager: users' policies kept by a daemon; speed limits need root (nftables).
proxyInboundsManagerCfg = proxyInboundsCfg.manager;
proxyInboundsManagerEnabled = proxyInboundsEnabled && proxyInboundsManagerCfg.enable;
proxyInboundsSpeedLimits =
proxyInboundsManagerEnabled && proxyInboundsManagerCfg.speedLimits.enable && cfg.host.privileged;
proxyInboundsRuntimeVias = lib.optionals proxyInboundsRuntimeEnabled (
lib.unique ([ proxyInboundsCfg.routing.via ] ++ proxyInboundsCfg.runtime.vias ++ [ "block" ])
);
@@ -1185,6 +1190,15 @@ let
# Loopback listener behind the selector `proxy-ctl proxy outbounds test` switches.
outboundTestPort = 18537;
inboundStatsFile = "${stateDir}/inbound-stats.json";
# inbounds.manager: its policy and state files (root's), its sockets, and its nftables
# table (scripts/inbound_netfilter.py). The exits' sockopt.mark when speed limits are on:
# the XRay patch's flag (0x40000000) and the base users' levels are added to (0x04000000).
inboundsManagerDir = "${stateDir}/inbounds-manager";
inboundsManagerRuntimeDir = "${runtimeDir}/proxy-suite-inbounds-manager";
inboundsManagerApiSocket = "${runtimeDir}/proxy-suite-inbounds-manager/api.sock";
inboundsManagerSubSocket = "${runtimeDir}/proxy-suite-inbounds-manager/sub.sock";
inboundLimitsTable = "proxy_suite_inbound_limits";
inboundExitMark = 1140850688;
# Written by proxy-suite-tor as it starts, before it reaches the network.
torOnionHostnameFile = "${stateDir}/tor/onion/hostname";
# proxy-ctl tor status|newnym.
@@ -1324,6 +1338,9 @@ in
proxyInboundsEnabled
proxyInbounds
proxyInboundsRuntimeEnabled
proxyInboundsManagerCfg
proxyInboundsManagerEnabled
proxyInboundsSpeedLimits
proxyInboundsRuntimeVias
proxyInboundRuntimePorts
proxyInboundRuntimeSinglePorts
+1
View File
@@ -9,6 +9,7 @@
./proxy-tun.nix
./proxy-tproxy.nix
./inbounds.nix
./inbounds-manager.nix
./per-app-routing.nix
./zapret.nix
./zapret2.nix
@@ -0,0 +1,215 @@
{ config, lib, ... }:
let
inherit (lib)
literalExpression
mkEnableOption
mkOption
types
;
cfg = config.services.proxy-suite.inbounds;
listenType = types.strMatching "([[][0-9A-Fa-f:.]+[]]|[0-9.]+|localhost):[0-9]{1,5}";
# scripts/inbound_manager.py's EVENTS.
events = [
"user.created"
"user.deleted"
"user.updated"
"user.enabled"
"user.disabled"
"user.reset"
"user.activated"
"user.traffic"
"user.expiring"
"user.ip-limit"
];
in
{
# Consumed by scripts/inbound_manager.py (manager.json, service/inbounds-manager.nix) and
# scripts/inbound_policy.py (the spec's "manager").
options.services.proxy-suite.inbounds.manager = {
enable = mkEnableOption "" // {
description = ''
The inbound manager, a daemon that keeps the users' policies (`inbounds.users.<name>.policy`,
and what it is told at runtime): who is switched off, whose time ran out, who used up
their traffic, how many addresses and how much speed each may have. It applies them to
the running inbounds without a restart, answers an HTTP+JSON API for proxy-ctl and bots,
serves subscriptions with the traffic and expiry clients show, and calls webhooks.
Users and listeners added through it need `inbounds.runtime`.
'';
};
interval = mkOption {
type = types.ints.between 5 3600;
default = 30;
description = "Seconds between two rounds of counting traffic and checking the policies.";
};
api = {
group = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Group that may use the API socket, /run/proxy-suite-inbounds-manager/api.sock: all of
it, every user's secrets included. `null`: `userControl.group` when it has the
"inbounds" scope, root only otherwise.
'';
example = "vpn-admins";
};
listen = mkOption {
type = types.nullOr listenType;
default = null;
description = ''
Address and port the API also listens on over TCP, for a bot on another host. Plain
HTTP: put it on loopback behind a TLS proxy. Needs `tokensFile`; the firewall is not
opened for it.
'';
example = "127.0.0.1:9180";
};
tokensFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
File with the bearer tokens the TCP API takes, one per line, "name:token" or the token
alone. Read at start.
'';
example = "/run/secrets/inbounds-manager-tokens";
};
};
subscriptions = {
enable = mkOption {
type = types.bool;
default = cfg.shareLinks;
defaultText = literalExpression "config.services.proxy-suite.inbounds.shareLinks";
description = ''
Serve each user's subscription from /run/proxy-suite-inbounds-manager/sub.sock, with the
headers clients read their traffic, allowance and expiry from (subscription-userinfo),
a title and an update interval. The token is the last part of the path, the same
as the static files' (`inbounds.subscriptions`), so their URLs keep working:
```nix
services.nginx.virtualHosts."vpn.example.com".locations."/sub/".proxyPass =
"http://unix:/run/proxy-suite-inbounds-manager/sub.sock:";
```
'';
};
group = mkOption {
type = types.str;
default = cfg.subscriptions.group;
defaultText = literalExpression "config.services.proxy-suite.inbounds.subscriptions.group";
description = "Group of the web server that connects to the subscription socket.";
};
listen = mkOption {
type = types.nullOr listenType;
default = null;
description = "Address and port the subscriptions are also served on over TCP, for a web server that cannot reach the socket.";
example = "127.0.0.1:9181";
};
profileTitle = mkOption {
type = types.str;
default = "{user}";
description = "The profile's name in clients; {user} is the user's.";
example = "My VPN ({user})";
};
updateInterval = mkOption {
type = types.nullOr types.ints.positive;
default = 12;
description = "Hours between clients' updates of the subscription (profile-update-interval).";
};
supportUrl = mkOption {
type = types.nullOr types.str;
default = null;
description = "Where clients send users for help (support-url), such as a Telegram link.";
example = "https://t.me/my_vpn_support";
};
webPageUrl = mkOption {
type = types.nullOr types.str;
default = null;
description = "The service's page (profile-web-page-url).";
};
};
speedLimits = {
enable = mkEnableOption "" // {
description = ''
Speed limits (`policy.speedLimit`). XRay marks the sockets its exits dial for a limited
user with the user's slot, which proxy-suite's XRay build carries a patch for
(pkgs/patches/xray-user-level-mark.patch), and nftables polices each mark's
traffic both ways. AmneziaWG peers are policed by their tunnel address. Needs root.
'';
};
slots = mkOption {
type = types.ints.between 1 65535;
default = 512;
description = "How many users may have a speed limit at once: an XRay user level each.";
};
};
deleteExpiredAfter = mkOption {
type = types.nullOr (types.strMatching "[0-9]+[mhdw]");
default = null;
description = ''
Delete runtime users this long after their `expiresAt`, as `proxy-ctl inbounds users rm`
would: their secrets, policy and subscription go. A number with m, h, d or w. Users
declared in the config stay. `null`: never.
'';
example = "30d";
};
ipLimit.banTime = mkOption {
type = types.ints.positive;
default = 600;
description = "Seconds an address past a user's `ipLimit` is banned for.";
};
notify = {
trafficPercent = mkOption {
type = types.listOf (types.ints.between 1 100);
default = [
80
100
];
description = "Shares of the traffic allowance used that send a user.traffic event, once per period.";
};
expiryDays = mkOption {
type = types.listOf types.ints.positive;
default = [
3
1
];
description = "Days before the expiry that send a user.expiring event.";
};
};
webhooks = mkOption {
type = types.listOf (
types.submodule {
options = {
url = mkOption {
type = types.str;
description = "URL the events are POSTed to as JSON: {event, user, at, data}.";
};
events = mkOption {
type = types.listOf (types.enum events);
default = [ ];
description = "Events to send. Empty: all of them.";
};
secretFile = mkOption {
type = types.nullOr types.str;
default = null;
description = "File with a secret: each body is signed, X-Proxy-Suite-Signature: sha256=<HMAC-SHA256 hex>.";
};
};
}
);
default = [ ];
description = ''
Where to tell about users created, deleted, updated, switched off (with why) and back
on, their traffic reset, their term started on their first connection (user.activated), thresholds of their allowance, coming expiries and addresses
banned past their ipLimit. Retried a few times; a hook that stays down misses them.
'';
example = literalExpression ''
[ { url = "http://127.0.0.1:8088/proxy-suite"; secretFile = "/run/secrets/hook"; } ]
'';
};
};
}
+37
View File
@@ -106,6 +106,24 @@ in
description = "Public URL of the subscription directory, used by `proxy-ctl inbounds sub`.";
example = "https://vpn.example.com/sub";
};
keyFile = mkOption {
type = types.nullOr (types.either (types.enum [ false ]) types.str);
default = null;
description = ''
The key the subscription tokens are an HMAC under. Changing it changes every user's
URL.
- `null`: generated on first start and kept in the state directory
(inbounds/subscription-key), where `proxy-ctl inbounds export` takes it from.
- a file with a secret, such as `openssl rand -hex 32`: that one, read at start and
at each runtime change.
- `false`: no key. A token is a hash of the user's name and credentials alone, as
before there was a key: whoever learns one of a user's links can work out their
subscription URL, and from it every other link of theirs. For a server that gave
URLs out before.
'';
example = "/run/secrets/inbounds-subscription-key";
};
};
# Mirrors proxy.routing, for traffic arriving from outside instead of from this host.
@@ -132,6 +150,25 @@ in
addresses (loopback, and its public ones as its interfaces carry them at start) are
reachable only on the listener ports and `serverPorts`, whichever `via` a client takes.
'';
blockTorrent = bool true ''
Block BitTorrent: connections XRay's sniffing recognizes by the peers' handshake, and µTP.
Not trackers or DHT, nor what a client encrypts (MSE): it makes downloading slow, not
impossible. Hosters act on the copyright notices torrents bring. Listeners given as raw
XRay JSON need sniffing on for it.
'';
blockPorts = mkOption {
type = types.listOf (types.either types.port (types.strMatching "[0-9]+-[0-9]+"));
default = [ 25 ];
description = ''
Destination ports clients may not reach, TCP and UDP: single ports and "from-to"
ranges. Port 25 by default: mail sent straight to other servers, which spam goes
out by and hosters close. Mail clients' own ports (465, 587) stay open.
'';
example = [
25
"6881-6889"
];
};
zapretDirect = bool true "Send zapret hostlist sites direct, so this host's zapret unblocks them. Only for the default `via`. With a direct listener or the XRay backend, only by IP: XRay matches names by what a client puts in its handshake, whatever address it connects to.";
@@ -35,6 +35,86 @@ let
AmneziaWG tunnel IPv4 address, inside `amneziaWg.subnet`. `null`: the lowest free one,
kept for as long as the user exists.
'' "10.66.0.10";
# Read by scripts/inbound_policy.py, with inbounds.manager. What the manager is told at
# runtime (`proxy-ctl inbounds users set`, its API) overrides these field by field.
policy = {
enabled = mkOption {
type = types.bool;
default = true;
description = "Whether the user may connect. Needs `inbounds.manager`, as every `policy` field does.";
};
expiresAt = mkOption {
type = types.nullOr (
types.either types.ints.unsigned (
types.strMatching "[0-9]{4}-[0-9]{2}-[0-9]{2}([T ][0-9:.]+([+-][0-9:]+|Z)?)?"
)
);
default = null;
description = ''
When the user's access ends: a date (the end of that day, local time), an ISO time,
or a Unix time. Their connections are cut then, and their subscription still says
when it ended.
'';
example = "2026-12-31";
};
expiresAfter = mkOption {
type = types.nullOr (types.either types.ints.positive (types.strMatching "[0-9]+[mhdw]"));
default = null;
description = ''
A term that starts with the user's first connection, for access sold ahead: seconds,
or a number with m, h, d or w. Until they connect the user is on hold, and when
they do `expiresAt` is set to that much later. An `expiresAt` given wins.
'';
example = "30d";
};
trafficLimit = mkOption {
type = types.nullOr (
types.either types.ints.unsigned (types.strMatching "[0-9]+(\\.[0-9]+)?[KMGTP]?(i?B)?")
);
default = null;
description = ''
Traffic allowance, up and down together: bytes, or with K, M, G, T (binary units, as
clients show them). Past it the user is switched off until the period renews or the
traffic is reset.
'';
example = "50G";
};
trafficPeriod = mkOption {
type = types.nullOr (
types.enum [
"daily"
"weekly"
"monthly"
]
);
default = null;
description = ''
How often the allowance renews, at local midnight: daily, weekly, or monthly on the
day the count began. `null`: never; only a reset starts it over.
'';
};
ipLimit = mkOption {
type = types.nullOr types.ints.positive;
default = null;
description = ''
How many addresses may use the user at once. The ones past it that came last are
banned for `inbounds.manager.ipLimit.banTime` from the user's ports. Not on
AmneziaWG, whose peer has one address anyway, nor behind a PROXY-protocol front.
'';
example = 2;
};
speedLimit = mkOption {
type = types.nullOr (types.strMatching "[0-9]+(\\.[0-9]+)?[kKMG]?(/[0-9]+(\\.[0-9]+)?[kKMG]?)?");
default = null;
description = ''
Speed limit in bits per second, decimal (k, M, G): one rate for both ways, or
"down/up". Needs `inbounds.manager.speedLimits.enable`. On socks and http listeners
it does not apply.
'';
example = "20M/5M";
};
};
};
};
@@ -61,6 +61,22 @@ let
outboundTag = "block";
};
# Whatever the listener, its via, or a proxy exception: what hosters close servers over.
# Sniffing tells BitTorrent apart whatever destOverride lists (proxy_inbound.py).
abuseRules =
lib.optional proxyInboundsCfg.routing.blockTorrent {
type = "field";
ruleTag = "inbound-block-torrent";
protocol = [ "bittorrent" ];
outboundTag = "block";
}
++ lib.optional (proxyInboundsCfg.routing.blockPorts != [ ]) {
type = "field";
ruleTag = "inbound-block-ports";
port = lib.concatMapStringsSep "," toString proxyInboundsCfg.routing.blockPorts;
outboundTag = "block";
};
# The address clients dial must stay reachable even when blockRu covers it
# (a .ru domain or IP). After blockPrivate, so it cannot open the LAN. Its aliases
# too: routing.via usually cannot loop back to this host, so they would fail there.
@@ -308,6 +324,7 @@ let
xrayInboundRules =
onionRule
++ blockPrivateRule
++ abuseRules
++ serverAddressRule
++ proxyDomainRule
++ proxyIpRule
@@ -665,6 +665,57 @@ let
(mkAssertion (!derived.proxyInboundsRuntimeEnabled || derived.proxyInboundRuntimePorts != [ ])
"proxy-suite: inbounds.runtime.enable needs inbounds.runtime.ports, the ports runtime listeners may use"
)
]
# inbounds.manager and the users' policies.
++ (
let
mgr = cfg.inbounds.manager;
defaultPolicy = {
enabled = true;
expiresAt = null;
expiresAfter = null;
trafficLimit = null;
trafficPeriod = null;
ipLimit = null;
speedLimit = null;
};
withPolicy = lib.attrNames (
lib.filterAttrs (_: user: user.policy != defaultPolicy) cfg.inbounds.users
);
withSpeed = lib.attrNames (
lib.filterAttrs (_: user: user.policy.speedLimit != null) cfg.inbounds.users
);
withIpLimit = lib.attrNames (
lib.filterAttrs (_: user: user.policy.ipLimit != null) cfg.inbounds.users
);
speedOn = mgr.enable && mgr.speedLimits.enable;
in
[
(mkAssertion (withPolicy == [ ] || derived.proxyInboundsManagerEnabled)
"proxy-suite: inbounds.users.<name>.policy needs inbounds.manager.enable, which keeps it (set on: ${lib.concatStringsSep ", " withPolicy})"
)
(mkAssertion (withSpeed == [ ] || speedOn)
"proxy-suite: inbounds.users.<name>.policy.speedLimit needs inbounds.manager.speedLimits.enable (set on: ${lib.concatStringsSep ", " withSpeed})"
)
(mkAssertion (
!speedOn || cfg.host.privileged
) "proxy-suite: inbounds.manager.speedLimits needs root: nftables polices the users' traffic")
# Without root the manager has no nftables, and an ipLimit would hold nobody back.
(mkAssertion (withIpLimit == [ ] || cfg.host.privileged)
"proxy-suite: inbounds.users.<name>.policy.ipLimit needs root: nftables bans the addresses past it (set on: ${lib.concatStringsSep ", " withIpLimit})"
)
(mkAssertion (!speedOn || (cfg.inbounds.package.passthru.userLevelMark or false))
"proxy-suite: inbounds.manager.speedLimits needs proxy-suite's XRay (inbounds.package), whose patch marks a limited user's sockets"
)
(mkAssertion (mgr.api.listen == null || mgr.api.tokensFile != null)
"proxy-suite: inbounds.manager.api.listen needs inbounds.manager.api.tokensFile: the TCP API takes bearer tokens only"
)
(mkAssertion (
!mgr.subscriptions.enable || !mgr.enable || cfg.inbounds.shareLinks
) "proxy-suite: inbounds.manager.subscriptions.enable needs inbounds.shareLinks")
]
)
++ [
(requireEnabled proxyInboundsNeedLocalProxy proxyEnabled
"proxy-suite: inbounds.routing.via = \"proxy\" relays through the local proxy stack, which requires proxy.enable = true. Use via = \"direct\" for a plain exit node."
)
+3
View File
@@ -159,6 +159,9 @@ in
INBOUNDS_RUNTIME_ENABLED = flag proxyInboundsRuntimeEnabled;
INBOUNDS_RUNTIME_TOOL = "${proxySuiteScriptsDir}/inbound_runtime.py";
INBOUNDS_SPEC_FILE = "${proxyInboundsSpecFile}";
# inbounds.manager: `inbounds users show|set|...`, bans, export and import go to its API.
INBOUNDS_MANAGER_SOCKET =
if ctx.proxyInboundsManagerEnabled then constants.inboundsManagerApiSocket else "";
# Only the system-wide instance reads the site lists; per-app zapret handles all traffic.
ZAPRET_AUTO_ENABLED = flag (zapretEngine == "zapret2" && zapretGlobalEnabled);
ZAPRET_STATE_DIR = constants.zapret2StateDir;
@@ -28,8 +28,13 @@ let
proxyInboundsSpecFile
proxyInboundsSelfSources
proxyInboundsRuntimeEnabled
proxyInboundsManagerEnabled
proxyInboundsManagerCfg
proxyInboundsSpeedLimits
proxySuiteScriptsDir
builders
constants
cfg
;
# A value in a shell comment, on that one line: a newline in a tag (types.str) would end
# the comment and run the rest as root.
@@ -198,6 +203,11 @@ let
--spec ${proxyInboundsSpecFile} \
--server-address "$SERVER_ADDRESS" \
--onion-address "$ONION_ADDRESS"${lib.optionalString proxyInboundsRuntimeEnabled " \\\n --template ${proxyInboundsFile}"})
# What runs, and from what: inbound_apply.py renders again with these and changes the
# difference through XRay's API instead of restarting.
printf '%s' "$RENDERED" > "$RUNTIME_DIR/rendered.json"
${jq} -n --arg server "$SERVER_ADDRESS" --arg onion "$ONION_ADDRESS" \
'{serverAddress: $server, onionAddress: $onion}' > "$RUNTIME_DIR/render-args.json"
INBOUNDS_JSON=$(${jq} -c '.inbounds' <<< "$RENDERED")
@@ -230,6 +240,9 @@ let
"--arg password ''"
} \
--argjson runtime ${if proxyInboundsRuntimeEnabled then "true" else "false"} \
--argjson exit_mark ${
if proxyInboundsSpeedLimits then toString constants.inboundExitMark else "null"
} \
--slurpfile rendered <(printf '%s' "$RENDERED") \
--argjson host_addresses "$HOST_ADDRESSES" \
'.inbounds += $ibs[0]
@@ -251,6 +264,13 @@ let
| if $auth_enabled then
(.outbounds[] | select(.tag == "proxy") | .settings.servers[0].users)
= [{user:$user,pass:$password}]
else . end
# Speed limits: every exit marks the sockets of a limited user with their level (the
# XRay patch), for nftables. Not the serverSource outbounds, nor one marked already.
| if $exit_mark != null then
(.outbounds[] | select(.protocol != "blackhole" and .tag != "api"
and ((.tag // "") | startswith("direct-self") | not)))
|= (.streamSettings.sockopt.mark //= $exit_mark)
else . end' \
${proxyInboundsFile} > "$RUNTIME_DIR/config.json.tmp"
@@ -368,16 +388,108 @@ let
'';
# inbounds.runtime: after proxy-ctl changes the spool. The AmneziaWG interfaces only when
# their peers changed: restarting them cuts off every one of their clients for a moment.
# Users through XRay's API and AmneziaWG peers through `awg syncconf`, so the others keep
# their connections; a restart only for what those cannot change (inbound_apply.py).
reloadInbounds = pkgs.writeShellScript "proxy-suite-inbounds" ''
set -euo pipefail
restart=$(PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${parserScriptsPythonPath}/inbound_runtime.py \
--spec ${proxyInboundsSpecFile} check${
lib.optionalString (
proxyInboundsAwg != [ ]
) " --awg-users ${constants.runtimeDir}/proxy-suite-inbounds-awg/users.json"
})
# shellcheck disable=SC2086
${constants.systemctl} try-restart $restart proxy-suite-inbounds.service
PYTHONPATH="${parserScriptsPythonPath}" exec ${python3} ${parserScriptsPythonPath}/inbound_apply.py \
--config ${applyConfigFile} --spec ${proxyInboundsSpecFile}
'';
# The links and subscriptions of a rendering saved by the start script, written as it
# writes them: for inbound_apply.py, after users changed without a restart.
writeInboundOutputs = pkgs.writeShellScript "proxy-suite-inbounds" ''
set -euo pipefail
umask 077
RENDERED=$(cat "$1")
${writeLinksBlock}
${writeSubscriptionsBlock}
'';
# What inbound_apply.py works with: the binaries, units and names it may touch.
applyConfig = {
inherit runtimeDir;
unit = "proxy-suite-inbounds.service";
template = "${proxyInboundsFile}";
inherit xray;
api = "unix://${constants.inboundStatsApiSocket}";
ip = "${pkgs.iproute2}/bin/ip";
selfInterface =
if selfInterfaceWanted then proxyInboundsCfg.routing.serverSource.interface else null;
outputsScript = "${writeInboundOutputs}";
inherit (constants) systemctl;
tmpDir = runtimeDir;
env = lib.optionalAttrs (cfg.geodata.xray.assets != null) {
XRAY_LOCATION_ASSET = "${cfg.geodata.xray.assets}/share/v2ray";
};
}
# Killing a cut user's sockets, and the table their UDP is dropped in, take root.
// lib.optionalAttrs constants.privileged {
ss = "${pkgs.iproute2}/bin/ss";
}
// lib.optionalAttrs (constants.privileged && proxyInboundsManagerEnabled) {
nft = "${pkgs.nftables}/bin/nft";
nftTable = constants.inboundLimitsTable;
}
// lib.optionalAttrs (proxyInboundsAwg != [ ]) {
awg = awgBin;
awgRuntimeDir = "${constants.runtimeDir}/proxy-suite-inbounds-awg";
awgUnit = "proxy-suite-inbounds-awg.service";
};
applyConfigFile = pkgs.writeText "proxy-suite-inbounds" (builtins.toJSON applyConfig);
# The manager's own: where it keeps things, what it serves, whom it tells.
mgr = proxyInboundsManagerCfg;
managerApiGroup =
if mgr.api.group != null then
mgr.api.group
else if userControlAllows "inbounds" then
userControlCfg.group
else
null;
managerConfig = {
apply = applyConfig;
policyFile = "${constants.inboundsManagerDir}/policy.json";
stateFile = "${constants.inboundsManagerDir}/state.json";
statsFile = constants.inboundStatsFile;
collector = "${collectInboundStats}";
inherit (mgr)
interval
webhooks
notify
deleteExpiredAfter
;
api = {
socket = constants.inboundsManagerApiSocket;
group = managerApiGroup;
mode = if managerApiGroup == null then "0600" else "0660";
inherit (mgr.api) listen tokensFile;
};
subscriptions = {
socket = if mgr.subscriptions.enable then constants.inboundsManagerSubSocket else null;
inherit (mgr.subscriptions)
group
listen
profileTitle
updateInterval
supportUrl
webPageUrl
;
inherit (subsCfg) baseUrl;
};
ipLimit.banSeconds = mgr.ipLimit.banTime;
speedLimits = proxyInboundsSpeedLimits;
inherit (mgr.speedLimits) slots;
nft = if constants.privileged then "${pkgs.nftables}/bin/nft" else null;
};
managerConfigFile = pkgs.writeText "proxy-suite-inbounds-manager" (builtins.toJSON managerConfig);
runManager = pkgs.writeShellScript "proxy-suite-inbounds-manager" ''
set -euo pipefail
umask 077
mkdir -p ${lib.escapeShellArg constants.inboundsManagerDir}
export PYTHONPATH=${proxySuiteScriptsDir}
exec ${python3} ${proxySuiteScriptsDir}/inbound_manager.py \
--config ${managerConfigFile} --spec ${proxyInboundsSpecFile} serve
'';
stopInboundsInterface =
@@ -392,6 +504,7 @@ in
stopInboundsInterface
collectInboundStats
reloadInbounds
runManager
linksFile
subscriptionsFile
;
+2
View File
@@ -197,6 +197,7 @@ let
stopInboundsInterface
collectInboundStats
reloadInbounds
runManager
;
proxyInboundsLinksFile = proxyInboundsScripts.linksFile;
proxyInboundsSubscriptionsFile = proxyInboundsScripts.subscriptionsFile;
@@ -236,6 +237,7 @@ in
stopInboundsInterface
collectInboundStats
reloadInbounds
runManager
;
inherit
proxyInboundsLinksFile
+28 -2
View File
@@ -24,6 +24,8 @@ let
whitelistBypassJoiners
proxyInboundsEnabled
proxyInboundsRuntimeEnabled
proxyInboundsManagerEnabled
proxyInboundsAwg
proxyInboundsNeedLocalProxy
scripts
perAppRouting
@@ -60,6 +62,7 @@ let
subscriptionUpdate = "proxy-suite-subscription-update";
inbounds = "proxy-suite-inbounds";
inboundStats = "proxy-suite-inbound-stats";
inboundsManager = "proxy-suite-inbounds-manager";
};
backendDescription =
@@ -267,6 +270,10 @@ let
// lib.optionalAttrs (extra != [ ]) { ReadWritePaths = map (path: "-${path}") extra; }
);
socksRuntimeDir = "${ctx.constants.runtimeDir}/${serviceNames.socks}";
inboundsRuntimeDirs = [
"${ctx.constants.runtimeDir}/${serviceNames.inbounds}"
"${ctx.constants.runtimeDir}/proxy-suite-inbounds-awg"
];
# XRay finds geoip.dat/geosite.dat through this; sing-box ignores it.
xrayAssetEnv = lib.optionalAttrs (geodata.xray.assets != null) {
@@ -361,11 +368,30 @@ let
description = "Apply proxy-suite inbound users and listeners added at runtime";
execStart = scripts.reloadInbounds;
stateDirectory = "proxy-suite";
# Root, over the spool userControl's group writes.
# Root, over the spool userControl's group writes. It renders into the inbounds' and
# the AmneziaWG listeners' runtime directories, and changes the running ones in place.
extraServiceConfig = {
RemainAfterExit = false;
}
// spoolReaderSandbox [ ];
// spoolReaderSandbox inboundsRuntimeDirs;
};
}
{
enable = proxyInboundsManagerEnabled;
name = serviceNames.inboundsManager;
value = mkRestartingService {
description = "proxy-suite inbound manager - users' policies, API and subscriptions";
after = [
"${serviceNames.inbounds}.service"
"nftables.service"
]
++ lib.optional (proxyInboundsAwg != [ ]) "proxy-suite-inbounds-awg.service";
wants = [ "${serviceNames.inbounds}.service" ];
wantedBy = [ "multi-user.target" ];
execStart = scripts.runManager;
runtimeDirectory = serviceNames.inboundsManager;
stateDirectory = "proxy-suite";
extraServiceConfig = spoolReaderSandbox inboundsRuntimeDirs;
};
}
{
+3 -1
View File
@@ -223,9 +223,11 @@ pkgs.testers.runNixOSTest {
assert server.succeed("jq -S .users /var/lib/proxy-suite/awg-inbounds/roam/state.json") == before
through_server(alice, timeout=90)
with subtest("a runtime user becomes a peer, and only its listener's interfaces restart"):
with subtest("a runtime user becomes a peer, synced in: the interfaces do not restart"):
since = server.succeed("systemctl show -p ActiveEnterTimestampMonotonic --value proxy-suite-inbounds-awg.service").strip()
server.succeed("proxy-ctl inbounds users add ring --listener roam")
server.wait_until_succeeds("awg show awgi-roam peers | wc -l | grep -qx 3", timeout=30)
assert server.succeed("systemctl show -p ActiveEnterTimestampMonotonic --value proxy-suite-inbounds-awg.service").strip() == since
server.succeed("jq -e '.users.ring.publicKey' /var/lib/proxy-suite/awg-inbounds/roam/state.json")
server.succeed("proxy-ctl inbounds link roam ring --config | grep -q '^PrivateKey'")
# A change that leaves the peers alone restarts only XRay.
+5
View File
@@ -52,6 +52,11 @@ let
enable = true;
serverAddress = "vpn.example.com";
users.user.uuidFile = "/run/secrets/uuid";
# A policy level per speed slot and the API services the manager uses: XRay must take them.
manager = {
enable = true;
speedLimits.enable = true;
};
listeners.vless-in = {
type = "vless";
port = 443;
+11 -2
View File
@@ -13,6 +13,10 @@ let
serverAddress = "11.0.0.1";
# XRay refuses plain VLESS to a public IP, so the client dials a private one.
serverPrivateAddress = "10.0.0.1";
# The inbounds' own XRay, for its API.
xrayApi = "${
import ../../pkgs/xray.nix { inherit pkgs; }
}/bin/xray api inbounduser --server=unix:///run/proxy-suite-inbounds/api/stats.sock -tag=vless-in";
network = public: private: {
networking.useDHCP = false;
@@ -191,10 +195,12 @@ pkgs.testers.runNixOSTest {
with subtest("runtime users and listeners"):
cfg = "/run/proxy-suite-inbounds/config.json"
# A user comes through XRay's API: the same XRay, config.json kept in step with it.
pid = server.succeed("systemctl show -p MainPID --value proxy-suite-inbounds.service").strip()
server.succeed("proxy-ctl inbounds users add friend --listener vless-in")
# The reload's restart returns once the start script is forked: config.json is
# gone until it renders it again.
server.wait_until_succeeds(f"jq -e '.inbounds[] | select(.tag == \"vless-in\") | .settings.clients | map(.email) == [\"tester\", \"friend\"]' {cfg}")
server.succeed("${xrayApi} | grep -q friend")
assert server.succeed("systemctl show -p MainPID --value proxy-suite-inbounds.service").strip() == pid
server.succeed("proxy-ctl inbounds add rt vless --port 9001 --user friend")
server.wait_for_open_port(9001)
server.succeed("proxy-ctl inbounds users | grep friend | grep -q rt")
@@ -225,7 +231,10 @@ pkgs.testers.runNixOSTest {
server.succeed(f"jq -e '[.inbounds[].tag] | index(\"rt\") == null' {cfg}")
server.succeed("journalctl -u proxy-suite-inbounds | grep -q \"ignoring runtime listener 'rt'\"")
server.succeed("rm /var/lib/proxy-suite/inbounds.d/listeners/rt.json")
pid = server.succeed("systemctl show -p MainPID --value proxy-suite-inbounds.service").strip()
server.succeed("proxy-ctl inbounds users rm friend")
server.wait_until_succeeds(f"jq -e '.inbounds[] | select(.tag == \"vless-in\") | .settings.clients | map(.email) == [\"tester\"]' {cfg}")
server.fail("${xrayApi} | grep -q friend")
assert server.succeed("systemctl show -p MainPID --value proxy-suite-inbounds.service").strip() == pid
'';
}
+132 -1
View File
@@ -251,10 +251,58 @@ let
);
runtimeNoPortsFixture = mkInbounds (runtimeInbounds // { runtime.enable = true; });
# inbounds.manager: the daemon, its spec and the XRay config it changes in place.
managerInbounds = runtimeInbounds // {
manager = {
enable = true;
speedLimits = {
enable = true;
slots = 3;
};
api = {
listen = "127.0.0.1:9180";
tokensFile = "/run/secrets/manager-tokens";
};
webhooks = [ { url = "http://127.0.0.1:8088/hook"; } ];
};
};
managerFixture = mkInbounds managerInbounds;
managerConfig = mkInboundsConfig managerFixture;
managerSpec = mkInboundsSpec managerFixture;
managerService = managerFixture.config.systemd.services."proxy-suite-inbounds-manager";
policyWithoutManagerFixture = evalWithUsers [
baseModule
{
services.proxy-suite.inbounds = {
enable = true;
listeners.vless-in = realityListener;
users.user.policy.trafficLimit = "10G";
};
}
];
speedWithoutLimitsFixture = mkInbounds (
lib.recursiveUpdate managerInbounds {
manager.speedLimits.enable = false;
users.user.policy.speedLimit = "20M/5M";
}
);
unpatchedXrayFixture = mkInbounds (managerInbounds // { package = pkgs.xray; });
tokenlessApiFixture = mkInbounds (
lib.recursiveUpdate managerInbounds { manager.api.tokensFile = null; }
);
# subscriptions.keyFile: null generates one, a path is the config's, false is none.
keySpec =
keyFile:
mkInboundsSpec (
mkInbounds (lib.recursiveUpdate runtimeInbounds { subscriptions.keyFile = keyFile; })
);
unguardedFixture = mkInbounds {
routing = {
blockRu = false;
blockPrivate = false;
blockTorrent = false;
blockPorts = [ ];
};
listeners.vless-in = realityListener;
};
@@ -915,14 +963,23 @@ let
(ok ((ruleByTag relayConfig "inbound-block-ru-domain").domain == [ "geosite:category-ru" ]))
(ok ((ruleByTag relayConfig "inbound-block-ru-ip").ip == [ "geoip:ru" ]))
(ok (!builtins.elem "inbound-block-private" (ruleTags unguardedConfig)))
# What hosters close servers over, ahead of every exception: no listener or via lets it by.
(ok ((ruleByTag relayConfig "inbound-block-torrent").protocol == [ "bittorrent" ]))
(ok (!(ruleByTag relayConfig "inbound-block-torrent") ? inboundTag))
(ok ((ruleByTag relayConfig "inbound-block-ports").port == "25"))
(ok ((ruleByTag relayConfig "inbound-block-ports").outboundTag == "block"))
(ok (!builtins.elem "inbound-block-torrent" (ruleTags unguardedConfig)))
(ok (!builtins.elem "inbound-block-ports" (ruleTags unguardedConfig)))
# serverAddress is exempt after blockPrivate, before the country blocks. Sniffing is
# routeOnly, so a connection to another IP naming this host in its handshake would match
# the name: the guard before it sends those the listener's way.
(
assert
lib.take 5 (ruleTags namedConfig) == [
lib.take 7 (ruleTags namedConfig) == [
"inbound-stats-api"
"inbound-block-private"
"inbound-block-torrent"
"inbound-block-ports"
"inbound-server-address-sniffed-proxy"
"inbound-server-address-direct"
"inbound-block-ru-domain"
@@ -1502,6 +1559,80 @@ let
)
(ok (!lib.hasInfix "masquerade" (awgRules awgProxyFixture)))
(
let
generated = keySpec null;
own = keySpec "/run/secrets/sub-key";
none = keySpec false;
in
assert generated.subscriptionKeyFile == null;
assert generated.subscriptionKeyStateFile == "/var/lib/proxy-suite/inbounds/subscription-key";
assert own.subscriptionKeyFile == "/run/secrets/sub-key";
assert own.subscriptionKeyStateFile == null;
assert none.subscriptionKeyFile == null;
assert none.subscriptionKeyStateFile == null;
true
)
# inbounds.manager
(
assert
managerSpec.manager == {
policyFile = "/var/lib/proxy-suite/inbounds-manager/policy.json";
stateFile = "/var/lib/proxy-suite/inbounds-manager/state.json";
statsFile = "/var/lib/proxy-suite/inbound-stats.json";
speedLimits = true;
};
assert runtimeSpec.manager == null;
# A level per speed slot, and the API services that change users and rules in place.
assert
builtins.attrNames managerConfig.policy.levels == [
"0"
"1"
"2"
"3"
];
assert builtins.attrNames relayConfig.policy.levels == [ "0" ];
assert builtins.elem "HandlerService" relayConfig.api.services;
assert builtins.elem "RoutingService" relayConfig.api.services;
true
)
(
let
start = readInboundsStart managerFixture;
in
assert lib.hasInfix "rendered.json" start;
assert lib.hasInfix "render-args.json" start;
assert lib.hasInfix "--argjson exit_mark 1140850688" start;
assert lib.hasInfix "--argjson exit_mark null" (readInboundsStart relayFixture);
true
)
(
assert builtins.elem "multi-user.target" managerService.wantedBy;
assert builtins.elem "proxy-suite-inbounds.service" managerService.after;
assert managerService.serviceConfig.RuntimeDirectory == "proxy-suite-inbounds-manager";
assert lib.hasInfix "inbound_manager.py" (
(import ./read-generated.nix).readDerivation managerService.serviceConfig.ExecStart
);
assert !(runtimeFixture.config.systemd.services ? "proxy-suite-inbounds-manager");
# Runtime changes go through the API now, a restart only where it cannot.
assert lib.hasInfix "inbound_apply.py" (
(import ./read-generated.nix).readDerivation
runtimeFixture.config.systemd.services."proxy-suite-inbounds-reload".serviceConfig.ExecStart
);
assert builtins.elem "-/run/proxy-suite-inbounds" (
runtimeFixture.config.systemd.services."proxy-suite-inbounds-reload".serviceConfig.ReadWritePaths
);
true
)
(ok (failedMessages managerFixture == [ ]))
(ok (hasFailed policyWithoutManagerFixture "policy needs inbounds.manager.enable"))
(ok (
hasFailed speedWithoutLimitsFixture "policy.speedLimit needs inbounds.manager.speedLimits.enable"
))
(ok (hasFailed unpatchedXrayFixture "needs proxy-suite's XRay"))
(ok (hasFailed tokenlessApiFixture "api.listen needs inbounds.manager.api.tokensFile"))
]
++ failing;
in
+29
View File
@@ -67,6 +67,35 @@ pkgs.lib.mapAttrs mkPythonCheck {
file = "${scripts}/test-inbound-runtime.py";
env = withPath scripts;
};
# inbounds.manager: policies and the traffic they are measured by, the statuses the
# renderers take; changes through XRay's API, against proxy-suite's own XRay; the daemon,
# its API and subscriptions, with apply and nftables stubbed.
inbound-policy = {
file = "${scripts}/test-inbound-policy.py";
env = withPath scripts;
};
inbound-apply = {
file = "${scripts}/test-inbound-apply.py";
env = withPath scripts // {
XRAY = "${import ../../pkgs/xray.nix { inherit pkgs; }}/bin/xray";
};
};
inbound-manager = {
file = "${scripts}/test-inbound-manager.py";
env = withPath scripts;
};
# The subscription in each client's format: sing-box checks its config; node runs the page's
# QR encoder and zbar reads what it drew.
inbound-subscription = {
file = "${scripts}/test-inbound-subscription.py";
env =
withPath scripts
// singBox
// {
NODE = "${pkgs.nodejs-slim}/bin/node";
ZBARIMG = "${pkgs.zbar}/bin/zbarimg";
};
};
# The NFQWS_OPT rewrites the zapret v1 package build applies.
patch-zapret-config = {
file = "${scripts}/test-patch-zapret-config.py";
+47
View File
@@ -0,0 +1,47 @@
--- a/transport/internet/system_dialer.go
+++ b/transport/internet/system_dialer.go
@@ -6,8 +6,11 @@
"syscall"
"time"
+ "google.golang.org/protobuf/proto"
+
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net"
+ "github.com/xtls/xray-core/common/session"
"github.com/xtls/xray-core/features/dns"
"github.com/xtls/xray-core/features/outbound"
)
@@ -46,8 +49,32 @@
}
}
+// proxy-suite: an outbound whose sockopt.mark carries userLevelMarkFlag marks each socket
+// with the rest of the mark plus the level of the inbound user it dials for, and leaves
+// those of level 0 unmarked: one outbound, and one routing rule, for users the kernel
+// tells apart (their speed limits).
+const userLevelMarkFlag = 0x40000000
+
+func userLevelMark(ctx context.Context, sockopt *SocketConfig) *SocketConfig {
+ if sockopt == nil || sockopt.Mark&userLevelMarkFlag == 0 {
+ return sockopt
+ }
+ var level int32
+ if inbound := session.InboundFromContext(ctx); inbound != nil && inbound.User != nil {
+ level = int32(inbound.User.Level)
+ }
+ marked := proto.Clone(sockopt).(*SocketConfig)
+ if level == 0 {
+ marked.Mark = 0
+ } else {
+ marked.Mark = sockopt.Mark&^userLevelMarkFlag + level
+ }
+ return marked
+}
+
func (d *DefaultSystemDialer) Dial(ctx context.Context, src net.Address, dest net.Destination, sockopt *SocketConfig) (net.Conn, error) {
errors.LogDebug(ctx, "dialing to "+dest.String())
+ sockopt = userLevelMark(ctx, sockopt)
if dest.Network == net.Network_UDP {
destAddr, err := net.ResolveUDPAddr("udp", dest.NetAddr())
+2 -1
View File
@@ -115,9 +115,10 @@ let
Name=Proxy Suite
GenericName=Proxy Control
Comment=Control proxy-suite services, routing and outbounds
Exec=$out/bin/proxy-suite-gui
Exec=$out/bin/proxy-suite-gui %u
Icon=io.github.FUFSoB.ProxySuite
Categories=Network;System;
MimeType=x-scheme-handler/proxy-suite;
Keywords=proxy;vpn;sing-box;zapret;tray;
StartupNotify=true
Terminal=false
+381 -7
View File
@@ -204,6 +204,29 @@ Changes and secrets need root or the userControl group.
inbounds rm <tag> remove a runtime listener
inbounds show <tag> a runtime listener's JSON
inbounds online who is online, and when others were last seen
With inbounds.manager (users' policies; the API proxy-ctl and bots use):
inbounds users [list] [--json] users, whether they may connect, traffic, expiry
inbounds users show <name> [--json] one user: policy, traffic, online, subscription
inbounds users add <name> [...] [policy flags]
add a runtime user with a policy
inbounds users set <name> [--expires 2026-12-31|+30d] [--on-hold 30d] [--traffic 50G]
[--period monthly] [--ips 2] [--speed 20M/5M] [--enable|--disable] [--meta key=value]...
change a user's policy (declared users too);
--on-hold: a term that starts on the first connection
inbounds users unset <name> <expires|hold|traffic|period|ips|speed|meta|enabled>...
back to the config's value, or none
inbounds users enable|disable <name> switch a user on or off
inbounds users reset <name> start their traffic over
inbounds users extend <name> 30d [--reset]
move the expiry on (from now, or from it if later;
on hold: a longer term); --reset: traffic anew too
inbounds users extend <name> --until <time> [--reset]
inbounds users rotate-sub <name> a new subscription URL, the old one stops answering
inbounds bans [rm <address>] addresses banned past a user's ipLimit
inbounds export [file] [--no-stats] users, policies, keys and traffic, to move them
inbounds import <file|-> [--replace] take them in on this server
inbounds events [N] what the manager did and told its webhooks
"""
ROUTE_MODES = ["whitelist", "blacklist", "all-proxy", "all-bypass"]
@@ -1016,19 +1039,46 @@ COMPLETE = {
"add": "add a listener at runtime",
"rm": "remove a runtime listener",
"show": "a runtime listener's JSON",
"bans": "addresses banned past a user's ipLimit",
"export": "users, policies, keys and traffic as JSON",
"import": "take an export in",
"events": "what the inbound manager did",
}
},
"inbounds import": {"flags": {"--replace": "the export wins over what is here"}},
"inbounds export": {"flags": {"--no-stats": "leave the traffic counts out"}},
"inbounds stats": {"flags": {"--by": "user, inbound or outbound"}},
"inbounds users": {
"words": {
"list": "users, their order, address and listeners",
"show": "one user's policy, traffic and subscription",
"add": "add a user at runtime",
"rm": "remove a runtime user",
"order": "set a runtime user's order",
"listeners": "put a user on exactly these listeners",
"on": "put exactly these users on a listener",
"set": "change a user's policy",
"unset": "drop policy fields set at runtime",
"enable": "switch a user on",
"disable": "switch a user off",
"reset": "start a user's traffic over",
"extend": "move a user's expiry on",
"rotate-sub": "give a user a new subscription URL",
}
},
"inbounds users show": {"args": lambda: _inbound_runtime_names("users")},
"inbounds users set": {
"args": lambda: _inbound_runtime_names("users"),
"flags": {"--expires": "a date, +30d, never", "--on-hold": "30d: from the first connection", "--traffic": "50G, none", "--period": "daily, weekly, monthly, none",
"--ips": "addresses at once", "--speed": "20M or down/up", "--enable": "switch on",
"--disable": "switch off", "--meta": "key=value"},
},
"inbounds users unset": {"args": lambda: {**_inbound_runtime_names("users"), **{k: "" for k in POLICY_NAMES}}, "repeat": True},
"inbounds users enable": {"args": lambda: _inbound_runtime_names("users")},
"inbounds users disable": {"args": lambda: _inbound_runtime_names("users")},
"inbounds users reset": {"args": lambda: _inbound_runtime_names("users")},
"inbounds users extend": {"args": lambda: _inbound_runtime_names("users")},
"inbounds users rotate-sub": {"args": lambda: _inbound_runtime_names("users")},
"inbounds users listeners": {"args": lambda: {**_inbound_runtime_names("users"), **_inbound_runtime_names("listeners")}, "repeat": True},
"inbounds users on": {"args": lambda: {**_inbound_runtime_names("listeners"), **_inbound_runtime_names("users")}, "repeat": True},
"inbounds users add": {"flags": {"--order": "its serverSource number", "--listener": "a listener to put it on"}},
@@ -6088,11 +6138,17 @@ def _inbound_subscriptions(*args):
user = arg
path = env("INBOUNDS_SUBS_FILE", f"{runtime_dir()}/proxy-suite-inbounds/subscriptions.json")
base = env("INBOUNDS_SUB_BASE_URL")
if not os.path.isfile(path):
if not os.path.isfile(path) and _manager_enabled():
# Served by the manager only (no static files): its API knows the tokens.
rows = [r for r in _manager("GET", "/users") if r.get("subscription")]
subs = [{"user": r["name"], "token": r["subscription"]["token"]} for r in rows]
path = ""
elif not os.path.isfile(path):
die("No subscriptions available. Is proxy-suite-inbounds running, and is inbounds.subscriptions enabled?")
if not readable(path):
elif not readable(path):
denied(path)
subs = read_json(path)
else:
subs = read_json(path)
if not user:
if qr:
usage("inbounds sub <user> --qr")
@@ -6109,7 +6165,8 @@ def _inbound_subscriptions(*args):
else:
if qr:
die("A QR code needs inbounds.subscriptions.baseUrl.")
print(f"{path.removesuffix('.json')}/{_s(token)}")
# The manager's: the token, which its socket serves at any path ending in it.
print(f"{path.removesuffix('.json')}/{_s(token)}" if path else _s(token))
sys.stdout.flush()
print("Set inbounds.subscriptions.baseUrl to get a URL instead of a path.", file=sys.stderr)
@@ -6204,7 +6261,311 @@ def _inbound_runtime_apply():
print(f"warning: {line}", file=sys.stderr)
# --- the inbound manager --------------------------------------------------------
#
# inbounds.manager: a daemon with an HTTP+JSON API on a Unix socket (scripts/inbound_manager.py),
# which bots use too. `inbounds users show|set|unset|enable|disable|reset|extend`, bans, export
# and import go to it; with it on, adding and removing users do as well, so a user's policy
# comes and goes with them.
MANAGER_TIMEOUT = 120
# The CLI's names for the policy's fields, as `users set` takes them and `users unset` names them.
POLICY_FLAGS = {
"--expires": "expiresAt",
"--on-hold": "expiresAfter",
"--traffic": "trafficLimit",
"--period": "trafficPeriod",
"--ips": "ipLimit",
"--speed": "speedLimit",
}
POLICY_NAMES = {
"expires": "expiresAt",
"hold": "expiresAfter",
"traffic": "trafficLimit",
"period": "trafficPeriod",
"ips": "ipLimit",
"speed": "speedLimit",
"meta": "meta",
"enabled": "enabled",
}
def _manager_enabled():
return bool(env("INBOUNDS_MANAGER_SOCKET"))
def _manager(method, path, body=None):
"""One call to the manager's API: its JSON, or its complaint as ours."""
socket_path = env("INBOUNDS_MANAGER_SOCKET")
if not socket_path:
die("The inbound manager is not enabled in this configuration (inbounds.manager.enable).")
conn = _UnixHTTPConnection(socket_path, MANAGER_TIMEOUT)
try:
conn.request(method, "/api/v1" + path, body=None if body is None else json.dumps(body),
headers={"Content-Type": "application/json"})
response = conn.getresponse()
status, raw = response.status, response.read()
except PermissionError:
die(f"Cannot use the inbound manager ({socket_path}): permission denied - {ask_group()}.", 77)
except (FileNotFoundError, ConnectionRefusedError):
die("The inbound manager is not running - see: proxy-ctl logs proxy-suite-inbounds-manager")
except (OSError, http.client.HTTPException) as e:
die(f"Cannot reach the inbound manager: {e}")
finally:
conn.close()
try:
value = json.loads(raw) if raw else None
except ValueError:
value = None
if status >= 400:
error = value.get("error") if isinstance(value, dict) else None
die(error or f"The inbound manager answered {status}.")
return value
def _when(ts):
return datetime.datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M") if ts else "-"
def _rate(bits):
if not bits:
return "-"
for unit, size in (("Gbit/s", 1e9), ("Mbit/s", 1e6), ("kbit/s", 1e3)):
if bits >= size:
return f"{bits / size:g} {unit}"
return f"{bits} bit/s"
def _user_status(row):
if not row.get("active"):
return "off: " + ",".join(row.get("reasons") or [])
return "on hold" if row.get("onHold") else "active"
def _user_expiry(row):
if row.get("onHold"):
return f"+{_span((row.get('policy') or {}).get('expiresAfter'))} on 1st use"
return _when(row.get("expiresAt"))
def _span(seconds):
for unit, size in (("w", 604800), ("d", 86400), ("h", 3600), ("m", 60)):
if seconds and seconds % size == 0:
return f"{seconds // size}{unit}"
return f"{seconds}s"
def _user_traffic(row):
traffic = row.get("traffic") or {}
used = _human_bytes(traffic.get("used") or 0)
return f"{used} / {_human_bytes(traffic['limit'])}" if traffic.get("limit") else used
def _manager_users_table(rows):
line = " {:<20} {:<18} {:<24} {:<17} {}"
print(line.format("USER", "STATUS", "TRAFFIC", "EXPIRES", "LISTENERS").rstrip())
for row in rows:
print(line.format(_s(row["name"]), _user_status(row), _user_traffic(row), _user_expiry(row),
",".join(row.get("listeners") or []) or "-").rstrip())
for problem in row.get("problems") or []:
print(f" ! {problem}")
def _manager_user_show(row):
policy = row.get("policy") or {}
traffic = row.get("traffic") or {}
speed = policy.get("speedLimit") or {}
out = [
f"{row['name']} ({row.get('source')}): {_user_status(row)}",
f" listeners {', '.join(row.get('listeners') or []) or '-'}",
f" expires {_user_expiry(row)}",
f" traffic {_user_traffic(row)} (down {_human_bytes(traffic.get('down') or 0)}, up {_human_bytes(traffic.get('up') or 0)})"
+ (f", renews {policy['trafficPeriod']} at {_when(traffic.get('periodEnd'))}" if traffic.get("periodEnd") else ""),
f" since {_when(traffic.get('periodStart'))}",
f" addresses {policy.get('ipLimit') or 'any number'} at once; online: {', '.join(row['online']['ips']) or '-'}",
f" speed down {_rate(speed.get('down'))}, up {_rate(speed.get('up'))}",
]
if row.get("subscription") and row["subscription"].get("url"):
out.append(f" sub {row['subscription']['url']}")
for key, value in sorted((policy.get("meta") or {}).items()):
out.append(f" meta.{key} = {value}")
overridden = sorted(set(row.get("stored") or {}) & set(row.get("declared") or {}))
if overridden:
out.append(f" (set at runtime over the config: {', '.join(overridden)})")
for problem in row.get("problems") or []:
out.append(f" ! {problem}")
print("\n".join(out))
def _policy_args(args):
"""Policy fields from `users set`'s flags; the arguments that are none of them."""
fields, rest, i = {}, [], 0
args = list(args)
while i < len(args):
arg = args[i]
flag, has_value, value = arg.partition("=")
if flag in POLICY_FLAGS or flag == "--meta":
if not has_value:
if i + 1 >= len(args):
usage(f"inbounds users set <name> {flag} <value>")
value = args[i + 1]
i += 1
if flag == "--meta":
key, sep, item = value.partition("=")
if not sep:
usage("inbounds users set <name> --meta <key>=<value>")
fields.setdefault("meta", {})[key] = item
else:
fields[POLICY_FLAGS[flag]] = value
elif arg in ("--enable", "--disable"):
fields["enabled"] = arg == "--enable"
else:
rest.append(arg)
i += 1
return fields, rest
def _manager_users(verb, args):
"""`inbounds users ...` with the manager on. False: not one of its verbs."""
as_json = "--json" in args
args = [a for a in args if a != "--json"]
def show(row):
print(_json_text(row)) if as_json else _manager_user_show(row)
if verb in ("list", "--json"):
rows = _manager("GET", "/users")
print(_json_text(rows)) if as_json or verb == "--json" else _manager_users_table(rows)
elif verb == "show" and len(args) == 1:
show(_manager("GET", f"/users/{urllib.parse.quote(args[0], safe='')}"))
elif verb == "add" and args:
fields, rest = _policy_args(args[1:])
listeners, order, i = [], None, 0
while i < len(rest):
if rest[i] in ("--listener", "--order") and i + 1 < len(rest):
if rest[i] == "--listener":
listeners.append(rest[i + 1])
else:
order = int(rest[i + 1]) if rest[i + 1].isdigit() else die(f"Not an order: {rest[i + 1]}")
i += 2
else:
usage("inbounds users add <name> [--order N] [--listener <tag>]... [policy flags: see users set]")
body = {"name": args[0], "listeners": listeners, "policy": fields}
if order is not None:
body["order"] = order
show(_manager("POST", "/users", body))
elif verb == "rm" and len(args) == 1:
print(_manager("DELETE", f"/users/{urllib.parse.quote(args[0], safe='')}").get("message", ""))
elif verb == "set" and args:
fields, rest = _policy_args(args[1:])
if rest or not fields:
usage("inbounds users set <name> [--expires T] [--traffic SIZE] [--period daily|weekly|monthly|none]"
" [--ips N] [--speed RATE[/RATE]] [--enable|--disable] [--meta k=v]...")
show(_manager("PATCH", f"/users/{urllib.parse.quote(args[0], safe='')}", fields))
elif verb == "unset" and len(args) >= 2:
unknown = [a for a in args[1:] if a not in POLICY_NAMES]
if unknown:
usage(f"inbounds users unset <name> <{'|'.join(POLICY_NAMES)}>...")
show(_manager("PATCH", f"/users/{urllib.parse.quote(args[0], safe='')}", {"unset": [POLICY_NAMES[a] for a in args[1:]]}))
elif verb in ("enable", "disable") and len(args) == 1:
show(_manager("POST", f"/users/{urllib.parse.quote(args[0], safe='')}/{verb}"))
elif verb == "reset" and len(args) == 1:
show(_manager("POST", f"/users/{urllib.parse.quote(args[0], safe='')}/reset-traffic"))
elif verb == "extend" and len([a for a in args if a != "--reset"]) in (2, 3):
reset = "--reset" in args
rest = [a for a in args if a != "--reset"]
if len(rest) == 2:
body = {"by": rest[1]}
elif rest[1] == "--until":
body = {"until": rest[2]}
else:
usage("inbounds users extend <name> <30d | --until <time>> [--reset]")
if reset:
body["resetTraffic"] = True
show(_manager("POST", f"/users/{urllib.parse.quote(rest[0], safe='')}/extend", body))
elif verb == "rotate-sub" and len(args) == 1:
show(_manager("POST", f"/users/{urllib.parse.quote(args[0], safe='')}/rotate-subscription"))
else:
return False
return True
def _inbound_bans(*args):
as_json = "--json" in args
args = [a for a in args if a != "--json"]
if args[:1] == ["rm"] and len(args) == 2:
result = _manager("DELETE", f"/bans/{urllib.parse.quote(args[1], safe='')}")
print(f"{result['ip']}: {result['lifted']} ban(s) lifted")
return
if args:
usage("inbounds bans [--json] | bans rm <address>")
bans = _manager("GET", "/bans")
if as_json:
print(_json_text(bans))
return
if not bans:
print("No address is banned.")
return
print(" {:<40} {:<6} {}".format("ADDRESS", "PORT", "LEFT"))
for ban in bans:
print(" {:<40} {:<6} {}".format(ban["ip"], ban["port"], f"{ban['expires']}s" if ban.get("expires") is not None else "-"))
def _inbound_export(*args):
"""The users, their policies, keys and traffic, as JSON: to a file (0600) or stdout."""
rest = [a for a in args if a != "--no-stats"]
if len(rest) > 1:
usage("inbounds export [file] [--no-stats]")
bundle = _manager("GET", "/export" + ("?stats=0" if "--no-stats" in args else ""))
text = json.dumps(bundle, indent=2) + "\n"
if not rest or rest[0] == "-":
sys.stdout.write(text)
return
fd = os.open(rest[0], os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as f:
# A file that was there keeps its mode through O_CREAT: this one holds every secret.
os.fchmod(f.fileno(), 0o600)
f.write(text)
users = len(((bundle.get("runtime") or {}).get("users") or {}))
print(f"Exported {users} runtime user(s), {len(bundle.get('policies') or {})} policies to {rest[0]} - it holds their secrets.")
def _inbound_import(*args):
rest = [a for a in args if a != "--replace"]
if len(rest) != 1:
usage("inbounds import <file|-> [--replace]")
try:
text = sys.stdin.read() if rest[0] == "-" else open(rest[0], encoding="utf-8").read()
bundle = json.loads(text)
except (OSError, ValueError) as e:
die(f"Cannot read {rest[0]}: {e}")
report = _manager("POST", "/import", {"bundle": bundle, "replace": "--replace" in args})
for key in ("users", "listeners", "policies", "amneziaWg", "salamander"):
if report.get(key):
print(f"{key}: {', '.join(report[key])}")
if report.get("subscriptionKey"):
print("subscriptionKey: taken; the subscription URLs are the exported server's")
for line in report.get("skipped") or []:
print(f"skipped: {line}")
for line in report.get("applied") or []:
print(f"applied: {line}")
def _inbound_events(*args):
limit = args[0] if args and args[0].isdigit() else "50"
events = _manager("GET", f"/events?limit={limit}")
if "--json" in args:
print(_json_text(events))
return
for event in events:
print(f"{_when(event['at'])} {event['event']:<15} {event.get('user') or '-':<20} {json.dumps(event.get('data') or {}, sort_keys=True)}")
def _inbound_users(verb="list", *args):
if _manager_enabled() and _manager_users(verb, list(args)):
return
if verb in ("show", "set", "unset", "enable", "disable", "reset", "extend", "rotate-sub"):
die("Policies need the inbound manager (inbounds.manager.enable).")
if verb in ("list", "--json"):
sys.stdout.write(_inbound_runtime("users", *(["--json"] if "--json" in (verb, *args) else []), listing=True)[1])
elif verb == "add" and args:
@@ -6219,8 +6580,10 @@ def _inbound_users(verb="list", *args):
_inbound_bindings_set(tag=args[0], wanted=args[1:])
else:
usage(
"inbounds users [list] | add <name> [--order N] [--listener <tag>]... | rm <name> | order <name> <N>"
" | listeners <name> [tag...] | on <tag> [user...]"
"inbounds users [list] [--json] | show <name> | add <name> [--order N] [--listener <tag>]... | rm <name>"
" | order <name> <N> | listeners <name> [tag...] | on <tag> [user...]"
" | set <name> [policy flags] | unset <name> <field>... | enable|disable|reset <name>"
" | extend <name> <30d>|--until <time> | rotate-sub <name>"
)
@@ -6285,8 +6648,19 @@ def cmd_inbounds(verb="list", *args):
_inbound_online()
elif verb == "sub":
_inbound_subscriptions(*args)
elif verb == "bans":
_inbound_bans(*args)
elif verb == "export":
_inbound_export(*args)
elif verb == "import":
_inbound_import(*args)
elif verb == "events":
_inbound_events(*args)
else:
usage("inbounds [list] | link <tag> [user] [--qr] | sub [user] [--qr] | stats [days] [--by user|inbound|outbound] | online")
usage(
"inbounds [list] | link <tag> [user] [--qr] | sub [user] [--qr] | stats [days] [--by user|inbound|outbound]"
" | online | users ... | bans | export [file] | import <file> | events"
)
# --- main ---------------------------------------------------------------------
+14 -1
View File
@@ -1515,13 +1515,26 @@ class ProxySuiteGui(Adw.Application):
if self.timer is None:
self.timer = GLib.timeout_add_seconds(self.refresh, self.tick)
self.reload()
if not options.get("hidden"):
# proxy-suite:// links, from xdg-open (the .desktop file's %u): shown even to --hidden.
links = [a for a in command_line.get_arguments()[1:] if a.lower().startswith(model.DEEP_LINK_SCHEME + ":")]
if not options.get("hidden") or links:
# A launcher's token comes along when the running instance is asked to show itself.
platform = command_line.get_platform_data()
token = platform.lookup_value("activation-token", None) if platform else None
self.present(options.get("tab"), token=token.get_string() if token else None)
for link in links:
self.open_link(link)
return 0
def open_link(self, link):
"""A proxy-suite:// link: what it adds, run once confirmed."""
argv, why, stdin = model.deep_link_argv(link)
if argv is None:
self.window.toast(why)
return
# Asked first, as a paste is: any web page can open such a link.
self.confirm(argv, lambda: self.run_argv("run", argv, self.window, stdin=stdin), self.window, stdin=stdin)
def do_activate(self):
self.present()
+23
View File
@@ -16,6 +16,7 @@ import signal
import subprocess
import sys
import time
import urllib.parse
import zlib
from dataclasses import dataclass, field, replace
from typing import Callable
@@ -1360,6 +1361,28 @@ def paste_argv(tab_id, text):
return None, "Not a share link, a subscription URL or a host.", None
DEEP_LINK_SCHEME = "proxy-suite"
def deep_link_argv(link):
"""What a proxy-suite://install-config?url=<subscription>&name=... link runs, as paste_argv.
The subscription pages of inbounds.manager offer it on Linux, as clash:// for Clash. Any web
page can open one, so the GUI asks first. Only a subscription: the URL on stdin, and
proxy-ctl refuses plain http. name is a title, so it is made a tag as proxy-ctl makes one
(-2, -3... when taken); without one left, proxy-ctl names it after its host.
"""
parts = urllib.parse.urlsplit((link or "").strip())
if parts.scheme.lower() != DEEP_LINK_SCHEME or parts.netloc.lower() not in ("install-config", "installconfig"):
return None, f"Not a {DEEP_LINK_SCHEME}://install-config link.", None
query = urllib.parse.parse_qs(parts.query)
url = (query.get("url") or [""])[0].strip()
if url.split("://", 1)[0].lower() not in ("http", "https") or len(url.splitlines()) > 1:
return None, "The link carries no subscription URL.", None
tag = ctl._unique_runtime_tag("subscription", (query.get("name") or [""])[0], "")
return ["proxy", "subs", "add", *([tag] if tag else []), "-"], "", url
def _awg_paste(tab_id, text):
"""An AmneziaWG config, on stdin: an outbound where outbounds are, else a global profile."""
outbound = ctl.env("AWG_RUNTIME_OUTBOUNDS") == "1"
+135
View File
@@ -2175,6 +2175,141 @@ class OutboundTestTest(EnvTest):
self.assertIn("proxy-suite group, or re-run with sudo", err)
class InboundManagerTest(EnvTest):
"""inbounds.manager through proxy-ctl: requests to its socket, its answers shown."""
ROW = {
"name": "alice", "source": "runtime", "active": False, "reasons": ["traffic"], "listeners": ["vless-in"],
"problems": [], "policy": {"trafficLimit": 1073741824, "trafficPeriod": "monthly", "expiresAt": None, "ipLimit": 2,
"speedLimit": {"up": 5000000, "down": 20000000}, "meta": {"tg": "42"}, "enabled": True},
"stored": {"ipLimit": 2}, "declared": {},
"traffic": {"up": 1, "down": 1073741823, "used": 1073741824, "limit": 1073741824, "periodStart": 1700000000,
"periodEnd": 1702592000},
"expiresAt": None, "online": {"ips": ["198.51.100.7"], "lastSeen": None},
"subscription": {"token": "a" * 32, "url": "https://vpn.example.com/sub/" + "a" * 32},
}
def setUp(self):
super().setUp()
import http.server
import socketserver
self.requests = []
self.answers = {}
test = self
class Handler(http.server.BaseHTTPRequestHandler):
def log_message(self, *_):
pass
def address_string(self):
return "unix"
def handle_one(self):
length = int(self.headers.get("Content-Length") or 0)
body = json.loads(self.rfile.read(length)) if length else None
test.requests.append((self.command, self.path, body))
status, value = test.answers.get((self.command, self.path.split("?")[0]), (200, test.ROW))
raw = json.dumps(value).encode()
self.send_response(status)
self.send_header("Content-Length", str(len(raw)))
self.end_headers()
self.wfile.write(raw)
do_GET = do_POST = do_PATCH = do_DELETE = handle_one
class Server(socketserver.ThreadingMixIn, socketserver.UnixStreamServer):
daemon_threads = True
def get_request(self):
request, _ = super().get_request()
return request, ("unix", 0)
sock = self.path("api.sock")
server = Server(sock, Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
self.addCleanup(server.server_close)
self.addCleanup(server.shutdown)
os.environ.update(INBOUNDS_ENABLED="1", INBOUNDS_MANAGER_SOCKET=sock)
def test_set_unset_and_the_rest(self):
out = ok(ctl.cmd_inbounds, "users", "set", "alice", "--traffic", "1G", "--speed=20M/5M", "--meta", "tg=42", "--disable",
"--expires", "+30d")
self.assertEqual(self.requests[-1], ("PATCH", "/api/v1/users/alice", {
"trafficLimit": "1G", "speedLimit": "20M/5M", "meta": {"tg": "42"}, "enabled": False, "expiresAt": "+30d"}))
self.assertIn("alice (runtime): off: traffic", out)
self.assertIn("down 20 Mbit/s, up 5 Mbit/s", out)
self.assertIn("https://vpn.example.com/sub/", out)
ok(ctl.cmd_inbounds, "users", "unset", "alice", "ips", "speed")
self.assertEqual(self.requests[-1][2], {"unset": ["ipLimit", "speedLimit"]})
ok(ctl.cmd_inbounds, "users", "extend", "alice", "30d")
self.assertEqual(self.requests[-1], ("POST", "/api/v1/users/alice/extend", {"by": "30d"}))
ok(ctl.cmd_inbounds, "users", "reset", "alice")
self.assertEqual(self.requests[-1][:2], ("POST", "/api/v1/users/alice/reset-traffic"))
ok(ctl.cmd_inbounds, "users", "add", "bob", "--listener", "vless-in", "--ips", "3", "--order", "7")
self.assertEqual(self.requests[-1], ("POST", "/api/v1/users", {
"name": "bob", "listeners": ["vless-in"], "policy": {"ipLimit": "3"}, "order": 7}))
rows = json.loads(ok(ctl.cmd_inbounds, "users", "show", "alice", "--json"))
self.assertEqual(rows["name"], "alice")
def test_on_hold_and_renewals(self):
ok(ctl.cmd_inbounds, "users", "add", "bob", "--on-hold", "30d")
self.assertEqual(self.requests[-1][2]["policy"], {"expiresAfter": "30d"})
ok(ctl.cmd_inbounds, "users", "unset", "bob", "hold")
self.assertEqual(self.requests[-1][2], {"unset": ["expiresAfter"]})
ok(ctl.cmd_inbounds, "users", "extend", "alice", "30d", "--reset")
self.assertEqual(self.requests[-1], ("POST", "/api/v1/users/alice/extend", {"by": "30d", "resetTraffic": True}))
ok(ctl.cmd_inbounds, "users", "extend", "alice", "--until", "2027-01-31")
self.assertEqual(self.requests[-1][2], {"until": "2027-01-31"})
held = {**self.ROW, "active": True, "reasons": [], "onHold": True,
"policy": {**self.ROW["policy"], "expiresAfter": 30 * 86400}}
self.answers[("GET", "/api/v1/users")] = (200, [held])
out = ok(ctl.cmd_inbounds, "users")
self.assertIn("on hold", out)
self.assertIn("+30d on 1st use", out)
def test_list_table(self):
self.answers[("GET", "/api/v1/users")] = (200, [self.ROW])
out = ok(ctl.cmd_inbounds, "users")
self.assertIn("alice", out)
self.assertIn("1.0 GiB / 1.0 GiB", out)
self.assertIn("off: traffic", out)
def test_errors_and_absence(self):
self.answers[("PATCH", "/api/v1/users/zed")] = (404, {"error": "no user 'zed'"})
status, _, err = run(ctl.cmd_inbounds, "users", "set", "zed", "--ips", "1")
self.assertEqual(status, 1)
self.assertIn("no user 'zed'", err)
os.environ["INBOUNDS_MANAGER_SOCKET"] = ""
status, _, err = run(ctl.cmd_inbounds, "users", "set", "zed", "--ips", "1")
self.assertIn("need the inbound manager", err)
os.environ["INBOUNDS_MANAGER_SOCKET"] = self.path("nothing.sock")
status, _, err = run(ctl.cmd_inbounds, "bans")
self.assertIn("not running", err)
def test_subscription_urls_from_the_manager(self):
os.environ.update(INBOUNDS_SUBS_FILE=self.path("absent.json"), INBOUNDS_SUB_BASE_URL="https://vpn.example.com/sub")
self.answers[("GET", "/api/v1/users")] = (200, [self.ROW])
self.assertEqual(ok(ctl.cmd_inbounds, "sub", "alice"), "https://vpn.example.com/sub/" + "a" * 32 + "\n")
self.assertIn("alice", ok(ctl.cmd_inbounds, "sub"))
def test_bans_export_import(self):
self.answers[("GET", "/api/v1/bans")] = (200, [{"ip": "203.0.113.9", "port": 443, "expires": 120}])
self.assertIn("203.0.113.9", ok(ctl.cmd_inbounds, "bans"))
self.answers[("DELETE", "/api/v1/bans/203.0.113.9")] = (200, {"ip": "203.0.113.9", "lifted": 1})
self.assertIn("1 ban(s) lifted", ok(ctl.cmd_inbounds, "bans", "rm", "203.0.113.9"))
bundle = {"format": "proxy-suite-inbounds", "version": 1, "runtime": {"users": {"a": {}}}, "policies": {}}
self.answers[("GET", "/api/v1/export")] = (200, bundle)
target = self.path("export.json")
ok(ctl.cmd_inbounds, "export", target, "--no-stats")
self.assertEqual(self.requests[-1][1], "/api/v1/export?stats=0")
self.assertEqual(stat.S_IMODE(os.stat(target).st_mode), 0o600)
self.answers[("POST", "/api/v1/import")] = (200, {"users": ["a"], "skipped": [], "applied": ["vless-in: +a"]})
out = ok(ctl.cmd_inbounds, "import", target, "--replace")
self.assertEqual(self.requests[-1][2], {"bundle": bundle, "replace": True})
self.assertIn("users: a", out)
class InboundRuntimeTest(EnvTest):
"""inbounds.runtime through proxy-ctl: the tool does the work, proxy-ctl reloads after."""
+30
View File
@@ -11,6 +11,7 @@ import subprocess
import tempfile
import time
import unittest
import urllib.parse
import zlib
from unittest import mock
@@ -406,6 +407,35 @@ class ModelTest(unittest.TestCase):
self.assertEqual([i.id for i in model.tray_menu(None)], ["status", "open", "sep-0", "quit"])
self.assertEqual(model.icon_name(ctl._overall_state(None)), "proxy-suite-disabled-unknown")
def test_deep_link_argv(self):
link = model.deep_link_argv
sub = "https://vpn.test/sub/" + "a" * 32 + "?format=links&x=1"
quoted = urllib.parse.quote(sub, safe="")
# The URL on stdin, as pasted; the name made a tag, one not taken yet.
with mock.patch.object(ctl, "_runtime_tags", lambda kind: ["work"]), \
mock.patch.object(ctl, "_sub_tags", lambda: ["home"]):
self.assertEqual(link(f"proxy-suite://install-config?url={quoted}&name=VPN%20alice"),
(["proxy", "subs", "add", "VPN-alice", "-"], "", sub))
for name, tag in [("work", "work-2"), ("home", "home-2"), ("tor", "tor-2"), ("..%2F..%2Fx", "x"),
("%F0%9F%87%A9%F0%9F%87%AA%20" + "y" * 40, "y" * 32)]:
self.assertEqual(link(f"proxy-suite://install-config?url={quoted}&name={name}")[0][3], tag, name)
# No name, or none left of it: proxy-ctl names it after its host.
for name in ["", "&name=", "&name=%F0%9F%87%A9%F0%9F%87%AA"]:
self.assertEqual(link(f"proxy-suite://install-config?url={quoted}{name}")[0], ["proxy", "subs", "add", "-"], name)
self.assertEqual(link(f"PROXY-SUITE://installconfig?url={quoted}")[2], sub)
for text in [
"",
f"clash://install-config?url={quoted}",
f"proxy-suite://import?url={quoted}",
"proxy-suite://install-config?name=x",
"proxy-suite://install-config?url=vless%3A%2F%2Fu%40a.test%3A443",
"proxy-suite://install-config?url=https%3A%2F%2Fa.test%2F%0Ahttps%3A%2F%2Fb.test%2F",
]:
argv, why, stdin = link(text)
self.assertIsNone(argv, text)
self.assertIsNone(stdin)
self.assertTrue(why)
def test_paste_argv(self):
paste = model.paste_argv
# Links and JSON carry credentials: on stdin, never in argv (ps, pkexec's log).
+29 -19
View File
@@ -1,27 +1,37 @@
# Xray-core ahead of nixpkgs, which still ships 26.3.27. From 26.9.8 its go.mod
# asks for Go 1.27, so the builder is swapped along with the source. Steps
# aside once nixpkgs has caught up.
# aside once nixpkgs has caught up; the patch stays.
#
# The patch marks an outbound's sockets by the level of the inbound user they dial for
# (inbounds.manager's speed limits); passthru.userLevelMark says it is in.
{ pkgs }:
let
inherit (pkgs) lib;
version = "26.10.10";
base =
if lib.versionAtLeast pkgs.xray.version version then
pkgs.xray
else
(pkgs.xray.override (
args: lib.optionalAttrs (args ? buildGo126Module) { buildGo126Module = pkgs.buildGo127Module; }
)).overrideAttrs
(
finalAttrs: _: {
inherit version;
src = pkgs.fetchFromGitHub {
owner = "XTLS";
repo = "Xray-core";
rev = "v${finalAttrs.version}";
hash = "sha256-M6biUT2RgP4xNGj9RUAVG7rrGNm65+sWL7pRQpbpWFI=";
};
vendorHash = "sha256-XfTEpPMKyIhaoG53omH5rewI86QFNc9pnzhvZvxgFp0=";
}
);
in
if lib.versionAtLeast pkgs.xray.version version then
pkgs.xray
else
(pkgs.xray.override (
args: lib.optionalAttrs (args ? buildGo126Module) { buildGo126Module = pkgs.buildGo127Module; }
)).overrideAttrs
(
finalAttrs: _: {
inherit version;
src = pkgs.fetchFromGitHub {
owner = "XTLS";
repo = "Xray-core";
rev = "v${finalAttrs.version}";
hash = "sha256-M6biUT2RgP4xNGj9RUAVG7rrGNm65+sWL7pRQpbpWFI=";
};
vendorHash = "sha256-XfTEpPMKyIhaoG53omH5rewI86QFNc9pnzhvZvxgFp0=";
}
)
base.overrideAttrs (old: {
patches = (old.patches or [ ]) ++ [ ./patches/xray-user-level-mark.patch ];
passthru = (old.passthru or { }) // {
userLevelMark = true;
};
})
+3
View File
@@ -240,6 +240,9 @@ def render_server_config(listener: dict, state: dict) -> str:
awg = listener["amneziaWg"]
peers = []
for user in listener["users"]:
# Switched off by the manager: no peer, but the keys and address stay in the state.
if user.get("active") is False:
continue
entry = state["users"][user["name"]]
peer: dict[str, Any] = {
"publicKey": entry["publicKey"],
+5 -7
View File
@@ -5,8 +5,7 @@ import argparse
import json
import sys
import inbound_runtime
from proxy_inbound import build_inbounds
from inbound_apply import render
def main() -> None:
@@ -42,14 +41,13 @@ def main() -> None:
sys.exit(1)
try:
spec, runtime, warnings = inbound_runtime.merge(spec, check_ports=True)
for warning in warnings:
print(f"proxy-suite: warning: {warning}", file=sys.stderr)
result = build_inbounds(spec, server_address, args.onion_address)
template = None
if args.template and spec.get("runtime"):
with open(args.template, encoding="utf-8") as handle:
template = json.load(handle)
result.update(inbound_runtime.routing(spec, runtime, template["routing"]["rules"]))
result, warnings = render(spec, server_address, args.onion_address, template, check_ports=True)
for warning in warnings:
print(f"proxy-suite: warning: {warning}", file=sys.stderr)
except (ValueError, OSError) as exc:
print(f"error: {exc}", file=sys.stderr)
sys.exit(1)
+473
View File
@@ -0,0 +1,473 @@
#!/usr/bin/env python3
"""Apply a change to the inbounds without restarting them, where XRay's API can.
The inbounds' start script keeps what it rendered (build-inbound.py's output) and with
what, in its runtime directory. This renders the spec again the same way and compares:
- users who came, went or changed on a listener that is otherwise the same: removed and
added through the API (rmu, adu), and the connections of those removed cut (ss -K for
TCP, a short drop in proxy-suite's nftables table for UDP), since XRay keeps them;
- the routing rules (runtime users' serverSource rules): replaced whole (adrules);
- their serverSource outbounds and addresses: added and removed (ado, rmo, ip addr);
- the share links and subscriptions: written again by the module's own writer;
- AmneziaWG listeners whose peers changed: their interfaces synced (awg syncconf), which
leaves the other peers' sessions alone.
Anything else (a listener added, removed or changed, a Shadowsocks listener going between
one user and many, socks or http accounts) needs the restart it always needed, and so does
an API call that fails. One apply at a time (a lock in the runtime directory).
"""
from __future__ import annotations
import argparse
import copy
import fcntl
import json
import os
import subprocess
import sys
import tempfile
import inbound_runtime
from proxy_inbound import build_inbounds
# The inbound's user list, by XRay protocol; a Shadowsocks inbound has one only with more
# than one user. The others (socks, http, a single-user Shadowsocks, AmneziaWG's) change
# only with a restart.
USER_LISTS = {"vless": "clients", "vmess": "clients", "trojan": "clients", "hysteria": "clients", "shadowsocks": "clients"}
# Inbounds that speak UDP to their clients: a cut user's sessions there are dropped for a
# while instead (QUIC has no socket to kill).
UDP_CUT_SECONDS = 90
def render(spec: dict, server_address: str, onion_address: str = "", template: dict | None = None,
check_ports: bool | set = False, now: float | None = None) -> tuple[dict, list[str]]:
"""What build-inbound.py prints: the inbounds, links and subscriptions, and with
inbounds.runtime and the template its routing additions. check_ports: whether a runtime
listener's port must be free, or the ports the running XRay holds, which count as free."""
merged, runtime, warnings = inbound_runtime.merge(spec, check_ports=check_ports, now=now)
result = build_inbounds(merged, server_address, onion_address)
if template is not None and merged.get("runtime"):
result.update(inbound_runtime.routing(merged, runtime, template["routing"]["rules"]))
return result, warnings
# --- the comparison -------------------------------------------------------------------
def split_users(inbound: dict) -> tuple[dict, dict[str, dict]]:
"""The inbound without its users, and its users by email. One whose users cannot be
told apart from the rest comes whole, with none."""
key = USER_LISTS.get(inbound.get("protocol", ""))
settings = inbound.get("settings") or {}
if key is None or not isinstance(settings.get(key), list):
return inbound, {}
shape = copy.deepcopy(inbound)
users = {client.get("email"): client for client in shape["settings"].pop(key)}
if None in users or len(users) != len(settings[key]):
return inbound, {}
return shape, users
def plan(old: dict, new: dict) -> dict:
"""What it takes to go from the old rendering to the new one: {"restart": [reasons],
"users": {tag: {"remove": [emails], "add": [clients]}}, "rules": rules | None,
"outbounds": {"remove": [tags], "add": [outbounds]}, "addresses": {"remove", "add"},
"outputs": bool}. A non-empty "restart" means the rest does not apply."""
result: dict = {"restart": [], "users": {}, "rules": None, "outbounds": {"remove": [], "add": []},
"addresses": {"remove": [], "add": []}, "outputs": False}
old_inbounds = {ib.get("tag"): ib for ib in old.get("inbounds") or []}
new_inbounds = {ib.get("tag"): ib for ib in new.get("inbounds") or []}
if set(old_inbounds) != set(new_inbounds):
added = sorted(set(new_inbounds) - set(old_inbounds))
gone = sorted(set(old_inbounds) - set(new_inbounds))
result["restart"].append(
"listeners " + ", ".join(filter(None, [added and f"added: {', '.join(added)}", gone and f"gone: {', '.join(gone)}"]))
)
return result
for tag, inbound in new_inbounds.items():
old_shape, old_users = split_users(old_inbounds[tag])
new_shape, new_users = split_users(inbound)
if old_shape != new_shape:
result["restart"].append(f"listener '{tag}' changed")
continue
remove = sorted(e for e in old_users if e not in new_users or old_users[e] != new_users[e])
add = [new_users[e] for e in sorted(new_users) if e not in old_users or old_users[e] != new_users[e]]
if remove or add:
result["users"][tag] = {"remove": remove, "add": add}
if result["restart"]:
return result
if (old.get("rules") or []) != (new.get("rules") or []):
result["rules"] = new.get("rules") or []
old_outbounds = {ob["tag"]: ob for ob in old.get("selfOutbounds") or []}
new_outbounds = {ob["tag"]: ob for ob in new.get("selfOutbounds") or []}
result["outbounds"]["remove"] = sorted(t for t in old_outbounds if old_outbounds[t] != new_outbounds.get(t))
result["outbounds"]["add"] = [new_outbounds[t] for t in sorted(new_outbounds) if new_outbounds[t] != old_outbounds.get(t)]
def addresses(rendering):
return {(family, entry[key]) for entry in rendering.get("selfAddresses") or []
for family, key in (("4", "ipv4"), ("6", "ipv6")) if entry.get(key)}
old_addresses, new_addresses = addresses(old), addresses(new)
result["addresses"]["remove"] = sorted(old_addresses - new_addresses)
result["addresses"]["add"] = sorted(new_addresses - old_addresses)
result["outputs"] = (old.get("links"), old.get("subscriptions")) != (new.get("links"), new.get("subscriptions"))
return result
def is_noop(steps: dict) -> bool:
return not (steps["restart"] or steps["users"] or steps["rules"] is not None or steps["outbounds"]["remove"]
or steps["outbounds"]["add"] or steps["addresses"]["remove"] or steps["addresses"]["add"]
or steps["outputs"])
def udp_inbound(inbound: dict) -> bool:
stream = inbound.get("streamSettings") or {}
alpn = ((stream.get("tlsSettings") or {}).get("alpn")) or []
return inbound.get("protocol") == "hysteria" or (stream.get("network") == "xhttp" and alpn == ["h3"])
# --- doing it -------------------------------------------------------------------------
class ApplyError(RuntimeError):
pass
class Tools:
"""The binaries and names the module hands over (apply.json), and how to call them."""
def __init__(self, config: dict, dry_run: bool = False):
self.config = config
self.dry_run = dry_run
self.log: list[str] = []
def run(self, argv: list[str], what: str, stdin: str | None = None, check: bool = True) -> str:
self.log.append(" ".join(argv))
if self.dry_run:
return ""
env = dict(os.environ)
env.update(self.config.get("env") or {})
try:
done = subprocess.run(argv, input=stdin, capture_output=True, text=True, env=env, timeout=30)
except (OSError, subprocess.TimeoutExpired) as exc:
raise ApplyError(f"{what}: {exc}") from None
if check and done.returncode != 0:
raise ApplyError(f"{what}: {(done.stderr or done.stdout).strip() or f'exit {done.returncode}'}")
return done.stdout
def xray_api(self, command: str, *args: str, what: str) -> str:
# The server first: Go's flags end at the first argument that is none (rmu's emails).
return self.run([self.config["xray"], "api", command, f"--server={self.config['api']}", *args], what)
def xray_api_file(self, command: str, value: dict, what: str) -> str:
with tempfile.NamedTemporaryFile("w", suffix=".json", dir=self.config.get("tmpDir"), delete=True) as handle:
json.dump(value, handle)
handle.flush()
return self.run([self.config["xray"], "api", command, f"--server={self.config['api']}", handle.name], what)
def online_ips(tools: Tools, email: str) -> list[str]:
"""Where a user is connected from now, as XRay counts it (loopback never is)."""
try:
out = tools.xray_api("statsonlineiplist", "-email", email, what=f"online addresses of {email}")
return sorted((json.loads(out or "{}").get("ips") or {}).keys())
except (ApplyError, ValueError):
return []
def cut(tools: Tools, ips: list[str], tcp_ports: set[int], udp_ports: set[int]) -> None:
"""Close what these addresses hold open on these ports: TCP sockets killed, UDP dropped
for a while. Other users behind the same address reconnect once."""
ss = tools.config.get("ss")
if ss:
for ip in ips:
# A prefix: a bare IPv6 address would read as address and port to ss.
prefix = f"{ip}/128" if ":" in ip else f"{ip}/32"
for port in sorted(tcp_ports):
tools.run([ss, "-K", "-n", "-t", "state", "established", f"( sport = :{port} )", "dst", prefix],
f"closing {ip}'s connections to {port}", check=False)
nft, table = tools.config.get("nft"), tools.config.get("nftTable")
if nft and table and udp_ports and ips:
lines = []
for ip in ips:
family = "6" if ":" in ip else "4"
for port in sorted(udp_ports):
lines.append(f"add element inet {table} cut{family} {{ {ip} . {port} timeout {UDP_CUT_SECONDS}s }}")
tools.run([nft, "-f", "-"], "dropping UDP of the users cut off", stdin="\n".join(lines) + "\n", check=False)
def run_steps(tools: Tools, steps: dict, new: dict, template: dict | None) -> list[str]:
"""Carry out a plan without "restart". What was done, line by line."""
done = []
by_tag = {ib["tag"]: ib for ib in new.get("inbounds") or []}
# Where the users going away are connected from, before XRay forgets them.
leaving: dict[str, list[str]] = {}
for change in steps["users"].values():
for email in change["remove"]:
if email not in leaving:
leaving[email] = online_ips(tools, email)
tcp_ports: dict[str, set[int]] = {}
udp_ports: dict[str, set[int]] = {}
for tag, change in sorted(steps["users"].items()):
inbound = by_tag[tag]
if change["remove"]:
tools.xray_api("rmu", f"-tag={tag}", *change["remove"], what=f"removing users from {tag}")
ports = udp_ports if udp_inbound(inbound) else tcp_ports
for email in change["remove"]:
ports.setdefault(email, set()).add(int(inbound["port"]))
done.append(f"{tag}: -{','.join(change['remove'])}")
if change["add"]:
key = USER_LISTS[inbound["protocol"]]
partial = copy.deepcopy(inbound)
partial["settings"][key] = change["add"]
tools.xray_api_file("adu", {"inbounds": [partial]}, f"adding users to {tag}")
done.append(f"{tag}: +{','.join(c['email'] for c in change['add'])}")
# A user whose secret or level changed was removed and added: their old sessions go too.
for email, ips in sorted(leaving.items()):
if ips:
cut(tools, ips, tcp_ports.get(email, set()), udp_ports.get(email, set()))
done.append(f"cut {email} ({', '.join(ips)})")
for tag in steps["outbounds"]["remove"]:
tools.xray_api("rmo", tag, what=f"removing outbound {tag}")
if steps["outbounds"]["add"]:
tools.xray_api_file("ado", {"outbounds": steps["outbounds"]["add"]}, "adding serverSource outbounds")
if steps["outbounds"]["remove"] or steps["outbounds"]["add"]:
done.append("serverSource outbounds")
if steps["rules"] is not None:
routing = {key: value for key, value in ((template or {}).get("routing") or {}).items() if key != "rules"}
routing["rules"] = steps["rules"]
tools.xray_api_file("adrules", {"routing": routing}, "replacing the routing rules")
done.append("routing rules")
ip, interface = tools.config.get("ip"), tools.config.get("selfInterface")
if ip and interface:
for family, address in steps["addresses"]["remove"]:
prefix = "32" if family == "4" else "128"
tools.run([ip, f"-{family}", "addr", "del", f"{address}/{prefix}", "dev", interface],
f"removing {address}", check=False)
for family, address in steps["addresses"]["add"]:
prefix = "32" if family == "4" else "128"
extra = ["nodad"] if family == "6" else []
tools.run([ip, f"-{family}", "addr", "add", f"{address}/{prefix}", "dev", interface, *extra],
f"adding {address}")
if steps["addresses"]["remove"] or steps["addresses"]["add"]:
done.append("serverSource addresses")
return done
def sync_config(runtime_dir: str, steps: dict, new: dict) -> None:
"""The running XRay's config.json, as it now runs: what proxy-ctl and people read. In
place, so its owner, mode and ACLs stay."""
path = os.path.join(runtime_dir, "config.json")
config = load_json(path)
if not isinstance(config, dict):
return
by_tag = {ib["tag"]: ib for ib in new.get("inbounds") or []}
for inbound in config.get("inbounds") or []:
tag = inbound.get("tag")
if tag in steps["users"]:
key = USER_LISTS[inbound["protocol"]]
inbound.setdefault("settings", {})[key] = copy.deepcopy(by_tag[tag]["settings"][key])
if steps["rules"] is not None:
config.setdefault("routing", {})["rules"] = steps["rules"]
gone = set(steps["outbounds"]["remove"])
if gone or steps["outbounds"]["add"]:
config["outbounds"] = [ob for ob in config.get("outbounds") or [] if ob.get("tag") not in gone]
config["outbounds"] += copy.deepcopy(steps["outbounds"]["add"])
fd = os.open(path, os.O_WRONLY | os.O_TRUNC | os.O_NOFOLLOW)
with os.fdopen(fd, "w", encoding="utf-8") as handle:
json.dump(config, handle)
def write_outputs(tools: Tools, rendered_path: str) -> None:
script = tools.config.get("outputsScript")
if script:
tools.run([script, rendered_path], "writing the share links and subscriptions")
def save_rendering(runtime_dir: str, rendered: dict) -> str:
path = os.path.join(runtime_dir, "rendered.json")
tmp = path + ".tmp"
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as handle:
json.dump(rendered, handle)
os.replace(tmp, path)
return path
def load_json(path: str):
try:
with open(path, encoding="utf-8") as handle:
return json.load(handle)
except (OSError, ValueError):
return None
def restart(tools: Tools, units: list[str], reason: str) -> list[str]:
systemctl = tools.config["systemctl"]
tools.run([systemctl, "try-restart", *units], f"restarting {', '.join(units)}")
return [f"restarted {', '.join(units)}: {reason}"]
def apply_xray(tools: Tools, spec: dict) -> list[str]:
"""The XRay side; restarts the inbounds when the API cannot do it."""
config = tools.config
runtime_dir = config["runtimeDir"]
unit = config["unit"]
old = load_json(os.path.join(runtime_dir, "rendered.json"))
args = load_json(os.path.join(runtime_dir, "render-args.json"))
if not isinstance(old, dict) or not isinstance(args, dict):
return restart(tools, [unit], "nothing rendered to compare with")
template = load_json(config["template"]) if config.get("template") else None
try:
server_address = args.get("serverAddress") or spec.get("serverAddress") or ""
# As the start script checks them, but the ports XRay holds now are its own.
held = {int(ib["port"]) for ib in old.get("inbounds") or [] if isinstance(ib.get("port"), int)}
new, warnings = render(spec, server_address, args.get("onionAddress", ""), template, check_ports=held or True)
except (ValueError, OSError) as exc:
return restart(tools, [unit], f"cannot render: {exc}")
for warning in warnings:
print(f"proxy-suite: warning: {warning}", file=sys.stderr)
steps = plan(old, new)
if steps["restart"]:
return restart(tools, [unit], "; ".join(steps["restart"]))
if is_noop(steps):
return []
try:
done = run_steps(tools, steps, new, template)
except ApplyError as exc:
return restart(tools, [unit], f"the API failed: {exc}")
path = save_rendering(runtime_dir, new)
try:
sync_config(runtime_dir, steps, new)
except (OSError, ValueError, KeyError) as exc:
print(f"proxy-suite: config.json not updated: {exc}", file=sys.stderr)
if steps["outputs"]:
try:
write_outputs(tools, path)
done.append("links and subscriptions")
except ApplyError as exc:
print(f"proxy-suite: {exc}", file=sys.stderr)
return done
# --- AmneziaWG ------------------------------------------------------------------------
STRIPPED_INTERFACE_KEYS = {"address", "dns", "mtu", "table", "preup", "postup", "predown", "postdown", "saveconfig"}
def strip_config(text: str) -> str:
"""awg-quick strip: what `awg setconf` takes, without awg-quick's own keys."""
lines, section = [], ""
for line in text.splitlines():
stripped = line.strip()
if stripped.startswith("["):
section = stripped.lower()
elif section == "[interface]" and "=" in stripped:
if stripped.split("=", 1)[0].strip().lower() in STRIPPED_INTERFACE_KEYS:
continue
lines.append(line)
return "\n".join(lines) + "\n"
def interface_part(text: str) -> str:
out, section = [], ""
for line in strip_config(text).splitlines():
if line.strip().startswith("["):
section = line.strip().lower()
if section == "[interface]":
out.append(line.strip())
return "\n".join(out)
def apply_awg(tools: Tools, spec: dict) -> list[str]:
"""Write the AmneziaWG listeners' configs again and sync the interfaces whose peers
changed. A change to an interface itself restarts their unit."""
config = tools.config
awg = config.get("awg")
if not awg or not any(listener.get("type") == "amneziawg" for listener in spec["listeners"]):
return []
import awg_inbound
awg_dir = config["awgRuntimeDir"]
if not os.path.isdir(awg_dir):
return restart(tools, [config["awgUnit"]], "the AmneziaWG listeners are not running")
before = {}
for listener in spec["listeners"]:
if listener.get("type") == "amneziawg":
path = os.path.join(awg_dir, f"{listener['amneziaWg']['interfaceName']}.conf")
try:
with open(path, encoding="utf-8") as handle:
before[listener["amneziaWg"]["interfaceName"]] = handle.read()
except OSError:
before[listener["amneziaWg"]["interfaceName"]] = None
merged, _, _ = inbound_runtime.merge(spec)
if tools.dry_run:
return []
prepared = awg_inbound.prepare(merged, awg, awg_dir)
if {entry["interface"] for entry in prepared} != set(before):
return restart(tools, [config["awgUnit"]], "AmneziaWG listeners added or removed")
done = []
for entry in prepared:
with open(entry["config"], encoding="utf-8") as handle:
text = handle.read()
old = before.get(entry["interface"])
if old == text:
continue
if old is None or interface_part(old) != interface_part(text):
return done + restart(tools, [config["awgUnit"]], f"interface {entry['interface']} changed")
stripped = entry["config"] + ".stripped"
fd = os.open(stripped, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as handle:
handle.write(strip_config(text))
try:
tools.run([awg, "syncconf", entry["interface"], stripped], f"syncing {entry['interface']}")
except ApplyError as exc:
return done + restart(tools, [config["awgUnit"]], str(exc))
finally:
os.unlink(stripped)
done.append(f"{entry['interface']}: peers synced")
return done
# --- entry ----------------------------------------------------------------------------
def apply(config: dict, spec: dict, dry_run: bool = False) -> list[str]:
"""Both sides, under the apply lock. With the inbounds stopped (no runtime directory)
there is nothing to change in place: try-restart, which leaves them stopped."""
tools = Tools(config, dry_run)
if not os.path.isdir(config["runtimeDir"]):
return apply_awg(tools, spec) + restart(tools, [config["unit"]], "the inbounds are not running")
lock_path = os.path.join(config["runtimeDir"], "apply.lock")
fd = os.open(lock_path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
try:
fcntl.flock(fd, fcntl.LOCK_EX)
return apply_awg(tools, spec) + apply_xray(tools, spec)
finally:
os.close(fd)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
parser.add_argument("--config", required=True, help="apply.json, from the module")
parser.add_argument("--spec", required=True)
parser.add_argument("--dry-run", action="store_true")
args = parser.parse_args(argv)
with open(args.config, encoding="utf-8") as handle:
config = json.load(handle)
with open(args.spec, encoding="utf-8") as handle:
spec = json.load(handle)
try:
for line in apply(config, spec, args.dry_run):
print(line)
except (ApplyError, OSError) as exc:
print(f"error: {exc}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
File diff suppressed because it is too large. Load diff
+194
View File
@@ -0,0 +1,194 @@
#!/usr/bin/env python3
"""The inbound manager's nftables table: banned addresses, cut-off UDP, and speed limits.
- ban4/ban6: an address on a port, for a while (an address past a user's ipLimit).
- cut4/cut6: the same, for the UDP sessions of a user just switched off (inbound_apply.py).
- up/down: speed limits of XRay users, by socket mark. The patched XRay marks the sockets
its exits dial for a user of level N with MARK_BASE + N (pkgs/patches/
xray-user-level-mark.patch); the mark goes to the connection, whose packets toward the
site (original direction, leaving this host) are policed against the user's "up" limit
and those back (reply direction, arriving) against "down". Through the local proxy the
connection is on loopback, where both directions arrive and leave: each is policed once.
- awg_up/awg_down: AmneziaWG peers, by interface and tunnel address.
Limits police (drop past the rate), which TCP and QUIC back off from. The table is
replaced whole when it is missing (nftables flushed it); the limits are swapped in one
transaction; the bans' sets are left alone.
"""
from __future__ import annotations
import json
import subprocess
TABLE = "proxy_suite_inbound_limits"
MARK_BASE = 0x04000000
MARK_MASK = 0xFFFF0000
# What the exits' sockopt.mark carries: the patch's flag, and the base the levels are added to.
LEVEL_MARK_FLAG = 0x40000000
EXIT_MARK = LEVEL_MARK_FLAG | MARK_BASE
MAX_SLOTS = 0xFFFF
def ruleset(table: str = TABLE) -> str:
"""The table from nothing: an existing one of that name goes first."""
mark = f"ct mark & 0x{MARK_MASK:08x} == 0x{MARK_BASE:08x}"
return f"""table inet {table}
delete table inet {table}
table inet {table} {{
set ban4 {{ type ipv4_addr . inet_service; flags timeout; }}
set ban6 {{ type ipv6_addr . inet_service; flags timeout; }}
set cut4 {{ type ipv4_addr . inet_service; flags timeout; }}
set cut6 {{ type ipv6_addr . inet_service; flags timeout; }}
map up {{ type mark : limit; }}
map down {{ type mark : limit; }}
map awg_up4 {{ type ifname . ipv4_addr : limit; }}
map awg_down4 {{ type ifname . ipv4_addr : limit; }}
map awg_up6 {{ type ifname . ipv6_addr : limit; }}
map awg_down6 {{ type ifname . ipv6_addr : limit; }}
chain input {{
type filter hook input priority filter - 5; policy accept;
ip saddr . th dport @ban4 drop
ip6 saddr . th dport @ban6 drop
meta l4proto udp ip saddr . th dport @cut4 drop
meta l4proto udp ip6 saddr . th dport @cut6 drop
ct direction reply {mark} limit name ct mark map @down drop
}}
chain output {{
type filter hook output priority filter - 5; policy accept;
ct state new meta mark & 0x{MARK_MASK:08x} == 0x{MARK_BASE:08x} ct mark set meta mark
ct direction original {mark} limit name ct mark map @up drop
}}
chain awg_in {{
type filter hook prerouting priority filter - 5; policy accept;
limit name iifname . ip saddr map @awg_up4 drop
limit name iifname . ip6 saddr map @awg_up6 drop
}}
chain awg_out {{
type filter hook postrouting priority filter - 5; policy accept;
limit name oifname . ip daddr map @awg_down4 drop
limit name oifname . ip6 daddr map @awg_down6 drop
}}
}}
"""
def _limit(name: str, bits: int) -> str:
rate = max(bits // 8, 1)
# Room for a TCP window or two: a burst too small holds a fast link far below its rate.
burst = max(rate // 4, 65536)
return f"{name} {{ rate over {rate} bytes/second burst {burst} bytes }}"
def limits_script(table: str, existing: list[str], users: dict[int, dict], peers: list[dict]) -> str:
"""One transaction that empties the maps, drops the old limits and adds the new ones.
users: {slot: {"up": bit/s|None, "down": bit/s|None}}; peers: [{"interface", "address",
"up", "down"}]."""
lines = [f"flush map inet {table} {m}" for m in ("up", "down", "awg_up4", "awg_down4", "awg_up6", "awg_down6")]
lines += [f"delete limit inet {table} {name}" for name in sorted(existing)]
for slot, speed in sorted(users.items()):
for direction in ("up", "down"):
if speed.get(direction):
name = f"u{slot}_{direction}"
lines.append(f"add limit inet {table} {_limit(name, speed[direction])}")
lines.append(f'add element inet {table} {direction} {{ 0x{MARK_BASE + slot:08x} : "{name}" }}')
for index, peer in enumerate(peers):
family = "6" if ":" in peer["address"] else "4"
for direction in ("up", "down"):
if peer.get(direction):
name = f"p{index}_{direction}"
lines.append(f"add limit inet {table} {_limit(name, peer[direction])}")
lines.append(
f'add element inet {table} awg_{direction}{family} {{ "{peer["interface"]}" . {peer["address"]} : "{name}" }}'
)
return "\n".join(lines) + "\n"
class Netfilter:
"""nft, for the manager. Off (nft None) on hosts it cannot run on: nothing happens."""
def __init__(self, nft: str | None, table: str = TABLE):
self.nft = nft
self.table = table
self.installed: tuple | None = None
@property
def enabled(self) -> bool:
return bool(self.nft)
def _run(self, *args: str, stdin: str | None = None) -> str:
done = subprocess.run([self.nft, *args], input=stdin, capture_output=True, text=True, timeout=30)
if done.returncode != 0:
raise RuntimeError(done.stderr.strip() or f"nft exited with {done.returncode}")
return done.stdout
def present(self) -> bool:
try:
self._run("list", "table", "inet", self.table)
return True
except RuntimeError:
return False
def ensure(self) -> bool:
"""Make the table if it is gone. True when it was (the limits must go in again)."""
if not self.enabled or self.present():
return False
self._run("-f", "-", stdin=ruleset(self.table))
self.installed = None
return True
def objects(self) -> list[str]:
out = self._run("-j", "list", "table", "inet", self.table)
names = []
for item in json.loads(out).get("nftables", []):
if "limit" in item and isinstance(item["limit"], dict) and "name" in item["limit"]:
names.append(item["limit"]["name"])
return names
def sync_limits(self, users: dict[int, dict], peers: list[dict]) -> bool:
"""Install these limits unless they are what is in. True when it changed them."""
if not self.enabled:
return False
wanted = (tuple(sorted((slot, s.get("up"), s.get("down")) for slot, s in users.items())),
tuple(sorted((p["interface"], p["address"], p.get("up"), p.get("down")) for p in peers)))
if wanted == self.installed and self.present():
return False
self.ensure()
self._run("-f", "-", stdin=limits_script(self.table, self.objects(), users, peers))
self.installed = wanted
return True
def ban(self, ip: str, ports: list[int], seconds: int) -> None:
if not self.enabled or not ports:
return
family = "6" if ":" in ip else "4"
elements = ", ".join(f"{ip} . {port} timeout {int(seconds)}s" for port in sorted(set(ports)))
self._run("add", "element", "inet", self.table, f"ban{family}", "{ " + elements + " }")
def bans(self) -> list[dict]:
"""[{"ip", "port", "expires"}]: seconds left."""
if not self.enabled or not self.present():
return []
result = []
for family in ("4", "6"):
out = self._run("-j", "list", "set", "inet", self.table, f"ban{family}")
for item in json.loads(out).get("nftables", []):
for element in (item.get("set") or {}).get("elem") or []:
value = element.get("elem", element) if isinstance(element, dict) else element
expires = value.get("expires") if isinstance(value, dict) else None
concat = (value.get("val") if isinstance(value, dict) else value) or {}
parts = concat.get("concat") if isinstance(concat, dict) else None
if parts and len(parts) == 2:
result.append({"ip": str(parts[0]), "port": int(parts[1]), "expires": expires})
return result
def unban(self, ip: str) -> int:
"""Lift every ban of this address; how many there were."""
found = [ban for ban in self.bans() if ban["ip"] == ip]
if found:
family = "6" if ":" in ip else "4"
elements = ", ".join(f"{ip} . {ban['port']}" for ban in found)
self._run("delete", "element", "inet", self.table, f"ban{family}", "{ " + elements + " }")
return len(found)
+538
View File
@@ -0,0 +1,538 @@
#!/usr/bin/env python3
"""Per-user policies of the inbound manager (services.proxy-suite.inbounds.manager).
A policy says whether a user may connect and how much: switched on or off by hand, an
expiry time (or a term that starts with the first connection), a traffic allowance that may renew every day, week or month, how many
addresses may use it at once, and a speed limit. Declared users take theirs from
`inbounds.users.<name>.policy`; the manager's policy file overrides those field by field,
and holds the runtime users' whole. Only the manager (root) writes that file.
The manager's state file keeps what the policies are measured against: when each user's
traffic period began, and the speed slot (XRay user level) a limited user's sockets are
marked with. Traffic comes from the collector's file (proxy-suite-inbound-stats), whose
daily totals are summed from the period's first day, less what that day had carried before
the period began.
Whoever renders the inbounds (build-inbound.py, awg_inbound.py) asks statuses() which users
are active and at which level; this module never writes there.
"""
from __future__ import annotations
import calendar
import copy
import datetime
import fcntl
import json
import math
import os
import re
import secrets
import time
PERIODS = ("daily", "weekly", "monthly")
DEFAULT_POLICY = {
"enabled": True,
"expiresAt": None,
"expiresAfter": None,
"trafficLimit": None,
"trafficPeriod": None,
"ipLimit": None,
"speedLimit": None,
"meta": {},
}
FIELDS = tuple(DEFAULT_POLICY)
MAX_META_KEYS = 32
MAX_META_VALUE = 1024
STATE_VERSION = 1
MAX_TIME = 253402214400 # 9999-12-31
class PolicyError(ValueError):
"""A policy value that cannot be used."""
# --- parsing --------------------------------------------------------------------------
_SIZE = re.compile(r"\s*([0-9]+(?:\.[0-9]+)?)\s*([KMGTP]?)(?:I?B)?\s*", re.IGNORECASE)
_RATE = re.compile(r"\s*([0-9]+(?:\.[0-9]+)?)\s*([KMG]?)(?:BIT|BPS|BIT/S|B/S)?\s*", re.IGNORECASE)
_RELATIVE = re.compile(r"\s*\+\s*([0-9]+)\s*([mhdw])\s*", re.IGNORECASE)
_DURATION = re.compile(r"\s*\+?\s*([0-9]+)\s*([mhdw])\s*", re.IGNORECASE)
SIZE_UNITS = {"": 1, "K": 1024, "M": 1024**2, "G": 1024**3, "T": 1024**4, "P": 1024**5}
RATE_UNITS = {"": 1, "K": 1000, "M": 1000**2, "G": 1000**3}
RELATIVE_UNITS = {"m": 60, "h": 3600, "d": 86400, "w": 7 * 86400}
def parse_size(value) -> int | None:
"""Bytes, from an int or "50G", "1.5T", "512MiB": binary units, as clients show them.
None, "", "none", "unlimited" and 0 mean no limit."""
if value is None or value == 0:
return None
if type(value) is int:
if value < 0:
raise PolicyError(f"size {value} is negative")
return value
if not isinstance(value, str):
raise PolicyError(f"size {json.dumps(value)} is neither a number nor a string")
if value.strip().lower() in ("", "none", "unlimited", "0"):
return None
match = _SIZE.fullmatch(value)
if not match:
raise PolicyError(f"size {json.dumps(value)}: a number with K, M, G or T")
return int(float(match.group(1)) * SIZE_UNITS[match.group(2).upper()])
def parse_rate(value) -> int | None:
"""Bits per second, from an int or "10M", "500k", "1G": decimal units, as ISPs sell them."""
if value is None or value == 0:
return None
if type(value) is int:
if value < 0:
raise PolicyError(f"rate {value} is negative")
return value
if not isinstance(value, str):
raise PolicyError(f"rate {json.dumps(value)} is neither a number nor a string")
if value.strip().lower() in ("", "none", "unlimited", "0"):
return None
match = _RATE.fullmatch(value)
if not match:
raise PolicyError(f"rate {json.dumps(value)}: bits per second, a number with k, M or G")
return int(float(match.group(1)) * RATE_UNITS[match.group(2).upper()])
def parse_speed(value) -> dict | None:
"""{"up": bit/s|None, "down": bit/s|None}, from one rate for both ("20M"), "down/up"
("20M/5M"), or such an object. None: no limit."""
if value is None:
return None
if isinstance(value, dict):
unknown = set(value) - {"up", "down"}
if unknown:
raise PolicyError(f"speedLimit: unknown keys {sorted(unknown)}")
speed = {"up": parse_rate(value.get("up")), "down": parse_rate(value.get("down"))}
elif isinstance(value, str) and "/" in value:
down, up = value.split("/", 1)
speed = {"up": parse_rate(up), "down": parse_rate(down)}
else:
rate = parse_rate(value)
speed = {"up": rate, "down": rate}
return speed if speed["up"] or speed["down"] else None
def parse_duration(value) -> int | None:
"""Seconds, from an int or "30d", "+12h" (m, h, d, w). None, "", "none" and 0: none."""
if value is None or value == 0:
return None
if type(value) is int:
if value < 0:
raise PolicyError(f"duration {value} is negative")
return value
if not isinstance(value, str):
raise PolicyError(f"duration {json.dumps(value)} is neither a number nor a string")
text = value.strip()
if text.lower() in ("", "none", "0"):
return None
if text.isdigit():
return int(text)
match = _DURATION.fullmatch(text)
if not match:
raise PolicyError(f"duration {json.dumps(value)}: a number with m, h, d or w, such as 30d")
return int(match.group(1)) * RELATIVE_UNITS[match.group(2).lower()] or None
def _local_midnight(day: datetime.date) -> int:
return int(time.mktime(day.timetuple()))
def parse_time(value, now: float | None = None) -> int | None:
"""A Unix time from an int, "2026-12-31" (the end of that day, local time),
"2026-12-31T18:00" (local), an ISO time with its zone, or "+30d" from now (m, h, d, w).
None, "", "never": no expiry."""
if value is None:
return None
if type(value) is int:
return value
if not isinstance(value, str):
raise PolicyError(f"time {json.dumps(value)} is neither a number nor a string")
text = value.strip()
if text.lower() in ("", "never", "none"):
return None
if text.isdigit():
return int(text)
relative = _RELATIVE.fullmatch(text)
if relative:
base = time.time() if now is None else now
return int(base) + int(relative.group(1)) * RELATIVE_UNITS[relative.group(2).lower()]
try:
if re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}", text):
return _local_midnight(datetime.date.fromisoformat(text) + datetime.timedelta(days=1))
moment = datetime.datetime.fromisoformat(text)
except ValueError:
raise PolicyError(f"time {json.dumps(value)}: a date, an ISO time, a Unix time or +<n>d") from None
return int(moment.timestamp())
# --- policies -------------------------------------------------------------------------
def _check_meta(value) -> dict:
if not isinstance(value, dict):
raise PolicyError("meta must be an object of strings")
if len(value) > MAX_META_KEYS:
raise PolicyError(f"meta holds at most {MAX_META_KEYS} keys")
for key, item in value.items():
if not isinstance(key, str) or not re.fullmatch(r"[A-Za-z0-9_.-]{1,64}", key):
raise PolicyError(f"meta key {json.dumps(key)}: letters, digits, dot, dash and underscore, up to 64")
if not isinstance(item, str) or len(item) > MAX_META_VALUE:
raise PolicyError(f"meta.{key} must be a string of at most {MAX_META_VALUE} characters")
return dict(value)
def normalize(fields: dict, now: float | None = None) -> dict:
"""Policy fields as the file keeps them, from what a person or a bot gave: sizes,
rates and times in any form parse_* takes. Only the fields given."""
if not isinstance(fields, dict):
raise PolicyError("a policy is an object")
unknown = set(fields) - set(FIELDS)
if unknown:
raise PolicyError(f"unknown policy fields: {', '.join(sorted(unknown))}")
out: dict = {}
for key, value in fields.items():
if key == "enabled":
if type(value) is not bool:
raise PolicyError("enabled must be true or false")
out[key] = value
elif key == "expiresAt":
# 0 is no expiry, as 0 is no limit in the other fields: not 1970.
out[key] = None if value in (0, "0") else parse_time(value, now)
if out[key] is not None and not 0 < out[key] < MAX_TIME:
raise PolicyError(f"time {json.dumps(value)} is out of range")
elif key == "expiresAfter":
out[key] = parse_duration(value)
if out[key] is not None and out[key] >= MAX_TIME:
raise PolicyError(f"duration {json.dumps(value)} is out of range")
elif key == "trafficLimit":
out[key] = parse_size(value)
elif key == "trafficPeriod":
if value in (None, "", "none", "never"):
out[key] = None
elif value in PERIODS:
out[key] = value
else:
raise PolicyError(f"trafficPeriod must be one of {', '.join(PERIODS)} or none")
elif key == "ipLimit":
if value in (None, 0, ""):
out[key] = None
elif type(value) is int and value > 0:
out[key] = value
elif isinstance(value, str) and value.isdigit():
out[key] = int(value) or None
else:
raise PolicyError("ipLimit must be a positive number, or 0 for none")
elif key == "speedLimit":
out[key] = parse_speed(value)
elif key == "meta":
out[key] = _check_meta(value)
return out
def check_stored(entry: dict) -> dict:
"""A stored policy, already normalized: the same check, which must change nothing."""
normalized = normalize(entry)
if normalized != entry:
raise PolicyError("not in its stored form")
return entry
def effective(declared: dict | None, stored: dict | None) -> dict:
"""The defaults, then the declared policy, then the stored one, field by field."""
policy = copy.deepcopy(DEFAULT_POLICY)
for layer in (declared or {}, stored or {}):
for key in FIELDS:
if key in layer:
policy[key] = copy.deepcopy(layer[key])
return policy
def declared_policies(spec: dict) -> dict[str, dict]:
"""The declared users' `policy` options, normalized; a bad one is left out (the module's
assertions catch it at build time)."""
policies = {}
for name, user in (spec.get("users") or {}).items():
declared = {k: v for k, v in (user.get("policy") or {}).items() if v is not None}
try:
policies[name] = normalize(declared)
except PolicyError:
continue
return policies
# --- files ----------------------------------------------------------------------------
def read_json(path: str, default):
try:
with open(path, encoding="utf-8") as handle:
value = json.load(handle)
except FileNotFoundError:
return copy.deepcopy(default)
except (OSError, ValueError):
return copy.deepcopy(default)
return value if isinstance(value, type(default)) else copy.deepcopy(default)
def write_json(path: str, value, mode: int = 0o600) -> None:
"""Atomically, through a new file of its own next to it."""
directory = os.path.dirname(path) or "."
os.makedirs(directory, mode=0o700, exist_ok=True)
tmp = os.path.join(directory, f".{os.path.basename(path)}.{secrets.token_hex(6)}")
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, mode)
try:
with os.fdopen(fd, "w", encoding="utf-8") as handle:
handle.write(json.dumps(value, indent=2, sort_keys=True) + "\n")
handle.flush()
os.fsync(handle.fileno())
os.replace(tmp, path)
except BaseException:
try:
os.unlink(tmp)
except OSError:
pass
raise
class Locked:
"""flock on <path>.lock, for a read-modify-write of path."""
def __init__(self, path: str):
self.path = path + ".lock"
self.fd = -1
def __enter__(self):
os.makedirs(os.path.dirname(self.path) or ".", mode=0o700, exist_ok=True)
self.fd = os.open(self.path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
fcntl.flock(self.fd, fcntl.LOCK_EX)
return self
def __exit__(self, *_):
os.close(self.fd)
def load_policies(path: str) -> dict[str, dict]:
"""The policy file: {name: stored fields}; entries that do not hold up are left out."""
raw = read_json(path, {})
policies = {}
for name, entry in (raw.get("users") or {}).items() if isinstance(raw.get("users"), dict) else []:
try:
policies[name] = check_stored(entry)
except PolicyError:
continue
return policies
def _count(value) -> bool:
return type(value) is int and value >= 0
def check_user_state(entry) -> dict:
"""A user's entry in the state file, as start_period() and roll_period() make it: the
renderers read it at every start, so a bad one (an import, a hand edit) must not get in."""
if not isinstance(entry, dict):
raise PolicyError("a user's state is an object")
for key in ("periodStart", "baselineUp", "baselineDown"):
if key in entry and not _count(entry[key]):
raise PolicyError(f"{key} must be a whole number")
# A date the calendar functions still take (the year 9999).
if entry.get("periodStart", 0) >= MAX_TIME:
raise PolicyError("periodStart is too far ahead")
if "anchorDay" in entry and not (type(entry["anchorDay"]) is int and 1 <= entry["anchorDay"] <= 31):
raise PolicyError("anchorDay must be a day of the month")
if "notified" in entry and not isinstance(entry["notified"], dict):
raise PolicyError("notified must be an object")
return entry
def load_state(path: str) -> dict:
"""The state file; entries that do not hold up are left out, as the policy file's are."""
state = read_json(path, {})
state.setdefault("version", STATE_VERSION)
for key in ("users", "slots", "bans", "seen", "subscriptions"):
if not isinstance(state.get(key), dict):
state[key] = {}
for name, entry in list(state["users"].items()):
try:
check_user_state(entry)
except PolicyError:
del state["users"][name]
for name, slot in list(state["slots"].items()):
if not (type(slot) is int and slot > 0):
del state["slots"][name]
for name, first in list(state["seen"].items()):
if not isinstance(first, dict):
del state["seen"][name]
# Salts of the users whose subscription URL was moved on (proxy_inbound.subscription_token).
for name, salt in list(state["subscriptions"].items()):
if not is_subscription_salt(salt):
del state["subscriptions"][name]
return state
def is_subscription_salt(value) -> bool:
return isinstance(value, str) and re.fullmatch(r"[0-9a-f]{32}", value) is not None
def read_stats(path: str) -> dict:
return read_json(path, {})
# --- traffic --------------------------------------------------------------------------
def day_key(ts: float) -> str:
"""The collector's day: its `date +%F`, in local time."""
return time.strftime("%Y-%m-%d", time.localtime(ts))
def _counters(entry) -> tuple[int, int]:
"""(up, down) of one day's counters; nothing from a malformed entry, which must not stop
the renderers that ask statuses()."""
if not isinstance(entry, dict):
return 0, 0
def number(value) -> int:
# jq may write a large sum as a float.
return int(value) if type(value) in (int, float) and math.isfinite(value) and value >= 0 else 0
return number(entry.get("up", 0)), number(entry.get("down", 0))
def day_traffic(stats: dict, day: str, name: str) -> tuple[int, int]:
buckets = (stats.get("days") or {}).get(day)
users = buckets.get("user") if isinstance(buckets, dict) else None
return _counters(users.get(name) if isinstance(users, dict) else None)
def day_total(stats: dict, day: str, name: str) -> int:
return sum(day_traffic(stats, day, name))
def period_traffic(stats: dict, user_state: dict, name: str) -> tuple[int, int]:
"""(up, down) since the period began: every day from its first, less what that day had
before it (the baselines). A user the manager has not measured yet has used nothing:
their count begins when it first sees them, not with whatever the file kept before."""
start = user_state.get("periodStart")
if not start:
return 0, 0
first = day_key(start)
up = down = 0
days = stats.get("days")
for day, buckets in (days.items() if isinstance(days, dict) else []):
if not isinstance(day, str) or day < first or not isinstance(buckets, dict):
continue
users = buckets.get("user")
day_up, day_down = _counters(users.get(name) if isinstance(users, dict) else None)
up += day_up
down += day_down
return (max(up - int(user_state.get("baselineUp", 0) or 0), 0),
max(down - int(user_state.get("baselineDown", 0) or 0), 0))
def used_bytes(stats: dict, user_state: dict, name: str) -> int:
return sum(period_traffic(stats, user_state, name))
def _add_period(day: datetime.date, period: str, anchor_day: int) -> datetime.date:
if period == "daily":
return day + datetime.timedelta(days=1)
if period == "weekly":
return day + datetime.timedelta(days=7)
year, month = (day.year + 1, 1) if day.month == 12 else (day.year, day.month + 1)
return datetime.date(year, month, min(anchor_day, calendar.monthrange(year, month)[1]))
def period_end(policy: dict, user_state: dict) -> int | None:
"""When the current period ends and the traffic starts over, or None."""
period = policy.get("trafficPeriod")
start = user_state.get("periodStart")
if period not in PERIODS or not start:
return None
first = datetime.date.fromtimestamp(start)
anchor = int(user_state.get("anchorDay") or first.day)
return _local_midnight(_add_period(first, period, anchor))
def start_period(stats: dict, name: str, now: float) -> dict:
"""A period that begins now: the day so far is the baseline. A renewing period begins
at midnight, so a monthly one renews on this day of the month."""
up, down = day_traffic(stats, day_key(now), name)
return {
"periodStart": int(now),
"baselineUp": up,
"baselineDown": down,
"anchorDay": datetime.date.fromtimestamp(now).day,
}
def roll_period(policy: dict, user_state: dict, now: float) -> bool:
"""Move a renewing period on past now, from boundary to boundary (midnights, so nothing
of the day before counts). True when it moved."""
moved = False
while True:
end = period_end(policy, user_state)
if end is None or end > now:
return moved
user_state["periodStart"] = end
user_state["baselineUp"] = user_state["baselineDown"] = 0
moved = True
# --- status ---------------------------------------------------------------------------
def on_hold(policy: dict) -> bool:
"""A term that starts with the first connection, and has not: expiresAfter without
expiresAt. An expiresAt set by hand wins over it."""
return policy.get("expiresAt") is None and bool(policy.get("expiresAfter"))
def status(policy: dict, used: int, now: float) -> dict:
"""{"active", "reasons"}: why a user may not connect now, if they may not. A user on
hold may: their term begins when they do."""
reasons = []
if not policy.get("enabled", True):
reasons.append("disabled")
expires = policy.get("expiresAt")
if expires is not None and now >= expires:
reasons.append("expired")
limit = policy.get("trafficLimit")
if limit is not None and used >= limit:
reasons.append("traffic")
return {"active": not reasons, "reasons": reasons}
def user_names(spec: dict, runtime_users) -> list[str]:
return sorted(set(spec.get("users") or {}) | set(runtime_users))
def statuses(spec: dict, runtime_users, now: float | None = None) -> dict[str, dict]:
"""Each user's {"active", "level", "reasons"}, for the renderers. Empty without the
manager: everyone active, nobody limited, as before it."""
manager = spec.get("manager")
if not manager:
return {}
now = time.time() if now is None else now
declared = declared_policies(spec)
stored = load_policies(manager["policyFile"])
state = load_state(manager["stateFile"])
stats = read_stats(manager["statsFile"])
result = {}
for name in user_names(spec, runtime_users):
policy = effective(declared.get(name), stored.get(name))
user_state = copy.deepcopy(state["users"].get(name) or {})
roll_period(policy, user_state, now)
view = status(policy, used_bytes(stats, user_state, name), now)
slot = state["slots"].get(name)
limited = bool(policy.get("speedLimit")) and manager.get("speedLimits", False)
view["level"] = int(slot) if limited and isinstance(slot, int) and slot > 0 else 0
result[name] = view
return result
+58 -9
View File
@@ -37,6 +37,8 @@ import time
import urllib.parse
import uuid
import inbound_policy
# User names and listener tags: they become file names, XRay emails and tags, and URL parts.
NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,31}")
MAX_ENTRY_BYTES = 65536
@@ -841,17 +843,55 @@ def number_users(spec: dict, names: list[str], state_users: dict, warnings: list
return numbered
def merge_state(spec: dict, state: dict, check_ports: bool = False) -> tuple[dict, dict, list[str]]:
# Listener types whose XRay inbound runs with no client at all, so a user switched off by
# the manager leaves it in place, ready to take them back without a restart. A Shadowsocks
# listener has a client list only with more than one user (render_xray_inbound).
EMPTY_CLIENTS_TYPES = ("vless", "vmess", "trojan", "hysteria2")
def _runs_without_clients(listener: dict) -> bool:
if listener.get("type") in EMPTY_CLIENTS_TYPES:
return True
return listener.get("type") == "shadowsocks" and len(listener["users"]) > 1
def apply_statuses(merged: dict, statuses: dict, warnings: list[str]) -> None:
"""The manager's view of each user (inbound_policy.statuses): "active" and "level" on
every listener's users. A listener whose users are all switched off stays when it runs
without clients, and is left out otherwise, as one without users is."""
kept = []
for listener in merged["listeners"]:
for user in listener["users"]:
view = statuses.get(user["name"]) or {}
user["active"] = view.get("active", True)
user["level"] = view.get("level", 0)
if (
listener["users"]
and listener.get("type") not in (None, "amneziawg")
and not any(user["active"] for user in listener["users"])
and not _runs_without_clients(listener)
):
warnings.append(f"listener '{listener['tag']}' has no active users; not started")
continue
kept.append(listener)
merged["listeners"] = kept
def merge_state(spec: dict, state: dict, check_ports: bool | set = False, statuses: dict | None = None) -> tuple[dict, dict, list[str]]:
"""The spec with the runtime entries merged in, what was made of them, and warnings.
The result's "runtime" key holds {"listeners": [runtime tags kept], "users": [runtime
names kept], "selfSources": [...], "problems": {("user"|"listener", name): [why]}}.
statuses: the manager's, by user name (inbound_policy.statuses); None leaves everyone
active, at level 0.
"""
runtime = spec.get("runtime")
merged = copy.deepcopy(spec)
result = {"listeners": [], "users": [], "selfSources": [], "problems": {}}
if not runtime:
return merged, result, []
warnings: list[str] = []
apply_statuses(merged, statuses or {}, warnings)
return merged, result, warnings
warnings: list[str] = []
problems: dict = result["problems"]
@@ -948,7 +988,11 @@ def merge_state(spec: dict, state: dict, check_ports: bool = False) -> tuple[dic
why = [f"cannot be checked: {exc}"]
if listener["port"] in declared_ports or listener["port"] in used_ports:
why.append(f"port {listener['port']} is taken by another listener")
if not why and check_ports and not port_free(listener["listen"], listener["port"], _protocols(listener)):
# check_ports may name the ports the running XRay holds already (inbound_apply.py):
# those are its own, not taken.
held = check_ports if isinstance(check_ports, (set, frozenset)) else set()
if (not why and check_ports and listener["port"] not in held
and not port_free(listener["listen"], listener["port"], _protocols(listener))):
why.append(f"port {listener['port']} is in use on this host")
if why:
for message in why:
@@ -1005,16 +1049,21 @@ def merge_state(spec: dict, state: dict, check_ports: bool = False) -> tuple[dic
}
result["users"] = sorted(users)
result["selfSources"] = number_users(spec, sorted(on_xray), state["users"], warnings)
apply_statuses(merged, statuses or {}, warnings)
result["listeners"] = [tag for tag in result["listeners"] if any(l["tag"] == tag for l in merged["listeners"])]
return merged, result, warnings
def merge(spec: dict, check_ports: bool = False) -> tuple[dict, dict, list[str]]:
"""merge_state() on the spool the spec names, as the services read it at start."""
def merge(spec: dict, check_ports: bool | set = False, now: float | None = None) -> tuple[dict, dict, list[str]]:
"""merge_state() on the spool the spec names, as the services read it at start, with
the manager's statuses when it is on."""
runtime = spec.get("runtime")
if not runtime:
return spec, {"listeners": [], "users": [], "selfSources": [], "problems": {}}, []
state, warnings = load_spool(runtime["spool"])
merged, result, more = merge_state(spec, state, check_ports)
state, warnings = load_spool(runtime["spool"]) if runtime else ({"users": {}, "listeners": {}}, [])
statuses = inbound_policy.statuses(spec, state["users"], now) if spec.get("manager") else None
merged, result, more = merge_state(spec, state, check_ports, statuses)
if spec.get("manager"):
# Users whose subscription URL the manager moved on (proxy_inbound.subscription_token).
merged["subscriptionSalts"] = inbound_policy.load_state(spec["manager"]["stateFile"])["subscriptions"]
return merged, result, warnings + more
+543
View File
@@ -0,0 +1,543 @@
#!/usr/bin/env python3
"""A user's subscription in the shape their client asks for (inbounds.manager).
The manager serves one URL per user. Most clients (v2rayN, v2rayNG, Happ, Hiddify,
Streisand, Shadowrocket, NekoBox) read base64 of the share links, which stays the answer to
anything not recognized. Clash and mihomo clients get a config of proxies and groups, the
sing-box apps a sing-box config, and a browser a page with the subscription's state, a QR
code and buttons that open it in an app. `?format=` picks one by hand.
Everything comes from rendered.json (proxy_inbound.build_inbounds): each link's client
outbound is already parsed there, as sing-box JSON where sing-box can dial it and XRay's
where only XRay can (XHTTP, ECH). The configs leave those out; the links keep them.
"""
from __future__ import annotations
import base64
import datetime
import hashlib
import html
import json
import re
import urllib.parse
FORMATS = ("base64", "links", "clash", "sing-box", "html")
# The configs' own groups and exits, which no server may be named as.
RESERVED = {"proxy", "auto", "direct", "block", "reject", "dns"}
# By the start of the User-Agent: Hiddify says "like ClashMeta v2ray sing-box" further on,
# and reads the links best.
_CLASH_AGENTS = re.compile(r"(clash|mihomo|stash|flclash|koala-clash)", re.IGNORECASE)
_SING_BOX_AGENTS = re.compile(r"(SF[AIMT]/|sing-box)", re.IGNORECASE)
def pick_format(query_format: str | None, user_agent: str, accept: str) -> str:
"""The format to answer in: the query's, or one the client is known to read."""
if query_format in FORMATS:
return query_format
if _CLASH_AGENTS.match(user_agent):
return "clash"
if _SING_BOX_AGENTS.match(user_agent):
return "sing-box"
if user_agent.startswith("Mozilla/") and "text/html" in accept:
return "html"
return "base64"
def entries(rendered: dict, user: str) -> list[dict]:
"""The user's links as subscriptions carry them: no AmneziaWG configs, which clients
reading these do not speak. Each with a name of its own, the listener's tag and variant."""
result = []
seen: set[str] = set()
for link in rendered.get("links") or []:
if link.get("user") != user or link.get("config") is not None:
continue
name = link.get("tag", "proxy") + (f"-{link['variant']}" if link.get("variant") else "")
base, index = name, 2
if name.lower() in RESERVED:
name = f"{base}-{index}"
index += 1
while name in seen:
name, index = f"{base}-{index}", index + 1
seen.add(name)
result.append({**link, "name": name})
return result
# --- sing-box -------------------------------------------------------------------------
def sing_box_outbounds(items: list[dict]) -> list[dict]:
"""Outbounds sing-box dials, named for the config: XRay-only ones are left out."""
outbounds = []
for item in items:
outbound = item.get("outbound")
if isinstance(outbound, dict) and "type" in outbound:
outbounds.append({**outbound, "tag": item["name"]})
return outbounds
def sing_box_config(items: list[dict]) -> dict:
"""A whole client config for the sing-box apps (1.12 and later): TUN, the user's
servers under a selector whose default picks the fastest, private networks direct."""
outbounds = sing_box_outbounds(items)
names = [o["tag"] for o in outbounds]
groups = []
if names:
groups = [
{"type": "selector", "tag": "proxy", "outbounds": ["auto", *names], "default": "auto"},
{"type": "urltest", "tag": "auto", "outbounds": names, "interval": "10m"},
]
return {
"log": {"level": "warn"},
"dns": {
"servers": [
{"type": "https", "tag": "remote", "server": "1.1.1.1", "detour": "proxy" if names else "direct"},
{"type": "local", "tag": "local"},
],
"final": "remote",
},
"inbounds": [
{
"type": "tun",
"tag": "tun-in",
"address": ["172.19.0.1/30", "fdfe:dcba:9876::1/126"],
"auto_route": True,
"strict_route": True,
}
],
"outbounds": [*groups, *outbounds, {"type": "direct", "tag": "direct"}],
"route": {
"rules": [
{"action": "sniff"},
{"protocol": "dns", "action": "hijack-dns"},
{"ip_is_private": True, "outbound": "direct"},
],
"final": "proxy" if names else "direct",
"auto_detect_interface": True,
"default_domain_resolver": "local",
},
}
# --- Clash and mihomo -----------------------------------------------------------------
def _clash_tls(proxy: dict, tls: dict, sni_key: str) -> None:
if not tls.get("enabled"):
return
proxy["tls"] = True
if tls.get("server_name"):
proxy[sni_key] = tls["server_name"]
if tls.get("insecure"):
proxy["skip-cert-verify"] = True
if tls.get("alpn"):
proxy["alpn"] = list(tls["alpn"])
fingerprint = (tls.get("utls") or {}).get("fingerprint")
if fingerprint:
proxy["client-fingerprint"] = fingerprint
reality = tls.get("reality") or {}
if reality.get("enabled"):
proxy["reality-opts"] = {"public-key": reality.get("public_key", ""), "short-id": reality.get("short_id", "")}
proxy.setdefault("client-fingerprint", "chrome")
def _clash_transport(proxy: dict, transport: dict | None) -> bool:
"""mihomo's network and its options; False for a transport it lacks."""
if not transport:
proxy["network"] = "tcp"
return True
kind = transport.get("type")
if kind in ("ws", "httpupgrade"):
proxy["network"] = "ws"
opts: dict = {"path": transport.get("path") or "/"}
host = (transport.get("headers") or {}).get("Host") or transport.get("host")
if host:
opts["headers"] = {"Host": host}
if kind == "httpupgrade":
opts["v2ray-http-upgrade"] = True
proxy["ws-opts"] = opts
elif kind == "grpc":
proxy["network"] = "grpc"
proxy["grpc-opts"] = {"grpc-service-name": transport.get("service_name", "")}
elif kind == "http":
proxy["network"] = "h2"
proxy["h2-opts"] = {"host": list(transport.get("host") or []), "path": transport.get("path") or "/"}
else:
return False
return True
def clash_proxy(name: str, outbound: dict) -> dict | None:
"""A mihomo proxy from a sing-box outbound; None for what it cannot dial the same way."""
kind = outbound.get("type")
proxy: dict = {"name": name, "server": outbound.get("server"), "port": outbound.get("server_port")}
tls = outbound.get("tls") or {}
if kind in ("vless", "vmess"):
proxy.update(type=kind, uuid=outbound.get("uuid"), udp=True)
if kind == "vless":
if outbound.get("flow"):
proxy["flow"] = outbound["flow"]
if outbound.get("packet_encoding"):
proxy["packet-encoding"] = outbound["packet_encoding"]
else:
proxy.update({"alterId": outbound.get("alter_id", 0), "cipher": outbound.get("security") or "auto"})
_clash_tls(proxy, tls, "servername")
elif kind == "trojan":
proxy.update(type="trojan", password=outbound.get("password"), udp=True)
_clash_tls(proxy, tls, "sni")
elif kind == "shadowsocks":
if outbound.get("plugin"):
return None
proxy.update(type="ss", cipher=outbound.get("method"), password=outbound.get("password"), udp=True)
elif kind == "hysteria2":
proxy.update(type="hysteria2", password=outbound.get("password"))
if tls.get("server_name"):
proxy["sni"] = tls["server_name"]
if tls.get("insecure"):
proxy["skip-cert-verify"] = True
if tls.get("alpn"):
proxy["alpn"] = list(tls["alpn"])
obfs = outbound.get("obfs") or {}
if obfs.get("type"):
proxy.update({"obfs": obfs["type"], "obfs-password": obfs.get("password", "")})
if outbound.get("server_ports"):
proxy["ports"] = ",".join(p.replace(":", "-") for p in outbound["server_ports"])
return proxy
elif kind in ("socks", "http"):
proxy["type"] = "socks5" if kind == "socks" else "http"
for key in ("username", "password"):
if outbound.get(key):
proxy[key] = outbound[key]
_clash_tls(proxy, tls, "sni")
return proxy
else:
return None
if kind in ("vless", "vmess", "trojan") and not _clash_transport(proxy, outbound.get("transport")):
return None
return proxy
def clash_config(items: list[dict]) -> dict:
"""A mihomo config: the user's servers, a group that picks the fastest and one to choose
by hand, private networks direct."""
proxies = []
for item in items:
outbound = item.get("outbound")
if isinstance(outbound, dict) and "type" in outbound:
proxy = clash_proxy(item["name"], outbound)
if proxy is not None:
proxies.append(proxy)
names = [p["name"] for p in proxies]
groups = [
{"name": "PROXY", "type": "select", "proxies": ["auto", *names] if names else ["DIRECT"]},
{"name": "auto", "type": "url-test", "proxies": names or ["DIRECT"],
"url": "https://www.gstatic.com/generate_204", "interval": 600},
]
return {
"mixed-port": 7890,
"mode": "rule",
"log-level": "warning",
"proxies": proxies,
"proxy-groups": groups,
"rules": [
"IP-CIDR,10.0.0.0/8,DIRECT,no-resolve",
"IP-CIDR,172.16.0.0/12,DIRECT,no-resolve",
"IP-CIDR,192.168.0.0/16,DIRECT,no-resolve",
"IP-CIDR,127.0.0.0/8,DIRECT,no-resolve",
"MATCH,PROXY",
],
}
# --- the page -------------------------------------------------------------------------
TEXT = {
"en": {
"active": "Active", "hold": "Starts with the first connection", "off": "Switched off",
"disabled": "switched off", "expired": "expired", "traffic": "out of traffic",
"used": "Traffic", "of": "of", "unlimited": "unlimited", "renews": "renews",
"expires": "Expires", "never": "never", "term": "for {} from the first connection",
"sub": "Subscription", "copy": "Copy", "copied": "Copied", "open": "Add to an app",
"more": "Other apps", "links": "Connections", "support": "Support", "user": "User",
"hint": "Keep this page to yourself: its address is your access.",
},
"ru": {
"active": "Активна", "hold": "Начнётся с первого подключения", "off": "Отключена",
"disabled": "отключена", "expired": "срок истёк", "traffic": "трафик исчерпан",
"used": "Трафик", "of": "из", "unlimited": "без лимита", "renews": "обновится",
"expires": "Действует до", "never": "бессрочно", "term": "{} с первого подключения",
"sub": "Подписка", "copy": "Копировать", "copied": "Скопировано", "open": "Добавить в приложение",
"more": "Другие приложения", "links": "Подключения", "support": "Поддержка", "user": "Пользователь",
"hint": "Не показывайте эту страницу никому: её адрес и есть ваш доступ.",
},
}
ANDROID, IOS, MACOS, WINDOWS, LINUX = "android", "ios", "macos", "windows", "linux"
EVERYWHERE = frozenset({ANDROID, IOS, MACOS, WINDOWS, LINUX})
# Each opens the subscription in that app, on the systems the app takes the link on; {url} is
# quoted, {raw} is not. clash:// is taken by Clash Meta, FlClash, Clash Verge Rev, Clash Party
# and Stash; v2rayN and Throne take no link, only the URL pasted.
APPS = [
("Happ", "happ://add/{raw}", EVERYWHERE),
("Hiddify", "hiddify://import/{raw}#{name}", EVERYWHERE),
("v2rayNG", "v2rayng://install-config?url={url}#{name}", {ANDROID}),
("Streisand", "streisand://import/{raw}#{name}", {IOS, MACOS}),
("Karing", "karing://install-config?url={url}&name={name}", {ANDROID, IOS, MACOS, WINDOWS}),
("sing-box", "sing-box://import-remote-profile?url={url}#{name}", {ANDROID, IOS, MACOS}),
("Clash / mihomo", "clash://install-config?url={url}&name={name}", EVERYWHERE),
# proxy-suite-gui (gui.enable): asks before it runs `proxy subs add`.
("Proxy Suite", "proxy-suite://install-config?url={url}&name={name}", {LINUX}),
]
# In this order: Android's User-Agent says Linux too, and a Chromebook runs Android apps.
_PLATFORMS = [
(ANDROID, re.compile(r"Android|CrOS")),
(IOS, re.compile(r"iPhone|iPad|iPod")),
(WINDOWS, re.compile(r"Windows")),
(MACOS, re.compile(r"Macintosh|Mac OS X")),
(LINUX, re.compile(r"Linux|X11")),
]
def platform(user_agent: str) -> str | None:
"""The system a browser runs on, as APPS names them; None when it does not say."""
return next((name for name, pattern in _PLATFORMS if pattern.search(user_agent or "")), None)
def language(accept_language: str) -> str:
for part in (accept_language or "").split(","):
tag = part.split(";")[0].strip().lower()
if tag.startswith("ru"):
return "ru"
if tag.startswith("en"):
return "en"
return "en"
def human_bytes(value: int) -> str:
size = float(value)
for unit in ("B", "KiB", "MiB", "GiB", "TiB"):
if size < 1024 or unit == "TiB":
return f"{size:.0f} {unit}" if unit == "B" else f"{size:.1f} {unit}"
size /= 1024
return f"{value} B"
def human_span(seconds: int) -> str:
for unit, size in (("w", 604800), ("d", 86400), ("h", 3600), ("m", 60)):
if seconds % size == 0:
return f"{seconds // size}{unit}"
return f"{seconds}s"
_STYLE = """
:root{--bg:#f6f7f9;--card:#fff;--fg:#1c1f24;--muted:#646b75;--line:#e1e4e8;--accent:#2563eb;--ok:#15803d;--warn:#b45309;--bad:#b91c1c}
@media (prefers-color-scheme:dark){:root{--bg:#111316;--card:#1b1e23;--fg:#e8eaed;--muted:#9aa1ab;--line:#2c3036;--accent:#6ea0ff;--ok:#4ade80;--warn:#fbbf24;--bad:#f87171}}
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.5 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
main{max-width:560px;margin:0 auto;padding:24px 16px 48px}h1{font-size:22px;margin:0 0 4px}
.card{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:16px;margin-top:16px}
.status{font-weight:600}.ok{color:var(--ok)}.warn{color:var(--warn)}.bad{color:var(--bad)}
.row{display:flex;justify-content:space-between;gap:12px;padding:6px 0;border-bottom:1px solid var(--line)}.row:last-child{border:0}
.muted{color:var(--muted);font-size:14px}.bar{display:block;width:100%;height:6px;border-radius:3px;overflow:hidden;margin-top:6px}
.bar .track{fill:var(--line)}.bar .fill{fill:var(--accent)}
.qr{display:flex;justify-content:center;margin:8px 0}.qr svg{width:220px;height:220px;background:#fff;border-radius:8px}
code{display:block;word-break:break-all;font-size:13px;background:var(--bg);border:1px solid var(--line);border-radius:8px;padding:8px;margin:8px 0}
button,a.app{font:inherit;font-size:14px;border:1px solid var(--line);background:var(--bg);color:var(--fg);border-radius:8px;padding:6px 12px;cursor:pointer;text-decoration:none;display:inline-block;margin:4px 4px 0 0}
button:hover,a.app:hover{border-color:var(--accent)}
summary{cursor:pointer;color:var(--muted);font-size:14px;margin-top:12px}h2{font-size:16px;margin:0 0 8px}h2.next{margin-top:16px}
"""
# The QR code is drawn by the browser: a request costs the server no encoder run, and the page
# takes no image from elsewhere, for the people opening it may not reach much. qrMatrix(text):
# the modules, rows of booleans, of the smallest QR code (byte mode, error correction M) that
# holds text, mask chosen by the standard's penalty; null past version 40. A test decodes its
# output with zbar.
_QR_SCRIPT = """
function qrMatrix(text){
var ECC=[0,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],
BLK=[0,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49];
var bytes=new TextEncoder().encode(text),ver,size,raw,i,j,x,y;
function rawModules(v){var r=(16*v+128)*v+64;if(v>=2){var n=Math.floor(v/7)+2;r-=(25*n-10)*n-55;if(v>=7)r-=36}return r}
for(ver=1;;ver++){if(ver>40)return null;raw=Math.floor(rawModules(ver)/8);if(4+(ver<10?8:16)+8*bytes.length<=(raw-ECC[ver]*BLK[ver])*8)break}
size=ver*4+17;var cap=raw-ECC[ver]*BLK[ver],bits=[];
function put(v,n){for(var k=n-1;k>=0;k--)bits.push(v>>>k&1)}
put(4,4);put(bytes.length,ver<10?8:16);for(i=0;i<bytes.length;i++)put(bytes[i],8);
put(0,Math.min(4,cap*8-bits.length));put(0,(8-bits.length%8)%8);
for(var pad=0xEC;bits.length<cap*8;pad^=0xEC^0x11)put(pad,8);
var data=[];for(i=0;i<bits.length;i+=8){for(x=0,j=0;j<8;j++)x=x<<1|bits[i+j];data.push(x)}
function mul(a,b){for(var z=0,k=7;k>=0;k--){z=(z<<1)^((z>>>7)*0x11D);z^=(b>>>k&1)*a}return z}
var deg=ECC[ver],gen=[],root=1;for(i=0;i<deg;i++)gen.push(0);gen[deg-1]=1;
for(i=0;i<deg;i++){for(j=0;j<deg;j++){gen[j]=mul(gen[j],root);if(j+1<deg)gen[j]^=gen[j+1]}root=mul(root,2)}
var nb=BLK[ver],nshort=nb-raw%nb,slen=Math.floor(raw/nb),blocks=[],eccs=[],at=0;
for(i=0;i<nb;i++){var d=data.slice(at,at+=slen-deg+(i<nshort?0:1)),rem=gen.map(function(){return 0});
for(j=0;j<d.length;j++){var f=d[j]^rem.shift();rem.push(0);for(var k=0;k<deg;k++)rem[k]^=mul(gen[k],f)}
blocks.push(d);eccs.push(rem)}
var words=[];for(i=0;i<=slen-deg;i++)for(j=0;j<nb;j++)if(i<blocks[j].length)words.push(blocks[j][i]);
for(i=0;i<deg;i++)for(j=0;j<nb;j++)words.push(eccs[j][i]);
var m=[],fn=[];for(y=0;y<size;y++){m.push([]);fn.push([]);for(x=0;x<size;x++){m[y].push(false);fn[y].push(false)}}
function set(x,y,dark){m[y][x]=dark;fn[y][x]=true}
for(i=0;i<size;i++){set(6,i,i%2==0);set(i,6,i%2==0)}
[[3,3],[size-4,3],[3,size-4]].forEach(function(c){for(var dy=-4;dy<=4;dy++)for(var dx=-4;dx<=4;dx++){
var q=Math.max(Math.abs(dx),Math.abs(dy)),xx=c[0]+dx,yy=c[1]+dy;if(xx>=0&&xx<size&&yy>=0&&yy<size)set(xx,yy,q!=2&&q!=4)}});
var pos=[];if(ver>1){var na=Math.floor(ver/7)+2,step=Math.floor((ver*8+na*3+5)/(na*4-4))*2;pos=[6];for(x=size-7;pos.length<na;x-=step)pos.splice(1,0,x)}
for(i=0;i<pos.length;i++)for(j=0;j<pos.length;j++){if(i==0&&j==0||i==0&&j==pos.length-1||i==pos.length-1&&j==0)continue;
for(var ay=-2;ay<=2;ay++)for(var ax=-2;ax<=2;ax++)set(pos[i]+ax,pos[j]+ay,Math.max(Math.abs(ax),Math.abs(ay))!=1)}
function format(mask){var v=mask,r=v;for(var k=0;k<10;k++)r=(r<<1)^((r>>>9)*0x537);v=(v<<10|r)^0x5412;
function b(k){return (v>>>k&1)==1}
for(k=0;k<=5;k++)set(8,k,b(k));set(8,7,b(6));set(8,8,b(7));set(7,8,b(8));for(k=9;k<15;k++)set(14-k,8,b(k));
for(k=0;k<8;k++)set(size-1-k,8,b(k));for(k=8;k<15;k++)set(8,size-15+k,b(k));set(8,size-8,true)}
format(0);
if(ver>=7){var r=ver;for(i=0;i<12;i++)r=(r<<1)^((r>>>11)*0x1F25);var vb=ver<<12|r;
for(i=0;i<18;i++){var bit=(vb>>>i&1)==1,a=size-11+i%3,c=Math.floor(i/3);set(a,c,bit);set(c,a,bit)}}
for(i=0,x=size-1;x>=1;x-=2){if(x==6)x=5;for(var v=0;v<size;v++)for(j=0;j<2;j++){
var xx=x-j;y=(x+1&2)==0?size-1-v:v;if(!fn[y][xx]&&i<words.length*8){m[y][xx]=(words[i>>>3]>>>7-(i&7)&1)==1;i++}}}
var masks=[function(x,y){return (x+y)%2==0},function(x,y){return y%2==0},function(x,y){return x%3==0},
function(x,y){return (x+y)%3==0},function(x,y){return (Math.floor(x/3)+Math.floor(y/2))%2==0},
function(x,y){return x*y%2+x*y%3==0},function(x,y){return (x*y%2+x*y%3)%2==0},function(x,y){return ((x+y)%2+x*y%3)%2==0}];
function flip(k){for(var y=0;y<size;y++)for(var x=0;x<size;x++)if(!fn[y][x]&&masks[k](x,y))m[y][x]=!m[y][x]}
function line(get){var p=0,dark=0,run=0,last=null,seq='';for(var k=0;k<size;k++){var d=get(k);dark+=d;seq+=d?'1':'0';
if(d===last)run++;else{if(run>=5)p+=run-2;run=1;last=d}}if(run>=5)p+=run-2;
for(k=seq.indexOf('1011101');k>=0;k=seq.indexOf('1011101',k+1))
if(seq.substr(k-4,4)=='0000'||seq.substr(k+7,4)=='0000'||k<4||k+11>size)p+=40;return p}
function score(){var p=0,dark=0;for(var a=0;a<size;a++){p+=line(function(k){return m[a][k]?1:0});p+=line(function(k){return m[k][a]?1:0})}
for(var y=0;y<size;y++)for(var x=0;x<size;x++){dark+=m[y][x];if(x<size-1&&y<size-1&&m[y][x]==m[y][x+1]&&m[y][x]==m[y+1][x]&&m[y][x]==m[y+1][x+1])p+=3}
return p+10*Math.max(0,Math.ceil(Math.abs(dark*20-size*size*10)/(size*size))-1)}
var best=0,low=Infinity;for(k=0;k<8;k++){flip(k);format(k);var s=score();if(s<low){low=s;best=k}flip(k)}
flip(best);format(best);return m}
"""
_SCRIPT = _QR_SCRIPT + """
document.querySelectorAll('[data-qr]').forEach(function(e){var m=qrMatrix(e.getAttribute('data-qr'));if(!m)return;
var n=m.length+8,ns='http://www.w3.org/2000/svg',s=document.createElementNS(ns,'svg'),p=document.createElementNS(ns,'path'),d='';
for(var y=0;y<m.length;y++)for(var x=0;x<m.length;x++)if(m[y][x])d+='M'+(x+4)+' '+(y+4)+'h1v1h-1z';
s.setAttribute('viewBox','0 0 '+n+' '+n);s.setAttribute('shape-rendering','crispEdges');p.setAttribute('d',d);p.setAttribute('fill','#000');
s.appendChild(p);e.appendChild(s)});
document.querySelectorAll('button[data-copy]').forEach(function(b){b.addEventListener('click',function(){
var t=b.getAttribute('data-copy'),l=b.textContent;function done(){b.textContent=b.getAttribute('data-done');setTimeout(function(){b.textContent=l},1500)}
if(navigator.clipboard){navigator.clipboard.writeText(t).then(done)}else{var a=document.createElement('textarea');a.value=t;document.body.appendChild(a);a.select();document.execCommand('copy');a.remove();done()}})});
"""
def _csp_hash(source: str) -> str:
return "'sha256-" + base64.b64encode(hashlib.sha256(source.encode("utf-8")).digest()).decode("ascii") + "'"
# Every answer: the address is the secret, not to be sent on, indexed, sniffed into something
# else or read by other sites' pages.
HEADERS = {
"Cache-Control": "no-store",
"Referrer-Policy": "no-referrer",
"X-Robots-Tag": "noindex, nofollow",
"X-Content-Type-Options": "nosniff",
"Cross-Origin-Resource-Policy": "same-origin",
}
# The page, besides: nothing runs or styles it but its own script and stylesheet, by their
# hashes; no style attribute, no frame, no form, no other origin.
PAGE_HEADERS = {
"Content-Security-Policy": f"default-src 'none'; script-src {_csp_hash(_SCRIPT)}; style-src {_csp_hash(_STYLE)}; "
"base-uri 'none'; form-action 'none'; frame-ancestors 'none'; "
"require-trusted-types-for 'script'",
"Cross-Origin-Opener-Policy": "same-origin",
}
def html_page(row: dict, items: list[dict], sub_url: str, title: str, settings: dict, lang: str,
user_agent: str = "") -> str:
"""The page a browser gets: the state of the subscription, its QR code and links. The apps
for the browser's system come first, the rest folded away: the page may be open on a laptop
to set up a phone."""
t = TEXT[lang]
esc = html.escape
if not row.get("active"):
state = f'<span class="status bad">{esc(t["off"])}</span>'
reasons = ", ".join(t.get(r, r) for r in row.get("reasons") or [])
if reasons:
state += f' <span class="muted">({esc(reasons)})</span>'
elif row.get("onHold"):
state = f'<span class="status warn">{esc(t["hold"])}</span>'
else:
state = f'<span class="status ok">{esc(t["active"])}</span>'
traffic = row.get("traffic") or {}
used, limit = traffic.get("used") or 0, traffic.get("limit")
usage = esc(human_bytes(used)) + (f' {esc(t["of"])} {esc(human_bytes(limit))}' if limit else f' <span class="muted">({esc(t["unlimited"])})</span>')
if limit and traffic.get("periodEnd"):
renew = datetime.datetime.fromtimestamp(traffic["periodEnd"]).strftime("%Y-%m-%d")
usage += f' <span class="muted">· {esc(t["renews"])} {esc(renew)}</span>'
# An SVG's width attribute, not a style one: the CSP lets no style attribute through.
bar = (f'<svg class="bar" viewBox="0 0 100 1" preserveAspectRatio="none"><rect class="track" width="100" height="1"/>'
f'<rect class="fill" width="{min(100, int(used * 100 / limit))}" height="1"/></svg>') if limit else ""
if row.get("onHold"):
expires = esc(t["term"].format(human_span((row.get("policy") or {}).get("expiresAfter") or 0)))
elif row.get("expiresAt"):
expires = esc(datetime.datetime.fromtimestamp(row["expiresAt"]).strftime("%Y-%m-%d %H:%M"))
else:
expires = esc(t["never"])
name = urllib.parse.quote(title, safe="")
system = platform(user_agent)
buttons = {
label: f'<a class="app" href="{esc(pattern.format(url=urllib.parse.quote(sub_url, safe=""), raw=sub_url, name=name))}">{esc(label)}</a>'
for label, pattern, _ in APPS
}
mine = [label for label, _, systems in APPS if system in systems]
others = [label for label, _, _ in APPS if label not in mine]
if mine:
apps = "".join(buttons[label] for label in mine)
if others:
apps += f'<details><summary>{esc(t["more"])}</summary>{"".join(buttons[label] for label in others)}</details>'
else:
apps = "".join(buttons.values())
links = "".join(
f'<div class="row"><span>{esc(item["name"])}</span>'
f'<button data-copy="{esc(item["link"])}" data-done="{esc(t["copied"])}">{esc(t["copy"])}</button></div>'
for item in items
)
# Whose it is, unless the title (profileTitle's {user}) says so already.
user = ""
if row.get("name") and row["name"] not in title:
user = f'<div class="muted">{esc(t["user"])}: {esc(row["name"])}</div>'
support = ""
if settings.get("supportUrl"):
support = f'<p class="muted"><a href="{esc(settings["supportUrl"])}">{esc(t["support"])}</a></p>'
return f"""<!doctype html>
<html lang="{lang}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="robots" content="noindex,nofollow"><meta name="referrer" content="no-referrer">
<title>{esc(title)}</title><style>{_STYLE}</style></head>
<body><main>
<h1>{esc(title)}</h1>{user}<div>{state}</div>
<div class="card">
<div class="row"><span>{esc(t["used"])}</span><span>{usage}</span></div>{bar}
<div class="row"><span>{esc(t["expires"])}</span><span>{expires}</span></div>
</div>
<div class="card"><h2>{esc(t["sub"])}</h2>
<div class="qr" data-qr="{esc(sub_url)}"></div>
<code>{esc(sub_url)}</code>
<button data-copy="{esc(sub_url)}" data-done="{esc(t["copied"])}">{esc(t["copy"])}</button>
<h2 class="next">{esc(t["open"])}</h2>{apps}
</div>
{f'<div class="card"><h2>{esc(t["links"])}</h2>{links}</div>' if links else ''}
<p class="muted">{esc(t["hint"])}</p>{support}
</main><script>{_SCRIPT}</script></body></html>
"""
# --- the answer -----------------------------------------------------------------------
def render(fmt: str, rendered: dict, user: str, body_b64: str, row: dict | None, sub_url: str, title: str,
settings: dict, accept_language: str = "", user_agent: str = "") -> tuple[bytes, str]:
"""(body, Content-Type) of a subscription in one format."""
items = entries(rendered, user)
if fmt == "links":
return base64.b64decode(body_b64) + b"\n", "text/plain; charset=utf-8"
if fmt == "sing-box":
return (json.dumps(sing_box_config(items), indent=2) + "\n").encode("utf-8"), "application/json; charset=utf-8"
if fmt == "clash":
# JSON is YAML: no YAML library needed, and mihomo reads it as such.
return (json.dumps(clash_config(items), indent=2, ensure_ascii=False) + "\n").encode("utf-8"), "text/yaml; charset=utf-8"
if fmt == "html" and row is not None:
page = html_page(row, items, sub_url, title, settings, language(accept_language), user_agent)
return page.encode("utf-8"), "text/html; charset=utf-8"
return body_b64.encode("ascii"), "text/plain; charset=utf-8"
+45 -9
View File
@@ -10,6 +10,7 @@ without changing the spec or the link generator.
import base64
import hashlib
import hmac
import json
import os
import secrets
@@ -73,7 +74,11 @@ def _salamander(listener: dict) -> str | None:
return _resolve(
salamander.get("password"), salamander.get("passwordFile"), "salamander password", listener["tag"]
)
path = listener["salamanderStateFile"]
return _kept_secret(listener["salamanderStateFile"], lambda: secrets.token_urlsafe(24))
def _kept_secret(path: str, generate) -> str:
"""The secret kept in path, or one generated now and kept there for the next start."""
try:
stored = _read_secret(path)
except FileNotFoundError:
@@ -81,7 +86,7 @@ def _salamander(listener: dict) -> str | None:
if stored:
return stored
os.makedirs(os.path.dirname(path), mode=0o700, exist_ok=True)
generated = secrets.token_urlsafe(24)
generated = generate()
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as handle:
handle.write(generated + "\n")
@@ -100,8 +105,13 @@ def _share_port(listener: dict) -> int:
def _clients(listener: dict, tag: str) -> list[dict]:
"""The users XRay accepts: those the manager has switched off are left out (their links
stay), and a speed-limited one carries its slot as its level, which the patched XRay
marks its sockets with (pkgs/patches/xray-user-level-mark.patch)."""
clients = []
for index, user in enumerate(listener["users"]):
if user.get("active") is False:
continue
secret = _user_secret(user, listener["type"], tag)
email = user.get("name") or f"{tag}-{index}"
if listener["type"] in UUID_TYPES:
@@ -112,6 +122,8 @@ def _clients(listener: dict, tag: str) -> list[dict]:
client = {"auth": secret, "email": email}
else:
client = {"password": secret, "email": email}
if user.get("level"):
client["level"] = user["level"]
clients.append(client)
return clients
@@ -119,6 +131,8 @@ def _clients(listener: dict, tag: str) -> list[dict]:
def _accounts(listener: dict, tag: str) -> list[dict]:
accounts = []
for index, user in enumerate(listener["users"]):
if user.get("active") is False:
continue
secret = _user_secret(user, listener["type"], tag)
accounts.append({"user": user.get("name") or f"{tag}-{index}", "pass": secret})
return accounts
@@ -226,6 +240,8 @@ def render_xray_inbound(listener: dict) -> dict:
if len(users) == 1:
settings["password"] = _user_secret(users[0], listener_type, tag)
settings["email"] = users[0].get("name") or f"{tag}-0"
if users[0].get("level"):
settings["level"] = users[0]["level"]
keys = [(settings["email"], settings["password"])]
else:
# Multi-user is 2022-blake3-aes only: the server key, then one key per user.
@@ -558,15 +574,33 @@ def client_outbound(link: str, tag: str) -> dict | None:
return None
def subscription_token(name: str, secrets: list[str]) -> str:
def subscription_token(name: str, secrets: list[str], key: str | None = None, salt: str = "") -> str:
"""Name of a user's subscription file, and so the secret part of its URL.
Derived from the user's own credentials rather than stored: there is no
second secret to manage, it stays put for as long as they do, and rotating
the user's uuid rotates the URL with it.
Derived from the user's own credentials rather than stored: it stays put for
as long as they do, and rotating the user's uuid rotates the URL with it.
key (inbounds.subscriptions.keyFile, or the one generated) makes it an HMAC under
a secret only this server holds: whoever learns one of a user's links cannot work
the URL out from it. salt (the manager's, `proxy-ctl inbounds users rotate-sub`) moves one
user's URL on without new credentials. Neither: the plain hash of before.
"""
material = "\n".join(["proxy-suite-subscription", name, *sorted(set(secrets))])
return hashlib.sha256(material.encode("utf-8")).hexdigest()[:32]
material = "\n".join(["proxy-suite-subscription", name, *sorted(set(secrets)), *([salt] if salt else [])])
if key is None:
return hashlib.sha256(material.encode("utf-8")).hexdigest()[:32]
return hmac.new(key.encode("utf-8"), material.encode("utf-8"), hashlib.sha256).hexdigest()[:32]
def _subscription_key(spec: dict) -> str | None:
"""The config's key file; else the one generated on first start (subscriptions.keyFile
null); else none (false)."""
path = spec.get("subscriptionKeyFile")
if not path:
state = spec.get("subscriptionKeyStateFile")
return _kept_secret(state, lambda: secrets.token_hex(32)) if state else None
key = _read_secret(path)
if not key:
raise ValueError(f"subscription key file '{path}' is empty")
return key
def build_inbounds(spec: dict, server_address: str, onion_address: str = "") -> dict:
@@ -628,10 +662,12 @@ def build_inbounds(spec: dict, server_address: str, onion_address: str = "") ->
"outbound": None,
}
)
key = _subscription_key(spec) if by_user else None
salts = spec.get("subscriptionSalts") or {}
subscriptions = [
{
"user": name,
"token": subscription_token(name, entry["secrets"]),
"token": subscription_token(name, entry["secrets"], key, salts.get(name, "")),
"body": base64.b64encode("\n".join(entry["links"]).encode("utf-8")).decode("ascii"),
}
for name, entry in by_user.items()
+41
View File
@@ -707,6 +707,47 @@ class BuildInboundsTests(unittest.TestCase):
self.assertNotEqual(token, next(s["token"] for s in rotated if s["user"] == "fufsob"))
# No links, nothing to subscribe to.
self.assertEqual(build_inbounds(spec(share=False), "vpn.example.com")["subscriptions"], [])
# Under a key only the server holds, the credentials alone do not give the token away.
with tempfile.TemporaryDirectory() as tmp:
key_file = os.path.join(tmp, "key")
with open(key_file, "w", encoding="utf-8") as handle:
handle.write("k" * 64 + "\n")
keyed = {s["user"]: s["token"] for s in build_inbounds({**spec(), "subscriptionKeyFile": key_file},
"vpn.example.com")["subscriptions"]}
self.assertRegex(keyed["fufsob"], "^[0-9a-f]{32}$")
self.assertNotEqual(keyed["fufsob"], token)
self.assertEqual(keyed["fufsob"], subscription_token("fufsob", ["uuid-fufsob"], "k" * 64))
self.assertNotEqual(keyed["fufsob"], subscription_token("fufsob", ["uuid-fufsob"], "other"))
# The manager's salt moves one user's on, the rest stay.
salted = {s["user"]: s["token"] for s in build_inbounds(
{**spec(), "subscriptionKeyFile": key_file, "subscriptionSalts": {"fufsob": "ab" * 16}},
"vpn.example.com")["subscriptions"]}
self.assertNotEqual(salted["fufsob"], keyed["fufsob"])
self.assertEqual(salted["teri"], keyed["teri"])
# Without a key too: a salt is a secret of the server's.
self.assertNotEqual(subscription_token("fufsob", ["uuid-fufsob"], salt="ab" * 16), token)
# No key file: one generated on first start, kept, and used from then on.
state = os.path.join(tmp, "state", "subscription-key")
generated = {s["user"]: s["token"] for s in build_inbounds(
{**spec(), "subscriptionKeyStateFile": state}, "vpn.example.com")["subscriptions"]}
with open(state, encoding="utf-8") as handle:
kept = handle.read().strip()
self.assertRegex(kept, "^[0-9a-f]{64}$")
self.assertEqual(os.stat(state).st_mode & 0o777, 0o600)
self.assertEqual(generated["fufsob"], subscription_token("fufsob", ["uuid-fufsob"], kept))
self.assertEqual(generated, {s["user"]: s["token"] for s in build_inbounds(
{**spec(), "subscriptionKeyStateFile": state}, "vpn.example.com")["subscriptions"]})
# The config's key wins over it.
self.assertEqual(keyed, {s["user"]: s["token"] for s in build_inbounds(
{**spec(), "subscriptionKeyFile": key_file, "subscriptionKeyStateFile": state},
"vpn.example.com")["subscriptions"]})
# A key file that is empty or not there stops the rendering, as a secret's would.
with open(key_file, "w", encoding="utf-8") as handle:
handle.write("\n")
with self.assertRaises(ValueError):
build_inbounds({**spec(), "subscriptionKeyFile": key_file}, "vpn.example.com")
with self.assertRaises(OSError):
build_inbounds({**spec(), "subscriptionKeyFile": os.path.join(tmp, "none")}, "vpn.example.com")
def test_share_port_overrides_the_bound_port(self):
spec = {
+223
View File
@@ -0,0 +1,223 @@
#!/usr/bin/env python3
import copy
import json
import os
import secrets
import subprocess
import tempfile
import time
import unittest
import inbound_apply as ap
UUID_A = "b831381d-6324-4d53-ad4f-8cda48b30811"
UUID_B = "11111111-2222-3333-4444-555555555555"
def vless(tag, clients, port=443, **extra):
inbound = {"tag": tag, "listen": "::", "port": port, "protocol": "vless",
"settings": {"clients": clients, "decryption": "none"},
"streamSettings": {"network": "raw", "security": "none"}}
inbound.update(extra)
return inbound
def client(email, uuid=UUID_A, **extra):
return {"id": uuid, "email": email, **extra}
def rendering(*inbounds, **extra):
return {"inbounds": list(inbounds), "links": [], "subscriptions": [], **extra}
class Plan(unittest.TestCase):
def test_nothing_changed(self):
old = rendering(vless("a", [client("u")]))
steps = ap.plan(old, copy.deepcopy(old))
self.assertTrue(ap.is_noop(steps))
def test_users_come_and_go(self):
old = rendering(vless("a", [client("u"), client("v", UUID_B)]))
new = rendering(vless("a", [client("v", UUID_B, level=3), client("w")]))
steps = ap.plan(old, new)
self.assertEqual(steps["restart"], [])
self.assertEqual(steps["users"]["a"]["remove"], ["u", "v"])
self.assertEqual([c["email"] for c in steps["users"]["a"]["add"]], ["v", "w"])
def test_a_changed_listener_restarts(self):
old = rendering(vless("a", [client("u")]))
new = rendering(vless("a", [client("u")], port=8443))
self.assertEqual(ap.plan(old, new)["restart"], ["listener 'a' changed"])
def test_listeners_added_or_gone_restart(self):
old = rendering(vless("a", [client("u")]))
new = rendering(vless("a", [client("u")]), vless("b", [client("u")], port=8443))
self.assertEqual(ap.plan(old, new)["restart"], ["listeners added: b"])
self.assertEqual(ap.plan(new, old)["restart"], ["listeners gone: b"])
def test_accounts_and_single_user_shadowsocks_restart(self):
socks = {"tag": "s", "protocol": "socks", "port": 1080, "settings": {"accounts": [{"user": "u", "pass": "1"}]}}
changed = copy.deepcopy(socks)
changed["settings"]["accounts"].append({"user": "v", "pass": "2"})
self.assertTrue(ap.plan(rendering(socks), rendering(changed))["restart"])
single = {"tag": "ss", "protocol": "shadowsocks", "port": 8388,
"settings": {"method": "aes-128-gcm", "password": "x", "email": "u"}}
other = copy.deepcopy(single)
other["settings"]["level"] = 2
self.assertTrue(ap.plan(rendering(single), rendering(other))["restart"])
def test_routing_outbounds_addresses_and_outputs(self):
old = rendering(vless("a", []), rules=[{"ruleTag": "x"}],
selfOutbounds=[{"tag": "direct-self4-1", "sendThrough": "10.0.0.1"}],
selfAddresses=[{"ipv4": "10.0.0.1", "ipv6": None}])
new = rendering(vless("a", []), rules=[{"ruleTag": "x"}, {"ruleTag": "y"}],
selfOutbounds=[{"tag": "direct-self4-2", "sendThrough": "10.0.0.2"}],
selfAddresses=[{"ipv4": "10.0.0.2", "ipv6": "fd00::2"}])
new["links"] = [{"link": "vless://..."}]
steps = ap.plan(old, new)
self.assertEqual(steps["rules"], [{"ruleTag": "x"}, {"ruleTag": "y"}])
self.assertEqual(steps["outbounds"]["remove"], ["direct-self4-1"])
self.assertEqual([o["tag"] for o in steps["outbounds"]["add"]], ["direct-self4-2"])
self.assertEqual(steps["addresses"]["remove"], [("4", "10.0.0.1")])
self.assertEqual(steps["addresses"]["add"], [("4", "10.0.0.2"), ("6", "fd00::2")])
self.assertTrue(steps["outputs"])
def test_udp_inbounds(self):
self.assertTrue(ap.udp_inbound({"protocol": "hysteria"}))
self.assertTrue(ap.udp_inbound({"protocol": "vless", "streamSettings": {"network": "xhttp", "tlsSettings": {"alpn": ["h3"]}}}))
self.assertFalse(ap.udp_inbound(vless("a", [])))
class Steps(unittest.TestCase):
def test_the_commands(self):
config = {"xray": "xray", "api": "unix:///run/api.sock", "ss": "ss", "nft": "nft", "nftTable": "t",
"ip": "ip", "selfInterface": "ps-self"}
tools = ap.Tools(config, dry_run=True)
new = rendering(vless("a", [client("w")]), {"tag": "h", "protocol": "hysteria", "port": 443, "settings": {"clients": []}})
steps = {"restart": [], "users": {"a": {"remove": ["u"], "add": [client("w")]}, "h": {"remove": ["u"], "add": []}},
"rules": None, "outbounds": {"remove": [], "add": []},
"addresses": {"remove": [("4", "10.0.0.1")], "add": [("6", "fd00::2")]}, "outputs": False}
done = ap.run_steps(tools, steps, new, None)
self.assertIn("a: -u", done)
self.assertIn("a: +w", done)
log = "\n".join(tools.log)
self.assertIn("xray api statsonlineiplist --server=unix:///run/api.sock -email u", log)
self.assertIn("xray api rmu --server=unix:///run/api.sock -tag=a u", log)
self.assertIn("xray api adu --server=unix:///run/api.sock", log)
self.assertIn("ip -4 addr del 10.0.0.1/32 dev ps-self", log)
self.assertIn("ip -6 addr add fd00::2/128 dev ps-self nodad", log)
class SyncConfig(unittest.TestCase):
def test_config_json_follows_in_place(self):
with tempfile.TemporaryDirectory() as directory:
path = os.path.join(directory, "config.json")
running = {"inbounds": [vless("a", [client("u")]), vless("b", [client("u")], port=8443)],
"routing": {"rules": [{"ruleTag": "x"}]},
"outbounds": [{"tag": "direct"}, {"tag": "direct-self4-1"}]}
with open(path, "w", encoding="utf-8") as handle:
json.dump(running, handle)
os.chmod(path, 0o440 | 0o200)
inode = os.stat(path).st_ino
new = rendering(vless("a", [client("w")]), vless("b", [client("u")], port=8443))
steps = {"users": {"a": {"remove": ["u"], "add": [client("w")]}}, "rules": [{"ruleTag": "y"}],
"outbounds": {"remove": ["direct-self4-1"], "add": [{"tag": "direct-self4-2"}]}}
ap.sync_config(directory, steps, new)
with open(path, encoding="utf-8") as handle:
synced = json.load(handle)
self.assertEqual(os.stat(path).st_ino, inode)
self.assertEqual([c["email"] for c in synced["inbounds"][0]["settings"]["clients"]], ["w"])
self.assertEqual([c["email"] for c in synced["inbounds"][1]["settings"]["clients"]], ["u"])
self.assertEqual(synced["routing"]["rules"], [{"ruleTag": "y"}])
self.assertEqual([o["tag"] for o in synced["outbounds"]], ["direct", "direct-self4-2"])
class Stopped(unittest.TestCase):
def test_stopped_inbounds_are_left_to_try_restart(self):
config = {"runtimeDir": "/nonexistent/proxy-suite-inbounds", "unit": "proxy-suite-inbounds.service",
"systemctl": "systemctl"}
done = ap.apply(config, {"listeners": []}, dry_run=True)
self.assertEqual(done, ["restarted proxy-suite-inbounds.service: the inbounds are not running"])
class AmneziaWG(unittest.TestCase):
CONFIG = "[Interface]\nPrivateKey = k\nAddress = 10.66.0.1/24\nListenPort = 51820\nMTU = 1380\nTable = off\nJc = 4\n\n[Peer]\nPublicKey = p\nAllowedIPs = 10.66.0.2/32\n"
def test_strip(self):
stripped = ap.strip_config(self.CONFIG)
self.assertNotIn("Address", stripped)
self.assertNotIn("MTU", stripped)
self.assertIn("Jc = 4", stripped)
self.assertIn("AllowedIPs = 10.66.0.2/32", stripped)
def test_interface_part_ignores_peers(self):
other = self.CONFIG.replace("10.66.0.2/32", "10.66.0.3/32")
self.assertEqual(ap.interface_part(self.CONFIG), ap.interface_part(other))
self.assertNotEqual(ap.interface_part(self.CONFIG), ap.interface_part(self.CONFIG.replace("Jc = 4", "Jc = 5")))
@unittest.skipUnless(os.environ.get("XRAY"), "XRAY is not set: no live XRay to talk to")
class LiveXray(unittest.TestCase):
"""The API steps against a running XRay: users added and removed, rules replaced."""
def setUp(self):
self.dir = tempfile.TemporaryDirectory()
self.socket = f"@proxy-suite-test-{secrets.token_hex(4)}"
self.api = f"unix-abstract:{self.socket[1:]}"
template = {"routing": {"domainStrategy": "AsIs", "rules": [{"ruleTag": "inbound-stats-api", "inboundTag": ["api-in"], "outboundTag": "api"}]}}
config = {
"log": {"loglevel": "warning"},
"api": {"tag": "api", "services": ["StatsService", "HandlerService", "RoutingService"]},
"stats": {},
"inbounds": [
{"tag": "api-in", "protocol": "dokodemo-door", "listen": self.socket,
"settings": {"address": "127.0.0.1", "network": "unix"}},
vless("a", [client("u")], port=0, listen="127.0.0.1"),
],
"outbounds": [{"tag": "direct", "protocol": "freedom"}, {"tag": "api", "protocol": "freedom"}],
"routing": template["routing"],
}
self.template = template
# Port 0 is no port to XRay: take a free one.
import socket
with socket.socket() as probe:
probe.bind(("127.0.0.1", 0))
config["inbounds"][1]["port"] = probe.getsockname()[1]
self.inbound = config["inbounds"][1]
path = os.path.join(self.dir.name, "config.json")
with open(path, "w", encoding="utf-8") as handle:
json.dump(config, handle)
self.xray = subprocess.Popen([os.environ["XRAY"], "run", "-c", path], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
self.tools = ap.Tools({"xray": os.environ["XRAY"], "api": self.api, "tmpDir": self.dir.name})
for _ in range(50):
try:
self.tools.xray_api("lsi", what="waiting")
break
except ap.ApplyError:
time.sleep(0.1)
def tearDown(self):
self.xray.terminate()
self.xray.wait()
self.dir.cleanup()
def users(self):
out = self.tools.xray_api("inbounduser", "-tag=a", what="listing")
return sorted(u["email"] for u in json.loads(out or "{}").get("users") or [])
def test_users_and_rules(self):
old = rendering(self.inbound)
new_inbound = copy.deepcopy(self.inbound)
new_inbound["settings"]["clients"] = [client("v", UUID_B, level=4)]
new = rendering(new_inbound, rules=self.template["routing"]["rules"] + [{"ruleTag": "extra", "user": ["v"], "outboundTag": "direct"}])
steps = ap.plan(old, new)
self.assertEqual(steps["restart"], [])
ap.run_steps(self.tools, steps, new, self.template)
self.assertEqual(self.users(), ["v"])
rules = json.loads(self.tools.xray_api("lsrules", what="rules"))["rules"]
self.assertEqual([r["ruleTag"] for r in rules], ["inbound-stats-api", "extra"])
if __name__ == "__main__":
unittest.main()
+628
View File
@@ -0,0 +1,628 @@
#!/usr/bin/env python3
import base64
import copy
import http.client
import importlib.util
import json
import os
import socket
import tempfile
import threading
import time
import unittest
import uuid
from unittest import mock
import inbound_apply
import inbound_manager as im
import inbound_subscription
import inbound_policy as policy
import inbound_runtime as rt
# The runtime tests' spec, spool and all.
_spec = importlib.util.spec_from_file_location("runtime_tests", os.path.join(os.path.dirname(__file__), "test-inbound-runtime.py"))
runtime_tests = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(runtime_tests)
class FakeNetfilter:
enabled = True
def __init__(self):
self.banned = []
self.limits = None
def ensure(self):
return False
def ban(self, ip, ports, seconds):
self.banned.append((ip, sorted(ports), seconds))
def bans(self):
return [{"ip": ip, "port": port, "expires": seconds} for ip, ports, seconds in self.banned for port in ports]
def unban(self, ip):
found = [b for b in self.banned if b[0] == ip]
self.banned = [b for b in self.banned if b[0] != ip]
return len(found)
def sync_limits(self, users, peers):
self.limits = (users, peers)
return True
class Clock:
def __init__(self, now):
self.now = now
def __call__(self):
return self.now
class ManagerTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
base = self.tmp.name
self.spool = os.path.join(base, "spool")
os.makedirs(self.spool)
self.runtime_dir = os.path.join(base, "run")
os.makedirs(self.runtime_dir)
self.spec = runtime_tests.make_spec(self.spool)
self.config = {
"policyFile": os.path.join(base, "policy.json"),
"stateFile": os.path.join(base, "state.json"),
"statsFile": os.path.join(base, "stats.json"),
"speedLimits": True,
"slots": 4,
"apply": {"runtimeDir": self.runtime_dir},
"subscriptions": {"baseUrl": "https://vpn.example.com/sub", "profileTitle": "VPN {user}", "updateInterval": 12},
"ipLimit": {"banSeconds": 300},
}
self.spec["manager"] = {k: self.config[k] for k in ("policyFile", "stateFile", "statsFile", "speedLimits")}
self.clock = Clock(time.time())
self.netfilter = FakeNetfilter()
self.webhooks = im.Webhooks([])
self.applies = []
patcher = mock.patch.object(inbound_apply, "apply", side_effect=lambda config, spec: self.applies.append(spec) or [])
patcher.start()
self.addCleanup(patcher.stop)
self.cut = mock.patch.object(inbound_apply, "cut").start()
self.addCleanup(mock.patch.stopall)
self.manager = im.Manager(self.config, self.spec, clock=self.clock, netfilter=self.netfilter, webhooks=self.webhooks)
def tearDown(self):
self.tmp.cleanup()
def events(self, kind=None):
return [(e["event"], e["user"]) for e in self.webhooks.sent if kind is None or e["event"] == kind]
def write_stats(self, stats):
policy.write_json(self.config["statsFile"], stats)
def write_rendered(self, rendered):
with open(os.path.join(self.runtime_dir, "rendered.json"), "w", encoding="utf-8") as handle:
json.dump(rendered, handle)
# --- users and policies -----------------------------------------------------------
def test_create_a_user_with_a_policy(self):
row = self.manager.create_user({"name": "alice", "listeners": ["vless-in"],
"policy": {"trafficLimit": "10G", "expiresAt": "+30d", "speedLimit": "20M/5M"}})
self.assertEqual(row["source"], "runtime")
self.assertEqual(row["listeners"], ["vless-in"])
self.assertEqual(row["policy"]["trafficLimit"], 10 * 1024**3)
self.assertEqual(row["expiresAt"], int(self.clock.now) + 30 * 86400)
self.assertEqual(row["level"], 1)
self.assertTrue(row["active"])
self.assertEqual(len(self.applies), 1)
self.assertIn(("user.created", "alice"), self.events())
with self.assertRaises(im.ApiError) as raised:
self.manager.create_user({"name": "alice"})
self.assertEqual(raised.exception.status, 409)
def test_bad_policy_is_refused_before_anything_is_written(self):
with self.assertRaises(im.ApiError) as raised:
self.manager.create_user({"name": "zed", "policy": {"trafficLimit": "lots"}})
self.assertEqual(raised.exception.status, 400)
self.assertNotIn("zed", rt.load_spool(self.spool)[0]["users"])
def test_declared_users_get_policies_too(self):
row = self.manager.set_policy("bob", {"enabled": False})
self.assertFalse(row["active"])
self.assertEqual(row["reasons"], ["disabled"])
self.assertEqual(row["stored"], {"enabled": False})
row = self.manager.set_policy("bob", {}, unset=["enabled"])
self.assertTrue(row["active"])
self.assertEqual(policy.load_policies(self.config["policyFile"]), {})
def test_disabling_reaches_the_renderers(self):
self.manager.set_policy("bob", {"enabled": False})
merged, _, _ = rt.merge(self.spec)
vless = next(l for l in merged["listeners"] if l["tag"] == "vless-in")
bob = next(u for u in vless["users"] if u["name"] == "bob")
self.assertFalse(bob["active"])
def test_extend_from_the_later_of_now_and_the_expiry(self):
now = int(self.clock.now)
self.manager.set_policy("bob", {"expiresAt": now + 86400})
row = self.manager.extend("bob", by="30d")
self.assertEqual(row["expiresAt"], now + 31 * 86400)
self.manager.set_policy("bob", {"expiresAt": now - 86400})
self.assertEqual(self.manager.extend("bob", by="1d")["expiresAt"], now + 86400)
with self.assertRaises(im.ApiError):
self.manager.extend("bob")
def test_extend_with_a_reset_starts_the_traffic_over(self):
today = policy.day_key(self.clock.now)
self.manager.create_user({"name": "alice", "policy": {"trafficLimit": 100}})
self.manager.tick()
self.write_stats({"days": {today: {"user": {"alice": {"up": 60, "down": 60}}}}})
self.manager.tick()
self.assertEqual(self.manager.overview("alice")[0]["reasons"], ["traffic"])
row = self.manager.extend("alice", by="30d", reset=True)
self.assertTrue(row["active"])
self.assertEqual(row["traffic"]["used"], 0)
self.assertEqual(row["expiresAt"], int(self.clock.now) + 30 * 86400)
self.assertIn(("user.reset", "alice"), self.events())
def test_on_hold_starts_with_the_first_connection(self):
today = policy.day_key(self.clock.now)
row = self.manager.create_user({"name": "alice", "policy": {"expiresAfter": "30d"}})
self.assertTrue(row["active"])
self.assertTrue(row["onHold"])
self.assertIsNone(row["expiresAt"])
# Extended while on hold: the term grows, nothing starts.
row = self.manager.extend("alice", by="5d")
self.assertEqual(row["policy"]["expiresAfter"], 35 * 86400)
self.assertTrue(row["onHold"])
self.manager.tick()
self.clock.now += 3 * 86400
self.manager.tick()
self.assertTrue(self.manager.overview("alice")[0]["onHold"])
self.assertEqual(self.events("user.activated"), [])
self.write_stats({"days": {today: {"user": {"alice": {"up": 1, "down": 2}}}}})
self.manager.tick()
row = self.manager.overview("alice")[0]
self.assertFalse(row["onHold"])
self.assertEqual(row["expiresAt"], int(self.clock.now) + 35 * 86400)
self.assertEqual(self.events("user.activated"), [("user.activated", "alice")])
self.manager.tick()
self.assertEqual(len(self.events("user.activated")), 1)
def test_on_hold_starts_when_seen_online(self):
self.manager.create_user({"name": "alice", "policy": {"expiresAfter": "1d", "trafficLimit": "1G"}})
self.manager.create_user({"name": "zed", "policy": {"expiresAfter": policy.MAX_TIME - 1, "trafficLimit": "1G"}})
self.write_stats({"online": [{"email": name, "ips": [{"ip": "198.51.100.1"}]} for name in ("alice", "zed")]})
self.manager.tick()
self.assertEqual(self.manager.overview("alice")[0]["expiresAt"], int(self.clock.now) + 86400)
# A term past the year 9999 ends just before it: the rest of the policy stays.
zed = self.manager.overview("zed")[0]
self.assertEqual(zed["expiresAt"], policy.MAX_TIME - 1)
self.assertEqual(zed["policy"]["trafficLimit"], 1024**3)
def test_expired_runtime_users_are_deleted_after_a_while(self):
self.config["deleteExpiredAfter"] = "7d"
now = int(self.clock.now)
self.manager.create_user({"name": "alice", "policy": {"expiresAt": now + 86400}})
self.manager.create_user({"name": "carol"})
self.manager.set_policy("bob", {"expiresAt": now + 86400})
self.clock.now += 7 * 86400
self.manager.tick()
self.assertIn("alice", self.manager.names())
self.clock.now += 86400 + 1
self.manager.tick()
names = self.manager.names()
self.assertNotIn("alice", names)
# Declared in the config: kept. Never expires: kept.
self.assertIn("bob", names)
self.assertIn("carol", names)
deleted = [e for e in self.webhooks.sent if e["event"] == "user.deleted"]
self.assertEqual([(e["user"], e["data"]) for e in deleted], [("alice", {"reason": "expired"})])
def test_delete_forgets_the_policy(self):
self.manager.create_user({"name": "alice", "policy": {"ipLimit": 2}})
self.manager.delete_user("alice")
self.assertNotIn("alice", policy.load_policies(self.config["policyFile"]))
with self.assertRaises(im.ApiError) as raised:
self.manager.delete_user("bob")
self.assertEqual(raised.exception.status, 409)
def test_set_listeners(self):
self.manager.create_user({"name": "alice", "listeners": ["vless-in"]})
self.assertEqual(self.manager.set_listeners("alice", [])["listeners"], [])
self.assertEqual(self.manager.set_listeners("alice", ["vless-in"])["listeners"], ["vless-in"])
# A single-user shadowsocks listener takes no second user.
with self.assertRaises(im.ApiError) as raised:
self.manager.set_listeners("alice", ["ss-in"])
self.assertEqual(raised.exception.status, 409)
def test_slots_run_out(self):
for name in ("a1", "a2", "a3", "a4"):
self.manager.create_user({"name": name, "policy": {"speedLimit": "1M"}})
with self.assertRaises(im.ApiError):
self.manager.create_user({"name": "a5", "policy": {"speedLimit": "1M"}})
# Refused whole: no user without the slot their policy needs.
self.assertNotIn("a5", rt.load_spool(self.spool)[0]["users"])
self.manager.create_user({"name": "a5"})
with self.assertRaises(im.ApiError):
self.manager.set_policy("a5", {"speedLimit": "1M"})
self.assertNotIn("a5", self.manager.stored_policies())
# A slot comes back when its user's limit goes.
self.manager.set_policy("a1", {"speedLimit": None})
self.manager.tick()
self.assertNotIn("a1", self.manager.state()["slots"])
self.manager.set_policy("a5", {"speedLimit": "1M"})
self.assertIn("a5", self.manager.state()["slots"])
# --- the tick ---------------------------------------------------------------------
def test_traffic_runs_out_and_comes_back_with_the_period(self):
today = policy.day_key(self.clock.now)
self.manager.create_user({"name": "alice", "policy": {"trafficLimit": 1000, "trafficPeriod": "daily"}})
self.manager.tick()
self.write_stats({"days": {today: {"user": {"alice": {"up": 300, "down": 600}}}}})
self.manager.tick()
self.assertIn(("user.traffic", "alice"), self.events())
self.assertTrue(self.manager.overview("alice")[0]["active"])
self.write_stats({"days": {today: {"user": {"alice": {"up": 400, "down": 700}}}}})
applies = len(self.applies)
self.manager.tick()
row = self.manager.overview("alice")[0]
self.assertFalse(row["active"])
self.assertEqual(row["reasons"], ["traffic"])
self.assertEqual(len(self.applies), applies + 1)
self.assertIn(("user.disabled", "alice"), self.events())
self.assertEqual([e for e in self.events("user.traffic")], [("user.traffic", "alice")] * 2)
# The next day: a new period.
self.clock.now += 86400
self.manager.tick()
self.assertTrue(self.manager.overview("alice")[0]["active"])
self.assertIn(("user.enabled", "alice"), self.events())
def test_expiry_warnings_and_expiry(self):
self.manager.create_user({"name": "alice", "policy": {"expiresAt": int(self.clock.now) + 2 * 86400}})
self.manager.tick()
self.assertEqual(self.events("user.expiring"), [("user.expiring", "alice")])
self.manager.tick()
self.assertEqual(len(self.events("user.expiring")), 1)
self.clock.now += 2 * 86400 + 1
self.manager.tick()
self.assertEqual(self.manager.overview("alice")[0]["reasons"], ["expired"])
self.assertIn(("user.disabled", "alice"), self.events())
def test_ip_limit_bans_the_newest(self):
self.manager.create_user({"name": "alice", "listeners": ["vless-in"], "policy": {"ipLimit": 1}})
self.write_rendered({"inbounds": [
{"tag": "vless-in", "listen": "::", "port": 443, "protocol": "vless", "settings": {"clients": [{"email": "alice"}]}},
{"tag": "behind", "listen": "127.0.0.1", "port": 9000, "protocol": "vless", "settings": {"clients": [{"email": "alice"}]}},
]})
self.write_stats({"online": [{"email": "alice", "ips": [{"ip": "198.51.100.1"}]}]})
self.manager.tick()
self.assertEqual(self.netfilter.banned, [])
self.clock.now += 10
self.write_stats({"online": [{"email": "alice", "ips": [{"ip": "198.51.100.1"}, {"ip": "203.0.113.9"}]}]})
self.manager.tick()
self.assertEqual(self.netfilter.banned, [("203.0.113.9", [443], 300)])
self.assertTrue(self.cut.called)
self.assertEqual(self.events("user.ip-limit"), [("user.ip-limit", "alice")])
def test_speed_limits_follow_activity(self):
self.manager.create_user({"name": "alice", "policy": {"speedLimit": "8M/2M"}})
users, _ = self.netfilter.limits
self.assertEqual(users, {1: {"up": 2_000_000, "down": 8_000_000}})
self.manager.set_policy("alice", {"enabled": False})
self.assertEqual(self.netfilter.limits[0], {})
# --- subscriptions ----------------------------------------------------------------
def test_subscription_headers(self):
today = policy.day_key(self.clock.now)
self.manager.create_user({"name": "alice", "policy": {"trafficLimit": 5000, "expiresAt": 2_000_000_000}})
self.manager.tick()
self.write_stats({"days": {today: {"user": {"alice": {"up": 10, "down": 20}}}}})
self.write_rendered({"subscriptions": [{"user": "alice", "token": "a" * 32, "body": "Ym9keQ=="}]})
body, headers = self.manager.subscription("a" * 32)
self.assertEqual(body, b"Ym9keQ==")
self.assertEqual(headers["subscription-userinfo"], "upload=10; download=20; total=5000; expire=2000000000")
self.assertEqual(base64.b64decode(headers["profile-title"][len("base64:"):]).decode(), "VPN alice")
self.assertEqual(headers["Content-Type"], "text/plain; charset=utf-8")
self.assertEqual(headers["profile-update-interval"], "12")
self.assertIsNone(self.manager.subscription("b" * 32))
self.assertEqual(self.manager.overview("alice")[0]["subscription"]["url"], "https://vpn.example.com/sub/" + "a" * 32)
def test_subscription_formats(self):
self.manager.create_user({"name": "alice", "policy": {"expiresAfter": "30d"}})
link = "trojan://pass@vpn.example.com:8443?security=tls&sni=vpn.example.com#tr"
self.write_rendered({
"subscriptions": [{"user": "alice", "token": "a" * 32, "body": base64.b64encode(link.encode()).decode()}],
"links": [{"tag": "tr", "user": "alice", "link": link,
"outbound": {"type": "trojan", "tag": "tr", "server": "vpn.example.com", "server_port": 8443,
"password": "pass", "tls": {"enabled": True, "server_name": "vpn.example.com"}}}],
})
body, headers = self.manager.subscription("a" * 32, user_agent="ClashMetaForAndroid/2.11")
self.assertEqual(json.loads(body)["proxies"][0]["name"], "tr")
self.assertIn("subscription-userinfo", headers)
body, headers = self.manager.subscription("a" * 32, user_agent="Mozilla/5.0", accept="text/html",
accept_language="ru")
self.assertEqual(headers["Content-Type"], "text/html; charset=utf-8")
self.assertEqual(headers["Referrer-Policy"], "no-referrer")
self.assertEqual(headers["Content-Security-Policy"], inbound_subscription.PAGE_HEADERS["Content-Security-Policy"])
self.assertNotIn("content-disposition", headers)
page = body.decode()
self.assertIn("Начнётся с первого подключения", page)
# baseUrl wins over the address asked at: it is what clients are given.
self.assertIn("https://vpn.example.com/sub/" + "a" * 32, page)
body, headers = self.manager.subscription("a" * 32, fmt="links")
self.assertEqual(body.decode().strip(), link)
# Every format: not cached, sniffed, sent on or indexed; the page's CSP on the page only.
self.assertEqual({k: headers[k] for k in inbound_subscription.HEADERS}, inbound_subscription.HEADERS)
self.assertNotIn("Content-Security-Policy", headers)
def test_rotate_subscription(self):
self.manager.create_user({"name": "alice", "listeners": ["vless-in"]})
merged, _, _ = rt.merge(self.spec)
self.assertEqual(merged["subscriptionSalts"], {})
status, _ = im.handle_api(self.manager, "POST", "/api/v1/users/alice/rotate-subscription", {}, None)
self.assertEqual(status, 200)
salt = policy.load_state(self.config["stateFile"])["subscriptions"]["alice"]
self.assertTrue(policy.is_subscription_salt(salt))
# The renderers take it (proxy_inbound.subscription_token), on the apply it asked for.
self.assertEqual(rt.merge(self.spec)[0]["subscriptionSalts"], {"alice": salt})
self.assertEqual(self.applies[-1], self.spec)
self.assertEqual(self.webhooks.sent[-1]["data"], {"subscription": "rotated"})
self.manager.rotate_subscription("alice")
self.assertNotEqual(policy.load_state(self.config["stateFile"])["subscriptions"]["alice"], salt)
with self.assertRaises(im.ApiError) as raised:
self.manager.rotate_subscription("nobody")
self.assertEqual(raised.exception.status, 404)
# It travels with an export; a deleted user's goes with them.
bundle = self.manager.export()
self.assertIn("alice", bundle["state"]["subscriptions"])
self.manager.delete_user("alice")
self.assertNotIn("alice", policy.load_state(self.config["stateFile"])["subscriptions"])
self.manager.import_bundle(bundle)
self.assertEqual(policy.load_state(self.config["stateFile"])["subscriptions"]["alice"],
bundle["state"]["subscriptions"]["alice"])
with self.assertRaises(im.ApiError):
self.manager.import_bundle({**bundle, "state": {"subscriptions": {"alice": "../x"}}})
# A salt that does not hold up is left out.
state = policy.load_state(self.config["stateFile"])
state["subscriptions"]["bob"] = "short"
policy.write_json(self.config["stateFile"], state)
self.assertNotIn("bob", policy.load_state(self.config["stateFile"])["subscriptions"])
def test_misses_are_logged_sparingly(self):
clock = Clock(1000.0)
misses = im.Misses(every=60, clock=clock)
with mock.patch.object(im, "_log") as log:
for _ in range(5):
misses.note("203.0.113.7")
misses.note("198.51.100.1")
clock.now += 61
misses.note("203.0.113.7")
self.assertEqual([c.args[0] for c in log.call_args_list], [
"subscription: unknown token from 203.0.113.7",
"subscription: unknown token from 198.51.100.1",
"subscription: unknown token from 203.0.113.7 (4 more since the last line)",
])
# --- export and import ------------------------------------------------------------
def test_export_and_import_into_an_empty_server(self):
self.manager.create_user({"name": "alice", "listeners": ["vless-in"], "policy": {"trafficLimit": "1G"}})
self.write_stats({"days": {"2026-10-01": {"user": {"alice": {"up": 1, "down": 2}}}}})
awg_state = os.path.join(self.tmp.name, "awg.json")
self.spec["listeners"][2]["amneziaWg"] = {"stateFile": awg_state, "interfaceName": "awgi-awg", "subnet": "10.66.0.0/24"}
server_key = base64.b64encode(b"S" * 32).decode()
policy.write_json(awg_state, {"version": 1, "server": {"publicKey": server_key}, "users": {"bob": {"offset": 2}}})
bundle = json.loads(json.dumps(self.manager.export()))
self.assertEqual(sorted(bundle["runtime"]["users"]), ["alice"])
self.assertEqual(bundle["amneziaWg"]["awg"]["server"]["publicKey"], server_key)
other = tempfile.TemporaryDirectory()
self.addCleanup(other.cleanup)
spool = os.path.join(other.name, "spool")
os.makedirs(spool)
spec = runtime_tests.make_spec(spool)
spec["listeners"][2]["amneziaWg"] = {"stateFile": os.path.join(other.name, "awg.json"), "interfaceName": "awgi-awg", "subnet": "10.66.0.0/24"}
config = copy.deepcopy(self.config)
for key in ("policyFile", "stateFile", "statsFile"):
config[key] = os.path.join(other.name, os.path.basename(config[key]))
spec["manager"] = {k: config[k] for k in ("policyFile", "stateFile", "statsFile", "speedLimits")}
target = im.Manager(config, spec, clock=self.clock, netfilter=FakeNetfilter(), webhooks=im.Webhooks([]))
report = target.import_bundle(bundle)
self.assertEqual(report["users"], ["alice"])
self.assertEqual(report["amneziaWg"], ["awg"])
row = target.overview("alice")[0]
self.assertEqual(row["policy"]["trafficLimit"], 1024**3)
self.assertEqual(rt.load_spool(spool)[0]["users"]["alice"]["uuid"], rt.load_spool(self.spool)[0]["users"]["alice"]["uuid"])
self.assertEqual(policy.read_stats(config["statsFile"])["days"]["2026-10-01"]["user"]["alice"], {"up": 1, "down": 2})
with self.assertRaises(im.ApiError) as raised:
target.import_bundle(bundle)
self.assertEqual(raised.exception.status, 409)
self.assertEqual(target.import_bundle(bundle, replace=True)["users"], ["alice"])
def test_the_generated_subscription_key_travels(self):
key_path = os.path.join(self.tmp.name, "inbounds", "subscription-key")
self.spec["subscriptionKeyStateFile"] = key_path
self.assertIsNone(self.manager.export()["subscriptionKey"])
os.makedirs(os.path.dirname(key_path))
with open(key_path, "w", encoding="utf-8") as handle:
handle.write("e" * 64 + "\n")
bundle = self.manager.export()
self.assertEqual(bundle["subscriptionKey"], "e" * 64)
# A key the config names is the config's: not exported.
named = im.Manager(self.config, {**self.spec, "subscriptionKeyFile": "/run/secrets/k"}, netfilter=FakeNetfilter())
self.assertIsNone(named.export()["subscriptionKey"])
other = tempfile.TemporaryDirectory()
self.addCleanup(other.cleanup)
target_path = os.path.join(other.name, "inbounds", "subscription-key")
target = im.Manager(self.config, {**self.spec, "subscriptionKeyStateFile": target_path},
clock=self.clock, netfilter=FakeNetfilter(), webhooks=im.Webhooks([]))
report = {"skipped": []}
target._import_subscription_key(bundle["subscriptionKey"], False, report)
self.assertTrue(report["subscriptionKey"])
with open(target_path, encoding="utf-8") as handle:
self.assertEqual(handle.read().strip(), "e" * 64)
self.assertEqual(os.stat(target_path).st_mode & 0o777, 0o600)
# One of its own already: kept, unless replace.
report = {"skipped": []}
target._import_subscription_key("f" * 64, False, report)
self.assertIn("kept this server's", report["skipped"][0])
target._import_subscription_key("f" * 64, True, report)
with open(target_path, encoding="utf-8") as handle:
self.assertEqual(handle.read().strip(), "f" * 64)
# None to keep it in: said so.
report = {"skipped": []}
im.Manager(self.config, {**self.spec, "subscriptionKeyStateFile": None},
netfilter=FakeNetfilter())._import_subscription_key("f" * 64, False, report)
self.assertIn("keyFile is false", report["skipped"][0])
with self.assertRaises(im.ApiError):
self.manager.import_bundle({**bundle, "subscriptionKey": "short\nline"})
def test_import_refuses_garbage(self):
for bad in (None, {}, {"format": "x"}, {"format": im.BUNDLE_FORMAT, "version": 99}):
with self.assertRaises(im.ApiError):
self.manager.import_bundle(bad)
bundle = self.manager.export()
bundle["runtime"]["users"]["evil"] = {"order": 1, "uuid": "nope", "password": "x"}
with self.assertRaises(im.ApiError) as raised:
self.manager.import_bundle(bundle)
self.assertEqual(raised.exception.status, 400)
def test_import_refuses_what_would_escape_or_break_its_files(self):
clean = self.manager.export()
awg_state = os.path.join(self.tmp.name, "awg.json")
self.spec["listeners"][2]["amneziaWg"] = {"stateFile": awg_state, "interfaceName": "awgi-awg", "subnet": "10.66.0.0/24"}
key = base64.b64encode(b"k" * 32).decode()
bad_parts = [
# A tag is a directory under the Salamander state: not a way out of it.
("salamander", {"../../escape": "password"}),
("salamander", {"hy2": "two\nlines"}),
# A key with a line break would add a line (PostUp = ...) to what awg-quick runs.
("amneziaWg", {"awg": {"version": 1, "server": {"privateKey": key + "\nPostUp = touch /x"}, "users": {}}}),
("amneziaWg", {"awg": {"version": 1, "server": {}, "users": {"bob": {"offset": 2, "presharedKey": "short"}}}}),
# A state of another version: its keys would be made anew.
("amneziaWg", {"awg": {"server": {"privateKey": key}, "users": {}}}),
# The renderers and the collector read these at every start and run.
("state", {"users": {"alice": {"periodStart": "yesterday"}}, "slots": {}}),
("stats", {"days": {"2026-10-01": {"user": {"alice": {"up": "lots"}}}}}),
]
for section, value in bad_parts:
bundle = copy.deepcopy(clean)
bundle[section] = value
with self.subTest(section=section, value=value), self.assertRaises(im.ApiError) as raised:
self.manager.import_bundle(bundle)
self.assertEqual(raised.exception.status, 400)
self.assertFalse(os.path.exists(os.path.join(self.tmp.name, "escape")))
self.assertFalse(os.path.exists(awg_state))
def test_import_takes_declared_names_outside_the_runtime_pattern(self):
# Declared tags and user names are any string; only a path made of one is checked.
awg_state = os.path.join(self.tmp.name, "awg.json")
salamander_file = os.path.join(self.tmp.name, "declared-salamander")
self.spec["listeners"][2]["amneziaWg"] = {"stateFile": awg_state, "interfaceName": "awgi-awg", "subnet": "10.66.0.0/24"}
self.spec["listeners"][0]["salamanderStateFile"] = salamander_file
tag = self.spec["listeners"][0]["tag"]
bundle = self.manager.export()
bundle["amneziaWg"] = {"awg": {"version": 1, "server": {}, "users": {"bob smith": {"offset": 3}}}}
bundle["salamander"] = {tag: "secret-password"}
report = self.manager.import_bundle(bundle)
self.assertEqual(report["amneziaWg"], ["awg"])
self.assertEqual(report["salamander"], [tag])
with open(salamander_file, encoding="utf-8") as handle:
self.assertEqual(handle.read(), "secret-password\n")
def test_import_refuses_a_runtime_user_named_as_a_declared_one(self):
bundle = self.manager.export()
declared = sorted(self.spec["users"])[0]
bundle["runtime"]["users"][declared] = {"order": 900, "uuid": str(uuid.uuid4()), "password": "x" * 16}
with self.assertRaises(im.ApiError) as raised:
self.manager.import_bundle(bundle)
self.assertEqual(raised.exception.status, 409)
self.assertNotIn(declared, rt.load_spool(self.spool)[0]["users"])
def test_a_malformed_state_entry_is_left_out(self):
policy.write_json(self.config["stateFile"], {"users": {"alice": {"periodStart": "x"}, "bob": {"periodStart": 5}},
"slots": {"alice": "1", "bob": 2}})
state = policy.load_state(self.config["stateFile"])
self.assertEqual(state["users"], {"bob": {"periodStart": 5}})
self.assertEqual(state["slots"], {"bob": 2})
class Api(ManagerTest):
def test_routes(self):
status, value = im.handle_api(self.manager, "POST", "/api/v1/users", {}, {"name": "alice", "policy": {"ipLimit": 2}})
self.assertEqual(status, 201)
self.assertEqual(value["policy"]["ipLimit"], 2)
status, value = im.handle_api(self.manager, "PATCH", "/api/v1/users/alice", {}, {"trafficLimit": "1G", "unset": ["ipLimit"]})
self.assertIsNone(value["policy"]["ipLimit"])
status, value = im.handle_api(self.manager, "POST", "/api/v1/users/alice/disable", {}, None)
self.assertFalse(value["active"])
with self.assertRaises(im.ApiError) as raised:
im.handle_api(self.manager, "PUT", "/api/v1/users/alice", {}, {})
self.assertEqual(raised.exception.status, 405)
with self.assertRaises(im.ApiError) as raised:
im.handle_api(self.manager, "GET", "/api/v1/users/nobody", {}, None)
self.assertEqual(raised.exception.status, 404)
def request(self, path, method="GET", body=None, headers=None, sock=None):
connection = http.client.HTTPConnection("localhost")
connection.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
connection.sock.connect(sock)
payload = body if isinstance(body, bytes) or body is None else json.dumps(body).encode()
connection.request(method, path, body=payload, headers=headers or {})
response = connection.getresponse()
return response.status, dict(response.getheaders()), response.read()
def test_over_the_sockets(self):
api_socket = os.path.join(self.tmp.name, "api.sock")
sub_socket = os.path.join(self.tmp.name, "sub.sock")
misses = mock.Mock()
servers = [im.unix_server(api_socket, im._handler(self.manager, "api", []), None, 0o600),
im.unix_server(sub_socket, im._handler(self.manager, "sub", [], misses), None, 0o600)]
for server in servers:
threading.Thread(target=server.serve_forever, daemon=True).start()
self.addCleanup(server.shutdown)
status, _, body = self.request("/api/v1/users", "POST", {"name": "alice"}, sock=api_socket)
self.assertEqual(status, 201, body)
status, _, body = self.request("/api/v1/users/alice", sock=api_socket)
self.assertEqual(json.loads(body)["name"], "alice")
status, _, body = self.request("/api/v1/users", "POST", b"x", sock=api_socket)
self.assertEqual(status, 400)
# The subscription socket answers subscriptions only.
self.write_rendered({"subscriptions": [{"user": "alice", "token": "c" * 32, "body": "eA=="}]})
status, headers, body = self.request("/sub/" + "c" * 32, sock=sub_socket)
self.assertEqual((status, body), (200, b"eA=="))
self.assertIn("subscription-userinfo", {k.lower() for k in headers})
status, headers, _ = self.request("/api/v1/users", sock=sub_socket)
self.assertEqual(status, 404)
self.assertEqual(headers.get("X-Content-Type-Options"), "nosniff")
# A miss is noted by the address the web server says it came from, when that is one.
self.request("/sub/" + "d" * 32, sock=sub_socket, headers={"X-Real-IP": "203.0.113.7"})
self.request("/sub/" + "d" * 32, sock=sub_socket, headers={"X-Forwarded-For": "10.0.0.1, 198.51.100.1"})
self.request("/sub/" + "d" * 32, sock=sub_socket, headers={"X-Real-IP": "forged words"})
self.assertEqual([c.args[0] for c in misses.note.call_args_list][-3:], ["203.0.113.7", "198.51.100.1", "unix"])
# The format from the query or the client; a page that names the address it was asked at.
status, headers, body = self.request("/sub/" + "c" * 32 + "?format=sing-box", sock=sub_socket)
self.assertEqual(json.loads(body)["route"]["final"], "direct")
del self.config["subscriptions"]["baseUrl"]
status, headers, body = self.request("/sub/" + "c" * 32, sock=sub_socket, headers={
"User-Agent": "Mozilla/5.0", "Accept": "text/html", "Host": "vpn.example.org", "X-Forwarded-Proto": "https"})
self.assertEqual(status, 200)
self.assertIn("https://vpn.example.org/sub/" + "c" * 32, body.decode())
status, headers, body = self.request("/sub/" + "c" * 32, sock=sub_socket, headers={
"User-Agent": "Mozilla/5.0", "Accept": "text/html", "Host": "evil\"><script>"})
self.assertNotIn("evil", body.decode())
def test_tokens(self):
path = os.path.join(self.tmp.name, "tokens")
with open(path, "w", encoding="utf-8") as handle:
handle.write("# bots\nbot:s3cret\nplain\n")
self.assertEqual(im.read_tokens(path), [b"s3cret", b"plain"])
if __name__ == "__main__":
unittest.main()
+244
View File
@@ -0,0 +1,244 @@
#!/usr/bin/env python3
import datetime
import json
import os
import tempfile
import time
import unittest
import inbound_policy as policy
import inbound_runtime as rt
from proxy_inbound import render_xray_inbound
def midnight(year, month, day):
return int(time.mktime(datetime.date(year, month, day).timetuple()))
class Parsing(unittest.TestCase):
def test_sizes_are_binary(self):
self.assertEqual(policy.parse_size("50G"), 50 * 1024**3)
self.assertEqual(policy.parse_size("1.5T"), int(1.5 * 1024**4))
self.assertEqual(policy.parse_size("512MiB"), 512 * 1024**2)
self.assertEqual(policy.parse_size(1000), 1000)
for none in (None, 0, "", "none", "unlimited", "0"):
self.assertIsNone(policy.parse_size(none))
for bad in ("lots", "-5G", -1, 1.5, "5X"):
with self.assertRaises(policy.PolicyError):
policy.parse_size(bad)
def test_rates_are_decimal_bits(self):
self.assertEqual(policy.parse_rate("10M"), 10_000_000)
self.assertEqual(policy.parse_rate("500k"), 500_000)
self.assertEqual(policy.parse_rate("1Gbit"), 1_000_000_000)
self.assertIsNone(policy.parse_rate("0"))
def test_speed_forms(self):
self.assertEqual(policy.parse_speed("20M"), {"up": 20_000_000, "down": 20_000_000})
self.assertEqual(policy.parse_speed("20M/5M"), {"up": 5_000_000, "down": 20_000_000})
self.assertEqual(policy.parse_speed({"down": "8M"}), {"up": None, "down": 8_000_000})
self.assertIsNone(policy.parse_speed("0/0"))
with self.assertRaises(policy.PolicyError):
policy.parse_speed({"sideways": "1M"})
def test_times(self):
now = 1_800_000_000
self.assertEqual(policy.parse_time("+30d", now), now + 30 * 86400)
self.assertEqual(policy.parse_time("+2h", now), now + 7200)
# A date is the end of that day.
self.assertEqual(policy.parse_time("2026-12-31"), midnight(2027, 1, 1))
self.assertEqual(policy.parse_time("2026-12-31T00:00:00+00:00"), 1798675200)
self.assertEqual(policy.parse_time(str(now)), now)
self.assertIsNone(policy.parse_time("never"))
with self.assertRaises(policy.PolicyError):
policy.parse_time("next tuesday")
class Policies(unittest.TestCase):
def test_normalize_and_store_round_trip(self):
fields = policy.normalize(
{"trafficLimit": "10G", "speedLimit": "10M/2M", "ipLimit": "2", "trafficPeriod": "monthly",
"meta": {"telegram": "42"}, "enabled": False, "expiresAt": "+1d"},
now=1_800_000_000,
)
self.assertEqual(fields["trafficLimit"], 10 * 1024**3)
self.assertEqual(fields["ipLimit"], 2)
self.assertEqual(fields["expiresAt"], 1_800_086_400)
self.assertEqual(policy.check_stored(fields), fields)
self.assertIsNone(policy.normalize({"expiresAt": 0})["expiresAt"])
def test_unknown_and_bad_fields(self):
for bad in ({"colour": "red"}, {"enabled": "yes"}, {"trafficPeriod": "yearly"}, {"ipLimit": -1},
{"meta": {"a b": "x"}}, {"meta": {"k": 5}}):
with self.assertRaises(policy.PolicyError, msg=bad):
policy.normalize(bad)
def test_stored_overrides_declared_field_by_field(self):
declared = {"trafficLimit": 100, "ipLimit": 3}
stored = {"ipLimit": None, "enabled": False}
merged = policy.effective(declared, stored)
self.assertEqual(merged["trafficLimit"], 100)
self.assertIsNone(merged["ipLimit"])
self.assertFalse(merged["enabled"])
def test_declared_nulls_do_not_override(self):
spec = {"users": {"phone": {"policy": {"trafficLimit": None, "ipLimit": 2, "expiresAt": None}}}}
self.assertEqual(policy.declared_policies(spec), {"phone": {"ipLimit": 2}})
class Traffic(unittest.TestCase):
STATS = {
"days": {
"2026-10-01": {"user": {"a": {"up": 10, "down": 90}, "b": {"up": 1, "down": 1}}},
"2026-10-02": {"user": {"a": {"up": 5, "down": 5}}},
}
}
def test_usage_from_period_start_less_baseline(self):
start = midnight(2026, 10, 1) + 3600
self.assertEqual(policy.used_bytes(self.STATS, {"periodStart": start, "baselineUp": 10, "baselineDown": 30}, "a"), 70)
self.assertEqual(policy.period_traffic(self.STATS, {"periodStart": start, "baselineDown": 30}, "a"), (15, 65))
self.assertEqual(policy.used_bytes(self.STATS, {"periodStart": midnight(2026, 10, 2)}, "a"), 10)
# Not measured yet: the history before the manager saw the user does not count.
self.assertEqual(policy.used_bytes(self.STATS, {}, "a"), 0)
self.assertEqual(policy.used_bytes(self.STATS, {"periodStart": 1, "baselineUp": 500, "baselineDown": 500}, "a"), 0)
def test_start_period_takes_the_day_so_far(self):
now = midnight(2026, 10, 1) + 7200
state = policy.start_period(self.STATS, "a", now)
self.assertEqual((state["baselineUp"], state["baselineDown"]), (10, 90))
self.assertEqual(policy.used_bytes(self.STATS, state, "a"), 10)
def test_monthly_periods_renew_at_midnight_on_the_anchor_day(self):
state = {"periodStart": midnight(2026, 1, 31) + 5000, "baselineUp": 7, "anchorDay": 31}
pol = {"trafficPeriod": "monthly"}
self.assertEqual(policy.period_end(pol, state), midnight(2026, 2, 28))
self.assertTrue(policy.roll_period(pol, state, midnight(2026, 3, 5)))
# Feb 28, then Mar 31 is still ahead: the anchor day survives the short month.
self.assertEqual(state["periodStart"], midnight(2026, 2, 28))
self.assertEqual(state["baselineUp"], 0)
self.assertEqual(policy.period_end(pol, state), midnight(2026, 3, 31))
self.assertFalse(policy.roll_period(pol, state, midnight(2026, 3, 6)))
def test_no_period_never_rolls(self):
state = {"periodStart": 1, "baselineUp": 3}
self.assertFalse(policy.roll_period({"trafficPeriod": None}, state, time.time()))
self.assertEqual(state["baselineUp"], 3)
def test_durations(self):
self.assertEqual(policy.parse_duration("30d"), 30 * 86400)
self.assertEqual(policy.parse_duration("+12h"), 12 * 3600)
self.assertEqual(policy.parse_duration(90), 90)
for none in (None, 0, "", "none", "0d"):
self.assertIsNone(policy.parse_duration(none))
for bad in ("30 days", "-1d", -5, 1.5):
with self.assertRaises(policy.PolicyError):
policy.parse_duration(bad)
self.assertEqual(policy.normalize({"expiresAfter": "1w"}), {"expiresAfter": 7 * 86400})
policy.check_stored({"expiresAfter": 604800})
def test_on_hold_until_an_expiry_is_set(self):
self.assertTrue(policy.on_hold(policy.effective({"expiresAfter": 86400}, None)))
# A term started, or an expiry given by hand: no longer on hold.
self.assertFalse(policy.on_hold(policy.effective({"expiresAfter": 86400}, {"expiresAt": 2_000_000_000})))
self.assertFalse(policy.on_hold(policy.effective(None, None)))
self.assertTrue(policy.status(policy.effective({"expiresAfter": 86400}, None), 0, 2_000_000_000)["active"])
def test_status_reasons(self):
now = 2_000_000_000
self.assertEqual(policy.status(policy.effective(None, None), 10**12, now), {"active": True, "reasons": []})
pol = policy.effective({"trafficLimit": 100, "expiresAt": now - 1}, {"enabled": False})
self.assertEqual(policy.status(pol, 100, now)["reasons"], ["disabled", "expired", "traffic"])
self.assertTrue(policy.status(policy.effective({"trafficLimit": 100}, None), 99, now)["active"])
class Statuses(unittest.TestCase):
def setUp(self):
self.dir = tempfile.TemporaryDirectory()
base = self.dir.name
self.manager = {
"policyFile": os.path.join(base, "policy.json"),
"stateFile": os.path.join(base, "state.json"),
"statsFile": os.path.join(base, "stats.json"),
"speedLimits": True,
}
def tearDown(self):
self.dir.cleanup()
def write(self, key, value):
with open(self.manager[key], "w", encoding="utf-8") as handle:
json.dump(value, handle)
def test_without_the_manager_nothing_changes(self):
self.assertEqual(policy.statuses({"users": {"a": {}}}, []), {})
def test_statuses_from_the_files(self):
now = time.time()
today = policy.day_key(now)
self.write("policyFile", {"users": {"rt": {"trafficLimit": 50}, "phone": {"speedLimit": {"up": 1000, "down": 1000}}}})
self.write("stateFile", {"users": {"rt": {"periodStart": int(now) - 60}}, "slots": {"phone": 3, "rt": 4}})
self.write("statsFile", {"days": {today: {"user": {"rt": {"up": 30, "down": 30}}}}})
spec = {"manager": self.manager, "users": {"phone": {"policy": {"expiresAt": None}}}}
views = policy.statuses(spec, ["rt"], now)
self.assertEqual(views["rt"], {"active": False, "reasons": ["traffic"], "level": 0})
self.assertEqual(views["phone"], {"active": True, "reasons": [], "level": 3})
def test_a_broken_policy_file_is_no_policy(self):
with open(self.manager["policyFile"], "w", encoding="utf-8") as handle:
handle.write("{nope")
spec = {"manager": self.manager, "users": {"a": {}}}
self.assertTrue(policy.statuses(spec, [])["a"]["active"])
def listener(tag, kind, users, **extra):
base = {"tag": tag, "type": kind, "port": 443, "listen": "::", "via": "direct", "users": users,
"flow": None, "fallbacks": [], "transport": {"type": "raw", "path": "/"},
"tls": {"enable": False}, "reality": {"enable": False}, "hysteria": {}}
base.update(extra)
return base
def user(name, **fields):
return {"name": name, "uuid": "b831381d-6324-4d53-ad4f-8cda48b30811", "password": "pw-" + name, **fields}
class MergeWithStatuses(unittest.TestCase):
def spec(self):
return {
"runtime": None,
"users": {},
"listeners": [
listener("vl", "vless", [user("a"), user("b")]),
listener("sk", "socks", [user("a")]),
listener("ss", "shadowsocks", [user("b")], method="aes-128-gcm"),
],
}
def test_inactive_users_leave_xray_but_listeners_that_can_stay_do(self):
statuses = {"a": {"active": False, "level": 0}, "b": {"active": True, "level": 7}}
merged, _, warnings = rt.merge_state(self.spec(), {"users": {}, "listeners": {}}, statuses=statuses)
tags = [l["tag"] for l in merged["listeners"]]
self.assertEqual(tags, ["vl", "ss"])
self.assertIn("listener 'sk' has no active users; not started", warnings)
inbound = render_xray_inbound(merged["listeners"][0])
self.assertEqual([(c["email"], c.get("level")) for c in inbound["settings"]["clients"]], [("b", 7)])
ss = render_xray_inbound(merged["listeners"][1])
self.assertEqual(ss["settings"]["level"], 7)
def test_a_vless_listener_with_everyone_off_runs_empty(self):
statuses = {"a": {"active": False}, "b": {"active": False}}
merged, _, _ = rt.merge_state(self.spec(), {"users": {}, "listeners": {}}, statuses=statuses)
vl = next(l for l in merged["listeners"] if l["tag"] == "vl")
self.assertEqual(render_xray_inbound(vl)["settings"]["clients"], [])
def test_no_statuses_keeps_everyone(self):
merged, _, warnings = rt.merge_state(self.spec(), {"users": {}, "listeners": {}})
self.assertEqual(len(merged["listeners"]), 3)
self.assertEqual(warnings, [])
self.assertTrue(all(u["active"] for l in merged["listeners"] for u in l["users"]))
if __name__ == "__main__":
unittest.main()
+272
View File
@@ -0,0 +1,272 @@
#!/usr/bin/env python3
import base64
import json
import os
import re
import subprocess
import tempfile
import unittest
import inbound_subscription as sub
import proxy_inbound
UUID = "11111111-2222-3333-4444-555555555555"
LINKS = {
"reality": f"vless://{UUID}@vpn.example.com:443?type=tcp&security=reality&sni=www.microsoft.com&fp=chrome"
"&pbk=jNXHt1yRo0vDuchQlIP6Z0ZvjT3KtzVI-T4E7RoLJS0&sid=0123abcd&flow=xtls-rprx-vision#reality",
"ws": f"vless://{UUID}@vpn.example.com:443?type=ws&security=tls&sni=vpn.example.com&path=%2Fws"
"&host=vpn.example.com&fp=chrome&alpn=h2%2Chttp%2F1.1#ws",
"grpc": f"vless://{UUID}@vpn.example.com:443?type=grpc&security=tls&sni=vpn.example.com&serviceName=gs#grpc",
"xhttp": f"vless://{UUID}@vpn.example.com:443?type=xhttp&security=tls&sni=vpn.example.com&path=%2Fx#xh",
"trojan": "trojan://pass@vpn.example.com:8443?security=tls&sni=vpn.example.com&type=httpupgrade&path=%2Fhu#tr",
"hy2": "hysteria2://pw@vpn.example.com:443?sni=vpn.example.com&obfs=salamander&obfs-password=xx&mport=20000-20010#hy2",
}
def rendered_for(user="alice"):
links = [{"tag": tag, "user": user, "link": link, "outbound": proxy_inbound.client_outbound(link, tag)}
for tag, link in LINKS.items()]
links.append({"tag": "reality", "user": user, "link": LINKS["reality"], "variant": "onion",
"outbound": proxy_inbound.client_outbound(LINKS["reality"], "reality")})
links.append({"tag": "awg", "user": user, "link": "vpn://x", "config": "[Interface]", "outbound": None})
links.append({"tag": "ws", "user": "bob", "link": LINKS["ws"], "outbound": None})
body = base64.b64encode("\n".join(LINKS.values()).encode()).decode()
return {"links": links, "subscriptions": [{"user": user, "token": "a" * 32, "body": body}]}
ROW = {"name": "alice", "active": True, "reasons": [], "onHold": False, "expiresAt": 2_000_000_000,
"policy": {"expiresAfter": None},
"traffic": {"up": 1, "down": 1023, "used": 1024, "limit": 4096, "periodEnd": 1_900_000_000}}
class Formats(unittest.TestCase):
def test_pick_by_client(self):
cases = {
"ClashMetaForAndroid/2.11.2.Meta": "clash",
"clash-verge/v2.0.0": "clash",
"FlClash/v0.8": "clash",
"mihomo/1.19": "clash",
"Stash/2.4.6 Clash/1.9.0": "clash",
"SFA/1.11.4 (Android 14; sing-box 1.11.4)": "sing-box",
"SFI/1.12.0": "sing-box",
"sing-box 1.12.0": "sing-box",
# Hiddify names Clash and sing-box after "like": the links serve it best.
"HiddifyNext/2.5.7 (android) like ClashMeta v2ray sing-box": "base64",
"v2rayNG/1.9.1": "base64",
"Happ/1.0": "base64",
"": "base64",
}
for agent, expected in cases.items():
self.assertEqual(sub.pick_format(None, agent, "*/*"), expected, agent)
browser = "Mozilla/5.0 (X11; Linux x86_64) Firefox/131.0"
self.assertEqual(sub.pick_format(None, browser, "text/html,application/xhtml+xml"), "html")
# A client that says Mozilla but wants no page.
self.assertEqual(sub.pick_format(None, browser, "*/*"), "base64")
self.assertEqual(sub.pick_format("clash", "v2rayNG/1.9", ""), "clash")
self.assertEqual(sub.pick_format("nonsense", "v2rayNG/1.9", ""), "base64")
def test_entries_are_the_users_links_named_apart(self):
names = [e["name"] for e in sub.entries(rendered_for(), "alice")]
self.assertEqual(names, ["reality", "ws", "grpc", "xhttp", "trojan", "hy2", "reality-onion"])
def test_names_stay_clear_of_the_groups(self):
rendered = {"links": [{"tag": tag, "user": "u", "link": LINKS["ws"], "outbound": None}
for tag in ("proxy", "AUTO", "direct", "proxy")]}
self.assertEqual([e["name"] for e in sub.entries(rendered, "u")], ["proxy-2", "AUTO-2", "direct-2", "proxy-3"])
def test_sing_box_config(self):
config = sub.sing_box_config(sub.entries(rendered_for(), "alice"))
tags = [o["tag"] for o in config["outbounds"]]
# XHTTP only XRay dials: left out of the config.
self.assertNotIn("xhttp", tags)
self.assertEqual(tags[:2], ["proxy", "auto"])
self.assertEqual(config["outbounds"][0]["outbounds"][0], "auto")
self.assertIn("reality-onion", config["outbounds"][1]["outbounds"])
self.assertEqual(config["route"]["final"], "proxy")
empty = sub.sing_box_config([])
self.assertEqual(empty["route"]["final"], "direct")
self.assertEqual([o["tag"] for o in empty["outbounds"]], ["direct"])
sing_box = os.environ.get("SING_BOX")
if sing_box:
for value in (config, empty):
with tempfile.NamedTemporaryFile("w", suffix=".json") as handle:
json.dump(value, handle)
handle.flush()
done = subprocess.run([sing_box, "check", "-c", handle.name], capture_output=True, text=True)
self.assertEqual(done.returncode, 0, done.stderr)
def test_clash_proxies(self):
config = sub.clash_config(sub.entries(rendered_for(), "alice"))
proxies = {p["name"]: p for p in config["proxies"]}
self.assertNotIn("xhttp", proxies)
reality = proxies["reality"]
self.assertEqual((reality["type"], reality["server"], reality["port"], reality["uuid"]),
("vless", "vpn.example.com", 443, UUID))
self.assertEqual(reality["flow"], "xtls-rprx-vision")
self.assertEqual(reality["servername"], "www.microsoft.com")
self.assertEqual(reality["reality-opts"], {"public-key": "jNXHt1yRo0vDuchQlIP6Z0ZvjT3KtzVI-T4E7RoLJS0",
"short-id": "0123abcd"})
self.assertEqual(reality["client-fingerprint"], "chrome")
self.assertEqual(reality["network"], "tcp")
self.assertEqual(proxies["ws"]["ws-opts"], {"path": "/ws", "headers": {"Host": "vpn.example.com"}})
self.assertEqual(proxies["ws"]["alpn"], ["h2", "http/1.1"])
self.assertEqual(proxies["grpc"]["grpc-opts"], {"grpc-service-name": "gs"})
trojan = proxies["trojan"]
self.assertEqual((trojan["type"], trojan["sni"], trojan["network"]), ("trojan", "vpn.example.com", "ws"))
self.assertTrue(trojan["ws-opts"]["v2ray-http-upgrade"])
hy2 = proxies["hy2"]
self.assertEqual((hy2["type"], hy2["obfs"], hy2["obfs-password"], hy2["ports"]),
("hysteria2", "salamander", "xx", "20000-20010"))
groups = {g["name"]: g for g in config["proxy-groups"]}
self.assertEqual(groups["PROXY"]["proxies"][0], "auto")
self.assertEqual(config["rules"][-1], "MATCH,PROXY")
self.assertEqual(sub.clash_proxy("x", {"type": "shadowsocks", "method": "aes-128-gcm", "password": "p",
"server": "h", "server_port": 1, "plugin": "obfs-local"}), None)
self.assertEqual(sub.clash_proxy("x", {"type": "shadowsocks", "method": "aes-128-gcm", "password": "p",
"server": "h", "server_port": 1})["cipher"], "aes-128-gcm")
def test_render(self):
rendered = rendered_for()
body_b64 = rendered["subscriptions"][0]["body"]
args = (rendered, "alice", body_b64, ROW, "https://vpn.example.com/sub/" + "a" * 32, "VPN alice", {})
body, kind = sub.render("base64", *args)
self.assertEqual((body, kind), (body_b64.encode(), "text/plain; charset=utf-8"))
body, _ = sub.render("links", *args)
self.assertEqual(body.decode().split("\n")[0], LINKS["reality"])
body, kind = sub.render("clash", *args)
self.assertEqual(kind, "text/yaml; charset=utf-8")
self.assertIn("proxies", json.loads(body))
body, kind = sub.render("sing-box", *args)
self.assertEqual(json.loads(body)["route"]["final"], "proxy")
def test_page(self):
rendered = rendered_for()
url = "https://vpn.example.com/sub/" + "a" * 32
row = {**ROW, "name": "<b>alice</b>"}
page = sub.html_page(row, sub.entries(rendered, "alice"), url, "VPN <b>", {"supportUrl": "https://t.me/x"}, "en")
self.assertIn("VPN &lt;b&gt;", page)
self.assertNotIn("<b>", page)
self.assertIn("User: &lt;b&gt;alice&lt;/b&gt;", page)
# Named in the title already: not again.
self.assertNotIn("Пользователь", sub.html_page(ROW, [], url, "VPN alice", {}, "ru"))
self.assertIn("Пользователь: alice", sub.html_page(ROW, [], url, "Stage", {}, "ru"))
self.assertIn("Active", page)
self.assertIn("1.0 KiB of 4.0 KiB", page)
self.assertIn('<rect class="fill" width="25"', page)
self.assertIn(f'data-qr="{url}"', page)
self.assertIn("happ://add/" + url, page)
self.assertIn("v2rayng://install-config?url=https%3A%2F%2Fvpn.example.com", page)
self.assertIn("https://t.me/x", page)
# Share links are attributes, escaped: & stays &amp;.
self.assertIn("type=tcp&amp;security=reality", page)
held = sub.html_page({**ROW, "onHold": True, "expiresAt": None, "policy": {"expiresAfter": 30 * 86400}},
[], url, "VPN", {}, "ru")
self.assertIn("Начнётся с первого подключения", held)
self.assertIn("30d с первого подключения", held)
off = sub.html_page({**ROW, "active": False, "reasons": ["expired", "traffic"]}, [], url, "VPN", {}, "en")
self.assertIn("expired, out of traffic", off)
self.assertEqual(sub.language("ru-RU,ru;q=0.9,en;q=0.8"), "ru")
self.assertEqual(sub.language("de-DE,en;q=0.5"), "en")
self.assertEqual(sub.language(""), "en")
def test_apps_for_the_system(self):
url = "https://vpn.example.com/sub/" + "a" * 32
agents = {
"android": "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 Chrome/130.0 Mobile Safari/537.36",
"ios": "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 Mobile/15E148",
"macos": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 Version/18.0 Safari/605.1.15",
"windows": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/130.0 Safari/537.36",
"linux": "Mozilla/5.0 (X11; Linux x86_64; rv:131.0) Gecko/20100101 Firefox/131.0",
}
for system, agent in agents.items():
self.assertEqual(sub.platform(agent), system)
self.assertEqual(sub.platform("Mozilla/5.0 (X11; CrOS x86_64 15917.0.0) Chrome/130.0"), "android")
self.assertIsNone(sub.platform(""))
def shown(agent):
"""(labels up front, labels folded away) on the page for this browser."""
page = sub.html_page(ROW, [], url, "VPN", {}, "en", user_agent=agent)
apps = page.split("Add to an app</h2>", 1)[1].split("</div>", 1)[0]
first, _, folded = apps.partition("<details>")
label = lambda part: re.findall(r'<a class="app" href="[^"]*">([^<]*)</a>', part)
return label(first), label(folded)
first, folded = shown(agents["android"])
self.assertIn("v2rayNG", first)
self.assertIn("Streisand", folded)
self.assertNotIn("Proxy Suite", first)
first, folded = shown(agents["linux"])
self.assertEqual(first, ["Happ", "Hiddify", "Clash / mihomo", "Proxy Suite"])
self.assertIn("v2rayNG", folded)
# Nothing said: every app, none folded away.
first, folded = shown("")
self.assertEqual((len(first), folded), (len(sub.APPS), []))
self.assertIn('proxy-suite://install-config?url=https%3A%2F%2Fvpn.example.com%2Fsub%2F' + "a" * 32 + "&amp;name=VPN",
sub.html_page(ROW, [], url, "VPN", {}, "ru", user_agent=agents["linux"]))
self.assertIn("Другие приложения", sub.html_page(ROW, [], url, "VPN", {}, "ru", user_agent=agents["linux"]))
def test_page_policy(self):
"""The CSP lets the page's own script and stylesheet run, by their hashes, and nothing
else: no style attribute, no other script or stylesheet."""
page = sub.html_page({**ROW, "active": False, "reasons": ["expired"]},
sub.entries(rendered_for(), "alice"), "https://vpn.example.com/sub/x", "VPN", {}, "en")
csp = dict(part.strip().split(" ", 1) for part in sub.PAGE_HEADERS["Content-Security-Policy"].split(";"))
scripts = re.findall(r"<script>(.*?)</script>", page, re.S)
styles = re.findall(r"<style>(.*?)</style>", page, re.S)
self.assertEqual((len(scripts), len(styles)), (1, 1))
self.assertEqual(csp["script-src"], sub._csp_hash(scripts[0]))
self.assertEqual(csp["style-src"], sub._csp_hash(styles[0]))
self.assertEqual(csp["default-src"], "'none'")
self.assertNotIn("unsafe", sub.PAGE_HEADERS["Content-Security-Policy"])
self.assertNotIn(" style=", page)
self.assertEqual(page.count("<script"), 1)
def test_qr_code(self):
"""The browser's QR encoder, run by node, read back by zbar: each length up to version
40, multibyte text, and every mask."""
node, zbarimg = os.environ.get("NODE"), os.environ.get("ZBARIMG")
if not (node and zbarimg):
self.skipTest("needs NODE and ZBARIMG")
driver = """
const fs = require('fs');
const [source, text, mask, out] = process.argv.slice(2);
let code = fs.readFileSync(source, 'utf8');
if (mask !== '') code = code.replace('flip(best);format(best);return m', `flip(${mask});format(${mask});return m`);
const qrMatrix = new Function(code + ';return qrMatrix')();
const m = qrMatrix(text), quiet = 4, scale = 3, n = (m.length + 2 * quiet) * scale;
const rows = [];
for (let y = 0; y < n; y++) {
const row = [];
for (let x = 0; x < n; x++) {
const my = Math.floor(y / scale) - quiet, mx = Math.floor(x / scale) - quiet;
row.push(my >= 0 && mx >= 0 && my < m.length && mx < m.length && m[my][mx] ? 1 : 0);
}
rows.push(row.join(' '));
}
fs.writeFileSync(out, `P1\\n${n} ${n}\\n${rows.join('\\n')}\\n`);
console.log(m.length);
"""
self.assertIn("flip(best);format(best);return m", sub._QR_SCRIPT)
cases = [("https://vpn.example.com/sub/" + "0123456789abcdef" * 2, ""), ("https://vpn.example.com/sub/привет", "")]
cases += [("".join(chr(0x21 + (i * 7 + n) % 90) for i in range(n)), "") for n in (1, 14, 15, 84, 154, 213, 400, 1000, 2331)]
cases += [("https://vpn.example.com/sub/" + "a" * 32, str(mask)) for mask in range(8)]
with tempfile.TemporaryDirectory() as tmp:
source, script, image = (os.path.join(tmp, name) for name in ("qr.js", "driver.js", "qr.pbm"))
with open(source, "w", encoding="utf-8") as handle:
handle.write(sub._QR_SCRIPT)
with open(script, "w", encoding="utf-8") as handle:
handle.write(driver)
sizes = set()
for text, mask in cases:
with self.subTest(length=len(text), mask=mask):
drawn = subprocess.run([node, script, source, text, mask, image], capture_output=True, text=True, check=True)
sizes.add(int(drawn.stdout))
read = subprocess.run([zbarimg, "-q", "--raw", image], capture_output=True)
self.assertEqual(read.stdout.decode("utf-8").rstrip("\n"), text)
# Versions 1 and 40, and some between.
self.assertTrue({21, 177} <= sizes and len(sizes) >= 8, sizes)
if __name__ == "__main__":
unittest.main()