Replace k3s clash with declarative host mihomo service (flakes-k0sx)
Replace the clash-in-k3s deployment with a declarative services.mihomo host
service, and make the proxy environment for nix-daemon / k3s / containerd
static Nix config instead of imperative systemd drop-ins.
Prerequisite
[[flakes-dw38]] restructures the lan mixins into per-site lan/{102,401,708}
and creates mixins/nixos/cn/, which is where this bean’s proxy-env.nix goes.
Until that lands there is no mixin that covers every CN host.
g1 is confirmed to be a clash host (site 708), so the autowired pack is the
right shape — every host wants the service.
Problems being fixed
- Circular dependency. clash runs as a k3s Deployment, so
k3sandcontainerdneed the proxy in order to pull the image that provides the proxy. Every sync script works around this by hand. - Undeclared state. The
clashDeployment, its NodePort Service and theclash-configConfigMap, plus theyacdDeployment/Service/Ingress, were applied imperatively (152 days ago) and exist nowhere in this repo. - Six imperative scripts in
packs/home/host/common/scripts/nixos/proxy/(sync-/reset-/show-proxy_{nix-daemon,k3s,containerd}) write/run/systemd/system/<svc>.service.d/override.conffrom whatever is in the current shell, thendaemon-reloadand restart the service. Living in/run, they evaporate on reboot. - The ingress was the only reason for k3s, and its HTTPS half is unusable:
yacdserved over TLS atclash-ui.pc.yjpark.orgcannot reach clash’s controller over plain HTTP (mixed content), so only the port-80 route works.
The insight that unblocks it
services.mihomo has a webui option and metacubexd is packaged in
nixpkgs (1.244.2). mihomo serves the dashboard itself from the
external-controller port (-ext-ui), i.e. same origin as the API. That removes
the mixed-content problem and the need for any ingress — which was the only
thing keeping clash in k3s.
yacd is not in nixpkgs, so the dashboard changes to metacubexd.
Verified facts
- Live clash is
docker.io/metacubex/mihomo:latestwith config from theclash-configConfigMap — so the engine is already mihomo; this is a packaging change, not an engine change. - That config is only 46 lines and uses
proxy-providers, so the sole secret is the subscription URL. Current keys:socks-port: 1101,port: 1102,allow-lan: true,external-controller: 0.0.0.0:1109,proxy-providers,proxy-groups,rules. sops-nixin this flake supportssops.templates.<name>.content,sops.placeholder.<secret>andrestartUnits— so a Nix-authored config with the subscription URL injected at activation is possible without a wrapper script.- The
services.mihomounit runs-d /var/lib/private/mihomounderDynamicUser+StateDirectory, so relativeproxy-providerspaths persist across restarts in the state dir. curl8.18 does honour CIDR notation inNO_PROXY(tested against a dead proxy, with a non-matching control that correctly failed), so CIDRs are safe to use in thenix-daemonno_proxylist.- Reachability of the NodePort today depends on
mixins/nixos/ext4/k3s.ext4.nixopening the entire 30000-32767 range to the firewalldpubliczone. Once nothing needs a NodePort from outside, that can be narrowed (separate concern).
Decisions taken
- Ports 21100 / 21101 / 21102 / 21109 (mixed / socks5 / http / controller).
clash-vergestays exactly as it is on 1100-1109 — no collision, no change toset-proxy-verge, and the new service can run alongside it. - Nix-generated config + SOPS subscription URL via
sops.templates, rather than lifting the whole ConfigMap into one opaque encrypted blob. The config is small enough that rules and proxy-groups become reviewable. - No API secret on the controller. 21109 is only reachable over LAN and ZeroTier, which is a personal VPN, so the current no-auth behaviour is kept.
- A pack, not a mixin. Most hosts run clash, so it goes in
packs/nixos/host/clash/and is autowired into all five hosts. All of them already import sops-nix, and every host age key is in both.sops.yamlcreation rules, so one shared subscription secret decrypts everywhere with no per-host work. Precedent:packs/nixos/host/clash-verge.nixis already a pack. - Proxy env lives in
mixins/nixos/cn/, not in the pack and not underlan/— it belongs to “this host is behind the CN firewall”, which is orthogonal to both “runs clash” and “is on a LAN”.g1is on no LAN, so anything underlan/*could never reach it. The newcn/mixin comes from [[flakes-dw38]]. - k3s stays for now. After this lands it hosts only minio — tracked separately.
Spec
1. New: packs/nixos/host/clash/default.nix
Autowired into every host. services.mihomo is a singleton option, but the only
other user is mixins/nixos/services/egress-proxy.nix, which applies inside the
onecli container — a different NixOS configuration, so there is no collision.
services.mihomo = {
enable = true;
configFile = config.sops.templates."clash.yaml".path;
webui = pkgs.metacubexd; # served at http://<host>:21109/ui/
};
sops.secrets."clash-sub-url" = { sopsFile = ./secrets/clash.txt; format = "binary"; };
sops.templates."clash.yaml" = {
restartUnits = [ "mihomo.service" ];
content = ''
mixed-port: 21100
socks-port: 21101
port: 21102
allow-lan: true
external-controller: 0.0.0.0:21109
proxy-providers:
main:
type: http
url: ${config.sops.placeholder."clash-sub-url"}
path: ./providers/main.yaml
interval: 86400
health-check: { enable: true, interval: 600, url: ... }
proxy-groups: ... # ported from the live ConfigMap
rules: ... # ported from the live ConfigMap
'';
};
- No controller
secret— see decisions above. - firewalld: a
clashservice covering 21100/21101/21102/21109, added to thepubliczone (mirroringpacks/nixos/host/clash-verge.nix) and to theincuszone so containers can reach it.
2. New: mixins/nixos/cn/proxy-env.nix
Replaces all six sync/reset scripts. Lands in the cn/ mixin created by
[[flakes-dw38]], which every CN host imports including g1 (which is on no
LAN).
let
proxy = "http://127.0.0.1:21102";
noProxy = lib.concatStringsSep "," [
"localhost" "127.0.0.1" "::1"
"mirrors.tuna.tsinghua.edu.cn" "cache.nixos.org"
"10.0.0.0/8" "10.42.0.0/16" "10.43.0.0/16" "10.100.0.0/24"
"172.22.0.0/16" ".yjpark.org" ".incus"
];
in {
systemd.services.nix-daemon.environment = {
http_proxy = proxy; https_proxy = proxy; no_proxy = noProxy;
};
}
- Same for
k3sandcontainerd, guarded bylib.mkIf config.services.k3s.enable. - Add
after = [ "mihomo.service" ]tok3s/containerd— now safe, since mihomo is a plain unit with nothing to pull. nix-daemonneeds no ordering: it reads the env at start but only uses it lazily at fetch time.- Keep
10.0.0.0/8etc. inno_proxy— confirmed curl honours CIDRs.
3. Modify mixins/nixos/services/egress-proxy.nix
proxyPort = 31102 → 21102, and update the comment: it is no longer a k3s
NodePort but a host service port.
4. Modify packs/nixos/host/incus.nix
The incus-zone firewall port 31102 → 21102.
5. Modify packs/home/common/programs/fish/aliases.nix
Low priority — these are legacy and barely used. Since every host will run clash on the same port, most of them collapse:
set-proxy-trojan31102 → 21102 (consider renaming toset-proxy-clash)set-proxy-edger→ 21102;set-proxy-edger_lanis doubly stale (it points at10.0.1.2, and edger is now10.0.4.2) so deleting it beats fixing itset-proxy-verge(1102) untouched, since clash-verge is unchanged- Worth considering deleting the per-host variants outright rather than renumbering them.
6. Delete packs/home/host/common/scripts/nixos/proxy/
All nine bash scripts. The directory’s default.nix autowires everything in it
into ~/.local/bin/nixos/, so removing the whole directory is the clean
removal.
7. Decommission the k3s objects
Imperative, after the host service is proven:
kubectl -n services delete deploy/clash svc/clash cm/clash-config deploy/yacd svc/yacd ingress/yacd
Migration order
Getting this wrong means losing internet access on a CN-side host, so sequence matters:
- Extract the subscription URL (and pick an API secret) out of the live
clash-configConfigMap and intosecrets/clash.txt. - Land the host mihomo pack and switch pc first. Verify
curl -x http://127.0.0.1:21102 https://example.comand that the dashboard loads athttp://pc:21109/ui/— with the k3s clash still running, so there is a fallback. Only then switch edger. - Land the declarative proxy env; confirm
nix-daemonstill substitutes fast (i.e.no_proxyis actually bypassing the TUNA mirror). - Flip
egress-proxy.nix,incus.nixand the fish aliases to 21102. - Only then delete the k3s clash/yacd objects and the sync scripts.
Both pc and edger are k3s clash hosts
Confirmed: edger runs clash in k3s as well, so both hosts get the same migration
and the same decommission step. The service is an autowired pack, so a single
nixos-rebuild on each host picks it up and the k3s teardown is identical.
Per-host unknowns to check while implementing:
- whether edger’s clash Deployment/Service uses the same ports and the same
clash-configConfigMap shape as pc’s - whether edger also runs a
yacdDeployment + Ingress to drop - whether edger’s k3s hosts anything else (pc’s only other workload is minio, tracked in [[flakes-jspq]])
Corrections to the original spec
Two things in this bean’s spec were wrong, found by reading the live ConfigMap:
- There are two subscription providers,
shadowsocksandokcloud, not one. Each has its own URL, so there are two secrets. Theirhealth-checkURLs are bothhttp://www.gstatic.com/generate_204— not secret, so they stay in the Nix source. - The rules do use
GEOIP,CN. The spec said to keep the config free of GEOIP/GEOSITE rules, because matching them makes mihomo download geodata which it cannot do before the proxy works. The constraint was real but the conclusion was not: the rule has to stay, so the geodata ships from the store instead.
Geodata, and the bootstrap problem it was hiding
The k3s pod’s working directory held geoip.dat (19M), geoip.metadb (9M) and
geosite.dat (4M), all downloaded — into an ephemeral filesystem with no
PVC, so a pod restart re-fetched ~32M through the very proxy it was starting up
to provide.
GEOIP,CN is the only geo rule, so v2ray-geoip’s
geoip-only-cn-private.dat subset suffices at 260K, against 23M for the
full geoip.dat or 8.1M for a dbip mmdb. Installed from the store by an
ExecStartPre, with geo-auto-update: false, so nothing is fetched at runtime
and the data tracks nixpkgs.
Verified against mihomo 1.19.23: Load GeoIP rule: cn →
Finished initial GeoIP rule cn => DIRECT, records: 16482, no download
attempted. Routing then checked both ways through mihomo’s HTTP proxy —
www.baidu.com (CN) returned 200 via DIRECT, example.com matched MATCH and
went to the upstream proxy.
Summary of Changes
packs/nixos/host/clash/default.nix (new)
Autowired into every host.
services.mihomoon 21100 (mixed) / 21101 (socks) / 21102 (http) / 21109 (controller), leaving clash-verge’s 1100-1109 untouched.webui = pkgs.metacubexd— dashboard served from the controller port, same origin as the API, so no ingress and no mixed-content problem. metacubexd shipsindex.htmlat its package root so the path works as-is. (yacdis not in nixpkgs.)- Config rendered via
sops.templates."clash.yaml"with the provider URLs fromsops.placeholder, andrestartUnits = [ "mihomo.service" ]. Providers, proxy-groups and rules are generated from oneprovidersattrset and one rules list. - Rules carried over verbatim, including the absence of
no-resolveon the IP-CIDR rules, so matching behaviour is unchanged. - Exposes read-only
clash.httpPort/clash.proxyUrlso host-side consumers do not repeat the port number. - firewalld: a
clashservice (all four ports) in thepubliczone, plus only 21102 in theincuszone, so containers get the proxy and nothing else.
packs/nixos/host/clash/secrets/clash.yaml (new, SOPS)
The two provider URLs, extracted from the live ConfigMap, encrypted to all six host age keys. Decrypt round-trip checked.
mixins/nixos/cn/proxy-env.nix (new)
http_proxy/https_proxy/all_proxy/no_proxy on nix-daemon, and on k3s
and containerd behind lib.mkIf on their enable flags, the latter two ordered
after mihomo.service. Lowercase names only: curl reads those, Nix propagates
exactly those into fixed-output derivation builders via impureEnvVars, and Go
falls back to lowercase. NIX_CURL_FLAGS dropped — modern Nix ignores it.
no_proxy keeps both substituters direct. Note containerd is not a separate
unit on pc (virtualisation.containerd.enable = false; k3s embeds its own), so
that branch is inert there — the old sync-proxy_containerd script was
targeting something that no longer exists.
Other
mixins/nixos/services/egress-proxy.nix:proxyPort31102 → 21102, with a note on why it stays hardcoded rather than readingconfig.clash.httpPort(the container’s configuration does not import the host pack).packs/nixos/host/incus.nix: the 31102 hole is reverted — the clash pack owns that rule now, so the port number lives in one place.aliases.nix:set-proxy-trojan→set-proxy-clashon 21102, andset-proxy-edgerusesedger.yjpark.zerotierinstead of a raw IP.- Deleted
packs/home/host/common/scripts/nixos/proxy/(nine scripts).
Verification
- All five host configs plus the
oneclicontainer dry-run build. - The rendered config passes
mihomo -twith placeholders substituted, including the GeoIP load. - The
ExecStartPrewas checked against the real sandbox viasystemd-runwithDynamicUser=yes,StateDirectory=,ProtectSystem=strictandPrivateUsers=yes— the file lands in the state directory. onecli’s generated config points at10.100.0.1:21102.- firewalld:
clashinpublic;incuszone ports are 21102 plus the pre-existing 5354 pair.
Not verified, because it needs a switch: that mihomo actually starts, fetches the subscriptions, and serves the dashboard.
Migration hazard: stale /run overrides
/run/systemd/system/nix-daemon.service.d/override.conf exists on pc right
now, written by the old sync-proxy_nix-daemon, pointing at localhost:31102.
/run drop-ins outrank /etc ones, so it will shadow the new declarative
environment until removed or the host reboots — and it names a port that stops
existing once the k3s clash is deleted.
Clear it during the switch, before deleting the k3s objects:
sudo rm -rf /run/systemd/system/{nix-daemon,k3s,containerd}.service.d
sudo systemctl daemon-reload
sudo systemctl restart nix-daemon
Then check systemctl cat nix-daemon | grep proxy shows only 21102.
reset-proxy_nix-daemon used to do this and is being deleted, so the step must
happen before or during the switch.
Switched pc — verification results
Switched on 2026-10-06 and verified in place.
Working:
| check | result |
|---|---|
| mihomo.service | active, all four ports listening (21100/21101/21102/21109) |
| geodata | geoip.dat 262965 bytes installed from the store by ExecStartPre |
| subscriptions | both shadowsocks.yaml and okcloud.yaml fetched and persisted in the state directory |
| sops | pc host key imported, both secrets and the rendered clash.yaml applied |
| proxy | example.com 200, github.com 200, api.anthropic.com 403 (auth, so reachable) |
| GEOIP,CN | www.baidu.com 200 via DIRECT |
| dashboard | http://127.0.0.1:21109/ui/ returns 200 |
| firewall | lan sources narrowed to 10.0.1.0/24; clash in public; incus ports 5354/tcp 21102/tcp 5354/udp |
| nix-daemon | declarative env active after clearing the stale /run drop-in |
| substituters stay direct | cache.nixos.org download succeeded with no corresponding entry in mihomo’s log |
| FOD proxy propagation | proven: a fixed-output derivation whose hash only matches the string http://127.0.0.1:21102 built successfully, so the daemon’s env does reach FOD builders |
| k3s fallback | the k3s clash pod survived the k3s restart (same pod, no new restart count), so the old proxy remained available throughout |
The stale /run/systemd/system/nix-daemon.service.d/override.conf was removed
as planned; nix-daemon now shows only the 21102 environment.
Two issues found while verifying
1. firewalld reload was broken — fixed
The switch reported Failed to reload firewalld.service, and the new firewall
config did not apply: the lan zone still showed 10.0.0.0/16 and clash was
absent from the public zone.
Cause: the unit ends up with two ExecReload= lines — firewalld’s own
packaged /bin/kill -HUP $MAINPID, which does not exist on NixOS, plus the
correct coreutils path the nixpkgs module adds as a drop-in. systemd appends
Exec* directives rather than replacing them, so the broken one runs first and
fails the whole reload with 203/EXEC.
This is an upstream nixpkgs bug: the module sets
serviceConfig.ExecReload to a bare string instead of a list beginning with
"". It means no firewalld config change in this repo has ever applied on
switch without a manual systemctl restart firewalld — including the
reloadTriggers wiring already present in
packs/nixos/common/settings/firewalld.nix, which was added for exactly this
symptom and never worked.
Fixed locally in that file with ExecReload = lib.mkForce [ "" "<coreutils>/bin/kill -HUP $MAINPID" ].
Verified: systemctl reload firewalld now logs Reloaded firewalld and exits 0.
2. Provider fetch races the proxy group at startup
mihomo’s first shadowsocks fetch failed with a TLS handshake timeout because
MATCH,Shadowsocks routed the subscription request through a group whose
provider was not loaded yet (logged as Shadowsocks[COMPATIBLE]). It recovered
on retry, but startup is non-deterministic as a result.
Both subscription hosts are reachable directly from CN — checked before
switching, 404 and 403 on the bare paths, i.e. TLS completes. So explicit
DIRECT rules for the two subscription domains ahead of MATCH would make
startup deterministic. Worth doing, tracked as a follow-up task below.
Incidental
cache.numtide.com — newly enabled for llm-agents — does go through the proxy,
since it is not in no_proxy. Probably what is wanted for a non-CN cache, but
noting it in case it should be direct.
Decision: no DIRECT rules for the subscription domains (task dropped)
The earlier suggestion to add DOMAIN-SUFFIX,<subscription host>,DIRECT ahead
of MATCH was wrong, and the objection to it is correct: subscription refreshes
sometimes need the proxy, and a DIRECT rule would permanently remove that.
The current rules already do the right thing in both directions:
- Cold start, no cached provider list. The group holds no proxies yet, so
mihomo falls back to its
Compatibleadapter — what the log showed asShadowsocks[COMPATIBLE]— which dials direct. That is the only thing it could do; there is no proxy available to use. - Every later refresh. Providers are loaded, so the fetch matches
MATCH,Shadowsocksand goes through the proxy. This is exactly the case worth protecting, and a DIRECT rule would break it.
The “startup race” also turned out not to matter. Verified by restarting
mihomo: the proxy served traffic 0.24s after restart, with no provider
fetch and no error, because shadowsocks.yaml and okcloud.yaml now persist
in the state directory. The blocking first fetch only happens on a genuinely
empty state directory — first start after deploy — and even then it retried and
succeeded.
That persistence is itself an improvement over the pod, which had no PVC and so took the cold path on every single restart.
So the only remaining failure mode is “first ever start and the subscription host is blocked directly”, where a DIRECT rule would make things worse rather than better. No change.
Dashboard access
Served by mihomo itself from the controller port, same origin as the API, so it needs no ingress and has no mixed-content problem:
http://pc:21109/ui/from site 102http://pc.yjpark.zerotier:21109/ui/from any site
Verified 200 from loopback, the LAN address and the ZeroTier address. The
clash firewalld service is in the public zone, which covers both eno1 and
ZeroTier. No token is needed — the controller has no secret, as decided.
Node selection needs attention in the UI
The controller reports Shadowsocks with 27 options and OKCloud with 35, but
both selectors default to their provider’s first entry, which in both cases
is an information label rather than a server:
Shadowsocks→有效期2026-11-13, 剩余 81.15 GB— this one does route; traffic through 21102 works.OKCloud→官网:okyun01.com 如果没有节点请更新软件— almost certainly not a routable server. Harmless today becauseMATCHpoints atShadowsocks, but selectingOKCloudwould fail until a real node is picked.
Selections persist in cache.db in the state directory, so choosing nodes in
the dashboard survives restarts.
Tasks
- Inspect edger’s k3s — moot: k3s removed entirely (flakes-itu2); edger ran only cert-manager + clash + yacd
- Extract the subscription URLs (two providers) into
packs/nixos/host/clash/secrets/clash.yaml(SOPS) - Port
proxy-groupsandrulesfrom the ConfigMap into the Nix-authored config - Create
packs/nixos/host/clash/default.nix(services.mihomo + sops.templates + firewalld, ports 21100/21101/21102/21109, metacubexd webui, no controller secret) - Ship GeoIP data from the store instead of letting mihomo download it
- Switch pc, then verify the proxy and the dashboard work while the k3s clash is still running
- Clear the stale
/run/systemd/system/*.service.ddrop-ins (see Migration hazard) - Create
mixins/nixos/cn/proxy-env.nixfor nix-daemon / k3s / containerd, withafter = mihomo.serviceon the latter two - Verify
no_proxykeeps substituter traffic direct - Fix the firewalld ExecReload bug that stopped firewall changes applying on switch
- Decide on DIRECT rules for the subscription domains — dropped, see Decision below
- Flip
egress-proxy.nixproxyPort to 21102; theincus.nixhole is reverted and now owned by the clash pack - Update the
set-proxy-*fish aliases - Delete
packs/home/host/common/scripts/nixos/proxy/ - Delete the k3s
clashandyacdobjects — done by removing k3s from all hosts (flakes-itu2) - Roll out to the remaining hosts (a13, g1, p2) and confirm each one’s proxy works
- Re-verify the onecli → clash egress chain after the port flip (see [[flakes-i9ao]])
Coupling with flakes-i9ao
flakes-i9ao just landed the onecli egress chain pointing at 10.100.0.1:31102
and still has unverified in-situ checks. Either verify it on edger first and
then renumber, or do both in one deploy — but do not renumber while the original
chain is still unproven.
Notes (2026-10-07)
- a13 and p2: host mihomo active, nix-daemon proxied via 127.0.0.1:21102 (checked during flakes-itu2). g1 still unverified (offline).