From 46049df416b2fc3968a315cbd9dddb4a72464bf3 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Fri, 4 Sep 2026 13:24:39 -0500 Subject: [PATCH] feat(nixos): refactor dedicated headless server profile and install SOPS in user space --- .sops.yaml | 2 +- README.md | 33 ++-- flake.nix | 34 +++- home.nix | 15 +- hosts/desktop/home.nix | 9 +- hosts/laptop/home.nix | 7 +- hosts/server/configuration.nix | 70 ++++++++ hosts/server/ddclient.conf | 12 ++ hosts/server/dynu.nix | 92 +++++++++++ hosts/server/hardware-configuration.nix | 41 +++++ hosts/server/home.nix | 14 ++ hosts/server/homeserver.nix | 68 ++++++++ hosts/server/monitor.py | 205 ++++++++++++++++++++++++ hosts/server/secrets.yaml | 42 +++++ hosts/server/traefik-deployments.nix | 96 +++++++++++ modules/user/base.nix | 2 +- modules/user/graphical.nix | 64 +------- modules/user/neovim.nix | 59 +++++++ 18 files changed, 775 insertions(+), 90 deletions(-) create mode 100644 hosts/server/configuration.nix create mode 100644 hosts/server/ddclient.conf create mode 100644 hosts/server/dynu.nix create mode 100644 hosts/server/hardware-configuration.nix create mode 100644 hosts/server/home.nix create mode 100644 hosts/server/homeserver.nix create mode 100644 hosts/server/monitor.py create mode 100644 hosts/server/secrets.yaml create mode 100644 hosts/server/traefik-deployments.nix create mode 100644 modules/user/neovim.nix diff --git a/.sops.yaml b/.sops.yaml index 6f193d0..cb2b38c 100644 --- a/.sops.yaml +++ b/.sops.yaml @@ -3,7 +3,7 @@ keys: - &desktop age18q3lr2z4yeg2f86my42ym4hx0dvcwgjshmchyhdkgwvf4k37dsyq3mcjse creation_rules: - - path_regex: hosts/desktop/secrets\.yaml$ + - path_regex: hosts/(desktop|server)/secrets\.yaml$ key_groups: - pgp: [] age: diff --git a/README.md b/README.md index 4c5bdca..ab8c260 100644 --- a/README.md +++ b/README.md @@ -12,19 +12,26 @@ This configuration maintains a strict separation between global system defaults, graph TD A[flake.nix Entrypoint] --> B{Host Configuration} - B -->|desktop| C[hosts/desktop] + B -->|server| S_HOST[hosts/server] + B -->|desktop (legacy)| C[hosts/desktop] B -->|laptop| D[hosts/laptop] + S_HOST --> S1[hardware-configuration.nix] + S_HOST --> S2[configuration.nix] + S_HOST --> S3[home.nix (CLI-only)] + S_HOST --> S4[dynu.nix + monitor.py] + S_HOST --> S5[homeserver.nix + traefik-deployments.nix] + C --> C1[hardware-configuration.nix] C --> C2[configuration.nix] C --> C3[home.nix] - C --> C4[dynu.nix + monitor.py] D --> D1[hardware-configuration.nix] D --> D2[configuration.nix] D --> D3[home.nix] - C3 --> H[home.nix base] + S3 --> H[home.nix base] + C3 --> H D3 --> H H --> M[modules/user] @@ -34,16 +41,20 @@ graph TD ### Directory Structure -* [flake.nix](flake.nix) — Main entry point defining dependencies (inputs) and system host targets. +* [flake.nix](flake.nix) — Main entry point defining dependencies (inputs) and system host targets (`server`, `desktop`, `laptop`). * [home.nix](home.nix) — Global Home Manager declaration defining the user context (`kiskaadee`). * [hosts/](hosts/) — Specific hardware configuration files and profiles. - * [hosts/desktop/](hosts/desktop/) — Configuration for the main workstation: - * [configuration.nix](hosts/desktop/configuration.nix) — Main desktop NixOS config. - * [dynu.nix](hosts/desktop/dynu.nix) — Service settings triggering Dynu DNS. - * [homeserver.nix](hosts/desktop/homeserver.nix) — Headless home server specialisation profile (`server-on` / `server-off`). - * [traefik-deployments.nix](hosts/desktop/traefik-deployments.nix) — Traefik edge proxy, SSL certs, and microservice definitions (`appctl`). - * [monitor.py](hosts/desktop/monitor.py) — Python script checking for public WAN IP rotations. - * [secrets.yaml](hosts/desktop/secrets.yaml) — Encrypted host credentials. + * [hosts/server/](hosts/server/) — Dedicated headless homelab server configuration: + * [configuration.nix](hosts/server/configuration.nix) — Headless server NixOS config (power-tuned, no GUI, no greeter). + * [home.nix](hosts/server/home.nix) — Pure CLI user environment with server diagnostic tools (`htop`, `iotop`, `ncdu`). + * [dynu.nix](hosts/server/dynu.nix) — Service settings triggering Dynu DDNS. + * [homeserver.nix](hosts/server/homeserver.nix) — Core services declarative systemd service. + * [traefik-deployments.nix](hosts/server/traefik-deployments.nix) — Edge proxy secrets and microservice templates. + * [monitor.py](hosts/server/monitor.py) — Python script checking for public WAN IP rotations. + * [secrets.yaml](hosts/server/secrets.yaml) — Encrypted server credentials. + * [hosts/desktop/](hosts/desktop/) — Legacy dual-mode workstation configuration: + * [configuration.nix](hosts/desktop/configuration.nix) — Main desktop NixOS config with specialisation. + * [home.nix](hosts/desktop/home.nix) — Hyprland desktop environment settings. * [hosts/laptop/](hosts/laptop/) — Configuration for the mobile workstation: * [configuration.nix](hosts/laptop/configuration.nix) — Main laptop NixOS config. * [home.nix](hosts/laptop/home.nix) — Niri-based workspace environment settings. diff --git a/flake.nix b/flake.nix index 69d5fd3..fe6f97e 100644 --- a/flake.nix +++ b/flake.nix @@ -67,8 +67,33 @@ outputs = { self, nixpkgs, home-manager, dms, dgop, dank-greeter, dankcalendar, danksearch, zen-browser, antigravity, ...}@inputs: { nixosConfigurations = { - # 🖥️ DESKTOP HOST - # Target workstation running Hyprland as the window manager. + # 🌐 SERVER HOST (Dedicated Headless Homelab Node) + # Production server host running Docker, Traefik, SOPS secrets, and DDNS. + server = nixpkgs.lib.nixosSystem { + system = "x86_64-linux"; + specialArgs = { inherit inputs; }; + modules = [ + ./hosts/server/hardware-configuration.nix + ./hosts/server/configuration.nix + inputs.sops-nix.nixosModules.sops + + home-manager.nixosModules.home-manager { + home-manager.useGlobalPkgs = true; + home-manager.useUserPackages = true; + home-manager.backupFileExtension = "backup"; + home-manager.extraSpecialArgs = { inherit inputs; }; + home-manager.users.kiskaadee = { + imports = [ + ./home.nix + ./hosts/server/home.nix + ]; + }; + } + ]; + }; + + # 🖥️ DESKTOP HOST (Legacy Dual-Mode Workstation) + # Workstation running Hyprland with specialisation fallback. desktop = nixpkgs.lib.nixosSystem { system = "x86_64-linux"; specialArgs = { inherit inputs; }; # Pass flake inputs into submodules (e.g. system/base.nix) @@ -95,9 +120,8 @@ ]; }; - # 💻 LAPTOP HOST - # Target laptop workstation. Intended to run Niri window manager. - # Shares modules/ base, but customizes graphical desktop components. + # 💻 LAPTOP HOST (Mobile Workstation) + # Target laptop workstation running Niri window manager. laptop = nixpkgs.lib.nixosSystem { system = "x86_64-linux"; specialArgs = { inherit inputs; }; diff --git a/home.nix b/home.nix index 6bb4599..2a15df6 100644 --- a/home.nix +++ b/home.nix @@ -1,15 +1,13 @@ -# 🏠 Home Manager Configuration Entrypoint -# This module defines the user-space environment config for 'kiskaadee' -# across all systems (desktop and laptop). +# 🏠 Home Manager Base Configuration Entrypoint +# Shared user environment foundations (Git, Shell, Neovim, Terminal) across all systems. { config, pkgs, ... }: { - # Import user-specific modules + # Import core user-specific modules imports = [ - ./modules/user/base.nix # Core shell configurations, utilities, git aliases - ./modules/user/apps.nix # User applications (e.g. Zen Browser, media players, SDKs) - ./modules/user/graphical.nix # Graphical user apps (Neovim configuration, window manager targets) + ./modules/user/base.nix # Core shell configurations, utilities, git aliases, SOPS & age + ./modules/user/neovim.nix # Neovim configuration, plugins, tree-sitter, LSP, DAP ./modules/user/terminal.nix # Terminal emulators and multiplexers (Alacritty, Tmux, Starship) ]; @@ -23,9 +21,8 @@ ]; # The state version of Home Manager that this configuration is compatible with. - # Avoid changing this value even if you upgrade NixOS. home.stateVersion = "26.05"; - # Enable Home Manager to manage itself (creates `home-manager` command) + # Enable Home Manager to manage itself programs.home-manager.enable = true; } diff --git a/hosts/desktop/home.nix b/hosts/desktop/home.nix index 1c95e30..7414c2a 100644 --- a/hosts/desktop/home.nix +++ b/hosts/desktop/home.nix @@ -1,10 +1,15 @@ # 🏠 Desktop Host-Specific Home Manager Configuration -# This module defines user-space environment configs unique to the desktop host. +# Graphical workstation environment for legacy desktop host. { config, pkgs, ... }: { - # Host-specific package installations for desktop (Hyprland environment only) + imports = [ + ../../modules/user/apps.nix + ../../modules/user/graphical.nix + ]; + + # Host-specific package installations for desktop (Hyprland environment) home.packages = with pkgs; [ grimblast # Screenshot utility for Hyprland obs-studio # High-feature video capture and streaming studio diff --git a/hosts/laptop/home.nix b/hosts/laptop/home.nix index 375900c..d591f65 100644 --- a/hosts/laptop/home.nix +++ b/hosts/laptop/home.nix @@ -1,9 +1,14 @@ # 🏠 Laptop Host-Specific Home Manager Configuration -# This module defines user-space environment configs unique to the laptop host. +# Graphical workstation environment for Niri-powered mobile laptop. { config, pkgs, ... }: { + imports = [ + ../../modules/user/apps.nix + ../../modules/user/graphical.nix + ]; + # Host-specific package installations for laptop workstation home.packages = with pkgs; [ obs-studio # High-feature video capture and streaming studio diff --git a/hosts/server/configuration.nix b/hosts/server/configuration.nix new file mode 100644 index 0000000..b87ab8b --- /dev/null +++ b/hosts/server/configuration.nix @@ -0,0 +1,70 @@ +# 🌐 Server Machine Configuration (Headless Homelab Node) +# This file defines host-specific system configurations for the dedicated Server environment. + +{ config, lib, pkgs, ... }: + +{ + imports = [ + ./hardware-configuration.nix # Server-specific disk and CPU configuration + ../../modules/system/base.nix # General hardware-agnostic OS settings + ./dynu.nix # Dynu DDNS update service + ./traefik-deployments.nix # Traefik deployments secrets module + ./homeserver.nix # Homeserver core services module + ]; + + # Enable experimental Nix features + nix.settings.experimental-features = [ "nix-command" "flakes" ]; + + # System-wide fonts + fonts.packages = with pkgs; [ + nerd-fonts.fira-code + nerd-fonts.jetbrains-mono + ]; + + # EFI bootloader configuration + boot.loader.systemd-boot.enable = true; + boot.loader.efi.canTouchEfiVariables = true; + + # Network identification + networking.hostName = "server"; + + # Define the main user profile + users.users.kiskaadee = { + isNormalUser = true; + extraGroups = [ + "wheel" # Enable sudo access + "docker" # Allows running docker commands without sudo + "networkmanager" # Allows modifying network configurations + ]; + }; + + # Dynamic binary execution support + programs.nix-ld = { + enable = true; + libraries = with pkgs; [ + stdenv.cc.cc.lib + zlib + glib + ]; + }; + + # Headless Server Optimizations: + # Disable peripheral hardware & desktop services + services.pipewire.enable = lib.mkForce false; + services.printing.enable = lib.mkForce false; + hardware.bluetooth.enable = lib.mkForce false; + services.blueman.enable = lib.mkForce false; + services.greetd.enable = lib.mkForce false; + + # Disable power-saving suspend/sleep/hibernate behaviors to keep homelab always active + systemd.targets.sleep.enable = lib.mkForce false; + systemd.targets.suspend.enable = lib.mkForce false; + systemd.targets.hibernate.enable = lib.mkForce false; + systemd.targets.hybrid-sleep.enable = lib.mkForce false; + + # Kernel-level power management tuning + powerManagement.powertop.enable = true; + + # Rebuild/State version. Do not modify. + system.stateVersion = "26.05"; +} diff --git a/hosts/server/ddclient.conf b/hosts/server/ddclient.conf new file mode 100644 index 0000000..c61a9b2 --- /dev/null +++ b/hosts/server/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/hosts/server/dynu.nix b/hosts/server/dynu.nix new file mode 100644 index 0000000..071d0e2 --- /dev/null +++ b/hosts/server/dynu.nix @@ -0,0 +1,92 @@ +# 🌐 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 ./monitor.py); +in +{ + # 1. Load the encrypted secrets file + sops.defaultSopsFile = ./secrets.yaml; + sops.defaultSopsFormat = "yaml"; + + # Define the keys to decrypt + sops.secrets.dynu_user = { }; + sops.secrets.dynu_domain = { }; + sops.secrets.dynu_password = { }; + sops.secrets.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 ./ddclient.conf); + }; + + # 2. 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}" ]; + }; + }; + + # 3. Disable ddclient's automatic timer. + # This stops ddclient from polling every 10 minutes on its own. + systemd.timers.ddclient.enable = false; + + # 4. 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"; + }; + }; + + # 5. 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/hosts/server/hardware-configuration.nix b/hosts/server/hardware-configuration.nix new file mode 100644 index 0000000..0b10a8a --- /dev/null +++ b/hosts/server/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/hosts/server/home.nix b/hosts/server/home.nix new file mode 100644 index 0000000..e0ba747 --- /dev/null +++ b/hosts/server/home.nix @@ -0,0 +1,14 @@ +# 🏠 Server Host-Specific Home Manager Configuration +# Pure CLI environment for headless server operation. + +{ config, pkgs, ... }: + +{ + # Server CLI packages + home.packages = with pkgs; [ + htop + iotop + iftop + ncdu + ]; +} diff --git a/hosts/server/homeserver.nix b/hosts/server/homeserver.nix new file mode 100644 index 0000000..3ffcbe7 --- /dev/null +++ b/hosts/server/homeserver.nix @@ -0,0 +1,68 @@ +# 🌐 Homeserver Core Environment Secrets & Systemd service configuration +# This NixOS module manages secrets and the systemd lifecycle for the core homeserver stack. + +{ config, lib, pkgs, ... }: + +{ + # 1. Load the encrypted secrets file + sops.defaultSopsFile = ./secrets.yaml; + sops.defaultSopsFormat = "yaml"; + + # Define the keys to decrypt from secrets.yaml + sops.secrets = lib.genAttrs [ + "dynu_api_key" + "acme_email" + "authelia_session_secret" + "authelia_storage_encryption_key" + "authelia_identity_validation_reset_password_jwt_secret" + "authelia_user_kiskaadee_password_hash" + ] (name: { owner = "kiskaadee"; }); + + # 2. 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.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_identity_validation_reset_password_jwt_secret; + }; + }; + + # Generate the declarative Authelia user database file at runtime in /run/secrets/users.yml + sops.templates."users.yml" = { + owner = "kiskaadee"; + content = '' + users: + kiskaadee: + displayname: "Kiskaadee" + password: "${config.sops.placeholder.authelia_user_kiskaadee_password_hash}" + email: "fcortesbio@gmail.com" + groups: + - admins + - dev + ''; + }; + + # 3. 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"; + }; + }; + + # 4. Open ports in the firewall for Traefik + networking.firewall.allowedTCPPorts = [ 80 443 ]; +} diff --git a/hosts/server/monitor.py b/hosts/server/monitor.py new file mode 100644 index 0000000..964ba00 --- /dev/null +++ b/hosts/server/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/hosts/server/secrets.yaml b/hosts/server/secrets.yaml new file mode 100644 index 0000000..8a4a3bd --- /dev/null +++ b/hosts/server/secrets.yaml @@ -0,0 +1,42 @@ +dynu_user: ENC[AES256_GCM,data:wDnJP2jHasV4,iv:7yk+J9tO9yqwe3POjFUTkP10I0gp1eEEQPvs4SJzBd0=,tag:98+v/rJGrTDTrxAQqhVomA==,type:str] +dynu_domain: ENC[AES256_GCM,data:bZGnwbQEGVWnTRe7aWMSAMuhsZcIcmb2,iv:nWQzYtJeLYbtqlfe2hDMvtksFGuJ76Qjm+lnG7X2zgo=,tag:65UFCJl4JueHvkiRwcwdjQ==,type:str] +dynu_password: ENC[AES256_GCM,data:F+YtoH6rJov2tgDdrIBGQ99b66PfJhUH0rybYhiF9ck=,iv:3o7vaYT8lNwn0fDt3opHtg5OGKkSxF8RkONTbFGe6Hw=,tag:T5EnMSwGHwAtfK1mS6FvMQ==,type:str] +dynu_api_key: ENC[AES256_GCM,data:4v2mHY8gXIYfiEDjTcDYxhVXc5Lb/szA40oLOvwltGE=,iv:cq7pYGmN7lIWQYG5x+kaoH3GbdAb7MEufdHEMwaeFnA=,tag:sUTgBFcMGRMFgDzgDobsKw==,type:str] +pdf_decrypt_password: ENC[AES256_GCM,data:8lh3pW2rMFs9AA==,iv:4+e0urvjYmdZ4/c0KcD7v9Ps8nKvopdYquwaMlYi2xQ=,tag:XHUESw6g1h1tR4EHrD4SaQ==,type:str] +learning_turso_db_url: ENC[AES256_GCM,data:yV3wJI7Y5kymKjaWZ7i2Ywm7N3vSMO2ApJZALJbGVxsyIs77Z336Rljvf90hbuaTKnY=,iv:Bx2m1NpDDRU2lhiwRRlEZrhFzpNqMCDx4bbfHK63Fl8=,tag:xC7OeNC6+4Zk+IZxozWqgQ==,type:str] +learning_turso_auth_token: ENC[AES256_GCM,data:1fl1kIEw7Z/Xv4ilMRZIt8/ei42O7KSg/yjBs5sxTYVaLrC3GNsngXuTClti8x3AjNsVN39uK2fLI8pUjGb60u07448SlByeBRQkodX/PX7WycaRl3IJ+FlaZJ/DijK2L3AEvOlECs/0PGr7hkgnVnjjg9c2YK+mJuT3xqY5DPytMU7f4nMFM/o63qNffB/N+WtxMsrD5izsawe95Bf6YQvpH+ue4qNn+ZIFmu/MRdCEsLjIRT4rbG76G6iIbLCT2Hr3W1hrzrCPcJ1KvLsAeT97iyNvfDdEWIdpv3DWS8jptS/G9Xvd2xJ8FWkbulZYpHLcjs4nNI0vKULi8VRfJYLYWqZ0gjNb+lkrYt6QgD13VWoC5X/H,iv:sc7Ppa5Jbrnhw97OSMSBQUrnYPH9rJfo+QzeNCbwtIM=,tag:v3AAGyqW9ahXL+dnmDr8BA==,type:str] +mongo_root_username: ENC[AES256_GCM,data:9jIpJnClrLAc,iv:ZtOwIUdXZoY4168YWTCE1Vcz+fek1YHRsAAyFbgkU64=,tag:WmtiJ1sdeFSQxHz5k5I2dQ==,type:str] +mongo_root_password: ENC[AES256_GCM,data:fbtY9aMXhd8D4TL6s7Ce,iv:xXckK6Sbg1PB+1Cifq6WkHtIk9FMgZ3Yf2HdjxPO6vU=,tag:bmyC2dv+QAaoOff+ejw2/g==,type:str] +ollama_api_key: ENC[AES256_GCM,data:1vw8FayOxXv3kfy5xcUy,iv:2zgPy1GUfPtPCyFgtED0R6cPPFJmDdhDbVA+jnomG/k=,tag:3HOdQll25oMPx3jg7Mbrdg==,type:str] +postgres_user: ENC[AES256_GCM,data:81MBXlhjMgKd,iv:54hTY9wtxy16iB/P2QqRsIgdJZyLWYdjaWUqVQFOd74=,tag:Z/idYinY3lB1THGqG7UWAA==,type:str] +postgres_password: ENC[AES256_GCM,data:U2ttYoopG/Uc8HrX3kKq,iv:5pUV00FPcVtKsAx2M3HSUXxRhEXFZWWt9O97CRhKrkM=,tag:ZzbB3Ggu45sylveJcfqStw==,type:str] +postgres_db: ENC[AES256_GCM,data:DJCXJz4SSjcETw==,iv:pM2UfxK8yOL8XxbAZY6XQyNKVPRrrGwjxtM8F3XOCU0=,tag:DcCu/9L4pz7WAkF8WkKzCA==,type:str] +acme_email: ENC[AES256_GCM,data:nQwu6pSUVGwkoq3wvY1wKNMMvis=,iv:jDY32yCLQCruelmeZ1DaeFPoxMyM4/+Mpt6g5rsYrO8=,tag:ROcVL+/2zCzF8fId6MSlrg==,type:str] +authelia_session_secret: ENC[AES256_GCM,data:sz99LUaspa4PyTZb0ukBPKZ5uQoomEiDZ/+IxU9OxzLhBysZChTZ7nIMAmxnffbT6dHuWE3cvGntKAAOqx7DKpTOkk/YFZk31Z1FfYZ59csrIW9LChWc7EeM21SzS9Z+1jU9Zo5PBsK93X7E1m9OTKtinCwivb+hLa6AVpmdOm4=,iv:V+oxP22Nm3DyY6/SA61SrQoVwraixlM8RANQ9wejFnI=,tag:8bAuoJ6jkg5hsrzMna23vQ==,type:str] +authelia_storage_encryption_key: ENC[AES256_GCM,data:f/pHK6GORv8iHiQbDvybi/KShoKl9b3NJbfW6m8iBK4X0A9n9UiYj+LBRFY79xs78YvYj/fDROaWN1fQM6nXJf+HsUqZ7/V3cIfk8eQdYto1mVI53VByIAEURQopnb9/+ypAN61YnCwkL2CEm0ID/sOmbLVO/aQmK7ccuN9CP2I=,iv:BcoAkOdR/gGoiiP+KJNa0H/9rXpfZf2h8dT0sw5o9pU=,tag:DsPWeWABjZVvDHC5dE1XDA==,type:str] +authelia_identity_validation_reset_password_jwt_secret: ENC[AES256_GCM,data:HNK2JEBHQBWuNnuqiqyhbk3NOoRhV40C4H+aM7kbFl+Ag1u0Vh4yafpQuyhzBH/e2jb3KDDu12m/7u2jv8bTLFhlp3b91KeKLz4c1sVoMNRzGYzIyynx42KYutaFLH42sBVgOQ/sCw1ug+Plt2bGFMK20PODdNzFELStvk4qH1Q=,iv:6nqNlshXJoemh97LlpUCp2t/AmXmxzufzjRZYEJzGXc=,tag:ATA3lP2hQl+jFFUERIayTw==,type:str] +authelia_user_kiskaadee_password_hash: ENC[AES256_GCM,data:ZJvq9ocETSzIl3RH9Qg0Ls4p+9QCD1/e+g1uzpAKs6HZk0AjKtCrUtqxEUjqbPi3W9ymsXQzkurtfYRw47lqsom5yGoyW6Q1Tq19crCqibgn4DHc0XGp1uoIvtxUkDSijg==,iv:rsP/z/fwhJhJs7hH0Qx3ry7K++tmEiWke2MwNULHKWg=,tag:vA7cRip2+Y7ALPL/Kqo3uQ==,type:str] +sops: + age: + - enc: | + -----BEGIN AGE ENCRYPTED FILE----- + YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBGRUpiNDJVODBxZ3o0TGwv + MHNCU2lENkdXMGJVcW5DeDJjQjJCaExTR0VVCjlTbVF4VW9FR3Q0akwrNlZZR09V + Z2NYT2Q1bGtHdkhhNnJtdGVzVVJIZ2MKLS0tIHhkU1l0TDMxWUVEK280WVcxVk8w + Y0ZUZ0xRdXhTRGxGSk9lOE1Ha1l2MFUKxUhwgiNLkWuYcxq/4vKVJ/Kdot8b8fEh + DcZmV3Q+7hi2cZvkJ3MFEGNmESe7//bGHXDJOt7rEnCcjgbU+jPAug== + -----END AGE ENCRYPTED FILE----- + recipient: age16nr2t9jrw09kakuxy2vtvtgtwa9jvy5dmtge25rzlqelf5cjy4es46alu9 + - enc: | + -----BEGIN AGE ENCRYPTED FILE----- + YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSA0U3dFSTBxckZjTFpMYzIv + L2lwVk5HMk91YjdNejNGTkR0Uy9qR0pYVEJNCk5CQ2xLRS9rQnU5UzFzc2RzY1Rr + NUNCWlA0Nmg5VFVkTzBNVG8vaWZkMEEKLS0tIFFwdW0yVFJyQmdhMk9tcStURTFm + MjdVUVJEZHB1SUlGYVlNTDdER0lnb2cKbJ6sWXplLLph2o+0RbAk5DXPBk3Q9LaD + KHX+ZcBi2WoOtZJEs5G+Z6fGeZHjJ1X2JTCv9oINsppu8FUovkYX/A== + -----END AGE ENCRYPTED FILE----- + recipient: age18q3lr2z4yeg2f86my42ym4hx0dvcwgjshmchyhdkgwvf4k37dsyq3mcjse + lastmodified: "2026-08-11T16:01:34Z" + mac: ENC[AES256_GCM,data:PoTV9ffRfrA04oKQj57pAK3TeH4VRZ9IYxlt3qQ9ELM6fgc0+HxXYGF3XHwier1Qk8KieZtL1CeWsCwVSMIbvs6krDqqv7dSWoVs8re2cVlkSpa99eReR1wpbNBOvv2mAHBVUgMfQlht/GaBbwbswk9bnIUY5zB7AsqCSjSsPQE=,iv:49yMPyXAPeyp1Peq/L3ruLingnyWnaok4t05lSqEnTQ=,tag:PXuMC2ZjZ9eq2Xn2V+ubHQ==,type:str] + unencrypted_suffix: _unencrypted + version: 3.13.3 diff --git a/hosts/server/traefik-deployments.nix b/hosts/server/traefik-deployments.nix new file mode 100644 index 0000000..daea7e0 --- /dev/null +++ b/hosts/server/traefik-deployments.nix @@ -0,0 +1,96 @@ +# 🌐 Traefik Deployments Environment Secrets configuration +# This NixOS module manages secrets and environment variables for the unified apps in /traefik-deployments + +{ config, lib, pkgs, ... }: + +{ + # Load the encrypted secrets file + sops.defaultSopsFile = ./secrets.yaml; + sops.defaultSopsFormat = "yaml"; + + # 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" + ] (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_AUTH_MIDDLEWARE = "https-redirect@docker"; + + # --- 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/modules/user/base.nix b/modules/user/base.nix index 30474fe..c1dd00f 100644 --- a/modules/user/base.nix +++ b/modules/user/base.nix @@ -273,6 +273,6 @@ home.packages = with pkgs; [ ripgrep fd glow jq tree wl-clipboard sqlite python3 nodejs bc qpdf tty-clock grim slurp swappy libnotify uv - curl parallel tuxedo + curl parallel tuxedo sops age ]; } diff --git a/modules/user/graphical.nix b/modules/user/graphical.nix index 67148e0..72a4b66 100644 --- a/modules/user/graphical.nix +++ b/modules/user/graphical.nix @@ -1,10 +1,10 @@ # 🎨 User Graphical Module -# Configures graphical workspace tools, text editors, and session unit targets. +# Configures graphical workspace tools, GUI applications, and window manager session unit targets. +# Only imported by desktop and laptop profiles. + +{ inputs, pkgs, ... }: -{ inputs, pkgs, ...}: { - - # Graphical packages managed via Home Manager home.packages = with pkgs; [ inputs.zen-browser.packages.${pkgs.stdenv.hostPlatform.system}.default # Modern browser build @@ -36,64 +36,10 @@ # Disable pocket-telemetry "extensions.pocket.enabled" = false; "datareporting.healthreport.uploadEnabled" = false; - }; }; }; - - # Neovim configuration - programs.neovim = { - enable = true; - defaultEditor = true; # Make neovim the default `$EDITOR` - viAlias = true; # Symlink `vi` to `nvim` - vimAlias = true; # Symlink `vim` to `nvim` - - ## Core Editor Settings (Lua-based) - initLua = builtins.readFile ./config/nvim/init.lua; - - ## Declarative Plugin Management - plugins = with pkgs.vimPlugins; [ - # Color scheme loaded dynamically - { - plugin = catppuccin-nvim; - type = "lua"; - config = builtins.readFile ./config/nvim/catppuccin.lua; - } - - # Advanced Syntax Highlighting for developer workflows (Python, Rust, Java, Nix, KDL) - (nvim-treesitter.withPlugins (p: with p; [ - python - rust - nix - lua - java - javascript - typescript - markdown - kdl - toml - bash - ])) - - # LSP Configuration & Language Servers - { - plugin = nvim-lspconfig; - type = "lua"; - } - - # DAP (Debug Adapter Protocol) - { - plugin = nvim-dap; - } - { - plugin = nvim-dap-ui; - } - ]; }; - # Declarative configuration files for Neovim (lsp.lua & dap.lua loaded dynamically via init.lua) - home.file.".config/nvim/lsp.lua".source = ./config/nvim/lsp.lua; - home.file.".config/nvim/dap.lua".source = ./config/nvim/dap.lua; - # Declarative configuration files for Zed editor home.file.".config/zed/settings.json".source = ./config/zed/settings.json; home.file.".config/zed/themes".source = ./config/zed/themes; @@ -103,8 +49,6 @@ home.file.".config/niri/custom.kdl".source = ./config/niri/custom.kdl; # ⚙️ Systemd user session targets for window managers - # These targets allow user services (like DMS daemons, screenshot helpers) to bind - # to the graphical workspace startup cycle correctly. systemd.user.targets.hyprland-session = { Unit = { Description = "Hyprland graphical session"; diff --git a/modules/user/neovim.nix b/modules/user/neovim.nix new file mode 100644 index 0000000..8d72d56 --- /dev/null +++ b/modules/user/neovim.nix @@ -0,0 +1,59 @@ +# 🖋️ Neovim CLI & IDE Editor Configuration +# Shared across all host profiles (server, desktop, laptop). + +{ pkgs, ... }: + +{ + programs.neovim = { + enable = true; + defaultEditor = true; # Make neovim the default `$EDITOR` + viAlias = true; # Symlink `vi` to `nvim` + vimAlias = true; # Symlink `vim` to `nvim` + + ## Core Editor Settings (Lua-based) + initLua = builtins.readFile ./config/nvim/init.lua; + + ## Declarative Plugin Management + plugins = with pkgs.vimPlugins; [ + # Color scheme loaded dynamically + { + plugin = catppuccin-nvim; + type = "lua"; + config = builtins.readFile ./config/nvim/catppuccin.lua; + } + + # Advanced Syntax Highlighting for developer workflows (Python, Rust, Java, Nix, KDL) + (nvim-treesitter.withPlugins (p: with p; [ + python + rust + nix + lua + java + javascript + typescript + markdown + kdl + toml + bash + ])) + + # LSP Configuration & Language Servers + { + plugin = nvim-lspconfig; + type = "lua"; + } + + # DAP (Debug Adapter Protocol) + { + plugin = nvim-dap; + } + { + plugin = nvim-dap-ui; + } + ]; + }; + + # Declarative configuration files for Neovim (lsp.lua & dap.lua loaded dynamically via init.lua) + home.file.".config/nvim/lsp.lua".source = ./config/nvim/lsp.lua; + home.file.".config/nvim/dap.lua".source = ./config/nvim/dap.lua; +}