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

@@ -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;
};
}
{