Files
nixos/modules/containers/3x-ui.nix
T
oqyude 1e7da18bd4
nixos flake checks / invariant-checks (push) Successful in 2m11s
test-runner / smoke (push) Successful in 1s
3x-ui v3.12.0, nixpkgs-master удалён, opencode 2.4.1 на sapphira
3x-ui (ADR-0013): пин v3.11.0 -> v3.12.0 (2026-11-29), бандл Xray-core
26.11.9. Блокеры апстрима проверены и не применимы: нешифрованных
VLESS/Trojan аутбаундов в CGNAT/198.18.0.0/15 нет, секций geodata нет.
REALITY-условия (fp=chrome/firefox/safari, minClientVer=1.0.0) те же.
Развёрнуто: otreca gen 96, sapphira gen 882; панель 200, ядро 26.11.9,
порты сохранены, warp-masque не тронут. Бэкапы db/ сняты до старта.

nixpkgs-master: вход удалён из flake.nix (lock перегенерирован), brave
снова из дефолтного nixpkgs (1.100.59), nginx = pkgs.nginxMainline
(1.31.10, CVE-2026-123007 закрыт), мёртвые ссылки в nextcloud/onlyoffice/
opencode вычищены. Все 6 конфигураций эвалируются.

opencode: на sapphira 2.4.1 — собран в WSL и замыкание скопировано в её
store до активации (слабая машина не компилирует bun-пакет).

Плюс nixfmt-правка modules/server/engipy-backend.nix (дрейф форматтера).
2026-12-02 02:51:22 +03:00

211 lines
11 KiB
Nix
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
{
config,
lib,
pkgs,
xlib,
...
}:
let
panel = "${xlib.dirs.services-nodes-folder}/${xlib.device.hostname}/3x-ui";
# Domain whose Let's Encrypt cert (at /var/lib/acme/<domain>/) gets mounted
# read-only into the 3x-ui container so the panel can terminate TLS itself.
# Null when 3x-ui serves plain HTTP and TLS is terminated by an upstream
# nginx.
certDomain = config.host."3x-ui".certDomain;
certMounts =
if certDomain == null then
[ ]
else
# LE cert mounted read-only so 3x-ui can terminate TLS itself.
# The 3x-ui settings table must point webCertFile / webKeyFile at
# /root/cert/fullchain.pem and /root/cert/key.pem.
map (f: "/var/lib/acme/${certDomain}/${f}:/root/cert/${f}:ro") [
"fullchain.pem"
"key.pem"
];
basePorts = [
# Local-only upstreams for the 3x-ui panel and subscription endpoint.
# The direct Xray inbound remains publicly reachable on 8443.
"127.0.0.1:2049:2049/tcp"
"127.0.0.1:2096:2096/tcp"
"0.0.0.0:8443:8443/tcp"
# Local proxy (socks5 + http) into the node outbound
# `telegram-edge-of-truth`: the panel's inbound `host-egress` listens on
# this port inside the container. Published on the host loopback only, so
# ordinary host processes can use it (`curl -x socks5h://127.0.0.1:10808`)
# without exposing it to the LAN.
"127.0.0.1:10808:10808/tcp"
# Public forward-proxy of the Xray inbound `bridge-http` (protocol http,
# auth=password, one account): the bridge to this host for an external
# device (Windows: Параметры → Сеть → Прокси → Вручную). Inside the
# container it listens on 10809, outside it is published as 3128.
# Its outbound is DIRECT (freedom), not `telegram-edge-of-truth`.
#
# ВНИМАНИЕ: порты контейнера применяются только при СОЗДАНИИ контейнера,
# поэтому включение этого маппинга пересоздаёт контейнер и рвёт ВСЕ
# соединения Xray — включая `host-egress` (Telegram) — на секунды.
#
# Файрвол на sapphira выключен намеренно (`networking.firewall.enable =
# false`, граница — роутер), поэтому наружу порт открывается пробросом
# TCP 3128 → sapphira в настройках роутера (как 443/80/8443/22000).
"0.0.0.0:3128:10809/tcp"
];
# VDS-only: nginx stream forwards host:443 → 127.0.0.1:15380 →
# container:443, so Xray sees its REALITY inbound on port 443.
realityPorts = lib.optional config.host."3x-ui".reality443Forwarding "127.0.0.1:15380:443/tcp";
in
{
# `host."3x-ui"` options are declared in modules/options.nix: they are set
# by modules/server and modules/vds, so this module cannot be the only place
# that knows they exist.
config = {
virtualisation = {
podman = {
enable = true;
autoPrune = {
enable = true;
flags = [ "--all" ];
};
dockerCompat = true;
};
oci-containers = {
backend = "podman";
containers."3xui_app" = {
# Тег образа ЗАПИНЕН (2026-10-20, R1.5). До этого был `:latest`,
# и это был вектор тихого дрейфа: 2026-10-14 вышел 3x-ui v3.10.x с
# ядром Xray **26.10.10** (26.7.x → 26.10.x мимо рук), а ядро ≥ 26.9.8
# требует в REALITY ClientHello key share `X25519MLKEM768` (см. R1.16).
# Итог: все клиентские ссылки перестали работать молча — TCP есть,
# TLS «есть», трафика нет. Пришлось чинить fingerprint и minClientVer
# на живых хостах. Панель обновлять — только вместе с записью в
# `.agent/decisions/` или `.agent/decisions/notes/` (R1.5).
#
# 2026-10-25: `v3.10.2` → `v3.11.0` (ADR-0007). Причины: (1) апстрим
# отозвал бандл 26.10.10 — release notes v3.11.0 прямо говорят, что
# «the pulled v26.10.10 binary pins are replaced», то есть старый пин
# тянул отозванное ядро; (2) владелец хочет быть на свежем стабильном
# релизе. Новый бандл — Xray-core **26.10.21** (≥ 26.9.8 ⇒ REALITY
# по-прежнему требует `fp` ∈ {chrome,firefox,safari} и
# `minClientVer = 1.0.0`, R1.16). `:latest` запрещён так же, как и
# раньше: только явный тег, иначе снова тихий дрейф ядра.
#
# 2026-12-02: `v3.11.0` → `v3.12.0` (ADR-0013). Бандл — Xray-core
# **26.11.9**: та же ветка ≥ 26.9.8 ⇒ REALITY по-прежнему требует
# `fp` ∈ {chrome,firefox,safari} и `minClientVer = 1.0.0` (R1.16).
# Апстрим объявил два блокера на старте нового ядра; оба проверены и
# не применимы: (1) нешифрованных VLESS/Trojan аутбаундов в
# 100.64.0.0/10 / 198.18.0.0/15 в шаблонах нет (только freedom,
# blackhole и masque), (2) секции geodata в шаблонах нет вовсе.
# Первый старт **необратимо** мигрирует БД панели и разлогинивает
# админов ⇒ бэкап `db/` снят до старта на обоих хостах (ADR-0013).
image = "ghcr.io/mhsanaei/3x-ui:v3.12.0";
environment = {
"XRAY_VMESS_AEAD_FORCED" = "false";
"XUI_ENABLE_FAIL2BAN" = "true";
"TZ" = "Europe/Moscow";
};
volumes = [
"${panel}/cert/:/root/cert:rw"
"${panel}/db/:/etc/x-ui:rw"
]
++ certMounts;
log-driver = "journald";
# Every port an inbound listens on has to be published from the
# container, otherwise it is unreachable from outside. Ports 2049,
# 2096 and 8443 are published by `basePorts` above; 443 (VDS only)
# by `realityPorts`. A new inbound on any other port means
# extending one of those lists and rebuilding.
ports = basePorts ++ realityPorts;
};
};
};
systemd = {
services = {
"podman-3xui_app" = {
# Guard goes to `unitConfig` → `[Unit]`: `ConditionPathIsMountPoint`
# is a unit-level directive and is ignored by systemd in `[Service]`
# (T4/R1.2).
unitConfig = xlib.helpers.mkStorageGuard xlib;
serviceConfig = {
Restart = lib.mkOverride 90 "always";
};
partOf = [ "podman-compose-3x-ui-root.target" ];
wantedBy = [ "podman-compose-3x-ui-root.target" ];
};
# `webDomain` — persisted-настройка панели (таблица `settings` в
# x-ui.db), а не значение из Nix (инвариант 19 / R1.20). При смене
# домена rebuild обновит nginx и ACME, но панель продолжит отвечать
# на старое имя → 403 на каждом запросе. Юнит выполняется ДО старта
# контейнера (пока SQLite никто не держит) и правит БД; панель
# читает настройку при старте.
#
# Триггер осознанно не автоматический: юнит стартует вместе с
# `podman-3xui_app.service`, поэтому миграция =
# nixos-rebuild switch && systemctl restart podman-3xui_app
# (перезапуск из самого юнита дал бы цикл зависимостей).
# На `vds` guard пуст (mkStorageGuard), на sapphira — монтирование
# External, как у самого контейнера.
"3xui-domain-sync" = lib.mkIf (certDomain != null) {
description = "Reconcile the 3x-ui panel webDomain with the domain declared in Nix";
unitConfig = xlib.helpers.mkStorageGuard xlib;
before = [ "podman-3xui_app.service" ];
wantedBy = [ "podman-3xui_app.service" ];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = false;
ExecStart = "${config.modules."3x-ui".domainSync}/bin/3xui-domain-sync";
Environment = [
"PANEL_DB=${panel}/db/x-ui.db"
"PANEL_DOMAIN=${certDomain}"
];
};
};
# Auto-update was removed intentionally: the `podman pull` path on the
# auto-update timer caused the declarative Nix state to diverge from the
# runtime state in 2026-10-04 (see
# .agent/decisions/notes/3x-ui-xray-26.9.md). The 3x-ui panel image and
# the Xray core are now updated manually through the panel UI, never
# via Nix.
};
# 3xui-reconfig.service определён в:
# - modules/server/default.nix (sapphira, панель через x.zeroq.su)
# - modules/vds/default.nix (otrecа, панель через pubray1.zeroq.su)
# Скрипт и обёртка: modules/3x-ui/default.nix — опции
# modules."3x-ui".reconfig (POST restartXrayService) и
# modules."3x-ui".reconfigRunner (читает webBasePath/apiToken из БД
# этого контейнера в рантайме и отдаёт их скрипту через окружение).
# См. R1.18 в .agent/rules/project-rules.md.
# Starts/stops together with all 3x-ui compose resources.
targets."podman-compose-3x-ui-root" = {
unitConfig.Description = "Root target generated by compose2nix.";
wantedBy = [ "multi-user.target" ];
};
tmpfiles.rules = [
(xlib.helpers.mkTmpfile "d" xlib.dirs.services-mnt-folder "0755" "root" "root")
(xlib.helpers.mkTmpfile "d" xlib.dirs.services-nodes-folder "0755" "root" "root")
(xlib.helpers.mkTmpfile "d" "${xlib.dirs.services-nodes-folder}/${xlib.device.hostname}" "0755"
"root"
"root"
)
(xlib.helpers.mkTmpfile "d" panel "0755" "root" "root")
(xlib.helpers.mkTmpfile "d" "${panel}/db" "0755" "root" "root")
(xlib.helpers.mkTmpfile "d" "${panel}/cert" "0755" "root" "root")
# Relabel panel dir for SELinux so containers can access it.
(xlib.helpers.mkTmpfile "Z" panel "0755" "root" "root")
];
};
# Enable container name DNS for all Podman networks.
networking.firewall = {
interfaces =
let
matchAll = if !config.networking.nftables.enable then "podman+" else "podman*";
in
{
"${matchAll}".allowedUDPPorts = [ 53 ];
};
};
};
}