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.
This commit is contained in:
kiskaadee committed 2026-06-25 16:43:35 -05:00
1 parent 1a7ce2f1be
commit ff3ab012f0
3 files changed
+215 -107

No files matched your search

+121 -89
View File
@@ -1,127 +1,159 @@
# ❄️ Declarative NixOS Workstation # ❄️ Declarative NixOS Workstation Configuration
## 📖 Overview 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.
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/).
--- ---
## 🛑 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. ```mermaid
* **Imperative Rot:** System stability degrades as manual tweaks, forgotten dependencies, and monolithic Bash configurations (`.bashrc` files spanning hundreds of lines) pile up. graph TD
* **Replication Friction:** Setting up a new machine requires manually executing scripts, remembering package names, and migrating complex configurations by hand. 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). ```mermaid
* **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. flowchart TD
* **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. A[Timer triggers monitor script] --> B[Fetch public IP from seq. providers]
* **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. 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 <pattern>` — Appends pattern to project-root `.gitignore`, commits the change, and pushes to remote.
* `gacp <message>` — Shorthand to stage all edits, commit with a message, and push directly to the current branch.
* `new-repo <name>` — 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. ```mermaid
* **Full Desktop Environments (DEs):** Avoiding bloated DEs (like GNOME or KDE) in favor of lightweight, composable window managers and standalone system monitors. graph LR
* **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. 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 For detailed steps on bootstrapping, key generation, and service decryption, see the [Secrets Management Guide](docs/secrets-management.md).
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`).
--- ---
## 🚀 Quick Start / Deployment ## 🚀 Quick Start / Deployment
### 1. Clone the Configuration ### 1. Installation
Clone this repository to your home directory (usually target location is `~/Config`): Clone the configuration workspace directly into your home folder:
```bash ```bash
git clone https://github.com/kiskaadee/nixos-config.git ~/Config git clone https://github.com/kiskaadee/nixos-config.git ~/Config
cd ~/Config cd ~/Config
``` ```
### 2. Build and Switch the Configuration ### 2. Deploy System Configurations
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: Rebuild and switch to the profile matching your active target host machine:
* **Desktop Workstation:**
```bash ```bash
# Rebuild the system for the 'desktop' target
sudo nixos-rebuild switch --flake ~/Config#desktop sudo nixos-rebuild switch --flake ~/Config#desktop
``` ```
* **Laptop Workstation:**
*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 ```bash
nix flake update sudo nixos-rebuild switch --flake ~/Config#laptop
``` ```
*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: * [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.
### Phase 1: Complete DankMaterialShell (DMS) Integration * [Tmux Terminal Multiplexer](docs/tmux.md) — Fast navigation bindings, layouts, and pane splits guide.
* [ ] **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)). * [Google Antigravity Setup](docs/antigravity.md) — Technical instructions for packaging and using the Antigravity agent CLI on NixOS.
* [ ] **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.
+31 -15
View File
@@ -1,30 +1,40 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Screen Recording script for Hyprland using wf-recorder # 📹 Hyprland Screen Recording Utility
# Usage: record.sh [area|window|output|screen] [audio] # 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" PID_FILE="/tmp/wf-recorder.pid"
TYPE_FILE="/tmp/wf-recorder.type" TYPE_FILE="/tmp/wf-recorder.type"
OUTPUT_DIR="$HOME/Videos" OUTPUT_DIR="$HOME/Videos"
# Ensure output directory exists
mkdir -p "$OUTPUT_DIR" mkdir -p "$OUTPUT_DIR"
# Stop any active recording session gracefully
stop_recording() { stop_recording() {
# Check if we have a saved process ID
if [ -f "$PID_FILE" ]; then if [ -f "$PID_FILE" ]; then
PID=$(cat "$PID_FILE") PID=$(cat "$PID_FILE")
if kill -0 "$PID" 2>/dev/null; then 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" kill -INT "$PID"
# Wait a moment for wf-recorder to finish writing the file # Wait briefly to permit filesystem write finalization
sleep 0.5 sleep 0.5
fi fi
rm -f "$PID_FILE" rm -f "$PID_FILE"
fi 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 if pgrep -x "wf-recorder" > /dev/null; then
pkill -INT -x wf-recorder pkill -INT -x wf-recorder
sleep 0.5 sleep 0.5
fi fi
# Read the recording type metadata for user notification
TYPE="Recording" TYPE="Recording"
if [ -f "$TYPE_FILE" ]; then if [ -f "$TYPE_FILE" ]; then
TYPE=$(cat "$TYPE_FILE") TYPE=$(cat "$TYPE_FILE")
@@ -35,20 +45,20 @@ stop_recording() {
exit 0 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 if pgrep -x "wf-recorder" > /dev/null; then
stop_recording stop_recording
fi fi
# Determine type # Define operation modes
MODE="${1:-area}" MODE="${1:-area}"
AUDIO_DEVICE="" AUDIO_DEVICE=""
TYPE_DESC="Screen Recording" TYPE_DESC="Screen Recording"
# Get recording parameters # Extract geometric regions based on requested target
case "$MODE" in case "$MODE" in
area) area)
# Select area using slurp # Interactive region selector using 'slurp'. User clicks and drags to select.
GEOM=$(slurp) GEOM=$(slurp)
if [ -z "$GEOM" ]; then if [ -z "$GEOM" ]; then
notify-send -t 2000 "Screen Recorder" "Recording cancelled" notify-send -t 2000 "Screen Recorder" "Recording cancelled"
@@ -57,7 +67,7 @@ case "$MODE" in
TYPE_DESC="Area Recording" TYPE_DESC="Area Recording"
;; ;;
window) 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])"') GEOM=$(hyprctl activewindow -j | jq -r '"\(.at[0]),\(.at[1]) \(.size[0])x\(.size[1])"')
if [ -z "$GEOM" ] || [ "$GEOM" = "null,null nullxnull" ]; then if [ -z "$GEOM" ] || [ "$GEOM" = "null,null nullxnull" ]; then
notify-send -t 2000 "Screen Recorder" "No active window found" notify-send -t 2000 "Screen Recorder" "No active window found"
@@ -66,40 +76,44 @@ case "$MODE" in
TYPE_DESC="Window Recording" TYPE_DESC="Window Recording"
;; ;;
output) 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)"') GEOM=$(hyprctl monitors -j | jq -r '.[] | select(.focused == true) | "\(.x),\(.y) \(.width)x\(.height)"')
TYPE_DESC="Monitor Recording" TYPE_DESC="Monitor Recording"
;; ;;
screen) screen)
# All outputs (no geometry restriction) # Clear geometry: captures the full desktop layout spanning all connected monitors
GEOM="" GEOM=""
TYPE_DESC="Full Screen Recording" TYPE_DESC="Full Screen Recording"
;; ;;
esac 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 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 '.') SINK_ID=$(wpctl status | sed -n '/Sinks:/,/Sources:/p' | grep '*' | awk '{print $3}' | tr -d '.')
if [ -n "$SINK_ID" ]; then 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}') NODE_NAME=$(wpctl inspect "$SINK_ID" | grep 'node.name' | awk -F'"' '{print $2}')
if [ -n "$NODE_NAME" ]; then if [ -n "$NODE_NAME" ]; then
# Append .monitor to route output system audio loopback to the recording device
AUDIO_DEVICE="${NODE_NAME}.monitor" AUDIO_DEVICE="${NODE_NAME}.monitor"
fi fi
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 if [ -z "$AUDIO_DEVICE" ]; then
AUDIO_DEVICE="default" AUDIO_DEVICE="default"
fi fi
TYPE_DESC="${TYPE_DESC} (with Audio)" TYPE_DESC="${TYPE_DESC} (with Audio)"
fi fi
# Define output filename format (ISO-like timestamping)
FILENAME="recording_$(date +%Y-%m-%d_%H-%M-%S).mp4" FILENAME="recording_$(date +%Y-%m-%d_%H-%M-%S).mp4"
FILEPATH="$OUTPUT_DIR/$FILENAME" FILEPATH="$OUTPUT_DIR/$FILENAME"
# Start recording # Trigger user-facing low-priority desktop notification
notify-send -t 2000 -u low "Screen Recorder" "Starting $TYPE_DESC..." 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 "$AUDIO_DEVICE" ]; then
if [ -n "$GEOM" ]; then if [ -n "$GEOM" ]; then
wf-recorder -a "$AUDIO_DEVICE" -g "$GEOM" -f "$FILEPATH" & wf-recorder -a "$AUDIO_DEVICE" -g "$GEOM" -f "$FILEPATH" &
@@ -114,6 +128,8 @@ else
fi fi
fi fi
# Track PID and Type metadata in /tmp for future toggle invocation
PID=$! PID=$!
echo "$PID" > "$PID_FILE" echo "$PID" > "$PID_FILE"
echo "$TYPE_DESC" > "$TYPE_FILE" echo "$TYPE_DESC" > "$TYPE_FILE"
+63 -3
View File
@@ -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 urllib.request
import re import re
import json import json
@@ -6,7 +18,11 @@ import subprocess
import sys import sys
from datetime import datetime 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") 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 = [ PROVIDERS = [
"https://api.ipify.org", "https://api.ipify.org",
"https://ifconfig.me/ip", "https://ifconfig.me/ip",
@@ -16,6 +32,12 @@ PROVIDERS = [
def is_valid_public_ipv4(ip): 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) match = re.match(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$", ip)
if not match: if not match:
return False return False
@@ -23,32 +45,47 @@ def is_valid_public_ipv4(ip):
if any(x > 255 for x in octets): if any(x > 255 for x in octets):
return False return False
a, b, c, d = octets 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: if a == 10:
return False return False
if a == 192 and b == 168: if a == 192 and b == 168:
return False return False
if a == 172 and 16 <= b <= 31: if a == 172 and 16 <= b <= 31:
return False return False
# Carrier-Grade NAT (CGNAT) RFC 6598: 100.64.0.0/10
if a == 100 and 64 <= b <= 127: if a == 100 and 64 <= b <= 127:
return False return False
# Loopback address range: 127.0.0.0/8
if a == 127: if a == 127:
return False return False
# Link-local addresses: 169.254.0.0/16
if a == 169 and b == 254: if a == 169 and b == 254:
return False return False
return True return True
def get_public_ip(): 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 = [] errors = []
for provider in PROVIDERS: for provider in PROVIDERS:
try: try:
req = urllib.request.Request( req = urllib.request.Request(
provider, provider,
headers={ 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: with urllib.request.urlopen(req, timeout=5) as response:
ip = response.read().decode('utf-8').strip() ip = response.read().decode('utf-8').strip()
if is_valid_public_ipv4(ip): if is_valid_public_ipv4(ip):
@@ -57,6 +94,7 @@ def get_public_ip():
errors.append(f"{provider}: invalid public IPv4 '{ip}'") errors.append(f"{provider}: invalid public IPv4 '{ip}'")
except Exception as e: except Exception as e:
errors.append(f"{provider}: {str(e)}") errors.append(f"{provider}: {str(e)}")
print( print(
f"Error: All IP discovery providers failed. Details: {errors}", f"Error: All IP discovery providers failed. Details: {errors}",
file=sys.stderr file=sys.stderr
@@ -65,6 +103,12 @@ def get_public_ip():
def get_last_recorded_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): if not os.path.exists(HISTORY_FILE):
return None return None
try: try:
@@ -72,6 +116,7 @@ def get_last_recorded_ip():
lines = f.readlines() lines = f.readlines()
if not lines: if not lines:
return None return None
# Search backwards to find the most recent successful transition
for line in reversed(lines): for line in reversed(lines):
try: try:
entry = json.loads(line) entry = json.loads(line)
@@ -85,6 +130,9 @@ def get_last_recorded_ip():
def record_ip(ip, status, details=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) os.makedirs(os.path.dirname(HISTORY_FILE), exist_ok=True)
entry = { entry = {
"timestamp": datetime.utcnow().isoformat() + "Z", "timestamp": datetime.utcnow().isoformat() + "Z",
@@ -101,7 +149,14 @@ def record_ip(ip, status, details=None):
def trigger_ddclient(): def trigger_ddclient():
"""
Invokes the systemd service unit for `ddclient` on-demand.
Returns:
tuple: (bool, str) representing (success_boolean, error_details_string)
"""
try: try:
# Run ddclient as a one-shot activation via systemd to perform the API call
res = subprocess.run( res = subprocess.run(
["systemctl", "start", "ddclient.service"], ["systemctl", "start", "ddclient.service"],
capture_output=True, capture_output=True,
@@ -120,17 +175,21 @@ def trigger_ddclient():
def main(): def main():
"""
Orchestrator logic for DDNS state management.
"""
current_ip = get_public_ip() current_ip = get_public_ip()
if not current_ip: if not current_ip:
sys.exit(1) sys.exit(1)
last_ip = get_last_recorded_ip() last_ip = get_last_recorded_ip()
if current_ip == last_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) sys.exit(0)
print(f"IP rotation detected! Old: {last_ip}, New: {current_ip}") print(f"IP rotation detected! Old: {last_ip}, New: {current_ip}")
# Trigger ddclient to perform the DNS record update
success, error_msg = trigger_ddclient() success, error_msg = trigger_ddclient()
if success: if success:
print("Dynu DDNS update via ddclient triggered successfully.") print("Dynu DDNS update via ddclient triggered successfully.")
@@ -144,3 +203,4 @@ def main():
if __name__ == "__main__": if __name__ == "__main__":
main() main()