feat: allow using suite on non-nixos systems

This commit is contained in:
FUFSoB committed 2026-09-17 13:27:08 +05:00
1 parent e852bef400
commit 3b568bb54e
63 files changed
+3572 -523

No files matched your search

+30
View File
@@ -0,0 +1,30 @@
# Shared by the adapters whose host runs NixOS's own systemd unit options (NixOS,
# system-manager).
{ lib }:
rec {
# Only what the core set: an internal option's default would add a definition of its
# own. Definitions are forwarded rather than values, so priorities nested inside them
# (mkDefault in a unit, say) still meet the rest of the host's.
forwardWith =
wrap: option:
lib.mkIf (option.highestPrio < (lib.mkOptionDefault null).priority) (
lib.mkMerge (map wrap option.definitions)
);
forward = forwardWith lib.id;
# Scripts share one store name per block, and journald names a unit's output
# after its ExecStart basename; tag each unit with its own name instead.
unitsWithOwnSyslogIdentifier = lib.mkOption {
type = lib.types.attrsOf (
lib.types.submodule (
{ name, ... }:
{
config.serviceConfig.SyslogIdentifier = lib.mkIf (lib.hasPrefix "proxy-suite-" name) (
lib.mkDefault (lib.removeSuffix "@" name)
);
}
)
);
};
}
@@ -0,0 +1,64 @@
# home-manager: the services run rootless in the user's systemd manager, rendered into
# home-manager's INI form by ./user-units.nix.
{
config,
options,
lib,
pkgs,
...
}:
let
cfg = config.services.proxy-suite;
host = cfg.host;
internal = cfg.internal;
inherit
(import ./user-units.nix {
inherit lib pkgs;
inherit (host) runtimeDir;
stateDir = dirOf host.stateDir;
})
toService
toTimer
toPath
;
enabled = lib.filterAttrs (_: unit: unit.enable);
in
{
config = lib.mkMerge [
{
services.proxy-suite.host = {
kind = "home-manager";
privileged = false;
serviceManager = "systemd-user";
stateDir = lib.mkDefault "${config.xdg.stateHome}/proxy-suite";
# A literal path the scripts and proxy-ctl can share: the user's runtime
# directory is only known once the manager runs. Point it at /run/user/UID to
# have it cleared on reboot.
runtimeDir = lib.mkDefault "${config.xdg.cacheHome}/proxy-suite/run";
};
}
(lib.mkIf cfg.enable (
lib.mkMerge [
{
systemd.user.services = lib.mapAttrs toService (
enabled (internal.services // internal.userServices)
);
systemd.user.timers = lib.mapAttrs toTimer (enabled internal.timers);
systemd.user.paths = lib.mapAttrs toPath (enabled internal.paths);
home.packages = lib.mkMerge [
(lib.mkBefore internal.earlyPackages)
internal.packages
];
}
(lib.optionalAttrs (options.systemd.user ? tmpfiles) {
systemd.user.tmpfiles.rules = internal.tmpfiles;
})
]
))
];
}
+123
View File
@@ -0,0 +1,123 @@
# nix-on-droid: no systemd and no root. The units run under proxy-suitectl, a small
# supervisor that reads them, rendered as for a user manager, from a manifest the
# activation links into place; proxy-ctl and the scripts talk to it in systemctl's words.
{
config,
lib,
pkgs,
...
}:
let
cfg = config.services.proxy-suite;
host = cfg.host;
internal = cfg.internal;
home = config.user.home;
inherit
(import ./user-units.nix {
inherit lib pkgs;
inherit (host) runtimeDir;
stateDir = dirOf host.stateDir;
hostPath = "${home}/.nix-profile/bin";
})
toService
toTimer
toPath
;
enabled = lib.filterAttrs (_: unit: unit.enable);
supervisorDir = "${host.runtimeDir}/proxy-suite-supervisor";
# Outside the store, so proxy-suitectl stays the same from one generation to the next.
manifestLink = "${host.stateDir}/supervisor/manifest.json";
manifest = pkgs.writeText "proxy-suite-units.json" (
builtins.toJSON {
services = lib.mapAttrs toService (enabled (internal.services // internal.userServices));
timers = lib.mapAttrs toTimer (enabled internal.timers);
paths = lib.mapAttrs toPath (enabled internal.paths);
inherit (internal) tmpfiles;
}
);
suitectl = import ../../../pkgs/proxy-suite-supervisor.nix { inherit lib pkgs; } {
inherit supervisorDir;
manifest = manifestLink;
inherit (host) runtimeDir;
stateDir = dirOf host.stateDir;
};
suitectlBin = "${suitectl}/bin/proxy-suitectl";
# Once per session tree: nested shells find it exported.
sessionStart = ''
if [ -z "''${__PROXY_SUITE_SESSION:-}" ]; then
export __PROXY_SUITE_SESSION=1
( ${suitectlBin} ensure >/dev/null 2>&1 & )
fi
'';
in
{
options.services.proxy-suite.nixOnDroid.startWithSession = lib.mkOption {
type = lib.types.bool;
default = true;
description = ''
Start the services when a Nix-on-Droid shell opens, if they are not running yet.
Android offers the app no boot hook, so without this they only start on
`nix-on-droid switch` or `proxy-suitectl boot`. Android may still stop them in
the background: keep the app's wake lock on and exempt it from battery optimisation.
'';
};
config = lib.mkMerge [
{
services.proxy-suite.host = {
kind = "nix-on-droid";
privileged = false;
serviceManager = "supervisor";
stateDir = lib.mkDefault "${home}/.local/state/proxy-suite";
runtimeDir = lib.mkDefault "${home}/.cache/proxy-suite/run";
systemctl = suitectlBin;
journalctl = "${suitectlBin} journal";
enableIPv6 = true;
# Android's kernel, resolver and firewall are not the app's to change.
kernelPackages = null;
firewallPackage = null;
resolvconfPackage = null;
};
}
(lib.mkIf cfg.enable {
assertions = [
{
assertion = !cfg.gui.enable;
message = "proxy-suite: the GUI needs a desktop session, which a nix-on-droid host does not have; use proxy-ctl or proxy-tui";
}
];
environment.packages = internal.earlyPackages ++ internal.packages ++ [ suitectl ];
build.activationAfter.proxySuite = ''
$DRY_RUN_CMD mkdir -p ${lib.escapeShellArg (dirOf manifestLink)}
$DRY_RUN_CMD ln -sfn ${manifest} ${lib.escapeShellArg manifestLink}
# Starts the supervisor, or restarts what changed under a running one.
if ! $DRY_RUN_CMD ${suitectlBin} boot; then
warnEcho "proxy-suite: some units did not start; see proxy-ctl status"
fi
'';
environment.etc = lib.mkIf cfg.nixOnDroid.startWithSession {
"profile".text = lib.mkAfter sessionStart;
"zshenv".text = lib.mkAfter sessionStart;
};
})
(lib.mkIf (!cfg.enable) {
# Disabled since the last generation: nothing should keep running.
build.activationAfter.proxySuite = ''
if [ -S ${lib.escapeShellArg "${supervisorDir}/control.sock"} ]; then
$DRY_RUN_CMD ${suitectlBin} shutdown || true
fi
'';
})
];
}
+75
View File
@@ -0,0 +1,75 @@
# NixOS: the core's declarations become NixOS settings as they are.
{
config,
options,
lib,
...
}:
let
cfg = config.services.proxy-suite;
internal = options.services.proxy-suite.internal;
inherit (import ./common.nix { inherit lib; })
forwardWith
forward
unitsWithOwnSyslogIdentifier
;
in
{
options.systemd.services = unitsWithOwnSyslogIdentifier;
options.systemd.user.services = unitsWithOwnSyslogIdentifier;
config = lib.mkMerge [
{
services.proxy-suite.host = {
kind = "nixos";
privileged = true;
serviceManager = "systemd";
inherit (config.networking) enableIPv6;
inherit (config.boot) kernelPackages;
firewallPackage = config.networking.firewall.package;
resolvconfPackage = config.networking.resolvconf.package;
};
}
(lib.mkIf cfg.enable {
systemd.services = forward internal.services;
systemd.user.services = forward internal.userServices;
systemd.timers = forward internal.timers;
systemd.paths = forward internal.paths;
systemd.tmpfiles.rules = forward internal.tmpfiles;
environment.systemPackages = lib.mkMerge [
(forwardWith lib.mkBefore internal.earlyPackages)
(forward internal.packages)
];
users.users = lib.genAttrs cfg.internal.systemUsers (name: {
isSystemUser = true;
group = name;
description = "proxy-suite daemons";
});
users.groups = lib.genAttrs (cfg.internal.systemUsers ++ cfg.internal.groups) (_: { });
security.polkit.enable = lib.mkIf cfg.internal.polkit.enable true;
security.polkit.extraConfig = forwardWith lib.mkAfter internal.polkit.rules;
networking.nftables.enable = lib.mkIf cfg.internal.nftables (lib.mkDefault true);
networking.firewall = {
allowedTCPPorts = forward internal.firewall.allowedTCPPorts;
allowedUDPPorts = forward internal.firewall.allowedUDPPorts;
extraReversePathFilterRules = forward internal.firewall.extraReversePathFilterRules;
};
boot.extraModulePackages = forward internal.kernelModulePackages;
})
# Off by default since nixpkgs 26.11, and always there before, where the option does
# not exist.
(lib.optionalAttrs (options.security.polkit ? enablePkexecWrapper) {
security.polkit.enablePkexecWrapper = lib.mkIf (
cfg.enable && cfg.internal.polkit.pkexecWrapper
) true;
})
];
}
@@ -0,0 +1,118 @@
# system-manager (numtide/system-manager): root services on another distribution. Its
# systemd options are NixOS's own, so units are forwarded as on NixOS; what it lacks
# (user units, polkit, nftables, the firewall, kernel modules) is written to /etc or
# left to the host.
{
config,
options,
lib,
pkgs,
...
}:
let
cfg = config.services.proxy-suite;
internal = options.services.proxy-suite.internal;
inherit (import ./common.nix { inherit lib; })
forwardWith
forward
unitsWithOwnSyslogIdentifier
;
# For the user manager each session runs: units go to /etc/systemd/user, which it reads
# alongside the distribution's own.
userUnits = import ./user-units.nix {
inherit lib pkgs;
runtimeDir = "%t";
stateDir = "%S";
# The GUI escalates through the distribution's setuid pkexec.
hostPath = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
};
toINI = lib.generators.toINI { listsAsDuplicateKeys = true; };
userServiceFiles = lib.concatMapAttrs (
name: unit:
let
fileName = "${name}.service";
rendered = userUnits.toService name unit;
file = pkgs.writeText fileName (toINI rendered);
link = target: lib.nameValuePair "systemd/user/${target}/${fileName}" { source = file; };
in
{
"systemd/user/${fileName}".source = file;
}
// lib.listToAttrs (
map (target: link "${target}.wants") (rendered.Install.WantedBy or [ ])
++ map (target: link "${target}.requires") (rendered.Install.RequiredBy or [ ])
)
) (lib.filterAttrs (_: unit: unit.enable) cfg.internal.userServices);
# awg-quick pushes DNS through resolvconf: resolvectl stands in for it where
# systemd-resolved owns resolv.conf, openresolv everywhere else.
resolvconf = pkgs.writeShellScriptBin "resolvconf" ''
if [ -d /run/systemd/resolve ]; then
exec -a resolvconf ${pkgs.systemd}/bin/resolvectl "$@"
fi
exec ${pkgs.openresolv}/bin/resolvconf "$@"
'';
in
{
options.systemd.services = unitsWithOwnSyslogIdentifier;
config = lib.mkMerge [
{
services.proxy-suite.host = {
kind = "system-manager";
privileged = true;
serviceManager = "systemd";
inherit (config.networking) enableIPv6;
# The host's kernel is not Nix's to extend: AmneziaWG runs in userspace.
kernelPackages = null;
firewallPackage = pkgs.nftables;
resolvconfPackage = resolvconf;
};
}
(lib.mkIf cfg.enable {
assertions = [
{
assertion = cfg.internal.kernelModulePackages == [ ];
message = "proxy-suite: system-manager cannot load kernel modules from Nix; leave amneziaWg.kernelModulePackage at null";
}
];
systemd.services = forward internal.services;
systemd.timers = forward internal.timers;
systemd.paths = forward internal.paths;
systemd.tmpfiles.rules = forward internal.tmpfiles;
environment.systemPackages = lib.mkMerge [
(forwardWith lib.mkBefore internal.earlyPackages)
(forward internal.packages)
];
environment.etc = lib.mkMerge [
userServiceFiles
# Read by polkit 0.106 and later; the distribution runs the daemon. The rules
# go through the host's setuid pkexec: nothing here needs a wrapper.
(lib.mkIf cfg.internal.polkit.enable {
"polkit-1/rules.d/50-proxy-suite.rules".text = cfg.internal.polkit.rules;
})
];
users.users = lib.genAttrs cfg.internal.systemUsers (name: {
isSystemUser = true;
group = name;
description = "proxy-suite daemons";
});
users.groups = lib.genAttrs (cfg.internal.systemUsers ++ cfg.internal.groups) (_: { });
# Only reported: system-manager leaves the host firewall alone. The routing modes
# load their own nftables tables, and the distribution's loose reverse-path filter
# already lets AmneziaWG replies in.
networking.firewall = {
allowedTCPPorts = forward internal.firewall.allowedTCPPorts;
allowedUDPPorts = forward internal.firewall.allowedUDPPorts;
};
})
];
}
+217
View File
@@ -0,0 +1,217 @@
# Renders the core's systemd-shaped units into a user manager's INI sections
# ({ Unit, Service, Install }), with what only NixOS's unit options provide spelled out:
# the directories systemd would create and the PATH NixOS would set. runtimeDir and
# stateDir are the bases of RuntimeDirectory= and StateDirectory= (specifiers allowed);
# hostPath ends every PATH, for the host's own setuid binaries.
{
lib,
pkgs,
runtimeDir,
stateDir,
hostPath ? null,
}:
let
# The user manager has none of the system targets; the default target stands in for
# multi-user.target.
systemTargets = [
"network.target"
"network-online.target"
"nss-lookup.target"
"sysinit.target"
];
userTargets = {
"multi-user.target" = "default.target";
};
toUserUnits =
units: lib.unique (map (unit: userTargets.${unit} or unit) (lib.subtractLists systemTargets units));
# Identity, capabilities and sandboxing: a user manager can apply them only partly
# (and ProtectHome would hide the state directory), and the core sets none of them
# for a rootless host itself.
systemOnlyKeys = [
"User"
"Group"
"DynamicUser"
"SupplementaryGroups"
"AmbientCapabilities"
"CapabilityBoundingSet"
"PrivateTmp"
"PrivateDevices"
"ProtectSystem"
"ProtectHome"
"ProtectClock"
"ProtectHostname"
"ProtectKernelModules"
"ProtectKernelLogs"
"ProtectKernelTunables"
"ProtectControlGroups"
"RestrictSUIDSGID"
"RestrictRealtime"
"LockPersonality"
"ReadWritePaths"
"ReadOnlyPaths"
# Rendered below against runtimeDir and stateDir: a user manager resolves them
# against XDG directories, which need not be where the core looks.
"RuntimeDirectory"
"RuntimeDirectoryMode"
"StateDirectory"
"StateDirectoryMode"
];
# home-manager takes plain values only.
iniValue =
value:
if lib.isList value then
map iniValue value
else if lib.isBool value || lib.isInt value then
value
else
toString value;
iniSection = section: lib.mapAttrs (_: iniValue) (lib.filterAttrs (_: v: v != null) section);
# As NixOS's service `path` default.
defaultPath = with pkgs; [
coreutils
findutils
gnugrep
gnused
systemd
];
# As NixOS: "@" is not allowed in a store path name.
jobScript =
name: text: pkgs.writeShellScript (lib.replaceStrings [ "@" ] [ "_" ] name) "set -e\n${text}";
dirsScript = pkgs.writeShellScript "proxy-suite-dirs" ''
while (( $# )); do
${pkgs.coreutils}/bin/install -d -m "$1" -- "$2"
shift 2
done
'';
removeDirsScript = pkgs.writeShellScript "proxy-suite-remove-dirs" ''
${pkgs.coreutils}/bin/rm -rf -- "$@"
'';
directories =
serviceConfig: key: base:
map (dir: {
path = "${base}/${dir}";
mode = serviceConfig."${key}Mode" or "0755";
}) (lib.concatMap (lib.splitString " ") (lib.toList (serviceConfig.${key} or [ ])));
unitSection =
unit:
iniSection (
{
Description = unit.description;
}
// lib.filterAttrs (_: v: v != [ ]) {
After = toUserUnits unit.after;
Before = toUserUnits unit.before;
Wants = toUserUnits unit.wants;
Requires = toUserUnits unit.requires;
BindsTo = toUserUnits unit.bindsTo;
PartOf = toUserUnits unit.partOf;
Conflicts = toUserUnits unit.conflicts;
}
// lib.optionalAttrs (unit.startLimitIntervalSec != null) {
StartLimitIntervalSec = unit.startLimitIntervalSec;
}
// unit.unitConfig
);
installSection =
unit:
lib.filterAttrs (_: v: v != [ ]) {
WantedBy = toUserUnits unit.wantedBy;
RequiredBy = toUserUnits unit.requiredBy;
};
withInstall =
unit: attrs:
attrs
// lib.optionalAttrs (installSection unit != { }) {
Install = installSection unit;
};
toService =
name: unit:
let
sc = unit.serviceConfig;
runtimeDirs = directories sc "RuntimeDirectory" runtimeDir;
stateDirs = directories sc "StateDirectory" stateDir;
dirs = runtimeDirs ++ stateDirs;
joinPaths = ds: lib.concatMapStringsSep ":" (d: d.path) ds;
# Paths go on the command line, where systemd expands specifiers such as %t.
commandLine =
script: args: lib.concatStringsSep " " ([ "${script}" ] ++ map (arg: ''"${arg}"'') args);
makeDirs = commandLine dirsScript (
lib.concatMap (d: [
d.mode
d.path
]) dirs
);
removeRuntimeDirs = commandLine removeDirsScript (map (d: d.path) runtimeDirs);
path = unit.path ++ defaultPath;
environment = {
PATH = lib.concatStringsSep ":" (
[
(lib.makeBinPath path)
(lib.makeSearchPathOutput "bin" "sbin" path)
]
++ lib.optional (hostPath != null) hostPath
);
}
// lib.optionalAttrs (runtimeDirs != [ ]) { RUNTIME_DIRECTORY = joinPaths runtimeDirs; }
// lib.optionalAttrs (stateDirs != [ ]) { STATE_DIRECTORY = joinPaths stateDirs; }
// lib.filterAttrs (_: v: v != null) unit.environment;
optionalScript = suffix: text: lib.optional (text != "") (jobScript "${name}-${suffix}" text);
in
withInstall unit {
Unit = unitSection unit;
Service = iniSection (
builtins.removeAttrs sc systemOnlyKeys
// lib.optionalAttrs (sc ? WorkingDirectory && !lib.hasPrefix "-" sc.WorkingDirectory) {
# Created by the first ExecStartPre, which already runs in it.
WorkingDirectory = "-${sc.WorkingDirectory}";
}
// lib.filterAttrs (_: v: v != [ ]) {
Environment =
lib.mapAttrsToList (n: v: builtins.toJSON "${n}=${toString v}") environment
++ lib.toList (sc.Environment or [ ]);
ExecStartPre =
lib.optional (dirs != [ ]) makeDirs
++ optionalScript "pre-start" unit.preStart
++ lib.toList (sc.ExecStartPre or [ ]);
ExecStart = optionalScript "start" unit.script ++ lib.toList (sc.ExecStart or [ ]);
ExecStartPost = optionalScript "post-start" unit.postStart ++ lib.toList (sc.ExecStartPost or [ ]);
ExecStop = optionalScript "pre-stop" unit.preStop ++ lib.toList (sc.ExecStop or [ ]);
ExecStopPost =
optionalScript "post-stop" unit.postStop
++ lib.toList (sc.ExecStopPost or [ ])
++ lib.optional (runtimeDirs != [ ]) removeRuntimeDirs;
}
);
};
toTimer =
_: unit:
withInstall unit {
Unit = unitSection unit;
Timer = iniSection unit.timerConfig;
};
toPath =
_: unit:
withInstall unit {
Unit = unitSection unit;
Path = iniSection unit.pathConfig;
};
in
{
inherit toService toTimer toPath;
}