From 1a50c8a6685289b876fa845d626c3bccf441e8e4 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Fri, 11 Sep 2026 17:29:22 -0500 Subject: [PATCH] feat(nixos): scaffold declarative NixOS appliance for homelab server Phase 1 & 2 of the homelab-core NixOS migration plan. Adds a fully standalone NixOS flake configuration targeting the roadtotech.me homelab server. Goal: wipe & restore from any bare NixOS install via `nixos-install --flake ~/Core#server`. Changes: - flake.nix: 2-input flake (nixpkgs channel tarball + sops-nix) - flake.lock: generated lockfile pinning nixos-26.11pre1070770.8ce4ef6 - .sops.yaml: SOPS rules scoped to nixos/secrets.yaml (server + laptop keys) - nixos/configuration.nix: clean standalone config; no HM, no desktop inheritance, no lib.mkForce; headless-optimised; SOPS set exactly once - nixos/hardware-configuration.nix: copied from Config/hosts/server/ - nixos/secrets.yaml: copied SOPS-encrypted secrets from Config/hosts/server/ - nixos/modules/homeserver.nix: migrated; sops.defaultSopsFile removed - nixos/modules/traefik-deployments.nix: migrated; sops.defaultSopsFile removed - nixos/modules/dynu.nix: migrated; paths updated to ../scripts/ - nixos/scripts/monitor.py: dynu IP monitor Python script - nixos/scripts/ddclient.conf: ddclient config template - AGENTS.md: fix stale reference to deprecated desktop secrets path Validated: nix flake check -> all checks passed nix build .#nixosConfigurations.server.config.system.build.toplevel \ --no-link -> success (nixos-system-server-26.11.20260910.8ce4ef6) --- .sops.yaml | 11 ++ AGENTS.md | 2 +- flake.lock | 45 ++++++ flake.nix | 23 +++ nixos/configuration.nix | 122 +++++++++++++++ nixos/hardware-configuration.nix | 41 ++++++ nixos/modules/dynu.nix | 88 +++++++++++ nixos/modules/homeserver.nix | 118 +++++++++++++++ nixos/modules/traefik-deployments.nix | 95 ++++++++++++ nixos/scripts/ddclient.conf | 12 ++ nixos/scripts/monitor.py | 205 ++++++++++++++++++++++++++ nixos/secrets.yaml | 59 ++++++++ 12 files changed, 820 insertions(+), 1 deletion(-) create mode 100644 .sops.yaml create mode 100644 flake.lock create mode 100644 flake.nix create mode 100644 nixos/configuration.nix create mode 100644 nixos/hardware-configuration.nix create mode 100644 nixos/modules/dynu.nix create mode 100644 nixos/modules/homeserver.nix create mode 100644 nixos/modules/traefik-deployments.nix create mode 100644 nixos/scripts/ddclient.conf create mode 100644 nixos/scripts/monitor.py create mode 100644 nixos/secrets.yaml diff --git a/.sops.yaml b/.sops.yaml new file mode 100644 index 0000000..fa9faee --- /dev/null +++ b/.sops.yaml @@ -0,0 +1,11 @@ +keys: + - &server age18q3lr2z4yeg2f86my42ym4hx0dvcwgjshmchyhdkgwvf4k37dsyq3mcjse + - &laptop age1pln9sxy5j93lklqklfwp3qepx7x4cs4y2w63n9y3ykt68qgra5ysqleesg + +creation_rules: + - path_regex: nixos/secrets\.yaml$ + key_groups: + - pgp: [] + age: + - *server + - *laptop diff --git a/AGENTS.md b/AGENTS.md index c770468..b20334d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,7 +13,7 @@ This repository is the central control plane for the `roadtotech.me` homelab clu - `socket-proxy` must remain restricted to read-only endpoints (`POST=0`, `DELETE=0`). 3. **Zero Hardcoded Secrets**: - Never commit raw `.env` files, password strings, database files (`*.db`, `*.sqlite3`), or SSL certificates (`acme.json`, `*.key`). - - All runtime secrets are managed declaratively in `~/Config/hosts/desktop/secrets.yaml` via SOPS and rendered to `/run/secrets/rendered/`. + - All runtime secrets are managed declaratively in `nixos/secrets.yaml` via SOPS and rendered to `/run/secrets/` at boot. 4. **License Invariant**: - Preserve and maintain `The Unlicense` (public domain) across all Core and Sites repositories. diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..8e31381 --- /dev/null +++ b/flake.lock @@ -0,0 +1,45 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1789006805, + "narHash": "sha256-q+GdZ3yq4Y2LXHRK0vKTM32Hwy7RCgUgy+hjwZLI5pY=", + "rev": "8ce4ef6cb6f871616146b9fe26d2a5ae594e94fe", + "type": "tarball", + "url": "https://releases.nixos.org/nixos/unstable/nixos-26.11pre1070770.8ce4ef6cb6f8/nixexprs.tar.zst" + }, + "original": { + "type": "tarball", + "url": "https://channels.nixos.org/nixos-unstable/nixexprs.tar.zst" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs", + "sops-nix": "sops-nix" + } + }, + "sops-nix": { + "inputs": { + "nixpkgs": [ + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1788914643, + "narHash": "sha256-4GuMPW90JSxXWDPUB9M+1m7fYbe3H0apOd86/zBQ2Kw=", + "owner": "Mic92", + "repo": "sops-nix", + "rev": "13616fff713a9f94055c66f15687ebdc17a335df", + "type": "github" + }, + "original": { + "owner": "Mic92", + "repo": "sops-nix", + "type": "github" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..1aee834 --- /dev/null +++ b/flake.nix @@ -0,0 +1,23 @@ +{ + description = "Homelab Core β€” Turnkey Declarative NixOS Appliance for roadtotech.me"; + + inputs = { + nixpkgs.url = "https://channels.nixos.org/nixos-unstable/nixexprs.tar.zst"; + + sops-nix = { + url = "github:Mic92/sops-nix"; + inputs.nixpkgs.follows = "nixpkgs"; + }; + }; + + outputs = { self, nixpkgs, sops-nix, ... }@inputs: { + nixosConfigurations.server = nixpkgs.lib.nixosSystem { + system = "x86_64-linux"; + specialArgs = { inherit inputs; }; + modules = [ + ./nixos/configuration.nix + sops-nix.nixosModules.sops + ]; + }; + }; +} diff --git a/nixos/configuration.nix b/nixos/configuration.nix new file mode 100644 index 0000000..1b81df8 --- /dev/null +++ b/nixos/configuration.nix @@ -0,0 +1,122 @@ +# 🌐 Server NixOS Configuration β€” Turnkey Headless Homelab Appliance +# Standalone declarative configuration for the roadtotech.me homelab server. +# No Home Manager. No shared desktop modules. +# Goal: wipe & restore from any NixOS installation via `nixos-install --flake ~/Core#server` + +{ config, lib, pkgs, inputs, ... }: + +{ + imports = [ + ./hardware-configuration.nix # Server-specific disk and CPU configuration + ./modules/homeserver.nix # Core services: systemd units, Authelia, SOPS secrets + ./modules/traefik-deployments.nix # Traefik deployment secrets and env templates + ./modules/dynu.nix # Dynu DDNS smart IP monitor service + ]; + + # ── SOPS secrets configuration ────────────────────────────────────────────── + # Set once here to avoid duplicate-option conflicts across submodules + sops.defaultSopsFile = ./secrets.yaml; + sops.defaultSopsFormat = "yaml"; + + # ── Nix settings ───────────────────────────────────────────────────────────── + nix.settings.experimental-features = [ "nix-command" "flakes" ]; + + # Pin nixpkgs registry to the flake input (avoids GitHub API calls from the CLI) + nix.registry.nixpkgs.flake = inputs.nixpkgs; + + nixpkgs.config.allowUnfree = true; + + # ── Regional & locale settings ─────────────────────────────────────────────── + time.timeZone = "America/Bogota"; + i18n.defaultLocale = "en_US.UTF-8"; + + # ── Console ────────────────────────────────────────────────────────────────── + console = { + font = "Lat2-Terminus16"; + keyMap = "us"; + }; + + # ── Bootloader ─────────────────────────────────────────────────────────────── + boot.loader.systemd-boot.enable = true; + boot.loader.efi.canTouchEfiVariables = true; + + # ── Network ────────────────────────────────────────────────────────────────── + networking.hostName = "server"; + networking.networkmanager.enable = true; + + # ── User account ───────────────────────────────────────────────────────────── + users.users.kiskaadee = { + isNormalUser = true; + openssh.authorizedKeys.keys = [ + "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICAVPPMk+WApUd/fo78+lsRGnLKSlY4GDZiNGKwBAifD" + ]; + extraGroups = [ + "wheel" # sudo access + "docker" # run docker without sudo + "networkmanager" # modify network settings + ]; + }; + + # ── SSH ────────────────────────────────────────────────────────────────────── + services.openssh = { + enable = true; + ports = [ 22 ]; + settings.PermitRootLogin = "no"; + }; + + # ── Virtualisation ─────────────────────────────────────────────────────────── + virtualisation.docker.enable = true; + + # ── Dynamic binary support ─────────────────────────────────────────────────── + programs.nix-ld = { + enable = true; + libraries = with pkgs; [ + stdenv.cc.cc.lib + zlib + glib + ]; + }; + + # ── Headless optimizations ─────────────────────────────────────────────────── + # Disable peripheral hardware & desktop services not needed on a headless server + services.pipewire.enable = false; + services.printing.enable = false; + hardware.bluetooth.enable = false; + + # Disable power-saving sleep/suspend to keep the homelab always active + systemd.targets.sleep.enable = false; + systemd.targets.suspend.enable = false; + systemd.targets.hibernate.enable = false; + systemd.targets.hybrid-sleep.enable = false; + + # Kernel-level power management tuning + powerManagement.powertop.enable = true; + + # ── CLI tools ──────────────────────────────────────────────────────────────── + # Minimal server-appropriate tooling (no desktop apps or user dotfiles) + programs.tmux.enable = true; + programs.neovim = { + enable = true; + defaultEditor = true; + }; + + environment.systemPackages = with pkgs; [ + # Monitoring & diagnostics + htop + iotop + iftop + ncdu + # Secrets tooling + sops + age + # Utilities + git + curl + wget + rclone + ]; + + # ── State version ───────────────────────────────────────────────────────────── + # Do not modify this value after the first install. + system.stateVersion = "26.05"; +} diff --git a/nixos/hardware-configuration.nix b/nixos/hardware-configuration.nix new file mode 100644 index 0000000..0b10a8a --- /dev/null +++ b/nixos/hardware-configuration.nix @@ -0,0 +1,41 @@ +# Do not modify this file! It was generated by β€˜nixos-generate-config’ +# and may be overwritten by future invocations. Please make changes +# to /etc/nixos/configuration.nix instead. +{ config, lib, pkgs, modulesPath, ... }: + +{ + imports = + [ (modulesPath + "/installer/scan/not-detected.nix") + ]; + + boot.initrd.availableKernelModules = [ "nvme" "xhci_pci" "thunderbolt" "usbhid" ]; + boot.initrd.kernelModules = [ "dm-snapshot" ]; + boot.kernelModules = [ "kvm-amd" ]; + boot.extraModulePackages = [ ]; + + fileSystems."/" = + { device = "/dev/mapper/nixos_vg-root"; + fsType = "ext4"; + }; + + fileSystems."/boot" = + { device = "/dev/disk/by-uuid/66E6-7442"; + fsType = "vfat"; + options = [ "fmask=0022" "dmask=0022" ]; + }; + + fileSystems."/media" = + { device = "/dev/mapper/nixos_vg-media"; + fsType = "ext4"; + }; + + fileSystems."/home" = + { device = "/dev/mapper/nixos_vg-home"; + fsType = "ext4"; + }; + + swapDevices = [ ]; + + nixpkgs.hostPlatform = lib.mkDefault "x86_64-linux"; + hardware.cpu.amd.updateMicrocode = lib.mkDefault config.hardware.enableRedistributableFirmware; +} diff --git a/nixos/modules/dynu.nix b/nixos/modules/dynu.nix new file mode 100644 index 0000000..9574e51 --- /dev/null +++ b/nixos/modules/dynu.nix @@ -0,0 +1,88 @@ +# 🌐 Dynu DDNS IP Monitor & Updater Service +# This NixOS module configures a smart, local-first IP change detector. +# It queries public IP providers, maintains a history log of WAN IP rotations, +# and triggers ddclient only when an actual change is detected to prevent API rate limits. + +{ config, lib, pkgs, ... }: + +let + # Declaratively read the external Python script into the Nix store at evaluation time + ipMonitorScript = pkgs.writers.writePython3Bin "dynu-ip-monitor" { } (builtins.readFile ../scripts/monitor.py); +in +{ + # Define the keys to decrypt + sops.secrets."dynu/user" = { }; + sops.secrets."dynu/domain" = { }; + sops.secrets."dynu/password" = { }; + sops.secrets."system/pdf_decrypt_password" = { + owner = "kiskaadee"; + }; + + # Assemble the ddclient config file securely at boot time in /run/secrets/ + # Defaults to owner root:root (which avoids dynamic user evaluation issues) + sops.templates."ddclient.conf" = { + content = builtins.replaceStrings + [ "@dynu_user@" "@dynu_password@" "@dynu_domain@" ] + [ + config.sops.placeholder."dynu/user" + config.sops.placeholder."dynu/password" + config.sops.placeholder."dynu/domain" + ] + (builtins.readFile ../scripts/ddclient.conf); + }; + + # Enable ddclient and feed it the decrypted configuration template via systemd credentials + services.ddclient = { + enable = true; + configFile = "/run/credentials/ddclient.service/ddclient.conf"; + }; + + systemd.services.ddclient = { + serviceConfig = { + # Securely load the root-owned secret file into the dynamic ddclient service + LoadCredential = [ "ddclient.conf:${config.sops.templates."ddclient.conf".path}" ]; + }; + }; + + # Disable ddclient's automatic timer. + # This stops ddclient from polling every 10 minutes on its own. + systemd.timers.ddclient.enable = false; + + # Define the smart IP change detector service + systemd.services.dynu-monitor = { + description = "Dynu DDNS Smart IP Change Monitor"; + after = [ "network-online.target" ]; + wants = [ "network-online.target" ]; + path = with pkgs; [ + systemd # Required for systemctl + ]; + serviceConfig = { + Type = "oneshot"; + User = "root"; + Group = "root"; + StateDirectory = "dynu"; + Environment = "HISTORY_FILE=/var/lib/dynu/ip_history.jsonl"; + ExecStart = "${ipMonitorScript}/bin/dynu-ip-monitor"; + TimeoutSec = 30; + + # Hardening + NoNewPrivileges = true; + PrivateTmp = true; + ProtectSystem = "strict"; + ProtectHome = true; + ReadWritePaths = "/var/lib/dynu"; + }; + }; + + # Run the smart IP change monitor periodically (every 30 minutes) + systemd.timers.dynu-monitor = { + description = "Run Dynu IP monitor periodically"; + timerConfig = { + OnBootSec = "5min"; + OnUnitActiveSec = "30min"; + AccuracySec = "1min"; + Persistent = true; + }; + wantedBy = [ "timers.target" ]; + }; +} diff --git a/nixos/modules/homeserver.nix b/nixos/modules/homeserver.nix new file mode 100644 index 0000000..78df3c8 --- /dev/null +++ b/nixos/modules/homeserver.nix @@ -0,0 +1,118 @@ +# 🌐 Homeserver Core Environment Secrets & Systemd service configuration +# This NixOS module manages secrets and the systemd lifecycle for the core homeserver stack. + +{ config, lib, pkgs, ... }: + +let + # Declarative user database for Authelia + autheliaUsers = { + kiskaadee = { + displayName = "kiskaadee"; + email = "fcortesbio@gmail.com"; + groups = [ "admins" "dev" ]; + passwordPlaceholder = config.sops.placeholder."authelia/users/kiskaadee/password_hash"; + }; + misa = { + displayName = "misa"; + email = "icdf0728@gmail.com"; + groups = [ "users" ]; + passwordPlaceholder = config.sops.placeholder."authelia/users/misa/password_hash"; + }; + valenvg = { + displayName = "valenvg"; + email = "vegavalentina069@gmail.com"; + groups = [ "users" ]; + passwordPlaceholder = config.sops.placeholder."authelia/users/valenvg/password_hash"; + }; + }; + + renderUser = username: user: " " + username + ":\n" + + " displayname: \"" + user.displayName + "\"\n" + + " password: '" + user.passwordPlaceholder + "'\n" + + " email: \"" + user.email + "\"\n" + + " groups:\n" + + (lib.concatMapStringsSep "\n" (g: " - " + g) user.groups); + + renderedUsersYaml = "users:\n" + (lib.concatStringsSep "\n\n" (lib.mapAttrsToList renderUser autheliaUsers)) + "\n"; +in +{ + # Define the keys to decrypt from secrets.yaml + sops.secrets = lib.genAttrs [ + "dynu/api_key" + "traefik/acme_email" + "authelia/session_secret" + "authelia/storage_encryption_key" + "authelia/jwt_secret" + "authelia/users/kiskaadee/password_hash" + "authelia/users/misa/password_hash" + "authelia/users/valenvg/password_hash" + ] (name: { owner = "kiskaadee"; }); + + # Generate the unified environment file at runtime in /run/secrets/homeserver.env + sops.templates."homeserver.env" = { + owner = "kiskaadee"; + content = lib.generators.toKeyValue {} { + DOMAIN = "roadtotech.me"; + DOCKER_API_VERSION = "1.40"; + DYNU_API_KEY = config.sops.placeholder."dynu/api_key"; + ACME_EMAIL = config.sops.placeholder."traefik/acme_email"; + AUTHELIA_SESSION_SECRET = config.sops.placeholder."authelia/session_secret"; + AUTHELIA_STORAGE_ENCRYPTION_KEY = config.sops.placeholder."authelia/storage_encryption_key"; + AUTHELIA_IDENTITY_VALIDATION_RESET_PASSWORD_JWT_SECRET = config.sops.placeholder."authelia/jwt_secret"; + }; + }; + + # Generate the declarative Authelia user database file at runtime in /run/secrets/users.yml + sops.templates."users.yml" = { + owner = "kiskaadee"; + content = renderedUsersYaml; + }; + + # Define the declarative systemd service to manage the homeserver container stack + systemd.services.homeserver-core = { + description = "Homeserver Core Stack (Traefik, Authelia, Homepage, etc.)"; + after = [ "network-online.target" "docker.service" ]; + wants = [ "network-online.target" ]; + wantedBy = [ "multi-user.target" ]; + + serviceConfig = { + Type = "oneshot"; + RemainAfterExit = true; + WorkingDirectory = "/home/kiskaadee/Core"; + ExecStart = "${pkgs.docker-compose}/bin/docker-compose --env-file ${config.sops.templates."homeserver.env".path} up -d --remove-orphans"; + ExecStop = "${pkgs.docker-compose}/bin/docker-compose down"; + }; + }; + + # Declarative Dynamic GitOps Webhook Service (Internal Port 9000) + systemd.services.homelab-gitops = { + description = "Dynamic Homelab GitOps Webhook Dispatcher"; + after = [ "network-online.target" "docker.service" ]; + wants = [ "network-online.target" ]; + wantedBy = [ "multi-user.target" ]; + + path = with pkgs; [ git docker docker-compose python3 coreutils bash openssh ]; + + serviceConfig = { + Type = "simple"; + User = "kiskaadee"; + WorkingDirectory = "/home/kiskaadee/Core"; + ExecStart = "${pkgs.webhook}/bin/webhook -hooks ${pkgs.writeText "hooks.json" (builtins.toJSON [ + { + id = "deploy"; + execute-command = "/home/kiskaadee/Core/scripts/gitops_dispatcher.py"; + pass-arguments-to-command = [ + { source = "entire-payload"; } + ]; + command-working-directory = "/home/kiskaadee/Core"; + response-message = "Deployment payload dispatched successfully."; + } + ])} -port 9000 -verbose"; + Restart = "on-failure"; + RestartSec = "5s"; + }; + }; + + # Open ports in the firewall for Traefik, Gitea SSH, and GitOps Webhook Receiver + networking.firewall.allowedTCPPorts = [ 80 443 2223 9000 ]; +} diff --git a/nixos/modules/traefik-deployments.nix b/nixos/modules/traefik-deployments.nix new file mode 100644 index 0000000..795ef4b --- /dev/null +++ b/nixos/modules/traefik-deployments.nix @@ -0,0 +1,95 @@ +# 🌐 Traefik Deployments Environment Secrets configuration +# This NixOS module manages secrets and environment variables for the unified apps in /traefik-deployments + +{ config, lib, pkgs, ... }: + +{ + # Define the keys to decrypt from secrets.yaml (avoiding repeating the owner boilerplate) + sops.secrets = lib.genAttrs [ + "learning/turso_db_url" + "learning/turso_auth_token" + "mongo/root_username" + "mongo/root_password" + "ollama/api_key" + "postgres/user" + "postgres/password" + "postgres/db" + "gitea/runner_token" + ] (name: { owner = "kiskaadee"; }); + + # Generate the unified environment file at runtime in /run/secrets/traefik-deployments.env + sops.templates."traefik-deployments.env" = { + owner = "kiskaadee"; + content = lib.generators.toKeyValue {} { + # --- Core / Infrastructure Settings --- + PROXY_NETWORK = "proxy-net"; + CERT_RESOLVER = "myresolver"; + DOMAIN_SUFFIX = "roadtotech.me"; + + # --- Dashboard & Landing --- + DASHBOARD_DOMAIN = "dashboard.roadtotech.me"; + LANDING_DOMAIN = "roadtotech.me"; + + # --- Docs --- + DOCS_DOMAIN = "docs.roadtotech.me"; + DOCS_PROJECT_PATH = "/home/kiskaadee/Brain"; + + # --- Excalidraw --- + EXCALIDRAW_DOMAIN = "excalidraw.roadtotech.me"; + + # --- Gitea --- + GITEA_DOMAIN = "gitea.roadtotech.me"; + GITEA_SSH_DOMAIN = "gitea.roadtotech.me"; + GITEA_SSH_PORT = "2223"; + GITEA_AUTH_MIDDLEWARE = "https-redirect@docker"; + GITEA_RUNNER_TOKEN = config.sops.placeholder."gitea/runner_token"; + + # --- Jellyfin --- + JELLYFIN_SERVICE_NAME = "jellyfin"; + JELLYFIN_CONTAINER_NAME = "jellyfin"; + JELLYFIN_IMAGE_TAG = "latest"; + JELLYFIN_DOMAIN = "jellyfin.roadtotech.me"; + JELLYFIN_TZ = "UTC"; + JELLYFIN_PUID = "1000"; + JELLYFIN_PGID = "1000"; + JELLYFIN_MEDIA_PATH = "/media"; + JELLYFIN_HTTP_ENTRYPOINT = "web"; + JELLYFIN_HTTPS_ENTRYPOINT = "websecure"; + JELLYFIN_RATE_LIMIT_AVG = "100"; + JELLYFIN_RATE_LIMIT_BURST = "50"; + + # --- Learning Dashboard --- + LEARNING_SERVICE_NAME = "learning-hub"; + LEARNING_DOMAIN = "learning.roadtotech.me"; + LEARNING_APP_PORT = "8000"; + LEARNING_SOCKET_PROXY_NETWORK = "socket-net"; + LEARNING_DOCKER_HOST = "tcp://socket-proxy:2375"; + TURSO_DATABASE_URL = config.sops.placeholder."learning/turso_db_url"; + TURSO_AUTH_TOKEN = config.sops.placeholder."learning/turso_auth_token"; + + # --- Mermaid --- + MERMAID_DOMAIN = "mermaid.roadtotech.me"; + MERMAID_SERVICE_NAME = "mermaid"; + + # --- Minecraft --- + MINECRAFT_DOMAIN = "minecraft.roadtotech.me"; + + # --- MongoDB --- + MONGO_ROOT_USERNAME = config.sops.placeholder."mongo/root_username"; + MONGO_ROOT_PASSWORD = config.sops.placeholder."mongo/root_password"; + MONGO_DOMAIN = "mongodb.roadtotech.me"; + + # --- PostgreSQL --- + POSTGRES_USER = config.sops.placeholder."postgres/user"; + POSTGRES_PASSWORD = config.sops.placeholder."postgres/password"; + POSTGRES_DB = config.sops.placeholder."postgres/db"; + POSTGRES_DOMAIN = "pgsql.roadtotech.me"; + + # --- Ollama --- + OLLAMA_DOMAIN = "ollama.roadtotech.me"; + OLLAMA_API_KEY = config.sops.placeholder."ollama/api_key"; + OLLAMA_REPLICAS = "1"; + OLLAMA_DATA_VOLUME = "ollama_data"; + }; + }; +} diff --git a/nixos/scripts/ddclient.conf b/nixos/scripts/ddclient.conf new file mode 100644 index 0000000..c61a9b2 --- /dev/null +++ b/nixos/scripts/ddclient.conf @@ -0,0 +1,12 @@ +# General configuration +syslog=no +pid=/run/ddclient/ddclient.pid +cache=/var/lib/ddclient/ddclient.cache +usev4=webv4 + +# Provider definition using credentials decrypted at runtime +protocol=dyndns2 +server=api.dynu.com +login=@dynu_user@ +password=@dynu_password@ +@dynu_domain@ diff --git a/nixos/scripts/monitor.py b/nixos/scripts/monitor.py new file mode 100644 index 0000000..964ba00 --- /dev/null +++ b/nixos/scripts/monitor.py @@ -0,0 +1,205 @@ +""" +Dynu DDNS Smart IP Change Monitor and Updater. + +This script determines the current public IPv4 address by querying multiple +external resolvers sequentially. It compares the discovered IP against the last +recorded successful IP in a local history log. If a change is detected, it +triggers the `ddclient.service` on-demand to perform the DNS record update. + +This local-first state verification prevents making redundant API requests to +the DNS provider, avoiding rate-limiting, IP bans, or API abuse flags. +""" + +import urllib.request +import re +import json +import os +import subprocess +import sys +from datetime import datetime + +# History file location storing the transition log of public IP states. +# Defaults to a state directory managed securely by the systemd service unit. +HISTORY_FILE = os.environ.get("HISTORY_FILE", "/var/lib/dynu/ip_history.jsonl") + +# Fallback sequence of external services to discover the public WAN IP. +PROVIDERS = [ + "https://api.ipify.org", + "https://ifconfig.me/ip", + "https://icanhazip.com", + "https://wtfismyip.com/text" +] + + +def is_valid_public_ipv4(ip): + """ + Validates that a string is a properly formatted public IPv4 address. + + This function excludes standard private, loopback, link-local, and CGNAT + blocks to avoid recording temporary, local, or invalid network states. + """ + match = re.match(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$", ip) + if not match: + return False + octets = [int(x) for x in match.groups()] + if any(x > 255 for x in octets): + return False + a, b, c, d = octets + + # RFC 1918 Private ranges: 10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12 + if a == 10: + return False + if a == 192 and b == 168: + return False + if a == 172 and 16 <= b <= 31: + return False + + # Carrier-Grade NAT (CGNAT) RFC 6598: 100.64.0.0/10 + if a == 100 and 64 <= b <= 127: + return False + + # Loopback address range: 127.0.0.0/8 + if a == 127: + return False + + # Link-local addresses: 169.254.0.0/16 + if a == 169 and b == 254: + return False + + return True + + +def get_public_ip(): + """ + Queries public IP providers until a valid public IPv4 is returned. + + Returns: + str: The validated public IP string, or None if all providers fail. + """ + errors = [] + for provider in PROVIDERS: + try: + req = urllib.request.Request( + provider, + headers={ + 'User-Agent': 'Mozilla/5.0 (NixOS WAN Monitor)' + } + ) + # Fetch with 5s timeout to avoid hanging the systemd service + with urllib.request.urlopen(req, timeout=5) as response: + ip = response.read().decode('utf-8').strip() + if is_valid_public_ipv4(ip): + return ip + else: + errors.append(f"{provider}: invalid public IPv4 '{ip}'") + except Exception as e: + errors.append(f"{provider}: {str(e)}") + + print( + f"Error: All IP discovery providers failed. Details: {errors}", + file=sys.stderr + ) + return None + + +def get_last_recorded_ip(): + """ + Reads the history log to locate the last successful IP address. + + Returns: + str: The last successfully updated IP, or None if no log exists yet. + """ + if not os.path.exists(HISTORY_FILE): + return None + try: + with open(HISTORY_FILE, "r") as f: + lines = f.readlines() + if not lines: + return None + # Search backwards to find the most recent successful transition + for line in reversed(lines): + try: + entry = json.loads(line) + if entry.get("status") == "success": + return entry.get("ip") + except json.JSONDecodeError: + continue + except Exception as e: + print(f"Warning: Failed to read history file: {e}", file=sys.stderr) + return None + + +def record_ip(ip, status, details=None): + """ + Appends a new event entry into the JSONLines history registry. + """ + os.makedirs(os.path.dirname(HISTORY_FILE), exist_ok=True) + entry = { + "timestamp": datetime.utcnow().isoformat() + "Z", + "ip": ip, + "status": status + } + if details: + entry["details"] = details + try: + with open(HISTORY_FILE, "a") as f: + f.write(json.dumps(entry) + "\n") + except Exception as e: + print(f"Error: Failed to write to history file: {e}", file=sys.stderr) + + +def trigger_ddclient(): + """ + Invokes the systemd service unit for `ddclient` on-demand. + + Returns: + tuple: (bool, str) representing (success_boolean, error_details_string) + """ + try: + # Run ddclient as a one-shot activation via systemd to perform API call + res = subprocess.run( + ["systemctl", "start", "ddclient.service"], + capture_output=True, + text=True + ) + if res.returncode == 0: + return True, None + else: + err_msg = ( + f"systemctl exited with {res.returncode}: " + f"{res.stderr.strip()}" + ) + return False, err_msg + except Exception as e: + return False, str(e) + + +def main(): + """ + Orchestrator logic for DDNS state management. + """ + current_ip = get_public_ip() + if not current_ip: + sys.exit(1) + + last_ip = get_last_recorded_ip() + if current_ip == last_ip: + # IP matches last recorded working IP; do nothing to conserve quota + sys.exit(0) + + print(f"IP rotation detected! Old: {last_ip}, New: {current_ip}") + + # Trigger ddclient to perform the DNS record update + success, error_msg = trigger_ddclient() + if success: + print("Dynu DDNS update via ddclient triggered successfully.") + record_ip(current_ip, "success") + else: + err_msg = f"Error: Failed to trigger ddclient update: {error_msg}" + print(err_msg, file=sys.stderr) + record_ip(current_ip, "failed_update", details=error_msg) + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/nixos/secrets.yaml b/nixos/secrets.yaml new file mode 100644 index 0000000..0dff655 --- /dev/null +++ b/nixos/secrets.yaml @@ -0,0 +1,59 @@ +authelia: + session_secret: ENC[AES256_GCM,data:TmujJ9I51cQrzRMcvFkhFnG1CICebOM332NUTwXSj33niFdrV3xfHWR3h83/WcNk+M/i0AjcFtZ7fRYNW5VV2766p2BAfsaihSN8yQPrsQRNPyQKvSgij2xWL/B5I1a7NQGRh7xX6yiQYqaPzrwKnlcv8kmKp8aFPlkdmWYOCPc=,iv:Pcj6yu1MvZBJ0VPfuEO4RiTiE5SOULI/jGAz8dy/X4g=,tag:firz8cjG9HP8HEgKM4c53Q==,type:str] + storage_encryption_key: ENC[AES256_GCM,data:ycsfhh9cAsIbSEVaPvCH8ky0t+zayLtI6NVLcb+v2HIJMYSqD8eXu7JCvp5E0u1PkGTyaAoatXtcdChb2ABEiUNeqlOPXciF4ED+4yFAXftfMKy/M4AAYgp9jBA1v8JsE5mfBEOfmnBWV5SwGSaHBcQgUoJubKqcODPfHOmkKwg=,iv:1bgvgcClI+2VG6wXa5el5jfOrkCx+bj33VYiFdA1gas=,tag:0n7nJaZomtllFzSH2+Z8yw==,type:str] + jwt_secret: ENC[AES256_GCM,data:C1FnoRi49PSaIZNp+SAS6Q5+odYwai75OR4UfvGx1Jk8wb4nVDUASpaOgm7ZFJysTX4WjuQi99PYyG5GshlHoJ5dVbLSFpEq7MSSiY8tZA2PqnHmIODNYARfFw6lB7udPjz8ANyU2UcrnwRKXnDD+T2Pa1uL9joW5rg7vWZlRks=,iv:IDZ2/wbmCPoR14b1imZrTJR5LuQp6V91tcZ/Z5Znl0w=,tag:d0UQ49QcEqgD+PCIBoOJ7Q==,type:str] + users: + kiskaadee: + password_hash: ENC[AES256_GCM,data:/Sz5Z5YH2+ksjLw60/PkL/P3PJgYR4FEHV3CFlLShP1RASpJ+b3c8ywXlkUEKqNacfIkgaZsYsIpeNwApEYFt+4QLpDOPrX1wyF1sFnD5bDaeKJkV7wVgDO18D6LWJPX4A==,iv:TivrHulGSMtqDtWYyFHL36MHzLCymmceH0ptzF+dvBk=,tag:WQce4BeqHg4jS30gHSqZMw==,type:str] + misa: + password_hash: ENC[AES256_GCM,data:pYNPWzT1m+uYjrz8ZMWROz+q7qcp6+TaYsVmXT5899ItWVX5S2wF0cz08uTu3fveF3iHp27IWOwd3TBpmc0xmkYyeY31LCCMXrtRhuqVzfshVy29jHI/QNgeH4T3kU6UVg==,iv:7kS2+OiUWlApeReOunbJ1i4nYFpl9dcFryjTIOLUEe0=,tag:JYiV8/NJSzetvyzAzWMnWg==,type:str] + valenvg: + password_hash: ENC[AES256_GCM,data:GYf6/rvz2WK5w2T0usPbAP8LQY8EqOKPcFQJrHVEjjN/dVaQqg9IMm5cA0+dyYuJpW/+bdALdIDLjSYIFF3L7KgLij0jiIJhJxxV+7e1HIto+WhoavKBNfv5OREmW9cM7Q==,iv:zZeAL5v0YOHGca8ZebQirucUA7UtR5gnucKVfNJSzTc=,tag:cgm1qBzQKmpD5ttZKWHHjw==,type:str] +traefik: + acme_email: ENC[AES256_GCM,data:U2IPYioGlfgSpfZy5E+2+VM0iXQ=,iv:zQ5Txq9H7mF7GcaZfyPPjSQFKa0736/DI7Y4XARMFqM=,tag:7Q4YN9OPA1rRVpXuapewQQ==,type:str] +dynu: + api_key: ENC[AES256_GCM,data:f4dAZjCplklE08kll1yGuYYYDKKTVEwvSL0d6fM9K+g=,iv:xjR/5lNfRXxTPWJ+WM+/qzZGWTMf7iNua/FoGwTYXTg=,tag:PuZZWUJ+WoZVcWDVKwxM9g==,type:str] + user: ENC[AES256_GCM,data:RdKa9JmnllYQ,iv:2xW8vvzWvKp1rEV8G9fp+Jae38Wr3+lHAQ15htP3Sjs=,tag:tts/zHJqoBoK6vVnt7ho3A==,type:str] + domain: ENC[AES256_GCM,data:Towv0BFeoXhIaP/pzA==,iv:yzMv6t/Z3NEiE7t5u9lVA5siy5APsWHpdPvqYI8EmQU=,tag:8YTWCtA/sshOOLaHOMH+nw==,type:str] + password: ENC[AES256_GCM,data:oF8O3S5n2fuSFpgu8RVa0SwS4U4yYl/I7EMRTt640SQ=,iv:x0npliyj1cZocDce3hofvJYuQbXGOu+EU04GwR48cD4=,tag:ddNmxWp1uL2POW5mXdqfVQ==,type:str] +postgres: + user: ENC[AES256_GCM,data:ifJ3KSf6E6EQ,iv:Ryu/fce3mMRItSoRmwC6/HFWBebT3UXAwccfKMM+B1s=,tag:53ct7ZiF6UmklvPw0oeajw==,type:str] + password: ENC[AES256_GCM,data:wbLdF/1RZwL6fY/IXJdT,iv:5Xk0B0qtDh0hoAKDtwpzwKdhQHhsLvlsnHiwMJP9VeE=,tag:BGlHuEHp0YucoJopg1rzBQ==,type:str] + db: ENC[AES256_GCM,data:zBgGgioMBlVhUw==,iv:4X86eXVILuf98st1po5ipvEUDE2UG9jEPOso7CGR48k=,tag:ZXng+qF6/PUjP6D+Y/AC6w==,type:str] +mongo: + root_username: ENC[AES256_GCM,data:ImHe4j6Botsc,iv:dEXIA746kuh9//SLQO+RfDxIpObMMPZ2wfjgiwouS9Q=,tag:sD2uZKtwgbOgnKffv7DD4g==,type:str] + root_password: ENC[AES256_GCM,data:hETEsUQ+EMnV2rN+ZoOd,iv:8Zt1RLAOm6CCt8W/ie1IC+3PXs2qGzcLCTGTjNxWkI0=,tag:Q9iowfgg5JjaMekRCdUizA==,type:str] +ollama: + api_key: ENC[AES256_GCM,data:D2KSzK6WP9Xstx2l5A3I,iv:DbEnYwhrcVMWPipwfGQ1cvUOhZuB4Q64vCDcutb24Nw=,tag:V4KIOKM7in1i8rTNDLIzZA==,type:str] +gitea: + runner_token: ENC[AES256_GCM,data:aFk3l8rah+lj5iNVDT2RXF2Ie5aqwcBUi9UPjsWv0aRM+i97kYtybA==,iv:pkJpmgt5goEHotx3sCbw6jBy8detOwhaE77yO+NTQ5g=,tag:nLVNSwH1bfAq+gduwgRJuQ==,type:str] +learning: + turso_db_url: ENC[AES256_GCM,data:DveoFqwgimUHJv48Sozh2XqT7Ha9DeX3VAslT7SrqSVHab5RPlEujF+eIHyvAUiE81A=,iv:PgWZMty5hBUsmRJW85xilcvIMO/j54WY249Jsw6LfiM=,tag:osYPQc/Q9734L0FUo9hOCQ==,type:str] + turso_auth_token: ENC[AES256_GCM,data:lRdFDrsKWv90QSvNvYjqp07jU7DcWfrNlpg0bVljbOizixgstnFF70jjafN/QK4kId0nSJTx1DFlsTy7vG8+M00+UYl8SWDW7uTq/Ll1UGkaYinkhKFLNKUHXg5SUTfH3UA+nPBlZSNoZe6kdBgrt35TuV78lI/eUkxpVOI3D/70B6BP2DR4zmb70GztcxUY3e7xkGtVkCbyJd+BY8YOep/MgYvYg512LjESFwL/rJtJBYnh8XtQMcIDVDxRO5hGiy66xpXE4IC3wTPr4+/ZWS00H6VQccUcL0QVEVBkq+c9iytUlcTzTa7FkcYyiBnnlp1XGsk7OaE0E/VESaSaiUpQ6YQY7AllPTmhHs0uo+3KMbttjFLr,iv:OoPEVzYsmbdS2Po8C/lxo53UWxzA3gbPkrP3HZLB6Jo=,tag:1YKmvjWf5o3XZo40BZ6IWw==,type:str] +system: + gh_repo_token: ENC[AES256_GCM,data:QAsmG5iQQJ4TUhtrIbkq3wlw4JWbj2tFX6u2BbdB4werXfWyak8sdw==,iv:orGtlDW71QHDRSTED1xNfdOggF61hHsbGztWOUSdY+Y=,tag:4xe1I+hNjxWLc16BW4yTLA==,type:str] + pdf_decrypt_password: ENC[AES256_GCM,data:n3XTANd+PbejUw==,iv:y2VIabyv/DfTgztbjS6M/xIfRNKOL+U+r3eXsal32OQ=,tag:oFpXg2E9dDM5dwkjSZkLgw==,type:str] +sops: + age: + - enc: | + -----BEGIN AGE ENCRYPTED FILE----- + YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBkeEdCUncxWS9CUDJmbFow + THJpbE9tSmtZcURMcXoyYnd5eHlrcVhNdURrCjJBSFNBTnVpRE9SdkkyWXAwRFFo + Um5UUDFTVVl2ZDBBT1hNMHdQZ0RLYjAKLS0tIDUrS3g2a0QralpuN2hiMHRkRVN6 + MUdvK0FTemxZeGpPTUJiRkcrdWFCL2cKm7EEdZpYdoqQHgTNN1NkR+8xBzYj3ayx + 2zp9GAJgiEz+XaRkVi52JeDkEr2NuZR8WvcF0hvDMuFBslV6N9JZ+g== + -----END AGE ENCRYPTED FILE----- + recipient: age18q3lr2z4yeg2f86my42ym4hx0dvcwgjshmchyhdkgwvf4k37dsyq3mcjse + - enc: | + -----BEGIN AGE ENCRYPTED FILE----- + YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSAwWjFNOERYbTg4RWQxS3ox + cDFycmFkaFRvaHg2aXQzTlk4QTVCYVc1ejNzCjR0bUJEc3ZiaHo2V21xYTlsMGgv + ajNPelFUT3JucFRFaDBkeGtVS0trdFEKLS0tIEVtdFZsUHZKNkFlL0NHUnF2UG5s + eEpDb1VLZ2dCVERQUXl5enhZYlZaR1UK8xnixMh5Xk5SkeHj30wPb5wbsKeWxh80 + yvBksdjSVYITIR6E6sZJx4ujk8Gmu64UsHwxtASMZRQ60sUjLCo8+A== + -----END AGE ENCRYPTED FILE----- + recipient: age1pln9sxy5j93lklqklfwp3qepx7x4cs4y2w63n9y3ykt68qgra5ysqleesg + lastmodified: "2026-09-11T19:59:23Z" + mac: ENC[AES256_GCM,data:BcBncbSLf5CdYQxLn5THA6aMyxqipHpTwTgPOSZXf4B8PwO7yH4J7mL/sKEZ08448nAUaOABOrgFHoLlvVzGrUVJegRC/G9OgFQT8A4v1Dkq0yx0VSplMtf2q4ylyTjLHQb5bd4r4OzfBNFjmruyrZHS3ydxn8gfbgOft50w2vM=,iv:dTzR9j4crCaaG/wjMRxiGjVZMyBNOCN+qKlSN34m0m8=,tag:D8go58ulc1nu5biQWq1TpA==,type:str] + unencrypted_suffix: _unencrypted + version: 3.13.3