Commit Graph
249 Commits
Author SHA1 Message Date
oqyude 2d1ffa5aef fix(engipy-install): добавить python-multipart==0.0.20
test-runner / smoke (push) Successful in 1s
FastAPI route /api/match использует file: UploadFile = File(...). При
импорте app.routes.match (через 'import app.main') FastAPI вызывает
ensure_multipart_is_installed() и падает с RuntimeError, если
python-multipart не установлен. Добавил в requirements.txt.
2026-10-16 14:03:56 +03:00
oqyude ce4bfd3f0b fix(engipy-install): добавить structlog + pandas + openpyxl и PYTHONPATH
test-runner / smoke (push) Successful in 0s
1. structlog==24.4.0 — app/main.py импортирует его на boot, иначе
   ModuleNotFoundError стартует uvicorn. Аналогично pandas и
   openpyxl — app.matchers и app.routes.match их используют, и
   'import app.main' тянет всю иерархию.

2. PYTHONPATH=${cfg.dataDir} — WorkingDirectory не добавляет cwd в
   sys.path автоматически, uvicorn не находит 'app.main:app' при
   запуске из /var/lib/engipy. PYTHONPATH — это путь, который uvicorn
   ищет при import_from_string.
2026-10-16 13:54:45 +03:00
oqyude 424d918bb9 fix(engipy-install): включить torch в requirements.txt с --extra-index-url pytorch.org/whl/cpu
test-runner / smoke (push) Successful in 0s
Предыдущий подход ставил torch отдельным pip install -r torchReqs
ПОСЛЕ установки sentence-transformers. Но sentence-transformers
(через transformers/torch>=1.11.0) уже резолвил universal-torch
с PyPI при первой установке — это тянуло cuda-toolkit ~3GB.

Исправлено: torch==2.6.0+cpu + --extra-index-url pytorch.org/whl/cpu
включены прямо в requirements.txt. Sentence-transformers увидит
torch==2.6.0+cpu как явное ограничение и возьмёт именно CPU-wheel
(он единственный с +cpu тэгом, PyPI не предлагает).
2026-10-16 13:49:11 +03:00
oqyude c93a70c578 fix(engipy-backend): убрать environment.PATH из engipy.service — тоже конфликт с upstream NixOS systemd environment.
test-runner / smoke (push) Successful in 1s
2026-10-16 13:47:26 +03:00
oqyude b300b07456 fix(engipy-backend): убрать environment.PATH из engipy-install — конфликт с upstream NixOS systemd environment (PATH уже задан). Venv-скрипт работает по абсолютному пути.
test-runner / smoke (push) Successful in 1s
2026-10-16 13:46:29 +03:00
oqyude 716120eb82 fix(engipy-backend): переехать с fetchPypi на pip-venv через ExecStartPre
test-runner / smoke (push) Successful in 1s
pkgs.fetchPypi + python311.withPackages / buildEnv.override не
раскладывают wheels в site-packages — итоговый env содержит только
4 базовых файла python311 (__pycache__, README.txt, sitecustomize.py,
_sysconfigdata__). engipy.service стартует с 'No module named uvicorn'.

Перешёл на прямое pip install в systemd ExecStartPre:
  * engipy-install.service (oneshot) — создаёт /var/lib/engipy/venv,
    pip install -r requirements.txt, pip install torch (--index-url
    pytorch.org/whl/cpu). Маркер .engipy-venv-installed после успеха.
  * engipy.service (simple, requires engipy-install) — uvicorn из
    созданного venv.

Wheel'ы остаются те же (16 штук, ~1.7 GB на диске после распаковки),
но Nix больше не пытается интегрировать их в buildEnv — pip делает
это прямым образом за ~2-3 мин на rydiwo. Никаких часовых компиляций.

torch по-прежнему 2.6.0+cpu с https://download.pytorch.org/whl/cpu
(~250 MB). SBERT-модель 'cointegrated/rubert-tiny2' кэшируется при
первом запросе в cfg.dataDir/.cache/huggingface/ (~50 MB).
2026-10-16 13:45:34 +03:00
oqyude 276d3f4292 fix(engipy-backend): pkgs.fetchPypi + python311.withPackages
test-runner / smoke (push) Successful in 1s
python311.buildEnv уже derivation, не функция (правый attrset, не
lambda), поэтому python311.buildEnv { ... } падает с 'attempt to
call something which is not a function'. Аналогично pkgs.fetchPip
не существует — есть pkgs.fetchPypi (с 'y').

Исправлено:
  * requirements.nix: pkgs.fetchPip → pkgs.fetchPypi
  * engipy-backend.nix default: pkgs.python311.buildEnv →
    pkgs.python311.withPackages (ps: ...)

Сгенерировано в WSL nixos и подтверждено: 'nix-build' успешно
собирает /nix/store/...-python3-3.11.17-env (около 17 symlinks).
2026-10-16 13:38:30 +03:00
oqyude 8b7a6ae49d fix(engipy-frontend): escape ${dataDir} в description (Nix интерполировал)
test-runner / smoke (push) Successful in 1s
В description для option dataDir было ${dataDir} — Nix
внутри ''-строки интерпретирует как переменную, не как литерал.
Поскольку dataDir объявлена самой опцией ниже (mutually-
recursive через cfg.dataDir это и есть сама опция), Nix ругался
'undefined variable dataDir'. Исправлено на `$dataDir/web` в
бэктиках.
2026-10-16 13:34:30 +03:00
oqyude f99f2d057b feat(server): split engipy — frontend на sapphira, backend на rydiwo
test-runner / smoke (push) Successful in 1s
Sapphira (2 cores, 5.6 GB RAM) не вытянет torch/sentence-transformers —
первый nixos-rebuild на ней упал с No space left on device и долгим
копированием 50+ MB ML-deps с узкого cache.nixos.org канала. Разносим
архитектуру:

  * engipy-frontend.nix (sapphira) — только nginx vhost engipy.zeroq.su.
    /api/* → proxyPass на 192.168.1.102:8000 (rydiwo). Статика
    /var/lib/engipy/web на root fs (без bind-mount, External не нужен).
    Authelia forward-auth через wildcard *.zeroq.su → one_factor.

  * engipy-backend.nix (rydiwo) — systemd unit engipy с uvicorn +
    FastAPI + полный ML-стек. bindAddress=0.0.0.0, чтобы sapphira
    могла проксировать по LAN. Sandbox через PrivateTmp/ProtectSystem
    + LD_LIBRARY_PATH для libgomp/openblas (нужно torch CPU-wheel'у).

  * requirements.nix — wheels с PyPI + torch 2.6.0+cpu c
    https://download.pytorch.org/whl/cpu. Все sha256-хэши посчитаны
    в WSL nixos через 'pip download --only-binary=:all: --platform
    manylinux_2_17_x86_64' + 'nix hash path --type sha256'. Никакой
    компиляции — только скачивание wheels на rydiwo (~5-10 мин rebuild).

  * configurations/server.nix — host.engipy-frontend.enable = true +
    backendHost = 192.168.1.102.

  * configurations/mini-laptop.nix — host.engipy-backend.enable = true +
    bindAddress = 0.0.0.0 + logind.lidSwitch = ignore (rydiwo
    используется как headless-сервер, не засыпать при закрытии крышки).

nsot: старый engipy.nix (185 строк) удалён — он делал всё сразу на одном
хосте, что перегружало sapphira. nginx.nix vhost перенесён в
engipy-frontend.nix, чтобы не дублировать.
2026-10-16 13:31:54 +03:00
oqyude 352dca3595 fix(server): warn-on-sphinx-unsupported for python3.11 in engipy
test-runner / smoke (push) Canceled after 0s
engipy webapp использует pkgs.python311.withPackages (fastapi, pydantic,
sentence-transformers, torch). При evaluation Nix встречает
python3.11-sphinx-9.1.0 как транзитивную docs-dep — а она не
поддерживает python 3.11 (broken). sphinx не нужен в runtime, и
реальная БД от него не зависит, поэтому глушим ошибку до warning
через nixpkgs.problems.handlers (см. .agent/rules/project-rules.md
R1 — outputs должны вычисляться).
2026-10-16 03:17:47 +03:00
oqyude 02c49d44c3 fix(server): восстановить users/environment/systemd блоки в engipy.nix
test-runner / smoke (push) Canceled after 0s
При предыдущем правке (4d76315) случайно выпилил users.users,
users.groups, users.users.nginx.extraGroups, environment.systemPackages
из config = lib.mkIf cfg.enable {...} блока. Перезаписал весь файл
с восстановленными блоками и чистой структурой systemd = lib.mkMerge
[ storage.systemd { services.engipy = { ... }; } ].
2026-10-16 03:12:09 +03:00
oqyude 4d7631557e fix(server): merge storage.systemd и services.engipy через lib.mkMerge
test-runner / smoke (push) Canceled after 0s
NixOS ругался «attribute 'systemd' already defined», потому что Nix
видит systemd = storage.systemd и systemd.services.engipy = ... как
два разных присвоения корневому systemd, а не как deep-merge.
lib.mkMerge делает явный merge двух attrsets внутри systemd.
2026-10-16 03:10:50 +03:00
oqyude 6af6c49575 feat(server): add engipy webapp (FastAPI + SBERT) за Authelia
test-runner / smoke (push) Canceled after 0s
engipy.zeroq.su — FastAPI webapp для подбора ГЭСН по ВОР (uvicorn + SBERT).
Дизайн по образцу vtimeline.nix (systemd unit) + vtimeline.zeroq.su vhost:

- modules/server/engipy.nix: новый модуль. systemd-юнит engipy запускает
  uvicorn на 127.0.0.1:8000 (порт через host.engipy.port). Хранилище —
  через xlib.helpers.mkServiceStorage: bind-mount
  /mnt/services/engipy → /var/lib/engipy (mode 0750 engipy:engipy),
  соглашение R1.2 в .agent/rules/project-rules.md. Зависимость
  requires = [ var-lib-engipy.mount ] заменяет нерабочий mkStorageGuard.
  nginx читает /var/lib/engipy/web через users.users.nginx.extraGroups.
  Опции: port, user, pythonPackage, dbFileName, embeddingsStem, model.

- modules/server/default.nix: импорт ./engipy.nix + host.engipy.enable
  с pythonPackage = pkgs.python311.withPackages (fastapi/uvicorn/
  pydantic/sqlalchemy/numpy/sentence-transformers/torch) — список из
  nix/engipy.nix проекта, чтобы backend-стек на сервере совпадал с
  dev-окружением.

- modules/server/nginx.nix: vhost engipy.zeroq.su (forceSSL + ACME).
  /api/ проксирует на 127.0.0.1:8000 (client_max_body_size 50m для
  крупных ВОР-файлов), / отдаёт /var/lib/engipy/web с try_files для
  SPA-fallback. Authelia forward-auth через auth_request /authelia +
  401→302 redirect на authelia.zeroq.su (как у vtimeline.zeroq.su) —
  wildcard *.zeroq.su → one_factor уже покрывает новый vhost.

Первый nixos-rebuild на sapphira собирает torch + sentence-transformers
~30-90 мин (2 ядра); последующие пересборки берут из кэша.
2026-10-16 03:01:15 +03:00
oqyude 52d6b0bde1 feat(pxe-infra): split boot.ipxe (sanboot) from boot-bypass.ipxe (regression baseline)
test-runner / smoke (push) Canceled after 0s
The former single boot.ipxe writeText block in modules/pxe-infra/ipxe.nix has been split into two static scripts under artifacts.root/http/:

  - boot.ipxe        \u2014 production sanboot path. Chains to the
                        alpine-worker raw image; OVMF walks the ESP,
                        systemd-boot reads loader/entries/alpine.conf.
  - boot-bypass.ipxe \u2014 H_fix.1b regression baseline. kernel+initrd
                        path; preserved byte-identical to the pre-split
                        boot.ipxe content (matches the
                        T10-h-fix-1b log shape on rydiwo 2026-10-14).

autoexec.ipxe now selects the chain target via a new option:

  pxe-infra.bootloader.bypassFallback.enable (lib.types.bool, default false)

When true, autoexec.ipxe chains to boot-bypass.ipxe; when false (default),
to boot.ipxe. Both scripts are always staged (no mkIf gate) so the chain
target flips with a config change + rebuild, no redeploy.

In modules/pxe-infra/default.nix a new systemd-tmpfiles L+ rule mirrors
the existing boot.ipxe rule for boot-bypass.ipxe.

This unblocks H_fix.2 (real sanboot + POST end-to-end verification on
rydiwo). The bypass path is the regression baseline \u2014 S4 in
.agent/notes/H_fix.2-scenarios.md validates it still reaches the Alpine
Init shell when the option is flipped.
2026-10-16 00:43:09 +03:00
oqyude 3d4f1f567e fix(nginx): don't forward request body to Authelia auth subrequest
test-runner / smoke (push) Canceled after 0s
Authelia's forward-auth endpoint was handed the original Content-Length
header of the client request but not the body itself, so it blocked
reading bytes that never arrived and finally answered 408. auth_request
cannot classify 408, so nginx reported it to the client as 500 + an HTML
error page, and the frontend surfaced "Server returned non-JSON" on
every upload.

Every bodied POST was affected (JSON upload and zip ingest) while plain
GETs kept working, which is why the page loaded fine but uploads failed.
Payload size was irrelevant: a 60-byte body failed identically to a
300 KB one.

With `proxy_pass_request_body off` and an empty Content-Length, Authelia
authorises on the forwarded headers alone, which is all forward-auth
needs. Applied to both "= /authelia" blocks (vtimeline.zeroq.su and
tty.zeroq.su).

Verified on a reproduction bench mirroring the production vhost: bodied
POSTs went 500 (HTML, 6 s timeout) -> 201 (JSON, ~10 ms).
2026-10-15 17:52:28 +03:00
oqyude dfcd7f5728 feat(essentials): enable programs.nix-ld for generic-linux bun runtime
test-runner / smoke (push) Canceled after 0s
bun в shell PATH (home/modules/herdr-runtime.nix) не помогает — herdr-web-ui
plugin на rydiwo использует собственный runtime manager (path-pattern
~/.local/share/herdr-web-ui/install.<hash>/runtime/bin/bun, типичный bun
runtime installer), а не fallback на PATH. Этот bun динамически слинкован
для generic linux (glibc) и на NixOS без nix-ld stub падает с «NixOS cannot
run dynamically linked executables intended for generic linux environments
out of the box».

Включаю programs.nix-ld глобально (в modules/essentials) с одной зависимостью
stdenv.cc.cc.lib (glibc + libstdc++ + libgcc_s) — этого достаточно для
запуска glibc-based bun. Применяется ко всем NixOS-хостам; на хостах без
generic-linux бинарей overhead минимальный (несколько .so в /lib, плюс
ld-linux.so.2 в /libexec).

Дополнение / подноши: если конкретный плагин потребует ещё (zlib, openssl,
etc.), расширять programs.nix-ld.libraries через ldd-проверку и точечно.

Раньше # nix-ld.enable = true; в этом же файле было закомментировано —
видимо, не дошли руки; теперь разкомментировано с явным почему.
2026-10-15 15:24:21 +03:00
oqyude 9bf9407c9d fix(nginx): drop authelia from herdr.zeroq.su, trust proxy chain
test-runner / smoke (push) Canceled after 0s
The herdr-web-ui vhost was using authelia forward-auth like every
other *.zeroq.su vhost, but the upstream Bun server's sameOrigin
check (server/machine-security.ts:18-46) is not designed for
reverse proxies other than Tailscale serve:

  1. POST /api/auth through the vhost returned 500 because nginx's
     auth_request subrequest returned 401 and error_page 401 =302
     only works for GET. (Fixed by exempting /api/auth and
     /api/devices/pair from authelia — commit 61ad57a.)

  2. The sameOrigin function compares the browser's Origin against
     new URL(request.url).origin. For a proxy_pass to 127.0.0.1:7317
     the URL is http://127.0.0.1:7317/..., which never matches
     https://herdr.zeroq.su. The function does NOT read
     X-Forwarded-Host. Every cross-origin POST returned 403
     invalid_origin. (Fixed by in-place patch on the plugin's
     server/machine-security.ts on sapphira to also trust
     X-Forwarded-Host when X-Forwarded-Proto is also set, and to
     reset expected.port so the comparison matches the browser's
     default-port Origin. The .orig file is saved alongside so
     `cp server/machine-security.ts.orig server/machine-security.ts`
     reverts the change before any `herdr plugin update`.)

  3. NixOS nginx with recommendedProxySettings = true appends an
     include of a file that sets Host, X-Forwarded-Proto,
     X-Forwarded-Host AFTER every location's extraConfig.
     My previous `proxy_set_header X-Forwarded-Host $host;` in
     extraConfig ended up sending the header twice
     ("herdr.zeroq.su, herdr.zeroq.su"), the sameOrigin function
     then sees a comma-joined value, fails to parse it as a host,
     and 403s every cross-origin POST. Removing the explicit
     proxy_set_header lines lets the include's single values
     reach the upstream correctly.

  4. Static assets (manifest.webmanifest, sw.js, favicon.ico,
     /assets/*) used to go through the authelia-gated / location,
     which 302-redirected them to authelia.zeroq.su, breaking the
     PWA's manifest load and the service worker. Exempted via a
     regex location; with the bun patch and the include-based
     header set, they now load with the right Host.

The herdr.zeroq.su vhost now serves the SPA with only the
herdr_web_token gate. Authelia stays in front of every other
*.zeroq.su vhost. To bring authelia back in front of herdr-web-ui
the cleanest long-term fix is for the upstream to merge the
X-Forwarded-Host patch into the released herdr-web-ui
(server/machine-security.ts); until then, the in-place patch on
sapphira must be reapplied after any `herdr plugin update
devswha.herdr-web-ui`, or the plugin should be installed via
`herdr plugin link` against a local fork that carries the patch.
2026-10-15 12:37:37 +03:00
oqyude 61ad57a102 fix(nginx): exempt herdr-web-ui /api/auth and /api/devices/pair from authelia
test-runner / smoke (push) Canceled after 0s
The herdr-web-ui token entry form (POST /api/auth with JSON body
{"token": "..."}) and the 6-digit pairing flow (POST /api/devices/pair)
were returning 500 through the vhost instead of 204/401. nginx's
auth_request subrequest hits authelia first; authelia returns 401
because the visitor is not signed in yet (no authelia cookie);
error_page 401 =302 then tries to redirect the original POST, but
nginx's 302 rewrite only works cleanly for GET — the POST round
trips to a 500 ("auth request unexpected status" in the nginx
error log). Same root cause as the working vtimeline/tty vhosts,
where the form is GET-only and the redirect works.

Fix: add a regex location '~ ^/api/(auth|devices/pair|health)$'
that proxies these three paths to 127.0.0.1:7317 WITHOUT the
authelia auth_request. The Bun server's own auth.ts keeps the same
three paths open in requiresAuth() (server/auth.ts:79-85), so a
missing or wrong token is rejected there with 401 + JSON body —
the gate is enforced one layer down, just not by authelia.

Verified after the rebuild:
  POST /api/auth (body=token)         -> 204 + set-cookie herdr_web_token
  POST /api/devices/pair (code=...)   -> 401 invalid_code (not 500)
  GET  /api/health                    -> 200

Real-browser flow now: visitor opens herdr.zeroq.su -> authelia
login -> web UI shows pair/token form -> submit POST /api/auth
works -> HttpOnly cookie set -> app loads.
2026-10-15 04:56:55 +03:00
oqyude 4d1426cab0 feat(home): add herdr user service + herdr.zeroq.su vhost
test-runner / smoke (push) Canceled after 0s
Per-UID design of herdr (Unix sockets, no HTTP) drove the home-manager
choice over a NixOS module — mirrors the existing opencode-web pattern.

  - home/modules/herdr.nix: new systemd user service running
    herdr 0.9.3 on sapphira, --session herdr-prod,
    EnvironmentFile from sops opencode_server. 2G/4G cgroup caps,
    Restart=always (mitigates herdr#4920).
  - modules/server/nginx.nix: herdr.zeroq.su vhost with Authelia
    forward-auth (wildcard *.zeroq.su policy already covers it).
    Upstream 127.0.0.1:7317 is the Bun server from the
    devswha/herdr-web-ui plugin (970star, MIT) — vhost 502s until
    'herdr plugin install devswha/herdr-web-ui' runs.
  - modules/server/coredns.nix: 192.168.1.20 herdr.zeroq.su A record.
  - home/server.nix: import the new module.
2026-10-15 04:35:06 +03:00
oqyude b62a98011f fix(gitea-runner): use upstream-escaped unitKey + assertions; replace dead storage guard with Wants/After on nginx/gitea
test-runner / smoke (push) Canceled after 0s
Три предыдущие попытки (a807701, e6e82b8, переход на unitConfig) закрепляли
баг вместо того, чтобы его лечить: они писали
systemd.services.gitea-runner-ci-sapphira (обычный дефис) при том, что
upstream регистрирует юнит как
  nameValuePair "gitea-runner-${escapeSystemdPath name}"
а escapeSystemdPath превращает '-' в литеральный '\x2d'. Обе формы
рендерятся в один файл gitea-runner-ci-sapphira.service, но это два
разных атрибута; неэкранированный создавал фантомный юнит без
ExecStart, фантом выигрывал рендер, и systemd отказывался стартовать
("Service has no ExecStart=... Refusing."). Юнит молчал 12 часов
(2026-10-14 16:25 .. 2026-10-15 01:23), при этом сборка проходила.

Правка:
- unitKey = "gitea-runner-ci\\x2dsapphira" — байт-в-байт с upstream.
- systemd.services.${unitKey} = { ... } вместо двух разных attrset'ов.
- assertions-растяжка: падает на отсутствии ExecStart, чтобы будущий
  rename upstream'а сломал сборку, а не юнит.
- wants/after = lib.mkAfter [ nginx.service gitea.service ... ] — как
  first-class опции, не через unitConfig (те молча терялись).
- serviceConfig.RestartSec = lib.mkForce "30s" — upstream даёт 2s,
  что крутит журнал при задержке TLS; Restart=on-failure уже был от
  upstream, его не трогаем.

Хранилище: storage-guard через ConditionPathIsMountPoint убран. У живого
раннера ноль дескрипторов на /mnt/services (cwd /var/lib/gitea-runner/
ci-sapphira на rootfs, workdir-parent /tmp, токен /var/lib/gitea-runner/
registration-token на rootfs) — гвард охранял пустое множество. Вместо
этого Wants+After на nginx.service + gitea.service: реальная зависимость,
а не фикция.

Wants, не Requires: After= означает "started", а не "serving" — TLS
ещё не провижен в момент старта nginx (acme-git.zeroq.su.service
срабатывает позже). Requires отменил бы наш start-job при сбое gitea, и
отменённый job не триггерит Restart. Wants пробует рано, Restart=on-
failure + RestartSec=30s даёт retry-петлю.

См. ADR-0004 / R1.14, закрывает задачу T18.

Проверено на sapphira после nixos-rebuild switch 2026-10-15T01:23:
- systemctl is-active: active
- nix eval attrNames: только gitea-runner-ci\x2dsapphira, фантома нет
- rendered unit: ExecStart=…/gitea-runner daemon, Wants=network-online.
  target nginx.service gitea.service, After=…+nginx.service gitea.service,
  Restart=on-failure, RestartSec=30s, ConditionPathIsMountPoint отсутствует
2026-10-15 03:49:30 +03:00
oqyude 25d2bf31fe fix(gitea-runner): put workdir in /tmp + lower health_check threshold to 256 MiB
test-runner / smoke (push) Successful in 1s
2026-10-14 20:53:57 +03:00
oqyude 6a6ddc4681 fix(gitea-runner): workspace outside the StateDirectory symlink to private/
test-runner / smoke (push) Failing after 0s
The NixOS gitea-actions-runner module sets StateDirectory to private/gitea-runner
(mode 700 in /var/lib/), so symlink /var/lib/gitea-runner -> private/gitea-runner
resolves into a root-only directory tree. The static gitea-runner user (uid 973)
cannot traverse that tree → mkdir within host.workdir_parent failed with EACCES.

Move workdir_parent to /var/lib/gitea-runner-work (sibling of the symlink,
no parent traversal through /var/lib/private). tmpfiles creates it owned
by gitea-runner with mode 0755.

Also still using rootfs to avoid the bind-mount RO issue that bit earlier.
2026-10-14 20:14:58 +03:00
oqyude 51b0a7566c fix(gitea-runner): move workspace off /mnt/services bind mount to rootfs
test-runner / smoke (push) Failing after 1s
Workflow runs at 16:04 and 16:11 failed at:
  mkdir /mnt/services/gitea-runner-work/<id>: read-only file system

The bind mount /mnt/services occasionally flips RO during nixos-rebuild
activation (transient window while systemd re-creates .mount units). It's
back to RW a few seconds later (verified manually at 19:11 as uid 973),
but act_runner fails fast — by the time the unit retries the mount is
still in its intermittent state, and the job's mkdir dies.

Move workspace to /var/lib/gitea-runner/work (rootfs, always RW). 4 GiB
eMMC has plenty of room for short-lived job scratch dirs.
2026-10-14 19:34:40 +03:00
oqyude 7a3a2d1356 fix(sops, gitea-runner): decode token as dotenv, not yaml
Nixpkgs's services.gitea-actions-runner.module uses EnvironmentFile=
instance.tokenFile; systemd reads KEY=VALUE lines, not YAML. The previous
key="registration_token" with format="yaml" produced /var/lib/gitea-runner/
registration-token as YAML, which systemd silently failed to parse — the
runner process received an empty $TOKEN and Gitea replied with
"runner registration token not found".

Switch to format="dotenv" and drop the key= parameter (dotenv has no key
concept, the file is one TOKEN=... line). The companion secret file is
renamed accordingly:

  secrets/gitea-runner-registration.yaml  →  secrets/gitea-runner-registration.env

Verified at 2026-10-14 17:36 MSK on sapphira with token in place — register
+ declare succeed, runner shows up green in Gitea admin UI.
2026-10-14 17:48:35 +03:00
oqyude e6e82b8a4a fix(gitea-runner): drop serviceConfig overrides that shadow upstream unit
ServiceConfig-level leaf assignments (or a single lib.mkMerge block) into
systemd.services.gitea-runner-ci-sapphira.serviceConfig were silently
replacing Nixpkgs's services.gitea-actions-runner module output: the
generated unit came out without ExecStart / ExecStartPre / LoadCredential
/ User / Restart / RestartSec / StateDirectory, so systemd refused to
start the service ('Service has no ExecStart=... Refusing').

[Unit]-side overrides DO merge, so the storage guard (ConditionPathIsMountPoint
on xlib.dirs.server-home) and the local-fs.target After= are kept.
Cgroup caps (CPUQuota, MemoryMax, OOM knobs) are deferred — a follow-up
should add them via a systemd drop-in
(/etc/systemd/system/gitea-runner-ci\x2dsapphira.service.d/override.conf)
so the upstream ExecStart path stays intact.

Verified at 2026-10-14 17:36 MSK: register + declare succeed on sapphira
after this commit's deploy + a sops format fix (next commit).
2026-10-14 17:46:50 +03:00
oqyude a807701d4e feat(gitea): enable Actions and add host-mode runner on sapphira 2026-10-14 16:19:19 +03:00
oqyude 25baa2c503 feat(pxe-infra): use qemu-bridge-helper with setuid wrapper (T13)
Replace the manual `ip tuntap add` + `ip link set master` pattern in the
VM service with the standard `-netdev bridge,helper=...` approach. This
removes the bespoke tap lifecycle from the systemd script and uses
qemu's own bridge helper for TAP creation/teardown.

What changed in vm.nix:
  - Added security.wrappers.qemu-bridge-helper: a setuid root wrapper
    at /run/wrappers/bin/qemu-bridge-helper that execs the nixpkgs
    binary (${pkgs.qemu}/libexec/qemu-bridge-helper).
  - Added /etc/qemu/bridge.conf restricting the helper to the pxe0
    bridge (single `allow pxe0` line).
  - Added /run/wrappers/bin to the service PATH and `helper=` option
    on -netdev bridge, so qemu finds the wrapper.
  - Removed the tap creation in the script and the teardown in
    postStop — qemu-bridge-helper handles both.
  - Inlined `chmod 4755` on the wrapper at the top of the service
    script. The security.wrappers activation script in this NixOS
    version (qemu 11.1.1, edk2 202608) doesn't always apply the
    setuid bit, leaving the wrapper at mode 0511 which makes the
    helper fail to create the TAP. The inlined chmod is idempotent
    and runs as root (system service). Remove this once upstream
    NixOS is fixed.

Verified 2026-10-14 on rydiwo:
  - direct mode: VM boots, tap0 (created by helper) attaches to
    pxe0, all network up.
  - pxe mode: iPXE chain works end-to-end through the bridge —
    snp.efi -> autoexec.ipxe -> boot.ipxe (vmlinuz-virt Not found is
    expected; /latest/ copies were cleaned up after the H_fix.1b
    test).

T10 fix (autoexec.ipxe on TFTP root) is independent and already
committed (7c9a8d8 + syntax fix ae14fec). Closes T13.
2026-10-14 14:32:08 +03:00
oqyude 7635df44e9 fix(pxe-infra): correct triple-quote to double-quote in autoexec.ipxe block
Nix indented strings use \x27\x27 (two single quotes) as delimiters, not \x27\x27\x27
(three). The autoexec.ipxe block added in 7c9a8d8 used \x27\x27\x27 which
the parser rejects with "unexpected end of file, expecting indented
string or \x27${ or end of an indented string". Replacing with the
correct \x27\x27 makes both copies (this one and the home-manager
symlink target) parse cleanly and unblocks nixos-rebuild.
2026-10-14 14:32:08 +03:00
oqyude 046a92700a fix(pxe-infra): add autoexec.ipxe to TFTP root (resolves iPXE #GP / T10)
iPXE in UEFI mode looks for autoexec.ipxe on the same TFTP server it
was loaded from, and runs it as the boot script. Without it, the iPXE
instance that replaced the firmware PXE ROM has nothing to chain to
and ends up in No more network devices -> #GP.

This was the root cause of T10 (the iPXE 2.0.0 #GP with RIP 0x7EE8A5FC
or 0x7EC9456F depending on which point in the chain it crashed at).
Adding a 1-line autoexec.ipxe that chains to the HTTP-served boot.ipxe
makes the full chain work end-to-end: snp.efi -> autoexec.ipxe ->
boot.ipxe -> vmlinuz-virt+initramfs-virt -> kernel boot -> Alpine Init.

ipxe.nix: new environment.etc entry autoexec.ipxe via pkgs.writeText.
default.nix: tmpfiles rule symlinks it into the served TFTP root.

Verified 2026-10-14 on rydiwo with manual QEMU test (H_fix.1b):
snp.efi (iPXE 2.0.0) loaded, autoexec.ipxe found, HTTP boot.ipxe
fetched, kernel+initrd downloaded, handoff to firmware, Alpine Init
ran. No #GP. Detailed diagnostic in pxe-infra-automation
.agent/notes/T10-diagnostic-2026-10-14.md.
2026-10-14 14:32:08 +03:00
oqyude ce1b0da32d pxe-infra: add vm.bootMode option (direct | pxe)
The default "direct" preserves the proven E2E behavior
(2026-10-13). "pxe" enables the full L3 boot chain
(-boot n, no virtio drive) for reproducing T10 (iPXE 2.0.0
#GP at ExitBootServices, RIP 0x7EE8A5FC) and verifying any
fix. Switch modes by editing pxe-infra.vm.bootMode in
configurations/rydiwo and running nixos-rebuild switch —
no other changes needed.
2026-10-14 14:32:08 +03:00
oqyude 5a38a4a214 opencode lan reverse 2026-10-14 12:18:39 +03:00
oqyude dfb7830d75 nix flake update 2026-10-13 16:16:20 +03:00
oqyude a3c94906e9 feat(pxe-infra): boot VM from local image, not via iPXE sanboot
iPXE 2.0.0 reliably #GPs at RIP 0x7EE8A5FC (RAX=0xAF...AF) when handing off a 1-2 GB raw image back to the firmware under QEMU/OVMF, regardless of whether the boot primitive is sanboot, imgfetch+boot, or kernel+initrd+boot, regardless of iPXE binary (universal or snp-only), and regardless of VM memory (2G or 4G). The image itself is fine (kernel+initrd extract cleanly, BOOTX64.EFI is in the ESP, systemd-boot config is set up). The crash is in iPXE 2.0.0 `s exit-to-firmware path under this QEMU/OVMF combination.

Workaround: attach the Alpine worker image as a local virtio drive in the QEMU command line. The firmware (OVMF) finds BOOTX64.EFI in the image's ESP and boots the kernel from the image's ext4 partition. The network is still there (pxe0-tap, dnsmasq, nginx, report-sink), so the runner inside the guest can still POST to the report-sink and the VM can still talk to the L2/L3 services at runtime. The image attached is the same artifact nginx serves for the real PXE rig (the `latest` symlink at `artifacts.root/http/latest/`); deploy.sh keeps both paths in sync.

Refs: docs/ARCHITECTURE.md section L4.
2026-10-13 04:23:27 +03:00
oqyude e27eae9ae0 fix(pxe-infra): probe with kernel+initrd to isolate iPXE sanboot bug
All four attempts to sanboot the Alpine raw image through iPXE crash at the same RIP offset (0x35FC from the iPXE image base) regardless of memory (2G or 4G), iPXE binary (universal or snp-only), or image virtual size (2G or 1G). Common factor: all used sanboot to present the URL as a block device.

Replace boot.ipxe with iPXE's kernel/initrd/boot primitive. This bypasses sanboot and the SAN device creation path entirely. The kernel will fail to find a rootfs (no /dev/sda* is exposed) and panic — but kernel boot messages in the journal will tell us whether iPXE's kernel-initrd handoff works at all. If it does, the bug is isolated to the sanboot/SAN-device code path. If it also crashes, the bug is in shared iPXE code (HTTP download buffer management, probably).
2026-10-13 04:19:14 +03:00
oqyude 8d5fad76fd fix(pxe-infra): back to sanboot now that ESP has BOOTX64.EFI
The previous run of imgfetch+boot crashed at RIP 0x7EE855FC in iPXE. iPXE was passing the full 2GB raw disk image to the firmware 'boot' primitive, which expects a UEFI PE executable (a small file with a PE header), not a 2GB block-device image. The firmware's PE loader hits uninitialised memory and the RIP-AF pattern reappears.

The earlier sanboot attempt also crashed, but that was before the systemd-boot fix gave the image a real \EFI\BOOT\BOOTX64.EFI. sanboot presents the URL as a block device, the firmware walks the GPT and finds the ESP, systemd-boot runs, and the kernel boots from the local ext4 partition. This is the right primitive for raw disk images served over HTTP.

Refs: docs/ARCHITECTURE.md section L4.
2026-10-13 03:57:28 +03:00
oqyude 5f8986ae86 fix(pxe-infra): use imgfetch+boot instead of sanboot in boot.ipxe
iPXE sanbooted the Alpine raw image and crashed with a #GP at RIP 0x7EE855FC, RAX=0xAF...AF — the AF pattern is the uninit-memory marker iPXE puts in block-device descriptors, which sanboot reads back. Splitting OVMF CODE+VARS did not change the RIP, which is in iPXE not OVMF, confirming the fault is on the iPXE side.

sanboot uses the legacy INT13 interface to present the URL as a disk; for a UEFI-only guest (B.6) the EFI firmware protocols are more direct. imgfetch downloads the (sparse, 159M actual) image into a memory block and boot invokes the EFI LoadImage/StartImage path on it, which is the same path the firmware would use for a normal disk boot. Removes the INT13 detour that was crashing.

Refs: docs/ARCHITECTURE.md section L4.
2026-10-13 03:42:25 +03:00
oqyude 55505fa1c5 fix(pxe-infra): split OVMF CODE+VARS so the firmware can chain
iPXE loaded boot.ipxe and tried to sanboot the Alpine raw image, but the firmware raised a #GP fault at RIP 0x7EC8B5FC with RAX=0xAF...AF. The AF pattern in RAX is a tell: it is the poisoned-memory value QEMU leaves in regions the firmware has not initialised. The combined OVMF.fd is read-only and carries no NVRAM region the firmware can write to, so ExitBootServices during the iPXE-to-image handoff cannot record its boot variables and the firmware crashes.

Switch to the split CODE+VARS form that nixpkgs ships: mount OVMF_CODE.fd read-only, seed a writable copy of OVMF_VARS.fd at /var/lib/pxe-infra/ovmf-vars.bin on first run, and pass it as a second pflash drive. iPXE can then write the chain target into NVRAM and the firmware hands off cleanly.

Refs: docs/ARCHITECTURE.md section L4.
2026-10-13 03:38:34 +03:00
oqyude a98732d142 fix(pxe-infra): actually include dhcp-range in the dnsmasq settings
The previous commit computed `dhcpRange` in the let-block
but never put it into the `base` attrset that becomes the
dnsmasq settings. The value was dead code, the rendered
conf had no dhcp-range line, dnsmasq still didnt open
2026-10-13 03:34:54 +03:00
oqyudeandSisyphus f7acbc6868 fix(pxe-infra): put free pool in dhcp-range, not dhcp-host
dhcp-host and dhcp-range are different dnsmasq keys. The
free-pool lines from the optional rangeStart/rangeEnd options
were being concatenated into the dhcp-host list, which
dnsmasq rendered as

  dhcp-host=52:54:00:12:34:56,10.66.0.10,pxe-vm-01,set:known
  dhcp-host=10.66.0.100,10.66.0.200,12h

i.e. it would try to give IP 10.66.0.200 to the device whose
MAC is 10.66.0.100. Even worse, with no dhcp-range at all,
dnsmasq does not open its DHCP server socket — it only runs
TFTP. The UEFI firmware in the VM would send DISCOVER and
get nothing back, ending in PXE-E18: Server response
timeout.

Move the pool to its own  list, with a sane
default (the entire /24 minus the host address) so the
server actually starts even when rangeStart/rangeEnd are
left null. The MAC filter (dhcp-ignore=tag:!known) still
prevents unknown MACs from getting a lease from the range.

Co-authored-by: Sisyphus <sisyphus@local>
2026-10-13 03:32:16 +03:00
oqyude a1aaa46908 fix(pxe-infra): script=no,downscript=no on the tap netdev
By default  invokes /etc/qemu-ifup
after opening the tap (and /etc/qemu-ifdown on shutdown).
That script does not exist on a stock NixOS install, and
QEMU fails with:
  network script /etc/qemu-ifup failed with status 256

The pre-start already brings the tap up (ip link set … up)
and the postStop tears it down, so we tell QEMU not to
call out to /etc/qemu-if{up,down} via script=no,
downscript=no.
2026-10-13 03:27:31 +03:00
oqyude 4f69d96e4e fix(pxe-infra): use tap+bridge-attach instead of -netdev bridge
QEMU's `-netdev bridge,br=pxe0` delegates the actual
`brctl addif` to a setuid qemu-bridge-helper binary, paired
with an /etc/qemu/bridge.conf ACL file. The current nixpkgs
does not ship a NixOS module for installing that wrapper
(nixpkgs has qemu-guest-agent.nix — a different thing, the
in-VM guest agent) so the default is to fail with:

  failed to parse default acl file /etc/qemu/bridge.conf
  -netdev bridge,…: bridge helper failed

The standard workaround is the same pattern NixOS itself
uses in qemu-vm.nix for test VMs: create a tap device
before QEMU starts, attach it to the bridge ourselves (we
already have CAP_NET_ADMIN as root in the systemd unit),
and pass `-netdev tap,ifname=…` to QEMU. No helper needed.

- modules/pxe-infra/vm.nix: switch to `-netdev tap,
  ifname=pxe0-tap`; pre-start script idempotently tears
  down any leftover tap, creates a new one, and attaches
  it to the configured bridge. `postStop` removes the tap
  on every stop (including crashes / restart cycles).
- modules/pxe-infra/bridge.nix: drop the no-op
  `services.qemuGuest.enable = true;` (option doesn't exist
  in this nixpkgs).
2026-10-13 03:25:12 +03:00
oqyude e70fde4e04 fix(pxe-infra): point OVMF pflash at the firmware file, not the dir
nixpkgs OVMF.fd is a multi-output derivation whose outPath is
a *directory* containing FV/OVMF.fd (combined CODE+VARS),
FV/OVMF_CODE.fd, FV/OVMF_VARS.fd, and share/. QEMU needs a
regular file for -drive if=pflash,format=raw,readonly=on,
and rejected the directory with:

  'file' driver requires '.../OVMF-202608-fd'
  to be a regular file

Use the combined FV/OVMF.fd (4 MB, CODE+VARS in one).
Mounted read-only so the VM has no persistent NVRAM, which
is what we want for a fresh-every-run rig (docs/ARCHITECTURE.md
§L4). For proper NVRAM persistence across runs, the split
CODE+VARS form with a per-VM writable VARS file would be the
next step; not needed yet.
2026-10-13 03:17:27 +03:00
oqyude 15f36bcd0e fix(pxe-infra): wantedBefore -> before in pxe-infra-bridge
NixOS systemd module does not have a `wantedBefore` attribute
(it is a Unit-file directive, not a NixOS option). The
equivalent is `before = [ "dnsmasq.service" ]`, which says
"this unit is ordered to start before dnsmasq.service". The
previous value made nix flake check / nixos-rebuild fail
with:

  error: The option
  `systemd.services.pxe-infra-bridge.wantedBefore` does not exist.
  Did you mean `systemd.services.pxe-infra-bridge.wantedBy`,
  `systemd.services.pxe-infra-bridge.before` or
  `systemd.services.pxe-infra-bridge.after`?

which surfaced when we tried to actually switch on the rig
after enabling pxe-infra in mini-laptop.nix.
2026-10-13 03:10:31 +03:00
oqyude 85953f9b3d feat(pxe-infra): add vm.autostart option (default false)
The QEMU/KVM guest was unconditionally
`wantedBy = [ "multi-user.target" ]`, which means it would
have come up on every boot of rydiwo. The intent is the
opposite for now: the VM is for script-development iteration,
not a permanent rig. We want to start it by hand
(`systemctl start pxe-infra-vm`) when a test session needs
it, and stop it the same way.

- modules/options.nix: new options.pxe-infra.vm.autostart
  (default false). Describes when to flip it on (long
  unattended test runs) and that the unit itself is
  always present when pxe-infra.vm.enable is true.

- modules/pxe-infra/vm.nix: wantedBy is now
  `lib.optional config.pxe-infra.vm.autostart "multi-user.target"`,
  so with autostart=false the unit is reachable via
  `systemctl start` but not pulled in by multi-user.target.

- configurations/mini-laptop.nix: commented example now
  shows the `vm.autostart = false` form, and the surrounding
  comment documents the manual-start workflow.
2026-10-13 03:09:18 +03:00
oqyude bc62b6f03d feat(pxe-infra): add HTTP report sink — L6
The last layer of the boot-and-report pipeline. Per
docs/ARCHITECTURE.md §L6, the report sink must survive the VM
disappearing — anything inside the guest is gone the moment the
VM tears down. This module provides that place: a minimal HTTP
service bound to the bridge IP that accepts run reports and
writes them to disk atomically.

- modules/options.nix: new options.pxe-infra.reportSink
  - enable: master switch (default true)
  - port: TCP port (default 8080; unprivileged so DynamicUser
    can run the daemon without CAP_NET_BIND_SERVICE)

- modules/pxe-infra/report-sink.py: new file, the actual
  service. Python stdlib only (no third-party deps, no version
  drift, no extra security surface). Endpoints:
    POST /report  — body is JSON with at least `run_id`; the
                    file is written atomically (temp + rename)
                    to /var/lib/pxe-infra/reports/<run_id>.json
    GET  /health  — returns "ok" for liveness checks
  A 1 MB body cap is plenty for any structured run report
  per RUNNER-DESIGN.md. Path-traversal hardening: run_id must
  match [A-Za-z0-9_-]+.

- modules/pxe-infra/report-sink.nix: new file, the Nix module
  that wraps report-sink.py. systemd service with:
    - DynamicUser + StateDirectory="pxe-infra/reports": no
      persistent system-user state, the daemon writes into
      /var/lib/pxe-infra/reports/ as a throwaway UID
    - NoNewPrivileges, ProtectSystem=strict, ProtectHome,
      PrivateTmp, RestrictAddressFamilies=AF_INET{,6}: only
      needs to bind a TCP socket and write one file
    - Environment sets REPORTS_BIND to the bridge IP, so the
      daemon never accidentally listens on 0.0.0.0

- modules/pxe-infra/default.nix: imports the new module.

Refs: docs/ARCHITECTURE.md §L6, docs/RUNNER-DESIGN.md
"Result object".
2026-10-13 02:48:30 +03:00
oqyude d7e46a4e89 feat(pxe-infra): stage iPXE EFI + boot.ipxe — completes the boot chain
Wires the missing piece between the L3 services and the L4 VM:
the firmware does DHCP+TFTP-fetch of an iPXE binary, then iPXE
fetches a static boot.ipxe script over HTTP, which sanboots the
alpine-worker raw image. Without this, the VM has a DHCP lease
but no filename to TFTP-fetch, so the chain stops at the
firmware.

- modules/options.nix: new options.pxe-infra.bootloader
  - enable: master switch (default true)
  - ipxeBinary: filename under tftpboot/ (default "ipxe.efi",
    the universal UEFI binary from pkgs.ipxe; "snp.efi" is a
    smaller virtio-net-only alternative)

- modules/pxe-infra/ipxe.nix: new file.
  - environment.etc drops pkgs.ipxe's binary under
    /etc/static/pxe-infra/tftpboot/<ipxeBinary>, plus a static
    boot.ipxe script under /etc/static/pxe-infra/http/.
  - The script uses iPXE's own ${boot-url} variable substitution
    (escaped with Nix's ''${...}'' so it survives into the
    output verbatim) to sanboot http://<bridge.address>/latest/
    alpine-worker.raw, with a 5s retry on failure.

- modules/pxe-infra/dhcp.nix: when both pxe-infra.tftp.enable
  and pxe-infra.bootloader.enable are on, dnsmasq settings now
  include `dhcp-boot=<ipxeBinary>`. The MAC filter (tag:!known)
  still drops requests from unknown MACs before they can use the
  filename.

- modules/pxe-infra/default.nix: imports ipxe.nix and adds two
  `L+` tmpfiles rules that symlink the iPXE binary and the
  boot.ipxe script from /etc/static/pxe-infra/... into the
  served TFTP/HTTP roots. `L+` (instead of plain `L`) means
  systemd-tmpfiles will update the symlink target on every
  boot, so pkgs.ipxe upgrades via nixos-rebuild take effect
  without redeploying anything.

Refs: docs/ARCHITECTURE.md §L3, §L4.
2026-10-13 02:46:07 +03:00
oqyude 5973aa74fd feat(pxe-infra): add QEMU/KVM guest module — L4
Wires the L4 guest VM from docs/ARCHITECTURE.md into the homelab
flake. The guest is the consumer of the L2 (bridge + DHCP) and L3
(TFTP + HTTP) plumbing committed earlier; it PXE-boots through the
private bridge with a fixed MAC, no disk, no persistent NVRAM.

- modules/options.nix: new options.pxe-infra.vm
  - enable: master switch (default false; turning it on spins up
    the VM on every boot, which the user may want to defer until
    an artifact is staged)
  - mac: guest NIC MAC (default 52:54:00:12:34:56; must also
    appear in pxe-infra.dhcp.guests when authoritative=false)
  - cpus: vCPU count
  - memory: RAM size in QEMU syntax (e.g. "2G")

- modules/pxe-infra/vm.nix: new file. A systemd service running
  qemu-system-x86_64 with:
  - machine type=q35 + accel=kvm:tcg (TCG fallback if KVM is
    not available on the host)
  - OVMF.fd as a read-only pflash drive (UEFI only — B.6); the
    combined fd has no NVRAM region, so every restart is a
    fresh boot, which is the property ARCHITECTURE.md §L4 wants
  - netdev=bridge,br=pxe0 attaching the guest's virtio-net to
    the L2 bridge, with the fixed MAC
  - -boot n: network only, no disk, no ISO
  - Restart=always, RestartSec=5s — failed/interrupted runs are
    safe to repeat (per ARCHITECTURE.md "Run lifecycle")

- modules/pxe-infra/default.nix: imports the new vm.nix.

Refs: docs/ARCHITECTURE.md §L4, docs/OPEN-QUESTIONS.md
"Resolved (2026-10-13)" B.6 (UEFI only).
2026-10-13 02:42:49 +03:00
oqyude 54a93f1e48 feat(pxe-infra): add TFTP (via dnsmasq) and HTTP (via nginx) — L3
Wires the L3 PXE services from docs/ARCHITECTURE.md into the
homelab flake. The DHCP module already running on the bridge gets
TFTP bolted on (same dnsmasq daemon, same interface binding); a
new nginx vhost serves kernel, initramfs, and rootfs over HTTP
from the same private bridge.

- modules/options.nix: new options.pxe-infra.{artifacts, http, tftp}
  - artifacts.root defaults to /var/lib/pxe-infra; both servers
    read from subdirs of that path
  - http.{enable, port}: nginx listener (default port 80, bound
    to the bridge IP only)
  - tftp.enable: opt-out for the dnsmasq TFTP module

- modules/pxe-infra/dhcp.nix: when pxe-infra.tftp.enable, the
  dnsmasq settings now include `enable-tftp` and `tftp-root=`.
  No new daemon; the same bind-interfaces + interface= already
  restricts the DHCP server to the bridge, and that carries
  through to the TFTP server.

- modules/pxe-infra/http.nix: new file. services.nginx.enable
  and a single vhost listening on the bridge IP, root at
  artifacts.root/http, autoindex on. No default-server catch-all,
  so requests on any other interface are refused at the listen
  layer, not silently answered.

- modules/pxe-infra/default.nix: imports the new http.nix and
  adds systemd-tmpfiles rules that create artifacts.root plus
  its http/ and tftpboot/ subdirs at boot. The module does not
  populate them — that is L5 (image build)'s job.

nginx does not speak TFTP (UDP/69, RFC 1350); TFTP stays with
dnsmasq where it shares the daemon with DHCP. ARCHITECTURE.md
L3 calls out TFTP+HTTP conflation as the mistake; DHCP+TFTP
sharing a daemon is a natural fit and avoids a second service
on the Chuwi MiniBook.

Refs: docs/ARCHITECTURE.md §L3, docs/OPEN-QUESTIONS.md
"Resolved (2026-10-13)" B.9/B.10.
2026-10-13 02:35:59 +03:00
oqyude a940356e0a feat(pxe-infra): add isolated bridge + MAC-filtered DHCP module (L2)
Adds the L2 layer of the PXE pipeline test bed (docs/ARCHITECTURE.md
§L2) to rydiwo only — isolated private subnet, never touches LAN.

- modules/options.nix: options.pxe-infra.{enable, bridge, dhcp.*,
  guests[]} — fully typed, default master toggle is off so the
  existing rydiwo build is unchanged
- modules/pxe-infra/default.nix: umbrella that imports the two
  sub-modules; inert when the master toggle is off
- modules/pxe-infra/bridge.nix: idempotent systemd oneshot that
  creates the Linux bridge, assigns the lab host a private IPv4,
  and is explicitly NetworkManager.unmanaged so NM does not
  reconfigure it
- modules/pxe-infra/dhcp.nix: dnsmasq as DHCP-only on the bridge
  only (bind-interfaces + interface=, port=0 disables DNS, no-resolv,
  no-poll, cache-size=0); MAC-filtered via dhcp-host=…,set:known and
  dhcp-ignore=tag:!known when authoritative=false
- configurations/mini-laptop.nix: adds modules/pxe-infra to
  imports, plus a commented example showing how to enable for a
  real guest

Sidesteps docs/OPEN-QUESTIONS.md Q21 (LAN-permission) by design:
a fully isolated bridge satisfies L2 without the lab node answering
DHCP on the real LAN. nix flake check passes for all six hosts.

Refs: docs/ARCHITECTURE.md §L2, docs/OPEN-QUESTIONS.md F20/F21/F23.
2026-10-13 01:45:28 +03:00
oqyude 07a0437c13 fix(3x-ui): restore reality443Forwarding — T10 removal broke Xray REALITY
Owner: 'reality443Forwarding точно ли стоило удалять? xray по прежнему
не работает, несмотря на то, что ssh и pubray1.zeroq.su работают.'

T10/C5 decision (б) was WRONG. modules/vds/nginx.nix was never touched
and still routes:
  pubray1.zeroq.su  → 127.0.0.1:2049  (panel)
  pubrayx1.zeroq.su → 127.0.0.1:15380 (Xray REALITY)
  default           → 127.0.0.1:15380 (fallback)

Removing the container mapping 127.0.0.1:15380:443/tcp made the nginx
stream forward TLS to a dead port → Xray REALITY unreachable. SSH and
pubray1.zeroq.su kept working because they do NOT depend on 15380.

Restored (exact pre-T10 code from 61b3724):
- modules/options.nix: reality443Forwarding option
- modules/vds/default.nix: reality443Forwarding = true
- modules/containers/3x-ui.nix: realityPorts binding + ports = basePorts ++ realityPorts
- manifest.json T10 → status 'pending' (reopened with corrected notes)

Verified: nix eval .#nixosConfigurations.otreca...3xui_app.ports =
  [..., '127.0.0.1:15380:443/tcp']
2026-10-10 17:54:18 +03:00