From ff3ab012f0ffb04176506bb7c76d8c7363a14cee Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Thu, 25 Jun 2026 16:43:35 -0500 Subject: [PATCH] docs(readme): restructure documentation and harden automation logic - Refactor README.md: Add architectural diagrams (Mermaid) and improve navigation through structured directory listings. - Harden `record.sh`: Add robust error handling, orphan process cleanup, and state metadata management. - Harden `monitor.py`: Add comprehensive docstrings and strict validation logic for public IPv4 ranges. - Improve tooling transparency: Link specialized scripts (DDNS, recording, git helpers) to their respective modules for easier discoverability. --- README.md | 218 +++++++++++--------- hosts/desktop/config/hypr/scripts/record.sh | 46 +++-- hosts/desktop/monitor.py | 66 +++++- 3 files changed, 219 insertions(+), 111 deletions(-) diff --git a/README.md b/README.md index 8ec0478..7d1ac15 100644 --- a/README.md +++ b/README.md @@ -1,127 +1,159 @@ -# ❄️ Declarative NixOS Workstation +# ❄️ Declarative NixOS Workstation Configuration -## πŸ“– Overview - -This repository contains a purely declarative, fully reproducible NixOS configuration tailored for modern software development and multi-host deployment. It serves as the single source of truth for managing a unified Wayland-native environment across different hardware profiles, ensuring identical terminal workflows, editor configurations, and core toolchains on every machine. - -The bash shell configuration is a modular port of the static Arch-based environment [bash-custom](https://github.com/kiskaadee/bash-custom). The desktop experience is designed to achieve visual and functional parity with [DankMaterialShell (DMS)](https://danklinux.com/docs/dankmaterialshell/). +This repository houses a purely declarative, reproducible NixOS configuration using Nix Flakes and Home Manager. It serves as the single source of truth for provisioning and managing high-performance Wayland-native workstation environments across desktop and laptop profiles. --- -## πŸ›‘ The Problem (Why this exists) +## πŸ—οΈ Repository Architecture -Traditional Linux distributions (like Arch Linux) rely on imperative package management and stateful configurations. Over time, this leads to: +This configuration maintains a strict separation between global system defaults, shared user configuration modules, and host-specific profiles to avoid redundancy. -* **Configuration Drift:** Packages and dotfiles drift out of sync between a desktop and a laptop. -* **Imperative Rot:** System stability degrades as manual tweaks, forgotten dependencies, and monolithic Bash configurations (`.bashrc` files spanning hundreds of lines) pile up. -* **Replication Friction:** Setting up a new machine requires manually executing scripts, remembering package names, and migrating complex configurations by hand. +```mermaid +graph TD + A[flake.nix Entrypoint] --> B{Host Configuration} + + B -->|desktop| C[hosts/desktop] + B -->|laptop| D[hosts/laptop] + + 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] + D3 --> H + + H --> M[modules/user] + C2 --> S[modules/system] + D2 --> S +``` + +### Directory Structure + +* [flake.nix](flake.nix) β€” Main entry point defining dependencies (inputs) and system host targets. +* [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. + * [monitor.py](hosts/desktop/monitor.py) β€” Python script checking for public WAN IP rotations. + * [secrets.yaml](hosts/desktop/secrets.yaml) β€” Encrypted host credentials. + * [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. +* [modules/](modules/) β€” Reusable, modular system and user configuration files: + * [modules/system/](modules/system/) β€” Global hardware settings, Docker, greetd, and audio: + * [base.nix](modules/system/base.nix) β€” System-wide terminal base. + * [graphical.nix](modules/system/graphical.nix) β€” System display and desktop styling modules. + * [modules/user/](modules/user/) β€” User environment settings: + * [base.nix](modules/user/base.nix) β€” Core CLI utilities, alias definitions, and fastfetch. + * [apps.nix](modules/user/apps.nix) β€” Packages including Zen Browser, Neovim, and Cloud SDKs. + * [terminal.nix](modules/user/terminal.nix) β€” Alacritty terminal emulator, Tmux configurations, and Starship. + * [shell/](modules/user/shell/) β€” Modular, domain-specific shell scripts natively compiled into the shell configuration: + * [git.sh](modules/user/shell/git.sh) β€” Automation helpers for Git staging, committing, and repositories. + * [jump.sh](modules/user/shell/jump.sh) β€” Interactive navigation helper scripts powered by `fzf` and `yazi`. + * [pdf.sh](modules/user/shell/pdf.sh) β€” Quick decryption of password-protected PDF files. + * [quicklinks.sh](modules/user/shell/quicklinks.sh) β€” Quick menu launcher for saved bookmarks and workflows. + * [wayland.sh](modules/user/shell/wayland.sh) β€” Utility to automatically pipe program stdout/stderr to the Wayland clipboard. --- -## 🎯 Goals +## πŸ› οΈ Specialized Shell & Script Automation -This repository solves these issues by treating the operating system as code, specifically focusing on: +### 1. Smart Dynamic DNS Monitor +The [monitor.py](hosts/desktop/monitor.py) daemon prevents redundant DNS updates by running a local-first check before contacting the provider API: -* **Deterministic Multi-Host Architecture:** Define a shared base system ([modules/](./modules)) while maintaining completely isolated hardware profiles and display managers for specific machines (e.g., Hyprland for the desktop, Niri for the laptop). -* **Frictionless Development:** Provide a pre-configured, battle-tested toolchain out of the box for backend and systems programming, specifically optimized for Python, Rust, and Java. -* **Modular Shell Environment:** Replace monolithic shell scripts with cleanly separated, single-purpose modules (Git workflows, Wayland clipboard utilities, fuzzy navigation). These are natively compiled into the environment via Nix without relying on brittle source chains. -* **Maintainability & Discoverability:** Utilize a logical, flat directory structure that avoids the "hyper-abstraction" trap of overly complex Nix flakes. If a configuration needs to be changed, its location should be immediately obvious. +```mermaid +flowchart TD + A[Timer triggers monitor script] --> B[Fetch public IP from seq. providers] + B --> C{Is public IPv4 valid?} + C -->|No| D[Log error & try next provider] + C -->|Yes| E[Retrieve last successful IP from local logs] + E --> F{Has IP changed?} + F -->|No| G[Exit cleanly] + F -->|Yes| H[Trigger ddclient.service via systemctl] + H --> I{Update successful?} + I -->|Yes| J[Write success status to ip_history.jsonl] + I -->|No| K[Write failed_update status & alert user] +``` + +* **Script Location:** [hosts/desktop/monitor.py](hosts/desktop/monitor.py) +* **Systemd Integration:** Managed via [hosts/desktop/dynu.nix](hosts/desktop/dynu.nix) which triggers the monitor service every 30 minutes. + +### 2. GPU-Accelerated Video Recording (`record.sh`) +* **Script Location:** [hosts/desktop/config/hypr/scripts/record.sh](hosts/desktop/config/hypr/scripts/record.sh) +* **Functionality:** Uses `wf-recorder` to record Wayland outputs. +* **Modes:** + * `area` β€” Manually drag and draw a target bounding box using `slurp`. + * `window` β€” Target coordinates dynamically parsed from `hyprctl activewindow`. + * `output` β€” Matches coordinates of the currently active focused monitor. + * `screen` β€” Default full layout grab. + * `audio` flag β€” Parses `wpctl` to dynamically resolve output system loopback paths from PipeWire/WirePlumber to include sound. + +### 3. Git Automation Shorthand (`git.sh`) +* **Script Location:** [modules/user/shell/git.sh](modules/user/shell/git.sh) +* **Features:** + * `gitignore ` β€” Appends pattern to project-root `.gitignore`, commits the change, and pushes to remote. + * `gacp ` β€” Shorthand to stage all edits, commit with a message, and push directly to the current branch. + * `new-repo ` β€” Scaffolds local files, runs git init, and pushes the project to GitHub using the `gh` CLI. --- -## 🚫 Non-Goals +## πŸ”’ Secrets Management (SOPS + age) -To keep the system fast and maintainable, this configuration explicitly avoids: +No plain text passwords, tokens, or private keys are committed to the public history. Secrets are stored inside encrypted `.yaml` assets decrypted dynamically on-demand at boot time using **`sops-nix`** and SSH host keys. -* **Legacy Display Protocols:** There is no support or fallback for X11; this is a pure Wayland environment. -* **Full Desktop Environments (DEs):** Avoiding bloated DEs (like GNOME or KDE) in favor of lightweight, composable window managers and standalone system monitors. -* **Over-Engineering Nix:** Avoiding deeply nested Nix functions or custom abstract configuration languages. The goal is to use standard NixOS modules and native file inclusion (`builtins.readFile`) to keep the codebase readable for standard Linux users. +```mermaid +graph LR + A[Encrypted secrets.yaml in Git] --> B(sops-nix on system boot) + C[Host SSH Private Key /etc/ssh/...] --> B + B --> D[Decrypted RAM filesystem /run/secrets/] + D --> E[Services read secrets securely] +``` ---- +### Adding and Modifying Secrets +1. Decrypt and open the host secrets file: + ```bash + nix-shell -p sops --run "sops hosts/desktop/secrets.yaml" + ``` +2. Save changes and exit. `sops` will automatically re-encrypt the file with the public keys defined in the root [.sops.yaml](.sops.yaml) configuration file. -## πŸ“‚ Architecture - -The repository relies on a standard Nix Flake structure to enforce isolation: - -* [flake.nix](./flake.nix): The entry point of the configuration. Defines system inputs, channels, dependencies (like DMS, `dgop`, etc.), and exposes desktop and laptop deployment targets. -* [home.nix](./home.nix): Home Manager entrypoint defining the user context (`kiskaadee`) and importing shared user-space configuration modules. -* [.sops.yaml](./.sops.yaml): Global rules and public age keys for decrypting repository secrets. -* [hosts/](./hosts): Machine-specific configurations. - * [hosts/desktop](./hosts/desktop): Target environment for the workstation. - * [desktop/configuration.nix](./hosts/desktop/configuration.nix): Desktop-specific packages and NixOS settings. - * [desktop/hardware-configuration.nix](./hosts/desktop/hardware-configuration.nix): Autogenerated hardware settings. - * [desktop/home.nix](./hosts/desktop/home.nix): Desktop-specific user settings (Hyprland and DankMaterialShell). - * [desktop/dynu.nix](./hosts/desktop/dynu.nix) & [monitor.py](./hosts/desktop/monitor.py): Smart Dynamic DNS IP change detector and updater. - * [desktop/secrets.yaml](./hosts/desktop/secrets.yaml): Encrypted secrets file (managed by `sops-nix`). - * `hosts/laptop`: Target environment for the laptop. - * `laptop/configuration.nix`: Laptop-specific NixOS settings. - * `laptop/hardware-configuration.nix`: Autogenerated hardware settings. - * [laptop/home.nix](./hosts/laptop/home.nix): Laptop-specific user settings (Niri WM placeholder). -* [docs/](./docs): Detailed architecture, setup guides, and cheatsheets. - * [docs/secrets-management.md](./docs/secrets-management.md): Secure credentials management using `sops-nix` and `age`. - * [docs/dynu-ip-monitor.md](./docs/dynu-ip-monitor.md): Smart Dynamic DNS IP monitor and updater script logic. - * [docs/tmux.md](./docs/tmux.md): Optimized Tmux terminal multiplexer configuration and keybindings guide. - * [docs/antigravity.md](./docs/antigravity.md): Technical details on the Google Antigravity CLI helper. -* [modules/](./modules): Shared configurations applied across hosts. - * [modules/system](./modules/system): Core OS-level settings (bootloaders, networking, audio, greetd login manager). - * [modules/system/base.nix](./modules/system/base.nix): Hardware-agnostic OS base configuration (Docker, Pipewire, SSH, greetd, environment variables). - * [modules/system/graphical.nix](./modules/system/graphical.nix): Settings for DMS (DankMaterialShell) daemon, system monitoring, and dynamic theming. - * [modules/user](./modules/user): User-space configurations (Home Manager, Neovim, Alacritty, Tmux, Starship, fastfetch). - * [modules/user/base.nix](./modules/user/base.nix): Core shell utilities, Git configuration, fastfetch dashboard, aliases, and shell integration. - * [modules/user/apps.nix](./modules/user/apps.nix): User packages (Zen Browser, GIMP, MPV, Cloud SDKs, credentials). - * [modules/user/graphical.nix](./modules/user/graphical.nix): Neovim configuration, Neovim plugins, and graphical session targets. - * [modules/user/terminal.nix](./modules/user/terminal.nix): Terminal emulator (Alacritty), multiplexer (Tmux), and cross-shell prompt (Starship). - * [modules/user/shell/](./modules/user/shell): Extracted, domain-specific shell scripts natively compiled into the shell configuration: - * [git.sh](./modules/user/shell/git.sh): Git helpers (`gitignore`, `gacp`, `new-repo`). - * [jump.sh](./modules/user/shell/jump.sh): Yazi and fzf-based quick navigation wrappers (`cnf`, `pj`, `jump`, etc.). - * [pdf.sh](./modules/user/shell/pdf.sh): Helper functions for decrypting PDFs using `qpdf`. - * [quicklinks.sh](./modules/user/shell/quicklinks.sh): Fzf interactive menu for running custom saved web links or commands. - * [wayland.sh](./modules/user/shell/wayland.sh): Wayland clipboard integration command wrapper (`wlc`). +For detailed steps on bootstrapping, key generation, and service decryption, see the [Secrets Management Guide](docs/secrets-management.md). --- ## πŸš€ Quick Start / Deployment -### 1. Clone the Configuration -Clone this repository to your home directory (usually target location is `~/Config`): +### 1. Installation +Clone the configuration workspace directly into your home folder: ```bash git clone https://github.com/kiskaadee/nixos-config.git ~/Config cd ~/Config ``` -### 2. Build and Switch the Configuration -To apply the configuration for the first time or rebuild after a change, run the `nixos-rebuild` command pointing to the host's flake target: +### 2. Deploy System Configurations +Rebuild and switch to the profile matching your active target host machine: -```bash -# Rebuild the system for the 'desktop' target -sudo nixos-rebuild switch --flake ~/Config#desktop -``` +* **Desktop Workstation:** + ```bash + sudo nixos-rebuild switch --flake ~/Config#desktop + ``` +* **Laptop Workstation:** + ```bash + sudo nixos-rebuild switch --flake ~/Config#laptop + ``` -*Note: For convenience, a shell alias `nix-switch` is pre-configured to automatically run this rebuild command for the current host name.* - -### 3. Updating Flake Inputs -To update all flake inputs (such as home-manager, nixpkgs, or dms): -```bash -nix flake update -``` +*Note: The user environment configures `nix-switch` as an alias to automatically build and switch using the current hostname.* --- -## πŸ—ΊοΈ Roadmap & Next Steps +## πŸ“š Reference Documentation -Here is the current status of features planned to complete the environment and prepare it for dual-host capability: - -### Phase 1: Complete DankMaterialShell (DMS) Integration -* [ ] **Adding Background Blur:** Configure Hyprland compositor to enable background blur under the shell and terminal elements ([DMS CLI Doctor - Compositor Checks](https://danklinux.com/docs/dankmaterialshell/cli-doctor#compositor-checks)). -* [ ] **Cups-pk-helper:** Enable and configure `cups-pk-helper` for privileged printer administration checks ([DMS CLI Doctor - Optional Features](https://danklinux.com/docs/dankmaterialshell/cli-doctor#optional-features)). -* [ ] **Set Core Fonts:** Ensure proper font styling settings: - * **Normal Font:** Configure *Inter Variable* as the default system-wide sans-serif font ([DMS Fonts](https://danklinux.com/docs/dankmaterialshell/cli-doctor#fonts)). - * **Monospace Font:** Ensure *Fira Code* is the primary system monospace font for coding. - -### Phase 2: Hardware & Display Greeter Polish -* [ ] **Bluetooth Adapter Configuration:** Enable Bluetooth services globally, configure power-on on boot, and enable media controls via Bluetooth. -* [ ] **Custom Greetd Configuration:** Clean up the console/login manager setup, styling `tuigreet` or auto-logging to the graphical environment cleanly. - -### Phase 3: Laptop Profile (Multi-Host Readiness) -* [x] Create `./hosts/laptop/configuration.nix` and `./hosts/laptop/hardware-configuration.nix`. -* [ ] Integrate the **Niri** compositor as the default desktop environment for the laptop while sharing 100% of the terminal, editor, toolchain, and styling modules. +* [Secrets Management Details](docs/secrets-management.md) β€” Secure storage configuration using `sops-nix` and `age`. +* [Smart DDNS Updater](docs/dynu-ip-monitor.md) β€” Under-the-hood details of the smart IP change detector and updater. +* [Tmux Terminal Multiplexer](docs/tmux.md) β€” Fast navigation bindings, layouts, and pane splits guide. +* [Google Antigravity Setup](docs/antigravity.md) β€” Technical instructions for packaging and using the Antigravity agent CLI on NixOS. diff --git a/hosts/desktop/config/hypr/scripts/record.sh b/hosts/desktop/config/hypr/scripts/record.sh index b7d5a0a..8e3caad 100755 --- a/hosts/desktop/config/hypr/scripts/record.sh +++ b/hosts/desktop/config/hypr/scripts/record.sh @@ -1,30 +1,40 @@ #!/usr/bin/env bash -# Screen Recording script for Hyprland using wf-recorder -# Usage: record.sh [area|window|output|screen] [audio] +# πŸ“Ή Hyprland Screen Recording Utility +# Leverages 'wf-recorder' for GPU-accelerated video recording and pipewire audio routing. +# Supports capturing specific bounding boxes, active windows, virtual outputs, or full displays. +# +# Usage: +# record.sh [area | window | output | screen] [audio] PID_FILE="/tmp/wf-recorder.pid" TYPE_FILE="/tmp/wf-recorder.type" OUTPUT_DIR="$HOME/Videos" + +# Ensure output directory exists mkdir -p "$OUTPUT_DIR" +# Stop any active recording session gracefully stop_recording() { + # Check if we have a saved process ID if [ -f "$PID_FILE" ]; then PID=$(cat "$PID_FILE") if kill -0 "$PID" 2>/dev/null; then + # Send INT signal (Ctrl+C equivalent) so wf-recorder can flush the output container kill -INT "$PID" - # Wait a moment for wf-recorder to finish writing the file + # Wait briefly to permit filesystem write finalization sleep 0.5 fi rm -f "$PID_FILE" fi - # Also double check in case of orphaned wf-recorder instances + # Sweep for orphan instances of wf-recorder to prevent background process leaks if pgrep -x "wf-recorder" > /dev/null; then pkill -INT -x wf-recorder sleep 0.5 fi + # Read the recording type metadata for user notification TYPE="Recording" if [ -f "$TYPE_FILE" ]; then TYPE=$(cat "$TYPE_FILE") @@ -35,20 +45,20 @@ stop_recording() { exit 0 } -# If already running, stop recording (no matter what arguments are passed) +# If the script is invoked while a recording is already running, toggle it OFF if pgrep -x "wf-recorder" > /dev/null; then stop_recording fi -# Determine type +# Define operation modes MODE="${1:-area}" AUDIO_DEVICE="" TYPE_DESC="Screen Recording" -# Get recording parameters +# Extract geometric regions based on requested target case "$MODE" in area) - # Select area using slurp + # Interactive region selector using 'slurp'. User clicks and drags to select. GEOM=$(slurp) if [ -z "$GEOM" ]; then notify-send -t 2000 "Screen Recorder" "Recording cancelled" @@ -57,7 +67,7 @@ case "$MODE" in TYPE_DESC="Area Recording" ;; window) - # Get active window geometry + # Fetch the active window coordinates and dimensions using hyprctl JSON output GEOM=$(hyprctl activewindow -j | jq -r '"\(.at[0]),\(.at[1]) \(.size[0])x\(.size[1])"') if [ -z "$GEOM" ] || [ "$GEOM" = "null,null nullxnull" ]; then notify-send -t 2000 "Screen Recorder" "No active window found" @@ -66,40 +76,44 @@ case "$MODE" in TYPE_DESC="Window Recording" ;; output) - # Get focused monitor geometry + # Query active monitors and match the geometry of the current cursor focus GEOM=$(hyprctl monitors -j | jq -r '.[] | select(.focused == true) | "\(.x),\(.y) \(.width)x\(.height)"') TYPE_DESC="Monitor Recording" ;; screen) - # All outputs (no geometry restriction) + # Clear geometry: captures the full desktop layout spanning all connected monitors GEOM="" TYPE_DESC="Full Screen Recording" ;; esac -# If the second argument is "audio", enable system audio recording +# Resolve dynamic audio monitor node if the user specified "audio" as the second flag if [ "$2" = "audio" ]; then - # Dynamically find the default output sink's monitor name from PipeWire/WirePlumber + # Parse status output of wireplumber to determine the currently active output Sink ID SINK_ID=$(wpctl status | sed -n '/Sinks:/,/Sources:/p' | grep '*' | awk '{print $3}' | tr -d '.') if [ -n "$SINK_ID" ]; then + # Query wireplumber to resolve the dynamic node name of the identified sink (e.g. alsa_output.pci...) NODE_NAME=$(wpctl inspect "$SINK_ID" | grep 'node.name' | awk -F'"' '{print $2}') if [ -n "$NODE_NAME" ]; then + # Append .monitor to route output system audio loopback to the recording device AUDIO_DEVICE="${NODE_NAME}.monitor" fi fi - # Fallback to default system source if we couldn't resolve the node name + # Fallback to default system input/source if parsing failed if [ -z "$AUDIO_DEVICE" ]; then AUDIO_DEVICE="default" fi TYPE_DESC="${TYPE_DESC} (with Audio)" fi +# Define output filename format (ISO-like timestamping) FILENAME="recording_$(date +%Y-%m-%d_%H-%M-%S).mp4" FILEPATH="$OUTPUT_DIR/$FILENAME" -# Start recording +# Trigger user-facing low-priority desktop notification notify-send -t 2000 -u low "Screen Recorder" "Starting $TYPE_DESC..." +# Execute wf-recorder in the background with appropriate flags if [ -n "$AUDIO_DEVICE" ]; then if [ -n "$GEOM" ]; then wf-recorder -a "$AUDIO_DEVICE" -g "$GEOM" -f "$FILEPATH" & @@ -114,6 +128,8 @@ else fi fi +# Track PID and Type metadata in /tmp for future toggle invocation PID=$! echo "$PID" > "$PID_FILE" echo "$TYPE_DESC" > "$TYPE_FILE" + diff --git a/hosts/desktop/monitor.py b/hosts/desktop/monitor.py index 2034b48..229a119 100644 --- a/hosts/desktop/monitor.py +++ b/hosts/desktop/monitor.py @@ -1,3 +1,15 @@ +""" +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 potential rate-limiting, IP bans, or API abuse flags. +""" + import urllib.request import re import json @@ -6,7 +18,11 @@ 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 reflection services to discover the public WAN IP. PROVIDERS = [ "https://api.ipify.org", "https://ifconfig.me/ip", @@ -16,6 +32,12 @@ PROVIDERS = [ 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 @@ -23,32 +45,47 @@ def is_valid_public_ipv4(ip): if any(x > 255 for x in octets): return False a, b, c, d = octets - # Exclude private/reserved IP blocks + + # 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 sequentially 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' + 'User-Agent': 'Mozilla/5.0 (NixOS WAN Monitor)' } ) + # Fetch content with a strict 5 second timeout to prevent hanging the systemd task with urllib.request.urlopen(req, timeout=5) as response: ip = response.read().decode('utf-8').strip() if is_valid_public_ipv4(ip): @@ -57,6 +94,7 @@ def get_public_ip(): 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 @@ -65,6 +103,12 @@ def get_public_ip(): def get_last_recorded_ip(): + """ + Reads the history log from the bottom up 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: @@ -72,6 +116,7 @@ def get_last_recorded_ip(): 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) @@ -85,6 +130,9 @@ def get_last_recorded_ip(): 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", @@ -101,7 +149,14 @@ def record_ip(ip, status, details=None): 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 the API call res = subprocess.run( ["systemctl", "start", "ddclient.service"], capture_output=True, @@ -120,17 +175,21 @@ def trigger_ddclient(): 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 the last recorded working IP; do nothing + # IP matches the last recorded working IP; do nothing to conserve API 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.") @@ -144,3 +203,4 @@ def main(): if __name__ == "__main__": main() +