SwarselSystems: NixOS + Emacs Configuration
Table of Contents
- 1. Introduction (no config code)
- 2. An introduction to nix
- 3. flake.nix
- 3.1. flake.nix skeleton (inputs)
- 3.2. Library functions
- 3.3. Packages (pkgs)
- 3.4. Globals
- 3.5. PII evaluation
- 3.6. Hosts
- 3.7. Topology (nix-topology generated network diagram)
- 3.8. Pre-commit hooks (checks)
- 3.9. Devshell
- 3.10. Templates
- 3.11. Formatter (treefmt-nix)
- 3.12. Modules
- 3.13. Apps
- 3.14. Overlays/Overrides
- 3.15. flake-file
- 3.16. Outputs
- 3.17. Installer images (live ISO, kexec)
- 3.18. Tests
- 3.19. Installer flake
- 4. System
- 4.1. Manual steps when setting up a new machine
- 4.2. Current issues
- 4.3. System specific configuration
- 4.3.1. Physical hosts
- 4.3.1.1. pyramid (Framework Laptop 16)
- 4.3.1.2. Bakery (Lenovo ThinkPad)
- 4.3.1.3. Winters (Server: ASRock J4105-ITX)
- 4.3.1.4. Summers (Server: ASUS Z10PA-D8)
- 4.3.1.4.1. Main Configuration
- 4.3.1.4.2. hardware-configuration
- 4.3.1.4.3. Guests
- 4.3.1.4.3.1. Kavita
- 4.3.1.4.3.2. Jellyfin
- 4.3.1.4.3.3. Audio
- 4.3.1.4.3.4. Matrix
- 4.3.1.4.3.5. Nextcloud
- 4.3.1.4.3.6. Immich
- 4.3.1.4.3.7. Paperless
- 4.3.1.4.3.8. Transmission
- 4.3.1.4.3.9. Storage
- 4.3.1.4.3.10. Monitoring
- 4.3.1.4.3.11. FreshRSS
- 4.3.1.4.3.12. Kanidm
- 4.3.1.4.3.13. Firefly-III
- 4.3.1.4.3.14. Koillection
- 4.3.1.4.3.15. Radicale
- 4.3.1.4.3.16. Atuin
- 4.3.1.4.3.17. Forgejo
- 4.3.1.4.3.18. Anki Sync Server
- 4.3.1.4.3.19. Homebox
- 4.3.1.4.3.20. Mealie
- 4.3.1.4.3.21. Dawarich
- 4.3.1.4.3.22. Utility
- 4.3.1.5. Hintbooth (Router: HUNSN RM02)
- 4.3.1.6. machpizza (MacBook Pro)
- 4.3.1.7. Magicant (Phone)
- 4.3.1.8. Treehouse (DGX Spark)
- 4.3.2. Virtual hosts
- 4.3.3. Utility hosts
- 4.3.1. Physical hosts
- 4.4. Modules
- 4.4.1. Common
- 4.4.1.1. Share configuration between nodes (distributed config, automatically active)
- 4.4.1.2. Global options (automatically active)
- 4.4.1.3. Configuration options
- 4.4.1.4. Topology (automatically active)
- 4.4.1.5. General NixOS settings (nix config, stateVersion)
- 4.4.1.6. Setup home-manager base
- 4.4.1.7. User setup, Make users non-mutable
- 4.4.1.8. Setup login keymap (xserver)
- 4.4.1.9. Time, locale settings
- 4.4.1.10. PII management
- 4.4.1.11. PII agent
- 4.4.1.12. Meta options (options only)
- 4.4.1.13. Remote building
- 4.4.1.14. Lanzaboote (secure boot)
- 4.4.1.15. Disk encryption
- 4.4.1.16. DNS
- 4.4.1.17. Config Library (confLib)
- 4.4.1.18. BTRFS
- 4.4.1.19. Boot
- 4.4.1.20. ssh
- 4.4.1.21. sops
- 4.4.1.22. Impermanence
- 4.4.1.23. Disk layout (single root)
- 4.4.1.24. Disk layout (mirrored root)
- 4.4.1.25. nftables (firewall)
- 4.4.1.26. Persistent user/group IDs
- 4.4.1.27. Network scanner (SANE)
- 4.4.2. Client
- 4.4.2.1. Mirror home-manager shared options (automatically active)
- 4.4.2.2. nixGL
- 4.4.2.3. Self-defined Packages
- 4.4.2.4. Theme (stylix)
- 4.4.2.5. Desktop Entries, MIME types (xdg)
- 4.4.2.6. nix-index
- 4.4.2.7. nix-your-shell
- 4.4.2.8. password-store
- 4.4.2.9. direnv
- 4.4.2.10. eza
- 4.4.2.11. git
- 4.4.2.12. Fuzzel
- 4.4.2.13. Starship
- 4.4.2.14. Kitty
- 4.4.2.15. zsh
- 4.4.2.16. bash
- 4.4.2.17. zellij
- 4.4.2.18. Mail
- 4.4.2.19. Home-manager: Emacs
- 4.4.2.20. Glide
- 4.4.2.20.1. Main Config
- 4.4.2.20.2. Containers
- 4.4.2.20.3. Findbar
- 4.4.2.20.4. site-specific hint-selectors
- 4.4.2.20.5. find mode (hints, vimperator-reflow)
- 4.4.2.20.6. Rapidfire hints
- 4.4.2.20.7. Ignored sites, ignore-mode
- 4.4.2.20.8. Invidious CSS
- 4.4.2.20.9. Search engines
- 4.4.2.20.10. Site shortcuts
- 4.4.2.20.11. Status line
- 4.4.2.20.12. General keybindings
- 4.4.2.20.13. Glide CSS
- 4.4.2.20.14. Toolbar auto-hide and states
- 4.4.2.20.15. Commands for opening and searching
- 4.4.2.20.16. Find audio tabs
- 4.4.2.20.17. Jump to site heading
- 4.4.2.20.18. Clone git repositories
- 4.4.2.21. KDE Connect
- 4.4.2.22. attic store push service
- 4.4.2.23. Tray applets
- 4.4.2.24. Shikane
- 4.4.2.25. gpg-agent
- 4.4.2.26. Spicetify
- 4.4.2.27. Obsidian
- 4.4.2.28. Anki
- 4.4.2.29. Element-desktop
- 4.4.2.30. obs-studio
- 4.4.2.31. spotify-player
- 4.4.2.32. vesktop
- 4.4.2.33. Khal
- 4.4.2.34. System Packages
- 4.4.2.35. Environment setup
- 4.4.2.36. enable GVfs
- 4.4.2.37. Security (polkit)
- 4.4.2.38. Reduce systemd timeouts
- 4.4.2.39. Hardware settings
- 4.4.2.40. Pulseaudio
- 4.4.2.41. Pipewire
- 4.4.2.42. Common network settings
- 4.4.2.43. "Small" Programs
- 4.4.2.44. nautilus
- 4.4.2.45. syncthing
- 4.4.2.46. interception-tools: Make CAPS work as ESC/CTRL
- 4.4.2.47. Network devices
- 4.4.2.48. Bluetooth
- 4.4.2.49. power-profiles-daemon
- 4.4.2.50. Hardware: Yubikey
- 4.4.2.51. Hardware: Ledger
- 4.4.2.52. Hardware: Keyboards
- 4.4.2.53. System Login (greetd)
- 4.4.2.54. nix-ld
- 4.4.2.55. Summary of NixOS-rebuild diff
- 4.4.2.56. gnome-keyring
- 4.4.2.57. xdg-portal (Screensharing)
- 4.4.2.58. Podman (distrobox)
- 4.4.2.59. AppImage
- 4.4.2.60. Handle lid switch correctly
- 4.4.2.61. Nix-on-Droid
- 4.4.2.62. Auto-login
- 4.4.2.63. UWSM
- 4.4.2.64. Firezone Client
- 4.4.2.65. Niri
- 4.4.2.66. Noctalia
- 4.4.2.67. gaming
- 4.4.2.68. work
- 4.4.2.69. Work (dev, pizauth)
- 4.4.2.70. Work (mail)
- 4.4.2.71. Work (desktop)
- 4.4.2.72. AMD CPU
- 4.4.2.73. AMD GPU
- 4.4.2.74. Framework
- 4.4.2.75. Hibernation
- 4.4.2.76. nswitch-rcm
- 4.4.2.77. VirtualBox
- 4.4.2.78. Sandbox Access for Clients
- 4.4.2.79. Pedantix
- 4.4.3. Server
- 4.4.3.1. General NixOS Server settings
- 4.4.3.2. System Packages (Server Programs)
- 4.4.3.3. MicroVM-host
- 4.4.3.4. MicroVM-guest
- 4.4.3.5. MicroVM-guest-shares
- 4.4.3.6. nix-topology node config
- 4.4.3.7. systemd-networkd (base)
- 4.4.3.8. systemd-networkd (server base)
- 4.4.3.9. systemd-networkd (server home)
- 4.4.3.10. nfs/samba (smb)
- 4.4.3.11. acme
- 4.4.3.12. acme-dns
- 4.4.3.13. NGINX
- 4.4.3.14. NGINX OpenTelemetry
- 4.4.3.15. Bastion
- 4.4.3.16. ssh builder config
- 4.4.3.17. Network settings (globals.networks population)
- 4.4.3.18. Attic setup
- 4.4.3.19. Wireguard
- 4.4.3.20. Router
- 4.4.3.21. Kavita
- 4.4.3.22. jellyfin
- 4.4.3.23. Seerr
- 4.4.3.24. Navidrome
- 4.4.3.25. Spotifyd
- 4.4.3.26. MPD
- 4.4.3.27. pipewire
- 4.4.3.28. PostgreSQL
- 4.4.3.29. Podman
- 4.4.3.30. matrix (use db)
- 4.4.3.31. Nextcloud
- 4.4.3.32. Immich (use db)
- 4.4.3.33. paperless (Tika, Gotenberg)
- 4.4.3.34. transmission
- 4.4.3.35. pia-netns
- 4.4.3.36. syncthing
- 4.4.3.37. restic backups
- 4.4.3.38. sanoid
- 4.4.3.39. syncoid
- 4.4.3.40. Grafana
- 4.4.3.41. tempo
- 4.4.3.42. Gotify
- 4.4.3.43. Pyroscope
- 4.4.3.44. Loki
- 4.4.3.45. alloy
- 4.4.3.46. blackbox-exporter
- 4.4.3.47. Gatus
- 4.4.3.48. parsedmarc
- 4.4.3.49. smartctl-exporter
- 4.4.3.50. zfs-exporter
- 4.4.3.51. ipmi-exporter
- 4.4.3.52. nginx-exporter
- 4.4.3.53. Mimir
- 4.4.3.54. FreshRSS
- 4.4.3.55. Forgejo (git server)
- 4.4.3.56. Anki Sync Server
- 4.4.3.57. kanidm
- 4.4.3.58. oauth2-proxy
- 4.4.3.59. Firefly-III
- 4.4.3.60. Koillection (use db)
- 4.4.3.61. Atuin (use db)
- 4.4.3.62. Radicale
- 4.4.3.63. Croc
- 4.4.3.64. Microbin
- 4.4.3.65. Shlink
- 4.4.3.66. slink
- 4.4.3.67. Readeck
- 4.4.3.68. Yubal
- 4.4.3.69. Collabora Online
- 4.4.3.70. Filestash
- 4.4.3.71. Audiobookshelf
- 4.4.3.72. slskd
- 4.4.3.73. Dawarich
- 4.4.3.74. MeTube
- 4.4.3.75. Spliit
- 4.4.3.76. OpnForm
- 4.4.3.77. LibreSpeed
- 4.4.3.78. Homebox (use db)
- 4.4.3.79. OPKSSH
- 4.4.3.80. Garage
- 4.4.3.81. Set host domain for dns
- 4.4.3.82. Set dns host entries for home servers
- 4.4.3.83. Set node role global entries
- 4.4.3.84. Knot (dns)
- 4.4.3.85. Minecraft
- 4.4.3.86. Mail server
- 4.4.3.87. Attic (nix binary cache)
- 4.4.3.88. Kea DHCP
- 4.4.3.89. Hostapd
- 4.4.3.90. Mosquitto
- 4.4.3.91. Zigbee2MQTT
- 4.4.3.92. Home Assistant
- 4.4.3.93. scanservjs
- 4.4.3.94. Chrony
- 4.4.3.95. Firezone
- 4.4.3.96. Adguardhome
- 4.4.3.97. Buildbot
- 4.4.3.98. SearX
- 4.4.3.99. Invidious
- 4.4.3.100. Invidious-companion
- 4.4.3.101. Firefox-syncserver
- 4.4.3.102. CrowdSec
- 4.4.3.103. CopyParty
- 4.4.3.104. Mealie
- 4.4.3.105. Shopservatory
- 4.4.3.106. Socks-Proxy
- 4.4.3.107. Treehouse services
- 4.4.1. Common
- 4.5. Shared
- 4.6. Profiles
- 5. Emacs
-
- 5.0.1. early-init
- 5.0.2. Core settings
- 5.0.3. Python
- 5.0.4. Session related settings
- 5.0.5. Custom Keybindings
- 5.0.6. Unclutter .Emacs.d
- 5.0.7. Indentation
- 5.0.8. Scrolling
- 5.0.9. Evil
- 5.0.10. Font Configuration
- 5.0.11. Theme
- 5.0.12. Icons
- 5.0.13. Variable Pitch Mode
- 5.0.14. mini-modeline
- 5.0.15. Minibuffer enhancements (vertico, marginalia, consult, embark)
- 5.0.16. Helpful + which-key: Better help defaults
- 5.0.17. Ligatures
- 5.0.18. Popup (popper) + Shackle Buffers
- 5.0.19. Org Mode
- 5.0.20. Nix Mode
- 5.0.21. HCL Mode
- 5.0.22. Jenkinsfile/Groovy
- 5.0.23. Ansible
- 5.0.24. Terraform Mode
- 5.0.25. pedantix
- 5.0.26. shfmt
- 5.0.27. Markdown Mode
- 5.0.28. elfeed
- 5.0.29. Grep
- 5.0.30. Tree-sitter
- 5.0.31. direnv (envrc)
- 5.0.32. avy
- 5.0.33. devdocs
- 5.0.34. Projectile
- 5.0.35. Magit
- 5.0.36. Yubikey support
- 5.0.37. Forge
- 5.0.38. git-timemachine
- 5.0.39. Delimiters (brackets): rainbow-delimiters, highlight-parentheses
- 5.0.40. rainbow-mode
- 5.0.41. Corfu
- 5.0.42. cape
- 5.0.43. Tramp
- 5.0.44. diff-hl
- 5.0.45. eglot
- 5.0.46. dape
- 5.0.47. Dirvish
- 5.0.48. undo-tree
- 5.0.49. Hydra
- 5.0.50. Mail
- 5.0.51. Calendar
- 5.0.52. Dashboard: Emacs startup screen
- 5.0.53. vterm
- 5.0.54. Less logging
- 5.0.55. Popup frames
- 5.0.56. Close pane when closing buffer
- 5.0.57. hunkle
- 5.0.58. apheleia
- 5.0.59. jinx
- 5.0.60. pulsar
-
- 6. Tofu
- 7. Appendix A: Noweb-Ref blocks
- 8. Appendix B: Supplementary Files
- 8.1. Doc Page style.css
- 8.2. justfile
- 8.3. Matrix IRC Patch to allow on-connect commands
- 8.4. Matrix IRC Patch to open rooms on bot DMs in v12 matrix rooms
- 8.5. Matrix IRC Patch to not reply to all DMs received by the bot
- 8.6. Niri patch to support hidden workspaces
- 8.7. Niri patch to get events for hidden workspaces
- 8.8. Niri patch to keep gestures out of hidden workspaces
- 8.9. Niri patch to allow actions to target workspaces under the cursor
- 8.10. Firezone-GUI patch to fix state loop
- 8.11. nginx-otel patch for c++20
- 8.12. Default Flake Template
- 8.13. Go Flake Template
- 8.14. LaTeX Flake Template
- 8.15. Python Flake Template
- 8.16. Rust Flake Template
- 8.17. GitHub README
- 8.18. GitHub Workflow: Build-and-deploy
- 8.19. GitHub Workflow: emacs-init.nix
- 8.20. Private topology flake
- 8.21. Public topology flake
- 8.22. Grafana dashboard
- 8.23. Repo-wide Pedantix config
- 9. Appendix C: Explanations to nix functions and operators
- 9.1. Concepts
- 9.2. Built-in functions
- 9.3. Built-in functions exported to nixpkgs
- 9.3.1. nixpkgs.lib.listToAttrs
- 9.3.2. nixpkgs.lib.attrNames
- 9.3.3. nixpkgs.lib.map
- 9.3.4. nixpkgs.lib.filter
- 9.3.5. nixpkgs.lib.concatLists
- 9.3.6. nixpkgs.lib.genList
- 9.3.7. nixpkgs.lib.concatStringsSep
- 9.3.8. nixpkgs.lib.split
- 9.3.9. nixpkgs.lib.tail
- 9.3.10. nixpkgs.lib.head
- 9.3.11. nixpkgs.lib.isString
- 9.3.12. nixpkgs.lib.length
- 9.3.13. nixpkgs.lib.stringLength
- 9.3.14. nixpkgs.lib.subString
- 9.4. Functions in nixpkgs
- 10. Appendix D: Notable Commits
- 10.1. 978f4a7 - treewide: major cleanup (2026-11-11)
- 10.2. bb0d4ad - feat: adopt sops-rekey (2026-11-04)
- 10.3. bfb70b7 - refactor[client]: move magicant to dendritic (2026-11-01)
- 10.4. 78edb33 - feat[client]: migrate to emacs-init (2026-06-10)
- 10.5. fffcee1 - refactor: move to dendritic pattern (2026-06-06)
- 10.6. 85e830d - feat: use flake-file (2026-06-04)
- 10.7. 8b2fe83 - feat[server]: modernize nginx/acme setup (2026-06-02)
- 10.8. 9e2cb74 - fix[server]: move away from full module load system (2026-05-06)
- 10.9. 99d0d75 - feat: manage .sops.yaml using tofu (2026-05-02)
- 10.10. 2cb6780 - feat[server]: use confLib to manage services (2025-11-25)
- 10.11. 0caef3e - feat: use nixos-extra-modules (2025-11-08)
- 10.12. 7d614f7 - feat!: switch to full flake-parts (2025-07-03)
- 10.13. 2aa5e00 - feat: add globals system (2025-06-29)
- 10.14. a11c785 - feat: new deploy system, allows for in-repo pii (2025-06-11)
- 10.15. 267c03f - Merge pull request #1: Module refactor (2025-05-24)
- 10.16. 47b99bb - feat: add nix-topology (2024-12-28)
- 10.17. 6788494 - feat: full bootstrapping (2024-12-17)
- 10.18. 3a272b1 - feat!: dynamically create hosts (2024-12-10)
- 10.19. 040fce3 - feat: add private secrets flake for flake purity (2024-12-10)
- 10.20. 33046cb - refactor: use inputs.self instead of rel. paths (2024-12-05)
- 10.21. 84b5cd8 - move flake to own repository (2023-12-11)
- 11. Appendix E: Current TODOs
This file has 177859 words spanning 52417 lines (of which 45520 are code) and was last revised on 2026-11-25 01:26:33 +0000.
1. Introduction (no config code)
This literate configuration file holds the entirety of all configuration for both NixOS PCs and servers as well as home-manager only systems across all machines that I currently use. It also holds an extensive Emacs configuration. I use this project to manage my entire home + cloud infrastructure
This configuration is part of a NixOS system that is for the most part fully declarative (except for the steps outlined in Manual steps when setting up a new machine) and can be found here:
The literate configuration approach lets me explain my choices to my future self as well as you, the reader. I go to great lengths to explain the choices for all design steps that I take in order for me to pay due diligence in crafting my setup, and not simply copying big chunks of other peoples code. Also, this is very convenient to me as I only need to keep of (ideally) a single file to manage all of my configuration. I hope that this documentation will make it easier for beginners to get into NixOS (and, to some extent, Emacs) as I know it can be a struggle in the beginning.
1.1. What I achieve with this project
(click to enlarge; topology graph last updated on 2026-11-03.)
This project manages my entire IT infrastructure. In particular:
- A mail server (Eagleland (Hetzner))
- My home router (Hintbooth (Router: HUNSN RM02)) and its MicroVMs
- Two home servers (Summers (Server: ASUS Z10PA-D8), Winters (Server: ASRock J4105-ITX) and their respective MicroVMs) and one cloud server (Moonside (OCI)) that are using other services defined in Services (a list can be found in Services)
- Two servers (the cloud host Twothreetunnel (OCI) and one MicroVM Nginx hosted on Hintbooth (Router: HUNSN RM02)) that proxy requests to those services
- A build farm (Belchsfactory (OCI)) with binary caching that helps me build derivations faster and cache them for reuse
- An authoritative DNS server (Stoicclub (OCI)) that pushes records to both Hetzner and Hurricane Electric DNS
- An SSH bastion (Liliputsteps (OCI)) that gate-keeps access to all cloud hosts
- My work laptop (pyramid (Framework Laptop 16)) and my personal laptop (Bakery (Lenovo ThinkPad))
- My work workstation (Treehouse (DGX Spark))
My phone (Magicant (Phone))
This is a system that grew organically over 1824 days and has reached considerable complexity at this point. This documents exists to try and make it understandable to other people as well.
1.2. How to use this document
When I started out with nix, it was a painful time. For a beginner, the available resources tend to be too detailed or assume too much prior knowledge. Also, it seems that using nix requires the user to understand it pretty well before many things start to make sense.
That is the reason why I keep this configuration as a literate one: so that I am able to explain how everything works as best as I can. In the start, it was my goal to keep this project simple, so that it would be easy to understand when seen by a beginner. However, over time I have implemented more and more complicated solutions. Still, I try to keep the prosaic descriptions sufficient.
For a beginner, I recommend to read this file like a book, from start to finish. I will try to explain concepts whenever they first come up, and will regularly link to Appendix C: Explanations to nix functions and operators when more context is needed. For the first few times that I am using a new function, I will place such a link again. However, to keep the writing of this file manageable, I will generally only do this no more than three times.
This page offers some utilities to you:
- you can pin specific headings to the right "pinned" bar by hovering over the heading and clicking
[pin] - If a section seems uninteresting to you, you can press the
↓button to skip to the next one. - If a sections upcoming subsections seem uninteresting to you, you can press the
⇣button to skip to the next heading of at least same or higher level. - If you are currently in a level of subsections that all seem uninteresting to you, you can press the
⇑button to skip to the next heading that is at least one level higher. - And if you want to send a section to somebody else, you can click the
#in order to copy its link to the clipboard. Your pinned headings will be saved locally, so you can continue reading in case you take a break.
1.3. Structure of this file
Now, I will outline how this document is structured. I have segmented this file into the following sections:
- Introduction (no code) This is the block you are currently in. It holds no code that actually builds the system, it just outlines the general approach and explains the rough design mentality. For understanding the nix (or Emacs) code in here, reading this should not be necessary if you already know some nix (feel free to skip to flake.nix). Otherwise, I will also give a brief introduction to some nix terms here.
- An introduction to nix Here I will give a coarse overview over some important concepts in the nix landscape. This is aimed at beginners in the field; others might want to skip this section as they are likely to not find much that will be worth their time.
- flake.nix
This block holds everything related to the heart of the nix side of the configuration - the
flake.nixfile. I am using flake-parts to manage this flake, so different aspects of the configuration are handled by flake-part modules in different files. - System This section holds all configuration options that apply to NixOS or home-manager. In other words, here we are doing system and user level configuration. In a way, I consider this the most important part of this file, as (nearly) all of the nix magic is going to happen here.
- Emacs
This section defines my Emacs configuration. For a while, I considered to use rycee's
emacs-initmodule (https://github.com/nix-community/nur-combined/blob/master/repos/rycee/hm-modules/emacs-init.nix) to manage my Emacs configuration; I have since come to the conclusion that this would be a bad idea: at the moment, even though it might seem as I am very bound to the configuration file that you are currently reading, if I ever decide to change how I run my system, I can simply take the generated.nixand.elfiles and put them wherever I need them. This file only simplifies that generation without putting further restrictions on my. If I were however to switch toemacs-initthen I would be indeed to some level confined to the nix ecosystem with my Emacs configuration, as I would no longer have a valid.orgfile to manage it with, instead generating aninit.eldirectly from nix code. I like to keep that level of freedom for potential future use. Also, you will notice there is no package system setup in this configuration. This is because packages are automatically handled on the NixOS side by parsing the generatedinit.elfile for package installs.
nix build My Emacs is built using the emacs-overlay nix flake, which builds a bleeding edge Emacs on Wayland (pgtk) with utilities like treesitter support. By executing the below source block, the current build setting can be updated at any time, and you can see my most up-to-date build options (last updated: 2026-11-25 01:26:33 +0000)
system-configuration-options
--prefix=/nix/store/zvxm2rjbn2gigwaz7njdwarpxsi0isml-emacs-unstable-pgtk-30.2 --disable-build-details --with-modules --with-pgtk --disable-gc-mark-trace --with-compress-install --with-toolkit-scroll-bars --with-native-compilation --without-imagemagick --with-mailutils --without-small-ja-dic --with-tree-sitter --without-xinput2 --without-xwidgets --with-dbus --with-selinux
This file is not loaded by Emacs directly as the configuration (even though this would be possible - actually I did that in the past!) - instead, it generates two more files:
early-init.elThis file handle startup optimization and sets up the basic frame that I will be working in.init.elThis file handles the rest of the Emacs configuration.
By using the configuration offered by this file, the file you are reading right now (SwarselSystems.org) will not be freshly tangled on every file save, as this slows down Emacs over time. However, when you clone this configuration yourself and have not yet activated it, you need to tangle the file yourself. This can be done using the general keybinding C-c C-v t or my personal chord C-SPC o t. Alternatively, execute the following block:
(org-babel-tangle)
This section holds code that can be templated by other parts of the configuration.
These blocks were used in several places throughout the configurations, but not on all machines necessarily. For example, the theming section used need to be in a NixOS block on NixOS machines but in a home-manager block on non-NixOS.
Originally, I used this method a lot throughout my configuration. However, as my knowledge of NixOS grew, I have been weeding these snippets out more and more as I find more efficient native solutions. Now, only the theming block remains. For example, the above problem can be solved by defining a theme attribute set and using lib.recursiveUpdate as shown in Configuration options and Theme (stylix). Nowadays I use this mostly for some meta information in this file, e.g. for defining the Programs, Services and Hosts blocks only once. I also use it to merge the Manual steps when setting up a new machine.
As such, this served to reduce code duplication in this file. The tangled files experienced no size reduction, since noweb-ref only substitutes these blocks in.
An example of using a noweb-ref block:
First we define the block:
# source block headers: :tangle no :noweb-ref blockName
enable = true;
which can then be used in a block like:
# source block headers: :tangle no :noweb no :results silent
another_value = 1;
<<blockName>>
and is finally parsed as:
# source block headers: :tangle no :noweb yes :results silent
another_value = 1;
# source block headers: :tangle no :noweb-ref blockName
enable = true;
Note that noweb-reffed blocks will not always be indented correctly. You will want to account for that when checking your nix flake with the formatter of your choice. Personally, I have solved this issue using the functions defined in org-mode: Upon-save actions (Auto-tangle, export to html, formatting). Originally, I also automatically exported to HTML there, but it incurred a too high memory penalty which made Emacs become sluggish over time - instead I now build the website version whenever I push to GitHub.
- Appendix B: Supplementary Files This section holds files that are not written in nix but are still referenced in the configuration in some way. This is mostly used for configuration of programs that have no native nix support, like aspell, as well as "meta" files like the GitHub Readme or the GitHub Workflow: Build-and-deploy. Note that shell scripts are still defined under their respective entry in Packages. Over time, the goal is to reduce this section to a minimum.
- Appendix C: Explanations to nix functions and operators When I started to learn about nix, I found that journey quite arduous; while I disagree with the general public in that the documentation is too sparse, I will say that, while it is very good, reading (and understanding!) it requires a certain level of existing nix knowledge that one will probably not have when starting out. Hence, the goal of this document is to explain common nix functions as they come up in this document (I thing I wrote this before :sweat:), in hopes that you will be able to understand most of the code. When a new function appears for the first time, I will try to link to an entry in the appendix.
1.3.1. HTML version of this document
I will also quickly talk about the web page that (I hope) you are currently viewing works:
The .html version of this page is built by a GitHub workflow; it can also be generated manually by calling the chord C-SPC o e, or by executing the below block
(org-html-export-to-html)
The web version is useful because it allows navigation using org-mode links, which makes the configuration easier to follow in a number of ways:
- mobile-friendly documentation
- Functionality to save links to certain headers in a "Pinned" menu that can be toggled
- These links are locally saved
I add a JavaScript bit to the file in order to have a dark mode toggle when exporting to HTML (defined in HTML Export: Darkmode toggle). NOTE: What I am doing is defining an elisp multi-line string which gives me HereDoc capabilities for defining blocks that should be both exported to the final .html but should also be shown in the document itself (only putting a #+[begin/end]_export block would not show the block in the content of the page) which is then output as HTML and exported to both.
"
<script src='https://cdn.jsdelivr.net/npm/darkmode-js@1.5.7/lib/darkmode-js.min.js'></script>
<script>
function addDarkmodeWidget() {
new Darkmode({label:'[☀︎]'}).showWidget();
}
window.addEventListener('load', addDarkmodeWidget);
</script>
"
I also add this JavaScript to add header pinning functionality to the site, using the same trick as above (this is defined in HTML Export: Docs QoL):
"
<script>
(function() {
function ready(fn) {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', fn);
} else {
fn();
}
}
ready(function initPinned() {
const STORAGE_KEY = 'org-pinned-items-v2';
let pinnedPanel = document.getElementById('pinned-panel');
if (!pinnedPanel) {
pinnedPanel = document.createElement('aside');
pinnedPanel.id = 'pinned-panel';
pinnedPanel.innerHTML = `
<div id='pinned-panel-header'>
<h2>Pinned</h2>
<button id='toggle-pinned-btn' type='button' title='Hide pinned panel'>✕</button>
</div>
<button id='clear-all-pins-btn' type='button'>Clear All</button>
<ul id='pinned-list'></ul>
`;
document.body.appendChild(pinnedPanel);
}
let showBtn = document.getElementById('show-pinned-btn');
if (!showBtn) {
showBtn = document.createElement('button');
showBtn.id = 'show-pinned-btn';
showBtn.type = 'button';
showBtn.textContent = 'Pinned';
document.body.appendChild(showBtn);
}
const content = document.getElementById('content');
const pinnedList = document.getElementById('pinned-list');
const toggleBtn = document.getElementById('toggle-pinned-btn');
const clearAllBtn = document.getElementById('clear-all-pins-btn');
const toc = document.getElementById('table-of-contents');
const body = document.body;
if (!content || !pinnedList || !toggleBtn || !clearAllBtn || !toc) return;
function injectSearch() {
if (document.getElementById('toc-search-input')) return;
const searchContainer = document.createElement('div');
searchContainer.id = 'toc-search-container';
const searchInput = document.createElement('input');
searchInput.id = 'toc-search-input';
searchInput.type = 'text';
searchInput.placeholder = 'Search TOC...';
searchInput.autocomplete = 'off';
const clearBtn = document.createElement('button');
clearBtn.id = 'toc-search-clear';
clearBtn.type = 'button';
clearBtn.textContent = 'Clear';
searchContainer.appendChild(searchInput);
searchContainer.appendChild(clearBtn);
toc.insertBefore(searchContainer, toc.firstChild);
function filterTOC(term) {
const allLinks = toc.querySelectorAll('a');
allLinks.forEach(link => {
const li = link.closest('li');
if (!li) return;
const text = link.textContent.toLowerCase();
const matches = text.includes(term);
if (matches) {
li.classList.remove('hidden-by-search');
let parent = li.parentElement;
while (parent && parent !== toc) {
if (parent.tagName === 'UL') {
parent.style.display = '';
}
if (parent.tagName === 'LI') {
parent.classList.remove('hidden-by-search');
}
parent = parent.parentElement;
}
} else {
li.classList.add('hidden-by-search');
}
});
if (term === '') {
const allLis = toc.querySelectorAll('li');
allLis.forEach(li => li.classList.remove('hidden-by-search'));
}
}
searchInput.addEventListener('input', function(e) {
const term = e.target.value.toLowerCase();
filterTOC(term);
});
clearBtn.addEventListener('click', function() {
searchInput.value = '';
filterTOC('');
searchInput.focus();
});
}
injectSearch();
function addHeadingLinks() {
const headers = content.querySelectorAll('h1, h2, h3, h4, h5, h6, h7, h8, h9');
headers.forEach(header => {
const id = header.getAttribute('id');
if (!id) return;
if (header.querySelector('.heading-link')) return;
const link = document.createElement('a');
link.className = 'heading-link';
link.href = '#' + id;
link.textContent = '#';
link.title = 'Copy link to this heading';
const pinBtn = header.querySelector('.toc-pin-btn');
if (pinBtn) {
header.insertBefore(link, pinBtn);
} else {
header.appendChild(link);
}
link.addEventListener('click', function(e) {
e.preventDefault();
const url = window.location.origin + window.location.pathname + '#' + id;
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(url)
.then(() => {
const originalText = link.textContent;
link.textContent = '✓';
setTimeout(() => {
link.textContent = originalText;
}, 1000);
})
.catch(err => {
console.warn('Failed to copy to clipboard', err);
window.location.hash = id;
});
} else {
window.location.hash = id;
}
});
});
}
addHeadingLinks();
function addNextHeadingButtons() {
const headers = Array.from(content.querySelectorAll('h1, h2, h3, h4, h5, h6, h7, h8, h9'));
function getLevel(header) {
return parseInt(header.tagName.substring(1), 10);
}
headers.forEach((header, index) => {
const currentLevel = getLevel(header);
const headingLink = header.querySelector('.heading-link');
const pinBtn = header.querySelector('.toc-pin-btn');
function insertActionBtn(btn) {
if (pinBtn) {
header.insertBefore(btn, pinBtn);
return;
}
if (headingLink && headingLink.parentNode === header) {
headingLink.after(btn);
return;
}
header.appendChild(btn);
}
const nextHeader = headers[index + 1];
if (nextHeader && !header.querySelector('.heading-next')) {
const nextId = nextHeader.getAttribute('id');
if (nextId) {
const nextBtn = document.createElement('button');
nextBtn.className = 'heading-next';
nextBtn.type = 'button';
nextBtn.textContent = '↓';
nextBtn.title = 'Jump to next heading';
insertActionBtn(nextBtn);
nextBtn.addEventListener('click', function(e) {
e.preventDefault();
nextHeader.scrollIntoView({ behavior: 'smooth', block: 'start' });
history.pushState(null, null, '#' + nextId);
});
}
}
if (!header.querySelector('.heading-skip')) {
let skipHeader = null;
for (let i = index + 1; i < headers.length; i++) {
if (getLevel(headers[i]) <= currentLevel) {
skipHeader = headers[i];
break;
}
}
if (skipHeader) {
const skipId = skipHeader.getAttribute('id');
if (skipId) {
const skipBtn = document.createElement('button');
skipBtn.className = 'heading-skip';
skipBtn.type = 'button';
skipBtn.textContent = '⇣';
skipBtn.title = 'Skip to next section (same level)';
insertActionBtn(skipBtn);
skipBtn.addEventListener('click', function(e) {
e.preventDefault();
skipHeader.scrollIntoView({ behavior: 'smooth', block: 'start' });
history.pushState(null, null, '#' + skipId);
});
}
}
}
if (!header.querySelector('.heading-skip-up')) {
let upHeader = null;
for (let i = index + 1; i < headers.length; i++) {
if (getLevel(headers[i]) < currentLevel) {
upHeader = headers[i];
break;
}
}
if (upHeader) {
const upId = upHeader.getAttribute('id');
if (upId) {
const upBtn = document.createElement('button');
upBtn.className = 'heading-skip-up';
upBtn.type = 'button';
upBtn.textContent = '⇑';
upBtn.title = 'Jump to next higher-level section (escape subsections)';
insertActionBtn(upBtn);
upBtn.addEventListener('click', function(e) {
e.preventDefault();
upHeader.scrollIntoView({ behavior: 'smooth', block: 'start' });
history.pushState(null, null, '#' + upId);
});
}
}
}
});
}
addNextHeadingButtons();
let mobileTocBtn = document.getElementById('mobile-toc-toggle');
if (!mobileTocBtn) {
mobileTocBtn = document.createElement('button');
mobileTocBtn.id = 'mobile-toc-toggle';
mobileTocBtn.type = 'button';
mobileTocBtn.textContent = 'TOC';
document.body.appendChild(mobileTocBtn);
}
let mobilePinnedBtn = document.getElementById('mobile-pinned-toggle');
if (!mobilePinnedBtn) {
mobilePinnedBtn = document.createElement('button');
mobilePinnedBtn.id = 'mobile-pinned-toggle';
mobilePinnedBtn.type = 'button';
mobilePinnedBtn.textContent = 'Pinned';
document.body.appendChild(mobilePinnedBtn);
}
function anyMobilePanelOpen() {
return toc.classList.contains('mobile-visible') ||
pinnedPanel.classList.contains('mobile-visible');
}
function updateBodyMobilePanelState() {
if (anyMobilePanelOpen()) body.classList.add('mobile-panel-open');
else body.classList.remove('mobile-panel-open');
}
document.addEventListener('click', function(e) {
if (window.innerWidth > 1000) return;
if (!anyMobilePanelOpen()) return;
const clickedInsideToc = toc.contains(e.target);
const clickedInsidePinned = pinnedPanel.contains(e.target);
const clickedTocBtn = mobileTocBtn.contains(e.target);
const clickedPinnedBtn = mobilePinnedBtn.contains(e.target);
const clickedInteractive =
e.target.tagName === 'A' ||
e.target.tagName === 'BUTTON' ||
e.target.tagName === 'INPUT' ||
e.target.tagName === 'TEXTAREA' ||
e.target.closest('a') ||
e.target.closest('button');
if (!clickedInsideToc && !clickedInsidePinned && !clickedTocBtn && !clickedPinnedBtn && !clickedInteractive) {
toc.classList.remove('mobile-visible');
pinnedPanel.classList.remove('mobile-visible');
updateBodyMobilePanelState();
}
});
mobileTocBtn.addEventListener('click', function() {
const isOpen = toc.classList.toggle('mobile-visible');
if (isOpen) {
pinnedPanel.classList.remove('mobile-visible');
}
updateBodyMobilePanelState();
});
mobilePinnedBtn.addEventListener('click', function() {
const isOpen = pinnedPanel.classList.toggle('mobile-visible');
if (isOpen) {
toc.classList.remove('mobile-visible');
}
updateBodyMobilePanelState();
});
const pinnedItems = new Map();
let initiallyPinnedHrefs = new Set();
function loadFromStorage() {
try {
const raw = window.localStorage && localStorage.getItem(STORAGE_KEY);
if (!raw) return;
const arr = JSON.parse(raw);
if (!Array.isArray(arr)) return;
initiallyPinnedHrefs = new Set(arr);
} catch (e) {
console.warn('Pinned: failed to load from localStorage', e);
}
}
function saveToStorage() {
try {
if (!window.localStorage) return;
const arr = [];
pinnedItems.forEach((entry, href) => {
if (entry.li) arr.push(href);
});
localStorage.setItem(STORAGE_KEY, JSON.stringify(arr));
} catch (e) {
console.warn('Pinned: failed to save to localStorage', e);
}
}
function sortPinnedList() {
const items = Array.from(pinnedList.children)
.map(li => {
const link = li.querySelector('a');
return {
li: li,
text: link ? link.textContent.trim()
.toLowerCase() : ''
};
});
items.sort((a, b) => a.text.localeCompare(b.text));
items.forEach(item => pinnedList.appendChild(item.li));
}
function hidePinnedPanel() {
pinnedPanel.classList.add('hidden');
content.classList.add('pinned-hidden');
showBtn.classList.add('visible');
}
function showPinnedPanel() {
pinnedPanel.classList.remove('hidden');
content.classList.remove('pinned-hidden');
showBtn.classList.remove('visible');
}
toggleBtn.addEventListener('click', hidePinnedPanel);
showBtn.addEventListener('click', showPinnedPanel);
clearAllBtn.addEventListener('click', function() {
if (pinnedItems.size === 0) return;
const confirmed = confirm('Are you sure you want to clear all pinned items?');
if (!confirmed) return;
pinnedItems.forEach((entry, href) => {
if (entry.li && entry.li.parentElement) {
entry.li.parentElement.removeChild(entry.li);
}
entry.li = null;
entry.btns.forEach(b => b.textContent = '[pin]');
});
saveToStorage();
});
function attachPinBehavior(pinBtn, href, text) {
if (!href) return;
if (!pinnedItems.has(href)) {
pinnedItems.set(href, {
li: null,
btns: new Set(),
text: text
});
}
const entry = pinnedItems.get(href);
entry.btns.add(pinBtn);
pinBtn.textContent = entry.li ? '[unpin]' : '[pin]';
pinBtn.addEventListener('click', function(e) {
e.preventDefault();
e.stopPropagation();
const current = pinnedItems.get(href);
if (!current) return;
if (current.li) {
if (current.li.parentElement) {
current.li.parentElement.removeChild(current.li);
}
current.li = null;
current.btns.forEach(b => b.textContent = '[pin]');
saveToStorage();
} else {
const li = document.createElement('li');
const a = document.createElement('a');
a.href = href;
a.textContent = current.text;
const removeBtn = document.createElement('button');
removeBtn.className = 'pin-remove';
removeBtn.type = 'button';
removeBtn.textContent = '✕';
removeBtn.addEventListener('click', () => {
const cur = pinnedItems.get(href);
if (!cur) return;
if (cur.li && cur.li.parentElement) {
cur.li.parentElement.removeChild(cur.li);
}
cur.li = null;
cur.btns.forEach(b => b.textContent = '[pin]');
saveToStorage();
});
li.appendChild(a);
li.appendChild(removeBtn);
pinnedList.appendChild(li);
current.li = li;
current.btns.forEach(b => b.textContent = '[unpin]');
sortPinnedList();
saveToStorage();
}
});
}
loadFromStorage();
const tocLinks = document.querySelectorAll('#text-table-of-contents a');
tocLinks.forEach(link => {
if (link.parentElement && link.parentElement.classList.contains('toc-entry')) {
return;
}
const li = link.closest('li');
if (!li) return;
const wrapper = document.createElement('span');
wrapper.className = 'toc-entry';
li.insertBefore(wrapper, link);
wrapper.appendChild(link);
const pinBtn = document.createElement('button');
pinBtn.className = 'toc-pin-btn';
pinBtn.type = 'button';
pinBtn.textContent = '[pin]';
wrapper.appendChild(pinBtn);
const href = link.getAttribute('href');
const text = link.textContent.trim();
attachPinBehavior(pinBtn, href, text);
});
const headers = content.querySelectorAll('h2, h3, h4, h5, h6, h7, h8, h9');
headers.forEach(header => {
const id = header.getAttribute('id');
if (!id) return;
if (header.querySelector('.toc-pin-btn')) return;
const href = '#' + id;
const text = header.textContent.trim();
const pinBtn = document.createElement('button');
pinBtn.className = 'toc-pin-btn';
pinBtn.type = 'button';
pinBtn.textContent = '[pin]';
pinBtn.style.marginLeft = '0.8rem';
pinBtn.style.fontSize = '0.75em';
header.appendChild(pinBtn);
attachPinBehavior(pinBtn, href, text);
});
initiallyPinnedHrefs.forEach(href => {
const entry = pinnedItems.get(href);
if (!entry) return;
const li = document.createElement('li');
const a = document.createElement('a');
a.href = href;
a.textContent = entry.text;
const removeBtn = document.createElement('button');
removeBtn.className = 'pin-remove';
removeBtn.type = 'button';
removeBtn.textContent = '✕';
removeBtn.addEventListener('click', () => {
const cur = pinnedItems.get(href);
if (!cur) return;
if (cur.li && cur.li.parentElement) {
cur.li.parentElement.removeChild(cur.li);
}
cur.li = null;
cur.btns.forEach(b => b.textContent = '[pin]');
saveToStorage();
});
li.appendChild(a);
li.appendChild(removeBtn);
pinnedList.appendChild(li);
entry.li = li;
entry.btns.forEach(b => b.textContent = '[unpin]');
});
sortPinnedList();
saveToStorage();
});
})();
</script>
"
1.4. Structure of this flake
The structure of this flake as seen many revisions, however lately I have settled on a system that I have grown to like:
hosts: This folder is used to house all configurations that are used across the infrastructure. At the top level, it splits into the subfoldersnixos,home,darwin, andandroid. These folders specify the mode that the configuration is running in:- NixOS: Full NixOS host (may or may not also use home-manager)
- Darwin: Host that uses NixOS on MacOS (may or may not use home-manager)
- home: Host that uses only home-manager (no full NixOS)
- android: Phone using nix-on-droid (may or may not use home-manager)
The corresponding configurations are automatically generated by mkNixosHost, mkDarwinHost and mkHalfHost. A "full" host is either in the NixOS or Darwin folder, while a "half" host is in either of home or android. This has to do with the scheme in which these configurations are generated.
These <host type> folders hold on the first level a folder describing the machine archetype (x86_64-linux or aarch64-linux for Linux, x86_64-darwin or aarch64-darwin for macs). Those folders then hold a number of <hostname> folders, the actual configurations. At this time, the files stored in this folder are:
- default.nix: This file holds the abstracted configuration of the host. This should mostly be enabling Profiles as well as setting some Configuration options.
- hardware-config.nix: It is not clearly defined what I hold in this file. Mostly it is just the attributes that nix originally sets when setting up the system for the first time (although at this time modified by me!), bar any filesystem configuration. This makes my deployment in swarsel-bootstrap a little bit simpler.
- disk-config.nix
Only present for hosts whose filesystem layout differs from the shared Disk layout (single root) module (currently
moonsideandpyramid); either way the layout is applied using disko. - The hosts/<host type>/<hostname> folders may also have a
secretsfolder, under which files of the ending.nix.encmay be stored. As the name suggests, these files should be encrypted. Specifically, they need to be sops-encrypted files (sops does not seem to suggest a file ending other than.ymlor others, which is not verbose enough for me, so I went with.enc). This should have the structure of a nix expression, e.g.:
{
my_value = 2;
my_attrSet = {
enable = true;
};
}
It is also possible to pass it as a function:
{ config }: {
my_value = 2;
my_attrSet = {
enable = config.myconfig.enable;
};
}
Using the mechanisms in PII management, these files are decrypted during evaluation time and stored in the nix store. As the name suggests, I am using these files to store personally identifiable information - these "secrets" are stored world-readable in the nix store. As such, this should not be used to store important secrets, but rather information that you would not like everyone on the internet to easily find in your git repo.
Other than that, the secrets folder will also be used to store conventional (decrypted at activation-time) sops-encrypted secrets in the standard .yaml / .toml / .ini formats.
- a host might have a
guests/subdirectory. That is telling of that host acting as a MicroVM hypervisor. Each MicroVM has it's own secret directory under thesecrets/directory of the root host directory. Here is a rough outline on how to add a new MicroVM to a host:- update
secrets/repo/globals.nix.enc, adding interface information to the new host (virtual MAC address as well as WireGuard interfaces mostly) - add a new entry under
guestsin the hypervisors main configuration - add a guest
default.nixinguests/<guestName> - add the guest to the
guestslist of the hypervisor intofu/sops/terraform.tfvarsand apply the tofu config (this only matters for the eval-time.encfiles) - the guest's secrets live under
hosts/<host>-<guestName>/insecrets/root.yaml; nothing needs to be created by hand - add the MicroVM name to the clients of
wgHome/wgProxyin the respective main host config - rebuild once so that the guest gets created and its ssh hostkey deployed
- write the guest's age key (
ssh-to-ageof itsssh_host_ed25519_key.pub) tofiles/public/age/hosts/<host>-<guestName>.pub,git addit and apply the tofu config again just rekeygenerates the missing WireGuard private key and preshared keys (the public key lands infiles/public/wg/<host>-<guestName>.pub) and encrypts the guest's secrets for it- fill in whatever other secrets the guest needs with
just secret-set hosts/<host>-<guestName>/<name>, thenjust rekeyagain - rebuild the hypervisor
- update
modulesThis folder holds all of the actual nix-based system configuration done in this repository. This is done in a dendritic manner (see for example the dendritic design guide). The important terminology here is:aspect: a bit of configuration for a given context (e.g. NixOS, home-manager, etc.)feature: the file that holds configuration for different system contexts by including one or more aspects (or flake-file inputs)
The folder splits up into:
- client: features that are used primarily on client machines (laptops, workstations)
- server: features that are primarily on server machines - the corresponding client aspects may be defined in those features as well
- flake: features that contribute to the flake architecture, for the following functionality (an excerpt):
lib: I define some utility functions that I add to the nixpkgs library under theswarselsystemsattribute set. An example would be themkIfElsefunction.checks: As part of a Devshell (checks), I declare pre-commit hooks that should run before I push changes to my repo.overlays: Here we also define the main (default) overlay I am using in my configuration. It is responsible for adding my defined packages and modifications to the final nixpkgs. Also I add some other conveniences like all past stable nixpkgs and some other package sets.apps: I also define Apps, which is an output of derivations that can be called bynix runwithout having the flake locally - this is mostly used for myswarsel-*utilities.topology: I also created a diagram of my infrastructure using nix-topology. While I do not update this too often, this (I think) can quickly give a good overview of the scope of this flake as well as its services.
- profiles: sets of aspects that can be imported as a collection by hosts
common: features that are used by (mostly) all hosts
This structure is very opinionated and highly subjective. I will possibly change this in the future.
pkgs: This folder holds derivations (mostly packages) that I define myself. This is mostly used to grab versions that are not (yet) in nixpkgs, or modified versions of another package. Each derivation in this folder is in turn in its own folder which holds a default.nix. Using the mechanism in Packages, these are automatically built and available to all configurations (packages still need to be installed e.g. inenvironment.systemPackages). Note that the folder at the top level splits up inconfigandflakesubdirectories:- The
configdirectory is used for packages that need the actual config of the machine where they run in order to be built. These packages cannot simply be released as a flake output (or better, it would not make a lot of sense). Instead, these are added within the configuration as an overlay - The
flakedirectory is used for the conventional packages that I described above.
- The
files: This is kind of a catchall folder that holds (nearly) all non-nix files. It mostly holds blocks created in Appendix B: Supplementary Files, but also some more specific directories:wallpaper: Holds my wallpapers and profile pictures :)topology-images: Holds pictures used by Topology :)
secrets: Unlike the similar folder underhosts, this folder holds sops-encrypted secrets and PIIs that are used by a number of hosts that is greater than one.install: This folder holds another Installer flake. That flake pulls in thenixosConfigurationsMinimalthat are defined in Hosts of the main flake, which enables me to build an extremely reduced configuration when I deploy a new host for the first time - this is used by swarsel-bootstrap in the first installation step. It also holds the configuration of the two installer images that I use to deploy this flake:- Drugstore (ISO installer config): This is the general installer ISO that I use whenever I can when I want to deploy a new host. It has a few conveniences like some of my utility programs for figuring out some dependencies or network quirks, as well as my public ssh keys so that I can immediately login to them.
- Brick Road (kexec image): This is a kexec tarball that can be used by swarsel-bootstrap in case that I need to deploy to a machine that has less than 1GB of RAM. It is basically just an even more stripped down version of the default one used by
nixos-anywhere, but notably I addedcryptsetupso that it can be used when setting up an encrypted device usingdisko.
.github: Canonically, this holds GitHub related files like the GitHub Readme and some workflows.
1.5. Hosts
Here I give a brief overview over the host machines that I am using. This is held in markdown so that I can render it into my GitHub Readme without further effort.
| Name | Hardware | Use |
|-----------------------|--------------------------------------------------|---------------------------------|
| 💻 **bakery** | Lenovo Ideapad 720S-13IKB | Personal laptop |
| 💻 **pyramid** | Framework 16, AMD 7940HS, RX 7700S, 64GB RAM | Work laptop |
| 💻 **machpizza** | MacBook Pro 2016 | Alternative work laptop, MacOS |
| 🏠 **treehouse** | NVIDIA DGX Spark | AI sandbox, HM-only |
| 🖥️ **hintbooth** | HUNSN RM02, 8GB RAM | Router, home proxy/DNS |
| 🖥️ **summers** | ASUS Z10PA-D8, 2 Intel Xeon E5-2650 v4, 128G RAM | Main Homeserver, NAS |
| 🖥️ **winters** | ASRock J4105-ITX, 32GB RAM | IoT Homeserver, Wi-Fi(6) AP |
| ☁️ **belchsfactory** | 4 vCPUs, 24GB RAM | Remote Builder, nix cache |
| ☁️ **eagleland** | 2 vCPUs, 8GB RAM | Mailserver |
| ☁️ **liliputsteps** | 1 vCPUs, 8GB RAM | SSH bastion |
| ☁️ **moonside** | 4 vCPUs, 24GB RAM | Non-critical services |
| ☁️ **stoicclub** | 1 vCPUs, 8GB RAM | Authoritative DNS server |
| ☁️ **twothreetunnel** | 2 vCPUs, 8GB RAM | Web proxy |
| 🪟 **chaostheater** | Asus Z97-A, i7-4790k, GTX970, 32GB RAM | Game streaming (on AtlasOS) |
| 📱 **magicant** | Samsung Galaxy Z Flip 6 | Phone (nix-on-droid) |
| 💿 **brickroad** | - | Kexec tarball for low-mem hosts |
| 💿 **drugstore** | - | Installer ISO for new hosts |
| 💿 **policestation** | - | Live ISO for generating keys |
| ❔ **vacanthouse** | - | Staging environment |
1.6. Programs
This is meant to give a brief overview over the main programs/components that I use on a daily basis on my client machines. This should be mostly useful for people wanting to rice their config, or people who believed this repos title and are looking for .dotfiles :p
| Topic | Program |
|-----------------|-------------------------------------|
| ⛩️ **Bar** | [Noctalia Shell][] |
| ✒️ **Editor** | [Emacs][] |
| 🌐 **Browser** | [Glide][] |
| 🎨 **Theme** | [City-Lights (managed by stylix)][] |
| 🐚 **Shell** | [zsh][] |
| 🖥️ **Terminal** | [Kitty][] |
| 🚀 **Launcher** | [Noctalia Shell][] |
| 🚨 **Alerts** | [Noctalia Shell][] |
| 🚪 **DM** | [greetd][] |
| 🪟 **WM** | [Niri][] |
[Noctalia Shell]: https://github.com/Swarsel/.dotfiles/tree/main/modules/client/programs/noctalia.nix
[Emacs]: https://swarsel.github.io/.dotfiles/emacs/init.el.html
[Glide]: https://github.com/Swarsel/.dotfiles/tree/main/modules/client/programs/glide.nix
[City-Lights (managed by stylix)]: https://github.com/Swarsel/.dotfiles/tree/main/modules/client/programs/stylix.nix
[zsh]: https://github.com/Swarsel/.dotfiles/tree/main/modules/client/programs/zsh.nix
[Kitty]: https://github.com/Swarsel/.dotfiles/tree/main/modules/client/programs/kitty.nix
[greetd]: https://github.com/Swarsel/.dotfiles/tree/main/modules/client/system/login.nix
[Niri]: https://github.com/Swarsel/.dotfiles/tree/main/modules/client/programs/niri.nix
1.7. Services
This is a comprehensive list of the services/components ran by my server machines.
| Topic | Program |
|------------------------------|-----------------------------------------------------------------------------------------|
| ☁️ **S3** | [Garage][] |
| ⚓ **Anki Sync** | [Anki Sync Server][] |
| ⛏️ **Minecraft** | [Minecraft][] |
| ✂️ **Paste Tool** | [Microbin][] |
| ✉️ **Mail** | [simple-nixos-mailserver][] |
| 🃏 **Collections** | [Koillection][] |
| 🌳 **Git** | [Forgejo][] |
| 🍴 **RSS** | [FreshRss][] |
| 🍽️ **Recipes** | [Mealie][] |
| 🎞️ **Photos** | [Immich][] |
| 🎧 **Audiobooks** | [Audiobookshelf][] |
| 🎵 **Music** | [Navidrome][] + [Spotifyd][] + [MPD][] |
| 🎼 **Music Downloader** | [Yubal][] |
| 🐙 **Nix Build farm** | [Buildbot][] |
| 🐝 **Home Automation** | [Home Assistant][] + [Zigbee2MQTT][] + [Mosquitto][] |
| 🐽 **Threat Detection** | [CrowdSec][] |
| 👀 **DNS Records** | [Knot][] |
| 👁️ **Monitoring** | [Grafana][] + [Mimir][] + [Loki][] + [Tempo][] + [Alloy][] + [Pyroscope][] + [Gotify][] |
| 💸 **Finance** | [Firefly-III][] + [Spliit][] |
| 💾 **Backups** | [Restic][] |
| 📁 **Filesharing** | [Nextcloud][] + [CopyParty][] + [Croc][]. Also [slskd][], [transmission + friends][] |
| 📄 **Documents** | [Paperless][] |
| 📅 **CalDav/CardDav** | [Radicale][] |
| 📖 **Books** | [Kavita][] |
| 📚 **Bookmarks** | [Readeck][] |
| 📝 **Office Suite** | [Collabora Online][] + [Filestash][] |
| 📋 **Forms** | [OpnForm][] |
| 📸 **Image Sharing** | [Slink][] |
| 📹 **Video Downloader** | [MeTube][] |
| 📺 **Video Streaming** | [Invidious][] + [Invidious Companion][] |
| 📼 **Videos** | [Jellyfin][] |
| 🔄 **File Sync** | [Syncthing][] |
| 🚀 **Speedtest** | [LibreSpeed][] |
| 🔎 **Search Engine** | [SearXNG][] |
| 🔑 **Cert-based SSH** | [OPKSSH][] |
| 🔗 **Link Shortener** | [Shlink][] |
| 🔨 **Home Asset Management** | [Homebox][] |
| 🕸️ **Nix Binary Cache** | [Attic][] |
| 🗃️ **Shell History** | [Atuin][] |
| 🗨️ **Messaging** | [Matrix][] |
| 🗺️ **Location History** | [Dawarich][] |
| 🚇 **VPN Access** | [Firezone][] |
| 🛎️ **DHCP** | [Kea][] |
| 🛡️ **Local DNS Resolver** | [AdGuard Home][] |
| 🦊 **Firefox Sync** | [Firefox-Syncserver][] |
| **Second Hand Site Info** | [Shopservatory][] + [Socks Proxy][] |
| 🪪 **SSO** | [Kanidm][] + [oauth2-proxy][] |
[Garage]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/garage.nix
[Anki Sync Server]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/ankisync.nix
[Minecraft]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/minecraft.nix
[Microbin]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/microbin.nix
[simple-nixos-mailserver]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/mailserver.nix
[Koillection]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/koillection.nix
[Forgejo]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/forgejo.nix
[FreshRss]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/freshrss.nix
[Mealie]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/mealie.nix
[Immich]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/immich.nix
[Audiobookshelf]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/audiobookshelf.nix
[Navidrome]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/navidrome.nix
[Spotifyd]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/spotifyd.nix
[MPD]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/mpd.nix
[Yubal]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/yubal.nix
[Buildbot]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/buildbot.nix
[Home Assistant]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/home-assistant.nix
[Zigbee2MQTT]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/zigbee2mqtt.nix
[Mosquitto]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/mosquitto.nix
[CrowdSec]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/crowdsec.nix
[Knot]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/knot.nix
[Grafana]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/grafana.nix
[Mimir]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/mimir.nix
[Loki]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/loki.nix
[Tempo]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/tempo.nix
[Alloy]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/alloy.nix
[Pyroscope]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/pyroscope.nix
[Gotify]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/gotify.nix
[Firefly-III]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/firefly-iii.nix
[Spliit]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/spliit.nix
[Restic]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/restic.nix
[Nextcloud]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/nextcloud.nix
[CopyParty]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/copyparty.nix
[Croc]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/croc.nix
[slskd]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/slskd.nix
[transmission + friends]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/transmission.nix
[Paperless]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/paperless.nix
[Radicale]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/radicale.nix
[Kavita]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/kavita.nix
[Readeck]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/readeck.nix
[Collabora Online]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/collabora-online.nix
[Filestash]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/filestash.nix
[OpnForm]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/opnform.nix
[Slink]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/slink.nix
[MeTube]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/metube.nix
[Invidious]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/invidious.nix
[Invidious Companion]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/invidious-companion.nix
[Jellyfin]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/jellyfin.nix
[Syncthing]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/syncthing.nix
[LibreSpeed]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/librespeed.nix
[SearXNG]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/searx.nix
[OPKSSH]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/opkssh.nix
[Shlink]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/shlink.nix
[Homebox]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/homebox.nix
[Attic]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/attic.nix
[Atuin]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/atuin.nix
[Matrix]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/matrix.nix
[Dawarich]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/dawarich.nix
[Firezone]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/firezone.nix
[Kea]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/kea.nix
[AdGuard Home]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/adguardhome.nix
[Firefox-Syncserver]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/firefox-syncserver.nix
[Shopservatory]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/shopservatory.nix
[Socks Proxy]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/socks-proxy.nix
[Kanidm]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/kanidm.nix
[oauth2-proxy]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/oauth2-proxy.nix
2. An introduction to nix
This is where it gets interesting.
In this section, I want to give an overview over some important concepts needed when working in the nix ecosystem.
2.1. Nix, NixOS, Nixpkgs, and Nix
First off, when talking about nix, we need to differentiate between several things:
- The nix language
- The nix package manager
- The Linux distribution NixOS
- the
nix-communityinput nixpkgs
While these terms are all connected with each other, it is important to keep in mind that fundamentally those are separate entities. Let us briefly talk about each one:
2.1.1. nix language
The base of all the other concepts named above is the nix language, a pure functional programming language that is declarative, dynamically typed, and evaluated lazily. That means:
- Functions are just values, that can be assigned to variables, passed as arguments to other functions, or returned by functions
- All variables are immutable (their values cannot change during computation)
- Values will only be computed when their result is needed
- There is no sequential order of operations; instead, operations get ordered they need to evaluate another expression that they depend on
- We do not need to specify a values type when declaring it
Now, I will give a brief overview over some important concepts of the nix language. This aims to only build the essential understanding needed for dealing with the configuration I am using (this should be sufficient to then understand most other configurations online). For deepening your knowledge, you might want to check out the nix reference manual.
2.1.1.1. Derivations and the nix store
The main purpose of the nix language is to build packages. These packages are built by functions that can be roughly described by something like this:
f: { source, compiler, dependencies, etc. } -> package
This function along with all its inputs we call a derivation. What is important to realize is that such a derivation can itself depend on other derivations, and the resulting package does not necessarily need to be a callable program (a more correct name for the function result is outputs). When we as nix users define a package, we will usually use a function called pkgs.stdenv.mkDerivation (ore one of its derived wrappers like buildRustPackage; for now, it is not important what these do exactly), which will run things like install phases and setup hooks for us. It is a wrapper around nix function derivation(name, system, builder, args=[],outputs=["out"]), where name is the derivation name, system is the system architecture to build for, builder is the executable responsible for building the result, args are arbitrary arguments passed to builder, and outputs, which can be thought of a list of locations where we want to put different build artifacts that can be referenced separately when using the package. There are more attributes, but these five are the most important and commonly used ones.
Building a package (in nix terms: "realizing") from a derivation causes the package to be created in the nix store. This is a read-only filesystem that is usually located at /nix/store. When building a package, nix will place its content of each output at /nix/store/<hash>-<package name>-<package version>-<output name if not 'out'>/, where <hash> is a unique identifier that changes whenever one of the inputs to the above function changes. That means that it is no problem to store different versions of the same file on one system, and each program can use the correct dependencies that it needs.
A key observation that follows from this is that packages are declarative and reproducible; when not changing the inputs, a derivation will always yield the same package with the same store path.
We call the set of derivations (and, recursively, the derivations that those depend on) that a derivation depends on its closure.
Usually when installing a package, we do not need all the outputs it provides: For example, the pcscliteWithPolkit package on nixpkgs that is used for configuring smart cards provides 5 outputs: out, dev, doc, man, and lib. By default, a NixOS system will install out, man, info and doc outputs (the latter three have respective documentation.<name>.enable NixOS options, where <name> would be either of man, info, or doc) as well as any outputs listed in environment.extraOutputsToInstall (by default an empty list). However, if we need to debug something, we might need the dev output of the package, which can then be installed by referencing pcscliteWithPolkit.dev.
Also, a note that may be useful when reading package source code (for example in nixpkgs); you will often come across $out and $src. The $out represents the root of that build output ($src are the build sources). You will often see that in build phases (it is there set as an environment variable). In other places, you will instead see placeholder <output>, which will be replaced by the outputs future location in the nix store.
2.1.1.2. Types in the nix language
The nix language supports the following types and how they look in the wild:
- null:
null - bool:
true - strings:
"text"- strings can also be defined as
multiline strings- Those will look for the lowest level of indent shared over all lines and strip it:
- strings can also be defined as
swarsel-instantiate "
''
indent0
indent2
indent1
''
"
(you can ignore the swarsel-instantiate; it is just a wrapper around nix-instantiate that preloads nixpkgs. I will use this to show you the evaluation results of nix calls)
- note that tab characters will not be stripped:
swarsel-instantiate "
''
indentTab
indent1
indent2
''
"
- an URI string can assume the type of string without need for quoting (e.g. you can write
http://about.orginstead of"http://about.org") - Strings can be interpolated by using
${expression}(read on for an example)expressioncan be any valid nix expression that is compatible with the enclosing type (here: string)
- As in many languages, you have
\n,\r, and\tavailable - in normal strings, you can escape stuff using
\- the following characters need to be escaped in normal strings:
- Backslash:
\(escape using\\) - Double quote:
"(using\") - Opening of nix expression:
${(using\${)
- Backslash:
- the following characters need to be escaped in normal strings:
- in multi-line strings, you escape stuff using one or two apostrophes
'- the following characters need to be escaped in multi-line strings:
- Two apostrophes are escaped with a single apostrophe:
''(escape with''') - All other things are escaped using
'':- Dollar sign:
$(escape with''$) \n,\r, and\t(''\nand so on)''\is a catchall for all other escaping
- Dollar sign:
- Two apostrophes are escaped with a single apostrophe:
- somewhat interestingly, double dollars
$$(as used in Makefiles) never need to be escaped
- the following characters need to be escaped in multi-line strings:
- ints: 1
- floats: 1.1
- paths:
/home- a path can also be given as a relative path (e.g.
./.config)
- a path can also be given as a relative path (e.g.
- attribute sets:
{ }- these hold name value pairs, e.g.
{ a = 3; } - a "chain" of attributes, separated by dots, is called an
attribute path, e.g.config.environment.systemPackages- in such a chain, all attributes but the last will be
attribute sets config.environment.systemPackages = <some list>;is equivalent toconfig = { environment = { systemPackages = <some list>; }; };
- in such a chain, all attributes but the last will be
- these hold name value pairs, e.g.
- lists: [ ]
- these hold values, e.g.
[ { a = 3; b = 2; } ]. In this example, the list holds a single value, that is, the attribute set{ a = 3; b = 2; }.
- these hold values, e.g.
- functions:
arg: bodyargcan be any of these data types, including functions- when
argis an attribute set, some special things apply:- default values can be specified using
arg ? defaultValue, e.g.{ name ? "Default", age }: "${name} is ${age} years old"will yield"X is 20 years old"when called using the attribute set{ name = "X"; age = "20"; }. Otherwise it will yield "Default is 20 years old" when called using{ age = "20"; }. When not passingagein this example, it will throw an error (also not that we had to passageas a string as the value is not cast to a string automatically. Alternatively, we could have passedage = 20;and updated the function body to"${name} is ${builtins.toString age} years old". But that is just a side note)
- default values can be specified using
- when
Let's see this in action:
Calling with explicit values:
swarsel-instantiate 'let f = {name ? "Default", age }: "${name} is ${age} years old"; in f { name = "X"; age = "20"; }'
X is 20 years old
Calling by using a default value with ?:
swarsel-instantiate 'let f = {name ? "Default", age }: "${name} is ${age} years old"; in f { age = "20"; }'
Default is 20 years old
Not passing age errors out:
swarsel-instantiate 'let f = {name ? "Default", age }: "${name} is ${age} years old"; in f { }'
error:
… from call site
at «string»:1:104:
1| let lib = import <nixpkgs/lib>; in let f = {name ? "Default", age }: "${name} is ${age} years old"; in f { }
| ^
error: function 'f' called without required argument 'age'
at «string»:1:44:
1| let lib = import <nixpkgs/lib>; in let f = {name ? "Default", age }: "${name} is ${age} years old"; in f { }
| ^
- the evaluator will error out if it is called with an argument that is not explicitly mentioned in the function definition. Passing a superfluous
anothererrors out:
swarsel-instantiate 'let f = {name ? "Default", age }: "${name} is ${age} years old"; in f { age = "2"; another = "0"; }'
error:
… from call site
at «string»:1:104:
1| let lib = import <nixpkgs/lib>; in let f = {name ? "Default", age }: "${name} is ${age} years old"; in f { age = "2"; another = "0"; }
| ^
error: function 'f' called with unexpected argument 'another'
at «string»:1:44:
1| let lib = import <nixpkgs/lib>; in let f = {name ? "Default", age }: "${name} is ${age} years old"; in f { age = "2"; another = "0"; }
| ^
- this behavior can be suppressed by adding an ellipsis
...to the function arguments ({ name ? "Default", age, ... }:). Adding this ellipsis...to the function definition, we can now passanother:
swarsel-instantiate 'let f = {name ? "Default", age, ... }: "${name} is ${age} years old"; in f { age = "2"; another = "0"; }'
Default is 2 years old
The latter is useful mainly in the NixOS module system, where a lot of things will be passed by default. More on that later.
Finally, we can make the values in ... available by using @ as in extra @ { name, ... }: "${name} likes ${extra.object}":
swarsel-instantiate 'let f = extra @ { name, ... }: "${name} likes ${extra.object}"; in f { name = "Nyx"; object = "nix"; }'
Nyx likes nix
Note that it is equivalent to write {} @ extra:
swarsel-instantiate 'let f = { name, ... } @ extra: "${name} likes ${extra.object}"; in f { name = "Nyx"; object = "nix"; }'
Nyx likes nix
This looks cumbersome on first sight, but is for example useful when referencing flake inputs in the flake outputs, as it allows you to forego listing them all in the arguments (which can be a very long list!). More on that later.
2.1.1.3. Language features
- The functions available to the nix language can be found in the nix reference manual. Some explanations to common functions are provided in Builtin functions.
- Scopes are static in nix; scoped variables are not inherited by the context of the evaluation
- Variables can be created in an enclosing scope using
let <variable declarations> in <expression>. You actually saw me use this several times in the above function call. Note that "usually", you will not be able to declare arbitrary variables; this is because usually we will be working within The module system - in that scope, you either need to resort to thelet ... inconstruct or you need to declare things as module options (more on that later). In general nix however, this would be no problem. - another way to add an expression to the scope is using the
reckeyword:- this adds all attributes of the enclosing attribute
- the following will error out:
- Variables can be created in an enclosing scope using
swarsel-instantiate '
{
a = true;
b = a;
}
'
error: undefined variable 'a'
at «string»:4:9:
3| a = true;
4| b = a;
| ^
5| }
- however,
recmakesaavailable to the scope (also remember that the order of expressions does not matter):
swarsel-instantiate '
rec {
b = a;
a = true;
}
'
{ a = true; b = true; }
- the last way to something to the scope is by using
with:- this adds the passed set to the lexical scope of the enclosing expression:
- the following will error out:
swarsel-instantiate '
let
functions = {
print = v: v;
};
in
print "ok"
'
error: undefined variable 'print'
at «string»:7:5:
6| in
7| print "ok"
| ^
8|
- using
withwill make it work:
swarsel-instantiate '
let
functions = {
print = v: v;
};
in
with functions; print "ok"
'
ok
- generally, the values of the variable in the innermost scope is given precedence in evaluation:
swarsel-instantiate '
let
scope = "outer";
in
let
scope = "inner";
in
scope
'
inner
- the same holds true for
with:
swarsel-instantiate '
with { scope = "outer"; }; with { scope = "inner"; }; scope
'
inner
- you can copy variables from an outer scope by using
inherit (<outer scope>) <name>;- This is syntactic sugar to achieve the same as
<name> = <outer scope>.<name>;
- This is syntactic sugar to achieve the same as
- when not in a string, we can place parentheses around a nix expression to provide its return value to other expressions (remember the
builtins.toString (-1)example from before.-1is indeed a nix expression.) - you can write inline comments using
#and multi-line comments using/* ... */ - The following words are reserved keywords and cannot be used for variable names:
assert,else,if,ininherit,let,or,rec,then,with
2.1.1.4. Operators
The following operators work as you know them from most other programming languages:
- Any operator involving numbers (
+,-,*,/) Side note: When negating a number in actual nix code you will need to wrap it in parentheses nearly every time due to function evaluation:
swarsel-instantiate '
builtins.toString (-1)
'
-1
but:
swarsel-instantiate '
builtins.toString -1
'
error:
… while calling the 'sub' builtin
at «string»:2:21:
1| let lib = import <nixpkgs/lib>; in
2| builtins.toString -1
| ^
3|
… while evaluating the first argument of the subtraction
error: expected an integer but found the built-in function 'toString': «primop toString»
- Logical operators (
!,==,!=,<,>,>=,<=,&&,||)- additionally, logical implications are available as
->(defined as!v1 || v2a.k.a.if v1 then v2 else true)
- additionally, logical implications are available as
The following operators are nix specific:
- Concatenations can be done between strings and paths (in any order) using
+ - List Concatenations however use the
++operator - you can use the
?operator on an attribute set to check whether it has an attribute:
swarsel-instantiate '
{ exists = true; } ? exists
'
swarsel-instantiate '
{ exists = true; } ? noExists
'
| true |
| false |
- Attribute selection (on attribute sets) is done using
.:
swarsel-instantiate '
{ v = 1; }.v
'
1
- Updates to attribute sets are done using The '//' operator
2.1.1.5. Flakes
Next, we shall talk about some concepts regarding nix flakes.
What are flakes? The answer is surprisingly simple: Flakes can be thought of packages that contain nix expressions. They can include other flakes as inputs (acting as libraries if you want) and build on their functionality (in fact, this is exactly what happens when you are using NixOS with nixpkgs). What exactly is provided by a flake is up to the owner entirely, although there are some "norms" that we will get to later.
A directory becomes a flake as soon as it contains a file called flake.nix, which contains an attribute set that has at least an attribute outputs, which must be a function returning an attribute set. Hence, the simplest possible flake is the following:
{
outputs = _: { };
}
What is very nice about flakes is that each flake generates a corresponding flake.lock file the first time a nix command is called targeting it. This file exactly specifies at which revision every flake input should be pulled in. This makes flakes very nice for declaratively setting up development environments that can then be committed to a project; this enables collaborators to do nix develop which will setup a reproducible environment, which is the same for every developer.
That was a very dry introduction. Now, what we are usually interested in when pulling in a flake is any of the following:
- modules to extend our configuration with
- packages that are not in
nixpkgs
and, to a somewhat lesser degree:
- flake templates
devshells
Where these things come from we will learn soon.
2.1.1.5.1. Why flakes
Flakes are, as of writing, an experimental feature in nix, although their interface has been quite stable for a while now - in fact, stable enough that most bigger nix projects are exposing a flake nowadays. People like to (mistakenly) claim that it is because of flakes that we have version pinning in nix. In fact, people were doing this long before flakes were a thing using a construct that looks roughly like this:
let
let pkgs = import (fetchTarball "https://github.com/NixOS/nixpkgs/archive/0b20bf89e0035b6d62ad58f9db8fdbc99c2b01e8.tar.gz") {};
in
pkgs.mkShell {
buildInputs = [ pkgs.cowsay ];
}
This approach simply imports a chunk of nix code that is fetched using fetchTarball - and the version is pinned by the git revision. However, imagine a bigger project; even if you were to import every input like this and pass the expressions to the modules that need them, updating the inputs manually would be a chore. And even though projects like niv and npins exist(/ed) to help with these problems, flakes provide a uniform interface and are reasonably easy to work with, and provide a lot more other stuff on the side.
That being said, some people decide to work without flakes. Depending on the reasoning, I think this is totally fair (as really for the code itself they don't automatically provide a lot of extra functionality that cannot be achieved with other tools). However, some people dismiss flakes for the only reason being "they are too complex" with really is not at all true (which is what I hope to prove to you soon!). A simple project devshell for example could very reasonably be built only from the fetchTarball construct I showed above.
Finally and for completeness sake, a historical note on nix channels.
Nix channels are one of the official mechanisms to provide package sources. They are managed manually through the CLI. A channel would be given a name (like nixpkgs) which could then in nix code be referenced for example like:
{ pkgs ? import <nixpkgs> {} }: ...
Really, this leaves it up to the caller to decide what nixpkgs really is, along with a few other considerations that I do not want to get into. This chapter is intentionally left short; I just want you to know how the pattern above (the <nixpkgs>) looks so that you know what you are working with if you encounter it in the wild.
Channels are not a great tool for reproducibility and I would advise against using them if possible.
2.1.1.5.2. Flake arguments
Let us now talk about arguments that a flake (kind of) expects.
As we already learned, a flake must provide an attribute called outputs (whatever that might mean at this point!). However, unless we want to build everything that our flake provides from the ground up, we probably also want to pass some libraries or build tools to it. This is done using the attribute called inputs. An inputs definition might look something like this:
{
inputs = {
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
hydra = {
url = "github:nixos/hydra/nix-2.30";
inputs.nix-eval-jobs.follows = "nix-eval-jobs";
};
nix-eval-jobs = {
url = "github:nix-community/nix-eval-jobs/v2.30.0";
flake = false;
};
toplevel.url = "./..";
};
}
This is a surprisingly real-world example from my flake.nix (I used this snippet in the past) that we can use so explain most of the important inputs options:
- the most important attribute is
url. It describes where the source should be fetched from. As you can see from thetoplevelinput, you can put as an input a path on the local filesystem. Note that by default, it is expected that every input is itself a flake - meaning, aflake.nixexists there which will be loaded into our flake along with its dependencies. You can also see that we set this tofalsefor thenix-eval-jobsinput. This is usually done when the target project is simply not a flake. Nix will then load in the contents of the repository as a raw file tree.
However, if you go and check out nix-eval-jobs you will see that this project does have a flake.nix, and it is also very active; so what is going on here? In this particular case, this is done to avoid pulling in the dependencies that the nix-eval-jobs would bring along. Instead, the files provided by it must be then made to work using what is provided in the parent flake. This is not a common pattern, but something that is good to know.
Another interesting option is the hydra.inputs.nix-eval-jobs.follows. Let us first talk about the general interface <input>.inputs.<dependency>: This structure allows to customize options for the dependency of a flake input. For example, we could have customized the source of the nix-eval-jobs dependency of hydra had we written hydra.inputs.nix-eval-jobs.url = .... The follows option takes a similar approach by setting an input dependency to the same version as some other input of the parent flake (in our case, it is pinned to the nix-eval-jobs v2.30.0 version).
When we are done defining our flake inputs, we can then decide what our flake should actually do.
As we already learned earlier, outputs is a function returning an attribute set. In fact, it is usually a function that takes as an argument an attribute set containing our inputs, looking roughly like this:
{
inputs.nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
outputs = inputs @ { self, nixpkgs, ... }:
let
inherit (self) outputs;
in
{
nixosConfigurations = {
main = nixpkgs.lib.nixosSystem {
modules = [ "${self}/configuration.nix" ];
specialArgs = {
inherit inputs outputs;
};
};
};
};
}
With what we learned so far, you are already able to understand most of what is going on here:
- outputs is a function that expects
selfandnixpkgsbut tolerates other attributes in the set, and the attribute setinputscan be referenced. - an attribute
outputsis inherited from the outer scopeself, meaningoutputs = self.outputs;(whatselfis and why we can reference theoutputsin the same place where we are defining them I will explain shortly) - the resulting attribute set holds an attribute called
nixosConfigurationsthat holds an attribute calledmain, which is set by calling a function that we now do not want to get into too much.
You might (rightfully!) wonder where the self argument comes from. It is actually not a flake input. Instead, self is a special flake construct that refers to the root of the current flake, meaning all flake attributes can be accessed using self.<attribute>. Moreover, when using self as a path, it refers to the path of the current flake in the nix store. This can be used to reference files within the repository without needing relative paths (this is exactly what happens in self.outputs.nixosConfigurations.main.modules: it loads in configuration.nix, which resides in the same directory as the flake.nix. We could have also written ./configuration.nix here instead).
Another question might be what happens when we load in self.outputs while defining outputs. Normally that should not work? Remember that nix is a lazy language. When outputs is first created in the let ... in block, its value will be something along the lines of outputs = <thunk>;. That means, not all values are loaded upon instantiation, but only whenever they are needed. And if a value is needed, nix will then move on to compute that value.
Of course that does mean that we need to be careful to not introduce circular chains of dependency. Doing that would result in what is called an infinite recursion error, a type of error that can be very hard to wrap one's head around. Luckily, when writing a simple config, you are not very likely to encounter it in a shape that is not rather easily solved.
Like we saw here with nixosConfigurations and some other outputs that we heard about earlier, there are some "standard" outputs that nix recognizes and is able to apply some defaults on. Let us quickly go over them:
I will now list output names and explain what they to; some outputs are what I call "system-scoped". That means they have top-level attribute in the name of system architectures, e.g. x86_64-linux. I will mention when an output is system-scoped. This list is roughly ordered by importance to a NixOS beginner:
nixosConfigurations: A set of NixOS host configurationsdevShells: system-scoped. A set of devshells that can be used by calling nix develop. Defaults to the devshell calleddefault.nixosModules: A set of NixOS Modules. By default, when consuming one of these modules but not specifying which one, the overlaydefaultwill be chosen.overlays: A set of nixpkgs Overlays. By default, when consuming one of these overlays but not specifying which one, the overlaydefaultwill be chosen.checks: system-scoped. Flake checks to perform when calling nix flake checkformatter: system-scoped. Formatting package/config to use when calling nix fmtpackages: system-scoped. Packages that can be directly built using nix buildapps: system-scoped. Packages that can be directly run using nix runtemplates: A set of templates that can be initialized usingnix flake init -t <template name>. By default, thedefaulttemplate will be chosen.legacyPackages: system-scoped. An alternative topackagesthat does not provide guarantees on the structure within. An attribute here might be a package, but it could also be a package set in need of further evaluation. This is used for example innix flake show nixpkgsbecause the number of packages inpackagestakes very long to evaluate. Whenever nix encounters alegacyPackageshowever, it simply displays "omitted" instead of evaluating everything within. In a way you could saylegacyPackagescontains an attribute that is closer to what the structure used by the Channels construct yields.hydraJobs: An arbitrarily deeply nested attribute set of derivations that defines jobs that should run on a hydra build farmbundlers: A set of bundlers (a bundler packages app for usage outside of the nix store). Will choose thedefaultbundler by default
The following are also recognized by nix, but are deprecated:
devShell: system-scoped, deprecated. A single devshell that can be used by calling nix develop.overlay: deprecated. A single overlay.nixosModule: deprecated. A single NixOS module.defaultApp: system-scoped, deprecated. The app that this flake should default to. Instead, you can also defineapps.<system>.default.defaultPackage: system-scoped, deprecated. The package that this flake should default to. Instead, you can also definepackages.<system>.default.defaultTemplates: deprecated. The template that this flake should default to. Instead, you can also definetemplates.default.defaultBundler: deprecated. The bundler that this flake should default to. Instead, you can also definebundlers.default.bundler: deprecated. A single bundler.
Again, you can also define other outputs (for example, a widely used output that is not recognized by nix is homeModules, used in, you guessed it, modules for home-manager). nix flake check will simply emit a warning when it encounters such an output, but there are no other side-effects. Also, keep in mind that flake outputs are things that your flake exposes to others. That means, unless you have written NixOS modules that you want to share with the world, you probably do not need a nixosModules output in your flake.
2.1.1.5.3. References
When interacting with flakes on the CLI, you will always do it in the same style:
<reference>#<attribute path><optional: ^<outputs>>
The flake reference can be an absolute or relative path, but also a URI. It can also be an identifier in the Registries. This means that all of the following are valid (the output to stderr is needed because my flake loads some nix values per default that get printed to the command line on stderr, which org-babel does not capture. This makes the evaluator sad):
nix run nixpkgs#cowsay -- hello 2>/dev/null
nix run github:nixos/nixpkgs#cowsay -- hello 2>/dev/null
nix run .#pkgs.x86_64-linux.cowsay -- hello 2>/dev/null
nix run /home/swarsel/.dotfiles#pkgs.x86_64-linux.cowsay -- hello 2>/dev/null
_______
< hello >
-------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
_______
< hello >
-------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
_______
< hello >
-------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
_______
< hello >
-------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
However:
nix shell n#cowsay^man --command hello
error: unable to execute 'hello': No such file or directory
This happens because the man output of cowsay does not provide the package itself, but only its manpage. nix run reads your mind a little more in that case and makes it available anyway (this is because the apps output is tailored towards running programs):
nix run nixpkgs#cowsay^man -- hello
_______
< hello >
-------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
2.1.1.5.4. Registries
All you really need to know about flake registries is that they provide a shorthand to access flake References easily. By default, the nixpkgs identifier is provided when installing nix with flakes. Additional registries can however be configured (I do this in General NixOS settings (nix config, stateVersion)). For example, I have configured a n identifier that simply mirrors the nixpkgs identifier, which allows me to save on some typing with most nix commands:
nix run n#cowsay -- hello
_______
< hello >
-------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
2.1.1.6. Essential commands
Finally, here are some of the most essential nix commands. Note that there is a "legacy CLI" as well as a "new CLI", the latter of which is enabled by setting =--experimental-features 'nix-command'= or enabling nix.settings.experimental-features = [ "nix-command" ];. I will only talk about the new CLI, which is meant to deprecate the legacy one. Also, these explanations assume that we are interacting with them in flakes (which also need to be separately enabled by appending flakes to the two snippets given above).
2.1.1.6.1. nix shell
This is a very important command. It spawns a subshell in which the commands specified are available. You can pass multiple arguments:
nix shell nixpkgs#cowsay n#bonsai 2>/dev/null
2.1.1.6.2. nix build
This is the essential command to trigger a nix build of stuff. Anything that is a derivation can be built. Typically, these are the packages and legacyPackages outputs of a flake; for these outputs, the full path does not need to be specified. For example, to build the very simple vershell tool from this flake:
nix build .#vershell 2>/dev/null && echo success
success
However, you can also specify the full path
nix build .#packages.x86_64-linux.vershell 2>/dev/null && echo success
success
What is often useful is to build a nixosConfiguration using nix build prior to applying it. E.g. this can be done using the Bakery (Lenovo ThinkPad) host:
nix build .#nixosConfigurations.bakery.config.system.build.toplevel 2>/dev/null && echo success
success
2.1.1.6.3. nix run
This is the command that allows you to run a command directly. These apps are per default defined under the apps output, and that again allows to run them directly instead of specifying the full path. For example to run the swarsel-bootstrap tool that I explore under Apps:
nix run s#swarsel-bootstrap -- -h 2>&1
usage: swarsel-bootstrap [-p ssh-port] [-k] <host> <destination>
2.1.1.6.4. nix develop
This command spins up a development shell in the current directory, provided that the passed nix expression exposes a devshell:
If the current directory has such a flake.nix, you can simply do
nix develop 2>/dev/null
Otherwise you can pass the path (or any flake reference); again, per default the default devshell will be loaded. If you need another one, use the syntax we discussed above. For example, here is how to use a path in the nix store, loading the deploy devshell:
nix develop swarsel#deploy 2>&1
2.1.1.6.5. nix eval
This command evaluates the nix expression given to it:
nix eval .#nixosConfigurations.pyramid.config.networking.hostName 2>/dev/null
"pyramid"
2.1.1.6.6. nix repl
This starts the nix REPL ("Read Evaluate Print Loop"), an interactive environment for evaluating nix expressions for the given environment. Usually you will want to start this pointing to your flake like:
nix repl . 2>/dev/null
Nix 2.30.3 Type :? for help. Using saved setting for 'extra-substituters = https://nix-community.cachix.org' from ~/.local/share/nix/trusted-settings.json. Using saved setting for 'extra-trusted-public-keys = nix-community.cachix.org-1:mB9FSh9qf2dCimDSUo8Zy7bkq5CX+/rkCWyvRCYg3Fs=' from ~/.local/share/nix/trusted-settings.json. Loading installable 'git+file:///home/swarsel/.dotfiles#'... Added 25 variables. apps, checks, darwinConfigurations, darwinConfigurationsMinimal, devShells, diskoConfigurations, formatter, globals, guestConfigurations, homeConfigurations, homeLib, homeModules, legacyPackages, lib, nixOnDroidConfigurations, nixosConfigurations, nixosConfigurationsMinimal, nixosModules, nodes, overlays ... and 5 more; view with :ll
In there you get tab completion and have all functions available that you can use in your flake. This is my preferred command to get insight into what is happening in my config if some error is not obvious.
2.1.1.6.7. nix fmt
This uses the formatter that is defined in the passed flakes formatter output and formats the repository accordingly.
nix fmt 2>&1
Using saved setting for 'extra-substituters = https://nix-community.cachix.org' from ~/.local/share/nix/trusted-settings.json. Using saved setting for 'extra-trusted-public-keys = nix-community.cachix.org-1:mB9FSh9qf2dCimDSUo8Zy7bkq5CX+/rkCWyvRCYg3Fs=' from ~/.local/share/nix/trusted-settings.json. traversed 582 files emitted 387 files for processing formatted 0 files (0 changed) in 24ms
2.1.1.6.8. nix hash
This command allows us to convert between different hash algorithms that are used by nix. The interesting command for us is nix hash convert, which is used like
nix hash convert --from base16 --hash-algo sha1 --to nix32 bb0d59cfdddd37f62fee1e214be3467acffe58df
The supported formats for --from are: base16, nix32, base64, and sri. Per default, nix will try to choose the correct format from the input.
The supported formats for --to are: base16, nix32, base64, and sri. The default is sri.
The supported hashing algorithms for --hash-algo are: blake3, md5, sha1, sha256, and sha512. For SRI hashes, this can be omitted.
2.1.1.6.9. nix flake
This is the main command that we use to interact with our flake. It has several subcommand, but only a few really interest us:
This updates your flake inputs. That means, it will fetch the latest revisions from the inputs.<name> source that we discussed in Flake arguments. By default, all flake inputs will be updates:
nix flake update
It is also possible to only update specific inputs:
nix flake update home-manager
To lock an input from ever updating, a nice trick is to pin it to a specific revision in the inputs' source URL like I do in flake.nix skeleton (inputs) for the nixpkgs-kernelpin input.
This evaluates the entire flake and runs its tests, if there are any.
nix flake check
This lists all outputs of the passed flake. The default is the flake in the current directory. This can be useful to check whether outputs are configured correctly or which templates are exposed by a flake.
nix flake show . 2>/dev/null
This initializes a new flake. Per default it chooses the simple flake that you might have seen before if you ever tried this command. After you already have your own config flake, this command is mainly useful to create a project flake from a template. If you have a flake that exposes templates as outputs, you can list them as shown in nix flake show and then initialize the flake using:
nix flake init -t .#<template name>
Keep in mind that you are free in choosing the flake reference.
2.1.2. nix package manager
In contrast to the nix language, there really is not much important stuff that you need to know about the nix package manager. Just keep in mind that the nix package manager is the tool that the nix language was invented for in the first place. It aims to escape the dependency problems that conventional package managers bring by the mechanisms that we learned about earlier.
In practice, you should never need to install a package with the nix package manager imperatively. For things you only need once you can resort to nix shell or nix run or even comma. Otherwise you should probably make it available in your config or in a devshell.
2.1.3. nixpkgs
Nixpkgs is the name of the community project that provides loads of packages for different architectures and is the main building block that NixOS builds upon.
The main way that we as users interact with nixpkgs (unless we contribute to it) is that we add it as one of the Inputs of our flake. That will provide the majority of packages and modules that we will need to build our system. However, there are a few things that deserves a special mention:
2.1.3.1. Configuring nixpkgs
The main way of configuring nixpkgs is the nixpkgs.config option. There we can configure what packages we want to use. Some flags that we might want to set are:
{ allowUnfree = true; }=to allow packages with an unfree license to be built{ permittedInsecurePackages = [ <package name> ]; }to selectively allow packages that are marked as insecure to be built{ cudaSupport = true; }=to build packages with CUDRA support by default{ rocmSupport = true; }=to build packages with ROCm support by default
2.1.3.2. Overrides
A simple way to modify packages that are already in nixpkgs is the use of overrides. Two main override methods exist:
overridefor overriding the arguments passed to a functionoverrideAttrsfor overriding the attribute set passed tostdenv.mkDervivationoverrideAttrsis used as follows:
pkgs.<package>.overrideAttrs (finalAttrs: previousAttrs: { pname = previousAttrs.pname + "-new"; })
in the wild, this can be used for example directly when installing packages:
{ pkgs, ... }: {
environment.systemPackages = [
(pkgs.hello.overrideAttrs (finalAttrs: previousAttrs: { pname = previousAttrs.pname + "-new"; }))
];
}
For an explanation to override and the overrideAttrs parameters, read on.
2.1.3.3. Overlays
Other than that, we can also extend nixpkgs with packages that it does not normally ship with; this is done using a concept called overlays. An overlay is defined as such
final: prev: { newVesktop = prev.vesktop.override { withSystemVencord = true; }; }
This overlay will add a newVesktop package with a vesktop package that has the withSystemVencord flag set to true to nixpkgs when applied (this is due to override overriding the arguments of the vesktop package; such flags can be found by checking out the source of the package. To find that source. you can use the nix package search to search for a package, and then click the "source" button, which for the vesktop example yields this GitHub page. There you will also see that withSystemVencord defaults to false.). In this case of course, this has the same effect as simply using an override, so this is better used for adding new packages.
When installing newVesktop afterwards, we will get a vekstop that will have system vencord enabled. Overlays can also be added by referencing a flake overlay output. Here is an example of how to use both of these methods in practice:
{ outputs, inputs, ... }:
{
nixpkgs.overlays = [
outputs.overlays.this
inputs.someExternalFlake.overlays.default
(final: prev: { vesktop = prev.vesktop.override { withSystemVencord = true; }; })
];
}
This will add the previous vesktop override as well as the this overlay from our flake (keep in mind that outputs refers to the outputs that our flake exposes) and the default overlay from a flake input called someExternalFlake.
Also keep the parentheses around the inline overlay in mind; we need to pass whole elements to the list, so we use parentheses to evaluate a nix expression. This is the standard equivalent to the ${} approach that we took with strings, as you remember.
2.1.4. NixOS
NixOS is the name of the Linux distribution that relies on the nix package manager. NixOS also relies heavily on nixpkgs to provide packages, library functions, and modules. The one part this really important to understand here is the module system.
2.1.4.1. The module system
The module system can be thought of a nix library acts as an extension to nix in NixOS. It much enhances the ways in which we can set values within "the configuration" - for example, it becomes possible to set something like environment.systemPackages in two files, and both set values will be merged. Also, to these so-called "options" we can easily add type checking.
2.1.4.1.1. Modules
This provides a broad overview over the module system.
On a very high level, a module is just a function returning an attribute set. Hence the simplest possible module should be:
_: { }
Actually, because of syntactic sugar, the module arguments can be omitted if they are not accessed at all, so the simplest simplest module is actually:
{ }
but that is just a note for completeness sake.
In the module systems, the above attribute sets supports three main options:
imports, which allows for importing further filesoptions, for declaring Nix options that should be added to the module systemconfig, for setting said options.
imports is a simple list that takes paths to other nix files and adds them to be evaluated by the module system:
_:
{
imports = [
./configuration.nix
./extras
]
}
The module system will pass an attribute as an argument to this function. When a module requires no args from the outer scope. As soon as you pass any argument however, you also need to pass the ellipsis ... to the attribute set. This is because the module systems always adds the following arguments to each module contained within:
libfor library functionspkgsthe set of packages of the systems architectureoptions, the option declarations. Note that you only need to import this if you need the access the option declarations themselves. You will not need this for declaring options in a modules - i.e. you will only need to add this very rarelyconfig, the option definitions - you need this whenever you want to access configuration parts that has been defined somewherethe set of values passed to
specialArgsin the call tonixpkgs.lib.nixosSystem. To that, everything should be added that is needed to be evaluated when resolving the model structure (e.g. imports)specialArgsincludesmodulesPath, which can be used to importnixpkgsmodules without knowing their location in the nix store- this happens by default in
hardware-configuration.nix:
- this happens by default in
{ modulesPath, ... }: { imports = [ (modulesPath + "/installer/scan/not-detected.nix") ]; };
Remember now what we said above: here we now need to pass the ellipsis ..., only { modulesPath } would error out because of the other passed arguments. _ works because that accepts any value.
- any values set under
_module.args(sometimes you might seeextraArgs; that has been deprecated in favor of_module.args)
If a directory is passed to imports, nix will look for a file called default.nix in the passed directory.
Options are declared (not defined) using lib.mkOption (or one of its derivatives, like lib.mkEnableOption, which creates a boolean option defaulting to false)
{ lib, ... }:
{
options.myBool = lib.mkOption {
type = lib.types.bool;
default = true;
description = "An example of a boolean option definition.";
};
}
config is what we use to actually set the values for which we declared options somewhere. Note that an option does not need to be declared in the same file where it is set (in fact, option declarations need to be unique across the entire module system). We call the process of setting a value under config.<name> an option definition.
We can extend our module from options:
{ lib, ... }:
{
options.myBool = lib.mkOption {
type = lib.types.bool;
default = true;
description = "An example of a boolean option definition.";
};
config.myBool = false;
}
This will define config.myBool to be false, which can now be referenced in another file under config.myBool.
If a file does not use either imports or options but only config, you can omit the config attribute:
{ pkgs, ... }:
{
environment.systemPackages = [ pkgs.cowsay ];
}
If we would however declare options in the same file, we would need to write:
{ lib, pkgs, ... }:
{
options.myDo = lib.mkEnableOption "do it"; # this expects a string that will be prepended by "whether to" and appended a dot
config.environment.systemPackages = [ pkgs.cowsay ];
}
3. flake.nix
Handling the flake.nix file used to be a bit of a chore, since it felt like writing so much boilerplate code just to define new systems. For a while, I used noweb-ref in order to alleviate this problem (see Appendix A: Noweb-Ref blocks, an example of the repository at that time would be acc0ad6: Add several NixOS hosts on Proxmox and Oracle Cloud.). However, the true answer laid in making use of built-in nix functionality.
Nowadays, I use flake-parts in conjunction with flake-file to manage my flake. It allows me to conveniently split the actual flake into multiple files ("parts") using the following mechanism:
importsare files pulled in to build the flake configuration (similar to the imports in the module system)systemsdefines the architectures that the flake should be provided for - I go here for the four "main" architectures, although true support is only provided for Linux systems (see Packages (pkgs) for the main reason)
The above two are used in Outputs by flake-file; flake-file allows to fetch the actual input URLs etc. from the corresponding features where they are used. I think this is a lot more concise than manually curating the separate flake.nix. Some attention must be paid since flake-file assumes the flake to be able to fully evaluate. Hence, if the input-defining features also try to import said inputs in some way, a bootstrapping problem can arise if that input is not yet in the flake.nix - this can be circumvented by doing a conditional import (see for example Topology (nix-topology generated network diagram) with the optionalAttrs).
3.1. flake.nix skeleton (inputs)
In general, a nix flake consists of one or more inputs and several outputs. The inputs are used to define where nix should be looking for packages, modules, and more (the most common input is nixpkgs, which provides a lot of packages, library functions and modules). The outputs generate expressions that can be used in .nix files as well as system configurations using these files.
In the start, I enable some public cache repositories. This saves some time during rebuilds because it avoids building as many packages from scratch - this is mainly important for community flakes like emacs-overlay, which basically would trigger a rebuild whenever updating the flake. The repository does of course not hold everything, but it lightens the pain. It would look cleaner if this were to be used only inside a nix configuration block of an actual system, but I want these caches to be used for e.g. app calls as well.
In many flakes, you see a structure like this: outputs = inputs@ [...], the inputs@ makes it so that all inputs are automatically passed to the outputs and can be called as inputs.<name>, whereas explicit arguments may just be called by using <name>. For most flakes this is fully sufficient, as they do not need to be called often and it saves me maintenance effort with this file. In fact, I also used to make use of this mechanism. However, using flake-parts, all I really need for the outputs function is inputs, which is why I used to do
outputs = inputs: inputs.flake-parts.lib.mkFlake { inherit inputs; } { [...] }.
Note that flake-parts must inherit these inputs and no other arguments are expected. flake-file makes this obsolete (again).
In this section I am creating some attributes that define general concepts of my configuration:
nixosModulesimports self-defined options that I only want to use on NixOS systems. All modules are held as separately as possible, to allow for easier sharing with other people mostly.homeModulesimports modules that are to be used on NixOS and non-NixOS systems. These are mostly used to define outputs (monitors), keyboards and special commands for machines.packagesholds packages that I am building myself. These are mostly shell scripts, but also a few others such as AppImages and Firefox addons.devShellsprovides a development shell that can be used as a bootstrap for new installs usingnix developwhile inside the flake directory. It received an overhaul in0a6cf0e feat: add checks to devShell, since when it is handled usingforAllSystemsand now including pre-commit-hook checks.formatterprovides the formatter that is to be used on.nixfiles. It can be called by usingnix fmt.checkprovides the pre-commit-hook checks that I have explained in Devshell (checks).overlaysimports a few community overlays (such as the Emacs-overlay) and also three overlays of my own:additionsholds derivations that I am adding myself to nixpkgs - i.e. this is where the packages defined in/pkgsget added to nixpkgs.modificationsholds derivations that I have performed overrides on. The list of interesting attribute overrides can be found by looking at the source code of a derivation and looking at the start of the file for lines of the form<name> ? <val>. But this can also be used to, for example, fetch a different version of a package instead.nixpkgs-stableholds the newest version of stable nixpkgs. I only use this on packages that seem broken on unstable, which are not many.zjstatusholds the status bar plugin forzellij.
They are defined in Overlays. The way this is handled was simplified in
647a2ae feat: simplify overlay structure; however, the old structure might be easier to understand as a reference.
I no longer maintain flake.nix by hand. It is generated by flake-file: some required inputs (nixpkgs, flake-parts, import-tree, and flake-file) (and some where I was too lazy to find an appropriate spot) are declared in modules/flake/_flake-file.nix, while every other input is declared right next to the feature that actually uses it, via a flake-file.inputs.<name>.url attribute at the top of that features module. Running nix run .#write-flake gathers all of these declarations (the merged config.flake-file.inputs) and regenerates flake.nix.
Many inputs set nixpkgs.follows: this tells an input to not pull in its own copy of nixpkgs, but instead 'nest' itself into mine, which for one avoids duplicate nixpkgs evaluations (saving space - whatever). However, what this also does it supplying that input with a version of nixpkgs that might be the needed/supported one for the infrastructure. I try to only do a follows if the consuming package actually needs it - I do not care about the marginal space savings.
A short overview over each notable input and what it does (NOTE: I usually forget updating this list):
- nixpkgs This is the base repository that I am following for all packages. I follow the unstable branch. Also I pull in some older revisions of nixpkgs stable for various purposes.
- home-manager
This handles user-level configuration and mostly provides dotfiles that are generated and symlinked to
~/.config/. - swarsel-nix This pulls in the very dotfiles you are currently reading. I am adding this to the flake registry in order to
- NUR The nix user repository contains user provided modules, packages and expressions. These are not audited by the nix community, so be aware of supply chain vulnerabilities when using those. I am only really using rycee's Firefox addons from there which saves me a lot of hassle, and it seems to be a safe resource.
- nixGL
This solves the problem that nix has with
OpenGL, as libraries are not linked and programs will often fail to find drivers. Nowadays, this is included in the nixGL module of home-manager, but even that requires a binary for nixGL, which is what I pull from this input. - stylix As described before, this handles all theme related options.
- sops-nix This provides declarative secrets management for NixOS and home manager using sops and age keys. It is a bit more cumbersome to use on home manager systems - which is a bother because I then have to resort to that configuration to keep everything supported - but it is super practical and really the primary reason why it makes sense for me to go for NixOS, as I do not have to do any extra secrets provisioning.
- Lanzaboote Provides secure boot for NixOS. Needed for my Surface Pro 3.
- nix-on-droid This brings nix to android in an app that is similar to tmux! Of course most of the configuration does not apply to this, but it is still neat to have!
- nixos-hardware Provides specific hardware setting for some hardware configurations. For example, this sets some better defaults for my Lenovo Thinkpad P14s Gen2.
- nixos-generators Provides me with images that I can use to create LXCs on Proxmox.
- nswitch-rcm-nix Allows auto injection of payloads upon connecting a Nintendo Switch.
- nix-index-database
This provides a database for
nix-indexthat is updated weekly. This allows for declarative management, without needing to run thenix-indexcommand for database assembly. - disko
diskoprovides declarative disk partitioning, which I use for impermanence as well as nixos-anywhere. - Impermanence Some of my machines are using a btrfs filesystem that wipes the root directory on each reboot. This forces me to pay more attention in keeping my system declarative as well as helping me keeping the system uncluttered. However, it is a chore to make sure that important files are not deleted. This flake helps with this problem, allowing me to select files and directories for persisting.
- zjstatus This provides the status bar plugin that I use in zellij.
- nix-darwin After learning that MacOS systems can also be configured using nix, I managed to get access to an old Mac Book for testing. This allows to set most general settings that can otherwise be set using the Mac GUI.
- pre-commit-hooks Provides access to several checks that can be hooked to be run before several stages in the process.
- nix-topology This automatically creates a topology diagram of my configuration.
- flake-parts The aforementioned system that allows for more convenient flake crafting.
- devshell This provides devshell support for flake-parts
- spicetify This is a improved Spotify client. This provides a NixOS module to manage it.
- niri-flake This is an optional input that I reserve to use in the future; it provides a module to manage Niri in a way that is way more all-encompassing than the current modules in nixpkgs/home-manager. However, I do not include this by default as this leads to a full compilation of latest Niri - this is used only be the Niri config evaluator, but is even built if Niri is not included in the final config. Also, the binary cache provided by this flake does usually not have the latest Niri cached.
- microvm.nix This flake brings support for MicroVMs to nix. This is basically a more isolated alternative to classic NixOS containers, while keeping most of their benefits.
- treefmt-nix
This allows to specify a range of formatters for different languages and aspects which can all be run upon
nix fmt. nixos-extra-modules This is a collection of modules that add some qualitative functions to several aspects of nix, for example:
- MicroVM management
- WireGuard support for nix-topology
- some extensions to the network library
At the moment I am not using the full range of modules, but my usage keeps increasing steadily. Using this module forced me to make some adjustments in my config, namely exposing the
nodesoutput in Hosts.- dns.nix
This adds a module that helps with creating zone files (like DNS zone - site1). This flake was competing with NixOS-DNS for my favor - while the latter adds many nice utilities that generate records straight from a host configuration, I prefer to do this myself using the Globals + Share sconfiguration between nodes (automatically active) systems. In the end, I just tried out
dns.nixwithout giving NixOS-DNS a chance and it has been working great, but I believe NixOS-DNS still deserves a mention here, as it would have been a great fit as well, most likely. - nix-minecraft This adds a module that makes it easier to manage (modded) Minecraft servers. At the moment, it does not really work with Forge 1.20.1 (which is what my server is running), so I am not making full use of it right now, but I keep close watch on it every day.
- nixos-mailserver This adds a module that basically sets up a full mail server stack. Apart of DNS records and a few extra steps for e.g. a web client, this is one-stop solution that has been working greatly for me.
- nixos-nftables-firewall This flake introduces a module that allows for more structured nftables config.
- topologyPrivate
This input per default provides a simple output
topologyPrivate = false;. This is the value that is normally used in the config. When I export my setup to a topology diagram, there are some public IPs and domains that I want to obfuscate. When doing that, I can then override this input. - noctalia
A flake that provides options for the desktop shell
noctalia-shell. - niritiling A flake that provides automatic window tiling for the first column in Niri
- noctoggle A flake that toggles the Noctalia-shell bar when a modifier key is pressed
- flake-file
Allows to generate
flake.nixfrom the inputs that feature declare locally - import-tree Recursively imports every module file under a given path, which is what lets the dendritic structure work without a hand-maintained list of imports.
- systems Provides the canonical list of systems that I iterate over when building per-system outputs.
- emacs-overlay Provides bleeding-edge Emacs as well as an up-to-date set of Emacs packages, which I pull in through my overlay.
- nur-expressions
Provides rycee's
emacs-inithome-manager module, which I use to generate my Emacs configuration (see Home-manager: Emacs) - vbc-nix A private flake for my work setup, providing work-specific packages and overlays. It is fetched over SSH and is stripped out by the deployment scripts when I do not have access to it.
- nixos-images Provides the kexec-installer module that I use to build my kexec image.
- smallpkgs A nixpkgs revision pinned to a shallow checkout, used only to keep the kexec image build as small as possible. Essentially this is an old nixpkgs revision where the size was simply still smaller.
- copyparty Provides the NixOS module for the CopyParty file server.
- invidious-companion Provides the companion helper service that my Invidious instance needs.
- nginx-otel Provides an NGINX module extension that adds OpenTelemetry support.
# DO-NOT-EDIT. This file was auto-generated using github:denful/flake-file.
# Use `nix run .#write-flake` to regenerate it.
{
description = "SwarseFlake - Nix Flake for all SwarselSystems";
inputs = {
copyparty = {
inputs = {
flake-utils.follows = "flake-utils";
nixpkgs.follows = "nixpkgs";
};
url = "github:9001/copyparty/hovudstraum";
};
devshell = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:numtide/devshell";
};
disko = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:nix-community/disko";
};
dns = {
inputs = {
flake-utils.follows = "flake-utils";
nixpkgs.follows = "nixpkgs";
};
url = "github:kirelagin/dns.nix";
};
emacs-overlay = {
inputs = {
nixpkgs.follows = "nixpkgs";
nixpkgs-stable.follows = "nixpkgs-stable";
};
url = "github:nix-community/emacs-overlay";
};
flake-file.url = "github:vic/flake-file";
flake-parts = {
inputs.nixpkgs-lib.follows = "nixpkgs";
url = "github:hercules-ci/flake-parts";
};
flake-utils = {
inputs.systems.follows = "systems";
url = "github:numtide/flake-utils";
};
follow-nix = {
inputs = {
flake-parts.follows = "flake-parts";
git-hooks-nix.follows = "pre-commit-hooks";
nixpkgs.follows = "nixpkgs";
treefmt-nix.follows = "treefmt-nix";
};
url = "github:Swarsel/follow-nix";
};
glide-nix = {
inputs = {
home-manager.follows = "home-manager";
nixpkgs.follows = "nixpkgs";
};
url = "github:glide-browser/glide.nix";
};
hint-selectors = {
inputs = {
flake-parts.follows = "flake-parts";
nixpkgs.follows = "nixpkgs";
pedantix.follows = "pedantix";
systems.follows = "systems";
treefmt-nix.follows = "treefmt-nix";
};
url = "github:Swarsel/hint-selectors";
};
home-manager = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:nix-community/home-manager";
};
hunkle = {
inputs = {
flake-parts.follows = "flake-parts";
git-hooks-nix.follows = "pre-commit-hooks";
nixpkgs.follows = "nixpkgs";
treefmt-nix.follows = "treefmt-nix";
};
url = "github:Swarsel/hunkle";
};
impermanence = {
inputs = {
home-manager.follows = "home-manager";
nixpkgs.follows = "nixpkgs";
};
url = "github:nix-community/impermanence";
};
import-tree.url = "github:vic/import-tree";
invidious-companion = {
flake = false;
url = "https://github.com/iv-org/invidious-companion/releases/download/release-master/invidious_companion-x86_64-unknown-linux-gnu.tar.gz";
};
lanzaboote = {
inputs = {
nixpkgs.follows = "nixpkgs";
pre-commit.follows = "pre-commit-hooks";
};
url = "github:nix-community/lanzaboote";
};
microvm = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:astro/microvm.nix";
};
niri = {
flake = false;
url = "github:niri-wm/niri/v26.04";
};
niri-flake = {
inputs = {
niri-unstable.follows = "niri";
nixpkgs.follows = "nixpkgs";
nixpkgs-stable.follows = "nixpkgs-stable";
};
url = "github:sodiboo/niri-flake";
};
niritiling = {
inputs = {
flake-parts.follows = "flake-parts";
git-hooks-nix.follows = "pre-commit-hooks";
nixpkgs.follows = "nixpkgs";
treefmt-nix.follows = "treefmt-nix";
};
url = "github:Swarsel/niritiling";
};
nix-darwin = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:lnl7/nix-darwin";
};
nix-index-database = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:nix-community/nix-index-database";
};
nix-minecraft = {
inputs = {
nixpkgs.follows = "nixpkgs";
systems.follows = "systems";
};
url = "github:Infinidoge/nix-minecraft";
};
nix-on-droid = {
inputs = {
home-manager.follows = "home-manager";
nixpkgs.follows = "nixpkgs";
nixpkgs-docs.follows = "nixpkgs";
};
url = "github:nix-community/nix-on-droid";
};
nix-topology = {
inputs = {
flake-parts.follows = "flake-parts";
nixpkgs.follows = "nixpkgs";
};
url = "github:Swarsel/nix-topology/dev";
};
nixgl = {
inputs = {
flake-utils.follows = "flake-utils";
nixpkgs.follows = "nixpkgs";
};
url = "github:guibou/nixGL";
};
nixos-extra-modules = {
inputs = {
devshell.follows = "devshell";
flake-parts.follows = "flake-parts";
nixpkgs.follows = "nixpkgs";
pre-commit-hooks.follows = "pre-commit-hooks";
};
url = "github:Swarsel/nixos-extra-modules/dev";
};
nixos-hardware = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:NixOS/nixos-hardware/master";
};
nixos-home-assistant = {
inputs = {
flake-parts.follows = "flake-parts";
git-hooks-nix.follows = "pre-commit-hooks";
nixpkgs.follows = "nixpkgs";
pedantix.follows = "pedantix";
treefmt-nix.follows = "treefmt-nix";
};
url = "github:Swarsel/nixos-home-assistant";
};
nixos-images.url = "github:Swarsel/nixos-images/main";
nixos-nftables-firewall.url = "github:thelegy/nixos-nftables-firewall";
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
nixpkgs-dev.url = "github:Swarsel/nixpkgs/main";
nixpkgs-firezone.url = "github:Swarsel/nixpkgs/1fef1eb69b3f8f9a778441b386eadbb1fa3fa436?narHash=sha256-HY1UfmtZOuk7Y+9cTIF8Kx5TV7qOTtRqk7A+W6lyMm8%3D";
nixpkgs-kernelpin.url = "github:nixos/nixpkgs/31ecbaca1bdefa45dffc409f0250bd8039ea0010?narHash=sha256-dhoW6VgFWlaodSY5jrBn%2BCF2FLmaUvDVgM7%2BC7T2%2BNM%3D";
nixpkgs-sandbox.url = "github:r-ryantm/nixpkgs/4800f20ae2dc52cc7422118d28d427ef412f0841";
nixpkgs-stable.follows = "nixpkgs-stable26_05";
nixpkgs-stable24_11.url = "github:NixOS/nixpkgs/nixos-24.11";
nixpkgs-stable25_05.url = "github:NixOS/nixpkgs/nixos-25.05";
nixpkgs-stable26_05.url = "github:NixOS/nixpkgs/nixos-26.05";
noctalia = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:noctalia-dev/noctalia-shell";
};
noctalia-greeter = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:noctalia-dev/noctalia-greeter";
};
noctoggle = {
inputs = {
flake-parts.follows = "flake-parts";
git-hooks-nix.follows = "pre-commit-hooks";
nixpkgs.follows = "nixpkgs";
treefmt-nix.follows = "treefmt-nix";
};
url = "github:Swarsel/noctoggle";
};
nswitch-rcm-nix = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:Swarsel/nswitch-rcm-nix";
};
nur = {
inputs = {
flake-parts.follows = "flake-parts";
nixpkgs.follows = "nixpkgs";
};
url = "github:nix-community/NUR";
};
nur-expressions = {
flake = false;
url = "gitlab:rycee/nur-expressions";
};
pedantix = {
inputs = {
flake-parts.follows = "flake-parts";
git-hooks-nix.follows = "pre-commit-hooks";
nixpkgs.follows = "nixpkgs";
treefmt-nix.follows = "treefmt-nix";
};
url = "github:Swarsel/pedantix";
};
piix = {
inputs = {
flake-parts.follows = "flake-parts";
git-hooks-nix.follows = "pre-commit-hooks";
nixpkgs.follows = "nixpkgs";
pedantix.follows = "pedantix";
systems.follows = "systems";
treefmt-nix.follows = "treefmt-nix";
};
url = "git+ssh://forgejo@swagit.swarsel.win:2222/swarsel/piix.git?ref=main-devel";
};
pre-commit-hooks = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:cachix/git-hooks.nix";
};
seerr-oidc = {
flake = false;
url = "github:michaelhthomas/seerr/feat/oidc-login-basic";
};
shopservatory = {
inputs = {
flake-parts.follows = "flake-parts";
git-hooks-nix.follows = "pre-commit-hooks";
nixpkgs.follows = "nixpkgs";
treefmt-nix.follows = "treefmt-nix";
};
url = "github:Swarsel/shopservatory";
};
simple-nixos-mailserver = {
inputs = {
git-hooks.follows = "pre-commit-hooks";
nixpkgs.follows = "nixpkgs";
};
url = "gitlab:simple-nixos-mailserver/nixos-mailserver/main";
};
smallpkgs.url = "github:nixos/nixpkgs/08fcb0dcb59df0344652b38ea6326a2d8271baff?narHash=sha256-HXIQzULIG/MEUW2Q/Ss47oE3QrjxvpUX7gUl4Xp6lnc%3D";
sops = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:Mic92/sops-nix";
};
sops-rekey = {
inputs = {
nixpkgs.follows = "nixpkgs";
sops-nix.follows = "sops";
};
url = "github:Swarsel/sops-rekey";
};
spicetify-nix = {
inputs = {
nixpkgs.follows = "nixpkgs";
systems.follows = "systems";
};
url = "github:Gerg-l/spicetify-nix";
};
stylix = {
inputs = {
flake-parts.follows = "flake-parts";
nixpkgs.follows = "nixpkgs";
nur.follows = "nur";
systems.follows = "systems";
};
url = "github:danth/stylix";
};
swarsel-nix = {
inputs = {
flake-parts.follows = "flake-parts";
nixpkgs.follows = "nixpkgs";
systems.follows = "systems";
};
url = "github:Swarsel/swarsel-nix/main";
};
systems.url = "github:nix-systems/default";
topologyPrivate.url = "./files/topology/public";
treefmt-nix = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:numtide/treefmt-nix";
};
vbc-nix = {
inputs = {
nixpkgs.follows = "nixpkgs-stable26_05";
nixpkgs-2411.follows = "nixpkgs-stable24_11";
nixpkgs-mcp.follows = "nixpkgs-stable26_05";
nixpkgs-mcp-unstable.follows = "nixpkgs";
nixpkgs-unstable.follows = "nixpkgs";
systems.follows = "systems";
};
url = "git+ssh://git@github.com/vbc-it/vbc-nix.git?ref=main";
};
yubikey-touch-alarm = {
inputs = {
flake-parts.follows = "flake-parts";
git-hooks-nix.follows = "pre-commit-hooks";
nixpkgs.follows = "nixpkgs";
treefmt-nix.follows = "treefmt-nix";
};
url = "git+ssh://forgejo@swagit.swarsel.win:2222/swarsel/yubikey-touch-alarm";
};
zjstatus = {
inputs = {
flake-utils.follows = "flake-utils";
nixpkgs.follows = "nixpkgs";
};
url = "github:dj95/zjstatus";
};
};
outputs = inputs: import ./modules/flake/_outputs.nix inputs;
}
3.2. Library functions
This section defines all functions of my own that I add to lib. These are used in all places over the config, however mainly in the files responsible for handling various imports.
A breakdown for the functions that have a non-obvious purpose:
pkgsFor: This function reads all available systems from nixpkgs and generates pkgs for them. This is needed for my generation of home-manager and nix-on-droid systems in Hosts.- uses nixpkgs.lib.genAttrs
- Also, in that function I am defining the
pkgsthat should be used when I referencepkgsin the actual configuration. I want to make sure that the correct system is used (keep in mind this is for home-manager configurations, which need that info! As a remark, you would not set this for a NixOS host), that I load my Overlays (extra packages and modifications that I add topkgs), as well as a setting that allows me to install unfree software. As a base package set I choosenixpkgsfrom my inputs (and so does nearly every configuration out there. Keep in mind however that you could use any package set here!nixpkgshowever also comes with a lot of usefullibfunctions (that are notbuiltinsto the nix language!))
mkTrueOption: Defines a NixOS module option that is by default enables (as opposed tomkEnableOptionwhich are per default disabled).- uses lib.mkOption to create the defaulted option.
mkStrong:- An alias for (nixpkgs.lib.mkOverride 60), which is higher than setting an option normally (i.e.
option = value; which has priority 100), but being of lower priority than using nixpkgs.lib.mkForce, which has priority 50 (lower priority takes precedence). For completeness' sake, the priority set when using nixpkgs.lib.mkDefault is 1000 (a very low value).
- An alias for (nixpkgs.lib.mkOverride 60), which is higher than setting an option normally (i.e.
forEachLinuxSystem: performs thepkgsForfunction for a set ofsystems(here:x86_64-linuxandaarch64-linux). I need to use this in the Packages (pkgs) section in order to avoid trying to build those packages for Darwin systems.- uses nixpkgs.lib.genAttrs
readHosts: Reads the names of directories under thehosts/folder for a particular system type- uses builtins.readDir
- uses nixpkgs.lib.attrNames to acquire attribute names from the outputs of
builtins.readDir
readNix: reads all files in a directory that are notdefault.nix(usually used to simply load everything from a folder and is called inside that respectivedefault.nix).- uses builtins.readDir
- uses nixpkgs.lib.attrNames to acquire attribute names from the outputs of
builtins.readDir
mkImports: These are used to help with importing files mostly:- uses nixpkgs.lib.map to actually import the list of modules that are passed to
mkImportsin names.
- uses nixpkgs.lib.map to actually import the list of modules that are passed to
cidrToSubnetMask: this takes in an IP address in CIDR notation (for example 192.168.1.0/24) and returns the matching subnet-mask (here: 255.255.255.0)- uses nixpkgs.lib.toInt to grab the CIDR mask as an int
- uses nixpkgs.lib.genList to both get the bit-wise representation of said CIDR mask as well as converting it to the octet notation of the subnet mask.
- uses nixpkgs.lib.concatStringsSep to build the final subnet most of the octets calculated.
mkIfElseListgenerates either one or another list based on a conditional- uses nixpkgs.lib.mkMerge to merge the results of the de-facto
ifandelse, yielding a single list in the end.
- uses nixpkgs.lib.mkMerge to merge the results of the de-facto
getBaseDomaintakes in a domain (likesub.about.com) and extracts only the base domain (here:about.com)- uses nixpkgs.lib.split to get the parts of the input domain
- uses nixpkgs.lib.filter to keep only the non-empty strings (checking using nixpkgs.lib.isString) from the list generated by split
- uses nixpkgs.lib.tail to strip the subdomain which keeps the base domain and then conjoins the remaining two elements using nixpkgs.lib.concatStringsSep. Indeed this means that this function would break for deeper subdomain nestings, but so far I am not using these.
getSubDomainworks in a similar way on a domain subdomain (for the above example:sub)- works similar to
getBaseDomainbut I also calls nixpkgs.lib.length to make sure we have an element left which we then grab by nixpkgs.lib.head.
- works similar to
toCapitalized: returns the capitalized version of a string ("about"->"About")- uses nixpkgs.lib.stringLength to prevent working on an empty string
- nixpkgs.lib.subString as well as
nixpkgs.lib.toUpperandnixpkgs.lib.toLowerto build the respective capitalized string
root: for a long time, I just resorted toselfwhenever I wanted to refer to the root of the flake. However, for files that were used in derivations, this incurred the cost of rebuilding the derivation whenever the flake changed in any way. I only noticed this once I added a custom patch to Niri. This function simply replaces this with a call tobuiltins.path, and I then import therootfunction asspecialArgseverywhere.
Concerning the flake = [...] part:
- this is a mechanism introduced by flake-parts. A
flakeoutput is akin to a 'normal' output of a standard nix flake (meaning, it will not be built specifically for each system defined bymkFlake) libis then defined asnixpkgs.libextended (using its.extend()method) with home-manager'shmhelper namespace (so that I can uselib.hm.*) and the customswarselsystemsfunctions that I define in the let-block
{ self, inputs, ... }:
let
swarselsystems =
let
inherit (inputs) systems;
inherit (inputs.nixpkgs) lib;
domainParts = domain: builtins.filter (part: part != "") (lib.splitString "." domain);
in
rec {
inherit (inputs.piix.lib.mkPii { lock = "${self}/secrets/pii.lock"; }) importEncrypted;
cidrToSubnetMask =
cidr:
let
prefixLength = lib.toInt (lib.last (lib.splitString "/" cidr));
bits = lib.genList (i: if i < prefixLength then 1 else 0) 32;
in
lib.concatMapStringsSep "." (
i: toString (lib.foldl (acc: bit: acc * 2 + bit) 0 (lib.sublist (i * 8) 8 bits))
) (lib.range 0 3);
darwinSystems = builtins.filter (lib.hasSuffix "-darwin") (import systems);
forEachLinuxSystem = f: lib.genAttrs linuxSystems (system: f pkgsFor.${system});
getBaseDomain = domain: lib.concatStringsSep "." (lib.drop 1 (domainParts domain));
getSubDomain = domain: lib.concatStrings (lib.take 1 (domainParts domain));
linuxSystems = builtins.filter (lib.hasSuffix "-linux") (import systems);
mkStrong = lib.mkOverride 60;
mkTrueOption = lib.mkOption {
default = true;
type = lib.types.bool;
};
pkgsFor = lib.genAttrs (import systems) (
system:
import inputs.nixpkgs {
inherit system;
config = {
allowUnfree = true;
permittedInsecurePackages = [
# matrix
"olm-3.2.16"
];
};
overlays = [
self.overlays.default
self.overlays.stables
self.overlays.modifications
];
}
);
readNix = type: lib.remove "default.nix" (lib.attrNames (builtins.readDir "${self}/${type}"));
root =
subpath:
builtins.path {
name = builtins.baseNameOf subpath;
path = "${self}/${subpath}";
};
toCapitalized =
str:
lib.toUpper (builtins.substring 0 1 str)
+ lib.toLower (builtins.substring 1 (builtins.stringLength str) str);
};
in
{
flake = {
lib = inputs.nixpkgs.lib.extend (
_: _: {
inherit (inputs.home-manager.lib) hm;
inherit swarselsystems;
}
);
swarselsystemsLib = swarselsystems;
};
_module.args.root = swarselsystems.root;
}
3.3. Packages (pkgs)
This does not use perSystem from flake-parts for package outputs, since some of my custom packages are not able to be built on Darwin systems, and I was not yet interested in writing logic for handling that. Instead I use forEachLinuxSystem as described in Library functions in order to only build this for Linux hosts.
Other nix users can make use of these packages either by installing them directly in their config (using my flake as an input and then installing <packages.<systems>.<name>) or by making use of the overlay that I provide in Overlays. In the latter case all packages will be made available to the consuming flake.
You might now be wondering why I then have a perSystem in this file. This has to do with the nixos-extra-modules flake output that I pulled in in flake.nix skeleton (inputs): it provides a few library functions that I want to use in the Globals system. Since however these globals are evaluated to a flake output I need to make sure that these library functions are not only available from within a configuration, but also as a callable expression in the flake - and of course they also should be available in configurations. Generally, lib exists under pkgs, which means that it is built for an architecture. So, if I want to expand lib, I need to make sure this is done for all architectures. For that, I extend the flake-parts perSystem options by a pkgs option using mkTransposedPerSystemModule. This points to a file that will specify the correct pkgs - in this case, this is the same file. We then add a module argument named pkgs which can no make use of the system parameter thanks to what we did above, and set the correct overlay - the self.overlay.defaults includes the overlay from nixos-extra-modules that we need (see Overlays). Finally, we make this pkgs available as an output.
The _module.args part is needed because we need to set/override the flake-parts pkgs as per https://flake.parts/module-arguments.html?highlight=modulewith#pkgs.
More information on the actual packages build can be found in Packages.
{ self, ... }:
{
flake =
let
inherit (self.outputs) lib;
in
{
packages = lib.swarselsystems.forEachLinuxSystem (
pkgs: import "${self}/pkgs/flake" { inherit self lib pkgs; }
);
};
imports = [
(
{ lib, flake-parts-lib, ... }:
flake-parts-lib.mkTransposedPerSystemModule {
file = ./packages.nix;
name = "pkgs";
option = lib.mkOption {
type = lib.types.unspecified;
};
}
)
];
perSystem =
{ pkgs, system, ... }:
{
inherit pkgs;
# see https://flake.parts/module-arguments.html?highlight=modulewith#persystem-module-parameters
_module.args.pkgs = self.swarselsystemsLib.pkgsFor.${system};
};
}
3.4. Globals
This file is used to parse each nixosConfiguration present in this flake and scan them for options set under the globals attribute set. I use lib.evalModules to evaluate a mini module system that only consists of these globals options and then load them into the actual configuration by providing a globals output to the flake. This treads a dangerous ground of infinite recursions, which is why both the module system as well as the inherited attributes are kept to the minimal size. Each module has a globals option loaded from a module file which will be separately loaded by this mini-evaluation.
- uses nixpkgs.lib.mapAttrsToList on
config.nodes - uses nixpkgs.lib.flip to reverse the function argument order of the
mapAttrsToListcall, so that we can give the attribute set (config.nodes) first. Alternatively, we could have writtenlib.mapAttrsToList (name: cfg: [...]) config.nodesbut it would be harder to read since there would be a big block between the arguments. - uses nixpkgs.lib.concatLists.
options.config._globalDefsholds theoptions.globals.definitionsfor each node (which in turn basically holds the information that has been set for each node under theglobalsoption), so the concatenated list will look something like[ { services.kanidm.domain = "foo"; }; } { services.freshrss.domain = "bar"; } ]. - uses nixpkgs.lib.mkMerge to merge these separate attribute sets in the list into one big attribute set (the above attribute set example would become then
{ services = { kanidm.domain = "foo"; freshrss.domain = "bar"; }; }. You can see how this can now be referenced as a "global" set.
I also have a file for global values that cannot be attributed to one nixosConfiguration alone; the structure of this globals.nix.enc requires a toplevel globals - that means, globals.nix.enc has the structure { globals = [...] }.
Lastly, in order make this actually available to my configurations, i use the inherit (globalsSystem.config.globals) [...] which produces the globals output which I will pass to the specialArgs of my nixosConfigurations, which is when I will be finally able to use these definitions in my config.
Similar to Packages (pkgs), we again create a perSystem module for globals. We want this because we need to ingest the right lib with the extensions from nixos-extra-modules as discussed in Packages (pkgs). One side effect is that instead of a single globals output, we instead create outputs of the form globals.<arch>. This is not a problem as long as we pass one of these in Hosts, but it needs to be kept in mind. In effect, because we overrode pkgs, we can now use the perSystem module argument pkgs which will fetch the right pkgs. Anther method would be using inputs' together with inputs'.pkgs.lib as per https://flake.parts/module-arguments.html?highlight=modulewith#inputs.
# adapted from https://github.com/oddlama/nix-config/blob/main/nix/globals.nix
{ self, inputs, ... }:
{
flake-file.inputs.topologyPrivate.url = "./files/topology/public";
imports = [
(
{ lib, flake-parts-lib, ... }:
flake-parts-lib.mkTransposedPerSystemModule {
file = ./globals.nix;
name = "globals";
option = lib.mkOption {
type = lib.types.unspecified;
};
}
)
];
perSystem =
{ lib, pkgs, ... }:
{
globals =
let
globalsSystem = lib.evalModules {
modules = [
self.modules.generic.globals
(self.swarselsystemsLib.importEncrypted ../../secrets/repo/globals.nix.enc)
(
{ lib, ... }:
{
globals = lib.mkMerge (
lib.concatLists (
lib.flip lib.mapAttrsToList self.outputs.nodes (
name: cfg:
builtins.addErrorContext "while aggregating globals from nixosConfigurations.${name} into flake-level globals:" cfg.config._globalsDefs
)
)
);
}
)
];
prefix = [ "globals" ];
specialArgs = {
inherit (pkgs) lib;
inherit (self.outputs) nodes;
inherit inputs;
inherit (inputs.topologyPrivate) topologyPrivate;
};
};
in
{
inherit (globalsSystem.config.globals)
dns
domains
general
hosts
monitoring
networks
roaming
root
services
user
wireguard
;
};
};
}
3.5. PII evaluation
This provides a way to quickly see all PII values evaluated, either by full eval or by using the cached values.
{ self, lib, ... }:
{
flake-file.inputs.piix = {
inputs = {
flake-parts.follows = "flake-parts";
git-hooks-nix.follows = "pre-commit-hooks";
nixpkgs.follows = "nixpkgs";
pedantix.follows = "pedantix";
systems.follows = "systems";
treefmt-nix.follows = "treefmt-nix";
};
url = "git+ssh://forgejo@swagit.swarsel.win:2222/swarsel/piix.git?ref=main-devel";
};
flake.pii =
let
sanitize =
v:
let
t = builtins.tryEval v;
in
if !t.success then
"<eval error>"
else if builtins.isFunction t.value then
"<function>"
else if builtins.isAttrs t.value then
builtins.mapAttrs (_: sanitize) t.value
else if builtins.isList t.value then
map sanitize t.value
else
t.value;
load =
path:
let
v = self.swarselsystemsLib.importEncrypted path;
in
sanitize (
if builtins.isFunction v then
v (builtins.mapAttrs (_: _: throw "arg") (builtins.functionArgs v))
else
v
);
root = ../..;
attrPath =
path:
lib.splitString "/" (
lib.removeSuffix ".nix.enc" (lib.removePrefix "${toString root}/" (toString path))
);
hostSecrets = lib.mapAttrs (_: cfg: sanitize cfg.config.repo.secrets) (
self.nixosConfigurations // self.darwinConfigurations
);
in
{
evaluated = {
globals = sanitize (builtins.head (builtins.attrValues self.globals));
common = (builtins.head (builtins.attrValues hostSecrets)).common or null;
hosts = lib.mapAttrs (_: lib.flip builtins.removeAttrs [ "common" ]) hostSecrets;
};
files = lib.foldl' lib.recursiveUpdate { } (
map (path: lib.setAttrByPath (attrPath path) (load path)) (
lib.filter (path: lib.hasSuffix ".nix.enc" (toString path)) (lib.filesystem.listFilesRecursive root)
)
);
};
}
3.6. Hosts
Here I define my hosts. Earlier (in flake.nix skeleton), I told you how I used to use noweb-ref blocks to achieve this task. You see, a single nixosConfiguration uses nixpkgs.lib.nixosSystem, passing modules and arguments to define itself. I have automated this process by reading all directories in the hosts/ directory and then applying nixpkgs.lib.nixosSystem as a function on these returns. I also provide a nixosConfigurationsMinimal output which is ingested by the flake in install/flake.nix to be used during the initial deployment of a new system (it basically just disables most modules).
Note that the config top-level module attribute includes the entire flake config (this is not the same behavior as for perSystem).
There are a few interesting specialArgs to be noted:
- we pass
withHomeManagerfor all normal hosts (all hosts that are discovered) to keep compatibility with configurations that do not use home-manager. mkNixosHost: Very much akin to a simple call ofnixpkgs.lib.nixosSystem, I simply definespecialArgsandmodulesthat I want to use for every configuration. Here, I load all the extra modules from my other input flakes. Also, I add theglobalsoutput from Globals and thenodesoutput that I define right here (it simply mirrors all "full" configurations - NixOS and Darwin. I like to refer to home-manager only and nix-on-droid as a "half" configurations). It is also here that I set the node name for the configuration (I prefer this explicit call over referencingnetworking.hostNameor such) and the directory that should be used for secrets of a configuration.mkDarwinHostworks in the same way but for Darwin machines.mkHalfHostis a function that either creates a pure home-manager configuration or a nix-on-droid one. The type must be explicitly passed when calling the function. Here, again, we make use ofpkgsForthat we defined in Library functions. Also, we make sure to passextraSpecialArgs(the pendant tospecialArgs, just for home-manager configurations).diskoConfigurations: specifies a default disko configuration that is to be used if someone pulls in my flake as a disko configuration. This is not used by me, but I think it is kind of neat.nodes: As stated above, a shorthand for my configurations. Is built using the The '//' operatorguestConfigurations: This holds all MicroVM hosts.
The rest of the functions are used to build full NixOS systems as well as halfConfigurations regardless of system architecture:
readHostDirssimply gets the config directoriesmkHalfHostsForArchgenerates attribute sets for every halfHost found throughreadHostDirsmkHostsForArchdoes the same for full NixOS configurationsmkConfigurationsPerArchis the wrapper that callsmkHalfHostsForArchormkHostsForArchdepending on the config it is called for, holding all configurations in principalhalfConfigurationsPerArchreturns all halfConfigurations of a certain type (android or home-manager only)ConfigurationsPerArchdoes the same for full NixOS systems (NixOS or Darwin). These can further be specialized by passing in the correspondingminimalarg that is used during bootstrapping.
{ self, inputs, ... }:
{
flake-file.inputs = {
disko = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:nix-community/disko";
};
microvm = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:astro/microvm.nix";
};
nix-darwin = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:lnl7/nix-darwin";
};
nix-index-database = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:nix-community/nix-index-database";
};
nix-on-droid = {
inputs = {
home-manager.follows = "home-manager";
nixpkgs.follows = "nixpkgs";
nixpkgs-docs.follows = "nixpkgs";
};
url = "github:nix-community/nix-on-droid";
};
};
flake =
{ config, ... }:
let
inherit (self) outputs;
inherit (outputs) lib;
mkNixosHost =
{ minimal }:
configName: arch:
inputs.nixpkgs.lib.nixosSystem {
modules = [
inputs.disko.nixosModules.disko
inputs.home-manager.nixosModules.home-manager
inputs.microvm.nixosModules.host
inputs.microvm.nixosModules.microvm
inputs.nix-index-database.nixosModules.nix-index
inputs.swarsel-nix.nixosModules.default
(inputs.nixos-extra-modules + "/modules/guests")
(inputs.nixos-extra-modules + "/modules/interface-naming.nix")
"${self}/hosts/nixos/${arch}/${configName}"
self.modules.nixos.profile-base
{
swarselsystems.mainUser = lib.swarselsystems.mkStrong "swarsel";
microvm.guest.enable = lib.mkDefault false;
networking.hostName = lib.swarselsystems.mkStrong configName;
node = {
arch = lib.mkForce arch;
configDir = ../../hosts/nixos/${arch}/${configName};
lockFromBootstrapping = lib.mkIf (!minimal) (lib.swarselsystems.mkStrong true);
name = lib.mkForce configName;
secretsDir = ../../hosts/nixos/${arch}/${configName}/secrets;
type = lib.mkForce "nixos";
};
}
]
++ lib.optionals minimal [
self.modules.nixos.profile-minimal
];
specialArgs = {
inherit
self
inputs
arch
configName
minimal
outputs
;
inherit (config.pkgs.${arch}) lib;
inherit (config) nodes topologyPrivate;
inherit (outputs.swarselsystemsLib) root;
globals = config.globals.${arch};
extraModules = [ ];
homeLib = outputs.lib;
type = "nixos";
withHomeManager = true;
};
};
mkDarwinHost =
{ minimal }:
configName: arch:
inputs.nix-darwin.lib.darwinSystem {
modules = [
inputs.home-manager.darwinModules.home-manager
"${self}/hosts/darwin/${arch}/${configName}"
{
node = {
arch = lib.mkForce arch;
name = lib.mkForce configName;
secretsDir = ../../hosts/darwin/${arch}/${configName}/secrets;
type = lib.mkForce "darwin";
};
}
];
specialArgs = {
inherit
self
inputs
lib
configName
minimal
outputs
;
inherit (config) nodes topologyPrivate;
inherit (outputs.swarselsystemsLib) root;
globals = config.globals.${arch};
withHomeManager = true;
};
};
mkHalfHost =
configName: type: arch:
let
pkgs = lib.swarselsystems.pkgsFor.${arch};
extraSpecialArgs = {
inherit
self
inputs
lib
arch
configName
outputs
type
;
inherit (config) nodes topologyPrivate;
inherit (outputs.swarselsystemsLib) root;
globals = config.globals.${arch};
minimal = false;
};
nodeModule = {
node = {
arch = lib.mkForce arch;
name = lib.mkForce configName;
secretsDir = ../../hosts/${type}/${arch}/${configName}/secrets;
type = lib.mkForce type;
};
};
homeModules = [
inputs.nix-index-database.homeModules.nix-index
inputs.swarsel-nix.homeModules.default
inputs.glide-nix.homeModules.default
self.modules.generic.pii
nodeModule
];
in
if (type == "home") then
inputs.home-manager.lib.homeManagerConfiguration {
inherit extraSpecialArgs;
modules = homeModules ++ [ "${self}/hosts/${type}/${arch}/${configName}" ];
pkgs = import inputs.nixpkgs {
config.allowUnfree = true;
system = arch;
};
}
else
inputs.nix-on-droid.lib.nixOnDroidConfiguration {
inherit pkgs extraSpecialArgs;
modules = [
"${self}/hosts/${type}/${arch}/${configName}"
self.modules.nixOnDroid.profile-base
{
home-manager = {
config.imports = homeModules ++ [
self.modules.homeManager.profile-base
{ home.stateVersion = "23.05"; }
];
extraSpecialArgs = extraSpecialArgs // {
nixosConfig = null;
};
};
}
];
};
inherit (lib.swarselsystems) darwinSystems linuxSystems;
mkArches =
type:
if (type == "nixos") then
linuxSystems
else if (type == "darwin") then
darwinSystems
else
linuxSystems ++ darwinSystems;
readHostDirs =
hostDir:
if builtins.pathExists hostDir then
builtins.attrNames (lib.filterAttrs (_: type: type == "directory") (builtins.readDir hostDir))
else
[ ];
utilityHostNames = readHostDirs "${self}/hosts/utility";
mkHalfHostsForArch =
type: arch:
let
hostDir = "${self}/hosts/${type}/${arch}";
hosts = readHostDirs hostDir;
in
lib.genAttrs hosts (host: mkHalfHost host type arch);
mkHostsForArch =
type: arch: minimal:
let
hostDir = "${self}/hosts/${type}/${arch}";
hosts = readHostDirs hostDir;
in
lib.genAttrs hosts (
host:
if (type == "nixos") then
mkNixosHost { inherit minimal; } host arch
else
mkDarwinHost { inherit minimal; } host arch
);
configurationsPerArch =
type: minimal: lib.mergeAttrsList (map (arch: mkHostsForArch type arch minimal) (mkArches type));
halfConfigurationsPerArch =
type: lib.mergeAttrsList (map (mkHalfHostsForArch type) (mkArches type));
in
rec {
"@" = lib.mapAttrs (_: v: v.config.system.build.toplevel) config.nodes;
darwinConfigurations = configurationsPerArch "darwin" false;
darwinConfigurationsMinimal = configurationsPerArch "darwin" true;
diskoConfigurations.default = config.modules.nixos.disk-single-root;
guestConfigurations = lib.flip lib.concatMapAttrs config.nixosConfigurations (
_: node:
lib.flip lib.mapAttrs' (node.config.guests or { }) (
guestName: guestDef: lib.nameValuePair guestDef.nodeName node.config.microvm.vms.${guestName}.config
)
);
guestResources = lib.mapAttrs (
name: _:
let
f =
arg:
lib.foldr (base: acc: base + acc) 0 (
map (node: nodes."${name}-${node}".config.microvm.${arg}) (
builtins.attrNames nodes.${name}.config.guests
)
);
in
{
mem = f "mem";
vcpu = f "vcpu";
}
) nodes;
homeConfigurations = halfConfigurationsPerArch "home";
nixOnDroidConfigurations = halfConfigurationsPerArch "android";
nixosConfigurations = configurationsPerArch "nixos" false;
nixosConfigurationsMinimal = configurationsPerArch "nixos" true;
nodes = builtins.removeAttrs (
config.nixosConfigurations // config.darwinConfigurations // config.guestConfigurations
) utilityHostNames;
};
}
3.7. Topology (nix-topology generated network diagram)
This defines some topology for the nix-topology module that can not otherwise be parsed from the config (or is global). For example, this is used to define a number of switches, printers and routers. The topology graph is built from left to right, meaning that nodes.internet = mkInternet { connections = [ (mkConnection "moonside" "wan") ]; }; means that the node internet 'initiates' the connection to the node moonside (internet will be on the left).
Another note concerning flake-parts:
perSystemis a mechanism that tells flake-parts to build the following attribute set for all systems. This replaces the need to handle myself anysystemorpkgsvariables, this is done by flake-parts. In this case this is needed so that the topology diagram can be built locally.
{
self,
root,
inputs,
lib,
...
}:
{
flake-file.inputs.nix-topology = {
inputs = {
flake-parts.follows = "flake-parts";
nixpkgs.follows = "nixpkgs";
};
url = "github:Swarsel/nix-topology/dev";
};
}
// lib.optionalAttrs (inputs ? nix-topology) {
imports = [
inputs.nix-topology.flakeModule
];
perSystem =
{ system, ... }:
let
inherit (self.outputs) lib;
in
{
topology = {
modules = [
(
{ config, ... }:
let
globals = self.outputs.globals.${system};
inherit (config.lib.topology)
mkConnection
mkDevice
mkInternet
mkRouter
mkSwitch
;
in
{
networks =
lib.mapAttrs
(vlan: name: {
inherit (globals.networks.home-lan.vlans.${vlan}) cidrv4 cidrv6;
name = "VLAN: ${name}";
})
{
services = "Services";
devices = "Devices";
guests = "Guests";
home = "Home";
iot = "IoT";
}
// {
fritz-lan = {
inherit (globals.networks.home-lan) cidrv4 cidrv6;
name = "Fritz!Box LAN";
};
fritz-wg = {
inherit (globals.networks.fritz-wg) cidrv4 cidrv6;
name = "WireGuard: Fritz!Box tunnel";
};
wgHome = {
inherit (globals.networks.home-wgHome) cidrv4 cidrv6;
name = "WireGuard: Home proxy tunnel";
};
wgProxy = {
inherit (globals.networks.twothreetunnel-wgProxy) cidrv4 cidrv6;
name = "WireGuard: Web proxy tunnel";
};
};
renderer = "elk";
nodes = {
ender3 = mkDevice "Ender 3" {
services.octoprint = {
icon = root "files/topology-images/octoprint.png";
name = "OctoPrint";
};
deviceIcon = root "files/topology-images/ender3.png";
icon = root "files/topology-images/raspi.png";
info = "SKR V1.3, TMC2209 (Dual), TFT35";
interfaces.eth1 = { };
};
fritzbox = mkRouter "FRITZ!Box" {
connections.eth-wan = mkConnection "hintbooth" "lan";
image = root "files/topology-images/FritzBox_7682.png";
info = "FRITZ!Box 7682";
interfaceGroups = [
[
"eth1"
"eth2"
"eth3"
"eth-wan"
"wifi"
]
[ "dsl" ]
];
interfaces = {
eth-wan = {
addresses = [ globals.networks.home-lan.hosts.fritzbox.ipv4 ];
network = "fritz-lan";
};
eth1 = {
addresses = [ globals.networks.home-lan.hosts.fritzbox.ipv4 ];
network = "fritz-lan";
};
eth2 = { };
eth3 = { };
fritz-wg = {
addresses = [ globals.networks.fritz-wg.hosts.fritzbox.ipv4 ];
network = "fritz-wg";
physicalConnections = [
(mkConnection "pyramid" "fritz-wg")
(mkConnection "magicant" "fritz-wg")
];
renderer.hidePhysicalConnections = true;
type = "wireguard";
virtual = true;
};
wifi = {
addresses = [ globals.networks.home-lan.hosts.fritzbox.ipv4 ];
network = "fritz-lan";
physicalConnections = [
(mkConnection "pyramid" "wifi")
(mkConnection "bakery" "wifi")
(mkConnection "machpizza" "wifi")
];
renderer.hidePhysicalConnections = true;
virtual = true;
};
};
};
internet = mkInternet {
connections = [
(mkConnection "fritzbox" "dsl")
(mkConnection "magicant" "wifi")
(mkConnection "liliputsteps" "lan")
]
++ lib.optional (globals.roaming.treehouse.location == "work") (mkConnection "treehouse" "eth1");
};
machpizza = mkDevice "machpizza" {
deviceIcon = root "files/topology-images/mac.png";
icon = "devices.laptop";
info = "MacBook Pro 2016";
interfaces = {
eth1.network = "guests";
wifi = { };
};
};
magicant = mkDevice "magicant" {
icon = root "files/topology-images/phone.png";
image = root "files/topology-images/zflip6.png";
info = "Samsung Z Flip 6";
interfaces = {
fritz-wg.network = "fritz-wg";
wifi = { };
};
};
nswitch = mkDevice "Nintendo Switch" {
image = root "files/topology-images/nintendo-switch.png";
info = "Atmosphère 1.3.2 @ FW 19.0.1";
interfaces.eth1 = { };
};
pc = mkDevice "Chaostheater" {
services.sunshine = {
icon = root "files/topology-images/sunshine.png";
name = "Sunshine";
};
deviceIcon = root "files/topology-images/atlasos.png";
icon = root "files/topology-images/windows.png";
info = "ASUS Z97-A, i7-4790k, GTX970, 32GB RAM";
interfaces.eth1.network = "guests";
};
printer = mkDevice "Printer" {
image = root "files/topology-images/DELL-C2665dnf.png";
info = "DELL C2665dnf";
interfaces.eth1 = { };
};
ps4 = mkDevice "PlayStation 4" {
image = root "files/topology-images/ps4.png";
info = "GoldHEN @ FW 5.05";
interfaces.eth1 = { };
};
switch-bedroom = mkSwitch "Switch Bedroom" {
connections = {
eth2 = mkConnection "printer" "eth1";
eth3 = mkConnection "machpizza" "eth1";
};
image = root "files/topology-images/TL-SG108E.png";
info = "TL-SG108E";
interfaceGroups = [
# trunk
[ "eth1" ]
# devices
[ "eth2" ]
# guests
[
"eth3"
"eth4"
"eth5"
"eth6"
"eth7"
"eth8"
]
];
interfaces = {
eth2.network = lib.mkForce "devices";
eth3.network = lib.mkForce "guests";
};
};
switch-kitchen = mkSwitch "Switch Kitchen" {
connections = {
eth2 = mkConnection "zigbee-coordinator" "eth1";
eth8 = mkConnection "winters" "lan";
}
// lib.optionalAttrs (globals.roaming.treehouse.location == "home") {
eth3 = mkConnection "treehouse" "eth1";
};
image = root "files/topology-images/TL-SG108E.png";
info = "TL-SG108E";
interfaceGroups = [
[
"eth1"
"eth3"
"eth8"
]
[ "eth2" ]
];
interfaces.eth2.network = lib.mkForce "iot";
};
switch-livingroom = mkSwitch "Switch Livingroom" {
connections = {
eth2 = mkConnection "nswitch" "eth1";
eth3 = mkConnection "bakery" "eth1";
eth5 = mkConnection "ps4" "eth1";
eth6 = mkConnection "ender3" "eth1";
eth7 = mkConnection "pc" "eth1";
eth8 = mkConnection "pyramid" "eth1";
};
image = root "files/topology-images/TL-SG108E.png";
info = "TL-SG108E";
interfaceGroups = [
# trunk
[ "eth1" ]
# devices
[
"eth2"
"eth5"
"eth6"
]
# home
[
"eth3"
"eth8"
]
# guests
[
"eth4"
"eth7"
]
];
interfaces = {
eth2.network = lib.mkForce "devices";
eth3.network = lib.mkForce "home";
eth5.network = lib.mkForce "devices";
eth6.network = lib.mkForce "devices";
eth7.network = lib.mkForce "guests";
eth8.network = lib.mkForce "home";
};
};
treehouse = mkDevice "treehouse" {
services = {
comfyui = {
icon = root "files/topology-images/comfyui.png";
name = "Comfy UI";
};
ollama = {
icon = "services.ollama";
name = "Ollama";
};
openwebui = {
icon = "services.open-webui";
name = "Open WebUI";
};
};
deviceIcon = root "files/topology-images/dgxos.png";
icon = root "files/topology-images/home-manager.png";
info = "NVIDIA DGX Spark";
interfaces = {
eth1 = { };
wifi = { };
};
};
zigbee-coordinator = mkDevice "Zigbee Coordinator" {
image = root "files/topology-images/SLZB-06M.png";
info = "SMLIGHT SLZB-06M";
interfaces.eth1 = { };
};
};
}
)
];
nixosConfigurations = builtins.removeAttrs self.nixosConfigurations [ "vacanthouse" ];
};
};
}
3.8. Pre-commit hooks (checks)
This file defines a number of checks that can either be run by calling nix flake check or while in a nix-shell or nix develop. This helps me make sure that my flake confirms to my self-imposed standards. The GitHub actions perform less checks than are being done here (they are only checking the formatting, as well as statix and deadnix).
{
self,
inputs,
lib,
...
}:
{
flake-file.inputs.pre-commit-hooks = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:cachix/git-hooks.nix";
};
}
// lib.optionalAttrs (inputs ? pre-commit-hooks) {
imports = [
inputs.pre-commit-hooks.flakeModule
];
perSystem =
{
pkgs,
system,
...
}:
{
pre-commit = {
check.enable = true;
settings = {
addGcRoot = true;
hooks = {
check-added-large-files.enable = true;
check-case-conflicts.enable = true;
check-executables-have-shebangs.enable = true;
check-merge-conflicts.enable = true;
check-shebang-scripts-are-executable.enable = false;
deadnix.enable = true;
destroyed-symlinks = {
enable = true;
entry = lib.getExe' pkgs.python3Packages.pre-commit-hooks "destroyed-symlinks";
};
detect-private-keys = {
enable = true;
excludes = [ "files/public/age" ];
};
end-of-file-fixer.enable = true;
fix-byte-order-marker.enable = true;
flake-checker.enable = true;
flake-file-in-sync = {
enable = true;
entry = "${pkgs.writeShellScript "flake-file-in-sync" ''
if [[ -z $NIX_BUILD_TOP ]]; then
nix build --no-link --print-build-logs .#checks.${system}.check-flake-file
fi
''}";
files = "\\.nix$";
pass_filenames = false;
};
forbid-new-submodules.enable = true;
mixed-line-endings.enable = true;
modules-tangled = {
enable = true;
always_run = true;
entry = "${pkgs.writeShellScript "modules-tangled" ''
untangled=$(comm -23 <(find modules -type f | sort) <(grep -oP ':tangle\s+\Kmodules/\S+' SwarselSystems.org | sort -u))
if [[ -n $untangled ]]; then
echo "not tangled from SwarselSystems.org:"
echo "$untangled"
exit 1
fi
''}";
pass_filenames = false;
};
org-custom-ids = {
enable = true;
entry = "${pkgs.writeScript "org-custom-ids" ''
#!${pkgs.emacs-nox}/bin/emacs --script
;; -*- lexical-binding: t -*-
(require 'org-id)
(dolist (file command-line-args-left)
(with-current-buffer (find-file-noselect file)
(org-map-entries
(lambda ()
(unless (org-entry-get nil "CUSTOM_ID")
(org-entry-put nil "CUSTOM_ID" (org-id-new "h")))))
(save-buffer)))
''}";
files = "^SwarselSystems\\.org$";
pass_filenames = true;
};
org-in-sync = {
enable = true;
always_run = true;
entry = "${lib.getExe self.packages.${system}.swarsel-sync-org} --dry-run";
pass_filenames = false;
};
pii-lock = {
enable = true;
always_run = true;
entry = "${lib.getExe inputs.piix.packages.${system}.pii} check";
pass_filenames = false;
};
shellcheck = {
enable = true;
entry = "${pkgs.shellcheck}/bin/shellcheck --shell=bash";
};
shfmt = {
enable = true;
entry = "${pkgs.shfmt}/bin/shfmt -i 4 -sr -d -s -l";
};
statix.enable = true;
topology-in-sync = {
enable = true;
entry = "${pkgs.writeShellScript "topology-in-sync" ''
if [[ $# -eq 1 ]]; then
echo "$1 was staged without the other topology image."
exit 1
fi
''}";
files = "^files/topology/topology(_small)?\\.png$";
pass_filenames = true;
};
treefmt.enable = true;
trim-trailing-whitespace.enable = true;
};
};
};
};
}
3.9. Devshell
This file provides a number of useful shorthand commands, as well as a 'safe' version of nixpkgs that I can use to rebuild from in case a version bump in nixpkgs suddenly breaks something.
Aside from the default devShell which is the one that should usually be called interactively, I also define a deploy devshell: this one pins the version of nix that the NixOS-anywhere I am using works with.
{
self,
inputs,
lib,
...
}:
{
flake-file.inputs.devshell = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:numtide/devshell";
};
}
// lib.optionalAttrs (inputs ? devshell) {
imports = [
inputs.devshell.flakeModule
];
perSystem =
{
config,
pkgs,
system,
...
}:
let
preCommitStartup = ''
top="$(${lib.getExe pkgs.git} rev-parse --show-toplevel)"
hooks="$(${lib.getExe pkgs.git} rev-parse --path-format=absolute --git-common-dir)/hooks"
if [[ ! -e "$top/.pre-commit-config.yaml" || ! -x "$hooks/pre-commit" ]]; then
rm -f "$top/.pre-commit-config.yaml"
fi
${config.pre-commit.installationScript}
'';
mkPackages = stable: nix-version: [
(builtins.trace "alarm: pinned nix_${nix-version}" pkgs.${stable}.nixVersions."nix_${nix-version}")
pkgs.git
pkgs.just
pkgs.age
pkgs.ssh-to-age
pkgs.sops
];
in
{
devshells = {
default =
let
nix-version = "2_30";
in
{
commands = [
{
package = pkgs.statix;
help = "Lint flake";
}
{
package = pkgs.deadnix;
help = "Check flake for dead code";
}
{
package = pkgs.nix-tree;
help = "Interactively browse dependency graphs of Nix derivations";
}
{
package = pkgs.nvd;
help = "Diff two nix toplevels and show which packages were upgraded";
}
{
package = pkgs.nix-diff;
help = "Explain why two Nix derivations differ";
}
{
package = pkgs.nix-output-monitor;
help = "Nix Output Monitor (a drop-in alternative for `nix` which shows a build graph)";
name = "nom \"$@\"";
}
{
command = "home-manager \"$@\"";
help = "Manage home-manager config";
name = "hm";
}
{
command = "treefmt --tree-root \"$FLAKE\" \"$@\"";
help = "Format flake";
name = "fmt";
}
{
command = "swarsel-deploy \"$@\"";
help = "Build and deploy this nix config to nodes";
name = "sd";
}
{
command = "swarsel-deploy \${1} switch";
help = "Build and deploy a config to nodes";
name = "sl";
}
{
command = "swarsel-deploy $(hostname) switch";
help = "Build and switch to the host's config locally";
name = "sw";
}
{
command = "git --git-dir=$FLAKE/.git --work-tree=$FLAKE/ \"$@\"";
help = "Work with the flake git repository";
name = "c";
}
];
devshell.startup.pre-commit.text = preCommitStartup;
packages = mkPackages "stable26_05" nix-version ++ [
config.treefmt.build.wrapper
self.packages.${system}.swarsel-deploy
inputs.piix.packages.${system}.pii
(pkgs.symlinkJoin {
buildInputs = [ pkgs.makeWrapper ];
name = "home-manager";
paths = [ pkgs.home-manager ];
postBuild = ''
wrapProgram $out/bin/home-manager \
--append-flags '--flake .#$(hostname)'
'';
})
];
};
deploy =
let
nix-version = "2_28";
in
{
packages = mkPackages "stable25_05" nix-version ++ [
pkgs.opentofu
self.packages.${system}.swarsel-bootstrap
];
};
hooks.devshell = {
motd = "";
startup.pre-commit.text = preCommitStartup;
};
};
};
}
3.10. Templates
This file defines the templates that are being exposed by the flake. These can be used by running nix flake init -t github:Swarsel/.dotfiles#<TEMPLATE_NAME> by others. Personally, I mostly use these as part of the [BROKEN LINK: h:154b6df4-dd50-4f60-9794-05a140d02994] utility.
Otherwise, I define the function mkTemplates here which builds a named attribute set for each type of template that I have.
- uses builtins.listToAttrs
{ root, lib, ... }:
{
flake.templates =
lib.genAttrs
[
"python"
"rust"
"go"
"latex"
"default"
]
(name: {
description = "${name} project";
path = root "files/templates/${name}";
});
}
3.11. Formatter (treefmt-nix)
Defines a formatter that can be called using nix fmt.
Usually all formatting in this repo is done automatically while editing in Emacs. However, it is nice to have a backup formatter to rely on and treefmt is extremely nice to work with, as it allows setting formatters for all kinds of aspects of the flake.
{
inputs,
lib,
withSystem,
...
}:
{
flake-file = {
formatter = lib.mkIf (inputs ? treefmt-nix) (
pkgs:
withSystem pkgs.stdenv.hostPlatform.system (
{ config, ... }:
let
inherit (config.treefmt.settings) formatter;
nixFormatter = formatter.pedantix or formatter.nixfmt;
in
pkgs.writeShellApplication {
name = "flake-file-formatter";
text = ''exec ${nixFormatter.command} ${lib.escapeShellArgs nixFormatter.options} "$@"'';
}
)
);
inputs = {
pedantix = {
inputs = {
flake-parts.follows = "flake-parts";
git-hooks-nix.follows = "pre-commit-hooks";
nixpkgs.follows = "nixpkgs";
treefmt-nix.follows = "treefmt-nix";
};
url = "github:Swarsel/pedantix";
};
treefmt-nix = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:numtide/treefmt-nix";
};
};
};
}
// lib.optionalAttrs (inputs ? treefmt-nix) {
imports = [
inputs.treefmt-nix.flakeModule
]
++ lib.optional (inputs ? pedantix) inputs.pedantix.flakeModules.default;
perSystem = { pkgs, ... }: {
# formatter is set by treefmt to:
# formatter = lib.mkIf config.treefmt.flakeFormatter (lib.mkDefault config.treefmt.build.wrapper);
treefmt = {
programs = {
deadnix.enable = true;
shellcheck.enable = true;
shfmt = {
enable = true;
# needed to replicate what my Emacs shfmt does
# there is no builtin option for space-redirects
package = pkgs.symlinkJoin {
buildInputs = [ pkgs.makeWrapper ];
name = "shfmt";
paths = [ pkgs.shfmt ];
postBuild = ''
wrapProgram $out/bin/shfmt \
--add-flags '-sr'
'';
meta.mainProgram = "shfmt";
};
indent_size = 4;
simplify = true;
};
statix.enable = true;
}
// (
if inputs ? pedantix then
{
pedantix = {
enable = true;
settings = import ../../files/nix/pedantix-settings.nix;
};
}
else
{
nixfmt = {
enable = true;
package = pkgs.nixfmt;
};
}
);
projectRootFile = "flake.nix";
settings.formatter.shellcheck.options = [
"--shell"
"bash"
];
};
};
}
3.12. Modules
This exposes all of my modular configuration as modules. Other people can use them in their flake using imports = [ inputs.<name>.nixosModules ];. Per default, this enables some mechanisms like config sharing between nodes and the globals system.
nixosModules is a `defined` flake output, where external tools might expect some sort of structure; hence, I call the default output default, which will, in many cases, allow the user to just reference to the flake itself (which will then use nixosModules.default automatically.
homeModules on the other hand is not standardized in this way (for example, many flakes refer to homeManagerModules instead); in order not to unnecessarily break things, I leave it as is.
{ self, ... }:
{
flake = {
homeModules = self.modules.homeManager.profile-base;
nixosModules.default = self.modules.nixos.profile-base;
};
}
3.13. Apps
This defines some apps; they differ from normal packages in that they can be called using nix run <repo><appName>. So, for example, I can call my deployment script using nix run --experimental-features 'nix-command flakes' github:Swarsel/.dotfiles -- -n <CONFIGURATION_NAME> -d <TARGET_IP> (here I did not specify #swarsel-bootstrap since it is set as the default. In general, whenever the #... part is omitted, the object under the default attribute will be used. This is also true for nixosConfigurations: in that case, the default will be the current hostname of the machine).
- uses builtins.listToAttrs
- uses The '//' operator to add the default output to the set of built apps.
{ self, ... }:
{
perSystem =
{ system, ... }:
let
bootstrap = {
program = "${self.packages.${system}.swarsel-bootstrap}/bin/swarsel-bootstrap";
type = "app";
meta.description = "Custom app swarsel-bootstrap.";
};
in
{
apps = {
default = bootstrap;
swarsel-bootstrap = bootstrap;
};
};
}
3.14. Overlays/Overrides
In this section I define packages that I manually add to nixpkgs, or that I want to use in a modified way. This can be useful for packages that are currently awaiting a PR or public packages that I do not want to maintain. This is done in a three step process.
The first overlay stage is responsible for extending the base nixpkgs:
additionsThese are for the aforementioned added packages. NOTE: The packages themselves are built in Packages (pkgs); here, we just add them to the overlay that we then use in the configuration.nixpkgs-stable-versionsThese are simply mirrors of other branches of nixpkgs (mostly past stable branches). Useful for packages that are broken on nixpkgs, but do not need to be on bleeding edge anyway. Automatically fetches all inputs namesnixpkgs-<suffix>and adds them under the name in<suffix>. They will be available underpkgs.<suffix>.
The second stage of overlays is responsible to replace packages in nixpkgs with stable versions. The benefit here is that I have a central place (this part of the config) where I can declare what needs to be stable - broken packages tend to be end-user packages, as packages with huge dependency chains will normally be caught earlier upstream if there is a failure (see Current issues). In effect, that means I can override package xyz right here, and then use pkgs.xyz in the rest of the config, whereas I would need to use pkgs.<suffix>.xyz if I were to only use nixpkgs-stable-versions from the first stage.
Note that packages with bigger dependencies should NOT be added here. Such as:
- chromium
- bluez
- pipewire
As doing so will trigger enormous rebuilds of e.g. electron.
The third stage takes care of further modifications that should be performed to the packages after they have been overridden in stages 1 and 2: These modifications are for packages that do not fit my use case, meaning I need to perform modifications on them.
As part of the modifications, I add some of my own library functions to be used alongside the functions provided by nixpkgs and home-manager.
On the structure of overlays: as you notice, all of the attributes within overlays are functions which take final and prev as arguments. This is a convention (sometimes you also see super instead of final) that aims to tell you that final represents the pkgs set after it has gone over all modifications, while prev is the pkgs set before the current modification.
- So, in
additions, thefinalset is the same as inmodifications, but theirprevsets differ. - This starts to make a difference when you use multiple overlays and have one overlay depend on the modifications in another overlay.
- The
_argument is used like in a number of other programming languages and signals that the argument is never actually used in the function.
{
self,
root,
inputs,
...
}:
let
inherit (self) outputs;
inherit (outputs) lib;
stablePins = {
dev = [ ];
firezone = [
"firezone-gateway"
"firezone-headless-client"
"firezone-relay"
"firezone-server"
];
stable = [
"dwarfs"
"wayprompt"
];
stable25_05 = [
"steam-fhsenv-without-steam"
"transmission_3"
];
stable26_05 = [
"azure-cli"
"libdisplay-info_0_2"
];
};
in
{
flake-file.inputs = {
emacs-overlay = {
inputs = {
nixpkgs.follows = "nixpkgs";
nixpkgs-stable.follows = "nixpkgs-stable";
};
url = "github:nix-community/emacs-overlay";
};
follow-nix = {
inputs = {
flake-parts.follows = "flake-parts";
git-hooks-nix.follows = "pre-commit-hooks";
nixpkgs.follows = "nixpkgs";
treefmt-nix.follows = "treefmt-nix";
};
url = "github:Swarsel/follow-nix";
};
nix-minecraft = {
inputs = {
nixpkgs.follows = "nixpkgs";
systems.follows = "systems";
};
url = "github:Infinidoge/nix-minecraft";
};
nixgl = {
inputs = {
flake-utils.follows = "flake-utils";
nixpkgs.follows = "nixpkgs";
};
url = "github:guibou/nixGL";
};
nur = {
inputs = {
flake-parts.follows = "flake-parts";
nixpkgs.follows = "nixpkgs";
};
url = "github:nix-community/NUR";
};
zjstatus = {
inputs = {
flake-utils.follows = "flake-utils";
nixpkgs.follows = "nixpkgs";
};
url = "github:dj95/zjstatus";
};
};
flake = {
overlays =
let
nixpkgs-stable-versions =
final: _:
lib.mapAttrs' (
name: src:
lib.nameValuePair (lib.removePrefix "nixpkgs-" name) (
import src {
inherit (final.stdenv.hostPlatform) system;
config.allowUnfree = true;
}
)
) (lib.filterAttrs (name: _: lib.hasPrefix "nixpkgs-" name) inputs);
in
rec {
additions =
final: prev:
let
inherit (prev.stdenv.hostPlatform) system;
in
import "${self}/pkgs/flake" {
inherit self lib;
pkgs = final;
}
// {
follow-nix = inputs.follow-nix.packages.${system}.default;
hunkle = inputs.hunkle.packages.${system}.default;
pedantix = inputs.pedantix.packages.${system}.pedantix-wrapped;
swarsel-nix = import inputs.swarsel-nix { pkgs = prev; };
zjstatus = inputs.zjstatus.packages.${system}.default;
}
// nixpkgs-stable-versions final prev
// lib.mergeAttrsList (
map (overlay: overlay final prev) [
inputs.niri-flake.overlays.niri
inputs.noctalia.overlays.default
inputs.nur.overlays.default
inputs.emacs-overlay.overlay
inputs.nix-topology.overlays.default
inputs.nix-index-database.overlays.nix-index
inputs.nixgl.overlay
inputs.nix-minecraft.overlay
inputs.nixos-extra-modules.overlays.default
]
);
default = additions;
modifications = _final: prev: {
firezone-gui-client = prev.firezone-gui-client.overrideAttrs (
old:
let
frontend = old.passthru.frontend.overrideAttrs {
patches = [ (root "files/patches/firezone-gui-client-update-state-loop.patch") ];
};
in
{
passthru = old.passthru // {
inherit frontend;
};
postPatch = builtins.replaceStrings [ "${old.passthru.frontend}" ] [ "${frontend}" ] old.postPatch;
}
);
go-mockery = prev.go-mockery.overrideAttrs { doCheck = false; };
grafanaPlugins = prev.grafanaPlugins // {
grafana-pyroscope-datasource = prev.grafanaPlugins.grafanaPlugin {
packages.any = {
hash = "sha256-JZHurlO+5Anr5VDcO9sXewxjLIPkz6JAchkF9qkLR4Y=";
url = "https://grafana.com/api/plugins/grafana-pyroscope-datasource/versions/13.0.9/download";
};
pname = "grafana-pyroscope-datasource";
version = "13.0.9";
};
};
isync = prev.isync.override {
withCyrusSaslXoauth2 = true;
};
lib = prev.lib // {
inherit (self.outputs.lib) hm;
swarselsystems = self.outputs.swarselsystemsLib;
};
matrix-appservice-irc = prev.matrix-appservice-irc.overrideAttrs {
patches = [
(root "files/patches/matrix-appservice-irc-on-connect-commands.patch")
(root "files/patches/matrix-appservice-irc-pm-room-v12.patch")
(root "files/patches/matrix-appservice-irc-provisioner-silent-pm.patch")
];
};
mautrix-telegram = prev.mautrix-telegram.override {
python3 = prev.python313;
};
niri-unstable = prev.niri-unstable.override {
patches = [
(root "files/patches/niri-workspace-under-mouse-binds.patch")
(root "files/patches/niri-hidden-workspaces.patch")
(root "files/patches/niri-hidden-workspaces-event-stream.patch")
(root "files/patches/niri-hidden-workspaces-gesture-bounds.patch")
];
};
retroarch = prev.retroarch.withCores (
cores: with cores; [
snes9x # snes
nestopia # nes
dosbox # dos
scummvm # scumm
vba-m # gb/a
mgba # gb/a
melonds # ds
dolphin # gc/wii
]
);
sesh = prev.sesh.overrideAttrs {
doCheck = false;
preBuild = "";
};
shikane = prev.shikane.overrideAttrs (old: {
postPatch = (old.postPatch or "") + ''
substituteInPlace src/settings.rs \
--replace-fail ".create(true)" "" \
--replace-fail ".append(true)" ""
'';
});
syncstorage-rs =
(prev.syncstorage-rs.override {
python3 = prev.python313;
}).overrideAttrs
(old: {
env = old.env // {
RUSTFLAGS = (old.env.RUSTFLAGS or "") + " -Aambiguous_glob_imports";
};
});
vencord = prev.vencord.overrideAttrs (old: {
patches = [ ];
pnpmDeps = old.pnpmDeps.overrideAttrs {
outputHash = "sha256-/BoLLeKsftWv1bjWuND8967YGhqWEaCZZU6z/oa+0oM=";
patches = [ ];
postPatch = "";
};
postPatch = "";
src = old.src.override {
hash = "sha256-+dN4wAFNmYVDiEe0QStqrFBRFHBBRkApqbmhuvsLZZM=";
tag = "v1.15.17";
};
version = "1.15.17";
});
vesktop = prev.vesktop.override {
withSystemVencord = true;
};
zellij-unwrapped = prev.zellij-unwrapped.overrideAttrs (old: {
postPatch =
old.postPatch
+
lib.concatMapStrings
(name: ''
substituteInPlace zellij-utils/src/input/layout.rs \
--replace-fail 'available_layouts.push(LayoutInfo::BuiltIn("${name}".to_owned()));' ""
'')
[
"default"
"strider"
"disable-status-bar"
"compact"
"classic"
];
});
};
pedantix-emacs = inputs.pedantix.overlays.emacs;
stables =
final: prev:
let
stablePackages = nixpkgs-stable-versions final prev;
in
lib.concatMapAttrs (
suffix: names: lib.genAttrs names (name: stablePackages.${suffix}.${name})
) stablePins;
};
stablePinsUnstable = lib.genAttrs lib.swarselsystems.linuxSystems (
system:
let
pkgs = import inputs.nixpkgs {
inherit system;
config = {
allowBroken = true;
allowUnfree = true;
};
};
supportedOn =
name:
let
r = builtins.tryEval (pkgs ? ${name} && lib.meta.availableOn pkgs.stdenv.hostPlatform pkgs.${name});
in
r.success && r.value;
in
builtins.mapAttrs (
_: names: lib.genAttrs (builtins.filter supportedOn names) (name: pkgs.${name})
) stablePins
);
};
}
3.15. flake-file
{ inputs, ... }:
{
flake-file = {
description = "SwarseFlake - Nix Flake for all SwarselSystems";
inputs = {
flake-file.url = "github:vic/flake-file";
flake-parts = {
inputs.nixpkgs-lib.follows = "nixpkgs";
url = "github:hercules-ci/flake-parts";
};
flake-utils = {
inputs.systems.follows = "systems";
url = "github:numtide/flake-utils";
};
home-manager = {
# url = "github:Swarsel/home-manager/main";
inputs.nixpkgs.follows = "nixpkgs";
url = "github:nix-community/home-manager";
};
import-tree.url = "github:vic/import-tree";
nixos-extra-modules = {
inputs = {
devshell.follows = "devshell";
flake-parts.follows = "flake-parts";
nixpkgs.follows = "nixpkgs";
pre-commit-hooks.follows = "pre-commit-hooks";
};
url = "github:Swarsel/nixos-extra-modules/dev";
};
nixos-hardware = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:NixOS/nixos-hardware/master";
};
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
nixpkgs-dev.url = "github:Swarsel/nixpkgs/main";
nixpkgs-kernelpin.url = "github:nixos/nixpkgs/31ecbaca1bdefa45dffc409f0250bd8039ea0010?narHash=sha256-dhoW6VgFWlaodSY5jrBn%2BCF2FLmaUvDVgM7%2BC7T2%2BNM%3D";
nixpkgs-stable.follows = "nixpkgs-stable26_05";
nixpkgs-stable24_11.url = "github:NixOS/nixpkgs/nixos-24.11";
nixpkgs-stable25_05.url = "github:NixOS/nixpkgs/nixos-25.05";
nixpkgs-stable26_05.url = "github:NixOS/nixpkgs/nixos-26.05";
swarsel-nix = {
inputs = {
flake-parts.follows = "flake-parts";
nixpkgs.follows = "nixpkgs";
systems.follows = "systems";
};
url = "github:Swarsel/swarsel-nix/main";
};
systems.url = "github:nix-systems/default";
};
outputs = "inputs: import ./modules/flake/_outputs.nix inputs";
};
imports = [
inputs.flake-file.flakeModules.default
];
}
3.16. Outputs
inputs:
inputs.flake-parts.lib.mkFlake { inherit inputs; } {
imports = [
inputs.flake-parts.flakeModules.modules
(inputs.import-tree ../.)
./_flake-file.nix
];
debug = true;
systems = [
"x86_64-linux"
"aarch64-linux"
"x86_64-darwin"
"aarch64-darwin"
];
}
3.17. Installer images (live ISO, kexec)
This sections makes use of nixos-generators in order to easily allow me to build a live ISO of my installer system. It can be built using nix build --print-out-paths --no-link <flake path>#live-iso, and can then be copied to a USB drive using, for example, dd.
In a similar way, nix build --print-out-paths --no-link <flake-path>.#pnap-kexec --system <system> will build the kexec tarball that I need when using disko to deploy to a low-RAM systems.
This is an improvement to what I did earlier, where I did not use nixos-generators but instead manually imported the needed modules to make this configuration into a bootable USB image. Now, I can just write this in the same way that I would to write any other configuration.
{ self, inputs, ... }:
{
flake-file.inputs = {
nixos-images.url = "github:Swarsel/nixos-images/main";
smallpkgs.url = "github:nixos/nixpkgs/08fcb0dcb59df0344652b38ea6326a2d8271baff?narHash=sha256-HXIQzULIG/MEUW2Q/Ss47oE3QrjxvpUX7gUl4Xp6lnc%3D";
};
perSystem =
{
lib,
pkgs,
system,
...
}:
let
installerImage =
{
modules,
specialArgs ? { },
}:
let
format =
{
aarch64-linux = {
attr = "sdImage";
module =
{ modulesPath, ... }:
{
imports = [ "${modulesPath}/installer/sd-card/sd-image-aarch64-installer.nix" ];
};
};
x86_64-linux = {
attr = "isoImage";
module =
{ modulesPath, ... }:
{
imports = [ "${modulesPath}/installer/cd-dvd/installation-cd-base.nix" ];
systemd.services = {
sshd.wantedBy = lib.mkForce [ "multi-user.target" ];
wpa_supplicant.wantedBy = lib.mkForce [ "multi-user.target" ];
};
};
};
}
.${system};
in
(lib.nixosSystem {
inherit pkgs specialArgs;
modules = [
format.module
inputs.home-manager.nixosModules.home-manager
]
++ modules;
}).config.system.build.${format.attr};
in
{
packages = {
keygen = installerImage { modules = [ "${self}/hosts/utility/policestation" ]; };
# nix build --print-out-paths --no-link .#live-iso
live-iso = installerImage {
modules = [ "${self}/hosts/utility/drugstore" ];
specialArgs = {
inherit self;
inherit (self.swarselsystemsLib) root;
};
};
# nix build --print-out-paths --no-link .#swarsel-kexec --system <system>
swarsel-kexec =
(inputs.smallpkgs.legacyPackages.${system}.nixos [
{
imports = [ "${self}/hosts/utility/brickroad" ];
_file = __curPos.file;
system.kexec-installer.name = "swarsel-kexec";
}
inputs.nixos-images.nixosModules.kexec-installer
]).config.system.build.kexecInstallerTarball;
};
};
}
3.18. Tests
3.18.1. Bootstrapping
{ self, ... }:
{
perSystem =
{
lib,
pkgs,
system,
...
}:
let
secretKey = "toto-deploy-test";
in
lib.optionalAttrs (system == "x86_64-linux") {
packages.bootstrap-install-test = pkgs.writeShellApplication {
name = "bootstrap-install-test";
runtimeInputs = [
pkgs.coreutils
pkgs.git
pkgs.gnupg
pkgs.openssh
pkgs.qemu
pkgs.rsync
pkgs.sops
pkgs.ssh-to-age
self.packages.${system}.swarsel-bootstrap
];
text = ''
target_config=toto
secret_key="${secretKey}"
secret_plaintext="bootstrap-secret-deployment-ok"
ssh_port=2222
repo=$(git rev-parse --show-toplevel)
tmp=$(mktemp -d /tmp/bootstrap-test.XXXXXX)
work="$tmp/dotfiles"
host_dir="$work/hosts/nixos/${system}/$target_config"
qemu_pid=""
cleanup() {
rm -rf "$tmp"
if [[ -n $qemu_pid ]]; then
kill "$qemu_pid"
fi
}
trap cleanup EXIT
SSH_AUTH_SOCK=$(gpgconf --list-dirs agent-ssh-socket)
export SSH_AUTH_SOCK
ssh_up() {
timeout 3 bash -c "exec 3<> /dev/tcp/127.0.0.1/$ssh_port; head -c 4 <&3" 2> /dev/null | grep -q SSH
}
wait_for_ssh() {
for _ in $(seq 120); do
if ssh_up; then
return 0
fi
sleep 5
done
echo "no ssh on port $ssh_port after 10 minutes" >&2
exit 1
}
mkdir -p "$host_dir"
rsync -a --filter=':- .gitignore' --exclude=.git "$repo"/ "$work"/
install -m644 ${pkgs.writeText "toto.nix" ''
{
inputs,
lib,
pkgs,
minimal,
...
}:
{
imports = [
inputs.self.modules.nixos.disk-single-root
./hardware-configuration.nix
]
++ lib.optionals (!minimal) [
inputs.self.modules.nixos.profile-minimal
];
swarselsystems = {
info = "~SwarselSystems~ bootstrap test host";
isBtrfs = true;
isCrypted = false;
isImpermanence = true;
isLaptop = false;
isLinux = true;
isSecureBoot = false;
isSwap = true;
rootDisk = "/dev/vda";
swapSize = "2G";
};
sops.secrets.${secretKey} = { };
environment.systemPackages = [ pkgs.yubikey-manager ];
networking.firewall.enable = false;
nixpkgs.hostPlatform = "${system}";
node.lockFromBootstrapping = lib.mkForce false;
}
''} "$host_dir/default.nix"
echo "{ }" > "$host_dir/hardware-configuration.nix"
sed -i "/^host_configs = {$/a\\ $target_config = {\n type = \"nixos\"\n arch = \"${system}\"\n guests = []\n }" "$work/tofu/sops/terraform.tfvars"
echo "touch the yubikey to add the test secret"
sops set "$work/secrets/root.yaml" "[\"hosts\"][\"$target_config\"][\"$secret_key\"]" "\"$secret_plaintext\""
git -C "$work" init -q -b main
git -C "$work" add -A
git -C "$work" -c user.email=test@example.org -c user.name=test -c commit.gpgsign=false commit -q --no-verify -m "bootstrap-test base"
cp ${pkgs.OVMF.fd}/FV/OVMF_VARS.fd "$tmp/OVMF_VARS.fd"
chmod u+w "$tmp/OVMF_VARS.fd"
qemu-img create -q -f qcow2 "$tmp/disk.qcow2" 32G
qemu-system-x86_64 \
-enable-kvm -m 8192 -smp 4 \
-drive if=pflash,format=raw,readonly=on,file=${pkgs.OVMF.fd}/FV/OVMF_CODE.fd \
-drive if=pflash,format=raw,file="$tmp/OVMF_VARS.fd" \
-drive id=hd0,file="$tmp/disk.qcow2",if=none,format=qcow2 \
-device virtio-blk-pci,drive=hd0,bootindex=1 \
-drive id=cd0,file="$(echo ${self.packages.${system}.live-iso}/iso/*.iso)",if=none,media=cdrom \
-device ide-cd,drive=cd0,bootindex=2 \
-boot menu=off \
-netdev "user,id=net0,hostfwd=tcp::$ssh_port-:22" -device virtio-net,netdev=net0 \
-display none -serial "file:$tmp/console.log" &
qemu_pid=$!
wait_for_ssh
echo "running swarsel-bootstrap, touch the yubikey for the ssh login and the rekey"
FLAKE="$work" swarsel-bootstrap -p "$ssh_port" "$target_config" 127.0.0.1
if ! grep -q "&$target_config age1" "$work/.sops.yaml"; then
echo ".sops.yaml has no age key for $target_config" >&2
exit 1
fi
for _ in $(seq 60); do
ssh_up || break
sleep 2
done
wait_for_ssh
fetch_hostkey() {
scp -q -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null \
-o IdentitiesOnly=yes -i "$repo/files/public/ssh/yubikey.pub" \
-o PreferredAuthentications=publickey -P "$ssh_port" \
root@127.0.0.1:/etc/ssh/ssh_host_ed25519_key "$tmp/hostkey"
}
echo "touch the yubikey to fetch the host key of the installed system"
fetch_hostkey || fetch_hostkey || fetch_hostkey
SOPS_AGE_KEY=$(ssh-to-age -private-key -i "$tmp/hostkey")
export SOPS_AGE_KEY
got=$(sops decrypt --extract "[\"secrets__root.yaml\"][\"hosts\"][\"$target_config\"][\"$secret_key\"]" \
"$work/secrets/rekeyed/$target_config.yaml")
if [[ $got != "$secret_plaintext" ]]; then
echo "expected '$secret_plaintext', got '$got'" >&2
exit 1
fi
'';
};
};
}
3.18.2. Sandbox
{ self, inputs, ... }:
let
configName = "vacanthouse";
hostDir = "${self}/hosts/utility/${configName}";
overlays = [
self.overlays.default
self.overlays.stables
self.overlays.modifications
];
forArch =
arch:
let
sandboxPkgs = import inputs.nixpkgs-sandbox {
inherit overlays;
config.allowUnfree = true;
system = arch;
};
inherit (sandboxPkgs) lib;
mkSpecialArgs = nodes: {
inherit
self
inputs
lib
arch
configName
nodes
;
inherit (self) outputs;
inherit (self.outputs.swarselsystemsLib) root;
globals =
(lib.evalModules {
modules = [
self.modules.generic.globals
"${hostDir}/secrets/globals.nix"
{ globals = lib.mkMerge nodes.${configName}.config._globalsDefs; }
];
prefix = [ "globals" ];
specialArgs = {
inherit inputs lib nodes;
inherit (inputs.topologyPrivate) topologyPrivate;
};
}).config.globals;
homeLib = self.outputs.lib;
minimal = false;
type = "nixos";
withHomeManager = false;
};
nodeModule = {
swarselsystems.mainUser = "swarsel";
networking.hostName = configName;
nixpkgs = {
inherit overlays;
config.allowUnfree = true;
hostPlatform = arch;
};
node = {
inherit arch;
configDir = ../../hosts/utility/vacanthouse;
lockFromBootstrapping = true;
name = configName;
secretsDir = ../../hosts/utility/vacanthouse/secrets;
type = "nixos";
};
};
vacanthouseArgs = mkSpecialArgs { ${configName} = vacanthouse; };
vacanthouse = inputs.nixpkgs-sandbox.lib.nixosSystem {
modules = [
hostDir
nodeModule
];
specialArgs = vacanthouseArgs;
};
testCerts =
let
domains = vacanthouse.config.sandbox.tlsDomains;
baseDomain = self.outputs.swarselsystemsLib.getBaseDomain (builtins.head domains);
in
sandboxPkgs.runCommand "sandbox-test-certs" { nativeBuildInputs = [ sandboxPkgs.openssl ]; } ''
mkdir -p "$out"
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \
-keyout "$out/ca.key" -out "$out/ca.crt" -days 3650 -subj "/CN=${configName} test CA" \
-addext "basicConstraints=critical,CA:TRUE" -addext "keyUsage=critical,keyCertSign,cRLSign" \
-addext "nameConstraints=critical,permitted;DNS:${baseDomain}"
openssl req -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \
-keyout "$out/wildcard.key" -out wildcard.csr -subj "/CN=*.${baseDomain}" \
-addext "subjectAltName=${lib.concatMapStringsSep "," (d: "DNS:${d}") domains}"
openssl x509 -req -in wildcard.csr -CA "$out/ca.crt" -CAkey "$out/ca.key" -CAcreateserial \
-out "$out/wildcard.crt" -days 3650 -copy_extensions copy
'';
in
{
inherit
mkSpecialArgs
nodeModule
sandboxPkgs
testCerts
vacanthouse
;
inherit (vacanthouseArgs.globals) services;
};
in
{
flake-file.inputs.nixpkgs-sandbox.url = "github:r-ryantm/nixpkgs/4800f20ae2dc52cc7422118d28d427ef412f0841";
flake.nixosConfigurations.${configName} = (forArch "x86_64-linux").vacanthouse;
perSystem =
{
lib,
system,
...
}:
lib.optionalAttrs (lib.hasSuffix "-linux" system) (
let
inherit (forArch system)
mkSpecialArgs
nodeModule
sandboxPkgs
services
testCerts
;
in
{
packages.sandbox-test = sandboxPkgs.testers.runNixOSTest (
{ nodes, ... }:
{
name = "sandbox-${configName}";
node = {
pkgsReadOnly = false;
specialArgs = mkSpecialArgs { ${configName}.config = nodes.${configName}; };
};
testScript = ''
vacanthouse.start()
vacanthouse.wait_for_unit("multi-user.target")
vacanthouse.wait_for_unit("kanidm.service")
vacanthouse.wait_until_succeeds("curl -sSf https://${services.kanidm.domain}/status", timeout=600)
vacanthouse.succeed("curl -sSf https://${services.kanidm.domain}/oauth2/openid/homebox/.well-known/openid-configuration")
vacanthouse.wait_until_succeeds("curl -sSf http://127.0.0.1:3004/ready", timeout=600)
vacanthouse.succeed("curl -sSf -o /dev/null https://${services.oauth2-proxy.domain}/oauth2/sign_in")
vacanthouse.wait_until_succeeds("curl -sSf https://${services.homebox.domain}/api/v1/status", timeout=600)
'';
nodes.${configName} = {
imports = [
hostDir
nodeModule
];
users.users.root.hashedPassword = lib.mkForce null;
sandbox.tls = {
ca = "${testCerts}/ca.crt";
certificate = "${testCerts}/wildcard.crt";
keyFile = "${testCerts}/wildcard.key";
};
virtualisation = {
cores = 2;
memorySize = 4096;
};
};
}
);
}
);
}
3.18.3. Root mirror
{ self, inputs, ... }:
{
perSystem =
{
lib,
pkgs,
system,
...
}:
lib.optionalAttrs (lib.hasSuffix "-linux" system) {
packages.root-mirror-test =
let
mirror = inputs.nixpkgs.lib.nixosSystem {
modules = [
inputs.disko.nixosModules.disko
inputs.lanzaboote.nixosModules.lanzaboote
self.modules.generic.options
self.modules.nixos.disk-encrypt
self.modules.nixos.impermanence
self.modules.nixos.disk-mirrored-root
"${inputs.nixpkgs}/nixos/modules/profiles/qemu-guest.nix"
(
{ config, pkgs, ... }:
{
swarselsystems = {
isBtrfs = true;
isCrypted = true;
isImpermanence = true;
rootDisk = "/dev/disk/by-id/virtio-mirror-a";
rootMirrorDisk = "/dev/disk/by-id/virtio-mirror-b";
};
services.getty.autologinUser = "root";
boot = {
initrd.systemd = {
services.root-mirror-degraded.serviceConfig.StandardError = "journal+console";
contents."/etc/ssh/authorized_keys.d/root".source = lib.mkForce (
pkgs.runCommand "root-mirror-test-authorized-keys" { } ''
echo "command=\"${config.swarselsystems.initrdSshCommand}\" $(cat ${testKey}/key.pub)" > $out
''
);
emergencyAccess = true;
network = {
enable = true;
networks."10-test" = {
address = [ "192.168.1.200/24" ];
matchConfig.Name = "en* eth*";
};
};
};
loader.grub.enable = false;
};
networking.hostName = "mirror";
nixpkgs = {
hostPlatform = system;
overlays = [ self.overlays.additions ];
};
system.stateVersion = "26.05";
}
)
];
specialArgs = {
inherit self inputs;
inherit (self.outputs) lib;
inherit (self.outputs.swarselsystemsLib) root;
minimal = true;
};
};
inherit
(import "${inputs.nixpkgs}/nixos/lib/qemu-common.nix" {
inherit lib;
inherit (pkgs) stdenv;
})
qemuSerialDevice
;
testKey = pkgs.runCommand "root-mirror-test-key" { nativeBuildInputs = [ pkgs.openssh ]; } ''
mkdir $out
ssh-keygen -q -t ed25519 -N "" -C root-mirror-test -f $out/key
'';
normal = mirror.config.system.build.toplevel;
mkTarget = disks: {
virtualisation = {
directBoot.enable = false;
diskImage = null;
fileSystems."/" = {
device = "/dev/disk/by-label/unused";
fsType = "btrfs";
};
memorySize = 2048;
qemu = {
options = [
"-kernel ${normal}/kernel"
"-initrd ${normal}/initrd"
''-append "$(cat ${normal}/kernel-params) init=${normal}/init console=${qemuSerialDevice}"''
];
drives = map (disk: {
deviceExtraOpts.serial = "mirror-${disk}";
file = "$(pwd)/disk-${disk}.qcow2";
name = "disk-${disk}";
}) disks;
networkingOptions = lib.mkForce [ ];
};
useDefaultFilesystems = false;
useEFIBoot = true;
};
};
in
pkgs.testers.runNixOSTest {
name = "root-mirror-test";
testScript = ''
import shutil
from datetime import timedelta
from test_driver.errors import RequestedAssertionFailed
with subtest("install"):
installer.start()
installer.wait_for_unit("multi-user.target")
installer.succeed("echo mirrorpass > /tmp/disko-password")
installer.succeed("${mirror.config.system.build.formatMount}/bin/disko-format-mount >&2", timeout=timedelta(minutes=15))
installer.succeed("btrfs filesystem df /mnt | grep -q 'Data, RAID1'")
installer.succeed("nixos-install --no-root-passwd --no-bootloader --no-channel-copy --system ${normal} >&2", timeout=timedelta(minutes=30))
installer.succeed("umount -R /mnt && cryptsetup close cryptroot && cryptsetup close cryptroot-mirror && sync")
installer.shutdown()
for index, disk in enumerate("ab"):
(installer.state_dir / f"empty{index}.qcow2").rename(installer.state_dir / f"disk-{disk}.qcow2")
def boot(machine):
machine.state_dir = installer.state_dir
machine.start()
for _ in range(40):
machine.send_console("mirrorpass\n")
try:
machine.wait_for_console_text("root@mirror:~", timeout=timedelta(seconds=15))
return
except RequestedAssertionFailed:
continue
raise RequestedAssertionFailed(f"{machine.name} did not reach a shell")
def check(machine, command):
machine.send_console(f"{command} && printf 'check-%s\\n' ok\n")
machine.wait_for_console_text("check-ok", timeout=timedelta(minutes=2))
def poweroff(machine):
machine.send_console("poweroff\n")
machine.wait_for_shutdown()
def assert_degraded_flag(machine):
machine.wait_for_console_text("reboot: Restarting system", timeout=timedelta(minutes=3))
machine.wait_for_shutdown()
flags = [var.data for var in machine.read_efi_vars() if var.name == "SwarselDegraded"]
assert flags == [b"\x01"], f"{machine.name} has SwarselDegraded {flags!r}"
def degraded_checks(machine):
check(machine, "btrfs filesystem show / | grep -qi missing")
check(machine, "test ! -e /sys/firmware/efi/efivars/SwarselDegraded-*")
check(machine, "grep -q kept /persist/marker")
check(machine, "test ! -e /wiped")
with subtest("both disks"):
boot(both)
check(both, "test \"$(btrfs filesystem show / | grep -c devid)\" = 2 && ! btrfs filesystem show / | grep -qi missing")
check(both, "btrfs filesystem df / | grep -q 'Data, RAID1' && btrfs filesystem df / | grep -q 'Metadata, RAID1'")
check(both, "echo kept > /persist/marker && touch /wiped && sync")
both.send_console("swarsel-degraded\n")
assert_degraded_flag(both)
with subtest("flagged boot with disk b"):
shutil.copy(both.efi_vars_path, onlyB.efi_vars_path)
boot(onlyB)
degraded_checks(onlyB)
poweroff(onlyB)
with subtest("unflagged boot with disk a stops in initrd"):
hungA.state_dir = installer.state_dir
hungA.start()
hungA.wait_for_console_text("passphrase", timeout=timedelta(minutes=5))
hungA.send_console("mirrorpass\n")
hungA.wait_for_console_text("Press Enter for system maintenance", timeout=timedelta(minutes=5))
client.start()
client.wait_until_succeeds("nc -z 192.168.1.200 2222", timeout=timedelta(minutes=5))
client.execute("ssh -p 2222 -i /etc/mirror-key -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root@192.168.1.200 degraded")
assert_degraded_flag(hungA)
with subtest("flagged boot with disk a"):
boot(hungA)
degraded_checks(hungA)
poweroff(hungA)
'';
nodes = {
both = mkTarget [
"a"
"b"
];
client.environment = {
etc.mirror-key = {
mode = "0600";
source = "${testKey}/key";
};
systemPackages = [ pkgs.netcat ];
};
hungA = mkTarget [ "a" ];
installer = {
boot.supportedFilesystems = [ "btrfs" ];
environment.systemPackages = [ pkgs.cryptsetup ];
nix.settings.substituters = lib.mkForce [ ];
virtualisation = {
additionalPaths = [
normal
mirror.config.system.build.formatMount
];
emptyDiskImages = [
{
driveConfig.deviceExtraOpts.serial = "mirror-a";
size = 4096;
}
{
driveConfig.deviceExtraOpts.serial = "mirror-b";
size = 4096;
}
];
memorySize = 4096;
};
};
onlyB = mkTarget [ "b" ];
};
};
};
}
3.19. Installer flake
When using tools like (the builtin) nixos-rebuild or nixos-anywhere, these tools expect the flake to have a certain structure; namely, they expect to find an output named nixosConfigurations, which is implicitly used when passing --flake .#<config name> (it is used in front of <config name>).
When I define my configurations, I am actually defining two versions for each actual system:
- One 'regular' config that should be used by all rebuild tools such as
nixos-rebuild - One 'minimal' config that should be used by
nixos-anywhereduring initial deployment of a system
Now, I could of course define a <name> and <name>-minimal attribute for each configuration and just put these under nixosConfigurations, but that would have several drawbacks:
- evaluation time would increase
- my
nodesoutput (that holds information for all actual systems) would bloat - it is actually not clear that
<name>and<name>-minimalrepresent the same config
Hence, what I instead do is to define another output nixosConfigurationsMinimal as an output to this flakes' config, and then use it to set the nixosConfigurations of another, minimal, flake that I keep in install/. When using nixos-anywhere during initial deployment, I will then point it to that minimal flake, where the minimal configs can be found.
{
description = "Minimal installer flake - automatically generated by SwarselSystems.org";
inputs.swarsel.url = "./../..";
outputs = { swarsel, ... }: { nixosConfigurations = swarsel.nixosConfigurationsMinimal; };
}
4. System
This section holds most of the relevant NixOS side of configuration.
4.1. Manual steps when setting up a new machine
In the Introduction (no code), I mentioned that this is a nearly fully declarative config. In fact, most client configs are in one way or another not fully declarative. I use oneshotting systemd services + sentinel files for most such tasks (which makes them declarative!), but some of them I would rather perform manually once. This mainly concerns work related things.
Whenever I encounter a configuration bit that needs manual steps, I use a Appendix A: Noweb-Ref blocks to tangle that bit of information into a central place (here). I discern between the following scenarios:
setup: Used in a standard NixOS + home-manager deploymentworksetup: Stuff to be done only on work machineshomemanageronlysetup: Steps that are needed only on machines that are not running NixOS.
4.1.1. Steps to setup/upgrade home-manager only
Steps to get a home-manager only setup up and running:
- (Optional) Install openssh-server
- Set hostname to the name specified in the home-manager configuration
- Install nix, either:
- (if upgrading existing nix) Install nix version matching with version that `nix-plugins` is compiled against: `nix-env --install --file '<nixpkgs>' cacert -I nixpkgs=channel:nixpkgs-unstable --attr nixVersions.nix_x_yy`
- (or installing nix freshly):
- Grab the link to the install script of the needed nix version from https://releases.nixos.org/?prefix=nix, e.g. https://releases.nixos.org/nix/nix-2.30.1/install
- `bash <(curl -L https://releases.nixos.org/nix/nix-x-yy-y/install) --daemon`
- add the following to /etc/nix/nix.conf to become a trusted user: `trusted-users = @wheel root swarsel`
- For the first build:
1) Clone dotfile repo & change into it
2) `nix --extra-experimental-features 'nix-command flakes' develop`
3) `home-manager --extra-experimental-features 'nix-command flakes' switch --flake .#$(hostname) --show-trace`
4.1.2. Steps to setup systems
4.2. Current issues
Besides the manual steps outlined above, sometimes things break when I update this flake. The fix, for me, is most of the times one of these two:
- instead of the broken package, use the package from the latest stable nixpkgs release where the package is still functioning (this is why I pull all of these in as inputs)
- if the broken component is critical, I perform manual patches/overrides.
In order to keep track of these changes, I gather them here in a similar style to what you saw in Manual steps when setting up a new machine. I simply prefix them with the date and check them after a while to see if things got better.
Currently, these adaptions are made to the configuration to account for bugs in upstream repos: - <2026-07-16 Do> - mautrix-telegram's python version is pinned to 3.13 - <2026-04-28 Di>: - element sets appid as "electron" - > match window-rule in niri to "title" - > set searchelement in the niri swarselcheck script to "title" - evolution data server broken > turn off in noctalia config - openldap test fails in lutris build chain > overlay that skips test (# TEMP comment) - 20260302: - navidrome is having build issues and set to stable - noto-fonts is having build issues and set to stable - libreoffice-* is having build issues and set to stable - also need to set services.gotenberg.libreoffice.package to stable - 20260224: - azure-cli is having build issues and set to stable - dwarfs is having build issues and set to stable - shortkeys is having build issues and disabled - anki is having build issues and set to stable - khal is having build issues and set to stable - 202501102: - flake: - emacs-overlay: - : version pinned because emacsclient is currently broken on latest - niri-flake: - currently not using the sugared version of screenshot-[,window], as it is currently broken - home-manager: - emacs-tramp: - using stable version in extraPackages (broken in unstable) - :ensure nil in emacs tramp settings to use package in extraPackages - emacs-calfwL - pinned to version not in nixpkgs (is in latest emacs-overlay, but that is broken) - vesktop: - running stable version (broken in unstable) - batgrep: - running stable version (broken in unstable)4.3. System specific configuration
This section mainly exists to house different default.nix files to define some modules that should be loaded on respective systems.
Every host is housed in the hosts/ directory, which is first subdivided by each respective system (nixos/, darwin/, home/, android/) and then its architecture, after which we find the host directory. As described earlier, configurations can be defined automatically in this flake.
4.3.1. Physical hosts
This is a list of all physical machines that I maintain.
4.3.1.1. pyramid (Framework Laptop 16)
My work machine. Built for more security, this is the gold standard of my configurations at the moment. Most of the client work configurations are in work and home-manager/work.
4.3.1.1.1. Main Configuration
{
inputs,
config,
lib,
minimal,
...
}:
{
imports = [
inputs.nixos-hardware.nixosModules.framework-16-7040-amd
./disk-config.nix
./hardware-configuration.nix
]
++ lib.optionals (!minimal) (
builtins.attrValues (
lib.getAttrs [
"profile-personal"
"amdcpu"
"amdgpu"
"framework"
"gaming"
"hibernation"
"nswitch-rcm"
"virtualbox"
"work"
"niri"
"noctalia"
] inputs.self.modules.nixos
)
);
swarselsystems = {
inherit (config.repo.secrets.local) hostName;
inherit (config.repo.secrets.local) fqdn;
firewall = lib.mkForce true;
hasBluetooth = true;
hasFingerprint = true;
hibernation.offset = 533760;
highResolution = "2560x1600";
info = "Framework Laptop 16, 7940HS, RX7700S, 64GB RAM";
isBtrfs = true;
isCrypted = true;
isImpermanence = false;
isLaptop = true;
isLinux = true;
isSecureBoot = true;
lowResolution = "1280x800";
sharescreen = "eDP-2";
wifiMac = config.repo.secrets.local.network.wifiMac;
};
topology.self.interfaces = {
eth1.network = lib.mkForce "home";
fritz-wg.network = "fritz-wg";
wifi = { };
};
home-manager.users.${config.swarselsystems.mainUser}.swarselsystems = {
isSecondaryGpu = true;
monitors.main = {
mode = "2560x1600";
name = "BOE 0x0BC9";
output = "eDP-2";
position = "2560,0";
scale = "1";
workspace = "15:L";
};
secondaryGpuCard = "pci-0000_03_00_0";
};
}
// lib.optionalAttrs (!minimal) {
networking.nftables.firewall.zones.untrusted.interfaces = [
"wlan*"
"enp*"
"eth*"
];
}
4.3.1.1.2. hardware-configuration
dcdebugmask enums: https://docs.kernel.org/gpu/amdgpu/driver-core.html#c.DC_DEBUG_MASK
This system is built with support for arm emulation, so it can build configurations that are meant to run on most of my cloud hosts (even though the remote builders are a better fit for this).
{
config,
lib,
pkgs,
modulesPath,
...
}:
{
imports = [
(modulesPath + "/installer/scan/not-detected.nix")
];
# Fix Wlan after suspend or Hibernate
# environment.etc."systemd/system-sleep/fix-wifi.sh".source =
# pkgs.writeShellScript "fix-wifi.sh" ''
# case $1/$2 in
# pre/*)
# ${pkgs.kmod}/bin/modprobe -r mt7921e mt792x_lib mt76
# echo 1 > /sys/bus/pci/devices/0000:04:00.0/remove
# ;;
# post/*)
# ${pkgs.kmod}/bin/modprobe mt7921e
# echo 1 > /sys/bus/pci/rescan
# ;;
# esac
# '';
boot = {
# kernelPackages = lib.mkDefault pkgs.linuxPackages_latest;
binfmt.emulatedSystems = [ "aarch64-linux" ];
extraModulePackages = [ ];
initrd = {
availableKernelModules = [
"nvme"
"xhci_pci"
"thunderbolt"
"usb_storage"
"cryptd"
"usbhid"
"sd_mod"
"r8152"
"drm"
"drm_kms_helper"
"ttm"
"gpu_sched"
];
# allow to remote build on arm (needed for moonside)
kernelModules = [ "sg" ];
luks.devices.cryptroot = {
# improve performance on ssds
bypassWorkqueues = true;
# crypttabExtraOpts = ["fido2-device=auto"];
};
};
kernelModules = [
"amdgpu"
"kvm-amd"
];
# kernelPackages = lib.mkDefault pkgs.kernelpin.linuxPackages;
kernelPackages = lib.mkDefault pkgs.kernelpin.linuxPackages_latest;
kernelParams = [
# deep sleep is discontinued by amd
# "mem_sleep_default=deep"
# supposedly, this helps save power on laptops
# in reality (at least on this model), this just generate excessive heat on the CPUs
# "amd_pstate=passive"
# Fix screen flickering issue at the cost of battery life (disable PSR and PSR-SU, keep PR enabled)
# test PSR/PR state with 'sudo grep '' /sys/kernel/debug/dri/0000*/eDP-2/*_capability'
# ref:
# https://old.reddit.com/r/framework/comments/1goh7hc/anyone_else_get_this_screen_flickering_issue/
# https://www.reddit.com/r/NixOS/comments/1hjruq1/graphics_corruption_on_kernel_6125_and_up/
# https://gitlab.freedesktop.org/drm/amd/-/issues/3797
"amdgpu.dcdebugmask=0x410"
];
};
hardware = {
cpu.amd.updateMicrocode = lib.mkDefault config.hardware.enableRedistributableFirmware;
deviceTree.enable = false;
};
# Enables DHCP on each ethernet and wireless interface. In case of scripted networking
# (the default) this is the recommended approach. When using systemd-networkd it's
# still possible to use this option, but it's recommended to use it in conjunction
# with explicit per-interface declarations with `networking.interfaces.<interface>.useDHCP`.
networking.useDHCP = lib.mkDefault true;
# networking.interfaces.enp196s0f3u1c2.useDHCP = lib.mkDefault true;
# networking.interfaces.wlp4s0.useDHCP = lib.mkDefault true;
nixpkgs.hostPlatform = lib.mkDefault "x86_64-linux";
}
4.3.1.1.3. disko
This system uses an encrypted root that is however not impermanent. At some point I should reset this host, but this will probably not happen while I use this machine at work.
{
disko.devices.disk.nvme0n1 = {
content = {
partitions = {
ESP = {
content = {
format = "vfat";
mountOptions = [
"defaults"
"umask=0077"
];
mountpoint = "/boot";
type = "filesystem";
};
label = "boot";
name = "ESP";
size = "512M";
type = "EF00";
};
luks = {
content = {
content = {
extraArgs = [
"-L"
"nixos"
"-f"
];
subvolumes = {
"/home" = {
mountOptions = [
"subvol=home"
"compress=zstd"
"noatime"
];
mountpoint = "/home";
};
"/log" = {
mountOptions = [
"subvol=log"
"compress=zstd"
"noatime"
];
mountpoint = "/var/log";
};
"/nix" = {
mountOptions = [
"subvol=nix"
"compress=zstd"
"noatime"
];
mountpoint = "/nix";
};
"/persist" = {
mountOptions = [
"subvol=persist"
"compress=zstd"
"noatime"
];
mountpoint = "/persist";
};
"/root" = {
mountOptions = [
"subvol=root"
"compress=zstd"
"noatime"
];
mountpoint = "/";
};
"/swap" = {
mountpoint = "/swap";
swap.swapfile.size = "64G";
};
};
type = "btrfs";
};
extraOpenArgs = [
"--allow-discards"
"--perf-no_read_workqueue"
"--perf-no_write_workqueue"
];
name = "cryptroot";
# https://0pointer.net/blog/unlocking-luks2-volumes-with-tpm2-fido2-pkcs11-security-hardware-on-systemd-248.html
settings.crypttabExtraOpts = [
"fido2-device=auto"
"token-timeout=10"
];
type = "luks";
};
label = "luks";
size = "100%";
};
};
type = "gpt";
};
device = "/dev/nvme0n1";
type = "disk";
};
fileSystems = {
"/".neededForBoot = true; # this is ok because this is not a impermanence host
"/home".neededForBoot = true;
"/persist".neededForBoot = true;
"/var/log".neededForBoot = true;
};
}
4.3.1.2. Bakery (Lenovo ThinkPad)
My personal laptop. Closely follows the pyramid config, but leaves out some security features that I consider a bother on my work machine. Contrary to pyramid, this uses a clean, impermanent setup.
4.3.1.2.1. Main Configuration
{
inputs,
config,
lib,
pkgs,
minimal,
...
}:
{
imports = [
inputs.nixos-hardware.nixosModules.common-cpu-intel
inputs.self.modules.nixos.disk-single-root
./hardware-configuration.nix
]
++ lib.optionals (!minimal) (
builtins.attrValues (
lib.getAttrs [
"profile-personal"
"gaming"
"nswitch-rcm"
"virtualbox"
"niri"
"noctalia"
] inputs.self.modules.nixos
)
);
swarselsystems = {
firewall = lib.mkForce true;
hasBluetooth = true;
hasFingerprint = true;
highResolution = "1920x1080";
info = "Lenovo Ideapad 720S-13IKB";
isBtrfs = true;
isCrypted = true;
isFullBuild = false;
isImpermanence = true;
isLaptop = true;
isLinux = true;
isSecureBoot = false;
isSwap = true;
lowResolution = "1280x800";
rootDisk = "/dev/nvme0n1";
sharescreen = "eDP-1";
swapSize = "4G";
};
topology.self.interfaces = {
eth1.network = lib.mkForce "home";
wifi = { };
};
environment.systemPackages = [ pkgs.yubikey-manager ];
home-manager.users.${config.swarselsystems.mainUser}.swarselsystems.monitors.main = {
mode = "1920x1080";
name = "LG Display 0x04EF Unknown";
output = "eDP-1";
position = "1920,0";
scale = "1";
workspace = "15:L";
};
}
4.3.1.2.2. hardware-configuration
# 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,
modulesPath,
...
}:
{
imports = [
(modulesPath + "/installer/scan/not-detected.nix")
];
boot = {
extraModulePackages = [ ];
initrd = {
availableKernelModules = [
"xhci_pci"
"nvme"
"usb_storage"
"sd_mod"
];
kernelModules = [ ];
};
kernelModules = [ ];
};
hardware.cpu.intel.updateMicrocode = lib.mkDefault config.hardware.enableRedistributableFirmware;
nixpkgs.hostPlatform = lib.mkDefault "x86_64-linux";
# FIXME: remove when redeploying and instead increase swapSize
swapDevices = [
{
device = "/swapfile";
size = 20 * 1024;
}
];
}
4.3.1.3. Winters (Server: ASRock J4105-ITX)
This used to be my main server (it is now replaced by Summers (Server: ASUS Z10PA-D8)). It is now my IoT management system and the Wi-Fi access point for the home, guest and IoT networks. Its root filesystem is a btrfs RAID1 mirrored across two encrypted disks.
4.3.1.3.1. Main Configuration
{
self,
inputs,
lib,
minimal,
...
}:
{
imports = [
./hardware-configuration.nix
inputs.nixos-hardware.nixosModules.common-cpu-intel
self.modules.nixos.disk-mirrored-root
self.modules.nixos.systemd-networkd-server-home
self.modules.nixos.nix-topology-self
]
++ lib.optionals minimal [
self.modules.nixos.server-network
]
++ lib.optionals (!minimal) [
self.modules.nixos.profile-localserver
self.modules.nixos.wireguard
self.modules.nixos.smartctl-exporter
self.modules.nixos.zigbee2mqtt
self.modules.nixos.home-assistant
self.modules.nixos.hostapd
self.modules.nixos.scanservjs
];
swarselsystems = {
flakePath = "/root/.dotfiles";
info = "ASRock J4105-ITX, 32GB RAM";
initrdVLAN = "home";
isBtrfs = true;
isCrypted = true;
isImpermanence = true;
isLinux = true;
isSecureBoot = true;
isSwap = false;
localVLANs = [
"services"
"home"
"iot"
];
networkKernelModules = [ "r8169" ];
proxyHost = "twothreetunnel";
rootDisk = "/dev/disk/by-id/ata-Vi550_S3_SSD_493525388374974";
rootMirrorDisk = "/dev/disk/by-id/ata-C300-CTFDDAC064MAG_00000000104302FE494D";
writeGlobalNetworks = false;
};
topology.self.interfaces.lan = { };
boot.loader = {
efi.canTouchEfiVariables = true;
systemd-boot.enable = true;
};
hardware.enableRedistributableFirmware = true;
}
4.3.1.3.2. hardware-configuration
{
config,
lib,
modulesPath,
...
}:
{
imports = [
(modulesPath + "/installer/scan/not-detected.nix")
];
boot = {
extraModulePackages = [ ];
initrd = {
availableKernelModules = [
"ahci"
"xhci_pci"
"usb_storage"
"usbhid"
"sd_mod"
];
kernelModules = [ ];
};
kernelModules = [ "kvm-intel" ];
};
hardware.cpu.intel.updateMicrocode = lib.mkDefault config.hardware.enableRedistributableFirmware;
nixpkgs.hostPlatform = lib.mkDefault "x86_64-linux";
}
4.3.1.4. Summers (Server: ASUS Z10PA-D8)
This is my current main server at home; all services except filesystem backups run in separate MicroVMs (see Guests). Generally, all services that have any amount of significant data will be run on this server, and not on the Oracle Cloud instances.
4.3.1.4.1. Main Configuration
{
self,
inputs,
config,
lib,
confLib,
minimal,
...
}:
{
imports = [
./hardware-configuration.nix
inputs.nixos-hardware.nixosModules.common-cpu-intel
self.modules.nixos.disk-mirrored-root
self.modules.nixos.systemd-networkd-server-home
self.modules.nixos.microvm-host
]
++ lib.optionals (!minimal) [
self.modules.nixos.profile-localserver
self.modules.nixos.wireguard
self.modules.nixos.restic
self.modules.nixos.syncoid
self.modules.nixos.podman
self.modules.nixos.opkssh
self.modules.nixos.smartctl-exporter
self.modules.nixos.zfs-exporter
self.modules.nixos.ipmi-exporter
];
swarselsystems = {
flakePath = "/root/.dotfiles";
info = "ASUS Z10PA-D8, 2* Intel Xeon E5-2650 v4, 128GB RAM";
initrdVLAN = "home";
isBtrfs = true;
isCrypted = true;
isImpermanence = true;
isLinux = true;
isSecureBoot = true;
isSwap = false;
localVLANs = [
"services"
"home"
]; # devices is only provided on interface for bmc
microVMPool = "Speed";
networkKernelModules = [ "igb" ];
proxyHost = "twothreetunnel";
rootDisk = "/dev/disk/by-id/ata-TS120GMTS420S_J024880123";
rootMirrorDisk = "/dev/disk/by-id/ata-Intenso_SSD_Sata_III_2026071600222";
server = {
restic.targets = {
SwarselState = {
# nextcloud stores all data in state dir and has no data that needs backup
paths = lib.map (guest: "/${config.swarselsystems.microVMPool}/guests/${guest}/state") (
builtins.filter (name: name != "nextcloud") (builtins.attrNames config.guests)
);
repository = config.repo.secrets.local.resticRepoState;
};
SwarselStorage = {
paths = [
"/${config.swarselsystems.storagePool}/Eternor/Pictures"
"/${config.swarselsystems.storagePool}/Eternor/Documents/paperless"
];
repository = config.repo.secrets.local.resticRepoStorage;
};
};
sanoid.datasets."${config.swarselsystems.microVMPool}/guests" = { };
syncoid.targets."${config.swarselsystems.microVMPool}/guests".target =
"${config.swarselsystems.storagePool}/backup/guests";
};
storagePool = "Lazy";
withMicroVMs = true;
writeGlobalNetworks = false;
};
topology.self.interfaces = {
bmc = { };
lan = { };
};
boot = {
blacklistedKernelModules = [
"snd_virtuoso"
"snd_oxygen"
];
initrd.kernelModules = [
"vfio_pci"
"vfio_iommu_type1"
"vfio"
];
kernelParams = [
"intel_iommu=on"
"iommu=pt"
"vfio-pci.ids=13f6:8788"
];
loader = {
efi.canTouchEfiVariables = true;
systemd-boot.enable = true;
};
};
hardware.enableRedistributableFirmware = true;
}
// lib.optionalAttrs (!minimal) {
guests = lib.concatMapAttrs (name: args: confLib.mkMicrovm name ({ withZfs = true; } // args)) {
ankisync = { };
atuin = { };
audio.eternorPaths = [ "Music" ];
dawarich = { };
firefly = { };
forgejo = { };
freshrss = { };
homebox = { };
immich.eternorPaths = [ "Pictures" ];
jellyfin.eternorPaths = [ "Videos" ];
kanidm = { };
kavita.eternorPaths = [ "Books" ];
koillection = { };
matrix = { };
mealie = { };
monitoring = { };
nextcloud = { };
paperless.eternorPaths = [ "Documents" ];
radicale = { };
storage.eternorPaths = [
"Backup"
"Books"
"Videos"
"Music"
"Pictures"
"Software"
"Documents"
];
transmission.eternorPaths = [
"Books"
"Videos"
"Music"
"Software"
];
utility = { };
};
networking.nftables.firewall.zones.untrusted.interfaces = [
"lan"
"bmc"
];
}
4.3.1.4.2. hardware-configuration
{
config,
lib,
modulesPath,
...
}:
{
imports = [
(modulesPath + "/installer/scan/not-detected.nix")
];
boot = {
extraModulePackages = [ ];
initrd = {
availableKernelModules = [
"ahci"
"xhci_pci"
"usbhid"
"usb_storage"
"sd_mod"
];
kernelModules = [ ];
};
kernelModules = [ "kvm-intel" ];
supportedFilesystems = [ "zfs" ];
zfs = {
extraPools = [
"Lazy"
"Speed"
];
forceImportRoot = false;
};
};
hardware.cpu.intel.updateMicrocode = lib.mkDefault config.hardware.enableRedistributableFirmware;
# Enables DHCP on each ethernet and wireless interface. In case of scripted networking
# (the default) this is the recommended approach. When using systemd-networkd it's
# still possible to use this option, but it's recommended to use it in conjunction
# with explicit per-interface declarations with `networking.interfaces.<interface>.useDHCP`.
networking.useDHCP = lib.mkDefault true;
# networking.interfaces.enp3s0.useDHCP = lib.mkDefault true;
nixpkgs.hostPlatform = lib.mkDefault "x86_64-linux";
}
4.3.1.4.3. Guests
echo "Currently using $(nix eval .#guestResources.summers.mem 2>/dev/null) MB out of 128GB RAM"
echo "Currently using $(nix eval .#guestResources.summers.vcpu 2>/dev/null) vCPUs. 48 threads are available."
{
self,
lib,
minimal,
...
}:
{
imports = [
self.modules.nixos.profile-microvm
self.modules.nixos.kavita
self.modules.nixos.audiobookshelf
];
}
// lib.optionalAttrs (!minimal) {
microvm = {
mem = 1024 * 3;
vcpu = 2;
};
}
{
self,
lib,
minimal,
...
}:
{
imports = [
self.modules.nixos.profile-microvm
self.modules.nixos.jellyfin
self.modules.nixos.seerr
];
}
// lib.optionalAttrs (!minimal) {
microvm = {
mem = 1024 * 3;
vcpu = 4;
};
}
{
self,
lib,
pkgs,
minimal,
...
}:
{
imports = [
self.modules.nixos.profile-microvm
self.modules.nixos.navidrome
self.modules.nixos.spotifyd
self.modules.nixos.mpd
self.modules.nixos.yubal
];
}
// lib.optionalAttrs (!minimal) {
environment.persistence."/state".directories = [
{
directory = "/var/lib/alsa";
group = "root";
user = "root";
}
];
microvm = {
devices = [
{
bus = "pci";
path = "0000:04:04.0";
}
];
mem = 1024 * 3;
qemu.machine = "q35";
vcpu = 2;
};
systemd.services.audio-mixer-init = {
after = [ "sound.target" ];
script = ''
${pkgs.alsa-utils}/bin/amixer -c 0 sset 'Analog Output' Multichannel
'';
serviceConfig = {
RemainAfterExit = true;
Type = "oneshot";
};
wantedBy = [ "sound.target" ];
};
}
{
self,
lib,
minimal,
...
}:
{
imports = [
self.modules.nixos.profile-microvm
self.modules.nixos.matrix
];
}
// lib.optionalAttrs (!minimal) {
microvm = {
mem = 1024 * 3;
vcpu = 2;
};
}
{
self,
lib,
minimal,
...
}:
{
imports = [
self.modules.nixos.profile-microvm
self.modules.nixos.nextcloud
];
}
// lib.optionalAttrs (!minimal) {
microvm = {
mem = 1024 * 3;
vcpu = 2;
};
}
{
self,
lib,
minimal,
...
}:
{
imports = [
self.modules.nixos.profile-microvm
self.modules.nixos.immich
];
}
// lib.optionalAttrs (!minimal) {
microvm = {
mem = 1024 * 10;
vcpu = 8;
};
}
{
self,
lib,
minimal,
...
}:
{
imports = [
self.modules.nixos.profile-microvm
self.modules.nixos.paperless
];
}
// lib.optionalAttrs (!minimal) {
microvm = {
mem = 1024 * 5;
vcpu = 4;
};
}
{
self,
config,
lib,
minimal,
...
}:
{
imports = [
self.modules.nixos.profile-microvm
self.modules.nixos.transmission
self.modules.nixos.slskd
];
swarselsystems.proxyHost = config.node.name;
}
// lib.optionalAttrs (!minimal) {
microvm = {
mem = 1024 * 6;
vcpu = 4;
};
}
{
self,
lib,
minimal,
...
}:
{
imports = [
self.modules.nixos.profile-microvm
self.modules.nixos.nfs
self.modules.nixos.server-syncthing
];
swarselsystems.nodeRoles = [ "homeSyncthingServer" ];
}
// lib.optionalAttrs (!minimal) {
microvm = {
mem = 1024 * 2 - 1;
vcpu = 2;
};
}
{
self,
lib,
minimal,
...
}:
{
imports = [
self.modules.nixos.profile-microvm
self.modules.nixos.grafana
self.modules.nixos.mimir
self.modules.nixos.loki
self.modules.nixos.tempo
self.modules.nixos.pyroscope
self.modules.nixos.gotify
self.modules.nixos.parsedmarc
];
swarselsystems.nodeRoles = [ "monitoringServer" ];
}
// lib.optionalAttrs (!minimal) {
microvm = {
mem = 1024 * 8;
vcpu = 4;
};
}
{
self,
lib,
minimal,
...
}:
{
imports = [
self.modules.nixos.profile-microvm
self.modules.nixos.freshrss
];
}
// lib.optionalAttrs (!minimal) {
microvm = {
mem = 1024 * 2 - 1;
vcpu = 1;
};
}
{
self,
lib,
minimal,
...
}:
{
imports = [
self.modules.nixos.profile-microvm
self.modules.nixos.kanidm
];
}
// lib.optionalAttrs (!minimal) {
microvm = {
mem = 1024 * 2 - 1;
vcpu = 2;
};
}
{
self,
lib,
minimal,
...
}:
{
imports = [
self.modules.nixos.profile-microvm
self.modules.nixos.firefly-iii
];
}
// lib.optionalAttrs (!minimal) {
microvm = {
mem = 1024 * 2 - 1;
vcpu = 1;
};
}
{
self,
lib,
minimal,
...
}:
{
imports = [
self.modules.nixos.profile-microvm
self.modules.nixos.koillection
];
}
// lib.optionalAttrs (!minimal) {
microvm = {
mem = 1024 * 1;
vcpu = 1;
};
}
{
self,
lib,
minimal,
...
}:
{
imports = [
self.modules.nixos.profile-microvm
self.modules.nixos.radicale
];
}
// lib.optionalAttrs (!minimal) {
microvm = {
mem = 1024 * 1;
vcpu = 1;
};
}
{
self,
lib,
minimal,
...
}:
{
imports = [
self.modules.nixos.profile-microvm
self.modules.nixos.atuin
];
}
// lib.optionalAttrs (!minimal) {
microvm = {
mem = 1024 * 1;
vcpu = 1;
};
}
{
self,
lib,
minimal,
...
}:
{
imports = [
self.modules.nixos.profile-microvm
self.modules.nixos.forgejo
];
}
// lib.optionalAttrs (!minimal) {
microvm = {
mem = 1024 * 2 - 1;
vcpu = 1;
};
}
{
self,
lib,
minimal,
...
}:
{
imports = [
self.modules.nixos.profile-microvm
self.modules.nixos.ankisync
];
}
// lib.optionalAttrs (!minimal) {
microvm = {
mem = 1024 * 1;
vcpu = 1;
};
}
{
self,
lib,
minimal,
...
}:
{
imports = [
self.modules.nixos.profile-microvm
self.modules.nixos.homebox
];
}
// lib.optionalAttrs (!minimal) {
microvm = {
mem = 1024 * 1;
vcpu = 1;
};
}
{
self,
lib,
minimal,
...
}:
{
imports = [
self.modules.nixos.profile-microvm
self.modules.nixos.mealie
];
}
// lib.optionalAttrs (!minimal) {
microvm = {
mem = 1024 * 2 - 1;
vcpu = 1;
};
}
{
self,
lib,
minimal,
...
}:
{
imports = [
self.modules.nixos.profile-microvm
self.modules.nixos.dawarich
];
}
// lib.optionalAttrs (!minimal) {
microvm = {
mem = 1024 * 3;
vcpu = 2;
};
}
{
self,
lib,
minimal,
...
}:
{
imports = [
self.modules.nixos.profile-microvm
self.modules.nixos.invidious-companion
self.modules.nixos.socks-proxy
];
}
// lib.optionalAttrs (!minimal) {
microvm = {
mem = 1024 * 2 - 1;
vcpu = 2;
};
}
4.3.1.5. Hintbooth (Router: HUNSN RM02)
This machine serves as my home router (see Router). It also provides an HTTP proxy endpoint in my local network over DNS rewrites.
4.3.1.5.1. Main Configuration
{
self,
config,
lib,
confLib,
globals,
minimal,
nodes,
...
}:
{
imports = [
./hardware-configuration.nix
self.modules.nixos.disk-mirrored-root
self.modules.nixos.systemd-networkd-server-home
self.modules.nixos.microvm-host
]
++ lib.optionals minimal [
self.modules.nixos.server-network
]
++ lib.optionals (!minimal) [
self.modules.nixos.wireguard
self.modules.nixos.profile-localserver
self.modules.nixos.profile-router
self.modules.nixos.smartctl-exporter
];
swarselsystems = {
flakePath = "/root/.dotfiles";
info = "HUNSN RM02, 8GB RAM";
initrdVLAN = "home";
isBtrfs = true;
isCrypted = true;
isImpermanence = true;
isLinux = true;
isSecureBoot = true;
isSwap = false;
localVLANs = builtins.attrNames globals.networks.home-lan.vlans;
networkKernelModules = [ "igb" ];
nodeRoles = [
"homeProxy"
"ntpServer"
"routerServer"
];
rootDisk = "/dev/disk/by-id/ata-TS64GMSA220S_K191160084";
rootMirrorDisk = "/dev/disk/by-id/ata-Fanxiang_S101_256GB_AA000000000000001538";
withMicroVMs = true;
};
topology.self.interfaces = {
lan1.physicalConnections = [
{
interface = "eth1";
node = "switch-bedroom";
}
];
lan2.physicalConnections = [
{
interface = "eth1";
node = "switch-kitchen";
}
];
lan3.physicalConnections = [
{
interface = "lan";
node = "summers";
}
];
lan4.physicalConnections = [
{
interface = "bmc";
node = "summers";
}
];
lan5.physicalConnections = [
{
interface = "eth1";
node = "switch-livingroom";
}
];
};
globals.wireguard.wgHome = {
clients = [
"hintbooth-adguardhome"
"hintbooth-nginx"
"summers"
]
++ map (guest: "summers-${guest}") (builtins.attrNames nodes.summers.config.guests)
++ [
"treehouse"
"winters"
];
netConfigPrefix = "home";
server = config.node.name;
};
zramSwap.enable = true;
}
// lib.optionalAttrs (!minimal) {
guests = confLib.mkMicrovm "adguardhome" { } // confLib.mkMicrovm "nginx" { };
}
4.3.1.5.2. hardware-configuration
{
config,
lib,
modulesPath,
...
}:
{
imports = [
(modulesPath + "/installer/scan/not-detected.nix")
];
boot = {
extraModulePackages = [ ];
initrd = {
availableKernelModules = [
"ahci"
"xhci_pci"
"usbhid"
"usb_storage"
"sd_mod"
];
kernelModules = [ ];
};
};
hardware.cpu.intel.updateMicrocode = lib.mkDefault config.hardware.enableRedistributableFirmware;
# Enables DHCP on each ethernet and wireless interface. In case of scripted networking
# (the default) this is the recommended approach. When using systemd-networkd it's
# still possible to use this option, but it's recommended to use it in conjunction
# with explicit per-interface declarations with `networking.interfaces.<interface>.useDHCP`.
networking.useDHCP = lib.mkDefault true;
# networking.interfaces.enp3s0.useDHCP = lib.mkDefault true;
nixpkgs.hostPlatform = lib.mkDefault "x86_64-linux";
}
4.3.1.5.3. Guests
echo "Currently using $(nix eval .#guestResources.hintbooth.mem 2>/dev/null) MB out of 8GB RAM"
echo "Currently using $(nix eval .#guestResources.hintbooth.vcpu 2>/dev/null) vCPUs. 4 threads are available."
{
self,
lib,
minimal,
...
}:
{
imports = [
self.modules.nixos.profile-microvm
self.modules.nixos.microvm-guest-shares
self.modules.nixos.adguardhome
];
swarselsystems.nodeRoles = [ "homeDnsServer" ];
}
// lib.optionalAttrs (!minimal) {
microvm = {
mem = 1024 * 1;
vcpu = 1;
};
}
{
self,
config,
lib,
confLib,
globals,
minimal,
...
}:
{
imports = [
self.modules.nixos.profile-microvm
self.modules.nixos.microvm-guest-shares
self.modules.nixos.oauth2-proxy
self.modules.nixos.nginx
self.modules.nixos.nginx-exporter
self.modules.nixos.acme
self.modules.nixos.nginx-otel
self.modules.nixos.treehouse-services
];
swarselsystems = {
nodeRoles = [ "homeWebProxy" ];
proxyHost = config.node.name;
};
}
// lib.optionalAttrs (!minimal) {
services.nginx = {
upstreams.fritzbox = {
servers.${globals.networks.home-lan.hosts.fritzbox.ipv4} = { };
};
virtualHosts.${globals.services.fritzbox.domain} = {
acmeRoot = null;
extraConfig = ''
proxy_ssl_verify off;
''
+ confLib.static.nginxAccessRules;
forceSSL = true;
locations."/" = {
proxyPass = "http://fritzbox";
proxyWebsockets = true;
};
useACMEHost = globals.domains.main;
};
};
microvm = {
mem = 3072;
vcpu = 1;
};
}
4.3.1.6. machpizza (MacBook Pro)
A Mac notebook that I have received from work. I use this machine for getting accustomed to the Apple ecosystem as well as as a sandbox for nix-Darwin configurations (the Darwin configuration is severely under-developed).
{
self,
config,
lib,
...
}:
let
inherit (config.repo.secrets.local) workUser;
in
{
imports = [
self.modules.darwin.profile-darwin
];
users.users.${workUser}.home = "/home/${workUser}";
services.karabiner-elements.enable = true;
home-manager.users.${workUser} = {
swarselsystems = {
isBtrfs = false;
isLaptop = true;
mainUser = workUser;
};
home.username = lib.mkForce workUser;
};
system.primaryUser = workUser;
}
4.3.1.7. Magicant (Phone)
{ self, ... }:
{
imports = [ self.modules.nixOnDroid.profile-personal ];
home-manager.config.swarselsystems.sshHosts = [
"belchsfactory"
"eagleland"
"hintbooth"
"liliputsteps"
"liliputstepsjump"
"moonside"
"stoicclub"
"summers"
"twothreetunnel"
"winters"
];
system.stateVersion = "23.05";
user = {
gid = 10418;
uid = 10418;
};
}
4.3.1.8. Treehouse (DGX Spark)
This is my workstation located at my workplace - I use it as a remote builder and for testing things on ARM architecture.
{
self,
root,
inputs,
config,
lib,
pkgs,
confLib,
globals,
...
}:
let
wireguardInterfaces = lib.filterAttrs (
_: wgCfg: builtins.elem config.node.name wgCfg.clients
) globals.wireguard;
presharedKeyName =
ifName: wgCfg: "wireguard-${wgCfg.server}-${config.node.name}-${ifName}-presharedKey";
in
{
imports = [
inputs.self.modules.homeManager.profile-base
inputs.self.modules.homeManager.profile-dgxspark
inputs.vbc-nix.homeManagerModules.work-remote
];
swarselsystems = {
homeSopsSecrets = {
automationhubtoken.rekey.keyPrefix = confLib.static.sharedSecrets.work;
ucKey.rekey.keyPrefix = confLib.static.sharedSecrets.work;
vpn-cert = {
path = "${config.home.homeDirectory}/.config/vpn/vbc.pem";
rekey.keyPrefix = confLib.static.sharedSecrets.work;
};
};
isLaptop = false;
wallpaper = root "files/wallpaper/landscape/surfacewp.png";
};
sops.secrets =
lib.genAttrs
[
"claude-mcp-env"
"openshift-kubeconfig"
"vcenter-config"
]
(_: {
rekey.enable = false;
})
// {
wireguard-private-key.rekey = {
generator.script = "wireguard";
pubFile = self + "/files/public/wg/${config.node.name}.pub";
};
}
// lib.mapAttrs' (
ifName: wgCfg:
lib.nameValuePair (presharedKeyName ifName wgCfg) {
rekey = {
generator.script = "wireguard-psk";
keyPrefix = "wireguard/${wgCfg.server}-${config.node.name}/";
};
}
) wireguardInterfaces;
services = {
work-remote.enable = true;
xcape = {
enable = true;
mapExpression.Control_L = "Escape";
};
};
programs = {
bash.sessionVariables = lib.genAttrs [
"ANSIBLE_GALAXY_SERVER_COMMUNITY_TOKEN"
"ANSIBLE_GALAXY_SERVER_PUBLISHED_TOKEN"
"ANSIBLE_GALAXY_SERVER_RH_CERTIFIED_TOKEN"
"ANSIBLE_GALAXY_SERVER_STAGING_TOKEN"
] (_: "$(cat ${config.sops.secrets.automationhubtoken.path})");
git.signing = {
format = lib.mkForce "ssh";
key = lib.mkForce "${config.home.homeDirectory}/.ssh/id_rsa.pub";
};
openstackclient = {
enable = true;
cloudsSettings = {
inherit (config.repo.secrets.work) clouds;
};
};
ssh = {
enable = true;
enableDefaultConfig = false;
settings = builtins.removeAttrs config.repo.secrets.work.sshConfig [ "*" ];
};
};
home.packages = [
pkgs._1password-cli
pkgs.attic-client
pkgs.azure-cli
pkgs.step-cli
(config.repo.secrets.work.vpnCli pkgs)
];
nix.settings.max-jobs = lib.mkForce "auto";
nixpkgs.overlays = [ inputs.vbc-nix.overlays.default ];
repo.secretFiles.work = ../../../../secrets/work/pii.nix.enc;
}
4.3.2. Virtual hosts
My server setup was originally built on Proxmox VE; back when I started, I created all kinds of wild Debian/Ubuntu/etc. KVMs and LXCs on there. However, the root disk suffered a weird failure at some point where it became unable to be cloned, while still functioning. I was for a long time rewriting all machines on there to use NixOS instead; this process is now finished.
Nowadays, this section holds only hosts living in the cloud. For VM guests on physical hosts, see the Guests section under the corresponding hostname in Physical hosts.
4.3.2.1. Moonside (OCI)
This machine used to be my proxy server, a functionality that is now provided by Twothreetunnel (OCI); nowadays, I use it to run non-crucial services in the cloud - i.e. any service that does not use important private data. As an effect, this mostly holds some text and image sharing tools as well as a number of game servers.
4.3.2.1.1. Main Configuration
{
self,
config,
lib,
minimal,
...
}:
let
inherit (config.repo.secrets.local.syncthing)
dev1
dev2
dev3
devices
loc1
;
in
{
imports = [
./hardware-configuration.nix
./disk-config.nix
self.modules.nixos.disk-single-root
self.modules.nixos.systemd-networkd-server
self.modules.nixos.nix-topology-self
]
++ lib.optionals (!minimal) [
self.modules.nixos.profile-localserver
self.modules.nixos.wireguard
self.modules.nixos.croc
self.modules.nixos.microbin
self.modules.nixos.shlink
self.modules.nixos.slink
self.modules.nixos.server-syncthing
self.modules.nixos.minecraft
self.modules.nixos.restic
self.modules.nixos.searx
self.modules.nixos.invidious
self.modules.nixos.firefox-syncserver
self.modules.nixos.copyparty
self.modules.nixos.shopservatory
self.modules.nixos.readeck
self.modules.nixos.metube
self.modules.nixos.collabora-online
self.modules.nixos.filestash
self.modules.nixos.librespeed
self.modules.nixos.opnform
self.modules.nixos.spliit
self.modules.nixos.gatus
];
swarselsystems = {
flakePath = "/root/.dotfiles";
info = "VM.Standard.A1.Flex, 4 vCPUs, 24GB RAM";
isBtrfs = true;
isCloud = true;
isCrypted = false;
isImpermanence = true;
isLinux = true;
isSecureBoot = false;
isSwap = false;
nodeRoles = [ "webSyncthingServer" ];
proxyHost = "twothreetunnel";
rootDisk = "/dev/sda";
server.restic.targets.SwarselMoonside = {
paths = [
"/persist/opt/minecraft"
];
postgresDatabases = [ "spliit" ];
repository = config.repo.secrets.local.resticRepo;
};
};
globals.services.syncthing-moonside.extraConfig = {
dataDir = "/sync";
extraDevices = devices;
extraFolders = {
"${loc1}" = {
devices = [
dev1
dev2
dev3
];
id = "5gsxv-rzzst";
path = "/sync/${loc1}";
type = "sendreceive";
versioning = {
params.keep = "3";
type = "simple";
};
};
Documents = {
devices = [ "pyramid" ];
id = "hgr3d-pfu3w";
path = "/sync/Documents";
type = "receiveonly";
versioning = {
params.keep = "2";
type = "simple";
};
};
runandbun = {
devices = [
"pyramid"
"magicant"
];
id = "kwnql-ev64v";
path = "/sync/runandbun";
type = "receiveonly";
versioning = {
params.keep = "5";
type = "simple";
};
};
};
};
system.stateVersion = "23.11";
}
// lib.optionalAttrs (!minimal) {
networking.nftables.firewall.zones.untrusted.interfaces = [ "lan" ];
}
4.3.2.1.2. hardware-configuration
{ lib, modulesPath, ... }:
{
imports = [ (modulesPath + "/profiles/qemu-guest.nix") ];
boot = {
extraModulePackages = [ ];
initrd = {
availableKernelModules = [
"xhci_pci"
"virtio_pci"
"virtio_scsi"
"usbhid"
];
kernelModules = [ ];
};
kernelModules = [ ];
};
nixpkgs.hostPlatform = lib.mkForce "aarch64-linux";
}
4.3.2.1.3. disko
{
disko.devices.disk.disk1 = {
content = {
partitions.sync = {
content = {
extraArgs = [
"-L"
"sync"
"-f"
]; # force overwrite
subvolumes."/sync" = {
mountOptions = [
"subvol=root"
"compress=zstd"
"noatime"
];
mountpoint = "/sync";
};
type = "btrfs";
};
size = "100%";
};
type = "gpt";
};
device = "/dev/sdb";
type = "disk";
};
}
4.3.2.2. Belchsfactory (OCI)
This machine acts as my build farm and nix binary cache. It also provides an S3 bucket that is meant to be used for the binary cache (however, it is occasionally used to have a separate object storage).
4.3.2.2.1. Main Configuration
{
self,
lib,
minimal,
...
}:
{
imports = [
./hardware-configuration.nix
self.modules.nixos.disk-single-root
self.modules.nixos.systemd-networkd-server
self.modules.nixos.nix-topology-self
]
++ lib.optionals (!minimal) [
self.modules.nixos.profile-localserver
self.modules.nixos.wireguard
self.modules.nixos.ssh-builder
self.modules.nixos.attic
self.modules.nixos.garage
self.modules.nixos.buildbot
self.modules.nixos.remotebuild
];
swarselsystems = {
flakePath = "/root/.dotfiles";
info = "VM.Standard.A1.Flex, 4 vCPUs, 24GB RAM";
isBtrfs = true;
isCloud = true;
isCrypted = true;
isImpermanence = true;
isLinux = true;
isSecureBoot = false;
isSwap = false;
proxyHost = "twothreetunnel";
rootDisk = "/dev/sda";
server.garage = {
buckets = [
"attic"
];
data_dir = {
capacity = "100G";
path = "/var/lib/garage/data";
};
keys.nixos = [
"attic"
];
};
};
topology.self.icon = "devices.cloud-server";
# use SSH key with own limits for nixbuild.net instead of the general one in remotebuild.nix
sops.secrets.nixbuild-net-key = lib.mkForce {
mode = "0400";
};
node.lockFromBootstrapping = lib.mkForce false;
zramSwap.enable = true;
}
4.3.2.2.2. hardware-configuration
{ lib, modulesPath, ... }:
{
imports = [ (modulesPath + "/profiles/qemu-guest.nix") ];
boot = {
binfmt.emulatedSystems = [
"x86_64-linux"
"i686-linux"
];
extraModulePackages = [ ];
initrd = {
availableKernelModules = [
"xhci_pci"
"virtio_pci"
"virtio_scsi"
"usbhid"
];
kernelModules = [ ];
};
kernelModules = [ ];
};
nixpkgs.hostPlatform = lib.mkForce "aarch64-linux";
}
4.3.2.3. Stoicclub (OCI)
This machine is the authoritative DNS server for my domain and is responsible for pushing records to Hurricane Electric as well as Hetzner Cloud.
4.3.2.3.1. Main Configuration
{
self,
lib,
minimal,
...
}:
{
imports = [
./hardware-configuration.nix
self.modules.nixos.disk-single-root
self.modules.nixos.systemd-networkd-server
self.modules.nixos.nix-topology-self
]
++ lib.optionals (!minimal) [
self.modules.nixos.profile-localserver
self.modules.nixos.wireguard
self.modules.nixos.knot
self.modules.nixos.acme-dns
];
swarselsystems = {
flakePath = "/root/.dotfiles";
info = "VM.Standard.A1.Flex, 1 vCPUs, 8GB RAM";
isBtrfs = true;
isCloud = true;
isCrypted = true;
isImpermanence = true;
isLinux = true;
isSecureBoot = false;
isSwap = false;
nodeRoles = [
"dnsServer"
"acmeDnsServer"
];
proxyHost = "twothreetunnel";
rootDisk = "/dev/disk/by-id/scsi-360e1a5236f034316a10a97cc703ce9e3";
};
topology.self.icon = "devices.cloud-server";
}
// lib.optionalAttrs (!minimal) {
networking.nftables.firewall.zones.untrusted.interfaces = [ "lan" ];
}
4.3.2.3.2. hardware-configuration
{ lib, modulesPath, ... }:
{
imports = [ (modulesPath + "/profiles/qemu-guest.nix") ];
boot = {
extraModulePackages = [ ];
initrd = {
availableKernelModules = [
"xhci_pci"
"virtio_pci"
"virtio_scsi"
"usbhid"
];
kernelModules = [ ];
};
kernelModules = [ ];
};
nixpkgs.hostPlatform = lib.mkForce "aarch64-linux";
}
4.3.2.4. Liliputsteps (OCI)
This servers is an SSH bastion responsible for shielding my others cloud instances from unauthorized access.
4.3.2.4.1. Main Configuration
{
self,
config,
lib,
minimal,
...
}:
{
imports = [
./hardware-configuration.nix
self.modules.nixos.disk-single-root
self.modules.nixos.systemd-networkd-server
self.modules.nixos.nix-topology-self
]
++ lib.optionals (!minimal) [
self.modules.nixos.profile-localserver
self.modules.nixos.bastion
self.modules.nixos.crowdsec
];
swarselsystems = {
flakePath = "/root/.dotfiles";
info = "VM.Standard.A1.Flex, 1 vCPUs, 8GB RAM";
isBtrfs = true;
isCloud = true;
isCrypted = true;
isImpermanence = true;
isLinux = true;
isSecureBoot = false;
isSwap = false;
nodeRoles = [ "jumphost" ];
rootDisk = "/dev/disk/by-id/scsi-360fb180663ec4f2793a763a087d46885";
};
topology.self = {
icon = "devices.cloud-server";
interfaces.ProxyJump = {
physicalConnections = [
(config.lib.topology.mkConnection "moonside" "lan")
(config.lib.topology.mkConnection "twothreetunnel" "lan")
(config.lib.topology.mkConnection "belchsfactory" "lan")
(config.lib.topology.mkConnection "stoicclub" "lan")
(config.lib.topology.mkConnection "eagleland" "wan")
];
virtual = true;
};
};
}
4.3.2.4.2. hardware-configuration
{ lib, modulesPath, ... }:
{
imports = [ (modulesPath + "/profiles/qemu-guest.nix") ];
boot = {
extraModulePackages = [ ];
initrd = {
availableKernelModules = [
"xhci_pci"
"virtio_pci"
"virtio_scsi"
"usbhid"
];
kernelModules = [ ];
};
kernelModules = [ ];
};
nixpkgs.hostPlatform = lib.mkForce "aarch64-linux";
}
4.3.2.5. Twothreetunnel (OCI)
This host acts as my main HTTP proxy for external access.
4.3.2.5.1. Main Configuration
{
self,
config,
lib,
minimal,
nodes,
...
}:
{
imports = [
./hardware-configuration.nix
self.modules.nixos.disk-single-root
self.modules.nixos.systemd-networkd-server
self.modules.nixos.nix-topology-self
]
++ lib.optionals (!minimal) [
self.modules.nixos.profile-localserver
self.modules.nixos.nginx
self.modules.nixos.nginx-exporter
self.modules.nixos.crowdsec
self.modules.nixos.acme
self.modules.nixos.oauth2-proxy
self.modules.nixos.wireguard
self.modules.nixos.firezone
self.modules.nixos.nginx-otel
];
swarselsystems = {
flakePath = "/root/.dotfiles";
info = "VM.Standard.A1.Flex, 2 vCPUs, 8GB RAM";
isBtrfs = true;
isCloud = true;
isCrypted = true;
isImpermanence = true;
isLinux = true;
isSecureBoot = false;
isSwap = false;
nodeRoles = [
"webProxy"
"oauthServer"
];
rootDisk = "/dev/disk/by-id/scsi-3608deb9b0d4244de95c6620086ff740d";
};
topology.self.icon = "devices.cloud-server";
globals.wireguard.wgProxy = {
clients = [
"moonside"
"stoicclub"
"winters"
"summers"
]
++ builtins.filter (name: nodes.${name}.config.swarselsystems.proxyHost == config.node.name) (
map (guest: "summers-${guest}") (builtins.attrNames nodes.summers.config.guests)
)
++ [
"belchsfactory"
"eagleland"
"hintbooth-adguardhome"
"hintbooth-nginx"
"treehouse"
];
netConfigPrefix = config.node.name;
server = config.node.name;
};
}
// lib.optionalAttrs (!minimal) {
networking.nftables = {
chains.forward.dnat = {
after = [ "conntrack" ];
rules = [ "ct status dnat accept" ];
};
firewall.zones.untrusted.interfaces = [ "lan" ];
};
}
4.3.2.5.2. hardware-configuration
{ lib, modulesPath, ... }:
{
imports = [ (modulesPath + "/profiles/qemu-guest.nix") ];
boot = {
extraModulePackages = [ ];
initrd = {
availableKernelModules = [
"xhci_pci"
"virtio_pci"
"virtio_scsi"
"usbhid"
];
kernelModules = [ ];
};
kernelModules = [ ];
};
nixpkgs.hostPlatform = lib.mkForce "aarch64-linux";
}
4.3.2.6. Eagleland (Hetzner)
This is my mail server. Since I do not really want to trust Oracle Cloud with any important data, I am running this one on Hetzner.
4.3.2.6.1. Main Configuration
:CUSTOMID: h:96540b9c-1610-45f2-ba19-916051ab5e10
{
self,
config,
lib,
minimal,
...
}:
{
imports = [
./hardware-configuration.nix
self.modules.nixos.disk-single-root
self.modules.nixos.systemd-networkd-server
self.modules.nixos.nix-topology-self
]
++ lib.optionals (!minimal) [
self.modules.nixos.profile-localserver
self.modules.nixos.mailserver
self.modules.nixos.wireguard
self.modules.nixos.restic
];
swarselsystems = {
flakePath = "/root/.dotfiles";
info = "2vCPU, 4GB Ram";
isBtrfs = true;
isCloud = true;
isCrypted = true;
isImpermanence = true;
isLinux = true;
isSecureBoot = false;
isSwap = true;
proxyHost = "twothreetunnel"; # proxies roundcube and mta-sts, mail records point at this host directly
rootDisk = "/dev/sda";
server.restic.targets.SwarselMail = {
paths = [
"/var/dkim"
"/var/sieve"
"/var/vmail"
];
repository = config.repo.secrets.local.resticRepo;
withPostgres = true;
};
swapSize = "4G";
};
topology.self.icon = "devices.cloud-server";
}
// lib.optionalAttrs (!minimal) {
networking.nftables.firewall.zones.untrusted.interfaces = [ "wan" ];
}
4.3.2.6.2. hardware-configuration
{ lib, modulesPath, ... }:
{
imports = [
(modulesPath + "/profiles/qemu-guest.nix")
];
boot = {
extraModulePackages = [ ];
initrd = {
availableKernelModules = [
"ahci"
"xhci_pci"
"virtio_pci"
"virtio_scsi"
"sd_mod"
"sr_mod"
];
kernelModules = [ ];
};
kernelModules = [ ];
};
nixpkgs.hostPlatform = lib.mkDefault "x86_64-linux";
}
4.3.3. Utility hosts
The machines listed here are not real hosts per se, but are rather used in some aspects of testing or deployment, i.e. these hosts do not exist permanently.
4.3.3.1. Drugstore (live ISO installer config)
This is a live environment ISO that I use to bootstrap new systems. It only loads a minimal configuration and no graphical interface. After booting this image on a host, find out its IP and bootstrap the system using the bootstrap utility.
NOTE: Yes, the path to this system does not follow the scheme outlined above - I still consider this a 'config' however, so I keep it here.
Steps to recover using live ISO:
- unlock LUKS:
cryptsetup luksOpen /dev/<crypted device> cryptroot - mount root:
mount -t btrfs -o subvol=root /dev/mapper/cryptroot /mnt - mounted other subvolumes:
mount -t btrfs -o subvol=<name> /dev/mapper/cryptroot /mnt/<name>for all subvolumes - mounted boot:
mount -o umask=077 /dev/<boot device> /mnt/boot - mount sbctl keys:
mount -o bind /mnt/persist/var/lib/sbctl /mnt/var/lib/sbctl - make it look like NixOS system:
touch /mnt/etc/NIXOS - chroot:
nixos-enter - Then to e.g. fix missing bootloader entries:
/nix/var/nix/profiles/system/bin/switch-to-configuration boot
{
self,
root,
config,
lib,
pkgs,
...
}:
let
pubKeys = lib.filesystem.listFilesRecursive (root "files/public/ssh");
stateVersion = lib.mkDefault "23.05";
isSdImage = config.boot.loader.generic-extlinux-compatible.enable;
userHome = config.users.users.swarsel.home;
stablePkgs = import self.inputs.nixpkgs-stable26_05 { inherit (pkgs.stdenv.hostPlatform) system; };
in
{
config = {
users = {
users = {
root = {
initialHashedPassword = lib.mkForce null;
openssh.authorizedKeys.keys = config.users.users.swarsel.openssh.authorizedKeys.keys;
password = lib.mkForce config.users.users.swarsel.password; # this is overwritten after install
};
swarsel = {
extraGroups = [ "wheel" ];
group = "swarsel";
isNormalUser = true;
name = "swarsel";
openssh.authorizedKeys.keys = map builtins.readFile pubKeys;
password = "setup"; # this is overwritten after install
};
};
allowNoPasswordLogin = true;
groups.swarsel = { };
};
services = {
getty.autologinUser = lib.mkForce "root";
openssh = {
enable = true;
authorizedKeysFiles = lib.mkForce [
"/etc/ssh/authorized_keys.d/%u"
"%h/.ssh/authorized_keys"
];
settings.PermitRootLogin = "yes";
};
qemuGuest.enable = true;
xserver.xkb.layout = "us";
};
programs = {
bash.shellAliases = {
swarsel-kernel-module = "lspci -k -d";
swarsel-net-manufacturer = "lspci -nn | grep -i 'network\\|ethernet'";
};
git.enable = true;
};
boot = {
loader.systemd-boot.enable = !isSdImage;
supportedFilesystems = lib.mkForce [
"btrfs"
"vfat"
];
};
console.keyMap = "us";
environment = {
etc.issue.text = ''
[32m${self.pii.files.secrets.repo.pii.names.installer}[0m
IP of primary interface: [31m\4[0m
These IPs were also found: \4{eth0} \4{eth1} \4{eth2} \4{eth3} \4{eth4} \4{eth5} \4{wlan0}
The Password for all users & root is '[31msetup[0m'.
Install the system remotely by running '[33mswarsel-bootstrap <CONFIGURATION_NAME> <IP_FROM_ABOVE>[0m' on a machine with deployed secrets.
'';
systemPackages = with pkgs; [
curl
gnupg
rsync
ssh-to-age
sops
vim
just
sbctl
lsof
dig
cryptsetup
btrfs-progs
];
};
fileSystems."/boot" = lib.mkIf (!isSdImage) { options = [ "umask=0077" ]; };
home-manager.users = {
root.home = {
inherit stateVersion;
};
swarsel.home = {
inherit stateVersion;
homeDirectory = lib.mkDefault userHome;
sessionVariables.FLAKE = "${userHome}/.dotfiles";
username = "swarsel";
};
};
networking = {
hostName = "drugstore";
networkmanager = {
enable = true;
ensureProfiles.profiles = lib.listToAttrs (
lib.genList (
index:
let
parent = "eth${toString index}";
inherit (self.outputs.globals.${pkgs.stdenv.hostPlatform.system}.networks.home-lan.vlans.home) id;
in
lib.nameValuePair "vlan-home-${parent}" {
connection = {
autoconnect = true;
id = "vlan-home-${parent}";
interface-name = "${parent}.${toString id}";
type = "vlan";
};
ipv4.method = "auto";
ipv6.method = "auto";
vlan = {
inherit id parent;
};
}
) 8
);
};
usePredictableInterfaceNames = false;
wireless.enable = lib.mkForce false;
};
nix = {
package = stablePkgs.nixVersions.nix_2_30;
channel.enable = false;
settings.experimental-features = [
"nix-command"
"flakes"
];
};
security = {
pam.sshAgentAuth.enable = true;
sudo.extraConfig = ''
Defaults env_keep+=SSH_AUTH_SOCK
Defaults lecture = never
'';
};
system.stateVersion = lib.mkForce "23.05";
systemd = {
services.sshd.wantedBy = lib.mkForce [ "multi-user.target" ];
targets = {
hibernate.enable = false;
hybrid-sleep.enable = false;
sleep.enable = false;
suspend.enable = false;
};
};
};
}
4.3.3.2. Policestation (live ISO key generator config, keygen)
This live ISO config provides a secure environment for setting up cryptographic keys. All networking capabilities are turned off and only necessary tools for generating the keys are enabled.
{
config,
lib,
pkgs,
...
}:
{
config = {
users.users.nixos = {
extraGroups = [ "wheel" ];
initialHashedPassword = "";
isNormalUser = true;
};
services = {
getty.autologinUser = "nixos";
pcscd.enable = true;
udev.packages = [ pkgs.yubikey-personalization ];
};
programs = {
gnupg = {
agent = {
enable = true;
enableSSHSupport = true;
};
dirmngr.enable = true;
};
ssh.startAgent = false;
};
boot = {
initrd.network.enable = false;
kernel.sysctl."kernel.unprivileged_bpf_disabled" = 1;
tmp.cleanOnBoot = true;
zfs.forceImportRoot = false;
};
environment = {
interactiveShellInit = ''
unset HISTFILE
export GNUPGHOME="/run/user/$(id -u)/gnupg"
if [ ! -d "$GNUPGHOME" ]; then
install -m=0700 --directory="$GNUPGHOME"
fi
[ ! -f "$GNUPGHOME/gpg.conf" ] && cp /home/nixos/gpg-hardened.conf "$GNUPGHOME/gpg.conf"
[ ! -f "$GNUPGHOME/gpg-agent.conf" ] && cp /home/nixos/gpg-agent.conf "$GNUPGHOME/gpg-agent.conf"
'';
systemPackages = with pkgs; [
paperkey
pgpdump
parted
cryptsetup
yubikey-manager
yubikey-personalization
pcsc-tools
];
};
home-manager.users.nixos = {
services.gpg-agent = {
enable = true;
defaultCacheTtl = 60;
enableBashIntegration = true;
enableSshSupport = true;
maxCacheTtl = 120;
pinentry = {
package = pkgs.pinentry-curses;
program = "pinentry-curses";
};
};
programs.gpg.enable = true;
home = {
inherit (config.system) stateVersion;
file.".gnupg/gpg-hardened.conf".text = ''
personal-cipher-preferences AES256 AES192 AES
personal-digest-preferences SHA512 SHA384 SHA256
personal-compress-preferences ZLIB BZIP2 ZIP Uncompressed
default-preference-list SHA512 SHA384 SHA256 AES256 AES192 AES ZLIB BZIP2 ZIP Uncompressed
cert-digest-algo SHA512
s2k-digest-algo SHA512
s2k-cipher-algo AES256
charset utf-8
no-comments
no-emit-version
no-greeting
keyid-format 0xlong
list-options show-uid-validity
verify-options show-uid-validity
with-fingerprint
require-cross-certification
require-secmem
no-symkey-cache
armor
use-agent
throw-keyids
'';
homeDirectory = "/home/nixos";
keyboard.layout = "us";
username = "nixos";
};
};
networking = {
dhcpcd = {
enable = false;
allowInterfaces = [ ];
};
firewall.enable = true;
hostName = "policestation";
interfaces = { };
networkmanager.enable = lib.mkForce false;
resolvconf.enable = false;
useDHCP = false;
useNetworkd = false;
wireless.enable = false;
};
nix = {
channel.enable = false;
settings.experimental-features = [
"nix-command"
"flakes"
];
};
security.sudo = {
enable = true;
wheelNeedsPassword = false;
};
swapDevices = [ ];
system.stateVersion = lib.mkForce "23.05";
systemd.targets = {
hibernate.enable = false;
hybrid-sleep.enable = false;
sleep.enable = false;
suspend.enable = false;
};
};
}
4.3.3.3. Brick Road (kexec image)
This is a specialized kexec image that I use to have disko available on RAM-limited machines, as the kexec provided directly by NixOS-anywhere does not include it. Note that I had to strip most other stuff from this image, so this is not a good image for general deployment.
{
lib,
pkgs,
options,
modulesPath,
...
}:
{
imports = [
# reduce closure size by removing perl
"${modulesPath}/profiles/perlless.nix"
# FIXME: we still are left with nixos-generate-config due to nixos-install-tools
{ system.forbiddenDependenciesRegexes = lib.mkForce [ ]; }
];
config = {
users = {
# normal users are not allowed with sys-users
# see https://github.com/NixOS/nixpkgs/pull/328926
users.nixos = {
group = "nixos";
isNormalUser = lib.mkForce false;
isSystemUser = true;
shell = "/run/current-system/sw/bin/bash";
};
groups.nixos = { };
};
services = {
# no dependency on x11
dbus.implementation = "broker";
# we prefer root as this is also what we use in nixos-anywhere
getty.autologinUser = lib.mkForce "root";
# included in systemd anyway
userborn.enable = false;
};
# would pull in nano
programs.nano.enable = false;
# we are missing this from base.nix
boot.supportedFilesystems = [
"ext4"
"btrfs"
"xfs"
];
documentation = {
enable = false;
doc.enable = false;
info.enable = false;
man.enable = false;
nixos.enable = false;
};
# prevents strace
environment = {
defaultPackages = lib.mkForce [
pkgs.parted
pkgs.gptfdisk
pkgs.e2fsprogs
];
# Don't install the /lib/ld-linux.so.2 stub. This saves one instance of nixpkgs.
ldso32 = null;
systemPackages = with pkgs; [
cryptsetup.bin
];
};
networking.hostName = "brickroad";
# prevents shipping nixpkgs, unnecessary if system is evaluated externally
nix.registry = lib.mkForce { };
security = {
# introduces x11 dependencies
pam.services.su.forwardXAuth = lib.mkForce false;
polkit.enable = lib.mkForce false;
# we have still run0 from systemd and most of the time we just use root
sudo.enable = false;
};
system = {
# among others, this prevents carrying a stdenv with gcc in the image
extraDependencies = lib.mkForce [ ];
# nixos-option is mainly useful for interactive installations
tools.nixos-option.enable = false;
};
# included in systemd anyway
systemd.sysusers.enable = true;
}
// lib.optionalAttrs (options.hardware ? firmwareCompression) {
hardware.firmwareCompression = "xz";
};
disabledModules = [
# This module adds values to multiple lists (systemPackages, supportedFilesystems)
# which are impossible/unpractical to remove, so we disable the entire module.
"profiles/base.nix"
];
}
4.3.3.4. Vacant House (Test Environment)
4.3.3.4.1. Main configuration
{
self,
config,
lib,
pkgs,
confLib,
globals,
...
}:
{
imports = [
self.modules.generic.meta
self.modules.generic.options
self.modules.generic.globals
self.modules.generic.config-lib
self.modules.generic.pii
self.modules.nixos.nodes
self.modules.nixos.node-roles
self.modules.nixos.nftables
self.modules.nixos.id
self.modules.nixos.impermanence
self.modules.nixos.topology
self.modules.nixos.sops
self.modules.nixos.users
self.modules.nixos.nginx
self.modules.nixos.kanidm
self.modules.nixos.oauth2-proxy
./sandbox.nix
];
options.sandbox = {
tls = {
ca = lib.mkOption {
default = ../../../files/public/certs/ca.crt;
type = lib.types.path;
};
certificate = lib.mkOption {
default = ../../../files/public/certs/wildcard.crt;
type = lib.types.path;
};
keyFile = lib.mkOption {
default = "/mnt/sandbox-tls/wildcard.key";
type = lib.types.str;
};
};
tlsDomains = lib.mkOption {
default = [ ];
type = lib.types.listOf lib.types.str;
};
};
config = {
swarselsystems = {
isLinux = true;
isPublic = true;
nodeRoles = [
"webProxy"
"oauthServer"
];
};
sops = {
age = {
keyFile = "/var/lib/sops-nix/key.txt";
sshKeyPaths = lib.mkForce [ ];
};
secrets.kanidm-oauth2-proxy = {
group = lib.mkForce "kanidm";
mode = lib.mkForce "0440";
owner = lib.mkForce "kanidm";
};
templates.motd = {
content = ''
vacanthouse sandbox
===================
kanidm idm_admin password: ${config.sops.placeholder.kanidm-idm-admin-pw}
set a credential for the sandbox person:
kanidm login -D idm_admin
kanidm person credential create-reset-token sandbox
'';
mode = "0444";
};
};
users.motdFile = config.sops.templates.motd.path;
services = lib.mkMerge [
(confLib.mkKanidmOauth2ProxyAccess { serviceName = "sandbox"; }).services
{
kanidm.provision.groups."sandbox.access".members = [ "sandbox" ];
nginx.virtualHosts = lib.genAttrs config.sandbox.tlsDomains (_: {
sslCertificate = "${config.sandbox.tls.certificate}";
sslCertificateKey = "/run/sandbox-tls/nginx.key";
useACMEHost = lib.mkForce null;
});
}
];
boot.loader.grub.enable = false;
fileSystems."/" = {
device = "/dev/disk/by-label/nixos";
fsType = "ext4";
};
networking = {
firewall.allowedTCPPorts = [ 8300 ];
hosts."127.0.0.1" = config.sandbox.tlsDomains;
};
repo.secretFiles = {
common = lib.mkForce ./secrets/pii.nix;
local = ./secrets/pii-local.nix;
};
sandbox.tlsDomains = [
globals.services.kanidm.domain
globals.services.oauth2-proxy.domain
];
security.pki.certificateFiles = [ config.sandbox.tls.ca ];
system = {
activationScripts = {
sandboxAgeKey.text = ''
install -d -m 700 /var/lib/sops-nix
install -m 600 ${../../../files/public/age/hosts/vacanthouse.key} /var/lib/sops-nix/key.txt
'';
setupSecrets.deps = [ "sandboxAgeKey" ];
};
stateVersion = "24.11";
};
virtualisation.vmVariant.virtualisation = {
cores = 2;
forwardPorts =
map
(port: {
from = "host";
guest.port = port;
host.port = port;
})
[
80
443
8300
];
graphics = false;
memorySize = 4096;
sharedDirectories.sandbox-tls = {
source = "/run/sandbox-tls";
target = "/mnt/sandbox-tls";
};
};
systemd = {
services.sandbox-tls = {
before = [
"kanidm.service"
"nginx.service"
];
requiredBy = [
"kanidm.service"
"nginx.service"
];
script = ''
install -d -m 0755 /run/sandbox-tls /etc/ssl/private
install -m 0400 -o nginx -g nginx ${config.sandbox.tls.keyFile} /run/sandbox-tls/nginx.key
install -m 0600 -o kanidm -g kanidm ${config.sandbox.tls.keyFile} /etc/ssl/private/kanidm.key
'';
serviceConfig = {
RemainAfterExit = true;
Type = "oneshot";
};
unitConfig.RequiresMountsFor = [ config.sandbox.tls.keyFile ];
};
tmpfiles.rules = [
"C+ /etc/ssl/certs/kanidm.crt 0644 kanidm kanidm - ${config.sandbox.tls.certificate}"
"C /root/.bash_history 0600 root root - ${pkgs.writeText "sandbox-seed-history" ''
cat /run/secrets/kanidm-idm-admin-pw
kanidm login -D idm_admin
kanidm person credential create-reset-token sandbox
''}"
];
};
};
}
4.3.3.4.2. Test Sandbox
{
self,
lib,
globals,
...
}:
{
imports = [
self.modules.nixos.homebox
];
config = {
sops.secrets.kanidm-homebox = {
group = lib.mkForce "kanidm";
mode = lib.mkForce "0440";
owner = lib.mkForce "kanidm";
};
services.kanidm.provision.groups."homebox.access".members = [ "sandbox" ];
networking.firewall.allowedTCPPorts = [ 7745 ];
sandbox.tlsDomains = [ globals.services.homebox.domain ];
virtualisation.vmVariant.virtualisation.forwardPorts = [
{
from = "host";
guest.port = 7745;
host.port = 7745;
}
];
systemd.services.homebox = {
after = [
"kanidm.service"
"nginx.service"
];
wants = [ "kanidm.service" ];
};
};
}
4.3.3.4.3. Sandbox secrets and input stubs
{
services.domains = {
homebox = "homebox.swarsel.internal";
kanidm = "kanidm.swarsel.internal";
oauth2-proxy = "oauth.swarsel.internal";
};
}
{
persons.sandbox = {
displayName = "Sandbox User";
mailAddresses = [ "sandbox@swarsel.internal" ];
};
}
{
globals = {
services.alloy.extraConfig.otlpGrpcPort = 4317;
domains.main = "swarsel.internal";
general = {
homeProxy = "shim";
homeWebProxy = "shim";
};
networks.home-lan.vlans.services = {
cidrv4 = "192.168.110.0/24";
cidrv6 = "fd00:5a4d:10::/64";
id = 10;
};
root = {
emergencyHashedPassword = "$6$Hkbhj1DujcKvZP9t$hQEyYT11m/4/UjR6kq8NqINQk3PD5cKTvuyWTz5SstW2IbLDB/rgPs59MrVTbMzEPhimRp90HrxVbDvNG16Ny0";
hashedPassword = "$6$Hkbhj1DujcKvZP9t$hQEyYT11m/4/UjR6kq8NqINQk3PD5cKTvuyWTz5SstW2IbLDB/rgPs59MrVTbMzEPhimRp90HrxVbDvNG16Ny0";
};
};
}
4.4. Modules
4.4.1. Common
These are system-level settings specific to NixOS machines. All settings that are required on all machines should go here.
4.4.1.1. Share configuration between nodes (distributed config, automatically active)
This section of code allows different nixosConfigurations (i.e. hosts) to "send" configuration to each other. That means host A can define in a module some configuration that should then be applied on host B. This is very useful for servers, where the full functionality may be split over multiple hosts.
An example:
Summers (Server: ASUS Z10PA-D8) provides a service and loads a module. In that module I can then also define:
- NGINX config for the internal proxy hintbooth-nginx
- NGINX config for the external proxy Twothreetunnel (OCI)
- DNS records to be published by Stoicclub (OCI)
Note that not all configuration can be sent by default, rather it has to be defined in forwardedOptions below (otherwise we get an infinite recursion error). For options that do not take a submodule as argument, we need to define every last option we set by hand - see for example the services.firezone.gateway options below, where we redefine [ "enable" "name" "apiUrl" "tokenFile" "package" "logLevel" ].
# adapted from https://github.com/oddlama/nix-config/blob/main/modules/distributed-config.nix
{
flake.modules.nixos.nodes =
{
config,
lib,
nodes,
...
}:
let
nodeName = config.node.name;
mkForwardedOption =
path:
lib.mkOption {
default._type = "__distributed_config_empty";
description = ''
Anything specified here will be forwarded to `${lib.concatStringsSep "." path}`
on the given node. Forwarding happens as-is to the raw values,
so validity can only be checked on the receiving node.
'';
type = lib.mkOptionType {
merge =
_loc: defs:
builtins.filter (x: builtins.isAttrs x -> ((x._type or "") != "__distributed_config_empty")) (
map (x: x.value) defs
);
name = "Same type that the receiving option `${lib.concatStringsSep "." path}` normally accepts.";
};
};
splitPath = path: lib.splitString "." path;
expandOptions = basePath: optionNames: map (option: basePath ++ splitPath option) optionNames;
forwardedOptions = [
(splitPath "boot.kernel.sysctl")
(splitPath "networking.nftables.chains.postrouting")
(splitPath "services.kanidm.provision.groups")
(splitPath "services.kanidm.provision.systems.oauth2")
(splitPath "sops.secrets")
(splitPath "topology.self.services")
]
++ expandOptions [ "environment" ] [ "persistence" "etc" ]
++ expandOptions (splitPath "networking.nftables.firewall") [
"zones"
"rules"
]
++ expandOptions (splitPath "services.collabora-online") [
"aliasGroups"
"settings"
]
++ expandOptions (splitPath "services.firezone.gateway") [
"enable"
"name"
"apiUrl"
"tokenFile"
"package"
"logLevel"
]
++ expandOptions (splitPath "services.nginx") [
"upstreams"
"virtualHosts"
"streamConfig"
]
++ expandOptions (splitPath "services.grafana") [
"settings"
"provision.datasources.settings.datasources"
"provision.alerting.rules.settings.groups"
];
attrsForEachOption =
f:
lib.foldl' (
acc: path: lib.recursiveUpdate acc (lib.setAttrByPath path (f path))
) { } forwardedOptions;
in
{
options.nodes = lib.mkOption {
default = { };
description = "Options forwarded to the given node.";
type = lib.types.attrsOf (
lib.types.submodule {
options = attrsForEachOption mkForwardedOption;
}
);
};
config =
let
getConfig =
path: otherNode:
let
cfg = nodes.${otherNode}.config.nodes.${nodeName} or null;
in
lib.optionals (cfg != null) (lib.getAttrFromPath path cfg);
mergeConfigFromOthers = path: lib.mkMerge (lib.concatMap (getConfig path) (lib.attrNames nodes));
in
attrsForEachOption mergeConfigFromOthers;
};
}
4.4.1.2. Global options (automatically active)
Since I am maintaining an infrastructure of moderate size, it is also useful to be able to have some mechanism of shared variables between configurations. For example, I have to reference the domain of my identity management system in some places across the config, which I can reference using globals.services.kanidm.domain.
Do note that the below does not achieve anything on its own - as is, these would only be normal ("local") NixOS options. The real magic, as we have touched on before, happens in Globals, where we then ingest the values here and expose them as a flake output.
{
flake.modules.generic.globals =
{
inputs,
lib,
options,
...
}:
let
inherit (lib)
mkOption
types
;
inherit (inputs) dns;
firewallOptions = {
allowedTCPPortRanges = mkOption {
default = [ ];
description = "Convenience option to open specific TCP port ranges for traffic from another node.";
type = lib.types.listOf (lib.types.attrsOf lib.types.port);
};
allowedTCPPorts = mkOption {
default = [ ];
description = "Convenience option to open specific TCP ports for traffic from the network.";
type = types.listOf types.port;
};
allowedUDPPortRanges = mkOption {
default = [ ];
description = "Convenience option to open specific UDP port ranges for traffic from another node.";
type = lib.types.listOf (lib.types.attrsOf lib.types.port);
};
allowedUDPPorts = mkOption {
default = [ ];
description = "Convenience option to open specific UDP ports for traffic from the network.";
type = types.listOf types.port;
};
};
probeOptions = {
address = mkOption {
description = "host:port";
type = types.str;
};
alertFor = mkOption {
default = null;
description = "How long the probe must fail before alerting.";
type = types.nullOr types.str;
};
network = mkOption {
type = types.str;
};
};
networkOptions = netSubmod: {
cidrv4 = mkOption {
default = null;
description = "The CIDRv4 of this network";
type = types.nullOr types.net.cidrv4;
};
cidrv6 = mkOption {
default = null;
description = "The CIDRv6 of this network";
type = types.nullOr types.net.cidrv6;
};
firewallRuleForAll = mkOption {
default = { };
description = ''
If this is a wireguard network: Allows you to set specific firewall rules for traffic originating from any participant in this
wireguard network. A corresponding rule `<network-name>-to-<local-zone-name>` will be created to easily expose
services to the network.
'';
type = types.submodule {
options = firewallOptions;
};
};
hosts = mkOption {
default = { };
type = types.attrsOf (
types.submodule (hostSubmod: {
options = {
cidrv4 = mkOption {
default =
if netSubmod.config.cidrv4 == null then
null
else
lib.net.cidr.hostCidr hostSubmod.config.id netSubmod.config.cidrv4;
description = "The IPv4 of this host in this network, including CIDR mask";
readOnly = true;
type = types.nullOr types.str; # FIXME: this is not types.net.cidr because it would zero out the host part
};
cidrv6 = mkOption {
default =
if netSubmod.config.cidrv6 == null then
null
else
# if we use the /32 wan address as local address directly, do not use the network address in ipv6
lib.net.cidr.hostCidr (
if hostSubmod.config.id == 0 then 1 else hostSubmod.config.id
) netSubmod.config.cidrv6;
description = "The IPv6 of this host in this network, including CIDR mask";
readOnly = true;
type = types.nullOr types.str; # FIXME: this is not types.net.cidr because it would zero out the host part
};
firewallRuleForNode = mkOption {
default = { };
description = ''
If this is a wireguard network: Allows you to set specific firewall rules just for traffic originating from another network node.
A corresponding rule `<network-name>-node-<node-name>-to-<local-zone-name>` will be created to easily expose
services to that node.
'';
type = types.attrsOf (
types.submodule {
options = firewallOptions;
}
);
};
id = mkOption {
description = "The id of this host in the network";
type = types.int;
};
ipv4 = mkOption {
default =
if netSubmod.config.cidrv4 == null then
null
else
lib.net.cidr.host hostSubmod.config.id netSubmod.config.cidrv4;
description = "The IPv4 of this host in this network";
readOnly = true;
type = types.nullOr types.net.ipv4;
};
ipv6 = mkOption {
default =
if netSubmod.config.cidrv6 == null then
null
else
lib.net.cidr.host hostSubmod.config.id netSubmod.config.cidrv6;
description = "The IPv6 of this host in this network";
readOnly = true;
type = types.nullOr types.net.ipv6;
};
mac = mkOption {
default = null;
description = "The MAC of the interface on this host that belongs to this network.";
type = types.nullOr types.net.mac;
};
};
})
);
};
subnetMask4 = mkOption {
default = lib.swarselsystems.cidrToSubnetMask netSubmod.config.cidrv4;
description = "The dotted decimal form of the subnet mask of this network";
readOnly = true;
type = types.nullOr types.net.ipv4;
};
};
in
{
options = {
globals = mkOption {
default = { };
type = types.submodule {
options = {
services = mkOption {
type = types.attrsOf (
types.submodule (serviceSubmod: {
options = {
baseDomain = mkOption {
default = lib.swarselsystems.getBaseDomain serviceSubmod.config.domain;
readOnly = true;
type = types.str;
};
domain = mkOption {
default = "";
description = "Empty for internal-only services.";
type = types.str;
};
extraConfig = mkOption {
default = { };
type = types.attrsOf types.anything;
};
firezoneTcpPorts = mkOption {
default = [ ];
description = "Ports besides 80 and 443 that Firezone clients may reach.";
type = types.listOf types.port;
};
hasWebInterface = mkOption {
default = true;
type = types.bool;
};
homeServiceAddress = mkOption {
default = null;
type = types.nullOr types.str;
};
isHome = mkOption {
default = false;
type = types.bool;
};
proxyAddress4 = mkOption {
default = null;
type = types.nullOr types.str;
};
proxyAddress6 = mkOption {
default = null;
type = types.nullOr types.str;
};
serviceAddress = mkOption {
default = null;
type = types.nullOr types.str;
};
subDomain = mkOption {
default = lib.swarselsystems.getSubDomain serviceSubmod.config.domain;
readOnly = true;
type = types.str;
};
webPaths = mkOption {
default.${serviceSubmod.config._module.args.name} = "/";
description = "The path that a web interfaces of a service is served on on the domain";
type = types.attrsOf types.str;
};
};
})
);
};
dns = mkOption {
default = { };
type = types.attrsOf (
types.submodule {
options.subdomainRecords = mkOption {
default = { };
type = types.attrsOf dns.lib.types.subzone;
};
}
);
};
domains = {
externalDns = mkOption {
description = "List of external dns nameservers";
type = types.listOf types.str;
};
main = mkOption {
type = types.str;
};
reverse6 = mkOption {
description = "ip6.arpa zone of the delegated IPv6 prefix";
type = types.str;
};
};
general = lib.mkOption {
type = types.submodule {
freeformType = types.unspecified;
};
};
hosts = mkOption {
type = types.attrsOf (
types.submodule {
options = {
defaultGateway4 = mkOption {
type = types.nullOr types.net.ipv4;
};
defaultGateway6 = mkOption {
type = types.nullOr types.net.ipv6;
};
isHome = mkOption {
type = types.bool;
};
wanAddress4 = mkOption {
type = types.nullOr types.net.ipv4;
};
wanAddress6 = mkOption {
type = types.nullOr types.net.ipv6;
};
};
}
);
};
monitoring = mkOption {
default = { };
description = "Blackbox exporter probes.";
type = types.submodule {
options = {
cert = mkOption {
default = { };
type = types.attrsOf (
types.submodule {
options = {
inherit (probeOptions) address network;
serverName = mkOption {
description = "SNI name";
type = types.str;
};
};
}
);
};
dns = mkOption {
default = { };
type = types.attrsOf (
types.submodule {
options = {
inherit (probeOptions) address alertFor network;
queryName = mkOption {
type = types.str;
};
queryType = mkOption {
default = "SOA";
type = types.str;
};
};
}
);
};
hostNetworks = mkOption {
default = { };
description = "Networks each host can probe in; a probe runs on every host whose list contains its `network`.";
type = types.attrsOf (types.listOf types.str);
};
http = mkOption {
default = { };
type = types.attrsOf (
types.submodule {
options = {
inherit (probeOptions) alertFor network;
expectedBodyRegex = mkOption {
default = null;
type = types.nullOr types.str;
};
expectedStatus = mkOption {
default = 200;
type = types.int;
};
failIfBodyMatchesRegex = mkOption {
default = null;
type = types.nullOr types.str;
};
hostHeader = mkOption {
default = null;
type = types.nullOr types.str;
};
url = mkOption {
type = types.str;
};
};
}
);
};
ping = mkOption {
default = { };
type = types.attrsOf (
types.submodule {
options = {
inherit (probeOptions) network;
host = mkOption {
type = types.str;
};
};
}
);
};
tcp = mkOption {
default = { };
type = types.attrsOf (
types.submodule {
options = {
inherit (probeOptions) address alertFor network;
expectedRegex = mkOption {
default = null;
type = types.nullOr types.str;
};
tls = mkOption {
default = false;
type = types.bool;
};
};
}
);
};
systemd = mkOption {
default = { };
type = types.attrsOf (
types.submodule {
options = {
host = mkOption {
type = types.str;
};
oneshot = mkOption {
default = false;
type = types.bool;
};
unit = mkOption {
type = types.str;
};
};
}
);
};
};
};
};
networks = mkOption {
default = { };
type = types.attrsOf (
types.submodule (netSubmod: {
options = networkOptions netSubmod // {
vlans = mkOption {
default = { };
type = types.attrsOf (
types.submodule (vlanNetSubmod: {
options = networkOptions vlanNetSubmod // {
id = mkOption {
type = types.ints.between 1 4094;
};
name = mkOption {
default = vlanNetSubmod.config._module.args.name;
type = types.str;
};
};
})
);
};
};
})
);
};
roaming = mkOption {
default = { };
description = "Hosts that have multiple possible locations";
type = types.attrsOf (
types.submodule (roamingSubmod: {
options = {
address = mkOption {
default = roamingSubmod.config.addresses.${roamingSubmod.config.location};
description = "The address of this host at its current location";
readOnly = true;
type = types.net.ipv4;
};
addresses = mkOption {
description = "Addresses per location";
type = types.attrsOf types.net.ipv4;
};
location = mkOption {
description = "The hosts current location";
type = types.str;
};
};
})
);
};
root = {
emergencyHashedPassword = mkOption {
default = null;
type = types.nullOr types.str;
};
hashedPassword = mkOption {
default = null;
type = types.nullOr types.str;
};
};
user = {
name = mkOption {
type = types.str;
};
work = mkOption {
type = types.str;
};
};
wireguard = mkOption {
default = { };
description = "Keyed by interface name.";
type = types.attrsOf (
types.submodule {
options = {
clients = mkOption {
default = [ ];
type = types.listOf types.str;
};
netConfigPrefix = mkOption {
description = "The network is globals.networks.\"<prefix>-<ifName>\".";
type = types.str;
};
port = mkOption {
default = 52829;
type = types.int;
};
server = mkOption {
type = types.str;
};
};
}
);
};
};
};
};
_globalsDefs = mkOption {
default = options.globals.definitions;
internal = true;
readOnly = true;
type = types.unspecified;
};
};
};
}
4.4.1.3. Configuration options
These are my own configuration options that are used in multiple places throughout the configuration - for which reason I did not put them right where they are used for the first time.
{
flake.modules.generic.options =
{
root,
config,
lib,
...
}:
{
options.swarselsystems = {
bridgedVLANs = lib.mkOption {
default = [ ];
description = "Home VLANs that get a `br-<name>` bridge on this host.";
type = lib.types.listOf lib.types.str;
};
enabledHomeModules = lib.mkOption {
default = [ ];
description = "List of enabled home module names, populated automatically by each module when imported. Used for cross-module checks.";
type = lib.types.listOf lib.types.str;
};
enabledServerModules = lib.mkOption {
default = [ ];
description = "List of enabled server module names, populated automatically by each module when imported. Used for cross-module checks.";
type = lib.types.listOf lib.types.str;
};
flakePath = lib.mkOption {
default = "${config.swarselsystems.homeDir}/.dotfiles";
type = lib.types.str;
};
highResolution = lib.mkOption {
default = "";
type = lib.types.str;
};
homeDir = lib.mkOption {
default = "/home/${config.swarselsystems.mainUser}";
type = lib.types.str;
};
# @ future me: dont put initrdVLAN or localVLANs under server prefix
# home-manager would then try to import all swarselsystems.server.* options
initrdVLAN = lib.mkOption {
default = null;
type = lib.types.nullOr lib.types.str;
};
isBtrfs = lib.mkEnableOption "use btrfs filesystem";
isClient = lib.mkOption {
default = config.swarselsystems.isLaptop;
type = lib.types.bool;
};
isCloud = lib.mkOption {
default = false;
type = lib.types.bool;
};
isCrypted = lib.mkEnableOption "uses full disk encryption";
isFullBuild = lib.mkOption {
default = true;
type = lib.types.bool;
};
isImpermanence = lib.mkEnableOption "use impermanence on this system";
isLaptop = lib.mkEnableOption "laptop host";
isLinux = lib.mkEnableOption "linux host";
isMicroVM = lib.mkOption {
default = false;
type = lib.types.bool;
};
isPublic = lib.mkEnableOption "is a public machine (no secrets)";
isSecureBoot = lib.mkEnableOption "use secure boot on this system";
isServer = lib.mkOption {
default = config.swarselsystems.isCloud;
type = lib.types.bool;
};
isSwap = lib.mkOption {
default = true;
type = lib.types.bool;
};
localVLANs = lib.mkOption {
default = [ ];
type = lib.types.listOf lib.types.str;
};
lowResolution = lib.mkOption {
default = "";
type = lib.types.str;
};
mainUser = lib.mkOption {
default = "swarsel";
type = lib.types.str;
};
microVMPool = lib.mkOption {
default = config.swarselsystems.storagePool;
description = "ZFS pool for the persist and state datasets of the guests.";
type = lib.types.str;
};
nodeRoles = lib.mkOption {
default = [ ];
description = "List of roles this server fulfills in the infrastructure. Will set `globals.general.<itemName>` to the nodeName for each item.";
type = lib.types.listOf lib.types.str;
};
proxyHost = lib.mkOption {
default = config.node.name;
type = lib.types.str;
};
rootDisk = lib.mkOption {
default = "";
type = lib.types.str;
};
sharescreen = lib.mkOption {
default = "";
type = lib.types.str;
};
storagePool = lib.mkOption {
description = "ZFS pool for the storage datasets shared into the guests.";
type = lib.types.str;
};
swapSize = lib.mkOption {
default = "8G";
type = lib.types.str;
};
wallpaper = lib.mkOption {
default = root "files/wallpaper/landscape/lenovowp.png";
type = lib.types.path;
};
wifiMac = lib.mkOption {
default = null;
type = lib.types.nullOr lib.types.str;
};
withMicroVMs = lib.mkEnableOption "enable MicroVMs on this host";
writeGlobalNetworks = lib.mkOption {
default = true;
type = lib.types.bool;
};
};
};
}
4.4.1.4. Topology (automatically active)
This is just some additional configuration that proliferates some Topology node fields automatically from my own options.
{
flake.modules.nixos.topology =
{
inputs,
config,
lib,
...
}:
{
imports = [ inputs.nix-topology.nixosModules.default ];
options.swarselsystems.info = lib.mkOption {
default = "";
type = lib.types.str;
};
config.topology = {
id = config.node.name;
self = {
hardware.info = config.swarselsystems.info;
icon = lib.mkIf config.swarselsystems.isLaptop "devices.laptop";
};
};
};
}
4.4.1.5. General NixOS settings (nix config, stateVersion)
We disable the warnings that trigger when rebuilding with a dirty flake. At this point, I am also disabling channels and pinning the flake registry - the latter lets me use the local version of nixpkgs for commands like nix shell (without it, we will always download the newest version of nixpkgs for these commands).
Also, the system state version is set here. No need to touch it.
A breakdown of the flags being set:
nixpgks.config.allowUnfree: allows packages with an unfree license to be built- nix.settings:
- experimental-features:
- nix-command: Enables the
nixcommand from nix 2.4 - flakes: Enables flakes to be used
- ca-derivations: Enables content-addressed derivations, which stops unnecessary rebuilds
- cgroups: allows the use of cgroups in builds
- pipe-operators: Enables 'piping' instead of the classic currying syntax -
fun argcan be expressed asarg |> fun. Associatively, it is weaker than functions:a |> b |> d c |> e = e ((d c) (b a))
- nix-command: Enables the
- trusted-users: these users have elevated privileges in nix (mostly used to acknowledge binary caches) - root is added per default here
- connect-timeout: normally, nix tries to reach the cache for 300 seconds for each derivation per cache. This setting lets me change that
- bash-prompt-prefix: adds a prefix to shells spawned by
nix develop - [min,max]-free: amounts of space where intermittent GC will be run during builds
- flake registry: URI of the global flake registry (I disable it)
- auto-optimize-store: create hardlinks in the nix store to save space
- warn-dirty: I do not need to see the warning when I have uncommitted changes
- max-jobs: How many build jobs should be run in parallel.
autosets this to the number of CPUs (which is all) - on systems with many cores this can lead to OOM situations. The default is now1, but used to beauto, I set this manually just to be safe in the future. - use-cgroups: Actually run builds within cgroups
- netrc-file: sets the netrc file that is used to authenticate to remote machines (used during e.g. nix build) - this is needed for my attic cache
- experimental-features:
- nix.channel.enable: whether to use channels
- nix.registry: Sets the registry for this flake, which I set to its inputs. This allows me to use e.g.
nixpkgsdirectly innix repl - nix.nixPath: Basically the same as
nix.registry, but for the legacy nix commands
let
nix-version = "2_34";
mkExtraOptions =
config: minimal: if minimal then "" else "!include ${config.sops.secrets.github-api-token.path}\n";
experimentalFeatures = [
"nix-command"
"flakes"
"ca-derivations"
"cgroups"
"pipe-operators"
];
commonScalarSettings = {
auto-optimise-store = true;
connect-timeout = 5;
fallback = true;
max-free = 1000000000;
max-jobs = 1;
min-free = 128000000;
warn-dirty = false;
};
mkCaches =
{
atticPublicKey,
globals,
isPublic,
mainUser,
}:
{
substituters = [
"https://nix-community.cachix.org"
]
++ (if isPublic then [ ] else [ "https://${globals.services.attic.domain}/${mainUser}" ]);
trusted-public-keys = (if isPublic then [ ] else [ atticPublicKey ]) ++ [
"nix-community.cachix.org-1:mB9FSh9qf2dCimDSUo8Zy7bkq5CX+/rkCWyvRCYg3Fs="
];
};
mkCacheSecrets = confLib: globals: config: {
secrets = {
attic-cache-key.rekey.keyPrefix = confLib.static.sharedSecrets.common;
github-api-token = {
mode = "0440";
rekey.keyPrefix = confLib.static.sharedSecrets.common;
};
};
templates.netrc.content = ''
machine ${globals.services.attic.domain}
password ${config.sops.placeholder.attic-cache-key}
'';
};
baseOverlays = outputs: [
outputs.overlays.default
outputs.overlays.pedantix-emacs
outputs.overlays.stables
outputs.overlays.modifications
];
mkAdditionsOverlay =
{
self,
homeConfig,
config,
lib,
}:
final: _:
import "${self}/pkgs/config" {
inherit
self
homeConfig
config
lib
;
pkgs = final;
};
in
{
flake.modules = {
darwin.settings =
{ config, outputs, ... }:
{
nix.settings.experimental-features = "nix-command flakes";
nixpkgs = {
config.allowUnfree = true;
hostPlatform = config.node.arch;
overlays = baseOverlays outputs;
};
system.stateVersion = 4;
};
homeManager.settings =
{
self,
config,
lib,
pkgs,
confLib,
globals,
minimal,
outputs,
type,
...
}:
let
inherit (config.swarselsystems)
flakePath
homeDir
isLinux
isPublic
mainUser
;
isStandaloneLinux = type == "home";
caches = mkCaches {
inherit (confLib.getConfig.repo.secrets.common) atticPublicKey;
inherit globals isPublic mainUser;
};
in
{
config = {
swarselsystems.enabledHomeModules = [ "general" ];
programs.man = {
enable = true;
generateCaches = true;
};
home = {
extraOutputsToInstall = [
"doc"
"info"
"devdoc"
];
homeDirectory = lib.mkDefault homeDir;
keyboard.layout = "us";
packages = lib.mkIf isStandaloneLinux [
(pkgs.symlinkJoin {
buildInputs = [ pkgs.makeWrapper ];
name = "home-manager";
paths = [ pkgs.home-manager ];
postBuild = ''
wrapProgram $out/bin/home-manager \
--append-flags '--flake ${flakePath}#$(hostname)'
'';
})
];
sessionVariables.FLAKE = flakePath;
stateVersion = lib.mkDefault "23.05";
username = lib.mkDefault mainUser;
};
nix = lib.mkIf isStandaloneLinux {
package = lib.mkForce pkgs.nixVersions."nix_${nix-version}";
extraOptions = mkExtraOptions config minimal;
settings = commonScalarSettings // {
bash-prompt = lib.mkIf config.swarselsystems.isClient "$(if [[ $? -gt 0 ]]; then printf \"[31m\"; else printf \"[32m\"; fi)λ [0m";
bash-prompt-prefix = lib.mkIf config.swarselsystems.isClient "[33m$SHLVL:\\w [0m";
experimental-features = experimentalFeatures;
extra-substituters = caches.substituters;
extra-trusted-public-keys = caches.trusted-public-keys;
extra-trusted-substituters = caches.substituters;
netrc-file = lib.mkIf (!minimal) config.sops.templates.netrc.path;
trusted-users = [
"@wheel"
mainUser
];
use-cgroups = lib.mkIf isLinux true;
};
};
nixpkgs = lib.mkIf isStandaloneLinux {
config.allowUnfree = true;
overlays = baseOverlays outputs ++ [
(mkAdditionsOverlay {
inherit self config lib;
homeConfig = config;
})
];
};
targets.genericLinux.enable = lib.mkIf isStandaloneLinux true;
}
// lib.optionalAttrs isStandaloneLinux {
sops = lib.mkIf (!isPublic) (mkCacheSecrets confLib globals config);
};
};
nixos.settings =
{
self,
inputs,
config,
lib,
pkgs,
confLib,
globals,
minimal,
outputs,
withHomeManager,
...
}:
let
inherit (config.swarselsystems) isPublic mainUser;
caches = mkCaches {
inherit (config.repo.secrets.common) atticPublicKey;
inherit globals isPublic mainUser;
};
secretsOwner = lib.mkIf config.users.users.${mainUser}.enable mainUser;
in
{
config = lib.mkMerge [
{
sops = lib.mkIf (!minimal) (
lib.mkMerge [
(mkCacheSecrets confLib globals config)
{
secrets = {
attic-cache-key.owner = secretsOwner;
github-api-token = {
group = "builder";
owner = secretsOwner;
};
};
templates.netrc = {
group = "builder";
owner = secretsOwner;
};
}
]
);
users = {
groups.builder = { };
persistentIds.builder = confLib.mkIds 965;
};
nix = {
package = pkgs.nixVersions."nix_${nix-version}";
extraOptions = mkExtraOptions config minimal;
settings = {
inherit (caches) substituters trusted-public-keys;
experimental-features = experimentalFeatures;
netrc-file = lib.mkIf (!minimal) config.sops.templates.netrc.path;
trusted-substituters = caches.substituters;
trusted-users = [
"@wheel"
(lib.mkIf config.users.users.${mainUser}.enable mainUser)
(lib.mkIf (builtins.elem "ssh-builder" config.swarselsystems.enabledServerModules) "builder")
];
};
};
nixpkgs = {
config = lib.mkIf (!config.swarselsystems.isMicroVM) {
allowUnfree = true;
};
overlays =
baseOverlays outputs
++ lib.optionals withHomeManager [
(mkAdditionsOverlay {
inherit self config lib;
homeConfig = config.home-manager.users.${mainUser} or { };
})
];
};
system.stateVersion = lib.mkDefault "23.05";
}
(lib.mkIf (!minimal) {
services.dbus.implementation = "broker";
environment.etc."nixos/configuration.nix".source = pkgs.writeText "configuration.nix" ''
assert builtins.trace "This location is not used. The config is found in ${config.swarselsystems.flakePath}!" false;
{ }
'';
nix =
let
flakeInputs = lib.filterAttrs (_: lib.isType "flake") inputs;
in
{
channel.enable = false;
gc = {
options = "--delete-older-than 10d";
automatic = true;
dates = "weekly";
};
nixPath = lib.mapAttrsToList (n: _: "${n}=flake:${n}") flakeInputs;
optimise = {
automatic = true;
dates = "weekly";
};
registry = rec {
n = nixpkgs;
nixpkgs.flake = inputs.nixpkgs;
s = swarsel;
swarsel.flake = self;
};
settings = commonScalarSettings // {
bash-prompt = "$(if [[ $? -gt 0 ]]; then printf \"[31m\"; else printf \"[32m\"; fi)λ [0m";
bash-prompt-prefix = "[33m$SHLVL:\\w [0m";
flake-registry = "";
use-cgroups = lib.mkIf config.swarselsystems.isLinux true;
};
};
systemd.services.nix-daemon.environment.TMPDIR = "/var/tmp";
})
];
};
};
}
4.4.1.6. Setup home-manager base
We enable the use of home-manager as a NixOS module. A nice trick here is the extraSpecialArgs = self line (inherit ...). This is useful to refer to the root of the flake (which is otherwise quite hard while maintaining flake purity).
let
mkExtraSpecialArgs =
{
inputs,
configName,
globals,
minimal,
nodes,
outputs,
...
}:
{
inherit (inputs) self nixgl;
inherit
inputs
configName
globals
minimal
nodes
outputs
;
inherit (outputs.swarselsystemsLib) root;
inherit (outputs) lib;
};
in
{
flake.modules = {
darwin.home-manager =
{
self,
config,
lib,
globals,
withHomeManager,
...
}@args:
{
config = lib.mkIf withHomeManager {
home-manager = {
users.${globals.user.work}.imports = [
self.modules.homeManager.profile-base
self.modules.homeManager.settings
{ home.stateVersion = "23.05"; }
];
extraSpecialArgs = mkExtraSpecialArgs args // {
arch = config.node.arch;
nixosConfig = config;
type = "darwin";
};
};
};
};
nixos.home-manager =
{
self,
inputs,
config,
lib,
arch,
minimal,
type,
...
}@args:
let
inherit (config.swarselsystems) isMicroVM isServer mainUser;
homeSwarsel = config.home-manager.users.${mainUser}.swarselsystems or { };
in
{
config = {
sops = {
secrets = lib.mapAttrs (_: v: v // { owner = mainUser; }) (homeSwarsel.homeSopsSecrets or { });
templates = lib.mapAttrs (_: v: v // { owner = mainUser; }) (homeSwarsel.homeSopsTemplates or { });
};
home-manager = lib.mkIf (!isServer && !isMicroVM) {
users.${mainUser}.imports = [
inputs.swarsel-nix.homeModules.default
inputs.glide-nix.homeModules.default
{
imports = [
self.modules.homeManager.profile-base
]
++ lib.optionals minimal [
self.modules.homeManager.profile-minimal
];
home.stateVersion = lib.mkDefault config.system.stateVersion;
node.name = config.node.name;
}
];
backupFileExtension = "hm-bak";
extraSpecialArgs = mkExtraSpecialArgs args // {
inherit arch type;
};
overwriteBackup = true;
useGlobalPkgs = true;
useUserPackages = true;
verbose = true;
};
};
};
};
}
4.4.1.7. User setup, Make users non-mutable
This ensures that all user-configuration happens here in the config file. In case of using a fully setup system, this makes also sure that no further user level modifications can be made using CLI utilities (e.g. usermod etc.). Everything must be defined in the flake.
For that reason, make sure that sops-nix is properly working before finishing the minimal setup, otherwise we might lose user access. The bootstrapping script takes care of this.
{
flake.modules.nixos.users =
{
config,
lib,
confLib,
globals,
minimal,
...
}:
let
mainUserEnabled = config.users.users.${config.swarselsystems.mainUser}.enable;
in
{
config = {
sops.secrets = {
main-user-hashed-pw = lib.mkIf (mainUserEnabled && !config.swarselsystems.isPublic) {
neededForUsers = true;
rekey.keyPrefix = confLib.static.sharedSecrets.common;
};
root-hashed-pw = lib.mkIf (!minimal && !config.swarselsystems.isPublic) {
neededForUsers = true;
rekey.keyPrefix = confLib.static.sharedSecrets.common;
};
};
users = {
users = {
"${config.swarselsystems.mainUser}" = {
enable = lib.mkDefault (
minimal
|| config.swarselsystems.isPublic
|| (config.home-manager.users or { }) ? ${config.swarselsystems.mainUser}
);
autoSubUidGidRange = false;
description = config.repo.secrets.common.fullName or "User";
extraGroups = [
"wheel"
]
++ lib.optionals (!minimal && !config.swarselsystems.isMicroVM) [
"networkmanager"
"input"
"syncthing"
"docker"
"lp"
"audio"
"video"
"vboxusers"
"builder"
"libvirtd"
"scanner"
];
hashedPasswordFile = lib.mkIf (
mainUserEnabled && !minimal && !config.swarselsystems.isPublic
) config.sops.secrets.main-user-hashed-pw.path;
isNormalUser = true;
password = lib.mkIf (minimal || config.swarselsystems.isPublic) "setup";
subGidRanges = [
{
count = 65534;
startGid = 100001;
}
];
subUidRanges = [
{
count = 65534;
startUid = 100001;
}
];
uid = lib.mkIf mainUserEnabled 1000;
};
root = {
hashedPassword = lib.mkIf config.swarselsystems.isPublic globals.root.hashedPassword;
hashedPasswordFile = lib.mkIf (
!minimal && !config.swarselsystems.isPublic
) config.sops.secrets.root-hashed-pw.path;
};
};
mutableUsers = lib.mkIf (!minimal) false;
};
security.pam.services.su.requireWheel = true;
};
};
}
4.4.1.8. Setup login keymap (xserver)
Next, we setup the keymap in case we are not in a graphical session. At this point, I always resort to us/altgr-intl, as it is comfortable to use and I do not write too much German anyway.
{
flake.modules.nixos.xserver.config.services.xserver.xkb = {
layout = "us";
variant = "altgr-intl";
};
}
4.4.1.9. Time, locale settings
Setup timezone and locale. I want to use the US layout, but have the rest adapted to my country and timezone. Also, there is an issue with running Windows/Linux dualboot on the same machine where the hardware clock desyncs between the two OSes. We fix that bug here as well.
{
flake.modules.nixos.time.config = {
i18n = {
defaultLocale = "en_US.UTF-8";
extraLocaleSettings = {
LC_ADDRESS = "de_AT.UTF-8";
LC_IDENTIFICATION = "de_AT.UTF-8";
LC_MEASUREMENT = "de_AT.UTF-8";
LC_MONETARY = "de_AT.UTF-8";
LC_NAME = "de_AT.UTF-8";
LC_NUMERIC = "de_AT.UTF-8";
LC_PAPER = "de_AT.UTF-8";
LC_TELEPHONE = "de_AT.UTF-8";
LC_TIME = "de_AT.UTF-8";
};
};
time = {
timeZone = "Europe/Vienna";
# hardwareClockInLocalTime = true;
};
};
}
4.4.1.10. PII management
This is also exposed to home-manager configurations, in case this ever breaks, I can also go back to importing nixosConfig as an attribute in the input attribute set and call the secrets using nixosConfig.repo.secrets.
Two modes of operation are supported:
- loading in a secret as a plain attribute set
{a = 3;} - loading in a function
{ nodes, ...}: {mac = nodes.xxx.interface.mac;}
Both cases should return the proper values - in the second case the parent set must be passed to the inherit under options.repo.secrets.
In general, there are three types of PII file:
- Per-node secrets: found under the nodes
secretDiraspii.nix.enc(exposed asconfig.repo.secrets.local) - Common secrets: found in
secrets/repo/pii.nix.enc(exposed asconfig.repo.secrets.common)- if those use
globalsas in input argument, it needs to have{ }as an input argument as we cannot pass it to the global evaluator.
- if those use
- Global definitions of networks and domains: found in
secrets/repo/globals.nix.enc(not exposed to nodes, but only loaded in in Globals)- these cannot use
globalsas input argument, as that would cause infinite recursion
- these cannot use
# largely based on https://github.com/oddlama/nix-config/blob/main/modules/secrets.nix
{ self, ... }:
{
flake.modules.generic.pii =
{
inputs,
config,
lib,
dns,
globals,
homeLib,
nodes,
...
}:
let
# If the given expression is a bare set, it will be wrapped in a function,
# so that the imported file can always be applied to the inputs, similar to
# how modules can be functions or sets.
constSet = x: if builtins.isAttrs x then (_: x) else x;
# This "imports" an encrypted .nix.enc file by evaluating the decrypted content.
# Plain .nix files are imported directly.
importEncrypted =
path:
constSet (
if !builtins.pathExists path then
{ }
else if lib.hasSuffix ".enc" (toString path) then
self.swarselsystemsLib.importEncrypted path
else
import path
);
in
{
options.repo = {
secretFiles = lib.mkOption {
default = { };
description = ''
This file manages the origin for this machine's repository-secrets. Anything that is
technically not a secret in the classical sense (i.e. that it has to be protected
after it has been deployed), but something you want to keep secret from the public;
Anything that you wouldn't want people to see on GitHub, but that can live unencrypted
on your own devices. Consider it a more ergonomic nix alternative to using git-crypt.
All of these secrets may (and probably will be) put into the world-readable nix-store
on the build and target hosts. You'll most likely want to store personally identifiable
information here, such as:
- MAC Addreses
- Static IP addresses
- Your full name (when configuring your users)
- Your postal address (when configuring e.g. home-assistant)
- ...
Each path given here must be an sops-encrypted .nix file. For each attribute `<name>`,
the corresponding file will be decrypted, imported and exposed as {option}`repo.secrets.<name>`.
'';
example = lib.literalExpression "{ local = ./pii.nix.enc; }";
type = lib.types.attrsOf lib.types.path;
};
secrets = lib.mkOption {
default = lib.mapAttrs (
_: x:
importEncrypted x {
inherit
inputs
config
lib
dns
globals
homeLib
nodes
;
inherit (inputs.topologyPrivate) topologyPrivate;
}
) config.repo.secretFiles;
description = "Exposes the loaded repo secrets. This option is read-only.";
readOnly = true;
type = lib.types.unspecified;
};
};
config.repo.secretFiles =
let
local = config.node.secretsDir + "/pii.nix.enc";
in
(lib.optionalAttrs (lib.pathExists local) { inherit local; })
// {
common = ../../secrets/repo/pii.nix.enc;
};
};
}
4.4.1.11. PII agent
{ inputs, ... }:
{
flake.modules = {
homeManager.pii-agent =
{
config,
lib,
nixosConfig ? null,
...
}:
{
imports = [ inputs.piix.homeModules.default ];
swarselsystems.enabledHomeModules = [ "pii-agent" ];
services.pii-agent = {
enable = true;
sshKey = lib.mkIf (nixosConfig == null) (lib.mkDefault (lib.head config.sops.age.sshKeyPaths));
};
};
nixos.pii-agent =
{ config, lib, ... }:
{
imports = [ inputs.piix.nixosModules.default ];
services.pii-agent = {
enable = true;
sshKey = lib.mkDefault (lib.head config.sops.age.sshKeyPaths);
};
environment.persistence."/persist".directories = lib.mkIf config.swarselsystems.isImpermanence [
config.services.pii-agent.linkDir
];
};
};
}
4.4.1.12. Meta options (options only)
{
flake.modules.generic.meta =
{ lib, ... }:
{
options.node = {
arch = lib.mkOption {
type = lib.types.str;
};
configDir = lib.mkOption {
default = ./.;
description = "Path to the base directory for this node.";
type = lib.types.path;
};
lockFromBootstrapping = lib.mkOption {
description = "Whether this host should be marked to not be bootstrapped again using swarsel-bootstrap.";
type = lib.types.bool;
};
name = lib.mkOption {
type = lib.types.str;
};
secretsDir = lib.mkOption {
default = ./.;
description = "Path to the secrets directory for this node.";
type = lib.types.path;
};
type = lib.mkOption {
type = lib.types.str;
};
};
};
}
4.4.1.13. Remote building
This defines all remote builds that I want to use on client machines. This includes the nixbuild.net machine as well as my own private builders. I can use these to perform x8664 builds as well as aarch64.
{
flake.modules.nixos.remotebuild =
{
config,
lib,
confLib,
globals,
...
}:
let
inherit (config.swarselsystems) homeDir isClient mainUser;
clientsSecrets = confLib.static.sharedSecrets.clients;
in
{
config = {
sops.secrets = {
builder-key = lib.mkIf isClient {
mode = "0600";
owner = mainUser;
path = "${homeDir}/.ssh/builder";
rekey.keyPrefix = clientsSecrets;
};
nixbuild-net-key = {
mode = "0600";
owner = mainUser;
path = "${homeDir}/.ssh/nixbuild-net";
rekey.keyPrefix = clientsSecrets;
};
};
programs.ssh = {
extraConfig = ''
Host eu.nixbuild.net
ConnectTimeout 5
PubkeyAcceptedKeyTypes ssh-ed25519
ServerAliveInterval 60
IPQoS throughput
IdentityFile ${config.sops.secrets.nixbuild-net-key.path}
''
+ lib.optionalString isClient ''
Host ${globals.roaming.treehouse.address}
ConnectTimeout 2
User ${mainUser}
IdentityFile ${config.sops.secrets.builder-key.path}
Host ${globals.hosts.belchsfactory.wanAddress4}
ConnectTimeout 5
ProxyJump ${globals.hosts.liliputsteps.wanAddress4}
User builder
IdentityFile ${config.sops.secrets.builder-key.path}
Host ${globals.hosts.liliputsteps.wanAddress4}
ConnectTimeout 2
User jump
IdentityFile ${config.sops.secrets.builder-key.path}
'';
knownHosts = lib.mkMerge [
{
nixbuild = {
hostNames = [ "eu.nixbuild.net" ];
publicKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPIQCZc54poJ8vqawd8TraNryQeJnvH1eLpIDgbiqymM";
};
}
(lib.mkIf isClient {
builder1 = {
hostNames = [ globals.roaming.treehouse.address ];
publicKey = config.repo.secrets.common.builder1-pubHostKey;
};
builder2 = {
hostNames = [ globals.hosts.belchsfactory.wanAddress4 ];
publicKey = config.repo.secrets.common.builder2-pubHostKey;
};
jump = {
hostNames = [ globals.hosts.liliputsteps.wanAddress4 ];
publicKey = config.repo.secrets.common.jump-pubHostKey;
};
})
];
};
nix = {
buildMachines = lib.optionals isClient [
{
hostName = globals.roaming.treehouse.address;
maxJobs = 20;
speedFactor = 10;
system = "aarch64-linux";
}
{
hostName = globals.hosts.belchsfactory.wanAddress4;
maxJobs = 4;
protocol = "ssh-ng";
speedFactor = 2;
system = "aarch64-linux";
}
{
hostName = "eu.nixbuild.net";
maxJobs = 100;
speedFactor = 2;
supportedFeatures = [
"benchmark"
"big-parallel"
];
system = "x86_64-linux";
}
];
distributedBuilds = true;
settings.builders-use-substitutes = true;
};
};
};
}
4.4.1.14. Lanzaboote (secure boot)
This dynamically uses systemd boot or Lanzaboote depending on the minimal system state and `config.swarselsystems.isSecureBoot`.
{
flake-file.inputs.lanzaboote = {
inputs = {
nixpkgs.follows = "nixpkgs";
pre-commit.follows = "pre-commit-hooks";
};
url = "github:nix-community/lanzaboote";
};
flake.modules.nixos.lanzaboote =
{
inputs,
config,
lib,
pkgs,
minimal,
...
}:
let
inherit (config.swarselsystems) isImpermanence isSecureBoot;
in
{
imports = [ inputs.lanzaboote.nixosModules.lanzaboote ];
boot = {
lanzaboote = lib.mkIf (!minimal && isSecureBoot) {
enable = true;
configurationLimit = 6;
pkiBundle = "/var/lib/sbctl";
};
loader = {
efi.canTouchEfiVariables = true;
systemd-boot.enable = lib.mkForce (minimal || !isSecureBoot);
};
};
environment = {
persistence."/persist" = lib.mkIf (isImpermanence && isSecureBoot) {
directories = [ { directory = "/var/lib/sbctl"; } ];
};
systemPackages = lib.mkIf isSecureBoot [
pkgs.sbctl
];
};
};
}
4.4.1.15. Disk encryption
The hostkey can be generated with ssh-keygen -t ed25519 -N "" -f /etc/secrets/initrd/ssh_host_ed25519_key.
Use lspci -v | grep -iA8 'network\|ethernet' to supposedly find out which kernel module is needed for networking in initrd. However I prefer a different approach:
Use lspci -nn | grep -i network to find out manufacturer info:
lspci -nn | grep -i 'network\|ethernet'
04:00.0 Network controller [0280]: MEDIATEK Corp. MT7922 802.11ax PCI Express Wireless Network Adapter [14c3:0616]
From the last bracket you then find out the correct kernel module:
lspci -k -d 14c3:0616
04:00.0 Network controller: MEDIATEK Corp. MT7922 802.11ax PCI Express Wireless Network Adapter Subsystem: MEDIATEK Corp. Device e616 Kernel driver in use: mt7921e Kernel modules: mt7921e
A little note about the secrets part:
systemd-initrd provides a lightweight SSH server in form of dropbear - in order to not crash we need to have a hostkey ready in the initrd. I achieve this by generating a hostkey in the build process in case I am doing an initial install (another way - and safer - would be to push that in swarsel-bootstrap I guess) - this results in the hostkey landing in the nix store. However, I only ever spend like 5 minutes in this state before I rebuild to the full system, where this hostkey is no longer used. This is because upon first activation, we will then run another ssh-keygen that will then write to persisted storage. All "unlock" SSH hosts are to be reached over port 2222, and systemctl default will be run immediately upon login, which will guide towards attaining a working system (in normal operation, it will simply ask for the password).
I also take some precautions in how I get networking information during stage 1. For the most part, I just use systemd-networkd (server), however, for hosts in my local network, I take another step to define the network in the kernelParams, to make extra sure I can reach it.
{
flake.modules.nixos.disk-encrypt =
{
self,
config,
lib,
pkgs,
minimal,
...
}:
let
hostKeyPathBase = "/etc/secrets/initrd/ssh_host_ed25519_key";
hostKeyPath =
if config.swarselsystems.isImpermanence then "/persist/${hostKeyPathBase}" else hostKeyPathBase;
# this key is only used for ssh to stage 1 in initial provisioning (in nix store)
generatedHostKey = pkgs.runCommand "initrd-hostkey" { } ''
${pkgs.openssh}/bin/ssh-keygen -t ed25519 -N "" -f $out
'';
in
{
options.swarselsystems = {
initrdSshCommand = lib.mkOption {
default = "/bin/systemctl default";
description = "Command forced on every SSH login to the initrd.";
type = lib.types.str;
};
networkKernelModules = lib.mkOption {
default = [ ];
type = lib.types.listOf lib.types.str;
};
};
config = lib.mkIf config.swarselsystems.isCrypted {
swarselsystems.enabledServerModules = [ "diskEncryption" ];
boot = lib.mkIf (!config.swarselsystems.isClient) {
initrd = {
availableKernelModules = config.swarselsystems.networkKernelModules;
kernelModules = config.swarselsystems.networkKernelModules; # at least summers needs this to actually find the interfaces
network = {
enable = true;
flushBeforeStage2 = true;
ssh = {
enable = true;
authorizedKeys = [
''command="${config.swarselsystems.initrdSshCommand}" ${builtins.readFile "${self}/files/public/ssh/yubikey.pub"}''
''command="${config.swarselsystems.initrdSshCommand}" ${builtins.readFile "${self}/files/public/ssh/magicant.pub"}''
];
hostKeys = [ "/tmp${hostKeyPathBase}" ]; # use a tmp file otherwise persist mount will be unhappy
port = 2222; # avoid hostkey changed nag
};
};
secrets."/tmp${hostKeyPathBase}" =
if minimal then (lib.mkForce "${generatedHostKey}") else (lib.mkForce hostKeyPath); # need to mkForce this or it behaves stateful
systemd.initrdBin = with pkgs; [
cryptsetup
];
};
};
environment.persistence."/persist" =
lib.mkIf (config.swarselsystems.isImpermanence && (config.swarselsystems.isServer || minimal))
{
files = [ hostKeyPathBase ];
};
# as soon as we hit a stable system, we will use a persisted key
# @future me: dont mkIf this to minimal, we need to create this as soon as possible
system.activationScripts.ensureInitrdHostkey = {
deps = [
"users"
]
++ lib.optional config.swarselsystems.isImpermanence "createPersistentStorageDirs";
text = ''
[[ -e ${hostKeyPath} ]] || ${pkgs.openssh}/bin/ssh-keygen -t ed25519 -N "" -f ${hostKeyPath}
'';
};
};
};
}
4.4.1.16. DNS
{
flake-file.inputs.dns = {
inputs = {
flake-utils.follows = "flake-utils";
nixpkgs.follows = "nixpkgs";
};
url = "github:kirelagin/dns.nix";
};
flake.modules.nixos.dns =
{ inputs, ... }:
{
_module.args.dns = inputs.dns;
};
}
4.4.1.17. Config Library (confLib)
{
flake.modules.generic.config-lib =
{
self,
inputs,
config,
lib,
globals,
minimal,
outputs,
nixosConfig ? null,
...
}:
let
domainDefault = service: config.repo.secrets.common.services.domains.${service};
proxyDefault = config.swarselsystems.proxyHost;
isWgProxyClient =
globals.wireguard ? wgProxy && builtins.elem config.node.name globals.wireguard.wgProxy.clients;
addressDefault =
if config.swarselsystems.proxyHost != config.node.name then
if isWgProxyClient then
globals.networks."${globals.wireguard.wgProxy.netConfigPrefix}-wgProxy".hosts.${config.node.name}.ipv4
else
globals.networks.${config.swarselsystems.server.netConfigName}.hosts.${config.node.name}.ipv4
else
"localhost";
in
{
_module.args.confLib = rec {
gen =
{
name,
address ? addressDefault,
dir ? null,
domain ? (domainDefault name),
group ? user,
port ? null,
proxy ? proxyDefault,
user ? name,
}:
rec {
baseDomain = lib.swarselsystems.getBaseDomain domain;
proxyAddress4 = globals.hosts.${proxy}.wanAddress4 or null;
proxyAddress6 = globals.hosts.${proxy}.wanAddress6 or null;
serviceAddress = address;
serviceDir = dir;
serviceDomain = domain;
serviceGroup = group;
serviceName = name;
serviceNode = config.node.name;
servicePort = port;
serviceProxy = proxy;
serviceUser = user;
specificServiceName = "${name}-${config.node.name}";
subDomain = lib.swarselsystems.getSubDomain domain;
topologyContainerName = "${serviceNode}-${config.virtualisation.oci-containers.backend}-${name}";
};
genNginx =
{
serviceAddress,
serviceDomain,
serviceName,
servicePort,
extraConfig ? "",
extraConfigLoc ? "",
maxBody ? (-1),
maxBodyUnit ? "",
noSslVerify ? false,
oauth2 ? false,
oauth2Groups ? [ ],
protocol ? "http",
proxyWebsockets ? false,
}:
{
upstreams = {
${serviceName}.servers = {
"${serviceAddress}:${builtins.toString servicePort}" = { };
};
};
virtualHosts = {
"${serviceDomain}" = {
acmeRoot = null;
extraConfig =
lib.optionalString noSslVerify ''
proxy_ssl_verify off;
''
+ extraConfig;
forceSSL = true;
locations."/" = {
extraConfig =
lib.optionalString (maxBody != (-1)) ''
client_max_body_size ${builtins.toString maxBody}${maxBodyUnit};
''
+ extraConfigLoc;
proxyPass = "${protocol}://${serviceName}";
proxyWebsockets = lib.mkIf proxyWebsockets true;
};
oauth2 = {
enable = lib.mkIf oauth2 true;
allowedGroups = lib.mkIf (oauth2Groups != [ ]) oauth2Groups;
};
useACMEHost = globals.domains.main;
};
};
};
getConfig = if nixosConfig == null then config else nixosConfig;
kanidmSecrets = "kanidm/${config.node.name}/";
mkAlloyPushUrl =
{
domain,
host,
path,
port,
}:
let
inherit (globals.general) monitoringServer;
in
if host == monitoringServer then
"http://127.0.0.1:${toString port}${path}"
else if globals.hosts.${host}.isHome then
"http://${
globals.networks.home-lan.vlans.services.hosts.${monitoringServer}.ipv4
}:${toString port}${path}"
else
"https://${domain}${path}";
mkAlloyScrape =
{
name,
port,
scrapeSettings ? { },
}:
lib.mkIf config.services.alloy.enable (
lib.mkAfter ''
prometheus.scrape "${name}" {
targets = [{"__address__" = "127.0.0.1:${toString port}"}]
forward_to = [prometheus.remote_write.mimir.receiver]
job_name = "${name}"
${lib.concatStrings (lib.mapAttrsToList (key: value: " ${key} = \"${value}\"\n") scrapeSettings)}}
''
);
mkDeviceMac =
id:
let
hex = lib.fixedWidthString 6 "0" (lib.toLower (lib.toHexString id));
in
lib.concatMapStringsSep ":" (i: builtins.substring i 2 hex) [
0
2
4
];
mkDnsMonitoring =
{
address,
queryName,
serviceName,
alertFor ? null,
queryType ? null,
}:
{
${serviceName} = {
inherit address queryName;
network = "local-${config.node.name}";
}
// lib.optionalAttrs (alertFor != null) { inherit alertFor; }
// lib.optionalAttrs (queryType != null) { inherit queryType; };
};
mkDnsRecord =
{
proxyAddress4,
proxyAddress6,
serviceName,
}:
let
svc = globals.services.${serviceName};
in
{
${svc.baseDomain}.subdomainRecords.${svc.subDomain} =
inputs.dns.lib.combinators.host proxyAddress4 proxyAddress6;
};
mkDualFirewallRules =
{
forHomeProxy ? true,
forWebProxy ? true,
tcpPorts ? [ ],
udpPortRanges ? [ ],
udpPorts ? [ ],
}:
let
rule = {
allowedTCPPorts = lib.mkIf (tcpPorts != [ ]) tcpPorts;
allowedUDPPortRanges = lib.mkIf (udpPortRanges != [ ]) udpPortRanges;
allowedUDPPorts = lib.mkIf (udpPorts != [ ]) udpPorts;
};
in
{
${static.homeProxyIf}.hosts = lib.mkIf (forHomeProxy && static.isHome) {
${config.node.name}.firewallRuleForNode.${static.homeWebProxy} = rule;
};
${static.webProxyIf}.hosts = lib.mkIf (forWebProxy && static.isProxied) {
${config.node.name}.firewallRuleForNode.${static.webProxy} = rule;
};
};
mkGrafanaAlertRule =
{
expr,
summary,
title,
uid,
datasourceUid ? "mimir",
forDuration ? "5m",
noDataState ? "NoData",
op ? "lt",
queryType ? null,
severity ? "critical",
threshold ? 1,
}:
{
inherit noDataState title uid;
annotations.summary = summary;
condition = "C";
data = [
{
inherit datasourceUid;
model = {
inherit expr;
instant = true;
range = false;
refId = "A";
}
// lib.optionalAttrs (queryType != null) { inherit queryType; };
refId = "A";
relativeTimeRange = {
from = 600;
to = 0;
};
}
{
datasourceUid = "__expr__";
model = {
conditions = [
{
evaluator = {
params = [ threshold ];
type = op;
};
}
];
expression = "A";
refId = "C";
type = "threshold";
};
refId = "C";
}
];
execErrState = "Alerting";
for = forDuration;
labels.severity = severity;
};
mkHttpMonitoring =
{
serviceName,
servicePort,
alertFor ? null,
expectedBodyRegex ? null,
expectedStatus ? null,
failIfBodyMatchesRegex ? null,
hostHeader ? null,
path ? "/",
scheme ? "http",
}:
{
${serviceName} = {
network = "local-${config.node.name}";
url = "${scheme}://127.0.0.1:${toString servicePort}${path}";
}
// lib.optionalAttrs (expectedBodyRegex != null) { inherit expectedBodyRegex; }
// lib.optionalAttrs (expectedStatus != null) { inherit expectedStatus; }
// lib.optionalAttrs (hostHeader != null) { inherit hostHeader; }
// lib.optionalAttrs (failIfBodyMatchesRegex != null) { inherit failIfBodyMatchesRegex; }
// lib.optionalAttrs (alertFor != null) { inherit alertFor; };
};
mkIds = id: {
gid = id;
uid = id;
};
mkKanidmOauth2ProxyAccess =
{
serviceName,
proxyGroup ? "${serviceName}_access",
}:
{
services.kanidm.provision = {
groups."${serviceName}.access" = { };
systems.oauth2.oauth2-proxy = {
claimMaps.groups.valuesByGroup."${serviceName}.access" = [ proxyGroup ];
scopeMaps."${serviceName}.access" = [
"openid"
"email"
"profile"
];
};
};
};
mkKanidmOidcSystem =
{
originUrl,
serviceDomain,
serviceName,
displayName ? lib.swarselsystems.toCapitalized serviceName,
extraGroups ? [ ],
}:
{
sops.secrets."kanidm-${serviceName}" = {
group = "kanidm";
mode = "0440";
owner = "kanidm";
rekey = {
generator.script = "alnum";
keyPrefix = kanidmSecrets;
};
};
services.kanidm.provision = {
groups = lib.genAttrs ([ "${serviceName}.access" ] ++ extraGroups) (_: { });
systems.oauth2.${serviceName} = {
inherit displayName originUrl;
basicSecretFile = config.sops.secrets."kanidm-${serviceName}".path;
originLanding = "https://${serviceDomain}/";
preferShortUsername = true;
scopeMaps."${serviceName}.access" = [
"openid"
"email"
"profile"
];
};
};
};
mkMicrovm =
if config.swarselsystems.withMicroVMs then
(
guestName:
{
eternorPaths ? [ ],
withZfs ? false,
}:
{
${guestName} = {
autostart = true;
backend = "microvm";
extraSpecialArgs = {
inherit (inputs.self) nodes;
inherit (inputs.self.pkgs.${config.node.arch}) lib;
inherit (inputs.self.swarselsystemsLib) root;
inherit inputs minimal outputs;
inherit (inputs) self;
globals = inputs.self.globals.${config.node.arch};
microVMParent = config.node.name;
withHomeManager = false;
};
microvm = {
baseMac = config.repo.secrets.local.networking.networks.lan.mac;
interfaces.vlan-services.mac = lib.mkForce "02:${
lib.substring 3 5 config.guests.${guestName}.microvm.baseMac
}:${
mkDeviceMac globals.networks.home-lan.vlans.services.hosts."${config.node.name}-${guestName}".id
}";
system = config.node.arch;
};
modules = [
(config.node.configDir + /guests/${guestName}/default.nix)
{
fileSystems = {
"/persist".neededForBoot = true;
}
// lib.optionalAttrs withZfs {
"/state".neededForBoot = true;
};
networking.nftables.firewall.zones.untrusted.interfaces = lib.mkIf (
lib.length config.guests.${guestName}.networking.links == 1
) config.guests.${guestName}.networking.links;
node = {
configDir = config.node.configDir + /guests/${guestName};
secretsDir = config.node.configDir + /secrets/${guestName};
};
}
self.modules.nixos.microvm-guest
self.modules.nixos.systemd-networkd-base
];
zfs = lib.mkIf withZfs (
{
# other stuff that should only reside on zfs, not backed up remotely
"/persist" = {
dataset = "guests/${guestName}/persist";
pool = config.swarselsystems.microVMPool;
};
# stateful config usually bind-mounted to /var/lib/ that should be backed up remotely
"/state" = {
dataset = "guests/${guestName}/state";
pool = config.swarselsystems.microVMPool;
};
}
// lib.optionalAttrs (eternorPaths != [ ]) (
lib.listToAttrs (
map
# data that is pulled in externally by services, some of which is backed up externally
(
eternorPath:
lib.nameValuePair "/storage/${eternorPath}" {
dataset = "Eternor/${eternorPath}";
pool = config.swarselsystems.storagePool;
}
)
eternorPaths
)
)
);
};
}
)
else
(_: _: { });
mkOtelEnvironment = serviceName: {
OTEL_EXPORTER_OTLP_ENDPOINT = "http://127.0.0.1:${toString globals.services.alloy.extraConfig.otlpGrpcPort}";
OTEL_EXPORTER_OTLP_PROTOCOL = "grpc";
OTEL_SERVICE_NAME = "${serviceName}-${config.node.name}";
OTEL_TRACES_EXPORTER = "otlp";
};
mkServiceGlobal =
{
homeServiceAddress,
isHome,
proxyAddress4,
proxyAddress6,
serviceAddress,
serviceDomain,
serviceName,
extra ? { },
}:
{
${serviceName} = {
inherit
isHome
proxyAddress4
proxyAddress6
serviceAddress
;
domain = serviceDomain;
homeServiceAddress = lib.mkIf isHome homeServiceAddress;
}
// extra;
};
mkShikaneOutput =
monitor: overrides:
{
inherit (monitor) position;
enable = true;
match =
if monitor ? vendor then
[
"m=${monitor.model}"
"s=${monitor.serial}"
"v=${monitor.vendor}"
]
else
monitor.output;
mode = monitor.mode + lib.optionalString (monitor ? refresh) "@${monitor.refresh}Hz";
scale = builtins.fromJSON monitor.scale * 1.0;
}
// lib.optionalAttrs (monitor ? transform) { inherit (monitor) transform; }
// overrides;
mkSystemdMonitoring =
{
serviceName,
unit,
oneshot ? false,
}:
{
${serviceName} = {
inherit oneshot unit;
host = config.node.name;
};
};
mkTcpMonitoring =
{
serviceName,
servicePort,
address ? "127.0.0.1",
alertFor ? null,
expectedRegex ? null,
tls ? false,
}:
{
${serviceName} = {
inherit tls;
address = "${address}:${toString servicePort}";
network = "local-${config.node.name}";
}
// lib.optionalAttrs (alertFor != null) { inherit alertFor; }
// lib.optionalAttrs (expectedRegex != null) { inherit expectedRegex; };
};
mkTrayApplet =
{
description,
execStart,
extraService ? { },
}:
{
Install.WantedBy = [ "tray.target" ];
Service = {
ExecStart = execStart;
}
// extraService;
Unit = {
After = [
"graphical-session.target"
"tray.target"
];
Description = description;
PartOf = [ "tray.target" ];
Requires = [ "graphical-session.target" ];
};
};
overrideTarget = target: {
Install.WantedBy = lib.mkForce [ target ];
Unit = {
After = lib.mkForce [ target ];
PartOf = lib.mkForce [ target ];
};
};
static = rec {
inherit (globals.hosts.${config.node.name}) isHome;
inherit (globals.general)
dnsServer
homeDnsServer
homeProxy
homeWebProxy
idmServer
monitoringServer
ntpServer
oauthServer
routerServer
webProxy
;
dmarcMailAddress = "dmarc@${globals.domains.main}";
homeProxyIf = "home-wgHome";
homeServiceAddress =
lib.optionalString inWgHome
globals.networks."${globals.wireguard.wgHome.netConfigPrefix}-wgHome".hosts.${config.node.name}.ipv4;
inWgHome = builtins.elem config.node.name wgHomeMembers;
inWgProxy = builtins.elem config.node.name wgProxyMembers;
isProxied = config.node.name != webProxy;
nginxAccessRules =
let
wgHomeNet = globals.networks."${globals.wireguard.wgHome.netConfigPrefix}-wgHome";
in
''
allow ${globals.networks.home-lan.vlans.home.cidrv4};
allow ${globals.networks.home-lan.vlans.home.cidrv6};
allow ${globals.networks.home-lan.vlans.services.hosts.${homeProxy}.ipv4};
allow ${globals.networks.home-lan.vlans.services.hosts.${homeProxy}.ipv6};
allow ${wgHomeNet.cidrv4};
allow ${wgHomeNet.cidrv6};
deny all;
'';
notificationMail = rec {
address = "${localPart}@${domain}";
domain = globals.domains.main;
host = globals.services.mailserver.domain;
keyPrefix = sharedSecrets.mail;
localPart = "notification";
};
probeKinds = [
"http"
"ping"
"cert"
"tcp"
"dns"
];
scannerDropRules = ''
location ~* "\.(php|aspx?|env|jsp|cgi|bak|sql|old)(\?|$|/)" {
access_log off;
return 444;
}
location ~* "(^|/)(\.git/|\.env|\.DS_Store|wp-admin|wp-login|wp-content|wp-includes|xmlrpc\.php|phpmy?admin|cgi-bin)" {
access_log off;
return 444;
}
'';
sharedSecrets = {
clients = "general/clients/";
common = "common/";
gatus = "general/gatus/";
invidiousCompanion = "general/invidious-companion/";
mail = "mail/";
parsedmarc = "general/parsedmarc/";
sandbox = "general/sandbox/";
work = "work/";
};
webProxyIf = "${webProxy}-wgProxy";
wgHomeMembers = lib.optionals (globals.wireguard ? wgHome) (
globals.wireguard.wgHome.clients ++ [ globals.wireguard.wgHome.server ]
);
wgProxyAccessRules =
let
wgProxyNet = globals.networks."${globals.wireguard.wgProxy.netConfigPrefix}-wgProxy";
extraAllows = lib.concatMapStrings (
host:
let
cfg = globals.hosts.${host};
in
lib.optionalString (cfg.wanAddress4 != null) "allow ${cfg.wanAddress4};\n"
+ lib.optionalString (cfg.wanAddress6 != null) "allow ${cfg.wanAddress6};\n"
) (lib.filter (h: !(builtins.elem h wgProxyMembers)) (lib.attrNames globals.hosts));
in
''
allow ${wgProxyNet.cidrv4};
allow ${wgProxyNet.cidrv6};
''
+ extraAllows
+ ''
deny all;
'';
wgProxyMembers = lib.optionals (globals.wireguard ? wgProxy) (
globals.wireguard.wgProxy.clients ++ [ globals.wireguard.wgProxy.server ]
);
};
};
};
}
4.4.1.18. BTRFS
This literally just adds the btrfs parameters.
{
flake.modules.nixos.btrfs =
{
config,
lib,
pkgs,
...
}:
let
inherit (config.swarselsystems) isBtrfs isLaptop;
in
{
config = {
swarselsystems.enabledServerModules = [ "btrfs" ];
services.btrfs.autoScrub = lib.mkIf isBtrfs {
enable = true;
interval = "monthly";
};
boot.supportedFilesystems = lib.mkIf isBtrfs [ "btrfs" ];
systemd = lib.mkIf isBtrfs {
services.btrfs-balance = {
serviceConfig = {
ExecStart = "${lib.getExe' pkgs.btrfs-progs "btrfs"} balance start -dusage=50 -musage=30 /";
IOSchedulingClass = "idle";
Nice = 19;
Type = "oneshot";
};
unitConfig.ConditionACPower = lib.mkIf isLaptop true;
};
timers.btrfs-balance = {
timerConfig = {
OnCalendar = "Sun 04:00";
Persistent = true;
};
wantedBy = [ "timers.target" ];
};
};
};
};
}
4.4.1.19. Boot
Here I set some general boot options, mostly enabling an emergency shell and some extra tools that would normally not be available in stage 1. Also I reduce the bootloaders default timeout because I do not really need that anymore ever since I have stopped to use specializations.
{
flake.modules.nixos.boot =
{
lib,
pkgs,
globals,
...
}:
{
config = {
boot = {
bcache.enable = false;
initrd.systemd = {
users.root.shell = "${pkgs.bashInteractive}/bin/bash";
emergencyAccess =
if globals.root.emergencyHashedPassword == null then
false
else
globals.root.emergencyHashedPassword;
extraBin = {
cryptsetup = "${pkgs.cryptsetup}/bin/cryptsetup";
ip = "${pkgs.iproute2}/bin/ip";
ping = "${pkgs.iputils}/bin/ping";
};
storePaths = [ "${pkgs.bashInteractive}/bin/bash" ];
};
kernelParams = [ "log_buf_len=16M" ];
loader.timeout = lib.mkDefault 2;
swraid.enable = false;
tmp.useTmpfs = true;
};
console.earlySetup = true;
};
};
}
4.4.1.20. ssh
Here I am forcing startWhenNeeded to false so that the value will not be set to true in containers = this would be a problem because it would delay ssh host key generation.
{
flake.modules = {
homeManager.ssh =
{
config,
lib,
options,
confLib,
nixosConfig ? null,
...
}:
{
options.swarselsystems.sshHosts = lib.mkOption {
default = null;
description = "Hosts to configure from the personal ssh host list; null for all.";
type = lib.types.nullOr (lib.types.listOf lib.types.str);
};
config = {
swarselsystems.enabledHomeModules = [ "ssh" ];
programs.ssh = {
enable = true;
enableDefaultConfig = false;
extraConfig = ''
SetEnv TERM=xterm-256color
ServerAliveInterval 20
'';
includes = [ "~/.ssh/extra/*" ];
settings = {
"*" = {
addKeysToAgent = "no";
compression = false;
controlMaster = "no";
controlPath = "~/.ssh/master-%r@%n:%p";
controlPersist = "no";
forwardAgent = false;
hashKnownHosts = false;
serverAliveCountMax = 3;
serverAliveInterval = 0;
userKnownHostsFile = "~/.ssh/known_hosts";
};
}
// (
let
inherit (confLib.getConfig.repo.secrets.common.ssh) hosts;
in
if config.swarselsystems.sshHosts == null then
hosts
else
lib.getAttrs config.swarselsystems.sshHosts hosts
);
};
}
// lib.optionalAttrs (nixosConfig == null && options ? sops) {
sops.secrets = lib.mkIf (!config.swarselsystems.isPublic) {
builder-key = {
mode = "0600";
path = "${config.home.homeDirectory}/.ssh/builder";
rekey.keyPrefix = confLib.static.sharedSecrets.clients;
};
};
};
};
nixos.ssh =
{
root,
config,
lib,
confLib,
withHomeManager,
...
}:
let
keyFiles = [
(root "files/public/ssh/yubikey.pub")
(root "files/public/ssh/magicant.pub")
];
in
{
config = {
swarselsystems.enabledServerModules = [ "ssh" ];
users = {
users = {
"${config.swarselsystems.mainUser}".openssh.authorizedKeys.keyFiles =
lib.mkIf withHomeManager keyFiles;
root.openssh.authorizedKeys.keyFiles = keyFiles;
};
persistentIds.sshd = confLib.mkIds 979;
};
services.openssh = {
enable = true;
hostKeys = [
{
path = "/etc/ssh/ssh_host_ed25519_key";
type = "ed25519";
}
];
settings = {
AllowUsers = [
"root"
]
++
lib.optional config.users.users.${config.swarselsystems.mainUser}.enable
config.swarselsystems.mainUser;
KbdInteractiveAuthentication = false;
PasswordAuthentication = false;
PermitRootLogin = "prohibit-password";
};
startWhenNeeded = lib.mkForce false;
};
security.sudo.extraConfig = ''
Defaults env_keep+=SSH_AUTH_SOCK
'';
};
};
};
}
4.4.1.21. sops
I use sops-nix to handle secrets that I want to have available on my machines at all times. For some reason validateSopsFiles needs to be turned off, probably because my age keys are not real age keys but just the host ssh keys being read in by ssh-go-age. The default sopsFile is the one that is available to all systems - if the secret in question is not in that file, we need to override sopsFile in the respective secret.
Do note that we have to account for impermanent file systems here, otherwise system activation will fail because the secret files cannot be found.
{
inputs,
config,
lib,
...
}:
{
flake-file.inputs = {
sops = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:Mic92/sops-nix";
};
sops-rekey = {
inputs = {
nixpkgs.follows = "nixpkgs";
sops-nix.follows = "sops";
};
url = "github:Swarsel/sops-rekey";
};
};
flake.modules = {
generic.sops-rekey =
{
self,
inputs,
config,
lib,
...
}:
{
imports = [ inputs.sops-rekey.nixosModules.default ];
sops = {
defaultSopsFile = self + /secrets/root.yaml;
rekey = {
generators.laravel-key =
{ pkgs, ... }:
''
printf 'base64:%s' "$(${pkgs.openssl}/bin/openssl rand -base64 32)"
'';
hostPubkey =
let
pubFile = self + "/files/public/age/hosts/${config.node.name}.pub";
in
lib.mkIf (builtins.pathExists pubFile) pubFile;
keyPrefix = "hosts/${config.node.name}/";
rekeyAllSecrets = true;
storageDir = self + "/secrets/rekeyed";
};
};
};
homeManager.sops =
{
self,
inputs,
config,
lib,
nixosConfig ? null,
...
}:
{
imports = [
inputs.sops.homeManagerModules.sops
self.modules.generic.sops-rekey
];
swarselsystems.enabledHomeModules = [ "sops" ];
sops = lib.mkIf (nixosConfig == null) {
age.sshKeyPaths = [
"${lib.optionalString config.swarselsystems.isImpermanence "/persist"}${config.swarselsystems.homeDir}/.ssh/sops"
];
secrets = lib.mkIf (!config.swarselsystems.isPublic) config.swarselsystems.homeSopsSecrets;
templates = lib.mkIf (!config.swarselsystems.isPublic) config.swarselsystems.homeSopsTemplates;
};
};
nixos.sops =
{
self,
inputs,
config,
lib,
...
}:
{
imports = [
inputs.sops.nixosModules.sops
self.modules.generic.sops-rekey
];
sops.age.sshKeyPaths = [
"${lib.optionalString config.swarselsystems.isImpermanence "/persist"}/etc/ssh/ssh_host_ed25519_key"
];
};
};
imports = [ inputs.sops-rekey.flakeModule ];
perSystem =
{ config, pkgs, ... }:
{
checks.sops-rekey =
pkgs.runCommand "sops-rekey-check" { nativeBuildInputs = [ config.packages.sops-rekey ]; }
''
cd ${inputs.self}
sops-rekey check
touch $out
'';
};
sops-rekey = {
masterRecipients.pgp = [ "4BE7925262289B476DBBC17B76FD3810215AE097" ];
nodes =
config.flake.nixosConfigurations
// config.flake.guestConfigurations
// lib.mapAttrs (
_: home: home.extendModules { modules = [ { assertions = lib.mkForce [ ]; } ]; }
) config.flake.homeConfigurations;
};
}
4.4.1.22. Impermanence
This is where the impermanence magic happens. When this is enabled, the root directory is rolled back to a blanket state on each reboot.
Normally, doing that also resets the lecture that happens on the first use of sudo, so we disable that at this point. Also, here we can set files to be persisted. Do note that you should still pay attention to files that need sudo access, as these need to be copied manually.
{
flake-file.inputs.impermanence = {
inputs = {
home-manager.follows = "home-manager";
nixpkgs.follows = "nixpkgs";
};
url = "github:nix-community/impermanence";
};
flake.modules.nixos.impermanence =
{
inputs,
config,
lib,
utils,
...
}:
let
rootDevice = config.fileSystems."/".device;
rootDeviceUnit = "${utils.escapeSystemdPath rootDevice}.device";
inherit (config.swarselsystems) isBtrfs isImpermanence;
in
{
imports = [ inputs.impermanence.nixosModules.impermanence ];
boot = {
# This script does the actual wipe of the system
# So if it doesn't run, the btrfs system effectively acts like a normal system
# Taken from https://github.com/NotAShelf/nyx/blob/2a8273ed3f11a4b4ca027a68405d9eb35eba567b/modules/core/common/system/impermanence/default.nix
initrd.systemd = lib.mkIf (isImpermanence && isBtrfs) {
services.rollback = {
# make sure it's done after encryption
# i.e. LUKS/TPM process
after = [ rootDeviceUnit ];
# mount the root fs before clearing
before = [ "sysroot.mount" ];
description = "Rollback BTRFS root subvolume to a pristine state";
requires = [ rootDeviceUnit ];
script = ''
mkdir -p /mnt
# We first mount the btrfs root to /mnt
# so we can manipulate btrfs subvolumes.
mount -o ${
lib.concatStringsSep "," (
[ "subvolid=5" ] ++ lib.optional (lib.elem "degraded" config.fileSystems."/".options) "degraded"
)
} -t btrfs ${rootDevice} /mnt
btrfs subvolume list -o /mnt/root
# While we're tempted to just delete /root and create
# a new snapshot from /root-blank, /root is already
# populated at this point with a number of subvolumes,
# which makes `btrfs subvolume delete` fail.
# So, we remove them first.
#
# /root contains subvolumes:
# - /root/var/lib/portables
# - /root/var/lib/machines
btrfs subvolume list -o /mnt/root |
cut -f9 -d' ' |
while read subvolume; do
echo "deleting /$subvolume subvolume..."
btrfs subvolume delete "/mnt/$subvolume"
done &&
echo "deleting /root subvolume..." &&
btrfs subvolume delete /mnt/root
echo "restoring blank /root subvolume..."
btrfs subvolume snapshot /mnt/root-blank /mnt/root
# Once we're done rolling back to a blank snapshot,
# we can unmount /mnt and continue on the boot process.
umount /mnt
'';
serviceConfig.Type = "oneshot";
unitConfig.DefaultDependencies = "no";
wantedBy = [ "initrd.target" ];
};
};
tmp.useTmpfs = lib.mkIf (!isImpermanence) true;
};
environment.persistence."/persist" = lib.mkIf isImpermanence {
directories = [
"/root/.dotfiles"
"/etc/nix"
"/etc/NetworkManager/system-connections"
"/var/lib/nixos"
"/var/tmp"
# "/etc/secureboot"
];
files = [
"/etc/ssh/ssh_host_ed25519_key"
"/etc/ssh/ssh_host_ed25519_key.pub"
"/etc/machine-id"
];
hideMounts = true;
};
security.sudo.extraConfig = lib.mkIf isImpermanence ''
# rollback results in sudo lectures after each reboot
Defaults lecture = never
'';
systemd.tmpfiles.settings."10-impermanence-private" = lib.mkIf isImpermanence {
"/var/lib/private".d.mode = "0700";
};
};
}
4.4.1.23. Disk layout (single root)
{
flake.modules.nixos.disk-single-root =
{
config,
lib,
pkgs,
...
}:
let
inherit (config.swarselsystems)
isCloud
isCrypted
isImpermanence
isSwap
rootDisk
swapSize
;
mountOptions = subvol: [
"subvol=${subvol}"
"compress=zstd"
"noatime"
];
btrfs = device: {
extraArgs = [
"-L"
"nixos"
"-f"
];
postCreateHook = lib.mkIf isImpermanence ''
MNTPOINT=$(mktemp -d)
mount "${device}" "$MNTPOINT" -o subvolid=5
trap 'umount $MNTPOINT; rm -rf $MNTPOINT' EXIT
btrfs subvolume snapshot -r $MNTPOINT/root $MNTPOINT/root-blank
'';
subvolumes = {
"/home" = lib.mkIf isImpermanence {
mountOptions = mountOptions "home";
mountpoint = "/home";
};
"/log" = lib.mkIf isImpermanence {
mountOptions = mountOptions "log";
mountpoint = "/var/log";
};
"/nix" = {
mountOptions = mountOptions "nix";
mountpoint = "/nix";
};
"/persist" = lib.mkIf isImpermanence {
mountOptions = mountOptions "persist";
mountpoint = "/persist";
};
"/root" = {
mountOptions = mountOptions "root";
mountpoint = "/";
};
"/swap" = lib.mkIf isSwap {
mountpoint = "/.swapvol";
swap.swapfile.size = swapSize;
};
};
type = "btrfs";
};
in
{
disko = {
devices.disk.disk0 = {
content = {
partitions = {
ESP = {
content = {
format = "vfat";
mountOptions = [ "defaults" ];
mountpoint = "/boot";
type = "filesystem";
};
name = "ESP";
priority = 1;
size = "512M";
type = "EF00";
};
luks = lib.mkIf isCrypted {
content = {
content = btrfs "/dev/mapper/cryptroot";
name = "cryptroot";
passwordFile = "/tmp/disko-password";
settings = {
allowDiscards = true;
crypttabExtraOpts = [
"fido2-device=auto"
"token-timeout=10"
];
};
type = "luks";
};
size = "100%";
};
root = lib.mkIf (!isCrypted) {
content = btrfs "/dev/disk/by-label/nixos";
size = "100%";
};
};
type = "gpt";
};
device = rootDisk;
type = "disk";
};
imageBuilder.extraDependencies = lib.mkIf (isCloud && isCrypted) [ pkgs.kmod ];
};
fileSystems = {
"/home".neededForBoot = lib.mkIf isImpermanence true;
"/persist".neededForBoot = lib.mkIf isImpermanence true;
};
};
}
4.4.1.24. Disk layout (mirrored root)
This module sets up disks for hosts that use a mirrored root. (#TODO: generalize the module)
If a disk dies, do either:
swarsel-degradedif the system is still runningssh -p 2222 <host> degradedinto the initrdboth set according EFI variables for the next boot and then reboot the system.
{
flake.modules.nixos.disk-mirrored-root =
{
config,
lib,
pkgs,
utils,
...
}:
let
label = "nixos";
rootLuks = "cryptroot";
mirrorLuks = "cryptroot-mirror";
initrdSshCommand = pkgs.writeShellApplication {
name = "initrd-ssh-command";
text = ''
if [ "''${SSH_ORIGINAL_COMMAND:-}" = degraded ]; then
exec ${lib.getExe pkgs.swarsel-degraded}
fi
exec /bin/systemctl default
'';
};
degradedFlag = "/run/root-mirror-degraded";
efiVariable = "/sys/firmware/efi/efivars/${pkgs.swarsel-degraded.efiVariable}";
mkDisk =
{
content,
cryptName,
device,
espMountpoint,
}:
{
inherit device;
content = {
partitions = {
ESP = {
content = {
format = "vfat";
mountOptions = [
"defaults"
"nofail"
];
mountpoint = espMountpoint;
type = "filesystem";
};
name = "ESP";
priority = 1;
size = "512M";
type = "EF00";
};
luks = {
content = {
inherit content;
name = cryptName;
passwordFile = "/tmp/disko-password";
settings = {
allowDiscards = true;
crypttabExtraOpts = [
"fido2-device=auto"
"token-timeout=10"
"nofail"
"x-systemd.device-timeout=30s"
];
};
type = "luks";
};
size = "100%";
};
};
type = "gpt";
};
type = "disk";
};
mkSubvolume = name: mountpoint: {
inherit mountpoint;
mountOptions = [
"subvol=${name}"
"compress=zstd"
"noatime"
"degraded"
];
};
subvolumes = {
"/home" = mkSubvolume "home" "/home";
"/log" = mkSubvolume "log" "/var/log";
"/nix" = mkSubvolume "nix" "/nix";
"/persist" = mkSubvolume "persist" "/persist";
"/root" = mkSubvolume "root" "/";
};
in
{
options.swarselsystems.rootMirrorDisk = lib.mkOption {
type = lib.types.str;
};
config = {
swarselsystems.initrdSshCommand = lib.getExe initrdSshCommand;
boot = {
initrd = {
services.udev.rules = ''TEST=="${degradedFlag}", SUBSYSTEM=="block", ENV{ID_FS_TYPE}=="btrfs", ENV{ID_FS_LABEL}=="${label}", ENV{SYSTEMD_READY}="1"'';
systemd = {
services = {
root-mirror-degraded = {
before = [ "cryptsetup-pre.target" ];
script = ''
${lib.getExe' pkgs.e2fsprogs "chattr"} -i ${efiVariable}
rm ${efiVariable}
touch ${degradedFlag}
'';
serviceConfig.Type = "oneshot";
unitConfig = {
ConditionPathExists = efiVariable;
DefaultDependencies = "no";
};
wantedBy = [ "initrd.target" ];
wants = [ "cryptsetup-pre.target" ];
};
root-mirror-scan = {
after = map (name: "systemd-cryptsetup@${utils.escapeSystemdPath name}.service") [
rootLuks
mirrorLuks
];
before = [
"rollback.service"
"sysroot.mount"
];
script = ''
udevadm settle
btrfs device scan
'';
serviceConfig.Type = "oneshot";
unitConfig = {
ConditionPathExists = degradedFlag;
DefaultDependencies = "no";
};
wantedBy = [ "initrd.target" ];
};
};
storePaths = [
initrdSshCommand
(lib.getExe pkgs.swarsel-degraded)
(lib.getExe' pkgs.e2fsprogs "chattr")
];
};
};
lanzaboote.extraEfiSysMountPoints = [ "/boot-mirror" ];
};
disko.devices.disk = {
disk0 = mkDisk {
content = null;
cryptName = rootLuks;
device = config.swarselsystems.rootDisk;
espMountpoint = "/boot";
};
disk1 = mkDisk {
content = {
inherit subvolumes;
extraArgs = [
"-L"
label
"-f"
"-d"
"raid1"
"-m"
"raid1"
"/dev/mapper/${rootLuks}"
];
postCreateHook = ''
MNTPOINT=$(mktemp -d)
mount "/dev/mapper/${mirrorLuks}" "$MNTPOINT" -o subvolid=5
trap 'umount $MNTPOINT; rm -rf $MNTPOINT' EXIT
btrfs subvolume snapshot -r $MNTPOINT/root $MNTPOINT/root-blank
'';
type = "btrfs";
};
cryptName = mirrorLuks;
device = config.swarselsystems.rootMirrorDisk;
espMountpoint = "/boot-mirror";
};
};
environment.systemPackages = [ pkgs.swarsel-degraded ];
fileSystems = lib.mkMerge [
(lib.genAttrs (lib.mapAttrsToList (_: subvolume: subvolume.mountpoint) subvolumes) (_: {
device = lib.mkForce "/dev/disk/by-label/${label}";
}))
{
"/home".neededForBoot = true;
"/persist".neededForBoot = true;
}
];
};
};
}
4.4.1.25. nftables (firewall)
This is the main declarative nftables configuration that I run on all servers. It basically just makes sure that the rules remain in place even when nftables stops and that the networking.allowed*Port[...] options work on the untrusted zone.
{
flake-file.inputs.nixos-nftables-firewall.url = "github:thelegy/nixos-nftables-firewall";
flake.modules.nixos = {
nftables =
{ inputs, ... }:
{
imports = [ inputs.nixos-nftables-firewall.nixosModules.default ];
};
nftables-rules =
{
config,
lib,
globals,
...
}:
let
inherit (globals.general) jumphost;
restrictSsh = config.swarselsystems.isCloud && config.node.name != jumphost;
sshSources = family: [
globals.hosts.${jumphost}."wanAddress${family}"
globals.networks.home-wan."cidrv${family}"
];
in
{
config = {
swarselsystems.enabledServerModules = [ "nftables" ];
services.openssh.openFirewall = lib.mkIf restrictSsh false;
networking.nftables = {
firewall = {
enable = true;
localZoneName = "local";
rules = {
icmp-and-igmp = {
after = [
"ct"
"ssh"
];
extraLines = [
"meta l4proto ipv6-icmp accept"
"meta l4proto icmp accept"
"ip protocol igmp accept"
];
from = "all";
to = [ "local" ];
};
ssh = lib.mkIf restrictSsh {
allowedTCPPorts = config.services.openssh.ports;
from = [
"trusted-ssh"
]
++ lib.attrNames (
lib.filterAttrs (
name: zone: zone.parent == null && !zone.localZone && name != "untrusted"
) config.networking.nftables.firewall.zones
);
to = [ "local" ];
};
untrusted-to-local = {
inherit (config.networking.firewall)
allowedTCPPortRanges
allowedTCPPorts
allowedUDPPortRanges
allowedUDPPorts
;
from = [ "untrusted" ];
ignoreEmptyRule = true;
to = [ "local" ];
};
};
snippets = {
nnf-common.enable = false;
nnf-conntrack.enable = true;
nnf-dhcpv6.enable = true;
nnf-drop.enable = true;
nnf-loopback.enable = true;
nnf-ssh.enable = !restrictSsh;
};
zones.trusted-ssh = lib.mkIf restrictSsh {
ipv4Addresses = sshSources "4";
ipv6Addresses = sshSources "6";
parent = lib.mkIf (config.networking.nftables.firewall.zones ? untrusted) "untrusted";
};
};
stopRuleset = lib.mkDefault ''
table inet filter {
chain input {
type filter hook input priority filter; policy drop;
ct state invalid drop
ct state {established, related} accept
iifname lo accept
meta l4proto ipv6-icmp accept
meta l4proto icmp accept
ip protocol igmp accept
tcp dport ${toString (lib.head config.services.openssh.ports)} accept
}
chain forward {
type filter hook forward priority filter; policy drop;
}
chain output {
type filter hook output priority filter; policy accept;
}
}
'';
};
};
key = "swarsel/nftables-rules";
};
};
}
4.4.1.26. Persistent user/group IDs
When using MicroVMs, I opted to use ZFS with it, and mount datasets into the MicroVMs. That however means that we need to make sure that userids stay consistent between MicroVM reboots. This could be done by persisting /var/lib/nixos, but even then it would not be guaranteed that all UIDs/GIDs match up with the hypervising host, which would not be a big problem, but I like to keep it consistent anyway.
With this, evaluation will fail if there are any users/groups that are not declaratively managed.
{
flake.modules.nixos.id =
{
config,
lib,
confLib,
...
}:
let
inherit (lib)
concatLists
filterAttrs
flip
mapAttrsToList
mkDefault
mkIf
mkOption
types
;
cfg = config.users.persistentIds;
in
{
options.users = {
users = mkOption {
type = types.attrsOf (
types.submodule (
{ name, ... }:
{
config.uid =
let
persistentUid = cfg.${name}.uid or null;
in
mkIf (persistentUid != null) (mkDefault persistentUid);
}
)
);
};
groups = mkOption {
type = types.attrsOf (
types.submodule (
{ name, ... }:
{
config.gid =
let
persistentGid = cfg.${name}.gid or null;
in
mkIf (persistentGid != null) (mkDefault persistentGid);
}
)
);
};
persistentIds = mkOption {
default = { };
description = ''
Maps a user or group name to its expected uid/gid values. If a user/group is
used on the system without specifying a uid/gid, this module will assign the
corresponding ids defined here, or show an error if the definition is missing.
'';
type = types.attrsOf (
types.submodule {
options = {
gid = mkOption {
default = null;
description = "The gid to assign if it is missing in `users.groups.<name>`.";
type = types.nullOr types.int;
};
uid = mkOption {
default = null;
description = "The uid to assign if it is missing in `users.users.<name>`.";
type = types.nullOr types.int;
};
};
}
);
};
};
config = {
users.persistentIds = {
dhcpcd = confLib.mkIds 952;
nscd = confLib.mkIds 972;
polkituser = confLib.mkIds 973;
resolvconf = confLib.mkIds 951;
systemd-coredump = confLib.mkIds 998;
systemd-oom = confLib.mkIds 997;
uinput = confLib.mkIds 944;
};
assertions =
concatLists (
flip mapAttrsToList (filterAttrs (_: user: user.enable) config.users.users) (
name: user: [
{
assertion = user.uid != null;
message = "non-persistent uid detected for '${name}', please assign one via `users.persistentIds`";
}
{
assertion = !user.autoSubUidGidRange;
message = "non-persistent subUids/subGids detected for: ${name}";
}
]
)
)
++ flip mapAttrsToList config.users.groups (
name: group: {
assertion = group.gid != null;
message = "non-persistent gid detected for '${name}', please assign one via `users.persistentIds`";
}
);
};
};
}
4.4.1.27. Network scanner (SANE)
Used by scanservjs to make my printer available to SANE
{
flake.modules.nixos.network-scanner =
{ pkgs, globals, ... }:
{
environment.etc."sane.d/airscan.conf".text = ''
[devices]
"Dell C2665dnf" = http://${globals.networks.home-lan.vlans.devices.hosts.dell-C2665dnf-F49D60.ipv4}/ws, wsd
'';
hardware.sane = {
enable = true;
extraBackends = [ pkgs.sane-airscan ];
};
};
}
4.4.2. Client
4.4.2.1. Mirror home-manager shared options (automatically active)
{
flake.modules.homeManager.sharedoptions =
{
config,
lib,
nixosConfig ? null,
...
}:
{
options.swarselsystems = {
homeSopsSecrets = lib.mkOption {
default = { };
type = lib.types.attrsOf (lib.types.attrsOf lib.types.anything);
};
homeSopsTemplates = lib.mkOption {
default = { };
type = lib.types.lazyAttrsOf (lib.types.lazyAttrsOf lib.types.anything);
};
monitors = lib.mkOption {
default = { };
type = lib.types.attrsOf (lib.types.attrsOf lib.types.str);
};
};
config.swarselsystems = lib.mapAttrs (_: lib.mkDefault) (
builtins.intersectAttrs config.swarselsystems (nixosConfig.swarselsystems or { })
);
};
}
4.4.2.2. nixGL
This integrates nixGL into home-manager. NixGL provides OpenGL and Vulkan APIs to nix installed utilities. This is needed for graphical applications on non-NixOS systems.
to get the info for the secondary GPU, use `lspci -nn | grep VGA` It can be set to either:
- a number, selecting the n-th non-default GPU
- a PCI bus id in the form
pci-XXX_YY_ZZ_U - a PCI id in the form
vendor_id:device_id
{
flake.modules.homeManager.nixgl =
{
inputs,
config,
lib,
pkgs,
nixosConfig ? null,
...
}:
{
options.swarselsystems = {
isSecondaryGpu = lib.mkEnableOption "device has a secondary GPU";
secondaryGpuCard = lib.mkOption {
default = "";
type = lib.types.str;
};
};
config = {
swarselsystems.enabledHomeModules = [ "nixgl" ];
targets.genericLinux.nixGL = lib.mkIf (nixosConfig == null) (
{
defaultWrapper = "mesa";
installScripts = [
"mesa"
"mesaPrime"
];
packages = import "${inputs.nixgl}/default.nix" {
inherit pkgs;
enable32bits = pkgs.stdenv.hostPlatform.isx86_64;
enableIntelX86Extensions = pkgs.stdenv.hostPlatform.isx86_64;
};
vulkan.enable = false;
}
// lib.optionalAttrs config.swarselsystems.isSecondaryGpu {
offloadWrapper = "mesaPrime";
prime = {
card = config.swarselsystems.secondaryGpuCard;
installScript = "mesa";
};
}
);
};
};
}
4.4.2.3. Self-defined Packages
This is just a separate container for derivations defined in Packages. This is a good idea so that I do not lose track of package names I have defined myself, as this was once a problem in the past already.
{
flake.modules.homeManager.custom-packages =
{
config,
lib,
pkgs,
...
}:
{
config = {
swarselsystems.enabledHomeModules = [ "ownpackages" ];
home.packages =
with pkgs;
lib.mkIf (!config.swarselsystems.isPublic) [
pass-fuzzel
swarsel-bootstrap
swarsel-deploy
swarsel-instantiate
swarsel-git-remotes
hunkle
swarsel-gens
swarsel-project
swarsel-switch
swarsel-sync-org
follow-nix
];
};
};
}
4.4.2.4. Theme (stylix)
These section allows home-manager to allow theme settings, and handles some other appearance-related settings like cursor styles. Interestingly, system icons (adwaita) still need to be setup on system-level, and will break if defined here.
This section has been notably empty ever since switching to stylix. Only Emacs is not allowed to be styled by it, because it becomes more ugly compared to my handcrafted setup.
theme is defined in [BROKEN LINK: h:2e9b84d7-cb18-4e74-83f8-65ada11a8911].
let
settings =
pkgs:
let
proportional = {
# package = (pkgs.nerdfonts.override { fonts = [ "FiraMono" "FiraCode"]; });
# package = pkgs.cantarell-fonts;
# package = pkgs.montserrat;
# name = "Cantarell";
package = pkgs.iosevka-bin.override { variant = "Aile"; };
name = "Iosevka Aile";
# name = "FiraCode Nerd Font Propo";
# name = "Montserrat";
};
in
{
base16Scheme = {
base00 = "1d252c";
base01 = "171d23";
base02 = "206a86";
base03 = "003a66";
base04 = "5ec4ff";
base05 = "a0b3c5";
base06 = "7ed4ff";
base07 = "8ef4ff";
base08 = "d95468";
base09 = "ffa880";
base0A = "6ed4ff";
base0B = "8bd49c";
base0C = "008b94";
base0D = "5ec4ff";
base0E = "c06ece";
base0F = "3c0044";
};
cursor = {
package = pkgs.banana-cursor;
# package = pkgs.capitaine-cursors;
name = "Banana";
# name = "capitaine-cursors";
size = 16;
};
fonts = {
emoji = {
package = pkgs.noto-fonts-color-emoji;
name = "Noto Color Emoji";
};
monospace = {
package = pkgs.nerd-fonts.fira-code; # has overrides
name = "FiraCode Nerd Font";
};
sansSerif = proportional;
serif = proportional;
sizes = {
applications = 11;
terminal = 10;
};
};
opacity.popups = 0.5;
polarity = "dark";
};
in
{
flake-file.inputs.stylix = {
inputs = {
flake-parts.follows = "flake-parts";
nixpkgs.follows = "nixpkgs";
nur.follows = "nur";
systems.follows = "systems";
};
url = "github:danth/stylix";
};
flake.modules = {
homeManager.stylix =
{
inputs,
lib,
arch,
type,
...
}:
{
imports = lib.optionals (inputs ? stylix) (
lib.optionals (type != "nixos") [ inputs.stylix.homeModules.stylix ]
++ [
(
{
config,
lib,
pkgs,
nixosConfig ? null,
...
}:
{
swarselsystems.enabledHomeModules = [ "stylix" ];
gtk.gtk4.theme = lib.mkForce config.gtk.theme;
home.pointerCursor.enable = true;
stylix = {
targets = {
emacs.enable = false;
rofi.enable = false;
spicetify.enable = arch != "aarch64-linux";
wayprompt.enable = false; # removed by home-manager
};
}
// lib.optionalAttrs (nixosConfig == null) (
lib.recursiveUpdate {
enable = true;
} (settings pkgs)
);
}
)
]
);
};
nixos.stylix = { inputs, lib, ... }: {
imports = lib.optionals (inputs ? stylix) [
inputs.stylix.nixosModules.stylix
(
{
config,
lib,
pkgs,
...
}:
{
stylix = lib.recursiveUpdate {
enable = true;
image = config.swarselsystems.wallpaper;
targets.grub.enable = false; # the styling makes grub more ugly
} (settings pkgs);
}
)
];
};
};
}
4.4.2.5. Desktop Entries, MIME types (xdg)
Some programs lack a dmenu launcher - I define them myself here.
{
flake.modules.homeManager.desktop.config = {
swarselsystems.enabledHomeModules = [ "desktop" ];
xdg = {
configFile."mimeapps.list".force = true;
mimeApps = {
enable = true;
associations.added = {
"application/epub+zip" = [ "calibre-ebook-viewer.desktop" ];
"application/x-zerosize" = [ "emacsclient.desktop" ];
};
defaultApplications = {
"application/epub+zip" = [ "calibre-ebook-viewer.desktop" ];
"application/metalink+xml" = [ "emacsclient.desktop" ];
"application/msword" = [ "writer.desktop" ];
"application/pdf" = [ "org.gnome.Evince.desktop" ];
"application/sql" = [ "emacsclient.desktop" ];
"application/vnd.ms-excel" = [ "calc.desktop" ];
"application/vnd.ms-powerpoint" = [ "impress.desktop" ];
"application/x-extension-htm" = [ "glide.desktop" ];
"application/x-extension-html" = [ "glide.desktop" ];
"application/x-extension-shtml" = [ "glide.desktop" ];
"application/x-extension-xht" = [ "glide.desktop" ];
"application/x-extension-xhtml" = [ "glide.desktop" ];
"application/xhtml+xml" = [ "glide.desktop" ];
"audio/flac" = [ "mpv.desktop" ];
"audio/mp3" = [ "mpv.desktop" ];
"audio/ogg" = [ "mpv.desktop" ];
"audio/wav" = [ "mpv.desktop" ];
"image/gif" = [ "imv.desktop" ];
"image/jpeg" = [ "imv.desktop" ];
"image/png" = [ "imv.desktop" ];
"image/svg" = [ "imv.desktop" ];
"image/vnd.adobe.photoshop" = [ "gimp.desktop" ];
"image/vnd.dxf" = [ "org.inkscape.Inkscape.desktop" ];
"image/webp" = [ "glide.desktop" ];
"text/csv" = [ "emacsclient.desktop" ];
"text/html" = [ "glide.desktop" ];
"text/plain" = [ "emacsclient.desktop" ];
"video/3gp" = [ "umpv.desktop" ];
"video/flv" = [ "umpv.desktop" ];
"video/mkv" = [ "umpv.desktop" ];
"video/mp4" = [ "umpv.desktop" ];
"x-scheme-handler/chrome" = [ "glide.desktop" ];
"x-scheme-handler/firezone-fd0020211111" = [ "firezone-client-gui-deep-link.desktop" ];
"x-scheme-handler/http" = [ "glide.desktop" ];
"x-scheme-handler/https" = [ "glide.desktop" ];
};
};
};
xdg.desktopEntries = {
anki = {
categories = [ "Application" ];
exec = "anki";
genericName = "Anki";
name = "Anki Flashcards";
terminal = false;
};
cura = {
categories = [ "Application" ];
exec = "cura";
genericName = "Cura";
name = "Ultimaker Cura";
terminal = false;
};
element = {
categories = [ "Application" ];
exec = "element-desktop -enable-features=UseOzonePlatform -ozone-platform=wayland --disable-gpu-driver-bug-workarounds";
genericName = "Element";
name = "Element Matrix Client";
terminal = false;
};
emacsclient-newframe = {
categories = [
"Development"
"TextEditor"
];
exec = "emacsclient -r %u";
genericName = "Emacs (Client, New Frame)";
icon = "emacs";
name = "Emacs (Client, New Frame)";
terminal = false;
};
rustdesk-vbc = {
categories = [ "Application" ];
exec = "rustdesk-vbc";
genericName = "rustdesk-vbc";
name = "Rustdesk VBC";
terminal = false;
};
teamsNoGpu = {
categories = [ "Application" ];
exec = "teams-for-linux --performance.disableGpu=true --tray.enabled=true";
genericName = "Teams (no GPU)";
name = "Microsoft Teams (no GPU)";
terminal = false;
};
};
};
}
4.4.2.6. nix-index
nix-index provides a way to find out which packages are provided by which derivations. By default it also comes with a replacement for command-not-found.sh, however, the implementation is based on a channel based setup. I like consistency, so I replace the command with one that provides a flakes-based output. This also uses the nix-index-with-full-db from the nix-index-database input thanks to its overlay.
{ lib, ... }:
{
flake-file.inputs.nix-index-database = lib.mkDefault {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:nix-community/nix-index-database";
};
flake.modules.homeManager.nix-index = { inputs, lib, ... }: {
imports = lib.optionals (inputs ? nix-index-database) [
inputs.nix-index-database.homeModules.nix-index
({ pkgs, ... }: {
swarselsystems.enabledHomeModules = [ "nix-index" ];
programs = {
nix-index = {
enable = true;
package = pkgs.runCommandLocal "nix-index" { } ''
mkdir -p $out/etc/profile.d
cat > $out/etc/profile.d/command-not-found.sh <<'EOF'
# Adapted from https://github.com/bennofs/nix-index/blob/master/command-not-found.sh
command_not_found_handle() {
if [ -n "''${MC_SID-}" ] || ! [ -t 1 ]; then
>&2 echo "$1: command not found"
return 127
fi
echo -n "searching nix-index..."
ATTRS=$(@nix-locate@ --minimal --no-group --type x --type s --whole-name --at-root "/bin/$1")
case $(echo -n "$ATTRS" | grep -c "^") in
0)
>&2 echo -ne "$(@tput@ el1)\r"
>&2 echo "$1: command not found"
;;
*)
>&2 echo -ne "$(@tput@ el1)\r"
>&2 echo "The program ‘$(@tput@ setaf 4)$1$(@tput@ sgr0)’ is currently not installed."
>&2 echo "It is provided by the following derivation(s):"
while read -r ATTR; do
ATTR=''${ATTR%.out}
>&2 echo " $(@tput@ setaf 12)nixpkgs#$(@tput@ setaf 4)$ATTR$(@tput@ sgr0)"
done <<< "$ATTRS"
;;
esac
return 127
}
command_not_found_handler() {
command_not_found_handle "$@"
return $?
}
EOF
substitute $out/etc/profile.d/command-not-found.sh \
$out/etc/profile.d/command-not-found.sh \
--replace-fail @nix-locate@ ${pkgs.nix-index}/bin/nix-locate \
--replace-fail @tput@ ${pkgs.ncurses}/bin/tput
'';
};
nix-index-database.comma.enable = true;
};
})
];
};
}
4.4.2.7. nix-your-shell
{
flake.modules.homeManager.nix-your-shell.config = {
swarselsystems.enabledHomeModules = [ "nix-your-shell" ];
programs.nix-your-shell = {
enable = true;
enableZshIntegration = true;
};
};
}
4.4.2.8. password-store
Enables password store with the pass-otp extension which allows me to store and generate one-time-passwords.
{
flake.modules.homeManager.password-store =
{
config,
lib,
pkgs,
...
}:
{
config = {
swarselsystems.enabledHomeModules = [ "passwordstore" ];
programs.password-store = {
enable = true;
package = pkgs.pass.withExtensions (exts: [ exts.pass-otp ]);
settings.PASSWORD_STORE_DIR = "${config.home.homeDirectory}/.local/share/password-store";
};
home.activation.setupPasswordStore = lib.hm.dag.entryAfter [ "writeBoundary" ] ''
storeDir="${config.programs.password-store.settings.PASSWORD_STORE_DIR}"
if [ ! -e "$storeDir" ]; then
GIT_SSH_COMMAND='${pkgs.openssh}/bin/ssh -o StrictHostKeyChecking=accept-new' \
${pkgs.git}/bin/git clone git@github.com:Swarsel/secrets.git "$storeDir" || warnEcho "failed to clone the password store"
fi
'';
};
};
}
4.4.2.9. direnv
Enables direnv, which I use for nearly all of my nix dev flakes.
{
flake.modules.homeManager.direnv.config = {
swarselsystems.enabledHomeModules = [ "direnv" ];
programs.direnv = {
enable = true;
nix-direnv.enable = true;
silent = true;
};
};
}
4.4.2.10. eza
Eza provides me with a better ls command and some other useful aliases.
{
flake.modules.homeManager.eza.config = {
swarselsystems.enabledHomeModules = [ "eza" ];
programs.eza = {
enable = true;
extraOptions = [
"-l"
"--group-directories-first"
];
git = true;
icons = "auto";
};
};
}
4.4.2.11. git
Here I set up my git config, automatic signing of commits, useful aliases for my most used commands (for when I am not using Magit) as well as a git template defined in [BROKEN LINK: h:5ef03803-e150-41bc-b603-e80d60d96efc].
{
flake.modules.homeManager.git =
{
config,
lib,
pkgs,
confLib,
globals,
minimal,
nixosConfig ? null,
...
}:
let
inherit (confLib.getConfig.repo.secrets.common.mail) address1;
inherit (confLib.getConfig.repo.secrets.common) fullName;
inherit (config.swarselsystems) homeDir mainUser;
gitUser = globals.user.name;
in
{
config = {
swarselsystems.enabledHomeModules = [ "git" ];
programs = {
difftastic.enable = lib.mkIf (!minimal) true;
git = {
enable = true;
}
// lib.optionalAttrs (!minimal) {
includes = [
{
contents = {
commit.template = "${pkgs.writeText "gitmessage" ''
# max. 50 chars is here: #
# <type>[optional scope]: <description>
# types: feat, fix, build, chore, ci, docs, style, refactor, perf, test
# ! indicates a breaking change.
# Body: wrap at 72 chars is here: #
# Include at least one empty line before co-authored. Format:
# Co-authored-by: name <user@users.noreply.github.com>
''}";
forge = {
remote = globals.services.forgejo.subDomain;
url = "${globals.services.forgejo.extraConfig.sshUrl}/${gitUser}";
};
github.user = gitUser;
};
}
];
lfs.enable = true;
maintenance.enable = true;
settings = {
alias = {
a = "add";
b = "branch";
c = "commit";
cl = "clone";
co = "checkout";
i = "init";
m = "merge";
p = "pull";
pp = "push";
r = "restore";
s = "status";
};
maintenance.prefetch.enabled = false;
user = {
email = lib.mkIf ((nixosConfig != null) && !config.swarselsystems.isPublic) (
lib.mkDefault address1
);
name = lib.mkIf ((nixosConfig != null) && !config.swarselsystems.isPublic) fullName;
};
};
signing = {
format = "openpgp";
key = "0x76FD3810215AE097";
signByDefault = true;
};
};
};
systemd.user.tmpfiles.rules = [
"f ${homeDir}/.gitconfig 0644 ${mainUser} users - -"
];
};
};
}
4.4.2.12. Fuzzel
Here I only need to set basic layout options - the rest is being managed by stylix.
{
flake.modules.homeManager.fuzzel.config = {
swarselsystems.enabledHomeModules = [ "fuzzel" ];
programs.fuzzel = {
enable = true;
settings = {
border.radius = "0";
main = {
layer = "overlay";
lines = "10";
width = "40";
};
};
};
};
}
4.4.2.13. Starship
Starship makes my zsh look cooler! I have symbols for most programming languages and tool chains, also I build my own powerline.
{
flake.modules.homeManager.starship.config = {
swarselsystems.enabledHomeModules = [ "starship" ];
programs.starship = {
enable = true;
enableZshIntegration = true;
settings = {
package.symbol = " ";
add_newline = false;
aws.symbol = " ";
buf.symbol = " ";
c.symbol = " ";
character = {
error_symbol = "[λ](bold red)";
success_symbol = "[λ](bold green)";
};
command_timeout = 3000;
conda.symbol = " ";
dart.symbol = " ";
directory = {
read_only = " ";
substitutions = {
Documents = " ";
Downloads = " ";
Music = " ";
Pictures = " ";
};
};
docker_context.symbol = " ";
elixir.symbol = " ";
elm.symbol = " ";
format = "$shlvl$character";
fossil_branch.symbol = " ";
git_branch.symbol = " ";
git_status = {
format = "[[($all_status$ahead_behind)](fg:#769ff0 bg:#394260)]($style) ";
style = "bg:#394260";
};
golang.symbol = " ";
guix_shell.symbol = " ";
haskell.symbol = " ";
haxe.symbol = " ";
hg_branch.symbol = " ";
hostname.ssh_symbol = " ";
java.symbol = " ";
julia.symbol = " ";
lua.symbol = " ";
memory_usage.symbol = " ";
meson.symbol = " ";
nim.symbol = " ";
nix_shell = {
disabled = false;
format = "[$symbol$name]($style)";
heuristic = true;
symbol = " ";
};
nodejs.symbol = " ";
os.symbols = {
Alpaquita = " ";
Alpine = " ";
Amazon = " ";
Android = " ";
Arch = " ";
Artix = " ";
CentOS = " ";
Debian = " ";
DragonFly = " ";
Emscripten = " ";
EndeavourOS = " ";
Fedora = " ";
FreeBSD = " ";
Garuda = " ";
Gentoo = " ";
HardenedBSD = " ";
Illumos = " ";
Linux = " ";
Mabox = " ";
Macos = " ";
Manjaro = " ";
Mariner = " ";
MidnightBSD = " ";
Mint = " ";
NetBSD = " ";
NixOS = " ";
OpenBSD = " ";
OracleLinux = " ";
Pop = " ";
Raspbian = " ";
RedHatEnterprise = " ";
Redhat = " ";
Redox = " ";
SUSE = " ";
Solus = " ";
Ubuntu = " ";
Unknown = " ";
Windows = " ";
openSUSE = " ";
};
pijul_channel.symbol = " ";
python.symbol = " ";
right_format = "$all";
rlang.symbol = " ";
ruby.symbol = " ";
rust.symbol = " ";
scala.symbol = " ";
shlvl = {
disabled = false;
format = "[$symbol]($style) ";
repeat = true;
repeat_offset = 1;
style = "blue";
symbol = "↳";
};
};
};
};
}
4.4.2.14. Kitty
Kitty is the terminal emulator of choice for me, it is nice to configure using nix, fast, and has a nice style.
The theme is handled by stylix.
{
flake.modules.homeManager.kitty = { lib, ... }: {
config = {
swarselsystems.enabledHomeModules = [ "kitty" ];
programs.kitty = {
enable = true;
keybindings =
let
hintTargets = {
f = "path";
h = "hash";
i = "ip";
l = "line";
u = "url";
w = "word";
};
bindWithModifier = lib.mapAttrs' (key: lib.nameValuePair ("ctrl+shift+" + key));
hint =
prefix: program:
lib.mapAttrs' (
key: type: lib.nameValuePair "${prefix}>${key}" "kitten hints --type ${type} --program ${program}"
);
copyHint = hint "y" "@";
pasteHint = hint "p" "-";
disable = keys: lib.genAttrs keys (_: "no_op");
font = mode: keys: lib.genAttrs keys (_: "change_font_size all ${mode}2.0");
in
disable [ "ctrl+tab" ]
// bindWithModifier (
{
backspace = "change_font_size all 0";
e = "open_url_with_hints";
"p>n" = "kitten hints --type linenum";
u = "kitten unicode_input";
}
// font "+" [
"equal"
"plus"
]
// font "-" [
"minus"
]
// disable (
[
","
"."
"/"
"["
"]"
"`"
"alt+t"
"b"
"down"
"end"
"enter"
"f"
"f7"
"f8"
"g"
"h"
"home"
"j"
"k"
"l"
"left"
"page_down"
"page_up"
"q"
"r"
"right"
"t"
"tab"
"up"
"w"
"x"
"z"
]
++ map toString (lib.range 0 9)
)
// pasteHint hintTargets
// copyHint hintTargets
);
settings = {
cursor_blink_interval = 0;
disable_ligatures = "cursor";
enable_audio_bell = false;
notify_on_cmd_finish = "always 20";
open_url_with = "xdg-open";
scrollback_lines = 100000;
scrollback_pager_history_size = 512;
};
};
};
};
}
4.4.2.15. zsh
zsh is the most convenient shell for me and it happens to be super neat to configure within home manager.
Here we set some aliases (some of them should be shellApplications instead) as well as some zsh plugins like fzf-tab.
Concerning the shell extensions, zle <widget-name> will run an existing widget and zle -N <function_name> will make a function available for use. The my- functions all remove . / and : from the WORDCHARS so that functions will stop there. The keycodes can be found using showkeys -a
Regarding initContent:
To specify the order, use lib.mkOrder.
Common order values:
- 500 (mkBefore: Early initialization (replaces initExtraFirst
- 550: Before completion initialization (replaces initExtraBeforeCompInit
- 1000 (default: General configuration (replaces initExtra
- 1500 (mkAfter: Last to run configuration
To specify both content in Early initialization and General configuration, use lib.mkMerge:
let
zshConfigEarlyInit = lib.mkOrder 500 "do something";
zshConfig = lib.mkOrder 1000 "do something";
in
lib.mkMerge [ zshConfigEarlyInit zshConfig ];
Currently I only use it as before with initExtra though.
{
flake.modules = {
homeManager.zsh =
{
root,
config,
lib,
pkgs,
arch,
confLib,
globals,
minimal,
nixosConfig ? null,
...
}:
let
inherit (config.swarselsystems) flakePath homeDir;
isNixos = nixosConfig != null;
fzf = lib.getExe pkgs.fzf;
in
{
options.swarselsystems.shellAliases = lib.mkOption {
default = { };
type = lib.types.attrsOf lib.types.str;
};
config = {
swarselsystems = {
enabledHomeModules = [ "zsh" ];
homeSopsSecrets = {
croc-password.rekey.keyPrefix = confLib.static.sharedSecrets.clients;
github-nixpkgs-review-token.rekey.keyPrefix = confLib.static.sharedSecrets.clients;
};
};
programs.zsh = {
enable = true;
}
// lib.optionalAttrs (!minimal) {
autocd = false;
autosuggestion.enable = true;
cdpath = [
"~/.dotfiles"
# "~/Documents/GitHub"
];
defaultKeymap = "emacs";
dirHashes = {
dl = "$HOME/Downloads";
gh = "$HOME/Documents/GitHub";
};
enableCompletion = true;
history = {
append = true;
expireDuplicatesFirst = true;
ignoreDups = true;
ignoreSpace = true;
path = "${config.home.homeDirectory}/.histfile";
save = 100000;
size = 100000;
};
historySubstringSearch = {
enable = true;
searchDownKey = "^[OB";
searchUpKey = "^[OA";
};
initContent = ''
my-word-widget() {
local WORDCHARS=$WORDCHARS
WORDCHARS="''${WORDCHARS//:}"
WORDCHARS="''${WORDCHARS//\/}"
WORDCHARS="''${WORDCHARS//.}"
zle ''${WIDGET#my-}
}
zle -N my-forward-word my-word-widget
zle -N my-backward-word my-word-widget
zle -N my-backward-delete-word my-word-widget
# ctrl + right
bindkey "^[[1;5C" my-forward-word
# shift + right
bindkey "^[[1;2C" forward-word
# ctrl + left
bindkey "^[[1;5D" my-backward-word
# shift + left
bindkey "^[[1;2D" backward-word
# ctrl + del
bindkey '^H' my-backward-delete-word
cdr() {
local target=$({ find ${
lib.escapeShellArgs (
lib.attrValues (
lib.filterAttrs (name: _: lib.hasPrefix "DOCUMENT_DIR_" name) config.systemd.user.sessionVariables
)
)
} -maxdepth 1; print ${flakePath}; } | ${fzf})
[[ -n $target ]] && cd $target
}
cdb() {
local branch=$(git branch --format='%(refname:short)' | ${fzf})
[[ -n $branch ]] && git checkout $branch
}
cdw() {
local target=$(git worktree list | ${fzf} | cut -d' ' -f1)
[[ -n $target ]] && cd $target
}
bak() {
cp -r $1 $1.bak
}
t2ts() {
date -d $1 +%s
}
ts2t() {
date -d @$1 2>/dev/null || date -r $1
}
sshrm() {
local cmd=$(fc -lnm 'ssh *' 1 | tail -n 1)
local host=$(command ssh -G ''${=cmd#ssh } 2>/dev/null | sed -n 's/^hostname //p')
[[ -n $host ]] && ssh-keygen -R $host
}
'';
plugins = [
# {
# name = "fzf-tab";
# src = pkgs.zsh-fzf-tab;
# }
];
sessionVariables = lib.mkIf (!config.swarselsystems.isPublic) {
CROC_PASS = "$(cat ${confLib.getConfig.sops.secrets.croc-password.path})";
CROC_RELAY = globals.services.croc.domain;
GITHUB_TOKEN = "$(cat ${confLib.getConfig.sops.secrets.github-nixpkgs-review-token.path})";
QT_QPA_PLATFORM_PLUGIN_PATH = "${pkgs.qt5.qtbase.bin}/lib/qt-${pkgs.qt5.qtbase.version}/plugins";
# QTWEBENGINE_CHROMIUM_FLAGS = "--no-sandbox";
};
shellAliases = lib.recursiveUpdate {
config = "git --git-dir=$HOME/.cfg/ --work-tree=$HOME";
boot-diff = "nix store diff-closures /run/*-system";
build-iso = "nix build --print-out-paths .#live-iso";
build-topology = "nix build --override-input topologyPrivate ${root "files/topology/private"} ${flakePath}#topology.${arch}.config.output";
build-topology-dev = "nix build --show-trace --override-input nix-topology ${homeDir}/Documents/Private/nix-topology --override-input topologyPrivate ${root "files/topology/private"} ${flakePath}#topology.${arch}.config.output";
c = "git --git-dir=$FLAKE/.git --work-tree=$FLAKE/";
cat-orig = "cat";
cc = "wl-copy";
g = "git";
gen-diff = "nix profile diff-closures --profile /nix/var/nix/profiles/system";
hmswitch = lib.mkIf (
!isNixos
) "${lib.getExe pkgs.home-manager} --flake ${flakePath}#$(hostname) switch |& nom";
hotspot = "nmcli connection up local; nmcli device wifi hotspot;";
lt = "eza -las modified --total-size";
magit = "emacsclient -nc -e \"(magit-status)\"";
nb = "nix build";
nbl = "nix build --builders \"\"";
nbo = "nix build --offline --builders \"\"";
nboot = lib.mkIf isNixos "cd ${flakePath}; swarsel-deploy $(hostname) boot; cd -;";
nd = "nix develop";
ndry = lib.mkIf isNixos "cd ${flakePath}; swarsel-deploy $(hostname) dry-activate; cd -;";
nix-ldd = "LD_LIBRARY_PATH=$NIX_LD_LIBRARY_PATH ldd";
nix-ldd-locate = "nix-locate --minimal --top-level -w ";
nix-review-local = "nix run nixpkgs#nixpkgs-review -- rev HEAD";
nix-review-post = "nix run nixpkgs#nixpkgs-review -- pr --post-result --systems linux";
nix-store-search = "ls /nix/store | grep";
ns = "nix shell";
nswitch = lib.mkIf isNixos "cd ${flakePath}; swarsel-deploy $(hostname) switch; cd -;";
ntest = lib.mkIf isNixos "cd ${flakePath}; swarsel-deploy $(hostname) test; cd -;";
passpull = "cd ~/.local/share/password-store; git pull; cd -;";
passpush = "cd ~/.local/share/password-store; git add .; git commit -m 'pass file changes'; git push; cd -;";
youtube-dl = "yt-dlp";
} config.swarselsystems.shellAliases;
syntaxHighlighting.enable = true;
};
};
};
nixos.zsh = { pkgs, ... }: {
config = {
users.defaultUserShell = pkgs.zsh;
programs.zsh = {
enable = true;
enableCompletion = false;
};
environment = {
pathsToLink = [ "/share/zsh" ];
shells = with pkgs; [ zsh ];
};
};
};
};
}
4.4.2.16. bash
{
flake.modules.homeManager.bash =
{
config,
lib,
nixosConfig ? null,
...
}:
{
config = {
swarselsystems.enabledHomeModules = [ "bash" ];
programs.bash = {
enable = true;
# needed for remote builders
bashrcExtra = lib.mkIf (nixosConfig == null) ''
export PATH="/nix/var/nix/profiles/default/bin:$PATH"
'';
historyControl = [
"ignoreboth"
];
historyFile = "${config.home.homeDirectory}/.histfile";
historyFileSize = 100000;
historySize = 100000;
};
};
};
}
4.4.2.17. zellij
4.4.2.17.1. Main config
{
flake.modules.homeManager.zellij =
{
config,
lib,
pkgs,
...
}:
let
inherit (config.lib.stylix) colors;
zellij-delete-if-idle = pkgs.writeShellApplication {
name = "zellij-delete-if-idle";
runtimeInputs = [
config.programs.zellij.finalPackage
pkgs.procps
];
text = ''
server=$1
shells=$(pgrep -d, -P "$server")
if ps -o comm= -p "$shells" | grep -vqxE 'zsh|bash' || pgrep -P "$shells" | grep -vqxF "$$"; then
exit 0
fi
zellij delete-session --force "$(basename "$(tr '\0' '\n' <"/proc/$server/cmdline" | sed -n 3p)")" || kill "$server"
'';
};
zellij-kitty = pkgs.writeShellApplication {
name = "zellij-kitty";
runtimeInputs = [
config.programs.zellij.finalPackage
pkgs.procps
zellij-delete-if-idle
];
text = ''
tag="$$-$RANDOM"
hup=0
trap 'hup=1' HUP
ZELLIJ_KITTY_TAG="$tag" zellij "$@" || true
if [ "$hup" = 0 ]; then
exit 0
fi
exec >/dev/null 2>&1
for server in $(pgrep -f 'zellij --server'); do
grep -qxzF "ZELLIJ_KITTY_TAG=$tag" "/proc/$server/environ" || continue
zellij-delete-if-idle "$server"
done
'';
};
in
{
config = {
swarselsystems.enabledHomeModules = [ "zellij" ];
programs = {
kitty.settings.shell = lib.getExe zellij-kitty;
zellij = {
enable = true;
enableZshIntegration = false;
settings = {
copy_command = if pkgs.stdenv.hostPlatform.isDarwin then "pbcopy" else "wl-copy";
copy_on_select = true;
default_layout = "swarsel";
default_shell = "zsh";
on_force_close = "detach";
pane_frames = false;
scrollback_lines_to_serialize = config.programs.kitty.settings.scrollback_lines;
session_serialization = true;
show_startup_tips = false;
ui.pane_frames = {
hide_session_name = true;
rounded_corners = true;
};
};
};
zsh.initContent = ''
if [[ -n $ZELLIJ ]]; then
export ZELLIJ_SERVER_PID=''${ZELLIJ_SERVER_PID:-$PPID}
zellij_tab_name=/
zellij-tab-name() {
[[ $1 == $zellij_tab_name ]] && return
zellij_tab_name=$1
{
local tab=$(zellij action list-panes -tj | ${lib.getExe pkgs.jq} --argjson pane $ZELLIJ_PANE_ID '.[] | select((.is_plugin | not) and .id == $pane) | .tab_id')
if [[ -n $1 ]]; then
zellij action rename-tab --tab-id $tab $1
else
zellij action undo-rename-tab --tab-id $tab
fi
} &>/dev/null &!
}
zellij-git-tab-name() {
zellij-tab-name ''${$(git rev-parse --show-toplevel 2>/dev/null):t}
}
precmd_functions+=(zellij-git-tab-name)
ssh() {
zellij-tab-name $(command ssh -G "$@" 2>/dev/null | sed -n 's/^host //p')
command ssh "$@"
local ret=$?
if [[ -z $(zellij action list-clients | tail -n +2) ]]; then
${lib.getExe zellij-delete-if-idle} "$ZELLIJ_SERVER_PID"
fi
return $ret
}
fi
'';
};
home.activation.zellijPluginPermissions = lib.hm.dag.entryAfter [ "writeBoundary" ] ''
cache="${config.xdg.cacheHome}/zellij/permissions.kdl"
plugin="${config.xdg.dataHome}/zellij/plugins/zjstatus.wasm"
if ! grep -qsF "\"$plugin\"" "$cache"; then
run mkdir -p "$(dirname "$cache")"
run sh -c 'printf "\"%s\" {\n RunCommands\n ReadApplicationState\n ChangeApplicationState\n}\n" "$1" >> "$2"' _ "$plugin" "$cache"
fi
'';
xdg = {
configFile."zellij/layouts/swarsel.kdl".text = ''
layout {
default_tab_template {
children
pane size=1 borderless=true {
plugin location="file://${config.xdg.dataHome}/zellij/plugins/zjstatus.wasm" {
format_left "{mode}#[bg=#${colors.base00}] {tabs}"
format_center ""
format_right "#[bg=#${colors.base00},fg=#${colors.base02}]#[bg=#${colors.base02},fg=#${colors.base01},bold] #[bg=#${colors.base02},fg=#${colors.base01},bold] {session} #[bg=#${colors.base02},fg=#${colors.base01},bold]"
format_space ""
format_hide_on_overlength "false"
format_precedence "lcr"
border_enabled "false"
border_char "─"
border_format "#[fg=#6C7086]{char}"
border_position "top"
mode_normal "#[bg=#${colors.base0B},fg=#${colors.base01},bold] NORMAL#[bg=#${colors.base01},fg=#${colors.base0B}]█"
mode_locked "#[bg=#${colors.base04},fg=#${colors.base01},bold] LOCKED #[bg=#${colors.base01},fg=#${colors.base04}]█"
mode_resize "#[bg=#${colors.base08},fg=#${colors.base01},bold] RESIZE#[bg=#${colors.base01},fg=#${colors.base08}]█"
mode_pane "#[bg=#${colors.base0D},fg=#${colors.base01},bold] PANE#[bg=#${colors.base01},fg=#${colors.base0D}]█"
mode_tab "#[bg=#${colors.base07},fg=#${colors.base01},bold] TAB#[bg=#${colors.base01},fg=#${colors.base07}]█"
mode_scroll "#[bg=#${colors.base0A},fg=#${colors.base01},bold] SCROLL#[bg=#${colors.base01},fg=#${colors.base0A}]█"
mode_enter_search "#[bg=#${colors.base0D},fg=#${colors.base01},bold] ENT-SEARCH#[bg=#${colors.base01},fg=#${colors.base0D}]█"
mode_search "#[bg=#${colors.base0D},fg=#${colors.base01},bold] SEARCHARCH#[bg=#${colors.base01},fg=#${colors.base0D}]█"
mode_rename_tab "#[bg=#${colors.base07},fg=#${colors.base01},bold] RENAME-TAB#[bg=#${colors.base01},fg=#${colors.base07}]█"
mode_rename_pane "#[bg=#${colors.base0D},fg=#${colors.base01},bold] RENAME-PANE#[bg=#${colors.base01},fg=#${colors.base0D}]█"
mode_session "#[bg=#${colors.base0E},fg=#${colors.base01},bold] SESSION#[bg=#${colors.base01},fg=#${colors.base0E}]█"
mode_move "#[bg=#${colors.base0F},fg=#${colors.base01},bold] MOVE#[bg=#${colors.base01},fg=#${colors.base0F}]█"
mode_prompt "#[bg=#${colors.base0D},fg=#${colors.base01},bold] PROMPT#[bg=#${colors.base01},fg=#${colors.base0D}]█"
// formatting for inactive tabs
tab_normal "#[bg=#${colors.base01},fg=#${colors.base0C}]█#[bg=#${colors.base0C},fg=#${colors.base01},bold]{index} #[bg=#${colors.base01},fg=#${colors.base0C},bold] {name}{floating_indicator}#[bg=#${colors.base01},fg=#${colors.base01},bold]█"
tab_normal_fullscreen "#[bg=#${colors.base01},fg=#${colors.base0C}]█#[bg=#${colors.base0C},fg=#${colors.base01},bold]{index} #[bg=#${colors.base01},fg=#${colors.base0C},bold] {name}{fullscreen_indicator}#[bg=#${colors.base01},fg=#${colors.base01},bold]█"
tab_normal_sync "#[bg=#${colors.base01},fg=#${colors.base0C}]█#[bg=#${colors.base0C},fg=#${colors.base01},bold]{index} #[bg=#${colors.base01},fg=#${colors.base0C},bold] {name}{sync_indicator}#[bg=#${colors.base01},fg=#${colors.base01},bold]█"
// formatting for the current active tab
tab_active "#[bg=#${colors.base01},fg=#${colors.base09}]█#[bg=#${colors.base09},fg=#${colors.base01},bold]{index} #[bg=#${colors.base01},fg=#${colors.base09},bold] {name}{floating_indicator}#[bg=#${colors.base01},fg=#${colors.base01},bold]█"
tab_active_fullscreen "#[bg=#${colors.base01},fg=#${colors.base09}]█#[bg=#${colors.base09},fg=#${colors.base01},bold]{index} #[bg=#${colors.base01},fg=#${colors.base09},bold] {name}{fullscreen_indicator}#[bg=#${colors.base01},fg=#${colors.base01},bold]█"
tab_active_sync "#[bg=#${colors.base01},fg=#${colors.base09}]█#[bg=#${colors.base09},fg=#${colors.base01},bold]{index} #[bg=#${colors.base01},fg=#${colors.base09},bold] {name}{sync_indicator}#[bg=#${colors.base01},fg=#${colors.base01},bold]█"
// separator between the tabs
tab_separator "#[bg=#${colors.base00}] "
// indicators
tab_sync_indicator " "
tab_fullscreen_indicator " "
tab_floating_indicator " "
datetime "#[fg=#6C7086,bold] {format} "
datetime_format "%A, %d %b %Y %H:%M"
datetime_timezone "Europe/Vienna"
}
}
}
}
'';
dataFile."zellij/plugins/zjstatus.wasm".source = "${pkgs.zjstatus}/bin/zjstatus.wasm";
};
};
};
}
4.4.2.17.2. Keybindings
{
flake.modules.homeManager.zellij-keybinds =
{ lib, ... }:
let
bind = keys: actions: {
bind = {
_args = lib.toList keys;
_children = lib.toList actions;
};
};
switchTo = mode: { SwitchToMode._args = [ mode ]; };
directional =
action:
lib.mapAttrsToList (direction: keys: bind keys (action direction)) {
down = [
"j"
"down"
];
left = [
"h"
"left"
];
right = [
"l"
"right"
];
up = [
"k"
"up"
];
};
in
{
config.programs.zellij.settings.keybinds = {
_props.clear-defaults = true;
entersearch._children = [
(bind [ "Ctrl c" "esc" ] (switchTo "scroll"))
(bind "enter" (switchTo "search"))
];
locked._children = [ (bind "Ctrl g" (switchTo "normal")) ];
pane._children = [
(bind "Ctrl p" (switchTo "normal"))
(bind "d" [
{ NewPane._args = [ "down" ]; }
(switchTo "normal")
])
(bind "e" [
{ TogglePaneEmbedOrFloating = { }; }
(switchTo "normal")
])
(bind "f" [
{ ToggleFocusFullscreen = { }; }
(switchTo "normal")
])
(bind "n" [
{ NewPane = { }; }
(switchTo "normal")
])
(bind "p" { SwitchFocus = { }; })
(bind "f12" [
{ ToggleFloatingPanes = { }; }
(switchTo "normal")
])
(bind "x" [
{ CloseFocus = { }; }
(switchTo "normal")
])
]
++ directional (direction: {
MoveFocus._args = [ direction ];
});
renametab._children = [
(bind "esc" [
{ UndoRenameTab = { }; }
(switchTo "tab")
])
(bind "Ctrl c" (switchTo "normal"))
];
resize._children = [
(bind "Ctrl n" (switchTo "normal"))
(bind "+" { Resize._args = [ "Increase" ]; })
(bind "-" { Resize._args = [ "Decrease" ]; })
(bind "H" { Resize._args = [ "Decrease left" ]; })
(bind "J" { Resize._args = [ "Decrease down" ]; })
(bind "K" { Resize._args = [ "Decrease up" ]; })
(bind "L" { Resize._args = [ "Decrease right" ]; })
]
++ directional (direction: {
Resize._args = [ "Increase ${direction}" ];
});
scroll._children = [
(bind "e" [
{ EditScrollback = { }; }
(switchTo "normal")
])
(bind "s" [
(switchTo "entersearch")
{ SearchInput._args = [ 0 ]; }
])
];
search._children = [
(bind "c" { SearchToggleOption._args = [ "CaseSensitivity" ]; })
(bind "n" { Search._args = [ "down" ]; })
(bind "o" { SearchToggleOption._args = [ "WholeWord" ]; })
(bind "p" { Search._args = [ "up" ]; })
(bind "w" { SearchToggleOption._args = [ "Wrap" ]; })
];
session._children = [
(bind "Ctrl o" (switchTo "normal"))
(bind "w" [
{
LaunchOrFocusPlugin = {
_args = [ "session-manager" ];
_children = [
{ floating._args = [ true ]; }
{ move_to_focused_tab._args = [ true ]; }
];
};
}
(switchTo "normal")
])
(bind "d" { Detach = { }; })
];
"shared_among \"scroll\" \"search\""._children = [
(bind [ "PageDown" "right" "l" "Ctrl f" ] { PageScrollDown = { }; })
(bind [ "PageUp" "left" "h" "Ctrl b" ] { PageScrollUp = { }; })
(bind [ "down" "j" ] { ScrollDown = { }; })
(bind [ "up" "k" ] { ScrollUp = { }; })
(bind "d" { HalfPageScrollDown = { }; })
(bind "u" { HalfPageScrollUp = { }; })
(bind "Ctrl c" [
{ ScrollToBottom = { }; }
(switchTo "normal")
])
(bind "Ctrl s" (switchTo "normal"))
];
"shared_except \"locked\""._children = [
(bind [ "Alt h" "Alt left" ] { MoveFocusOrTab._args = [ "left" ]; })
(bind "Alt right" { MoveFocusOrTab._args = [ "right" ]; })
(bind [ "Alt j" "Alt down" ] { MoveFocus._args = [ "down" ]; })
(bind [ "Alt k" "Alt up" ] { MoveFocus._args = [ "up" ]; })
(bind "Alt +" { Resize._args = [ "Increase" ]; })
(bind "Alt -" { Resize._args = [ "Decrease" ]; })
(bind "Alt r" { WriteChars._args = [ "cdr\n" ]; })
(bind "Alt w" { WriteChars._args = [ "cdw\n" ]; })
(bind "Alt b" { WriteChars._args = [ "cdb\n" ]; })
(bind "Alt f" { ToggleFloatingPanes = { }; })
(bind "Alt i" { MoveTab._args = [ "left" ]; })
(bind "Alt p" { NewPane = { }; })
(bind "Alt n" { NewTab = { }; })
(bind "Ctrl g" (switchTo "locked"))
];
"shared_except \"locked\" \"pane\""._children = [ (bind "Ctrl p" (switchTo "pane")) ];
"shared_except \"locked\" \"resize\""._children = [ (bind "Ctrl n" (switchTo "resize")) ];
"shared_except \"locked\" \"scroll\" \"search\""._children = [
(bind "Ctrl s" (switchTo "scroll"))
];
"shared_except \"locked\" \"session\""._children = [ (bind "Ctrl o" (switchTo "session")) ];
"shared_except \"locked\" \"tab\""._children = [ (bind "Ctrl t" (switchTo "tab")) ];
"shared_except \"normal\" \"locked\" \"entersearch\""._children = [
(bind "enter" (switchTo "normal"))
];
"shared_except \"normal\" \"locked\" \"entersearch\" \"renametab\""._children = [
(bind "esc" (switchTo "normal"))
];
tab._children = [
(bind "Ctrl t" (switchTo "normal"))
(bind [ "h" "k" "left" "up" ] { GoToPreviousTab = { }; })
(bind [ "j" "l" "down" "right" ] { GoToNextTab = { }; })
(bind "n" [
{ NewTab = { }; }
(switchTo "normal")
])
(bind "r" [
(switchTo "renametab")
{ TabNameInput._args = [ 0 ]; }
])
(bind "s" [
{ ToggleActiveSyncTab = { }; }
(switchTo "normal")
])
(bind "x" [
{ CloseTab = { }; }
(switchTo "normal")
])
]
++ map (
n:
bind (toString n) [
{ GoToTab._args = [ n ]; }
(switchTo "normal")
]
) (lib.range 1 9);
};
};
}
4.4.2.18. Mail
Normally I use 4 mail accounts - here I set them all up. Three of them are Google accounts (sadly), which are a chore to setup. The last is just a sender account that I setup SMTP for here.
{
flake.modules.homeManager.mail =
{
config,
lib,
confLib,
globals,
nixosConfig ? null,
...
}:
let
inherit (confLib.getConfig.repo.secrets.common.mail)
address1
address2
address2-name
address3
address3-name
address4
;
inherit (confLib.getConfig.repo.secrets.common) fullName;
clientsSecrets = confLib.static.sharedSecrets.clients;
in
{
config = {
swarselsystems = {
enabledHomeModules = [ "mail" ];
homeSopsSecrets = {
address1-token.rekey.keyPrefix = clientsSecrets;
address2-token.rekey.keyPrefix = clientsSecrets;
address3-token.rekey.keyPrefix = clientsSecrets;
address4-token.rekey.keyPrefix = clientsSecrets;
};
};
services.mbsync.enable = true;
programs = {
mbsync.enable = true;
msmtp.enable = true;
mu.enable = true;
};
programs.thunderbird = {
enable = true;
profiles.default = {
isDefault = true;
settings = {
"gfx.webrender.all" = true;
"gfx.webrender.enabled" = true;
"mail.identity.default.archive_enabled" = true;
"mail.identity.default.archive_keep_folder_structure" = true;
"mail.identity.default.compose_html" = false;
"mail.identity.default.protectSubject" = true;
"mail.identity.default.reply_on_top" = 1;
"mail.identity.default.sig_bottom" = false;
"mail.identity.default.sig_on_reply" = false;
};
withExternalGnupg = true;
};
settings = {
"app.update.auto" = false;
"mail.identity.default.attachPgpKey" = true;
"mail.identity.default.auto_quote" = true;
"mail.imap.expunge_after_delete" = true;
"mail.server.default.allow_utf8_accept" = true;
"mail.server.default.check_all_folders_for_new" = true;
"mail.server.default.delete_model" = 2;
"mail.server.default.max_articles" = 1000;
"mail.show_headers" = 1;
"mail.warn_on_delete_from_trash" = false;
"mail.warn_on_shift_delete" = false;
"mailnews.default_sort_order" = 2;
"mailnews.default_sort_type" = 18;
"mailnews.default_view_flags" = 0;
"mailnews.headers.showMessageId" = true;
"mailnews.headers.showOrganization" = true;
"mailnews.headers.showReferences" = true;
"mailnews.headers.showUserAgent" = true;
"mailnews.sort_threads_by_root" = true;
"privacy.donottrackheader.enabled" = true;
"toolkit.telemetry.enabled" = false;
"toolkit.telemetry.prompted" = 2;
"toolkit.telemetry.rejected" = true;
};
};
accounts = lib.mkIf ((nixosConfig != null) && !config.swarselsystems.isPublic) {
email =
let
defaultSettings = {
imap = {
host = "imap.gmail.com";
port = 993;
tls.enable = true; # SSL/TLS
};
mbsync = {
enable = true;
create = "maildir";
expunge = "both";
extraConfig = {
account = {
AuthMechs = "LOGIN";
PipelineDepth = 1;
Timeout = 120;
};
channel.Sync = "All";
};
patterns = [
"*"
"![Gmail]*"
"[Gmail]/Sent Mail"
"[Gmail]/Starred"
"[Gmail]/All Mail"
];
};
msmtp.enable = true;
mu.enable = true;
smtp = {
host = "smtp.gmail.com";
port = 465;
tls.enable = true; # SSL/TLS
};
thunderbird = {
enable = true;
profiles = [ "default" ];
};
};
in
{
accounts = {
leon = lib.recursiveUpdate {
address = address1;
gpg = {
key = "0x76FD3810215AE097";
signByDefault = true;
};
passwordCommand = "cat ${confLib.getConfig.sops.secrets.address1-token.path}";
primary = true;
realName = fullName;
userName = address1;
} defaultSettings;
mrswarsel = lib.recursiveUpdate {
address = address3;
passwordCommand = "cat ${confLib.getConfig.sops.secrets.address3-token.path}";
primary = false;
realName = address3-name;
userName = address3;
} defaultSettings;
nautilus = lib.recursiveUpdate {
address = address2;
passwordCommand = "cat ${confLib.getConfig.sops.secrets.address2-token.path}";
primary = false;
realName = address2-name;
userName = address2;
} defaultSettings;
swarsel = lib.recursiveUpdate defaultSettings {
address = address4;
imap.host = globals.services.mailserver.domain;
mbsync.patterns = [ "*" ];
passwordCommand = "cat ${confLib.getConfig.sops.secrets.address4-token.path}";
realName = fullName;
smtp.host = globals.services.mailserver.domain;
userName = address4;
};
};
maildirBasePath = "Mail";
};
};
xdg.mimeApps.defaultApplications = {
"message/rfc822" = [ "thunderbird.desktop" ];
"x-scheme-handler/mailto" = [ "thunderbird.desktop" ];
"x-scheme-handler/mid" = [ "thunderbird.desktop" ];
};
# this is needed so that mbsync can use the passwords from sops
systemd.user.services.mbsync.Unit.After = [ "sops-nix.service" ];
};
};
}
4.4.2.19. Home-manager: Emacs
I install and configure Emacs through home-manager using rycee's emacs-init module on top of the emacs-overlay. Rather than writing an init.el in elisp and symlinking it (which I used to do in the past), I now declare the whole configuration using programs.emacs.init - split across the files under modules/client/programs/emacs/ - and the module generates early-init.el and init.el from it on rebuild. Packages under the usePackage attribute are resolved against the emacs-overlay package set of my base Emacs, which here is native Wayland Emacs (emacs-unstable-pgtk), so I get bleeding-edge MELPA snapshots. Niceties such as tree-sitter support are enabled by default, so I do not need to adjust the build process. This block itself only wires up the module, the base package, the SOPS secrets and the Emacs service; the actual package configuration lives in the sections further below.
The few packages that are not on ELPA or MELPA are built with trivialBuild directly in their respective sections rather than here.
{
flake-file.inputs.nur-expressions = {
flake = false;
url = "gitlab:rycee/nur-expressions";
};
flake.modules.homeManager.emacs =
{
self,
inputs,
config,
lib,
pkgs,
confLib,
globals,
...
}:
let
inherit (config.swarselsystems) homeDir;
inherit (confLib.getConfig.repo.secrets.common.emacs) radicaleUser;
clientsSecrets = confLib.static.sharedSecrets.clients;
in
{
imports = [
"${inputs.nur-expressions}/hm-modules/emacs-init.nix"
self.modules.homeManager.emacs-init
];
config = {
swarselsystems = {
enabledHomeModules = [ "emacs" ];
homeSopsSecrets = {
emacs-radicale-pw.rekey.keyPrefix = clientsSecrets;
fever-pw = {
path = "${homeDir}/.emacs.d/.fever";
rekey.keyPrefix = clientsSecrets;
};
github-forge-token.rekey.keyPrefix = clientsSecrets;
};
homeSopsTemplates.authinfo = {
content = ''
machine ${globals.services.radicale.domain} login ${radicaleUser} password ${confLib.getConfig.sops.placeholder.emacs-radicale-pw}
'';
path = "${homeDir}/.emacs.d/.authinfo";
};
};
services.emacs = {
enable = true;
socketActivation.enable = false;
startWithUserSession = "graphical";
};
programs.emacs = {
enable = true;
package = pkgs.emacs-igc-pgtk;
};
home = {
activation.setupEmacsOrgFiles = lib.hm.dag.entryAfter [ "writeBoundary" ] ''
if [ ! -d ${homeDir}/Org ]; then
install -d -m 0755 -g syncthing ${homeDir}/Org
fi
# the old mtime lets syncthing keep the synced copy and rename this one to a sync-conflict
for file in Tasks Archive Journal; do
if [ ! -f ${homeDir}/Org/$file.org ]; then
touch -t 197001010000.00 ${homeDir}/Org/$file.org
chgrp syncthing ${homeDir}/Org/$file.org
fi
find ${homeDir}/Org -maxdepth 1 -empty -name "$file.sync-conflict-*.org" -delete
done
'';
file = {
".emacs.d/early-init.el".text = lib.mkBefore ";;; early-init.el --- -*- lexical-binding: t; -*-\n";
".emacs.d/init.el".text = lib.mkBefore ";;; init.el --- -*- lexical-binding: t; -*-\n";
};
};
};
};
}
4.4.2.20. Glide
4.4.2.20.1. Main Config
Oh boy, it has been a while since I was THIS excited about a program.
Remember the good times of vimperator and pentadactly? When Firefox increased their security around Web Extensions, those add-ons were practically killed. Still, we had tridactyl to make up for some of the lost functionality. However, it never did the same thing in the end, as tridactyl could only start working once a page and its frames were fully loaded. This yielded a delay in usage that I always disliked.
Also, there were other projects like Vieb, conkeror, qutebrowser, and nyxt, but they all faced some sort of problem:
- Vieb is chromium-based and does not really support extensions
- conkeror has not been updated in years and does not support extensions
- qutebrowser and nyxt do not support extensions
Enter Glide; this crazy thing not only brings back full keyboard functionality at all times, it also allows you to use TypeScript to customize most aspects of the browser! In many ways, you could say it is the Emacs of browsers :) my only gripe here I guess is that I am not the biggest fan of TypeScript (as opposed of the beauty of Common Lisp used by nyxt <3), but that is nagging on a very high level!
In of itself, Glide (for some reason) does not support many of the (in my eyes) most useful keybindings of tridactyl, that being o, t, and b as well as the vimperator-reflow find mechanic. I recreated those here for that reason, Also, I was able to integrate my userChrome.css directly into the Glide config, for the reasons stated above :) also, it allowed me to not having to use Stylus anymore, as I, again, was able to embed the needed CSS directly in the Glide config.
{
flake-file.inputs.glide-nix = {
inputs = {
home-manager.follows = "home-manager";
nixpkgs.follows = "nixpkgs";
};
url = "github:glide-browser/glide.nix";
};
flake.modules.homeManager.glide =
{
root,
config,
lib,
pkgs,
globals,
...
}:
let
nixIcon = "${pkgs.nixos-icons}/share/icons/hicolor/scalable/apps/nix-snowflake.svg";
oneDayMs = 24 * 60 * 60 * 1000;
profile = rec {
extensions = {
packages =
with pkgs.nur.repos.rycee.firefox-addons;
[
tampermonkey
clearurls
darkreader
istilldontcareaboutcookies
translate-web-pages
ublock-origin
reddit-enhancement-suite
sponsorblock
web-archives
onepassword-password-manager
single-file
widegithub
enhanced-github
don-t-fuck-with-paste
redirector
readeck
yubal
]
++ lib.optional config.programs.password-store.enable browserpass;
settings =
lib.optionalAttrs config.programs.password-store.enable {
"browserpass@maximbaz.com" = {
force = true;
settings.stores.default = {
id = "default";
name = "default";
path = config.programs.password-store.settings.PASSWORD_STORE_DIR;
};
};
}
// {
"addon@darkreader.org" = {
force = true;
settings = {
automation = {
behavior = "OnOff";
enabled = false;
mode = "";
};
changeBrowserTheme = false;
detectDarkTheme = true;
disabledFor = [ "github.com" ];
enableContextMenus = false;
enableForPDF = true;
enableForProtectedPages = false;
enabled = true;
enabledByDefault = true;
enabledFor = [ ];
fetchNews = true;
schemeVersion = 2;
syncSettings = false;
syncSitesFixes = false;
theme = {
brightness = 100;
contrast = 100;
darkColorScheme = "Default";
darkSchemeBackgroundColor = "#181a1b";
darkSchemeTextColor = "#e8e6e3";
engine = "dynamicTheme";
fontFamily = "Open Sans";
grayscale = 0;
immediateModify = false;
lightColorScheme = "Default";
lightSchemeBackgroundColor = "#dcdad7";
lightSchemeTextColor = "#181a1b";
mode = 1;
scrollbarColor = "";
selectionColor = "auto";
sepia = 0;
styleSystemControls = false;
stylesheet = "";
textStroke = 0;
useFont = false;
};
time = {
activation = "18:00";
deactivation = "9:00";
};
};
};
"redirector@einaregilsson.com" = {
force = true;
settings = {
disabled = false;
enableNotifications = false;
redirects =
map
(
r:
r
// {
appliesTo = [ "main_frame" ];
disabled = false;
error = null;
excludePattern = "";
grouped = false;
patternDesc = "";
patternType = "R";
processMatches = "noProcessing";
}
)
[
{
description = "Youtube";
exampleResult = "https://${globals.services.invidious.domain}/watch?v=9szhjhO9epA";
exampleUrl = "https://www.youtube.com/watch?v=9szhjhO9epA";
includePattern = ''(.*\.)?youtube\.com/(.*)'';
redirectUrl = "https://${globals.services.invidious.domain}/$2";
}
{
description = "Youtu.be";
exampleResult = "https://${globals.services.invidious.domain}/watch?v=9szhjhO9epA";
exampleUrl = "https://www.youtu.be/watch?v=9szhjhO9epA";
includePattern = ''(.*\.)?youtu\.be/(.*)'';
redirectUrl = "https://${globals.services.invidious.domain}/$2";
}
{
description = "Reddit";
exampleResult = "https://old.reddit.com/r/NixOS";
exampleUrl = "https://www.reddit.com/r/NixOS";
includePattern = ''(.*\.)?reddit\.com/(.*)'';
redirectUrl = "https://old.reddit.com/$2";
}
{
description = "Redd.it";
exampleResult = "https://old.reddit.com/r/NixOS";
exampleUrl = "https://redd.it/r/NixOS";
includePattern = ''(.*\.)?redd\.it/(.*)'';
redirectUrl = "https://old.reddit.com/$2";
}
];
};
};
"uBlock0@raymondhill.net" = {
force = true;
settings = rec {
cloudStorageEnabled = false;
externalLists = lib.concatStringsSep "\n" importedLists;
importedLists = [
"https://filters.adtidy.org/extension/ublock/filters/3.txt"
"https://github.com/DandelionSprout/adfilt/raw/master/LegitimateURLShortener.txt"
];
selectedFilterLists = [
"user-filters"
"DEU-0"
"adguard-generic"
"adguard-annoyance"
"adguard-social"
"adguard-spyware-url"
"easylist"
"easyprivacy"
"https://github.com/DandelionSprout/adfilt/raw/master/LegitimateURLShortener.txt"
"plowe-0"
"ublock-abuse"
"ublock-badware"
"ublock-filters"
"ublock-privacy"
"ublock-quick-fixes"
"ublock-unbreak"
"urlhaus-1"
];
uiAccentCustom = true;
uiAccentCustom0 = config.lib.stylix.colors.withHashtag.base0C;
uiTheme = "dark";
};
};
};
};
search = {
# default = "Kagi";
default = "SearXNG";
engines = {
"Confluence search" = {
definedAliases = [
"@c"
"@cf"
"@confluence"
];
urls = [
{
params = [
{
name = "text";
value = "{searchTerms}";
}
];
template = "https://vbc.atlassian.net/wiki/search";
}
];
};
"Home Manager Options" = {
definedAliases = [
"@hm"
"@ho"
"@hmo"
];
icon = nixIcon;
urls = [
{
params = [
{
name = "query";
value = "{searchTerms}";
}
];
template = "https://home-manager-options.extranix.com/";
}
];
};
"Jira search" = {
definedAliases = [
"@j"
"@jire"
];
urls = [
{
params = [
{
name = "jql";
value = "textfields ~ \"{searchTerms}*\"&wildcardFlag=true";
}
];
template = "https://vbc.atlassian.net/issues/";
}
];
};
Kagi = {
definedAliases = [ "@k" ];
icon = "https://kagi.com/favicon.ico";
updateInterval = oneDayMs;
urls = [
{
params = [
{
name = "q";
value = "{searchTerms}";
}
];
template = "https://kagi.com/search";
}
];
};
"Nix Packages" = {
definedAliases = [ "@np" ];
icon = nixIcon;
urls = [
{
params = [
{
name = "type";
value = "packages";
}
{
name = "query";
value = "{searchTerms}";
}
];
template = "https://search.nixos.org/packages";
}
];
};
"NixOS Options" = {
definedAliases = [ "@no" ];
icon = nixIcon;
urls = [
{
params = [
{
name = "query";
value = "{searchTerms}";
}
];
template = "https://search.nixos.org/options";
}
];
};
"NixOS Wiki" = {
definedAliases = [ "@nw" ];
icon = "https://nixos.wiki/favicon.png";
updateInterval = oneDayMs;
urls = [
{
template = "https://nixos.wiki/index.php?search={searchTerms}";
}
];
};
SearXNG = {
definedAliases = [ "@sx" ];
icon = "https://${globals.services.searx.domain}/favicon.ico";
updateInterval = oneDayMs;
urls = [
{
params = [
{
name = "q";
value = "{searchTerms}";
}
];
template = "https://${globals.services.searx.domain}/search";
}
];
};
bing.metaData.hidden = true;
ddg.metaData.hidden = true;
ecosia.metaData.hidden = true;
github = {
definedAliases = [ "@gh" ];
icon = "https://github.com/favicon.ico";
name = "GitHub";
updateInterval = oneDayMs;
urls = [
{
params = [
{
name = "q";
value = "{searchTerms}";
}
];
template = "https://github.com/search";
}
];
};
google = {
definedAliases = [ "@g" ];
icon = "https://www.google.com/favicon.ico";
name = "Google";
urls = [
{
params = [
{
name = "q";
value = "{searchTerms}";
}
];
template = "https://www.google.com/search";
}
];
};
perplexity.metaData.hidden = true;
wikipedia.metaData.hidden = true;
youtube = {
definedAliases = [ "@yt" ];
icon = "https://www.youtube.com/favicon.ico";
name = "YouTube";
updateInterval = oneDayMs;
urls = [
{
params = [
{
name = "search_query";
value = "{searchTerms}";
}
];
template = "https://www.youtube.com/results";
}
];
};
};
force = true; # this is required because otherwise the search.json.mozlz4 symlink gets replaced on every firefox restart
# privateDefault = "Kagi";
privateDefault = "google";
};
settings = {
"browser.bookmarks.showMobileBookmarks" = true;
"browser.download.open_pdf_attachments_inline" = false;
"browser.newtabpage.activity-stream.feeds.section.topstories" = false;
"browser.newtabpage.activity-stream.section.highlights.includeBookmarks" = false;
"browser.newtabpage.activity-stream.section.highlights.includeDownloads" = false;
"browser.newtabpage.activity-stream.section.highlights.includeVisited" = false;
"browser.newtabpage.activity-stream.showSponsored" = false;
"browser.newtabpage.activity-stream.showSponsoredTopSites" = false;
"browser.newtabpage.activity-stream.system.showSponsored" = false;
"browser.profiles.enabled" = false;
"browser.search.suggest.enabled" = false;
"browser.search.suggest.enabled.private" = false;
"browser.toolbars.bookmarks.visibility" = "never";
"browser.topsites.contile.enabled" = false;
"browser.uiCustomization.state" = builtins.toJSON {
currentVersion = 24;
dirtyAreaCache = [
"unified-extensions-area"
"nav-bar"
"vertical-tabs"
"toolbar-menubar"
"TabsToolbar"
"PersonalToolbar"
];
newElementCount = 14;
placements = {
PersonalToolbar = [ ];
TabsToolbar = [
"firefox-view-button"
"tabbrowser-tabs"
"new-tab-button"
"alltabs-button"
];
nav-bar = [
"personal-bookmarks"
"back-button"
"forward-button"
"stop-reload-button"
"urlbar-container"
"downloads-button"
"privatebrowsing-button"
"developer-button"
"vertical-spacer"
"reset-pbm-toolbar-button"
"_73a6fe31-595d-460b-a920-fcc0f8843232_-browser-action"
"_3c078156-979c-498b-8990-85f7987dd929_-browser-action"
"customizableui-special-spring14"
"ublock0_raymondhill_net-browser-action"
"addon_darkreader_org-browser-action"
"browserpass_maximbaz_com-browser-action"
"_d634138d-c276-4fc8-924b-40a0ea21d284_-browser-action"
"redirector_einaregilsson_com-browser-action"
"unified-extensions-button"
];
toolbar-menubar = [ "menubar-items" ];
unified-extensions-area = [
"sponsorblocker_ajay_app-browser-action"
"dontfuckwithpaste_raim_ist-browser-action"
"_72742915-c83b-4485-9023-b55dc5a1e730_-browser-action"
"_72bd91c9-3dc5-40a8-9b10-dec633c0873f_-browser-action"
"_f209234a-76f0-4735-9920-eb62507a54cd_-browser-action"
"idcac-pub_guus_ninja-browser-action"
"firefox_tampermonkey_net-browser-action"
"_74145f27-f039-47ce-a470-a662b129930a_-browser-action"
"_036a55b4-5e72-4d05-a06c-cba2dfcc134a_-browser-action"
"_d07ccf11-c0cd-4938-a265-2a4d6ad01189_-browser-action"
"_531906d3-e22f-4a6c-a102-8057b88a1a63_-browser-action"
"kde-connect_0xc0dedbad_com-browser-action"
];
vertical-tabs = [ ];
widget-overflow-fixed-list = [ ];
};
seen = [
"reset-pbm-toolbar-button"
"dontfuckwithpaste_raim_ist-browser-action"
"redirector_einaregilsson_com-browser-action"
"_72742915-c83b-4485-9023-b55dc5a1e730_-browser-action"
"_72bd91c9-3dc5-40a8-9b10-dec633c0873f_-browser-action"
"_f209234a-76f0-4735-9920-eb62507a54cd_-browser-action"
"browserpass_maximbaz_com-browser-action"
"addon_darkreader_org-browser-action"
"idcac-pub_guus_ninja-browser-action"
"firefox_tampermonkey_net-browser-action"
"_74145f27-f039-47ce-a470-a662b129930a_-browser-action"
"_d634138d-c276-4fc8-924b-40a0ea21d284_-browser-action"
"_73a6fe31-595d-460b-a920-fcc0f8843232_-browser-action"
"_036a55b4-5e72-4d05-a06c-cba2dfcc134a_-browser-action"
"sponsorblocker_ajay_app-browser-action"
"_d07ccf11-c0cd-4938-a265-2a4d6ad01189_-browser-action"
"ublock0_raymondhill_net-browser-action"
"_3c078156-979c-498b-8990-85f7987dd929_-browser-action"
"_531906d3-e22f-4a6c-a102-8057b88a1a63_-browser-action"
"developer-button"
"kde-connect_0xc0dedbad_com-browser-action"
];
};
"browser.urlbar.showSearchSuggestionsFirst" = false;
"browser.urlbar.suggest.quicksuggest.nonsponsored" = false;
"browser.urlbar.suggest.quicksuggest.sponsored" = false;
"browser.urlbar.suggest.searches" = false;
"extensions.autoDisableScopes" = 0;
"identity.sync.tokenserver.uri" =
"https://${globals.services.firefox-syncserver.domain}/1.0/sync/1.5";
}
// lib.mapAttrs' (
id: _: lib.nameValuePair "extensions.webextensions.ExtensionStorageIDB.migrated.${id}" false
) extensions.settings;
};
in
{
config = {
swarselsystems.enabledHomeModules = [ "glide" ];
programs = {
glide-browser = {
config = lib.mkBefore ''
/// <reference types="./glide.d.ts" />
glide.o.hint_size = "16px";
glide.o.hint_label_generator = glide.hints.label_generators.numeric;
glide.o.keymaps_use_physical_layout = "force";
glide.o.yank_highlight = "${config.lib.stylix.colors.withHashtag.base09}";
'';
enable = true;
nativeMessagingHosts = lib.optionals config.programs.password-store.enable [ pkgs.browserpass ];
policies = {
AppAutoUpdate = false;
BackgroundAppUpdate = false;
Bookmarks = lib.concatLists (
lib.mapAttrsToList (
_: service:
lib.mapAttrsToList (title: path: {
Folder = "S";
Placement = "toolbar";
Title = title;
URL = "https://${service.domain}${path}";
}) service.webPaths
) (lib.filterAttrs (_: service: service.hasWebInterface && service.domain != "") globals.services)
);
Certificates = {
ImportEnterpriseRoots = true;
Install = [ (root "files/public/certs/ca.crt") ];
};
DisableBuiltinPDFViewer = true;
DisableFirefoxAccounts = false;
DisableFirefoxScreenshots = true;
DisableFirefoxStudies = true;
DisableMasterPasswordCreation = true;
DisableProfileImport = true;
DisableProfileRefresh = true;
DisableTelemetry = true;
DontCheckDefaultBrowser = true;
EnableTrackingProtection = {
Cryptomining = true;
EmailTracking = true;
Fingerprinting = true;
Locked = true;
Value = true;
};
ExtensionUpdate = false;
FirefoxHome = {
Highlights = true;
Locked = true;
Search = true;
SponsoredTopSites = false;
TopSites = true;
};
FirefoxSuggest = {
ImproveSuggest = false;
Locked = true;
SponsoredSuggestions = false;
WebSuggestions = false;
};
Handlers = {
extensions.pdf = {
action = "useHelperApp";
ask = true;
handlers = [
{
name = "GNOME Document Viewer";
path = "${pkgs.evince}/bin/evince";
}
];
};
mimeTypes."application/pdf".action = "saveToDisk";
};
NoDefaultBookmarks = true;
OfferToSaveLogins = false;
PDFjs = {
EnablePermissions = false;
Enabled = false;
};
PasswordManagerEnabled = false;
SanitizeOnShutdown = {
Cache = true;
Cookies = false;
Downloads = true;
FormData = true;
History = false;
Locked = true;
OfflineApps = true;
Sessions = false;
SiteSettings = false;
};
SearchEngines.PreventInstalls = true;
UserMessaging = {
ExtensionRecommendations = false;
FeatureRecommendations = false;
Locked = true;
MoreFromMozilla = false;
SkipOnboarding = true;
UrlbarInterventions = false;
WhatsNew = false;
};
};
profiles.default = lib.recursiveUpdate profile {
id = 0;
isDefault = true;
settings = {
"browser.sessionstore.max_resumed_crashes" = 0;
"browser.sessionstore.resume_from_crash" = false;
"browser.startup.homepage" = "https://lobste.rs";
"browser.startup.page" = 1;
};
};
};
zsh.sessionVariables.MOZ_DISABLE_RDD_SANDBOX = "1";
};
_module.args.glideProfile = profile;
home.activation.extensionSyncStorage =
let
invidiousInstances = [
"yewtu.be"
globals.services.invidious.domain
];
sponsorblockGrant = ''."sponsorBlocker@ajay.app" |= {permissions: [], data_collection: []} + . + {origins: ((.origins // []) + ${
builtins.toJSON (
lib.concatMap (i: [
"https://*.${i}/*"
"http://*.${i}/*"
]) invidiousInstances
)
} | unique)}'';
in
lib.hm.dag.entryAfter [ "writeBoundary" ] ''
profileDir="$HOME/.config/glide/glide/default"
prefs="$profileDir/extension-preferences.json"
if [ ! -f "$profileDir/storage-sync-v2.sqlite" ]; then
verboseEcho "extension sync storage does not exist yet, skipping"
elif ${pkgs.procps}/bin/pgrep -x .glide-wrapped > /dev/null; then
warnEcho "glide is running, skipping the extension sync storage update"
else
${lib.concatMapAttrsStringSep "\n"
(id: file: ''
run ${pkgs.sqlite}/bin/sqlite3 "$profileDir/storage-sync-v2.sqlite" \
"INSERT INTO storage_sync_data(ext_id, data) VALUES('${id}', json(readfile('${file}'))) ON CONFLICT(ext_id) DO UPDATE SET data = json_patch(data, json(readfile('${file}'))), sync_change_counter = sync_change_counter + 1;" \
|| warnEcho "failed to update the sync storage of ${id}"
'')
(
lib.mapAttrs (id: data: pkgs.writeText "${id}-sync-storage.json" (builtins.toJSON data)) {
"sponsorBlocker@ajay.app" = {
inherit invidiousInstances;
categorySelections = [
{
name = "sponsor";
option = 2;
}
{
name = "poi_highlight";
option = 1;
}
{
name = "exclusive_access";
option = 0;
}
{
name = "selfpromo";
option = 2;
}
{
name = "chapter";
option = 0;
}
];
supportInvidious = true;
};
"yubal@guillevc.xyz".yubalUrl = "https://${globals.services.yubal.domain}";
}
)
}
if [ -f "$prefs" ]; then
run sh -c '${lib.getExe pkgs.jq} --indent 1 "$1" "$2" > "$2.tmp" && mv "$2.tmp" "$2"' _ ${lib.escapeShellArg sponsorblockGrant} "$prefs" \
|| warnEcho "failed to grant sponsorblock its invidious origins"
fi
fi
'';
};
};
}
4.4.2.20.2. Containers
{
flake.modules.homeManager.glide.programs.glide-browser.config = ''
const container_rules: { prefix: string; container: string }[] = [];
const container_stores: Record<string, string> = {};
const container_names: Record<string, string> = {};
function match_rule(url: string) {
let best: { prefix: string; container: string } | null = null;
for (const r of container_rules) {
if (url.startsWith(r.prefix) && (best == null || r.prefix.length > best.prefix.length)) {
best = r;
}
}
return best;
}
async function refresh_container_stores() {
for (const identity of await browser.contextualIdentities.query({})) {
container_stores[identity.name] = identity.cookieStoreId;
container_names[identity.cookieStoreId] = identity.name;
}
}
const reopening = new Set<number>();
const placed = new Map<number, string>();
async function ensure_container(tab_id: number, url: string) {
const rule = match_rule(url);
if (!rule || reopening.has(tab_id) || placed.get(tab_id) === rule.container) {
return;
}
reopening.add(tab_id);
try {
if (container_stores[rule.container] == null) {
await refresh_container_stores();
}
const target = container_stores[rule.container];
if (target == null) {
return;
}
const tab = await browser.tabs.get(tab_id).catch(() => null);
if (tab == null) {
return;
}
if (tab.incognito || tab.cookieStoreId === target) {
placed.set(tab_id, rule.container);
return;
}
const created = await browser.tabs.create({
cookieStoreId: target,
url,
active: tab.active,
windowId: tab.windowId,
index: tab.index + 1,
});
if (created.id != null) {
placed.set(created.id, rule.container);
}
await browser.tabs.remove(tab_id);
} finally {
reopening.delete(tab_id);
}
}
glide.autocmds.create("ConfigLoaded", async () => {
browser.webRequest.onBeforeRequest.addListener(
(details) => {
if (details.tabId >= 0 && match_rule(details.url)) {
void ensure_container(details.tabId, details.url);
}
},
{ urls: ["<all_urls>"], types: ["main_frame"] },
);
browser.tabs.onRemoved.addListener((tab_id) => placed.delete(tab_id));
browser.contextualIdentities.onCreated.addListener(() => void refresh_container_stores());
await refresh_container_stores();
for (const tab of await browser.tabs.query({})) {
if (tab.id != null && tab.url != null) {
await ensure_container(tab.id, tab.url);
}
}
});
glide.autocmds.create("UrlEnter", /^https?:/, ({ url, tab_id }) => {
void ensure_container(tab_id, url);
});
glide.keymaps.set("normal", "<leader>c", async () => {
const identities = await browser.contextualIdentities.query({});
if (identities.length === 0) {
flash_message("no containers defined");
return;
}
const [current] = await browser.tabs.query({ active: true, currentWindow: true });
if (current?.incognito) {
flash_message("containers unavailable in private windows");
return;
}
const url = current?.url?.startsWith("http") ? current.url : undefined;
await glide.commandline.show({
title: "Open in container",
options: identities.map((identity) => ({
label: identity.name,
description: (url ? "open current page as " : "open new tab as ") + identity.name,
execute: async () => {
await browser.tabs.create({ cookieStoreId: identity.cookieStoreId, url });
},
})),
});
}, { description: "Open the current page in a container tab" });
'';
}
4.4.2.20.3. Findbar
{
flake.modules.homeManager.glide.programs.glide-browser.config = ''
function enforce_input_mode() {
if (glide.ctx.mode === "normal" && glide.findbar.is_focused()) {
void glide.excmds.execute("mode_change insert");
}
}
glide.autocmds.create("ModeChanged", "*:normal", enforce_input_mode);
let enforce_timer: ReturnType<typeof setInterval> | null = null;
function stop_enforce_polling() {
if (enforce_timer != null) {
clearInterval(enforce_timer);
enforce_timer = null;
}
}
function start_enforce_polling() {
if (enforce_timer != null) {
return;
}
enforce_timer = setInterval(() => {
if (!glide.findbar.is_open()) {
stop_enforce_polling();
return;
}
enforce_input_mode();
}, 100);
}
async function open_findbar() {
await glide.findbar.open({ query: "" });
start_enforce_polling();
}
glide.keymaps.set("normal", "/", open_findbar);
glide.keymaps.set("normal", "?", open_findbar);
glide.keymaps.set("normal", "n", async () => {
await glide.findbar.next_match();
start_enforce_polling();
});
glide.keymaps.set("normal", "N", async () => {
await glide.findbar.previous_match();
start_enforce_polling();
});
glide.keymaps.set(["insert", "normal", "visual", "op-pending"], "<Esc>", async () => {
rapidfire = false;
if (glide.findbar.is_open()) {
await glide.findbar.close();
}
await glide.excmds.execute("blur");
await glide.excmds.execute("mode_change normal");
});
glide.keymaps.set("command", "<Esc>", () => void glide.commandline.close());
'';
}
4.4.2.20.4. site-specific hint-selectors
{
flake-file.inputs.hint-selectors = {
inputs = {
flake-parts.follows = "flake-parts";
nixpkgs.follows = "nixpkgs";
pedantix.follows = "pedantix";
systems.follows = "systems";
treefmt-nix.follows = "treefmt-nix";
};
url = "github:Swarsel/hint-selectors";
};
flake.modules.homeManager.glide =
{
inputs,
lib,
pkgs,
...
}:
{
programs.glide-browser.config = ''
glide.autocmds.create("UrlEnter", /https?:\/\/www\.google\.com/, () => {
glide.buf.keymaps.set("normal", "gi", async () => {
await glide.excmds.execute("focusinput last");
await glide.excmds.execute("caret_move endline");
});
});
''
+ lib.optionalString (inputs ? hint-selectors) ''
glide.include("hint-selectors.glide.ts").then(() =>
glide.g.hint_selectors!.setup({
keys: { primary: "c" },
hint: start_hints,
extra: {
"vbc.atlassian.net": [
{
match: ["*://vbc.atlassian.net/wiki*"],
sets: {
primary: `[class="_1reo15vq _18m915vq _1bto1l2s _kqswh2mm _o5721q9c _syaz1fxt"], [class="_11c81ixg _1reo15vq _18m915vq _18s81b66 _kqswh2mm _k48p1wq8 _o5721q9c _1bto1l2s _u5f31b66"], [class="_1r04ze3t _kqswstnw"], [class="css-a61etj"], [class="jira-macro-table-underline-pdfexport"]`,
},
},
],
},
}),
);
'';
xdg.configFile = lib.mkIf (inputs ? hint-selectors) {
"glide/hint-selectors.glide.ts".source =
inputs.hint-selectors.packages.${pkgs.stdenv.hostPlatform.system}.glide-integration;
};
};
}
4.4.2.20.5. find mode (hints, vimperator-reflow)
{
flake.modules.homeManager.glide.programs.glide-browser.config = ''
let hint_session = false;
let hint_filter = "";
let hint_texts: string[] = [];
let hint_boxes: glide.Hint[] = [];
let hint_active = 0;
let hint_visible: number[] = [];
let hint_cooldown_until = 0;
let swallowing_keys = false;
async function swallow_keys(ms: number) {
hint_cooldown_until = Date.now() + ms;
if (swallowing_keys) {
return;
}
swallowing_keys = true;
try {
while (true) {
const key = await glide.keys.next();
if (Date.now() >= hint_cooldown_until) {
await glide.keys.send(key);
return;
}
}
} finally {
swallowing_keys = false;
}
}
function hint_label_is_ambiguous(label: string, count: number): boolean {
for (let m = 1; m <= count; m++) {
const s = String(m);
if (s !== label && s.startsWith(label)) {
return true;
}
}
return false;
}
function update_find_display(no_match = false) {
const find_el = document.getElementById("glide-statusline-find");
if (!find_el) {
return;
}
find_el.textContent = hint_session ? "find: " + hint_filter : "";
find_el.classList.toggle("nomatch", hint_session && no_match);
}
function follow_hint(index: number | undefined) {
if (index == null) {
return;
}
hint_session = false;
const label = String(index + 1);
void glide.keys
.send(hint_label_is_ambiguous(label, hint_texts.length) ? label + "<Enter>" : label)
.then(() => swallow_keys(500));
}
function apply_hint_filter(reset_active = true) {
const container = document.getElementById("glide-hints-container");
if (!container) {
return;
}
hint_visible = [];
for (let i = 0; i < container.children.length; i++) {
if ((hint_texts[i] ?? "").includes(hint_filter)) {
hint_visible.push(i);
}
}
if (reset_active || hint_visible.length === 0) {
hint_active = 0;
} else {
hint_active = ((hint_active % hint_visible.length) + hint_visible.length) % hint_visible.length;
}
const visible = new Set(hint_visible);
const active_index = hint_visible[hint_active];
for (let i = 0; i < container.children.length; i++) {
const marker = container.children[i] as HTMLElement;
const active = i === active_index;
const outline_box = hint_filter.length === 0 && (hint_texts[i] ?? "").trim() ? hint_boxes[i] : undefined;
marker.style.display = visible.has(i) ? "" : "none";
marker.classList.toggle("glide-hint-outline", outline_box != null);
marker.style.width = outline_box ? `''${outline_box.width}px` : "";
marker.style.height = outline_box ? `''${outline_box.height}px` : "";
marker.style.borderColor = active && outline_box ? "var(--base0B)" : "";
marker.style.background = active && !outline_box ? "var(--base0B)" : "";
marker.style.color = active ? "var(--base00)" : "";
marker.style.opacity = active ? "1" : "";
}
update_find_display(hint_filter.length > 0 && hint_visible.length === 0);
if (hint_session && hint_filter.length > 0 && hint_visible.length === 1) {
follow_hint(hint_visible[0]);
}
}
function start_hints({
selector,
include,
action,
pick: filter,
}: {
selector?: string;
include?: string;
action?: glide.HintAction;
pick?: glide.HintPicker;
} = {}) {
hint_session = true;
hint_filter = "";
hint_texts = [];
hint_boxes = [];
hint_active = 0;
hint_visible = [];
update_find_display();
glide.hints.show({
selector,
include,
action,
async pick(props) {
const hints = filter ? await filter(props) : props.hints;
const texts = await props.content.map((target) => (target.textContent ?? "").toLowerCase());
hint_texts = hints.map((hint) => texts[props.hints.indexOf(hint)] ?? "");
hint_boxes = hints;
setTimeout(() => apply_hint_filter(), 0);
return hints;
},
});
}
glide.keymaps.set("normal", "c", () => start_hints());
glide.keymaps.set("normal", "f", () => start_hints());
glide.keymaps.set("normal", "F", () =>
start_hints({
action: async ({ content }) => {
const href = await content.execute((target) => {
target.focus();
const link = (target as HTMLAnchorElement).href;
if (typeof link === "string" && link !== "") {
return link;
}
target.click();
return null;
});
if (href == null) {
return;
}
const current = await glide.tabs.active();
await browser.tabs.create({
url: href,
active: false,
cookieStoreId: current.cookieStoreId,
openerTabId: current.id,
windowId: current.windowId,
});
},
}), { description: "Open a link in a background tab using hints" });
for (const ch of "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-:./_,;!?@#%^&*()+=[]{}~'\"$") {
glide.keymaps.set("hint", ch, () => {
if (hint_session) {
hint_filter += ch.toLowerCase();
apply_hint_filter();
}
});
}
glide.keymaps.set("hint", "<Space>", () => {
if (hint_session) {
hint_filter += " ";
apply_hint_filter();
}
});
glide.keymaps.set("hint", "\\", async () => {
if (!hint_session) {
return;
}
const ch = await glide.keys.next_str();
if (ch.length === 1) {
hint_filter += ch.toLowerCase();
apply_hint_filter();
}
});
glide.keymaps.set("hint", "<Enter>", () => {
if (hint_session && hint_visible.length > 0) {
follow_hint(hint_visible[hint_active]);
}
});
glide.keymaps.set("hint", "<Tab>", () => {
if (hint_session) {
hint_active += 1;
apply_hint_filter(false);
}
});
glide.keymaps.set("hint", "<S-Tab>", () => {
if (hint_session) {
hint_active -= 1;
apply_hint_filter(false);
}
});
glide.keymaps.set("hint", "<BS>", () => {
if (hint_session) {
hint_filter = hint_filter.slice(0, -1);
apply_hint_filter();
}
});
glide.autocmds.create("ModeChanged", "*", ({ new_mode }) => {
if (new_mode !== "hint") {
hint_session = false;
update_find_display();
}
});
'';
}
4.4.2.20.6. Rapidfire hints
This adds a hint mode to glide that directly opens a new hint opener after the last one, for faster navigation
{
flake.modules.homeManager.glide.programs.glide-browser.config = ''
let rapidfire = false;
async function wait_for_page_load() {
await new Promise((resolve) => setTimeout(resolve, 500));
while (rapidfire && (await glide.tabs.active()).status === "loading") {
await new Promise((resolve) => setTimeout(resolve, 100));
}
}
glide.keymaps.set("normal", "q", () => {
rapidfire = true;
start_hints();
});
glide.keymaps.set("hint", "<Esc>", async () => {
rapidfire = false;
await glide.excmds.execute("hints_remove");
});
glide.autocmds.create("ModeChanged", "hint:*", async ({ new_mode }) => {
if (!rapidfire || new_mode === "hint") {
return;
}
await wait_for_page_load();
if (!rapidfire) {
return;
}
if (glide.ctx.mode !== "normal") {
rapidfire = false;
return;
}
start_hints();
});
'';
}
4.4.2.20.7. Ignored sites, ignore-mode
{
flake.modules.homeManager.glide.programs.glide-browser.config = ''
glide.keymaps.set("normal", "<C-Esc>", () => glide.excmds.execute("mode_change ignore"), {
description: "Enter ignore mode",
});
glide.keymaps.set("ignore", "<C-Esc>", () => glide.excmds.execute("mode_change normal"), {
description: "Leave ignore mode",
});
const ignore_mode_sites = [
/https?:\/\/pokerogue\.net/,
/https?:\/\/typelit\.io/,
/https?:\/\/vc-impimba-1\.m\.imp\.ac\.at\/ui\/webconsole/,
];
let ignore_mode_auto = false;
glide.autocmds.create("UrlEnter", /^/, ({ url }) => {
if (ignore_mode_sites.some((pattern) => pattern.test(url))) {
ignore_mode_auto = true;
void glide.excmds.execute("mode_change ignore");
} else if (ignore_mode_auto) {
ignore_mode_auto = false;
if (glide.ctx.mode === "ignore") {
void glide.excmds.execute("mode_change normal");
}
}
});
'';
}
4.4.2.20.8. Invidious CSS
{
flake.modules.homeManager.glide =
{ lib, globals, ... }:
{
programs.glide-browser.config = ''
const invidious_css = css`
body {
max-width: 100% !important;
margin: 0 !important;
padding: 0 !important;
}
.pure-u-md-2-3,
.pure-u-lg-2-3,
.pure-u-md-1-3,
.pure-u-lg-1-3 {
width: 100% !important;
}
#contents,
.pure-g,
.pure-u-md-2-3 > .h-box,
.pure-u-lg-2-3 > .h-box {
max-width: 100% !important;
width: 100% !important;
padding-left: 0 !important;
padding-right: 0 !important;
margin-left: 0 !important;
margin-right: 0 !important;
}
#player-container {
width: 100% !important;
max-width: 100% !important;
aspect-ratio: 16 / 9;
height: auto !important;
padding: 0 !important;
margin: 0 !important;
max-height: 90vh !important;
}
.video-js,
.video-js video,
.video-js .vjs-tech,
#player {
width: 100% !important;
height: 100% !important;
padding-top: 0 !important;
}
#player-container + .h-box,
#player-container + div {
margin-top: 0.5em !important;
padding-top: 0 !important;
}
`;
glide.autocmds.create("UrlEnter", /https:\/\/${
lib.replaceStrings [ "." ] [ "\\." ] globals.services.invidious.domain
}\/watch/, ({ tab_id }) => {
glide.content.execute((css_text) => {
if (!document.getElementById("glide-user-style")) {
const el = document.createElement("style");
el.id = "glide-user-style";
el.textContent = css_text;
document.head.appendChild(el);
}
}, { tab_id, args: [invidious_css] });
});
'';
};
}
4.4.2.20.9. Search engines
{
flake.modules.homeManager.glide =
{ lib, glideProfile, ... }:
let
aliases = lib.concatLists (
lib.mapAttrsToList (
key: engine:
let
url = lib.head engine.urls;
query = lib.concatMapStringsSep "&" (param: "${param.name}=${param.value}") (url.params or [ ]);
in
map (alias: {
keyword = lib.removePrefix "@" alias;
name = engine.name or key;
url = lib.replaceStrings [ "{searchTerms}" ] [ "%s" ] (
url.template + lib.optionalString (query != "") "?${query}"
);
}) (engine.definedAliases or [ ])
) glideProfile.search.engines
);
in
{
programs.glide-browser.config = ''
const engine_keywords = new Map<string, string>(
(${
builtins.toJSON (
map (a: [
a.keyword
a.name
]) aliases
)
} as [string, string][]).flatMap(([kw, name]): [string, string][] => [[kw, name], ["@" + kw, name]]),
);
const search_urls = ${
builtins.toJSON (
map (a: [
a.keyword
a.url
]) aliases
)
} as [string, string][];
function parse_search(args_arr: string[]): { query: string; engine?: string } {
const [first, ...rest] = args_arr;
if (first != null && rest.length > 0 && engine_keywords.has(first)) {
return { query: rest.join(" "), engine: engine_keywords.get(first) };
}
return { query: args_arr.join(" ") };
}
function to_url(input: string): string | null {
if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(input)) {
return input;
}
if (!input.includes(" ") && input.includes(".")) {
return `https://''${input}`;
}
return null;
}
async function active_tab_info() {
const tab = await glide.tabs.active();
return {
id: tab.id,
incognito: tab.incognito,
next_index: tab.index + 1,
store: tab.incognito ? undefined : "firefox-default",
contained: !tab.incognito && tab.cookieStoreId !== "firefox-default",
};
}
async function do_navigate(target: "current" | "tab" | "window", url: string) {
const { id, incognito, next_index, store, contained } = await active_tab_info();
if (target === "window") {
await browser.windows.create({ url, incognito });
} else if (target === "tab" || contained) {
await browser.tabs.create({ url, cookieStoreId: store, index: next_index });
} else {
await browser.tabs.update(id, { url });
}
}
async function do_search(target: "current" | "tab" | "window", search: { query: string; engine?: string }) {
const { id, incognito, next_index, store, contained } = await active_tab_info();
let tab_id: number | undefined = id;
if (target === "window") {
tab_id = (await browser.windows.create({ incognito })).tabs?.[0]?.id;
} else if (target === "tab" || contained) {
tab_id = (await browser.tabs.create({ cookieStoreId: store, index: next_index })).id;
}
if (tab_id != null) {
await browser.search.search({ ...search, tabId: tab_id });
}
}
function resolve_open(input: string): { url: string } | { search: { query: string; engine?: string } } {
const words = input.trim().split(" ").filter(Boolean);
if (words[0] === "search") {
return { search: { query: words.slice(1).join(" ") } };
}
const url = to_url(input.trim());
return url ? { url } : { search: parse_search(words) };
}
async function do_open(target: "current" | "tab" | "window", input: string) {
const resolved = resolve_open(input);
if ("url" in resolved) {
await do_navigate(target, resolved.url);
} else {
await do_search(target, resolved.search);
}
}
glide.excmds.create({ name: "open", description: "Open a URL or search in the current tab" }, ({ args_arr }) => do_open("current", args_arr.join(" ")));
glide.excmds.create({ name: "tabopen", description: "Open a URL or search in a new tab" }, ({ args_arr }) => do_open("tab", args_arr.join(" ")));
glide.excmds.create({ name: "winopen", description: "Open a URL or search in a new window" }, ({ args_arr }) => do_open("window", args_arr.join(" ")));
glide.excmds.create({ name: "search", description: "Search in the current tab" }, ({ args_arr }) => do_search("current", parse_search(args_arr)));
glide.excmds.create({ name: "tabsearch", description: "Search in a new tab" }, ({ args_arr }) => do_search("tab", parse_search(args_arr)));
'';
};
}
4.4.2.20.10. Site shortcuts
{
flake.modules.homeManager.glide = { globals, ... }: {
programs.glide-browser.config = ''
async function tab_or_tabopen(query: string) {
const url = query.includes("://") ? query : `https://''${query}`;
const tabs = await browser.tabs.query({ currentWindow: true });
const existing = tabs.find((t) => t.url != null && t.url.includes(query));
if (existing?.id != null) {
await browser.tabs.update(existing.id, { active: true });
return;
}
const { next_index, store } = await active_tab_info();
const rule = store == null ? null : match_rule(url);
if (rule != null && container_stores[rule.container] == null) {
await refresh_container_stores();
}
const target = rule != null ? container_stores[rule.container] : undefined;
const created = await browser.tabs.create({ url, cookieStoreId: target ?? store, index: next_index });
if (rule != null && target != null && created.id != null) {
placed.set(created.id, rule.container);
}
}
function add_site_shortcuts(shortcuts: Record<string, string>) {
for (const [keys, target] of Object.entries(shortcuts)) {
glide.keymaps.set("normal", keys, () => tab_or_tabopen(target), {
description: `Focus or open ''${target}`,
});
}
}
add_site_shortcuts({
ghc: "github.com/orgs/CLIP-HPC/repositories",
ghd: "github.com/Swarsel/.dotfiles",
ghi: "https://github.com/issues/assigned?q=is%3Aissue%20state%3Aopen%20archived%3Afalse%20(assignee%3A%40me%20OR%20author%3A%40me)%20sort%3Aupdated-desc",
ghni: "github.com/NixOS/nixpkgs/issues",
ghnp: "github.com/NixOS/nixpkgs/pulls",
ghp: "https://github.com/pulls",
ghv: "github.com/orgs/vbc-it/repositories",
gpd: "discourse.nixos.org/",
gpi: "instagram.com",
gpp: "parkour.wien/categories",
gprn: "www.reddit.com/r/NixOS/",
gsF: "${globals.services.freshrss.domain}",
gsG: "${globals.services.forgejo.domain}",
gsK: "${globals.services.kavita.domain}",
gsM: "${globals.services.mealie.domain}",
gsN: "${globals.services.nextcloud.domain}",
gsSh: "${globals.services.shlink.domain}",
gsSl: "${globals.services.slink.domain}",
gsSx: "${globals.services.searx.domain}",
gsSy1: "${globals.services.syncthing-moonside.domain}",
gsSy2: "${globals.services.syncthing-summers-storage.domain}",
gsb: "${globals.services.buildbot.domain}",
gsc: "${globals.services.copyparty.domain}",
gsf: "${globals.services.firefly-iii.domain}",
gsg: "${globals.services.grafana.domain}",
gsh: "${globals.services.homebox.domain}",
gsi: "${globals.services.immich.domain}",
gsj: "${globals.services.jellyfin.domain}",
gsk: "${globals.services.koillection.domain}",
gsm: "${globals.services.microbin.domain}",
gsn: "${globals.services.navidrome.domain}",
gsp: "${globals.services.paperless.domain}",
gss: "${globals.services.shopservatory.domain}",
gst: "${globals.services.transmission.domain}",
gsy: "${globals.services.invidious.domain}",
});
'';
};
}
4.4.2.20.11. Status line
{
flake.modules.homeManager.glide.programs.glide-browser.config = ''
function ensure_statusline() {
if (!document.getElementById("glide-statusline")) {
const profile_name = (glide.path.profile_dir.split("/").pop() ?? "").replace(/^[^.]+\./, "");
(document.body ?? document.documentElement).appendChild(
DOM.create_element("div", {
id: "glide-statusline",
children: [
DOM.create_element("span", {
id: "glide-statusline-profile",
children: profile_name === "default" ? [] : [profile_name],
}),
DOM.create_element("span", { id: "glide-statusline-container" }),
DOM.create_element("span", { id: "glide-statusline-root" }),
DOM.create_element("span", { id: "glide-statusline-mode" }),
DOM.create_element("span", { id: "glide-statusline-tabs" }),
DOM.create_element("span", { id: "glide-statusline-find" }),
DOM.create_element("span", { id: "glide-statusline-msg" }),
],
}),
);
}
void update_tab_count();
void refresh_active_indicators();
}
glide.autocmds.create("WindowLoaded", ensure_statusline);
glide.autocmds.create("ConfigLoaded", () => {
if (document.getElementById("glide-statusline")) {
ensure_statusline();
}
});
glide.styles.add(css`
#glide-statusline {
position: fixed;
right: 0;
bottom: 0;
z-index: 2147483645;
display: flex;
align-items: center;
gap: 1ex;
padding: 0.8ex;
background: var(--base00);
color: var(--base05);
border: 1px solid var(--base03);
border-right: none;
border-bottom: none;
font-family: "Fira Code", monospace;
font-size: 11px;
line-height: 1;
pointer-events: none;
}
#glide-statusline-mode {
color: var(--glide-current-mode-color, var(--base05));
}
#glide-statusline-mode:empty {
display: none;
}
#glide-statusline-profile {
color: var(--base0A);
}
#glide-statusline-profile:empty {
display: none;
}
#glide-statusline-container {
color: var(--base0C);
}
#glide-statusline-container:empty {
display: none;
}
#glide-statusline-root {
color: var(--base0D);
}
#glide-statusline-root:empty {
display: none;
}
#glide-statusline-msg {
color: var(--base09);
}
#glide-statusline-msg:empty {
display: none;
}
#glide-statusline-find {
color: var(--base0B);
font-size: 24pt;
}
#glide-statusline-find:empty {
display: none;
}
#glide-statusline-find.nomatch {
color: var(--base08);
}
#glide-hints-container > * {
opacity: 0.6;
}
#glide-hints-container > .glide-hint-outline {
box-sizing: border-box;
padding: 0;
background: transparent;
border: 2px solid var(--base0E);
box-shadow: none;
}
#glide-hints-container > .glide-hint-outline > span {
visibility: hidden;
}
`, { id: "statusline" });
let flash_timer: ReturnType<typeof setTimeout> | undefined;
function flash_message(msg: string) {
const msg_el = document.getElementById("glide-statusline-msg");
if (!msg_el) {
return;
}
msg_el.textContent = msg;
clearTimeout(flash_timer);
flash_timer = setTimeout(() => {
msg_el.textContent = "";
}, 2000);
}
glide.autocmds.create("ModeChanged", "*", ({ new_mode }) => {
const mode_el = document.getElementById("glide-statusline-mode");
if (mode_el) {
mode_el.textContent = new_mode === "normal" ? "" : new_mode;
}
});
async function update_tab_count() {
const tabs = await browser.tabs.query({ currentWindow: true });
const tabs_el = document.getElementById("glide-statusline-tabs");
if (tabs_el) {
tabs_el.textContent = String(tabs.length);
}
}
function update_container_indicator(store_id?: string) {
const container_el = document.getElementById("glide-statusline-container");
if (!container_el) {
return;
}
container_el.textContent = store_id != null && store_id !== "firefox-default" ? (container_names[store_id] ?? "") : "";
}
async function refresh_active_indicators() {
const win = await browser.windows.getLastFocused({ populate: true });
const active = win.tabs?.find((t) => t.active);
update_container_indicator(active?.cookieStoreId);
update_root_indicator(active?.id);
}
let root_indicator_timer: ReturnType<typeof setTimeout> | undefined;
function update_root_indicator(tab_id?: number) {
clearTimeout(root_indicator_timer);
root_indicator_timer = setTimeout(() => void update_root_indicator_now(tab_id), 100);
}
const tab_histories = new Map<number, { urls: string[]; index: number; key: string }>();
async function entry_key(tab_id: number, url: string) {
return await glide.content.execute(
(url: string) => (window.navigation.entries().findLast((e) => e.url === url) ?? window.navigation.currentEntry)?.key ?? "",
{ tab_id, args: [url] },
).catch(() => "");
}
async function track_navigation(details: { tabId: number; frameId: number; url: string; transitionType: string; transitionQualifiers: string[] }, same_document: boolean) {
if (details.frameId !== 0 || details.transitionType === "reload") {
return;
}
const key = await entry_key(details.tabId, details.url);
let entry = tab_histories.get(details.tabId);
if (entry == null) {
const length = await glide.content.execute(() => history.length, { tab_id: details.tabId }).catch(() => 1);
entry = { urls: [], index: length - 1, key };
entry.urls[entry.index] = details.url;
tab_histories.set(details.tabId, entry);
} else if (details.transitionQualifiers.includes("forward_back")) {
entry.index += entry.urls[entry.index + 1] === details.url ? 1 : -1;
} else if (same_document && key === entry.key) {
entry.urls[entry.index] = details.url;
} else {
entry.urls = [...entry.urls.slice(0, entry.index + 1), details.url];
entry.index += 1;
}
entry.key = key;
const tab = await browser.tabs.get(details.tabId);
if (tab.active) {
update_root_indicator(details.tabId);
}
}
async function update_root_indicator_now(tab_id?: number) {
const root_el = document.getElementById("glide-statusline-root");
if (window.closed || !root_el) {
return;
}
if (tab_id == null) {
root_el.textContent = "";
return;
}
const entry = tab_histories.get(tab_id);
const at_root = entry != null ? entry.index <= 0 : await glide.content.execute(() => history.length <= 1, { tab_id }).catch(() => true);
root_el.textContent = at_root ? "/" : "";
}
glide.autocmds.create("ConfigLoaded", () => {
browser.tabs.onCreated.addListener((tab) => {
if (tab.id != null && (tab.url === "about:newtab" || tab.url === "about:home")) {
tab_histories.set(tab.id, { urls: [], index: -1, key: "" });
}
void update_tab_count();
});
browser.tabs.onRemoved.addListener((tab_id) => {
tab_histories.delete(tab_id);
void update_tab_count();
});
browser.tabs.onActivated.addListener(async (info) => {
update_root_indicator(info.tabId);
const tab = await browser.tabs.get(info.tabId).catch(() => null);
update_container_indicator(tab?.cookieStoreId);
});
browser.tabs.onUpdated.addListener((_tab_id, change, tab) => {
if (!tab.active || change.url == null) {
return;
}
update_container_indicator(tab.cookieStoreId);
});
browser.windows.onFocusChanged.addListener(() => {
void refresh_active_indicators();
});
browser.webNavigation.onCommitted.addListener((details) => void track_navigation(details, false));
browser.webNavigation.onHistoryStateUpdated.addListener((details) => void track_navigation(details, true));
browser.webNavigation.onReferenceFragmentUpdated.addListener((details) => void track_navigation(details, true));
});
'';
}
4.4.2.20.12. General keybindings
{
flake.modules.homeManager.glide.programs.glide-browser.config = ''
glide.keymaps.set("normal", "b", "commandline_show tab ");
glide.keymaps.set("normal", "gt", "tab_next");
glide.keymaps.set("normal", "gT", "tab_prev");
glide.keymaps.set("normal", "u", async () => {
const [session] = await browser.sessions.getRecentlyClosed();
const closed = session?.tab ?? session?.window;
if (closed?.sessionId != null) {
await browser.sessions.restore(closed.sessionId);
}
}, { description: "Restore the most recently closed tab or window" });
glide.keymaps.set("normal", "U", async () => {
const session = (await browser.sessions.getRecentlyClosed()).find((s) => s.window != null);
if (session?.window?.sessionId != null) {
await browser.sessions.restore(session.window.sessionId);
}
}, { description: "Restore the most recently closed window" });
for (const [key, target] of [["p", "current"], ["P", "tab"]] as const) {
glide.keymaps.set("normal", key, async () => {
const text = (await navigator.clipboard.readText()).trim();
if (text) {
await do_open(target, text);
}
}, { description: "Open the clipboard contents" + (target === "tab" ? " in a new tab" : "") });
}
async function yank_url(url: string) {
const decoded = decode_url_for_display(url);
await navigator.clipboard.writeText(decoded);
flash_message("yanked " + decoded);
}
glide.keymaps.set("normal", "yy", async () => {
const tab = await glide.tabs.active();
await yank_url(tab.url ?? "");
}, { description: "Yank the URL of the current tab" });
glide.keymaps.set("normal", "yf", () =>
start_hints({
selector: "a[href]",
action: async ({ content }) => {
const href = await content.execute((target) => (target as HTMLAnchorElement).href);
if (href) {
await yank_url(href);
}
},
}), { description: "Yank a link URL using find hints" });
async function scroll_lines(lines: number) {
await glide.content.execute((lines: number) => {
const line_height = (element: Element | null) => element == null ? NaN : parseInt(getComputedStyle(element).lineHeight, 10);
const distance = lines * (line_height(document.documentElement) || line_height(document.body) || 22);
const scrolls = (element: Element) => {
const before = element.scrollTop;
element.scrollTop = before + distance;
return element.scrollTop !== before;
};
for (let element = document.activeElement; element != null; element = element.parentElement) {
if (scrolls(element)) {
return;
}
}
const walker = document.createTreeWalker(document.documentElement, NodeFilter.SHOW_ELEMENT);
do {
if (scrolls(walker.currentNode as Element)) {
return;
}
} while (walker.nextNode());
}, { tab_id: await glide.tabs.active(), args: [lines] });
}
glide.keymaps.set("normal", "j", () => scroll_lines(4), { description: "Scroll down four lines" });
glide.keymaps.set("normal", "k", () => scroll_lines(-4), { description: "Scroll up four lines" });
glide.keymaps.set(["normal", "insert", "visual"], "<A-d>", () => {}, {
description: "Disabled (would focus the urlbar)",
});
glide.keymaps.set("normal", "<C-m>", async () => {
const tabs = await browser.tabs.query({ currentWindow: true });
const target = tabs.sort((a, b) => (b.lastAccessed ?? 0) - (a.lastAccessed ?? 0))[1];
if (target?.id != null) {
await browser.tabs.update(target.id, { active: true });
}
}, { description: "Switch to the last-active tab" });
glide.keymaps.set("normal", "gd", async () => {
const tab = await glide.tabs.active();
await browser.windows.create({ tabId: tab.id });
}, { description: "Detach the current tab into a new window" });
glide.keymaps.set("normal", "gD", async () => {
const tab = await glide.tabs.active();
const dup = await browser.tabs.duplicate(tab.id);
if (dup?.id != null) {
await browser.windows.create({ tabId: dup.id });
}
}, { description: "Duplicate the current tab into a new window" });
glide.keymaps.set("normal", "d", async () => {
const tabs = await browser.tabs.query({ currentWindow: true });
const current = tabs.find((t) => t.active);
if (current?.id == null) {
return;
}
const ordered = tabs.filter((t) => t.id != null).sort((a, b) => a.index - b.index);
const pos = ordered.findIndex((t) => t.id === current.id);
const target = ordered[(pos - 1 + ordered.length) % ordered.length];
if (target?.id != null && target.id !== current.id) {
await browser.tabs.update(target.id, { active: true });
}
await browser.tabs.remove(current.id);
}, { description: "Close the current tab and focus the previous one" });
glide.keymaps.set("normal", "D", "tab_close");
'';
}
4.4.2.20.13. Glide CSS
{
flake.modules.homeManager.glide =
{ config, lib, ... }:
{
programs.glide-browser.config = ''
glide.styles.add(css`
:root {
${lib.concatMapStringsSep "\n" (
i:
let
name = "base0${lib.toHexString i}";
in
"--${name}: ${config.lib.stylix.colors.withHashtag.${name}};"
) (lib.range 0 15)}
--glide-bg: var(--base00);
--glide-fg: var(--base05);
--glide-cmdl-bg: var(--base00);
--glide-cmdl-fg: var(--base0D);
--glide-cmdl-font-family: "Fira Code", monospace;
--glide-cmdl-font-size: 1.5rem;
--glide-cmdl-line-height: 1.5;
--glide-cmplt-bg: var(--base00);
--glide-cmplt-fg: var(--base0D);
--glide-cmplt-font-family: "Fira Code", monospace;
--glide-cmplt-font-size: 0.8rem;
--glide-cmplt-border-top: unset;
--glide-header-first-bg: var(--base01);
--glide-header-second-bg: var(--base01);
--glide-header-third-bg: var(--base01);
--glide-header-font-weight: 200;
--glide-header-border-bottom: unset;
--glide-url-fg: var(--base0B);
--glide-url-bg: var(--base00);
--glide-of-bg: #44391F;
--glide-of-fg: var(--base09);
--glide-status-bg: var(--base00);
--glide-status-fg: var(--base05);
--glide-status-border: 1px solid var(--base03);
--glide-mode-normal: var(--base03);
--glide-mode-insert: var(--base0B);
--glide-mode-visual: var(--base09);
--glide-mode-hint: var(--base0E);
--glide-mode-ignore: var(--base01);
--glide-mode-command: var(--base0D);
--glide-mode-op-pending: var(--base0A);
--glide-search-highlight-color: var(--base0A);
--lwt-accent-color: var(--base01) !important;
--lwt-accent-color-inactive: var(--base01) !important;
--lwt-text-color: var(--base05) !important;
--toolbar-bgcolor: var(--base00) !important;
--toolbar-color: var(--base05) !important;
--toolbarbutton-icon-fill: var(--base05) !important;
--toolbarbutton-hover-background: var(--base01) !important;
--toolbarbutton-active-background: var(--base03) !important;
--toolbar-field-background-color: var(--base01) !important;
--toolbar-field-color: var(--base05) !important;
--toolbar-field-focus-background-color: var(--base01) !important;
--toolbar-field-focus-color: var(--base05) !important;
--toolbar-field-border-color: transparent !important;
--toolbar-field-focus-border-color: var(--base0D) !important;
--urlbar-box-bgcolor: var(--base01) !important;
--urlbar-box-focus-bgcolor: var(--base01) !important;
--urlbar-box-hover-bgcolor: var(--base03) !important;
--urlbar-popup-url-color: var(--base0D) !important;
--urlbarView-highlight-background: var(--base03) !important;
--arrowpanel-background: var(--base00) !important;
--arrowpanel-color: var(--base05) !important;
--arrowpanel-border-color: var(--base03) !important;
--panel-background: var(--base00) !important;
--panel-color: var(--base05) !important;
--menu-background-color: var(--base00) !important;
--menu-color: var(--base05) !important;
--menuitem-hover-background-color: var(--base03) !important;
--button-bgcolor: var(--base01) !important;
--button-color: var(--base05) !important;
--button-hover-bgcolor: var(--base03) !important;
--button-primary-bgcolor: var(--base0C) !important;
--button-primary-hover-bgcolor: var(--base0D) !important;
--button-primary-color: var(--base00) !important;
--focus-outline-color: var(--base0D) !important;
--tab-selected-bgcolor: var(--base00) !important;
--tab-selected-textcolor: var(--base0D) !important;
--tab-hover-background-color: var(--base01) !important;
--sidebar-background-color: var(--base00) !important;
--sidebar-text-color: var(--base05) !important;
}
#navigator-toolbox {
background-color: var(--base00) !important;
}
#TabsToolbar {
background-color: var(--base01) !important;
}
#PersonalToolbar {
background-color: var(--base00) !important;
color: var(--base05) !important;
}
#urlbar-background {
background-color: var(--base01) !important;
}
#urlbar-container {
max-width: 50vw !important;
}
findbar {
background-color: var(--base00) !important;
color: var(--base05) !important;
}
.tabbrowser-tab {
color: var(--base05) !important;
}
.tab-background[selected] {
background-color: var(--base00) !important;
}
.tabbrowser-tab[visuallyselected] {
color: var(--base0D) !important;
}
glide-commandline {
position: fixed !important;
top: 25% !important;
bottom: unset !important;
left: 10% !important;
width: 80% !important;
box-shadow: rgba(0, 0, 0, 0.5) 0px 0px 15px !important;
}
glide-commandline .glide-commandline-container {
box-shadow: none;
}
glide-commandline [anonid="glide-commandline-holder"] {
order: 1;
border: 2px solid var(--base0C);
}
glide-commandline [anonid="glide-commandline-completions"] {
order: 2;
font-weight: 200;
}
glide-commandline [anonid="glide-colon"] {
display: none;
}
glide-commandline input {
padding: 1rem;
}
glide-commandline [anonid="glide-commandline-completions"] > div > table {
padding: 1rem;
padding-top: 0;
width: 100%;
table-layout: fixed;
}
glide-commandline [anonid="glide-commandline-completions"] tr > td {
width: 100%;
max-width: 0;
}
`, { id: "theme" });
'';
};
}
4.4.2.20.14. Toolbar auto-hide and states
{
flake.modules.homeManager.glide.programs.glide-browser.config = ''
const toolbar_hidden_css = css`
#navigator-toolbox {
position: fixed !important;
top: 0;
width: 100vw;
transform: translateY(-100%);
opacity: 0;
pointer-events: none;
}
#urlbar[popover] {
opacity: 0 !important;
pointer-events: none !important;
}
:root[customizing] #navigator-toolbox {
position: relative !important;
transform: none !important;
opacity: 1 !important;
pointer-events: auto !important;
}
:root[customizing] #urlbar[popover] {
opacity: 1 !important;
pointer-events: auto !important;
}
`;
let toolbar_state: "hidden" | "urlbar" | "full" = "hidden";
glide.styles.add(toolbar_hidden_css, { id: "toolbar-hidden" });
function set_toolbar(state: "hidden" | "urlbar" | "full") {
toolbar_state = state;
glide.styles.remove("toolbar-hidden");
if (state === "hidden") {
glide.styles.add(toolbar_hidden_css, { id: "toolbar-hidden" });
}
glide.o.native_tabs = state === "urlbar" ? "hide" : "show";
}
glide.keymaps.set("normal", "<leader>b", () => set_toolbar(toolbar_state === "urlbar" ? "hidden" : "urlbar"), {
description: "Toggle the URL bar",
});
glide.keymaps.set("normal", "<leader>B", () => set_toolbar(toolbar_state === "full" ? "hidden" : "full"), {
description: "Toggle the full toolbar",
});'';
}
4.4.2.20.15. Commands for opening and searching
{
flake.modules.homeManager.glide.programs.glide-browser.config = ''
type HistoryEntry = { url: string; title: string; visits: number; last_visit: number; match_title: string; match_url: string };
type BookmarkEntry = { url: string; title: string; date_added: number; match_title: string; match_url: string };
type UrlCandidate = { title: string; url: string; bmark: boolean; search: boolean; visits: number };
const HISTORY_RESULTS = 50;
const BOOKMARK_WEIGHT = 100;
const SEARCH_URL_WEIGHT = 150;
let history_list: HistoryEntry[] = [];
let history_by_url = new Map<string, HistoryEntry>();
let bookmark_list: BookmarkEntry[] = [];
let top_sites: UrlCandidate[] = [];
function places_fold(text: string): string {
return text.slice(0, 255).toLowerCase().normalize("NFD").replace(/\p{M}/gu, "");
}
function places_unescape(url: string): string {
try {
return decodeURIComponent(url);
} catch {
return url;
}
}
function places_match(tokens: string[], entry: { match_title: string; match_url: string }): boolean {
return tokens.every((token) => entry.match_title.includes(token) || entry.match_url.includes(token));
}
function history_entry(item: Browser.History.HistoryItem & { url: string }): HistoryEntry {
const title = item.title ?? "";
return {
url: item.url,
title,
visits: item.visitCount ?? 0,
last_visit: item.lastVisitTime ?? 0,
match_title: places_fold(title),
match_url: places_fold(places_unescape(item.url)),
};
}
async function refresh_history() {
const items = await browser.history.search({ text: "", startTime: 0, maxResults: 2 ** 31 - 1 });
history_list = items
.filter((item): item is typeof item & { url: string } => item.url != null)
.map(history_entry)
.sort((a, b) => b.last_visit - a.last_visit);
history_by_url = new Map(history_list.map((entry) => [entry.url, entry]));
}
async function refresh_bookmarks() {
const items = await browser.bookmarks.search({});
bookmark_list = items
.filter((item): item is typeof item & { url: string } => URL.canParse(item.url ?? ""))
.map((item) => ({
url: item.url,
title: item.title,
date_added: item.dateAdded ?? 0,
match_title: places_fold(item.title),
match_url: places_fold(places_unescape(item.url)),
}))
.sort((a, b) => b.date_added - a.date_added);
}
async function refresh_top_sites() {
top_sites = (await browser.topSites.get())
.slice(0, HISTORY_RESULTS)
.map((site) => ({ title: site.title ?? "", url: site.url, bmark: false, search: false, visits: 0 }));
}
function debounced(ms: number, fn: () => Promise<void>): () => void {
let timer: ReturnType<typeof setTimeout> | undefined;
return () => {
clearTimeout(timer);
timer = setTimeout(() => void fn(), ms);
};
}
const schedule_history_refresh = debounced(1000, async () => {
await Promise.all([refresh_history(), refresh_top_sites()]);
});
const schedule_bookmarks_refresh = debounced(1000, refresh_bookmarks);
const schedule_top_sites_refresh = debounced(2000, refresh_top_sites);
function record_visit(item: Browser.History.HistoryItem) {
if (!item.url) {
return;
}
const existing = history_by_url.get(item.url);
if (existing != null) {
history_list.splice(history_list.indexOf(existing), 1);
}
const entry = history_entry({ ...item, url: item.url, title: item.title || existing?.title });
history_list.unshift(entry);
history_by_url.set(entry.url, entry);
schedule_top_sites_refresh();
}
function record_title(item: { url?: string; title?: string }) {
const entry = item.url != null ? history_by_url.get(item.url) : undefined;
if (entry != null && item.title != null) {
entry.title = item.title;
entry.match_title = places_fold(item.title);
}
}
glide.autocmds.create("ConfigLoaded", () => {
browser.bookmarks.onCreated.addListener(schedule_bookmarks_refresh);
browser.bookmarks.onRemoved.addListener(schedule_bookmarks_refresh);
browser.bookmarks.onChanged.addListener(schedule_bookmarks_refresh);
browser.bookmarks.onMoved.addListener(schedule_bookmarks_refresh);
browser.history.onVisited.addListener(record_visit);
browser.history.onTitleChanged.addListener(record_title);
browser.history.onVisitRemoved.addListener(schedule_history_refresh);
void refresh_history();
void refresh_bookmarks();
void refresh_top_sites();
});
function search_history(tokens: string[]): HistoryEntry[] {
const found: HistoryEntry[] = [];
for (const entry of history_list) {
if (found.length >= HISTORY_RESULTS) {
break;
}
if (places_match(tokens, entry)) {
found.push(entry);
}
}
return found.sort((a, b) => b.visits - a.visits);
}
function search_bookmarks(tokens: string[]): BookmarkEntry[] {
const seen = new Map<string, string>();
return bookmark_list.filter((entry) => {
if (!places_match(tokens, entry) || seen.get(entry.title) === entry.url) {
return false;
}
seen.set(entry.title, entry.url);
return true;
});
}
function rewrite_search_url_query(query: string): { query: string; keyword: string | null } {
const tokens = query.split(" ");
const match = tokens.length > 1 || query.endsWith(" ") ? search_urls.find(([keyword]) => keyword === tokens[0]?.replace(/^@/, "")) : undefined;
if (match == null) {
return { query, keyword: null };
}
return { query: match[1].split("%s").join(" ") + " " + tokens.slice(1).join(" "), keyword: match[0] };
}
function combined_history_bookmarks(query: string): UrlCandidate[] {
const tokens = places_fold(query).split(/\s+/).filter(Boolean);
const combined = new Map<string, UrlCandidate>(
search_bookmarks(tokens).map((b) => [b.url, { title: b.title, url: b.url, bmark: true, search: false, visits: 0 }]),
);
for (const page of search_history(tokens)) {
const existing = combined.get(page.url);
if (existing != null) {
existing.visits = page.visits;
} else {
combined.set(page.url, { title: page.title, url: page.url, bmark: false, search: false, visits: page.visits });
}
}
for (const [keyword, url] of search_urls) {
if (keyword.startsWith(query.replace(/^@/, ""))) {
combined.set(url, { title: keyword, url, bmark: false, search: true, visits: 0 });
}
}
const score = (c: UrlCandidate) => -c.visits - (c.bmark ? BOOKMARK_WEIGHT : 0) - (c.search ? SEARCH_URL_WEIGHT : 0);
return [...combined.values()].sort((a, b) => score(a) - score(b));
}
function decode_url_for_display(url: string): string {
return url.replace(/(?:%[89a-f][0-9a-f])+/gi, (encoded) => {
try {
const decoded = decodeURIComponent(encoded);
return /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(decoded) ? encoded : decoded;
} catch {
return encoded;
}
});
}
let active_fill_focused: ((focused_text: string) => string | null) | null = null;
let active_reshow: ((url: string) => void) | null = null;
let cmdline_input = "";
async function url_commandline(target: "current" | "tab" | "window", opts: { prefill?: string } = {}) {
await Promise.all([
history_list.length === 0 ? refresh_history() : null,
bookmark_list.length === 0 ? refresh_bookmarks() : null,
top_sites.length === 0 ? refresh_top_sites() : null,
]);
function describe_action(input: string): string {
if (input.trim() === "") {
return "Search with the default engine";
}
const resolved = resolve_open(input);
if ("url" in resolved) {
return "Open " + resolved.url;
}
return resolved.search.engine ? "Search " + resolved.search.engine + ": " + resolved.search.query : "Search: " + resolved.search.query;
}
cmdline_input = opts.prefill ?? "";
active_reshow = (url) => {
void glide.commandline.close().then(() => url_commandline(target, { ...opts, prefill: url }));
};
const action_text = DOM.create_element("span", { children: describe_action(opts.prefill ?? "") });
const options: glide.CommandLineCustomOption[] = [{
label: "search",
render: () => DOM.create_element("td", { attributes: { colspan: "2" }, children: [action_text] }),
matches: ({ input }) => {
cmdline_input = input;
action_text.textContent = describe_action(input);
return true;
},
execute: ({ input }) => {
void do_open(target, input);
},
}];
const HEADER = "History and bookmarks";
const slot_items: UrlCandidate[] = [];
const slot_titles: HTMLElement[] = [];
const slot_urls: HTMLElement[] = [];
let slot_query: string | null = null;
active_fill_focused = (focused_text) => {
const focused = slot_items.find((_, i) => focused_text === slot_titles[i]!.textContent + slot_urls[i]!.textContent);
if (focused == null) {
return null;
}
return focused.search ? focused.title : focused.url;
};
function set_header(text: string) {
const header = document.querySelector('glide-commandline [anonid="glide-commandline-completions-custom-options"] .section-header');
if (header != null && header.textContent !== text) {
header.textContent = text;
}
}
function recompute_slots(input: string) {
if (input === slot_query) {
return;
}
slot_query = input;
slot_items.length = 0;
if (input === "") {
set_header(HEADER);
slot_items.push(...top_sites);
} else {
const rewritten = rewrite_search_url_query(input);
set_header(rewritten.keyword != null ? "Search " + rewritten.keyword : HEADER);
slot_items.push(...combined_history_bookmarks(rewritten.query).slice(0, HISTORY_RESULTS));
}
slot_items.forEach((item, i) => {
slot_titles[i]!.textContent = (item.bmark ? "★ " : "") + (item.title || new URL(item.url).host);
slot_urls[i]!.textContent = (item.search ? "Search " : "") + decode_url_for_display(item.url);
});
}
for (let i = 0; i < HISTORY_RESULTS; i++) {
const title_el = DOM.create_element("span", { style: { flex: "1 1 50%", minWidth: "0", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" } });
const url_el = DOM.create_element("span", { style: { flex: "1 1 50%", minWidth: "0", textAlign: "right", color: "var(--base0B)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" } });
slot_titles.push(title_el);
slot_urls.push(url_el);
options.push({
label: "url-" + i,
render: () => DOM.create_element("td", {
attributes: { colspan: "2" },
children: [
DOM.create_element("div", {
style: { display: "flex", width: "100%", minWidth: "0", justifyContent: "space-between", gap: "2em", overflow: "hidden" },
children: [title_el, url_el],
}),
],
}),
matches: ({ input }) => {
recompute_slots(input);
return slot_items[i] != null;
},
execute: () => {
const entry = slot_items[i];
if (entry) {
void do_navigate(target, entry.search ? entry.url.split("%s").join("") : entry.url);
}
},
});
}
recompute_slots(opts.prefill ?? "");
await glide.commandline.show({ input: opts.prefill ?? "", title: HEADER, options });
}
glide.autocmds.create("CommandLineExit", () => {
active_fill_focused = null;
active_reshow = null;
});
glide.keymaps.set("command", "<Right>", () => {
const focused = document.querySelector("glide-commandline .gcl-option.focused");
const value = focused != null ? active_fill_focused?.(focused.textContent ?? "") : null;
if (value != null && value !== cmdline_input && active_reshow != null) {
active_reshow(value);
} else {
void glide.keys.send("<Right>", { skip_mappings: true });
}
}, { description: "Fill the focused history entry into the commandline for editing" });
glide.keymaps.set("normal", "o", () => url_commandline("current"), {
description: "Open a URL or search",
});
glide.keymaps.set("normal", "O", async () => {
const tab = await glide.tabs.active();
await url_commandline("current", { prefill: tab.url });
}, { description: "Edit the current URL" });
glide.keymaps.set("normal", "t", () => url_commandline("tab"), {
description: "Open a URL or search in a new tab",
});
glide.keymaps.set("normal", "T", async () => {
const tab = await glide.tabs.active();
await url_commandline("tab", { prefill: tab.url });
}, { description: "Open the current URL in a new tab" });
glide.keymaps.set("normal", "s", () => url_commandline("current", { prefill: "search " }), {
description: "Search with the default engine",
});
glide.keymaps.set("normal", "S", () => url_commandline("tab", { prefill: "search " }), {
description: "Search with the default engine in a new tab",
});
for (const [key, target] of [["s", "current"], ["S", "tab"]] as const) {
glide.keymaps.set("visual", key, async () => {
const selection = await glide.content.execute(() => window.getSelection()?.toString() ?? "", { tab_id: await glide.tabs.active() });
await url_commandline(target, { prefill: "search " + selection });
}, { description: "Search the selection with the default engine" + (target === "tab" ? " in a new tab" : "") });
}
glide.keymaps.set("normal", "w", () => url_commandline("window"), {
description: "Open a URL or search in a new window",
});'';
}
4.4.2.20.16. Find audio tabs
{
flake.modules.homeManager.glide.programs.glide-browser.config = ''
glide.keymaps.set("normal", "<leader>A", async () => {
const audible = await browser.tabs.query({ audible: true });
if (audible.length === 0) {
flash_message("no audible tabs");
return;
}
await glide.commandline.show({
title: "Audible tabs",
options: audible.map((tab) => ({
label: tab.title ?? "",
description: tab.url ?? "",
execute: async () => {
if (tab.windowId != null) {
await browser.windows.update(tab.windowId, { focused: true });
}
if (tab.id != null) {
await browser.tabs.update(tab.id, { active: true });
}
},
})),
});
}, { description: "Jump to a tab that is playing audio" });
'';
}
4.4.2.20.17. Jump to site heading
{
flake.modules.homeManager.glide =
{ config, ... }:
{
programs.glide-browser.config = ''
interface Heading {
text: string;
level: number;
xpath: string;
}
glide.keymaps.set("normal", "<leader>h", async () => {
const tab_id = (await glide.tabs.active()).id;
const headings = await glide.content.execute((): Heading[] => {
function is_visible(el: HTMLElement): boolean {
const style = window.getComputedStyle(el);
return (
style.display !== "none" &&
style.visibility !== "hidden" &&
style.opacity !== "0" &&
el.offsetParent !== null
);
}
function xpath_for(node: Element): string {
let path = "";
for (let el: Element | null = node; el; el = el.parentElement) {
let index = 0;
for (let sib = el.previousElementSibling; sib; sib = sib.previousElementSibling) {
if (sib.tagName === el.tagName) {
index++;
}
}
path = "/" + el.tagName.toLowerCase() + "[" + (index + 1) + "]" + path;
}
return path;
}
return Array.from(document.querySelectorAll("h1, h2, h3, h4, h5, h6"))
.filter((el) => is_visible(el as HTMLElement))
.map((el) => ({
text: (el.textContent ?? "").trim(),
level: Number(el.tagName[1]),
xpath: xpath_for(el),
}))
.filter((h) => h.text !== "");
}, { tab_id });
if (headings.length === 0) {
flash_message("no headings found");
return;
}
await glide.commandline.show({
title: "Jump to heading",
options: headings.map((heading) => ({
label: " ".repeat(heading.level - 1) + heading.text,
execute: async () => {
await glide.content.execute((xpath: string, color: string) => {
const target = document.evaluate(
xpath,
document,
null,
XPathResult.FIRST_ORDERED_NODE_TYPE,
null,
).singleNodeValue as HTMLElement | null;
if (!target) {
return;
}
target.scrollIntoView({ behavior: "smooth", block: "start" });
const previous = target.style.outline;
target.style.outline = "2px solid " + color;
setTimeout(() => {
target.style.outline = previous;
}, 2000);
}, { tab_id, args: [heading.xpath, "${config.lib.stylix.colors.withHashtag.base09}"] });
},
})),
});
}, { description: "Jump to a heading on the current page" });
'';
};
}
4.4.2.20.18. Clone git repositories
{
flake.modules.homeManager.glide =
{
config,
lib,
pkgs,
...
}:
{
programs.glide-browser.config = ''
async function advertised_repo(): Promise<{ https: string; ssh: string | null } | null> {
async function fetch_document(url: string, credentials: RequestCredentials): Promise<Document | null> {
try {
const response = await fetch(url, { credentials });
return response.ok ? new DOMParser().parseFromString(await response.text(), "text/html") : null;
} catch {
return null;
}
}
const nwo = document.querySelector('meta[name="octolytics-dimension-repository_nwo"]')?.getAttribute("content");
let https = nwo != null && (location.pathname + "/").toLowerCase().startsWith("/" + nwo.toLowerCase() + "/") ? location.origin + "/" + nwo + ".git" : undefined;
for (const credentials of ["omit", "include"] as const) {
if (https != null) {
break;
}
const go_get = await fetch_document(location.origin + location.pathname + "?go-get=1", credentials);
https = go_get?.querySelector('meta[name="go-import"]')?.getAttribute("content")?.split(/\s+/)[2];
}
if (https == null) {
return null;
}
const home = await fetch_document(https.replace(/\.git$/, ""), "include");
const ssh = home?.querySelector("#repo-clone-ssh")?.getAttribute("data-link") ?? home?.querySelector("[data-ssh-url]")?.getAttribute("data-ssh-url") ?? null;
return { https, ssh };
}
async function run(command: string, args: string[]): Promise<{ exit_code: number; output: string[] }> {
const proc = await glide.process.spawn(command, args, { check_exit_code: false, stderr: "stdout" });
const output = await proc.stdout.lines();
const { exit_code } = await proc.wait();
return { exit_code, output };
}
async function run_clone(url: string, dest: string, setup_remotes: boolean) {
flash_message("cloning " + url);
const clone = await run("${lib.getExe config.programs.git.package}", ["clone", url, dest]);
if (clone.exit_code !== 0) {
flash_message("clone failed: " + (clone.output.at(-1) ?? "exit code " + clone.exit_code));
return;
}
const remotes = setup_remotes ? (await run("${lib.getExe pkgs.swarsel-git-remotes}", [dest])).output : [];
flash_message(["cloned into " + dest, ...remotes.map((line) => line.replace(dest + ": ", ""))].join("; "));
}
async function clone_advertised_repo(dir: "Private" | "Work") {
const repo = await glide.content.execute(advertised_repo, { tab_id: await glide.tabs.active() });
if (repo == null) {
flash_message("no git repository advertised on this page");
return;
}
const { host, pathname } = new URL(repo.https);
const url = repo.ssh ?? "git@" + host + ":" + pathname.slice(1);
const dest = glide.path.home_dir + "/Documents/" + dir + "/" + pathname.split("/").pop()!.replace(/\.git$/, "");
if (await glide.fs.exists(dest)) {
flash_message(dest + " already exists");
return;
}
await glide.commandline.show({
title: "Clone " + url + " into " + dest + "? Type y to confirm",
options: [{
label: "y",
description: "git clone " + url + " " + dest,
matches: () => true,
execute: ({ input }) => {
if (input.trim() === "y") {
void run_clone(url, dest, dir === "Private");
}
},
}],
});
}
glide.keymaps.set("normal", "gcp", () => clone_advertised_repo("Private"), {
description: "Clone the repository of this page into ~/Documents/Private",
});
glide.keymaps.set("normal", "gcw", () => clone_advertised_repo("Work"), {
description: "Clone the repository of this page into ~/Documents/Work",
});
'';
};
}
4.4.2.21. KDE Connect
This enables phone/computer communication, including sending clipboard, files etc. Sadly on Wayland many of the features are broken (like remote control).
{
flake.modules.homeManager.kdeconnect.config = {
swarselsystems.enabledHomeModules = [ "kdeconnect" ];
services.kdeconnect = {
enable = true;
indicator = true;
};
};
}
4.4.2.22. attic store push service
Normally, I want to push all nix build artifacts to my main cache automatically, which is realized here. Note that authentication to the cache must be done manually once on client nodes.
Appendix E: Current TODOs: fix that
{
flake.modules.homeManager.attic-client =
{
config,
confLib,
globals,
...
}:
let
inherit (config.swarselsystems) mainUser;
in
{
config = {
swarselsystems = {
enabledHomeModules = [ "attic-client" ];
homeSopsSecrets.attic-cache-key.rekey.keyPrefix = confLib.static.sharedSecrets.common;
};
programs.attic-client = {
enable = true;
settings = {
default-server = mainUser;
servers.${mainUser} = {
endpoint = "https://${globals.services.attic.domain}";
token-file = confLib.getConfig.sops.secrets.attic-cache-key.path;
};
};
watchStore = [ "${mainUser}:${mainUser}" ];
};
systemd.user.services.attic-config.Unit.After = [ "sops-nix.service" ];
};
};
}
4.4.2.23. Tray applets
{
flake.modules.homeManager.tray-applets =
{
config,
lib,
pkgs,
confLib,
...
}:
let
applets = {
anki = {
execStart = "/etc/profiles/per-user/${config.swarselsystems.mainUser}/bin/anki";
extraService = {
Environment = [ "QT_QPA_PLATFORM=xcb" ];
KillMode = "mixed";
KillSignal = "SIGTERM";
SendSIGKILL = "yes";
TimeoutStopSec = "2s";
Type = "simple";
};
};
element.execStart = "${pkgs.element-desktop}/bin/element-desktop --hidden --enable-features=useozoneplatform --ozone-platform=wayland --disable-gpu-driver-bug-workarounds";
firezone.execStart = "${pkgs.firezone-gui-client}/bin/firezone-client-gui";
obsidian.execStart = "${lib.getExe config.programs.obsidian.package}";
vesktop.execStart = "${pkgs.vesktop}/bin/vesktop --start-minimized --ozone-platform-hint=auto --enable-features=WaylandWindowDecorations --enable-wayland-ime";
};
enabledApplets = lib.filterAttrs (n: _: config.swarselsystems.trayApplets.${n}.enable) applets;
in
{
options.swarselsystems.trayApplets = lib.mapAttrs (_: _: {
enable = lib.swarselsystems.mkTrueOption;
}) applets;
config = {
swarselsystems.enabledHomeModules = lib.mapAttrsToList (n: _: "${n}-tray") enabledApplets;
systemd.user.services = lib.mapAttrs' (
n: appletDef:
lib.nameValuePair "${n}-applet" (
confLib.mkTrayApplet (
appletDef // { description = "${lib.swarselsystems.toCapitalized n} applet"; }
)
)
) enabledApplets;
};
};
}
4.4.2.24. Shikane
{
flake.modules.homeManager.shikane =
{
config,
lib,
pkgs,
confLib,
...
}:
{
config = {
swarselsystems = {
enabledHomeModules = [ "shikane" ];
monitors.homedesktop = rec {
mode = "2560x1440";
model = "PHL BDM3270";
name = "${vendor} ${model} ${serial}";
output = name;
position = "0,0";
scale = "1";
serial = "AU11806002320";
vendor = "Philips Consumer Electronics Company";
workspace = "11:M";
};
};
services.shikane = {
enable = true;
settings =
let
homeMonitor = confLib.mkShikaneOutput config.swarselsystems.monitors.homedesktop { };
exec = [
"${lib.getExe' pkgs.libnotify "notify-send"} shikane \"Profile $SHIKANE_PROFILE_NAME has been applied\""
];
in
{
profile = [
{
inherit exec;
name = "internal-on";
output = [
{
enable = true;
match = config.swarselsystems.sharescreen;
mode = "${config.swarselsystems.highResolution}@165.000";
scale = 1.0;
}
];
}
{
inherit exec;
name = "home-internal-on";
output = [
{
enable = true;
match = config.swarselsystems.sharescreen;
position = "2560,0";
scale = 1.7;
}
homeMonitor
];
}
{
inherit exec;
name = "home-internal-off";
output = [
{
enable = false;
match = config.swarselsystems.sharescreen;
position = "2560,0";
}
homeMonitor
];
}
];
};
};
systemd.user.services.shikane = lib.mkIf (
builtins.elem "optional-noctalia" config.swarselsystems.enabledHomeModules
&& config.swarselsystems.noctalia-systemd
) (confLib.overrideTarget "noctalia-shell.target");
};
};
}
4.4.2.25. gpg-agent
Settings that are needed for the GPG-agent. Also we are enabling Emacs support for unlocking my Yubikey here.
In recent times, I often need support for SK keys (on HSKs) as well as certificate based login using step CA. Both of these are not present in gpg-agent, which is why in the new setup I run on ssh-agent per default, and only use gpg-agents' ssh login for hosts that need it. Interestingly, the other way around (which I would prefer) does not seem to work.
When setting up a new machine:
- setup gpgsm for signing of mails using S/MIME:
- `gpgsm --import ~/Certificates/<certname>.p12`
- `gpgsm --import ~/Certificates/harica-root.pem`
- `gpgsm --import ~/Certificates/harica-intermediate.pem`
- `gpgsm --list-keys --with-validation "HARICA Client RSA Root CA 2021"`
- trust the certificate and set passphrase
{
flake.modules.homeManager.gpg-agent =
{
root,
config,
lib,
pkgs,
options,
nixosConfig ? null,
...
}:
let
inherit (config.swarselsystems) homeDir mainUser;
in
{
config = {
swarselsystems.enabledHomeModules = [ "gpgagent" ];
services = {
gpg-agent = {
enable = true;
# pinentry.package = pkgs.pinentry.gtk2;
defaultCacheTtl = 600;
enableExtraSocket = true;
enableScDaemon = true;
enableSshSupport = false; # so that the SSH_AUTH_SOCK can still default to ssh-agent. however we want the capability of doing gpg ssh logins, hence the extraConfig
enableZshIntegration = true;
extraConfig = ''
enable-ssh-support
allow-loopback-pinentry
allow-emacs-pinentry
'';
maxCacheTtl = 7200;
pinentry = {
package = pkgs.wayprompt;
program = "pinentry-wayprompt";
};
sshKeys = [
"4BE7925262289B476DBBC17B76FD3810215AE097"
];
verbose = true;
};
# we need the normal ssh agent for cert based login as well as support for sk keys, both of which are not present for gpg-agent
ssh-agent.enable = true;
};
programs.gpg = {
enable = true;
publicKeys = [
{
source = root "files/public/gpg/gpg-public-key-0x76FD3810215AE097.asc";
trust = 5;
}
];
scdaemonSettings = {
disable-ccid = true; # prevent conflicts between pcscd and scdameon
# pcsc-shared = true; # as long as only one key is used, this prevents key from not being detected sometimes
};
settings.no-autostart = true;
};
systemd.user = {
services.gpg-agent.Unit = lib.mkIf (nixosConfig != null && nixosConfig.programs.uwsm.enable) {
After = lib.mkForce [
"gpg-agent.socket"
"graphical-session.target"
];
PartOf = [ "graphical-session.target" ];
};
sockets.gpg-agent-ssh =
let
inherit (config.programs.gpg) homedir;
# Act like `xxd -r -p | base32` but with z-base-32 alphabet and no trailing padding.
# Written in Nix for purity.
hexStringToBase32 =
let
mod = a: b: a - a / b * b;
pow2 = lib.elemAt [
1
2
4
8
16
32
64
128
256
];
base32Alphabet = lib.stringToCharacters "ybndrfg8ejkmcpqxot1uwisza345h769";
hexToIntTable = lib.listToAttrs (
lib.genList (x: {
name = lib.toLower (lib.toHexString x);
value = x;
}) 16
);
initState = {
buf = 0;
bufBits = 0;
ret = "";
};
go =
{
buf,
bufBits,
ret,
}:
hex:
let
buf' = buf * pow2 4 + hexToIntTable.${hex};
bufBits' = bufBits + 4;
extraBits = bufBits' - 5;
in
if bufBits >= 5 then
{
buf = mod buf' (pow2 extraBits);
bufBits = bufBits' - 5;
ret = ret + lib.elemAt base32Alphabet (buf' / pow2 extraBits);
}
else
{
inherit ret;
buf = buf';
bufBits = bufBits';
};
in
hexString: (lib.foldl' go initState (lib.stringToCharacters hexString)).ret;
gpgconf =
dir:
let
hash = lib.substring 0 24 (hexStringToBase32 (builtins.hashString "sha1" homedir));
subdir = if homedir == options.programs.gpg.homedir.default then "${dir}" else "d.${hash}/${dir}";
in
"%t/gnupg/${subdir}";
in
{
Install.WantedBy = [ "sockets.target" ];
Socket = {
DirectoryMode = "0700";
FileDescriptorName = "ssh";
ListenStream = gpgconf "S.gpg-agent.ssh";
Service = "gpg-agent.service";
SocketMode = "0600";
};
Unit = {
Description = "GnuPG cryptographic agent (ssh-agent emulation)";
Documentation = "man:gpg-agent(1) man:ssh-add(1) man:ssh-agent(1) man:ssh(1)";
};
};
tmpfiles.rules = [
"d ${homeDir}/.gnupg 0700 ${mainUser} users - -"
];
};
# assure correct permissions
# systemd.user.tmpfiles.settings."30-gpgagent".rules = {
# "${homeDir}/.gnupg" = {
# d = {
# group = "users";
# user = mainUser;
# mode = "0700";
# };
# };
# };
};
};
}
4.4.2.26. Spicetify
{
flake-file.inputs.spicetify-nix = {
inputs = {
nixpkgs.follows = "nixpkgs";
systems.follows = "systems";
};
url = "github:Gerg-l/spicetify-nix";
};
flake.modules.homeManager.spicetify =
{
inputs,
lib,
arch,
...
}:
{
imports = lib.optionals (inputs ? spicetify-nix && arch == "x86_64-linux") [
inputs.spicetify-nix.homeManagerModules.default
(
{ inputs, pkgs, ... }:
let
spicePkgs = inputs.spicetify-nix.legacyPackages.${pkgs.stdenv.hostPlatform.system};
in
{
swarselsystems.enabledHomeModules = [ "spicetify" ];
programs.spicetify = {
enable = true;
enabledExtensions = with spicePkgs.extensions; [
fullAppDisplay
shuffle
hidePodcasts
fullAlbumDate
skipStats
history
];
# spotifyPackage = pkgs.stable24_11.spotify;
spotifyPackage = pkgs.spotify;
};
}
)
];
};
}
4.4.2.27. Obsidian
{
flake.modules.homeManager.obsidian =
{
config,
lib,
pkgs,
confLib,
...
}:
let
inherit (confLib.getConfig.repo.secrets.common.obsidian) userIgnoreFilters;
name = "Main";
in
{
config = {
swarselsystems.enabledHomeModules = [ "obsidian" ];
programs.obsidian =
let
pluginSource = pkgs.nur.repos.swarsel;
in
{
enable = true;
package = pkgs.obsidian;
defaultSettings = {
app = {
inherit userIgnoreFilters;
alwaysUpdateLinks = true;
attachmentFolderPath = "attachments";
newFileLocation = "current";
spellcheck = false;
vimMode = false;
};
communityPlugins = with pluginSource; [
advanced-tables
calendar
file-hider
linter
omnisearch
sort-and-permute-lines
tag-wrangler
tray
];
corePlugins = [
"backlink"
"bookmarks"
"canvas"
"command-palette"
"daily-notes"
"editor-status"
"file-explorer"
"file-recovery"
"global-search"
"graph"
"note-composer"
"outgoing-link"
"outline"
"page-preview"
"properties"
"slides"
"switcher"
"tag-pane"
"templates"
"word-count"
];
hotkeys = {
"editor:delete-paragraph" = [ ];
"editor:save-file" = [ ];
"graph:open" = [ ];
"omnisearch:show-modal" = [
{
key = "S";
modifiers = [
"Mod"
];
}
];
};
};
vaults = {
${name} = {
settings = {
appearance.baseFontSize = lib.mkForce 19;
communityPlugins = with pluginSource; [
{
enable = true;
pkg = advanced-tables;
}
{
enable = true;
pkg = calendar;
}
{
enable = true;
pkg = sort-and-permute-lines;
}
{
enable = true;
pkg = tag-wrangler;
}
{
enable = true;
pkg = tray;
settings = {
createTrayIcon = true;
hideOnLaunch = true;
hideTaskbarIcon = false;
launchOnStartup = false;
runInBackground = true;
};
}
{
enable = true;
pkg = file-hider;
settings = {
hidden = true;
hiddenList = [
"attachments"
"images"
"ltximg"
"logseq"
];
};
}
{
enable = true;
pkg = linter;
settings = {
auto-correct-common-misspellings.skip-words-with-multiple-capitals = true;
convert-bullet-list-markers.enabled = true;
};
}
{
enable = true;
pkg = omnisearch;
settings.hideExcluded = true;
}
];
};
target = "./Obsidian/${name}";
};
};
};
home.file = lib.genAttrs' [ "app" "appearance" "core-plugins" ] (
file:
lib.nameValuePair "${config.programs.obsidian.vaults.${name}.target}/.obsidian/${file}.json" {
force = true;
}
);
};
};
}
4.4.2.28. Anki
{
flake.modules.homeManager.anki =
{
pkgs,
confLib,
globals,
...
}:
{
config = {
swarselsystems = {
enabledHomeModules = [ "anki" ];
homeSopsSecrets = {
anki-pw.rekey.keyPrefix = confLib.static.sharedSecrets.clients;
anki-user.rekey.keyPrefix = confLib.static.sharedSecrets.clients;
};
};
programs.anki = {
enable = true;
package = pkgs.anki;
addons =
let
minimize-to-tray = pkgs.anki-utils.buildAnkiAddon (finalAttrs: {
pname = "minimize-to-tray";
sourceRoot = "${finalAttrs.src.name}/src";
src = pkgs.fetchFromGitHub {
hash = "sha256-xmvbIOfi9K0yEUtUNKtuvv2Vmqrkaa4Jie6J1s+FuqY=";
owner = "simgunz";
repo = "anki21-addons_minimize-to-tray";
rev = finalAttrs.version;
sparseCheckout = [ "src" ];
};
version = "2.0.1";
});
in
[
(minimize-to-tray.withConfig {
config.hide_on_startup = "true";
})
];
hideBottomBar = true;
hideBottomBarMode = "always";
hideTopBar = true;
hideTopBarMode = "always";
# videoDriver = "opengl";
profiles."User 1".sync = {
autoSync = false; # sync on profile close will delay system shutdown
autoSyncMediaMinutes = 5;
# this is not the password but the syncKey
# get it by logging in or out, saving preferences and then
# show details on the "settings wont be saved" dialog
keyFile = confLib.getConfig.sops.secrets.anki-pw.path;
syncMedia = true;
url = "https://${globals.services.ankisync.domain}";
usernameFile = confLib.getConfig.sops.secrets.anki-user.path;
};
reduceMotion = true;
spacebarRatesCard = true;
};
};
};
}
4.4.2.29. Element-desktop
{
flake.modules.homeManager.element = { globals, ... }: {
config = {
swarselsystems.enabledHomeModules = [ "element-desktop" ];
programs.element-desktop = {
enable = true;
settings = {
UIFeature = {
deactivate = false;
feedback = false;
passwordReset = false;
registration = false;
shareSocial = false;
voip = false;
widgets = false;
};
default_server_config."m.homeserver".base_url = "https://${globals.services.matrix.domain}/";
};
};
};
};
}
4.4.2.30. obs-studio
{
flake.modules.homeManager.obs-studio.config = {
swarselsystems.enabledHomeModules = [ "obs-studio" ];
programs.obs-studio.enable = true;
};
}
4.4.2.31. spotify-player
{
flake.modules.homeManager.spotify-player.config = {
swarselsystems.enabledHomeModules = [ "spotify-player" ];
programs.spotify-player.enable = true;
};
}
4.4.2.32. vesktop
{
flake.modules.homeManager.vesktop =
{ pkgs, ... }:
{
config = {
swarselsystems.enabledHomeModules = [ "vesktop" ];
programs.vesktop = {
enable = true;
package = pkgs.vesktop;
settings = {
appBadge = false;
arRPC = false;
checkUpdates = false;
customTitleBar = false;
disableMinSize = true;
discordBranch = "stable";
hardwareAcceleration = true;
minimizeToTray = true;
staticTitle = true;
tray = true;
};
vencord = {
settings = {
autoUpdate = false;
autoUpdateNotification = false;
disableMinSize = true;
enableReactDevtools = false;
frameless = false;
notifyAboutUpdates = false;
plugins = {
ChatInputButtonAPI.enabled = false;
CommandsAPI.enabled = true;
FakeNitro.enabled = true;
MemberListDecoratorsAPI.enabled = false;
MessageAccessoriesAPI.enabled = true;
MessageDecorationsAPI.enabled = false;
MessageEventsAPI.enabled = false;
MessageLogger = {
enabled = true;
ignoreSelf = true;
};
MessagePopoverAPI.enabled = false;
MessageUpdaterAPI.enabled = false;
ServerListAPI.enabled = false;
UserSettingsAPI.enabled = true;
};
transparent = false;
useQuickCss = true;
winCtrlQ = false;
winNativeTitleBar = false;
};
useSystem = true;
};
};
};
};
}
4.4.2.33. Khal
{
flake.modules.homeManager.khal =
{ pkgs, ... }:
{
config = {
swarselsystems.enabledHomeModules = [ "khal" ];
programs.khal = {
enable = true;
package = pkgs.khal;
};
};
};
}
4.4.2.34. System Packages
Mostly used to install some compilers and lsp's that I want to have available when not using a devShell flake. Most other packages should go in Installed packages.
{
flake.modules = {
homeManager = {
cli-tools = { pkgs, ... }: {
swarselsystems.enabledHomeModules = [ "cli-tools" ];
home.packages = with pkgs; [
vim
util-linux
findutils
fd
unzip
gnutar
psmisc
lsof
sops
ssh-to-age
nvd
nix-output-monitor
nixfmt
deadnix
statix
nix-tree
nix-diff
];
};
packages =
{
self,
config,
lib,
pkgs,
...
}:
{
imports = [ self.modules.homeManager.cli-tools ];
config = {
swarselsystems.enabledHomeModules = [ "packages" ];
home.packages =
with pkgs;
[
(nixpkgs-review.override { nix = config.nix.package; })
libgsf
nautilus
wl-clipboard
wl-mirror
]
++ lib.optionals (config.swarselsystems.isFullBuild && pkgs.stdenv.hostPlatform.isx86_64) [
cura-appimage
zoom-us
]
++ lib.optionals config.swarselsystems.isFullBuild [
calibre
simple-scan
mgba
uv
croc
gimp
inkscape
libreoffice-qt
xournalpp
hugo
ffmpeg_7-full
texliveFull
unrar
zbar # qr codes
wf-recorder
adwaita-icon-theme
cantarell-fonts
nerd-fonts.symbols-only
];
};
};
};
nixos.packages =
{
config,
lib,
pkgs,
minimal,
...
}:
{
config.environment.systemPackages =
with pkgs;
lib.optionals (!minimal) (
[
just
yubikey-manager
]
++ lib.optionals (config.swarselsystems.isFullBuild && pkgs.stdenv.hostPlatform.isx86_64) [
# ledger packages
ledger-live-desktop
]
++ lib.optionals config.swarselsystems.isFullBuild [
pciutils
pre-commit
qmk
usbutils
]
)
++ lib.optionals minimal [
networkmanager
curl
git
gnupg
rsync
ssh-to-age
sops
vim
just
sbctl
];
};
};
}
4.4.2.35. Environment setup
Next, we will setup some environment variables that need to be set on the system-side. We apply some compatibility options for chromium apps on Wayland, enable the wordlist and make metadata reading possible for my file explorer (nautilus).
{
flake.modules = {
homeManager.env =
{
config,
lib,
confLib,
globals,
...
}:
let
inherit (confLib.getConfig.repo.secrets) common;
inherit (common) calendar mail;
inherit (config.swarselsystems) homeDir isPublic;
in
{
config = {
swarselsystems.enabledHomeModules = [ "env" ];
home.sessionVariables.DISPLAY = ":0";
systemd.user.sessionVariables = {
DOCUMENT_DIR_PRIV = "${homeDir}/Documents/Private";
FLAKE = "${homeDir}/.dotfiles";
}
// lib.optionalAttrs (!isPublic) {
HF_TOKEN = common.hfApi;
OPENROUTER_API_KEY = common.openrouterApi;
SWARSEL_CAL1 = calendar.source1;
SWARSEL_CAL1NAME = calendar.source1-name;
SWARSEL_CAL2 = calendar.source2;
SWARSEL_CAL2NAME = calendar.source2-name;
SWARSEL_CAL3 = calendar.source3;
SWARSEL_CAL3NAME = calendar.source3-name;
SWARSEL_DOMAIN = globals.domains.main;
SWARSEL_FILES_DOMAIN = globals.services.nextcloud.domain;
SWARSEL_FULLNAME = common.fullName;
SWARSEL_INSTA_DOMAIN = common.instaDomain;
SWARSEL_MAIL1 = mail.address1;
SWARSEL_MAIL2 = mail.address2;
SWARSEL_MAIL3 = mail.address3;
SWARSEL_MAIL4 = mail.address4;
SWARSEL_MAIL_ALL = lib.mkDefault mail.allMailAddresses;
SWARSEL_MUSIC_DOMAIN = globals.services.navidrome.domain;
SWARSEL_RSS_DOMAIN = globals.services.freshrss.domain;
SWARSEL_SPORT_DOMAIN = common.sportDomain;
};
};
};
nixos.env =
{
config,
lib,
pkgs,
...
}:
{
config.environment = {
sessionVariables = {
GST_PLUGIN_SYSTEM_PATH_1_0 = lib.makeSearchPathOutput "lib" "lib/gstreamer-1.0" (
with pkgs.gst_all_1;
[
gst-plugins-good
gst-plugins-bad
gst-plugins-ugly
gst-libav
]
);
NIXOS_OZONE_WL = "1";
SWARSEL_HI_RES = config.swarselsystems.highResolution;
SWARSEL_LO_RES = config.swarselsystems.lowResolution;
};
wordlist.enable = true;
};
};
};
}
4.4.2.36. enable GVfs
This is being set to allow myself to use all functions of nautilus in NixOS.
{
flake.modules.nixos.gvfs.config.services.gvfs.enable = true;
}
4.4.2.37. Security (polkit)
Needed for control over system-wide privileges etc. Also I make sure that the root user has access to SSH_AUTH_SOCK (without this, root will not be able to read my nix-secrets repository, however, that does not matter anymore since I stopped using that solution) in order to be able to keep using the same agent upon escalation.
{
flake.modules.nixos.polkit = { lib, minimal, ... }: {
config.security = {
# pki.certificateFiles = [
# config.sops.secrets.harica-root-ca.path
# ];
pam.services = lib.mkIf (!minimal) {
login = {
enableGnomeKeyring = lib.mkForce false;
u2fAuth = true;
};
sshd.u2fAuth = false;
sudo.u2fAuth = true;
};
polkit.enable = lib.mkIf (!minimal) true;
sudo.extraConfig = ''
Defaults insults
Defaults env_keep+=SSH_AUTH_SOCK
''
+ lib.optionalString (!minimal) ''
Defaults env_keep+=XDG_RUNTIME_DIR
Defaults env_keep+=WAYLAND_DISPLAY
'';
};
};
}
4.4.2.38. Reduce systemd timeouts
There is a persistent bug over Linux kernels that makes the user wait 1m30s on system shutdown due to the reason a stop job is running for session 1 of user .... I do not want to wait that long and am confident no important data is lost by doing this.
Nowadays, it seems that this bug was fixed (I think it was caused by VirtualBox), but still, I keep these shorter timeouts just to be safe (or unsafe, depending on your viewpoint).
{
flake.modules.nixos.systemd.config.systemd.settings.Manager = {
DefaultTimeoutStartSec = "60s";
DefaultTimeoutStopSec = "15s";
};
}
4.4.2.39. Hardware settings
Enable OpenGL, Sound, Bluetooth, support for my custom keyboards and various other drivers.
{
flake.modules.nixos.hardware =
{
config,
lib,
pkgs,
confLib,
...
}:
{
options.swarselsystems = {
hasBluetooth = lib.mkEnableOption "bluetooth availability";
hasFingerprint = lib.mkEnableOption "fingerprint sensor availability";
trackpoint = {
device = lib.mkOption {
default = "";
type = lib.types.str;
};
isAvailable = lib.mkEnableOption "trackpoint availability";
};
};
config = {
users.persistentIds.plugdev = confLib.mkIds 953;
services.fprintd.enable = lib.mkIf config.swarselsystems.hasFingerprint true;
hardware = {
bluetooth = lib.mkIf config.swarselsystems.hasBluetooth {
enable = true;
package = pkgs.bluez;
powerOnBoot = true;
settings.General.Enable = "Source,Sink,Media,Socket";
};
enableAllFirmware = lib.mkDefault true;
# opengl.driSupport32Bit = true is replaced with graphics.enable32Bit and hence redundant
graphics = {
enable = true;
enable32Bit = true;
};
keyboard.qmk.enable = true;
trackpoint = lib.mkIf config.swarselsystems.trackpoint.isAvailable {
inherit (config.swarselsystems.trackpoint) device;
enable = true;
};
usbStorage.manageShutdown = true;
};
};
};
}
4.4.2.40. Pulseaudio
This is only used on systems not running Pipewire (none at the moment).
{
flake.modules.nixos.pulseaudio =
{
config,
lib,
pkgs,
...
}:
{
config.services.pulseaudio = {
enable = lib.mkIf (!config.services.pipewire.enable) true;
package = pkgs.pulseaudioFull;
};
};
}
4.4.2.41. Pipewire
Pipewire handles communication on Wayland. This enables several sound tools as well as screen sharing through the XDG desktop portals. Back when I was on Sway this went through xdg-desktop-portal-wlr; nowadays on Niri screen sharing uses the GNOME portal (xdg-desktop-portal-gnome) instead.
{
flake.modules.nixos.pipewire = { pkgs, confLib, ... }: {
config = {
users.persistentIds.rtkit = confLib.mkIds 996;
services.pipewire = {
enable = true;
package = pkgs.pipewire;
alsa = {
enable = true;
support32Bit = true;
};
audio.enable = true;
jack.enable = true;
pulse.enable = true;
wireplumber.enable = true;
};
security.rtkit.enable = true; # this is required for pipewire real-time access
};
};
}
4.4.2.42. Common network settings
Here I only enable networkmanager and a few default networks. The rest of the network config is done separately in System specific configuration.
{
flake.modules = {
homeManager.network-manager-applet.config = {
swarselsystems.enabledHomeModules = [ "nm-applet" ];
services.network-manager-applet.enable = true;
xsession.preferStatusNotifierItems = true; # needed for indicator icon to show
};
nixos.network =
{
self,
config,
lib,
pkgs,
confLib,
...
}:
let
clientsSecrets = confLib.static.sharedSecrets.clients;
in
{
options.swarselsystems.firewall = lib.swarselsystems.mkTrueOption;
config = {
sops = {
secrets = lib.mkIf (!config.swarselsystems.isPublic) {
eduroam-pw.rekey.keyPrefix = clientsSecrets;
eduroam-user.rekey.keyPrefix = clientsSecrets;
home-wireguard-client-private-key.rekey = {
generator.script = "wireguard";
pubFile = self + "/files/public/wg/${config.node.name}-home.pub";
};
home-wireguard-endpoint.rekey.keyPrefix = clientsSecrets;
home-wireguard-preshared-key.rekey.generator.script = "wireguard-psk";
home-wireguard-server-public-key.rekey.keyPrefix = clientsSecrets;
laptop-hotspot-pw.rekey.keyPrefix = clientsSecrets;
mobile-hotspot-pw.rekey.keyPrefix = clientsSecrets;
pia-vpn-pw.rekey.keyPrefix = clientsSecrets;
pia-vpn-user.rekey.keyPrefix = clientsSecrets;
pia-vpn1-ca-pem = {
mode = "0444";
rekey.keyPrefix = clientsSecrets;
};
wlan1-pw.rekey.keyPrefix = clientsSecrets;
wlan2-pw.rekey.keyPrefix = clientsSecrets;
wlan3-pw.rekey.keyPrefix = clientsSecrets;
};
templates = lib.mkIf (!config.swarselsystems.isPublic) {
"network-manager.env".content = ''
WLAN1_PW=${config.sops.placeholder.wlan1-pw}
WLAN2_PW=${config.sops.placeholder.wlan2-pw}
WLAN3_PW=${config.sops.placeholder.wlan3-pw}
LAPTOP_HOTSPOT_PW=${config.sops.placeholder.laptop-hotspot-pw}
MOBILE_HOTSPOT_PW=${config.sops.placeholder.mobile-hotspot-pw}
EDUROAM_USER=${config.sops.placeholder.eduroam-user}
EDUROAM_PW=${config.sops.placeholder.eduroam-pw}
PIA_VPN_USER=${config.sops.placeholder.pia-vpn-user}
PIA_VPN_PW=${config.sops.placeholder.pia-vpn-pw}
HOME_WIREGUARD_CLIENT_PRIVATE_KEY=${config.sops.placeholder.home-wireguard-client-private-key}
HOME_WIREGUARD_PRESHARED_KEY=${config.sops.placeholder.home-wireguard-preshared-key}
HOME_WIREGUARD_SERVER_PUBLIC_KEY=${config.sops.placeholder.home-wireguard-server-public-key}
HOME_WIREGUARD_ENDPOINT=${config.sops.placeholder.home-wireguard-endpoint}
'';
};
};
users.persistentIds.nm-iodine = confLib.mkIds 957;
services.resolved.enable = true;
networking = {
enableIPv6 = lib.mkDefault true;
firewall = {
enable = lib.swarselsystems.mkStrong config.swarselsystems.firewall;
allowedTCPPortRanges = [
{
from = 1714;
to = 1764;
} # kde-connect
];
allowedUDPPortRanges = [
{
from = 1714;
to = 1764;
} # kde-connect
];
allowedUDPPorts = [ 51820 ]; # 51820: wireguard
checkReversePath = lib.mkDefault false;
};
hostName = config.node.name;
hosts = { };
modemmanager.enable = false;
networkmanager = {
enable = true;
dns = "systemd-resolved";
ensureProfiles = lib.mkIf (!config.swarselsystems.isPublic) {
environmentFiles = [
"${config.sops.templates."network-manager.env".path}"
];
profiles = config.repo.secrets.common.network.profiles;
};
plugins = [
# list of plugins: https://search.nixos.org/packages?query=networkmanager-
# docs https://networkmanager.dev/docs/vpn/
pkgs.networkmanager-openconnect
pkgs.networkmanager-openvpn
];
settings.main.no-auto-default = "*";
wifi.backend = "iwd";
};
nftables.enable = lib.mkDefault true;
wireless.iwd = {
enable = true;
settings = {
IPv6.Enabled = true;
Rank.BandModifier5GHz = 1.5;
Settings.AutoConnect = true;
# DriverQuirks = {
# UseDefaultInterface = true;
# };
};
};
};
systemd.services.NetworkManager-ensure-profiles.after = [ "NetworkManager.service" ];
};
};
};
}
4.4.2.43. "Small" Programs
Some programs profit from being installed through dedicated NixOS settings on system-level; these go here. Notably the zsh setup goes here and cannot be deleted under any circumstances (its config is in a subsection)
{
flake.modules = {
homeManager = {
programs = { self, ... }: {
imports = [ self.modules.homeManager.cli-programs ];
config = {
swarselsystems.enabledHomeModules = [ "programs" ];
programs = {
imv.enable = true;
mpv.enable = true;
pandoc.enable = true;
rclone.enable = true;
yt-dlp.enable = true;
};
};
};
cli-programs = {
swarselsystems.enabledHomeModules = [ "cli-programs" ];
programs = {
bat.enable = true;
bottom.enable = true;
carapace.enable = true;
fzf = {
enable = true;
enableBashIntegration = false;
enableZshIntegration = false;
};
jq.enable = true;
less.enable = true;
lesspipe.enable = true;
ripgrep.enable = true;
zoxide = {
options = [
"--cmd cd"
];
enable = true;
enableZshIntegration = true;
};
};
home.sessionVariables._ZO_EXCLUDE_DIRS = "$HOME:$HOME/.ansible/*:$HOME/test/*:/persist";
};
};
nixos.programs.config.programs = {
dconf.enable = true;
evince.enable = true;
kdeconnect.enable = true;
};
};
}
4.4.2.44. nautilus
This enabled the right-click context menu entry in nautilus that allows to open a folder in a terminal - I never use this to be honest, but I feel like the file explorer would not be complete otherwise.
{
flake.modules.nixos.nautilus.config.programs.nautilus-open-any-terminal = {
enable = true;
terminal = "kitty";
};
}
4.4.2.45. syncthing
This is the syncthing client configuration. Contrary to the server syncthing config, this sets all directories as send+receive (the servers only receive). Apart from that, I only really need to sync my Obsidian stuff and some Emacs files.
{
flake.modules = {
homeManager.syncthing-tray =
{
config,
lib,
pkgs,
...
}:
{
config = {
swarselsystems.enabledHomeModules = [ "syncthing-tray" ];
home.activation.setupSyncthingIni =
let
iniFile = "${config.home.homeDirectory}/.config/syncthingtray.ini";
in
lib.hm.dag.entryAfter [ "writeBoundary" ] ''
if [ ! -f ${iniFile} ]; then
cat >${iniFile} <<'EOF'
[General]
v=2.0.2
[qt]
customfont=false
customicontheme=false
customlocale=false
custompalette=false
customstylesheet=false
customwidgetstyle=false
font="Cantarell,11,-1,5,400,0,0,0,0,0,0,0,0,0,0,1"
icontheme=hicolor
iconthemepath=
locale=en_US
palette="@Variant(\0\0\0\x44\x1\x1\xff\xff\xa0\xa0\xb3\xb3\xc5\xc5\0\0\x1\x1\xff\xff jj\x86\x86\0\0\x1\x1\xff\xff\0\0::ff\0\0\x1\x1\xff\xff\0\0::ff\0\0\x1\x1\xff\xff\x1d\x1d%%,,\0\0\x1\x1\xff\xff\x1d\x1d%%,,\0\0\x1\x1\xff\xff\xa0\xa0\xb3\xb3\xc5\xc5\0\0\x1\x1\xff\xff\xff\xff\xff\xff\xff\xff\0\0\x1\x1\xff\xff\xa0\xa0\xb3\xb3\xc5\xc5\0\0\x1\x1\xff\xff\x1d\x1d%%,,\0\0\x1\x1\xff\xff\x17\x17\x1d\x1d##\0\0\x1\x1\xff\xff\0\0\0\0\0\0\0\0\x1\x1\xff\xff\0\0::ff\0\0\x1\x1\xff\xff\xa0\xa0\xb3\xb3\xc5\xc5\0\0\x1\x1\xff\xff^^\xc4\xc4\xff\xff\0\0\x1\x1\xff\xff\xc0\xc0nn\xce\xce\0\0\x1\x1\xff\xff\x17\x17\x1d\x1d##\0\0\x1\x1\xff\xff^^\xc4\xc4\xff\xff\0\0\x1\x1\xff\xff jj\x86\x86\0\0\x1\x1\xff\xff\0\0::ff\0\0\x1\x1\xff\xff\0\0::ff\0\0\x1\x1\xff\xff\x1d\x1d%%,,\0\0\x1\x1\xff\xff\x1d\x1d%%,,\0\0\x1\x1\xff\xff^^\xc4\xc4\xff\xff\0\0\x1\x1\xff\xff\xff\xff\xff\xff\xff\xff\0\0\x1\x1\xff\xff^^\xc4\xc4\xff\xff\0\0\x1\x1\xff\xff\x1d\x1d%%,,\0\0\x1\x1\xff\xff\x17\x17\x1d\x1d##\0\0\x1\x1\xff\xff\0\0\0\0\0\0\0\0\x1\x1\xff\xff\0\0::ff\0\0\x1\x1\x66\x66\xa0\xa0\xb3\xb3\xc5\xc5\0\0\x1\x1\xff\xff^^\xc4\xc4\xff\xff\0\0\x1\x1\xff\xff\xc0\xc0nn\xce\xce\0\0\x1\x1\xff\xff\x17\x17\x1d\x1d##\0\0\x1\x1\xff\xff\xa0\xa0\xb3\xb3\xc5\xc5\0\0\x1\x1\xff\xff jj\x86\x86\0\0\x1\x1\xff\xff\0\0::ff\0\0\x1\x1\xff\xff\0\0::ff\0\0\x1\x1\xff\xff\x1d\x1d%%,,\0\0\x1\x1\xff\xff\x1d\x1d%%,,\0\0\x1\x1\xff\xff\xa0\xa0\xb3\xb3\xc5\xc5\0\0\x1\x1\xff\xff\xff\xff\xff\xff\xff\xff\0\0\x1\x1\xff\xff\xa0\xa0\xb3\xb3\xc5\xc5\0\0\x1\x1\xff\xff\x1d\x1d%%,,\0\0\x1\x1\xff\xff\x17\x17\x1d\x1d##\0\0\x1\x1\xff\xff\0\0\0\0\0\0\0\0\x1\x2\xff\xffP\x14\xff\xff\x65\x65\0\0\x1\x1\xff\xff\xa0\xa0\xb3\xb3\xc5\xc5\0\0\x1\x1\xff\xff^^\xc4\xc4\xff\xff\0\0\x1\x1\xff\xff\xc0\xc0nn\xce\xce\0\0\x1\x1\xff\xff\x17\x17\x1d\x1d##\0\0)"
plugindir=
stylesheetpath=
trpath=
widgetstyle=
[startup]
considerForReconnect=false
considerLauncherForReconnect=false
showButton=false
showLauncherButton=false
stopOnMetered=false
stopServiceOnMetered=false
syncthingArgs="serve --no-browser --logflags=3"
syncthingAutostart=false
syncthingPath=syncthing
syncthingUnit=syncthing.service
systemUnit=false
useLibSyncthing=false
[tray]
connections\1\apiKey=@ByteArray($SYNCTHING_API_KEY)
connections\1\authEnabled=false
connections\1\autoConnect=true
connections\1\devStatsPollInterval=60000
connections\1\diskEventLimit=200
connections\1\errorsPollInterval=30000
connections\1\httpsCertPath=${config.home.homeDirectory}/.config/syncthing/https-cert.pem
connections\1\label=Primary instance
connections\1\localPath=
connections\1\longPollingTimeout=0
connections\1\password=
connections\1\pauseOnMetered=false
connections\1\reconnectInterval=30000
connections\1\requestTimeout=0
connections\1\statusComputionFlags=123
connections\1\syncthingUrl=http://${config.services.syncthing.guiAddress}
connections\1\trafficPollInterval=5000
connections\1\userName=
connections\size=1
dbusNotifications=true
distinguishTrayIcons=false
frameStyle=16
ignoreInavailabilityAfterStart=15
notifyOnDisconnect=true
notifyOnErrors=true
notifyOnLauncherErrors=true
notifyOnLocalSyncComplete=false
notifyOnNewDeviceConnects=false
notifyOnNewDirectoryShared=false
notifyOnRemoteSyncComplete=false
positioning\assumedIconPos=@Point(0 0)
positioning\useAssumedIconPosition=false
positioning\useCursorPos=true
preferIconsFromTheme=false
showDownloads=false
showSyncthingNotifications=true
showTabTexts=true
showTraffic=true
statusIcons="#ff26b6db,#ff0882c8,#ffffffff;#ffdb3c26,#ffc80828,#ffffffff;#ffc9ce3b,#ffebb83b,#ffffffff;#ff2d9d69,#ff2d9d69,#ffffffff;#ff26b6db,#ff0882c8,#ffffffff;#ff26b6db,#ff0882c8,#ffffffff;#ffa9a9a9,#ff58656c,#ffffffff;#ffa9a9a9,#ff58656c,#ffffffff;#ffa9a9a9,#ff58656c,#ffffffff"
statusIconsRenderSize=@Size(32 32)
statusIconsStrokeWidth=0
tabPos=1
trayIcons="#ff26b6db,#ff0882c8,#ffffffff;#ffdb3c26,#ffc80828,#ffffffff;#ffc9ce3b,#ffebb83b,#ffffffff;#ff2d9d69,#ff2d9d69,#ffffffff;#ff26b6db,#ff0882c8,#ffffffff;#ff26b6db,#ff0882c8,#ffffffff;#ffa9a9a9,#ff58656c,#ffffffff;#ffa9a9a9,#ff58656c,#ffffffff;#ffa9a9a9,#ff58656c,#ffffffff"
trayIconsRenderSize=@Size(32 32)
trayIconsStrokeWidth=0
trayMenuSize=@Size(575 475)
usePaletteForStatusIcons=false
usePaletteForTrayIcons=false
windowType=0
[webview]
customCommand=
disabled=false
mode=0
EOF
SYNCTHING_API_KEY=$(cat /run/syncthing-init/api_key) ${lib.getExe pkgs.envsubst} -i ${iniFile} -o ${iniFile}
fi
'';
};
};
nixos.syncthing =
{
config,
lib,
pkgs,
globals,
...
}:
let
inherit (config.swarselsystems) homeDir mainUser;
inherit (globals.services."syncthing-${globals.general.homeSyncthingServer}".extraConfig) devices;
syncDevices = builtins.attrNames devices;
servicePort = 8384;
in
{
config.services.syncthing = {
enable = true;
package = pkgs.syncthing;
configDir = "${homeDir}/.config/syncthing";
dataDir = homeDir;
guiAddress = "127.0.0.1:${builtins.toString servicePort}";
openDefaultPorts = true;
overrideDevices = true;
overrideFolders = true;
settings = {
inherit devices;
options.urAccepted = -1;
folders = {
"Default Folder" = lib.mkDefault {
devices = syncDevices;
id = "default";
path = "${homeDir}/Sync";
};
Obsidian = {
devices = syncDevices;
id = "yjvni-9eaa7";
path = "${homeDir}/Obsidian";
};
Org = {
devices = syncDevices;
id = "a7xnl-zjj3d";
path = "${homeDir}/Org";
};
Vpn = {
devices = syncDevices;
id = "hgp9s-fyq3p";
path = "${homeDir}/Vpn";
};
};
};
systemService = true;
user = mainUser;
};
};
};
}
4.4.2.46. interception-tools: Make CAPS work as ESC/CTRL
This is a super-convenient configuration bit that lets my remap my CAPS key to ESC if pressed shortly, and CTRL if being held. Interception-tools can do many other things as well, but that is really all I need when I am typing on my laptops internal keyboard.
{
flake.modules.nixos.interceptiontools = { pkgs, ... }: {
config = {
# Make CAPS work as a dual function ESC/CTRL key
services.interception-tools = {
enable = true;
udevmonConfig =
let
dualFunctionKeysConfig = builtins.toFile "dual-function-keys.yaml" ''
TIMING:
TAP_MILLISEC: 200
DOUBLE_TAP_MILLISEC: 0
MAPPINGS:
- KEY: KEY_CAPSLOCK
TAP: KEY_ESC
HOLD: KEY_LEFTCTRL
'';
in
''
- JOB: |
${pkgs.interception-tools}/bin/intercept -g $DEVNODE \
| ${pkgs.interception-tools-plugins.dual-function-keys}/bin/dual-function-keys -c ${dualFunctionKeysConfig} \
| ${pkgs.interception-tools}/bin/uinput -d $DEVNODE
DEVICE:
EVENTS:
EV_KEY: [KEY_CAPSLOCK]
'';
};
};
};
}
4.4.2.47. Network devices
In this section we enable compatibility with several network devices I have at home, mainly printers and scanners.
This allows me to use my big scanner/printer's scanning function over the network. This also allows me to use my big scanner/printer's printing function over the network. Most of the settings are driver related. Avahi is the service used for the network discovery.
{
flake.modules.nixos.networkdevices =
{
self,
pkgs,
confLib,
globals,
...
}:
let
printerAddress = globals.networks.home-lan.vlans.devices.hosts.dell-C2665dnf-F49D60.ipv4;
in
{
imports = [ self.modules.nixos.network-scanner ];
config = {
users.persistentIds = {
avahi = confLib.mkIds 978;
colord = confLib.mkIds 976;
lpadmin = confLib.mkIds 954;
};
services = {
avahi = {
enable = true;
nssmdns4 = true;
openFirewall = true;
settings.publish = {
disable-publishing = false;
disable-user-service-publishing = false;
publish-addresses = true;
};
};
# enable discovery and usage of network devices (esp. printers)
printing = {
enable = true;
browsedConf = ''
BrowseDNSSDSubTypes _cups,_print
BrowseLocalProtocols all
BrowseRemoteProtocols all
CreateIPPPrinterQueues All
BrowseProtocols all
'';
drivers = [
pkgs.gutenprint
pkgs.gutenprintBin
pkgs.foomatic-db-ppds
];
};
};
hardware.printers.ensurePrinters = [
{
deviceUri = "ipp://${printerAddress}:631/ipp";
model = "foomatic-db-ppds/Generic-PostScript_Printer-Postscript.ppd.gz";
name = "Dell_C2665dnf";
ppdOptions = {
Duplex = "DuplexNoTumble";
PageSize = "A4";
};
}
];
};
};
}
4.4.2.48. Bluetooth
Enables the blueman service including the nice system tray icon.
{
flake.modules = {
homeManager.blueman-applet.config = {
swarselsystems.enabledHomeModules = [ "blueman-applet" ];
services.blueman-applet.enable = true;
};
nixos.blueman.config.services = {
blueman.enable = true;
hardware.bolt.enable = true;
};
};
}
4.4.2.49. power-profiles-daemon
This enables power profile management. The available modes are:
- power-saver
- balanced
- performance
Most of the time I am using power-saver, however, it is good to be able to choose.
This is also used by Noctalia-shell in order to set and get the profiles.
{
flake.modules.nixos.power-profiles-daemon.config.services.power-profiles-daemon.enable = true;
}
4.4.2.50. Hardware: Yubikey
This takes care of the main Yubikey related configuration on the NixOS side - note that the gpg-agent itself is no longer started from here. It is configured in its own home-manager feature (gpg-agent) which enables services.gpg-agent directly, so that the same setup also applies on non-NixOS machines.
I want to use the ssh-agent from gpg-agent's ssh compatibility, which is why we disable ssh-agent. Also, we load some extra udev rules using hardware.gpgSmartcards.enable.
Many guides state that it is needed to enable pcscd to use the smartcard mode (CCID) of the Yubikey. However, enabling it causes some problems when locking the screen and unplugging the Yubikey, after which the Yubikey only becomes available again as a smart card after about one minute. I found that is is sufficient to enable services.gpg-agent.enableScDaemon in home-manager instead.
Also, since I use a GPG key in sops, it seems that scdaemon creates an instance at boot which sometimes hogs the Yubikey, which leads to significant delays after e.g. locking the screen and unplugging the Yubikey. Since I do not need the GPG key for the actual sops secrets (I use machine age keys instead), I kill that process.
{
flake-file.inputs.yubikey-touch-alarm = {
inputs = {
flake-parts.follows = "flake-parts";
git-hooks-nix.follows = "pre-commit-hooks";
nixpkgs.follows = "nixpkgs";
treefmt-nix.follows = "treefmt-nix";
};
url = "git+ssh://forgejo@swagit.swarsel.win:2222/swarsel/yubikey-touch-alarm";
};
flake.modules.nixos.hardwarecompatibility-yubikey =
{
root,
inputs,
config,
lib,
pkgs,
confLib,
...
}:
let
inherit (config.swarselsystems) mainUser;
inherit (config.repo.secrets.common.yubikeys) cfg1 cfg2 cfg3;
inherit (config.lib.stylix) colors;
in
{
imports = [ inputs.yubikey-touch-alarm.nixosModules.default ];
config = {
users.persistentIds.pcscd = confLib.mkIds 956;
services = {
gnome.gcr-ssh-agent.enable = false;
pcscd.enable = true;
udev.packages = with pkgs; [
yubikey-personalization
];
yubikey-agent.enable = false;
yubikey-touch-alarm = {
enable = true;
image = root "files/icons/smaaaash.png";
popupDelay = 2;
sound = root "files/audio/jetztgehtslos.flac";
soundDelay = 8;
soundRepeats = 30;
style = {
background = "alpha(#${colors.base00}, 0.8)";
font = config.stylix.fonts.monospace.name;
foreground = "#${colors.base05}";
};
};
};
programs = {
ssh = {
startAgent = false; # yes we want this to use FIDO2 keys
# enableAskPassword = true;
# askPassword = lib.getExe pkgs.kdePackages.ksshaskpass;
};
yubikey-touch-detector = {
enable = true;
libnotify = false;
};
};
environment.systemPackages = with pkgs; [
kdePackages.ksshaskpass
];
hardware.gpgSmartcards.enable = true;
security.pam.u2f = {
enable = true;
control = "sufficient";
settings = {
authfile = pkgs.writeText "u2f-mappings" (
lib.concatStrings [
mainUser
cfg1
cfg2
cfg3
]
);
cue = true; # prints a message that a touch is requrired
interactive = false; # displays a prompt BEFORE asking for presence
origin = "pam://${mainUser}"; # make the keys work on all machines
};
};
systemd.user.services.yubikey-touch-detector = {
after = [ "gpg-agent-ssh.socket" ];
environment.SSH_AUTH_SOCK = "%t/gnupg/S.gpg-agent.ssh";
partOf = [ "gpg-agent-ssh.socket" ];
};
};
};
}
4.4.2.51. Hardware: Ledger
This performs the necessary configuration to support this hardware.
{
flake.modules.nixos.hardwarecompatibility-ledger.config.hardware.ledger.enable = true;
}
4.4.2.52. Hardware: Keyboards
This loads some udev rules that I need for my split keyboards.
{
flake.modules.nixos.hardwarecompatibility-keyboards =
{
lib,
pkgs,
confLib,
...
}:
{
config = {
users.persistentIds.plugdev = confLib.mkIds 953;
services.udev.packages =
with pkgs;
[
qmk-udev-rules
]
++ lib.optionals pkgs.stdenv.hostPlatform.isx86_64 [
vial
via
];
};
};
}
4.4.2.53. System Login (greetd)
This section houses the greetd related settings. I do not really want to use a display manager, but it is useful to have setup in some ways - in my case for starting Niri on system startup. Notably the default user login setting that is commented out here goes into the system specific settings, make sure to update it there.
{
flake-file.inputs.noctalia-greeter = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:noctalia-dev/noctalia-greeter";
};
flake.modules.nixos.login =
{
inputs,
config,
confLib,
...
}:
{
imports = [ inputs.noctalia-greeter.nixosModules.default ];
config = {
users.persistentIds.greeter = confLib.mkIds 958;
services = {
displayManager.noctalia-greeter.enable = true;
greetd = {
enable = true;
settings.initial_session.command = "uwsm start -- niri-uwsm.desktop";
};
};
environment = {
pathsToLink = [ "/share/wayland-sessions" ];
systemPackages = config.services.displayManager.sessionPackages;
};
};
};
}
4.4.2.54. nix-ld
This provides libraries for binaries that are not patched for use on NixOS. This really makes the biggest gripe with NixOS go away, that being having to run a binary that is only found in a single spot. It is most of the times possible to patch such a file, but this makes such a situation take much less time to resolve.
Only some binaries that touch system settings might still not work, apart from that, the list of libraries I have curated here should be quite exhaustive.
When a program does not work, start with nix-ldd <program>. This will tell you which library is missing. Afterwards, continue with nix-locate <program> to find which packages provide that library. Add it to libraries below and rebuild. After a reboot, it will be visible using nix-ldd. It can also be useful to take a look at ldd to see which libraries are needed in general.
{
flake.modules.nixos.nix-ld = { lib, pkgs, ... }: {
config.programs.nix-ld = {
enable = true;
libraries =
with pkgs;
[
SDL
SDL2
SDL2_image
SDL2_mixer
SDL2_ttf
SDL_image
SDL_mixer
SDL_ttf
alsa-lib
at-spi2-atk
at-spi2-core
atk
bzip2
cairo
cups
curl
dbus
dbus-glib
expat
ffmpeg
flac
fontconfig
freeglut
freetype
fuse3
gdk-pixbuf
glew_1_10
glib
pango
gtk3
icu
libGL
libappindicator-gtk3
libcaca
libcanberra
libcap
libdrm
libelf
libgbm
libgcrypt
libglvnd
libidn
libjpeg
libmikmod
libnotify
libogg
libpng
libpulseaudio
librsvg
libsamplerate
libtheora
libtiff
libudev0-shim
libunwind
libusb1
libuuid
libva
libvdpau
libvorbis
libvpx
libxkbcommon
libxml2
libz
mesa
nspr
nss
openssl
pango
pipewire
pixman
speex
systemd
tbb
vulkan-loader
libice
libsm
libx11
libxscrnsaver
libxcomposite
libxcursor
libxdamage
libxext
libxfixes
libxft
libxi
libxinerama
libxmu
libxrandr
libxrender
libxt
libxtst
libxxf86vm
libxcb
libxshmfence
zlib
]
++ lib.optionals pkgs.stdenv.hostPlatform.isx86_64 [
steam-fhsenv-without-steam
];
};
};
}
4.4.2.55. Summary of NixOS-rebuild diff
This snippet is added to the activation script that is run after every rebuild and shows what packages have been added and removed. This is actually not the optimal place to add that snipped, but the correct spot is in some perl file that I have not had the leisure to take a look at yet.
{
flake.modules.nixos.nvd-rebuild = { pkgs, ... }: {
config = {
environment.systemPackages = [
pkgs.nvd
];
# system.activationScripts.diff = {
# supportsDryActivation = true;
# text = ''
# ${pkgs.nvd}/bin/nvd --color=always --nix-bin-dir=${pkgs.nix}/bin diff \
# /run/current-system "$systemConfig"
# '';
# };
};
};
}
4.4.2.56. gnome-keyring
Used for storing sessions in e.g. Nextcloud. Using this on a system level keeps the login information when logging out of the session as well.
{
flake.modules = {
homeManager.gnome-keyring =
{
lib,
nixosConfig ? null,
...
}:
{
config = {
swarselsystems.enabledHomeModules = [ "gnome-keyring" ];
services.gnome-keyring = lib.mkIf (nixosConfig == null) {
enable = true;
};
};
};
nixos.gnome-keyring.config = {
services.gnome.gnome-keyring.enable = true;
programs.seahorse.enable = true;
};
};
}
4.4.2.57. xdg-portal (Screensharing)
I only need to enable portals in general for use with Niri, which implements screen sharing using gnome-portal (which allows for neat things like hiding shared windows based on app_id).
{
flake.modules.nixos.xdg-portal.config.xdg.portal.enable = true;
}
4.4.2.58. Podman (distrobox)
I am using distrobox to quickly circumvent issues that I cannot immediately solve on NixOS (which has not happened in a while, but you never know). It is always the goal to quickly get things working on NixOS, but this should usually prevent me from getting completely stuck.
{
flake.modules.nixos.distrobox = { pkgs, confLib, ... }: {
config = {
users.persistentIds.podman = confLib.mkIds 969;
environment.systemPackages = [ pkgs.distrobox ];
virtualisation.podman = {
enable = true;
package = pkgs.podman;
dockerCompat = true;
};
};
};
}
4.4.2.59. AppImage
Adds the necessary tools to allow .AppImage programs handling easily.
{
flake.modules.nixos.appimage.config.programs.appimage = {
enable = true;
binfmt = true;
};
}
4.4.2.60. Handle lid switch correctly
This turns off the display when the lid is closed. When we are docked it just turns it off, when using the laptop standalone it instead sends it to suspend.
Notably we also make sure to handle the fingerprint sensor especially, because it can misfire or stop working on wake-up otherwise.
{
flake.modules.nixos.lid.config.services = {
acpid = {
enable = true;
handlers = {
lidClosed = {
action = ''
if grep -Fxq disabled /sys/class/backlight/amdgpu_bl1/device/enabled; then
systemctl stop fprintd
ln -s /dev/null /run/systemd/transient/fprintd.service
systemctl daemon-reload
fi
'';
event = "button/lid \\w+ close";
};
lidOpen = {
action = ''
if ! systemctl is-active --quiet fprintd; then
rm -f /run/systemd/transient/fprintd.service
systemctl daemon-reload
systemctl start fprintd
fi
'';
event = "button/lid \\w+ open";
};
};
};
logind.settings.Login = {
HandleLidSwitch = "suspend";
HandleLidSwitchDocked = "ignore";
};
};
}
4.4.2.61. Nix-on-Droid
{
flake.modules.nixOnDroid = {
packages = { pkgs, ... }: {
environment.packages = with pkgs; [
age
bzip2
cpio
croc
curl
diffutils
dig
file
gawk
gnugrep
gnupatch
gnupg
gnused
gzip
iproute2
iputils
just
ncdu
netcat-openbsd
openssh
openssl
procps
rsync
time
tree
wget
which
xz
yq-go
zstd
];
};
settings =
{
inputs,
lib,
pkgs,
...
}:
{
android-integration = {
termux-open.enable = true;
termux-open-url.enable = true;
termux-reload-settings.enable = true;
termux-setup-storage.enable = true;
xdg-open.enable = true;
};
environment = {
etcBackupExtension = ".bak";
extraOutputsToInstall = [
"doc"
"info"
"devdoc"
];
motd = null;
};
home-manager = {
config = {
swarselsystems.isPublic = true;
systemd.user.tmpfiles.rules = lib.mkForce [ ];
};
backupFileExtension = "hm-bak";
};
nix = {
extraOptions = ''
experimental-features = nix-command flakes
'';
registry.nixpkgs.flake = inputs.nixpkgs;
};
user.shell = "${pkgs.zsh}/bin/zsh";
};
swarsel-droid = { pkgs, configName, ... }: {
environment.packages = [ pkgs.swarsel-droid ];
home-manager.config.home.sessionVariables.DROID_PROFILE = "droid-${configName}";
};
};
}
4.4.2.62. Auto-login
Auto login for the initial session. This basically skips the System Login (greetd) screen.
{
flake.modules.nixos.autologin =
{ config, ... }:
{
config.services.greetd.settings.initial_session.user = config.swarselsystems.mainUser;
};
}
4.4.2.63. UWSM
UWSM is a helper tool meant to help with chaining systemd services correctly. When starting/ending sessions using it, we can be sure that the corresponding services also start and end with it - this is not standard behavior!
{
flake.modules.nixos.uwsm =
{
config,
lib,
pkgs,
...
}:
let
cfg = config.programs.uwsm;
in
{
config = {
services.displayManager.sessionPackages =
let
mk_uwsm_desktop_entry =
opts:
(pkgs.writeTextFile {
derivationArgs.passthru.providedSessions = [ "${opts.name}-uwsm" ];
destination = "/share/wayland-sessions/${opts.name}-uwsm.desktop";
name = "${opts.name}-uwsm";
text = ''
[Desktop Entry]
Name=${opts.prettyName} (UWSM)
Comment=${opts.comment}
Exec=${lib.getExe cfg.package} start -F -- ${opts.binPath} ${lib.strings.escapeShellArgs opts.extraArgs}
Type=Application
'';
});
in
lib.mkForce (
lib.mapAttrsToList (
name: value:
mk_uwsm_desktop_entry {
inherit name;
inherit (value)
binPath
comment
extraArgs
prettyName
;
}
) cfg.waylandCompositors
);
programs.uwsm = {
enable = true;
waylandCompositors.niri = lib.mkIf (config.programs ? niri) {
binPath = "/run/current-system/sw/bin/niri-session";
comment = "Niri compositor managed by UWSM";
prettyName = "Niri";
};
};
};
};
}
4.4.2.64. Firezone Client
This is the VPN client that I use to access my internal network at home.
{
flake.modules.nixos.firezone-client =
{ config, confLib, ... }:
let
inherit (config.swarselsystems) mainUser;
in
{
config = {
users.persistentIds.firezone-client = confLib.mkIds 955;
services.firezone.gui-client = {
inherit (config.node) name;
enable = true;
allowedUsers = [ mainUser ];
};
};
};
}
4.4.2.65. Niri
Auto login for the initial session.
{ config, ... }:
let
fmods = config.flake.modules;
in
{
flake-file.inputs = {
niri = {
flake = false;
url = "github:niri-wm/niri/v26.04";
};
niri-flake = {
inputs = {
niri-unstable.follows = "niri";
nixpkgs.follows = "nixpkgs";
nixpkgs-stable.follows = "nixpkgs-stable";
};
url = "github:sodiboo/niri-flake";
};
niritiling = {
inputs = {
flake-parts.follows = "flake-parts";
git-hooks-nix.follows = "pre-commit-hooks";
nixpkgs.follows = "nixpkgs";
treefmt-nix.follows = "treefmt-nix";
};
url = "github:Swarsel/niritiling";
};
};
flake.modules = {
homeManager.niri =
{
inputs,
config,
lib,
pkgs,
options,
type,
...
}:
{
imports = [
fmods.homeManager.gnome-keyring
]
++ lib.optionals (type != "nixos") [
inputs.niri-flake.homeModules.niri
];
config = {
swarselsystems.enabledHomeModules = [ "optional-niri" ];
programs.niri = {
config = options.programs.niri.config.default ++ [
(inputs.niri-flake.lib.kdl.node "workspace" "stash" [
(inputs.niri-flake.lib.kdl.leaf "hidden" true)
])
];
package = pkgs.niri-unstable; # which package to use for niri validation
settings = {
binds =
with config.lib.niri.actions;
let
sh = spawn "sh" "-c";
swarselcheck = lib.getExe (
pkgs.writeShellApplication {
name = "swarselcheck";
runtimeInputs = [
pkgs.jq
pkgs.socat
];
text = ''
case $1 in
-k)
cmd=(kitty --app-id kittyterm -T kittyterm -o confirm_os_window_close=0 zellij attach --create kittyterm)
field=app_id
search=kittyterm
;;
-e)
cmd=(element-desktop)
field=title
search=Element
;;
-d)
cmd=(vesktop)
field=app_id
search=vesktop
;;
-s)
cmd=(kitty --app-id spotifytui -T spotifytui -o confirm_os_window_close=0 spotify_player)
field=app_id
search=spotifytui
;;
esac
window=$(niri msg -j windows | jq -c --arg field "$field" --arg search "$search" 'first(.[] | select(.[$field] | test($search))) | { id, is_focused }')
id=$(jq -r '.id // empty' <<<"$window")
if [[ -z $id ]]; then
niri msg action spawn -- "''${cmd[@]}"
elif [[ $(jq -r .is_focused <<<"$window") == true ]]; then
niri msg action move-window-to-workspace --window-id "$id" --focus false stash
else
workspace=$(niri msg -j workspaces | jq -r '.[] | select(.is_focused) | .id')
jq -cn --argjson window "$id" --argjson workspace "$workspace" '{ Action: { MoveWindowToWorkspace: { window_id: $window, reference: { Id: $workspace }, focus: true } } }' | socat - "UNIX-CONNECT:$NIRI_SOCKET" >/dev/null
niri msg action focus-window --id "$id"
fi
'';
}
);
in
{
"Mod+0".action = focus-workspace 0;
"Mod+1".action = focus-workspace 1;
"Mod+2".action = focus-workspace 2;
"Mod+3".action = focus-workspace 3;
"Mod+4".action = focus-workspace 4;
"Mod+5".action = focus-workspace 5;
"Mod+6".action = focus-workspace 6;
"Mod+7".action = focus-workspace 7;
"Mod+8".action = focus-workspace 8;
"Mod+9".action = focus-workspace 9;
"Mod+Ctrl+p".action = spawn "1password";
"Mod+Down".action = focus-window-or-workspace-down;
"Mod+Equal".action = set-column-width "+10%";
"Mod+Escape".action = spawn "noctalia" "msg" "panel-toggle" "session";
"Mod+Left".action = focus-column-or-monitor-left;
"Mod+Minus".action = set-column-width "-10%";
"Mod+Return".action = sh "exec kitty -o confirm_os_window_close=0";
"Mod+Right".action = focus-column-or-monitor-right;
"Mod+Shift+0".action = move-column-to-index 0;
"Mod+Shift+1".action = move-column-to-index 1;
"Mod+Shift+2".action = move-column-to-index 2;
"Mod+Shift+3".action = move-column-to-index 3;
"Mod+Shift+4".action = move-column-to-index 4;
"Mod+Shift+5".action = move-column-to-index 5;
"Mod+Shift+6".action = move-column-to-index 6;
"Mod+Shift+7".action = move-column-to-index 7;
"Mod+Shift+8".action = move-column-to-index 8;
"Mod+Shift+9".action = move-column-to-index 9;
"Mod+Shift+Down".action = move-window-down-or-to-workspace-down;
"Mod+Shift+Equal".action = set-window-height "+10%";
"Mod+Shift+Escape".action = spawn "kitty" "-o" "confirm_os_window_close=0" "btm";
"Mod+Shift+Left".action = move-column-left-or-to-monitor-left;
"Mod+Shift+Minus".action = set-window-height "-10%";
"Mod+Shift+Right".action = move-column-right-or-to-monitor-right;
"Mod+Shift+Space".action = toggle-window-floating;
"Mod+Shift+Up".action = move-window-up-or-to-workspace-up;
"Mod+Shift+a".action = sh "exec emacsclient -ce '(swarsel/open-calendar)'";
"Mod+Shift+c".action = spawn "${lib.getExe pkgs.qalculate-gtk}";
"Mod+Shift+f".action = fullscreen-window;
"Mod+Shift+m".action = sh "exec emacsclient -ce '(mu4e)'";
"Mod+Shift+o".action = spawn "pass-fuzzel" "--otp" "--type";
"Mod+Shift+p".action = spawn "pass-fuzzel" "--type";
"Mod+Shift+s".action.screenshot-window.write-to-disk = true;
"Mod+Shift+t".action = toggle-window-rule-opacity;
"Mod+Space".action = sh "exec noctalia msg panel-toggle launcher";
"Mod+Up".action = focus-window-or-workspace-up;
"Mod+WheelScrollDown" = {
action.focus-workspace-down-under-mouse = [ ];
cooldown-ms = 150;
};
"Mod+WheelScrollLeft" = {
action = focus-column-or-monitor-left;
cooldown-ms = 150;
};
"Mod+WheelScrollRight" = {
action = focus-column-or-monitor-right;
cooldown-ms = 150;
};
"Mod+WheelScrollUp" = {
action.focus-workspace-up-under-mouse = [ ];
cooldown-ms = 150;
};
"Mod+a".action = spawn swarselcheck "-s";
"Mod+c".action = sh "exec emacsclient -ce '(org-capture)'";
"Mod+d".action = spawn swarselcheck "-d";
"Mod+e".action = sh "exec emacsclient -nquc -a emacs -e '(dashboard-open)'";
"Mod+f".action = sh "exec glide";
"Mod+h".action = sh "${lib.getExe pkgs.hyprpicker} | wl-copy";
"Mod+i".action = spawn "noctalia" "msg" "panel-toggle" "launcher" "/emo";
"Mod+m".action = focus-workspace-previous;
"Mod+o".action = spawn "pass-fuzzel" "--otp";
"Mod+p".action = spawn "pass-fuzzel";
"Mod+q".action = sh "niri msg action close-window";
"Mod+s".action.screenshot.show-pointer = false;
"Mod+t".action = sh "exec emacsclient -ce '(org-agenda)'";
"Mod+w".action = spawn swarselcheck "-e";
"Mod+x".action = spawn swarselcheck "-k";
"Mod+z".action = spawn "noctalia" "msg" "bar-toggle";
XF86AudioLowerVolume.action = spawn "noctalia" "msg" "volume-down";
XF86AudioMute.action = spawn "noctalia" "msg" "volume-mute";
XF86AudioNext.action = spawn "noctalia" "msg" "media" "next";
XF86AudioPlay.action = spawn "noctalia" "msg" "media" "toggle";
XF86AudioPrev.action = spawn "noctalia" "msg" "media" "previous";
XF86AudioRaiseVolume.action = spawn "noctalia" "msg" "volume-up";
XF86Display.action = spawn "wl-mirror" "eDP-1";
XF86MonBrightnessDown.action = spawn "noctalia" "msg" "brightness-down";
XF86MonBrightnessUp.action = spawn "noctalia" "msg" "brightness-up";
};
cursor = {
hide-after-inactive-ms = 2000;
hide-when-typing = true;
};
debug.honor-xdg-activation-with-invalid-serial = [ ];
environment = {
inherit (config.home.sessionVariables) EDITOR;
NIXOS_OZONE_WL = "1";
_JAVA_AWT_WM_NONREPARENTING = "1";
};
gestures.hot-corners.enable = false;
hotkey-overlay.skip-at-startup = true;
input = {
keyboard.xkb = {
layout = "us";
variant = "altgr-intl";
};
mod-key = "Super";
mouse.natural-scroll = false;
touchpad = {
enable = true;
click-method = "clickfinger";
disabled-on-external-mouse = true;
drag = true;
drag-lock = false;
dwt = true;
dwtp = true;
natural-scroll = true;
scroll-method = "two-finger";
tap = true;
tap-button-map = "left-right-middle";
};
};
layer-rules = [
{
block-out-from = "screen-capture";
matches = [ { namespace = "^noctalia-notification$"; } ];
}
{
matches = [ { namespace = "^wallpaper$"; } ];
place-within-backdrop = true;
}
{
matches = [ { namespace = "^noctalia-overview*"; } ];
place-within-backdrop = true;
}
];
layout = {
background-color = "transparent";
border = {
enable = true;
width = 1;
};
focus-ring.enable = false;
gaps = 5;
};
outputs = lib.mapAttrs' (
_: monitor:
lib.nameValuePair monitor.output (
let
mode = lib.splitString "x" monitor.mode;
position = lib.splitString "," monitor.position;
in
{
mode = {
height = lib.toInt (builtins.elemAt mode 1);
width = lib.toInt (builtins.elemAt mode 0);
};
position = {
x = lib.toInt (builtins.elemAt position 0);
y = lib.toInt (builtins.elemAt position 1);
};
scale = builtins.fromJSON monitor.scale;
transform.rotation = lib.toInt (monitor.transform or "0");
}
)
) config.swarselsystems.monitors;
prefer-no-csd = true;
screenshot-path = "~/Pictures/Screenshots/screenshot_%Y-%m-%d-%H%M%S.png";
spawn-at-startup = [
{
argv = [
"systemctl"
"--user"
"restart"
"noctalia-shell.target"
];
}
];
window-rules = [
{
clip-to-geometry = true;
default-column-width.proportion = 0.5;
geometry-corner-radius = {
bottom-left = 5.0;
bottom-right = 5.0;
top-left = 5.0;
top-right = 5.0;
};
matches = [ { app-id = ".*"; } ];
opacity = 0.95;
shadow = {
enable = true;
draw-behind-window = true;
};
}
{
matches = [ { app-id = "at.yrlf.wl_mirror"; } ];
opacity = 1.0;
}
{
matches = [ { app-id = "Gimp"; } ];
opacity = 1.0;
}
{
matches = [
{ app-id = "^glide$"; }
];
opacity = 0.95;
}
{
default-column-width.proportion = 0.9;
matches = [ { app-id = "^special.*"; } ];
open-on-workspace = "Scratchpad";
}
{
matches = [ { app-id = "chromium-browser"; } ];
opacity = 0.99;
}
{
matches = [ { app-id = "^qalculate-gtk$"; } ];
open-floating = true;
}
{
matches = [ { app-id = "^blueman$"; } ];
open-floating = true;
}
{
matches = [ { app-id = "^pavucontrol$"; } ];
open-floating = true;
}
{
matches = [ { app-id = "^syncthingtray$"; } ];
open-floating = true;
}
{
block-out-from = "screen-capture";
default-column-width.proportion = 0.5;
matches = [ { app-id = "^Element$"; } ];
open-floating = true;
}
{
block-out-from = "screen-capture";
default-column-width.proportion = 0.5;
matches = [ { title = "^Element"; } ];
open-floating = true;
}
{
block-out-from = "screen-capture";
default-column-width.proportion = 0.5;
matches = [ { app-id = "^vesktop$"; } ];
open-floating = true;
}
{
matches = [ { app-id = "^com.nextcloud.desktopclient.nextcloud$"; } ];
open-floating = true;
}
{
block-out-from = "screen-capture";
excludes = [
{ app-id = "^glide$"; }
{ app-id = "^emacs$"; }
{ app-id = "^kitty$"; }
];
matches = [ { title = ".*1Password.*"; } ];
open-floating = true;
}
{
matches = [ { title = "(?:Open|Save) (?:File|Folder|As)"; } ];
open-floating = true;
}
{
matches = [ { title = "^Add$"; } ];
open-floating = true;
}
{
matches = [ { title = "^Picture-in-Picture$"; } ];
open-floating = true;
}
{
matches = [ { title = "Syncthing Tray"; } ];
open-floating = true;
}
{
matches = [ { title = "^Emacs Popup Frame$"; } ];
open-floating = true;
}
{
matches = [ { title = "^Emacs Popup Anchor$"; } ];
open-floating = true;
}
{
default-column-width.proportion = 0.5;
matches = [ { app-id = "^spotifytui$"; } ];
open-floating = true;
}
{
default-column-width.proportion = 0.5;
matches = [ { app-id = "^kittyterm$"; } ];
open-floating = true;
}
];
xwayland-satellite = {
enable = true;
path = "${lib.getExe pkgs.xwayland-satellite-unstable}";
};
};
};
home = {
packages = [
pkgs.nirius
(pkgs.writeShellApplication {
name = "e-niri";
runtimeInputs = [
pkgs.emacs-pgtk
pkgs.jq
];
text = ''
wait=0
if [[ ''${1:-} == -w || ''${1:-} == --wait ]]; then
wait=1
shift
fi
id=$(niri msg -j windows | jq -r 'first(.[] | select(.app_id == "kittyterm")) | .id')
if [[ -n $id ]]; then
niri msg action close-window --id "$id"
emacsclient -c -a "" "$@"
niri msg action spawn -- kitty --app-id kittyterm -T kittyterm -o confirm_os_window_close=0 zellij attach --create kittyterm
elif [[ $wait -eq 1 ]]; then
emacsclient -c -a "" "$@"
else
emacsclient -n -c -a "" "$@"
fi
'';
})
];
sessionVariables.EDITOR = lib.mkDefault "e-niri -w";
};
xdg.portal = {
config.niri = {
default = [
"gtk"
"gnome"
];
"org.freedesktop.impl.portal.Access" = [ "gtk" ];
"org.freedesktop.impl.portal.FileChooser" = [ "gtk" ];
"org.freedesktop.impl.portal.Notification" = [ "gtk" ];
"org.freedesktop.impl.portal.RemoteDesktop" = [ "luminous" ];
"org.freedesktop.impl.portal.ScreenCast" = [ "gnome" ];
"org.freedesktop.impl.portal.Screenshot" = [ "gnome" ];
"org.freedesktop.impl.portal.Secret" = [ "gnome-keyring" ];
};
enable = true;
extraPortals = [
pkgs.gnome-keyring
pkgs.xdg-desktop-portal-gtk
pkgs.xdg-desktop-portal-gnome
pkgs.xdg-desktop-portal-luminous
];
xdgOpenUsePortal = true;
};
};
};
nixos.niri = { inputs, lib, ... }: {
imports = lib.optionals (inputs ? niritiling) [
inputs.niri-flake.nixosModules.niri
inputs.niritiling.nixosModules.default
({ config, pkgs, ... }: {
services.niritiling = {
enable = true;
columnTargets =
lib.mapAttrs' (_: monitor: lib.nameValuePair monitor.name (lib.toInt monitor.columns))
(
lib.filterAttrs (
_: monitor: monitor ? columns
) config.home-manager.users.${config.swarselsystems.mainUser}.swarselsystems.monitors
);
resizeColumns = true;
};
programs.niri = {
enable = true;
package = pkgs.niri-unstable;
};
environment.systemPackages = with pkgs; [
wayland-utils
gamescope
xwayland-satellite-unstable
];
home-manager.users.${config.swarselsystems.mainUser}.imports = [
fmods.homeManager.niri
];
niri-flake.cache.enable = true;
xdg.portal.extraPortals = [ pkgs.xdg-desktop-portal-luminous ];
})
];
};
};
}
4.4.2.66. Noctalia
{ config, ... }:
let
fmods = config.flake.modules;
in
{
flake-file.inputs = {
noctalia = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:noctalia-dev/noctalia-shell";
};
noctoggle = {
inputs = {
flake-parts.follows = "flake-parts";
git-hooks-nix.follows = "pre-commit-hooks";
nixpkgs.follows = "nixpkgs";
treefmt-nix.follows = "treefmt-nix";
};
url = "github:Swarsel/noctoggle";
};
};
flake.modules = {
homeManager.noctalia =
{
root,
inputs,
config,
lib,
pkgs,
confLib,
...
}:
let
inherit (confLib.getConfig.repo.secrets.common) caldavTasksEndpoint;
brightnessctl = lib.getExe pkgs.brightnessctl;
in
{
imports = [
inputs.noctalia.homeModules.default
];
options.swarselsystems.noctalia-systemd = lib.swarselsystems.mkTrueOption;
config = {
swarselsystems.enabledHomeModules = [ "optional-noctalia" ];
programs.noctalia = {
enable = true;
package = pkgs.noctalia;
settings = {
audio = {
enable_overdrive = false;
enable_sounds = false;
};
bar.main = {
auto_hide = false;
background_opacity = 0.5;
border_width = 0.0;
capsule = false;
center = [
"active_window"
"recorder_2"
];
color = "on_surface";
compositor_blur = false;
end = [
"tray"
"volume"
"network"
"bluetooth"
"battery"
"spacer_1"
"clock"
"control-center"
];
font_weight = 500;
margin_edge = 0;
margin_ends = 0;
position = "top";
radius = 12;
reserve_space = false;
scale = 1.1;
start = [ "workspaces" ];
thickness = 40;
widget_spacing = 10;
};
battery = {
device."/org/freedesktop/UPower/devices/battery_hidpp_battery_3".warning_threshold = 15;
warning_threshold = 20;
};
brightness.enable_ddcutil = false;
calendar = {
account.caldav = {
name = "CalDAV";
provider = "custom";
server_url = caldavTasksEndpoint;
type = "caldav";
username = config.swarselsystems.mainUser;
};
enabled = true;
};
control_center = {
shortcuts = [
{ type = "wifi"; }
{ type = "bluetooth"; }
{ type = "notification"; }
{ type = "caffeine"; }
{ type = "clipboard"; }
{ type = "power_profile"; }
];
sidebar = "compact";
sidebar_section = "compact";
};
desktop_widgets.enabled = false;
dock = {
background_opacity = 1.0;
enabled = false;
};
idle = {
behavior = {
dim = {
action = "command";
command = "${brightnessctl} -s; ${brightnessctl} set 80%-";
enabled = true;
resume_command = "${brightnessctl} -r";
timeout = 60;
};
lock = {
action = "lock";
enabled = true;
timeout = 300;
};
suspend = {
action = "lock_and_suspend";
enabled = true;
timeout = 600;
};
};
behavior_order = [
"dim"
"lock"
"suspend"
];
pre_action_fade_seconds = 0.0;
};
location = {
address = confLib.getConfig.repo.secrets.common.location.timezoneSpecific;
auto_locate = false;
};
lockscreen = {
blurred_desktop = true;
monitors = [ "eDP-2" ];
};
lockscreen_widgets = {
enabled = true;
grid = {
cell_size = 64;
major_interval = 4;
visible = true;
};
schema_version = 2;
widget = {
"lockscreen-login-box@eDP-2" = {
box_height = 0.0;
box_width = 0.0;
cx = 853.5;
cy = 981.5;
enabled = true;
output = "eDP-2";
rotation = 0.0;
type = "login_box";
};
lockscreen-widget-0000000000000001 = {
box_height = 192.0;
box_width = 192.0;
cx = 853.5;
cy = 789.5;
enabled = true;
output = "eDP-2";
rotation = 0.0;
settings.background = false;
type = "fancy_audio_visualizer";
};
lockscreen-widget-0000000000000002 = {
box_height = 0.0;
box_width = 0.0;
cx = 853.5;
cy = 533.5;
enabled = true;
output = "eDP-2";
rotation = 0.0;
settings = {
background = false;
image_path = root "files/icons/swarsel.png";
opacity = 1.0;
};
type = "sticker";
};
};
widget_order = [
"lockscreen-login-box@eDP-2"
"lockscreen-widget-0000000000000001"
"lockscreen-widget-0000000000000002"
];
};
nightlight = {
enabled = true;
force = false;
temperature_day = 5500;
temperature_night = 3700;
};
notification = {
background_opacity = lib.mkForce 0.8;
enable_daemon = true;
follow_focused_output = true;
layer = "overlay";
max_visible = 3;
position = "top_right";
};
osd = {
background_opacity = 0.5;
orientation = "vertical";
position = "center_right";
position_vertical = "center_right";
};
plugin_settings."noctalia/screen_recorder" = {
audio_codec = "opus";
audio_source = "default_output";
color_range = "limited";
copy_to_clipboard = true;
filename_pattern = "recording_%Y%m%d_%H%M%S";
frame_rate = 60;
hide_inactive = true;
resolution = "original";
show_cursor = true;
video_codec = "h264";
video_quality = "very_high";
video_source = "portal";
};
plugins.enabled = [
"noctalia/screen_recorder"
"noctalia/kaomoji"
"whyoolw/sharednd"
];
shell = {
animation = {
enabled = true;
speed = 4.0;
};
avatar_path = root "files/icons/swarsel.png";
clipboard_auto_paste = "off";
clipboard_enabled = true;
external_ip_enabled = true;
launch_apps_as_systemd_services = true;
launcher = {
categories = false;
compact = true;
show_icons = true;
};
panel = {
control_center_placement = "attached";
launcher_placement = "floating";
launcher_position = "center";
open_near_click_control_center = true;
session_placement = "floating";
session_position = "center";
transparency_mode = "solid";
};
screen_corners.enabled = false;
session.actions = [
{
action = "lock";
shortcut = "l";
}
{
action = "suspend";
shortcut = "s";
}
{
action = "command";
command = "systemctl hibernate";
glyph = "suspend";
label = "Hibernate";
shortcut = "h";
}
{
action = "reboot";
shortcut = "r";
}
{
action = "logout";
shortcut = "u";
}
{
action = "shutdown";
shortcut = "p";
}
{
action = "command";
command = "systemctl reboot --firmware-setup";
glyph = "reboot";
label = "Reboot to UEFI";
shortcut = "b";
}
];
settings_show_advanced = true;
shadow.direction = "center";
telemetry_enabled = false;
time_format = "{:%H:%M}";
};
system.monitor = {
cpu_poll_seconds = 1.0;
cpu_temp_activity_threshold = 80.0;
cpu_temp_critical_threshold = 90.0;
cpu_usage_activity_threshold = 80.0;
cpu_usage_critical_threshold = 90.0;
disk_poll_seconds = 30.0;
disk_used_pct_activity_threshold = 80.0;
disk_used_pct_critical_threshold = 90.0;
enabled = true;
gpu_poll_seconds = 3.0;
gpu_temp_activity_threshold = 80.0;
gpu_temp_critical_threshold = 90.0;
gpu_usage_activity_threshold = 80.0;
gpu_usage_critical_threshold = 90.0;
memory_poll_seconds = 1.0;
network_poll_seconds = 1.0;
ram_pct_activity_threshold = 80.0;
ram_pct_critical_threshold = 90.0;
swap_pct_activity_threshold = 80.0;
swap_pct_critical_threshold = 90.0;
};
theme = {
custom_palette = "stylix";
mode = "dark";
source = "custom";
templates = {
enable_builtin_templates = false;
enable_community_templates = false;
};
};
wallpaper = {
automation = {
enabled = true;
interval_seconds = 300;
order = "random";
recursive = true;
};
directory = root "files/wallpaper/landscape";
edge_smoothness = 0.05;
enabled = true;
fill_mode = "crop";
transition = [
"fade"
"wipe"
"disc"
"stripes"
"zoom"
"honeycomb"
];
transition_duration = 500.0;
};
weather = {
effects = false;
enabled = true;
unit = "celsius";
};
widget = {
active_window = {
display = "icon_and_text";
max_length = 300;
title_scroll = "on_hover";
};
battery = {
device = "auto";
display_mode = "graphic";
hide_when_full = true;
show_label = true;
};
bluetooth = {
hide_when_no_connected_device = true;
show_label = true;
};
clock = {
format = "{:%a %d. %b %H:%M:%S}";
tooltip_format = "{:%a %d. %b %H:%M:%S}";
};
control-center = {
custom_image = root "files/icons/swarsel.png";
custom_image_colorize = true;
glyph = "noctalia";
};
network.show_label = false;
notifications.hide_when_no_unread = false;
spacer_1.type = "spacer";
tray = {
drawer = true;
hidden = [ "bluetooth" ];
};
volume = {
device = "output";
show_label = true;
};
workspaces = {
empty_color = "primary";
focused_color = "primary";
hide_when_empty = true;
label_source = "name";
labels_only_when_occupied = false;
max_label_chars = 4;
occupied_color = "primary";
};
};
};
systemd.enable = config.swarselsystems.noctalia-systemd;
};
systemd.user = lib.mkMerge [
{ sessionVariables.TERMINAL = "kitty"; }
(lib.mkIf config.swarselsystems.noctalia-systemd {
services = {
noctalia = {
Install.WantedBy = [ "noctalia-shell.target" ];
Unit.PartOf = [ "noctalia-shell.target" ];
};
noctalia-init = {
Install.WantedBy = [ "tray.target" ];
Service = {
ExecStart = "${pkgs.coreutils}/bin/sleep 3";
RemainAfterExit = true;
Type = "oneshot";
};
Unit = {
After = [ "noctalia.service" ];
Requires = [ "noctalia.service" ];
};
};
};
targets = {
noctalia-shell.Unit.After = [ "graphical-session.target" ];
tray = {
Install.WantedBy = [ "noctalia-shell.target" ];
Unit = {
After = [
"noctalia.service"
"noctalia-init.service"
];
Wants = [ "noctalia-init.service" ];
};
};
};
})
];
};
};
nixos.noctalia = { inputs, lib, ... }: {
imports = lib.optionals (inputs ? noctoggle) [
inputs.noctoggle.nixosModules.default
(
{
inputs,
config,
pkgs,
...
}:
{
imports = [
"${inputs.nixpkgs-dev}/nixos/modules/programs/gpu-screen-recorder.nix"
];
services = {
gnome.evolution-data-server.enable = false;
noctoggle = {
enable = true;
hideCommand = "${lib.getExe pkgs.noctalia} msg bar-hide";
noctaliaPackage = pkgs.noctalia;
showCommand = "${lib.getExe pkgs.noctalia} msg bar-show";
};
upower.enable = true; # needed for battery percentage
};
programs = {
evolution.enable = false;
gpu-screen-recorder.enable = true;
};
disabledModules = [ "programs/gpu-screen-recorder.nix" ];
home-manager.users.${config.swarselsystems.mainUser}.imports = [
fmods.homeManager.noctalia
];
systemd.services.lock-before-sleep = {
before = [ "sleep.target" ];
serviceConfig = {
ExecStart = "${pkgs.systemd}/bin/loginctl lock-sessions";
Type = "oneshot";
};
wantedBy = [ "sleep.target" ];
};
}
)
];
};
};
}
4.4.2.67. gaming
This opens a few gaming ports and installs the steam configuration suite for gaming. There are more options in Gaming (home-manager side).
{ config, lib, ... }:
let
fmods = config.flake.modules;
in
{
flake.modules = {
homeManager.gaming =
{
pkgs,
confLib,
nixosConfig ? null,
...
}:
{
config = {
programs.lutris = {
enable = true;
extraPackages = with pkgs; [
winetricks
gamescope
umu-launcher
];
protonPackages = with pkgs; [
proton-ge-bin
];
steamPackage = if nixosConfig != null then confLib.getConfig.programs.steam.package else pkgs.steam;
winePackages = with pkgs; [
wineWow64Packages.waylandFull
];
};
# specialisation = {
# gaming.configuration = {
home.packages = with pkgs; [
# lutris
wine
protonplus
winetricks
dwarfs
fuse-overlayfs
# steam
steam-run
patchelf
gamescope
vulkan-tools
(symlinkJoin {
buildInputs = [ makeWrapper ];
name = "moonlight-qt";
paths = [ moonlight-qt ];
postBuild = ''
wrapProgram $out/bin/moonlight \
--set-default SDL_MOUSE_RELATIVE_SYSTEM_SCALE 1
'';
})
ns-usbloader
quark-goldleaf
# gog games installing
heroic
# minecraft
prismlauncher # has overrides
temurin-bin-17
retroarch
];
# };
# };
};
};
nixos.gaming =
{
config,
pkgs,
withHomeManager,
...
}:
lib.mkMerge [
{
programs.steam = {
enable = true;
package = pkgs.steam;
extraCompatPackages = [
pkgs.proton-ge-bin
];
};
}
(lib.mkIf withHomeManager {
home-manager.users."${config.swarselsystems.mainUser}".imports = [
fmods.homeManager.gaming
];
})
];
};
}
4.4.2.68. work
Options that I need specifically at work. There are more options at Work (home-manager side).
When setting up a new machine:
- setup the work VPN:
- using the laptop certificate `.pem` as User cert and private key (CA cert: none)
- vpn gateway is found in `nixosConfig.repo.secrets.local.work.vpnGateway`
{ config, ... }:
let
fmods = config.flake.modules;
in
{
flake-file.inputs.vbc-nix = {
inputs = {
nixpkgs.follows = "nixpkgs-stable26_05";
nixpkgs-2411.follows = "nixpkgs-stable24_11";
nixpkgs-mcp.follows = "nixpkgs-stable26_05";
nixpkgs-mcp-unstable.follows = "nixpkgs";
nixpkgs-unstable.follows = "nixpkgs";
systems.follows = "systems";
};
url = "git+ssh://git@github.com/vbc-it/vbc-nix.git?ref=main";
};
flake.modules = {
homeManager.work = {
imports = [
fmods.homeManager.work-mail
fmods.homeManager.work-dev
fmods.homeManager.work-desktop
];
config.swarselsystems.enabledHomeModules = [ "optional-work" ];
};
nixos.work =
{
inputs,
config,
lib,
pkgs,
confLib,
withHomeManager,
...
}:
let
inherit (config.swarselsystems) homeDir mainUser;
in
{
options.swarselsystems = {
fqdn = lib.mkOption {
default = "";
type = lib.types.str;
};
hostName = lib.mkOption {
default = config.node.name;
type = lib.types.str;
};
};
config = {
sops = {
secrets =
lib.genAttrs
[
"automationhubtoken"
"vcuser"
"vcpw"
"govcuser"
"govcpw"
"govcurl"
"govcdc"
"govcds"
"govchost"
"govcnetwork"
"govcpool"
"baseuser"
"basepw"
"vbc-guest-pw"
"vpn-cert"
]
(_: {
owner = mainUser;
rekey.keyPrefix = confLib.static.sharedSecrets.work;
});
templates."network-manager-work.env".content = ''
BASEUSER=${config.sops.placeholder.baseuser}
BASEPASS=${config.sops.placeholder.basepw}
VBC_GUEST_PW=${config.sops.placeholder.vbc-guest-pw}
'';
};
services = {
openssh.enable = true;
syncthing.settings = {
folders.Documents = {
devices = [ "moonside@oracle" ];
id = "hgr3d-pfu3w";
path = "${homeDir}/Documents";
};
"moonside@oracle".id = "VPCDZB6-MGVGQZD-Q6DIZW3-IZJRJTO-TCC3QUQ-2BNTL7P-AKE7FBO-N55UNQE";
winters.id = "O7RWDMD-AEAHPP7-7TAVLKZ-BSWNBTU-2VA44MS-EYGUNBB-SLHKB3C-ZSLMOAA";
};
# udev.extraRules = ''
# # lock screen when yubikey removed
# ACTION=="remove", ENV{PRODUCT}=="3/1050/407/110", RUN+="${pkgs.systemd}/bin/systemctl suspend"
# '';
};
programs = {
_1password.enable = true;
_1password-gui = {
enable = true;
package = pkgs._1password-gui;
polkitPolicyOwners = [ mainUser ];
};
browserpass.enable = true;
};
boot.initrd.services.udev.rules = ''
ACTION=="add", SUBSYSTEM=="thunderbolt", ATTR{authorized}=="0", ATTR{authorized}="1"
'';
environment = {
etc."1password/custom_allowed_browsers" = {
mode = "0755";
text = ''
glide
'';
};
systemPackages = with pkgs; [
qemu
# vm
virt-manager
virtiofsd
spice
spice-gtk
virtio-win
win-spice
];
};
networking = {
inherit (config.swarselsystems) fqdn hostName;
networkmanager = {
ensureProfiles = {
environmentFiles = [ config.sops.templates."network-manager-work.env".path ];
profiles = config.repo.secrets.work.network.profiles;
};
wifi.scanRandMacAddress = false;
};
nftables = {
chains.postrouting.libvirt-masq = {
after = [ "dnat" ];
rules = [
"iifname \"virbr*\" masquerade"
];
};
firewall = {
rules = {
virbr-dns-dhcp = {
allowedTCPPorts = [ 53 ];
allowedUDPPorts = [
53
67
547
];
from = [ "virbr" ];
to = [ "local" ];
};
virbr-forward = {
from = [ "virbr" ];
to = [ "untrusted" ];
verdict = "accept";
};
virbr-forward-return = {
extraLines = [
"ct state { established, related } accept"
];
from = [ "untrusted" ];
to = [ "virbr" ];
};
};
zones.virbr.interfaces = [ "virbr*" ];
};
};
search = [
"vbc.ac.at"
"clip.vbc.ac.at"
"imp.univie.ac.at"
];
};
nixpkgs.overlays = [
(
final: prev:
lib.getAttrs config.repo.secrets.work.overlayPackages (inputs.vbc-nix.overlays.default final prev)
)
];
repo.secretFiles.work = ../../../secrets/work/pii.nix.enc;
virtualisation = {
docker.enable = !config.virtualisation.podman.dockerCompat;
libvirtd = {
enable = true;
qemu = {
package = pkgs.qemu_kvm;
runAsRoot = true;
swtpm.enable = true;
vhostUserPackages = with pkgs; [ virtiofsd ];
};
};
spiceUSBRedirection.enable = true;
};
systemd.services = {
virtnetworkd.path = with pkgs; [
dnsmasq
iproute2
nftables
];
virtqemud.path = with pkgs; [
qemu_kvm
libvirt
];
virtstoraged.path = with pkgs; [
qemu_kvm
libvirt
];
};
# cgroups v1 is required for centos7 dockers
# specialisation = {
# cgroup_v1.configuration = {
# boot.kernelParams = [
# "SYSTEMD_CGROUP_ENABLE_LEGACY_FORCE=1"
# "systemd.unified_cgroup_hierarchy=0"
# ];
# };
# };
}
// lib.optionalAttrs withHomeManager {
home-manager.users.${mainUser}.imports = [
fmods.homeManager.work
];
};
};
};
}
4.4.2.69. Work (dev, pizauth)
The rest of the settings is at work. Here, I am setting up the different Firefox profiles that I need for the SSO sites that I need to access at work as well as a few ssh shorthands.
When setting up a new machine:
- setup pizauth for microsoft mail sync (account names are possibly `uni` and `work`):
- `pizauth auth <account name, e.g. 'work'>`
- `pizauth dump > ~/.pizauth.state`
{
flake.modules.homeManager.work-dev =
{
config,
lib,
pkgs,
confLib,
glideProfile,
osConfig,
...
}:
let
inherit (config.swarselsystems) homeDir;
inherit (confLib.getConfig.repo.secrets.work)
browser
clouds
githubOrgs
path1
sshCertificateLogin
sshConfig
sshKnownHosts
user1
user1Long
user2
user2Long
user3
user3Long
;
containerSites = lib.zipAttrsWith (_: lib.concatLists) [
confLib.getConfig.repo.secrets.common.browser.containerSites
browser.containerSites
];
step = pkgs.writeShellApplication {
name = "step";
runtimeInputs = [ pkgs.procps ];
text = ''
${lib.optionalString config.programs.glide-browser.enable ''
if [[ ''${1-} == ssh && ''${2-} == login ]] && ! pgrep -x .glide-wrapped >/dev/null; then
niri msg action spawn -- glide >/dev/null
sleep 5
fi
''}
exec ${pkgs.step-cli}/bin/step "$@"
'';
};
in
{
imports = [ osConfig.repo.secrets.work.default ];
config = {
swarselsystems.homeSopsSecrets =
lib.genAttrs [ "ucKey" "yubikey-1" "yubikey-2" "yubikey-3" ] (_: {
rekey.keyPrefix = confLib.static.sharedSecrets.work;
})
// {
harica-root-ca = {
path = "${homeDir}/.aws/certs/harica-root.pem";
rekey.keyPrefix = confLib.static.sharedSecrets.clients;
};
};
programs = {
awscli = {
enable = true;
package = pkgs.awscli2;
};
chromium = {
enable = true;
package = pkgs.chromium;
extensions = [
# 1password
"gejiddohjgogedgjnonbofjigllpkmbf"
# dark reader
"eimadpbcbfnmbkopoojfekhnkhdbieeh"
# ublock origin
"cjpalhdlnbpafiamejdnhcphjbkeiagm"
# i still dont care about cookies
"edibdbjcniadpccecjdfdjjppcpchdlm"
# browserpass
"naepdomgkenhinolocfifgehidddafch"
];
};
git.settings.url = lib.genAttrs' githubOrgs (
org: lib.nameValuePair "git@github.com:${org}/" { insteadOf = "https://github.com/${org}/"; }
);
glide-browser = lib.mkIf config.programs.glide-browser.enable {
config = lib.mkAfter ''
for (const [container, prefixes] of Object.entries(${builtins.toJSON containerSites})) {
container_rules.push(...prefixes.map((prefix) => ({ prefix, container })));
}
add_site_shortcuts(${builtins.toJSON browser.siteShortcuts});
'';
profiles =
let
mkProfile = attrs: lib.recursiveUpdate glideProfile ({ isDefault = false; } // attrs);
in
{
"${user1}" = mkProfile {
id = 1;
settings."browser.startup.homepage" = lib.concatStringsSep "|" browser.startPages.${user1};
};
"${user2}" = mkProfile {
id = 2;
settings."browser.startup.homepage" = lib.concatStringsSep "|" browser.startPages.${user2};
};
"${user3}" = mkProfile { id = 3; };
default = {
containers = {
"${user1}" = {
color = "blue";
icon = "briefcase";
id = 1;
};
"${user2}" = {
color = "orange";
icon = "fingerprint";
id = 2;
};
"${user3}" = {
color = "green";
icon = "circle";
id = 3;
};
work = {
color = "purple";
icon = "briefcase";
id = 4;
};
};
containersForce = true;
settings = {
"privacy.userContext.enabled" = true;
"privacy.userContext.ui.enabled" = true;
};
};
};
};
openstackclient = {
enable = true;
cloudsSettings = { inherit clouds; };
};
ssh = {
extraConfig = lib.mkAfter (sshCertificateLogin pkgs step);
settings = lib.recursiveUpdate sshConfig {
"*".userKnownHostsFile = lib.mkForce "~/.ssh/known_hosts ~/.ssh/known_hosts_work";
};
};
zsh = {
cdpath = [
"~/Documents/Work"
];
dirHashes = {
ac = path1;
d = "$HOME/.dotfiles";
pr = "$HOME/Documents/Private";
s = "$HOME/.dotfiles/secrets";
w = "$HOME/Documents/Work";
};
initContent = ''
_vbc_ansible_env() {
local tmpl=ansible-2_$1
local flake="git+ssh://git@github.com/vbc-it/vbc-nix?ref=main&dir=templates/$tmpl"
if [[ -e $HOME/Documents/Work/vbc-nix/templates/$tmpl/flake.nix ]]; then
flake=path:$HOME/Documents/Work/vbc-nix/templates/$tmpl
fi
mkdir -p $HOME/.local/state/nix/profiles/devshells
nix develop --profile $HOME/.local/state/nix/profiles/devshells/vbc-$tmpl "$flake" -c zsh
}
a215() { _vbc_ansible_env 15; }
a220() { _vbc_ansible_env 20; }
'';
sessionVariables =
lib.mapAttrs (_: secret: "$(cat ${confLib.getConfig.sops.secrets.${secret}.path})")
{
ANSIBLE_GALAXY_SERVER_COMMUNITY_TOKEN = "automationhubtoken";
ANSIBLE_GALAXY_SERVER_PUBLISHED_TOKEN = "automationhubtoken";
ANSIBLE_GALAXY_SERVER_RH_CERTIFIED_TOKEN = "automationhubtoken";
ANSIBLE_GALAXY_SERVER_STAGING_TOKEN = "automationhubtoken";
GOVC_DATACENTER = "govcdc";
GOVC_DATASTORE = "govcds";
GOVC_HOST = "govchost";
GOVC_NETWORK = "govcnetwork";
GOVC_PASSWORD = "govcpw";
GOVC_RESOURCE_POOL = "govcpool";
GOVC_URL = "govcurl";
GOVC_USERNAME = "govcuser";
VSPHERE_PW = "vcpw";
VSPHERE_USER = "vcuser";
};
shellAliases = {
cssh = "ssh -l ${user2Long}";
dssh = "ssh -l ${user1Long}";
step = lib.getExe step;
wssh = "ssh -l ${user3Long}";
};
};
};
home = {
file = {
".glide-browser/native-messaging-hosts/com.1password.1password.json" =
lib.mkIf config.programs.glide-browser.enable
{
text = builtins.toJSON {
allowed_extensions = [
"{0a75d802-9aed-41e7-8daa-24c067386e82}"
"{25fc87fa-4d31-4fee-b5c1-c32a7844c063}"
"{d634138d-c276-4fc8-924b-40a0ea21d284}"
];
description = "1Password BrowserSupport";
name = "com.1password.1password";
path = "/run/wrappers/bin/1Password-BrowserSupport";
type = "stdio";
};
};
".ssh/known_hosts_work".text = sshKnownHosts;
};
packages = with pkgs; [
teams-for-linux
shellcheck
dig
docker
postman
# rclone
# libguestfs-with-appliance
prometheus.cli
tigervnc
# openstackclient
step-cli
openshift
rustdesk-vbc
remmina
packer
gnumake
libisoburn
govc
opentofu
terragrunt
graphviz
azure-cli
gh
];
sessionVariables.AWS_CA_BUNDLE = confLib.getConfig.sops.secrets.harica-root-ca.path;
};
xdg = {
desktopEntries = lib.genAttrs' [ user1 user2 user3 ] (
profile:
lib.nameValuePair "glide_${profile}" {
categories = [ "Application" ];
exec = "glide -p ${profile}";
genericName = "Glide ${profile}";
icon = "glide";
name = "Glide (${profile})";
terminal = false;
}
);
mimeApps.defaultApplications."x-scheme-handler/msteams" = [ "teams-for-linux.desktop" ];
};
systemd.user = {
services = {
onepassword-applet = confLib.mkTrayApplet {
description = "1password applet";
execStart = lib.getExe osConfig.programs._1password-gui.package;
};
teams-applet = confLib.mkTrayApplet {
description = "teams applet";
execStart = "${pkgs.teams-for-linux}/bin/teams-for-linux --performance.disableGpu=true --window.minimized=true --tray.enabled=true";
};
};
sessionVariables.DOCUMENT_DIR_WORK = "${homeDir}/Documents/Work";
};
};
};
}
4.4.2.70. Work (mail)
{
flake.modules.homeManager.work-mail =
{
config,
lib,
pkgs,
confLib,
...
}:
let
inherit (config.swarselsystems) homeDir;
inherit (confLib.getConfig.repo.secrets.work) mailAddress;
notifySend = lib.getExe' pkgs.libnotify "notify-send";
in
{
config = {
services.pizauth = {
enable = true;
accounts.work = {
authUri = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize";
clientId = "08162f7c-0fd2-4200-a84a-f25a4db0b584";
clientSecret = "TxRBilcHdC6WGBee]fs?QR:SJ8nI[g82";
loginHint = mailAddress;
scopes = [
"https://outlook.office365.com/IMAP.AccessAsUser.All"
"https://outlook.office365.com/SMTP.Send"
"offline_access"
];
tokenUri = "https://login.microsoftonline.com/common/oauth2/v2.0/token";
};
extraConfig = ''
auth_notify_cmd = "if [[ \"$(${notifySend} -A \"Open $PIZAUTH_ACCOUNT\" -t 30000 'pizauth authorisation')\" == \"0\" ]]; then open \"$PIZAUTH_URL\"; fi";
error_notify_cmd = "${notifySend} -t 90000 \"pizauth error for $PIZAUTH_ACCOUNT\" \"$PIZAUTH_MSG\"";
token_event_cmd = "pizauth dump > ${homeDir}/.pizauth.state";
'';
};
accounts.email.accounts.work =
let
inherit (confLib.getConfig.repo.secrets.work) mailName;
in
{
address = mailAddress;
imap = {
host = "outlook.office365.com";
port = 993;
tls.enable = true;
};
mbsync = {
enable = true;
expunge = "both";
extraConfig.account.AuthMechs = "XOAUTH2";
patterns = [ "INBOX" ];
};
msmtp = {
enable = true;
extraConfig = {
auth = "xoauth2";
from = "${mailAddress}";
host = "outlook.office365.com";
passwordeval = "pizauth show work";
port = "587";
protocol = "smtp";
tls = "on";
tls_starttls = "on";
user = "${mailAddress}";
};
};
mu.enable = true;
passwordCommand = "pizauth show work";
primary = false;
realName = mailName;
smtp = {
host = "outlook.office365.com";
port = 587;
tls = {
enable = true;
useStartTls = true;
};
};
thunderbird = {
enable = true;
profiles = [ "default" ];
settings = id: {
"mail.server.server_${id}.authMethod" = 10;
"mail.smtpserver.smtp_${id}.authMethod" = 10;
};
};
userName = mailAddress;
};
systemd.user = {
services.pizauth.Service.ExecStartPost = [
"${pkgs.toybox}/bin/sleep 1"
"//bin/sh -c '${lib.getExe pkgs.pizauth} restore < ${homeDir}/.pizauth.state'"
];
sessionVariables = lib.optionalAttrs (!config.swarselsystems.isPublic) {
SWARSEL_MAIL_ALL = lib.mkForce "${confLib.getConfig.repo.secrets.common.mail.allMailAddresses},${mailAddress}";
SWARSEL_MAIL_WORK = lib.mkForce mailAddress;
};
};
};
};
}
4.4.2.71. Work (desktop)
{
flake.modules.homeManager.work-desktop =
{
config,
lib,
pkgs,
confLib,
...
}:
let
inherit (config.swarselsystems) monitors;
in
{
config = {
swarselsystems.monitors = {
work_middle_middle_main = rec {
columns = "3";
mode = "5120x2160";
model = "LG ULTRAFINE";
name = "${vendor} ${model} ${serial}";
output = name;
position = "-2560,0";
scale = "1";
serial = "510NTEPPU036";
vendor = "LG Electronics";
workspace = "1:一";
};
work_middle_middle_side = rec {
columns = "1";
mode = "3840x2160";
model = "HP 732pk";
name = "${vendor} ${model} ${serial}";
output = name;
position = "-4720,-1050";
refresh = "60";
scale = "1";
serial = "CNC4080YL5";
transform = "270";
vendor = "HP Inc.";
workspace = "12:S";
};
work_seminary = rec {
mode = "1280x720";
model = "Transmitter";
name = "${vendor} ${model} ${serial}";
output = name;
position = "10000,10000"; # i.e. this screen is inaccessible by moving the mouse
scale = "1";
serial = "QUATTRO201811";
vendor = "Applied Creative Technology";
workspace = "14:T";
};
};
services.shikane.settings =
let
workRight = confLib.mkShikaneOutput monitors.work_middle_middle_main { };
workLeft = confLib.mkShikaneOutput monitors.work_middle_middle_side { };
seminary = confLib.mkShikaneOutput monitors.work_seminary { };
internalOn = {
enable = true;
match = config.swarselsystems.sharescreen;
position = "2560,0";
scale = 1.7;
};
internalOff = internalOn // {
enable = false;
};
exec = [
"${lib.getExe' pkgs.libnotify "notify-send"} shikane \"Profile $SHIKANE_PROFILE_NAME has been applied\""
];
in
{
profile = [
{
inherit exec;
name = "work-internal-on";
output = [
internalOn
workRight
workLeft
];
}
{
inherit exec;
name = "work-internal-off";
output = [
internalOff
workRight
workLeft
];
}
{
exec = exec ++ [
(lib.getExe (
pkgs.writeShellApplication {
name = "nirishare";
runtimeInputs = [
pkgs.noctalia
pkgs.procps
pkgs.wl-mirror
pkgs.wlr-randr
];
text = ''
if pgrep wl-mirror >/dev/null; then
exit 0
fi
target=$(wlr-randr | grep '${monitors.work_seminary.name}' | cut -d' ' -f1)
setsid sh -c "
noctalia msg notification-dnd-set on
wl-present mirror '${config.swarselsystems.sharescreen}' --fullscreen-output '$target'
noctalia msg notification-dnd-set off
" >/dev/null 2>&1 &
'';
}
))
];
name = "seminar-internal-on";
output = [
internalOn
seminary
];
}
{
inherit exec;
name = "seminar-internal-off";
output = [
internalOff
seminary
];
}
];
};
programs.niri.settings.binds =
let
inherit (confLib.getConfig.repo.secrets.work) passEntries;
in
with config.lib.niri.actions;
{
"Mod+Shift+d".action = spawn "pass-fuzzel" "--type" "--entry" passEntries.admin;
"Mod+Shift+i".action = spawn "pass-fuzzel" "--type" "--entry" passEntries.account;
};
};
};
}
4.4.2.72. AMD CPU
{
flake.modules.nixos.amdcpu.config.hardware.cpu.amd.updateMicrocode = true;
}
4.4.2.73. AMD GPU
{
flake.modules.nixos.amdgpu.config.hardware.amdgpu = {
initrd.enable = true;
opencl.enable = true;
# amdvlk = {
# enable = true;
# support32Bit.enable = true;
# };
};
}
4.4.2.74. Framework
This holds configuration that is specific to framework laptops.
{
flake.modules.nixos.framework =
{
confLib,
...
}:
{
config = {
users.persistentIds.fwupd-refresh = confLib.mkIds 959;
services = {
fwupd = {
enable = true;
# framework also uses lvfs-testing, but I do not want to use it
extraRemotes = [ "lvfs" ];
};
udev.extraRules = ''
# disable Wakeup on Framework Laptop 16 Keyboard (ANSI)
ACTION=="add", SUBSYSTEM=="usb", ATTR{idVendor}=="32ac", ATTR{idProduct}=="0012", ATTR{power/wakeup}="disabled"
# disable Wakeup on Framework Laptop 16 Numpad Module
ACTION=="add", SUBSYSTEM=="usb", ATTR{idVendor}=="32ac", ATTR{idProduct}=="0014", ATTR{power/wakeup}="disabled"
# disable Wakeup on Framework Laptop 16 Trackpad
ACTION=="add", SUBSYSTEM=="i2c", DRIVERS=="i2c_hid_acpi", ATTRS{name}=="PIXA3854:00", ATTR{power/wakeup}="disabled"
'';
};
hardware.fw-fanctrl = {
config.defaultStrategy = "lazy";
enable = true;
};
};
};
}
4.4.2.75. Hibernation
{
flake.modules.nixos.hibernation = { config, lib, ... }: {
options.swarselsystems.hibernation = {
offset = lib.mkOption {
default = 0;
type = lib.types.int;
};
resumeDevice = lib.mkOption {
default = "/dev/disk/by-label/nixos";
type = lib.types.str;
};
};
config = {
boot = {
inherit (config.swarselsystems.hibernation) resumeDevice;
kernelParams = [
"resume_offset=${builtins.toString config.swarselsystems.hibernation.offset}"
# "mem_sleep_default=deep"
];
};
powerManagement.enable = true;
systemd = {
services.systemd-suspend-then-hibernate.aliases = [ "systemd-suspend.service" ];
sleep.settings.Sleep = {
HibernateDelaySec = "120m";
SuspendState = "freeze";
};
};
};
};
}
4.4.2.76. nswitch-rcm
This smashes Atmosphère 1.3.2 on the switch, which is what I am currently using.
{
flake-file.inputs.nswitch-rcm-nix = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:Swarsel/nswitch-rcm-nix";
};
flake.modules.nixos.nswitch-rcm = { inputs, lib, ... }: {
imports = lib.optionals (inputs ? nswitch-rcm-nix) [
inputs.nswitch-rcm-nix.nixosModules.nswitch-rcm
({ pkgs, ... }: {
services.nswitch-rcm = {
enable = true;
package = pkgs.fetchurl {
hash = "sha256-5AXzNsny45SPLIrvWJA9/JlOCal5l6Y++Cm+RtlJppI=";
url = "https://github.com/Atmosphere-NX/Atmosphere/releases/download/1.3.2/fusee.bin";
};
};
})
];
};
}
4.4.2.77. VirtualBox
This sets the VirtualBox configuration. Guest should not be enabled if not direly needed, it will make rebuilds unbearably slow. I only use this privately to run an old editor that does not run well under wine, so I put it into it's own specialization.
{
flake.modules.nixos.virtualbox =
{
config,
lib,
pkgs,
...
}:
{
config = {
# specialisation = {
# VBox.configuration = {
virtualisation.virtualbox = {
# leaving this here for future notice. setting guest.enable = true will make 'restarting sysinit-reactivation.target' take till timeout on nixos-rebuild switch
guest.enable = false;
host = {
enable = true;
package = pkgs.virtualbox;
addNetworkInterface = lib.mkIf config.virtualisation.virtualbox.host.enableKvm false;
enableExtensionPack = true;
enableKvm = true;
};
};
# run an older kernel to provide compatibility with windows vm
# boot = {
# kernelPackages = lib.mkForce pkgs.stable24_05.linuxPackages;
# # kernelParams = [
# # "amd_iommu=on"
# # ];
# };
# fixes the issue of running together with QEMU
# NOTE: once you start a QEMU VM (use kvm) VirtualBox will fail to start VMs
# boot.kernelParams = [ "kvm.enable_virt_at_load=0" ];
# };
# };
};
};
}
4.4.2.78. Sandbox Access for Clients
{
flake.modules.nixos.sandbox-access =
{ root, confLib, ... }:
{
sops.secrets.sandbox-wildcard-key.rekey.keyPrefix = confLib.static.sharedSecrets.sandbox;
networking.hosts."127.0.0.1" = builtins.attrValues (import (
root "hosts/utility/vacanthouse/secrets/pii.nix"
)).services.domains;
security.pki.certificateFiles = [
(root "files/public/certs/ca.crt")
];
};
}
4.4.2.79. Pedantix
{
flake.modules.homeManager.pedantix =
{ root, inputs, ... }:
{
imports = [ inputs.pedantix.homeModules.default ];
swarselsystems.enabledHomeModules = [ "pedantix" ];
programs.pedantix = {
enable = true;
settings = import (root "files/nix/pedantix-settings.nix");
};
};
}
4.4.3. Server
In a similar way as the Client section, these modules are to be used mostly on servers.
4.4.3.1. General NixOS Server settings
Here we just define some aliases for rebuilding the system, and we allow some insecure packages that are needed by some server derivations. It would be more elegant to define these in the respective module, but nixpkgs needs to be defined before we can evaluate modules within it, so this must be a top-level configuration.
{
flake.modules.nixos.server-settings =
{ config, lib, ... }:
let
inherit (config.swarselsystems) flakePath;
in
{
options.swarselsystems.shellAliases = lib.mkOption {
default = { };
type = lib.types.attrsOf lib.types.str;
};
config = {
swarselsystems.enabledServerModules = [ "general" ];
environment.shellAliases = {
nboot = "cd ${flakePath}; swarsel-deploy $(hostname) boot; cd -;";
ndry = "cd ${flakePath}; swarsel-deploy $(hostname) dry-activate; cd -;";
nswitch = "cd ${flakePath}; swarsel-deploy $(hostname) switch; cd -;";
ntest = "cd ${flakePath}; swarsel-deploy $(hostname) test; cd -;";
}
// config.swarselsystems.shellAliases;
nixpkgs.config = lib.mkIf (!config.swarselsystems.isMicroVM) {
permittedInsecurePackages = [
# matrix
"olm-3.2.16"
];
};
};
};
}
4.4.3.2. System Packages (Server Programs)
This is a collection of packages that are useful for server-type hosts that do not really fit into other modules; the optional part of the list is for packages that are built as part of Packages (config); systems that are not built with home-manager will not be able to pass the required parameters to build these packages, hence we cannot build them here. This mostly applies to MicroVMs.
{
flake.modules.nixos.server-packages =
{
lib,
pkgs,
withHomeManager,
...
}:
{
config = {
swarselsystems.enabledServerModules = [ "packages" ];
environment.systemPackages =
with pkgs;
[
gnupg
nvd
nix-output-monitor
ssh-to-age
git
emacs
vim
sops
tmux
busybox
ndisc6
tcpdump
swarsel-deploy
]
++ lib.optionals withHomeManager [
swarsel-gens
swarsel-switch
];
};
};
}
4.4.3.3. MicroVM-host
There is only one thing of interest here; by default, my setup (where MicroVMs use macvtaps on a certain vlan) creates a race condition between the setting up of said vlan devices and the bringing up of the macvtap interface of the MicroVM in systemd. Hence, the most important snippet here is fixing that ordering.
{
flake.modules.nixos.microvm-host =
{
config,
lib,
confLib,
...
}:
{
config = lib.mkIf (config.guests != { }) {
users.persistentIds.microvm = confLib.mkIds 999;
systemd = {
services."microvm-macvtap-interfaces@" = {
after = [ "sys-subsystem-net-devices-vlan\\x2dservices.device" ];
bindsTo = [ "sys-subsystem-net-devices-vlan\\x2dservices.device" ];
};
tmpfiles.settings."15-microvms" = builtins.listToAttrs (
map (path: {
name = "${lib.optionalString config.swarselsystems.isImpermanence "/persist"}/microvms/${path}";
value.d = {
group = "kvm";
mode = "0750";
user = "microvm";
};
}) (builtins.attrNames config.guests)
);
};
};
};
}
4.4.3.4. MicroVM-guest
Some standard options that should be set for every MicroVM guest. We set the default
{
flake.modules.nixos.microvm-guest =
{
self,
inputs,
config,
...
}:
{
imports = [
inputs.home-manager.nixosModules.home-manager
inputs.microvm.nixosModules.microvm
inputs.nix-index-database.nixosModules.nix-index
inputs.nix-minecraft.nixosModules.minecraft-servers
inputs.nswitch-rcm-nix.nixosModules.nswitch-rcm
inputs.simple-nixos-mailserver.nixosModules.default
inputs.stylix.nixosModules.stylix
inputs.swarsel-nix.nixosModules.default
(inputs.nixos-extra-modules + "/modules/interface-naming.nix")
self.modules.nixos.profile-base
];
config = {
# NOTE: this is needed, we dont import sevrer network module for microvms
globals.hosts.${config.node.name}.isHome = true;
_module.args.dns = inputs.dns;
nix.settings.experimental-features = [
"nix-command"
"flakes"
];
systemd.network.networks."10-vlan-services" = {
dhcpV6Config = {
# duid-en is nice in principle, but I already have MAC info anyways for reservations
DUIDType = "link-layer";
WithoutRA = "solicit";
};
ipv6AcceptRAConfig.DHCPv6Client = "always";
};
};
};
}
4.4.3.5. MicroVM-guest-shares
Some standard options that should be set for every MicroVM guest. We set the default
{
flake.modules.nixos.microvm-guest-shares =
{
config,
lib,
microVMParent,
nodes,
...
}:
{
config.microvm.shares = [
{
mountPoint = "/persist";
proto = "virtiofs";
source = "${
lib.optionalString nodes.${microVMParent}.config.swarselsystems.isImpermanence "/persist"
}/microvms/${config.networking.hostName}";
tag = "persist";
}
];
};
}
4.4.3.6. nix-topology node config
Hold standard options for nix-topology per config
{
flake.modules.nixos.nix-topology-self =
{
config,
lib,
globals,
...
}:
let
isWgParticipant =
ifName:
globals.wireguard ? ${ifName}
&& (
builtins.elem config.node.name globals.wireguard.${ifName}.clients
|| globals.wireguard.${ifName}.server == config.node.name
);
in
{
topology.self = {
icon = lib.mkIf config.swarselsystems.isCloud "devices.cloud-server";
interfaces = {
lan = lib.mkIf (
config.swarselsystems.isCloud && config.swarselsystems.server.localNetwork == "lan"
) { };
wan = lib.mkIf (
config.swarselsystems.isCloud && config.swarselsystems.server.localNetwork == "wan"
) { };
}
// lib.genAttrs [ "wgHome" "wgProxy" ] (
ifName:
lib.mkIf (isWgParticipant ifName) {
addresses = [
globals.networks."${
globals.wireguard.${ifName}.netConfigPrefix
}-${ifName}".hosts.${config.node.name}.ipv4
];
renderer.hidePhysicalConnections = true;
type = "wireguard";
virtual = true;
}
);
};
};
}
4.4.3.7. systemd-networkd (base)
This set of options enables the network of the system to be managed by systemd-networkd:
networking.useNetworkdhas the effect that options fromnetworking.*are not performed using network scripts but rather usingsystemd-networkd.systemd.network.enableenables the actual management of networks using thesystemd-networkdinterface.
{
flake.modules.nixos.systemd-networkd-base =
{ config, lib, ... }:
{
networking = {
dhcpcd.enable = lib.mkIf (!config.swarselsystems.isMicroVM) false;
renameInterfacesByMac = lib.mkIf (!config.swarselsystems.isMicroVM) (
lib.mapAttrs (_: v: v.mac or "") (config.repo.secrets.local.networking.networks or { })
);
useDHCP = lib.mkForce false;
useNetworkd = true;
};
systemd.network.enable = true;
};
}
4.4.3.8. systemd-networkd (server base)
Some standard options that should be set for every MicroVM guest. We set the default
{
flake.modules.nixos.systemd-networkd-server =
{
self,
config,
lib,
globals,
...
}:
let
inherit (config.swarselsystems) isCrypted localVLANs;
inherit (globals.general) routerServer;
isRouter = config.node.name == routerServer;
ifName = config.swarselsystems.server.localNetwork;
in
{
imports = [
self.modules.nixos.systemd-networkd-base
];
boot.initrd.systemd.network = lib.mkIf (isCrypted && ((localVLANs == [ ]) || isRouter)) {
enable = true;
networks."10-${ifName}" = config.systemd.network.networks."10-${ifName}";
};
systemd.network = {
networks =
let
netConfig = config.repo.secrets.local.networking;
in
{
"10-${ifName}" = lib.mkIf (isRouter || (localVLANs == [ ])) {
address = [
globals.networks.${config.swarselsystems.server.netConfigName}.hosts.${config.node.name}.cidrv4
globals.networks.${config.swarselsystems.server.netConfigName}.hosts.${config.node.name}.cidrv6
];
linkConfig.RequiredForOnline = "routable";
matchConfig.MACAddress = netConfig.networks.${ifName}.mac;
networkConfig = {
IPv6AcceptRA = false;
IPv6PrivacyExtensions = true;
};
routes = [
{
Gateway = netConfig.defaultGateway6;
GatewayOnLink = true;
}
{
Gateway = netConfig.defaultGateway4;
GatewayOnLink = true;
}
];
};
};
wait-online.enable = false;
};
};
}
4.4.3.9. systemd-networkd (server home)
This sets up the networking framework that is needed for a server that manages its VLAN interfaces using systemd-networkd. A host that is not both in the home network and using VLANs should rather be using systemd-networkd (server base) only.
We will differentiate between a host that uses MicroVMs versus a host that is not using them.
For a host with MicroVMs the general idea is as follows:
- For each local VLAN we create a VLAN here - we also create a macvlan interface for the hosts which is bound to the respective VLAN interface; also binding to that VLAN interface are the macvtap devices that are being created by the MicroVM module.
- normally, a guest using macvtap is not reachable by the host unless using a switch that supports hairpin-mode. However, consumers of the same VLAN can still communicate, which is realized using the macvlan
me-*interface. - even then, the kernel will only route requests when the underlying interface is up. In the case that no physical ports are used, this means that the bridge interface would effectively not work (even when administratively set to UP using
activationPolicy) - the aforementionedvethtakes care of that problem.- this is really only a consideration for the Router (because if the interface to the router is missing on the hosts, there will be no connectivity anyway) and is hence implemented there
- normally, a guest using macvtap is not reachable by the host unless using a switch that supports hairpin-mode. However, consumers of the same VLAN can still communicate, which is realized using the macvlan
The principle is the same for a host without MicroVMs, but we do not need the local me-* interfaces and can ignore macvtap config.
A VLAN can also be used as the initrd network - this is however disabled for the router host. For that host, we need to connect from the FritzBox! side in case we need to reboot it - this also acts as a safety net.
{
flake.modules.nixos.systemd-networkd-server-home =
{
self,
config,
lib,
globals,
...
}:
let
inherit (globals.general) routerServer;
inherit (config.swarselsystems)
bridgedVLANs
initrdVLAN
isCrypted
withMicroVMs
;
isRouter = config.node.name == routerServer;
localVLANsList = config.swarselsystems.localVLANs;
attachedVLANs = lib.genAttrs (lib.unique (localVLANsList ++ bridgedVLANs)) (
x: globals.networks.home-lan.vlans.${x}
);
# only carries attached vlans, so no link local address and only wait for a carrier
lanNetwork = {
linkConfig.RequiredForOnline = "carrier";
matchConfig.Name = "lan";
networkConfig.LinkLocalAddressing = "no";
};
in
{
imports = [
self.modules.nixos.systemd-networkd-server
];
config = {
topology.self.interfaces = lib.mergeAttrsList (
map (
vlanName:
lib.genAttrs [ "vlan-${vlanName}" "me-${vlanName}" ] (_: {
network = lib.mkForce vlanName;
})
) localVLANsList
);
assertions = [
{
assertion = localVLANsList == [ ] || initrdVLAN != null || !isCrypted;
message = "This host uses VLANs and disk encryption, thus a VLAN must be specified for initrd or disk encryption must be removed.";
}
{
assertion = (bridgedVLANs == [ ]) || (!withMicroVMs);
message = "Bridged VLANs cannot be combined with the MicroVM macvlan setup.";
}
];
boot.initrd = lib.mkIf (isCrypted && (localVLANsList != [ ]) && (!isRouter)) {
availableKernelModules = [ "8021q" ];
kernelModules = [ "8021q" ]; # at least summers needs this to actually find the interfaces
systemd.network = {
enable = true;
netdevs."30-vlan-${initrdVLAN}" = {
netdevConfig = {
Kind = "vlan";
Name = "vlan-${initrdVLAN}";
};
vlanConfig.Id = globals.networks.home-lan.vlans.${initrdVLAN}.id;
};
networks = {
"10-lan" = lanNetwork // {
vlan = [ "vlan-${initrdVLAN}" ];
};
"30-vlan-${initrdVLAN}" = {
address = [
globals.networks.home-lan.vlans.${initrdVLAN}.hosts.${config.node.name}.cidrv4
globals.networks.home-lan.vlans.${initrdVLAN}.hosts.${config.node.name}.cidrv6
];
linkConfig.RequiredForOnline = "routable";
matchConfig.Name = "vlan-${initrdVLAN}";
networkConfig.IPv6PrivacyExtensions = "yes";
};
};
};
};
systemd.network = {
netdevs = lib.flip lib.concatMapAttrs attachedVLANs (
vlanName: vlanCfg: {
"30-vlan-${vlanName}" = {
netdevConfig = {
Kind = "vlan";
Name = "vlan-${vlanName}";
};
vlanConfig.Id = vlanCfg.id;
};
# Create a MACVTAP for ourselves too, so that we can communicate with
# our guests on the same interface.
"40-me-${vlanName}" = lib.mkIf withMicroVMs {
extraConfig = ''
[MACVLAN]
Mode=bridge
'';
netdevConfig = {
Kind = "macvlan";
Name = "me-${vlanName}";
};
};
"50-br-${vlanName}" = lib.mkIf (lib.elem vlanName bridgedVLANs) {
bridgeConfig.MulticastSnooping = false;
netdevConfig = {
Kind = "bridge";
MACAddress = config.repo.secrets.local.networking.networks.lan.mac;
Name = "br-${vlanName}";
};
};
}
);
networks = {
"10-lan" = lib.mkIf (!isRouter) (
lanNetwork
// {
vlan = map (name: "vlan-${name}") (builtins.attrNames attachedVLANs);
}
);
# Remaining macvtap interfaces should not be touched.
"90-macvtap-ignore" = lib.mkIf withMicroVMs {
linkConfig = {
ActivationPolicy = "manual";
Unmanaged = "yes";
};
matchConfig.Kind = "macvtap";
};
}
// lib.flip lib.concatMapAttrs attachedVLANs (
vlanName: vlanCfg:
let
isBridged = lib.elem vlanName bridgedVLANs;
me = {
address = [
vlanCfg.hosts.${config.node.name}.cidrv4
vlanCfg.hosts.${config.node.name}.cidrv6
];
gateway = lib.optionals (vlanName == "services") [
vlanCfg.hosts.${routerServer}.ipv4
vlanCfg.hosts.${routerServer}.ipv6
];
linkConfig.RequiredForOnline = "routable";
matchConfig.Name = "${
if isBridged then
"br"
else if withMicroVMs then
"me"
else
"vlan"
}-${vlanName}";
networkConfig.IPv6PrivacyExtensions = "yes";
};
in
{
"30-vlan-${vlanName}" =
if isBridged then
{
linkConfig.RequiredForOnline = "enslaved";
matchConfig.Name = "vlan-${vlanName}";
networkConfig = {
Bridge = "br-${vlanName}";
LinkLocalAddressing = "no";
};
}
else if (!withMicroVMs) then
me
else
{
linkConfig.RequiredForOnline = if isRouter then "no" else "carrier";
matchConfig.Name = "vlan-${vlanName}";
networkConfig = {
LinkLocalAddressing = "no";
MACVLAN = "me-${vlanName}";
};
};
"40-me-${vlanName}" = lib.mkIf withMicroVMs (lib.mkDefault me);
"50-br-${vlanName}" = lib.mkIf isBridged (
if lib.elem vlanName localVLANsList then
me
else
{
linkConfig.RequiredForOnline = "no";
matchConfig.Name = "br-${vlanName}";
networkConfig = {
ConfigureWithoutCarrier = true;
LinkLocalAddressing = "no";
};
}
);
}
);
};
};
};
}
4.4.3.10. nfs/samba (smb)
Handles my main NFS share. User password setup is currently not declarative, I need to write a service for it at some point.
{
flake.modules.nixos.nfs =
{
config,
lib,
pkgs,
confLib,
globals,
...
}:
let
shareUser = "eternor";
in
{
config = {
swarselsystems.enabledServerModules = [ "nfs" ];
globals.monitoring = {
tcp = confLib.mkTcpMonitoring {
serviceName = "samba";
servicePort = 445;
};
systemd = lib.mkMerge [
(confLib.mkSystemdMonitoring {
serviceName = "avahi-${config.node.name}";
unit = "avahi-daemon.service";
})
(confLib.mkSystemdMonitoring {
serviceName = "samba-wsdd";
unit = "samba-wsdd.service";
})
];
};
sops.secrets.samba-user-pw.mode = "0400";
users = {
users.${shareUser} = {
group = "users";
isSystemUser = true;
};
persistentIds = {
${shareUser}.uid = 1000;
avahi = confLib.mkIds 978;
};
};
services = {
avahi = {
enable = true;
nssmdns4 = true;
openFirewall = true;
settings.publish = {
disable-publishing = false;
disable-user-service-publishing = false; # Needed to allow samba to automatically register mDNS records without the need for an `extraServiceFile`
publish-addresses = true;
};
};
samba = {
enable = true;
package = pkgs.samba4;
openFirewall = true;
settings = {
Eternor = {
browseable = "yes";
comment = "Eternor";
"create mask" = "0660";
"directory mask" = "2770";
"guest ok" = "no";
path = "/storage";
"read only" = "no";
"valid users" = shareUser;
writable = "true";
};
global = {
# share root is on the guest tmpfs, report the free space of the dataset mounts below it
"dfree command" = lib.getExe (
pkgs.writeShellApplication {
name = "samba-dfree";
runtimeInputs = [ pkgs.coreutils ];
text = "df -k --output=size,avail /storage/*/ | tail -n 1";
}
);
"username map" = "${pkgs.writeText "samba-username-map" "${shareUser} = ${globals.user.name}\n"}";
};
};
};
# This enables autodiscovery on windows since SMB1 (and thus netbios) support was discontinued
samba-wsdd = {
enable = true;
openFirewall = true;
};
};
environment.persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [
{ directory = "/var/cache/samba"; }
{ directory = "/var/lib/samba"; }
];
};
systemd.services.samba-ensure-user-pw = {
after = [ "samba-smbd.service" ];
description = "Create the SMB account for ${shareUser}";
partOf = [ "samba-smbd.service" ];
path = [ pkgs.samba4 ];
script = ''
if ! pdbedit -L | grep -q '^${shareUser}:'; then
pw=$(cat ${config.sops.secrets.samba-user-pw.path})
printf '%s\n%s\n' "$pw" "$pw" | smbpasswd -a -s ${shareUser}
fi
'';
serviceConfig.Type = "oneshot";
wantedBy = [ "samba-smbd.service" ];
};
};
};
}
4.4.3.11. acme
This sets up acme which I use to generate certificates. Nowadays I no longer use cloudflare but acme-dns, which allows me to have my dns records spread out over multiple providers for redundancy.
{
flake.modules.nixos.acme =
{
self,
config,
lib,
pkgs,
confLib,
globals,
...
}:
let
inherit (config.repo.secrets.common) dnsMail dnsProvider;
inherit (globals.general) acmeDnsServer;
inherit (confLib.static) webProxyIf;
acmeDns = globals.services.acme-dns;
probeDomain = "ssl.${globals.domains.main}";
in
{
config = {
swarselsystems.enabledServerModules = [ "acme" ];
globals = {
monitoring.cert.${config.node.name} = {
address = "127.0.0.1:443";
network = "local-${config.node.name}";
serverName = probeDomain;
};
networks.${webProxyIf}.hosts.${acmeDnsServer}.firewallRuleForNode.${config.node.name}.allowedTCPPorts =
[
acmeDns.extraConfig.port
];
};
sops = {
secrets.acme-creds = {
group = "acme";
mode = "0660";
rekey.file = self + "/secrets/nginx/acme.json.enc";
};
templates."certs.secret".content = ''
ACME_DNS_API_BASE=http://${acmeDns.serviceAddress}:${toString acmeDns.extraConfig.port}
ACME_DNS_STORAGE_PATH=${config.sops.secrets.acme-creds.path}
'';
};
users = {
groups.acme.members = lib.mkIf (builtins.elem "nginx" config.swarselsystems.enabledServerModules) [
"nginx"
];
persistentIds.acme = confLib.mkIds 967;
};
services.nginx.virtualHosts.${probeDomain} = {
acmeRoot = null;
locations."/".return = "444";
onlySSL = true;
useACMEHost = globals.domains.main;
};
environment = {
persistence."/persist" = lib.mkIf config.swarselsystems.isImpermanence {
directories = [ { directory = "/var/lib/acme"; } ];
};
systemPackages = with pkgs; [
lego
];
};
security.acme = {
acceptTerms = true;
certs."${globals.domains.main}".domain = "*.${globals.domains.main}";
defaults = {
inherit dnsProvider;
dnsResolver = "1.1.1.1:53";
email = dnsMail;
environmentFile = config.sops.templates."certs.secret".path;
keyType = "ec384";
reloadServices = [ "nginx" ];
};
};
};
};
}
4.4.3.12. acme-dns
{
flake.modules.nixos.acme-dns =
{
root,
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
dir = "/var/lib/private/acme-dns";
domain = "";
name = "acme-dns";
port = 8053;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDir
serviceDomain
serviceName
servicePort
;
inherit (confLib.static) homeServiceAddress isHome;
inherit (config.swarselsystems.server) localNetwork netConfigName;
inherit (globals.domains) reverse6;
zoneLabel = "dns";
zone = "${zoneLabel}.${reverse6}";
addressId = 53;
listenAddress6 = lib.net.cidr.host addressId globals.networks.${netConfigName}.cidrv6;
in
{
config = {
swarselsystems.enabledServerModules = [ serviceName ];
topology.self.services.${serviceName} = {
icon = root "files/topology-images/${serviceName}.png";
info = zone;
name = serviceName;
};
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
extra.extraConfig.port = servicePort;
};
dns.${reverse6}.subdomainRecords.${zoneLabel} = {
AAAA = [ listenAddress6 ];
NS = [ "${zone}." ];
};
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
path = "/health";
};
};
services.acme-dns = {
enable = true;
settings = {
api = {
disable_registration = true;
header_name = "X-Forwarded-For";
port = servicePort;
tls = "none";
use_header = true;
};
general = {
domain = zone;
listen = "[${listenAddress6}]:53";
nsadmin = lib.replaceStrings [ "@" ] [ "." ] config.repo.secrets.common.dnsMail;
nsname = zone;
protocol = "both6";
records = [
"${zone}. AAAA ${listenAddress6}"
"${zone}. NS ${zone}."
];
};
logconfig = {
logformat = "text";
loglevel = "info";
logtype = "stdout";
};
};
};
environment.persistence."/persist".directories = lib.mkIf config.swarselsystems.isImpermanence [
{
directory = serviceDir;
mode = "0700";
}
];
systemd = {
services.acme-dns.serviceConfig.RestartSec = 5;
network.networks."10-${localNetwork}".address = [
(lib.net.cidr.hostCidr addressId globals.networks.${netConfigName}.cidrv6)
];
};
};
};
}
4.4.3.13. NGINX
This is the general NGINX config using on Twothreetunnel (OCI) and the Nginx guest on Hintbooth (Router: HUNSN RM02). The virtual hosts themselves are declared in the respective service modules.
{
flake.modules.nixos.nginx =
{
config,
lib,
confLib,
...
}:
{
options.services.nginx = {
recommendedSecurityHeaders = lib.mkEnableOption "additional security headers by default in each location block.";
virtualHosts = lib.mkOption {
type = lib.types.attrsOf (
lib.types.submodule (_: {
options.locations = lib.mkOption {
type = lib.types.attrsOf (
lib.types.submodule (submod: {
options = {
X-Frame-Options = lib.mkOption {
default = "DENY";
description = "The value to use for X-Frame-Options";
type = lib.types.str;
};
recommendedSecurityHeaders = lib.mkOption {
default = config.services.nginx.recommendedSecurityHeaders;
description = "Whether to add additional security headers to this location.";
type = lib.types.bool;
};
};
config.extraConfig = lib.mkIf submod.config.recommendedSecurityHeaders (
lib.mkBefore ''
# Hide upstream's versions
proxy_hide_header Strict-Transport-Security;
proxy_hide_header Referrer-Policy;
proxy_hide_header X-Content-Type-Options;
proxy_hide_header X-Frame-Options;
# Enable HTTP Strict Transport Security (HSTS)
add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";
# Minimize information leaked to other domains
add_header Referrer-Policy "origin-when-cross-origin";
add_header X-XSS-Protection "1; mode=block";
add_header X-Frame-Options "${submod.config.X-Frame-Options}";
add_header X-Content-Type-Options "nosniff";
''
);
})
);
};
})
);
};
};
config = {
swarselsystems.enabledServerModules = [ "nginx" ];
services.nginx = {
enable = true;
recommendedBrotliSettings = true;
recommendedGzipSettings = true;
recommendedOptimisation = true;
recommendedProxySettings = true;
recommendedSecurityHeaders = true;
recommendedTlsSettings = true;
sslCiphers = "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:!aNULL";
statusPage = true;
virtualHosts.fallback = {
default = true;
locations."/".extraConfig = ''
deny all;
'';
rejectSSL = true;
};
};
environment.persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [
{
directory = "/var/cache/nginx";
group = "nginx";
user = "nginx";
}
];
};
networking.firewall.allowedTCPPorts =
lib.mkIf (!config.swarselsystems.isCloud || config.node.name == confLib.static.webProxy)
[
80
443
];
};
};
}
4.4.3.14. NGINX OpenTelemetry
{
flake.modules.nixos.nginx-otel =
{
config,
pkgs,
globals,
...
}:
{
services.nginx = {
additionalModules = [
(pkgs.nginxModules.otel.overrideAttrs {
patches = [ ../../../files/patches/nginx-otel-cpp20.patch ];
})
];
appendHttpConfig = ''
otel_service_name "nginx-${config.node.name}";
otel_exporter {
endpoint 127.0.0.1:${toString globals.services.alloy.extraConfig.otlpGrpcPort};
}
otel_trace on;
otel_trace_context propagate;
'';
};
};
}
4.4.3.15. Bastion
Some extra config to harden the config on my ssh bastion host. It makes it so that logging in as the jump user is prohibited on that host, and forwardAgent is forbidden.
{
flake.modules.nixos.bastion =
{
root,
config,
lib,
pkgs,
confLib,
globals,
nodes,
...
}:
let
homeWan = globals.networks.home-wan;
jumpTargets = lib.filterAttrs (
name: host: name != config.node.name && !host.isHome && host.wanAddress4 != null
) globals.hosts;
permitOpen = lib.concatLists (
lib.mapAttrsToList (
name: host:
let
inherit (nodes.${name}.config) boot services;
in
lib.concatMap
(
port:
[ "${host.wanAddress4}:${toString port}" ]
++ lib.optional (host.wanAddress6 != null) "[${host.wanAddress6}]:${toString port}"
)
(services.openssh.ports ++ lib.optional boot.initrd.network.ssh.enable boot.initrd.network.ssh.port)
) jumpTargets
);
journalSelector = unit: ''{host="${config.node.name}",unit="${unit}"}'';
mkJournalAlertRule =
args:
confLib.mkGrafanaAlertRule (
{
datasourceUid = "loki";
forDuration = "0s";
noDataState = "OK";
op = "gt";
queryType = "instant";
threshold = 0;
}
// args
);
in
{
config = {
swarselsystems.enabledServerModules = [ "bastion" ];
users = {
users = {
${config.swarselsystems.mainUser}.enable = false;
jump = {
autoSubUidGidRange = false;
createHome = lib.mkForce true;
group = lib.mkForce "jump";
isNormalUser = true;
openssh.authorizedKeys.keyFiles = [
(root "files/public/ssh/yubikey.pub")
(root "files/public/ssh/magicant.pub")
(root "files/public/ssh/builder.pub")
];
useDefaultShell = true;
};
};
groups.jump = { };
persistentIds.jump = confLib.mkIds 1001;
};
services.openssh = {
enable = true;
authorizedKeysInHomedir = false;
extraConfig = ''
Match User jump
ForceCommand ${lib.getExe' pkgs.coreutils "false"}
PermitTTY no
X11Forwarding no
PermitTunnel no
GatewayPorts no
AllowAgentForwarding no
AllowStreamLocalForwarding no
AllowTcpForwarding local
PermitOpen ${lib.concatStringsSep " " permitOpen}
'';
hostKeys = lib.mkIf (!(builtins.elem "ssh" config.swarselsystems.enabledServerModules)) [
{
path = "/etc/ssh/ssh_host_ed25519_key";
type = "ed25519";
}
];
settings = {
AllowUsers = lib.mkForce (
[ "jump" ]
++ map (cidr: "root@${cidr}") [
homeWan.cidrv4
homeWan.cidrv6
]
);
KbdInteractiveAuthentication = false;
LogLevel = "VERBOSE";
LoginGraceTime = 20;
MaxAuthTries = 3;
MaxStartups = "10:30:60";
PasswordAuthentication = false;
};
startWhenNeeded = lib.mkForce false;
};
nodes.${globals.general.monitoringServer}.services.grafana.provision.alerting.rules.settings.groups =
[
{
folder = "Infrastructure";
interval = "1m";
name = "bastion-${config.node.name}";
orgId = 1;
rules = [
(mkJournalAlertRule {
expr = ''sum(count_over_time(${journalSelector "sshd.service"} |= "Accepted publickey for root" [10m]))'';
severity = "warning";
summary = "root logged in on ${config.node.name} over ssh";
title = "bastion root login (${config.node.name})";
uid = "bastion_root_login_${config.node.name}";
})
(mkJournalAlertRule {
expr = ''sum(count_over_time(${journalSelector "sshd.service"} |= "but the request was denied" [10m]))'';
summary = "a jump session on ${config.node.name} requested a forward to a target outside the permitted list";
title = "bastion forward denied (${config.node.name})";
uid = "bastion_forward_denied_${config.node.name}";
})
(mkJournalAlertRule {
expr = ''sum(count_over_time(${journalSelector "sshd.service"} |= "Server listening on" [10m])) unless sum(count_over_time(${journalSelector "init.scope"} |= "Reloading..." [20m]))'';
summary = "sshd on ${config.node.name} started without a preceding configuration switch";
title = "bastion sshd restart outside deploy (${config.node.name})";
uid = "bastion_sshd_restart_${config.node.name}";
})
];
}
];
};
};
}
4.4.3.16. ssh builder config
Restricts access to the system by the nix build user as per https://discourse.nixos.org/t/wrapper-to-restrict-builder-access-through-ssh-worth-upstreaming/25834.
{
flake.modules.nixos.ssh-builder =
{
self,
config,
pkgs,
confLib,
...
}:
let
ssh-restrict = "restrict,pty,command=\"${wrapper-dispatch-ssh-nix}/bin/wrapper-dispatch-ssh-nix\" ";
wrapper-dispatch-ssh-nix = pkgs.writeShellApplication {
name = "wrapper-dispatch-ssh-nix";
text = ''
case "''${SSH_ORIGINAL_COMMAND:-}" in
"nix-daemon --stdio")
exec env NIX_SSL_CERT_FILE=${pkgs.cacert}/etc/ssl/certs/ca-bundle.crt ${config.nix.package}/bin/nix-daemon --stdio
;;
"nix-store --serve --write")
exec env NIX_SSL_CERT_FILE=${pkgs.cacert}/etc/ssl/certs/ca-bundle.crt ${config.nix.package}/bin/nix-store --serve --write
;;
*)
echo "Access only allowed for using the nix remote builder" 1>&2
exit 1
esac
'';
};
in
{
config = {
swarselsystems.enabledServerModules = [ "ssh-builder" ];
users = {
users.builder = {
group = "builder";
isSystemUser = true;
openssh.authorizedKeys.keys = [
"${ssh-restrict} ${builtins.readFile "${self}/files/public/ssh/builder.pub"}"
];
useDefaultShell = true;
};
groups.builder = { };
persistentIds.builder = confLib.mkIds 965;
};
services.openssh.settings.AllowUsers = [
"builder"
];
};
};
}
4.4.3.17. Network settings (globals.networks population)
Generate hostId using head -c4 /dev/urandom | od -A none -t x4
This section is mainly used to populate entries in globals.networks with the interfaces defined in the local secrets of the respective host. Also, we expose some convenient values under globals.hosts and setup basic networking.
{
flake.modules.nixos.server-network =
{ config, lib, ... }:
let
netConfig = config.repo.secrets.local.networking;
netPrefix = if config.swarselsystems.isCloud then config.node.name else "home";
in
{
options.swarselsystems.server = {
localNetwork = lib.mkOption {
default = "";
type = lib.types.str;
};
netConfigName = lib.mkOption {
default = "${netPrefix}-${config.swarselsystems.server.localNetwork}";
readOnly = true;
type = lib.types.str;
};
netConfigPrefix = lib.mkOption {
default = netPrefix;
readOnly = true;
type = lib.types.str;
};
};
config = {
swarselsystems = {
enabledServerModules = [ "network" ];
server.localNetwork = netConfig.localNetwork or "";
};
globals = {
hosts.${config.node.name} = {
defaultGateway4 = netConfig.defaultGateway4 or null;
defaultGateway6 = netConfig.defaultGateway6 or null;
isHome = netPrefix == "home";
wanAddress4 = netConfig.wanAddress4 or null;
wanAddress6 = netConfig.wanAddress6 or null;
};
networks = lib.mkIf config.swarselsystems.writeGlobalNetworks (
lib.mapAttrs' (
netName: net:
lib.nameValuePair "${netPrefix}-${netName}" {
hosts.${config.node.name} = {
inherit (net) id;
mac = net.mac or null;
};
}
) (lib.filterAttrs (_: net: net ? id) netConfig.networks)
);
};
networking = {
inherit (netConfig) hostId;
enableIPv6 = lib.mkDefault true;
firewall.enable = lib.mkDefault true;
hostName = config.node.name;
nftables.enable = lib.mkDefault false;
};
};
};
}
4.4.3.18. Attic setup
By default, attic only provides a CLI client to authenticate to caches. I want all my servers to use my main binary cache, which is what I set up here.
{
flake.modules.nixos.attic-setup =
{
config,
lib,
pkgs,
confLib,
globals,
...
}:
{
config = {
swarselsystems.enabledServerModules = [ "attic-setup" ];
sops = {
secrets.attic-cache-key.rekey.keyPrefix = confLib.static.sharedSecrets.common;
templates.attic-env.content = ''
DOMAIN=https://${globals.services.attic.domain}
TOKEN=${config.sops.placeholder.attic-cache-key}
'';
};
environment.systemPackages = with pkgs; [
attic-client
];
systemd.services.attic-cache-setup = {
after = [ "network-online.target" ];
description = "Log in to the attic cache";
path = [ pkgs.attic-client ];
script = ''
if ! grep -qsF "\"$TOKEN\"" /root/.config/attic/config.toml; then
attic login ${config.swarselsystems.mainUser} "$DOMAIN" "$TOKEN" --set-default
attic use ${config.swarselsystems.mainUser}
fi
''
+ lib.optionalString (config.users.users ? buildbot) ''
install -d -m 700 -o buildbot -g buildbot /home/buildbot/.config/attic
install -m 600 -o buildbot -g buildbot /root/.config/attic/config.toml /home/buildbot/.config/attic/config.toml
'';
serviceConfig = {
EnvironmentFile = [
config.sops.templates.attic-env.path
];
RemainAfterExit = true;
Restart = "on-failure";
RestartSec = 60;
Type = "oneshot";
};
wantedBy = [ "multi-user.target" ];
wants = [ "network-online.target" ];
};
};
key = "swarsel/server/attic-setup";
};
}
4.4.3.19. Wireguard
I use Wireguard for two things:
- proxying of my services (both internal and external) to my proxy node
- proxying of my internal services to an internal NGINX in order to save on bandwidth
At current, this means that I am running two Wireguard interfaces - the following configuration allows me to define an arbitrary number of Wireguard interfaces that each host can be part of (either as "client" or "server"). All of these connections are really point-to-point. On the client side, I set persistentKeepalive unconditionally, which is lazy (and a bit of a security issue).
In order to define a new Wireguard interface, I have to:
- add another <nodeName>-<wgInterfaceName> network to globals
- add its members under hosts
- add the
wgInterfaceNametogether with id to the server nodes local PII - make sure all members have their private keys in their secrets file and their public key under
secrets/public/wg make sure that all preshared keys exist in
secrets/repo/wg.yamlThe MTU computes like this:
| Component | Bytes |
|---|---|
| Ethernet payload | 1500 |
| 802.1Q VLAN tag | -4 |
| PPPoE header | -8 |
| IPv6 header | -40 |
| UDP header | -8 |
| WireGuard | -32 |
| Inner MTU | 1408 |
{
flake.modules.nixos.wireguard =
{
self,
config,
lib,
pkgs,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
group = "systemd-network";
name = "wireguard";
port = 52829;
user = "systemd-network";
})
serviceGroup
servicePort
serviceUser
;
peerPublicKey = peer: builtins.readFile (self + "/files/public/wg/${peer}.pub");
presharedKeySecret = server: client: {
group = serviceGroup;
mode = "0600";
owner = serviceUser;
rekey = {
generator.script = "wireguard-psk";
keyPrefix = "wireguard/${server}-${client}/";
};
};
interfaces =
lib.mapAttrs
(
ifName: wgCfg:
let
isServer = wgCfg.server == config.node.name;
isClient = builtins.elem config.node.name wgCfg.clients;
peers = if isServer then wgCfg.clients else [ wgCfg.server ];
netCfg = globals.networks."${wgCfg.netConfigPrefix}-${ifName}";
ruleSources = lib.attrNames netCfg.hosts.${config.node.name}.firewallRuleForNode;
in
{
inherit
ifName
isClient
isServer
netCfg
peers
;
inherit (wgCfg) port;
serverName = wgCfg.server;
# we need to add the node-port rules to "clients" without doing it generically for all nodes
# (because that blows up memory requirements enormously)
# e.g. summers eval needs ~80G if we do this for all hosts, but less than 20G like this
zonePeers = lib.unique (peers ++ ruleSources);
}
)
(
lib.filterAttrs (
_: wgCfg: wgCfg.server == config.node.name || builtins.elem config.node.name wgCfg.clients
) globals.wireguard
);
ifaceList = builtins.attrValues interfaces;
in
{
options.swarselsystems.server.wireguard.interfaces = lib.mkOption {
default = interfaces;
internal = true;
readOnly = true;
type = lib.types.unspecified;
};
config = {
swarselsystems.enabledServerModules = [ "wireguard" ];
topology.self.interfaces = lib.mapAttrs' (
wgName: _:
lib.nameValuePair wgName {
network = wgName;
}
) config.swarselsystems.server.wireguard.interfaces;
sops.secrets = lib.mkMerge (
[
{
wireguard-private-key = {
group = serviceGroup;
mode = "0600";
owner = serviceUser;
rekey = {
generator.script = "wireguard";
pubFile = self + "/files/public/wg/${config.node.name}.pub";
};
};
}
]
++ (map (
i:
let
clientSecrets = lib.optionalAttrs i.isClient {
"wireguard-${i.serverName}-${config.node.name}-${i.ifName}-presharedKey" =
presharedKeySecret i.serverName config.node.name;
};
serverSecrets = lib.optionalAttrs i.isServer (
builtins.listToAttrs (
map (clientName: {
name = "wireguard-${config.node.name}-${clientName}-${i.ifName}-presharedKey";
value = presharedKeySecret config.node.name clientName;
}) i.peers
)
);
in
clientSecrets // serverSecrets
) ifaceList)
);
assertions = lib.concatLists (
lib.flip lib.mapAttrsToList interfaces (
ifName: _ifCfg: [
{
assertion = lib.stringLength ifName < 16;
message = "While evaluating the wireguard network ${ifName}: The interface name '${ifName}' is too long (must be max 15 characters).";
}
]
)
);
boot.kernel.sysctl = lib.mkIf (lib.any (i: i.isServer) ifaceList) {
"net.ipv4.conf.all.forwarding" = lib.mkDefault true;
"net.ipv6.conf.all.forwarding" = lib.mkDefault true;
};
environment.systemPackages = with pkgs; [
wireguard-tools
];
networking = {
firewall = {
allowedUDPPorts = lib.mkMerge (
lib.flip lib.mapAttrsToList interfaces (_: ifCfg: lib.optional ifCfg.isServer ifCfg.port)
);
checkReversePath = lib.mkIf (lib.any (i: i.isClient) ifaceList) "loose";
};
nftables.firewall = {
rules = lib.mkMerge (
lib.flip lib.mapAttrsToList interfaces (
ifName: ifCfg:
let
inherit (config.networking.nftables.firewall) localZoneName;
inherit (ifCfg) netCfg;
in
{
"${ifName}-to-${localZoneName}" = {
inherit (netCfg.firewallRuleForAll)
allowedTCPPortRanges
allowedTCPPorts
allowedUDPPortRanges
allowedUDPPorts
;
from = [ ifName ];
ignoreEmptyRule = true;
to = [ localZoneName ];
};
}
// lib.optionalAttrs ifCfg.isServer {
"${ifName}-to-${ifName}" = {
from = [ ifName ];
to = [ ifName ];
verdict = "accept";
};
}
// lib.listToAttrs (
map (
peer:
lib.nameValuePair "${ifName}-node-${peer}-to-${localZoneName}" (
lib.mkIf (netCfg.hosts.${config.node.name}.firewallRuleForNode ? ${peer}) {
inherit (netCfg.hosts.${config.node.name}.firewallRuleForNode.${peer})
allowedTCPPortRanges
allowedTCPPorts
allowedUDPPortRanges
allowedUDPPorts
;
from = [ "${ifName}-node-${peer}" ];
ignoreEmptyRule = true;
to = [ localZoneName ];
}
)
) ifCfg.zonePeers
)
)
);
zones = lib.mkMerge (
lib.flip lib.mapAttrsToList interfaces (
ifName: ifCfg:
{
${ifName}.interfaces = [ ifName ];
}
// lib.listToAttrs (
map (
peer:
let
peerNet = ifCfg.netCfg.hosts.${peer};
in
lib.nameValuePair "${ifName}-node-${peer}" {
ipv4Addresses = lib.optional (peerNet.ipv4 != null) peerNet.ipv4;
ipv6Addresses = lib.optional (peerNet.ipv6 != null) peerNet.ipv6;
parent = ifName;
}
) ifCfg.zonePeers
)
)
);
};
};
systemd.network = {
enable = true;
netdevs = lib.mkMerge (
map (
i:
let
inherit (i) ifName;
in
{
"50-${ifName}" = {
netdevConfig = {
Kind = "wireguard";
Name = ifName;
};
wireguardConfig = {
ListenPort = lib.mkIf i.isServer servicePort;
PrivateKeyFile = config.sops.secrets.wireguard-private-key.path;
RouteTable = lib.mkIf i.isClient "main";
};
wireguardPeers =
lib.optionals i.isClient [
{
AllowedIPs =
(lib.optional (i.netCfg.cidrv4 != null) i.netCfg.cidrv4)
++ (lib.optional (i.netCfg.cidrv6 != null) i.netCfg.cidrv6);
Endpoint = "server.${i.serverName}.${globals.domains.main}:${toString servicePort}";
PersistentKeepalive = 25;
PresharedKeyFile =
config.sops.secrets."wireguard-${i.serverName}-${config.node.name}-${i.ifName}-presharedKey".path;
PublicKey = peerPublicKey i.serverName;
}
]
++ lib.optionals i.isServer (
map (clientName: {
AllowedIPs =
let
clientInWgNetwork = i.netCfg.hosts.${clientName};
in
(lib.optional (clientInWgNetwork.ipv4 != null) (lib.net.cidr.make 32 clientInWgNetwork.ipv4))
++ (lib.optional (clientInWgNetwork.ipv6 != null) (lib.net.cidr.make 128 clientInWgNetwork.ipv6));
PresharedKeyFile =
config.sops.secrets."wireguard-${i.serverName}-${clientName}-${i.ifName}-presharedKey".path;
PublicKey = peerPublicKey clientName;
}) i.peers
);
};
}
) ifaceList
);
networks = lib.mkMerge (
map (
i:
let
inherit (i) ifName;
in
{
"50-${ifName}" = {
address = [
i.netCfg.hosts.${config.node.name}.cidrv4
i.netCfg.hosts.${config.node.name}.cidrv6
];
linkConfig.MTUBytes = 1500 - 4 - 8 - 40 - 8 - 32;
matchConfig.Name = ifName;
};
}
) ifaceList
);
};
};
};
}
4.4.3.20. Router
This is the configuration to make Hintbooth (Router: HUNSN RM02) act as the router for my internal network. This is not a reusable module and highly adapted to its hardware. Below is a rough sketch of the functionality:
- six LAN ports, five of which are bridged
- lan1 to lan5 are enslaved into said bridge and behave as a single VLAN-aware switch
- all VLANs are defined under
globals.networks.home-lan.vlans - for each VLAN, a routed interface me-${vlanName} is created on the router (NOTE: this interface also serves as the communication link to the local MicroVMs - the respective extra interfaces are defined in systemd-networkd (server home))
- RA and forwarding are enabled on these me-* interfaces so the router advertises vlanCfg.cidrv6 and routes between VLANs / WAN / WireGuard
- all VLANs are defined under
- the sixth LAN port is used as the WAN / untrusted uplink to the
Fritz!Box - the mapping from MAC addresses to interfaces is defined in
config.repo.secrets.local.networking.networks.<ifName>.mac(and performed in systemd-networkd (base) usingrenameInterfacesByMac)
- lan1 to lan5 are enslaved into said bridge and behave as a single VLAN-aware switch
connectivity to MicroVMs should not be lost in case there is no cable connected to the router
- this is achieved by connecting the veth interface pair veth-br / veth-int
- veth-br is part of the bridge and carries all VLANs tagged, as if it were another physical switch port
- veth-int stays on the host side and is used as the internal attachment point for MicroVMs / guests
- ConfigureWithoutCarrier and ActivationPolicy = "always-up" are used so that the bridge and veth side stay UP; this however does not guarantee connectivity by itself as the kernel will not route packets if the underlying interface is not up (see also systemd-networkd (server home))
- nftables firewall is derived from the same VLAN definitions:
- a zone
vlan-*is created for each VLAN and bound tome-*, as well as zones for WAN, WG, and DNS - all internal
vlan-*zones are allowed to go to untrusted; NAT is implemented via a custom post-routing chain that masquerades both IPv4 and IPv6 traffic - any VLAN with internet access is allowed to reach AdGuardHome for DNS (access-adguardhome-dns)
- this is important so that we can make use of the internal NGINX instance to prevent bottlenecks over the web proxy
- policy between internal networks:
- the home VLAN is allowed to access the services and devices VLANs
- the services VLAN is allowed to reach selected ports on local (currently Wireguard)
- WireGuard peers in wgHome are allowed to talk to each other
- a zone
global IPv4/IPv6 forwarding is enabled via boot.kernel.sysctl so this host acts as the main router between all VLANs, the WireGuard network, and the WAN (untrusted)
Appendix E: Current TODOs: see code comment
{
flake.modules.nixos.router =
{
config,
lib,
confLib,
globals,
...
}:
let
bridgeVLANs = lib.mapAttrsToList (_: vlan: {
VLAN = vlan.id;
}) globals.networks.home-lan.vlans;
selectVLANs = vlans: map (vlan: { VLAN = globals.networks.home-lan.vlans.${vlan}.id; }) vlans;
summersVLANs = selectVLANs [
"home"
"devices"
"services"
];
inherit (globals.general) homeDnsServer;
in
{
config = {
swarselsystems.enabledServerModules = [ "router" ];
topology.self.interfaces = lib.flip lib.concatMapAttrs globals.networks.home-lan.vlans (
vlanName: _:
lib.genAttrs [ "vlan-${vlanName}" "me-${vlanName}" ] (_: {
network = lib.mkForce vlanName;
})
);
globals.monitoring.systemd = confLib.mkSystemdMonitoring {
serviceName = "avahi-${config.node.name}";
unit = "avahi-daemon.service";
};
users.persistentIds.avahi = confLib.mkIds 978;
services = {
avahi = {
enable = true;
openFirewall = true;
settings.reflector.enable-reflector = true;
};
resolved.settings.Resolve = {
FallbackDNS = [
"1.1.1.1"
"9.9.9.9"
];
MulticastDNS = "no";
};
};
boot.kernel.sysctl = {
"net.ipv4.conf.all.forwarding" = true;
"net.ipv6.conf.all.forwarding" = true;
};
networking = {
nameservers = [
globals.networks.home-lan.vlans.services.hosts.${homeDnsServer}.ipv4
globals.networks.home-lan.vlans.services.hosts.${homeDnsServer}.ipv6
];
nftables = {
chains.postrouting.masquerade-internet = {
after = [ "hook" ];
late = true;
rules = lib.forEach (map (name: "vlan-${name}") globals.general.internetVLANs) (
zone:
lib.concatStringsSep " " [
"meta protocol { ip, ip6 }"
(lib.head config.networking.nftables.firewall.zones.${zone}.ingressExpression)
(lib.head config.networking.nftables.firewall.zones.untrusted.egressExpression)
"masquerade random"
]
);
};
firewall = {
rules = {
# Allow access to the AdGuardHome DNS server from any VLAN that has internet access
access-adguardhome-dns = {
from = map (name: "vlan-${name}") globals.general.internetVLANs;
to = [ "adguardhome" ];
verdict = "accept";
};
# Allow devices in the home VLAN to talk to any of the services or home devices.
access-services = {
from = [ "vlan-home" ];
late = true;
to = [
"vlan-services"
"vlan-devices"
"vlan-iot"
];
verdict = "accept";
};
guests-to-fritzbox-lan = {
from = [ "vlan-guests" ];
to = [ "fritzbox-lan" ];
verdict = "reject";
};
masquerade-internet = {
from = map (name: "vlan-${name}") globals.general.internetVLANs;
# masquerade = true; NOTE: custom rule above for ip4 + ip6
late = true; # Only accept after any rejects have been processed
to = [ "untrusted" ];
verdict = "accept";
};
# Allow mDNS from any VLAN (plus FritzBox-LAN) into the router
mdns-to-local = {
allowedUDPPorts = [ 5353 ];
from = [
"vlan-services"
"vlan-home"
"vlan-devices"
"vlan-guests"
"untrusted"
];
to = [ "local" ];
};
# Allow the services VLAN to reach our wireguard server and dhcpv6
services-to-local = {
allowedUDPPorts = [
52829
547
];
from = [ "vlan-services" ];
to = [ "local" ];
};
# Allow kde connect from wifi into home
untrusted-to-kdeconnect = {
allowedTCPPortRanges = [
{
from = 1714;
to = 1764;
}
];
allowedUDPPortRanges = [
{
from = 1714;
to = 1764;
}
];
from = [ "untrusted" ];
to = [ "vlan-home" ];
};
# Allow printing/scanning from wifi
untrusted-to-printer = {
allowedTCPPorts = [
80
631
];
from = [ "untrusted" ];
to = [ "printer" ];
};
}
// lib.optionalAttrs (globals.services ? scanservjs) {
# Allow the scan server to reach the scanner's WSD endpoint
scanservjs-to-printer = {
allowedTCPPorts = [ 80 ];
from = [ "scanservjs" ];
to = [ "printer" ];
};
};
zones = {
adguardhome = {
ipv4Addresses = [
globals.networks.home-lan.vlans.services.hosts.${homeDnsServer}.ipv4
];
ipv6Addresses = [
globals.networks.home-lan.vlans.services.hosts.${homeDnsServer}.ipv6
];
};
fritzbox-lan = {
ipv4Addresses = [ globals.networks.home-lan.cidrv4 ];
ipv6Addresses = [ globals.networks.home-lan.cidrv6 ];
parent = "untrusted";
};
printer.ipv4Addresses = [
globals.networks.home-lan.vlans.devices.hosts.dell-C2665dnf-F49D60.ipv4
];
untrusted.interfaces = [ "lan" ];
wgHome.interfaces = [ "wgHome" ];
}
// lib.optionalAttrs (globals.services ? scanservjs) {
scanservjs.ipv4Addresses = [
globals.networks.home-lan.vlans.services.hosts.${globals.services.scanservjs.extraConfig.node}.ipv4
];
}
// lib.flip lib.concatMapAttrs globals.networks.home-lan.vlans (
vlanName: _: {
"vlan-${vlanName}".interfaces = [ "me-${vlanName}" ];
}
);
};
};
};
systemd.network = {
netdevs = {
"10-veth" = {
netdevConfig = {
Kind = "veth";
Name = "veth-br";
};
peerConfig.Name = "veth-int";
};
"20-br" = {
bridgeConfig.VLANFiltering = true;
netdevConfig = {
Kind = "bridge";
Name = "br";
};
};
};
networks = {
"15-veth-br" = {
inherit bridgeVLANs;
linkConfig.RequiredForOnline = "no";
matchConfig.Name = "veth-br";
networkConfig.Bridge = "br";
};
"15-veth-int" = {
linkConfig = {
ActivationPolicy = "always-up";
RequiredForOnline = "no";
};
matchConfig.Name = "veth-int";
networkConfig = {
ConfigureWithoutCarrier = true;
LinkLocalAddressing = "no";
};
vlan = map (name: "vlan-${name}") (builtins.attrNames globals.networks.home-lan.vlans);
};
"40-br" = {
bridgeConfig = { };
linkConfig = {
ActivationPolicy = "always-up";
RequiredForOnline = "no";
};
matchConfig.Name = "br";
networkConfig = {
ConfigureWithoutCarrier = true;
LinkLocalAddressing = "no";
};
};
}
//
lib.mapAttrs'
(
lan: lanVLANs:
lib.nameValuePair "30-${lan}" {
bridgeVLANs = lanVLANs;
linkConfig.RequiredForOnline = "enslaved";
matchConfig.MACAddress = config.repo.secrets.local.networking.networks.${lan}.mac;
networkConfig = {
Bridge = "br";
ConfigureWithoutCarrier = true;
};
}
)
{
# swBedroom
lan1 = selectVLANs [
"home"
"devices"
"guests"
];
# swKitchen
lan2 = bridgeVLANs;
# summers
lan3 = summersVLANs;
lan4 = summersVLANs;
# swLivingRoom
# TODO: remove services and reset ports 5+6 on swLR to guest when kitchen construction is finished
lan5 = selectVLANs [
"home"
"devices"
"services"
"guests"
];
}
// lib.flip lib.concatMapAttrs globals.networks.home-lan.vlans (
vlanName: vlanCfg: {
"40-me-${vlanName}" = lib.mkForce {
address = [
vlanCfg.hosts.${config.node.name}.cidrv4
vlanCfg.hosts.${config.node.name}.cidrv6
];
ipv6Prefixes = [
{
Prefix = vlanCfg.cidrv6;
}
];
ipv6SendRAConfig = {
Managed = true;
OtherInformation = true;
};
linkConfig.RequiredForOnline = "routable";
matchConfig.Name = "me-${vlanName}";
networkConfig = {
IPv4Forwarding = "yes";
IPv6AcceptRA = false;
IPv6PrivacyExtensions = "yes";
IPv6SendRA = true;
};
};
}
);
wait-online.anyInterface = true;
};
};
};
}
4.4.3.21. Kavita
Kavita is the service I use for my library management. It seems more tailored towards comics/graphic novels, but still I prefer its interface to what Calibre offers.
{
flake.modules.nixos.kavita =
{
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
name = "kavita";
port = 8080;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceGroup
serviceName
servicePort
serviceUser
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
webProxy
;
in
{
config = {
swarselsystems.enabledServerModules = [ "kavita" ];
topology.self.services.${serviceName}.info = "https://${serviceDomain}";
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = "<title>Kavita</title>";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops.secrets = {
kanidm-kavita = {
group = serviceGroup;
mode = "0440";
owner = serviceUser;
rekey.keyPrefix = confLib.kanidmSecrets;
};
kavita-token = {
owner = serviceUser;
rekey.generator.script = "base64";
};
};
users = {
users.${serviceUser}.extraGroups = [ "users" ];
persistentIds.kavita = confLib.mkIds 995;
};
services.${serviceName} = {
enable = true;
credentials = {
oidc_secret = config.sops.secrets.kanidm-kavita.path;
token_key = config.sops.secrets.kavita-token.path;
};
dataDir = "/var/lib/${serviceName}";
settings = {
OpenIdConnectSettings = {
Authority = "https://${globals.services.kanidm.domain}/oauth2/openid/${serviceName}";
ClientId = serviceName;
CustomScopes = [ ];
Secret = "@oidc_secret@";
};
Port = servicePort;
};
user = serviceUser;
};
environment.persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [
{
directory = "/var/lib/${serviceName}";
group = serviceGroup;
user = serviceUser;
}
];
};
nodes = lib.mkMerge [
{
${idmServer} = confLib.mkKanidmOidcSystem {
inherit serviceDomain serviceName;
originUrl = "https://${serviceDomain}/signin-oidc";
};
}
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
serviceAddress
serviceDomain
serviceName
servicePort
;
maxBody = 0;
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit serviceDomain serviceName servicePort;
extraConfig = nginxAccessRules;
maxBody = 0;
serviceAddress = homeServiceAddress;
}
);
}
];
};
};
}
4.4.3.22. jellyfin
My video streaming service of choice. In the past I used Plex, but I prefer using Jellyfin now, which looks more clean (and is not payment incentivized).
Using the SSO Plugin and Jellyfin Enhanced are sadly not declarative:
- Login as admin
- Dashboard > Plugins > Manage repositories:
- add https://raw.githubusercontent.com/Buco7854/jellyfin-plugin-sso/manifest-release/manifest.json (community-fork after archival of root)
- add https://raw.githubusercontent.com/n00bcodr/jellyfin-plugins/main/manifest.json (Jellyfin Enhanced)
- Restart service to trigger discovery
- Install "SSO-Auth" and "Jellyfin Enhanced"
- Restart service to initialize plugin
- Dashboard > Plugins > SSO-Auth > Settings:
| Field | Value |
|---|---|
| Name | kanidm |
| OID Endpoint | https://<kanidmdomain>/oauth2/openid/jellyfin |
| OID Client ID | jellyfin |
| OID Secret | <kanidm-secret> |
| Enabled | yes |
| Enable Authorization by Plugin | yes |
| Role Claim | groups |
| Enable All Folders | yes |
| Default Provider | kanidm |
| Preserve Existing Admin Permissions | yes |
- In Dashboard > Branding:
Login disclaimer:
<form action="https://<kanidmDomain>/sso/OID/start/kanidm"> <button class="raised block emby-button button-submit"> Sign in with Kanidm </button> </form>Custom CSS code:
a.raised.emby-button { padding: 0.9em 1em; color: inherit !important; } .disclaimerContainer { display: block; }
- Dashboard > Networking:
- Known proxies: put in IPv4 and IPv6 of homeProxy/webProxy
- Published Server URLs:
https://<jellyfinDomain>
- Dashboard > Plugins > Jellyfin Enhanced > Seerr
- paste API key from Seerr
- paste API key from TMDB
- Dashboard > Plugins > Jellyfin Enhanced > *arr
- import Radarr from Seerr
- import Sonarr from Seerr
{
flake.modules.nixos.jellyfin =
{
config,
lib,
pkgs,
confLib,
...
}:
let
inherit
(confLib.gen {
name = "jellyfin";
port = 8096;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceGroup
serviceName
servicePort
serviceUser
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
webProxy
;
in
{
config = {
swarselsystems.enabledServerModules = [ "jellyfin" ];
topology.self.services.${serviceName}.info = "https://${serviceDomain}";
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = "Healthy";
path = "/health";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops.secrets.kanidm-jellyfin = {
group = serviceGroup;
mode = "0440";
owner = serviceUser;
rekey.keyPrefix = confLib.kanidmSecrets;
};
users = {
users.${serviceUser}.extraGroups = [
"video"
"render"
"users"
];
persistentIds.jellyfin = confLib.mkIds 994;
};
services.${serviceName} = {
enable = true;
user = serviceUser;
};
environment.persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [
{
directory = "/var/lib/${serviceName}";
group = serviceGroup;
user = serviceUser;
}
{
directory = "/var/cache/${serviceName}";
group = serviceGroup;
user = serviceUser;
}
];
};
# nixpkgs.config.packageOverrides = pkgs: {
# intel-vaapi-driver = pkgs.intel-vaapi-driver.override { enableHybridCodec = true; };
# };
hardware.graphics = {
enable = true;
extraPackages = with pkgs; [
intel-media-driver # LIBVA_DRIVER_NAME=iHD
# intel-vaapi-driver # LIBVA_DRIVER_NAME=i965 (older but works better for Firefox/Chromium)
libva-vdpau-driver
libvdpau-va-gl
];
};
nodes = lib.mkMerge [
{
${idmServer} = confLib.mkKanidmOidcSystem {
inherit serviceDomain serviceName;
originUrl = "https://${serviceDomain}/sso/OID/redirect/kanidm";
};
}
{
${webProxy}.services.nginx = lib.recursiveUpdate (confLib.genNginx {
inherit
serviceAddress
serviceDomain
serviceName
servicePort
;
maxBody = 0;
}) { virtualHosts.${serviceDomain}.locations."/".X-Frame-Options = "SAMEORIGIN"; };
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
lib.recursiveUpdate (confLib.genNginx {
inherit serviceDomain serviceName servicePort;
extraConfig = nginxAccessRules;
maxBody = 0;
serviceAddress = homeServiceAddress;
}) { virtualHosts.${serviceDomain}.locations."/".X-Frame-Options = "SAMEORIGIN"; }
);
}
];
};
};
}
4.4.3.23. Seerr
This provides my family with an easy way to request me to download new movies or series into jellyfin.
The first setup must be done manually:
- login with webadmin and Jellyfin API key
- connect Radarr and Sonarr
- import all users from Jellyfin
- setup mail notifications
- setup Gotify notifications
{
flake-file.inputs.seerr-oidc = {
flake = false;
url = "github:michaelhthomas/seerr/feat/oidc-login-basic";
};
flake.modules.nixos.seerr =
{ inputs, lib, ... }:
{
imports = lib.optionals (inputs ? seerr-oidc) [
(
{
inputs,
config,
lib,
pkgs,
confLib,
...
}:
let
inherit
(confLib.gen {
dir = "/var/lib/private/jellyseerr";
name = "seerr";
port = 5055;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDir
serviceDomain
serviceName
servicePort
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
webProxy
;
in
{
swarselsystems.enabledServerModules = [ "seerr" ];
topology.self.services.${serviceName}.info = "https://${serviceDomain}";
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
extra.extraConfig.node = config.node.name;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = "version";
path = "/api/v1/status";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops.secrets.kanidm-seerr.rekey.keyPrefix = confLib.kanidmSecrets;
services.${serviceName} = {
enable = true;
package = pkgs.seerr.overrideAttrs (old: {
pnpmDeps = old.pnpmDeps.overrideAttrs {
outputHash = "sha256-gqjz0DM0VYdFKTkoKPG9fjAwZlKeQZS1GB4wwUcwZ9M=";
};
src = inputs.seerr-oidc;
version = "oidc-${inputs.seerr-oidc.shortRev}";
});
port = servicePort;
};
environment.persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [
{
directory = serviceDir;
mode = "0700";
}
];
};
nodes = lib.mkMerge [
{
${idmServer} = confLib.mkKanidmOidcSystem {
inherit serviceDomain serviceName;
originUrl = [
"https://${serviceDomain}/login"
"https://${serviceDomain}/profile/settings/linked-accounts"
];
};
}
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
serviceAddress
serviceDomain
serviceName
servicePort
;
maxBody = 0;
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit serviceDomain serviceName servicePort;
extraConfig = nginxAccessRules;
maxBody = 0;
serviceAddress = homeServiceAddress;
}
);
}
];
}
)
];
};
}
4.4.3.24. Navidrome
My music streaming service. In the past I used subsonic and Gonic, but I prefer the tag based management.
After the first login when setting up, you need to add a password to the user that is created using OIDC. This is so that login using DSub2 becomes possible.
{
flake.modules.nixos.navidrome =
{
self,
config,
lib,
pkgs,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
name = "navidrome";
port = 4040;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceGroup
serviceName
servicePort
serviceUser
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
webProxy
;
in
{
imports = [
self.modules.nixos.server-pipewire
];
config = {
swarselsystems.enabledServerModules = [ "navidrome" ];
topology.self.services.${serviceName}.info = "https://${serviceDomain}";
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = ''^\.$'';
path = "/ping";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
users = {
users = {
${serviceUser} = {
extraGroups = [
"audio"
"utmp"
"users"
"pipewire"
];
group = serviceGroup;
isSystemUser = true;
uid = 61593;
};
};
groups = {
${serviceGroup}.gid = 61593;
};
};
services.${serviceName} = {
enable = true;
settings = {
Address = "0.0.0.0";
AutoImportPlaylists = false;
EnableInsightsCollector = false;
EnableSharing = true;
EnableTranscodingConfig = true;
Jukebox = {
Default = "default";
Devices = [
# use mpv --audio-device=help to get these
[
"default"
"pipewire"
]
];
Enabled = true;
};
LastFM = {
inherit (config.repo.secrets.local.LastFM) ApiKey Secret;
};
MPVPath = "${pkgs.mpv}/bin/mpv";
MusicFolder = "/storage/Music";
PlaylistsPath = "./Playlists";
Port = servicePort;
ReverseProxyUserHeader = "X-User";
ReverseProxyWhitelist = lib.concatMapStringsSep "," (host: "${host.ipv4}/32,${host.ipv6}/128") (
[ globals.networks."${globals.wireguard.wgProxy.netConfigPrefix}-wgProxy".hosts.${webProxy} ]
++
lib.optional isHome
globals.networks."${globals.wireguard.wgHome.netConfigPrefix}-wgHome".hosts.${homeWebProxy}
);
ScanSchedule = "@every 24h";
Scanner.GroupAlbumReleases = true;
Spotify = {
inherit (config.repo.secrets.local.Spotify) ID Secret;
};
UILoginBackgroundUrl = "https://i.imgur.com/OMLxi7l.png";
UIWelcomeMessage = config.repo.secrets.common.names.navidrome;
};
};
environment = {
persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [
{
directory = "/var/lib/${serviceName}";
group = serviceGroup;
user = serviceUser;
}
];
};
systemPackages = with pkgs; [
pciutils
alsa-utils
mpv
];
};
hardware.enableAllFirmware = lib.mkForce true;
systemd.services = {
${serviceName} = {
after = [ "pipewire.service" ];
environment = {
PIPEWIRE_RUNTIME_DIR = "/run/pipewire";
SQLITE_TMPDIR = "/dev/shm";
};
serviceConfig = {
PrivateDevices = lib.mkForce false;
PrivateTmp = lib.mkForce false;
PrivateUsers = lib.mkForce false;
RestrictRealtime = lib.mkForce false;
RootDirectory = lib.mkForce null;
SystemCallFilter = lib.mkForce null;
};
wants = [ "pipewire.service" ];
};
};
nodes =
let
genNginx = toAddress: extraConfigPre: {
upstreams = {
${serviceName}.servers = {
"${toAddress}:${builtins.toString servicePort}" = { };
};
};
virtualHosts = {
"${serviceDomain}" = {
acmeRoot = null;
extraConfig = extraConfigPre;
forceSSL = true;
locations =
let
extraConfig = ''
proxy_redirect http:// https://;
proxy_read_timeout 600s;
proxy_send_timeout 600s;
proxy_buffering off;
proxy_request_buffering off;
client_max_body_size 0;
'';
in
{
"/" = {
inherit extraConfig;
proxyPass = "http://${serviceName}";
proxyWebsockets = true;
};
}
// lib.genAttrs [ "/rest" "/share" ] (_: {
bypassAuth = true;
extraConfig = extraConfig + ''
proxy_set_header X-User "";
'';
proxyPass = "http://${serviceName}";
proxyWebsockets = true;
setOauth2Headers = false;
});
oauth2 = {
enable = true;
allowedGroups = [ "navidrome_access" ];
};
useACMEHost = globals.domains.main;
};
};
};
in
lib.mkMerge [
{ ${idmServer} = confLib.mkKanidmOauth2ProxyAccess { inherit serviceName; }; }
{ ${webProxy}.services.nginx = genNginx serviceAddress ""; }
{ ${homeWebProxy}.services.nginx = lib.mkIf isHome (genNginx homeServiceAddress nginxAccessRules); }
];
};
};
}
4.4.3.25. Spotifyd
Simple config for running Spotifyd which allows me to remote play spotify songs on my speakers.
{
flake.modules.nixos.spotifyd =
{
config,
lib,
pkgs,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
name = "spotifyd";
port = 1025;
})
serviceGroup
serviceName
servicePort
serviceUser
;
inherit (confLib.static) routerServer;
in
{
config = {
swarselsystems.enabledServerModules = [ "spotifyd" ];
globals.monitoring.systemd = confLib.mkSystemdMonitoring {
inherit serviceName;
unit = "spotifyd.service";
};
users = {
users.${serviceUser} = {
extraGroups = [
"audio"
"utmp"
"pipewire"
];
group = serviceGroup;
isSystemUser = true;
uid = 65136;
};
groups.${serviceGroup}.gid = 65136;
};
services = {
pipewire.systemWide = true;
spotifyd = {
enable = true;
settings.global = {
backend = "pulseaudio";
dbus_type = "session";
device_name = config.repo.secrets.common.names.spotifyd;
use_mpris = false;
zeroconf_port = servicePort;
};
};
};
environment.persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [
{ directory = "/var/cache/private/spotifyd"; }
];
};
networking = {
firewall.allowedTCPPorts = [ servicePort ];
# https://github.com/Spotifyd/spotifyd/issues/1366
hosts."0.0.0.0" = [ "apresolve.spotify.com" ];
};
# hacky way to enable multi-session
# when another user connects, the service will crash and the new user will login
systemd = {
services = {
spotifyd.serviceConfig.RestartSec = lib.mkForce 1;
spotifyd-watchdog = {
path = with pkgs; [
gnugrep
iproute2
systemd
];
script = ''
pid=$(systemctl show --property MainPID --value spotifyd.service)
if [ "$pid" -eq 0 ]; then exit 0; fi
if ! ss -Htnp state established '( dport = :443 or dport = :4070 or dport = :80 )' | grep -q "pid=$pid,"; then
systemctl restart spotifyd.service
fi
'';
serviceConfig.Type = "oneshot";
};
};
timers.spotifyd-watchdog = {
timerConfig = {
OnBootSec = "10m";
OnUnitActiveSec = "10m";
};
wantedBy = [ "timers.target" ];
};
};
nodes.${routerServer}.networking.nftables.firewall.rules."fritzbox-to-${serviceName}" = {
extraLines = [
"ip saddr ${globals.networks.home-lan.cidrv4} tcp dport ${toString servicePort} accept"
];
from = [ "untrusted" ];
to = [ "vlan-services" ];
};
};
};
}
4.4.3.26. MPD
My jukebox replacement since the native one in navidrome does not work :)
{
flake.modules.nixos.mpd =
{
self,
config,
lib,
pkgs,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
name = "mpd";
port = 6600;
})
serviceGroup
serviceName
servicePort
serviceUser
;
inherit (confLib.static) routerServer;
in
{
imports = [
self.modules.nixos.server-pipewire
];
config = {
swarselsystems.enabledServerModules = [ "mpd" ];
globals.monitoring.tcp = confLib.mkTcpMonitoring {
inherit serviceName servicePort;
expectedRegex = "^OK MPD";
};
sops.secrets.mpd-pw = {
group = serviceGroup;
mode = "0440";
owner = serviceUser;
};
users = {
users = {
${serviceUser} = {
extraGroups = [
"audio"
"utmp"
"users"
"pipewire"
];
group = serviceGroup;
isSystemUser = true;
};
};
groups.${serviceGroup} = { };
};
services.${serviceName} = {
enable = true;
credentials = [
{
passwordFile = config.sops.secrets.mpd-pw.path;
permissions = [
"read"
"add"
"control"
"admin"
];
}
];
group = serviceGroup;
openFirewall = true;
settings = {
audio_output = [
{
name = "PipeWire";
type = "pipewire";
}
];
bind_to_address = "any";
music_directory = "/storage/Music";
port = servicePort;
};
user = serviceUser;
};
environment = {
persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [
{
directory = "/var/lib/${serviceName}";
group = serviceGroup;
user = serviceUser;
}
];
};
systemPackages = with pkgs; [
pciutils
alsa-utils
mpv
];
};
nodes.${routerServer}.networking.nftables.firewall.rules."fritzbox-to-${serviceName}" = {
extraLines = [
"ip saddr ${globals.networks.home-lan.cidrv4} tcp dport ${toString servicePort} accept"
];
from = [ "untrusted" ];
to = [ "vlan-services" ];
};
};
};
}
4.4.3.27. pipewire
Needed for audio and stuff.
{
flake.modules.nixos.server-pipewire =
{
config,
lib,
confLib,
...
}:
{
config = {
swarselsystems.enabledServerModules = [ "pipewire" ];
users.persistentIds.rtkit = confLib.mkIds 996;
services.pipewire = {
enable = true;
alsa = {
enable = true;
support32Bit = true;
};
audio.enable = true;
jack.enable = true;
pulse.enable = true;
wireplumber.enable = true;
};
environment.persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [
{
directory = "/var/lib/pipewire";
group = "pipewire";
user = "pipewire";
}
];
};
security.rtkit.enable = true;
};
key = "swarsel/server/server-pipewire";
};
}
4.4.3.28. PostgreSQL
Many services require a database, and I like to go with full postgres when giving the chance. Each host will usually run its own instance instead of maintaining a centralized one.
{
flake.modules.nixos.postgresql =
{
config,
lib,
pkgs,
confLib,
...
}:
let
inherit (confLib.gen { name = "postgresql"; })
serviceName
;
postgresVersion = config.swarselsystems.server.postgresql.version;
in
{
options.swarselsystems.server.postgresql = {
rolePasswordFiles = lib.mkOption {
default = { };
type = lib.types.attrsOf lib.types.path;
};
version = lib.mkOption {
default = 18;
type = lib.types.int;
};
};
config = {
swarselsystems.enabledServerModules = [ "postgresql" ];
globals.monitoring.tcp = confLib.mkTcpMonitoring {
serviceName = "${serviceName}-${config.node.name}";
servicePort = config.services.${serviceName}.settings.port;
};
services = {
${serviceName} = {
enable = true;
package = pkgs."postgresql_${builtins.toString postgresVersion}";
authentication = lib.concatMapStrings (role: ''
local all "${role}" scram-sha-256
'') (lib.attrNames config.swarselsystems.server.postgresql.rolePasswordFiles);
dataDir = "/var/lib/${serviceName}/${builtins.toString postgresVersion}";
settings = {
synchronous_commit = "off";
}
// (
if config.swarselsystems.isMicroVM then
{
effective_cache_size = "${builtins.toString (config.microvm.mem / 2)}MB";
shared_buffers = "${builtins.toString (config.microvm.mem / 4)}MB";
}
else
{ shared_buffers = "128MB"; }
);
};
};
environment.persistence = {
"/persist".directories =
lib.mkIf (config.swarselsystems.isImpermanence && config.swarselsystems.isCloud)
[
{
directory = "/var/lib/postgresql";
group = "postgres";
mode = "0750";
user = "postgres";
}
];
"/state".directories = lib.mkIf config.swarselsystems.isMicroVM [
{
directory = "/var/lib/postgresql";
group = "postgres";
mode = "0750";
user = "postgres";
}
];
};
systemd.services."${serviceName}-setup".postStart =
lib.mkIf (config.swarselsystems.server.postgresql.rolePasswordFiles != { })
(
lib.concatMapAttrsStringSep "\n" (role: passwordFile: ''
psql -tA -v ON_ERROR_STOP=1 <<'EOF'
\set password `cat ${passwordFile}`
ALTER ROLE "${role}" WITH PASSWORD :'password';
EOF
'') config.swarselsystems.server.postgresql.rolePasswordFiles
);
};
key = "swarsel/server/postgresql";
};
}
4.4.3.29. Podman
Allows me to spin up containers for services that do not provide NixOS options.
{
flake.modules.nixos.podman =
{
config,
lib,
confLib,
...
}:
{
config = {
swarselsystems.enabledServerModules = [ "podman" ];
users.persistentIds.podman = confLib.mkIds 969;
environment.persistence = {
"/persist".directories =
lib.mkIf (config.swarselsystems.isImpermanence && !config.swarselsystems.isMicroVM)
[
{ directory = "/var/lib/containers"; }
];
"/state".directories = lib.mkIf config.swarselsystems.isMicroVM [
{ directory = "/var/lib/containers"; }
];
};
networking.nftables.firewall = lib.mkIf config.networking.nftables.enable {
rules = {
local-to-podman = {
before = [ "drop" ];
from = [
"local"
"wgProxy"
"wgHome"
];
to = [ "podman" ];
verdict = "accept";
};
podman-to-internet = lib.mkIf (config.networking.nftables.firewall.zones ? untrusted) {
before = [ "drop" ];
from = [ "podman" ];
to = [ "untrusted" ];
verdict = "accept";
};
podman-to-postgres = lib.mkIf config.services.postgresql.enable {
allowedTCPPorts = [ config.services.postgresql.settings.port ];
before = [ "drop" ];
from = [ "podman" ];
to = [ "local" ];
};
};
zones.podman.interfaces = [ "podman0" ];
};
virtualisation = {
oci-containers.backend = "podman";
podman.enable = true;
};
systemd.services.podman-network-reload =
let
reload = "${lib.getExe config.virtualisation.podman.package} network reload --all";
in
lib.mkIf config.networking.nftables.enable {
after = [ "nftables.service" ];
partOf = [ "nftables.service" ];
serviceConfig = {
ExecReload = reload;
ExecStart = reload;
RemainAfterExit = true;
Type = "oneshot";
};
unitConfig.ReloadPropagatedFrom = [ "nftables.service" ];
wantedBy = [
"multi-user.target"
"nftables.service"
];
};
};
key = "swarsel/server/podman";
};
}
4.4.3.30. matrix (use db)
My messenger of choice. I use this mainly to bridge messages of WhatsApp/telegram/signal into it, which allows me to only use a single app for all of my communication needs.
{
flake.modules.nixos.matrix =
{
self,
config,
lib,
pkgs,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
name = "matrix";
port = 8008;
user = "matrix-synapse";
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceGroup
serviceName
servicePort
serviceUser
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
idmServer
isHome
isProxied
nginxAccessRules
notificationMail
webProxy
webProxyIf
;
federationPort = 8448;
whatsappPort = 29318;
telegramPort = 29317;
signalPort = 29328;
ircPort = 8009;
ircMediaPort = 11111;
serviceUsers = [
"matrix-synapse"
"matrix-appservice-irc"
"mautrix-discord"
"mautrix-meta-instagram"
"mautrix-telegram"
"mautrix-whatsapp"
"mautrix-signal"
];
mkPostgresUri = role: password: "postgresql://${role}:${password}@/${role}?host=/run/postgresql";
baseUrl = "https://${serviceDomain}";
homeserver = {
address = "http://localhost:${builtins.toString servicePort}";
domain = serviceDomain;
};
adminUser = "@${config.swarselsystems.mainUser}:${serviceDomain}";
bridgePermissions = {
${adminUser} = "admin";
"*" = "relay";
};
mkWellKnown = data: ''
default_type application/json;
add_header Access-Control-Allow-Origin *;
return 200 '${builtins.toJSON data}';
'';
in
{
imports = [
self.modules.nixos.postgresql
];
config = {
swarselsystems = {
enabledServerModules = [ "matrix" ];
server.postgresql.rolePasswordFiles = lib.genAttrs serviceUsers (
role: config.sops.secrets."${role}-db-password".path
);
};
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = "OK";
path = "/health";
};
networks = lib.mkMerge [
(confLib.mkDualFirewallRules {
tcpPorts = [
servicePort
ircMediaPort
];
})
{
${webProxyIf}.hosts = lib.mkIf isProxied {
${config.node.name}.firewallRuleForNode.${webProxy}.allowedTCPPorts = [ federationPort ];
};
}
];
};
sops = {
secrets =
lib.mapAttrs' (id: _: lib.nameValuePair "matrix-irc-${id}-key" { }) (
lib.filterAttrs (_: server: server ? onConnectCommands) config.repo.secrets.local.irc.servers
)
// {
kanidm-matrix = {
group = serviceGroup;
mode = "0440";
owner = serviceUser;
rekey.keyPrefix = confLib.kanidmSecrets;
};
matrix-doublepuppet-token.rekey.generator.script = "hex";
matrix-shared-secret = {
owner = serviceUser;
rekey.generator.script = "alnum";
};
mautrix-meta-instagram-as-token.rekey.generator.script = "hex";
mautrix-meta-instagram-hs-token.rekey.generator.script = "hex";
mautrix-meta-instagram-pickle-key.rekey.generator.script = "alnum";
mautrix-signal-pickle-key.rekey.generator.script = "alnum";
mautrix-telegram-api-hash.owner = serviceUser;
mautrix-telegram-api-id.owner = serviceUser;
mautrix-telegram-as-token = {
owner = serviceUser;
rekey.generator.script = "hex";
};
mautrix-telegram-hs-token = {
owner = serviceUser;
rekey.generator.script = "hex";
};
mautrix-whatsapp-pickle-key.rekey.generator.script = "alnum";
notification-mail-pw.rekey.keyPrefix = notificationMail.keyPrefix;
}
// lib.genAttrs (map (role: "${role}-db-password") serviceUsers) (_: {
owner = config.systemd.services.postgresql.serviceConfig.User;
rekey.generator.script = "alnum";
});
templates = {
"doublepuppet.yaml" = {
content = ''
id: doublepuppet
url:
as_token: ${config.sops.placeholder.matrix-doublepuppet-token}
hs_token: notused
sender_localpart: notused
rate_limited: false
namespaces:
users:
- regex: '@.*:${builtins.replaceStrings [ "." ] [ "\\." ] serviceDomain}'
exclusive: false
'';
owner = serviceUser;
};
"matrix-appservice-irc.yml" = {
content = builtins.toJSON config.services.matrix-appservice-irc.settings;
owner = "matrix-appservice-irc";
restartUnits = [ "matrix-appservice-irc.service" ];
};
"matrix-database.yaml" = {
content = builtins.toJSON {
database = lib.recursiveUpdate config.services.matrix-synapse.settings.database {
args.password = config.sops.placeholder."matrix-synapse-db-password";
};
};
owner = serviceUser;
};
"matrix-email.yaml" = {
content = builtins.toJSON {
email = {
app_name = "Matrix";
enable_notifs = true;
notif_from = "%(app)s <${notificationMail.address}>";
require_transport_security = true;
smtp_host = notificationMail.host;
smtp_pass = config.sops.placeholder.notification-mail-pw;
smtp_port = 587;
smtp_user = notificationMail.address;
};
};
owner = serviceUser;
};
"matrix_user_register.sh".content = ''
register_new_matrix_user -k ${config.sops.placeholder.matrix-shared-secret} http://localhost:${builtins.toString servicePort}
'';
matrixshared = {
content = ''
registration_shared_secret: ${config.sops.placeholder.matrix-shared-secret}
'';
owner = serviceUser;
};
mautrixdiscord = {
content = ''
MAUTRIX_DISCORD_DB_PASSWORD=${config.sops.placeholder."mautrix-discord-db-password"}
MAUTRIX_DISCORD_DOUBLEPUPPET=as_token:${config.sops.placeholder.matrix-doublepuppet-token}
'';
owner = serviceUser;
};
mautrixmetainstagram = {
content = ''
MAUTRIX_META_INSTAGRAM_DB_PASSWORD=${config.sops.placeholder."mautrix-meta-instagram-db-password"}
MAUTRIX_META_INSTAGRAM_AS_TOKEN=${config.sops.placeholder.mautrix-meta-instagram-as-token}
MAUTRIX_META_INSTAGRAM_HS_TOKEN=${config.sops.placeholder.mautrix-meta-instagram-hs-token}
MAUTRIX_META_INSTAGRAM_PICKLE_KEY=${config.sops.placeholder.mautrix-meta-instagram-pickle-key}
MAUTRIX_META_INSTAGRAM_DOUBLEPUPPET=as_token:${config.sops.placeholder.matrix-doublepuppet-token}
'';
owner = serviceUser;
};
mautrixsignal = {
content = ''
MAUTRIX_SIGNAL_DB_PASSWORD=${config.sops.placeholder."mautrix-signal-db-password"}
MAUTRIX_SIGNAL_PICKLE_KEY=${config.sops.placeholder.mautrix-signal-pickle-key}
MAUTRIX_SIGNAL_BRIDGE_LOGIN_SHARED_SECRET=as_token:${config.sops.placeholder.matrix-doublepuppet-token}
'';
owner = serviceUser;
};
mautrixtelegram = {
content = ''
MAUTRIX_TELEGRAM_DB_PASSWORD=${config.sops.placeholder."mautrix-telegram-db-password"}
MAUTRIX_TELEGRAM_APPSERVICE_AS_TOKEN=${config.sops.placeholder.mautrix-telegram-as-token}
MAUTRIX_TELEGRAM_APPSERVICE_HS_TOKEN=${config.sops.placeholder.mautrix-telegram-hs-token}
MAUTRIX_TELEGRAM_TELEGRAM_API_ID=${config.sops.placeholder.mautrix-telegram-api-id}
MAUTRIX_TELEGRAM_TELEGRAM_API_HASH=${config.sops.placeholder.mautrix-telegram-api-hash}
MAUTRIX_TELEGRAM_DOUBLEPUPPET=${config.sops.placeholder.matrix-doublepuppet-token}
'';
owner = serviceUser;
};
mautrixwhatsapp = {
content = ''
MAUTRIX_WHATSAPP_DB_PASSWORD=${config.sops.placeholder."mautrix-whatsapp-db-password"}
MAUTRIX_WHATSAPP_PICKLE_KEY=${config.sops.placeholder.mautrix-whatsapp-pickle-key}
MAUTRIX_WHATSAPP_BRIDGE_LOGIN_SHARED_SECRET=as_token:${config.sops.placeholder.matrix-doublepuppet-token}
'';
owner = serviceUser;
};
};
};
users.persistentIds = {
matrix-appservice-irc = confLib.mkIds 943;
mautrix-discord = confLib.mkIds 939;
mautrix-meta.gid = 941;
mautrix-meta-instagram = confLib.mkIds 942;
mautrix-meta-registration.gid = 940;
mautrix-signal = confLib.mkIds 993;
mautrix-telegram = confLib.mkIds 991;
mautrix-whatsapp = confLib.mkIds 992;
};
services = {
matrix-appservice-irc = {
enable = true;
port = ircPort;
registrationUrl = "http://localhost:${builtins.toString ircPort}";
settings = {
database = {
connectionString =
mkPostgresUri "matrix-appservice-irc"
config.sops.placeholder."matrix-appservice-irc-db-password";
engine = "postgres";
};
homeserver = {
inherit (homeserver) domain;
url = homeserver.address;
};
ircService = {
logging = {
level = "info";
toConsole = true;
};
mediaProxy = {
bindPort = ircMediaPort;
publicUrl = "https://${serviceDomain}/media";
};
permissions.${adminUser} = "admin";
servers = lib.mapAttrs' (
id: server:
lib.nameValuePair server.address (
lib.recursiveUpdate {
botConfig = {
enabled = false;
joinChannelsIfNoUsers = false;
nick = "MatrixBridge";
username = "matrixbridge";
};
dynamicChannels = {
aliasTemplate = "#${id}_$CHANNEL";
createAlias = true;
enabled = true;
federate = false;
joinRule = "public";
published = false;
useHomeserverDirectory = false;
};
ircClients = {
allowNickChanges = true;
idleTimeout = 0;
kickOn = {
channelJoinFailure = true;
ircConnectionFailure = true;
userQuit = true;
};
lineLimit = 3;
maxClients = 30;
nickTemplate = "$DISPLAY[m]";
realnameFormat = "mxid";
};
matrixClients = {
displayName = "$NICK (IRC)";
joinAttempts = -1;
userTemplate = "@${id}_$NICK";
};
membershipLists = {
enabled = true;
floodDelayMs = 10000;
global = {
ircToMatrix = {
incremental = true;
initial = false;
requireMatrixJoined = false;
};
matrixToIrc = {
incremental = true;
initial = true;
};
};
ignoreIdleUsersOnStartup = {
enabled = true;
idleForHours = 720;
};
};
networkId = id;
privateMessages = {
enabled = true;
federate = false;
};
sasl = true;
sendConnectionMessages = true;
ssl = true;
} (builtins.removeAttrs server [ "address" ])
)
) config.repo.secrets.local.irc.servers;
};
};
};
matrix-synapse = {
enable = true;
dataDir = "/var/lib/matrix-synapse";
extraConfigFiles = [
config.sops.templates."matrix-database.yaml".path
config.sops.templates."matrix-email.yaml".path
config.sops.templates.matrixshared.path
];
settings = {
app_service_config_files =
let
inherit (config.services.matrix-synapse) dataDir;
in
[
"${dataDir}/telegram-registration.yaml"
"${dataDir}/whatsapp-registration.yaml"
"${dataDir}/signal-registration.yaml"
"/var/lib/matrix-appservice-irc/registration.yml"
config.sops.templates."doublepuppet.yaml".path
];
listeners = [
{
bind_addresses = [ "0.0.0.0" ];
port = servicePort;
resources = [
{
compress = true;
names = [
"client"
"federation"
];
}
];
tls = false;
type = "http";
x_forwarded = true;
}
];
oidc_providers = [
{
client_id = serviceName;
client_secret_path = config.sops.secrets.kanidm-matrix.path;
idp_id = "kanidm";
idp_name = "Kanidm SSO";
issuer = "https://${globals.services.kanidm.domain}/oauth2/openid/${serviceName}";
scopes = [
"openid"
"email"
"profile"
];
user_mapping_provider.config = {
display_name_template = "{{ user.name }}";
email_template = "{{ user.email }}";
localpart_template = "{{ user.preferred_username }}";
subject_claim = "sub";
};
user_profile_method = "userinfo_endpoint";
}
];
public_baseurl = baseUrl;
server_name = serviceDomain;
};
};
mautrix-discord = {
enable = true;
environmentFile = config.sops.templates.mautrixdiscord.path;
settings = {
inherit homeserver;
appservice.database = {
type = "postgres";
uri = mkPostgresUri "mautrix-discord" "$MAUTRIX_DISCORD_DB_PASSWORD";
};
bridge = {
backfill.forward_limits = {
initial = {
channel = 50;
dm = 50;
thread = 50;
};
missed = {
channel = 50;
dm = 50;
thread = 50;
};
};
encryption = {
allow = true;
default = true;
};
login_shared_secret_map.${serviceDomain} = "as_token:$MAUTRIX_DISCORD_DOUBLEPUPPET";
permissions = bridgePermissions;
};
};
};
mautrix-meta.instances.instagram = {
enable = true;
environmentFile = config.sops.templates.mautrixmetainstagram.path;
settings = {
inherit homeserver;
appservice = {
as_token = "$MAUTRIX_META_INSTAGRAM_AS_TOKEN";
hs_token = "$MAUTRIX_META_INSTAGRAM_HS_TOKEN";
};
backfill.enabled = true;
bridge.permissions = bridgePermissions;
database = {
type = "postgres";
uri = mkPostgresUri "mautrix-meta-instagram" "$MAUTRIX_META_INSTAGRAM_DB_PASSWORD";
};
double_puppet.secrets.${serviceDomain} = "$MAUTRIX_META_INSTAGRAM_DOUBLEPUPPET";
encryption.pickle_key = "$MAUTRIX_META_INSTAGRAM_PICKLE_KEY";
};
};
mautrix-signal = {
enable = true;
environmentFile = config.sops.templates.mautrixsignal.path;
registerToSynapse = false;
settings = {
inherit homeserver;
appservice = {
address = "http://localhost:${builtins.toString signalPort}";
hostname = "0.0.0.0";
port = signalPort;
};
bridge.permissions = bridgePermissions;
database = {
type = "postgres";
uri = mkPostgresUri "mautrix-signal" "$MAUTRIX_SIGNAL_DB_PASSWORD";
};
encryption = {
allow = true;
default = true;
pickle_key = "$MAUTRIX_SIGNAL_PICKLE_KEY";
};
network.displayname_template = "{{or .ContactName .ProfileName .PhoneNumber}} (Signal)";
};
};
mautrix-telegram = {
enable = true;
environmentFile = config.sops.templates.mautrixtelegram.path;
registerToSynapse = false;
settings = {
inherit homeserver;
appservice = {
address = "http://localhost:${builtins.toString telegramPort}";
database = mkPostgresUri "mautrix-telegram" "$MAUTRIX_TELEGRAM_DB_PASSWORD";
hostname = "0.0.0.0";
id = "telegram";
port = telegramPort;
provisioning.enabled = true;
# ephemeral_events = true; # not needed due to double puppeting
public.enabled = false;
};
bridge = {
allow_avatar_remove = true;
allow_contact_info = true;
animated_sticker = {
args = {
background = "020202"; # only for gif, transparency not supported
fps = 30; # only for webm
height = 256;
width = 256;
};
target = "gif";
};
encryption = {
allow = true;
default = false;
};
login_shared_secret_map = {
${serviceDomain} = "as_token:$MAUTRIX_TELEGRAM_DOUBLEPUPPET";
};
permissions = {
${adminUser} = "admin";
"*" = "relaybot";
};
relaybot.authless_portals = true;
startup_sync = true;
sync_channel_members = true;
sync_create_limit = 0;
sync_direct_chats = true;
telegram_link_preview = true;
};
};
};
mautrix-whatsapp = {
enable = true;
environmentFile = config.sops.templates.mautrixwhatsapp.path;
registerToSynapse = false;
settings = {
inherit homeserver;
appservice = {
address = "http://localhost:${builtins.toString whatsappPort}";
hostname = "0.0.0.0";
port = whatsappPort;
};
backfill.enabled = true;
bridge.permissions = bridgePermissions;
database = {
type = "postgres";
uri = mkPostgresUri "mautrix-whatsapp" "$MAUTRIX_WHATSAPP_DB_PASSWORD";
};
encryption = {
allow = true;
default = true;
pickle_key = "$MAUTRIX_WHATSAPP_PICKLE_KEY";
};
network = {
displayname_template = "{{or .FullName .PushName .Phone}} (WA)";
extev_polls = true;
history_sync = {
full_sync_config = {
days_limit = 900;
size_mb_limit = 5000;
storage_quota_mb = 5000;
};
max_initial_conversations = -1;
request_full_sync = true;
};
send_presence_on_typing = true;
url_previews = true;
};
};
};
postgresql = {
ensureDatabases = serviceUsers;
ensureUsers = map (name: {
inherit name;
ensureDBOwnership = true;
}) serviceUsers;
initialScript = pkgs.writeText "synapse-init.sql" ''
CREATE DATABASE "matrix-synapse"
TEMPLATE template0
LC_COLLATE = "C"
LC_CTYPE = "C";
'';
};
};
environment = {
persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = map (user: {
inherit user;
inherit (config.users.users.${user}) group;
directory = "/var/lib/${user}";
}) serviceUsers;
};
systemPackages = [ pkgs.matrix-synapse ];
};
systemd = {
services = {
matrix-appservice-irc.serviceConfig.ExecStart = lib.mkForce (
lib.concatStringsSep " " [
(lib.getExe pkgs.matrix-appservice-irc)
"--config ${config.sops.templates."matrix-appservice-irc.yml".path}"
"--file /var/lib/matrix-appservice-irc/registration.yml"
"--port ${builtins.toString ircPort}"
]
);
mautrix-telegram.path = with pkgs; [
lottieconverter # for animated stickers conversion, unfree package
ffmpeg # if converting animated stickers to webm (very slow!)
];
# restart the bridges daily. this is done for the signal bridge mainly which stops carrying
# messages out after a while.
restart-bridges = {
script = ''
systemctl restart mautrix-whatsapp.service mautrix-signal.service mautrix-telegram.service mautrix-meta-instagram.service mautrix-discord.service
'';
serviceConfig.Type = "oneshot";
};
};
timers.restart-bridges = {
timerConfig = {
OnBootSec = "1d";
OnUnitActiveSec = "1d";
Unit = "restart-bridges.service";
};
wantedBy = [ "timers.target" ];
};
};
nodes =
let
genNginx = toAddress: extraConfig: {
upstreams = {
${serviceName}.servers = {
"${toAddress}:${builtins.toString servicePort}" = { };
};
"${serviceName}-irc-media".servers = {
"${toAddress}:${builtins.toString ircMediaPort}" = { };
};
};
virtualHosts = {
"${serviceDomain}" = {
inherit extraConfig;
acmeRoot = null;
forceSSL = true;
listen = [
{
addr = "0.0.0.0";
extraParameters = [
"default_server"
];
port = federationPort;
ssl = true;
}
{
addr = "[::0]";
extraParameters = [
"default_server"
];
port = federationPort;
ssl = true;
}
{
addr = "0.0.0.0";
port = 443;
ssl = true;
}
{
addr = "[::0]";
port = 443;
ssl = true;
}
];
locations = {
"/media/".proxyPass = "http://${serviceName}-irc-media/";
"= /.well-known/matrix/client".extraConfig = mkWellKnown { "m.homeserver".base_url = baseUrl; };
"= /.well-known/matrix/server".extraConfig = mkWellKnown { "m.server" = "${serviceDomain}:443"; };
"~ ^(/_matrix|/_synapse/client)" = {
extraConfig = ''
client_max_body_size 0;
'';
proxyPass = "http://${serviceName}";
};
};
useACMEHost = globals.domains.main;
};
};
};
in
lib.mkMerge [
{
${idmServer} = confLib.mkKanidmOidcSystem {
inherit serviceDomain serviceName;
originUrl = "https://${serviceDomain}/_synapse/client/oidc/callback";
};
}
{ ${webProxy}.services.nginx = genNginx serviceAddress ""; }
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (genNginx homeServiceAddress nginxAccessRules);
}
];
};
};
}
4.4.3.31. Nextcloud
My file server. I aim to decommission this as soon as I can, however, I need a replacement for the Cospend plugin (a shared expense manager).
Social Login (OIDC) setup:
- login as admin > administration settings
- Administration tab: Social login:
- Check-boxes:
| Setting | Value |
|---|---|
| Disable auto create new users | yes |
| Allow users to connect social logins with their account | yes |
| Update user profile every login | yes |
| Automatically create group if they do not exist | yes |
- Custom OpenID Connect:
| Setting | Value |
|---|---|
| Internal name | kanidm |
| Title | kanidm |
| Authorize URL | https://<kanidmdomain>/ui/oauth2 |
| Token URL | https://<kanidmdomain>/oauth2/token |
| Client ID | nextcloud |
| Client secret | <kanidm-secret> |
| Scope | openid email profile |
| Button style | OpenID |
| Default Group | None |
| Group mapping | admin -> admin |
{
flake.modules.nixos.nextcloud =
{
self,
config,
lib,
pkgs,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
name = "nextcloud";
port = 80;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceGroup
serviceName
servicePort
serviceUser
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
notificationMail
webProxy
;
nextcloudVersion = "35";
in
{
imports = [
self.modules.nixos.nginx
];
config = {
swarselsystems.enabledServerModules = [ "nextcloud" ];
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = ''"installed":\s*true'';
hostHeader = serviceDomain;
path = "/status.php";
};
};
sops = {
secrets = {
kanidm-nextcloud = {
group = serviceGroup;
mode = "0440";
owner = serviceUser;
rekey.keyPrefix = confLib.kanidmSecrets;
};
notification-mail-pw.rekey.keyPrefix = notificationMail.keyPrefix;
};
templates."nextcloud-secrets.json".content = builtins.toJSON {
mail_smtppassword = config.sops.placeholder.notification-mail-pw;
};
};
users.persistentIds.nextcloud = confLib.mkIds 990;
services = {
${serviceName} = {
config.dbtype = "sqlite";
enable = true;
package = pkgs."nextcloud${nextcloudVersion}";
configureRedis = true;
datadir = "/var/lib/${serviceName}";
extraApps = {
inherit (pkgs."nextcloud${nextcloudVersion}Packages".apps)
calendar
contacts
cospend
forms
mail
phonetrack
polls
sociallogin
tables
tasks
;
};
extraAppsEnable = true;
home = "/var/lib/${serviceName}";
hostName = serviceDomain;
https = true;
maxUploadSize = "64G";
secretFile = config.sops.templates."nextcloud-secrets.json".path;
settings = {
mail_domain = notificationMail.domain;
mail_from_address = notificationMail.localPart;
mail_smtpauth = true;
mail_smtphost = notificationMail.host;
mail_smtpmode = "smtp";
mail_smtpname = notificationMail.address;
mail_smtpport = 587;
overwriteprotocol = "https";
trusted_proxies = [
globals.networks."${globals.wireguard.wgProxy.netConfigPrefix}-wgProxy".hosts.${webProxy}.ipv4
globals.networks."${globals.wireguard.wgHome.netConfigPrefix}-wgHome".hosts.${homeWebProxy}.ipv4
];
};
};
phpfpm.pools.${serviceName}.phpEnv.SQLITE_TMPDIR = "/tmp";
};
environment.persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [
{
directory = "/var/lib/${serviceName}";
group = serviceGroup;
user = serviceUser;
}
{
directory = "/var/lib/redis-${serviceName}";
group = serviceGroup;
user = serviceUser;
}
];
};
systemd.services =
lib.genAttrs [ "${serviceName}-setup" "${serviceName}-update-db" "${serviceName}-cron" ]
(_: {
environment.SQLITE_TMPDIR = "/tmp";
});
nodes =
let
extraConfigLoc = ''
proxy_request_buffering off;
client_body_timeout 7200s;
proxy_read_timeout 7200s;
proxy_send_timeout 7200s;
send_timeout 7200s;
'';
in
lib.mkMerge [
(lib.optionalAttrs (globals.services ? collabora-online) {
${globals.services.collabora-online.extraConfig.node}.services.collabora-online.aliasGroups = [
{ host = "https://${serviceDomain}"; }
];
})
{
${idmServer} =
lib.recursiveUpdate
(confLib.mkKanidmOidcSystem {
inherit serviceDomain serviceName;
extraGroups = [ "nextcloud.admins" ];
originUrl = "https://${serviceDomain}/apps/sociallogin/custom_oidc/kanidm";
})
{
services.kanidm.provision.systems.oauth2.nextcloud = {
allowInsecureClientDisablePkce = true;
claimMaps.groups = {
joinType = "array";
valuesByGroup."nextcloud.admins" = [ "admin" ];
};
};
};
}
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
extraConfigLoc
serviceAddress
serviceDomain
serviceName
servicePort
;
maxBody = 0;
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit
extraConfigLoc
serviceDomain
serviceName
servicePort
;
extraConfig = nginxAccessRules;
maxBody = 0;
serviceAddress = homeServiceAddress;
}
);
}
];
};
};
}
4.4.3.32. Immich (use db)
My photo service. It does some cool things like face recognition automatically (locally).
{
flake.modules.nixos.immich =
{
self,
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
name = "immich";
port = 3001;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceGroup
serviceName
servicePort
serviceUser
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
notificationMail
webProxy
;
machineLearningUrl = "http://127.0.0.1:3003";
in
{
imports = [
self.modules.nixos.postgresql
];
config = {
swarselsystems = {
enabledServerModules = [ "immich" ];
server.postgresql.rolePasswordFiles.${serviceName} =
config.sops.secrets."${serviceName}-db-password".path;
};
topology.self.services.${serviceName}.info = "https://${serviceDomain}";
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = ''"res":\s*"pong"'';
path = "/api/server/ping";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops = {
secrets = {
"${serviceName}-db-password" = {
owner = config.systemd.services.postgresql.serviceConfig.User;
rekey.generator.script = "alnum";
};
kanidm-immich = {
group = serviceGroup;
mode = "0440";
owner = serviceUser;
rekey.keyPrefix = confLib.kanidmSecrets;
};
notification-mail-pw = {
group = serviceGroup;
mode = "0440";
owner = serviceUser;
rekey.keyPrefix = notificationMail.keyPrefix;
};
};
templates."${serviceName}-db-env".content =
let
inherit (config.services.${serviceName}) database;
in
''
DB_URL=postgresql://${database.user}:${
config.sops.placeholder."${serviceName}-db-password"
}@/${database.name}?host=${database.host}&port=${builtins.toString database.port}
'';
};
users = {
users.${serviceUser}.extraGroups = [
"video"
"render"
"users"
];
persistentIds = {
immich = confLib.mkIds 989;
redis-immich = confLib.mkIds 977;
};
};
services.${serviceName} = {
enable = true;
environment.IMMICH_MACHINE_LEARNING_URL = lib.mkForce machineLearningUrl;
host = "0.0.0.0";
mediaLocation = "/storage/Pictures/${serviceName}"; # dataDir
port = servicePort;
secretsFile = config.sops.templates."${serviceName}-db-env".path;
settings = {
backup.database = {
cronExpression = "0 02 * * *";
enabled = true;
keepLastAmount = 14;
};
ffmpeg = {
accel = "disabled";
accelDecode = false;
acceptedAudioCodecs = [
"aac"
"mp3"
"opus"
];
acceptedContainers = [
"mov"
"ogg"
"webm"
];
acceptedVideoCodecs = [ "h264" ];
bframes = -1;
cqMode = "auto";
crf = 23;
gopSize = 0;
maxBitrate = "0";
preferredHwDevice = "auto";
preset = "ultrafast";
refs = 0;
targetAudioCodec = "aac";
targetResolution = "720";
targetVideoCodec = "h264";
temporalAQ = false;
threads = 0;
tonemap = "hable";
transcode = "optimal";
twoPass = false;
};
image = {
colorspace = "p3";
extractEmbedded = false;
fullsize = {
enabled = false;
format = "jpeg";
progressive = false;
quality = 80;
};
preview = {
format = "jpeg";
progressive = false;
quality = 80;
size = 1440;
};
thumbnail = {
format = "webp";
progressive = false;
quality = 80;
size = 250;
};
};
job = {
backgroundTask.concurrency = 5;
editor.concurrency = 2;
faceDetection.concurrency = 2;
library.concurrency = 5;
metadataExtraction.concurrency = 5;
migration.concurrency = 5;
notifications.concurrency = 5;
ocr.concurrency = 1;
search.concurrency = 5;
sidecar.concurrency = 5;
smartSearch.concurrency = 2;
thumbnailGeneration.concurrency = 3;
videoConversion.concurrency = 1;
workflow.concurrency = 5;
};
library = {
scan = {
cronExpression = "0 0 * * *";
enabled = true;
};
watch.enabled = false;
};
logging.enabled = true;
machineLearning = {
availabilityChecks = {
enabled = true;
interval = 30000;
timeout = 2000;
};
clip = {
enabled = true;
modelName = "ViT-B-32__openai";
};
duplicateDetection = {
enabled = true;
maxDistance = 0.01;
};
enabled = true;
facialRecognition = {
enabled = true;
maxDistance = 0.5;
minFaces = 3;
minScore = 0.7;
modelName = "buffalo_l";
};
ocr = {
enabled = true;
maxResolution = 736;
minDetectionScore = 0.5;
minRecognitionScore = 0.8;
modelName = "PP-OCRv5_mobile";
};
urls = [ machineLearningUrl ];
};
map = {
darkStyle = "https://tiles.immich.cloud/v1/style/dark.json";
enabled = true;
lightStyle = "https://tiles.immich.cloud/v1/style/light.json";
};
metadata.faces.import = false;
nightlyTasks = {
clusterNewFaces = true;
databaseCleanup = true;
generateMemories = true;
missingThumbnails = true;
startTime = "00:00";
syncQuotaUsage = true;
};
notifications.smtp = {
enabled = true;
from = "Immich <${notificationMail.address}>";
replyTo = notificationMail.address;
transport = {
inherit (notificationMail) host;
ignoreCert = false;
password._secret = config.sops.secrets.notification-mail-pw.path;
port = 587;
secure = false;
username = notificationMail.address;
};
};
oauth = {
autoLaunch = false;
autoRegister = true;
buttonText = "Login with Kanidm";
clientId = serviceName;
clientSecret._secret = config.sops.secrets.kanidm-immich.path;
defaultStorageQuota = null;
enabled = true;
issuerUrl = "https://${globals.services.kanidm.domain}/oauth2/openid/${serviceName}";
mobileOverrideEnabled = true;
mobileRedirectUri = "https://${serviceDomain}/api/oauth/mobile-redirect";
profileSigningAlgorithm = "none";
roleClaim = "immich_role";
scope = "openid email profile";
signingAlgorithm = "RS256";
storageLabelClaim = "preferred_username";
storageQuotaClaim = "0";
timeout = 30000;
tokenEndpointAuthMethod = "client_secret_post";
};
passwordLogin.enabled = true;
reverseGeocoding.enabled = true;
trash = {
days = 30;
enabled = true;
};
user.deleteDelay = 7;
};
};
environment.persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [
{
directory = "/var/lib/${serviceName}";
group = serviceGroup;
user = serviceUser;
}
{
directory = "/var/cache/${serviceName}";
group = serviceGroup;
user = serviceUser;
}
{
directory = "/var/lib/redis-${serviceName}";
group = "redis-${serviceGroup}";
user = "redis-${serviceUser}";
}
];
};
nodes =
let
extraConfigLoc = ''
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_redirect off;
proxy_request_buffering off;
client_body_timeout 7200s;
proxy_read_timeout 7200s;
proxy_send_timeout 7200s;
send_timeout 7200s;
'';
in
lib.mkMerge [
{
${idmServer} =
lib.recursiveUpdate
(confLib.mkKanidmOidcSystem {
inherit serviceDomain serviceName;
originUrl = [
"https://${serviceDomain}/auth/login"
"https://${serviceDomain}/user-settings"
"app.immich:///oauth-callback"
"https://${serviceDomain}/api/oauth/mobile-redirect"
];
})
{
services.kanidm.provision.systems.oauth2.immich.enableLegacyCrypto = true;
};
}
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
extraConfigLoc
serviceAddress
serviceDomain
serviceName
servicePort
;
maxBody = 0;
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit
extraConfigLoc
serviceDomain
serviceName
servicePort
;
extraConfig = nginxAccessRules;
maxBody = 0;
serviceAddress = homeServiceAddress;
}
);
}
];
};
};
}
4.4.3.33. paperless (Tika, Gotenberg)
This is my personal document management system. It automatically pulls documents from several sources, the only manual step for physical documents is to put them in my scanner and use email delivery.
Also I install Tika and Gotenberg, which are needed to create PDFs out of .eml's. This is needed for e.g. online services that only send their invoices through email body text.
{
flake.modules.nixos.paperless =
{
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
name = "paperless";
port = 28981;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceGroup
serviceName
servicePort
serviceUser
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
notificationMail
webProxy
;
tikaPort = 9998;
gotenbergPort = 3002;
treehouseLocation = globals.roaming.treehouse.location;
in
{
config = {
swarselsystems.enabledServerModules = [ "paperless" ];
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
extra.extraConfig = {
node = config.node.name;
port = servicePort;
};
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = "Paperless";
hostHeader = serviceDomain;
path = "/accounts/login/";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops = {
secrets = {
kanidm-paperless.rekey.keyPrefix = confLib.kanidmSecrets;
notification-mail-pw.rekey.keyPrefix = notificationMail.keyPrefix;
paperless-admin-pw.owner = serviceUser;
paperless-ai-api-key = { };
};
templates = {
"paperless-mail.env" = {
content = ''
PAPERLESS_EMAIL_HOST_PASSWORD=${config.sops.placeholder.notification-mail-pw}
''
+ lib.optionalString (treehouseLocation == "work") ''
PAPERLESS_AI_LLM_API_KEY=${config.sops.placeholder.paperless-ai-api-key}
'';
owner = serviceUser;
};
"paperless-oidc.env".content = ''
PAPERLESS_SOCIALACCOUNT_PROVIDERS='${
builtins.toJSON {
openid_connect = {
APPS = [
rec {
client_id = "paperless";
name = "Kanidm";
provider_id = "kanidm";
secret = config.sops.placeholder.kanidm-paperless;
settings.server_url = "https://${globals.services.kanidm.domain}/oauth2/openid/${client_id}/.well-known/openid-configuration";
}
];
OAUTH_PKCE_ENABLED = "True";
};
}
}'
'';
};
};
users = {
users.${serviceUser}.extraGroups = [ "users" ];
persistentIds.redis-paperless = confLib.mkIds 975;
};
services = {
${serviceName} = {
enable = true;
address = "0.0.0.0";
dataDir = "/var/lib/${serviceName}";
environmentFile = config.sops.templates."paperless-mail.env".path;
mediaDir = "/storage/Documents/${serviceName}";
passwordFile = config.sops.secrets.paperless-admin-pw.path;
port = servicePort;
settings = {
PAPERLESS_APPS = "allauth.socialaccount.providers.openid_connect";
PAPERLESS_EMAIL_FROM = notificationMail.address;
PAPERLESS_EMAIL_HOST = notificationMail.host;
PAPERLESS_EMAIL_HOST_USER = notificationMail.address;
PAPERLESS_EMAIL_PORT = 587;
PAPERLESS_EMAIL_USE_TLS = true;
PAPERLESS_OCR_LANGUAGE = "deu+eng";
PAPERLESS_OCR_USER_ARGS = builtins.toJSON {
invalidate_digital_signatures = true;
optimize = 1;
pdfa_image_compression = "lossless";
};
PAPERLESS_TASK_WORKERS = 2;
PAPERLESS_TIKA_ENABLED = "true";
PAPERLESS_TIKA_ENDPOINT = "http://localhost:${builtins.toString tikaPort}";
PAPERLESS_TIKA_GOTENBERG_ENDPOINT = "http://localhost:${builtins.toString gotenbergPort}";
PAPERLESS_URL = "https://${serviceDomain}";
domain = serviceDomain;
}
// config.repo.secrets.local.paperless.ai.${treehouseLocation};
user = serviceUser;
};
gotenberg = {
enable = true;
bindIP = "127.0.0.1";
port = gotenbergPort;
timeout = "600s";
};
tika = {
enable = true;
enableOcr = true;
listenAddress = "127.0.0.1";
openFirewall = false;
port = tikaPort;
};
};
environment.persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [
{
directory = "/var/lib/${serviceName}";
group = serviceGroup;
user = serviceUser;
}
{
directory = "/var/lib/redis-${serviceName}";
group = "redis-${serviceGroup}";
user = "redis-${serviceUser}";
}
{ directory = "/var/lib/private/tika"; }
{
directory = "/var/cache/${serviceName}";
group = serviceGroup;
user = serviceUser;
}
{ directory = "/var/cache/private/tika"; }
];
};
systemd.services = {
paperless-scheduler.serviceConfig.TimeoutStartSec = "30min";
paperless-web.serviceConfig.EnvironmentFile = [
config.sops.templates."paperless-oidc.env".path
];
};
nodes =
let
extraConfigLoc = ''
proxy_connect_timeout 300;
proxy_send_timeout 300;
proxy_read_timeout 300;
send_timeout 300;
'';
in
lib.mkMerge [
{
${idmServer} = confLib.mkKanidmOidcSystem {
inherit serviceDomain serviceName;
originUrl = "https://${serviceDomain}/accounts/oidc/kanidm/login/callback/";
};
}
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
extraConfigLoc
serviceAddress
serviceDomain
serviceName
servicePort
;
maxBody = 0;
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit
extraConfigLoc
serviceDomain
serviceName
servicePort
;
extraConfig = nginxAccessRules;
maxBody = 0;
serviceAddress = homeServiceAddress;
}
);
}
];
};
};
}
4.4.3.34. transmission
I use this configuration for sailing.
{
flake.modules.nixos.transmission =
{
self,
root,
config,
lib,
pkgs,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
name = "transmission";
port = 9091;
})
serviceDomain
servicePort
;
inherit (confLib.static)
homeProxyIf
homeServiceAddress
homeWebProxy
isHome
nginxAccessRules
;
piaNamespace = "pia";
piaPortFile = "/run/pia/forwarded-port";
piaTunnel = config.services.pia-netns.tunnels.${piaNamespace};
arrPorts = {
bazarr = 6767;
lidarr = 8686;
prowlarr = 9696;
radarr = 7878;
readarr = 8787;
sonarr = 8989;
};
libraryApps = [
"lidarr"
"radarr"
"readarr"
"sonarr"
];
in
{
imports = [
self.modules.nixos.pia-netns
];
config = {
swarselsystems.enabledServerModules = [ "transmission" ];
topology.self.services =
lib.recursiveUpdate
(lib.mapAttrs (name: _: { info = "https://${serviceDomain}/${name}"; }) arrPorts)
{
bazarr = {
icon = root "files/topology-images/bazarr.png";
name = "Bazarr";
};
readarr = {
icon = root "files/topology-images/readarr.png";
name = "Readarr";
};
};
globals = {
services.transmission = {
inherit isHome;
domain = serviceDomain;
webPaths = lib.mapAttrs (name: _: "/${name}") arrPorts // {
transmission = "/transmission/web/";
};
};
monitoring = {
http = lib.mkMerge (
lib.mapAttrsToList (
serviceName: servicePort:
confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = "OK";
path = if serviceName == "bazarr" then "/bazarr/api/system/ping" else "/${serviceName}/ping";
}
) arrPorts
);
systemd = lib.mkMerge [
(confLib.mkSystemdMonitoring {
oneshot = true;
serviceName = "mam-dynamic-seedbox";
unit = "mam-dynamic-seedbox.service";
})
(confLib.mkSystemdMonitoring {
serviceName = "transmission";
unit = "transmission.service";
})
];
};
networks = lib.mkMerge [
(confLib.mkDualFirewallRules {
forWebProxy = false;
tcpPorts = [ servicePort ] ++ lib.attrValues arrPorts;
})
(lib.optionalAttrs (globals.services ? seerr) {
${homeProxyIf}.hosts.${config.node.name}.firewallRuleForNode.${globals.services.seerr.extraConfig.node}.allowedTCPPorts =
[
arrPorts.radarr
arrPorts.sonarr
];
})
];
};
sops = {
secrets = {
mam-id = { };
pia = { };
transmission-rpc-password = { };
};
templates."transmission-credentials.json" = {
content = ''
{"rpc-username":"${config.swarselsystems.mainUser}","rpc-password":"${config.sops.placeholder.transmission-rpc-password}"}
'';
mode = "0400";
};
};
users = {
users =
lib.mapAttrs (name: _: {
extraGroups = [ "users" ];
group = name;
isSystemUser = true;
}) arrPorts
// {
transmission.extraGroups = [ "users" ];
};
groups = lib.mapAttrs (_: _: { }) arrPorts;
persistentIds = {
bazarr = confLib.mkIds 932;
prowlarr = confLib.mkIds 971;
readarr = confLib.mkIds 970;
};
};
services =
lib.genAttrs libraryApps (name: {
enable = true;
dataDir = "/var/lib/${name}";
group = name;
openFirewall = true;
settings.server.port = arrPorts.${name};
user = name;
})
// {
bazarr = {
enable = true;
group = "bazarr";
openFirewall = true;
settings.general = {
base_url = "/bazarr";
ip = "0.0.0.0";
port = arrPorts.bazarr;
};
user = "bazarr";
};
pia-netns.tunnels.${piaNamespace} = {
credentialsFile = config.sops.secrets.pia.path;
forwards.transmission-rpc-forward = {
port = servicePort;
service = "transmission.service";
};
portForwarding = {
enable = true;
portFile = piaPortFile;
};
region = "sweden";
};
prowlarr = {
enable = true;
openFirewall = true;
settings.server.port = arrPorts.prowlarr;
};
transmission = {
enable = true;
package = pkgs.transmission_3;
credentialsFile = config.sops.templates."transmission-credentials.json".path;
group = "users";
openPeerPorts = false;
openRPCPort = false;
settings = {
alt-speed-down = 12000;
alt-speed-time-begin = 120;
alt-speed-time-enabled = true;
alt-speed-time-end = 480;
alt-speed-up = 4000;
cache-size-mb = 1024;
dht-enabled = false;
download-dir = "/storage/CHANGEME/seed";
encryption = 2;
peer-port-random-on-start = false;
pex-enabled = false;
port-forwarding-enabled = false;
rpc-authentication-required = true;
rpc-bind-address = "127.0.0.1";
rpc-host-whitelist-enabled = false;
rpc-port = servicePort;
rpc-whitelist-enabled = false;
speed-limit-down = 6000;
speed-limit-down-enabled = true;
speed-limit-up = 2000;
speed-limit-up-enabled = true;
umask = 7;
};
};
};
environment.persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories =
map (name: {
directory = "/var/lib/${name}";
group = name;
user = name;
}) libraryApps
++ [
{
directory = "/var/lib/bazarr";
group = "bazarr";
mode = "0700";
user = "bazarr";
}
{
directory = "/var/lib/private/prowlarr";
group = "prowlarr";
user = "prowlarr";
}
{
directory = "/var/lib/mam";
group = "root";
mode = "0700";
user = "root";
}
{
directory = "/var/lib/transmission";
group = "users";
user = "transmission";
}
];
};
systemd = {
services = {
mam-dynamic-seedbox = {
after = [ piaTunnel.unit ];
partOf = [ piaTunnel.unit ];
path = with pkgs; [
curl
iproute2
];
requires = [ piaTunnel.unit ];
script = ''
install -d -m 0700 /var/lib/mam
mam() {
ip netns exec ${piaNamespace} curl -sS --max-time 30 -c /var/lib/mam/cookies.txt -b "$1" "${config.repo.secrets.local.mamUrl}"
}
ok() {
grep -Eq '"Success":\s*true|Last change too recent' <<< "$1"
}
if [ -s /var/lib/mam/cookies.txt ] && ok "$(mam /var/lib/mam/cookies.txt)"; then
exit 0
fi
resp=$(mam "mam_id=$(cat ${config.sops.secrets.mam-id.path})")
ok "$resp" || { echo "$resp" >&2; exit 1; }
'';
serviceConfig = {
Restart = "on-failure";
RestartSec = "5min";
Type = "oneshot";
};
wantedBy = [ piaTunnel.unit ];
};
transmission = {
after = [ piaTunnel.unit ];
bindsTo = [ piaTunnel.unit ];
partOf = [ piaTunnel.unit ];
requires = [ piaTunnel.unit ];
serviceConfig = {
BindPaths = [
"/storage/Music"
"/storage/Videos"
"/storage/Books"
"/storage/Software"
];
BindReadOnlyPaths = [ "/etc/netns/${piaNamespace}/resolv.conf:/etc/resolv.conf" ];
NetworkNamespacePath = piaTunnel.netnsPath;
TimeoutStartSec = "3600s";
};
};
transmission-peer-port = {
after = [
"transmission.service"
"transmission-rpc-forward.service"
];
description = "Apply PIA-forwarded port to transmission";
path = [ pkgs.transmission_3 ];
script = ''
if [ -s ${piaPortFile} ]; then
transmission-remote 127.0.0.1:${toString servicePort} \
-n "${config.swarselsystems.mainUser}:$(cat ${config.sops.secrets.transmission-rpc-password.path})" \
-p "$(cat ${piaPortFile})"
fi
'';
serviceConfig = {
Restart = "on-failure";
RestartSec = "10s";
Type = "oneshot";
};
wantedBy = [ "transmission.service" ];
wants = [ "transmission-rpc-forward.service" ];
};
};
paths.transmission-peer-port = {
description = "Watch PIA forwarded-port file";
pathConfig = {
PathChanged = piaPortFile;
Unit = "transmission-peer-port.service";
};
wantedBy = [ "multi-user.target" ];
};
timers.mam-dynamic-seedbox = {
timerConfig = {
OnBootSec = "10min";
OnUnitActiveSec = "65min";
Unit = "mam-dynamic-seedbox.service";
};
wantedBy = [ "timers.target" ];
};
tmpfiles.rules = [
"d /storage/CHANGEME 0755 transmission users -"
"d /storage/CHANGEME/seed 0755 transmission users -"
];
};
nodes.${homeWebProxy}.services.nginx = lib.mkIf isHome (
let
unlimitedBodyLocation = upstream: {
extraConfig = ''
client_max_body_size 0;
'';
proxyPass = "http://${upstream}";
};
in
{
upstreams = lib.mapAttrs (_: port: {
servers."${homeServiceAddress}:${builtins.toString port}" = { };
}) (arrPorts // { transmission = servicePort; });
virtualHosts.${serviceDomain} = {
acmeRoot = null;
extraConfig = nginxAccessRules;
forceSSL = true;
locations =
lib.mapAttrs' (name: _: lib.nameValuePair "/${name}" (unlimitedBodyLocation name)) (
lib.removeAttrs arrPorts [ "bazarr" ]
)
// {
"/" = unlimitedBodyLocation "transmission";
"/bazarr" = {
proxyPass = "http://bazarr";
proxyWebsockets = true;
};
};
useACMEHost = globals.domains.main;
};
}
);
};
};
}
4.4.3.35. pia-netns
{
flake.modules.nixos.pia-netns =
{
config,
lib,
pkgs,
utils,
...
}:
let
cfg = config.services.pia-netns;
piaCaCert = pkgs.writeText "pia-ca.rsa.4096.crt" ''
-----BEGIN CERTIFICATE-----
MIIHqzCCBZOgAwIBAgIJAJ0u+vODZJntMA0GCSqGSIb3DQEBDQUAMIHoMQswCQYD
VQQGEwJVUzELMAkGA1UECBMCQ0ExEzARBgNVBAcTCkxvc0FuZ2VsZXMxIDAeBgNV
BAoTF1ByaXZhdGUgSW50ZXJuZXQgQWNjZXNzMSAwHgYDVQQLExdQcml2YXRlIElu
dGVybmV0IEFjY2VzczEgMB4GA1UEAxMXUHJpdmF0ZSBJbnRlcm5ldCBBY2Nlc3Mx
IDAeBgNVBCkTF1ByaXZhdGUgSW50ZXJuZXQgQWNjZXNzMS8wLQYJKoZIhvcNAQkB
FiBzZWN1cmVAcHJpdmF0ZWludGVybmV0YWNjZXNzLmNvbTAeFw0xNDA0MTcxNzQw
MzNaFw0zNDA0MTIxNzQwMzNaMIHoMQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0Ex
EzARBgNVBAcTCkxvc0FuZ2VsZXMxIDAeBgNVBAoTF1ByaXZhdGUgSW50ZXJuZXQg
QWNjZXNzMSAwHgYDVQQLExdQcml2YXRlIEludGVybmV0IEFjY2VzczEgMB4GA1UE
AxMXUHJpdmF0ZSBJbnRlcm5ldCBBY2Nlc3MxIDAeBgNVBCkTF1ByaXZhdGUgSW50
ZXJuZXQgQWNjZXNzMS8wLQYJKoZIhvcNAQkBFiBzZWN1cmVAcHJpdmF0ZWludGVy
bmV0YWNjZXNzLmNvbTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBALVk
hjumaqBbL8aSgj6xbX1QPTfTd1qHsAZd2B97m8Vw31c/2yQgZNf5qZY0+jOIHULN
De4R9TIvyBEbvnAg/OkPw8n/+ScgYOeH876VUXzjLDBnDb8DLr/+w9oVsuDeFJ9K
V2UFM1OYX0SnkHnrYAN2QLF98ESK4NCSU01h5zkcgmQ+qKSfA9Ny0/UpsKPBFqsQ
25NvjDWFhCpeqCHKUJ4Be27CDbSl7lAkBuHMPHJs8f8xPgAbHRXZOxVCpayZ2SND
fCwsnGWpWFoMGvdMbygngCn6jA/W1VSFOlRlfLuuGe7QFfDwA0jaLCxuWt/BgZyl
p7tAzYKR8lnWmtUCPm4+BtjyVDYtDCiGBD9Z4P13RFWvJHw5aapx/5W/CuvVyI7p
Kwvc2IT+KPxCUhH1XI8ca5RN3C9NoPJJf6qpg4g0rJH3aaWkoMRrYvQ+5PXXYUzj
tRHImghRGd/ydERYoAZXuGSbPkm9Y/p2X8unLcW+F0xpJD98+ZI+tzSsI99Zs5wi
jSUGYr9/j18KHFTMQ8n+1jauc5bCCegN27dPeKXNSZ5riXFL2XX6BkY68y58UaNz
meGMiUL9BOV1iV+PMb7B7PYs7oFLjAhh0EdyvfHkrh/ZV9BEhtFa7yXp8XR0J6vz
1YV9R6DYJmLjOEbhU8N0gc3tZm4Qz39lIIG6w3FDAgMBAAGjggFUMIIBUDAdBgNV
HQ4EFgQUrsRtyWJftjpdRM0+925Y6Cl08SUwggEfBgNVHSMEggEWMIIBEoAUrsRt
yWJftjpdRM0+925Y6Cl08SWhge6kgeswgegxCzAJBgNVBAYTAlVTMQswCQYDVQQI
EwJDQTETMBEGA1UEBxMKTG9zQW5nZWxlczEgMB4GA1UEChMXUHJpdmF0ZSBJbnRl
cm5ldCBBY2Nlc3MxIDAeBgNVBAsTF1ByaXZhdGUgSW50ZXJuZXQgQWNjZXNzMSAw
HgYDVQQDExdQcml2YXRlIEludGVybmV0IEFjY2VzczEgMB4GA1UEKRMXUHJpdmF0
ZSBJbnRlcm5ldCBBY2Nlc3MxLzAtBgkqhkiG9w0BCQEWIHNlY3VyZUBwcml2YXRl
aW50ZXJuZXRhY2Nlc3MuY29tggkAnS7684Nkme0wDAYDVR0TBAUwAwEB/zANBgkq
hkiG9w0BAQ0FAAOCAgEAJsfhsPk3r8kLXLxY+v+vHzbr4ufNtqnL9/1Uuf8NrsCt
pXAoyZ0YqfbkWx3NHTZ7OE9ZRhdMP/RqHQE1p4N4Sa1nZKhTKasV6KhHDqSCt/dv
Em89xWm2MVA7nyzQxVlHa9AkcBaemcXEiyT19XdpiXOP4Vhs+J1R5m8zQOxZlV1G
tF9vsXmJqWZpOVPmZ8f35BCsYPvv4yMewnrtAC8PFEK/bOPeYcKN50bol22QYaZu
LfpkHfNiFTnfMh8sl/ablPyNY7DUNiP5DRcMdIwmfGQxR5WEQoHL3yPJ42LkB5zs
6jIm26DGNXfwura/mi105+ENH1CaROtRYwkiHb08U6qLXXJz80mWJkT90nr8Asj3
5xN2cUppg74nG3YVav/38P48T56hG1NHbYF5uOCske19F6wi9maUoto/3vEr0rnX
JUp2KODmKdvBI7co245lHBABWikk8VfejQSlCtDBXn644ZMtAdoxKNfR2WTFVEwJ
iyd1Fzx0yujuiXDROLhISLQDRjVVAvawrAtLZWYK31bY7KlezPlQnl/D9Asxe85l
8jO5+0LdJ6VyOs/Hd4w52alDW/MFySDZSfQHMTIc30hLBJ8OnCEIvluVQQ2UQvoW
+no177N9L2Y+M9TcTA62ZyMXShHQGeh20rb4kK8f+iFX8NxtdHVSkxMEFSfDDyQ=
-----END CERTIFICATE-----
'';
mkForward =
namespace: forward:
let
socat = [
(lib.getExe pkgs.socat)
]
++ lib.optional (forward.idleTimeout != null) "-T${toString forward.idleTimeout}";
in
{
after = [ forward.service ];
bindsTo = [ forward.service ];
description = "Forward port ${toString forward.port} into the ${namespace} netns";
partOf = [ forward.service ];
serviceConfig = {
ExecStart = utils.escapeSystemdExecArgs (
socat
++ [
"TCP-LISTEN:${toString forward.port},${
lib.optionalString (forward.listenAddress != null) "bind=${forward.listenAddress},"
}reuseaddr,fork"
"EXEC:${lib.getExe' pkgs.iproute2 "ip"} netns exec ${namespace} ${toString socat} - TCP\\:127.0.0.1\\:${toString forward.targetPort}"
]
);
Restart = "on-failure";
RestartSec = "5s";
SuccessExitStatus = "143";
Type = "simple";
};
wantedBy = [
"multi-user.target"
forward.service
];
};
in
{
options.services.pia-netns.tunnels = lib.mkOption {
default = { };
description = "PIA WireGuard tunnels, each inside its own network namespace.";
type = lib.types.attrsOf (
lib.types.submodule (
{ name, ... }:
{
options = {
credentialsFile = lib.mkOption {
description = "File with PIA username on line 1 and password on line 2.";
type = lib.types.path;
};
forwards = lib.mkOption {
default = { };
description = "TCP forwarders from the host into the namespace, keyed by unit name.";
type = lib.types.attrsOf (
lib.types.submodule (
{ config, ... }:
{
options = {
idleTimeout = lib.mkOption {
default = null;
type = lib.types.nullOr lib.types.int;
};
listenAddress = lib.mkOption {
default = null;
type = lib.types.nullOr lib.types.str;
};
port = lib.mkOption {
type = lib.types.port;
};
service = lib.mkOption {
description = "Unit inside the namespace that the forwarder is bound to.";
type = lib.types.str;
};
targetPort = lib.mkOption {
default = config.port;
type = lib.types.port;
};
};
}
)
);
};
netnsPath = lib.mkOption {
default = "/var/run/netns/${name}";
readOnly = true;
type = lib.types.str;
};
portForwarding = {
enable = lib.mkEnableOption "PIA port forwarding with keepalive";
portFile = lib.mkOption {
default = "/run/pia/${name}/forwarded-port";
type = lib.types.path;
};
};
region = lib.mkOption {
example = "sweden";
type = lib.types.str;
};
unit = lib.mkOption {
default = "pia-netns-${name}.service";
readOnly = true;
type = lib.types.str;
};
};
}
)
);
};
config = lib.mkIf (cfg.tunnels != { }) {
boot.kernelModules = [ "wireguard" ];
systemd.services =
lib.mapAttrs' (
name: tunnel:
lib.nameValuePair "pia-netns-${name}" {
after = [ "network-online.target" ];
description = "PIA WireGuard tunnel in network namespace ${name}";
serviceConfig = {
ExecStart = lib.getExe (
pkgs.writeShellApplication {
name = "pia-netns-${name}-up";
runtimeInputs = with pkgs; [
coreutils
curl
iproute2
jq
systemd
wireguard-tools
];
text = ''
ok() {
jq -e '.status == "OK"' <<< "$1" > /dev/null || { echo "$1" >&2; exit 1; }
}
user=$(head -n1 ${tunnel.credentialsFile})
pass=$(tail -n1 ${tunnel.credentialsFile})
token=$(curl -sS --max-time 30 --location \
--header "Content-Type: application/json" \
--data "{\"username\":\"$user\",\"password\":\"$pass\"}" \
https://www.privateinternetaccess.com/api/client/v2/token | jq -er .token)
server=$(curl -sS --max-time 30 https://serverlist.piaservers.net/vpninfo/servers/v6 \
| head -n1 | jq -ec '.regions[] | select(.id == "${tunnel.region}") | .servers.wg[0]')
ip=$(jq -r .ip <<< "$server")
host=$(jq -r .cn <<< "$server")
api=(curl -sS --connect-timeout 5 --max-time 30 --cacert ${piaCaCert} --connect-to "$host::$ip:" -G)
private_key=$(wg genkey)
peer=$("''${api[@]}" \
--data-urlencode "pt=$token" \
--data-urlencode "pubkey=$(wg pubkey <<< "$private_key")" \
"https://$host:1337/addKey")
ok "$peer"
ip netns add ${name}
ip -n ${name} link set lo up
install -d /etc/netns/${name}
jq -r '"nameserver \(.dns_servers[0])"' <<< "$peer" > /etc/netns/${name}/resolv.conf
ip link add wg-${name} type wireguard
wg set wg-${name} private-key <(echo "$private_key") \
peer "$(jq -r .server_key <<< "$peer")" \
endpoint "$ip:$(jq -r .server_port <<< "$peer")" \
allowed-ips 0.0.0.0/0,::/0 \
persistent-keepalive 25
ip link set wg-${name} netns ${name}
ip -n ${name} addr add "$(jq -r .peer_ip <<< "$peer")" dev wg-${name}
ip -n ${name} link set wg-${name} mtu 1420 up
ip -n ${name} route add default dev wg-${name}
''
+ (
if tunnel.portForwarding.enable then
''
signature=$(ip netns exec ${name} "''${api[@]}" --retry 5 --retry-all-errors \
--data-urlencode "token=$token" \
"https://$host:19999/getSignature")
ok "$signature"
install -d ${dirOf tunnel.portForwarding.portFile}
jq -r .payload <<< "$signature" | base64 -d | jq -j .port > ${tunnel.portForwarding.portFile}
while true; do
ok "$(ip netns exec ${name} "''${api[@]}" \
--data-urlencode "payload=$(jq -r .payload <<< "$signature")" \
--data-urlencode "signature=$(jq -r .signature <<< "$signature")" \
"https://$host:19999/bindPort")"
systemd-notify --ready --status="port $(cat ${tunnel.portForwarding.portFile}) forwarded"
sleep 880
done
''
else
''
systemd-notify --ready
while sleep 60; do
handshake=$(ip netns exec ${name} wg show wg-${name} latest-handshakes | cut -f2)
if (( handshake > 0 && $(date +%s) - handshake > 300 )); then
echo "handshake older than 300s" >&2
exit 1
fi
done
''
);
}
);
ExecStopPost = [
"-${pkgs.iproute2}/bin/ip netns del ${name}"
"-${pkgs.iproute2}/bin/ip link del wg-${name}"
"${pkgs.coreutils}/bin/rm -rf /etc/netns/${name} ${tunnel.portForwarding.portFile}"
];
NotifyAccess = "exec";
Restart = "on-failure";
RestartSec = "30s";
TimeoutStartSec = "120s";
Type = "notify";
};
wantedBy = [ "multi-user.target" ];
wants = [ "network-online.target" ];
}
) cfg.tunnels
// lib.concatMapAttrs (name: tunnel: lib.mapAttrs (_: mkForward name) tunnel.forwards) cfg.tunnels;
};
};
}
4.4.3.36. syncthing
This is the server syncthings config, which makes sure that the servers never override client data. They also store more folders that the clients.
{
flake.modules.nixos.server-syncthing =
{
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
name = "syncthing";
port = 8384;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceGroup
serviceName
servicePort
serviceUser
;
inherit (confLib.static)
homeProxyIf
homeServiceAddress
homeWebProxy
isHome
isProxied
nginxAccessRules
webProxy
webProxyIf
;
specificServiceName = "${serviceName}-${config.node.name}";
serviceDomain = globals.services.${specificServiceName}.domain;
inherit (globals.services.${specificServiceName}) extraConfig;
cfg = config.services.${serviceName};
baseDevices = config.repo.secrets.common.syncthing.devices;
syncDevices = builtins.attrNames baseDevices ++ (extraConfig.extraSyncDevices or [ ]);
syncPort = 22000;
proxyFirewallRule = {
allowedTCPPorts = [
servicePort
syncPort
];
allowedUDPPorts = [
syncPort
21027
];
};
in
{
config = {
swarselsystems.enabledServerModules = [ "syncthing" ];
globals = {
services.${specificServiceName} = {
inherit
isHome
proxyAddress4
proxyAddress6
serviceAddress
;
domain = lib.mkDefault config.repo.secrets.common.services.domains.${specificServiceName};
extraConfig.devices = baseDevices;
homeServiceAddress = lib.mkIf isHome homeServiceAddress;
};
dns = confLib.mkDnsRecord {
inherit proxyAddress4 proxyAddress6;
serviceName = specificServiceName;
};
monitoring.http = confLib.mkHttpMonitoring {
inherit servicePort;
expectedBodyRegex = ''"status":\s*"OK"'';
path = "/rest/noauth/health";
serviceName = specificServiceName;
};
networks = {
${homeProxyIf}.hosts = lib.mkIf isHome {
${config.node.name}.firewallRuleForNode.${homeWebProxy} = proxyFirewallRule;
};
${webProxyIf}.hosts = lib.mkIf isProxied {
${config.node.name}.firewallRuleForNode.${webProxy} = proxyFirewallRule;
};
};
};
users = {
users.${serviceUser} = {
extraGroups = [ "users" ];
group = serviceGroup;
isSystemUser = true;
};
groups.${serviceGroup} = { };
};
services.${serviceName} = {
enable = true;
configDir =
if config.swarselsystems.isMicroVM then
"/var/lib/syncthing/.config/syncthing"
else
"${cfg.dataDir}/.config/${serviceName}";
dataDir =
if extraConfig ? dataDir then
lib.mkForce extraConfig.dataDir
else if config.swarselsystems.isMicroVM then
"/storage/Documents/syncthing"
else
lib.mkDefault "/var/lib/${serviceName}";
group = serviceGroup;
guiAddress = "0.0.0.0:${builtins.toString servicePort}";
openDefaultPorts = lib.mkIf (!isProxied) true; # opens ports TCP/UDP 22000 and UDP 21027 for discovery
relay.enable = false;
settings = {
options.urAccepted = -1;
devices = baseDevices // (extraConfig.extraDevices or { });
folders = {
"Default Folder" = lib.mkForce {
devices = syncDevices;
id = "default";
path = "${cfg.dataDir}/Sync";
type = "receiveonly";
};
}
//
lib.mapAttrs
(name: id: {
inherit id;
devices = syncDevices;
path = "${cfg.dataDir}/${name}";
type = "receiveonly";
versioning = {
params.keep = "5";
type = "simple";
};
})
{
Obsidian = "yjvni-9eaa7";
Org = "a7xnl-zjj3d";
Vpn = "hgp9s-fyq3p";
}
// (extraConfig.extraFolders or { });
};
user = serviceUser;
};
environment.persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [
{
directory = "/var/lib/${serviceName}";
group = serviceGroup;
user = serviceUser;
}
];
};
nodes = lib.mkMerge [
{
${webProxy}.services.nginx = confLib.genNginx {
inherit serviceAddress serviceDomain servicePort;
maxBody = 0;
serviceName = specificServiceName;
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit serviceDomain servicePort;
extraConfig = nginxAccessRules;
maxBody = 0;
serviceAddress = homeServiceAddress;
serviceName = specificServiceName;
}
);
}
];
};
};
}
4.4.3.37. restic backups
This manages backups for my pictures and obsidian files.
Note: you still need to run restic-<name> init once on the host to get the bucket running.
{
flake.modules.nixos.restic =
{
config,
lib,
pkgs,
confLib,
globals,
...
}:
let
inherit (config.swarselsystems.server.restic) targets;
metricsDir = "/var/lib/restic-metrics";
in
{
options.swarselsystems.server.restic.targets = lib.mkOption {
default = { };
type = lib.types.attrsOf (
lib.types.submodule (
{ name, ... }: {
options = {
bucketName = lib.mkOption {
default = name;
type = lib.types.str;
};
paths = lib.mkOption {
type = lib.types.listOf lib.types.str;
};
postgresDatabases = lib.mkOption {
default = [ ];
type = lib.types.listOf lib.types.str;
};
repository = lib.mkOption {
type = lib.types.str;
};
withPostgres = lib.mkOption {
default = false;
type = lib.types.bool;
};
};
}
)
);
};
config = {
swarselsystems.enabledServerModules = [ "restic" ];
sops = {
secrets = lib.mkMerge (
lib.mapAttrsToList (name: _: {
"resticaccesskey-${name}" = { };
"resticpw-${name}" = { };
"resticsecretaccesskey-${name}" = { };
}) targets
);
templates = lib.mkMerge (
lib.mapAttrsToList (name: _: {
"restic-env-${name}".content = ''
AWS_ACCESS_KEY_ID=${config.sops.placeholder."resticaccesskey-${name}"}
AWS_SECRET_ACCESS_KEY=${config.sops.placeholder."resticsecretaccesskey-${name}"}
'';
}) targets
);
};
services.restic.backups = lib.mapAttrs' (
name: target:
let
postgresDumpDir = "/var/backup/restic-${name}";
postgresDumps =
lib.optional target.withPostgres {
command = "pg_dumpall --clean --if-exists";
file = "dumpall.sql";
}
++ map (database: {
command = "pg_dump --clean --create --if-exists ${database}";
file = "${database}.sql";
}) target.postgresDatabases;
in
lib.nameValuePair target.bucketName {
inherit (target) repository;
backupPrepareCommand = ''
set -euo pipefail
''
+ lib.optionalString (postgresDumps != [ ]) ''
install -d -m 0700 ${postgresDumpDir}
''
+ lib.concatMapStrings (dump: ''
${pkgs.util-linux}/bin/runuser -u postgres -- ${config.services.postgresql.package}/bin/${dump.command} > ${postgresDumpDir}/${dump.file}
chmod 0600 ${postgresDumpDir}/${dump.file}
'') postgresDumps;
environmentFile = config.sops.templates."restic-env-${name}".path;
extraBackupArgs = [ "--group-by host" ];
initialize = true;
passwordFile = config.sops.secrets."resticpw-${name}".path;
paths = target.paths ++ lib.optional (postgresDumps != [ ]) postgresDumpDir;
pruneOpts = [
"--group-by host"
"--keep-daily 3"
"--keep-weekly 2"
"--keep-monthly 3"
"--keep-yearly 5"
];
timerConfig.OnCalendar = "03:00";
}
) targets;
environment = {
etc."alloy/config.alloy".text = lib.mkIf config.services.alloy.enable (
lib.mkAfter ''
prometheus.exporter.unix "restic" {
set_collectors = ["textfile"]
textfile {
directory = "${metricsDir}"
}
}
prometheus.scrape "restic" {
targets = prometheus.exporter.unix.restic.targets
forward_to = [prometheus.remote_write.mimir.receiver]
job_name = "restic"
}
''
);
persistence."/persist".directories = lib.mkIf config.swarselsystems.isImpermanence [
{
directory = metricsDir;
mode = "0755";
}
];
};
systemd = {
services = lib.mapAttrs' (
_: target:
lib.nameValuePair "restic-backups-${target.bucketName}" {
postStart = ''
echo "restic_backup_last_success_timestamp_seconds{target=\"${target.bucketName}\"} $(date +%s)" > ${metricsDir}/${target.bucketName}.prom.tmp
mv ${metricsDir}/${target.bucketName}.prom.tmp ${metricsDir}/${target.bucketName}.prom
'';
}
) targets;
tmpfiles.settings."10-restic-metrics".${metricsDir}.d.mode = "0755";
};
nodes.${globals.general.monitoringServer}.services.grafana.provision.alerting.rules.settings.groups =
lib.optional (targets != { }) {
folder = "Infrastructure";
interval = "1m";
name = "restic-${config.node.name}";
orgId = 1;
rules = lib.mapAttrsToList (
_: target:
let
staleAfter = 26 * 3600;
in
confLib.mkGrafanaAlertRule {
expr = ''time() - max(restic_backup_last_success_timestamp_seconds{host="${config.node.name}",target="${target.bucketName}"}) or vector(${toString (staleAfter + 1)})'';
forDuration = "30m";
op = "gt";
summary = "restic backup ${target.bucketName} on ${config.node.name} has not succeeded in the last ${toString (staleAfter / 3600)} hours";
threshold = staleAfter;
title = "restic backup stale (${config.node.name}/${target.bucketName})";
uid = "restic_stale_${target.bucketName}";
}
) targets;
};
};
};
}
4.4.3.38. sanoid
This prunes ZFS snapshots of local datasets and prunes them. I set this up in a way so that receiving systems keep them for longer. This allows me, together with syncoid, to use a single SSD storage for my MicroVMs safely.
{
flake.modules.nixos.sanoid =
{
root,
config,
lib,
confLib,
...
}:
let
inherit (config.swarselsystems.server.sanoid) datasets;
retentionFor =
dataset:
if dataset.replica then
{
daily = 30;
hourly = 48;
monthly = 6;
}
else
{
daily = 7;
hourly = 24;
monthly = 0;
};
in
{
options.swarselsystems.server.sanoid.datasets = lib.mkOption {
default = { };
type = lib.types.attrsOf (
lib.types.submodule {
options.replica = lib.mkOption {
default = false;
description = "Whether this dataset only receives snapshots instead of taking its own.";
type = lib.types.bool;
};
}
);
};
config = {
swarselsystems.enabledServerModules = [ "sanoid" ];
topology.self.services = lib.mapAttrs' (
name: dataset:
lib.nameValuePair "sanoid-${lib.replaceStrings [ "/" ] [ "-" ] name}" {
details.retention.text = lib.concatStringsSep ", " (
lib.mapAttrsToList (period: count: "${toString count} ${period}") (retentionFor dataset)
);
icon = root "files/topology-images/openzfs.png";
info = if dataset.replica then "${name} (replica)" else name;
name = "Sanoid snapshots";
}
) datasets;
globals.monitoring.systemd = confLib.mkSystemdMonitoring {
oneshot = true;
serviceName = "sanoid-${config.node.name}";
unit = "sanoid.service";
};
services.sanoid = {
enable = true;
datasets = lib.mapAttrs (
_: dataset:
{
autoprune = true;
autosnap = !dataset.replica;
recursive = true;
}
// retentionFor dataset
) datasets;
};
};
};
}
4.4.3.39. syncoid
This replicates ZFS datasets into another pool. I use this to backup the data on my SSD MicroVM storage onto my HDD storage.
{
flake.modules.nixos.syncoid =
{
self,
root,
config,
lib,
confLib,
...
}:
let
inherit (config.swarselsystems.server.syncoid) targets;
in
{
imports = [
self.modules.nixos.sanoid
];
options.swarselsystems.server.syncoid.targets = lib.mkOption {
default = { };
type = lib.types.attrsOf (
lib.types.submodule {
options.target = lib.mkOption {
description = "Dataset that receives the snapshots of the to be backed up dataset.";
type = lib.types.str;
};
}
);
};
config = {
swarselsystems = {
enabledServerModules = [ "syncoid" ];
server.sanoid.datasets = lib.mapAttrs' (
_: target: lib.nameValuePair target.target { replica = true; }
) targets;
};
topology.self.services = lib.mapAttrs' (
source: target:
lib.nameValuePair "syncoid-${lib.replaceStrings [ "/" ] [ "-" ] source}" {
details.interval.text = config.services.syncoid.interval;
icon = root "files/topology-images/openzfs.png";
info = "${source} to ${target.target}";
name = "Syncoid replication";
}
) targets;
globals.monitoring.systemd = lib.mkMerge (
map (
source:
let
unitName = "syncoid-${lib.replaceStrings [ "/" ] [ "-" ] source}";
in
confLib.mkSystemdMonitoring {
oneshot = true;
serviceName = "${unitName}-${config.node.name}";
unit = "${unitName}.service";
}
) (lib.attrNames targets)
);
users.persistentIds.syncoid = confLib.mkIds 933;
services.syncoid = {
enable = true;
commands = lib.mapAttrs (_: target: {
inherit (target) target;
extraArgs = [
"--no-sync-snap"
"--recvoptions=u"
];
recursive = true;
}) targets;
interval = "hourly";
};
};
};
}
4.4.3.40. Grafana
{
flake.modules.nixos.grafana =
{
root,
config,
lib,
pkgs,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
dir = "/var/lib/grafana";
name = "grafana";
port = 3000;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDir
serviceDomain
serviceGroup
serviceName
servicePort
serviceUser
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
notificationMail
webProxy
;
kanidmDomain = globals.services.kanidm.domain;
in
{
config = {
swarselsystems.enabledServerModules = [ serviceName ];
topology.self.services.${serviceName}.info = "https://${serviceDomain}";
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = "ok|database";
path = "/api/health";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops.secrets = lib.mkMerge [
(lib.genAttrs
[
"gatus-watchdog-token"
"grafana-admin-pw"
"grafana-gotify-token"
"kanidm-grafana"
"notification-mail-pw"
]
(_: {
group = serviceGroup;
mode = "0440";
owner = serviceUser;
})
)
{
gatus-watchdog-token.rekey.keyPrefix = confLib.static.sharedSecrets.gatus;
kanidm-grafana.rekey.keyPrefix = confLib.kanidmSecrets;
notification-mail-pw.rekey.keyPrefix = notificationMail.keyPrefix;
}
];
users = {
users.${serviceUser}.extraGroups = [ "users" ];
persistentIds.grafana = confLib.mkIds 974;
};
services.${serviceName} = {
enable = true;
dataDir = serviceDir;
declarativePlugins =
lib.pipe config.services.${serviceName}.provision.datasources.settings.datasources [
(map (datasource: datasource.type))
lib.unique
(lib.filter (type: pkgs.grafanaPlugins ? ${type}))
(map (type: pkgs.grafanaPlugins.${type}))
]
++ (with pkgs.grafanaPlugins; [
grafana-exploretraces-app
grafana-lokiexplore-app
grafana-metricsdrilldown-app
grafana-pyroscope-app
]);
provision = {
enable = true;
alerting = {
contactPoints.settings = {
apiVersion = 1;
contactPoints = [
{
name = "default";
orgId = 1;
receivers = [
{
settings = {
httpMethod = "POST";
message = "{{ template \"default.message\" . }}";
title = "{{ template \"default.title\" . }}";
url = "https://${globals.services.gotify.domain}/message?token=$__file{${config.sops.secrets.grafana-gotify-token.path}}";
};
type = "webhook";
uid = "gotify_webhook";
}
{
settings = {
addresses = "monitoring@${globals.domains.main}";
singleEmail = false;
};
type = "email";
uid = "email_default";
}
];
}
{
name = "watchdog";
orgId = 1;
receivers = [
{
disableResolveMessage = true;
settings = {
authorization_credentials = "$__file{${config.sops.secrets.gatus-watchdog-token.path}}";
authorization_scheme = "Bearer";
httpMethod = "POST";
url = globals.services.gatus.extraConfig.watchdogUrl;
};
type = "webhook";
uid = "gatus_watchdog";
}
];
}
];
};
policies.settings = {
apiVersion = 1;
policies = [
{
group_by = [
"grafana_folder"
"alertname"
];
group_interval = "5m";
group_wait = "30s";
orgId = 1;
receiver = "default";
repeat_interval = "4h";
routes = [
{
group_interval = "1m";
group_wait = "0s";
object_matchers = [
[
"alertname"
"="
"Watchdog"
]
];
receiver = "watchdog";
repeat_interval = "5m";
}
];
}
];
};
rules.settings = {
apiVersion = 1;
groups = [
{
folder = "Infrastructure";
interval = "1m";
name = "watchdog";
orgId = 1;
rules = [
(
confLib.mkGrafanaAlertRule {
expr = "vector(1)";
forDuration = "0s";
noDataState = "OK";
op = "gt";
severity = "none";
summary = "Dead mans switch";
threshold = 0;
title = "Watchdog";
uid = "watchdog";
}
// {
execErrState = "OK";
}
)
];
}
];
};
};
dashboards.settings.providers = [
{
options.path = root "files/grafana";
name = "default";
}
];
};
settings = {
users = {
allow_sign_up = false;
default_home_dashboard_path = root "files/grafana/service-status.json";
};
analytics.reporting_enabled = false;
"auth.generic_oauth" = {
allow_assign_grafana_admin = true;
allow_sign_up = true;
api_url = "https://${kanidmDomain}/oauth2/openid/grafana/userinfo";
auth_url = "https://${kanidmDomain}/ui/oauth2";
client_id = "grafana";
client_secret = "$__file{${config.sops.secrets.kanidm-grafana.path}}";
enabled = true;
icon = "signin";
login_attribute_path = "preferred_username";
name = "Kanidm";
role_attribute_path = "contains(groups[*], 'server_admin') && 'GrafanaAdmin' || contains(groups[*], 'admin') && 'Admin' || contains(groups[*], 'editor') && 'Editor' || 'Viewer'";
scopes = "openid email profile";
token_url = "https://${kanidmDomain}/oauth2/token";
use_pkce = true;
use_refresh_token = true;
};
security = {
cookie_secure = true;
disable_gravatar = true;
disable_initial_admin_creation = true;
hide_version = true;
secret_key = "$__file{${config.sops.secrets.grafana-admin-pw.path}}";
};
server = {
domain = serviceDomain;
enable_gzip = true;
enforce_domain = true;
http_addr = "0.0.0.0";
http_port = servicePort;
protocol = "http";
root_url = "https://${serviceDomain}";
};
smtp = {
enabled = true;
from_address = "monitoring@${globals.domains.main}";
from_name = "Monitoring";
host = "${notificationMail.host}:587";
password = "$__file{${config.sops.secrets.notification-mail-pw.path}}";
startTLS_policy = "MandatoryStartTLS";
user = notificationMail.address;
};
};
};
environment.persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [
{
directory = serviceDir;
group = serviceGroup;
user = serviceUser;
}
];
};
systemd.services.${serviceName}.serviceConfig.RestartSec = lib.mkForce "60";
nodes = lib.mkMerge [
{
${idmServer} =
lib.recursiveUpdate
(confLib.mkKanidmOidcSystem {
inherit serviceDomain serviceName;
extraGroups = [
"grafana.editors"
"grafana.admins"
"grafana.server-admins"
];
originUrl = "https://${serviceDomain}/login/generic_oauth";
})
{
services.kanidm.provision.systems.oauth2.grafana.claimMaps.groups = {
joinType = "array";
valuesByGroup = {
"grafana.admins" = [ "admin" ];
"grafana.editors" = [ "editor" ];
"grafana.server-admins" = [ "server_admin" ];
};
};
};
}
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
serviceAddress
serviceDomain
serviceName
servicePort
;
proxyWebsockets = true;
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit serviceDomain serviceName servicePort;
extraConfig = nginxAccessRules;
proxyWebsockets = true;
serviceAddress = homeServiceAddress;
}
);
}
];
};
};
}
4.4.3.41. tempo
{
flake.modules.nixos.tempo =
{
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
dir = "/var/lib/private/tempo";
name = "tempo";
port = 14318;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDir
serviceDomain
serviceName
servicePort
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
isHome
nginxAccessRules
webProxy
wgProxyAccessRules
;
inherit (globals.services.alloy.extraConfig) otlpGrpcPort otlpHttpPort;
tempoHttpApiPort = 3200;
in
{
config = {
swarselsystems.enabledServerModules = [ serviceName ];
topology.self.services.${serviceName}.info = "https://${serviceDomain}";
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
extra.hasWebInterface = false;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName;
expectedBodyRegex = "ready";
path = "/ready";
servicePort = tempoHttpApiPort;
};
networks = confLib.mkDualFirewallRules {
tcpPorts = [
servicePort
tempoHttpApiPort
];
};
};
services.${serviceName} = {
enable = true;
settings = {
backend_scheduler = {
local_work_path = "${serviceDir}/scheduler";
provider.compaction.compaction.block_retention = "168h";
};
distributor.receivers.otlp.protocols = {
grpc = {
endpoint = "127.0.0.1:14317";
max_recv_msg_size_mib = 20;
};
http.endpoint = "0.0.0.0:${toString servicePort}";
};
live_store = {
shutdown_marker_dir = "${serviceDir}/live-store/shutdown-marker";
wal.path = "${serviceDir}/live-store/traces";
};
metrics_generator = {
registry.external_labels.source = "tempo";
storage = {
path = "${serviceDir}/generator/wal";
remote_write = [
{
send_exemplars = true;
url = "https://${globals.services.mimir.domain}/api/v1/push";
}
];
};
};
overrides.defaults.metrics_generator.processors = [
"service-graphs"
"span-metrics"
];
server = {
grpc_listen_port = 9097;
http_listen_address = "0.0.0.0";
http_listen_port = tempoHttpApiPort;
log_level = "warn";
};
storage.trace = {
backend = "local";
local.path = "${serviceDir}/blocks";
wal.path = "${serviceDir}/wal";
};
usage_report.reporting_enabled = false;
};
};
environment.persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [
{
directory = serviceDir;
mode = "0700";
}
];
};
networking.firewall.allowedTCPPorts = [ servicePort ];
systemd.services.tempo = {
environment = confLib.mkOtelEnvironment serviceName // {
OTEL_TRACES_SAMPLER = "parentbased_traceidratio";
OTEL_TRACES_SAMPLER_ARG = "0.01";
};
serviceConfig.RestartSec = lib.mkForce "60";
};
nodes =
let
ingestUpstream = "${serviceName}-ingest";
queryUpstream = "${serviceName}-query";
genNginx = addr: extraConfig: {
upstreams = {
${ingestUpstream}.servers."${addr}:${toString servicePort}" = { };
${queryUpstream}.servers."${addr}:${toString tempoHttpApiPort}" = { };
};
virtualHosts.${serviceDomain} = {
inherit extraConfig;
acmeRoot = null;
forceSSL = true;
locations =
lib.mapAttrs
(_: upstream: {
extraConfig = ''
client_max_body_size 0;
'';
proxyPass = "http://${upstream}";
})
{
"/" = queryUpstream;
"/v1/" = ingestUpstream;
};
useACMEHost = globals.domains.main;
};
};
in
lib.mkMerge [
{
${webProxy}.services.nginx = genNginx serviceAddress wgProxyAccessRules;
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (genNginx homeServiceAddress nginxAccessRules);
}
{
${globals.general.monitoringServer}.services.grafana = {
provision.datasources.settings.datasources = [
{
access = "proxy";
jsonData = {
nodeGraph.enabled = true;
search.hide = false;
serviceMap.datasourceUid = "mimir";
tracesToLogsV2 = {
datasourceUid = "loki";
filterBySpanID = false;
filterByTraceID = true;
};
tracesToProfiles = {
datasourceUid = "pyroscope";
profileTypeId = "process_cpu:cpu:nanoseconds:cpu:nanoseconds";
tags = [
{
key = "service.name";
value = "service_name";
}
];
};
};
name = "Tempo";
type = "tempo";
uid = "tempo";
url = confLib.mkAlloyPushUrl {
domain = serviceDomain;
host = globals.general.monitoringServer;
path = "";
port = tempoHttpApiPort;
};
}
];
settings = {
"tracing.opentelemetry".custom_attributes =
"service.name:grafana-${globals.general.monitoringServer}";
"tracing.opentelemetry.otlp" = {
address = "127.0.0.1:${toString otlpGrpcPort}";
propagation = "w3c";
};
};
};
}
(lib.genAttrs (lib.attrNames globals.services.alloy.extraConfig.clients) (alloyHost: {
environment.etc."alloy/config.alloy".text = lib.mkAfter ''
otelcol.receiver.otlp "local_tempo" {
grpc {
endpoint = "127.0.0.1:${toString otlpGrpcPort}"
max_recv_msg_size = "20MiB"
}
http { endpoint = "127.0.0.1:${toString otlpHttpPort}" }
output {
traces = [otelcol.exporter.otlphttp.tempo.input]
}
}
otelcol.exporter.otlphttp "tempo" {
client {
endpoint = "${
confLib.mkAlloyPushUrl {
domain = serviceDomain;
host = alloyHost;
path = "";
port = servicePort;
}
}"
}
}
beyla.ebpf "auto" {
discovery {
instrument {
open_ports = "*"
exports = ["traces"]
}
}
output {
traces = [otelcol.exporter.otlphttp.tempo.input]
}
}
'';
}))
];
};
};
}
4.4.3.42. Gotify
{
flake.modules.nixos.gotify =
{
self,
root,
config,
lib,
confLib,
...
}:
let
inherit
(confLib.gen {
dir = "/var/lib/private/gotify-server";
name = "gotify";
port = 8080;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDir
serviceDomain
serviceName
servicePort
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
isHome
nginxAccessRules
webProxy
;
postgresRole = "gotify-server";
in
{
imports = [
self.modules.nixos.postgresql
];
config = {
swarselsystems = {
enabledServerModules = [ serviceName ];
server.postgresql.rolePasswordFiles.${postgresRole} =
config.sops.secrets."${postgresRole}-db-password".path;
};
topology.self.services.${serviceName} = {
icon = root "files/topology-images/${serviceName}.png";
info = "https://${serviceDomain}";
name = lib.swarselsystems.toCapitalized serviceName;
};
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
extra.extraConfig.port = servicePort;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = "ok|green";
path = "/health";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops = {
secrets."${postgresRole}-db-password" = {
owner = config.systemd.services.postgresql.serviceConfig.User;
rekey.generator.script = "alnum";
};
templates."${serviceName}-env".content = ''
GOTIFY_DATABASE_CONNECTION="host=/run/postgresql user=${postgresRole} dbname=${postgresRole} password=${
config.sops.placeholder."${postgresRole}-db-password"
} sslmode=disable"
'';
};
services = {
${serviceName} = {
enable = true;
environment = {
GOTIFY_DATABASE_DIALECT = "postgres";
GOTIFY_PASSSTRENGTH = 12;
GOTIFY_PLUGINSDIR = "${serviceDir}/plugins";
GOTIFY_SERVER_LISTENADDR = "0.0.0.0";
GOTIFY_SERVER_PORT = servicePort;
GOTIFY_UPLOADEDIMAGESDIR = "${serviceDir}/images";
};
environmentFiles = [ config.sops.templates."${serviceName}-env".path ];
};
postgresql = {
ensureDatabases = [ postgresRole ];
ensureUsers = [
{
ensureDBOwnership = true;
name = postgresRole;
}
];
};
};
environment.persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [
{
directory = serviceDir;
mode = "0700";
}
];
};
systemd.services.gotify-server.serviceConfig.RestartSec = lib.mkForce "60";
nodes = lib.mkMerge [
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
serviceAddress
serviceDomain
serviceName
servicePort
;
maxBody = 50;
maxBodyUnit = "M";
proxyWebsockets = true;
# extraConfig = wgProxyAccessRules;
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit serviceDomain serviceName servicePort;
extraConfig = nginxAccessRules;
maxBody = 50;
maxBodyUnit = "M";
proxyWebsockets = true;
serviceAddress = homeServiceAddress;
}
);
}
];
};
};
}
4.4.3.43. Pyroscope
{
flake.modules.nixos.pyroscope =
{
root,
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
dir = "/var/lib/private/pyroscope";
name = "pyroscope";
port = 4040;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDir
serviceDomain
serviceName
servicePort
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
isHome
nginxAccessRules
webProxy
wgProxyAccessRules
;
grpcPort = 9098;
grpcAddress = "localhost:${toString grpcPort}";
in
{
config = {
swarselsystems.enabledServerModules = [ serviceName ];
topology.self.services.${serviceName} = {
icon = root "files/topology-images/${serviceName}.png";
info = "https://${serviceDomain}";
name = lib.swarselsystems.toCapitalized serviceName;
};
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = "ready";
path = "/ready";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
services.${serviceName} = {
enable = true;
settings = {
analytics.reporting_enabled = false;
memberlist.bind_port = 7948;
metastore.address = grpcAddress;
multitenancy_enabled = false;
pyroscopedb.data_path = "${serviceDir}/pyroscope";
query_backend.address = grpcAddress;
server = {
grpc_listen_port = grpcPort;
http_listen_address = "0.0.0.0";
http_listen_port = servicePort;
log_level = "warn";
};
storage = {
backend = "filesystem";
filesystem.dir = "${serviceDir}/data";
};
target = "all";
};
};
environment.persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [
{
directory = serviceDir;
mode = "0700";
}
];
};
networking.firewall.allowedTCPPorts = [ servicePort ];
systemd.services.${serviceName}.serviceConfig.RestartSec = lib.mkForce "60";
nodes = lib.mkMerge [
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
serviceAddress
serviceDomain
serviceName
servicePort
;
extraConfig = wgProxyAccessRules;
maxBody = 0;
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit serviceDomain serviceName servicePort;
extraConfig = nginxAccessRules;
maxBody = 0;
serviceAddress = homeServiceAddress;
}
);
}
{
${globals.general.monitoringServer}.services.grafana.provision.datasources.settings.datasources = [
{
access = "proxy";
name = "Pyroscope";
type = "grafana-pyroscope-datasource";
uid = "pyroscope";
url = confLib.mkAlloyPushUrl {
domain = serviceDomain;
host = globals.general.monitoringServer;
path = "";
port = servicePort;
};
}
];
}
(lib.genAttrs (lib.attrNames globals.services.alloy.extraConfig.clients) (alloyHost: {
environment.etc."alloy/config.alloy".text = lib.mkAfter ''
discovery.process "all" {
refresh_interval = "30s"
discover_config {
cwd = false
exe = true
commandline = false
username = false
uid = false
container_id = true
}
}
discovery.relabel "process" {
targets = discovery.process.all.targets
rule {
source_labels = ["__meta_process_exe"]
regex = "(?:.*/)?([^/]+)"
target_label = "service_name"
}
rule {
source_labels = ["__meta_process_cgroup_id"]
regex = ".*/([^/]+)\\.service"
target_label = "service_name"
}
}
pyroscope.ebpf "auto" {
targets = discovery.relabel.process.output
forward_to = [pyroscope.write.central.receiver]
off_cpu_threshold = 0.01
}
pyroscope.write "central" {
endpoint {
url = "${
confLib.mkAlloyPushUrl {
domain = serviceDomain;
host = alloyHost;
path = "";
port = servicePort;
}
}"
}
external_labels = {
host = "${alloyHost}",
}
}
'';
}))
];
};
};
}
4.4.3.44. Loki
{
flake.modules.nixos.loki =
{
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
dir = "/var/lib/loki";
name = "loki";
port = 3100;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDir
serviceDomain
serviceGroup
serviceName
servicePort
serviceUser
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
isHome
nginxAccessRules
webProxy
wgProxyAccessRules
;
in
{
config = {
swarselsystems.enabledServerModules = [ serviceName ];
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
extra.hasWebInterface = false;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = "ready";
path = "/ready";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
users.persistentIds.loki = confLib.mkIds 948;
services.${serviceName} = {
enable = true;
configuration = {
analytics.reporting_enabled = false;
auth_enabled = false;
common = {
instance_addr = "127.0.0.1";
path_prefix = serviceDir;
replication_factor = 1;
ring.kvstore.store = "inmemory";
storage.filesystem = {
chunks_directory = "${serviceDir}/chunks";
rules_directory = "${serviceDir}/rules";
};
};
compactor = {
compactor_ring.kvstore.store = "inmemory";
retention_enabled = false;
working_directory = "${serviceDir}/compactor";
};
ingester = {
chunk_idle_period = "5m";
chunk_retain_period = "30s";
};
limits_config = {
allow_structured_metadata = true;
reject_old_samples = true;
reject_old_samples_max_age = "168h";
};
schema_config.configs = [
{
from = "2026-01-01";
index = {
period = "24h";
prefix = "index_";
};
object_store = "filesystem";
schema = "v13";
store = "tsdb";
}
];
server = {
grpc_listen_port = 9094;
http_listen_address = "0.0.0.0";
http_listen_port = servicePort;
log_level = "warn";
};
};
dataDir = serviceDir;
};
environment.persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [
{
directory = serviceDir;
group = serviceGroup;
user = serviceUser;
}
];
};
networking.firewall.allowedTCPPorts = [ servicePort ];
systemd.services.loki = {
environment = confLib.mkOtelEnvironment serviceName;
serviceConfig.RestartSec = lib.mkForce "60";
};
nodes = lib.mkMerge [
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
serviceAddress
serviceDomain
serviceName
servicePort
;
extraConfig = wgProxyAccessRules;
maxBody = 0;
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit serviceDomain serviceName servicePort;
extraConfig = nginxAccessRules;
maxBody = 0;
serviceAddress = homeServiceAddress;
}
);
}
{
${globals.general.monitoringServer}.services.grafana.provision.datasources.settings.datasources = [
{
access = "proxy";
name = "Loki";
type = "loki";
uid = "loki";
url = confLib.mkAlloyPushUrl {
domain = serviceDomain;
host = globals.general.monitoringServer;
path = "";
port = servicePort;
};
}
];
}
(lib.genAttrs (lib.attrNames globals.services.alloy.extraConfig.clients) (alloyHost: {
environment.etc."alloy/config.alloy".text = lib.mkAfter ''
loki.relabel "journal" {
forward_to = []
rule {
source_labels = ["__journal__systemd_unit"]
target_label = "unit"
}
rule {
source_labels = ["__journal_priority_keyword"]
target_label = "level"
}
}
loki.source.journal "journal" {
max_age = "12h"
relabel_rules = loki.relabel.journal.rules
forward_to = [loki.write.central.receiver]
labels = {
host = "${alloyHost}",
job = "systemd-journal",
}
}
loki.write "central" {
endpoint {
url = "${
confLib.mkAlloyPushUrl {
domain = serviceDomain;
host = alloyHost;
path = "/loki/api/v1/push";
port = servicePort;
}
}"
}
}
'';
}))
];
};
};
}
4.4.3.45. alloy
{
flake.modules.nixos.alloy =
{
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
name = "alloy";
port = 12345;
})
serviceName
servicePort
;
inherit (confLib.static)
homeWebProxy
inWgHome
inWgProxy
isHome
webProxy
;
otlpGrpcPort = 4317;
otlpHttpPort = 4318;
wgProxyHosts = globals.networks."${globals.wireguard.wgProxy.netConfigPrefix}-wgProxy".hosts;
wgHomeHosts = globals.networks."${globals.wireguard.wgHome.netConfigPrefix}-wgHome".hosts;
capabilities = [
"CAP_BPF"
"CAP_SYS_PTRACE"
"CAP_NET_RAW"
"CAP_CHECKPOINT_RESTORE"
"CAP_DAC_READ_SEARCH"
"CAP_PERFMON"
"CAP_SYS_RESOURCE"
"CAP_SYSLOG"
];
in
{
config = {
swarselsystems.enabledServerModules = [ serviceName ];
globals = {
services.${serviceName}.extraConfig = {
inherit otlpGrpcPort otlpHttpPort;
clients.${config.node.name} = true;
};
monitoring.hostNetworks.${config.node.name} = [
"local-${config.node.name}"
]
++ lib.optional isHome "home-lan"
++ lib.optional inWgHome "wgHome"
++ lib.optional inWgProxy "wgProxy"
++ lib.optional (
globals.hosts.${config.node.name}.wanAddress4 != null
|| globals.hosts.${config.node.name}.wanAddress6 != null
) "internet"
++ lib.mapAttrsToList (vlan: _: "${vlan}-vlan") (
lib.filterAttrs (_: vlan: vlan.hosts ? ${config.node.name}) globals.networks.home-lan.vlans
);
};
services.${serviceName} = {
enable = true;
extraFlags = [ "--server.http.listen-addr=127.0.0.1:${toString servicePort}" ];
};
environment = {
etc."alloy/config.alloy".text = ''
logging {
level = "warn"
format = "logfmt"
}
'';
persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [
{
directory = "/var/lib/private/alloy";
mode = "0700";
}
];
};
};
networking.hosts =
let
proxyIp =
if isHome && inWgHome then
wgHomeHosts.${homeWebProxy}.ipv4
else if inWgProxy then
wgProxyHosts.${webProxy}.ipv4
else
null;
in
lib.optionalAttrs (proxyIp != null) {
${proxyIp} = [
globals.services.mimir.domain
globals.services.loki.domain
globals.services.tempo.domain
globals.services.pyroscope.domain
];
};
systemd.services.alloy.serviceConfig = {
AmbientCapabilities = capabilities;
CapabilityBoundingSet = capabilities;
RestartSec = lib.mkForce "60";
};
};
};
}
4.4.3.46. blackbox-exporter
{
flake.modules.nixos.blackbox =
{
config,
lib,
pkgs,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
name = "blackbox";
port = 9115;
})
serviceName
servicePort
;
hostNetworks = globals.monitoring.hostNetworks.${config.node.name} or [ ];
defaultProbeFor = "3m";
in
{
config = {
swarselsystems.enabledServerModules = [ serviceName ];
topology.self.services.${serviceName} = {
icon = "services.prometheus";
name = "blackbox-exporter";
};
globals.monitoring.tcp = lib.mkIf config.services.openssh.enable (
confLib.mkTcpMonitoring {
expectedRegex = "^SSH-2.0";
serviceName = "ssh-${config.node.name}";
servicePort = lib.head config.services.openssh.ports;
}
);
services.prometheus.exporters.blackbox = {
enable = true;
configFile = pkgs.writeText "blackbox.yml" (
builtins.toJSON {
modules = {
icmp = {
icmp.preferred_ip_protocol = "ip4";
prober = "icmp";
timeout = "5s";
};
}
// lib.concatMapAttrs (name: cfg: {
"http_${name}" = {
http = {
follow_redirects = true;
method = "GET";
preferred_ip_protocol = "ip4";
tls_config.insecure_skip_verify = true;
valid_status_codes = [ cfg.expectedStatus ];
}
// lib.optionalAttrs (cfg.expectedBodyRegex != null) {
fail_if_body_not_matches_regexp = [ cfg.expectedBodyRegex ];
}
// lib.optionalAttrs (cfg.failIfBodyMatchesRegex != null) {
fail_if_body_matches_regexp = [ cfg.failIfBodyMatchesRegex ];
}
// lib.optionalAttrs (cfg.hostHeader != null) {
headers.Host = cfg.hostHeader;
};
prober = "http";
timeout = "10s";
};
}) globals.monitoring.http
// lib.concatMapAttrs (name: cfg: {
"tcp_${name}" = {
prober = "tcp";
tcp = {
inherit (cfg) tls;
preferred_ip_protocol = "ip4";
tls_config.insecure_skip_verify = true;
}
// lib.optionalAttrs (cfg.expectedRegex != null) {
query_response = [ { expect = cfg.expectedRegex; } ];
};
timeout = "10s";
};
}) globals.monitoring.tcp
// lib.concatMapAttrs (name: cfg: {
"dns_${name}" = {
dns = {
preferred_ip_protocol = "ip4";
query_name = cfg.queryName;
query_type = cfg.queryType;
valid_rcodes = [ "NOERROR" ];
validate_answer_rrs.fail_if_none_matches_regexp = [ ".+" ];
};
prober = "dns";
timeout = "5s";
};
}) globals.monitoring.dns
// lib.concatMapAttrs (name: cfg: {
"cert_${name}" = {
prober = "tcp";
tcp = {
preferred_ip_protocol = "ip4";
tls = true;
tls_config = {
insecure_skip_verify = true;
server_name = cfg.serverName;
};
};
timeout = "10s";
};
}) globals.monitoring.cert;
}
);
listenAddress = "127.0.0.1";
port = servicePort;
};
environment.etc."alloy/config.alloy".text = lib.mkIf config.services.alloy.enable (
lib.mkAfter (
lib.concatMapStrings (
kind:
let
targets = lib.mapAttrsToList (name: cfg: {
inherit name;
__address__ =
{
http = cfg.url;
ping = cfg.host;
}
.${kind} or cfg.address;
__param_module = if kind == "ping" then "icmp" else "${kind}_${name}";
probe = kind;
}) (lib.filterAttrs (_: cfg: builtins.elem cfg.network hostNetworks) globals.monitoring.${kind});
in
lib.optionalString (targets != [ ]) ''
discovery.relabel "blackbox_${kind}" {
targets = [
${
lib.concatMapStringsSep ",\n" (
target:
"{${
lib.concatStringsSep ", " (
lib.mapAttrsToList (key: value: "${builtins.toJSON key} = ${builtins.toJSON value}") target
)
}}"
) targets
},
]
rule {
source_labels = ["__address__"]
target_label = "__param_target"
}
rule {
source_labels = ["__param_target"]
target_label = "instance"
}
rule {
target_label = "__address__"
replacement = "127.0.0.1:${toString servicePort}"
}
rule {
target_label = "probe_from"
replacement = "${config.node.name}"
}
}
prometheus.scrape "blackbox_${kind}" {
targets = discovery.relabel.blackbox_${kind}.output
metrics_path = "/probe"
job_name = "blackbox_${kind}"
forward_to = [prometheus.remote_write.mimir.receiver]
}
''
) confLib.static.probeKinds
)
);
nodes.${globals.general.monitoringServer}.services.grafana.provision.alerting.rules.settings.groups =
[
{
folder = "Infrastructure";
interval = "1m";
name = "blackbox";
orgId = 1;
rules =
lib.concatMap
(
kind:
let
probes = globals.monitoring.${kind};
in
lib.mapAttrsToList (
forDuration: names:
let
selector = ''probe="${kind}",name=~"${lib.concatStringsSep "|" names}"'';
isDefault = forDuration == defaultProbeFor;
in
confLib.mkGrafanaAlertRule {
inherit forDuration;
expr = "min by (name) (probe_success{${selector}}) or on(name) (probe_expected{${selector}} * 0)";
summary = "Blackbox ${lib.toUpper kind} probe for {{ $labels.name }} has been failing";
title = "${lib.toUpper kind} probe failed${
lib.optionalString (!isDefault) " (after ${forDuration})"
}";
uid = "${kind}_probe_failed${lib.optionalString (!isDefault) "_${forDuration}"}";
}
) (lib.groupBy (name: lib.defaultTo defaultProbeFor probes.${name}.alertFor) (lib.attrNames probes))
)
[
"dns"
"http"
"tcp"
]
++ [
(confLib.mkGrafanaAlertRule {
expr = ''min by (name) ((probe_ssl_earliest_cert_expiry{probe="cert"} - time()) / 86400) or on(name) (max by (name) (probe_expected{probe="cert"}) * 0)'';
severity = "warning";
summary = "Certificate served by {{ $labels.name }} expires in {{ $values.A.Value | printf \"%.0f\" }} days or could not be fetched";
threshold = 14;
title = "Certificate expiring";
uid = "cert_expiring";
})
];
}
];
};
};
}
4.4.3.47. Gatus
This is just a lite probing that runs from the outside to make sure my most important "basic needs" are doing fine.
{
flake.modules.nixos.gatus =
{
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
dir = "/var/lib/private/gatus";
name = "gatus";
port = 8099;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDir
serviceDomain
serviceName
servicePort
;
inherit (confLib.static)
dnsServer
homeServiceAddress
idmServer
isHome
webProxy
;
alertAddress = config.repo.secrets.common.mail.address3;
certificateValid = "[CERTIFICATE_EXPIRATION] > 240h";
mkEndpoint =
endpoint:
{
alerts = [ { type = "email"; } ];
interval = "1m";
}
// endpoint;
watchdog = {
group = "home";
name = "grafana-watchdog";
};
in
{
config = {
swarselsystems.enabledServerModules = [ serviceName ];
topology.self.services.${serviceName} = {
info = "https://${serviceDomain}";
name = lib.swarselsystems.toCapitalized serviceName;
};
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
extra.extraConfig.watchdogUrl = "https://${serviceDomain}/api/v1/endpoints/${watchdog.group}_${watchdog.name}/external?success=true";
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = "UP";
path = "/health";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops = {
secrets = {
gatus-smtp-password = { };
gatus-watchdog-token.rekey = {
generator.script = "alnum";
keyPrefix = confLib.static.sharedSecrets.gatus;
};
};
templates.gatus-env.content = ''
GATUS_SMTP_PASSWORD=${config.sops.placeholder.gatus-smtp-password}
GATUS_WATCHDOG_TOKEN=${config.sops.placeholder.gatus-watchdog-token}
'';
};
services.${serviceName} = {
enable = true;
environmentFile = config.sops.templates.gatus-env.path;
settings = {
alerting.email = {
default-alert = {
failure-threshold = 3;
send-on-resolved = true;
success-threshold = 2;
};
from = alertAddress;
host = "smtp.gmail.com";
password = "\${GATUS_SMTP_PASSWORD}";
port = 587;
to = "${alertAddress},monitoring@${globals.domains.main}";
username = alertAddress;
};
endpoints = map mkEndpoint [
{
conditions = [
"[STATUS] == 200"
"[BODY].database == ok"
];
group = "home";
name = "grafana";
url = "https://${globals.services.grafana.domain}/api/health";
}
{
conditions = [
"[STATUS] == 200"
"[BODY] == true"
];
group = "home";
name = "kanidm";
url = "https://${globals.services.kanidm.domain}/status";
}
{
conditions = [
"[STATUS] == 200"
certificateValid
];
group = "cloud";
name = "web-proxy";
url = "https://${globals.services.oauth2-proxy.domain}/ping";
}
{
conditions = [
"[CONNECTED] == true"
certificateValid
];
group = "cloud";
name = "smtp";
url = "starttls://${globals.services.mailserver.domain}:587";
}
{
conditions = [
"[CONNECTED] == true"
certificateValid
];
group = "cloud";
name = "imap";
url = "tls://${globals.services.mailserver.domain}:993";
}
{
conditions = [ "[DNS_RCODE] == NOERROR" ];
dns = {
query-name = globals.domains.main;
query-type = "SOA";
};
group = "cloud";
name = "dns";
url = globals.hosts.${dnsServer}.wanAddress4;
}
{
conditions = [
"[STATUS] == 200"
"[BODY] == pat(*Attic Binary Cache*)"
];
group = "cloud";
name = "binary-cache";
url = "https://${globals.services.attic.domain}/";
}
];
external-endpoints = [
(
watchdog
// {
alerts = [
{
failure-threshold = 1;
type = "email";
}
];
heartbeat.interval = "10m";
token = "\${GATUS_WATCHDOG_TOKEN}";
}
)
];
storage = {
path = "/var/lib/gatus/data.db";
type = "sqlite";
};
web = {
address = "0.0.0.0";
port = servicePort;
};
};
};
environment.persistence."/persist".directories = lib.mkIf config.swarselsystems.isImpermanence [
{
directory = serviceDir;
mode = "0700";
}
];
nodes = lib.mkMerge [
{
${idmServer} = confLib.mkKanidmOauth2ProxyAccess { inherit serviceName; };
}
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
serviceAddress
serviceDomain
serviceName
servicePort
;
oauth2 = true;
oauth2Groups = [ "${serviceName}_access" ];
};
}
{
${webProxy}.services.nginx.virtualHosts.${serviceDomain}.locations."~ ^/api/v1/endpoints/[^/]+/external$" =
{
bypassAuth = true;
proxyPass = "http://${serviceName}";
setOauth2Headers = false;
};
}
];
};
};
}
4.4.3.48. parsedmarc
Reads the reports that arrive and makes them available to Grafana (the dashboard is disabled because it is not compatible with my Grafana version)
{
flake.modules.nixos.parsedmarc =
{
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
dir = "/var/lib/private/opensearch";
name = "parsedmarc";
})
serviceDir
serviceName
;
in
{
config = {
swarselsystems.enabledServerModules = [ serviceName ];
topology.self.services.${serviceName}.name = serviceName;
globals.monitoring = {
http = confLib.mkHttpMonitoring {
expectedBodyRegex = ''"status":"(green|yellow)"'';
path = "/_cluster/health";
serviceName = "opensearch";
servicePort = config.services.opensearch.settings."http.port";
};
systemd = confLib.mkSystemdMonitoring {
inherit serviceName;
unit = "parsedmarc.service";
};
};
sops.secrets.parsedmarc-imap-password.rekey = {
generator.script = "alnum";
keyPrefix = confLib.static.sharedSecrets.parsedmarc;
};
services = {
${serviceName} = {
enable = true;
provision = {
geoIp = false;
grafana.dashboard = false;
};
settings = {
general.save_smtp_tls = true;
imap = {
host = globals.services.mailserver.domain;
password._secret = config.sops.secrets.parsedmarc-imap-password.path;
port = 993;
ssl = true;
user = confLib.static.dmarcMailAddress;
};
};
};
opensearch.extraJavaOptions = [
"-Xms512m"
"-Xmx512m"
];
};
environment.persistence."/state".directories = lib.mkIf config.swarselsystems.isMicroVM [
{
directory = serviceDir;
mode = "0700";
}
];
};
};
}
4.4.3.49. smartctl-exporter
{
flake.modules.nixos.smartctl-exporter =
{
confLib,
...
}:
let
inherit
(confLib.gen {
name = "smartctl-exporter";
port = 9633;
})
serviceName
servicePort
;
in
{
config = {
swarselsystems.enabledServerModules = [ serviceName ];
topology.self.services.${serviceName} = {
icon = "services.prometheus";
name = serviceName;
};
users.persistentIds.smartctl-exporter-access = confLib.mkIds 947;
services.prometheus.exporters.smartctl = {
enable = true;
listenAddress = "127.0.0.1";
port = servicePort;
};
environment.etc."alloy/config.alloy".text = confLib.mkAlloyScrape {
name = "smartctl";
port = servicePort;
scrapeSettings.scrape_interval = "60s";
};
};
};
}
4.4.3.50. zfs-exporter
{
flake.modules.nixos.zfs-exporter =
{
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
name = "zfs-exporter";
port = 9134;
})
serviceName
servicePort
;
in
{
config = {
swarselsystems.enabledServerModules = [ serviceName ];
topology.self.services.${serviceName} = {
icon = "services.prometheus";
name = serviceName;
};
services.prometheus.exporters.zfs = {
enable = true;
listenAddress = "127.0.0.1";
port = servicePort;
};
environment.etc."alloy/config.alloy".text = confLib.mkAlloyScrape {
name = "zfs";
port = servicePort;
};
nodes.${globals.general.monitoringServer}.services.grafana.provision.alerting.rules.settings.groups =
[
{
folder = "Infrastructure";
interval = "1m";
name = "zfs";
orgId = 1;
rules = [
(confLib.mkGrafanaAlertRule {
expr = "max by (host, pool) (zfs_pool_health)";
forDuration = "5m";
op = "gt";
summary = "ZFS pool {{ $labels.host }}:{{ $labels.pool }} is not ONLINE";
threshold = 0;
title = "ZFS pool not online";
uid = "zfs_pool_unhealthy";
})
(confLib.mkGrafanaAlertRule {
expr = "max by (host, pool) (100 * zfs_pool_allocated_bytes / zfs_pool_size_bytes)";
forDuration = "10m";
op = "gt";
severity = "warning";
summary = "ZFS pool {{ $labels.host }}:{{ $labels.pool }} is more than 80% full";
threshold = 80;
title = "ZFS pool above 80% used";
uid = "zfs_pool_filling";
})
];
}
];
};
};
}
4.4.3.51. ipmi-exporter
{
flake.modules.nixos.ipmi-exporter =
{
pkgs,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
name = "ipmi-exporter";
port = 9290;
})
serviceName
servicePort
;
in
{
config = {
swarselsystems.enabledServerModules = [ serviceName ];
topology.self.services.${serviceName} = {
icon = "services.prometheus";
name = serviceName;
};
services.prometheus.exporters.ipmi = {
enable = true;
configFile = (pkgs.formats.yaml { }).generate "ipmi.yml" {
modules.default = {
collectors = [
"bmc"
"chassis"
"dcmi"
"ipmi"
"sel"
];
custom_args.ipmi = [
"--sdr-cache-directory"
"/var/cache/prometheus-ipmi-exporter"
];
driver = "OPENIPMI";
};
};
group = "root";
listenAddress = "127.0.0.1";
port = servicePort;
user = "root";
};
boot.kernelModules = [
"ipmi_devintf"
"ipmi_si"
];
environment.etc."alloy/config.alloy".text = confLib.mkAlloyScrape {
name = "ipmi";
port = servicePort;
scrapeSettings = {
scrape_interval = "60s";
scrape_timeout = "30s";
};
};
systemd.services.prometheus-ipmi-exporter.serviceConfig = {
CacheDirectory = "prometheus-ipmi-exporter";
DeviceAllow = [ "char-ipmidev rw" ];
DynamicUser = false;
PrivateDevices = false;
};
nodes.${globals.general.monitoringServer}.services.grafana.provision.alerting.rules.settings.groups =
[
{
folder = "Infrastructure";
interval = "1m";
name = "ipmi";
orgId = 1;
rules = [
(confLib.mkGrafanaAlertRule {
expr = "max by (host, name, type) (ipmi_sensor_state)";
op = "gt";
summary = "{{ $labels.host }}: IPMI {{ $labels.type }} sensor {{ $labels.name }} is in critical state";
threshold = 1;
title = "IPMI sensor critical";
uid = "ipmi_sensor_critical";
})
];
}
];
};
};
}
4.4.3.52. nginx-exporter
{
flake.modules.nixos.nginx-exporter =
{
confLib,
...
}:
let
inherit
(confLib.gen {
name = "nginx-exporter";
port = 9113;
})
serviceName
servicePort
;
in
{
config = {
swarselsystems.enabledServerModules = [ serviceName ];
topology.self.services.${serviceName} = {
icon = "services.prometheus";
name = serviceName;
};
services = {
nginx.statusPage = true;
prometheus.exporters.nginx = {
enable = true;
listenAddress = "127.0.0.1";
port = servicePort;
};
};
environment.etc."alloy/config.alloy".text = confLib.mkAlloyScrape {
name = "nginx";
port = servicePort;
};
};
};
}
4.4.3.53. Mimir
{
flake.modules.nixos.mimir =
{
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
dir = "/var/lib/private/mimir";
name = "mimir";
port = 9009;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDir
serviceDomain
serviceName
servicePort
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
isHome
nginxAccessRules
webProxy
wgProxyAccessRules
;
in
{
config = {
swarselsystems.enabledServerModules = [ serviceName ];
topology.self.services.${serviceName}.info = "https://${serviceDomain}";
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
extra.hasWebInterface = false;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = "Running";
failIfBodyMatchesRegex = "(Starting|Stopping|Failed|Terminated|New|Stuck)";
path = "/services";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
services.${serviceName} = {
enable = true;
configuration = {
blocks_storage = {
backend = "filesystem";
bucket_store.sync_dir = "${serviceDir}/tsdb-sync";
filesystem.dir = "${serviceDir}/blocks";
tsdb.dir = "${serviceDir}/tsdb";
};
common.storage = {
backend = "filesystem";
filesystem.dir = "${serviceDir}/data";
};
compactor = {
data_dir = "${serviceDir}/compactor";
sharding_ring.kvstore.store = "memberlist";
};
distributor.ring.instance_addr = "127.0.0.1";
ingester.ring = {
instance_addr = "127.0.0.1";
kvstore.store = "memberlist";
replication_factor = 1;
};
limits.max_global_series_per_user = 0;
multitenancy_enabled = false;
ruler.rule_path = "${serviceDir}/rules";
ruler_storage = {
backend = "filesystem";
filesystem.dir = "${serviceDir}/ruler";
};
server = {
grpc_listen_port = 9095;
http_listen_address = "0.0.0.0";
http_listen_port = servicePort;
log_level = "warn";
};
store_gateway.sharding_ring = {
instance_addr = "127.0.0.1";
replication_factor = 1;
};
};
};
environment.persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [
{
directory = serviceDir;
mode = "0700";
}
];
};
networking.firewall.allowedTCPPorts = [ servicePort ];
systemd.services.mimir = {
environment = confLib.mkOtelEnvironment serviceName;
serviceConfig.RestartSec = lib.mkForce "60";
};
nodes = lib.mkMerge [
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
serviceAddress
serviceDomain
serviceName
servicePort
;
extraConfig = wgProxyAccessRules;
maxBody = 0;
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit serviceDomain serviceName servicePort;
extraConfig = nginxAccessRules;
maxBody = 0;
serviceAddress = homeServiceAddress;
}
);
}
{
${globals.general.monitoringServer}.services.grafana.provision = {
alerting.rules.settings.groups = [
{
folder = "Infrastructure";
interval = "1m";
name = "mimir";
orgId = 1;
rules = [
(confLib.mkGrafanaAlertRule {
expr = "max by (host) (up) or max by (host) (host_expected * 0)";
summary = "{{ $labels.host }} stopped reporting";
title = "Host down";
uid = "host_down";
})
(confLib.mkGrafanaAlertRule {
expr = ''max by (host, mountpoint) (100 * (node_filesystem_size_bytes{fstype!~"tmpfs|.*tmpfs|overlay|virtiofs|zfs"} - node_filesystem_free_bytes) / (node_filesystem_size_bytes - node_filesystem_free_bytes + node_filesystem_avail_bytes))'';
forDuration = "10m";
op = "gt";
severity = "warning";
summary = "{{ $labels.host }}:{{ $labels.mountpoint }} is more than 80% full";
threshold = 80;
title = "Disk above 80% used";
uid = "disk_filling";
})
(confLib.mkGrafanaAlertRule {
expr = "max by (host, device) (node_btrfs_device_errors_total)";
op = "gt";
summary = "{{ $labels.host }}: btrfs device {{ $labels.device }} has recorded I/O or checksum errors";
threshold = 0;
title = "btrfs device errors";
uid = "btrfs_device_errors";
})
(confLib.mkGrafanaAlertRule {
expr = "min by (host, job) (up)";
summary = "{{ $labels.host }}: scrape job {{ $labels.job }} is down";
title = "Scrape target down";
uid = "scrape_target_down";
})
(confLib.mkGrafanaAlertRule {
expr = ''min by (check) (node_systemd_unit_state{state="active"} * on(host, name) group_left(check) unit_expected{oneshot="false"} or (1 - node_systemd_unit_state{state="failed"}) * on(host, name) group_left(check) unit_expected{oneshot="true"}) or on(check) (max by (check) (unit_expected) * 0)'';
summary = "systemd unit for {{ $labels.check }} is not active or has failed";
title = "Systemd unit unhealthy";
uid = "systemd_unit_unhealthy";
})
];
}
];
datasources.settings.datasources = [
{
access = "proxy";
isDefault = true;
jsonData = {
cacheLevel = "High";
httpMethod = "POST";
incrementalQueryOverlapWindow = "10m";
manageAlerts = true;
prometheusType = "Mimir";
};
name = "Mimir";
type = "prometheus";
uid = "mimir";
url = confLib.mkAlloyPushUrl {
domain = serviceDomain;
host = globals.general.monitoringServer;
path = "/prometheus";
port = servicePort;
};
}
];
};
}
(lib.genAttrs (lib.attrNames globals.services.alloy.extraConfig.clients) (
alloyHost:
let
isCentral = alloyHost == globals.general.monitoringServer;
units = lib.catAttrs "unit" (
lib.filter (check: check.host == alloyHost) (lib.attrValues globals.monitoring.systemd)
);
in
{
environment.etc = {
"alloy/config.alloy".text = lib.mkAfter ''
prometheus.exporter.unix "node" {${
lib.optionalString (units != [ ]) ''
enable_collectors = ["systemd"]
systemd {
unit_include = ${builtins.toJSON "(${lib.concatMapStringsSep "|" lib.escapeRegex units})"}
}
''
}${lib.optionalString isCentral ''
textfile {
directory = "/etc/alloy/textfiles"
}
''}}
prometheus.scrape "node" {
targets = prometheus.exporter.unix.node.targets
forward_to = [prometheus.remote_write.mimir.receiver]
job_name = "node"
}
prometheus.remote_write "mimir" {
endpoint {
url = "${
confLib.mkAlloyPushUrl {
domain = serviceDomain;
host = alloyHost;
path = "/api/v1/push";
port = servicePort;
}
}"
}
external_labels = {
host = "${alloyHost}",
}
}
'';
"alloy/textfiles/host_expected.prom" = lib.mkIf isCentral {
text = lib.concatMapStrings (host: ''
host_expected{host="${host}"} 1
'') (lib.attrNames globals.hosts);
};
"alloy/textfiles/probe_expected.prom" = lib.mkIf isCentral {
text = lib.concatMapStrings (
kind:
lib.concatMapStrings (name: ''
probe_expected{name="${name}",probe="${kind}"} 1
'') (lib.attrNames globals.monitoring.${kind})
) confLib.static.probeKinds;
};
"alloy/textfiles/unit_expected.prom" = lib.mkIf isCentral {
text = lib.concatStrings (
lib.mapAttrsToList (check: cfg: ''
unit_expected{check="${check}",host="${cfg.host}",name="${cfg.unit}",oneshot="${lib.boolToString cfg.oneshot}"} 1
'') globals.monitoring.systemd
);
};
};
}
))
];
};
};
}
4.4.3.54. FreshRSS
FreshRSS is a more 'classical' RSS aggregator that I can just host as a distinct service. This also has its upsides because I have more control over the state this way.
It serves both a Greader API at https://${servicename}/api/greader.php, as well as a Fever API at https://${servicename}/api/fever.php.
I am using this with CapyReader on my phone, set it up as a FreshRSS account with Server URL =https://${servicename}/api/greader.php
FreshRSS claims to support HTTP header Auth, but at least it does not work with my oauth2-proxy setup. Until this is fixed, I resorted to the "form" login, since I mostly do not use the web version anyway.
{
flake.modules.nixos.freshrss =
{
self,
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
name = "freshrss";
port = 80;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceGroup
serviceName
servicePort
serviceUser
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
webProxy
;
in
{
imports = [
self.modules.nixos.nginx
];
config = {
swarselsystems.enabledServerModules = [ "freshrss" ];
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = "FreshRSS";
hostHeader = serviceDomain;
};
};
sops.secrets.freshrss-pw.owner = serviceUser;
users = {
users.${serviceUser} = {
extraGroups = [ "users" ];
group = serviceGroup;
isSystemUser = true;
};
groups.${serviceGroup} = { };
persistentIds.freshrss = confLib.mkIds 986;
};
services.${serviceName} = {
inherit (config.repo.secrets.local.freshrss) defaultUser;
enable = true;
authType = "form";
baseUrl = "https://${serviceDomain}";
dataDir = "/var/lib/freshrss";
passwordFile = config.sops.secrets.freshrss-pw.path;
virtualHost = serviceDomain;
};
environment.persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [
{
directory = "/var/lib/${serviceName}";
group = serviceGroup;
user = serviceUser;
}
];
};
nodes =
let
genNginx = toAddress: extraConfig: {
upstreams = {
${serviceName}.servers = {
"${toAddress}:${builtins.toString servicePort}" = { };
};
};
virtualHosts = {
"${serviceDomain}" = {
inherit extraConfig;
acmeRoot = null;
forceSSL = true;
locations = {
"/".proxyPass = "http://${serviceName}";
"/api" = {
bypassAuth = true;
proxyPass = "http://${serviceName}";
setOauth2Headers = false;
};
};
oauth2 = {
enable = true;
allowedGroups = [ "ttrss_access" ];
};
useACMEHost = globals.domains.main;
};
};
};
in
lib.mkMerge [
{
${idmServer} = confLib.mkKanidmOauth2ProxyAccess {
inherit serviceName;
proxyGroup = "ttrss_access";
};
}
{ ${webProxy}.services.nginx = genNginx serviceAddress ""; }
{ ${homeWebProxy}.services.nginx = lib.mkIf isHome (genNginx homeServiceAddress nginxAccessRules); }
];
};
};
}
4.4.3.55. Forgejo (git server)
My self-hosted git solution.
Appendix E: Current TODOs: federate
{
flake.modules.nixos.forgejo =
{
config,
lib,
pkgs,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
name = "forgejo";
port = 3004;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceGroup
serviceName
servicePort
serviceUser
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
notificationMail
webProxy
;
sshProxyPort = 2222;
sshListenPort = 2222;
in
{
config = {
swarselsystems.enabledServerModules = [ "forgejo" ];
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
extra = {
extraConfig.sshUrl = "ssh://${serviceUser}@${serviceDomain}:${toString sshProxyPort}";
firezoneTcpPorts = [ sshProxyPort ];
};
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = ''"status":\s*"pass"'';
failIfBodyMatchesRegex = ''"status":\s*"(fail|warn|inactive|unknown)"'';
path = "/api/healthz";
};
networks = confLib.mkDualFirewallRules {
tcpPorts = [
servicePort
sshListenPort
];
};
};
sops.secrets = {
kanidm-forgejo = {
group = serviceGroup;
mode = "0440";
owner = serviceUser;
rekey.keyPrefix = confLib.kanidmSecrets;
};
notification-mail-pw.rekey.keyPrefix = notificationMail.keyPrefix;
};
users = {
users.${serviceUser} = {
group = serviceGroup;
isSystemUser = true;
};
groups.${serviceGroup} = { };
persistentIds.forgejo = confLib.mkIds 985;
};
services.${serviceName} = {
enable = true;
group = serviceGroup;
lfs.enable = lib.mkDefault true;
secrets.mailer.PASSWD = config.sops.secrets.notification-mail-pw.path;
settings = {
DEFAULT.APP_NAME = config.repo.secrets.common.names.forgejo;
federation = {
ENABLED = true;
SHARE_USER_STATISTICS = false;
};
mailer = {
ENABLED = true;
FROM = "Forgejo <${notificationMail.address}>";
PROTOCOL = "smtp+starttls";
SMTP_ADDR = notificationMail.host;
SMTP_PORT = 587;
USER = notificationMail.address;
};
oauth2_client = {
# "auto" linking lets users take over accounts by setting a matching email
ACCOUNT_LINKING = "login";
# shows a dialog to adjust name and email before the account is created
ENABLE_AUTO_REGISTRATION = false;
REGISTER_EMAIL_CONFIRM = false;
UPDATE_AVATAR = true;
USERNAME = "nickname";
};
server = {
DOMAIN = serviceDomain;
HTTP_ADDR = "0.0.0.0";
HTTP_PORT = servicePort;
PROTOCOL = "http";
ROOT_URL = "https://${serviceDomain}";
SSH_DOMAIN = serviceDomain;
SSH_LISTEN_HOST = "0.0.0.0";
SSH_LISTEN_PORT = sshListenPort;
SSH_PORT = sshProxyPort;
START_SSH_SERVER = true;
};
service = {
ALLOW_ONLY_EXTERNAL_REGISTRATION = true;
ALLOW_ONLY_INTERNAL_REGISTRATION = false;
DISABLE_REGISTRATION = false;
ENABLE_NOTIFY_MAIL = true;
SHOW_REGISTRATION_BUTTON = false;
};
session.COOKIE_SECURE = true;
};
stateDir = "/var/lib/${serviceName}";
user = serviceUser;
};
environment.persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [
{
directory = "/var/lib/${serviceName}";
group = serviceGroup;
user = serviceUser;
}
];
};
systemd.services.${serviceName} = {
preStart =
let
exe = lib.getExe config.services.forgejo.package;
providerName = "kanidm";
clientId = serviceName;
args = lib.escapeShellArgs (
lib.concatLists [
[
"--name"
providerName
]
[
"--provider"
"openidConnect"
]
[
"--key"
clientId
]
[
"--auto-discover-url"
"https://${globals.services.kanidm.domain}/oauth2/openid/${clientId}/.well-known/openid-configuration"
]
[
"--scopes"
"email"
]
[
"--scopes"
"profile"
]
[
"--group-claim-name"
"groups"
]
[
"--admin-group"
"admin"
]
[ "--skip-local-2fa" ]
]
);
in
lib.mkAfter ''
provider_id=$(${exe} admin auth list | ${pkgs.gnugrep}/bin/grep -w '${providerName}' | cut -f1)
SECRET="$(< ${config.sops.secrets.kanidm-forgejo.path})"
if [[ -z "$provider_id" ]]; then
${exe} admin auth add-oauth ${args} --secret "$SECRET"
else
${exe} admin auth update-oauth --id "$provider_id" ${args} --secret "$SECRET"
fi
'';
serviceConfig.RestartSec = "60";
};
nodes =
let
mkSshProxy =
{
address,
extraConfig ? "",
}:
{
services.nginx.streamConfig = ''
server {
listen ${toString sshProxyPort};
listen [::]:${toString sshProxyPort};
proxy_pass ${address}:${toString sshListenPort};
${extraConfig}
}
'';
networking.nftables.firewall.rules.forgejo-ssh-to-local = {
allowedTCPPorts = [ sshProxyPort ];
from = [ "untrusted" ];
to = [ "local" ];
};
};
in
lib.mkMerge [
{
${idmServer} =
lib.recursiveUpdate
(confLib.mkKanidmOidcSystem {
inherit serviceDomain serviceName;
extraGroups = [ "forgejo.admins" ];
originUrl = "https://${serviceDomain}/user/oauth2/kanidm/callback";
})
{
services.kanidm.provision.systems.oauth2.forgejo = {
# required because of https://github.com/go-gitea/gitea/issues/21376
allowInsecureClientDisablePkce = true;
claimMaps.groups = {
joinType = "array";
valuesByGroup."forgejo.admins" = [ "admin" ];
};
};
};
}
{
${webProxy} = lib.mkMerge [
{
services.nginx = confLib.genNginx {
inherit
serviceAddress
serviceDomain
serviceName
servicePort
;
maxBody = 0;
};
}
(mkSshProxy { address = serviceAddress; })
];
}
{
${homeWebProxy} = lib.mkIf isHome (
lib.mkMerge [
{
services.nginx = confLib.genNginx {
inherit serviceDomain serviceName servicePort;
extraConfig = nginxAccessRules;
maxBody = 0;
serviceAddress = homeServiceAddress;
};
}
(mkSshProxy {
address = homeServiceAddress;
extraConfig = nginxAccessRules;
})
]
);
}
];
};
};
}
4.4.3.56. Anki Sync Server
I am an extensive user of Anki, and this allows me to sync my collection on my own.
{
flake.modules.nixos.ankisync =
{
root,
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
name = "ankisync";
port = 27701;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
servicePort
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
isHome
nginxAccessRules
webProxy
;
in
{
config = {
swarselsystems.enabledServerModules = [ "ankisync" ];
topology.self.services.anki = {
icon = lib.mkForce (root "files/topology-images/${serviceName}.png");
info = "https://${serviceDomain}";
name = lib.mkForce "Anki Sync Server";
};
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
extra.hasWebInterface = false;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedStatus = 404;
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops.secrets.anki-pw.owner = "root";
services.anki-sync-server = {
users = [
{
passwordFile = config.sops.secrets.anki-pw.path;
username = globals.user.name;
}
];
enable = true;
address = "0.0.0.0";
port = servicePort;
};
environment.persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [ { directory = "/var/lib/private/anki-sync-server"; } ];
};
nodes = lib.mkMerge [
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
serviceAddress
serviceDomain
serviceName
servicePort
;
maxBody = 0;
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit serviceDomain serviceName servicePort;
extraConfig = nginxAccessRules;
maxBody = 0;
serviceAddress = homeServiceAddress;
}
);
}
];
};
};
}
4.4.3.57. kanidm
The Forgejo configuration is a little broken and will show a 500 error when signing in through kanidm. However, when pressing back and refreshing the page, I am logged in. Currently I cannot be bothered to fix this.
A stupid (but simple) way to get the originUrl is to simply set any URL there and try to Auth using kanidm. Then check the logs (journalctl -eu kanidm) and check for the line that says something along the lines of
`🚧 [warn]: Invalid OAuth2 redirecturi (must be an exact match to a redirect-url) - got <your =originURL=>`
To get other URLs (token, etc.), use https://<kanidmdomain>/oauth2/openid/%3CclientID%3E/.well-known/oauth-authorization-server, e.g. https://<kanidmdomain>/oauth2/openid/nextcloud/.well-known/oauth-authorization-server, with clientId being the client name as specified in kanidm.
Create user:
kanidm login -D idmadmin
kanidm person credential create-reset-token <user>
{
flake.modules.nixos.kanidm =
{
config,
lib,
pkgs,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
name = "kanidm";
port = 8300;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceGroup
serviceName
servicePort
serviceUser
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
isHome
nginxAccessRules
notificationMail
webProxy
;
inherit (globals.services.alloy.extraConfig) otlpGrpcPort;
certBase = "/etc/ssl";
certsDir = "${certBase}/certs";
privateDir = "${certBase}/private";
certPathBase = "${certsDir}/${serviceName}.crt";
persistPrefix = lib.optionalString config.swarselsystems.isImpermanence "/persist";
certPath = persistPrefix + certPathBase;
keyPathBase = "${privateDir}/${serviceName}.key";
keyPath = persistPrefix + keyPathBase;
mailSenderUnit = "${serviceName}-mail-sender";
hasMailserver = globals.services ? mailserver;
in
{
config = {
swarselsystems.enabledServerModules = [ "kanidm" ];
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
general.idmServer = config.node.name;
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = "true";
path = "/status";
scheme = "https";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops = {
secrets = {
kanidm-admin-pw = {
group = serviceGroup;
mode = "0440";
owner = serviceUser;
};
kanidm-idm-admin-pw = {
group = serviceGroup;
mode = "0440";
owner = serviceUser;
};
kanidm-mail-sender-token = lib.mkIf hasMailserver { };
kanidm-self-signed-crt = {
group = serviceGroup;
mode = "0440";
owner = serviceUser;
};
kanidm-self-signed-key = {
group = serviceGroup;
mode = "0440";
owner = serviceUser;
};
notification-mail-pw = lib.mkIf hasMailserver { rekey.keyPrefix = notificationMail.keyPrefix; };
};
templates."${mailSenderUnit}.toml" = lib.mkIf hasMailserver {
content = ''
token = "${config.sops.placeholder.kanidm-mail-sender-token}"
instance_display_name = "Kanidm"
instance_url = "https://${serviceDomain}"
mail_from_address = "${notificationMail.address}"
mail_reply_to_address = "${notificationMail.address}"
mail_relay = "smtp://${notificationMail.host}:587"
mail_username = "${notificationMail.address}"
mail_password = "${config.sops.placeholder.notification-mail-pw}"
'';
restartUnits = [ "${mailSenderUnit}.service" ];
};
};
users = {
users.${serviceUser} = {
group = serviceGroup;
isSystemUser = true;
};
groups.${serviceGroup} = { };
persistentIds.kanidm = confLib.mkIds 984;
};
services = {
${serviceName} = {
package = pkgs.kanidmWithSecretProvisioning_1_11;
client = {
enable = true;
settings = {
uri = config.services.kanidm.server.settings.origin;
verify_ca = true;
verify_hostnames = true;
};
};
provision = {
# oauth2 systems config is in the respective modules
inherit (config.repo.secrets.local) persons;
enable = true;
adminPasswordFile = config.sops.secrets.kanidm-admin-pw.path;
idmAdminPasswordFile = config.sops.secrets.kanidm-idm-admin-pw.path;
};
server = {
enable = true;
settings = {
bindaddress = "0.0.0.0:${toString servicePort}";
domain = serviceDomain;
origin = "https://${serviceDomain}";
otel_grpc_endpoint = "http://127.0.0.1:${toString otlpGrpcPort}";
tls_chain = certPathBase;
tls_key = keyPathBase;
};
};
};
};
environment.persistence = {
"/persist" = lib.mkIf config.swarselsystems.isImpermanence {
files = [
certPathBase
keyPathBase
];
};
"/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [
{
directory = "/var/lib/${serviceName}";
group = serviceGroup;
user = serviceUser;
}
];
};
};
systemd.services = {
${mailSenderUnit} = lib.mkIf hasMailserver {
after = [
"${serviceName}.service"
"network-online.target"
];
description = "Deliver queued Kanidm messages via SMTP";
serviceConfig = {
DynamicUser = true;
ExecStart = "${lib.getExe' config.services.kanidm.package "kanidm-mail-sender"} -m \${CREDENTIALS_DIRECTORY}/config";
LoadCredential = "config:${config.sops.templates."${mailSenderUnit}.toml".path}";
Restart = "on-failure";
RestartSec = "30";
};
wantedBy = [ "multi-user.target" ];
wants = [ "network-online.target" ];
};
"generateSSLCert-${serviceName}" = {
after = [ "local-fs.target" ];
before = [ "${serviceName}.service" ];
path = [ pkgs.openssl ];
requiredBy = [ "${serviceName}.service" ];
requires = [ "local-fs.target" ];
script = ''
install -d -m 0755 ${certsDir} ${privateDir}
''
+ lib.optionalString config.swarselsystems.isImpermanence ''
install -d -m 0755 /persist${certsDir}
install -d -m 0750 /persist${privateDir}
''
+ ''
if [ ! -f ${keyPath} ] || ! openssl x509 -checkend ${toString (365 * 86400)} -noout -in ${certPath}; then
openssl req -x509 -nodes -days 3650 -newkey rsa:4096 -sha256 \
-keyout ${keyPath} \
-out ${certPath} \
-subj "/CN=${serviceDomain}" \
-addext "subjectAltName=DNS:${serviceDomain}"
chmod 0644 ${certPath}
chmod 0600 ${keyPath}
chown ${serviceUser}:${serviceGroup} ${certPath} ${keyPath}
fi
'';
serviceConfig.Type = "oneshot";
};
kanidm = {
environment = {
KANIDM_TRUST_X_FORWARD_FOR = "true";
OTEL_SERVICE_NAME = "kanidm-${config.node.name}";
};
serviceConfig.RestartSec = "30";
};
};
nodes =
let
extraConfig = ''
allow ${globals.networks.home-lan.vlans.services.cidrv4};
allow ${globals.networks.home-lan.vlans.services.cidrv6};
'';
in
lib.mkMerge [
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
serviceAddress
serviceDomain
serviceName
servicePort
;
noSslVerify = true;
protocol = "https";
};
}
{
${homeWebProxy}.services.nginx = confLib.genNginx {
inherit serviceDomain serviceName servicePort;
extraConfig = extraConfig + nginxAccessRules;
noSslVerify = true;
protocol = "https";
serviceAddress = homeServiceAddress;
};
}
];
};
};
}
4.4.3.58. oauth2-proxy
This can be used to add OIDC in a way to services that do not support it natively, by tacking it onto the corresponding NGINX service config. In here, it is enabled by setting the oauth2.enable option on the respective virtualHost.
Appendix E: Current TODOs: UNIX socket has upstream permission issues
{
flake.modules.nixos.oauth2-proxy =
{
config,
lib,
pkgs,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
name = "oauth2-proxy";
port = 3004;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceGroup
serviceName
servicePort
serviceUser
;
inherit (confLib.static)
homeProxy
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
oauthServer
webProxy
;
mainDomain = globals.domains.main;
kanidmDomain = globals.services.kanidm.domain;
homeProxyWan4 = globals.hosts.${homeProxy}.wanAddress4 or null;
homeProxyWan6 = globals.hosts.${homeProxy}.wanAddress6 or null;
in
{
options = {
# largely based on https://github.com/oddlama/nix-config/blob/main/modules/oauth2-proxy.nix
services.nginx.virtualHosts = lib.mkOption {
type = lib.types.attrsOf (
lib.types.submodule (
{ config, ... }:
{
options = {
locations = lib.mkOption {
type = lib.types.attrsOf (
lib.types.submodule (locationSubmodule: {
options = {
bypassAuth = lib.mkOption {
default = false;
description = "Whether to set auth_request off for this location. Only takes effect is oauth2 is actually enabled on the parent vhost.";
type = lib.types.bool;
};
setOauth2Headers = lib.mkOption {
default = true;
description = "Whether to add oauth2 headers to this location. Only takes effect is oauth2 is actually enabled on the parent vhost.";
type = lib.types.bool;
};
};
config = lib.mkIf config.oauth2.enable {
extraConfig =
lib.optionalString locationSubmodule.config.setOauth2Headers ''
proxy_set_header X-User $user;
proxy_set_header Remote-User $user;
proxy_set_header X-Remote-User $user;
proxy_set_header X-Email $email;
# proxy_set_header X-Access-Token $token;
add_header Set-Cookie $auth_cookie;
''
+ lib.optionalString locationSubmodule.config.bypassAuth ''
auth_request off;
'';
};
})
);
};
oauth2 = {
enable = lib.mkEnableOption "access protection of this virtualHost using oauth2-proxy.";
X-Access-Token = lib.mkOption {
default = "$upstream_http_x_auth_request_access_token";
description = "The variable to set as X-Access-Token";
type = lib.types.str;
};
X-Email = lib.mkOption {
default = "$upstream_http_x_auth_request_email";
description = "The variable to set as X-Email";
type = lib.types.str;
};
X-User = lib.mkOption {
default = "$upstream_http_x_auth_request_user";
description = "The variable to set as X-User";
type = lib.types.str;
};
allowedGroups = lib.mkOption {
default = [ ];
description = ''
A list of kanidm groups that are allowed to access this resource, or the
empty list to allow any authenticated client.
'';
type = lib.types.listOf lib.types.str;
};
};
};
config = lib.mkIf config.oauth2.enable {
extraConfig = ''
auth_request /oauth2/auth;
error_page 401 = /oauth2/sign_in;
# set variables that can be used in locations.<name>.extraConfig
# pass information via X-User and X-Email headers to backend,
# requires running with --set-xauthrequest flag
auth_request_set $user ${config.oauth2.X-User};
auth_request_set $email ${config.oauth2.X-Email};
# if you enabled --pass-access-token, this will pass the token to the backend
# auth_request_set $token ${config.oauth2.X-Access-Token};
# if you enabled --cookie-refresh, this is needed for it to work with auth_request
auth_request_set $auth_cookie $upstream_http_set_cookie;
'';
locations = {
"/oauth2/" = {
bypassAuth = true;
extraConfig = ''
proxy_set_header X-Scheme $scheme;
proxy_set_header X-Auth-Request-Redirect $scheme://$host$request_uri;
'';
proxyPass = "http://oauth2-proxy";
setOauth2Headers = false;
};
"= /oauth2/auth" = {
bypassAuth = true;
extraConfig = ''
internal;
proxy_set_header X-Scheme $scheme;
# nginx auth_request includes headers but not body
proxy_set_header Content-Length "";
proxy_pass_request_body off;
'';
proxyPass =
"http://oauth2-proxy/oauth2/auth"
+ lib.optionalString (
config.oauth2.allowedGroups != [ ]
) "?allowed_groups=${lib.concatStringsSep "," config.oauth2.allowedGroups}";
setOauth2Headers = false;
};
};
};
}
)
);
};
};
config = lib.mkIf (builtins.elem "oauthServer" config.swarselsystems.nodeRoles) {
swarselsystems.enabledServerModules = [ "oauth2-proxy" ];
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
extra.hasWebInterface = false;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = "OK";
path = "/ready";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops = {
secrets = {
kanidm-oauth2-proxy = {
group = serviceGroup;
mode = "0440";
owner = serviceUser;
rekey.keyPrefix = confLib.kanidmSecrets;
};
oauth2-cookie-secret = {
group = serviceGroup;
mode = "0440";
owner = serviceUser;
rekey.generator.script = "base64url";
};
};
templates.kanidm-oauth2-proxy-client-env = {
content = ''
OAUTH2_PROXY_CLIENT_SECRET="${config.sops.placeholder.kanidm-oauth2-proxy}"
OAUTH2_PROXY_COOKIE_SECRET=${config.sops.placeholder.oauth2-cookie-secret}
'';
group = serviceGroup;
mode = "0440";
owner = serviceUser;
};
};
users.persistentIds.oauth2-proxy = confLib.mkIds 966;
services = {
${serviceName} = {
enable = true;
package = pkgs.oauth2-proxy;
clientID = serviceName;
clientSecretFile = null;
cookie = {
domain = ".${mainDomain}";
expire = "900m";
secretFile = null;
secure = true;
};
email.domains = [ "*" ];
extraConfig = {
code-challenge-method = "S256";
oidc-issuer-url = "https://${kanidmDomain}/oauth2/openid/oauth2-proxy";
pass-access-token = true;
provider-display-name = "Kanidm";
set-authorization-header = true;
skip-jwt-bearer-tokens = true;
whitelist-domain = ".${mainDomain}";
};
httpAddress = "0.0.0.0:${builtins.toString servicePort}";
loginURL = "https://${kanidmDomain}/ui/oauth2";
provider = "oidc";
redeemURL = "https://${kanidmDomain}/oauth2/token";
redirectURL = "https://${serviceDomain}/oauth2/callback";
reverseProxy = true;
scope = "openid email";
setXauthrequest = true;
trustedProxyIP = [
"127.0.0.1"
"::1"
]
++ lib.optional (homeProxyWan4 != null) homeProxyWan4
++ lib.optional (homeProxyWan6 != null) homeProxyWan6;
upstream = [
"static://202"
];
validateURL = "https://${kanidmDomain}/oauth2/openid/oauth2-proxy/userinfo";
};
};
# needed for homeWebProxy
networking.firewall.allowedTCPPorts = [ servicePort ];
systemd.services = {
${serviceName}.serviceConfig = {
EnvironmentFile = [
config.sops.templates.kanidm-oauth2-proxy-client-env.path
];
RestartSec = "60";
RuntimeDirectory = serviceName;
RuntimeDirectoryMode = "0750";
UMask = "007"; # TODO remove once https://github.com/oauth2-proxy/oauth2-proxy/issues/2141 is fixed
};
};
nodes =
let
extraConfig = ''
proxy_set_header X-Scheme $scheme;
proxy_set_header X-Auth-Request-Redirect $scheme://$host$request_uri;
allow ${globals.networks.home-lan.vlans.services.cidrv4};
allow ${globals.networks.home-lan.vlans.services.cidrv6};
'';
in
lib.mkMerge [
{
${idmServer} = {
sops.secrets.kanidm-oauth2-proxy = {
group = "kanidm";
mode = "0440";
owner = "kanidm";
rekey = {
generator.script = "alnum";
keyPrefix = confLib.kanidmSecrets;
};
};
services.kanidm.provision.systems.oauth2.oauth2-proxy = {
basicSecretFile = config.sops.secrets.kanidm-oauth2-proxy.path; # dirty but saves a cross-evaluation
claimMaps.groups.joinType = "array";
displayName = "Oauth2-Proxy";
originLanding = "https://${serviceDomain}/";
originUrl = "https://${serviceDomain}/oauth2/callback";
preferShortUsername = true;
};
};
}
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
extraConfig
serviceAddress
serviceDomain
serviceName
servicePort
;
};
}
{
${homeWebProxy}.services.nginx = confLib.genNginx {
inherit serviceDomain serviceName servicePort;
extraConfig = extraConfig + nginxAccessRules;
serviceAddress = globals.hosts.${oauthServer}.wanAddress4;
};
}
];
};
};
}
4.4.3.59. Firefly-III
My expenses tracker.
{
flake.modules.nixos.firefly-iii =
{
self,
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
name = "firefly-iii";
port = 80;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceGroup
serviceName
servicePort
serviceUser
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
notificationMail
webProxy
;
in
{
imports = [
self.modules.nixos.nginx
];
config = {
swarselsystems.enabledServerModules = [ "firefly-iii" ];
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = "OK";
hostHeader = serviceDomain;
path = "/health";
};
};
sops.secrets = {
firefly-iii-app-key = {
group = config.services.nginx.group;
mode = "0440";
owner = serviceUser;
rekey.generator = {
args.length = 32;
script = "alnum";
};
};
notification-mail-pw = {
group = config.services.nginx.group;
mode = "0440";
owner = serviceUser;
rekey.keyPrefix = notificationMail.keyPrefix;
};
};
users = {
users.${serviceUser} = {
extraGroups = [ config.services.nginx.group ];
group = lib.mkForce serviceGroup;
isSystemUser = true;
};
groups.${serviceGroup} = { };
persistentIds.firefly-iii = confLib.mkIds 983;
};
services = {
${serviceName} = {
enable = true;
dataDir = "/var/lib/${serviceName}";
enableNginx = true;
group = config.services.nginx.group;
settings = {
APP_ENV = "local";
APP_KEY_FILE = config.sops.secrets.firefly-iii-app-key.path;
APP_URL = "https://${serviceDomain}";
DB_CONNECTION = "sqlite";
MAIL_FROM = notificationMail.address;
MAIL_HOST = notificationMail.host;
MAIL_MAILER = "smtp";
MAIL_PASSWORD_FILE = config.sops.secrets.notification-mail-pw.path;
MAIL_PORT = 587;
MAIL_USERNAME = notificationMail.address;
TRUSTED_PROXIES = "**";
TZ = config.repo.secrets.common.location.timezone;
# turning these on breaks api access using the waterfly app
# AUTHENTICATION_GUARD = "remote_user_guard";
# AUTHENTICATION_GUARD_HEADER = "X-User";
# AUTHENTICATION_GUARD_EMAIL = "X-Email";
};
user = serviceUser;
virtualHost = serviceDomain;
};
nginx.virtualHosts = {
"${serviceDomain}".locations."/api" = {
# setOauth2Headers = false;
extraConfig = ''
index index.php;
try_files $uri $uri/ /index.php?$query_string;
add_header Access-Control-Allow-Methods 'GET, POST, HEAD, OPTIONS';
'';
};
};
};
environment.persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [
{
directory = "/var/lib/${serviceName}";
group = serviceGroup;
user = serviceUser;
}
];
};
nodes =
let
genNginx = toAddress: extraConfig: {
upstreams = {
${serviceName}.servers = {
"${toAddress}:${builtins.toString servicePort}" = { };
};
};
virtualHosts = {
"${serviceDomain}" = {
inherit extraConfig;
acmeRoot = null;
forceSSL = true;
locations = {
"/".proxyPass = "http://${serviceName}";
"/api" = {
bypassAuth = true;
proxyPass = "http://${serviceName}";
setOauth2Headers = false;
};
};
oauth2 = {
enable = true;
allowedGroups = [ "firefly_access" ];
};
useACMEHost = globals.domains.main;
};
};
};
in
lib.mkMerge [
{
${idmServer} = confLib.mkKanidmOauth2ProxyAccess {
proxyGroup = "firefly_access";
serviceName = "firefly";
};
}
{ ${webProxy}.services.nginx = genNginx serviceAddress ""; }
{ ${homeWebProxy}.services.nginx = lib.mkIf isHome (genNginx homeServiceAddress nginxAccessRules); }
];
};
};
}
4.4.3.60. Koillection (use db)
My collection tracker. I am not too happy with its GUI, but the API is good, and I mostly use it to check what I have manually anyway.
{
flake.modules.nixos.koillection =
{
self,
root,
config,
lib,
confLib,
...
}:
let
inherit
(confLib.gen {
dir = "/var/lib/koillection";
name = "koillection";
port = 2282;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDir
serviceDomain
serviceName
servicePort
serviceUser
topologyContainerName
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
isHome
nginxAccessRules
webProxy
;
postgresUser = config.systemd.services.postgresql.serviceConfig.User;
postgresPort = config.services.postgresql.settings.port;
containerRev = "sha256:bb8ad2b6891441d8ec5c3169b684b71574f3bb3e9afb345bad2f91d833d60340";
in
{
imports = [
self.modules.nixos.postgresql
self.modules.nixos.podman
];
config = {
swarselsystems = {
enabledServerModules = [ "koillection" ];
server.postgresql.rolePasswordFiles.${serviceName} =
config.sops.secrets.koillection-db-password.path;
};
topology.nodes.${topologyContainerName}.services.${serviceName} = {
icon = root "files/topology-images/${serviceName}.png";
info = "https://${serviceDomain}";
name = lib.swarselsystems.toCapitalized serviceName;
};
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = "Koillection";
};
networks = confLib.mkDualFirewallRules {
tcpPorts = [
servicePort
postgresPort
];
};
};
sops.secrets = {
koillection-db-password = {
group = postgresUser;
mode = "0440";
owner = postgresUser;
rekey.generator.script = "alnum";
};
koillection-env-file = { };
};
services.postgresql = {
enable = true;
authentication = ''
host ${serviceName} ${serviceName} 10.88.0.0/16 scram-sha-256
'';
enableTCPIP = true;
ensureDatabases = [ serviceName ];
ensureUsers = [
{
ensureDBOwnership = true;
name = serviceName;
}
];
};
environment.persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [ { directory = "/var/lib/${serviceName}"; } ];
};
virtualisation.oci-containers.containers.koillection = {
environment = {
APP_DEBUG = "0";
APP_ENV = "prod";
CORS_ALLOW_ORIGIN = "https?://(localhost|${lib.escapeRegex serviceDomain})(:[0-9]+)?$";
DB_DRIVER = "pdo_pgsql";
DB_HOST = "host.docker.internal";
DB_NAME = serviceName;
# DB_PASSWORD set in koillection-env-file
DB_PORT = "${toString postgresPort}";
DB_USER = serviceUser;
DB_VERSION = "16";
HTTPS_ENABLED = "1";
PHP_MEMORY_LIMIT = "512M";
PHP_TZ = config.repo.secrets.common.location.timezone;
UPLOAD_MAX_FILESIZE = "512M";
};
environmentFiles = [
config.sops.secrets.koillection-env-file.path
];
extraOptions = [
"--add-host=host.docker.internal:host-gateway"
];
image = "koillection/koillection@${containerRev}";
ports = [
"${toString servicePort}:80"
];
volumes = [
"${serviceDir}/uploads:/uploads"
];
};
nodes =
let
extraConfigLoc = ''
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
'';
in
lib.mkMerge [
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
extraConfigLoc
serviceAddress
serviceDomain
serviceName
servicePort
;
maxBody = 0;
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit
extraConfigLoc
serviceDomain
serviceName
servicePort
;
extraConfig = nginxAccessRules;
maxBody = 0;
serviceAddress = homeServiceAddress;
}
);
}
];
};
};
}
4.4.3.61. Atuin (use db)
Used to sync shell history across machines and have it backed up somewhere.
{
flake.modules = {
homeManager.atuin =
{ globals, ... }:
{
config = {
swarselsystems.enabledHomeModules = [ "atuin" ];
programs.atuin = {
enable = true;
enableBashIntegration = true;
enableZshIntegration = true;
settings = {
auto_sync = true;
sync_address = "https://${globals.services.atuin.domain}";
sync_frequency = "5m";
};
};
};
};
nixos.atuin =
{
self,
config,
lib,
confLib,
...
}:
let
inherit
(confLib.gen {
name = "atuin";
port = 8888;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
servicePort
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
isHome
nginxAccessRules
webProxy
;
in
{
imports = [
self.modules.nixos.postgresql
];
config = {
swarselsystems = {
enabledServerModules = [ "atuin" ];
server.postgresql.rolePasswordFiles.${serviceName} =
config.sops.secrets."${serviceName}-db-password".path;
};
topology.self.services.${serviceName}.info = "https://${serviceDomain}";
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
extra.hasWebInterface = false;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = ''"version":'';
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops = {
secrets."${serviceName}-db-password" = {
owner = config.systemd.services.postgresql.serviceConfig.User;
rekey.generator.script = "alnum";
};
templates."${serviceName}-env".content = ''
ATUIN_DB_URI=postgresql://${serviceName}:${
config.sops.placeholder."${serviceName}-db-password"
}@localhost/${serviceName}?host=/run/postgresql
'';
};
services.${serviceName} = {
enable = true;
database.uri = null;
environmentFile = config.sops.templates."${serviceName}-env".path;
host = "0.0.0.0";
openRegistration = false;
port = servicePort;
};
nodes = lib.mkMerge [
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
serviceAddress
serviceDomain
serviceName
servicePort
;
maxBody = 0;
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit serviceDomain serviceName servicePort;
extraConfig = nginxAccessRules;
maxBody = 0;
serviceAddress = homeServiceAddress;
}
);
}
];
};
};
};
}
4.4.3.62. Radicale
Self-hosted calendar and contacts.
{
flake.modules.nixos.radicale =
{
config,
lib,
confLib,
...
}:
let
inherit
(confLib.gen {
name = "radicale";
port = 8000;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceGroup
serviceName
servicePort
serviceUser
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
webProxy
;
cfg = config.services.${serviceName};
in
{
config = {
swarselsystems.enabledServerModules = [ "radicale" ];
topology.self.services.${serviceName}.info = "https://${serviceDomain}";
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = "Radicale Web Interface";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops = {
secrets.radicale-user = {
group = serviceGroup;
mode = "0440";
owner = serviceUser;
};
templates.radicale-users = {
content = ''
${config.repo.secrets.local.radicale.user1}:${config.sops.placeholder.radicale-user}
'';
group = serviceGroup;
mode = "0440";
owner = serviceUser;
};
};
users.persistentIds.radicale = confLib.mkIds 982;
services.${serviceName} = {
enable = true;
rights = {
calendars = {
collection = "{user}/[^/]+";
permissions = "rw";
user = ".+";
};
principal = {
collection = "{user}";
permissions = "RW";
user = ".+";
};
# all: match authenticated users only
root = {
collection = "";
permissions = "R";
user = ".+";
};
};
settings = {
auth = {
htpasswd_encryption = "autodetect";
htpasswd_filename = config.sops.templates.radicale-users.path;
type = "htpasswd";
};
server.hosts = [
"0.0.0.0:${builtins.toString servicePort}"
"[::]:${builtins.toString servicePort}"
];
storage.filesystem_folder = "/var/lib/radicale/collections";
};
};
environment.persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [
{
directory = "/var/lib/${serviceName}";
group = serviceGroup;
user = serviceUser;
}
];
};
systemd.tmpfiles.settings."10-radicale" = {
"${cfg.settings.storage.filesystem_folder}".d = {
group = serviceGroup;
mode = "0750";
user = serviceUser;
};
};
nodes = lib.mkMerge [
{
${idmServer} = confLib.mkKanidmOauth2ProxyAccess { inherit serviceName; };
}
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
serviceAddress
serviceDomain
serviceName
servicePort
;
maxBody = 16;
maxBodyUnit = "M";
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit serviceDomain serviceName servicePort;
extraConfig = nginxAccessRules;
maxBody = 16;
maxBodyUnit = "M";
serviceAddress = homeServiceAddress;
}
);
}
];
};
};
}
4.4.3.63. Croc
P2P file-sharing similar to what you might know from wormhole(/-rs), but fully self-hosted.
{
flake.modules.nixos.croc =
{
root,
config,
lib,
pkgs,
confLib,
...
}:
let
inherit
(confLib.gen {
name = "croc";
proxy = config.node.name;
})
proxyAddress4
proxyAddress6
serviceDomain
serviceName
;
inherit (confLib.static) isHome;
servicePorts = [
9009
9010
9011
9012
9013
];
cfg = config.services.croc;
in
{
config = {
swarselsystems.enabledServerModules = [ "croc" ];
topology.self.services.${serviceName} = {
icon = root "files/topology-images/${serviceName}.png";
info = "https://${serviceDomain}";
name = serviceName;
};
globals = {
services.${serviceName} = {
inherit isHome proxyAddress4 proxyAddress6;
domain = serviceDomain;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.tcp = confLib.mkTcpMonitoring {
inherit serviceName;
servicePort = lib.head servicePorts;
};
};
sops = {
secrets.croc-password = { };
templates.croc-env.content = ''
CROC_PASS="${config.sops.placeholder.croc-password}"
'';
};
services.${serviceName} = {
enable = true;
openFirewall = true;
pass = config.sops.secrets.croc-password.path;
ports = servicePorts;
};
systemd.services = {
${serviceName}.serviceConfig = {
EnvironmentFile = [
config.sops.templates.croc-env.path
];
ExecStart = lib.mkForce "${pkgs.croc}/bin/croc ${lib.optionalString cfg.debug "--debug"} relay --ports ${
lib.concatMapStringsSep "," toString cfg.ports
}";
};
};
# ports are opened on the firewall for croc, no nginx config
};
};
}
4.4.3.64. Microbin
Basically a self-hosted Pastebin that also offers syntax highlighting.
{
flake.modules.nixos.microbin =
{
root,
config,
lib,
confLib,
...
}:
let
inherit
(confLib.gen {
name = "microbin";
port = 8777;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceGroup
serviceName
servicePort
serviceUser
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
isHome
nginxAccessRules
webProxy
;
cfg = config.services.${serviceName};
in
{
config = {
swarselsystems.enabledServerModules = [ "microbin" ];
topology.self.services.${serviceName} = {
icon = root "files/topology-images/${serviceName}.png";
info = "https://${serviceDomain}";
name = lib.swarselsystems.toCapitalized serviceName;
};
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = "pasta-form";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops = {
secrets =
lib.genAttrs
[
"microbin-admin-password"
"microbin-admin-username"
"microbin-uploader-password"
]
(_: {
group = serviceGroup;
mode = "0440";
owner = serviceUser;
});
templates.microbin-env = {
content = ''
MICROBIN_ADMIN_USERNAME="${config.sops.placeholder.microbin-admin-username}"
MICROBIN_ADMIN_PASSWORD="${config.sops.placeholder.microbin-admin-password}"
MICROBIN_UPLOADER_PASSWORD="${config.sops.placeholder.microbin-uploader-password}"
'';
group = serviceGroup;
mode = "0440";
owner = serviceUser;
};
};
users = {
users.${serviceUser} = {
group = serviceGroup;
isSystemUser = true;
};
groups.${serviceGroup} = { };
persistentIds.${serviceName} = confLib.mkIds 964;
};
services.${serviceName} = {
enable = true;
dataDir = "/var/lib/microbin";
passwordFile = config.sops.templates.microbin-env.path;
settings = {
MICROBIN_BIND = "0.0.0.0";
MICROBIN_DEFAULT_EXPIRY = "1week";
MICROBIN_DISABLE_TELEMETRY = true;
MICROBIN_DISABLE_UPDATE_CHECKING = true;
MICROBIN_EDITABLE = true;
MICROBIN_ENABLE_BURN_AFTER = true;
MICROBIN_ENABLE_READONLY = true;
MICROBIN_ETERNAL_PASTA = true;
MICROBIN_GC_DAYS = 30;
MICROBIN_HIDE_FOOTER = true;
MICROBIN_HIDE_HEADER = true;
MICROBIN_HIDE_LOGO = true;
MICROBIN_HIGHLIGHTSYNTAX = true;
MICROBIN_LIST_SERVER = false;
MICROBIN_MAX_FILE_SIZE_ENCRYPTED_MB = 256;
MICROBIN_MAX_FILE_SIZE_UNENCRYPTED_MB = 1024;
MICROBIN_NO_FILE_UPLOAD = false;
MICROBIN_NO_LISTING = false;
MICROBIN_PORT = servicePort;
MICROBIN_PRIVATE = true;
MICROBIN_PUBLIC_PATH = "https://${serviceDomain}";
MICROBIN_QR = true;
MICROBIN_READONLY = true;
MICROBIN_SHOW_READ_STATS = true;
MICROBIN_THREADS = 1;
MICROBIN_TITLE = config.repo.secrets.common.names.microbin;
};
};
environment.persistence."/persist".directories = lib.mkIf config.swarselsystems.isImpermanence [
{
directory = cfg.dataDir;
group = serviceGroup;
mode = "0700";
user = serviceUser;
}
];
systemd.services = {
${serviceName}.serviceConfig = {
DynamicUser = lib.mkForce false;
Group = serviceGroup;
User = serviceUser;
};
};
nodes = lib.mkMerge [
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
serviceAddress
serviceDomain
serviceName
servicePort
;
maxBody = 1;
maxBodyUnit = "G";
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit serviceDomain serviceName servicePort;
extraConfig = nginxAccessRules;
maxBody = 1;
maxBodyUnit = "G";
serviceAddress = homeServiceAddress;
}
);
}
];
};
};
}
4.4.3.65. Shlink
Self-hosted link shortener.
{
flake.modules.nixos.shlink =
{
self,
root,
config,
lib,
confLib,
...
}:
let
inherit
(confLib.gen {
dir = "/var/lib/shlink";
name = "shlink";
port = 8081;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDir
serviceDomain
serviceName
servicePort
topologyContainerName
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
isHome
nginxAccessRules
scannerDropRules
webProxy
;
containerRev = "sha256:1a697baca56ab8821783e0ce53eb4fb22e51bb66749ec50581adc0cb6d031d7a";
in
{
imports = [
self.modules.nixos.podman
];
config = {
swarselsystems.enabledServerModules = [ "shlink" ];
topology.nodes.${topologyContainerName}.services.${serviceName} = {
icon = root "files/topology-images/${serviceName}.png";
info = "https://${serviceDomain}";
name = lib.swarselsystems.toCapitalized serviceName;
};
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = ''"status":"pass"'';
path = "/rest/health";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops = {
secrets.shlink-api = { };
templates.shlink-env.content = ''
INITIAL_API_KEY=${config.sops.placeholder.shlink-api}
'';
};
environment.persistence."/persist".directories = lib.mkIf config.swarselsystems.isImpermanence [
{ directory = serviceDir; }
];
virtualisation.oci-containers.containers.${serviceName} = {
environment = {
DEFAULT_DOMAIN = serviceDomain;
DEFAULT_SHORT_CODES_LENGTH = "4";
PORT = "${builtins.toString servicePort}";
TASK_WORKER_NUM = "1";
USE_HTTPS = "false";
WEB_WORKER_NUM = "1";
};
environmentFiles = [
config.sops.templates.shlink-env.path
];
extraOptions = [
''--health-cmd=wget -O - -q http://127.0.0.1:${builtins.toString servicePort}/rest/health | grep -q '"status":"pass"' ''
"--health-interval=30s"
"--health-retries=3"
"--health-timeout=10s"
"--health-start-period=60s"
"--health-on-failure=kill"
];
image = "shlinkio/shlink@${containerRev}";
ports = [ "${builtins.toString servicePort}:${builtins.toString servicePort}" ];
volumes = [
"${serviceDir}/data:/etc/shlink/data"
];
};
systemd.tmpfiles.settings."11-shlink" = builtins.listToAttrs (
map
(path: {
name = "${serviceDir}/${path}";
value.d = {
group = "root";
mode = "0750";
user = "1001";
};
})
[
"data"
"data/cache"
"data/locks"
"data/log"
"data/proxies"
]
);
nodes = lib.mkMerge [
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
serviceAddress
serviceDomain
serviceName
servicePort
;
extraConfig = scannerDropRules;
maxBody = 0;
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit serviceDomain serviceName servicePort;
extraConfig = scannerDropRules + nginxAccessRules;
maxBody = 0;
serviceAddress = homeServiceAddress;
}
);
}
];
};
};
}
4.4.3.66. slink
Image sharing service similar to imgur.
Deployment notes:
- enable user:
podman exec -it slink slink user:activate --email=<mail> - make user admin:
podman exec -it slink slink user:grant:role --email=<mail> ROLE_ADMIN - finally, disable new user registration in web UI
{
flake.modules.nixos.slink =
{
self,
root,
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
dir = "/var/lib/slink";
name = "slink";
port = 3000;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDir
serviceDomain
serviceName
servicePort
topologyContainerName
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
scannerDropRules
webProxy
;
containerRev = "sha256:98b9442696f0a8cbc92f0447f54fa4bad227af5dcfd6680545fedab2ed28ddd9";
in
{
imports = [
self.modules.nixos.podman
];
config = {
swarselsystems.enabledServerModules = [ "slink" ];
topology.nodes.${topologyContainerName}.services.${serviceName} = {
icon = root "files/topology-images/${serviceName}.png";
info = "https://${serviceDomain}";
name = lib.swarselsystems.toCapitalized serviceName;
};
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = "OK";
hostHeader = serviceDomain;
path = "/api/health";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
environment.persistence."/persist".directories = lib.mkIf config.swarselsystems.isImpermanence [
{ directory = serviceDir; }
];
virtualisation.oci-containers.containers.${serviceName} = {
environment = {
IMAGE_MAX_SIZE = "50M";
ORIGIN = "https://${serviceDomain}";
STORAGE_PROVIDER = "local";
TZ = config.repo.secrets.common.location.timezone;
USER_APPROVAL_REQUIRED = "true";
};
extraOptions = [
"--health-cmd=wget -O - -q http://127.0.0.1:${builtins.toString servicePort}/api/health | grep -q OK"
"--health-interval=30s"
"--health-retries=3"
"--health-timeout=10s"
"--health-start-period=60s"
"--health-on-failure=kill"
];
image = "anirdev/slink@${containerRev}";
ports = [ "${builtins.toString servicePort}:${builtins.toString servicePort}" ];
volumes = [
"${serviceDir}/var/data:/app/var/data"
"${serviceDir}/images:/app/slink/images"
];
};
systemd.tmpfiles.settings."12-slink" = builtins.listToAttrs (
map
(path: {
name = "${serviceDir}/${path}";
value.d = {
group = "root";
mode = "0750";
user = "root";
};
})
[
"var/data"
"images"
]
);
nodes =
let
genNginx = toAddress: extraConfig: {
upstreams = {
${serviceName}.servers = {
"${toAddress}:${builtins.toString servicePort}" = { };
};
};
virtualHosts = {
"${serviceDomain}" = {
inherit extraConfig;
acmeRoot = null;
forceSSL = true;
locations = {
"/".proxyPass = "http://${serviceName}";
"/image" = {
bypassAuth = true;
proxyPass = "http://${serviceName}";
setOauth2Headers = false;
};
};
oauth2 = {
enable = true;
allowedGroups = [ "slink_access" ];
};
useACMEHost = globals.domains.main;
};
};
};
in
lib.mkMerge [
{ ${idmServer} = confLib.mkKanidmOauth2ProxyAccess { inherit serviceName; }; }
{ ${webProxy}.services.nginx = genNginx serviceAddress scannerDropRules; }
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
genNginx homeServiceAddress (scannerDropRules + nginxAccessRules)
);
}
];
};
};
}
4.4.3.67. Readeck
I tried this and karakeep. Seems to me karakeep is more focused on forcing AI integration in, so I prefer this one.
{
flake.modules.nixos.readeck =
{
root,
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
dir = "/var/lib/private/readeck";
name = "readeck";
port = 8085;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDir
serviceDomain
serviceName
servicePort
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
notificationMail
webProxy
;
in
{
config = {
swarselsystems.enabledServerModules = [ "readeck" ];
topology.self.services.${serviceName} = {
icon = root "files/topology-images/${serviceName}.png";
info = "https://${serviceDomain}";
name = lib.swarselsystems.toCapitalized serviceName;
};
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = "Readeck";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops = {
secrets = {
kanidm-readeck.rekey.keyPrefix = confLib.kanidmSecrets;
notification-mail-pw.rekey.keyPrefix = notificationMail.keyPrefix;
readeck-secret-key.rekey.generator.script = "alnum";
};
templates.readeck-env.content = ''
READECK_AUTH_OIDC_PROVIDERS_0_CLIENT_SECRET=${config.sops.placeholder.kanidm-readeck}
READECK_MAIL_PASSWORD=${config.sops.placeholder.notification-mail-pw}
READECK_SECRET_KEY=${config.sops.placeholder.readeck-secret-key}
'';
};
services.${serviceName} = {
enable = true;
environmentFile = config.sops.templates.readeck-env.path;
settings = {
auth.oidc.providers = [
{
client_id = serviceName;
groups = [
[
"admin"
"admin"
]
[
"user"
"user"
]
];
name = "Kanidm";
provisioning = true;
url = "https://${globals.services.kanidm.domain}/oauth2/openid/${serviceName}";
}
];
email = {
inherit (notificationMail) host;
encryption = "starttls";
from = "Readeck <${notificationMail.address}>";
from_noreply = "Readeck <${notificationMail.address}>";
port = 587;
username = notificationMail.address;
};
main = {
data_directory = "/var/lib/${serviceName}/data";
log_format = "text";
};
server = {
host = "0.0.0.0";
port = servicePort;
};
};
};
environment.persistence."/persist".directories = lib.mkIf config.swarselsystems.isImpermanence [
{
directory = serviceDir;
mode = "0700";
}
];
nodes = lib.mkMerge [
{
${idmServer} =
lib.recursiveUpdate
(confLib.mkKanidmOidcSystem {
inherit serviceDomain serviceName;
extraGroups = [ "readeck.admins" ];
originUrl = "https://${serviceDomain}/login/oidc";
})
{
services.kanidm.provision.systems.oauth2.${serviceName}.claimMaps.groups = {
joinType = "array";
valuesByGroup = {
"readeck.access" = [ "user" ];
"readeck.admins" = [ "admin" ];
};
};
};
}
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
serviceAddress
serviceDomain
serviceName
servicePort
;
maxBody = 0;
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit serviceDomain serviceName servicePort;
extraConfig = nginxAccessRules;
maxBody = 0;
serviceAddress = homeServiceAddress;
}
);
}
];
};
};
}
4.4.3.68. Yubal
Self-hosted YouTube Music downloader that tags, organizes and keeps playlists in sync, I use this to directly download music and add it to Navidrome (it gets downloaded in a separate directory though). For general video downloads, see MeTube
{
flake.modules.nixos.yubal =
{
self,
root,
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
dir = "/var/lib/yubal";
name = "yubal";
port = 8086;
})
serviceDir
serviceDomain
serviceGroup
serviceName
servicePort
serviceUser
topologyContainerName
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
;
containerRev = "sha256:1447663d19eb69e4c6c6d274e979a99c4013a7d0a7666ca1bf2127612cd639eb";
containerPort = 8000;
musicDir = "/storage/Music/${serviceName}";
serviceId = 1003;
in
{
imports = [
self.modules.nixos.podman
];
config = {
swarselsystems.enabledServerModules = [ "yubal" ];
topology.nodes.${topologyContainerName}.services.${serviceName} = {
icon = root "files/topology-images/${serviceName}.png";
info = "https://${serviceDomain}";
name = lib.swarselsystems.toCapitalized serviceName;
};
globals = {
services.${serviceName} = {
inherit isHome;
domain = serviceDomain;
};
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = "yubal";
};
networks = confLib.mkDualFirewallRules {
forWebProxy = false;
tcpPorts = [ servicePort ];
};
};
users = {
users.${serviceUser} = {
extraGroups = [ "users" ];
group = serviceGroup;
isSystemUser = true;
};
groups.${serviceGroup} = { };
persistentIds.${serviceName} = confLib.mkIds serviceId;
};
environment.persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [
{
directory = serviceDir;
group = serviceGroup;
mode = "0750";
user = serviceUser;
}
];
};
virtualisation.oci-containers.containers.${serviceName} = {
environment = {
PGID = builtins.toString serviceId;
PUID = builtins.toString serviceId;
YUBAL_PORT = builtins.toString containerPort;
YUBAL_TZ = config.repo.secrets.common.location.timezone;
};
image = "ghcr.io/guillevc/yubal@${containerRev}";
ports = [ "${builtins.toString servicePort}:${builtins.toString containerPort}" ];
volumes = [
"${serviceDir}/config:/app/config"
"${musicDir}:/app/data"
];
};
systemd.services."podman-${serviceName}" = {
preStart = lib.mkAfter ''
install -d -o ${serviceUser} -g ${serviceGroup} -m 0750 ${serviceDir}/config
install -d -o ${serviceUser} -g users -m 2775 ${musicDir}
'';
unitConfig.RequiresMountsFor = [
serviceDir
musicDir
];
};
nodes = lib.mkMerge [
{ ${idmServer} = confLib.mkKanidmOauth2ProxyAccess { inherit serviceName; }; }
{
${homeWebProxy}.services.nginx = lib.mkIf isHome {
upstreams.${serviceName}.servers = {
"${homeServiceAddress}:${builtins.toString servicePort}" = { };
};
virtualHosts.${serviceDomain} = {
acmeRoot = null;
extraConfig = nginxAccessRules;
forceSSL = true;
locations = {
"/" = {
extraConfig = ''
client_max_body_size 0;
'';
proxyPass = "http://${serviceName}";
};
"/api" = {
bypassAuth = true;
proxyPass = "http://${serviceName}";
setOauth2Headers = false;
};
};
oauth2 = {
enable = true;
allowedGroups = [ "${serviceName}_access" ];
};
useACMEHost = globals.domains.main;
};
};
}
];
};
};
}
4.4.3.69. Collabora Online
Online office suite (WOPI server) using the native NixOS module, terminated behind nginx. The admin console credentials come from sops; Nextcloud is the allowed WOPI host.
{
flake.modules.nixos.collabora-online =
{
root,
config,
lib,
confLib,
...
}:
let
inherit
(confLib.gen {
name = "collabora-online";
port = 9980;
user = "cool";
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
servicePort
serviceUser
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
isHome
nginxAccessRules
webProxy
;
extraConfigLoc = ''
proxy_read_timeout 36000s;
'';
in
{
config = {
swarselsystems.enabledServerModules = [ "collabora-online" ];
topology.self.services.${serviceName} = {
icon = root "files/topology-images/${serviceName}.png";
info = "https://${serviceDomain}";
name = "Collabora Online";
};
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
extra = {
extraConfig = {
node = config.node.name;
port = servicePort;
};
hasWebInterface = false;
};
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = "wopi-discovery";
path = "/hosting/discovery";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops = {
secrets.collabora-admin-password = { };
templates.collabora-env.content = ''
username=admin
password=${config.sops.placeholder.collabora-admin-password}
'';
};
users.persistentIds.${serviceUser} = confLib.mkIds 1004;
services.${serviceName} = {
enable = true;
port = servicePort;
settings = {
server_name = serviceDomain;
ssl = {
enable = false;
termination = true;
};
};
};
systemd.services.coolwsd.serviceConfig.EnvironmentFile = config.sops.templates.collabora-env.path;
nodes = lib.mkMerge [
{
${webProxy}.services.nginx = lib.recursiveUpdate (confLib.genNginx {
inherit
extraConfigLoc
serviceAddress
serviceDomain
serviceName
servicePort
;
maxBody = 0;
proxyWebsockets = true;
}) { virtualHosts.${serviceDomain}.locations."/".recommendedSecurityHeaders = false; };
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
lib.recursiveUpdate (confLib.genNginx {
inherit
extraConfigLoc
serviceDomain
serviceName
servicePort
;
extraConfig = nginxAccessRules;
maxBody = 0;
proxyWebsockets = true;
serviceAddress = homeServiceAddress;
}) { virtualHosts.${serviceDomain}.locations."/".recommendedSecurityHeaders = false; }
);
}
];
};
};
}
4.4.3.70. Filestash
This is pretty much just used as the WOPI host for Collabora Online.
Collaborative editing of .odt files is a bit weird, as it requires creating the share link first and then opening the page through that share link. Otherwise some bug in Collabora will make it so that the live updates break. And also all editors are anonymous (oh well).
{
flake.modules.nixos.filestash =
{
self,
root,
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
dir = "/var/lib/filestash";
name = "filestash";
port = 8334;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDir
serviceDomain
serviceGroup
serviceName
servicePort
serviceUser
topologyContainerName
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
webProxy
;
inherit (config.swarselsystems) mainUser;
containerRev = "sha256:f595b7e8cffdad7105ad7a2fc5edad51b4de3f2b0ecf80d64d58bec3c246aab1";
containerUid = 1000;
serviceId = 1005;
storageLabel = "copyparty";
hostGateway = "host.docker.internal";
collaboraPort = globals.services.collabora-online.extraConfig.port;
copypartyPort = globals.services.copyparty.extraConfig.port;
in
{
imports = [
self.modules.nixos.podman
];
config = {
swarselsystems.enabledServerModules = [ "filestash" ];
topology.nodes.${topologyContainerName}.services.${serviceName} = {
icon = root "files/topology-images/${serviceName}.png";
info = "https://${serviceDomain}";
name = lib.swarselsystems.toCapitalized serviceName;
};
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = ''"status":\s*"pass"'';
path = "/healthz";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops = {
secrets = {
filestash-admin-hash = { };
filestash-secret-key.rekey.generator.script = "alnum";
};
templates.filestash-config.content = builtins.toJSON {
auth.admin = config.sops.placeholder.filestash-admin-hash;
connections = [
{
label = storageLabel;
type = "webdav";
}
];
features = {
office = {
enable = true;
filestash_server = "http://127.0.0.1:${builtins.toString servicePort}";
office_server = "http://${hostGateway}:${builtins.toString collaboraPort}";
rewrite_discovery_url = "https://${globals.services.collabora-online.domain}";
};
share.enable = true;
};
general = {
force_ssl = true;
host = serviceDomain;
logout = "https://${serviceDomain}/oauth2/sign_out";
secret_key = config.sops.placeholder.filestash-secret-key;
};
middleware = {
attribute_mapping = {
params = builtins.toJSON {
${storageLabel} = {
password = config.sops.placeholder.copyparty-password;
type = "webdav";
url = "http://${hostGateway}:${builtins.toString copypartyPort}";
username = mainUser;
};
};
related_backend = storageLabel;
};
identity_provider = {
params = builtins.toJSON {
strategy = "direct";
type = "passthrough";
};
type = "passthrough";
};
};
};
};
users = {
users.${serviceUser} = {
group = serviceGroup;
isSystemUser = true;
};
groups.${serviceGroup} = { };
persistentIds.${serviceName} = confLib.mkIds serviceId;
};
environment.persistence."/persist".directories = lib.mkIf config.swarselsystems.isImpermanence [
{
directory = serviceDir;
group = serviceGroup;
mode = "0750";
user = serviceUser;
}
];
networking.nftables.firewall.rules.podman-to-filestash-backends = {
allowedTCPPorts = [
collaboraPort
copypartyPort
];
before = [ "drop" ];
from = [ "podman" ];
to = [ "local" ];
};
virtualisation.oci-containers.containers.${serviceName} = {
environment.CONFIG_ENCRYPT = "false";
extraOptions = [
"--add-host=${hostGateway}:host-gateway"
"--gidmap=0:0:${builtins.toString containerUid}"
"--gidmap=${builtins.toString containerUid}:${builtins.toString serviceId}:1"
"--uidmap=0:0:${builtins.toString containerUid}"
"--uidmap=${builtins.toString containerUid}:${builtins.toString serviceId}:1"
];
image = "machines/filestash@${containerRev}";
ports = [ "${builtins.toString servicePort}:${builtins.toString servicePort}" ];
volumes = [ "${serviceDir}:/app/data/state" ];
};
systemd.services."podman-${serviceName}" = {
preStart = lib.mkAfter ''
install -d -o ${serviceUser} -g ${serviceGroup} -m 0750 ${serviceDir}/config
install -o ${serviceUser} -g ${serviceGroup} -m 0600 ${config.sops.templates.filestash-config.path} ${serviceDir}/config/config.json
'';
unitConfig.RequiresMountsFor = [ serviceDir ];
};
nodes =
let
genNginx = toAddress: extraConfig: {
upstreams = {
${serviceName}.servers = {
"${toAddress}:${builtins.toString servicePort}" = { };
};
};
virtualHosts = {
"${serviceDomain}" = {
inherit extraConfig;
acmeRoot = null;
forceSSL = true;
locations = {
"/" = {
X-Frame-Options = "SAMEORIGIN";
extraConfig = ''
client_max_body_size 0;
'';
proxyPass = "http://${serviceName}";
};
"/api/session/auth/" = {
X-Frame-Options = "SAMEORIGIN";
proxyPass = "http://${serviceName}";
};
}
//
lib.genAttrs
[
"/api/"
"/assets/"
"/overrides/"
"/s/"
]
(_: {
X-Frame-Options = "SAMEORIGIN";
bypassAuth = true;
extraConfig = ''
client_max_body_size 0;
'';
proxyPass = "http://${serviceName}";
setOauth2Headers = false;
});
oauth2 = {
enable = true;
allowedGroups = [ "${serviceName}_access" ];
};
useACMEHost = globals.domains.main;
};
};
};
in
lib.mkMerge [
{
${globals.services.collabora-online.extraConfig.node}.services.collabora-online = {
aliasGroups = [ { host = "http://127.0.0.1:${builtins.toString servicePort}"; } ];
settings.net.content_security_policy = "frame-ancestors https://${serviceDomain}";
};
}
{ ${idmServer} = confLib.mkKanidmOauth2ProxyAccess { inherit serviceName; }; }
{ ${webProxy}.services.nginx = genNginx serviceAddress ""; }
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (genNginx homeServiceAddress nginxAccessRules);
}
];
};
};
}
4.4.3.71. Audiobookshelf
Recently I have grown to enjoy listening to audio books and podcasts while riding my bike.
This one needs manual OIDC setup in the admin UI (TODO?)
{
flake.modules.nixos.audiobookshelf =
{
root,
config,
lib,
confLib,
...
}:
let
inherit
(confLib.gen {
dir = "/var/lib/audiobookshelf";
name = "audiobookshelf";
port = 13378;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDir
serviceDomain
serviceGroup
serviceName
servicePort
serviceUser
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
webProxy
;
in
{
config = {
swarselsystems.enabledServerModules = [ serviceName ];
topology.self.services.${serviceName} = {
icon = root "files/topology-images/${serviceName}.png";
info = "https://${serviceDomain}";
name = serviceName;
};
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
path = "/healthcheck";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops.secrets.kanidm-audiobookshelf = {
group = serviceGroup;
mode = "0440";
owner = serviceUser;
rekey.keyPrefix = confLib.kanidmSecrets;
};
users = {
users.${serviceUser}.extraGroups = [ "users" ];
persistentIds.${serviceName} = confLib.mkIds 938;
};
services.${serviceName} = {
enable = true;
host = "0.0.0.0";
port = servicePort;
};
environment.persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [
{
directory = serviceDir;
group = serviceGroup;
user = serviceUser;
}
];
};
nodes = lib.mkMerge [
{
${idmServer} = confLib.mkKanidmOidcSystem {
inherit serviceDomain serviceName;
originUrl = [
"https://${serviceDomain}/auth/openid/callback"
"https://${serviceDomain}/auth/openid/mobile-redirect"
];
};
}
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
serviceAddress
serviceDomain
serviceName
servicePort
;
maxBody = 0;
proxyWebsockets = true;
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit serviceDomain serviceName servicePort;
extraConfig = nginxAccessRules;
maxBody = 0;
proxyWebsockets = true;
serviceAddress = homeServiceAddress;
}
);
}
];
};
};
}
4.4.3.72. slskd
Another service that is only available locally … some ships sail only in friendly waters :)
To make the waters even friendlier, I run this behind its own PIA namespace, of course with port forwarding. This however means that I have to pass the entire config on the command line, which leads to a lot of redefining in the systemd service. But hey, at least I have two tunnels on the same machine!
{
flake.modules.nixos.slskd =
{
root,
config,
lib,
pkgs,
confLib,
...
}:
let
inherit
(confLib.gen {
dir = "/var/lib/slskd";
name = "slskd";
port = 5030;
})
serviceDir
serviceGroup
serviceName
servicePort
serviceUser
;
inherit (confLib.gen { name = "transmission"; }) serviceDomain;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
isHome
;
piaNamespace = "pia-slsk";
piaTunnel = config.services.pia-netns.tunnels.${piaNamespace};
urlBase = "/${serviceName}";
downloadDir = "/storage/Music/${serviceName}";
in
{
config = {
swarselsystems.enabledServerModules = [ serviceName ];
topology.self.services.${serviceName} = {
icon = root "files/topology-images/${serviceName}.png";
info = "https://${serviceDomain}${urlBase}";
name = serviceName;
};
globals = {
services.transmission.webPaths.${serviceName} = urlBase;
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
path = "${urlBase}/";
};
networks = confLib.mkDualFirewallRules {
forWebProxy = false;
tcpPorts = [ servicePort ];
};
};
sops = {
secrets = {
slskd-soulseek-password = { };
slskd-soulseek-username = { };
slskd-web-password = { };
};
templates."slskd.env".content = ''
SLSKD_SLSK_USERNAME=${config.sops.placeholder.slskd-soulseek-username}
SLSKD_SLSK_PASSWORD=${config.sops.placeholder.slskd-soulseek-password}
SLSKD_USERNAME=${config.swarselsystems.mainUser}
SLSKD_PASSWORD=${config.sops.placeholder.slskd-web-password}
'';
};
users = {
users.${serviceUser}.extraGroups = [ "users" ];
persistentIds.${serviceName} = confLib.mkIds 937;
};
services = {
${serviceName} = {
enable = true;
environmentFile = config.sops.templates."slskd.env".path;
settings = {
directories = {
downloads = downloadDir;
incomplete = "${serviceDir}/incomplete";
};
shares.directories = [ "/storage/Music" ];
transfers = {
download.speed_limit = 6000;
upload = {
slots = 5;
speed_limit = 100;
};
};
web = {
port = servicePort;
url_base = urlBase;
};
};
};
pia-netns.tunnels.${piaNamespace} = {
credentialsFile = config.sops.secrets.pia.path;
forwards."${serviceName}-web-forward" = {
port = servicePort;
service = "${serviceName}.service";
};
portForwarding.enable = true;
region = "sweden";
};
};
environment.persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [
{
directory = serviceDir;
group = serviceGroup;
user = serviceUser;
}
];
};
systemd = {
services = {
${serviceName} = {
after = [ piaTunnel.unit ];
bindsTo = [ piaTunnel.unit ];
environment = {
SQLITE_TMPDIR = "/tmp";
XDG_RUNTIME_DIR = "/run/${serviceName}";
};
partOf = [ piaTunnel.unit ];
requires = [ piaTunnel.unit ];
serviceConfig = {
BindReadOnlyPaths = [ "/etc/netns/${piaNamespace}/resolv.conf:/etc/resolv.conf" ];
ExecStart =
let
cfg = config.services.${serviceName};
configurationYaml = (pkgs.formats.yaml { }).generate "slskd.yml" (
lib.filterAttrsRecursive (_: value: (builtins.tryEval value).success && value != null) (
lib.removeAttrs cfg.settings [ "global" ]
)
);
in
lib.mkForce (
lib.getExe (
pkgs.writeShellApplication {
name = "${serviceName}-start";
text = ''
exec ${cfg.package}/bin/slskd \
--app-dir ${serviceDir} \
--config ${configurationYaml} \
--slsk-listen-port "$(cat "$CREDENTIALS_DIRECTORY/listen-port")"
'';
}
)
);
LoadCredential = [ "listen-port:${piaTunnel.portForwarding.portFile}" ];
NetworkNamespacePath = piaTunnel.netnsPath;
PrivateUsers = lib.mkForce false;
RuntimeDirectory = serviceName;
RuntimeDirectoryMode = "0700";
UMask = "0002";
};
wantedBy = [ piaTunnel.unit ];
};
};
tmpfiles.rules = [
"d ${downloadDir} 0775 ${serviceUser} users -"
"d ${serviceDir}/incomplete 0750 ${serviceUser} ${serviceGroup} -"
];
};
nodes.${homeWebProxy}.services.nginx = lib.mkIf isHome {
upstreams.${serviceName}.servers = {
"${homeServiceAddress}:${builtins.toString servicePort}" = { };
};
virtualHosts.${serviceDomain}.locations.${urlBase} = {
extraConfig = ''
client_max_body_size 0;
'';
proxyPass = "http://${serviceName}";
proxyWebsockets = true;
};
};
};
};
}
4.4.3.73. Dawarich
Self-hosted location history tracker. After my father paid for one month of subscription to a service called Li****0, I felt compelled to do this on my own to avoid such expenditures in the future ;0
{
flake.modules.nixos.dawarich =
{
self,
root,
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
dir = "/var/lib/dawarich";
name = "dawarich";
port = 3000;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDir
serviceDomain
serviceGroup
serviceName
servicePort
serviceUser
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
notificationMail
webProxy
;
in
{
imports = [
self.modules.nixos.postgresql
];
config = {
swarselsystems = {
enabledServerModules = [ serviceName ];
server.postgresql.rolePasswordFiles.${serviceName} =
config.sops.secrets."${serviceName}-db-password".path;
};
topology.self.services.${serviceName} = {
icon = root "files/topology-images/${serviceName}.png";
info = "https://${serviceDomain}";
name = serviceName;
};
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = ''"status":\s*"ok"'';
hostHeader = serviceDomain;
path = "/api/v1/health";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops = {
secrets = {
"${serviceName}-db-password" = {
owner = config.systemd.services.postgresql.serviceConfig.User;
rekey.generator.script = "alnum";
};
kanidm-dawarich.rekey.keyPrefix = confLib.kanidmSecrets;
notification-mail-pw.rekey.keyPrefix = notificationMail.keyPrefix;
};
templates.dawarich-oidc-env.content = ''
OIDC_CLIENT_SECRET=${config.sops.placeholder.kanidm-dawarich}
'';
};
users.persistentIds = {
${serviceName} = confLib.mkIds 936;
"redis-${serviceName}" = confLib.mkIds 934;
};
services.${serviceName} = {
enable = true;
configureNginx = false;
database.passwordFile = config.sops.secrets."${serviceName}-db-password".path;
environment = {
ALLOW_EMAIL_PASSWORD_REGISTRATION = "false";
OIDC_CLIENT_ID = serviceName;
OIDC_ISSUER = "https://${globals.services.kanidm.domain}/oauth2/openid/${serviceName}";
OIDC_PKCE_ENABLED = "true";
OIDC_PROVIDER_NAME = "Kanidm";
OIDC_REDIRECT_URI = "https://${serviceDomain}/users/auth/openid_connect/callback";
SMTP_DOMAIN = globals.domains.main;
};
extraEnvFiles = [ config.sops.templates.dawarich-oidc-env.path ];
localDomain = serviceDomain;
smtp = {
inherit (notificationMail) host;
fromAddress = "Dawarich <${notificationMail.address}>";
passwordFile = config.sops.secrets.notification-mail-pw.path;
port = 587;
user = notificationMail.address;
};
webPort = servicePort;
};
environment.persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [
{
directory = serviceDir;
group = serviceGroup;
mode = "0750";
user = serviceUser;
}
{
directory = "/var/lib/redis-${serviceName}";
group = "redis-${serviceName}";
user = "redis-${serviceName}";
}
];
};
nodes = lib.mkMerge [
{
${idmServer} = confLib.mkKanidmOidcSystem {
inherit serviceDomain serviceName;
originUrl = "https://${serviceDomain}/users/auth/openid_connect/callback";
};
}
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
serviceAddress
serviceDomain
serviceName
servicePort
;
maxBody = 0;
proxyWebsockets = true;
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit serviceDomain serviceName servicePort;
extraConfig = nginxAccessRules;
maxBody = 0;
proxyWebsockets = true;
serviceAddress = homeServiceAddress;
}
);
}
];
};
};
}
4.4.3.74. MeTube
For many years I depended on the plentiful options of services to download YouTube videos on the internet. Finally I host one myself. This one is for general videos; for music, we can directly use Yubal.
{
flake.modules.nixos.metube =
{
self,
root,
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
dir = "/var/lib/metube";
name = "metube";
port = 8087;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDir
serviceDomain
serviceGroup
serviceName
servicePort
serviceUser
topologyContainerName
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
webProxy
;
containerRev = "sha256:df929ef2453fd75c1f1cbd8dafb309ee03ff18d8705c7c1e01642b1202d4a650";
containerPort = 8081;
serviceId = 935;
in
{
imports = [
self.modules.nixos.podman
];
config = {
swarselsystems.enabledServerModules = [ serviceName ];
topology.nodes.${topologyContainerName}.services.${serviceName} = {
icon = root "files/topology-images/${serviceName}.png";
info = "https://${serviceDomain}";
name = "MeTube";
};
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = "MeTube";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
users = {
users.${serviceUser} = {
group = serviceGroup;
isSystemUser = true;
};
groups.${serviceGroup} = { };
persistentIds.${serviceName} = confLib.mkIds serviceId;
};
environment.persistence."/persist".directories = lib.mkIf config.swarselsystems.isImpermanence [
{
directory = serviceDir;
group = serviceGroup;
mode = "0750";
user = serviceUser;
}
];
virtualisation.oci-containers.containers.${serviceName} = {
environment = {
DOWNLOAD_DIR = "/downloads";
GID = builtins.toString serviceId;
STATE_DIR = "/state";
UID = builtins.toString serviceId;
};
image = "ghcr.io/alexta69/metube@${containerRev}";
ports = [ "${builtins.toString servicePort}:${builtins.toString containerPort}" ];
volumes = [
"${serviceDir}/downloads:/downloads"
"${serviceDir}/state:/state"
];
};
systemd.services."podman-${serviceName}" = {
preStart = lib.mkAfter ''
install -d -o ${serviceUser} -g ${serviceGroup} -m 0750 ${serviceDir}/downloads ${serviceDir}/state
'';
unitConfig.RequiresMountsFor = [ serviceDir ];
};
nodes =
let
genNginx = toAddress: extraConfig: {
upstreams.${serviceName}.servers = {
"${toAddress}:${builtins.toString servicePort}" = { };
};
virtualHosts.${serviceDomain} = {
inherit extraConfig;
acmeRoot = null;
forceSSL = true;
locations."/" = {
extraConfig = ''
client_max_body_size 0;
'';
proxyPass = "http://${serviceName}";
proxyWebsockets = true;
};
oauth2 = {
enable = true;
allowedGroups = [ "${serviceName}_access" ];
};
useACMEHost = globals.domains.main;
};
};
in
lib.mkMerge [
{ ${idmServer} = confLib.mkKanidmOauth2ProxyAccess { inherit serviceName; }; }
{ ${webProxy}.services.nginx = genNginx serviceAddress ""; }
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (genNginx homeServiceAddress nginxAccessRules);
}
];
};
};
}
4.4.3.75. Spliit
Interim podman implementation of spliit until (if?) https://github.com/NixOS/nixpkgs/pull/394621 is merged.
Replaces cospend in Nextcloud
{
flake.modules.nixos.spliit =
{
self,
root,
config,
lib,
confLib,
...
}:
let
inherit
(confLib.gen {
name = "spliit";
port = 8089;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
servicePort
topologyContainerName
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
webProxy
;
containerRev = "sha256:cfaf0f84ef4f11cd3e4c46329039a0f1f51a7d7bf8cc218bf7c1b366e58a99f1";
containerPort = 3000;
postgresSocketDir = "/run/postgresql";
in
{
imports = [
self.modules.nixos.podman
self.modules.nixos.postgresql
];
config = {
swarselsystems = {
enabledServerModules = [ serviceName ];
server.postgresql.rolePasswordFiles.${serviceName} =
config.sops.secrets."${serviceName}-db-password".path;
};
topology.nodes.${topologyContainerName}.services.${serviceName} = {
icon = root "files/topology-images/${serviceName}.png";
info = "https://${serviceDomain}";
name = lib.swarselsystems.toCapitalized serviceName;
};
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = ''"status":\s*"healthy"'';
path = "/api/health";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops = {
secrets."${serviceName}-db-password" = {
owner = config.systemd.services.postgresql.serviceConfig.User;
rekey.generator.script = "alnum";
};
templates."${serviceName}-env".content =
let
databaseUrl = "postgresql://${serviceName}:${
config.sops.placeholder."${serviceName}-db-password"
}@localhost/${serviceName}?host=${postgresSocketDir}";
in
''
POSTGRES_PRISMA_URL=${databaseUrl}
POSTGRES_URL_NON_POOLING=${databaseUrl}
'';
};
services.postgresql = {
ensureDatabases = [ serviceName ];
ensureUsers = [
{
ensureDBOwnership = true;
name = serviceName;
}
];
};
virtualisation.oci-containers.containers.${serviceName} = {
environment = {
BASE_URL = "https://${serviceDomain}";
DEFAULT_CURRENCY_CODE = "EUR";
NEXT_TELEMETRY_DISABLED = "1";
};
environmentFiles = [ config.sops.templates."${serviceName}-env".path ];
image = "ghcr.io/spliit-app/spliit@${containerRev}";
ports = [ "${builtins.toString servicePort}:${builtins.toString containerPort}" ];
volumes = [ "${postgresSocketDir}:${postgresSocketDir}" ];
};
systemd.services."podman-${serviceName}" = {
after = [ "postgresql-setup.service" ];
requires = [ "postgresql-setup.service" ];
};
nodes =
let
genNginx =
args:
lib.mkMerge [
(confLib.genNginx (
{
inherit serviceDomain serviceName servicePort;
oauth2 = true;
oauth2Groups = [ "${serviceName}_access" ];
}
// args
))
{
virtualHosts.${serviceDomain}.locations =
lib.genAttrs
[
"/api/trpc/"
"~ ^/(?:_next/|logo/|[^/]+\\.\\w+$)"
"~ ^/groups/(?!create(?:/|$))[^/]+"
]
(_: {
bypassAuth = true;
proxyPass = "http://${serviceName}";
setOauth2Headers = false;
})
// {
"~ ^/api/trpc/(?:[^/]*,)?groups\\.create(?:,|$)".proxyPass = "http://${serviceName}";
};
}
];
in
lib.mkMerge [
{ ${idmServer} = confLib.mkKanidmOauth2ProxyAccess { inherit serviceName; }; }
{ ${webProxy}.services.nginx = genNginx { inherit serviceAddress; }; }
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (genNginx {
extraConfig = nginxAccessRules;
serviceAddress = homeServiceAddress;
});
}
];
};
};
}
4.4.3.76. OpnForm
Replaces Forms and Polls from Nextcloud
{
flake.modules.nixos.opnform =
{
self,
root,
config,
lib,
pkgs,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
dir = "/var/lib/opnform";
name = "opnform";
port = 8090;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDir
serviceDomain
serviceName
servicePort
topologyContainerName
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
notificationMail
webProxy
;
maxBodySize = "64M";
podUnit = "podman-${serviceName}-pod.service";
postgresSocketDir = "/run/postgresql";
serviceUrl = "https://${serviceDomain}";
wgProxyNet = globals.networks."${globals.wireguard.wgProxy.netConfigPrefix}-wgProxy";
ingressConfig = pkgs.writeText "${serviceName}-ingress.conf" ''
map $request_uri $api_uri {
~^/api(/.*$) $1;
default $request_uri;
}
server {
listen 80;
root /usr/share/nginx/html/public;
client_max_body_size ${maxBodySize};
location / {
proxy_http_version 1.1;
proxy_pass http://127.0.0.1:3000;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Port $server_port;
}
location ^~ /api/_nuxt_icon/ {
proxy_http_version 1.1;
proxy_pass http://127.0.0.1:3000;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Port $server_port;
}
location ~/(api|open|local\/temp|forms\/assets)/ {
try_files $uri $uri/ /index.php$is_args$args;
}
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root/index.php;
fastcgi_param REQUEST_URI $api_uri;
fastcgi_param HTTP_X_FORWARDED_FOR $proxy_add_x_forwarded_for;
fastcgi_param HTTP_X_FORWARDED_HOST $http_x_forwarded_host;
fastcgi_param HTTP_X_FORWARDED_PORT $http_x_forwarded_port;
fastcgi_param HTTP_X_FORWARDED_PROTO $http_x_forwarded_proto;
}
location ~ /\. {
deny all;
}
}
'';
apiContainer = {
dependsOn = [ "${serviceName}-redis" ];
environment = {
APP_DEBUG = "false";
APP_ENV = "production";
APP_NAME = "OpnForm";
APP_URL = serviceUrl;
CACHE_DRIVER = "redis";
DB_CONNECTION = "pgsql";
DB_DATABASE = serviceName;
DB_HOST = postgresSocketDir;
DB_PORT = builtins.toString config.services.postgresql.settings.port;
DB_USERNAME = serviceName;
FILESYSTEM_DRIVER = "local";
FRONT_URL = serviceUrl;
LOCAL_FILESYSTEM_VISIBILITY = "public";
LOG_CHANNEL = "errorlog";
LOG_LEVEL = "info";
MAIL_ENCRYPTION = "tls";
MAIL_FROM_ADDRESS = notificationMail.address;
MAIL_FROM_NAME = "OpnForm";
MAIL_HOST = notificationMail.host;
MAIL_MAILER = "smtp";
MAIL_PORT = "587";
MAIL_USERNAME = notificationMail.address;
OPNFORM_ANONYMOUS_TELEMETRY_DISABLED = "true";
PHP_POST_MAX_SIZE = maxBodySize;
PHP_UPLOAD_MAX_FILESIZE = maxBodySize;
QUEUE_CONNECTION = "redis";
REDIS_HOST = "127.0.0.1";
SESSION_DRIVER = "redis";
TRUSTED_PROXIES = "${wgProxyNet.cidrv4},${wgProxyNet.cidrv6}";
};
environmentFiles = [ config.sops.templates."${serviceName}-api-env".path ];
extraOptions = [ "--pod=${serviceName}" ];
image = "docker.io/jhumanj/opnform-api@sha256:e0d23f380432191871025152afff74f0dd708fe6b8b79810b46a2f24893e6f79";
volumes = [
"${postgresSocketDir}:${postgresSocketDir}"
"${serviceDir}/storage:/usr/share/nginx/html/storage"
];
};
in
{
imports = [
self.modules.nixos.podman
self.modules.nixos.postgresql
];
config = {
swarselsystems = {
enabledServerModules = [ serviceName ];
server.postgresql.rolePasswordFiles.${serviceName} =
config.sops.secrets."${serviceName}-db-password".path;
};
topology.nodes.${topologyContainerName}.services.${serviceName} = {
icon = root "files/topology-images/${serviceName}.png";
info = serviceUrl;
name = "OpnForm";
};
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = ''"status":\s*"ok"'';
path = "/api/healthcheck";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops = {
secrets = {
"${serviceName}-app-key".rekey.generator.script = "laravel-key";
"${serviceName}-db-password" = {
owner = config.systemd.services.postgresql.serviceConfig.User;
rekey.generator.script = "alnum";
};
"${serviceName}-front-api-secret".rekey.generator.script = "alnum";
"${serviceName}-jwt-secret".rekey.generator.script = "alnum";
"kanidm-${serviceName}".rekey.keyPrefix = confLib.kanidmSecrets;
notification-mail-pw.rekey.keyPrefix = notificationMail.keyPrefix;
};
templates = {
"${serviceName}-api-env".content = ''
APP_KEY=${config.sops.placeholder."${serviceName}-app-key"}
DB_PASSWORD=${config.sops.placeholder."${serviceName}-db-password"}
FRONT_API_SECRET=${config.sops.placeholder."${serviceName}-front-api-secret"}
JWT_SECRET=${config.sops.placeholder."${serviceName}-jwt-secret"}
MAIL_PASSWORD=${config.sops.placeholder.notification-mail-pw}
'';
"${serviceName}-client-env".content = ''
NUXT_API_SECRET=${config.sops.placeholder."${serviceName}-front-api-secret"}
'';
};
};
services.postgresql = {
ensureDatabases = [ serviceName ];
ensureUsers = [
{
ensureDBOwnership = true;
name = serviceName;
}
];
};
environment.persistence."/persist".directories = lib.mkIf config.swarselsystems.isImpermanence [
{
directory = serviceDir;
mode = "0750";
}
];
virtualisation.oci-containers.containers = {
${serviceName} = {
dependsOn = [
"${serviceName}-api"
"${serviceName}-client"
];
extraOptions = [ "--pod=${serviceName}" ];
image = "docker.io/library/nginx@sha256:0e52bd054126cdc040b1276c0af347aeb02a41b9cfe305d6094767ac30e97949";
volumes = [ "${ingressConfig}:/etc/nginx/conf.d/default.conf:ro" ];
};
"${serviceName}-api" = apiContainer;
"${serviceName}-client" = {
dependsOn = [ "${serviceName}-api" ];
environment = {
NUXT_PRIVATE_API_BASE = "http://127.0.0.1/api";
NUXT_PUBLIC_API_BASE = "${serviceUrl}/api";
NUXT_PUBLIC_APP_URL = serviceUrl;
NUXT_PUBLIC_ENV = "production";
};
environmentFiles = [ config.sops.templates."${serviceName}-client-env".path ];
extraOptions = [ "--pod=${serviceName}" ];
image = "docker.io/jhumanj/opnform-client@sha256:c1aea2ba43a07c83373f4331acdaf68ce084d5f1361bc80969ebdff86dac5ea3";
};
"${serviceName}-redis" = {
extraOptions = [ "--pod=${serviceName}" ];
image = "docker.io/library/redis@sha256:21090af93f8324db2f0f0f4f38a7c60369d47d917e000c3423d89d2ae2883537";
volumes = [ "${serviceDir}/redis:/data" ];
};
"${serviceName}-scheduler" = apiContainer // {
cmd = [
"php"
"artisan"
"schedule:work"
];
dependsOn = [ "${serviceName}-api" ];
};
"${serviceName}-worker" = apiContainer // {
cmd = [
"php"
"artisan"
"queue:work"
];
dependsOn = [ "${serviceName}-api" ];
};
};
systemd.services = lib.mkMerge [
{
"podman-${serviceName}-api" = {
after = [ "postgresql-setup.service" ];
requires = [ "postgresql-setup.service" ];
};
"podman-${serviceName}-pod" = {
path = [ config.virtualisation.podman.package ];
postStop = ''
podman pod rm --force --ignore ${serviceName}
'';
preStart = ''
install -d -m 0750 ${serviceDir}/redis ${serviceDir}/storage
podman pod rm --force --ignore ${serviceName}
'';
script = ''
podman pod create --name ${serviceName} --publish ${builtins.toString servicePort}:80
'';
serviceConfig = {
RemainAfterExit = true;
Type = "oneshot";
};
unitConfig.RequiresMountsFor = [ serviceDir ];
};
}
(lib.genAttrs
(map (name: "podman-${name}") [
serviceName
"${serviceName}-api"
"${serviceName}-client"
"${serviceName}-redis"
"${serviceName}-scheduler"
"${serviceName}-worker"
])
(_: {
after = [ podUnit ];
partOf = [ podUnit ];
requires = [ podUnit ];
})
)
];
nodes = lib.mkMerge [
{
${idmServer} =
lib.recursiveUpdate
(confLib.mkKanidmOidcSystem {
inherit serviceDomain serviceName;
displayName = "OpnForm";
originUrl = "${serviceUrl}/auth/kanidm/callback";
})
{
services.kanidm.provision.systems.oauth2.${serviceName}.allowInsecureClientDisablePkce = true;
};
}
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
serviceAddress
serviceDomain
serviceName
servicePort
;
maxBody = maxBodySize;
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit serviceDomain serviceName servicePort;
extraConfig = nginxAccessRules;
maxBody = maxBodySize;
serviceAddress = homeServiceAddress;
}
);
}
];
};
};
}
4.4.3.77. LibreSpeed
A simple speedtest, using the NixOS module with the bundled frontend. Proxy buffering is disabled on the reverse proxy so the measured speeds are not skewed by nginx.
{
flake.modules.nixos.librespeed =
{
root,
lib,
confLib,
...
}:
let
inherit
(confLib.gen {
name = "librespeed";
port = 8092;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
servicePort
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
isHome
nginxAccessRules
notificationMail
webProxy
;
extraConfigLoc = ''
gzip off;
proxy_buffering off;
proxy_request_buffering off;
'';
in
{
config = {
swarselsystems.enabledServerModules = [ serviceName ];
topology.self.services.${serviceName} = {
icon = root "files/topology-images/${serviceName}.png";
info = "https://${serviceDomain}";
name = "LibreSpeed";
};
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = "LibreSpeed";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
services.${serviceName} = {
enable = true;
downloadIPDB = false;
frontend = {
enable = true;
contactEmail = notificationMail.address;
servers = [
{
name = serviceDomain;
server = "//${serviceDomain}";
}
];
settings.telemetry_level = "disabled";
};
settings.listen_port = servicePort;
};
nodes = lib.mkMerge [
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
extraConfigLoc
serviceAddress
serviceDomain
serviceName
servicePort
;
maxBody = 0;
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit
extraConfigLoc
serviceDomain
serviceName
servicePort
;
extraConfig = nginxAccessRules;
maxBody = 0;
serviceAddress = homeServiceAddress;
}
);
}
];
};
};
}
4.4.3.78. Homebox (use db)
My asset manager. I use it to track tools, cables and board games mostly.
{
flake.modules.nixos.homebox =
{
self,
root,
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
name = "homebox";
port = 7745;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceGroup
serviceName
servicePort
serviceUser
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
webProxy
;
in
{
imports = [
self.modules.nixos.postgresql
];
config = {
swarselsystems = {
enabledServerModules = [ "homebox" ];
server.postgresql.rolePasswordFiles.${serviceName} =
config.sops.secrets."${serviceName}-db-password".path;
};
topology.self.services.${serviceName} = {
icon = root "files/topology-images/${serviceName}.png";
info = "https://${serviceDomain}";
name = "Homebox";
};
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = ''"health":\s*true'';
path = "/api/v1/status";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops = {
secrets = {
"${serviceName}-db-password" = {
owner = config.systemd.services.postgresql.serviceConfig.User;
rekey.generator.script = "alnum";
};
kanidm-homebox = {
group = serviceGroup;
mode = "0440";
owner = serviceUser;
rekey.keyPrefix = confLib.kanidmSecrets;
};
};
templates.homebox-oidc-env = {
content = ''
HBOX_OIDC_CLIENT_SECRET=${config.sops.placeholder.kanidm-homebox}
'';
owner = serviceUser;
};
};
users.persistentIds.homebox = confLib.mkIds 981;
services.${serviceName} = {
enable = true;
database.createLocally = true;
secrets.HBOX_DATABASE_PASSWORD = config.sops.secrets."${serviceName}-db-password".path;
settings = {
HBOX_OIDC_BUTTON_TEXT = "Sign in with Kanidm";
HBOX_OIDC_CLIENT_ID = serviceName;
HBOX_OIDC_ENABLED = "true";
HBOX_OIDC_ISSUER_URL = "https://${globals.services.kanidm.domain}/oauth2/openid/${serviceName}";
HBOX_OPTIONS_ALLOW_REGISTRATION = "false";
HBOX_OPTIONS_TRUST_PROXY = "true";
HBOX_STORAGE_CONN_STRING = "file:///var/lib/homebox";
HBOX_STORAGE_PREFIX_PATH = ".data";
HBOX_WEB_PORT = builtins.toString servicePort;
};
};
environment.persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [
{
directory = "/var/lib/${serviceName}";
group = serviceGroup;
user = serviceUser;
}
];
};
systemd.services.${serviceName}.serviceConfig.EnvironmentFile =
config.sops.templates.homebox-oidc-env.path;
nodes = lib.mkMerge [
{
${idmServer} = confLib.mkKanidmOidcSystem {
inherit serviceDomain serviceName;
originUrl = "https://${serviceDomain}/api/v1/users/login/oidc/callback";
};
}
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
serviceAddress
serviceDomain
serviceName
servicePort
;
maxBody = 0;
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit serviceDomain serviceName servicePort;
extraConfig = nginxAccessRules;
maxBody = 0;
serviceAddress = homeServiceAddress;
}
);
}
];
};
};
}
4.4.3.79. OPKSSH
Allows certificate based SSH logins easily. I use this to be able to quickly give people access to my server when needed (by giving them the permissions in kanidm) - not that this happens ever. But it might be useful at some point.
let
redirectUris = [
"http://localhost:3000/login-callback"
"http://localhost:10001/login-callback"
"http://localhost:11110/login-callback"
];
in
{
flake.modules = {
homeManager.opkssh =
{ globals, ... }:
{
config = {
swarselsystems.enabledHomeModules = [ "opkssh" ];
programs.opkssh = {
enable = true;
settings = {
default_provider = "kanidm";
providers = [
{
alias = "kanidm";
client_id = "opkssh";
issuer = "https://${globals.services.kanidm.domain}/oauth2/openid/opkssh";
redirect_uris = redirectUris;
scopes = "openid email profile";
}
];
};
};
};
};
nixos.opkssh =
{
config,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
group = "opksshuser";
name = "opkssh";
user = "opksshuser";
})
serviceGroup
serviceName
serviceUser
;
inherit (confLib.static) idmServer;
in
{
config = {
swarselsystems.enabledServerModules = [ "opkssh" ];
users.persistentIds.opksshuser = confLib.mkIds 980;
services.${serviceName} = {
enable = true;
authorizations = [
{
inherit (config.services.opkssh.providers.kanidm) issuer;
principal = config.repo.secrets.common.mail.address4;
user = "root";
}
];
group = serviceGroup;
providers.kanidm = {
clientId = serviceName;
issuer = "https://${globals.services.kanidm.domain}/oauth2/openid/${serviceName}";
lifetime = "oidc";
};
user = serviceUser;
};
nodes = {
${idmServer}.services.kanidm.provision = {
groups."opkssh.access" = { };
systems.oauth2.opkssh = {
displayName = "OPKSSH";
enableLocalhostRedirects = true;
originLanding = "http://localhost:3000";
originUrl = [ "http://localhost:3000" ] ++ redirectUris;
public = true;
scopeMaps."opkssh.access" = [
"openid"
"email"
"profile"
];
};
};
};
};
};
};
}
4.4.3.80. Garage
Garage acts as my s3 endpoint. I use it on two of my servers:
- Winters (Server: ASRock J4105-ITX): General s3 storage
- Belchsfactory (OCI): s3 storage for nix binary cache (used by Attic (nix binary cache))
Generate the admin token using openssl rand -base64 32.
Generate the rpc token using openssl rand -hex 32.
Interact like aws s3 ls s3://<bucket> --endpoint-url https://<domain> --profile <name> --region <name> --no-verify-ssl (–no-verify-ssl is needed if the corresponding root CA certificate is not installed/trusted)
If a website is to be deployed using a s3 bucket, add the corresponding files in one of two ways:
either 1) use vhost addressing: aws s3 cp <local file> s3://<path to file; no bucket identifier needed> --endpoint-url https://<bucket>.<garage domain> --region swarsel
or 2) use classic path addressing aws s3 cp <local file> s3://<bucket>/<path to file> --endpoint-url https://<garage domain> --region swarsel
{
flake.modules.nixos.garage =
# inspired by https://github.com/atropos112/nixos/blob/7fef652006a1c939f4caf9c8a0cb0892d9cdfe21/modules/garage.nix
{
root,
config,
lib,
pkgs,
confLib,
dns,
globals,
...
}:
let
inherit
(confLib.gen {
domain = config.repo.secrets.common.services.domains."garage-${config.node.name}";
name = "garage";
port = 3900;
})
baseDomain
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
servicePort
specificServiceName
subDomain
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
isHome
nginxAccessRules
webProxy
;
cfg = config.swarselsystems.server.${serviceName};
inherit (config.services.${serviceName}) package;
inherit (config.swarselsystems) mainUser;
garageRpcPort = 3901;
garageWebPort = 3902;
garageAdminPort = 3903;
garageK2VPort = 3904;
adminDomain = "${subDomain}-admin.${baseDomain}";
webDomain = "${subDomain}-web.${baseDomain}";
in
{
options = {
swarselsystems.server.${serviceName} = {
buckets = lib.mkOption {
description = "List of buckets to create";
type = lib.types.listOf lib.types.str;
};
data_dir = {
capacity = lib.mkOption {
type = lib.types.str;
};
path = lib.mkOption {
description = "Directory where Garage stores its data blocks";
type = lib.types.str;
};
};
keys = lib.mkOption {
default = { };
description = "Keys and their associated buckets. Each key gets full access (read/write/owner) to its listed buckets.";
example = {
my_key_name = [
"bucket1"
"bucket2"
];
my_other_key = [
"bucket2"
"bucket3"
];
};
type = lib.types.attrsOf (lib.types.listOf lib.types.str);
};
};
};
config = {
swarselsystems.enabledServerModules = [ "garage" ];
topology.self.services.${serviceName} = {
icon = root "files/topology-images/${serviceName}.png";
info = "https://${serviceDomain}";
name = lib.swarselsystems.toCapitalized serviceName;
};
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
;
extra.hasWebInterface = false;
serviceName = specificServiceName;
};
dns.${baseDomain}.subdomainRecords = {
"${subDomain}" = dns.lib.combinators.host proxyAddress4 proxyAddress6;
"${subDomain}-admin" = dns.lib.combinators.host proxyAddress4 proxyAddress6;
"${subDomain}-web" = dns.lib.combinators.host proxyAddress4 proxyAddress6;
"*.${subDomain}" = dns.lib.combinators.host proxyAddress4 proxyAddress6;
"*.${subDomain}-web" = dns.lib.combinators.host proxyAddress4 proxyAddress6;
};
monitoring.http = confLib.mkHttpMonitoring {
expectedBodyRegex = "fully operational";
path = "/health";
serviceName = specificServiceName;
servicePort = garageAdminPort;
};
networks = confLib.mkDualFirewallRules {
tcpPorts = [
servicePort
garageRpcPort
garageWebPort
garageAdminPort
garageK2VPort
];
};
};
sops.secrets = {
garage-admin-token.rekey.generator.script = "base64";
garage-rpc-secret.rekey.generator = {
args.length = 32;
script = "hex";
};
};
services.${serviceName} = {
enable = true;
package = pkgs.garage_2;
settings = {
admin = {
admin_token_file = config.sops.secrets.garage-admin-token.path;
api_bind_addr = "[::]:${builtins.toString garageAdminPort}";
};
block_size = "128M";
compression_level = "none";
data_dir = [ cfg.data_dir ];
db_engine = "lmdb";
disable_scrub = true;
k2v_api.api_bind_addr = "[::]:${builtins.toString garageK2VPort}";
# needs SSD
metadata_dir = "/var/lib/garage/meta";
replication_factor = 1;
rpc_bind_addr = "[::]:${builtins.toString garageRpcPort}";
# we are not joining our nodes, just use the private ipv4
rpc_public_addr = "${
globals.networks.${config.swarselsystems.server.netConfigName}.hosts.${config.node.name}.ipv4
}:${builtins.toString garageRpcPort}";
rpc_secret_file = config.sops.secrets.garage-rpc-secret.path;
s3_api = {
api_bind_addr = "[::]:${builtins.toString servicePort}";
root_domain = ".${serviceDomain}";
s3_region = mainUser;
};
s3_web = {
add_host_to_metrics = true;
bind_addr = "[::]:${builtins.toString garageWebPort}";
root_domain = ".${config.repo.secrets.common.services.domains."garage-web-${config.node.name}"}";
};
use_local_tz = false;
};
};
assertions = [
{
assertion = cfg.buckets != [ ];
message = "If Garage is enabled, at least one bucket must be specified in swarselsystems.server.${serviceName}.buckets";
}
{
assertion = cfg.keys != { };
message = "If Garage is enabled, at least one key must be specified in swarselsystems.server.${serviceName}.keys";
}
{
assertion = lib.all (bucket: lib.elem bucket cfg.buckets) (lib.flatten (lib.attrValues cfg.keys));
message = "All buckets referenced in keys must exist in the buckets list";
}
];
environment = {
persistence."/persist".directories = lib.mkIf config.swarselsystems.isImpermanence [
{ directory = "/var/lib/garage"; }
(lib.mkIf config.swarselsystems.isCloud {
directory = cfg.data_dir.path;
})
];
systemPackages = [ package ];
};
systemd = {
services = {
garage-buckets = {
after = [ "garage.service" ];
description = "Create Garage buckets";
path = [
package
pkgs.gawk
pkgs.coreutils
];
script = ''
while ! garage status >/dev/null 2>&1; do
sleep 5
done
while garage status | grep -q "==== FAILED NODES ===="; do
sleep 5
done
existing_buckets=$(garage bucket list | tail -n +2 | awk '{print $3}' | grep -v '^$' || true)
${lib.concatMapStringsSep "\n" (bucket: ''
if [[ "$(garage bucket info ${lib.escapeShellArg bucket} 2>&1 >/dev/null)" == *"Bucket not found"* ]]; then
echo "Creating bucket ${lib.escapeShellArg bucket}"
garage bucket create ${lib.escapeShellArg bucket}
fi
'') cfg.buckets}
for bucket in $existing_buckets; do
should_exist=false
${lib.concatMapStringsSep "\n" (bucket: ''
if [[ "$bucket" == ${lib.escapeShellArg bucket} ]]; then
should_exist=true
fi
'') cfg.buckets}
if [[ "$should_exist" == "false" ]]; then
echo "Removing bucket $bucket"
garage bucket delete --yes "$bucket"
fi
done
'';
serviceConfig = {
RemainAfterExit = true;
Type = "oneshot";
};
wantedBy = [ "multi-user.target" ];
wants = [ "garage.service" ];
};
garage-keys = {
after = [ "garage-buckets.service" ];
description = "Create Garage keys and set permissions";
path = [
package
pkgs.gawk
pkgs.coreutils
];
requires = [ "garage-buckets.service" ];
script = ''
existing_keys=$(garage key list | tail -n +2 | awk '{print $3}' | grep -v '^$' || true)
${lib.concatStringsSep "\n" (
lib.mapAttrsToList (keyName: _: ''
if [[ "$(garage key info ${lib.escapeShellArg keyName} 2>&1)" == *"0 matching keys"* ]]; then
echo "Creating key ${lib.escapeShellArg keyName}"
garage key create ${lib.escapeShellArg keyName}
fi
'') cfg.keys
)}
${lib.concatStringsSep "\n" (
lib.mapAttrsToList (
keyName: buckets:
lib.concatMapStringsSep "\n" (bucket: ''
garage bucket allow --read --write --owner --key ${lib.escapeShellArg keyName} ${lib.escapeShellArg bucket}
'') buckets
) cfg.keys
)}
${lib.concatStringsSep "\n" (
lib.mapAttrsToList (keyName: buckets: ''
current_buckets=$(garage key info ${lib.escapeShellArg keyName} | grep -A 1000 "==== BUCKETS FOR THIS KEY ====" | tail -n +3 | awk '{print $3}' | grep -v '^$' || true)
for current_bucket in $current_buckets; do
should_have_access=false
${lib.concatMapStringsSep "\n" (bucket: ''
if [[ "$current_bucket" == ${lib.escapeShellArg bucket} ]]; then
should_have_access=true
fi
'') buckets}
if [[ "$should_have_access" == "false" ]]; then
echo "Removing access for key ${lib.escapeShellArg keyName} from bucket $current_bucket"
garage bucket deny --key ${lib.escapeShellArg keyName} $current_bucket
fi
done
'') cfg.keys
)}
for key in $existing_keys; do
should_exist=false
${lib.concatStringsSep "\n" (
lib.mapAttrsToList (keyName: _: ''
if [[ "$key" == ${lib.escapeShellArg keyName} ]]; then
should_exist=true
fi
'') cfg.keys
)}
if [[ "$should_exist" == "false" ]]; then
echo "Removing key $key"
garage key delete --yes "$key"
fi
done
'';
serviceConfig = {
RemainAfterExit = true;
Type = "oneshot";
};
wantedBy = [ "multi-user.target" ];
};
};
services.${serviceName}.serviceConfig = {
# DynamicUser cannot read sops secrets
DynamicUser = false;
ProtectHome = lib.mkForce false;
};
};
nodes =
let
genNginx = toAddress: extraConfig: {
upstreams = {
${serviceName}.servers = {
"${toAddress}:${builtins.toString servicePort}" = { };
};
"${serviceName}Admin".servers = {
"${toAddress}:${builtins.toString garageAdminPort}" = { };
};
"${serviceName}Web".servers = {
"${toAddress}:${builtins.toString garageWebPort}" = { };
};
};
virtualHosts = {
"${adminDomain}" = {
inherit extraConfig;
acmeRoot = null;
forceSSL = true;
locations."/".proxyPass = "http://${serviceName}Admin";
oauth2.enable = false;
useACMEHost = globals.domains.main;
};
"${serviceDomain}" = {
inherit extraConfig;
acmeRoot = null;
forceSSL = true;
locations."/" = {
extraConfig = ''
client_max_body_size 0;
client_body_timeout 600s;
proxy_connect_timeout 600s;
proxy_send_timeout 600s;
proxy_read_timeout 600s;
proxy_request_buffering off;
'';
proxyPass = "http://${serviceName}";
};
oauth2.enable = false;
serverAliases = [ "*.${serviceDomain}" ];
useACMEHost = globals.domains.main;
};
"*.${webDomain}" = {
inherit extraConfig;
acmeRoot = null;
forceSSL = true;
locations."/".proxyPass = "http://${serviceName}Web";
oauth2.enable = false;
useACMEHost = globals.domains.main;
};
};
};
in
lib.mkMerge [
{ ${webProxy}.services.nginx = genNginx serviceAddress ""; }
{ ${homeWebProxy}.services.nginx = lib.mkIf isHome (genNginx homeServiceAddress nginxAccessRules); }
];
};
};
}
4.4.3.81. Set host domain for dns
This is used to have a dns record that points to the public IP of my cloud servers (which is useful for consolidating IPv4 and IPv6).
{
flake.modules.nixos.dns-hostrecord =
{
config,
lib,
confLib,
dns,
globals,
...
}:
let
inherit
(confLib.gen {
name = "dns-hostrecord";
proxy = config.node.name;
})
proxyAddress4
proxyAddress6
;
in
{
config = lib.mkIf config.swarselsystems.isCloud {
swarselsystems.enabledServerModules = [ "dns-hostrecord" ];
globals.dns.${globals.domains.main}.subdomainRecords = {
"server.${config.node.name}" = dns.lib.combinators.host proxyAddress4 proxyAddress6;
};
};
};
}
4.4.3.82. Set dns host entries for home servers
This makes sure that my servers at home know about the home NGINX endpoint and use it over the external one.
{
flake.modules.nixos.dns-home =
{ confLib, globals, ... }:
let
inherit (confLib.static) homeProxy;
in
{
config = {
swarselsystems.enabledServerModules = [ "dns-home" ];
networking.hosts = {
${globals.networks.home-lan.vlans.services.hosts.${homeProxy}.ipv4} = [
"server.${homeProxy}.${globals.domains.main}"
];
${globals.networks.home-lan.vlans.services.hosts.${homeProxy}.ipv6} = [
"server.${homeProxy}.${globals.domains.main}"
];
};
};
};
}
4.4.3.83. Set node role global entries
Before, I had a mechanism for defining system roles that worked by simply setting <roleDescriptor> = true; in the globals.general host config; this was a little cumbersome.
Now, I have a separate setting for this (nodeRoles) in which I can define ALL those roles. Still, this list then fills the corresponding global entries.
{
flake.modules.nixos.node-roles =
{ config, lib, ... }:
{
config.globals.general = lib.listToAttrs (
map (name: {
inherit name;
value = config.node.name;
}) config.swarselsystems.nodeRoles
);
};
}
4.4.3.84. Knot (dns)
This is the setup of my authoritative dns server.
Restoring the keys:
pass show infra/<dnsServer>/knot-dnssec-backup | base64 -d | ssh root@<dnsServer> ' rm -rf /var/lib/knot/backup && tar -C /var/lib/knot -xzf - && chown -R knot:knot /var/lib/knot/backup && knotc -b zone-restore swarsel.win +backupdir /var/lib/knot/backup +nozonefile && rm -rf /var/lib/knot/backup'
Domain specific config at:
{
flake.modules.nixos.knot =
{
root,
config,
lib,
pkgs,
confLib,
dns,
globals,
...
}:
let
inherit
(confLib.gen {
dir = "/var/lib/knot";
name = "knot";
port = 53;
proxy = config.node.name;
})
proxyAddress4
proxyAddress6
serviceDir
serviceName
servicePort
;
listenHost =
globals.networks.${config.swarselsystems.server.netConfigName}.hosts.${config.node.name};
listenAddress4 = listenHost.ipv4;
listenAddress6 = listenHost.ipv6;
keyName = globals.domains.main;
keyName4 = "${keyName}.${proxyAddress4}";
keyName6 = "${keyName}.${
lib.concatMapStringsSep "-" (lib.fixedWidthString 4 "0") (
lib.splitString ":" (lib.network.ipv6.fromString proxyAddress6).address
)
}";
mkRemotes =
key:
map (address: {
inherit address key;
});
hetzner =
mkRemotes keyName4 [
"213.239.242.238"
"213.133.100.103"
"193.47.99.3"
]
++ mkRemotes keyName6 [
"2a01:4f8:0:a101::a:1"
"2a01:4f8:0:1::5ddc:2"
"2001:67c:192c::add:a3"
];
heNotify = mkRemotes keyName [ "216.218.130.2" ];
heTransfer = mkRemotes keyName [
"216.218.133.2"
"2001:470:600::2"
];
remoteIds = map (remote: remote.address);
mkZoneFile = name: data: pkgs.writeText "${name}.zone" (dns.lib.toString name data);
in
{
config = {
swarselsystems.enabledServerModules = [ serviceName ];
topology.self.services.${serviceName} = {
icon = root "files/topology-images/${serviceName}.png";
name = "Knot DNS";
};
globals.monitoring.dns = confLib.mkDnsMonitoring {
inherit serviceName;
address = "${listenAddress4}:${toString servicePort}";
queryName = globals.domains.main;
};
sops = {
secrets.tsig-key = { };
templates."knot-tsig.conf" = {
content =
"key:\n"
+
lib.concatMapStrings
(id: ''
- id: ${id}
algorithm: hmac-sha256
secret: ${config.sops.placeholder.tsig-key}
'')
[
keyName
keyName4
keyName6
];
owner = "knot";
};
};
users.persistentIds.knot = confLib.mkIds 931;
services.knot = {
enable = true;
keyFiles = [ config.sops.templates."knot-tsig.conf".path ];
settings = {
acl.secondaries = {
action = "transfer";
remote = remoteIds (hetzner ++ heTransfer);
};
remote = lib.listToAttrs (
map (
remote:
lib.nameValuePair remote.address (
remote
// {
via = [
listenAddress4
listenAddress6
];
}
)
) (hetzner ++ heNotify ++ heTransfer)
);
server.listen = [
"${listenAddress4}@${toString servicePort}"
"${listenAddress6}@${toString servicePort}"
];
template.default = {
journal-content = "all";
serial-policy = "dateserial";
zonefile-load = "difference-no-serial";
zonefile-sync = -1;
};
zone = {
"${globals.domains.main}" = {
acl = [ "secondaries" ];
dnssec-signing = true;
file = mkZoneFile globals.domains.main (
import ./_dns-site1.nix {
inherit (confLib.static) dmarcMailAddress;
inherit
config
dns
globals
proxyAddress4
proxyAddress6
;
}
);
notify = remoteIds (hetzner ++ heNotify);
};
"${globals.domains.reverse6}".file = mkZoneFile globals.domains.reverse6 (
import ./_dns-reverse6.nix { inherit globals; }
);
};
};
};
environment.persistence."/persist".directories = lib.mkIf config.swarselsystems.isImpermanence [
{
directory = serviceDir;
group = "knot";
mode = "0700";
user = "knot";
}
];
networking.firewall = {
allowedTCPPorts = [ servicePort ];
allowedUDPPorts = [ servicePort ];
};
};
};
}
4.4.3.84.1. DNS zone - site1
These are the specific records in use for my main domain.
The serial here is only used on the very first load. Knot ignores it afterwards (as opposed to how NSD did it)
Simple A/AAAA records should usually be defined in the respective service modules, using globals.dns.${globals.services.${serviceName}.baseDomain}.subdomainRecords.
Regarding the DANE TLSA record of the Mail server: this needs to be here due to a type-conversion issue (#TODO: check for upstream fix)
{
config,
dmarcMailAddress,
dns,
globals,
proxyAddress4,
proxyAddress6,
...
}:
with dns.lib.combinators;
{
A = [ config.repo.secrets.local.dns.homepage-ip ];
CAA = [
{
issuerCritical = false;
tag = "issue";
value = "letsencrypt.org";
}
{
issuerCritical = false;
tag = "issuewild";
value = "letsencrypt.org";
}
{
issuerCritical = false;
tag = "iodef";
value = "mailto:${config.repo.secrets.common.dnsMail}";
}
];
DKIM = [
{
k = "rsa";
p = config.repo.secrets.local.dns.mailserver.dkim-public;
selector = "mail";
ttl = 10800;
}
];
DMARC = [
{
p = "none";
rua = "mailto:${dmarcMailAddress}";
ttl = 10800;
}
];
MX = [
{
exchange = globals.services.mailserver.subDomain;
preference = 10;
}
];
NS = [
"soa"
"srv"
]
++ globals.domains.externalDns;
SOA = {
adminEmail = "admin@${globals.domains.main}"; # this option is not parsed as domain (we cannot just write "admin")
nameServer = "soa";
serial = 2026102901;
};
SRV = [
{
port = 443;
priority = 10;
proto = "_tcp";
service = "_matrix";
target = globals.services.matrix.subDomain;
weight = 5;
}
]
++
map
(
record:
record
// {
priority = 5;
proto = "_tcp";
target = globals.services.mailserver.subDomain;
ttl = 3600;
weight = 0;
}
)
[
{
port = 465;
service = "_submissions";
}
{
port = 587;
service = "_submission";
}
{
port = 143;
service = "_imap";
}
{
port = 993;
service = "_imaps";
}
];
TXT = [
(with spf; strict [ "a:${globals.services.mailserver.subDomain}.${globals.domains.main}" ])
"google-site-verification=${config.repo.secrets.local.dns.google-site-verification}"
];
subdomains =
globals.dns.${globals.domains.main}.subdomainRecords
// builtins.listToAttrs (
map
(port: {
name = "_${toString port}._tcp.${globals.services.mailserver.subDomain}";
value.TLSA = [
{
certUsage = "dane-ee";
certificate = "c012bcab175ceadb422f964fdeb1c5aa778f8efae9d46f37f7717456cbc61467";
matchingType = "sha256";
selector = "spki";
}
];
})
[
25
465
587
993
]
)
// {
_acme-challenge.CNAME = [ "${config.repo.secrets.local.dns.acme-challenge-domain}." ];
soa = host proxyAddress4 proxyAddress6;
srv = host proxyAddress4 proxyAddress6;
www.CNAME = [ "${globals.domains.main}." ];
}
// config.repo.secrets.local.dns.extra-records;
useOrigin = false;
}
4.4.3.84.2. DNS zone - reverse6
This is the reverse zone by Hurricane Electric using a trick I learned in https://hawksley.dev/blog/get-free-arpa-domain. It is delegated to soa and srv in the tunnel-broker rDNS settings and delegates the acme-dns subdomain.
{ globals, ... }:
{
NS = [
"soa.${globals.domains.main}."
"srv.${globals.domains.main}."
];
SOA = {
adminEmail = "admin@${globals.domains.main}";
nameServer = "soa.${globals.domains.main}.";
serial = 2026090903;
};
subdomains = globals.dns.${globals.domains.reverse6}.subdomainRecords;
useOrigin = false;
}
4.4.3.85. Minecraft
Handles my Minecraft server. It runs forge, so the full server is not NixOS managed, but merely the service that starts it (good enough I guess.)
{
flake.modules.nixos.minecraft =
{
root,
config,
lib,
pkgs,
confLib,
dns,
globals,
...
}:
let
inherit
(confLib.gen {
dir = "/opt/minecraft";
name = "minecraft";
port = 25565;
proxy = config.node.name;
})
proxyAddress4
proxyAddress6
serviceDir
serviceDomain
serviceName
servicePort
;
inherit (confLib.static) isHome;
inherit (config.swarselsystems) mainUser;
worldName = "${mainUser}craft";
in
{
config = {
swarselsystems.enabledServerModules = [ "minecraft" ];
topology.self.services.${serviceName} = {
icon = root "files/topology-images/${serviceName}.png";
info = "https://${serviceDomain}";
name = "Minecraft";
};
globals = {
services.${serviceName} = {
inherit isHome proxyAddress4 proxyAddress6;
domain = serviceDomain;
hasWebInterface = false;
};
dns.${globals.services.${serviceName}.baseDomain}.subdomainRecords = {
"${globals.services.${serviceName}.subDomain}" =
dns.lib.combinators.host proxyAddress4 proxyAddress6;
};
monitoring.tcp = confLib.mkTcpMonitoring { inherit serviceName servicePort; };
};
environment.persistence."/persist".directories = lib.mkIf config.swarselsystems.isImpermanence [
{
directory = serviceDir;
mode = "0755";
}
];
networking.firewall.allowedTCPPorts = [ servicePort ];
systemd.services."minecraft-${worldName}" = {
after = [ "network-online.target" ];
description = "Minecraft Server";
serviceConfig = {
ExecStart = "${lib.getExe pkgs.temurin-jre-bin-17} @user_jvm_args.txt @libraries/net/minecraftforge/forge/1.20.1-47.2.20/unix_args.txt nogui";
Restart = "always";
RestartSec = 30;
StandardInput = "null";
User = "root";
WorkingDirectory = "${serviceDir}/${worldName}";
};
wantedBy = [ "multi-user.target" ];
wants = [ "network-online.target" ];
};
};
};
}
4.4.3.86. Mail server
This runs a mail server using simple-nixos-mailserver.
When changing the hashed passwords, dovecot needs to be restarted manually, it will not happen upon rebuild.
Currently, the web UI for this is a bit wonky and requires reloading the page sometimes in order to show anything (this is because my security settings are too strict - even with the security headers off! - , but I do not have time to look into it) - in any case, I do rather use mu4e along with pizauth, with the web UI just being a fallback in case I need to access special fringe accounts.
{
flake-file.inputs.simple-nixos-mailserver = {
inputs = {
git-hooks.follows = "pre-commit-hooks";
nixpkgs.follows = "nixpkgs";
};
url = "gitlab:simple-nixos-mailserver/nixos-mailserver/main";
};
flake.modules.nixos.mailserver =
{
self,
inputs,
lib,
...
}:
{
imports = lib.optionals (inputs ? simple-nixos-mailserver) [
self.modules.nixos.postgresql
self.modules.nixos.nginx
self.modules.nixos.acme
inputs.simple-nixos-mailserver.nixosModules.default
(
{
root,
config,
lib,
pkgs,
confLib,
dns,
globals,
nodes,
...
}:
let
inherit
(confLib.gen {
dir = "/var/lib/dovecot";
group = "virtualMail";
name = "mailserver";
port = 443;
user = "virtualMail";
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDir
serviceDomain
serviceGroup
serviceName
servicePort
serviceUser
;
inherit (confLib.static)
dmarcMailAddress
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
webProxy
;
baseDomain = globals.domains.main;
roundcubeDB = config.services.roundcube.database;
roundcubeDomain = config.repo.secrets.common.services.domains.roundcube;
endpointAddress4 = globals.hosts.${config.node.name}.wanAddress4;
endpointAddress6 = globals.hosts.${config.node.name}.wanAddress6;
mtaStsDomain = "mta-sts.${baseDomain}";
mtaStsPolicy = lib.concatMapStrings (line: "${line}\\r\\n") [
"version: STSv1"
"mode: enforce"
"mx: ${serviceDomain}"
"max_age: 86400"
];
in
{
swarselsystems = {
enabledServerModules = [ "mailserver" ];
server.postgresql.rolePasswordFiles.${roundcubeDB.username} =
config.sops.secrets."${roundcubeDB.username}-db-password".path;
};
topology.self.services = lib.mkMerge [
(lib.genAttrs
[
"postfix"
"dovecot"
"rspamd"
"clamav"
"roundcube"
]
(service: {
icon = root "files/topology-images/${service}.png";
name = lib.swarselsystems.toCapitalized service;
})
)
{
postfix.info = "https://${serviceDomain}";
roundcube.info = "https://${roundcubeDomain}";
}
];
globals = {
services = {
${serviceName} = {
domain = serviceDomain;
hasWebInterface = false;
proxyAddress4 = endpointAddress4;
proxyAddress6 = endpointAddress6;
};
roundcube = {
inherit
isHome
proxyAddress4
proxyAddress6
serviceAddress
;
domain = roundcubeDomain;
homeServiceAddress = lib.mkIf isHome homeServiceAddress;
};
};
dns.${globals.services.${serviceName}.baseDomain}.subdomainRecords = {
"${globals.services.${serviceName}.subDomain}" =
dns.lib.combinators.host endpointAddress4 endpointAddress6;
"${globals.services.roundcube.subDomain}" = dns.lib.combinators.host proxyAddress4 proxyAddress6;
_mta-sts.TXT = [
"v=STSv1; id=${builtins.substring 0 32 (builtins.hashString "sha256" mtaStsPolicy)}"
];
"_smtp._tls".TXT = [ "v=TLSRPTv1; rua=mailto:${dmarcMailAddress}" ];
mta-sts = dns.lib.combinators.host proxyAddress4 proxyAddress6; # name required by rfc 8461
};
monitoring = {
http = confLib.mkHttpMonitoring {
inherit servicePort;
expectedBodyRegex = "Roundcube";
hostHeader = roundcubeDomain;
scheme = "https";
serviceName = "roundcube";
};
tcp = lib.mkMerge (
lib.mapAttrsToList
(
serviceName: args:
confLib.mkTcpMonitoring (
{
inherit serviceName;
expectedRegex = "^220 ";
}
// args
)
)
{
imaps = {
expectedRegex = "^\\* OK";
servicePort = 993;
tls = true;
};
smtp.servicePort = 25;
submission.servicePort = 587;
submissions = {
servicePort = 465;
tls = true;
};
}
);
systemd = lib.mkMerge (
map
(
serviceName:
confLib.mkSystemdMonitoring {
inherit serviceName;
unit = "${serviceName}.service";
}
)
[
"postfix-tlspol"
"redis-rspamd"
"rspamd"
]
++ [
(confLib.mkSystemdMonitoring {
oneshot = true;
serviceName = "rspamd-dmarc-reporter";
unit = "rspamd-dmarc-reporter.service";
})
(confLib.mkSystemdMonitoring {
oneshot = true;
serviceName = "dane-check";
unit = "dane-check.service";
})
]
);
};
};
sops = {
secrets =
lib.genAttrs config.repo.secrets.local.mailserver.passwordSecrets (_: {
owner = serviceUser;
})
// {
"${roundcubeDB.username}-db-password" = {
group = roundcubeDB.username;
mode = "0440";
owner = config.systemd.services.postgresql.serviceConfig.User;
rekey.generator.script = "alnum";
};
mail-tls-key.owner = "acme";
parsedmarc-imap-hashed-password = {
owner = serviceUser;
rekey = {
generator = {
dependencies = [
nodes.${confLib.static.monitoringServer}.config.sops.secrets.parsedmarc-imap-password
];
script = "bcrypt";
};
keyPrefix = confLib.static.sharedSecrets.parsedmarc;
};
};
};
templates.roundcube-setup-env.content = ''
PGPASSWORD=${config.sops.placeholder."${roundcubeDB.username}-db-password"}
'';
};
users.persistentIds = {
knot-resolver = confLib.mkIds 963;
postfix-tlspol = confLib.mkIds 962;
redis-rspamd = confLib.mkIds 960;
roundcube = confLib.mkIds 961;
};
services = {
nginx.virtualHosts = {
"${roundcubeDomain}" = {
acmeRoot = null;
enableACME = false;
forceSSL = true;
locations = {
"/".recommendedSecurityHeaders = false;
"~ ^/(CHANGELOG.md|INSTALL|LICENSE|README.md|SECURITY.md|UPGRADING|composer.json|composer.lock)".recommendedSecurityHeaders =
false;
"~ ^/(SQL|bin|config|logs|temp|vendor)/".recommendedSecurityHeaders = false;
"~* \\.php(/|$)".recommendedSecurityHeaders = false;
};
useACMEHost = baseDomain;
};
};
postfix.settings.main.smtpd_client_auth_rate_limit = 10;
roundcube = {
enable = true;
configureNginx = true;
extraConfig = ''
$config['db_dsnw'] = 'pgsql://${roundcubeDB.username}:' . rawurlencode(trim(file_get_contents('${
config.sops.secrets."${roundcubeDB.username}-db-password".path
}'))) . '@unix(/run/postgresql)/${roundcubeDB.dbname}';
$config['imap_host'] = "ssl://${config.mailserver.fqdn}";
$config['smtp_host'] = "ssl://${config.mailserver.fqdn}";
$config['smtp_user'] = "%u";
$config['smtp_pass'] = "%p";
'';
# this is the url of the vhost, not necessarily the same as the fqdn of
# the mailserver
hostName = roundcubeDomain;
};
};
environment.persistence."/persist".directories = lib.mkIf config.swarselsystems.isImpermanence [
{
directory = "/var/vmail";
group = serviceGroup;
mode = "0770";
user = serviceUser;
}
{
directory = "/var/sieve";
group = serviceGroup;
mode = "0770";
user = serviceUser;
}
{
directory = "/var/dkim";
group = "rspamd";
mode = "0700";
user = "rspamd";
}
{
directory = serviceDir;
group = serviceGroup;
mode = "0700";
user = serviceUser;
}
{
directory = "/var/lib/rspamd";
group = "rspamd";
mode = "0700";
user = "rspamd";
}
{
directory = "/var/lib/roundcube";
group = "roundcube";
mode = "0700";
user = "roundcube";
}
{
directory = "/var/lib/redis-rspamd";
group = "redis-rspamd";
mode = "0700";
user = "redis-rspamd";
}
{
directory = "/var/lib/postfix";
group = "root";
mode = "0755";
user = "root";
}
{
directory = "/var/lib/knot-resolver";
group = "knot-resolver";
mode = "0770";
user = "knot-resolver";
}
];
mailserver = {
enable = true;
accounts = config.repo.secrets.local.mailserver.accounts // {
${dmarcMailAddress}.hashedPasswordFile = config.sops.secrets.parsedmarc-imap-hashed-password.path;
};
dmarcReporting.enable = true;
domains = [ baseDomain ];
enableImapSsl = true;
enableSubmission = true;
enableSubmissionSsl = true;
fqdn = serviceDomain;
indexDir = "${serviceDir}/indices";
openFirewall = true;
stateVersion = 3;
x509.useACMEHost = baseDomain;
};
security.acme.certs.${baseDomain} = {
extraLegoFlags = [
"--private-key"
config.sops.secrets.mail-tls-key.path
];
extraLegoRenewFlags = [ "--reuse-key" ];
};
systemd = {
services = {
dane-check = {
script = ''
for port in 25 465 587 993; do
case "$port" in
25 | 587) starttls="-starttls smtp" ;;
*) starttls="" ;;
esac
served=$(${lib.getExe pkgs.openssl} s_client -connect "127.0.0.1:$port" -servername ${serviceDomain} $starttls </dev/null 2>/dev/null | ${lib.getExe pkgs.openssl} x509 -pubkey -noout | ${lib.getExe pkgs.openssl} pkey -pubin -outform DER | ${pkgs.coreutils}/bin/sha256sum | ${pkgs.coreutils}/bin/cut -d" " -f1)
published=$(${pkgs.knot-dns}/bin/kdig +short TLSA "_$port._tcp.${serviceDomain}" | ${pkgs.gnused}/bin/sed -E "s/^3 1 1 //; s/ //g" | ${pkgs.coreutils}/bin/tr "A-F" "a-f")
if [ -z "$served" ] || [ "$served" != "$published" ]; then
echo "TLSA record for port $port does not match the served certificate key"
exit 1
fi
done
'';
serviceConfig = {
DynamicUser = true;
Type = "oneshot";
};
};
roundcube-setup.serviceConfig.EnvironmentFile = config.sops.templates.roundcube-setup-env.path;
};
timers.dane-check = {
timerConfig = {
OnCalendar = "daily";
Persistent = true;
RandomizedDelaySec = "1h";
};
wantedBy = [ "timers.target" ];
};
};
nodes =
let
extraConfigLoc = ''
proxy_ssl_server_name on;
proxy_ssl_name ${roundcubeDomain};
'';
in
lib.mkMerge [
{ ${idmServer} = confLib.mkKanidmOauth2ProxyAccess { serviceName = "roundcube"; }; }
{
${webProxy}.services.nginx.virtualHosts.${mtaStsDomain} = {
acmeRoot = null;
forceSSL = true;
locations."= /.well-known/mta-sts.txt".extraConfig = ''
default_type text/plain;
return 200 "${mtaStsPolicy}";
'';
useACMEHost = baseDomain;
};
}
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
extraConfigLoc
serviceAddress
serviceName
servicePort
;
maxBody = 0;
oauth2 = true;
oauth2Groups = [ "roundcube_access" ];
protocol = "https";
serviceDomain = roundcubeDomain;
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit extraConfigLoc serviceName servicePort;
extraConfig = nginxAccessRules;
maxBody = 0;
protocol = "https";
serviceAddress = homeServiceAddress;
serviceDomain = roundcubeDomain;
}
);
}
];
}
)
];
};
}
4.4.3.87. Attic (nix binary cache)
This is my nix binary cache (similar to Cachix). It is what I use in conjunction with Buildbot in order to save time when rebuilding. All packages that are built by Client machines are pushed using attic store push service, and system configurations in the above are as well.
Generate the attic server token using openssl genrsa -traditional 4096 | base64 -w0
$ attic login local http://localhost:8080 eyJ… ✍️ Configuring server "local"
$ attic cache create hello ✨ Created cache "hello" on "local"
My instance is backed by S3 storage (Garage), hence we set the nar threshold to 0.
{
flake.modules.nixos.attic =
{
self,
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
name = "attic";
port = 8091;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDir
serviceDomain
serviceName
servicePort
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
isHome
nginxAccessRules
webProxy
;
inherit (config.swarselsystems) isPublic mainUser;
serviceDB = "atticd";
withGarage = builtins.elem "garage" config.swarselsystems.enabledServerModules;
in
{
imports = [
self.modules.nixos.postgresql
];
config = {
swarselsystems = {
enabledServerModules = [ "attic" ];
server.postgresql.rolePasswordFiles = lib.mkIf (!isPublic) {
${serviceDB} = config.sops.secrets."${serviceDB}-db-password".path;
};
};
topology.self.services.${serviceName} = {
icon = "services.not-available";
info = "https://${serviceDomain}";
name = lib.swarselsystems.toCapitalized serviceName;
};
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
extra.hasWebInterface = false;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = "Attic Binary Cache";
hostHeader = serviceDomain;
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops = lib.mkIf (!isPublic) {
secrets = {
"${serviceDB}-db-password" = {
owner = config.systemd.services.postgresql.serviceConfig.User;
rekey.generator.script = "alnum";
};
attic-cache-key.rekey.generator = {
dependencies = [ config.sops.secrets.attic-server-token ];
script =
{
lib,
pkgs,
decrypt,
deps,
...
}:
''
ATTIC_SERVER_TOKEN_RS256_SECRET_BASE64=$(${decrypt} ${lib.escapeShellArg (builtins.head deps).rekey.id}) \
${pkgs.attic-server}/bin/atticadm make-token \
--config ${(pkgs.formats.toml { }).generate "atticd.toml" config.services.atticd.settings} \
--sub ${mainUser} --validity 100y \
${
lib.concatMapStringsSep " " (flag: "--${flag} ${mainUser}") [
"pull"
"push"
"delete"
"configure-cache"
"configure-cache-retention"
]
} \
| ${pkgs.coreutils}/bin/tr -d '\n'
'';
};
attic-garage-access-key = { };
attic-garage-secret-key = { };
attic-server-token.rekey.generator.script =
{ pkgs, ... }:
''
${pkgs.openssl}/bin/openssl genrsa -traditional 4096 2>/dev/null | ${pkgs.coreutils}/bin/base64 -w0
'';
};
templates."attic.env".content = ''
ATTIC_SERVER_TOKEN_RS256_SECRET_BASE64=${config.sops.placeholder.attic-server-token}
AWS_ACCESS_KEY_ID=${config.sops.placeholder.attic-garage-access-key}
AWS_SECRET_ACCESS_KEY=${config.sops.placeholder.attic-garage-secret-key}
PGPASSWORD=${config.sops.placeholder."${serviceDB}-db-password"}
'';
};
services = {
atticd = {
enable = true;
environmentFile = config.sops.templates."attic.env".path;
settings = {
allowed-hosts = [
serviceDomain
];
api-endpoint = "https://${serviceDomain}/";
chunking = {
avg-size = 64 * 1024;
max-size = 256 * 1024;
min-size = 16 * 1024;
nar-size-threshold = if withGarage then 0 else 64 * 1024; # garage using s3
};
compression = {
level = 3;
type = "zstd";
};
database.url = "postgresql://${serviceDB}@localhost/${serviceDB}?host=/run/postgresql";
garbage-collection = {
default-retention-period = "1 month";
interval = "1 day";
};
listen = "[::]:${builtins.toString servicePort}";
require-proof-of-possession = false;
storage =
if withGarage then
{
bucket = serviceName;
# attic must be patched to never serve pre-signed s3 urls directly
# otherwise it will redirect clients to a localhost garage endpoint
endpoint = "https://${globals.services."garage-${config.node.name}".domain}";
region = mainUser;
type = "s3";
}
else
{
path = serviceDir;
type = "local";
};
};
};
postgresql = {
enable = true;
enableTCPIP = true;
ensureDatabases = [ serviceDB ];
ensureUsers = [
{
ensureDBOwnership = true;
name = serviceDB;
}
];
};
};
systemd.services.atticd = lib.mkIf withGarage {
after = [ "garage.service" ];
requires = [ "garage.service" ];
};
nodes =
let
extraConfigLoc = ''
client_body_timeout 600s;
proxy_connect_timeout 600s;
proxy_send_timeout 600s;
proxy_read_timeout 600s;
proxy_request_buffering off;
'';
in
lib.mkMerge [
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
extraConfigLoc
serviceAddress
serviceDomain
serviceName
servicePort
;
maxBody = 0;
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit
extraConfigLoc
serviceDomain
serviceName
servicePort
;
extraConfig = nginxAccessRules;
maxBody = 0;
serviceAddress = homeServiceAddress;
}
);
}
];
};
};
}
4.4.3.88. Kea DHCP
This is the DHCP config that runs on my router.
IPv4 and v6 require slightly different configurations each, hence I keep the bulk of it as a function that can simply check the version for the few areas where it matters.
Apart from that, the only interesting bit here are the advertised dns- and ntp-servers (see Adguardhome and Chrony)
{
flake.modules.nixos.kea =
{
root,
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
dir = "/var/lib/private/kea";
name = "kea";
})
serviceDir
serviceName
;
inherit (confLib.static) homeDnsServer ntpServer routerServer;
dhcpX =
intX:
let
x = builtins.toString intX;
in
{
enable = true;
settings = {
interfaces-config = {
interfaces = map (name: "me-${name}") (builtins.attrNames globals.networks.home-lan.vlans);
service-sockets-max-retries = -1;
};
lease-database = {
name = "/var/lib/kea/dhcp${x}.leases";
persist = true;
type = "memfile";
};
renew-timer = 3600;
reservations-out-of-pool = true;
"subnet${x}" = lib.flip lib.mapAttrsToList globals.networks.home-lan.vlans (
vlanName: vlanCfg: {
inherit (vlanCfg) id;
interface = "me-${vlanName}";
option-data =
lib.optional (intX == 4) {
data = vlanCfg.hosts.${routerServer}."ipv${x}";
name = "routers";
}
# Advertise DNS server for VLANS that have internet access
++ lib.optional (lib.elem vlanName globals.general.internetVLANs) {
data = globals.networks.home-lan.vlans.services.hosts.${homeDnsServer}."ipv${x}";
name = if (intX == 4) then "domain-name-servers" else "dns-servers";
}
++ [
{
data = vlanCfg.hosts.${ntpServer}."ipv${x}";
name = if (intX == 4) then "ntp-servers" else "sntp-servers";
}
]
++ lib.optional (lib.elem vlanName globals.general.internetVLANs) {
data = globals.domains.main;
name = "domain-search";
}
++ lib.optional (intX == 4 && lib.elem vlanName globals.general.internetVLANs) {
data = lib.concatMapStringsSep ", " (cidr: "${cidr} - ${vlanCfg.hosts.${routerServer}.ipv4}") (
lib.mapAttrsToList (_: otherVlan: otherVlan.cidrv4) (
lib.filterAttrs (otherName: _: otherName != vlanName) globals.networks.home-lan.vlans
)
++ [
globals.networks.home-wgHome.cidrv4
"0.0.0.0/0"
]
);
name = "classless-static-route";
};
pd-pools = lib.mkIf (intX == 6) [
{
delegated-len = 64;
prefix = builtins.replaceStrings [ "::" ] [ ":0:0:100::" ] (
lib.head (lib.splitString "/" vlanCfg.cidrv6)
);
prefix-len = 56;
}
];
pools = [
{
pool = "${lib.net.cidr.host 100 vlanCfg."cidrv${x}"} - ${
lib.net.cidr.host (-6) vlanCfg."cidrv${x}"
}";
}
];
rapid-commit = lib.mkIf (intX == 6) true;
reservations = lib.concatLists (
lib.forEach (builtins.attrValues vlanCfg.hosts) (
hostCfg:
lib.optional (hostCfg.mac != null) {
duid = lib.mkIf (intX == 6) "00:03:00:01:${hostCfg.mac}"; # 00:03 = duid type 3; 00:01 = ethernet
hw-address = lib.mkIf (intX == 4) hostCfg.mac;
ip-address = lib.mkIf (intX == 4) hostCfg."ipv${x}";
ip-addresses = lib.mkIf (intX == 6) [ hostCfg."ipv${x}" ];
prefixes = lib.mkIf (intX == 6) [
"${
builtins.replaceStrings [ "::" ] [ ":0:0:${builtins.toString (256 + hostCfg.id)}::" ] (
lib.head (lib.splitString "/" vlanCfg.cidrv6)
)
}/64"
];
}
)
);
subnet = vlanCfg."cidrv${x}";
}
);
valid-lifetime = 86400;
};
};
in
{
config = {
swarselsystems.enabledServerModules = [ "kea" ];
topology = {
extractors.kea.enable = false;
self.services.${serviceName} = {
icon = root "files/topology-images/${serviceName}.png";
name = lib.swarselsystems.toCapitalized serviceName;
};
};
globals.monitoring.systemd = lib.mkMerge (
map
(
daemon:
confLib.mkSystemdMonitoring {
serviceName = "kea-${daemon}";
unit = "kea-${daemon}-server.service";
}
)
[
"dhcp4"
"dhcp6"
]
);
users.persistentIds.kea = confLib.mkIds 968;
services.kea = {
dhcp4 = dhcpX 4;
dhcp6 = dhcpX 6;
};
environment.persistence."/persist".directories = lib.mkIf config.swarselsystems.isImpermanence [
{
directory = serviceDir;
mode = "0700";
}
];
};
};
}
4.4.3.89. Hostapd
The wifi access point. This uses a single SSID for both bands and different VLANs, depending on the password provided. Channels 1 and 36 should not collide with Zigbee2MQTT
{
flake.modules.nixos.hostapd =
{
config,
lib,
pkgs,
confLib,
globals,
utils,
...
}:
let
inherit (config.repo.secrets.local.networking) wifi;
wifiVLANs = [
"home"
"guests"
"iot"
];
vlanId = vlanName: toString globals.networks.home-lan.vlans.${vlanName}.id;
pskSecret = vlanName: "wifi-psk-${vlanName}";
bridgeDevices = map (
vlanName: "sys-subsystem-net-devices-${utils.escapeSystemdPath "br-${vlanName}"}.device"
) wifiVLANs;
mkNetwork = radio: {
inherit (wifi) ssid;
authentication = {
mode = "wpa2-sha1";
wpaPskFile = config.sops.templates."hostapd.psk".path;
};
settings = {
dynamic_vlan = 1;
vlan_file = toString (
pkgs.writeText "${radio}.vlan" (
lib.concatMapStrings (
vlanName: "${vlanId vlanName} ${radio}.${vlanId vlanName} br-${vlanName}\n"
) wifiVLANs
)
);
};
};
wifi6 = {
enable = true;
multiUserBeamformer = true;
singleUserBeamformee = true;
singleUserBeamformer = true;
};
in
{
config = {
swarselsystems = {
bridgedVLANs = wifiVLANs;
enabledServerModules = [ "hostapd" ];
};
topology.self = {
services.hostapd = {
details = lib.mapAttrs (_: radio: {
text = "${radio.band}, channel ${toString radio.channel}";
}) config.services.hostapd.radios;
icon = "interfaces.wifi";
info = "VLANs: ${lib.concatStringsSep ", " wifiVLANs}";
name = "Hostapd";
};
interfaces = lib.mapAttrs (_: _: { }) config.services.hostapd.radios;
};
globals.monitoring.systemd = confLib.mkSystemdMonitoring {
serviceName = "hostapd-${config.node.name}";
unit = "hostapd.service";
};
sops = {
secrets = lib.genAttrs (map pskSecret wifiVLANs) (_: { });
templates."hostapd.psk" = {
content = lib.concatMapStrings (
vlanName:
"keyid=${vlanName} vlanid=${vlanId vlanName} 00:00:00:00:00:00 ${
config.sops.placeholder.${pskSecret vlanName}
}\n"
) wifiVLANs;
reloadUnits = [ "hostapd.service" ];
};
};
services.hostapd = {
enable = true;
radios = {
wlan2g = {
inherit wifi6;
band = "2g";
channel = 1;
countryCode = "AT";
networks.wlan2g = mkNetwork "wlan2g";
wifi4.capabilities = [
"LDPC"
"SHORT-GI-20"
"TX-STBC"
"RX-STBC1"
];
wifi5.enable = false;
};
wlan5g = {
band = "5g";
channel = 36;
countryCode = "AT";
networks.wlan5g = mkNetwork "wlan5g";
settings = {
he_oper_centr_freq_seg0_idx = 42;
vht_oper_centr_freq_seg0_idx = 42;
};
wifi4.capabilities = [
"HT40+"
"LDPC"
"SHORT-GI-20"
"SHORT-GI-40"
"TX-STBC"
"RX-STBC1"
];
wifi5 = {
capabilities = [
"RXLDPC"
"SHORT-GI-80"
"TX-STBC-2BY1"
"RX-STBC-1"
"MAX-A-MPDU-LEN-EXP7"
"RX-ANTENNA-PATTERN"
"TX-ANTENNA-PATTERN"
];
operatingChannelWidth = "80";
};
wifi6 = wifi6 // {
operatingChannelWidth = "80";
};
};
};
};
environment.etc."alloy/config.alloy".text = lib.mkIf config.services.alloy.enable (
lib.mkAfter ''
prometheus.exporter.unix "hostapd" {
set_collectors = ["wifi"]
}
prometheus.scrape "hostapd" {
targets = prometheus.exporter.unix.hostapd.targets
forward_to = [prometheus.remote_write.mimir.receiver]
job_name = "hostapd"
}
''
);
systemd = {
services.hostapd = {
after = bridgeDevices;
bindsTo = bridgeDevices;
};
network.links = lib.mapAttrs' (
radio: mac:
lib.nameValuePair "10-${radio}" {
linkConfig = {
Name = radio;
NamePolicy = "keep";
};
matchConfig = {
PermanentMACAddress = mac;
Type = "wlan";
};
}
) wifi.radios;
};
nodes.${globals.general.monitoringServer}.services.grafana.provision.alerting.rules.settings.groups =
let
radios = lib.attrNames config.services.hostapd.radios;
in
[
{
folder = "Infrastructure";
interval = "1m";
name = "hostapd-${config.node.name}";
orgId = 1;
rules = [
(confLib.mkGrafanaAlertRule {
expr = ''count(node_wifi_interface_frequency_hertz{host="${config.node.name}",device=~"${lib.concatStringsSep "|" radios}"} > 0) or vector(0)'';
summary = "fewer than ${toString (lib.length radios)} wifi radios on ${config.node.name} are operating on a channel";
threshold = lib.length radios;
title = "hostapd radio down (${config.node.name})";
uid = "hostapd_radio_down_${config.node.name}";
})
];
}
];
};
};
}
4.4.3.90. Mosquitto
MQTT broker for Home Assistant.
{
flake.modules.nixos.mosquitto =
{
config,
lib,
confLib,
...
}:
let
inherit
(confLib.gen {
dir = "/var/lib/mosquitto";
name = "mosquitto";
port = 1883;
})
serviceDir
serviceGroup
serviceName
servicePort
serviceUser
;
in
{
config = {
swarselsystems.enabledServerModules = [ serviceName ];
topology.self.services.${serviceName}.info = "mqtt://127.0.0.1:${toString servicePort}";
globals.monitoring = {
tcp = confLib.mkTcpMonitoring { inherit serviceName servicePort; };
systemd = confLib.mkSystemdMonitoring {
inherit serviceName;
unit = "${serviceName}.service";
};
};
services.${serviceName} = {
enable = true;
listeners = [
{
acl = [ "topic readwrite #" ];
address = "127.0.0.1";
omitPasswordAuth = true;
port = servicePort;
settings.allow_anonymous = true;
}
];
};
environment.persistence."/persist".directories = lib.mkIf config.swarselsystems.isImpermanence [
{
directory = serviceDir;
group = serviceGroup;
user = serviceUser;
}
];
};
key = "swarsel/server/mosquitto";
};
}
4.4.3.91. Zigbee2MQTT
This talks to my SMLIGHT SLZB-06M coordinator and publishes to Mosquitto.
{
flake.modules.nixos.zigbee2mqtt =
{
self,
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
dir = "/var/lib/zigbee2mqtt";
name = "zigbee2mqtt";
port = 8080;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDir
serviceDomain
serviceGroup
serviceName
servicePort
serviceUser
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
;
mqttListener = lib.head config.services.mosquitto.listeners;
in
{
imports = [ self.modules.nixos.mosquitto ];
config = {
swarselsystems.enabledServerModules = [ serviceName ];
topology.self.services.${serviceName}.info = "https://${serviceDomain}";
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
monitoring = {
http = confLib.mkHttpMonitoring { inherit serviceName servicePort; };
systemd = confLib.mkSystemdMonitoring {
inherit serviceName;
unit = "${serviceName}.service";
};
};
networks = confLib.mkDualFirewallRules {
forWebProxy = false;
tcpPorts = [ servicePort ];
};
};
sops.secrets.zigbee2mqtt-env = {
group = serviceGroup;
mode = "0440";
owner = serviceUser;
};
services.${serviceName} = {
enable = true;
settings = {
advanced.channel = 20;
frontend = {
enabled = true;
port = servicePort;
url = "https://${serviceDomain}";
};
mqtt.server = "mqtt://${mqttListener.address}:${toString mqttListener.port}";
serial = {
adapter = "ember";
baudrate = 115200;
port = "tcp://${globals.networks.home-lan.vlans.iot.hosts.slzb-06m.ipv4}:6638";
rtscts = false;
};
};
};
environment.persistence."/persist".directories = lib.mkIf config.swarselsystems.isImpermanence [
{
directory = serviceDir;
group = serviceGroup;
user = serviceUser;
}
];
systemd.services.${serviceName} = {
after = [ "mosquitto.service" ];
serviceConfig.EnvironmentFile = config.sops.secrets.zigbee2mqtt-env.path;
wants = [ "mosquitto.service" ];
};
nodes = lib.mkMerge [
{
${idmServer} = confLib.mkKanidmOauth2ProxyAccess { inherit serviceName; };
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit serviceDomain serviceName servicePort;
extraConfig = nginxAccessRules;
oauth2 = true;
oauth2Groups = [ "${serviceName}_access" ];
proxyWebsockets = true;
serviceAddress = homeServiceAddress;
}
);
}
];
};
};
}
4.4.3.92. Home Assistant
{
flake-file.inputs.nixos-home-assistant = {
inputs = {
flake-parts.follows = "flake-parts";
git-hooks-nix.follows = "pre-commit-hooks";
nixpkgs.follows = "nixpkgs";
pedantix.follows = "pedantix";
treefmt-nix.follows = "treefmt-nix";
};
url = "github:Swarsel/nixos-home-assistant";
};
flake.modules.nixos.home-assistant =
{
self,
inputs,
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
dir = "/var/lib/hass";
name = "home-assistant";
port = 8123;
user = "hass";
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDir
serviceDomain
serviceGroup
serviceName
servicePort
serviceUser
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
isHome
nginxAccessRules
;
inherit (config.repo.secrets.common) location;
mqttListener = lib.head config.services.mosquitto.listeners;
in
{
imports = [
inputs.nixos-home-assistant.nixosModules.default
self.modules.nixos.mosquitto
];
config = {
swarselsystems.enabledServerModules = [ serviceName ];
topology.self.services.${serviceName}.info = "https://${serviceDomain}";
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
monitoring = {
http = confLib.mkHttpMonitoring { inherit serviceName servicePort; };
systemd = confLib.mkSystemdMonitoring {
inherit serviceName;
unit = "${serviceName}.service";
};
};
networks = confLib.mkDualFirewallRules {
forWebProxy = false;
tcpPorts = [ servicePort ];
};
};
sops.secrets.home-assistant-admin-pw = { };
services.${serviceName} = {
config = {
default_config = { };
homeassistant = {
inherit (location) latitude longitude;
external_url = "https://${serviceDomain}";
name = "Home";
time_zone = location.timezone;
unit_system = "metric";
};
http = {
server_port = servicePort;
trusted_proxies =
let
wgHomeNet = globals.networks."${globals.wireguard.wgHome.netConfigPrefix}-wgHome";
in
[
"127.0.0.1"
"::1"
wgHomeNet.cidrv4
wgHomeNet.cidrv6
];
use_x_forwarded_for = true;
};
};
enable = true;
extraComponents = [
"default_config"
"isal"
"met"
"mqtt"
"radio_browser"
];
provision = {
enable = true;
areas = {
bedroom.name = "Bedroom";
kitchen.name = "Kitchen";
living_room.name = "Living Room";
};
entries = {
met = {
domain = "met";
steps = [ { } ];
};
mqtt = {
domain = "mqtt";
steps = [
{
inherit (mqttListener) port;
broker = mqttListener.address;
}
];
};
};
owner = {
name = config.repo.secrets.common.fullName;
passwordFile = config.sops.secrets.home-assistant-admin-pw.path;
username = config.swarselsystems.mainUser;
};
removeOnboardingIntegrations = true;
url = "http://127.0.0.1:${toString servicePort}";
};
};
environment.persistence."/persist".directories = lib.mkIf config.swarselsystems.isImpermanence [
{
directory = serviceDir;
group = serviceGroup;
user = serviceUser;
}
];
nodes = lib.mkMerge [
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit serviceDomain serviceName servicePort;
extraConfig = nginxAccessRules;
proxyWebsockets = true;
serviceAddress = homeServiceAddress;
}
);
}
];
};
};
}
4.4.3.93. scanservjs
I use this to send scanned documents directly to paperless
{
flake.modules.nixos.scanservjs =
{
self,
config,
lib,
pkgs,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
name = "scanservjs";
port = 8090;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
servicePort
;
inherit (confLib.static)
homeProxyIf
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
;
paperless = globals.services.paperless;
uploadAction = "Send to Paperless";
in
{
imports = [ self.modules.nixos.network-scanner ];
config = {
swarselsystems.enabledServerModules = [ serviceName ];
topology.self.services.${serviceName}.info = "https://${serviceDomain}";
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
extra.extraConfig.node = config.node.name;
};
monitoring = {
http = confLib.mkHttpMonitoring { inherit serviceName servicePort; };
systemd = confLib.mkSystemdMonitoring {
inherit serviceName;
unit = "${serviceName}.service";
};
};
networks = lib.mkMerge [
(confLib.mkDualFirewallRules {
forWebProxy = false;
tcpPorts = [ servicePort ];
})
{
${homeProxyIf}.hosts.${paperless.extraConfig.node}.firewallRuleForNode.${config.node.name}.allowedTCPPorts =
[
paperless.extraConfig.port
];
}
];
};
sops = {
secrets.scanservjs-paperless-token = { };
templates.scanservjs-paperless-header.content = ''
Authorization: Token ${config.sops.placeholder.scanservjs-paperless-token}
'';
};
users.persistentIds.${serviceName} = confLib.mkIds 930;
services.${serviceName} = {
enable = true;
# pipeline afterActions are not awaited, so a thrown error would crash the server
extraActions = [
''
{
name: '${uploadAction}',
async execute(fileInfo) {
const { execFile } = require('node:child_process');
const { promisify } = require('node:util');
try {
await promisify(execFile)('${lib.getExe pkgs.curl}', [
'--fail-with-body',
'--silent',
'--show-error',
'--header', 'Host: ${paperless.domain}',
'--header', `@''${process.env.CREDENTIALS_DIRECTORY}/paperless-header`,
'--form', `document=@''${fileInfo.fullname}`,
'http://${paperless.homeServiceAddress}:${toString paperless.extraConfig.port}/api/documents/post_document/'
]);
fileInfo.delete();
} catch (error) {
console.error(`upload of ''${fileInfo.fullname} to paperless failed: ''${error.stderr || error.message}`);
}
}
}
''
];
extraConfig = ''
config.pipelines.unshift({
extension: 'pdf',
description: 'Paperless | PDF (JPG | @:pipeline.high-quality)',
afterAction: '${uploadAction}',
commands: [
'while read filename ; do convert -quality 92 $filename converted-$(date +%s.%N).jpg ; done && ls converted-*.jpg',
'convert @- scan-0000.pdf',
'ls scan-*.*'
]
});
'';
settings = {
host = "0.0.0.0";
port = servicePort;
};
};
systemd.services.${serviceName}.serviceConfig.LoadCredential = [
"paperless-header:${config.sops.templates.scanservjs-paperless-header.path}"
];
nodes = lib.mkMerge [
{
${idmServer} = confLib.mkKanidmOauth2ProxyAccess { inherit serviceName; };
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit serviceDomain serviceName servicePort;
extraConfig = nginxAccessRules;
maxBody = 0;
oauth2 = true;
oauth2Groups = [ "${serviceName}_access" ];
serviceAddress = homeServiceAddress;
}
);
}
];
};
};
}
4.4.3.94. Chrony
This serves NTP to all my VLANs.
{
flake.modules.nixos.chrony =
{
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
dir = "/var/lib/chrony";
name = "chrony";
port = 123;
})
serviceDir
serviceGroup
serviceName
servicePort
serviceUser
;
in
{
config = {
swarselsystems.enabledServerModules = [ serviceName ];
topology.self.services.${serviceName}.name = lib.swarselsystems.toCapitalized serviceName;
globals.monitoring.systemd = confLib.mkSystemdMonitoring {
inherit serviceName;
unit = "chronyd.service";
};
services.${serviceName} = {
enable = true;
extraConfig = lib.concatMapStrings (vlan: ''
allow ${vlan.cidrv4}
allow ${vlan.cidrv6}
'') (builtins.attrValues globals.networks.home-lan.vlans);
};
environment.persistence."/persist".directories = lib.mkIf config.swarselsystems.isImpermanence [
{
directory = serviceDir;
group = serviceGroup;
mode = "0750";
user = serviceUser;
}
];
networking.nftables.firewall.rules.ntp-to-local = {
allowedUDPPorts = [ servicePort ];
from = map (name: "vlan-${name}") (builtins.attrNames globals.networks.home-lan.vlans);
to = [ "local" ];
};
};
};
}
4.4.3.95. Firezone
Firezone provides VPN access to my services at home - this works separately from the Wireguard mesh that I run between my server nodes.
The client apps need wss://<firezone>-api.<domain>/
This currently runs on a WIP branch that I have been working on for updating Firezone.
This has some state:
- OIDC setup: the Kanidm client is provisioned on both sides. Providers created by the new portal use the static redirect URL
/auth/oidc/callback; the provider migrated from the old portal keeps the legacy URLs, whose account and provider UUIDs are runtime state (seeSettings > Authentication > Kanidm). - Relay setup: relay tokens are now created using:
firezone-rpc 'IO.puts(Portal.Authentication.encode_fragment!(elem(Portal.Authentication.create_relay_token(), 1)))' - Gateway setup:
Sites > Home > Deploy Gateway:- note FIREZONETOKEN and add it as the firezone-gateway-token secret
Sometimes the GUI login fails:
pgrep -af open-deep-linkprobably has a lingering process (journalctl --user -u firezone-applet -eshowing nothing after "Opening deep-link")systemctl --user restart firezone-applet.service- Sign In, do not press cancel
- If nothing happens
systemctl restart firezone-tunnel-service, followed by another applet restart
{
flake-file.inputs.nixpkgs-firezone.url = "github:Swarsel/nixpkgs/1fef1eb69b3f8f9a778441b386eadbb1fa3fa436?narHash=sha256-HY1UfmtZOuk7Y+9cTIF8Kx5TV7qOTtRqk7A+W6lyMm8%3D";
flake.modules.nixos.firezone =
{
self,
root,
inputs,
config,
lib,
pkgs,
confLib,
globals,
nodes,
...
}:
let
inherit
(confLib.gen {
dir = "/var/lib/private/firezone";
name = "firezone";
})
baseDomain
proxyAddress4
proxyAddress6
serviceAddress
serviceDir
serviceDomain
serviceName
subDomain
;
inherit (confLib.static)
homeProxy
homeServiceAddress
homeWebProxy
idmServer
isHome
isProxied
nginxAccessRules
notificationMail
webProxy
;
apiSubDomain = "${subDomain}-api";
apiDomain = "${apiSubDomain}.${baseDomain}";
portalPort = 8080;
relayPort = 3478;
relayHealthPort = 8082;
firezoneTargetVLANs = [
"services"
"home"
"devices"
"iot"
];
firezoneTargetZones = map (v: "vlan-${v}") firezoneTargetVLANs;
homeServices = lib.filterAttrs (_: serviceCfg: serviceCfg.isHome) globals.services;
homeDomains = lib.mapAttrsToList (_: serviceCfg: serviceCfg.domain) homeServices;
smbDomain = "smb.${globals.domains.main}";
vlanCidrResources = lib.listToAttrs (
lib.concatMap (
vlan:
map
(
family:
let
name = "home.vlan-${vlan}.v${family}";
in
lib.nameValuePair name {
inherit name;
address = globals.networks.home-lan.vlans.${vlan}."cidrv${family}";
gatewayGroups = [ "home" ];
type = "cidr";
}
)
[
"4"
"6"
]
) firezoneTargetVLANs
);
allow = group: resource: {
"${group}@${resource}" = {
inherit group resource;
description = "Allow ${group} access to ${resource}";
};
};
firezoneRpc = pkgs.writeShellApplication {
name = "firezone-rpc";
text = ''
cd ${serviceDir}
RELEASE_COOKIE=$(< secrets/RELEASE_COOKIE)
export RELEASE_COOKIE
export RELEASE_HOSTNAME=${config.services.firezone.server.settings.RELEASE_HOSTNAME}
exec ${lib.getExe config.services.firezone.server.package} rpc "$@"
'';
};
disabledFirezoneModules = [
"gateway.nix"
"relay.nix"
"server.nix"
"gui-client.nix"
"headless-client.nix"
];
disabledFirezoneModule = name: "services/networking/firezone/${name}";
in
{
imports = [
self.modules.nixos.postgresql
]
++ map (
name: "${inputs.nixpkgs-firezone}/nixos/modules/${disabledFirezoneModule name}"
) disabledFirezoneModules;
config = {
swarselsystems = {
enabledServerModules = [ "firezone" ];
server.postgresql.rolePasswordFiles.firezone = config.sops.secrets.firezone-db-password.path;
};
topology.self.services.${serviceName} = {
icon = root "files/topology-images/${serviceName}.png";
info = "https://${serviceDomain}";
name = lib.swarselsystems.toCapitalized serviceName;
};
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = lib.mkMerge [
(confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; })
{
${baseDomain}.subdomainRecords.${apiSubDomain} =
inputs.dns.lib.combinators.host proxyAddress4 proxyAddress6;
}
];
monitoring.http = lib.mkMerge [
(confLib.mkHttpMonitoring {
expectedBodyRegex = ''"status":"ready"'';
path = "/readyz";
serviceName = "firezone-server";
servicePort = portalPort;
})
(confLib.mkHttpMonitoring {
path = "/readyz";
serviceName = "firezone-relay";
servicePort = relayHealthPort;
})
{
firezone-gateway = {
network = "local-${homeProxy}";
url = "http://127.0.0.1:8080/healthz";
};
}
];
networks = confLib.mkDualFirewallRules {
tcpPorts = [ portalPort ];
udpPortRanges = [
{
from = config.services.firezone.relay.lowestPort;
to = config.services.firezone.relay.highestPort;
}
];
udpPorts = [ relayPort ];
};
};
sops.secrets = {
firezone-db-password = {
owner = config.systemd.services.postgresql.serviceConfig.User;
rekey.generator.script = "alnum";
};
firezone-relay-token.mode = "0400";
kanidm-firezone = {
mode = "0400";
rekey.keyPrefix = confLib.kanidmSecrets;
};
notification-mail-pw = {
mode = "0440";
rekey.keyPrefix = notificationMail.keyPrefix;
};
};
services.firezone = {
relay = {
inherit (config.node) name;
enable = true;
apiUrl = "wss://${apiDomain}/";
openFirewall = lib.mkIf (!isProxied) true;
port = relayPort;
publicIpv4 = proxyAddress4;
publicIpv6 = proxyAddress6;
tokenFile = config.sops.secrets.firezone-relay-token.path;
};
server = {
enable = true;
api.externalUrl = "https://${apiDomain}/";
enableLocalDB = true;
portal = {
address = "0.0.0.0";
port = portalPort;
};
provision = {
enable = true;
accounts.main = {
actors.admin = {
email = "admin@${globals.domains.main}";
name = "Admin";
type = "account_admin_user";
};
auth.oidc =
let
client_id = "firezone";
issuer = "https://${globals.services.kanidm.domain}/oauth2/openid/${client_id}";
in
{
adapter = "oidc";
adapter_config = {
inherit client_id issuer;
client_secret._secret = config.sops.secrets.kanidm-firezone.path;
discovery_document_uri = "${issuer}/.well-known/openid-configuration";
};
name = "Kanidm";
};
gatewayGroups.home.name = "Home";
groups.anyone = {
members = [
"admin"
];
name = "anyone";
};
name = "Home";
policies = lib.mergeAttrsList (
lib.concatMap (resource: [
(allow "everyone" resource)
(allow "anyone" resource)
]) (lib.attrNames vlanCidrResources ++ homeDomains ++ [ smbDomain ])
);
resources =
lib.mapAttrs' (
_: serviceCfg:
lib.nameValuePair serviceCfg.domain {
address = serviceCfg.domain;
filters = [
{ protocol = "icmp"; }
{
ports = [
443
80
]
++ serviceCfg.firezoneTcpPorts;
protocol = "tcp";
}
{
ports = [ 443 ];
protocol = "udp";
}
];
gatewayGroups = [ "home" ];
name = serviceCfg.domain;
type = "dns";
}
) homeServices
// vlanCidrResources
// {
${smbDomain} = {
address = smbDomain;
filters = [
{ protocol = "icmp"; }
{
ports = [
445
139
];
protocol = "tcp";
}
];
gatewayGroups = [ "home" ];
name = smbDomain;
type = "dns";
};
};
};
};
settings.ERLANG_DISTRIBUTION_PORT = 9003;
settingsSecret.DATABASE_PASSWORD = config.sops.secrets.firezone-db-password.path;
smtp = {
inherit (config.repo.secrets.local.firezone.mail) from username;
inherit (notificationMail) host;
implicitTls = true;
passwordFile = config.sops.secrets.notification-mail-pw.path;
port = 465;
};
web.externalUrl = "https://${serviceDomain}/";
};
};
environment = {
persistence."/persist".directories = lib.mkIf config.swarselsystems.isImpermanence [
{
directory = serviceDir;
mode = "0700";
}
{
directory = "${serviceDir}-relay";
mode = "0700";
}
];
systemPackages = [ firezoneRpc ];
};
systemd.services = {
firezone-relay.environment.HEALTH_CHECK_ADDR = "0.0.0.0:${toString relayHealthPort}";
firezone-server = {
serviceConfig.RestartSec = lib.mkForce 30;
startLimitBurst = 10;
startLimitIntervalSec = 600;
};
};
nodes =
let
genNginx = toAddress: extraConfig: {
upstreams.${serviceName}.servers."${toAddress}:${toString portalPort}" = { };
virtualHosts = lib.genAttrs [ serviceDomain apiDomain ] (_: {
inherit extraConfig;
acmeRoot = null;
forceSSL = true;
locations."/" = {
proxyPass = "http://${serviceName}/";
proxyWebsockets = true;
};
useACMEHost = globals.domains.main;
});
};
in
lib.mkMerge [
{
${homeProxy} =
let
nodeCfg = nodes.${homeProxy}.config;
in
{
topology.self.services."${serviceName}-gateway" = {
icon = root "files/topology-images/${serviceName}.png";
name = lib.swarselsystems.toCapitalized "${serviceName} Gateway";
};
sops.secrets.firezone-gateway-token.mode = "0400";
services.firezone.gateway = {
inherit (nodeCfg.node) name;
enable = true;
apiUrl = "wss://${apiDomain}/";
tokenFile = nodeCfg.sops.secrets.firezone-gateway-token.path;
};
boot.kernel.sysctl = {
"net.core.rmem_max" = 134217728;
"net.core.wmem_max" = 16777216;
};
environment.persistence."/persist".directories = lib.mkIf nodeCfg.swarselsystems.isImpermanence [
{
directory = "${serviceDir}-gateway";
mode = "0700";
}
];
networking.nftables = {
chains.postrouting.masquerade-firezone = {
after = [ "hook" ];
late = true;
rules = lib.forEach firezoneTargetZones (
targetZone:
lib.concatStringsSep " " [
"meta protocol { ip, ip6 }"
(lib.head nodeCfg.networking.nftables.firewall.zones.firezone.ingressExpression)
(lib.head nodeCfg.networking.nftables.firewall.zones.${targetZone}.egressExpression)
"masquerade random"
]
);
};
firewall = {
rules = {
forward-incoming-firezone-traffic = {
from = [ "firezone" ];
to = firezoneTargetZones;
verdict = "accept";
};
forward-outgoing-firezone-traffic = {
from = firezoneTargetZones;
to = [ "firezone" ];
verdict = "accept";
};
masquerade-firezone = {
from = [ "firezone" ];
late = true; # Only accept after any rejects have been processed
to = firezoneTargetZones;
verdict = "accept";
};
};
zones.firezone.interfaces = [ "tun-firezone" ];
};
};
};
}
{
${idmServer} =
let
accountId = "33464cc5-ccc5-4565-b842-1cc323c2df5f";
externalId = "2322e386-689f-4035-a64b-ce932c2d3c61";
in
confLib.mkKanidmOidcSystem {
inherit serviceDomain serviceName;
displayName = "Firezone VPN";
originUrl = [
"https://${serviceDomain}/auth/oidc/callback"
"https://${serviceDomain}/${accountId}/sign_in/providers/${externalId}/handle_callback"
"https://${serviceDomain}/${accountId}/settings/identity_providers/openid_connect/${externalId}/handle_callback"
];
};
}
{ ${webProxy}.services.nginx = genNginx serviceAddress ""; }
{ ${homeWebProxy}.services.nginx = lib.mkIf isHome (genNginx homeServiceAddress nginxAccessRules); }
];
};
disabledModules = map disabledFirezoneModule disabledFirezoneModules;
};
}
4.4.3.96. Adguardhome
Handles my home DNS server. It also provides some nice block-lists, but the main use case is the rewrite of service records to the homeProxy IP, which circumvents bottlenecks by connecting out to the external proxy.
{
flake.modules.nixos.adguardhome =
{
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
name = "adguardhome";
port = 3000;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
servicePort
;
inherit (confLib.static)
homeDnsServer
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
webProxy
;
homeServices = lib.attrNames (lib.filterAttrs (_: serviceCfg: serviceCfg.isHome) globals.services);
homeDomains = map (name: globals.services.${name}.domain) homeServices;
in
{
config = {
swarselsystems.enabledServerModules = [ "adguardhome" ];
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring = {
dns = confLib.mkDnsMonitoring {
address = "${lib.head config.services.adguardhome.settings.dns.bind_hosts}:53";
queryName = globals.domains.main;
serviceName = "${serviceName}-dns";
};
http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = ''"running":true'';
path = "/control/status";
};
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
services.adguardhome = {
enable = true;
mutableSettings = false;
settings = {
dns = {
bind_hosts = [
globals.networks.home-lan.vlans.services.hosts.${homeDnsServer}.ipv4
globals.networks.home-lan.vlans.services.hosts.${homeDnsServer}.ipv6
];
bootstrap_dns = [
"1.1.1.1"
"2606:4700:4700::1111"
"8.8.8.8"
"2001:4860:4860::8844"
];
dhcp.enabled = false;
fallback_dns = [ "https://dns.quad9.net/dns-query" ];
ratelimit = 300;
upstream_dns = [ "https://doh.mullvad.net/dns-query" ];
};
filtering.rewrites =
(map (domain: {
inherit domain;
answer = globals.networks.home-lan.vlans.services.hosts.${homeWebProxy}.ipv4;
enabled = true;
}) homeDomains)
++ lib.mapAttrsToList (hostName: hostCfg: {
answer = hostCfg.ipv4;
domain = "server.${hostName}.${globals.domains.main}";
enabled = true;
}) globals.networks.home-lan.vlans.services.hosts
++ [
{
answer = globals.networks.home-lan.vlans.services.hosts.summers-storage.ipv4;
domain = "smb.${globals.domains.main}";
enabled = true;
}
];
filters = [
{
enabled = true;
name = "AdGuard DNS filter";
url = "https://adguardteam.github.io/AdGuardSDNSFilter/Filters/filter.txt";
}
{
enabled = true;
name = "AdAway Default Blocklist";
url = "https://adaway.org/hosts.txt";
}
{
enabled = true;
name = "OISD (Big)";
url = "https://big.oisd.nl";
}
];
http.address = "0.0.0.0:${toString servicePort}";
user_rules = config.repo.secrets.local.adguardUserRules;
};
};
environment.persistence."/persist".directories = lib.mkIf config.swarselsystems.isImpermanence [
{
directory = "/var/lib/private/AdGuardHome";
mode = "0700";
}
];
networking.firewall = {
allowedTCPPorts = [ 53 ];
allowedUDPPorts = [ 53 ];
};
nodes = lib.mkMerge [
{
${idmServer} = confLib.mkKanidmOauth2ProxyAccess { inherit serviceName; };
}
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
serviceAddress
serviceDomain
serviceName
servicePort
;
oauth2 = true;
oauth2Groups = [ "adguardhome_access" ];
proxyWebsockets = true;
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit serviceDomain serviceName servicePort;
extraConfig = nginxAccessRules;
oauth2 = true;
oauth2Groups = [ "adguardhome_access" ];
proxyWebsockets = true;
serviceAddress = homeServiceAddress;
}
);
}
];
};
};
}
4.4.3.97. Buildbot
As my configuration grows, the chance that an odd package is broken on unstable grows with it; manually pushing the flake versions hence bears the risk of running into broken builds; also, many of my configurations take a considerable time to build.
Both of these problems can be alleviated by using a service that runs builds for all of my configurations automatically. This setup runs a build of the current configuration state every day; additionally, once per week, we will also update the inputs, and if all configurations build, a PR will be opened in my project repository. If a build failed, it will instead try again the next day - the failed build might then be fixed.
Using this mechanisms, I can quite simply jump between working states of all configurations. Additionally, by pushing to Attic (nix binary cache) as part of the jobs, I also make sure that the configurations I move to are already fully cached either in the public cache or my own.
Previously I was using Hydra to build my machine configurations; however, after adopting sops-decrypt-and-cache/nix-plugins for PII management, it became a chore to use and I never managed to make it use the correct nix version that nix-plugins would be compiled for. Buildbot in this regards is way easier to use, as it is meant to run arbitrary commands and I can more easily pass it the correct nix version.
{
flake.modules.nixos.buildbot =
{
self,
root,
config,
lib,
pkgs,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
name = "buildbot";
port = 8010;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
servicePort
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
webProxy
;
inherit (config.swarselsystems) mainUser;
buildbotHosts =
lib.concatMap (arch: lib.attrNames (builtins.readDir (self + "/hosts/nixos/${arch}")))
[
"aarch64-linux"
"x86_64-linux"
];
buildbotHome = config.services.buildbot-master.home;
flakeDir = "${buildbotHome}/flake";
updateStatusFile = "${buildbotHome}/.update-status";
retryFile = "${buildbotHome}/.flake-update-retry";
githubOwner = "Swarsel";
githubRepo = "${githubOwner}/.dotfiles";
githubApi = "https://api.github.com/repos/${githubRepo}/pulls";
buildCommand = ''nix build "${flakeDir}#nixosConfigurations.$HOST.config.system.build.toplevel" --no-link --keep-going --max-jobs 3 --print-out-paths --accept-flake-config'';
nixBuilders =
systems:
''--builders "${
lib.concatMapStrings (
system: "ssh://eu.nixbuild.net ${system} - 100 1 big-parallel,benchmark;"
) systems
}"'';
buildAndPushBody = ''
HOST="$1"
result=$(${buildCommand} || ${buildCommand} --max-jobs 0 ${
nixBuilders [
"x86_64-linux"
"i686-linux"
]
})
for attempt in 1 2 3; do
if xargs attic push ${mainUser} <<< "$result"; then
exit 0
fi
if [ "$attempt" -lt 3 ]; then
sleep 10
fi
done
echo "attic push of $HOST failed after 3 attempts" >&2
'';
syncFlake = pkgs.writeShellApplication {
name = "buildbot-sync-flake";
text = ''
(
flock -x 9
if [ -d ${flakeDir}/.git ]; then
git -C ${flakeDir} fetch origin
git -C ${flakeDir} reset --hard origin/main
else
git clone --branch main https://github.com/${githubRepo}.git ${flakeDir}
fi
) 9> ${buildbotHome}/.flake-update.lock
'';
};
buildAndPush = pkgs.writeShellApplication {
name = "buildbot-build-and-push";
text = ''
${lib.getExe syncFlake}
${buildAndPushBody}
'';
};
prepareUpdateBranch = pkgs.writeShellApplication {
name = "buildbot-prepare-update-branch";
text = ''
${lib.getExe syncFlake}
cd ${flakeDir}
git remote set-url --push origin git@github.com:${githubRepo}.git
git checkout --detach origin/main
git clean -fdx
git checkout -B flake-update
'';
};
shouldRunFlakeUpdate = pkgs.writeShellApplication {
name = "buildbot-should-run-flake-update";
text = ''
if [ "''${BUILDBOT_SCHEDULER:-}" = force ] || [ "$(date +%u)" = 1 ] || [ -f ${retryFile} ]; then
echo 1
else
echo no-changes > ${updateStatusFile}
echo 0
fi
'';
};
flakeUpdateScript = pkgs.writeShellApplication {
name = "buildbot-flake-update";
text = ''
cd ${flakeDir}
touch ${retryFile}
git config user.name buildbot
git config user.email buildbot@${globals.domains.main}
git config gpg.format ssh
git config user.signingkey ${config.sops.secrets.buildbot-github-key.path}
git config commit.gpgsign true
nix flake update --accept-flake-config
if git diff --quiet flake.lock; then
rm ${retryFile}
echo no-changes > ${updateStatusFile}
exit 0
fi
nix develop ${flakeDir}#hooks --accept-flake-config -c true
git add flake.lock
git commit -m "flake: update inputs $(date +%Y-%m-%d)"
git push -u origin flake-update --force
echo has-changes > ${updateStatusFile}
'';
};
buildFlakeUpdate = pkgs.writeShellApplication {
name = "buildbot-build-flake-update";
text = ''
if grep -qx no-changes ${updateStatusFile}; then
exit 0
fi
${buildAndPushBody}
'';
};
createPR = pkgs.writeShellApplication {
name = "buildbot-create-pr";
text = ''
if grep -qx no-changes ${updateStatusFile}; then
exit 0
fi
api=(curl -sf -H "Authorization: token $(cat ${config.sops.secrets.buildbot-github-token.path})" -H "Accept: application/vnd.github.v3+json")
existing=$("''${api[@]}" "${githubApi}?head=${githubOwner}:flake-update&state=open")
if jq -e 'length == 0' <<< "$existing" > /dev/null; then
"''${api[@]}" -X POST "${githubApi}" \
-d '{"title": "flake: update inputs", "body": "Automated flake update. All NixOS configurations build.", "head": "flake-update", "base": "main"}'
fi
rm ${retryFile}
'';
};
checkStablePins = pkgs.writeShellApplication {
excludeShellChecks = [ "SC2016" ];
name = "buildbot-check-stable-pins";
text = ''
${lib.getExe syncFlake}
pins=$(nix eval --json ${flakeDir}#stablePinsUnstable --apply 'builtins.mapAttrs (_: builtins.mapAttrs (_: builtins.attrNames))' \
| jq -r 'to_entries[] | .key as $system | .value | to_entries[] | select(.key | startswith("stable")) | .key as $suffix | .value[] | "\($system) \($suffix) \(.)"') || exit 2
status=0
while read -r system suffix pkg; do
if nix build --no-link --max-jobs 0 ${
nixBuilders [
"x86_64-linux"
"i686-linux"
"aarch64-linux"
]
} "${flakeDir}#stablePinsUnstable.\"$system\".\"$suffix\".\"$pkg\"" > /dev/null 2>&1; then
echo "$pkg (nixpkgs-$suffix, $system) builds on unstable and can be unpinned"
status=1
fi
done <<< "$pins"
exit $status
'';
};
checkInsecurePermits = pkgs.writeShellApplication {
excludeShellChecks = [ "SC2016" ];
name = "buildbot-check-insecure-permits";
text = ''
${lib.getExe syncFlake}
cd ${flakeDir}
names=$(mktemp)
trap 'rm -f "$names"' EXIT
targets=$(
nix eval --json .#nixosConfigurations --apply builtins.attrNames --accept-flake-config \
| jq -r '.[] | "nixosConfigurations.\(.).config.system.build.toplevel"'
nix eval --json .#devShells --apply 'builtins.mapAttrs (_: builtins.attrNames)' --accept-flake-config \
| jq -r 'to_entries[] | select(.key | endswith("-linux")) | .key as $system | .value[] | "devShells.\($system).\(.)"'
) || exit 2
for target in $targets; do
nix-store -qR "$(nix eval --raw ".#$target.drvPath" --accept-flake-config)" || exit 2
done | sed 's|^/nix/store/[a-z0-9]*-||; s|\.drv$||' | sort -u > "$names"
status=0
permits=(${lib.escapeShellArgs pkgs.config.permittedInsecurePackages})
for permit in "''${permits[@]}"; do
if ! grep -qxF "$permit" "$names"; then
echo "$permit is no longer needed by any output and can be removed from permittedInsecurePackages"
status=1
fi
done
exit $status
'';
};
masterCfg = pkgs.writeText "master.cfg" ''
from buildbot.plugins import *
from buildbot.process.results import SUCCESS, WARNINGS
c = BuildmasterConfig = {}
c['workers'] = [worker.LocalWorker('local-worker', max_builds=1)]
c['protocols'] = {'pb': {'port': 9989}}
hosts = ${builtins.toJSON buildbotHosts}
builders = []
build_builder_names = []
for host in hosts:
f = util.BuildFactory()
f.addStep(steps.ShellCommand(
name='build-and-push',
command=['${lib.getExe buildAndPush}', host],
timeout=28800,
))
builders.append(util.BuilderConfig(
name=f'build-{host}',
workernames=['local-worker'],
factory=f,
))
build_builder_names.append(f'build-{host}')
flake_update_factory = util.BuildFactory()
flake_update_factory.addStep(steps.SetPropertyFromCommand(
name='should-run-flake-update',
command=['${lib.getExe shouldRunFlakeUpdate}'],
property='run_flake_update',
env={
'BUILDBOT_SCHEDULER': util.Interpolate('%(prop:scheduler:-)s'),
},
haltOnFailure=True,
))
flake_update_factory.addStep(steps.ShellCommand(
name='prepare-update-branch',
command=['${lib.getExe prepareUpdateBranch}'],
doStepIf=lambda step: step.build.getProperty('run_flake_update') == '1',
haltOnFailure=True,
timeout=600,
))
flake_update_factory.addStep(steps.ShellCommand(
name='flake-update',
command=['${lib.getExe flakeUpdateScript}'],
doStepIf=lambda step: step.build.getProperty('run_flake_update') == '1',
haltOnFailure=True,
timeout=3600,
))
for host in hosts:
flake_update_factory.addStep(steps.ShellCommand(
name=f'build-update-{host}',
command=['${lib.getExe buildFlakeUpdate}', host],
doStepIf=lambda step: step.build.getProperty('run_flake_update') == '1',
haltOnFailure=True,
timeout=28800,
))
flake_update_factory.addStep(steps.ShellCommand(
name='create-pr',
command=['${lib.getExe createPR}'],
doStepIf=lambda step: step.build.getProperty('run_flake_update') == '1',
timeout=300,
))
builders.append(util.BuilderConfig(
name='flake-update',
workernames=['local-worker'],
factory=flake_update_factory,
))
pin_check_factory = util.BuildFactory()
pin_check_factory.addStep(steps.ShellCommand(
name='check-stable-pins',
command=['${lib.getExe checkStablePins}'],
decodeRC={0: SUCCESS, 1: WARNINGS},
timeout=7200,
))
builders.append(util.BuilderConfig(
name='check-stable-pins',
workernames=['local-worker'],
factory=pin_check_factory,
))
insecure_check_factory = util.BuildFactory()
insecure_check_factory.addStep(steps.ShellCommand(
name='check-insecure-permits',
command=['${lib.getExe checkInsecurePermits}'],
decodeRC={0: SUCCESS, 1: WARNINGS},
timeout=14400,
))
builders.append(util.BuilderConfig(
name='check-insecure-permits',
workernames=['local-worker'],
factory=insecure_check_factory,
))
all_builder_names = build_builder_names + ['flake-update', 'check-stable-pins', 'check-insecure-permits']
c['builders'] = builders
c['schedulers'] = [
schedulers.Periodic(
name='nightly',
builderNames=build_builder_names,
periodicBuildTimer=86400,
),
schedulers.Nightly(
name='daily-flake-update',
builderNames=['flake-update'],
hour=3,
minute=0,
),
schedulers.Periodic(
name='weekly-pin-check',
builderNames=['check-stable-pins'],
periodicBuildTimer=604800,
),
schedulers.Periodic(
name='weekly-insecure-check',
builderNames=['check-insecure-permits'],
periodicBuildTimer=604800,
),
schedulers.ForceScheduler(
name='force',
builderNames=all_builder_names,
),
]
c['www'] = dict(port=${builtins.toString servicePort})
c['db'] = dict(db_url='sqlite:///state.sqlite')
c['title'] = '${config.repo.secrets.common.names.buildbot}'
c['titleURL'] = 'https://${serviceDomain}'
c['buildbotURL'] = 'https://${serviceDomain}/'
c['buildbotNetUsageData'] = None
'';
in
{
imports = [
self.modules.nixos.attic-setup
];
config = {
swarselsystems.enabledServerModules = [ "buildbot" ];
topology.self.services.${serviceName} = {
icon = root "files/topology-images/${serviceName}.png";
info = "https://${serviceDomain}";
name = "Buildbot";
};
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = "Buildbot Web UI";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops.secrets =
lib.genAttrs
[
"buildbot-age-key"
"buildbot-github-key"
"buildbot-github-token"
]
(_: {
group = "buildbot";
mode = "0400";
owner = "buildbot";
});
users = {
users.${serviceName} = {
extraGroups = [ "builder" ];
subGidRanges = [
{
count = 999;
startGid = 1001;
}
];
subUidRanges = [
{
count = 65534;
startUid = 100001;
}
];
};
persistentIds.${serviceName} = confLib.mkIds 1002; # must be a normal user
};
services = {
buildbot-master = {
inherit masterCfg;
enable = true;
home = "/home/buildbot";
packages = with pkgs; [
config.nix.package
bash
coreutils
ssh-to-age
git
attic-client
util-linux
openssh
sops
curl
jq
gnugrep
gnused
];
pythonPackages = _p: [
pkgs.buildbot-worker
];
};
pii-agent = {
ageKeyFile = config.sops.secrets.buildbot-age-key.path;
sshKey = null;
user = serviceName;
};
};
programs.ssh.extraConfig = lib.mkAfter ''
Host github.com
IdentityFile ${config.sops.secrets.buildbot-github-key.path}
IdentitiesOnly yes
StrictHostKeyChecking accept-new
'';
environment.persistence."/persist".directories = lib.mkIf config.swarselsystems.isImpermanence [
{
directory = buildbotHome;
group = "buildbot";
mode = "0750";
user = "buildbot";
}
];
nix = {
gc = {
options = lib.mkForce "--delete-older-than 2d";
automatic = true;
dates = lib.mkForce "20:00";
};
settings = {
max-free = lib.mkForce (40 * 1024 * 1024 * 1024);
min-free = lib.mkForce (15 * 1024 * 1024 * 1024);
trusted-users = [ "buildbot" ];
};
};
systemd = {
services = {
buildbot-master.serviceConfig = {
MemoryMax = "20G";
Restart = "always";
};
nix-daemon.serviceConfig = {
MemoryHigh = "14G";
MemoryMax = "18G";
};
};
tmpfiles.settings."10-buildbot" =
lib.genAttrs
[
flakeDir
"${buildbotHome}/master"
]
(_: {
d = {
group = "buildbot";
mode = "0750";
user = "buildbot";
};
});
};
nodes = lib.mkMerge [
{
${idmServer} = confLib.mkKanidmOauth2ProxyAccess { inherit serviceName; };
}
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
serviceAddress
serviceDomain
serviceName
servicePort
;
oauth2 = true;
oauth2Groups = [ "buildbot_access" ];
proxyWebsockets = true;
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit serviceDomain serviceName servicePort;
extraConfig = nginxAccessRules;
oauth2Groups = [ "buildbot_access" ];
proxyWebsockets = true;
serviceAddress = homeServiceAddress;
}
);
}
];
};
};
}
4.4.3.98. SearX
I really love Kagi. However, I do not love it for it's AI features, or particularly for it's search results. What I always really enjoyed from it was the ability to manipulate the search results in a way that I saw fit.
However, I was not ready to pay 10€ per month just for that; using SearXNG, Thanks to the amazing hostnames plugin, I get the capability of blocking some really annoying sites, as well as increasing/decreasing the weight of some other sites.
{
flake.modules.nixos.searx =
{
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
name = "searx";
port = 3002;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceGroup
serviceName
servicePort
serviceUser
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
webProxy
;
in
{
config = {
swarselsystems.enabledServerModules = [ "searx" ];
topology.self.services.searxng.info = "https://${serviceDomain}";
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = "OK";
path = "/healthz";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops = {
secrets.searx-secret = {
group = serviceGroup;
mode = "0440";
owner = serviceUser;
rekey.generator.script = "alnum";
};
templates.searx-env = {
content = ''
SEARXNG_SECRET="${config.sops.placeholder.searx-secret}"
'';
group = serviceGroup;
mode = "0440";
owner = serviceUser;
};
};
users.persistentIds.searx = confLib.mkIds 950;
services.${serviceName} = {
enable = true;
environmentFile = config.sops.templates.searx-env.path;
redisCreateLocally = true;
settings = {
default_doi_resolver = "sci-hub.se";
doi_resolvers = {
"doai.io" = "https://dissem.in/";
"doi.org" = "https://doi.org/";
"oadoi.org" = "https://oadoi.org/";
"sci-hub.ru" = "https://sci-hub.ru/";
"sci-hub.se" = "https://sci-hub.se/";
"sci-hub.st" = "https://sci-hub.st/";
};
enabled_plugins = [
"Calculator"
"Self information"
"Hash plugin"
"Hostname replace"
"Open Access DOI rewrite"
"Timezones plugin"
"Tor check plugin"
"Tracker URL remover"
"Unit converter plugin"
];
engines = lib.mapAttrsToList (name: value: { inherit name; } // value) {
"aol images".disabled = true;
brave.disabled = true;
"brave.images".disabled = true;
deviantart.disabled = true;
"duckduckgo images".disabled = true;
"google images".disabled = true;
karmasearch.disabled = true;
"karmasearch images".disabled = true;
"karmasearch videos".disabled = true;
pexels.disabled = true;
"qwant images".disabled = true;
startpage.disabled = true;
"startpage images".disabled = true;
unsplash.disabled = true;
};
faviconsSettings.favicons = {
cache = {
BLOB_MAX_BYTES = 40960;
HOLD_TIME = 5184000;
LIMIT_TOTAL_BYTES = 2147483648;
MAINTENANCE_MODE = "auto";
MAINTENANCE_PERIOD = 600;
db_url = "/run/searx/faviconcache.db";
};
cfg_schema = 1;
proxy.max_age = 5184000;
};
general = {
contact_url = false;
debug = false;
donation_url = false;
enable_metrics = true;
instance_name = config.repo.secrets.common.names.searx;
privacypolicy_url = false;
};
# hostname_replace = {
# "pinterest\.com" = false;
# };
hostnames = {
high_priority = [
"(.*\\.)?arxiv\\.org$"
"(.*\\.)?askubuntu\\.com$"
"(.*\\.)?caniuse\\.com$"
"(.*\\.)?codeberg\\.org$"
"(.*\\.)?crates\\.io$"
"(.*\\.)?crossref\\.org$"
"(.*\\.)?dev\\.mysql\\.com$"
"(.*\\.)?devdocs\\.io$"
"(.*\\.)?developer\\.mozilla\\.org$"
"(.*\\.)?discourse\\.nixos\\.org$"
"(.*\\.)?doc\\.rust-lang\\.org$"
"(.*\\.)?docker\\.com$"
"(.*\\.)?docs\\.ansible\\.com$"
"(.*\\.)?docs\\.docker\\.com$"
"(.*\\.)?docs\\.python\\.org$"
"(.*\\.)?forums\\.gentoo\\.org$"
"(.*\\.)?freebsd\\.org$"
"(.*\\.)?git-scm\\.com$"
"(.*\\.)?github\\.com$"
"(.*\\.)?gitlab\\.com$"
"(.*\\.)?golang\\.org$"
"(.*\\.)?hackerne\\.ws$"
"(.*\\.)?helm\\.sh$"
"(.*\\.)?hub\\.docker\\.com$"
"(.*\\.)?huggingface\\.co$"
"(.*\\.)?ieeexplore\\.ieee\\.org$"
"(.*\\.)?kernel\\.org$"
"(.*\\.)?kubernetes\\.io$"
"(.*\\.)?letsencrypt\\.org$"
"(.*\\.)?lobste\\.rs$"
"(.*\\.)?mongodb\\.com/docs$"
"(.*\\.)?news\\.ycombinator\\.com$"
"(.*\\.)?nginx\\.org$"
"(.*\\.)?nixos\\.org$"
"(.*\\.)?nodejs\\.org$"
"(.*\\.)?npmjs\\.com$"
"(.*\\.)?old\\.reddit\\.com$"
"(.*\\.)?openwrt\\.org$"
"(.*\\.)?pkg\\.go\\.dev$"
"(.*\\.)?postgresql\\.org$"
"(.*\\.)?pubmed\\.ncbi\\.nlm\\.nih\\.gov$"
"(.*\\.)?pypi\\.org$"
"(.*\\.)?redd\\.it$"
"(.*\\.)?reddit\\.com$"
"(.*\\.)?scholar\\.google\\.com$"
"(.*\\.)?search\\.nixos\\.org$"
"(.*\\.)?semanticscholar\\.org$"
"(.*\\.)?serverfault\\.com$"
"(.*\\.)?specifications\\.freedesktop\\.org$"
"(.*\\.)?sqlite\\.org$"
"(.*\\.)?stackexchange\\.com$"
"(.*\\.)?stackoverflow\\.com$"
"(.*\\.)?superuser\\.com$"
"(.*\\.)?terraform\\.io$"
"(.*\\.)?tldp\\.org$"
"(.*\\.)?w3\\.org$"
"(.*\\.)?web\\.dev$"
"(.*\\.)?wiki\\.archlinux\\.org$"
"(.*\\.)?wiki\\.gentoo\\.org$"
"(.*\\.)?wiki\\.nixos\\.org$"
"(.*\\.)?wikipedia\\.org$"
];
low_priority = [
"(.*\\.)?medium\\.com$"
"(.*\\.)?quora\\.com$"
];
remove = [
"(.*\\.)?answers\\.microsoft\\.com$"
"(.*\\.)?breitbart\\.com$"
"(.*\\.)?dailymail\\.co\\.uk$"
"(.*\\.)?etsy\\.com$"
"(.*\\.)?facebook\\.com$"
"(.*\\.)?foxnews\\.com$"
"(.*\\.)?geeksforgeeks\\.org$"
"(.*\\.)?githubplus\\.com$"
"(.*\\.)?instagram\\.com$"
"(.*\\.)?linkedin\\.com$"
"(.*\\.)?msn\\.com$"
"(.*\\.)?nixos\\.wiki$"
"(.*\\.)?pinterest\\.ca$"
"(.*\\.)?pinterest\\.co\\.uk$"
"(.*\\.)?pinterest\\.com$"
"(.*\\.)?pinterest\\.com\\.au$"
"(.*\\.)?pinterest\\.de$"
"(.*\\.)?pinterest\\.es$"
"(.*\\.)?pinterest\\.fr$"
"(.*\\.)?play\\.google\\.com$"
"(.*\\.)?redditmedia\\.com$"
"(.*\\.)?softonic\\.com$"
"(.*\\.)?tiktok\\.com$"
"(.*\\.)?twitter\\.com$"
"(.*\\.)?w3schools\\.com$"
"(.*\\.)?wikihow\\.com$"
];
replace = {
"(.*\\.)?redd\\.it$" = "old.reddit.com";
"(.*\\.)?reddit\\.com$" = "old.reddit.com";
"(.*\\.)?youtu\\.be$" = globals.services.invidious.domain;
"(.*\\.)?youtube\\.com$" = globals.services.invidious.domain;
};
};
search = {
autocomplete = "google"; # "dbpedia", "duckduckgo", "google", "startpage", "swisscows", "qwant", "wikipedia" - leave blank to turn it off by default
autocomplete_min = 3;
default_lang = "en";
favicon_resolver = "google";
formats = [
"html"
"json"
"rss"
];
safe_search = 0; # 0 = None, 1 = Moderate, 2 = Strict
};
server = {
base_url = "https://${globals.services.${serviceName}.domain}";
bind_address = "0.0.0.0";
image_proxy = true;
limiter = false;
port = servicePort;
public_instance = false;
};
ui = {
center_alignment = true;
default_locale = "en";
default_theme = "simple";
infinite_scroll = false;
query_in_title = true;
search_on_category_select = true;
static_use_hash = true;
theme_args.simple_style = "auto";
};
};
};
environment.persistence."/persist".directories = lib.mkIf config.swarselsystems.isImpermanence [
{
directory = "/var/lib/redis-${serviceName}";
group = serviceGroup;
mode = "0700";
user = serviceUser;
}
];
systemd.services.${serviceName} = {
partOf = [ "redis-${serviceName}.service" ];
requires = [ "redis-${serviceName}.service" ];
};
nodes = lib.mkMerge [
{
${idmServer} = confLib.mkKanidmOauth2ProxyAccess { inherit serviceName; };
}
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
serviceAddress
serviceDomain
serviceName
servicePort
;
oauth2 = true;
oauth2Groups = [ "searx_access" ];
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit serviceDomain serviceName servicePort;
extraConfig = nginxAccessRules;
oauth2 = true;
oauth2Groups = [ "searx_access" ];
serviceAddress = homeServiceAddress;
}
);
}
];
};
};
}
4.4.3.99. Invidious
This is a service that lets me watch YouTube with less trackers, essentially. That is however not my main reason for using it. The main reason would be that YouTube, for a while now, for some reason defaults streams to 360p on my machine. Ads I already circumvent using uBlock in any case.
Apart from that, this has some nice features like the ability to turn off comments on videos - which is something that I otherwise like to waste time reading on often.
I use this in conjunction with the Glide plugin "Redirector" to make sure that all YouTube URLs instead point to my Invidious instance.
For SponsorBlock, configure the SponsorBlock extension in Glide under Miscellaneous > Support 3rd Party YouTube-Sites > Add 3rd-Party Client Instance > <invidiousDomain>
{
flake.modules.nixos.invidious =
{
self,
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
name = "invidious";
port = 3001;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
servicePort
serviceUser
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
webProxy
;
extraSettingsCredential = "extra-settings";
notificationStream = proxyPass: {
inherit proxyPass;
extraConfig = "proxy_buffering off;";
};
in
{
imports = [
self.modules.nixos.postgresql
];
config = {
swarselsystems = {
enabledServerModules = [ "invidious" ];
server.postgresql.rolePasswordFiles.${serviceUser} =
config.sops.secrets."${serviceUser}-db-password".path;
};
topology.self.services.${serviceName}.info = "https://${serviceDomain}";
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
alertFor = "30m";
expectedBodyRegex = "Invidious";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops = {
secrets = {
"${serviceUser}-db-password" = {
owner = config.systemd.services.postgresql.serviceConfig.User;
rekey.generator.script = "alnum";
};
invidious-companion-key = {
mode = "0444";
rekey.keyPrefix = confLib.static.sharedSecrets.invidiousCompanion;
};
};
templates.invidiousExtraSettings.content = builtins.toJSON {
db.password = config.sops.placeholder."${serviceUser}-db-password";
invidious_companion_key = config.sops.placeholder.invidious-companion-key;
};
};
services = {
${serviceName} = {
enable = true;
domain = serviceDomain;
extraSettingsFile = "/run/credentials/${serviceName}.service/${extraSettingsCredential}";
http3-ytproxy.enable = true;
nginx.enable = true;
port = servicePort;
settings = {
db.user = serviceUser;
default_user_preferences = {
dark_mode = "dark";
default_home = "Subscriptions";
extend_desc = true;
feed_menu = [
"Subscriptions"
"Playlists"
"Trending"
];
local = true;
player_style = "youtube";
quality = "dash";
save_player_pos = true;
};
external_port = 80;
https_only = false;
invidious_companion = [
{
private_url = "https://${serviceDomain}/companion";
public_url = "https://${serviceDomain}/companion";
}
];
popular_enabled = false;
};
};
nginx.virtualHosts.${serviceDomain} = {
enableACME = false;
forceSSL = false;
locations."/api/v1/auth/notifications" =
notificationStream "http://127.0.0.1:${builtins.toString servicePort}";
};
};
environment.persistence."/persist".directories = lib.mkIf config.swarselsystems.isImpermanence [
{ directory = "/var/lib/private/invidious"; }
];
systemd.services.${serviceName}.serviceConfig.LoadCredential = [
"${extraSettingsCredential}:${config.sops.templates.invidiousExtraSettings.path}"
];
nodes =
let
genNginx = toAddress: extraConfig: {
upstreams = {
${serviceName}.servers = {
"${toAddress}:80" = { };
};
};
virtualHosts = {
"${serviceDomain}" = {
inherit extraConfig;
acmeRoot = null;
forceSSL = true;
locations = {
"/".proxyPass = "http://${serviceName}";
"/api/v1/auth/notifications" = notificationStream "http://${serviceName}";
};
oauth2 = {
enable = true;
allowedGroups = [ "invidious_access" ];
};
useACMEHost = globals.domains.main;
};
};
};
in
lib.mkMerge [
{ ${idmServer} = confLib.mkKanidmOauth2ProxyAccess { inherit serviceName; }; }
{ ${webProxy}.services.nginx = genNginx serviceAddress ""; }
{ ${homeWebProxy}.services.nginx = lib.mkIf isHome (genNginx homeServiceAddress nginxAccessRules); }
];
};
};
}
4.4.3.100. Invidious-companion
In the recent efforts of the Invidious team to make sure that the service works, the sig-helper as well as session generator were dropped in favor of this companion app. Sadly this is a Deno app, which can not be packaged cleanly in nix as of writing (). What I thus do is to use the unpatched binary together with nix-ld (although I use a more lightweight setup here) .
The tool itself fetches a token that can then be used by Invidious to start a session. Sadly, most VPS providers' IP ranges have been blocked by YouTube for this purpose, so I run this app on a local server instead.
YouTube in theory has the IP where the PO token was derived from; however, when watching the actual videos, those run through the Invidious proxy which protects most information.
{
flake-file.inputs.invidious-companion = {
flake = false;
url = "https://github.com/iv-org/invidious-companion/releases/download/release-master/invidious_companion-x86_64-unknown-linux-gnu.tar.gz";
};
flake.modules.nixos.invidious-companion =
{ inputs, lib, ... }:
{
imports = lib.optionals (inputs ? invidious-companion) [
(
{
inputs,
config,
lib,
pkgs,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
name = "invidious-companion";
port = 8282;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceName
servicePort
;
inherit (confLib.gen { name = "invidious"; }) serviceDomain;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
isHome
nginxAccessRules
webProxy
;
companion = pkgs.runCommand "invidious-companion" { } ''
install -Dm755 ${inputs.invidious-companion}/invidious_companion $out/bin/invidious_companion
'';
in
{
swarselsystems.enabledServerModules = [ "invidious-companion" ];
topology.self.services.${serviceName} = {
icon = "services.invidious";
info = "https://${serviceDomain}/companion";
name = "invidious-companion";
};
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
extra.hasWebInterface = false;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = "OK";
path = "/healthz";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops = {
secrets.invidious-companion-key = {
mode = "0444";
rekey = {
generator = {
args.length = 16;
script = "alnum";
};
keyPrefix = confLib.static.sharedSecrets.invidiousCompanion;
};
};
templates."invidious-companion.env" = {
content = ''
SERVER_SECRET_KEY=${config.sops.placeholder.invidious-companion-key}
HOST=0.0.0.0
'';
mode = "0444";
};
};
programs.nix-ld.enable = true; # invidious-companion runs as an unpatched deno app
systemd.services.invidious-companion = {
after = [ "network.target" ];
description = "Invidious companion service";
# https://github.com/iv-org/invidious-companion/issues/397
environment = {
NETWORKING_FETCH_RETRY_DEBOUNCE_MULTIPLIER = "1";
NETWORKING_FETCH_RETRY_ENABLED = "true";
NETWORKING_FETCH_RETRY_TIMES = "3";
};
serviceConfig = {
DynamicUser = true;
EnvironmentFile = config.sops.templates."invidious-companion.env".path;
ExecStart = "${companion}/bin/invidious_companion";
Restart = "on-failure";
};
wantedBy = [ "multi-user.target" ];
};
nodes =
let
genNginx = toAddress: extraConfig: {
upstreams = {
"${serviceName}".servers = {
"${toAddress}:${builtins.toString servicePort}" = { };
};
};
virtualHosts = {
"${serviceDomain}" = {
inherit extraConfig;
acmeRoot = null;
forceSSL = true;
locations."/companion" = {
bypassAuth = true;
proxyPass = "http://${serviceName}";
};
useACMEHost = globals.domains.main;
};
};
};
homeInvidiousFallback = lib.optionalAttrs (!globals.services.invidious.isHome) {
virtualHosts.${serviceDomain}.locations =
let
fallback = extraConfig: {
extraConfig = ''
proxy_ssl_server_name on;
proxy_ssl_name ${serviceDomain};
${extraConfig}
'';
proxyPass = "https://${globals.services.invidious.proxyAddress4}";
};
in
{
"/" = fallback "";
"/api/v1/auth/notifications" = fallback "proxy_buffering off;";
};
};
in
lib.mkMerge [
{ ${webProxy}.services.nginx = genNginx serviceAddress ""; }
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
lib.recursiveUpdate (genNginx homeServiceAddress nginxAccessRules) homeInvidiousFallback
);
}
];
}
)
];
};
}
4.4.3.101. Firefox-syncserver
I only use Firefox sync for bookmarks and history; to me, those are not "important" information, hence I keep this service in the cloud.
Setting it up on android:
- Sign out of any Mozilla account, then force close
- Settings > About Firefox: tap the Firefox logo 5 times.
- Settings > Sync Debug (at the top under sign in)
- Custom sync server: https://<ffsyncdomain>/1.0/sync/1.5.
- Force close
{
flake.modules.nixos.firefox-syncserver =
{
config,
lib,
pkgs,
confLib,
...
}:
let
inherit
(confLib.gen {
name = "firefox-syncserver";
port = 5000;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceGroup
serviceName
servicePort
serviceUser
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
isHome
nginxAccessRules
webProxy
;
in
{
config = {
swarselsystems.enabledServerModules = [ "firefox-syncserver" ];
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
extra.hasWebInterface = false;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = ''"status":"Ok"'';
path = "/__heartbeat__";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops = {
secrets.firefox-syncserver-secret = {
group = serviceGroup;
mode = "0400";
owner = serviceUser;
rekey.generator.script = "hex";
};
templates."firefox-syncserver.env" = {
content = ''
SYNC_MASTER_SECRET=${config.sops.placeholder."firefox-syncserver-secret"}
'';
group = serviceGroup;
mode = "0400";
owner = serviceUser;
};
};
users = {
users.firefox-syncserver = {
group = "firefox-syncserver";
isSystemUser = true;
};
groups.firefox-syncserver = { };
persistentIds.firefox-syncserver = confLib.mkIds 949;
};
services = {
${serviceName} = {
enable = true;
database.type = "mysql";
secrets = config.sops.templates."firefox-syncserver.env".path;
settings = {
host = "0.0.0.0";
port = servicePort;
tokenserver.enabled = true;
};
singleNode = {
enable = true;
capacity = 1;
enableNginx = false;
enableTLS = false;
hostname = serviceDomain;
url = "https://${serviceDomain}";
};
};
mysql.package = pkgs.mariadb;
};
environment.persistence."/persist".directories = lib.mkIf config.swarselsystems.isImpermanence [
{ directory = "/var/lib/private/firefox-syncserver"; }
];
systemd.services.firefox-syncserver.serviceConfig.StateDirectory = "firefox-syncserver";
nodes = lib.mkMerge [
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
serviceAddress
serviceDomain
serviceName
servicePort
;
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit serviceDomain serviceName servicePort;
extraConfig = nginxAccessRules;
serviceAddress = homeServiceAddress;
}
);
}
];
};
};
}
4.4.3.102. CrowdSec
The firewall bouncer module seems a bit broken in regards to deploying a new instance; half of this module is just working around these issues. For now, I fix this with the crowdsecBootstrap flag.
{
flake.modules.nixos.crowdsec =
{
config,
lib,
confLib,
globals,
...
}:
let
bootstrap = config.swarselsystems.crowdsecBootstrap;
withNginx = config.services.nginx.enable;
jumphost = globals.hosts.${globals.general.jumphost};
homeWan = globals.networks.home-wan;
allowlist = config.repo.secrets.local.crowdsec;
allowlistIps = allowlist.allowlistIps or [ ];
allowlistCidrs = allowlist.allowlistCidrs or [ ];
allowlistCountryScenarios = allowlist.allowlistCountryScenarios or { };
stateDir = "/var/lib/crowdsec/state";
lapiPort = 8089;
in
{
options.swarselsystems.crowdsecBootstrap = lib.mkEnableOption "create lapi, capi, and bouncer api key. afterwards they can be added to sops and this disabled";
config = {
swarselsystems.enabledServerModules = [ "crowdsec" ];
globals.monitoring.http = confLib.mkHttpMonitoring {
expectedStatus = 403;
path = "/v1/decisions";
serviceName = "crowdsec-${config.node.name}";
servicePort = lapiPort;
};
sops.secrets = lib.mkIf (!bootstrap) (
lib.genAttrs [ "crowdsec-bouncer-key" "crowdsec-capi" "crowdsec-lapi" ] (_: {
group = "crowdsec";
mode = "0400";
owner = "crowdsec";
})
);
users = {
users.crowdsec.extraGroups = lib.optional withNginx "nginx";
persistentIds.crowdsec = confLib.mkIds 946;
};
services = {
crowdsec = {
enable = true;
autoUpdateService = true;
hub.collections = [
"crowdsecurity/linux"
"crowdsecurity/sshd"
]
++ lib.optionals withNginx [
"crowdsecurity/nginx"
"crowdsecurity/base-http-scenarios"
"crowdsecurity/http-cve"
];
settings = {
config = {
api = {
client.credentials_path =
if bootstrap then "${stateDir}/lapi.yaml" else config.sops.secrets.crowdsec-lapi.path;
server = {
listen_uri = "127.0.0.1:${toString lapiPort}";
online_client.credentials_path =
if bootstrap then "${stateDir}/capi.yaml" else config.sops.secrets.crowdsec-capi.path;
};
};
config_paths.data_dir = stateDir;
prometheus.listen_port = 6060;
};
acquisitions = [
{
journalctl_filter = [ "_SYSTEMD_UNIT=sshd.service" ];
labels.type = "syslog";
source = "journalctl";
}
]
++ lib.optional withNginx {
filenames = [
"/var/log/nginx/access.log"
"/var/log/nginx/error.log"
];
labels.type = "nginx";
source = "file";
};
parsers.s02Enrich = [
{
name = "local/private-networks";
whitelist = {
cidr = [
"10.0.0.0/8"
"172.16.0.0/12"
"192.168.0.0/16"
"fc00::/7"
];
reason = "private networks";
};
}
{
name = "local/home-wan";
whitelist = {
cidr = [
homeWan.cidrv4
homeWan.cidrv6
];
reason = "home wan";
};
}
]
++ lib.optional withNginx {
name = "local/attic-cache";
whitelist = {
expression = [ "evt.Meta.http_path matches `\\.nar(info)?$`" ];
reason = "attic cache lookups";
};
}
++ lib.optional (allowlistIps != [ ] || allowlistCidrs != [ ]) {
name = "local/allowlist";
whitelist = {
cidr = allowlistCidrs;
ip = allowlistIps;
reason = "allowlisted addresses";
};
};
postOverflows.s01Whitelist = [
{
name = "local/hosts";
whitelist = {
ip = lib.filter (a: a != null) (
lib.concatMap (h: [
h.wanAddress4
h.wanAddress6
]) (lib.attrValues globals.hosts)
);
reason = "host wan addresses";
};
}
{
name = "local/allowlist-as";
whitelist = {
expression = map (
asn: "evt.Overflow.Alert.Source.AsNumber == '${toString asn}'"
) allowlist.allowlistAs;
reason = "allowlisted as";
};
}
]
++ lib.optional (allowlistCountryScenarios != { }) {
name = "local/allowlist-country-scenarios";
whitelist = {
expression = lib.flatten (
lib.mapAttrsToList (
country:
map (
scenario:
"evt.Overflow.Alert.Source.Cn == '${country}' && evt.Overflow.Alert.GetScenario() contains '${scenario}'"
)
) allowlistCountryScenarios
);
reason = "noisy scenarios from home country";
};
};
};
};
crowdsec-firewall-bouncer = {
enable = true;
createRulesets = false;
registerBouncer.enable = bootstrap;
secrets.apiKeyPath = lib.mkIf (!bootstrap) config.sops.secrets.crowdsec-bouncer-key.path;
};
};
environment = {
etc."alloy/config.alloy".text = lib.mkIf config.services.alloy.enable (
lib.mkAfter ''
prometheus.scrape "crowdsec" {
targets = [{"__address__" = "127.0.0.1:${toString config.services.crowdsec.settings.config.prometheus.listen_port}"}]
forward_to = [prometheus.remote_write.mimir.receiver]
job_name = "crowdsec"
scrape_interval = "30s"
}
''
);
persistence."/persist" = lib.mkIf config.swarselsystems.isImpermanence {
directories = [
{
directory = "/var/lib/crowdsec";
group = "crowdsec";
mode = "0750";
user = "crowdsec";
}
];
};
};
networking.nftables.ruleset = ''
table ip crowdsec {
set crowdsec-blacklists {
type ipv4_addr
flags timeout
}
chain crowdsec-chain {
type filter hook input priority filter; policy accept;
ct state established,related accept
ip saddr { ${jumphost.wanAddress4}, ${homeWan.cidrv4} } tcp dport 22 accept
ip saddr @crowdsec-blacklists drop
}
}
table ip6 crowdsec6 {
set crowdsec6-blacklists {
type ipv6_addr
flags timeout
}
chain crowdsec6-chain {
type filter hook input priority filter; policy accept;
ct state established,related accept
ip6 saddr { ${jumphost.wanAddress6}, ${homeWan.cidrv6} } tcp dport 22 accept
ip6 saddr @crowdsec6-blacklists drop
}
}
'';
systemd = {
services = {
crowdsec-firewall-bouncer.after = lib.mkIf bootstrap [
"crowdsec-firewall-bouncer-register.service"
];
crowdsec-firewall-bouncer-register.serviceConfig = lib.mkIf bootstrap {
ReadWritePaths = [ "/var/lib/crowdsec" ];
StateDirectory = lib.mkForce "crowdsec-firewall-bouncer-register";
};
crowdsec-update-hub.serviceConfig.ExecStartPost = lib.mkForce "+systemctl try-restart crowdsec.service";
};
tmpfiles.settings."11-crowdsec-stub-capi" = lib.mkIf bootstrap {
"${stateDir}/capi.yaml".f = {
group = "crowdsec";
mode = "0600";
user = "crowdsec";
};
};
};
};
};
}
4.4.3.103. CopyParty
{
flake-file.inputs.copyparty = {
inputs = {
flake-utils.follows = "flake-utils";
nixpkgs.follows = "nixpkgs";
};
url = "github:9001/copyparty/hovudstraum";
};
flake.modules.nixos.copyparty =
{ inputs, lib, ... }:
{
imports = lib.optionals (inputs ? copyparty) [
inputs.copyparty.nixosModules.default
(
{
root,
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
name = "copyparty";
port = 3923;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceGroup
serviceName
servicePort
serviceUser
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
isHome
nginxAccessRules
webProxy
;
inherit (config.swarselsystems) mainUser;
dataDir = "/sync/copyparty";
cacheDir = "/var/cache/copyparty";
stateDir = "/var/lib/copyparty";
in
{
swarselsystems.enabledServerModules = [ "copyparty" ];
topology.self.services.${serviceName} = {
icon = root "files/topology-images/${serviceName}.png";
info = "https://${serviceDomain}";
name = lib.swarselsystems.toCapitalized serviceName;
};
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
extra.extraConfig.port = servicePort;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = "copyparty";
path = "/?h";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops.secrets =
lib.genAttrs
[
"copyparty-guest-password"
"copyparty-password"
]
(_: {
group = serviceGroup;
mode = "0400";
owner = serviceUser;
});
users.persistentIds.${serviceName} = confLib.mkIds 945;
services.${serviceName} = {
enable = true;
accounts = {
${mainUser}.passwordFile = config.sops.secrets.copyparty-password.path;
guest.passwordFile = config.sops.secrets.copyparty-guest-password.path;
};
group = serviceGroup;
settings = {
hist = cacheDir;
i = "0.0.0.0";
no-reload = true;
p = servicePort;
rproxy = 1;
xff-src = globals.networks."${globals.wireguard.wgProxy.netConfigPrefix}-wgProxy".cidrv4;
};
user = serviceUser;
volumes = {
"/" = {
access = {
r = "*";
rwmda = mainUser;
};
flags.daw = true;
path = "${dataDir}/public";
};
"/private" = {
access = {
rw = "guest";
rwmda = mainUser;
};
flags.daw = true;
path = "${dataDir}/private";
};
};
};
environment.persistence."/persist".directories = lib.mkIf config.swarselsystems.isImpermanence [
{
directory = stateDir;
group = serviceGroup;
mode = "0700";
user = serviceUser;
}
{
directory = cacheDir;
group = serviceGroup;
mode = "0700";
user = serviceUser;
}
];
nodes =
let
uploadProxyConfig = ''
proxy_request_buffering off;
proxy_buffering off;
proxy_read_timeout 1d;
proxy_send_timeout 1d;
'';
in
lib.mkMerge [
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
serviceAddress
serviceDomain
serviceName
servicePort
;
extraConfigLoc = uploadProxyConfig;
maxBody = 0;
proxyWebsockets = true;
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit serviceDomain serviceName servicePort;
extraConfig = nginxAccessRules;
extraConfigLoc = uploadProxyConfig;
maxBody = 0;
proxyWebsockets = true;
serviceAddress = homeServiceAddress;
}
);
}
];
}
)
];
};
}
4.4.3.104. Mealie
{
flake.modules.nixos.mealie =
{
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
name = "mealie";
port = 9000;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
servicePort
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
notificationMail
webProxy
;
kanidmDomain = globals.services.kanidm.domain;
in
{
config = {
swarselsystems.enabledServerModules = [ serviceName ];
topology.self.services.${serviceName}.info = "https://${serviceDomain}";
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = ''"production":\s*true'';
path = "/api/app/about";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops = {
secrets = {
kanidm-mealie = {
mode = "0400";
rekey.keyPrefix = confLib.kanidmSecrets;
};
notification-mail-pw.rekey.keyPrefix = notificationMail.keyPrefix;
};
templates.mealie-env.content = ''
OIDC_CLIENT_SECRET=${config.sops.placeholder.kanidm-mealie}
SMTP_PASSWORD=${config.sops.placeholder.notification-mail-pw}
'';
};
services.${serviceName} = {
enable = true;
credentialsFile = config.sops.templates.mealie-env.path;
settings = {
ALLOW_SIGNUP = "false";
BASE_URL = "https://${serviceDomain}";
OIDC_ADMIN_GROUP = "${serviceName}.admins@${kanidmDomain}";
OIDC_AUTH_ENABLED = "true";
OIDC_AUTO_REDIRECT = "true";
OIDC_CLIENT_ID = serviceName;
OIDC_CONFIGURATION_URL = "https://${kanidmDomain}/oauth2/openid/${serviceName}/.well-known/openid-configuration";
OIDC_GROUPS_CLAIM = "groups";
OIDC_PROVIDER_NAME = "Kanidm";
OIDC_SIGNUP_ENABLED = "true";
OIDC_USER_GROUP = "${serviceName}.access@${kanidmDomain}";
SMTP_AUTH_STRATEGY = "TLS";
SMTP_FROM_EMAIL = notificationMail.address;
SMTP_FROM_NAME = "Mealie";
SMTP_HOST = notificationMail.host;
SMTP_PORT = "587";
SMTP_USER = notificationMail.address;
TZ = config.repo.secrets.common.location.timezone;
};
};
environment.persistence."/state" = lib.mkIf config.swarselsystems.isMicroVM {
directories = [
{
directory = "/var/lib/private/${serviceName}";
mode = "0700";
}
];
};
nodes = lib.mkMerge [
{
${idmServer} =
lib.recursiveUpdate
(confLib.mkKanidmOidcSystem {
inherit serviceDomain serviceName;
extraGroups = [ "${serviceName}.admins" ];
originUrl = "https://${serviceDomain}/login";
})
{
services.kanidm.provision.systems.oauth2.${serviceName}.scopeMaps."${serviceName}.access" =
lib.mkForce
[
"openid"
"email"
"profile"
"groups"
];
};
}
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
serviceAddress
serviceDomain
serviceName
servicePort
;
maxBody = 0;
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit serviceDomain serviceName servicePort;
extraConfig = nginxAccessRules;
maxBody = 0;
serviceAddress = homeServiceAddress;
}
);
}
];
};
};
}
4.4.3.105. Shopservatory
{
flake-file.inputs.shopservatory = {
inputs = {
flake-parts.follows = "flake-parts";
git-hooks-nix.follows = "pre-commit-hooks";
nixpkgs.follows = "nixpkgs";
treefmt-nix.follows = "treefmt-nix";
};
url = "github:Swarsel/shopservatory";
};
flake.modules.nixos.shopservatory =
{
self,
root,
inputs,
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
dir = "/var/lib/shopservatory";
name = "shopservatory";
port = 8480;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDir
serviceDomain
serviceName
servicePort
;
inherit (confLib.static)
homeServiceAddress
homeWebProxy
idmServer
isHome
nginxAccessRules
scannerDropRules
webProxy
;
piaNamespace = "pia";
piaTunnel = config.services.pia-netns.tunnels.${piaNamespace};
jpProxyPort = 1081;
jpNetnsPort = 1080;
serviceReadable = {
group = serviceName;
mode = "0440";
owner = serviceName;
};
in
{
imports = [
inputs.shopservatory.nixosModules.default
self.modules.nixos.pia-netns
];
config = {
swarselsystems.enabledServerModules = [ "shopservatory" ];
topology.self.services.${serviceName} = {
icon = root "files/topology-images/${serviceName}.png";
info = "https://${serviceDomain}";
name = lib.swarselsystems.toCapitalized serviceName;
};
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
};
dns = confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; };
general.socksProxyConsumers = [ config.node.name ];
monitoring.http = confLib.mkHttpMonitoring {
inherit serviceName servicePort;
expectedBodyRegex = "ok";
path = "/healthz";
};
networks = confLib.mkDualFirewallRules { tcpPorts = [ servicePort ]; };
};
sops = {
secrets =
lib.genAttrs [
"shopservatory-ebay-client-id"
"shopservatory-ebay-client-secret"
"shopservatory-telegram-token"
"shopservatory-user-admin-password"
] (_: serviceReadable)
// {
kanidm-shopservatory = serviceReadable // {
rekey.keyPrefix = confLib.kanidmSecrets;
};
pia = { };
};
templates.shopservatory-env = serviceReadable // {
content = ''
SHOPSERVATORY_TELEGRAM_TOKEN=${config.sops.placeholder.shopservatory-telegram-token}
SHOPSERVATORY_EBAY_CLIENT_ID=${config.sops.placeholder.shopservatory-ebay-client-id}
SHOPSERVATORY_EBAY_CLIENT_SECRET=${config.sops.placeholder.shopservatory-ebay-client-secret}
SHOPSERVATORY_OIDC_CLIENT_SECRET=${config.sops.placeholder.kanidm-shopservatory}
SHOPSERVATORY_USER_ADMIN_PASSWORD=${config.sops.placeholder.shopservatory-user-admin-password}
'';
};
};
users.persistentIds = {
${serviceName} = confLib.mkIds 987;
microsocks = confLib.mkIds 988;
};
services = {
microsocks = {
enable = true;
ip = "127.0.0.1";
port = jpNetnsPort;
};
pia-netns.tunnels.${piaNamespace} = {
credentialsFile = config.sops.secrets.pia.path;
forwards.shopservatory-jp-proxy = {
idleTimeout = 120;
listenAddress = "127.0.0.1";
port = jpProxyPort;
service = "microsocks.service";
targetPort = jpNetnsPort;
};
region = "japan";
};
shopservatory = {
enable = true;
browser.enable = true;
environmentFile = config.sops.templates."shopservatory-env".path;
flaresolverr.enable = true;
settings = {
users = [
{
admin = true;
email = "admin@${globals.domains.main}";
name = "admin";
}
];
currency.target = "EUR";
oidc = {
client_id = serviceName;
issuer = "https://${globals.services.kanidm.domain}/oauth2/openid/${serviceName}";
name = "kanidm";
};
scrape = {
browser_proxy = "socks5://${globals.services."socks-proxy".serviceAddress}:${
builtins.toString globals.services."socks-proxy".extraConfig.port
}";
default_interval = "5m";
jp_proxy_url = "socks5://127.0.0.1:${builtins.toString jpProxyPort}";
};
server = {
base_url = "https://${serviceDomain}";
listen = "0.0.0.0:${builtins.toString servicePort}";
};
};
};
};
environment.persistence."/persist".directories = lib.mkIf config.swarselsystems.isImpermanence [
{
directory = serviceDir;
group = serviceName;
mode = "0750";
user = serviceName;
}
];
systemd.services.microsocks = {
after = [ piaTunnel.unit ];
bindsTo = [ piaTunnel.unit ];
partOf = [ piaTunnel.unit ];
requires = [ piaTunnel.unit ];
serviceConfig = {
BindReadOnlyPaths = [
"/etc/netns/${piaNamespace}/resolv.conf:/etc/resolv.conf"
];
NetworkNamespacePath = piaTunnel.netnsPath;
PrivateNetwork = lib.mkForce false;
};
wantedBy = lib.mkForce [ piaTunnel.unit ];
};
nodes = lib.mkMerge [
{
${idmServer} = confLib.mkKanidmOidcSystem {
inherit serviceDomain serviceName;
originUrl = "https://${serviceDomain}/auth/callback";
};
}
{
${webProxy}.services.nginx = confLib.genNginx {
inherit
serviceAddress
serviceDomain
serviceName
servicePort
;
extraConfig = scannerDropRules;
};
}
{
${homeWebProxy}.services.nginx = lib.mkIf isHome (
confLib.genNginx {
inherit serviceDomain serviceName servicePort;
extraConfig = scannerDropRules + nginxAccessRules;
serviceAddress = homeServiceAddress;
}
);
}
];
};
};
}
4.4.3.106. Socks-Proxy
{
flake.modules.nixos.socks-proxy =
{
root,
config,
lib,
confLib,
globals,
...
}:
let
inherit
(confLib.gen {
domain = "socks-proxy.${globals.domains.main}";
name = "socks-proxy";
port = 1080;
})
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
servicePort
;
inherit (confLib.static)
homeServiceAddress
isHome
webProxy
;
in
{
config = {
swarselsystems.enabledServerModules = [ serviceName ];
topology.self.services.${serviceName} = {
icon = root "files/topology-images/${serviceName}.png";
info = "socks5://${serviceAddress}:${toString servicePort}";
name = lib.swarselsystems.toCapitalized serviceName;
};
globals = {
services = confLib.mkServiceGlobal {
inherit
homeServiceAddress
isHome
proxyAddress4
proxyAddress6
serviceAddress
serviceDomain
serviceName
;
extra = {
extraConfig.port = servicePort;
hasWebInterface = false;
};
};
monitoring.tcp = confLib.mkTcpMonitoring { inherit serviceName servicePort; };
networks."${webProxy}-wgProxy".hosts.${config.node.name}.firewallRuleForNode =
lib.genAttrs globals.general.socksProxyConsumers
(_: {
allowedTCPPorts = [ servicePort ];
});
};
users.persistentIds.microsocks = confLib.mkIds 988;
services.microsocks = {
enable = true;
ip = "0.0.0.0";
port = servicePort;
};
};
};
}
4.4.3.107. Treehouse services
{
flake.modules.nixos.treehouse-services =
{
inputs,
config,
lib,
confLib,
globals,
...
}:
let
inherit (confLib.static)
homeWebProxy
idmServer
nginxAccessRules
webProxy
;
host = "treehouse";
hostIn = network: globals.networks.${network}.hosts.${host};
wgNetwork = ifName: "${globals.wireguard.${ifName}.netConfigPrefix}-${ifName}";
proxyAddress4 = globals.hosts.${webProxy}.wanAddress4;
proxyAddress6 = globals.hosts.${webProxy}.wanAddress6;
serviceAddress = (hostIn (wgNetwork "wgProxy")).ipv4;
homeServiceAddress = (hostIn (wgNetwork "wgHome")).ipv4;
webServicePorts = {
comfyui = 8188;
open-webui = 8080;
};
domainOf = serviceName: config.repo.secrets.common.services.domains.${serviceName};
wolfDomain = domainOf "wolf";
homeVlanHost = globals.networks.home-lan.vlans.home.hosts.${host};
in
{
config = {
swarselsystems.enabledServerModules = [ "treehouse-services" ];
globals = {
services = lib.mkMerge (
lib.forEach (lib.attrNames webServicePorts) (
serviceName:
confLib.mkServiceGlobal {
inherit
homeServiceAddress
proxyAddress4
proxyAddress6
serviceAddress
serviceName
;
isHome = true;
serviceDomain = domainOf serviceName;
}
)
);
dns = lib.mkMerge (
lib.forEach (lib.attrNames webServicePorts) (
serviceName: confLib.mkDnsRecord { inherit proxyAddress4 proxyAddress6 serviceName; }
)
++ lib.optional (globals.roaming.${host}.location == "home") {
${lib.swarselsystems.getBaseDomain wolfDomain}.subdomainRecords.${lib.swarselsystems.getSubDomain wolfDomain} =
inputs.dns.lib.combinators.host homeVlanHost.ipv4 null;
}
);
};
nodes = lib.mkMerge (
lib.concatLists (
lib.mapAttrsToList (serviceName: servicePort: [
{ ${idmServer} = confLib.mkKanidmOauth2ProxyAccess { inherit serviceName; }; }
{
${webProxy}.services.nginx = confLib.genNginx {
inherit serviceAddress serviceName servicePort;
maxBody = 0;
oauth2 = true;
oauth2Groups = [ "${serviceName}_access" ];
proxyWebsockets = true;
serviceDomain = domainOf serviceName;
};
}
{
${homeWebProxy}.services.nginx = confLib.genNginx {
inherit serviceName servicePort;
extraConfig = nginxAccessRules;
maxBody = 0;
oauth2 = true;
oauth2Groups = [ "${serviceName}_access" ];
proxyWebsockets = true;
serviceAddress = homeServiceAddress;
serviceDomain = domainOf serviceName;
};
}
]) webServicePorts
)
);
};
};
}
4.5. Shared
This section is for modules that are to be used on NixOS and home-manager scopes alike. This is for example needed in order to allow me to define and set my own custom functions only once in the NixOS config and then mirror them into the corresponding home-manager option.
4.5.1. Packages
This is the central station for self-defined packages. These are all referenced in default.nix. For scripts that are packaged via writeShellApplication, I now keep the executable body directly inside the Nix package definitions. Where a shell block still exists for readability in this document, it is no longer tangled to files/scripts and serves as documentation only.
Note: The structure of generating the packages was changed in commit 2cf03a3 refactor: package and module generation. That commit can be checked out in order to see a simpler version of achieving the same thing.
4.5.1.1. Packages (flake)
{
self,
lib,
pkgs,
...
}:
lib.genAttrs (lib.swarselsystems.readNix "pkgs/flake") (
name:
pkgs.callPackage "${self}/pkgs/flake/${name}" {
inherit self name;
inherit (self.swarselsystemsLib) root;
}
)
4.5.1.1.1. pass-fuzzel
This app allows me, in conjunction with my Yubikey, to quickly enter passwords when the need arises. Normal and TOTP passwords are supported, and they can either be printed directly or copied to the clipboard.
{
name,
fuzzel,
libnotify,
pass,
writeShellApplication,
wtype,
...
}:
writeShellApplication {
inherit name;
runtimeInputs = [
libnotify
(pass.withExtensions (exts: [ exts.pass-otp ]))
fuzzel
wtype
];
text = ''
# Adapted from https://code.kulupu.party/thesuess/home-manager/src/branch/main/modules/river.nix
shopt -s nullglob globstar
otp=0
typeit=0
entry=""
while :; do
case ''${1:-} in
-t | --type)
typeit=1
;;
-e | --entry)
entry=$2
shift
;;
-o | --otp)
otp=1
;;
*) break ;;
esac
shift
done
export PASSWORD_STORE_DIR=~/.local/share/password-store
prefix=''${PASSWORD_STORE_DIR-~/.local/share/password-store}
if [[ $otp -eq 0 ]]; then
password_files=("$prefix"/**/*.gpg)
else
password_files=("$prefix"/otp/**/*.gpg)
fi
password_files=("''${password_files[@]#"$prefix"/}")
password_files=("''${password_files[@]%.gpg}")
password=$entry
if [[ -z $password ]]; then
password=$(printf '%s\n' "''${password_files[@]}" | fuzzel --dmenu "$@")
fi
[[ -n $password ]] || exit
if [[ $otp -eq 0 ]]; then
if [[ $typeit -eq 0 ]]; then
pass show -c "$password" &> /tmp/pass-fuzzel
else
pass show "$password" | {
IFS= read -r pass
printf %s "$pass"
} | wtype -
fi
else
if [[ $typeit -eq 0 ]]; then
pass otp -c "$password" &> /tmp/pass-fuzzel
else
pass otp "$password" | {
IFS= read -r pass
printf %s "$pass"
} | wtype -
fi
fi
notify-send -u critical -a pass -t 1000 "Copied/Typed Password"
'';
}
4.5.1.1.2. swarsel-degraded
On hosts with a mirrored root, this sets a (non-volatile due to 0x07) EFI variable called SwarselDegraded and reboots. The variable is used and unset in Disk layout (mirrored root). The same is done by ssh -p 2222 <host> degraded.
{
name,
e2fsprogs,
systemd,
writeShellApplication,
...
}:
let
efiVariable = "SwarselDegraded-93933e1c-d7df-47ca-9af3-e98f6553ca3c";
in
writeShellApplication {
inherit name;
passthru = { inherit efiVariable; };
runtimeInputs = [
e2fsprogs
systemd
];
text = ''
variable=/sys/firmware/efi/efivars/${efiVariable}
if [ -e "$variable" ]; then
chattr -i "$variable"
fi
printf '\x07\x00\x00\x00\x01' > "$variable"
systemctl reboot
'';
}
4.5.1.1.3. swarsel-bootstrap
This program installs a host that is booted into an installer ISO using nixos-anywhere. It generates the SSH host key (and on encrypted hosts the initrd host key) locally and ships it as an extra file, lets nixos-anywhere generate the hardware configuration, and afterwards registers the host's age key in the sops configuration and rekeys the secrets.
{
name,
git,
nixos-anywhere,
openssh,
opentofu,
sops,
ssh-to-age,
writeShellApplication,
...
}:
writeShellApplication {
inherit name;
runtimeInputs = [
git
nixos-anywhere
openssh
(opentofu.withPlugins (p: [ p.hashicorp_local ]))
sops
ssh-to-age
];
text = ''
usage() {
echo "usage: ${name} [-p ssh-port] [-k] <host> <destination>" >&2
exit 1
}
port=22
kexec=0
while getopts :p:k opt; do
case $opt in
p) port=$OPTARG ;;
k) kexec=1 ;;
*) usage ;;
esac
done
shift $((OPTIND - 1))
if [[ $# -ne 2 ]]; then
usage
fi
host=$1
destination=$2
cd "''${FLAKE:-.}"
settings=$(nix eval --raw ".#nixosConfigurations.$host.config" --apply 'c: let flag = b: if b then "1" else "0"; in toString [ c.nixpkgs.hostPlatform.system (flag c.node.lockFromBootstrapping) (flag c.swarselsystems.isCrypted) (flag c.swarselsystems.isSecureBoot) (if c.swarselsystems.isImpermanence then "/persist" else "") ]')
read -r system locked crypted secureboot persist <<<"$settings"
if [[ $locked -eq 1 ]]; then
echo "$host is locked from bootstrapping, set node.lockFromBootstrapping = lib.mkForce false to proceed" >&2
exit 1
fi
temp=$(mktemp -d)
trap 'rm -rf "$temp"' EXIT
files=$temp/files
args=(--ssh-port "$port" --extra-files "$files")
mkdir -p "$files$persist/etc/ssh"
ssh-keygen -q -t ed25519 -N "" -C "root@$host" -f "$files$persist/etc/ssh/ssh_host_ed25519_key"
if [[ -n $persist ]]; then
systemd-id128 new > "$files$persist/etc/machine-id"
fi
if [[ $crypted -eq 1 ]]; then
mkdir -p "$files$persist/etc/secrets/initrd"
ssh-keygen -q -t ed25519 -N "" -f "$files$persist/etc/secrets/initrd/ssh_host_ed25519_key"
read -rsp "Disk encryption passphrase: " passphrase
echo
read -rsp "Repeat passphrase: " repeat
echo
if [[ $passphrase != "$repeat" ]]; then
echo "passphrases do not match" >&2
exit 1
fi
echo "$passphrase" > "$temp/disko-password"
args+=(--disk-encryption-keys /tmp/disko-password "$temp/disko-password")
fi
if [[ $secureboot -eq 1 ]]; then
mkdir -p "$files$persist/var/lib"
sudo tar -C /var/lib -c sbctl | tar -C "$files$persist/var/lib" -x
fi
if [[ $kexec -eq 1 ]]; then
args+=(--no-disko-deps --kexec "$(nix build --no-link --print-out-paths ".#packages.$system.swarsel-kexec")/swarsel-kexec-$system.tar.gz")
fi
hardware_config=hosts/nixos/$system/$host/hardware-configuration.nix
mkdir -p "$(dirname "$hardware_config")"
rm -f files/install/flake.lock
ssh-keygen -R "$host" &>/dev/null || true
ssh-keygen -R "$destination" &>/dev/null || true
nixos-anywhere "''${args[@]}" --generate-hardware-config nixos-generate-config "$hardware_config" --flake "./files/install#$host" "root@$destination"
nix fmt -- "$hardware_config"
ssh-to-age -i "$files$persist/etc/ssh/ssh_host_ed25519_key.pub" > "files/public/age/hosts/$host.pub"
tofu -chdir=tofu/sops init -upgrade -input=false >/dev/null
tofu -chdir=tofu/sops apply -auto-approve
eval_secrets=("hosts/nixos/$system/$host"/secrets/*.enc)
if [[ -e ''${eval_secrets[0]} ]]; then
sops updatekeys --yes --enable-local-keyservice "''${eval_secrets[@]}"
fi
nix run .#sops-rekey -- --add-to-git rekey
git add "$hardware_config" .sops.yaml "files/public/age/hosts/$host.pub"
if [[ $secureboot -eq 1 ]]; then
echo "put the firmware of $host into setup mode and run: sbctl enroll-keys --ignore-immutable --microsoft"
fi
'';
}
4.5.1.1.4. swarsel-project
This helper bootstraps a new project directory by initializing git, applying one of my flake templates, and immediately allowing direnv.
{
root,
name,
cargo,
direnv,
formats,
git,
go,
nix,
python3,
runCommand,
taplo,
uv,
writeShellApplication,
...
}:
writeShellApplication {
inherit name;
runtimeInputs = [
cargo
direnv
git
go
nix
python3
uv
];
text = ''
template=$1
project=''${2:-$(basename "$PWD")}
if [[ ! -d .git ]]; then
git init -q
fi
ignore=()
case $template in
go)
go mod init "$project"
printf 'package main\n\nimport "fmt"\n\nfunc main() {\n\tfmt.Println("Hello, World!")\n}\n' > main.go
;;
latex)
ignore=("*.pdf" "!figures/**/*.pdf" "*.aux" "*.bbl" "*.bcf" "*.blg" "*.fdb_latexmk" "*.fls" "*.log" "*.out" "*.run.xml" "*.synctex.gz" "*.toc" "_minted*/")
;;
python)
uv init --package --vcs none --no-readme --no-pin-python --name "$project"
uv add --dev --no-sync debugpy
ignore=(.venv/ __pycache__/)
;;
rust)
cargo init --vcs none --name "$project"
cargo generate-lockfile
ignore=(/target)
;;
esac
nix flake init --template "$FLAKE#$template"
sed -i "s/^ description = \"name\";/ description = \"$project\";/" flake.nix
printf 'use flake\n' > .envrc
printf '%s\n' /result .direnv/ .pre-commit-config.yaml "''${ignore[@]}" > .gitignore
install -m644 ${
runCommand "pedantix.toml" { nativeBuildInputs = [ taplo ]; } ''
taplo fmt - < ${
(formats.toml { }).generate "pedantix.toml" (import (root "files/nix/pedantix-settings.nix"))
} > $out
''
} pedantix.toml
git add -A
direnv allow
'';
}
4.5.1.1.5. swarsel-deploy
Remote deployment helper that builds one or more hosts, copies closures, activates the selected action, and prints diffs for quick review.
# heavily inspired from https://github.com/oddlama/nix-config/blob/d42cbde676001a7ad8a3cace156e050933a4dcc3/pkgs/deploy.nix
{
name,
bc,
nix-output-monitor,
writeShellApplication,
...
}:
writeShellApplication {
inherit name;
runtimeInputs = [
bc
nix-output-monitor
];
text = ''
shopt -s lastpipe
function die() {
echo "error: $*" >&2
exit 1
}
function show_help() {
echo 'Usage: deploy [OPTIONS] [--] <host,...> [ACTION]'
echo "Builds, pushes and activates configurations on target systems."
echo ""
echo 'ACTION:'
echo ' switch [default] Switch immediately to the new configuration and make it the boot default'
echo ' boot Make the configuration the new boot default (nixos only)'
echo " test Activate the configuration but don't make it the boot default (nixos only)"
echo " dry-activate Don't activate, just show what would be done"
echo ""
echo 'OPTIONS: [passed to nix build]'
echo ' Use -- to separate options from host/action when passing options with values'
}
function time_start() {
T_START=$(date +%s.%N)
}
function time_next() {
T_END=$(date +%s.%N)
T_LAST=$(${bc}/bin/bc <<< "scale=1; ($T_END - $T_START)/1")
T_START="$T_END"
}
USER_FLAKE_DIR=$(git rev-parse --show-toplevel 2> /dev/null || pwd) ||
die "Could not determine current working directory. Something went very wrong."
[[ -e "$USER_FLAKE_DIR/flake.nix" ]] ||
die "Could not determine location of your project's flake.nix. Please run this at or below your main directory containing the flake.nix."
cd "$USER_FLAKE_DIR"
[[ $# -gt 0 ]] || {
show_help
exit 1
}
OPTIONS=()
POSITIONAL_ARGS=()
args=("$@")
sep=-1
for i in "''${!args[@]}"; do
[[ "''${args[$i]}" == "--" ]] && sep=$i && break
done
if [[ $sep -ge 0 ]]; then
OPTIONS=("''${args[@]:0:$sep}")
POSITIONAL_ARGS=("''${args[@]:$((sep+1))}")
for opt in "''${OPTIONS[@]}"; do
case "$opt" in
"help"|"--help"|"-help"|"-h") show_help; exit 1 ;;
esac
done
else
while [[ $# -gt 0 ]]; do
case "$1" in
"help"|"--help"|"-help"|"-h")
show_help
exit 1
;;
-*) OPTIONS+=("$1") ;;
*)
POSITIONAL_ARGS+=("$1")
shift
POSITIONAL_ARGS+=("$@")
break
;;
esac
shift
done
fi
[[ ''${#POSITIONAL_ARGS[@]} -ge 1 ]] ||
die "Missing argument: <hosts...>"
[[ ''${#POSITIONAL_ARGS[@]} -le 2 ]] ||
die "Too many arguments given."
tr , '\n' <<< "''${POSITIONAL_ARGS[0]}" | sort -u | readarray -t HOSTS
ACTION="''${POSITIONAL_ARGS[1]-switch}"
nix eval --raw .#homeConfigurations --apply 'c: builtins.concatStringsSep "\n" (builtins.attrNames c)' | readarray -t HM_HOSTS
declare -A IS_HOME
for h in "''${HM_HOSTS[@]}"; do
IS_HOME["$h"]=1
done
declare -A TOPLEVEL_FLAKE_PATHS
for host in "''${HOSTS[@]}"; do
if [[ -n "''${IS_HOME[$host]:-}" ]]; then
[[ "$ACTION" == "switch" || "$ACTION" == "dry-activate" ]] ||
die "Action '$ACTION' is not supported for home-manager host '$host'"
TOPLEVEL_FLAKE_PATHS["$host"]=".#homeConfigurations.$host.activationPackage"
else
TOPLEVEL_FLAKE_PATHS["$host"]=".#nixosConfigurations.$host.config.system.build.toplevel"
fi
done
current_host=$(hostname)
ssh_control_dir=$(mktemp -d)
ssh_mux_opts=(-o ControlMaster=auto -o ControlPath="$ssh_control_dir/%C" -o ControlPersist=yes)
function cleanup_ssh() {
for host in "''${HOSTS[@]}"; do
[ "$host" = "$current_host" ] && continue
ssh -o ControlPath="$ssh_control_dir/%C" -O exit "$host" 2>/dev/null || true
done
rm -rf "$ssh_control_dir"
}
trap cleanup_ssh EXIT
for host in "''${HOSTS[@]}"; do
[ "$host" = "$current_host" ] && continue
echo -e "\033[1;36m Connecting \033[m🔑 \033[34m$host\033[m \033[90m(touch your key once)\033[m"
ssh "''${ssh_mux_opts[@]}" "$host" -- true
done
time_start
declare -A TOPLEVEL_STORE_PATHS
for host in "''${HOSTS[@]}"; do
toplevel="''${TOPLEVEL_FLAKE_PATHS["$host"]}"
[[ -n "''${IS_HOME[$host]:-}" ]] || sudo -v
echo -e "\033[1;36m Building \033[m📦 \033[34m$host\033[m"
build_log=$(mktemp)
store_path_file=$(mktemp)
set +e
nix build --no-link --print-out-paths "''${OPTIONS[@]}" --show-trace --log-format internal-json -v "$toplevel" >"$store_path_file" 2> >(tee "$build_log" | ${nix-output-monitor}/bin/nom --json >&2)
build_rc=$?
set -e
wait 2>/dev/null || true
if [[ $build_rc -ne 0 ]]; then
if grep -q '\[nixbuild\.net\] error: Authorization failed' "$build_log"; then
echo -e "\033[1;36m nixbuild.net failed: retrying locally... \033[m"
nix build --builders "" --no-link --print-out-paths "''${OPTIONS[@]}" --show-trace --log-format internal-json -v "$toplevel" >"$store_path_file" 2> >(${nix-output-monitor}/bin/nom --json >&2) ||
die "Failed to get derivation path for $host from ''${TOPLEVEL_FLAKE_PATHS["$host"]}"
wait 2>/dev/null || true
else
rm -f "$build_log" "$store_path_file"
die "Failed to get derivation path for $host from ''${TOPLEVEL_FLAKE_PATHS["$host"]}"
fi
fi
store_path=$(<"$store_path_file")
rm -f "$build_log" "$store_path_file"
TOPLEVEL_STORE_PATHS["$host"]="$store_path"
time_next
echo -e "\033[1;32m Built \033[m✅ \033[34m$host\033[m \033[33m''${TOPLEVEL_STORE_PATHS["$host"]}\033[m \033[90min ''${T_LAST}s\033[m"
done
for host in "''${HOSTS[@]}"; do
store_path="''${TOPLEVEL_STORE_PATHS["$host"]}"
if [ "$host" = "$current_host" ]; then
echo -e "\033[1;36m Running locally for $host... \033[m"
if [[ -n "''${IS_HOME[$host]:-}" ]]; then
ssh_prefix=""
else
ssh_prefix="sudo"
fi
else
echo -e "\033[1;36m Copying \033[m➡️ \033[34m$host\033[m"
NIX_SSHOPTS="''${ssh_mux_opts[*]}" nix copy --to "ssh://$host" "$store_path"
time_next
echo -e "\033[1;32m Copied \033[m✅ \033[34m$host\033[m \033[90min ''${T_LAST}s\033[m"
ssh_prefix="ssh ''${ssh_mux_opts[*]} $host --"
fi
echo -e "\033[1;36m Applying \033[m⚙️ \033[34m$host\033[m"
if [[ -n "''${IS_HOME[$host]:-}" ]]; then
prev_system=$($ssh_prefix readlink -e ~/.local/state/nix/profiles/home-manager || true)
if [[ "$ACTION" == "dry-activate" ]]; then
$ssh_prefix env DRY_RUN=1 "$store_path/activate" ||
echo "Error while activating new home configuration" >&2
else
$ssh_prefix "$store_path/activate" ||
echo "Error while activating new home configuration" >&2
fi
else
prev_system=$($ssh_prefix readlink -e /nix/var/nix/profiles/system)
if [[ "$ACTION" == "switch" || "$ACTION" == "boot" ]]; then
$ssh_prefix /run/current-system/sw/bin/nix-env --profile /nix/var/nix/profiles/system --set "$store_path" ||
die "Failed to set system profile"
else
echo -e "\033[1;36m $ACTION: Not setting system profile \033[m"
fi
$ssh_prefix "$store_path"/bin/switch-to-configuration "$ACTION" ||
echo "Error while activating new system" >&2
fi
if [[ -n $prev_system ]]; then
$ssh_prefix nvd --color always diff "$prev_system" "$store_path" || true
fi
time_next
echo -e "\033[1;32m Applied \033[m✅ \033[34m$host\033[m \033[90min ''${T_LAST}s\033[m"
done
'';
}
4.5.1.1.6. swarsel-instantiate
This is a convenience function that calls nix-instantiate with a number of flags that I need in order to evaluate nix expressions in org-src blocks.
{ name, writeShellApplication, ... }:
writeShellApplication {
inherit name;
text = ''
nix-instantiate --strict --eval --expr "let lib = import <nixpkgs/lib>; in $*"
'';
}
4.5.1.1.7. swarsel-droid
{
name,
coreutils,
gnugrep,
openssh,
writeShellApplication,
...
}:
writeShellApplication {
inherit name;
runtimeInputs = [
coreutils
gnugrep
openssh
];
text = ''
builder=belchsfactory
path=$(ssh "$builder" readlink -f "/nix/var/nix/profiles/$DROID_PROFILE")
nix copy --no-check-sigs --from "ssh://$builder" "$path"
# proot cannot allocate a pty, so builds that fail on the phone are done on the builder instead
for _ in 1 2 3; do
if log=$("$path/activate" 2>&1 | tee /dev/stderr); then
exit 0
fi
drv=$(grep -oE '/nix/store/[a-z0-9]{32}-[a-zA-Z0-9+._?=-]+\.drv' <<<"$log" | head -n 1) || exit 1
nix copy --no-check-sigs --to "ssh://$builder" "$drv"
mapfile -t outputs < <(ssh "$builder" nix-store --realise "$drv")
nix copy --no-check-sigs --from "ssh://$builder" "''${outputs[@]}"
done
exit 1
'';
}
4.5.1.1.8. swarsel-git-remotes
This script points origin at my GitHub repository (or my fork of it), upstream at its fork parent and adds my own git endpoint s another remote.
{
name,
gh,
git,
writeShellApplication,
...
}:
writeShellApplication {
inherit name;
runtimeInputs = [
gh
git
];
text = ''
user=$(git config github.user)
forge_remote=$(git config forge.remote)
forge_url=$(git config forge.url)
slug_of() {
local url=''${1%/}
url=''${url%.git}
if [[ $url =~ ^(git@github\.com:|ssh://git@github\.com/|https://github\.com/)([^/]+/[^/]+)$ ]]; then
echo "''${BASH_REMATCH[2]}"
elif [[ ''${url,,} == "''${forge_url,,}"/* ]]; then
echo "$user/''${url##*/}"
fi
}
is_own() {
local owner=''${1%%/*}
[[ ''${owner,,} == "''${user,,}" ]]
}
lookup() {
gh api "repos/$1" --jq '[.full_name, .name, (.parent.full_name // "")] | @tsv' 2>/dev/null
}
remote() {
echo "$dir: git remote $*"
git -C "$dir" remote "$@"
}
set_remote() {
local current
if ! current=$(git -C "$dir" remote get-url "$1" 2>/dev/null); then
remote add "$1" "$2"
elif [[ $current != "$2" ]]; then
remote set-url "$1" "$2"
fi
}
setup() {
local dir=$1 origin slug info full_name name parent upstream
if ! origin=$(git -C "$dir" remote get-url origin 2>/dev/null); then
echo "$dir: no origin remote, skipping"
return
fi
slug=$(slug_of "$origin")
if [[ -z $slug ]]; then
echo "$dir: origin is neither on GitHub nor on $forge_url, skipping"
return
fi
if ! info=$(lookup "$slug"); then
if [[ $origin != *github.com[:/]* ]] || ! is_own "$slug"; then
echo "$dir: $slug is not on GitHub, skipping"
return
fi
info=$(printf '%s\t%s\t' "$slug" "''${slug##*/}")
fi
IFS=$'\t' read -r full_name name parent <<<"$info"
if ! is_own "$full_name"; then
upstream=$full_name
IFS=$'\t' read -r full_name name parent <<<"$(lookup "$user/$name")"
if [[ ''${parent,,} != "''${upstream,,}" ]]; then
echo "$dir: $user has no fork of $upstream, skipping"
return
fi
if ! git -C "$dir" remote get-url upstream >/dev/null 2>&1; then
remote rename origin upstream
fi
fi
set_remote origin "git@github.com:$full_name.git"
if [[ -n $parent ]]; then
set_remote upstream "https://github.com/$parent.git"
fi
set_remote "$forge_remote" "$forge_url/$name.git"
}
for dir in "''${@:-.}"; do
setup "$dir"
done
'';
}
4.5.1.1.9. swarsel-sync-org
This script can be used to sync changes done to files back into the literate SwarselSystems.org. This is rarely but sometimes useful when trying out bigger changes. An example would be the time when I was debugging why my Summers (Server: ASUS Z10PA-D8) configuration took >90G of memory during eval. For that it was annoying to having to go through the org file all the time. Instead I fixed the problem in the code files and then funneled it back using this script.
Another use case for this (and the main point motivating me to do it) was to streamline implementing the changes automatically applied to the nix files by my pre-commit-hooks, so linting etc.
{
name,
writers,
...
}:
writers.writePython3Bin name { } ''
import difflib
import re
import sys
from collections import Counter
from pathlib import Path
org = Path("SwarselSystems.org")
header = re.compile(r"^\s*#\+begin_src\s.*?:tangle\s+(\S+)", re.I)
with org.open() as f:
old = f.readlines()
targets = Counter(m[1] for line in old if (m := header.match(line)))
new = []
source = None
for line in old:
if source:
if line.strip().lower() != "#+end_src":
continue
content = source.read_text().removesuffix("\n").split("\n")
new += [f" {c}\n" if c.strip() else "\n" for c in content]
source = None
new.append(line)
m = header.match(line)
if not m or targets[m[1]] > 1 or ":noweb yes" in line:
continue
if Path(m[1]).exists():
source = Path(m[1])
if new == old:
sys.exit()
if "--dry-run" in sys.argv:
sys.stdout.writelines(
difflib.unified_diff(old, new, f"a/{org}", f"b/{org}")
)
sys.exit(1)
org.write_text("".join(new))
''
4.5.1.1.10. swarsel-topology
Recreates the topology diagram + thumbnail.
{
root,
name,
chromium,
git,
imagemagick,
libxml2,
nix,
stdenv,
writeShellApplication,
...
}:
writeShellApplication {
inherit name;
runtimeInputs = [
chromium
git
imagemagick
libxml2
nix
];
text = ''
flake=''${FLAKE:-$(git rev-parse --show-toplevel)}
out=$flake/files/topology
svg=$(nix build --no-link --print-out-paths --builders "" \
--override-input topologyPrivate "${root "files/topology/private"}" \
"$flake#topology.${stdenv.hostPlatform.system}.config.output")/main.svg
width=$(xmllint --xpath 'string(/*/@width)' "$svg")
width=''${width%.*}
height=$(xmllint --xpath 'string(/*/@height)' "$svg")
height=$((''${height%.*} + 1))
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
strips=()
for ((offset = 0; offset < height; offset += 4096)); do
printf '<!doctype html><body style="margin:0"><img src="file://%s" style="display:block;margin-top:-%dpx"></body>' "$svg" "$offset" > "$work/strip.html"
strips+=("$work/strip-$offset.png")
chromium --headless --no-sandbox --hide-scrollbars --allow-file-access-from-files \
--force-device-scale-factor=1 --default-background-color=00000000 \
--user-data-dir="$work/profile" \
--window-size="$width,$((height - offset < 4096 ? height - offset : 4096))" \
--screenshot="''${strips[-1]}" "file://$work/strip.html"
done
magick "''${strips[@]}" +repage -append +repage "$out/topology.png"
magick "$out/topology.png" -resize 500x "$out/topology_small.png"
'';
}
4.5.1.2. Packages (config)
{
self,
homeConfig,
config,
lib,
pkgs,
...
}:
lib.genAttrs (lib.swarselsystems.readNix "pkgs/config") (
name:
pkgs.callPackage "${self}/pkgs/config/${name}" {
inherit
self
name
homeConfig
config
;
}
)
4.5.1.2.1. swarsel-gens
This script quickly lists all nix generations on the system
{
name,
config,
writeShellApplication,
...
}:
writeShellApplication {
inherit name;
runtimeInputs = [ config.nix.package ];
text = ''
sudo nix-env --list-generations --profile /nix/var/nix/profiles/system
'';
}
4.5.1.2.2. swarsel-switch
This script quickly switches to another nix generation.
{
name,
config,
writeShellApplication,
...
}:
writeShellApplication {
inherit name;
runtimeInputs = [ config.nix.package ];
text = ''
sudo nix-env --switch-generation "$1" -p /nix/var/nix/profiles/system && sudo /nix/var/nix/profiles/system/bin/switch-to-configuration switch
'';
}
4.6. Profiles
In this section I define custom aspect sets. These are mostly used to combine common functionality that is used on a specific "archetype" of host.
4.6.1. NixOS
{ config, lib, ... }:
let
fmods = config.flake.modules;
pickN = names: builtins.attrValues (lib.getAttrs names fmods.nixos);
in
{
flake.modules.nixos = {
profile-minimal.imports =
pickN [
"settings"
"home-manager"
"xserver"
"lanzaboote"
"time"
"users"
"impermanence"
"sops"
"boot"
"autologin"
"btrfs"
"ssh"
"disk-encrypt"
]
++ [
fmods.generic.pii
];
profile-personal = { config, ... }: {
imports = [
fmods.nixos.profile-public
]
++ pickN [
"hardwarecompatibility-yubikey"
"sandbox-access"
"ssh"
];
home-manager.users."${config.swarselsystems.mainUser}".imports = [
fmods.homeManager.profile-personal
];
};
profile-public = { config, ... }: {
imports = [
fmods.nixos.profile-public-small
]
++ pickN [
"appimage"
"distrobox"
"hardwarecompatibility-keyboards"
"hardwarecompatibility-ledger"
"lid"
"networkdevices"
"nix-ld"
];
home-manager.users."${config.swarselsystems.mainUser}".imports = [
fmods.homeManager.profile-public
];
};
profile-public-small = { config, ... }: {
imports =
pickN [
"settings"
"lanzaboote"
"home-manager"
"xserver"
"time"
"users"
"impermanence"
"sops"
"boot"
"autologin"
"blueman"
"env"
"firezone-client"
"gnome-keyring"
"gvfs"
"hardware"
"interceptiontools"
"login"
"nautilus"
"network"
"nvd-rebuild"
"packages"
"pipewire"
"polkit"
"power-profiles-daemon"
"programs"
"pulseaudio"
"remotebuild"
"stylix"
"syncthing"
"systemd"
"uwsm"
"xdg-portal"
"zsh"
"btrfs"
"nftables-rules"
]
++ [
fmods.generic.pii
];
home-manager.users."${config.swarselsystems.mainUser}".imports = [
fmods.homeManager.profile-public-small
];
};
};
}
4.6.2. home-manager
{ config, lib, ... }:
let
fmods = config.flake.modules;
pickH = names: builtins.attrValues (lib.getAttrs names fmods.homeManager);
in
{
flake.modules.homeManager = {
profile-dgxspark.imports = pickH [
"atuin"
"bash"
"blueman-applet"
"direnv"
"eza"
"glide"
"fuzzel"
"settings"
"git"
"gpg-agent"
"kitty"
"nix-index"
"nixgl"
"nix-your-shell"
"network-manager-applet"
"pii-agent"
"sops"
"stylix"
];
profile-minimal.imports = pickH [
"settings"
"sops"
"kitty"
"zsh"
"git"
];
profile-personal = { lib, ... }: {
imports = pickH [
"emacs"
"env"
"git"
"mail"
"obsidian"
"pii-agent"
"ssh"
];
swarselsystems.trayApplets.obsidian.enable = lib.swarselsystems.mkStrong true;
};
profile-public = {
imports = pickH [
"attic-client"
"atuin"
"kdeconnect"
"khal"
"nixgl"
"obs-studio"
"opkssh"
"spotify-player"
"vesktop"
"shikane"
"syncthing-tray"
];
swarselsystems.trayApplets.obsidian.enable = false;
};
profile-public-small = {
imports = pickH [
"anki"
"tray-applets"
"blueman-applet"
"custom-packages"
"desktop"
"direnv"
"element"
"eza"
"glide"
"fuzzel"
"settings"
"gnome-keyring"
"gpg-agent"
"kitty"
"nix-index"
"nix-your-shell"
"network-manager-applet"
"packages"
"password-store"
"pedantix"
"programs"
"spicetify"
"starship"
"stylix"
"zellij"
"zellij-keybinds"
"zsh"
];
swarselsystems.trayApplets.obsidian.enable = false;
};
};
}
4.6.3. Base
{
flake.modules = {
homeManager.profile-base = { self, lib, ... }: {
imports =
builtins.attrValues (lib.getAttrs [ "meta" "options" "config-lib" ] self.modules.generic)
++ [
self.modules.homeManager.sharedoptions
];
};
nixos.profile-base = { self, lib, ... }: {
imports =
builtins.attrValues (lib.getAttrs [ "meta" "options" "config-lib" "globals" ] self.modules.generic)
++ [
self.modules.nixos.dns
self.modules.nixos.nftables
self.modules.nixos.nodes
self.modules.nixos.topology
self.modules.nixos.id
];
};
};
}
4.6.4. Darwin
{
flake.modules.darwin.profile-darwin = { self, ... }: {
imports = [
self.modules.darwin.settings
self.modules.darwin.home-manager
self.modules.generic.meta
self.modules.generic.globals
self.modules.generic.pii
];
};
}
4.6.5. Android
{ config, lib, ... }:
let
fmods = config.flake.modules;
pickH = names: builtins.attrValues (lib.getAttrs names fmods.homeManager);
in
{
flake.modules.nixOnDroid = {
profile-base = {
imports = [
fmods.nixOnDroid.settings
fmods.nixOnDroid.packages
];
home-manager.config.imports = pickH [
"cli-programs"
"cli-tools"
"zsh"
];
};
profile-personal = {
imports = [ fmods.nixOnDroid.swarsel-droid ];
home-manager.config.imports = pickH [
"direnv"
"eza"
"git"
"nix-index"
"nix-your-shell"
"ssh"
"starship"
];
};
};
}
4.6.6. Server
{
flake.modules.nixos = {
profile-localserver = { self, ... }: {
imports = [
# common modules
self.modules.nixos.settings
self.modules.nixos.lanzaboote
self.modules.generic.pii
self.modules.nixos.xserver
self.modules.nixos.time
self.modules.nixos.users
self.modules.nixos.impermanence
self.modules.nixos.sops
self.modules.nixos.pii-agent
self.modules.nixos.boot
# server modules
self.modules.nixos.btrfs
self.modules.nixos.nftables-rules
self.modules.nixos.server-settings
self.modules.nixos.disk-encrypt
self.modules.nixos.ssh
self.modules.nixos.server-network
self.modules.nixos.server-packages
self.modules.nixos.attic-setup
self.modules.nixos.dns-hostrecord
# self.modules.nixos.oauth2-proxy
self.modules.nixos.node-roles
self.modules.nixos.alloy
self.modules.nixos.blackbox
];
};
profile-microvm = { self, lib, ... }: {
imports = [
# common modules
self.modules.nixos.settings
self.modules.generic.pii
self.modules.nixos.xserver
self.modules.nixos.time
self.modules.nixos.users
self.modules.nixos.impermanence
self.modules.nixos.sops
# server modules
self.modules.nixos.btrfs
self.modules.nixos.nftables-rules
self.modules.nixos.server-settings
self.modules.nixos.ssh
self.modules.nixos.server-packages
self.modules.nixos.wireguard
self.modules.nixos.dns-home
self.modules.nixos.opkssh
# self.modules.nixos.oauth2-proxy
self.modules.nixos.node-roles
self.modules.nixos.alloy
self.modules.nixos.blackbox
];
config.swarselsystems = {
isImpermanence = true;
isLinux = true;
isMicroVM = true;
proxyHost = lib.mkDefault "twothreetunnel";
};
};
profile-router = { self, ... }: {
imports = [
self.modules.nixos.nftables-rules
self.modules.nixos.router
self.modules.nixos.kea
self.modules.nixos.chrony
];
};
};
}
5. Emacs
5.0.1. early-init
{
flake.modules.homeManager.emacs-init =
{ config, ... }:
{
config.programs.emacs.init.earlyInit = ''
(defvar swarsel-file-name-handler-alist file-name-handler-alist)
(defvar swarsel-vc-handled-backends '(Git))
(defun swarsel/restore-startup-settings ()
"Restore startup-tuned variables to their regular runtime values."
(unless (featurep 'mps)
(setq gc-cons-threshold (* 100 1024 1024)
gc-cons-percentage 0.1))
(setq jit-lock-defer-time 0.05
read-process-output-max (* 1024 1024)
file-name-handler-alist swarsel-file-name-handler-alist
vc-handled-backends swarsel-vc-handled-backends)
(fset 'epg-wait-for-status #'ignore))
(unless (featurep 'mps)
(setq gc-cons-threshold most-positive-fixnum
gc-cons-percentage 0.6))
(setq file-name-handler-alist nil
vc-handled-backends nil)
(add-hook 'emacs-startup-hook #'swarsel/restore-startup-settings)
(tool-bar-mode 0)
(menu-bar-mode 0)
(scroll-bar-mode 0)
(setq frame-inhibit-implied-resize t
ring-bell-function 'ignore
use-dialog-box nil
use-file-dialog nil
use-short-answers t
inhibit-startup-message t
inhibit-splash-screen t
inhibit-startup-screen t
inhibit-x-resources t
inhibit-startup-buffer-menu t
inhibit-startup-echo-area-message user-login-name
native-comp-jit-compilation nil)
(setq-default left-margin-width 1
right-margin-width 1)
(setq-default default-frame-alist
(append
(list
'(undecorated . t)
'(background-color . "${config.lib.stylix.colors.withHashtag.base00}")
'(foreground-color . "${config.lib.stylix.colors.withHashtag.base05}")
'(font . "FiraCode Nerd Font")
'(vertical-scroll-bars . nil)
'(horizontal-scroll-bars . nil)
'(internal-border-width . 5)
'(tool-bar-lines . 0)
'(menu-bar-lines . 0))))
(add-hook
'after-make-frame-functions
(lambda (frame)
(with-selected-frame frame
(when (display-graphic-p)
(define-key input-decode-map (kbd "C-i") [DUMMY-i])
(define-key input-decode-map (kbd "C-[") [DUMMY-lsb])
(define-key input-decode-map (kbd "C-m") [DUMMY-m])
))))
'';
};
}
5.0.2. Core settings
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init = {
enable = true;
prelude = ''
(global-set-key (kbd "<escape>") 'keyboard-escape-quit)
(global-unset-key (kbd "C-z"))
(setq
swarsel-dotfiles-directory (getenv "FLAKE")
swarsel-swarsel-org-filepath (expand-file-name "SwarselSystems.org" swarsel-dotfiles-directory)
swarsel-tasks-org-file "Tasks.org"
swarsel-archive-org-file "Archive.org"
swarsel-work-projects-directory (getenv "DOCUMENT_DIR_WORK")
swarsel-private-projects-directory (getenv "DOCUMENT_DIR_PRIV")
)
(setq user-emacs-directory (expand-file-name "~/.cache/emacs/")
url-history-file (expand-file-name "url/history" user-emacs-directory))
(let ((backup-dir "~/tmp/emacs/backups")
(auto-saves-dir "~/tmp/emacs/auto-saves/"))
(dolist (dir (list backup-dir auto-saves-dir))
(when (not (file-directory-p dir))
(make-directory dir t)))
(setq backup-directory-alist `(("." . ,backup-dir))
auto-save-file-name-transforms `((".*" ,auto-saves-dir t))
auto-save-list-file-prefix (concat auto-saves-dir ".saves-")
tramp-backup-directory-alist `((".*" . ,backup-dir))
tramp-auto-save-directory auto-saves-dir))
(setq backup-by-copying t
delete-old-versions t
version-control t
kept-new-versions 5
kept-old-versions 2
backup-by-copying-when-linked t)
(set-language-environment "UTF-8")
(add-hook 'before-save-hook 'delete-trailing-whitespace)
(global-hl-line-mode 1)
(blink-cursor-mode -1)
(global-subword-mode 1)
(setq blink-matching-paren nil)
(delete-selection-mode 1)
(setq vc-follow-symlinks t)
(setq kill-region-dwim 'emacs-word)
(setq require-final-newline t)
(winner-mode 1)
(setq load-prefer-newer t)
(setq-default bidi-paragraph-direction 'left-to-right
bidi-display-reordering 'left-to-right
bidi-inhibit-bpa t)
(global-so-long-mode)
(setq fast-but-imprecise-scrolling t
redisplay-skip-fontification-on-input t
inhibit-compacting-font-caches t
auto-window-vscroll nil
auto-revert-avoid-polling t)
(setq idle-update-delay 1.0
which-func-update-delay 1.0)
(setq undo-limit 80000000
evil-want-fine-undo t
auto-save-default t)
(setq browse-url-browser-function 'browse-url-generic
browse-url-generic-program "glide")
(global-set-key [remap suspend-frame]
(lambda ()
(interactive)
(message "This keybinding is disabled (was 'suspend-frame')")))
(setq visible-bell nil)
(setq initial-major-mode 'fundamental-mode
initial-scratch-message nil)
(add-hook 'prog-mode-hook 'display-line-numbers-mode)
(setq custom-safe-themes t)
(setq byte-compile-warnings '(not free-vars unresolved noruntime lexical make-local))
(when (native-comp-available-p)
(setq native-comp-async-report-warnings-errors 'silent)
(setq native-comp-async-on-battery-power nil)
(setq native-compile-prune-cache t))
(setq garbage-collection-messages nil)
(unless (featurep 'mps)
(defvar k-gc-timer (run-with-idle-timer 15 t #'garbage-collect))
(defun swarsel/minibuffer-setup-hook ()
(setq gc-cons-threshold most-positive-fixnum))
(defun swarsel/minibuffer-exit-hook ()
(setq gc-cons-threshold (* 100 1024 1024)))
(add-hook 'minibuffer-setup-hook #'swarsel/minibuffer-setup-hook)
(add-hook 'minibuffer-exit-hook #'swarsel/minibuffer-exit-hook))
(setq-default indicate-buffer-boundaries t)
(setq auth-sources '( "~/.emacs.d/.authinfo")
auth-source-cache-expiry nil)
(defun swarsel/with-buffer-name-prompt-and-make-subdirs ()
(let ((parent-directory (file-name-directory buffer-file-name)))
(when (and (not (file-exists-p parent-directory))
(y-or-n-p (format "Directory `%s' does not exist! Create it? " parent-directory)))
(make-directory parent-directory t))))
(add-to-list 'find-file-not-found-functions #'swarsel/with-buffer-name-prompt-and-make-subdirs)
(defun suppress-messages (old-fun &rest args)
(cl-flet ((silence (&rest args1) (ignore)))
(advice-add 'message :around #'silence)
(unwind-protect
(apply old-fun args)
(advice-remove 'message #'silence))))
(advice-add 'push-mark :around #'suppress-messages)
'';
recommendedGcSettings = false;
};
}
5.0.3. Python
{
flake.modules.homeManager.emacs-init =
{ lib, pkgs, ... }:
let
python = ''"${lib.getExe pkgs.python3}"'';
in
{
config.programs.emacs.init.usePackage.python = {
enable = true;
custom = {
org-babel-python-command = python;
python-indent-guess-indent-offset-verbose = false;
python-shell-interpreter = python;
};
};
};
}
5.0.4. Session related settings
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init = {
prelude = "(context-menu-mode 1)";
usePackage = {
recentf = {
config = ''
(add-to-list 'recentf-exclude "\\Archive\\.org\\'")
(add-to-list 'recentf-exclude "\\Tasks\\.org\\'")
'';
enable = true;
};
repeat = {
enable = true;
custom.repeat-exit-timeout = 3;
init = "(repeat-mode 1)";
};
savehist = {
enable = true;
init = "(savehist-mode 1)";
};
saveplace = {
enable = true;
init = "(save-place-mode 1)";
};
};
};
}
5.0.5. Custom Keybindings
This defines a set of keybindings that I want to have available globally. I have one set of keys that is globally available through the C-SPC prefix. This set is used mostly for functions that I have trouble remembering the original keybinding for, or that I just want to have gathered in a common space.
I also define some keybindings to some combinations directly. Those are used mostly for custom functions that I call often enough to warrant this.
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage.general = {
config = ''
(swarsel/leader-keys
"e" '(:ignore e :which-key "evil")
"t" '(:ignore t :which-key "toggles")
"tl" '(display-line-numbers-mode :which-key "line numbers")
"to" '(olivetti-mode :wk "olivetti")
"td" '(darkroom-tentative-mode :wk "darkroom")
"tw" '((lambda () (interactive) (toggle-truncate-lines)) :which-key "line wrapping")
"m" '(:ignore m :which-key "modes/programs")
"l" '(:ignore l :which-key "links")
"hy" '(yas-describe-tables :which-key "yas tables")
"hb" '(embark-bindings :which-key "current key bindings")
"h" '(:ignore t :which-key "describe")
"he" 'view-echo-area-messages
"hf" 'describe-function
"hF" 'describe-face
"hl" '(view-lossage :which-key "show command keypresses")
"hL" 'find-library
"hm" 'describe-mode
"ho" 'describe-symbol
"hk" 'describe-key
"hK" 'describe-keymap
"hp" 'describe-package
"hv" 'describe-variable
"hd" 'devdocs-lookup
"w" '(:ignore t :which-key "window")
"wl" 'windmove-right
"w <right>" 'windmove-right
"wh" 'windmove-left
"w <left>" 'windmove-left
"wk" 'windmove-up
"w <up>" 'windmove-up
"wj" 'windmove-down
"w <down>" 'windmove-down
"wd" 'delete-window
"w=" 'balance-windows-area
"wD" 'kill-buffer-and-window
"wu" 'winner-undo
"wr" 'winner-redo
"w/" 'evil-window-vsplit
"w\\" 'evil-window-vsplit
"w-" 'evil-window-split
"wm" '(delete-other-windows :wk "maximize")
"<right>" 'up-list
"<left>" 'down-list
)
(general-define-key
"C-c d" 'crux-duplicate-current-line-or-region
"C-c D" 'crux-duplicate-and-comment-current-line-or-region
"<DUMMY-m>" 'swarsel/last-buffer
"M-\\" 'indent-region
"<Paste>" 'yank
"<Cut>" 'kill-region
"<Copy>" 'kill-ring-save
"<undo>" 'evil-undo
"<redo>" 'evil-redo
)
'';
enable = true;
init = ''
(defun swarsel/last-buffer () (interactive) (switch-to-buffer nil))
(defun crux-get-positions-of-line-or-region ()
"Return positions (beg . end) of the current line or region."
(let (beg end)
(if (and mark-active (> (point) (mark)))
(exchange-point-and-mark))
(setq beg (line-beginning-position))
(if mark-active
(exchange-point-and-mark))
(setq end (line-end-position))
(cons beg end)))
(defun crux-duplicate-current-line-or-region (arg)
"Duplicates the current line or region ARG times.
If there's no region, the current line will be duplicated. However, if
there's a region, all lines that region covers will be duplicated."
(interactive "p")
(pcase-let* ((origin (point))
(`(,beg . ,end) (crux-get-positions-of-line-or-region))
(region (buffer-substring-no-properties beg end)))
(dotimes (_i arg)
(goto-char end)
(newline)
(insert region)
(setq end (point)))
(goto-char (+ origin (* (length region) arg) arg))))
(defun crux-duplicate-and-comment-current-line-or-region (arg)
"Duplicates and comments the current line or region ARG times.
If there's no region, the current line will be duplicated. However, if
there's a region, all lines that region covers will be duplicated."
(interactive "p")
(pcase-let* ((origin (point))
(`(,beg . ,end) (crux-get-positions-of-line-or-region))
(region (buffer-substring-no-properties beg end)))
(comment-or-uncomment-region beg end)
(setq end (line-end-position))
(dotimes (_ arg)
(goto-char end)
(newline)
(insert region)
(setq end (point)))
(goto-char (+ origin (* (length region) arg) arg))))
(eval-and-compile
(require 'general)
(general-create-definer swarsel/leader-keys
:keymaps '(normal insert visual emacs)
:prefix "SPC"
:global-prefix "C-SPC"))
'';
};
}
5.0.6. Unclutter .Emacs.d
In this section I move the custom.el out of it's standard location in .emacs.d. Firstly, I dislike using this file at all since I would rather have fully stateful configuration as commanded by this file. Secondly, this file is too easily permanently changed. Recently I figured out the last bits that I needed to remove from custom.el to no longer be reliant on it, so I now just write it to a temporary file (through make-temp=file) which will be cleaned on shutdown. However, I like to retain the custom framework because it is nice for testing out theme customizations, hence why I still load the file.
This section also sets the Emacs directory to the ~/.cache/ directory which is useful for files that I do not want to have lying around in my .emacs.d.
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage.no-littering = {
config = ''
(setq custom-file (make-temp-file "emacs-custom-"))
(load custom-file t)
'';
enable = true;
};
}
5.0.7. Indentation
Here I define several options related to indentation; I first make it so that only whitespace will be used instead of tab characters for indentation, and I also set a small standard indent.
We set tab-always-indent to 'complete in order to indent first and then do completion if there are any. Also we make it so that python will not complain about missing indentation info.
Lastly, I load the indent-bars package. It draws configurable indentation guides using the display engine (stipple faces) rather than overlays, which keeps redisplay cheap, and is useful for languages like python.
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init = {
prelude = ''
(setq-default indent-tabs-mode nil
tab-width 2)
(setq tab-always-indent 'complete)
'';
usePackage.indent-bars = {
enable = true;
hook = [ "(prog-mode . indent-bars-mode)" ];
};
};
}
5.0.8. Scrolling
By default, Emacs scrolls half a page when reaching the bottom of the buffer. This is extremely annoying. This sets up more granular scrolling that allows scrolling with a mouse wheel or the two-finger touchscreen gesture. This now also works in buffers with a very small frame.
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init = {
prelude = ''
(setq mouse-wheel-scroll-amount
'(1
((shift) . 5)
((meta) . 0.5)
((control) . text-scale))
mouse-drag-copy-region nil
make-pointer-invisible t
mouse-wheel-follow-mouse t)
(setq-default scroll-preserve-screen-position t
next-screen-context-lines 0)
'';
usePackage.ultra-scroll = {
config = "(ultra-scroll-mode 1)";
enable = true;
custom.ultra-scroll-hide-functions = "'(global-hl-line-mode diff-hl-mode indent-bars-mode global-highlight-parentheses-mode rainbow-delimiters-mode)";
init = ''
(setq scroll-conservatively 101
scroll-margin 0)
'';
};
};
}
5.0.9. Evil
This setups up evil, which brings vim-like keybindings to Emacs. In the same location, I also unbind the C-z key (I am very unhappy with this implementation, but it is the only thing that works consistently so far) to make it available for cape later.
Also, I setup initial modes for several major-modes depending on what I deem fit.
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage = {
evil = {
config = ''
(evil-mode 1)
(advice-add 'evil-insert :around #'suppress-messages)
(advice-add 'evil-visual-char :around #'suppress-messages)
(define-key evil-normal-state-map (kbd "j") 'evil-next-visual-line)
(define-key evil-normal-state-map (kbd "<down>") 'evil-next-visual-line)
(define-key evil-normal-state-map (kbd "k") 'evil-previous-visual-line)
(define-key evil-normal-state-map (kbd "<up>") 'evil-previous-visual-line)
(define-key evil-normal-state-map (kbd "C-z") nil)
(define-key evil-insert-state-map (kbd "C-z") nil)
(define-key evil-visual-state-map (kbd "C-z") nil)
(define-key evil-motion-state-map (kbd "C-z") nil)
(define-key evil-operator-state-map (kbd "C-z") nil)
(define-key evil-replace-state-map (kbd "C-z") nil)
(evil-set-undo-system 'undo-tree)
(evil-set-initial-state 'messages-buffer-mode 'emacs)
(evil-set-initial-state 'dashboard-mode 'emacs)
(evil-set-initial-state 'dired-mode 'emacs)
(evil-set-initial-state 'cfw:details-mode 'emacs)
(evil-set-initial-state 'Custom-mode 'emacs)
(evil-set-initial-state 'mu4e-headers-mode 'normal)
(evil-set-initial-state 'python-inferior-mode 'normal)
(evil-set-initial-state 'vterm-mode 'emacs)
(add-hook 'org-capture-mode-hook 'evil-insert-state)
(add-to-list 'evil-buffer-regexps '("COMMIT_EDITMSG" . insert))
'';
enable = true;
init = ''
(defun swarsel/toggle-evil-state ()
(interactive)
(if (or (evil-emacs-state-p) (evil-insert-state-p))
(evil-normal-state)
(evil-emacs-state)))
(setq evil-want-integration t)
(setq evil-want-keybinding nil)
(setq evil-want-C-u-scroll t)
(setq evil-want-C-i-jump nil)
(setq evil-want-Y-yank-to-eol t)
(setq evil-shift-width 2)
(setq evil-respect-visual-line-mode nil)
(setq evil-split-window-below t)
(setq evil-vsplit-window-right t)
'';
};
evil-cleverparens.enable = true;
evil-collection = {
config = "(evil-collection-init)";
enable = true;
after = [ "evil" ];
};
evil-mc = {
config = "(global-evil-mc-mode 1)";
enable = true;
after = [ "evil" ];
};
evil-nerd-commenter = {
enable = true;
bind."M-/" = "evilnc-comment-or-uncomment-lines";
};
evil-numbers.enable = true;
evil-snipe = {
config = ''
(evil-snipe-mode +1)
(evil-snipe-override-mode +1)
'';
enable = true;
after = [ "evil" ];
demand = true;
};
evil-surround = {
config = "(global-evil-surround-mode 1)";
enable = true;
};
evil-textobj-tree-sitter = {
config = ''
(define-key evil-outer-text-objects-map "f" (evil-textobj-tree-sitter-get-textobj "function.outer"))
(define-key evil-inner-text-objects-map "f" (evil-textobj-tree-sitter-get-textobj "function.inner"))
(define-key evil-outer-text-objects-map "a" (evil-textobj-tree-sitter-get-textobj ("if_statement.outer" "conditional.outer" "loop.outer") '((python-mode . ((if_statement.outer) @if_statement.outer)) (python-ts-mode . ((if_statement.outer) @if_statement.outer)))))
'';
enable = true;
};
evil-visual-mark-mode = {
enable = true;
command = [ "evil-visual-mark-mode" ];
};
general.config = ''
(swarsel/leader-keys
"eo" '(evil-jump-backward :which-key "cursor jump backwards")
"eO" '(evil-jump-forward :which-key "cursor jump forwards")
"te" '(swarsel/toggle-evil-state :which-key "emacs/evil")
"tp" '(evil-cleverparens-mode :wk "cleverparens"))
'';
};
}
5.0.10. Font Configuration
Here I define my fonts to be used. Honestly I do not understand the face-attributes and pitches of Emacs all too well. It seems this configuration works fine, but I might have to revisit this at some point in the future.
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.prelude = ''
(setq swarsel/fixed-font "FiraCode Nerd Font"
swarsel/variable-font "Iosevka Aile")
(set-face-attribute 'default nil :font swarsel/fixed-font :height 100)
(set-face-attribute 'fixed-pitch nil :font swarsel/fixed-font :height 130)
(set-face-attribute 'variable-pitch nil :font swarsel/variable-font :weight 'light :height 130)
(defun swarsel/use-noto-emoji ()
(when (display-graphic-p)
(remove-hook 'server-after-make-frame-hook #'swarsel/use-noto-emoji)
(run-with-idle-timer 0 nil (lambda ()
(dolist (script '(emoji symbol))
(set-fontset-font t script "Noto Color Emoji" nil 'prepend))))))
(add-hook 'server-after-make-frame-hook #'swarsel/use-noto-emoji)
(swarsel/use-noto-emoji)
(set-char-table-range char-width-table #xFE0F 1)
'';
}
5.0.11. Theme
I have grown to love the doom-citylights theme and have modeled my whole system after it. Also solaire-mode is a nice mode that inverts the alt-faces with the normal faces for specific 'minor' buffers (like Help-buffers).
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage = {
doom-themes = {
config = ''
(load-theme 'doom-city-lights t)
(doom-themes-treemacs-config)
(doom-themes-org-config)
(custom-set-faces '(gnus-group-news-low ((t (:weight bold)))))
'';
enable = true;
hook = [ "(server-after-make-frame . swarsel/load-theme-once)" ];
init = ''
(defun swarsel/load-theme-once ()
(when (display-graphic-p)
(load-theme 'doom-city-lights t)
(remove-hook 'server-after-make-frame-hook #'swarsel/load-theme-once)))
'';
};
solaire-mode = {
enable = true;
custom.solaire-global-mode = "+1";
};
};
}
5.0.12. Icons
This section loads the base icons used in my configuration. I am using nerd-icons over all-the-icons since the former seems to have more integrations with different packages than the latter.
Used in:
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage.nerd-icons.enable = true;
}
5.0.13. Variable Pitch Mode
This minor mode allows mixing fixed and variable pitch fonts within the same buffer.
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage.mixed-pitch = {
enable = true;
custom = {
mixed-pitch-set-height = false;
mixed-pitch-variable-pitch-cursor = false;
};
hook = [ "(text-mode . mixed-pitch-mode)" ];
};
}
5.0.14. mini-modeline
I have found that the doom-modeline, while very useful, consumes too much screen space for my liking. This modeline takes a more minimalistic approach. The only information that is shown is:
- the line number
- state of the file (whether it is saved etc.)
- the name of the file
- the percentage of the cursor in the file
- the major mode of the file
- the current evil mode
This is really the perfect solution for me, but it might not be for everyone.
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage = {
mini-modeline = {
config = ''
(mini-modeline-mode t)
(setq window-divider-default-places t
window-divider-default-bottom-width 1
window-divider-default-right-width 1)
(window-divider-mode 1)
'';
enable = true;
after = [ "smart-mode-line" ];
custom = {
mini-modeline-display-gui-line = false;
mini-modeline-enhance-visual = false;
mini-modeline-l-format = false;
mini-modeline-r-format = '''("%e" mode-line-front-space mode-line-mule-info mode-line-client mode-line-modified mode-line-remote mode-line-frame-identification mode-line-buffer-identification " " mode-line-position " " mode-name evil-mode-line-tag)'';
mini-modeline-right-padding = 5;
mini-modeline-truncate-p = false;
};
};
smart-mode-line = {
config = ''
(sml/setup)
(add-to-list 'sml/replacer-regexp-list '("^~/Documents/Work/" ":WK:"))
(add-to-list 'sml/replacer-regexp-list '("^~/Documents/Private/" ":PR:"))
(add-to-list 'sml/replacer-regexp-list '("^~/.dotfiles/" ":D:") t)
'';
enable = true;
};
};
}
5.0.15. Minibuffer enhancements (vertico, marginalia, consult, embark)
Orderless allows for fuzzy matching.
When first installing Orderless, I often times faced the problem, that when editing long files and calling consult-line, Emacs would hang when changing a search term in the middle (e.g. from servicse.xserver to servic.xserver in order to fix the typo). The below Orderless rules have a more strict matching that has a positive impact on performance.
Consult provides better implementations for several user functions, e.g. consult-line or consult-outline.
The big winner here are the convenient keybindings being setup here for general use. Also, I setup vim-navigation for minibuffer completions. consult-buffer is set twice because I am still used to that weird C-M-j command that I chose for ivy-switch-buffer when I first started using Emacs. I want to move to the other command but for now it is not feasible to delete the other one.
Embark allows acting on the results in the minibuffer while the completion is still ongoing - this is extremely useful since it allows to, for example, read the documentation for several functions without closing the help search. It can also collect the results of a grep operation into a separate buffer that edits the result in their original location.
I have stripped down the embark keybindings heavily. It is very useful to me even in it's current state, but it quickly becomes overwhelming. embark-dwim acts on a candidate without closing the minibuffer, which is very useful. embark-act lets the user choose from all actions, but has an overwhelming interface.
Marginalia adds more information to completion results.
I set the annotation-mode of marginalia to heavy. This gives even more information on the stuff that you are looking at. One thing I am missing from ivy is the highlighting on mode-commands based on the current state of the mode. Also, I do not understand all the shorthands used by marginalia yet.
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init = {
prelude = ''
(setq read-buffer-completion-ignore-case t
read-file-name-completion-ignore-case t
completion-ignore-case t)
(defun up-directory (path)
"Move up a directory in PATH without affecting the kill buffer."
(interactive "p")
(if (string-match-p "/." (minibuffer-contents))
(let ((end (point)))
(re-search-backward "/.")
(forward-char)
(delete-region (point) end))))
(define-key minibuffer-local-filename-completion-map
[C-backspace] #'up-directory)
'';
usePackage = {
consult = {
enable = true;
bind = {
C-M-j = "consult-buffer";
"C-c <C-m>" = "consult-global-mark";
"C-c C-a" = "consult-org-agenda";
C-s = "consult-line";
"C-x O" = "consult-org-heading";
"C-x b" = "consult-buffer";
"M-g M-g" = "consult-goto-line";
"M-g i" = "consult-imenu";
"M-s M-s" = "consult-line-multi";
};
bindLocal.minibuffer-local-map = {
C-j = "next-line";
C-k = "previous-line";
};
custom.consult-fontify-max-size = 1024;
};
consult-dir = {
enable = true;
after = [ "consult" ];
bind."C-x C-d" = "consult-dir";
bindLocal.minibuffer-local-map = {
"C-x C-d" = "consult-dir";
"C-x C-j" = "consult-dir-jump-file";
};
};
consult-eglot = {
enable = true;
after = [
"consult"
"eglot"
];
bind."C-c s" = "consult-eglot-symbols";
};
embark = {
config = ''
(add-to-list 'display-buffer-alist
'("\\`\\*Embark Collect \\(Live\\|Completions\\)\\*"
nil
(window-parameters (mode-line-format . none))))
'';
enable = true;
bind = {
"C-." = "embark-act";
"C-c c" = "embark-collect";
"C-h B" = "embark-bindings";
"M-." = "embark-dwim";
};
custom = {
embark-quit-after-action = "'((t . nil))";
prefix-help-command = "#'embark-prefix-help-command";
};
};
embark-consult = {
enable = true;
after = [
"embark"
"consult"
];
demand = true;
hook = [ "(embark-collect-mode . consult-preview-at-point-mode)" ];
};
marginalia = {
enable = true;
after = [ "vertico" ];
bindLocal.minibuffer-local-map.M-A = "marginalia-cycle";
init = "(marginalia-mode)";
};
nerd-icons-completion = {
enable = true;
after = [
"marginalia"
"nerd-icons"
];
hook = [ "(marginalia-mode . nerd-icons-completion-marginalia-setup)" ];
init = "(nerd-icons-completion-mode)";
};
orderless = {
config = ''
(orderless-define-completion-style orderless+initialism
(orderless-matching-styles '(orderless-initialism orderless-literal orderless-regexp)))
(setq completion-styles '(orderless)
completion-category-defaults nil
completion-category-overrides
'((file (styles partial-completion orderless+initialism))
(buffer (styles orderless+initialism))
(consult-multi (styles orderless+initialism))
(command (styles orderless+initialism))
(eglot (styles orderless+initialism))
(variable (styles orderless+initialism))
(symbol (styles orderless+initialism)))
orderless-matching-styles '(orderless-literal orderless-regexp))
'';
enable = true;
};
vertico = {
enable = true;
custom = {
vertico-count = 10;
vertico-cycle = true;
vertico-resize = true;
vertico-scroll-margin = 0;
};
init = ''
(vertico-mode)
(vertico-mouse-mode)
'';
};
vertico-directory = {
enable = true;
after = [ "vertico" ];
bindLocal.vertico-map = {
C-DEL = "vertico-directory-delete-word";
DEL = "vertico-directory-delete-char";
RET = "vertico-directory-enter";
};
hook = [ "(rfn-eshadow-update-overlay . vertico-directory-tidy)" ];
};
};
};
}
5.0.16. Helpful + which-key: Better help defaults
This pair of packages provides information on keybindings in addition to function names, which makes it easier to remember keybindings (which-key). The helpful package provides a better Help framework for Emacs. For some reason, the Help windows are always being focused by the cursor even though I have set help-window-select to nil. I do not understand why.
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage = {
helpful = {
enable = true;
bind = {
"C-h C-." = "helpful-at-point";
"C-h f" = "helpful-callable";
"C-h k" = "helpful-key";
"C-h v" = "helpful-variable";
};
custom.help-window-select = false;
};
which-key = {
enable = true;
custom.which-key-idle-delay = 0.3;
diminish = [ "which-key-mode" ];
init = "(which-key-mode)";
};
};
}
5.0.17. Ligatures
Personally, I think ligatures are fancy. With this mode, they stay 'cursorable'. However, I do not need them in all modes, so I only use them in programming modes.
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage.ligature = {
config = ''
(ligature-set-ligatures 'prog-mode
'("|||>" "<|||" "<==>" "<!--" "####" "~~>" "***" "||=" "||>"
":::" "::=" "=:=" "===" "==>" "=!=" "=>>" "=<<" "=/=" "!=="
"!!." ">=>" ">>=" ">>>" ">>-" ">->" "->>" "-->" "---" "-<<"
"<~~" "<~>" "<*>" "<||" "<|>" "<$>" "<==" "<=>" "<=<" "<->"
"<--" "<-<" "<<=" "<<-" "<<<" "<+>" "</>" "###" "#_(" "..<"
"..." "+++" "/==" "///" "_|_" "www" "&&" "^=" "~~" "~@" "~="
"~>" "~-" "**" "*>" "*/" "||" "|}" "|]" "|=" "|>" "|-" "{|"
"[|" "]#" "::" ":=" ":>" ":<" "$>" "==" "=>" "!=" "!!" ">:"
">=" ">>" ">-" "-~" "-|" "->" "--" "-<" "<~" "<*" "<|" "<:"
"<$" "<=" "<>" "<-" "<<" "<+" "</" "#{" "#[" "#:" "#=" "#!"
"##" "#(" "#?" "#_" "%%" ".=" ".." ".?" "+>" "++" "?:" "?="
"?." "??" "/*" "/=" "/>" "//" "__" "~~" "(*" "*)" "\\\\"
"://" ";;"))
'';
enable = true;
init = "(global-ligature-mode t)";
};
}
5.0.18. Popup (popper) + Shackle Buffers
The popper package allows to declare different buffers as 'popup-type', which sort of acts like a scratchpad. It can be toggled at any time using popper-toggle and the resulting frame can be freely customized (with shackle) to a certain size. It is also possible to prevent a buffer from appearing - I do this for example to the *Warnings* buffer, since usually I am not interested in it's output.
popper-echo-mode shows all buffers that are currently stored as a popup in the echo area when a popup is opened - this is useful since you can cycle between all popup buffers.
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage = {
general.config = ''
(swarsel/leader-keys
"mp" '(popper-toggle :which-key "popper"))
'';
popper = {
enable = true;
bind."M-[" = "popper-toggle";
init = ''
(setq popper-reference-buffers
'("\\*Messages\\*"
("\\*Warnings\\*" . hide)
"Output\\*$"
"\\*Async Shell Command\\*"
"\\*Async-native-compile-log\\*"
help-mode
helpful-mode
"*Occur*"
"*scratch*"
"*julia*"
"*Python*"
"*rustic-compilation*"
"*cargo-run*"
(compilation-mode . hide)))
(popper-mode +1)
(popper-echo-mode +1)
'';
};
shackle = {
config = ''
(setq shackle-rules '(("*Messages*" :select t :popup t :align right :size 0.3)
("*Warnings*" :ignore t :popup t :align right :size 0.3)
("*Occur*" :select t :popup t :align below :size 0.2)
("*scratch*" :select t :popup t :align below :size 0.2)
("*Python*" :select t :popup t :align below :size 0.2)
("*rustic-compilation*" :select t :popup t :align below :size 0.4)
("*cargo-run*" :select t :popup t :align below :size 0.2)
("*tex-shell*" :ignore t :popup t :align below :size 0.2)
(helpful-mode :select t :popup t :align right :size 0.35)
(help-mode :select t :popup t :align right :size 0.4)))
(shackle-mode 1)
'';
enable = true;
};
};
}
5.0.19. Org Mode
org-mode is probably my most-used mode in Emacs. It acts as my organizer, config management tool and calendar even.
Note that nearly all headings within the Org-mode heading are coded within the use-package setup, so be very careful about moving stuff about here.
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage = {
auctex = {
enable = true;
custom = {
LaTeX-electric-left-right-brace = true;
TeX-auto-save = true;
TeX-electric-sub-and-superscript = true;
TeX-engine = "'luatex";
TeX-master = false;
TeX-parse-self = true;
TeX-save-query = false;
font-latex-fontify-script = false;
};
hook = [
"(LaTeX-mode . visual-line-mode)"
"(LaTeX-mode . flyspell-mode)"
"(LaTeX-mode . LaTeX-math-mode)"
"(LaTeX-mode . reftex-mode)"
];
};
general.config = ''
(swarsel/leader-keys
"o" '(:ignore o :which-key "org")
"op" '(org-present :which-key "org-present")
"oa" '(org-agenda :which-key "org-agenda")
"or" '(org-refile :which-key "org-refile")
"ob" '(org-babel-mark-block :which-key "Mark whole src-block")
"ol" '(org-insert-link :which-key "insert link")
"oc" '(org-store-link :which-key "copy (=store) link")
"os" '(shfmt-region :which-key "format sh-block")
"od" '(org-babel-demarcate-block :which-key "demarcate (split) src-block")
"on" '(pedantix-format-region :which-key "format nix-block")
"ot" '(swarsel/org-babel-tangle-config :which-key "tangle file")
"oe" '(org-html-export-to-html :which-key "export to html")
"c" '(:ignore c :which-key "capture")
"ct" '((lambda () (interactive) (org-capture nil "tt")) :which-key "task")
"lc" '((lambda () (interactive) (progn (find-file swarsel-swarsel-org-filepath) (org-overview) )) :which-key "SwarselSystems.org")
"le" '((lambda () (interactive) (progn (find-file swarsel-swarsel-org-filepath) (goto-char (org-find-exact-headline-in-buffer "Emacs") ) (org-overview) (org-cycle) )) :which-key "Emacs.org")
"ln" '((lambda () (interactive) (progn (find-file swarsel-swarsel-org-filepath) (goto-char (org-find-exact-headline-in-buffer "System") ) (org-overview) (org-cycle))) :which-key "Nixos.org"))
(general-define-key
"C-M-a" (lambda () (interactive) (org-capture nil "a"))
"M-i" 'swarsel/org-insert-link-to-heading)
'';
hide-mode-line.enable = true;
org = {
config = ''
(advice-add 'org-unlogged-message :around #'suppress-messages)
(setq org-ellipsis " ⤵"
org-link-descriptive t
org-hide-emphasis-markers t
org-startup-folded t
org-support-shift-select t
org-agenda-start-with-log-mode t
org-fontify-quote-and-verse-blocks t
org-log-done 'time
org-log-into-drawer t
org-startup-with-inline-images t
org-export-headline-levels 6
org-image-actual-width nil
org-format-latex-options '(:foreground "White" :background default :scale 2.0 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
org-agenda-files '("~/Org/Tasks.org" "~/Org/Archive.org"))
(setq org-capture-templates
'(("t" "Todo" entry (file+headline "~/Org/Tasks.org" "Inbox")
"* TODO %?\n %i\n %a")
("j" "Journal" entry (file+olp+datetree "~/Org/Journal.org")
"* %?\nEntered on %U\n %i\n %a")))
(setq org-refile-targets
'((swarsel-archive-org-file :maxlevel . 1)
(swarsel-tasks-org-file :maxlevel . 1)))
(org-babel-do-load-languages
'org-babel-load-languages
'((emacs-lisp . t)
(python . t)
(js . t)
(shell . t)))
(set-face-attribute 'org-block nil :foreground 'unspecified :inherit 'fixed-pitch)
(set-face-attribute 'org-table nil :inherit 'fixed-pitch)
(set-face-attribute 'org-formula nil :inherit 'fixed-pitch)
(set-face-attribute 'org-code nil :inherit '(shadow fixed-pitch))
(set-face-attribute 'org-quote nil :inherit '(shadow fixed-pitch))
(set-face-attribute 'org-verse nil :inherit '(shadow fixed-pitch))
(set-face-attribute 'org-verbatim nil :inherit '(shadow fixed-pitch))
(set-face-attribute 'org-special-keyword nil :inherit '(font-lock-comment-face fixed-pitch))
(set-face-attribute 'org-meta-line nil :inherit '(font-lock-comment-face fixed-pitch))
(set-face-attribute 'org-checkbox nil :inherit 'fixed-pitch)
(dolist (face '((org-level-1 . 1.2)
(org-level-2 . 1.1)
(org-level-3 . 1.0)
(org-level-4 . 1.0)
(org-level-5 . 1.0)
(org-level-6 . 1.0)
(org-level-7 . 1.0)
(org-level-8 . 1.0)))
(set-face-attribute (car face) nil :font swarsel/variable-font :weight 'medium :height (cdr face)))
(add-to-list 'org-src-lang-modes '("conf-unix" . conf-unix))
(define-advice org-src-font-lock-fontify-block (:before (lang _start _end) swarsel/quiet-fontification-buffer)
(when-let* ((lang-mode (org-src-get-lang-mode-if-bound lang)))
(with-current-buffer (get-buffer-create (format " *org-src-fontification:%s*" lang-mode))
(unless (eq major-mode lang-mode)
(delay-mode-hooks (funcall lang-mode))
(rainbow-delimiters-mode 1)))))
(advice-add 'org-babel-tangle-single-block :around #'swarsel/org-babel-tangle-single-block-advice)
(advice-add 'org-babel-tangle :around #'swarsel/org-babel-tangle-timing-advice)
(require 'org-tempo)
(add-to-list 'org-structure-template-alist '("sh" . "src shell"))
(add-to-list 'org-structure-template-alist '("el" . "src emacs-lisp"))
(add-to-list 'org-structure-template-alist '("py" . "src python :results output"))
(add-to-list 'org-structure-template-alist '("nix" . "src nix-ts :tangle"))
(add-to-list 'org-structure-template-alist '("ne" . "bash :exports both"))
'';
enable = true;
bind = {
"C-<tab>" = "org-fold-outer";
"C-c s" = "org-store-link";
};
custom = {
org-confirm-babel-evaluate = false;
org-export-with-broken-links = "'mark";
org-fold-core-style = "'overlays";
org-html-htmlize-output-type = false;
org-src-fontify-natively = true;
org-src-preserve-indentation = false;
};
hook = [ "(org-mode . swarsel/org-mode-setup)" ];
init = ''
(defun swarsel/org-mode-setup ()
(variable-pitch-mode 1)
(add-hook 'org-tab-first-hook 'org-end-of-line)
(visual-line-mode 1))
(defun swarsel/org-mode-visual-fill ()
(setq visual-fill-column-width 150
visual-fill-column-center-text t)
(visual-fill-column-mode 1))
(defun swarsel/run-formatting ()
(interactive)
(let ((default-directory (expand-file-name "~/.dotfiles")))
(shell-command "find . -name '*.nix' -exec pedantix {} + > /dev/null")))
(defun swarsel/org-babel-tangle-config ()
(interactive)
(when (string-equal (buffer-file-name) swarsel-swarsel-org-filepath)
(org-babel-tangle)
(swarsel/run-formatting)))
(defun swarsel/org-babel-tangle-single-block-advice (orig-fun &rest args)
(let ((inhibit-redisplay t)
(inhibit-message t))
(apply orig-fun args)))
(defun swarsel/org-babel-tangle-timing-advice (orig-fun &rest args)
(let ((start (current-time)))
(prog1 (apply orig-fun args)
(message "org-tangle took %f sec" (float-time (time-since start))))))
(defun org-fold-outer ()
(interactive)
(org-beginning-of-line)
(when (org-at-heading-p)
(outline-up-heading 1))
(outline-hide-subtree))
(defun prot-org--id-get ()
(or (org-entry-get nil "CUSTOM_ID")
(let ((id (org-id-new "h")))
(org-entry-put nil "CUSTOM_ID" id)
id)))
(defun prot-org-id-headlines ()
(interactive)
(org-map-entries #'prot-org--id-get))
(defun prot-org-id-headline ()
(interactive)
(prot-org--id-get))
(defun swarsel/org-colorize-outline (path)
(let ((palette ["#58B6ED" "#8BD49C" "#33CED8" "#4B9CCC" "yellow" "orange" "salmon" "red"]))
(string-join
(seq-map-indexed (lambda (part depth)
(propertize part 'face `(:foreground ,(aref palette (mod depth (length palette))) :weight bold)))
path)
"/")))
(defun swarsel/org-insert-link-to-heading ()
(interactive)
(let* ((candidates (org-map-entries
(lambda ()
(cons (swarsel/org-colorize-outline (org-get-outline-path t))
(point-marker)))))
(marker (cdr (assoc (completing-read "Heading: " candidates nil t) candidates))))
(insert (org-with-point-at marker
(org-link-make-string (concat "#" (prot-org--id-get))
(org-get-heading t t t t))))))
(defun swarsel/org-agenda-done-and-archive ()
(interactive)
(let ((org-archive-location "~/Org/Archive.org::Archive"))
(org-agenda-todo "DONE")
(org-agenda-archive)
(save-some-buffers t (lambda ()
(and buffer-file-name
(file-in-directory-p buffer-file-name "~/Org/"))))))
(with-eval-after-load 'org-agenda
(define-key org-agenda-mode-map (kbd "C-a") #'swarsel/org-agenda-done-and-archive))
(defun org-babel-execute:markdown (body params)
"Just return BODY unchanged, allowing noweb expansion."
body)
'';
};
org-appear = {
enable = true;
hook = [ "(org-mode . org-appear-mode)" ];
init = ''
(setq org-appear-autolinks t
org-appear-autokeywords t
org-appear-autoentities t
org-appear-autosubmarkers t)
'';
};
org-fragtog = {
enable = true;
hook = [
"(org-mode . org-fragtog-mode)"
"((markdown-mode markdown-ts-mode) . org-fragtog-mode)"
];
};
org-modern = {
config = ''
(setq org-modern-block-name
'((t . t)
("src" "»" "∥")))
'';
enable = true;
custom.org-modern-block-fringe = false;
hook = [ "(org-mode . org-modern-mode)" ];
};
org-present = {
config = ''
(setq org-present-startup-folded t)
'';
enable = true;
bindLocal.org-present-mode-keymap = {
"<left>" = "swarsel/org-present-prev";
"<right>" = "swarsel/org-present-next";
q = "org-present-quit";
};
hook = [
"(org-present-mode . swarsel/org-present-start)"
"(org-present-mode-quit . swarsel/org-present-end)"
];
init = ''
(defun swarsel/org-reveal-at-point ()
(when (and (derived-mode-p 'org-mode)
(org-at-heading-p))
(org-show-entry)
(org-show-children)))
(defun swarsel/org-present-maybe-read-only ()
(if (org-in-src-block-p)
(when buffer-read-only
(org-present-read-write)
(evil-insert-state 1))
(unless buffer-read-only
(org-present-read-only)
(evil-insert-state 1))))
(defun swarsel/org-present-narrow (orig-fn &rest args)
(cl-letf (((symbol-function 'show-all) #'ignore))
(apply orig-fn args))
(org-overview)
(org-show-entry))
(advice-add 'org-present-narrow :around #'swarsel/org-present-narrow)
(defun swarsel/org-present-start ()
(setq-local face-remapping-alist `((default (:height 1.5) variable-pitch)
(header-line (:height 4.0) variable-pitch)
(org-document-title (:height 2.75) org-document-title)
(org-code (:height 1.2) org-code)
(org-verbatim (:family ,swarsel/fixed-font :height 1.0) org-verbatim)
(org-quote (:height 1.0) org-quote)
(org-verse (:height 1.0) org-verse)
(org-table (:family ,swarsel/fixed-font :weight regular :height 1.0) org-table)
(org-block (:height 0.9) org-block)
(org-link (:underline nil) org-link)
(org-block-begin-line (:height 0.7) org-block)))
(setq header-line-format " ")
(setq visual-fill-column-width 150)
(setq indicate-buffer-boundaries nil)
(setq inhibit-message nil)
(setq org-babel-eval-error-notify t)
(org-display-inline-images)
(global-hl-line-mode 0)
(evil-insert-state 1)
(org-present-read-only)
(org-overview)
(add-hook 'post-command-hook #'swarsel/org-reveal-at-point nil t)
(add-hook 'post-command-hook #'swarsel/org-present-maybe-read-only nil t))
(defun swarsel/org-present-end ()
(setq-local face-remapping-alist
(append
(mapcar (lambda (face) `(,face (:family ,swarsel/fixed-font :weight regular) ,face))
'(org-verbatim
org-table
org-meta-line
org-formula
org-checkbox
org-latex-and-related
org-indent
org-code
org-document-info-keyword
org-block-end-line
org-block-begin-line
org-block
mu4e-compose-header-face
mu4e-compose-separator-face
mu4e-contact-face
mu4e-link-face
mu4e-header-value-face
mu4e-header-key-face
message-header-other
message-header-subject
message-header-xheader
message-header-newsgroups
message-header-cc
message-header-to
message-header-name
markdown-math-face
markdown-language-keyword-face
markdown-language-info-face
markdown-inline-code-face
markdown-gfm-checkbox-face
markdown-code-face
line-number-minor-tick
line-number-major-tick
line-number-current-line
line-number
font-lock-variable-name-face
font-lock-type-face
font-lock-string-face
font-lock-regexp-grouping-construct
font-lock-regexp-grouping-backslash
font-lock-preprocessor-face
font-lock-negation-char-face
font-lock-keyword-face
font-lock-function-name-face
font-lock-doc-face
font-lock-constant-face
font-lock-comment-delimiter-face
font-lock-builtin-face
font-latex-sectioning-5-face
font-latex-warning-face
font-latex-sedate-face
font-latex-math-face
diff-removed
diff-hunk-header
diff-header
diff-function
diff-file-header
diff-context
diff-added))
'((default (:family "Sans Serif" :weight light) variable-pitch default))))
(setq header-line-format nil)
(setq visual-fill-column-width 150)
(setq indicate-buffer-boundaries t)
(setq inhibit-message nil)
(setq org-babel-no-eval-on-error nil)
(global-hl-line-mode 1)
(org-remove-inline-images)
(evil-normal-state 1)
(remove-hook 'post-command-hook #'swarsel/org-reveal-at-point t)
(remove-hook 'post-command-hook #'swarsel/org-present-maybe-read-only t))
(defun swarsel/org-present-prev ()
(interactive)
(beginning-of-buffer)
(org-present-prev)
(org-overview)
(org-show-entry)
(org-show-children))
(defun swarsel/org-present-next ()
(interactive)
(let* ((next-heading (save-excursion
(when (outline-next-heading) (point))))
(next-block (save-excursion
(when (re-search-forward "^#\\+begin_src" nil t)
(match-beginning 0))))
(target (if (and next-heading next-block)
(min next-heading next-block)
(or next-heading next-block))))
(if (and target (< target (point-max)))
(progn
(goto-char target)
(org-fold-show-entry)
(unless (pos-visible-in-window-p (point-max))
(recenter 0)))
(org-present-next))))
'';
};
visual-fill-column = {
enable = true;
hook = [
"(org-mode . swarsel/org-mode-visual-fill)"
"(markdown-ts-mode . swarsel/org-mode-visual-fill)"
];
};
};
}
5.0.20. Nix Mode
{
flake.modules.homeManager.emacs-init =
{
config,
lib,
pkgs,
...
}:
let
flake = ''(builtins.getFlake \"${config.swarselsystems.flakePath}\")'';
nixosOptions = "${flake}.nixosConfigurations.${config.node.name}.options";
in
{
config.programs.emacs.init.usePackage = {
eglot = {
config = ''
(add-to-list 'eglot-server-programs
'((nix-mode nix-ts-mode)
. ("${lib.getExe pkgs.nixd}")))
'';
init = ''
(setq-default eglot-workspace-configuration
'(:nixd (:nixpkgs (:expr "import ${flake}.inputs.nixpkgs { }")
:formatting (:command ["pedantix"])
:options (:nixos (:expr "${nixosOptions}")
:home-manager (:expr "${nixosOptions}.home-manager.users.valueMeta.attrs.${config.swarselsystems.mainUser}.configuration.options")
:flake-parts (:expr "${flake}.debug.options")))))
'';
};
nix-mode = {
enable = true;
defer = true;
mode = lib.mkForce [ ];
};
nix-ts-mode = {
enable = true;
mode = [
''"\\.nix\\'"''
''"\\.nix\\.enc\\'"''
];
};
};
};
}
5.0.21. HCL Mode
This adds support for Hashicorp Configuration Language. Used at work, it is mostly a Terraform Mode that does not support auto-formatting upon save. It still is nice :)
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage.hcl-mode = {
enable = true;
custom.hcl-indent-level = 2;
mode = [ ''"\\.hcl\\'"'' ];
};
}
5.0.22. Jenkinsfile/Groovy
This adds support for Groovy, which I specifically need to work with Jenkinsfiles. Similar to HCL Mode, it just provides some nice functions.
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage = {
groovy-mode.enable = true;
jenkinsfile-mode = {
enable = true;
mode = [ ''"Jenkinsfile"'' ];
};
};
}
5.0.23. Ansible
This is supposed to provide auto-completion when turned on. Of course I cannot globally turn this on since it would run in any .yaml file then, but even when manually started, it seems to do nothing. This would be nice at work.
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage.ansible.enable = true;
}
5.0.24. Terraform Mode
This adds support for Terraform configuration files. This is basically the same as the HCL Mode mode as the languages are very similar.
{
flake.modules.homeManager.emacs-init = { lib, ... }: {
config.programs.emacs.init.usePackage.terraform-mode = {
enable = true;
custom = {
terraform-format-on-save = true;
terraform-indent-level = 2;
};
hook = [ "(terraform-mode . outline-minor-mode)" ];
mode = lib.mkForce [ ''"\\.tf\\'"'' ];
};
};
}
5.0.25. pedantix
Adds pedantix formatting for nix code, including format-on-save in nix buffers (apheleia is disabled there so only pedantix runs). I make huge use of this using the chords C-<Space> o b (org-babel-mark-block) and then C-<Space> o n (pedantix-format-region). This is what I use to keep my nix org-src-blocks formatted. However, using org-mode: Upon-save actions (Auto-tangle, export to html, formatting), the resulting tangled files will be formatted in any case.
Note that for files that are not managed using this file (which there should normally not be many of), we can still use nix fmt for running treefmt for formatting and checks.
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage.pedantix = {
config = ''
(with-eval-after-load 'apheleia
(setf (alist-get 'nix-mode apheleia-mode-alist) nil
(alist-get 'nix-ts-mode apheleia-mode-alist) nil))
'';
enable = true;
hook = [
"(nix-mode . pedantix-format-on-save-mode)"
"(nix-ts-mode . pedantix-format-on-save-mode)"
];
};
}
5.0.26. shfmt
Adds functions for formatting shell scripts. Similarly to pedantixm I use this using the chords C-<Space> o b (org-babel-mark-block) and then C-<Space> o s (shfmt-region). This is what I use to keep shell script blocks formatted in this file. This is also handled by treefmt, but still, I want this file to stay organized as well.
{
flake.modules.homeManager.emacs-init =
{ lib, pkgs, ... }:
let
shfmt = ''"${lib.getExe pkgs.shfmt}"'';
in
{
config.programs.emacs.init.usePackage.shfmt = {
config = ''
(with-eval-after-load 'apheleia
(setf (car (alist-get 'shfmt apheleia-formatters)) ${shfmt}))
'';
enable = true;
custom = {
shfmt-arguments = '''("-i" "4" "-s" "-sr")'';
shfmt-command = shfmt;
};
};
};
}
5.0.27. Markdown Mode
Markdown files open in the built-in markdown-ts-mode (through treesit-enabled-modes); markdown-mode stays installed for its commands and for MultiMarkdown rendering, which allows me to render LaTeX and other nice things.
{
flake.modules.homeManager.emacs-init = { lib, ... }: {
config.programs.emacs.init.usePackage.markdown-mode = {
enable = true;
bindLocal.markdown-mode-map = {
"C-c C-e" = "markdown-do";
"C-c C-x C-l" = "org-latex-preview";
"C-c C-x C-u" = "markdown-toggle-url-hiding";
};
custom = {
markdown-command = "\"multimarkdown\"";
markdown-ts-ellipsis = "\" ⤵\"";
markdown-ts-hide-markup = true;
};
hook = [
"(markdown-mode . swarsel/markdown-block-local-font-lock)"
"(markdown-ts-mode . swarsel/markdown-ts-mode-setup)"
];
init = ''
(defun swarsel/markdown-block-local-font-lock ()
"Stop font-lock from widening every jit-lock chunk to its whole block."
(remove-hook 'font-lock-extend-region-functions #'markdown-font-lock-extend-region t))
(defvar-local swarsel/markdown-revealed-line nil)
(defun swarsel/markdown-reveal-fontify (start end)
(when swarsel/markdown-revealed-line
(save-excursion
(goto-char swarsel/markdown-revealed-line)
(let ((bol (pos-bol))
(eol (pos-bol 2)))
(when (and (< start eol) (< bol end))
(with-silent-modifications
(remove-text-properties bol eol '(invisible nil display nil))))))))
(defun swarsel/markdown-reveal-line ()
(let ((old swarsel/markdown-revealed-line))
(unless (and old (= old (pos-bol)))
(setq swarsel/markdown-revealed-line (copy-marker (pos-bol)))
(when old
(save-excursion
(goto-char old)
(font-lock-flush (pos-bol) (pos-bol 2))))
(font-lock-flush (pos-bol) (pos-bol 2)))))
(defun swarsel-markdown-fontify-table-border (node override start end &rest _)
(let ((beg (treesit-node-start node))
(fin (treesit-node-end node)))
(treesit-fontify-with-override beg fin 'markdown-ts-delimiter override start end)
(when markdown-ts-hide-markup
(put-text-property beg fin 'display
(cond ((equal (treesit-node-type node) "pipe_table_delimiter_cell")
(make-string (- fin beg) ?─))
((not (equal (treesit-node-type (treesit-node-parent node)) "pipe_table_delimiter_row"))
"│")
((not (treesit-node-prev-sibling node)) "├")
((not (treesit-node-next-sibling node)) "┤")
(t "┼"))))))
(defun swarsel/markdown-ts-mode-setup ()
(variable-pitch-mode 1)
(visual-line-mode 1)
(setq-local treesit-font-lock-settings
(append treesit-font-lock-settings
(treesit-font-lock-rules
:language 'markdown
:feature 'paragraph
:override 'prepend
'("|" @swarsel-markdown-fontify-table-border
(pipe_table_delimiter_cell) @swarsel-markdown-fontify-table-border))))
(add-hook 'jit-lock-functions #'swarsel/markdown-reveal-fontify 90 t)
(add-hook 'post-command-hook #'swarsel/markdown-reveal-line nil t))
(with-eval-after-load 'markdown-ts-mode
(keymap-set markdown-ts-mode-map "C-c C-x C-l" #'org-latex-preview)
(keymap-set markdown-ts-mode-map "C-c C-x C-u" #'markdown-ts-toggle-hide-markup)
(dotimes (level 6)
(set-face-attribute (intern (format "markdown-ts-heading-%d" (1+ level))) nil
:inherit (intern (format "org-level-%d" (1+ level)))
:weight 'unspecified))
(set-face-attribute 'markdown-ts-code-span nil :inherit 'org-code)
(set-face-attribute 'markdown-ts-code-block nil :inherit 'org-block)
(set-face-attribute 'markdown-ts-code-block-markup-hidden nil :background 'unspecified :inherit 'org-block)
(set-face-attribute 'markdown-ts-table nil :inherit 'org-block)
(set-face-attribute 'markdown-ts-table-header nil :inherit '(org-table markdown-ts-table) :weight 'bold))
'';
mode = lib.mkForce [ ];
};
};
}
5.0.28. elfeed
This adds elfeed, a neat RSS reader for Emacs. I use this as a client for FreshRSS. While I read most of my feeds on my phone (using Capy Reader), it is still good to have an Emacs-native reader as well. Some time ago I was still running a separate Emacs instance on my server for this. This instance would then sync the read feeds to other instances. This was very brittle however and is only left as a historical note.
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage = {
elfeed = {
config = ''
(define-key elfeed-show-mode-map (kbd ";") #'visual-fill-column-mode)
(define-key elfeed-show-mode-map (kbd "j") #'elfeed-goodies/split-show-next)
(define-key elfeed-show-mode-map (kbd "k") #'elfeed-goodies/split-show-prev)
(define-key elfeed-search-mode-map (kbd "j") #'next-line)
(define-key elfeed-search-mode-map (kbd "k") #'previous-line)
(define-key elfeed-search-mode-map (kbd "q") #'bjm/elfeed-save-db-and-bury)
(define-key elfeed-show-mode-map (kbd "S-SPC") #'scroll-down-command)
'';
enable = true;
custom = {
elfeed-db-directory = ''"~/.elfeed/db/"'';
elfeed-set-timeout = 36000;
elfeed-use-curl = true;
};
init = ''
(defun bjm/elfeed-save-db-and-bury ()
(interactive)
(elfeed-db-save)
(quit-window))
(defun bjm/elfeed-load-db-and-open ()
(interactive)
(elfeed-db-load)
(elfeed)
(elfeed-search-update--force)
(elfeed-update))
'';
};
elfeed-goodies = {
config = "(elfeed-goodies/setup)";
enable = true;
after = [ "elfeed" ];
};
elfeed-protocol = {
config = ''
(elfeed-protocol-enable)
(let ((domain (getenv "SWARSEL_RSS_DOMAIN")))
(setq elfeed-protocol-feeds
`((,(concat "fever+https://Swarsel@" domain)
:api-url ,(concat "https://" domain "/api/fever.php")
:password-file "~/.emacs.d/.fever"))))
'';
enable = true;
after = [ "elfeed" ];
custom = {
elfeed-protocol-enabled-protocols = "'(fever)";
elfeed-protocol-fever-fetch-category-as-tag = true;
elfeed-protocol-fever-update-unread-only = true;
};
};
general.config = ''
(swarsel/leader-keys
"mr" '(bjm/elfeed-load-db-and-open :which-key "elfeed"))
'';
};
}
5.0.29. Grep
This is the ripgrep package for Emacs.
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage = {
rg.enable = true;
wgrep = {
enable = true;
custom.wgrep-auto-save-buffer = true;
};
};
}
5.0.30. Tree-sitter
Tree-sitter is a parsing library integrated into Emacs to provide better syntax highlighting and code analysis. It generates concrete syntax trees for source code, enabling more accurate and efficient text processing. Emacs' tree-sitter integration enhances language support, offering features like incremental parsing and precise syntax-aware editing. This improves the development experience by providing robust and dynamic syntax features, making it easier for me to navigate and manipulate code.
In order to update the language grammars, run the next command below. NOTE: since we now load epkgs.treesit-grammars.with-all-grammars in Home-manager: Emacs, we actually never run this anymore. I leave it here however for a potential future reader. For safety, I still instruct treesitter to install missing grammars on the fly.
(mapc #'treesit-install-language-grammar (mapcar #'car treesit-language-source-alist))
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init = {
prelude = ''
(setopt treesit-enabled-modes t)
'';
usePackage = {
treesit-fold = {
config = "(global-treesit-fold-mode 1)";
enable = true;
};
treesit-grammars = {
enable = true;
package = epkgs: epkgs.treesit-grammars.with-all-grammars;
enableUsePackage = false;
};
};
};
}
5.0.31. direnv (envrc)
In Emacs, there are two packages for managing dev environments - Emacs-direnv (direnv) and envrc. Direnv uses the global Emacs environment whereas envrc is buffer-local. I do not really care about this difference. What is more important to me is that Emacs should not block upon handling a bigger flake.nix while setting up the dev environment. This seems to be better handled by envrc.
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage.envrc = {
enable = true;
hook = [ "(after-init . envrc-global-mode)" ];
};
}
5.0.32. avy
avy provides the ability to search for any character on the screen (not only in the current buffer!) - I enjoy this utility a lot and use it possibly even more often than the native vim commands.
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage.avy = {
enable = true;
bind.M-o = "avy-goto-char-timer";
custom.avy-all-windows = "'all-frames";
};
}
5.0.33. devdocs
devdocs is a very nice package that provides documentation from https:devdocs.io. This is very useful since e.g. pyright provides only a very bad documentation and I do not want to leave Emacs all the time just to read documentation.
To install a documentation, use the devdocs=install command and select the appropriate version. devdocs-update-all can be used to download and reinstall all installed documents if a newer version is available. Check documentation with devdocs-lookup (C-SPC h d).
{
flake.modules.homeManager.emacs-init =
let
devdocsHook = mode: docs: "(${mode} . (lambda () (setq-local devdocs-current-docs '(${docs}))))";
pythonDocs = ''"python~3.12" "numpy~1.23" "matplotlib~3.7" "pandas~1"'';
in
{
config.programs.emacs.init.usePackage.devdocs = {
enable = true;
hook = [
(devdocsHook "python-mode" pythonDocs)
(devdocsHook "python-ts-mode" pythonDocs)
(devdocsHook "c-mode" ''"c"'')
(devdocsHook "c-ts-mode" ''"c"'')
(devdocsHook "c++-mode" ''"cpp"'')
(devdocsHook "c++-ts-mode" ''"cpp"'')
];
};
};
}
5.0.34. Projectile
projectile is useful for keeping track of your git projects within Emacs. I mostly use it to quickly switch between projects.
{
flake.modules.homeManager.emacs-init = { config, lib, ... }: {
config.programs.emacs.init.usePackage = {
general.config = ''
(swarsel/leader-keys
"lp" '((lambda () (interactive) (projectile-switch-project)) :which-key "switch project"))
'';
projectile = {
config = "(projectile-mode)";
enable = true;
bindKeyMap."C-c p" = "projectile-command-map";
custom.projectile-completion-system = "'auto";
diminish = [ "projectile-mode" ];
init = ''
(let ((dirs (list ${lib.optionalString (builtins.elem "optional-work" config.swarselsystems.enabledHomeModules) "swarsel-work-projects-directory "}swarsel-private-projects-directory)))
(when (seq-every-p #'file-directory-p dirs)
(setq projectile-project-search-path dirs)))
(setq projectile-switch-project-action #'magit-status)
'';
};
};
};
}
5.0.35. Magit
Magit is the best git utility I have ever used - it has a beautiful interface and is very verbose. Here I mostly just setup the list of repositories that I want to expose to Magit.
Also, Emacs needs a little extra love to accept my Yubikey for git commits etc. We set that here: Yubikey support.
{
flake.modules.homeManager.emacs-init =
{ config, lib, ... }:
{
config.programs.emacs.init.usePackage = {
general.config = ''
(swarsel/leader-keys
"mg" '(magit-list-repositories :which-key "magit-list-repos")
"lr" '(swarsel/magit-status-repo :which-key "List repos")
"lg" '(magit-list-repositories :which-key "list git repos"))
(general-define-key
"M-r" 'swarsel/magit-status-repo)
'';
magit = {
config = ''
(advice-add 'magit-auto-revert-mode--init-kludge :around #'suppress-messages)
(setq magit-repository-directories `((,swarsel-private-projects-directory . 3)
${lib.optionalString (builtins.elem "optional-work" config.swarselsystems.enabledHomeModules) "(,swarsel-work-projects-directory . 3)"}
("~/.dotfiles/" . 0)))
(with-eval-after-load 'magit-diff
(define-key magit-hunk-section-map [remap magit-visit-thing] #'magit-diff-visit-worktree-file)
(define-key magit-file-section-map [remap magit-visit-thing] #'magit-diff-visit-worktree-file))
(defun swarsel/magit-insert-remote-branch-headers ()
(when-let* ((branch (magit-get-current-branch)))
(let ((shown (list (magit-get-upstream-branch branch) (magit-get-push-branch branch))))
(dolist (remote (magit-list-remotes))
(let ((target (concat remote "/" branch)))
(when (and (not (member target shown)) (magit-rev-verify target))
(pcase-let ((`(,ahead ,behind) (magit-rev-diff-count branch target)))
(magit-insert-section (branch target)
(insert (format "%-10s" (concat (capitalize remote) ": "))
(propertize target 'font-lock-face 'magit-branch-remote)
(format " ↑%d ↓%d " ahead behind)
(magit-log--wash-summary (or (magit-rev-format "%s" target) "(no commit message)"))
?\n)))))))))
(magit-add-section-hook 'magit-status-headers-hook #'swarsel/magit-insert-remote-branch-headers #'magit-insert-push-branch-header t)
(transient-define-suffix swarsel/magit-push-current-to-forge (args)
:if (lambda () (when-let* ((remote (magit-get "forge.remote"))) (magit-remote-p remote)))
:description (lambda ()
(let ((target (concat (magit-get "forge.remote") "/" (magit-get-current-branch))))
(concat (propertize target 'face 'magit-branch-remote)
(unless (magit-rev-verify target) ", creating it"))))
(interactive (list (magit-push-arguments)))
(let ((branch (magit-get-current-branch)))
(magit-git-push branch (concat (magit-get "forge.remote") "/" branch) args)))
(transient-insert-suffix 'magit-push "e" '("f" swarsel/magit-push-current-to-forge))
(transient-suffix-put 'magit-dispatch 'magit-worktree :key "%")
(transient-suffix-put 'magit-dispatch 'magit-show-refs :key "yr")
(transient-suffix-put 'magit-dispatch 'magit-refresh :key "gr")
'';
enable = true;
custom.magit-display-buffer-function = "#'magit-display-buffer-same-window-except-diff-v1";
init = ''
(defun swarsel/magit-status-repo ()
(interactive)
(magit-status (completing-read "Magit repo: " (magit-list-repos) nil t)))
'';
};
};
};
}
5.0.36. Yubikey support
The following settings are needed to make sure Emacs works for Magit commits and pushes. It is not a beautiful solution since committing uses pinentry-Emacs and pushing uses pinentry-gtk2, but it works for now at least. This works especially well since I have switched from pinentry-gtk3 to pinentry-waypromt.
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage.pinentry = {
config = ''
(pinentry-start)
(setq epg-pinentry-mode 'loopback)
'';
enable = true;
};
}
5.0.37. Forge
NOTE: Make sure to configure a GitHub token before using this package!
- https://magit.vc/manual/forge/Token-Creation.html#Token-Creation
- https://magit.vc/manual/ghub/Getting-Started.html#Getting-Started
- https://magit.vc/manual/ghub/Storing-a-Token.html
https://www.emacswiki.org/emacs/GnuPG
(1) in practice: GitHub -<> settings -<> developer option -<> create classic token with repo; user; read:org permissions (2)
machine api.github.com login USERNAME^forge password 012345abcdef...The above is handled by Home-manager: Emacs and only here as a historical note. Forge lets me interact with non-core git objects like issues and pull requests from within Emacs.
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage.forge = {
enable = true;
after = [ "magit" ];
init = "(setq forge-add-default-bindings nil)";
};
}
5.0.38. git-timemachine
This is just a nice utility to browse different versions of a file of a git project within Emacs.
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage.git-timemachine = {
enable = true;
hook = [ "(git-time-machine-mode . evil-normalize-keymaps)" ];
init = "(setq git-timemachine-show-minibuffer-details t)";
};
}
5.0.39. Delimiters (brackets): rainbow-delimiters, highlight-parentheses
- rainbow-delimiters colors all delimiters, also ones not in current selection
- parentheses highlights the current delimiter selection especially bold
- highlight-parentheses boldly highlights all delimiters in current selection
I am not completely sure on electric-pair-mode yet, sometimes it is very helpful, sometimes it annoys me to no end.
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage = {
highlight-parentheses = {
config = ''
(setq highlight-parentheses-colors '("black" "white" "black" "black" "black" "black" "black"))
(setq highlight-parentheses-background-colors '("magenta" "blue" "cyan" "green" "yellow" "orange" "red"))
(global-highlight-parentheses-mode t)
'';
enable = true;
};
rainbow-delimiters = {
enable = true;
hook = [ "(prog-mode . rainbow-delimiters-mode)" ];
};
};
}
5.0.40. rainbow-mode
Complimentary to the delimiters-packages above, this package sets the background color of the delimiters, which makes it easier to see at a glance where we are in a delimiter-tree.
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage.rainbow-mode = {
enable = true;
hook = [ "((css-mode css-ts-mode web-mode html-mode html-ts-mode) . rainbow-mode)" ];
};
}
5.0.41. Corfu
This is the company equivalent to the vertico gang.
I dislike the standard behavior that makes the cursor move into the completion framework on presses of <up> and <down>.
Nerd icons is originally enabled here: Icons
Navigation functions defined here: corfu: Do not interrupt navigation
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage = {
corfu = {
config = ''
(dolist (key '("M-n" "M-p"
"<remap> <next-line>" "<remap> <previous-line>"
"<remap> <scroll-down-command>" "<remap> <scroll-up-command>"
"<remap> <beginning-of-buffer>" "<remap> <end-of-buffer>"))
(keymap-unset corfu-map key t))
(dolist (command '(swarsel/corfu-insert-or-newline swarsel/corfu-insert-or-expand))
(add-to-list 'corfu-continue-commands command))
'';
enable = true;
bindLocal.corfu-map = {
"<down>" = "swarsel/corfu-quit-and-down";
"<return>" = "swarsel/corfu-insert-or-newline";
"<up>" = "swarsel/corfu-quit-and-up";
"C-<down>" = "corfu-next";
"C-<up>" = "corfu-previous";
M-SPC = "corfu-insert-separator";
"S-<down>" = "corfu-popupinfo-scroll-up";
"S-<up>" = "corfu-popupinfo-scroll-down";
TAB = "swarsel/corfu-insert-or-expand";
};
custom = {
corfu-auto = true;
corfu-auto-delay = 0.2;
corfu-auto-prefix = 2;
corfu-cycle = true;
corfu-on-exact-match = false;
corfu-popupinfo-delay = "'(0.5 . 0.2)";
corfu-popupinfo-max-height = 70;
corfu-preselect = "'prompt";
corfu-quit-no-match = "'separator";
corfu-separator = ''?\s'';
};
init = ''
(defun swarsel/corfu-insert-or-newline ()
(interactive)
(if (>= corfu--index 0)
(corfu-insert)
(corfu-quit)
(newline)))
(defun swarsel/corfu-insert-or-expand ()
(interactive)
(if (>= corfu--index 0)
(corfu-insert)
(corfu-expand)))
(defun swarsel/corfu-quit-and-up (&optional arg)
(interactive)
(corfu-quit)
(evil-previous-visual-line))
(defun swarsel/corfu-quit-and-down (&optional arg)
(interactive)
(corfu-quit)
(evil-next-visual-line))
(defun swarsel/corfu-evil-keys (mode _keymaps)
(when (eq mode 'corfu)
(evil-define-key* 'insert corfu-map
(kbd "<escape>") #'corfu-quit
(kbd "C-d") nil
(kbd "C-u") nil)))
(add-hook 'evil-collection-setup-hook #'swarsel/corfu-evil-keys)
(global-corfu-mode)
(corfu-history-mode)
(corfu-popupinfo-mode)
'';
};
evil-collection.custom.evil-collection-corfu-key-themes = false;
nerd-icons-corfu = {
config = ''
(add-to-list 'corfu-margin-formatters #'nerd-icons-corfu-formatter)
(setq nerd-icons-corfu-mapping
'((array :style "cod" :icon "symbol_array" :face font-lock-type-face)
(boolean :style "cod" :icon "symbol_boolean" :face font-lock-builtin-face)
(t :style "cod" :icon "code" :face font-lock-warning-face)))
'';
enable = true;
after = [ "corfu" ];
};
};
}
5.0.42. cape
cape adds even more completion capabilities by adding a lot of completion logic that is exposed as separate functions. I tried out adding these to the completion-at-points-functions alist, but I felt like it cluttered my suggestions too much. Hence I now just call the respective functions when I need them. For this I setup the C-z keybinding in General evil.
I leave the commented out alist extensions here in case I want to try them out at some point in the future.
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage.cape = {
enable = true;
bind = {
"C-z &" = "cape-sgml";
"C-z :" = "cape-emoji";
"C-z \\\\" = "cape-tex";
"C-z ^" = "cape-tex";
"C-z _" = "cape-tex";
"C-z a" = "cape-abbrev";
"C-z d" = "cape-dabbrev";
"C-z e" = "cape-elisp-block";
"C-z f" = "cape-file";
"C-z h" = "cape-history";
"C-z k" = "cape-keyword";
"C-z l" = "cape-line";
"C-z p" = "completion-at-point";
"C-z r" = "cape-rfc1345";
"C-z s" = "cape-elisp-symbol";
"C-z t" = "complete-tag";
"C-z w" = "cape-dict";
};
custom.cape-dict-file = ''(getenv "WORDLIST")'';
};
}
5.0.43. Tramp
Tramp allows for SSH access of files over Emacs. I have no ideas what the options here mean, but this is a recommended configuration that I found (sadly I lost the link). I need to research more what these options really do.
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage.tramp = {
config = ''
(customize-set-variable 'tramp-ssh-controlmaster-options
(concat
"-o ControlPath=/tmp/ssh-tramp-%%r@%%h:%%p "
"-o ControlMaster=auto -o ControlPersist=yes"))
'';
enable = true;
init = ''
(setq vc-ignore-dir-regexp
(format "\\(%s\\)\\|\\(%s\\)"
vc-ignore-dir-regexp
tramp-file-name-regexp))
(setq tramp-default-method "ssh")
(setq tramp-auto-save-directory
(expand-file-name "tramp-auto-save" user-emacs-directory))
(setq tramp-persistency-file-name
(expand-file-name "tramp-connection-history" user-emacs-directory))
(setq password-cache-expiry nil)
(setq tramp-use-ssh-controlmaster-options nil)
(setq remote-file-name-inhibit-cache nil)
'';
};
}
5.0.44. diff-hl
This is a simple highlighting utility that uses the margin to visually show the differences since the last git commit.
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage.diff-hl = {
enable = true;
hook = [ "((prog-mode org-mode) . diff-hl-mode)" ];
init = ''
(diff-hl-margin-mode)
(diff-hl-show-hunk-mouse-mode)
'';
};
}
5.0.45. eglot
Up comes the section of lsp clients for Emacs. For a longer time, I thought that I had to choose one only, and after having started with lsp-mode I had tried out lsp-booster and then went to eglot. My requirements are as follow:
Must have:
- mostly unobtrusive, non-blocking
- fast (configurable) completion
- xref (or similar)
Nice to have:
- Debugger
- Multi-lsp support (running two lsp's on a single project)
- Native Emacs support
eglot fills most items on the first list except for the non-blocking issue initially. It blocks sometimes on bigger projects as well as when entering directories using (nix-)direnv and the lsp is not yet loaded. The first issue is solved by using eglot-booster, which increases the parsing speed by what feels like a huge margin (but I never ran any actual tests). The second issue is solved with eglot-sync-connect, which avoids blocking the interface while the server is starting.
A blocking issue can still occur while entering a direnv that has a longer evaluation/build time. That issue can only be fixed by using Mic92's emacs-direnv fork, which calls direnv asynchronously, which in turn avoids the blocking. I am not using this on a daily basis however, since my environments are normally cached anyway and most of them (except for the LaTeX one) are not blocking for long enough for this to be worth it. However, I am considering spinning up my own fork of this at some point.
{
flake.modules.homeManager.emacs-init =
{ pkgs, ... }:
let
eglot-booster =
epkgs:
epkgs.trivialBuild rec {
packageRequires = [
epkgs.jsonrpc
epkgs.eglot
];
pname = "eglot-booster";
src = pkgs.fetchFromGitHub {
hash = "sha256-PLfaXELkdX5NZcSmR1s/kgmU16ODF8bn56nfTh9g6bs=";
owner = "jdtsmith";
repo = "eglot-booster";
rev = "e6daa6bcaf4aceee29c8a5a949b43eb1b89900ed";
};
version = "main-29-10-2024";
};
in
{
config = {
programs.emacs.init.usePackage = {
eglot = {
config = "(fset #'jsonrpc--log-event #'ignore)";
enable = true;
bindLocal.eglot-mode-map = {
"C-c ," = "eglot-code-actions";
"M-(" = "flymake-goto-next-error";
};
custom = {
eglot-autoshutdown = true;
eglot-connect-timeout = false;
eglot-events-buffer-size = 0;
eglot-send-changes-idle-time = 0.5;
eglot-sync-connect = false;
eldoc-echo-area-prefer-doc-buffer = true;
eldoc-echo-area-use-multiline-p = false;
flymake-no-changes-timeout = 1;
};
hook = [
"((python-mode python-ts-mode c-mode c-ts-mode c++-mode c++-ts-mode go-mode go-ts-mode tex-mode LaTeX-mode) . swarsel/eglot-ensure-and-format)"
];
init = ''
(defun swarsel/eglot-ensure-and-format ()
(eglot-ensure)
(add-hook 'before-save-hook #'eglot-format nil 'local))
(defalias 'start-lsp-server #'eglot)
'';
};
eglot-booster = {
config = "(eglot-booster-mode)";
enable = true;
package = eglot-booster;
after = [ "eglot" ];
};
eldoc-box = {
config = ''
(defun swarsel/eldoc-box-escape-filter (&optional _)
(when (eldoc-box--frame-visible-p)
#'eldoc-box-quit-frame))
(evil-define-minor-mode-key 'insert 'eldoc-box-hover-at-point-mode
(kbd "<escape>") '(menu-item "" nil :filter swarsel/eldoc-box-escape-filter))
'';
enable = true;
after = [ "eglot" ];
hook = [ "(eglot-managed-mode . eldoc-box-hover-at-point-mode)" ];
};
};
home.packages = [ pkgs.emacs-lsp-booster ];
};
};
}
5.0.46. dape
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage = {
dape = {
enable = true;
custom = {
dape-buffer-window-arrangement = "'right";
dape-inlay-hints = true;
};
};
sideline-flymake = {
enable = true;
hook = [ "(flymake-mode . sideline-mode)" ];
init = ''
(setq sideline-flymake-display-mode 'point)
(setq sideline-backends-right '(sideline-flymake))
'';
};
};
}
5.0.47. Dirvish
Dirvish is an improvement upon the dired-framework and has more features like file preview etc. Sadly it has an incompatibility with openwith which is why I have disabled that package.
{
flake.modules.homeManager.emacs-init =
{ lib, pkgs, ... }:
{
config.programs.emacs.init.usePackage = {
dirvish = {
config = ''
(dirvish-peek-mode)
(dirvish-side-follow-mode)
'';
enable = true;
bind = {
"<DUMMY-i> d" = "'dirvish";
"C-=" = "'dirvish-side";
};
bindLocal.dirvish-mode-map = {
"/" = "dirvish-narrow";
"<left>" = "dired-up-directory";
"<right>" = "dired-find-file";
J = "dirvish-history-jump";
M-b = "dirvish-history-go-backward";
M-e = "dirvish-emerge-menu";
M-f = "dirvish-history-go-forward";
M-j = "dirvish-fd-jump";
M-l = "dirvish-ls-switches-menu";
M-m = "dirvish-mark-menu";
M-s = "dirvish-setup-menu";
M-t = "dirvish-layout-toggle";
TAB = "dirvish-subtree-toggle";
a = "dirvish-quick-access";
f = "dirvish-file-info-menu";
h = "dired-up-directory";
j = "evil-next-visual-line";
k = "evil-previous-visual-line";
l = "dired-find-file";
y = "dirvish-yank-menu";
z = "dirvish-history-last";
};
custom = {
delete-by-moving-to-trash = true;
dired-listing-switches = ''"-l --almost-all --human-readable --group-directories-first --no-group"'';
dirvish-7z-program = ''"${lib.getExe pkgs._7zz}"'';
dirvish-attributes = "'(vc-state subtree-state nerd-icons collapse file-time file-size)";
dirvish-epub-thumbnailer-program = ''"${lib.getExe pkgs.epub-thumbnailer}"'';
dirvish-fc-query-program = ''"${lib.getExe' pkgs.fontconfig "fc-query"}"'';
dirvish-ffmpegthumbnailer-program = ''"${lib.getExe pkgs.ffmpegthumbnailer}"'';
dirvish-magick-program = ''"${lib.getExe' pkgs.imagemagick "magick"}"'';
dirvish-mediainfo-program = ''"${lib.getExe pkgs.mediainfo}"'';
dirvish-pdfinfo-program = ''"${lib.getExe' pkgs.poppler-utils "pdfinfo"}"'';
dirvish-pdftoppm-program = ''"${lib.getExe' pkgs.poppler-utils "pdftoppm"}"'';
dirvish-quick-access-entries = ''
'(("h" "~/" "Home")
("c" "~/.dotfiles/" "Config")
("d" "~/Downloads/" "Downloads")
("D" "~/Documents/" "Documents")
("p" "~/Documents/GitHub/" "Projects")
("/" "/" "Root"))'';
dirvish-vipsthumbnail-program = ''"${lib.getExe' pkgs.vips "vipsthumbnail"}"'';
};
init = "(dirvish-override-dired-mode)";
};
general.config = ''
(swarsel/leader-keys
"md" '(dirvish :which-key "dirvish"))
'';
};
};
}
5.0.48. undo-tree
Base Emacs undo logic is very useful, but not easy to understand for me. I prefer undo-tree, which makes switching between branches easier and also allows quickly switching back to a much older state using the visualizer.
Evil needs to be told to use this mode, see (evil-set-undo-system 'undo-tree) in Evil/General.
By default, I am not using undo-tree-mode in every buffer. This might change in the future, but for now this is fine. It can be enabled manually should the need arise.
While we are at it, we are also setting up a persistent undo-file for every file that we are working with.
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage.undo-tree = {
config = ''
(setq undo-tree-history-directory-alist '(("." . "~/.emacs.d/undo")))
(defun swarsel/clear-undo-tree ()
(interactive)
(setq buffer-undo-tree nil))
(define-advice undo-list-transfer-to-tree (:around (orig-fun &rest args) ignore-gc)
(cl-letf (((symbol-function 'garbage-collect) #'ignore))
(apply orig-fun args)))
'';
enable = true;
bindLocal.undo-tree-visualizer-mode-map = {
h = "undo-tree-visualize-switch-branch-left";
j = "undo-tree-visualize-redo";
k = "undo-tree-visualize-undo";
l = "undo-tree-visualize-switch-branch-right";
};
custom.undo-tree-auto-save-history = false;
init = "(global-undo-tree-mode)";
};
}
5.0.49. Hydra
Hydra allows for the writing of macro-style functions. I have not yet looked into this all too much, but it seems to be a potent feature.
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage = {
general.config = ''
(swarsel/leader-keys
"ts" '(hydra-text-scale/body :which-key "scale text"))
'';
hydra = {
config = ''
(defhydra hydra-text-scale (:timeout 4)
"scale text"
("j" text-scale-increase "in")
("k" text-scale-decrease "out")
("f" nil "finished" :exit t))
'';
enable = true;
};
};
}
5.0.50. Mail
In this section we are setting up mu4e, a mail client for Emacs using mu with mbsync as backend. The mail accounts themselves are setup in the NixOS configuration, so we only need to add Emacs specific settings here.
The hook functions are defined here: mu4e functions
{
flake.modules.homeManager.emacs-init =
{ lib, pkgs, ... }:
{
config.programs.emacs.init.usePackage = {
general.config = ''
(swarsel/leader-keys
"mm" '((lambda () (interactive) (mu4e)) :which-key "mu4e"))
'';
mu4e = {
config = ''
(advice-add 'mu4e--server-filter :around #'suppress-messages)
(setq send-mail-function 'sendmail-send-it)
(setq mu4e-change-filenames-when-moving t)
(setq mu4e-mu-binary (executable-find "mu"))
(setq mu4e-hide-index-messages t)
(setq mu4e-search-skip-duplicates nil)
(setq mu4e-update-interval 60)
(setq mu4e-get-mail-command "systemctl --user start mbsync.service")
(setq mu4e-maildir "~/Mail")
(setq mu4e-view-show-images t)
(when (fboundp 'imagemagick-register-types)
(imagemagick-register-types))
(setq mu4e-drafts-folder "/Drafts")
(setq mu4e-sent-folder "/Sent Mail")
(setq mu4e-refile-folder "/All Mail")
(setq mu4e-trash-folder "/Trash")
(setq mu4e-maildir-shortcuts
'((:maildir "/leon/Inbox" :key ?1)
(:maildir "/nautilus/Inbox" :key ?2)
(:maildir "/mrswarsel/Inbox" :key ?3)
(:maildir "/work/Inbox" :key ?4)
(:maildir "/Sent Mail" :key ?s)
(:maildir "/Trash" :key ?t)
(:maildir "/Drafts" :key ?d)
(:maildir "/All Mail" :key ?a)))
(setq user-mail-address (getenv "SWARSEL_MAIL4")
user-full-name (getenv "SWARSEL_FULLNAME"))
(setq mu4e-user-mail-address-list
(mapcar #'intern (split-string (or (getenv "SWARSEL_MAIL_ALL") "") "[ ,]+" t)))
(setq mu4e--log-max-size 1000)
(mu4e t)
(let ((work (getenv "SWARSEL_MAIL_WORK")))
(when (and work (not (string-empty-p work)))
(setq mml-secure-prefer-scheme 'smime)
(setq mml-secure-smime-sign-with-sender t)
(add-hook 'mu4e-compose-mode-hook #'swarsel/mu4e-sign-if-work)
(setq smime-keys
`((,work
,(format "~/.Certificates/%s.pem" work)
("~/Certificates/harica-root.pem"
"~/Certificates/harica-intermediate.pem"))))))
(setq mu4e-bookmarks
`((:name "Unread messages" :query "flag:unread AND NOT flag:trashed" :key 117)
(:name "Undeleted messages" :query "NOT flag:trashed" :key 103)
(:name "Today's messages" :query "date:today..now" :key 116)
(:name "Today's undeleted messages" :query "date:today..now AND NOT flag:trashed" :key 100)
(:name "Last 7 days" :query "date:7d..now" :hide-unread t :key 119)
(:name "Messages with images" :query "mime:image/*" :key 112))
)
'';
enable = true;
package = "mu4e";
hook = [
"(mu4e-compose-mode . swarsel/mu4e-send-from-correct-address)"
"(mu4e-compose-post . swarsel/mu4e-restore-default)"
];
init = ''
(defun swarsel/mu4e-sign-if-work ()
(when (and (stringp user-mail-address)
(string-equal user-mail-address (getenv "SWARSEL_MAIL_WORK")))
(mml-secure-message-sign-smime)))
(defun swarsel/mu4e-switch-account ()
(interactive)
(let ((account (completing-read "Select account: " mu4e-user-mail-address-list)))
(setq user-mail-address account)))
(defun swarsel/mu4e-rfs--matching-address ()
(cl-loop for to-data in (mu4e-message-field mu4e-compose-parent-message :to)
for to-email = (pcase to-data
(`(_ . email) email)
(x (mu4e-contact-email x)))
for to-name = (pcase to-data
(`(_ . name) name)
(x (mu4e-contact-name x)))
when (mu4e-user-mail-address-p to-email)
return (list to-name to-email)))
(defun swarsel/mu4e-send-from-correct-address ()
(when mu4e-compose-parent-message
(save-excursion
(when-let ((dest (swarsel/mu4e-rfs--matching-address)))
(cl-destructuring-bind (from-user from-addr) dest
(setq user-mail-address from-addr)
(swarsel/mu4e-sign-if-work)
(message-position-on-field "From")
(message-beginning-of-line)
(delete-region (point) (line-end-position))
(insert (format "%s <%s>" (or from-user user-full-name) from-addr)))))))
(defun swarsel/mu4e-restore-default ()
(setq user-mail-address (getenv "SWARSEL_MAIL4")
user-full-name (getenv "SWARSEL_FULLNAME")))
'';
};
mu4e-alert = {
config = ''
(mu4e-alert-enable-notifications)
(mu4e-alert-set-default-style 'libnotify)
(setq mu4e-alert-interesting-mail-query
(concat "(maildir:/leon/Inbox AND date:today..now"
" OR maildir:/work/Inbox AND date:today..now)"
" AND flag:unread"))
(alert-add-rule
:category "mu4e-alert"
:predicate (lambda (_) (string-match-p "^mu4e-" (symbol-name major-mode)))
:continue t)
'';
enable = true;
custom.alert-libnotify-command = ''"${lib.getExe' pkgs.libnotify "notify-send"}"'';
};
};
};
}
5.0.51. Calendar
This provides a beautiful calendar to Emacs.
{
flake.modules.homeManager.emacs-init =
{
inputs,
config,
pkgs,
...
}:
let
calfw =
_:
(inputs.nixpkgs-dev.legacyPackages.${pkgs.stdenv.hostPlatform.system}.emacsPackagesFor
config.programs.emacs.package
).calfw;
in
{
config.programs.emacs.init.usePackage = {
calfw = {
config = ''
(bind-key "g" 'cfw:refresh-calendar-buffer cfw:calendar-mode-map)
(bind-key "q" 'evil-quit cfw:details-mode-map)
(setq calendar-day-name-array
["Sunday" "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday"])
(setq calendar-week-start-day 1)
'';
enable = true;
package = calfw;
bind."C-c A" = "swarsel/open-calendar";
init = ''
(defun swarsel/open-calendar ()
(interactive)
(cfw:open-calendar-buffer
:contents-sources
(list
(cfw:org-create-source "Blue")
(cfw:ical-create-source (getenv "SWARSEL_CAL1NAME") (getenv "SWARSEL_CAL1") "Cyan")
(cfw:ical-create-source (getenv "SWARSEL_CAL2NAME") (getenv "SWARSEL_CAL2") "Green")
(cfw:ical-create-source (getenv "SWARSEL_CAL3NAME") (getenv "SWARSEL_CAL3") "Magenta")
)))
(require 'calfw-cal)
(require 'calfw-org)
(require 'calfw-ical)
'';
};
general.config = ''
(swarsel/leader-keys
"mc" '((lambda () (interactive) (swarsel/open-calendar)) :which-key "calendar"))
'';
org-caldav = {
config = ''
(setq org-icalendar-alarm-time 1)
(setq org-icalendar-include-todo t)
(setq org-icalendar-use-deadline '(event-if-todo event-if-not-todo todo-due))
(setq org-icalendar-use-scheduled '(todo-start event-if-todo event-if-not-todo))
'';
enable = true;
};
};
};
}
5.0.52. Dashboard: Emacs startup screen
This sets up the dashboard, which is really quite useless. But, it looks cool and makes me happy whenever I start an emacsclient without a file name as argument :)
{
flake.modules.homeManager.emacs-init =
{ root, confLib, ... }:
let
inherit (confLib.getConfig.repo.secrets.common.names) dashboard;
in
{
config.programs.emacs.init.usePackage.dashboard = {
config = ''
(dashboard-setup-startup-hook)
(let ((files-domain (getenv "SWARSEL_FILES_DOMAIN"))
(music-domain (getenv "SWARSEL_MUSIC_DOMAIN"))
(insta-domain (getenv "SWARSEL_INSTA_DOMAIN"))
(sport-domain (getenv "SWARSEL_SPORT_DOMAIN"))
(swarsel-domain (getenv "SWARSEL_DOMAIN"))
)
(setq dashboard-display-icons-p t
dashboard-icon-type 'nerd-icons
dashboard-set-file-icons t
dashboard-items '((recents . 5)
(projects . 5)
(agenda . 5))
dashboard-set-footer nil
dashboard-banner-logo-title "${dashboard.title}"
dashboard-image-banner-max-height 300
dashboard-startup-banner "${root "files/icons/swarsel.png"}"
dashboard-projects-backend 'projectile
dashboard-projects-switch-function 'magit-status
dashboard-set-navigator t
dashboard-startupify-list '(dashboard-insert-banner
dashboard-insert-newline
dashboard-insert-banner-title
dashboard-insert-newline
dashboard-insert-navigator
dashboard-insert-newline
dashboard-insert-init-info
dashboard-insert-items
)
dashboard-navigator-buttons
`(;; line1
((,(char-to-string #xf16d)
"${dashboard.social}"
"${dashboard.socialHelp}"
(lambda (&rest _) (browse-url ,insta-domain)))
(,(char-to-string #xf001)
"${dashboard.music}"
"${dashboard.musicHelp}"
(lambda (&rest _) (browse-url ,(concat "https://" music-domain))) )
(,(char-to-string #xf09b)
"${dashboard.github}"
"${dashboard.githubHelp}"
(lambda (&rest _) (browse-url "https://github.com/Swarsel")) )
(,(char-to-string #xebaa)
"${dashboard.files}"
"${dashboard.filesHelp}"
(lambda (&rest _) (browse-url ,(concat "https://" files-domain))) )
(,(char-to-string #xf0ad1)
"${dashboard.sport}"
"${dashboard.sportHelp}"
(lambda (&rest _) (browse-url ,sport-domain)))
)
(
(,(char-to-string #xf1105)
,swarsel-domain
,(concat "Browse " swarsel-domain)
(lambda (&rest _) (browse-url ,(concat "https://" swarsel-domain))))
)
)))
'';
enable = true;
};
};
}
5.0.53. vterm
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage.vterm = {
enable = true;
custom.vterm-tramp-shells = '''(("ssh" "'sh'"))'';
};
}
5.0.54. Less logging
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.prelude = ''
(setq message-log-max 30)
(setq comint-buffer-maximum-size 50)
(add-hook 'comint-output-filter-functions 'comint-truncate-buffer)
'';
}
5.0.55. Popup frames
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.prelude = ''
(defun prot-window-delete-popup-frame (&rest _)
"Kill selected selected frame if it has parameter `prot-window-popup-frame'.
Use this function via a hook."
(when (frame-parameter nil 'prot-window-popup-frame)
(delete-frame)))
(defmacro prot-window-define-with-popup-frame (command)
"Define interactive function which calls COMMAND in a new frame.
Make the new frame have the `prot-window-popup-frame' parameter."
`(defun ,(intern (format "prot-window-popup-%s" command)) ()
,(format "Run `%s' in a popup frame with `prot-window-popup-frame' parameter.
Also see `prot-window-delete-popup-frame'." command)
(interactive)
(let ((frame (make-frame '((prot-window-popup-frame . t)
(title . "Emacs Popup Frame")))))
(unwind-protect
(progn
(select-frame frame)
(switch-to-buffer " prot-window-hidden-buffer-for-popup-frame")
(condition-case nil
(call-interactively ',command)
((quit error user-error)
(delete-frame frame))))
(dolist (fr (frame-list))
(when (string= (frame-parameter fr 'name) "Emacs Popup Anchor")
(delete-frame fr)))))))
(declare-function org-capture "org-capture" (&optional goto keys))
(defvar org-capture-after-finalize-hook)
(prot-window-define-with-popup-frame org-capture)
(add-hook 'org-capture-after-finalize-hook #'prot-window-delete-popup-frame)
(declare-function mu4e "mu4e" (&optional goto keys))
(prot-window-define-with-popup-frame mu4e)
(advice-add 'mu4e-quit :after #'prot-window-delete-popup-frame)
(declare-function swarsel/open-calendar "swarsel/open-calendar" (&optional goto keys))
(prot-window-define-with-popup-frame swarsel/open-calendar)
(advice-add 'bury-buffer :after #'prot-window-delete-popup-frame)
(declare-function org-agenda "org-agenda" (&optional goto keys))
(prot-window-define-with-popup-frame org-agenda)
'';
}
5.0.56. Close pane when closing buffer
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.prelude = ''
(defun swarsel/kill-buffer-delete-window ()
(let ((win (get-buffer-window (current-buffer))))
(when (and win (not (one-window-p)))
(delete-window win))))
(add-hook 'kill-buffer-hook #'swarsel/kill-buffer-delete-window)
'';
}
5.0.57. hunkle
{
flake-file.inputs.hunkle = {
inputs = {
flake-parts.follows = "flake-parts";
git-hooks-nix.follows = "pre-commit-hooks";
nixpkgs.follows = "nixpkgs";
treefmt-nix.follows = "treefmt-nix";
};
url = "github:Swarsel/hunkle";
};
flake.modules.homeManager.emacs-init = { inputs, pkgs, ... }: {
config.programs.emacs.init.usePackage.hunkle = {
config = "(hunkle-magit-setup)";
enable = true;
package =
epkgs:
epkgs.trivialBuild {
packageRequires = [ epkgs.magit ];
pname = "hunkle";
postPatch = ''
substituteInPlace hunkle.el \
--replace-fail '(defcustom hunkle-executable "hunkle"' \
'(defcustom hunkle-executable "${pkgs.hunkle}/bin/hunkle"'
'';
src = "${inputs.hunkle}/emacs";
version = "0.1.0";
};
after = [ "magit" ];
};
};
}
5.0.58. apheleia
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage.apheleia = {
config = "(apheleia-global-mode 1)";
enable = true;
};
}
5.0.59. jinx
{
flake.modules.homeManager.emacs-init =
{ lib, pkgs, ... }:
let
dictionaries = with pkgs.hunspellDicts; [
de_AT
de_CH
de_DE
en_GB-large
en_US-large
];
in
{
config = {
programs.emacs.init.usePackage = {
ispell = {
enable = true;
custom.ispell-program-name = ''"${lib.getExe (pkgs.hunspell.withDicts (_: dictionaries))}"'';
};
jinx = {
enable = true;
bind = {
"C-M-$" = "jinx-languages";
"M-$" = "jinx-correct";
};
custom.jinx-languages = ''"en_US"'';
hook = [
"(text-mode . jinx-mode)"
"(prog-mode . jinx-mode)"
"(conf-mode . jinx-mode)"
];
};
};
home.packages = dictionaries;
systemd.user.sessionVariables.DICPATH = lib.makeSearchPath "share/hunspell" dictionaries;
};
};
}
5.0.60. pulsar
{
flake.modules.homeManager.emacs-init.config.programs.emacs.init.usePackage.pulsar = {
config = ''
(pulsar-global-mode 1)
(with-eval-after-load 'consult
(add-hook 'consult-after-jump-hook #'pulsar-recenter-top)
(add-hook 'consult-after-jump-hook #'pulsar-reveal-entry))
'';
enable = true;
custom = {
pulsar-face = "'pulsar-green";
pulsar-highlight-face = "'pulsar-cyan";
pulsar-pulse = true;
};
};
}
6. Tofu
Recently I have started using OpenTofu to manage aspects of this configuration.
6.1. .sops.yaml
Over time, my .sops.yaml has become quite big, and maintaining it manually has become a chore. Using tofu, I can define some simple-ish rules that automate the process, and by doing so, it also makes my deployment script a little simpler.
6.1.1. main.tf
I have 5 main blocks of rules in my .sops.yaml:
- Repository-wide rules - these should generally be accessible by all hosts
- however, I make it possible to exclude a host from this list
- this is mostly used so that I can create placeholder keys using the
has_age_keyvariable. When deploying a new machine, I can set that to false initially to create all the blocks for the host but not add it's age key to them. As soon as I get the age key during provisioning, I can then insert it and runjust updatekeysand be set
- this is mostly used so that I can create placeholder keys using the
- however, I make it possible to exclude a host from this list
- Kanidm rules - these are used for the basic shared secrets used between the kanidm server and the client application server. That secret is shared and this way, I do not have to repeat myself (it also saves on some cross-evaluations in principle - there are still others, so this does not really help)
- Host rules - for each host in
hosts/, this creates two blocks:- one for general secrets, only available to that host
- one block that also includes PII files (ending in
.nix.enc) - these are also available to the host running Buildbot, so that that host is able to build those configurations. As PII are not really sensitive secrets, it is fine if they are available on that host as well (they land in the nix store and thus the (private) cache anyway)
- Guest rules - these are for the MicroVM guests that some of the hosts have. They follow the same pattern as the host rules
- WireGuard rules - these are used to create blocks for the preshared secrets used in WireGuard connections
- Extra rules - used for stuff that does not fit the above, e.g. NGINX secrets
locals {
key_dir = "${path.module}/../../files/public/age"
nodes = {
for f in fileset("${local.key_dir}/hosts", "*.pub") :
trimsuffix(f, ".pub") => trimspace(file("${local.key_dir}/hosts/${f}"))
}
users = {
for f in fileset("${local.key_dir}/users", "*.pub") :
trimsuffix(f, ".pub") => trimspace(file("${local.key_dir}/users/${f}"))
}
host_key_names = {
for name, cfg in var.host_configs : name => coalesce(cfg.age_key_name, name)
}
with_key = [for name in keys(local.nodes) : name]
repo_host_age_names = [
for name, cfg in var.host_configs : local.host_key_names[name]
if cfg.repo_access && contains(local.with_key, local.host_key_names[name])
]
repo_rules = [
{
path_regex = "secrets/repo/[^/]+\\.enc$"
age_names = concat(["buildbot"], local.repo_host_age_names)
},
]
extra_rules = [
for rule in var.extra_rules : {
path_regex = rule.path_regex
age_names = rule.age_keys
}
]
host_paths = {
for name, cfg in var.host_configs : name => coalesce(cfg.path, "hosts/${cfg.type}/${cfg.arch}/${name}")
}
host_rules = [
for name, cfg in var.host_configs : {
path_regex = "${local.host_paths[name]}/secrets/[^/]+\\.enc$"
age_names = [local.host_key_names[name], "buildbot"]
}
]
guest_rules = flatten([
for name, cfg in var.host_configs : [
for guest in cfg.guests : {
path_regex = "${local.host_paths[name]}/secrets/${guest}/[^/]+\\.enc$"
age_names = [local.host_key_names[name], "${name}-${guest}", "buildbot"]
}
]
])
master_rules = [
{
path_regex = "\\.(yaml|json|env|ini|enc)$"
age_names = []
},
]
all_rules_raw = concat(
local.repo_rules,
local.extra_rules,
local.host_rules,
local.guest_rules,
local.master_rules,
)
all_rules = [
for rule in local.all_rules_raw : {
path_regex = rule.path_regex
age_names = [for n in rule.age_names : n if n == "buildbot" || contains(local.with_key, n)]
}
]
}
6.1.2. variables.tf
variable "pgp_key" {
description = "PGP key fingerprint for the main user"
type = string
}
variable "buildbot_age_key" {
description = "Age key for buildbot"
type = string
}
variable "host_configs" {
description = "Host configurations with type, arch, and optional guest list; age keys are read from files/public/age/hosts/<name>.pub"
type = map(object({
type = string
arch = string
age_key_name = optional(string)
path = optional(string)
guests = optional(list(string), [])
repo_access = optional(bool, true)
}))
}
variable "extra_rules" {
description = "Additional creation rules for eval-time encrypted files outside the host directories (e.g. secrets/work)"
type = list(object({
path_regex = string
age_keys = list(string)
}))
default = []
}
6.1.3. terraform.tfvars
pgp_key = "4BE7925262289B476DBBC17B76FD3810215AE097"
buildbot_age_key = "age15dewhja45kljg3ehd6anzwlxmavaf8wpqqj0gf6u859kd5v70ves6zkxr7"
extra_rules = [
{
path_regex = "secrets/work/[^/]+\\.enc$"
age_keys = ["pyramid", "treehouse", "buildbot"]
},
]
host_configs = {
pyramid = {
type = "nixos"
arch = "x86_64-linux"
guests = []
}
bakery = {
type = "nixos"
arch = "x86_64-linux"
guests = []
}
winters = {
type = "nixos"
arch = "x86_64-linux"
guests = []
}
eagleland = {
type = "nixos"
arch = "x86_64-linux"
guests = []
}
summers = {
type = "nixos"
arch = "x86_64-linux"
guests = [
"ankisync",
"atuin",
"audio",
"dawarich",
"firefly",
"forgejo",
"freshrss",
"homebox",
"immich",
"jellyfin",
"kanidm",
"kavita",
"koillection",
"matrix",
"mealie",
"monitoring",
"nextcloud",
"paperless",
"radicale",
"storage",
"transmission",
"utility",
]
}
hintbooth = {
type = "nixos"
arch = "x86_64-linux"
guests = ["adguardhome", "nginx"]
}
moonside = {
type = "nixos"
arch = "aarch64-linux"
guests = []
}
belchsfactory = {
type = "nixos"
arch = "aarch64-linux"
guests = []
}
stoicclub = {
type = "nixos"
arch = "aarch64-linux"
guests = []
}
liliputsteps = {
type = "nixos"
arch = "aarch64-linux"
guests = []
}
twothreetunnel = {
type = "nixos"
arch = "aarch64-linux"
guests = []
}
machpizza = {
type = "darwin"
arch = "aarch64-darwin"
guests = []
}
vacanthouse = {
type = "utility"
arch = "x86_64-linux"
path = "hosts/utility/vacanthouse"
guests = []
repo_access = false
}
}
6.1.4. Output Template
# This file is generated by OpenTofu. Do not edit manually.
# Since switching to sops-rekey, only PII files are managed here.
keys:
- &users
- &swarsel ${pgp_key}
%{ for name, key in users ~}
- &${name} ${key}
%{ endfor ~}
- &hosts
%{ for name, key in nodes ~}
- &${name} ${key}
%{ endfor ~}
- &buildbot ${buildbot_age_key}
creation_rules:
%{ for rule in rules ~}
- path_regex: ${rule.path_regex}
key_groups:
- pgp:
- *swarsel
%{ if length(rule.age_names) > 0 || length(users) > 0 ~}
age:
%{ for name, _ in users ~}
- *${name}
%{ endfor ~}
%{ for name in rule.age_names ~}
- *${name}
%{ endfor ~}
%{ endif ~}
%{ endfor ~}
6.1.5. outputs.tf
resource "local_file" "sops_yaml" {
filename = "${path.module}/../../.sops.yaml"
file_permission = "0644"
content = templatefile("${path.module}/templates/sops.yaml.tftpl", {
pgp_key = var.pgp_key
buildbot_age_key = var.buildbot_age_key
users = local.users
nodes = local.nodes
rules = local.all_rules
})
}
6.1.6. providers.tf
terraform {
required_providers {
local = {
source = "hashicorp/local"
version = "~> 2.0"
}
}
}
7. Appendix A: Noweb-Ref blocks
This sections is no longer used really. An introduction can be found in Structure of this file under the historical note. The little noweb-ref blocks that I still use are found in Hosts and Services.
7.1. General steps when setting up a new machine
These general steps are needed when setting up a new machine and do not fit into another block well:
- setup yubikey (automatic yubikey enrollment is not yet supported by `disko`):
- `systemd-cryptenroll --fido2-device=auto /dev/<device, e.g. 'nvme0n1p2'>`
7.2. Current patches and fixes
These are current deviations from the standard settings that I take while some things are broken upstream
- 20260101:
- nixos:
- firezone-gateway does not work in newer versions with firezone-server (currently working version v1.4.8)
- 20251102:
- flake:
- emacs-overlay:
- : version pinned because emacsclient is currently broken on latest
- niri-flake:
- currently not using the sugared version of screenshot-[,window], as it is currently broken
- home-manager:
- emacs-tramp:
- using stable version in extraPackages (broken in unstable)
- :ensure nil in emacs tramp settings to use package in extraPackages
- emacs-calfwL
- pinned to version not in nixpkgs (is in latest emacs-overlay, but that is broken)
- vesktop:
- running stable version (broken in unstable)
- batgrep:
- running stable version (broken in unstable)
7.3. HTML export javascript: Darkmode toggle
This adds a simple dark mode toggle to the HTML version of this document.
<script src='https://cdn.jsdelivr.net/npm/darkmode-js@1.5.7/lib/darkmode-js.min.js'></script>
<script>
function addDarkmodeWidget() {
new Darkmode({label:'[☀︎]'}).showWidget();
}
window.addEventListener('load', addDarkmodeWidget);
</script>
7.4. HTML export javascript: Docs QoL
This adds the following functionalities to the HTML version of this document:
- Section pinning with persistent pins
- Copy section links to clipboard button
- Searching in table of contents
- Skip to next section buttons (one for simply next section, one for same level, one for at least higher level)
(function() {
function ready(fn) {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', fn);
} else {
fn();
}
}
ready(function initPinned() {
const STORAGE_KEY = 'org-pinned-items-v2';
let pinnedPanel = document.getElementById('pinned-panel');
if (!pinnedPanel) {
pinnedPanel = document.createElement('aside');
pinnedPanel.id = 'pinned-panel';
pinnedPanel.innerHTML = `
<div id='pinned-panel-header'>
<h2>Pinned</h2>
<button id='toggle-pinned-btn' type='button' title='Hide pinned panel'>✕</button>
</div>
<button id='clear-all-pins-btn' type='button'>Clear All</button>
<ul id='pinned-list'></ul>
`;
document.body.appendChild(pinnedPanel);
}
let showBtn = document.getElementById('show-pinned-btn');
if (!showBtn) {
showBtn = document.createElement('button');
showBtn.id = 'show-pinned-btn';
showBtn.type = 'button';
showBtn.textContent = 'Pinned';
document.body.appendChild(showBtn);
}
const content = document.getElementById('content');
const pinnedList = document.getElementById('pinned-list');
const toggleBtn = document.getElementById('toggle-pinned-btn');
const clearAllBtn = document.getElementById('clear-all-pins-btn');
const toc = document.getElementById('table-of-contents');
const body = document.body;
if (!content || !pinnedList || !toggleBtn || !clearAllBtn || !toc) return;
function injectSearch() {
if (document.getElementById('toc-search-input')) return;
const searchContainer = document.createElement('div');
searchContainer.id = 'toc-search-container';
const searchInput = document.createElement('input');
searchInput.id = 'toc-search-input';
searchInput.type = 'text';
searchInput.placeholder = 'Search TOC...';
searchInput.autocomplete = 'off';
const clearBtn = document.createElement('button');
clearBtn.id = 'toc-search-clear';
clearBtn.type = 'button';
clearBtn.textContent = 'Clear';
searchContainer.appendChild(searchInput);
searchContainer.appendChild(clearBtn);
toc.insertBefore(searchContainer, toc.firstChild);
function filterTOC(term) {
const allLinks = toc.querySelectorAll('a');
allLinks.forEach(link => {
const li = link.closest('li');
if (!li) return;
const text = link.textContent.toLowerCase();
const matches = text.includes(term);
if (matches) {
li.classList.remove('hidden-by-search');
let parent = li.parentElement;
while (parent && parent !== toc) {
if (parent.tagName === 'UL') {
parent.style.display = '';
}
if (parent.tagName === 'LI') {
parent.classList.remove('hidden-by-search');
}
parent = parent.parentElement;
}
} else {
li.classList.add('hidden-by-search');
}
});
if (term === '') {
const allLis = toc.querySelectorAll('li');
allLis.forEach(li => li.classList.remove('hidden-by-search'));
}
}
searchInput.addEventListener('input', function(e) {
const term = e.target.value.toLowerCase();
filterTOC(term);
});
clearBtn.addEventListener('click', function() {
searchInput.value = '';
filterTOC('');
searchInput.focus();
});
}
injectSearch();
function addHeadingLinks() {
const headers = content.querySelectorAll('h1, h2, h3, h4, h5, h6, h7, h8, h9');
headers.forEach(header => {
const id = header.getAttribute('id');
if (!id) return;
if (header.querySelector('.heading-link')) return;
const link = document.createElement('a');
link.className = 'heading-link';
link.href = '#' + id;
link.textContent = '#';
link.title = 'Copy link to this heading';
const pinBtn = header.querySelector('.toc-pin-btn');
if (pinBtn) {
header.insertBefore(link, pinBtn);
} else {
header.appendChild(link);
}
link.addEventListener('click', function(e) {
e.preventDefault();
const url = window.location.origin + window.location.pathname + '#' + id;
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(url)
.then(() => {
const originalText = link.textContent;
link.textContent = '✓';
setTimeout(() => {
link.textContent = originalText;
}, 1000);
})
.catch(err => {
console.warn('Failed to copy to clipboard', err);
window.location.hash = id;
});
} else {
window.location.hash = id;
}
});
});
}
addHeadingLinks();
function addNextHeadingButtons() {
const headers = Array.from(content.querySelectorAll('h1, h2, h3, h4, h5, h6, h7, h8, h9'));
function getLevel(header) {
return parseInt(header.tagName.substring(1), 10);
}
headers.forEach((header, index) => {
const currentLevel = getLevel(header);
const headingLink = header.querySelector('.heading-link');
const pinBtn = header.querySelector('.toc-pin-btn');
function insertActionBtn(btn) {
if (pinBtn) {
header.insertBefore(btn, pinBtn);
return;
}
if (headingLink && headingLink.parentNode === header) {
headingLink.after(btn);
return;
}
header.appendChild(btn);
}
const nextHeader = headers[index + 1];
if (nextHeader && !header.querySelector('.heading-next')) {
const nextId = nextHeader.getAttribute('id');
if (nextId) {
const nextBtn = document.createElement('button');
nextBtn.className = 'heading-next';
nextBtn.type = 'button';
nextBtn.textContent = '↓';
nextBtn.title = 'Jump to next heading';
insertActionBtn(nextBtn);
nextBtn.addEventListener('click', function(e) {
e.preventDefault();
nextHeader.scrollIntoView({ behavior: 'smooth', block: 'start' });
history.pushState(null, null, '#' + nextId);
});
}
}
if (!header.querySelector('.heading-skip')) {
let skipHeader = null;
for (let i = index + 1; i < headers.length; i++) {
if (getLevel(headers[i]) <= currentLevel) {
skipHeader = headers[i];
break;
}
}
if (skipHeader) {
const skipId = skipHeader.getAttribute('id');
if (skipId) {
const skipBtn = document.createElement('button');
skipBtn.className = 'heading-skip';
skipBtn.type = 'button';
skipBtn.textContent = '⇣';
skipBtn.title = 'Skip to next section (same level)';
insertActionBtn(skipBtn);
skipBtn.addEventListener('click', function(e) {
e.preventDefault();
skipHeader.scrollIntoView({ behavior: 'smooth', block: 'start' });
history.pushState(null, null, '#' + skipId);
});
}
}
}
if (!header.querySelector('.heading-skip-up')) {
let upHeader = null;
for (let i = index + 1; i < headers.length; i++) {
if (getLevel(headers[i]) < currentLevel) {
upHeader = headers[i];
break;
}
}
if (upHeader) {
const upId = upHeader.getAttribute('id');
if (upId) {
const upBtn = document.createElement('button');
upBtn.className = 'heading-skip-up';
upBtn.type = 'button';
upBtn.textContent = '⇑';
upBtn.title = 'Jump to next higher-level section (escape subsections)';
insertActionBtn(upBtn);
upBtn.addEventListener('click', function(e) {
e.preventDefault();
upHeader.scrollIntoView({ behavior: 'smooth', block: 'start' });
history.pushState(null, null, '#' + upId);
});
}
}
}
});
}
addNextHeadingButtons();
let mobileTocBtn = document.getElementById('mobile-toc-toggle');
if (!mobileTocBtn) {
mobileTocBtn = document.createElement('button');
mobileTocBtn.id = 'mobile-toc-toggle';
mobileTocBtn.type = 'button';
mobileTocBtn.textContent = 'TOC';
document.body.appendChild(mobileTocBtn);
}
let mobilePinnedBtn = document.getElementById('mobile-pinned-toggle');
if (!mobilePinnedBtn) {
mobilePinnedBtn = document.createElement('button');
mobilePinnedBtn.id = 'mobile-pinned-toggle';
mobilePinnedBtn.type = 'button';
mobilePinnedBtn.textContent = 'Pinned';
document.body.appendChild(mobilePinnedBtn);
}
function anyMobilePanelOpen() {
return toc.classList.contains('mobile-visible') ||
pinnedPanel.classList.contains('mobile-visible');
}
function updateBodyMobilePanelState() {
if (anyMobilePanelOpen()) body.classList.add('mobile-panel-open');
else body.classList.remove('mobile-panel-open');
}
document.addEventListener('click', function(e) {
if (window.innerWidth > 1000) return;
if (!anyMobilePanelOpen()) return;
const clickedInsideToc = toc.contains(e.target);
const clickedInsidePinned = pinnedPanel.contains(e.target);
const clickedTocBtn = mobileTocBtn.contains(e.target);
const clickedPinnedBtn = mobilePinnedBtn.contains(e.target);
const clickedInteractive =
e.target.tagName === 'A' ||
e.target.tagName === 'BUTTON' ||
e.target.tagName === 'INPUT' ||
e.target.tagName === 'TEXTAREA' ||
e.target.closest('a') ||
e.target.closest('button');
if (!clickedInsideToc && !clickedInsidePinned && !clickedTocBtn && !clickedPinnedBtn && !clickedInteractive) {
toc.classList.remove('mobile-visible');
pinnedPanel.classList.remove('mobile-visible');
updateBodyMobilePanelState();
}
});
mobileTocBtn.addEventListener('click', function() {
const isOpen = toc.classList.toggle('mobile-visible');
if (isOpen) {
pinnedPanel.classList.remove('mobile-visible');
}
updateBodyMobilePanelState();
});
mobilePinnedBtn.addEventListener('click', function() {
const isOpen = pinnedPanel.classList.toggle('mobile-visible');
if (isOpen) {
toc.classList.remove('mobile-visible');
}
updateBodyMobilePanelState();
});
const pinnedItems = new Map();
let initiallyPinnedHrefs = new Set();
function loadFromStorage() {
try {
const raw = window.localStorage && localStorage.getItem(STORAGE_KEY);
if (!raw) return;
const arr = JSON.parse(raw);
if (!Array.isArray(arr)) return;
initiallyPinnedHrefs = new Set(arr);
} catch (e) {
console.warn('Pinned: failed to load from localStorage', e);
}
}
function saveToStorage() {
try {
if (!window.localStorage) return;
const arr = [];
pinnedItems.forEach((entry, href) => {
if (entry.li) arr.push(href);
});
localStorage.setItem(STORAGE_KEY, JSON.stringify(arr));
} catch (e) {
console.warn('Pinned: failed to save to localStorage', e);
}
}
function sortPinnedList() {
const items = Array.from(pinnedList.children)
.map(li => {
const link = li.querySelector('a');
return {
li: li,
text: link ? link.textContent.trim()
.toLowerCase() : ''
};
});
items.sort((a, b) => a.text.localeCompare(b.text));
items.forEach(item => pinnedList.appendChild(item.li));
}
function hidePinnedPanel() {
pinnedPanel.classList.add('hidden');
content.classList.add('pinned-hidden');
showBtn.classList.add('visible');
}
function showPinnedPanel() {
pinnedPanel.classList.remove('hidden');
content.classList.remove('pinned-hidden');
showBtn.classList.remove('visible');
}
toggleBtn.addEventListener('click', hidePinnedPanel);
showBtn.addEventListener('click', showPinnedPanel);
clearAllBtn.addEventListener('click', function() {
if (pinnedItems.size === 0) return;
const confirmed = confirm('Are you sure you want to clear all pinned items?');
if (!confirmed) return;
pinnedItems.forEach((entry, href) => {
if (entry.li && entry.li.parentElement) {
entry.li.parentElement.removeChild(entry.li);
}
entry.li = null;
entry.btns.forEach(b => b.textContent = '[pin]');
});
saveToStorage();
});
function attachPinBehavior(pinBtn, href, text) {
if (!href) return;
if (!pinnedItems.has(href)) {
pinnedItems.set(href, {
li: null,
btns: new Set(),
text: text
});
}
const entry = pinnedItems.get(href);
entry.btns.add(pinBtn);
pinBtn.textContent = entry.li ? '[unpin]' : '[pin]';
pinBtn.addEventListener('click', function(e) {
e.preventDefault();
e.stopPropagation();
const current = pinnedItems.get(href);
if (!current) return;
if (current.li) {
if (current.li.parentElement) {
current.li.parentElement.removeChild(current.li);
}
current.li = null;
current.btns.forEach(b => b.textContent = '[pin]');
saveToStorage();
} else {
const li = document.createElement('li');
const a = document.createElement('a');
a.href = href;
a.textContent = current.text;
const removeBtn = document.createElement('button');
removeBtn.className = 'pin-remove';
removeBtn.type = 'button';
removeBtn.textContent = '✕';
removeBtn.addEventListener('click', () => {
const cur = pinnedItems.get(href);
if (!cur) return;
if (cur.li && cur.li.parentElement) {
cur.li.parentElement.removeChild(cur.li);
}
cur.li = null;
cur.btns.forEach(b => b.textContent = '[pin]');
saveToStorage();
});
li.appendChild(a);
li.appendChild(removeBtn);
pinnedList.appendChild(li);
current.li = li;
current.btns.forEach(b => b.textContent = '[unpin]');
sortPinnedList();
saveToStorage();
}
});
}
loadFromStorage();
const tocLinks = document.querySelectorAll('#text-table-of-contents a');
tocLinks.forEach(link => {
if (link.parentElement && link.parentElement.classList.contains('toc-entry')) {
return;
}
const li = link.closest('li');
if (!li) return;
const wrapper = document.createElement('span');
wrapper.className = 'toc-entry';
li.insertBefore(wrapper, link);
wrapper.appendChild(link);
const pinBtn = document.createElement('button');
pinBtn.className = 'toc-pin-btn';
pinBtn.type = 'button';
pinBtn.textContent = '[pin]';
wrapper.appendChild(pinBtn);
const href = link.getAttribute('href');
const text = link.textContent.trim();
attachPinBehavior(pinBtn, href, text);
});
const headers = content.querySelectorAll('h2, h3, h4, h5, h6, h7, h8, h9');
headers.forEach(header => {
const id = header.getAttribute('id');
if (!id) return;
if (header.querySelector('.toc-pin-btn')) return;
const href = '#' + id;
const text = header.textContent.trim();
const pinBtn = document.createElement('button');
pinBtn.className = 'toc-pin-btn';
pinBtn.type = 'button';
pinBtn.textContent = '[pin]';
pinBtn.style.marginLeft = '0.8rem';
pinBtn.style.fontSize = '0.75em';
header.appendChild(pinBtn);
attachPinBehavior(pinBtn, href, text);
});
initiallyPinnedHrefs.forEach(href => {
const entry = pinnedItems.get(href);
if (!entry) return;
const li = document.createElement('li');
const a = document.createElement('a');
a.href = href;
a.textContent = entry.text;
const removeBtn = document.createElement('button');
removeBtn.className = 'pin-remove';
removeBtn.type = 'button';
removeBtn.textContent = '✕';
removeBtn.addEventListener('click', () => {
const cur = pinnedItems.get(href);
if (!cur) return;
if (cur.li && cur.li.parentElement) {
cur.li.parentElement.removeChild(cur.li);
}
cur.li = null;
cur.btns.forEach(b => b.textContent = '[pin]');
saveToStorage();
});
li.appendChild(a);
li.appendChild(removeBtn);
pinnedList.appendChild(li);
entry.li = li;
entry.btns.forEach(b => b.textContent = '[unpin]');
});
sortPinnedList();
saveToStorage();
});
})();
8. Appendix B: Supplementary Files
This section now holds some of the configuration files that cannot be defined directly within NixOS configuration. These files are usually symlinked using home.file.
8.1. Doc Page style.css
This is the stylesheet used by the HTML version of this document. Mostly this holds logic for hiding/showing the pin icons and resizing the page dynamically.
html, body {
margin: 0;
padding: 0;
background-color: #1d252c;
color: #b7c5d3;
font-family: "Inter", "Fira Sans", system-ui, sans-serif;
line-height: 1.6;
overflow-x: hidden;
}
body {
display: flex;
}
#table-of-contents {
position: fixed;
top: 0;
left: 0;
width: 280px;
height: 100vh;
overflow-y: auto;
padding: 1.2rem 1rem;
background-color: #232b32;
border-right: 1px solid #2f3b45;
font-size: 0.9rem;
display: flex;
flex-direction: column;
}
#table-of-contents h2 {
display: none;
}
#toc-search-container {
margin-bottom: 1rem;
position: sticky;
top: 0;
background-color: #232b32;
z-index: 10;
padding-bottom: 0.5rem;
display: flex;
align-items: center;
gap: 0.5rem;
}
#toc-search-input {
flex: 1;
padding: 0.5rem;
background-color: #1d252c;
border: 1px solid #2f3b45;
color: #b7c5d3;
border-radius: 4px;
font-size: 0.9rem;
box-sizing: border-box;
}
#toc-search-input:focus {
outline: none;
border-color: #5ec4ff;
}
#toc-search-clear {
padding: 0.5rem 0.7rem;
background-color: #2f3b45;
border: 1px solid #3a4a56;
color: #b7c5d3;
cursor: pointer;
font-size: 0.85rem;
border-radius: 4px;
transition: background-color 0.2s, color 0.2s;
white-space: nowrap;
}
#toc-search-clear:hover {
background-color: #3a4a56;
color: #ff6b6b;
}
.hidden-by-search {
display: none !important;
}
#text-table-of-contents {
flex: 1;
}
#text-table-of-contents ul {
list-style: none;
padding-left: 0;
}
#text-table-of-contents li {
margin: 0.2rem 0;
position: relative;
}
.toc-entry {
display: inline-flex;
align-items: center;
}
#text-table-of-contents a {
color: #b7c5d3;
text-decoration: none;
}
#text-table-of-contents a:hover {
color: #5ec4ff;
}
#text-table-of-contents ul ul {
padding-left: 1rem;
border-left: 1px solid #2f3b45;
}
#content {
margin-left: 300px;
margin-right: 320px;
padding: 2rem 3rem;
max-width: 1200px;
width: calc(100vw - 620px);
box-sizing: border-box;
transition: margin 0.3s ease, padding 0.3s ease,
width 0.3s ease, max-width 0.3s ease;
}
#content.pinned-hidden {
margin-right: 0;
width: calc(100vw - 300px);
}
h1, h2, h3, h4, h5, h6, h7, h8, h9 {
color: #70e1e8;
font-weight: 500;
margin-top: 2.2rem;
}
h1 { font-size: 2rem; }
h2 { font-size: 1.6rem; }
h3 { font-size: 1.3rem; }
h4 { font-size: 1.2rem; }
h5 { font-size: 1.1rem; }
h6 { font-size: 1.0rem; }
h7 { font-size: 0.95rem; }
h8 { font-size: 0.925rem; }
h9 { font-size: 0.9rem; }
a {
color: #5ec4ff;
}
a:hover {
text-decoration: underline;
}
pre, code {
font-family: "Fira Code", monospace;
background-color: #232b32;
color: #b7c5d3;
}
pre {
padding: 1rem;
overflow-x: auto;
border: 1px solid #2f3b45;
border-radius: 4px;
max-width: 100%;
box-sizing: border-box;
}
code {
padding: 0.15rem 0.3rem;
border-radius: 3px;
}
table {
border-collapse: collapse;
max-width: 100%;
}
th, td {
border: 1px solid #2f3b45;
padding: 0.5rem 0.8rem;
}
th {
background-color: #232b32;
color: #70e1e8;
}
blockquote {
border-left: 3px solid #5ec4ff;
margin-left: 0;
padding-left: 1rem;
color: #718ca1;
}
#pinned-panel {
position: fixed;
top: 0;
right: 0;
width: 280px;
height: 100vh;
overflow-y: auto;
padding: 1.2rem 1rem;
padding-bottom: 5rem;
background-color: #232b32;
border-left: 1px solid #2f3b45;
font-size: 0.9rem;
box-sizing: border-box;
transition: transform 0.3s ease;
}
#pinned-panel.hidden {
transform: translateX(100%);
}
#pinned-panel-header {
display: flex;
justify-content: space-between;
align-items: center;
}
#pinned-panel h2 {
margin: 0;
font-size: 1rem;
color: #70e1e8;
font-weight: 500;
}
#toggle-pinned-btn {
background: none;
border: none;
color: #718ca1;
cursor: pointer;
font-size: 1.2rem;
padding: 0;
line-height: 1;
}
#toggle-pinned-btn:hover {
color: #5ec4ff;
}
#pinned-list {
list-style: none;
padding-left: 0;
}
#pinned-list li {
margin: 0.5rem 0;
display: flex;
justify-content: space-between;
align-items: center;
}
#pinned-list a {
color: #b7c5d3;
text-decoration: none;
flex: 1;
}
#pinned-list a:hover {
color: #5ec4ff;
}
.pin-remove {
background: none;
border: none;
color: #718ca1;
cursor: pointer;
font-size: 0.9rem;
padding: 0 0.3rem;
}
.pin-remove:hover {
color: #ff6b6b;
}
.toc-pin-btn {
opacity: 0;
visibility: hidden;
transition: opacity 0.2s, visibility 0.2s;
cursor: pointer;
margin-left: 0.4rem;
font-size: 0.85rem;
color: #718ca1;
background: none;
border: none;
padding: 0;
}
.toc-pin-btn:hover {
color: #5ec4ff;
}
#text-table-of-contents .toc-entry:hover .toc-pin-btn {
opacity: 1;
visibility: visible;
}
#show-pinned-btn {
position: fixed;
top: 4.5rem;
right: 1rem;
background-color: #232b32;
border: 1px solid #2f3b45;
color: #b7c5d3;
cursor: pointer;
padding: 0.5rem 0.8rem;
font-size: 0.9rem;
border-radius: 4px;
display: none;
z-index: 1000;
}
#show-pinned-btn:hover {
background-color: #2f3b45;
color: #5ec4ff;
}
#show-pinned-btn.visible {
display: block;
}
#mobile-toc-toggle,
#mobile-pinned-toggle {
position: fixed;
top: 1rem;
z-index: 1100;
padding: 0.5rem 0.8rem;
border-radius: 4px;
border: 1px solid #2f3b45;
background-color: #232b32;
color: #b7c5d3;
font-size: 0.8rem;
cursor: pointer;
display: none;
}
#mobile-toc-toggle {
left: 1rem;
}
#mobile-pinned-toggle {
right: 1rem;
}
#mobile-toc-toggle:hover,
#mobile-pinned-toggle:hover {
background-color: #2f3b45;
color: #5ec4ff;
}
.heading-next {
opacity: 0;
visibility: hidden;
transition: opacity 0.2s, visibility 0.2s;
margin-left: 0.5rem;
color: #718ca1;
text-decoration: none;
font-size: 0.8em;
vertical-align: middle;
cursor: pointer;
background: none;
border: none;
padding: 0;
}
.heading-next:hover {
color: #5ec4ff;
text-decoration: none;
}
h1:hover .heading-next,
h2:hover .heading-next,
h3:hover .heading-next,
h4:hover .heading-next,
h5:hover .heading-next,
h6:hover .heading-next,
h7:hover .heading-next,
h8:hover .heading-next,
h9:hover .heading-next {
opacity: 1;
visibility: visible;
}
.heading-skip {
opacity: 0;
visibility: hidden;
transition: opacity 0.2s, visibility 0.2s;
margin-left: 0.5rem;
color: #718ca1;
text-decoration: none;
font-size: 0.8em;
vertical-align: middle;
cursor: pointer;
background: none;
border: none;
padding: 0;
}
.heading-skip:hover {
color: #5ec4ff;
text-decoration: none;
}
h1:hover .heading-skip,
h2:hover .heading-skip,
h3:hover .heading-skip,
h4:hover .heading-skip,
h5:hover .heading-skip,
h6:hover .heading-skip,
h7:hover .heading-skip,
h8:hover .heading-skip,
h9:hover .heading-skip {
opacity: 1;
visibility: visible;
}
.heading-skip-up {
opacity: 0;
visibility: hidden;
transition: opacity 0.2s, visibility 0.2s;
margin-left: 0.5rem;
color: #718ca1;
text-decoration: none;
font-size: 0.8em;
vertical-align: middle;
cursor: pointer;
background: none;
border: none;
padding: 0;
}
.heading-skip-up:hover {
color: #5ec4ff;
text-decoration: none;
}
h1:hover .heading-skip-up,
h2:hover .heading-skip-up,
h3:hover .heading-skip-up,
h4:hover .heading-skip-up,
h5:hover .heading-skip-up,
h6:hover .heading-skip-up,
h7:hover .heading-skip-up,
h8:hover .heading-skip-up,
h9:hover .heading-skip-up {
opacity: 1;
visibility: visible;
}
@media (max-width: 1600px) {
#content {
max-width: 100%;
}
}
@media (max-width: 1300px) {
#mobile-pinned-toggle {
display: block;
}
#pinned-panel {
display: block !important;
position: fixed;
top: 0;
right: 0;
width: 260px;
max-width: 80vw;
height: 100vh;
overflow-y: auto;
transform: translateX(100%);
transition: transform 0.25s ease;
z-index: 1000;
}
#pinned-panel.mobile-visible {
transform: translateX(0);
}
#show-pinned-btn {
display: none !important;
}
#content,
#content.pinned-hidden {
margin-right: 0;
width: calc(100vw - 300px);
max-width: 100%;
padding: 1.8rem 2.2rem;
}
}
@media (max-width: 1000px) {
#mobile-toc-toggle,
#mobile-pinned-toggle {
display: block;
}
#table-of-contents {
display: block;
position: fixed;
top: 0;
left: 0;
width: 260px;
max-width: 80vw;
height: 100vh;
overflow-y: auto;
transform: translateX(-100%);
transition: transform 0.25s ease;
z-index: 1000;
}
#table-of-contents.mobile-visible {
transform: translateX(0);
}
#pinned-panel {
display: block !important;
position: fixed;
top: 0;
right: 0;
width: 260px;
max-width: 80vw;
height: 100vh;
overflow-y: auto;
transform: translateX(100%);
transition: transform 0.25s ease;
z-index: 1000;
}
#pinned-panel.mobile-visible {
transform: translateX(0);
}
#content,
#content.pinned-hidden {
margin-left: 0;
margin-right: 0;
width: 100vw;
max-width: 100%;
padding: 1.5rem 1.25rem;
}
#toc-search-container {
top: 3rem;
margin-top: 2.5rem;
}
}
.heading-link {
opacity: 0;
visibility: hidden;
transition: opacity 0.2s, visibility 0.2s;
margin-left: 0.5rem;
color: #718ca1;
text-decoration: none;
font-size: 0.8em;
vertical-align: middle;
}
.heading-link:hover {
color: #5ec4ff;
text-decoration: none;
}
h1:hover .heading-link,
h2:hover .heading-link,
h3:hover .heading-link,
h4:hover .heading-link,
h5:hover .heading-link,
h6:hover .heading-link,
h7:hover .heading-link,
h8:hover .heading-link,
h9:hover .heading-link {
opacity: 1;
visibility: visible;
}
@media (max-width: 700px) {
#content {
padding: 1.2rem 1rem;
}
}
.darkmode-layer,
.darkmode-toggle {
z-index: 500;
}
html,
body {
overflow-x: hidden;
}
h1 .toc-pin-btn,
h2 .toc-pin-btn,
h3 .toc-pin-btn,
h4 .toc-pin-btn,
h5 .toc-pin-btn,
h6 .toc-pin-btn,
h7 .toc-pin-btn,
h8 .toc-pin-btn,
h9 .toc-pin-btn {
opacity: 0;
visibility: hidden;
transition: opacity 0.2s, visibility 0.2s;
}
h1:hover .toc-pin-btn,
h2:hover .toc-pin-btn,
h3:hover .toc-pin-btn,
h4:hover .toc-pin-btn,
h5:hover .toc-pin-btn,
h6:hover .toc-pin-btn,
h7:hover .toc-pin-btn,
h8:hover .toc-pin-btn,
h9:hover .toc-pin-btn {
opacity: 1;
visibility: visible;
}
#clear-all-pins-btn {
width: 100%;
margin: 0.5rem 0;
padding: 0.4rem 0.6rem;
background-color: #2f3b45;
border: 1px solid #3a4a56;
color: #b7c5d3;
cursor: pointer;
font-size: 0.85rem;
border-radius: 4px;
transition: background-color 0.2s, color 0.2s;
}
#clear-all-pins-btn:hover {
background-color: #3a4a56;
color: #ff6b6b;
}
@media (max-width: 1000px) {
body.mobile-panel-open {
overflow: hidden;
}
}
8.2. justfile
This file defines a few workflows that I often need to run when working on my configuration. This works similar to make, but is geared towards general tasks and as such requires no extra handling (as long as there are no dependencies involved) or .PHONY recipes.
(In the org-src block I still call it a Makefile in order to get syntax highlighting)
sops_files := "git grep -lz --untracked 'ENC\\[AES256_GCM' -- ':!secrets/rekeyed'"
default:
@just --list
check:
nix flake check --keep-going
follows-check *ARGS:
follow-nix {{ARGS}}
iso CONFIG="live-iso":
rm -rf result
nix build --print-out-paths .#{{CONFIG}}
bootstrap-test:
nix develop .#deploy --command nix run .#bootstrap-install-test
sandbox:
sudo install -d -m 0700 -o "$USER" /run/sandbox-tls
sudo install -m 0400 -o "$USER" /run/secrets/sandbox-wildcard-key /run/sandbox-tls/wildcard.key
sudo systemd-run --collect --pty --same-dir --wait --uid="$USER" \
-p AmbientCapabilities=CAP_NET_BIND_SERVICE \
"$(nix build --no-link --print-out-paths .#nixosConfigurations.vacanthouse.config.system.build.vm)/bin/run-vacanthouse-vm"
sandbox-test:
nix build -L --no-link .#sandbox-test
sync:
nix run .#swarsel-sync-org
topology:
nix run .#swarsel-topology
flake:
nix run .#write-flake
iso-install DRIVE: iso
sudo dd if=$(eza --sort changed result/iso/*.iso | tail -n1) of={{DRIVE}} bs=4M status=progress oflag=sync
bootstrap DEST CONFIG *ARGS:
nix develop .#deploy --command zsh -c "SSH_AUTH_SOCK=\$(gpgconf --list-dirs agent-ssh-socket) swarsel-bootstrap {{ARGS}} {{CONFIG}} {{DEST}}"
rekey *ARGS:
{{sops_files}} | xargs -0 -n1 sops updatekeys --yes
nix run --builders '' .#sops-rekey -- --add-to-git rekey {{ARGS}}
nix run --inputs-from . piix#pii -- lock
secret-set PATH:
#!/usr/bin/env bash
set -euo pipefail
value=$(cat)
sops set secrets/root.yaml '{{ '["' + replace(PATH, "/", '"]["') + '"]' }}' "$(printf '%s' "$value" | jq -Rs .)"
git add secrets/root.yaml
secret-get PATH:
sops decrypt --extract '{{ '["' + replace(PATH, "/", '"]["') + '"]' }}' secrets/root.yaml
secret-edit FILE="":
#!/usr/bin/env bash
set -euo pipefail
file="{{FILE}}"
if [ -z "$file" ]; then
file=$({{sops_files}} | tr '\0' '\n' | fzf)
fi
sops "$file"
if [[ $file == *.nix.enc ]]; then
nix run --inputs-from . piix#pii -- lock
fi
free-id:
nix eval .#nodes --apply ' \
nodes: \
let \
ids = node: \
map (user: user.uid) (builtins.attrValues node.config.users.users) \
++ map (group: group.gid) (builtins.attrValues node.config.users.groups) \
++ builtins.concatMap (persistent: [ persistent.uid persistent.gid ]) (builtins.attrValues node.config.users.persistentIds); \
used = builtins.concatMap ids (builtins.filter (node: node.class == "nixos") (builtins.attrValues nodes)); \
free = id: if builtins.elem id used then free (id - 1) else id; \
in \
free 999'
droid HOST="magicant":
#!/usr/bin/env bash
set -euo pipefail
path=$(nix build --impure --no-link --print-out-paths \
--option extra-substituters https://nix-on-droid.cachix.org \
--option extra-trusted-public-keys nix-on-droid.cachix.org-1:56snoMJTXmDRC1Ei24CmKoUqvHJ9XCp+nidK7qkMQrU= \
.#nixOnDroidConfigurations.{{HOST}}.activationPackage)
nix copy --to ssh://belchsfactory "$path"
ssh belchsfactory nix-env --profile /nix/var/nix/profiles/droid-{{HOST}} --set "$path"
pii *ARGS:
nix run --inputs-from . piix#pii -- {{ARGS}}
8.3. Matrix IRC Patch to allow on-connect commands
diff -ruN irc-a/config.schema.yml irc-b/config.schema.yml
--- a/config.schema.yml
+++ b/config.schema.yml
@@ -243,6 +243,10 @@
type: "boolean"
allowExpiredCerts:
type: "boolean"
+ onConnectCommands:
+ type: "array"
+ items:
+ type: "string"
password:
type: "string"
sendConnectionMessages:
diff -ruN irc-a/src/irc/BridgedClient.ts irc-b/src/irc/BridgedClient.ts
--- a/src/irc/BridgedClient.ts
+++ b/src/irc/BridgedClient.ts
@@ -290,6 +290,14 @@
this.eventBroker.sendMetadata(this, connectText);
+ for (const command of this.isBot ? [] : this.server.getOnConnectCommands()) {
+ const trailingIndex = command.indexOf(" :");
+ const args = trailingIndex === -1
+ ? command.split(" ")
+ : [...command.slice(0, trailingIndex).split(" "), command.slice(trailingIndex + 2)];
+ connInst.client.send(...args);
+ }
+
connInst.client.on("nick", (old, newNick) => {
if (old === this.nick) {
this.log.info(
diff -ruN irc-a/src/irc/IrcServer.ts irc-b/src/irc/IrcServer.ts
--- a/src/irc/IrcServer.ts
+++ b/src/irc/IrcServer.ts
@@ -36,6 +36,7 @@
sasl?: boolean;
tlsOptions?: Record<string, unknown>;
password?: string;
+ onConnectCommands?: string[];
allowExpiredCerts?: boolean;
additionalAddresses?: string[];
onlyAdditionalAddresses: boolean;
@@ -342,6 +343,10 @@
return Boolean(this.config.allowExpiredCerts);
}
+ public getOnConnectCommands(): string[] {
+ return this.config.onConnectCommands || [];
+ }
+
public getIdleTimeout() {
return this.config.ircClients.idleTimeout;
}
8.4. Matrix IRC Patch to open rooms on bot DMs in v12 matrix rooms
diff -ruN irc-a/src/bridge/IrcHandler.ts irc-b/src/bridge/IrcHandler.ts
--- a/src/bridge/IrcHandler.ts
+++ b/src/bridge/IrcHandler.ts
@@ -17,7 +17,6 @@
import { PrivacyProtection } from "../irc/PrivacyProtection";
const NICK_USERID_CACHE_MAX = 512;
const PM_POWERLEVEL_MATRIXUSER = 10;
-const PM_POWERLEVEL_IRCUSER = 100;
const MEMBERSHIP_INITIAL_TTL_MS = 30 * 60 * 1000; // 30 mins
const PM_ROOM_CREATION_RETRIES = 3; // How often to retry to create a PM room, if it fails?
@@ -184,11 +183,11 @@
"m.federate": server.shouldFederatePMs()
},
is_direct: true,
+ room_version: "12",
initial_state: [{
content: {
users: {
[toUserId]: PM_POWERLEVEL_MATRIXUSER,
- [fromUserId]: PM_POWERLEVEL_IRCUSER,
},
events: {
"m.room.avatar": 10,
8.5. Matrix IRC Patch to not reply to all DMs received by the bot
diff -ruN irc-a/src/provisioning/Provisioner.ts irc-b/src/provisioning/Provisioner.ts
--- a/src/provisioning/Provisioner.ts
+++ b/src/provisioning/Provisioner.ts
@@ -608,6 +608,11 @@
}
public async handlePm (server: IrcServer, fromUser: IrcUser, text: string) {
+ const request = this.getRequest(server, fromUser.nick);
+ if (!request) {
+ log.warn(`Provisioner was not expecting PM from ${fromUser.nick} on ${server.domain}`);
+ return;
+ }
if (!['y', 'yes'].includes(text.trim().toLowerCase())) {
log.warn(`Provisioner only handles text 'yes'/'y' ` +
`(from ${fromUser.nick} on ${server.domain})`);
@@ -618,22 +623,12 @@
);
return;
}
- const request = this.getRequest(server, fromUser.nick);
- if (request) {
- request.log.info(`${fromUser.nick} has authorised a new provisioning`);
- request.defer.resolve();
-
- await this.sendToUser(
- fromUser.nick, server,
- 'Thanks for your response, bridge request authorised.'
- );
+ request.log.info(`${fromUser.nick} has authorised a new provisioning`);
+ request.defer.resolve();
- return;
- }
- log.warn(`Provisioner was not expecting PM from ${fromUser.nick} on ${server.domain}`);
await this.sendToUser(
fromUser.nick, server,
- 'The bot was not expecting a message from you. You might have already replied to a request.'
+ 'Thanks for your response, bridge request authorised.'
);
}
8.6. Niri patch to support hidden workspaces
diff --git a/docs/wiki/Getting-Started.md b/docs/wiki/Getting-Started.md
index 2dd697dc..3dd75e30 100644
--- a/docs/wiki/Getting-Started.md
+++ b/docs/wiki/Getting-Started.md
@@ -33,7 +33,7 @@ Check the DankMaterialShell's [compositor setup page](https://danklinux.com/docs
## Slower and more considered start
The easiest way to get niri is to install one of the distribution packages.
-Here are some of them: [Fedora COPR](https://copr.fedorainfracloud.org/coprs/yalter/niri/) and [nightly COPR](https://copr.fedorainfracloud.org/coprs/yalter/niri-git/) (which I maintain myself), [NixOS Flake](https://github.com/sodiboo/niri-flake), and some more from repology below, including a [pacstall package](https://pacstall.dev/packages/niri/) for Debian-based distros.
+Here are some of them: [Fedora COPR](https://copr.fedorainfracloud.org/coprs/niri-wm/niri/) and [nightly COPR](https://copr.fedorainfracloud.org/coprs/niri-wm/niri-git/) (which I maintain myself), [NixOS Flake](https://github.com/sodiboo/niri-flake), and some more from repology below, including a [pacstall package](https://pacstall.dev/packages/niri/) for Debian-based distros.
See the [Building](#building) section if you'd like to compile niri yourself and the [Packaging niri](./Packaging-niri.md) page if you want to package niri.
[](https://repology.org/project/niri/versions)
diff --git a/niri-config/src/binds.rs b/niri-config/src/binds.rs
index 0be7596f..488a5715 100644
--- a/niri-config/src/binds.rs
+++ b/niri-config/src/binds.rs
@@ -325,6 +325,7 @@ pub enum Action {
ExpandColumnToAvailableWidth,
SwitchLayout(#[knuffel(argument, str)] LayoutSwitchTarget),
ShowHotkeyOverlay,
+ ToggleWorkspaceVisibility(#[knuffel(argument, str)] String),
MoveWorkspaceToMonitorLeft,
MoveWorkspaceToMonitorRight,
MoveWorkspaceToMonitorDown,
diff --git a/niri-config/src/lib.rs b/niri-config/src/lib.rs
index 329b7669..38e47825 100644
--- a/niri-config/src/lib.rs
+++ b/niri-config/src/lib.rs
@@ -2271,6 +2271,7 @@ mod tests {
open_on_output: Some(
"eDP-1",
),
+ hidden: None,
layout: None,
},
Workspace {
@@ -2278,6 +2279,7 @@ mod tests {
"workspace-2",
),
open_on_output: None,
+ hidden: None,
layout: None,
},
Workspace {
@@ -2285,6 +2287,7 @@ mod tests {
"workspace-3",
),
open_on_output: None,
+ hidden: None,
layout: None,
},
],
diff --git a/niri-config/src/workspace.rs b/niri-config/src/workspace.rs
index d34dcf46..21bc3ce6 100644
--- a/niri-config/src/workspace.rs
+++ b/niri-config/src/workspace.rs
@@ -8,6 +8,8 @@ pub struct Workspace {
pub name: WorkspaceName,
#[knuffel(child, unwrap(argument))]
pub open_on_output: Option<String>,
+ #[knuffel(child, unwrap(argument))]
+ pub hidden: Option<bool>,
#[knuffel(child)]
pub layout: Option<WorkspaceLayoutPart>,
}
diff --git a/niri-ipc/src/lib.rs b/niri-ipc/src/lib.rs
index 0aa3cb4f..f8ad9f7d 100644
--- a/niri-ipc/src/lib.rs
+++ b/niri-ipc/src/lib.rs
@@ -71,6 +71,8 @@ pub enum Request {
Outputs,
/// Request information about workspaces.
Workspaces,
+ /// Request information for workspaces, including hidden.
+ WorkspacesWithHidden,
/// Request information about open windows.
Windows,
/// Request information about layer-shell surfaces.
@@ -1441,6 +1443,8 @@ pub struct Workspace {
pub is_focused: bool,
/// Id of the active window on this workspace, if any.
pub active_window_id: Option<u64>,
+ /// Is this workspace hidden
+ pub is_hidden: bool,
}
/// Configured keyboard layouts.
diff --git a/niri-visual-tests/src/cases/layout.rs b/niri-visual-tests/src/cases/layout.rs
index 81a936d1..16da354e 100644
--- a/niri-visual-tests/src/cases/layout.rs
+++ b/niri-visual-tests/src/cases/layout.rs
@@ -182,6 +182,7 @@ impl Layout {
false,
false,
ActivateWindow::default(),
+ false,
);
self.windows.push(window);
}
@@ -211,6 +212,7 @@ impl Layout {
false,
false,
ActivateWindow::default(),
+ false,
);
self.windows.push(window);
}
diff --git a/src/cli.rs b/src/cli.rs
index 308b3127..8a569b12 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -65,6 +65,8 @@ pub enum Msg {
Outputs,
/// List workspaces.
Workspaces,
+ /// List all workspaces, including hidden
+ WorkspacesWithHidden,
/// List open windows.
Windows,
/// List open layer-shell surfaces.
diff --git a/src/handlers/compositor.rs b/src/handlers/compositor.rs
index f38b2934..17a0ab7f 100644
--- a/src/handlers/compositor.rs
+++ b/src/handlers/compositor.rs
@@ -211,6 +211,17 @@ impl CompositorHandler for State {
} else {
AddWindowTarget::Auto
};
+
+ // Check if the window rule has a hidden workspace it's being mapped to
+ // If it does, we should not activate it.
+ let target_workspace_name = mapped.rules().open_on_workspace.clone();
+ let target_is_hidden = target_workspace_name.is_some_and(|name| {
+ self.niri
+ .layout
+ .find_workspace_by_name(&name)
+ .is_some_and(|(_, workspace)| workspace.hidden)
+ });
+
let output = self.niri.layout.add_window(
mapped,
target,
@@ -218,7 +229,12 @@ impl CompositorHandler for State {
height,
is_full_width,
is_floating,
- activate,
+ if target_is_hidden {
+ ActivateWindow::No
+ } else {
+ activate
+ },
+ false,
);
let output = output.cloned();
diff --git a/src/handlers/mod.rs b/src/handlers/mod.rs
index 3532078b..e7f0ec33 100644
--- a/src/handlers/mod.rs
+++ b/src/handlers/mod.rs
@@ -614,7 +614,7 @@ impl ExtWorkspaceHandler for State {
if let Some(output) = output {
self.niri.layout.focus_output(&output);
}
- self.niri.layout.switch_workspace(index);
+ self.niri.layout.switch_workspace(index, false);
// No mouse warp: assuming the layer-shell bar workspaces use-case.
// FIXME: granular
diff --git a/src/input/mod.rs b/src/input/mod.rs
index f1ad4932..1a13a4c0 100644
--- a/src/input/mod.rs
+++ b/src/input/mod.rs
@@ -8,6 +8,7 @@ use calloop::timer::{TimeoutAction, Timer};
use input::event::gesture::GestureEventCoordinates as _;
use niri_config::{
Action, Bind, Binds, Config, Key, ModKey, Modifiers, MruDirection, SwitchBinds, Trigger,
+ WorkspaceReference, Xkb,
};
use niri_ipc::LayoutSwitchTarget;
use smithay::backend::input::{
@@ -1457,6 +1458,7 @@ impl State {
}
}
Action::FocusWorkspace(reference) => {
+ let is_name = matches!(reference, WorkspaceReference::Name(_));
if let Some((mut output, index)) =
self.niri.find_output_and_workspace_index(reference)
{
@@ -1468,7 +1470,7 @@ impl State {
if let Some(output) = output {
self.niri.layout.focus_output(&output);
- self.niri.layout.switch_workspace(index);
+ self.niri.layout.switch_workspace(index, is_name);
if !self.maybe_warp_cursor_to_focus_centered() {
self.move_cursor_to_output(&output);
}
@@ -1477,7 +1479,7 @@ impl State {
if config.borrow().input.workspace_auto_back_and_forth {
self.niri.layout.switch_workspace_auto_back_and_forth(index);
} else {
- self.niri.layout.switch_workspace(index);
+ self.niri.layout.switch_workspace(index, is_name);
}
self.maybe_warp_cursor_to_focus();
}
@@ -2382,6 +2384,9 @@ impl State {
self.niri.queue_redraw_mru_output();
}
}
+ Action::ToggleWorkspaceVisibility(workspace_name) => {
+ self.niri.layout.toggle_workspace_visibility(workspace_name);
+ }
}
}
diff --git a/src/ipc/client.rs b/src/ipc/client.rs
index 40a58efa..19530549 100644
--- a/src/ipc/client.rs
+++ b/src/ipc/client.rs
@@ -48,6 +48,7 @@ pub fn handle_msg(mut msg: Msg, json: bool) -> anyhow::Result<()> {
Msg::EventStream => Request::EventStream,
Msg::RequestError => Request::ReturnError,
Msg::OverviewState => Request::OverviewState,
+ Msg::WorkspacesWithHidden => Request::WorkspacesWithHidden,
Msg::Casts => Request::Casts,
};
@@ -339,6 +340,54 @@ pub fn handle_msg(mut msg: Msg, json: bool) -> anyhow::Result<()> {
println!("The change will apply when it is connected.");
}
}
+ Msg::WorkspacesWithHidden => {
+ let Response::Workspaces(mut response) = response else {
+ bail!("unexpected response: expected Workspaces, got {response:?}");
+ };
+
+ if json {
+ let response =
+ serde_json::to_string(&response).context("error formatting response")?;
+ println!("{response}");
+ return Ok(());
+ }
+
+ if response.is_empty() {
+ println!("No workspaces.");
+ return Ok(());
+ }
+
+ response.sort_by_key(|ws| ws.idx);
+ response.sort_by(|a, b| a.output.cmp(&b.output));
+
+ let mut current_output = if let Some(output) = response[0].output.as_deref() {
+ println!("Output \"{output}\":");
+ Some(output)
+ } else {
+ println!("No output:");
+ None
+ };
+
+ for ws in &response {
+ if ws.output.as_deref() != current_output {
+ let output = ws.output.as_deref().context(
+ "invalid response: workspace with no output \
+ following a workspace with an output",
+ )?;
+ current_output = Some(output);
+ println!("\nOutput \"{output}\":");
+ }
+
+ let is_active = if ws.is_active { " * " } else { " " };
+ let idx = ws.idx;
+ let name = if let Some(name) = ws.name.as_deref() {
+ format!(" \"{name}\"")
+ } else {
+ String::new()
+ };
+ println!("{is_active}{idx}{name}");
+ }
+ }
Msg::Workspaces => {
let Response::Workspaces(mut response) = response else {
bail!("unexpected response: expected Workspaces, got {response:?}");
@@ -368,6 +417,9 @@ pub fn handle_msg(mut msg: Msg, json: bool) -> anyhow::Result<()> {
};
for ws in &response {
+ if ws.is_hidden {
+ continue;
+ }
if ws.output.as_deref() != current_output {
let output = ws.output.as_deref().context(
"invalid response: workspace with no output \
diff --git a/src/ipc/server.rs b/src/ipc/server.rs
index db71da6d..97e4e681 100644
--- a/src/ipc/server.rs
+++ b/src/ipc/server.rs
@@ -278,6 +278,18 @@ async fn process(ctx: &ClientCtx, request: Request) -> Reply {
Response::Outputs(outputs.collect())
}
Request::Workspaces => {
+ let state = ctx.event_stream_state.borrow();
+ let workspaces = state
+ .workspaces
+ .workspaces
+ .values()
+ .filter(|workspace| !workspace.is_hidden)
+ .cloned()
+ .collect();
+ Response::Workspaces(workspaces)
+ }
+
+ Request::WorkspacesWithHidden => {
let state = ctx.event_stream_state.borrow();
let workspaces = state.workspaces.workspaces.values().cloned().collect();
Response::Workspaces(workspaces)
@@ -603,10 +615,22 @@ impl State {
// Check for workspace changes.
let mut seen = HashSet::new();
let mut need_workspaces_changed = false;
+ let mut last_output: Option<String> = None;
+ let mut visible_idx = 0usize;
for (mon, ws_idx, ws) in layout.workspaces() {
let id = ws.id().get();
seen.insert(id);
+ if ws.hidden {
+ continue;
+ }
+
+ let output_name = mon.map(|mon| mon.output_name().clone());
+ if last_output != output_name {
+ visible_idx = 0;
+ last_output = output_name.clone();
+ }
+
let Some(ipc_ws) = state.workspaces.get(&id) else {
// A new workspace was added.
need_workspaces_changed = true;
@@ -614,10 +638,9 @@ impl State {
};
// Check for any changes that we can't signal as individual events.
- let output_name = mon.map(|mon| mon.output_name());
- if ipc_ws.idx != u8::try_from(ws_idx + 1).unwrap_or(u8::MAX)
+ if ipc_ws.idx != u8::try_from(visible_idx + 1).unwrap_or(u8::MAX)
|| ipc_ws.name.as_ref() != ws.name()
- || ipc_ws.output.as_ref() != output_name
+ || ipc_ws.output.as_ref() != output_name.as_ref()
{
need_workspaces_changed = true;
break;
@@ -641,6 +664,7 @@ impl State {
let is_focused = Some(id) == focused_ws_id;
if is_focused && !ipc_ws.is_focused {
events.push(Event::WorkspaceActivated { id, focused: true });
+ visible_idx += 1;
continue;
}
@@ -649,30 +673,52 @@ impl State {
if is_active && !ipc_ws.is_active {
events.push(Event::WorkspaceActivated { id, focused: false });
}
+
+ visible_idx += 1;
}
- // Check if any workspaces were removed.
- if !need_workspaces_changed && state.workspaces.keys().any(|id| !seen.contains(id)) {
+ // Check if any workspaces were removed that weren't also hidden.
+ if !need_workspaces_changed
+ && state.workspaces.keys().any(|id| {
+ !seen.contains(id) && state.workspaces.get(id).is_some_and(|ws| !ws.is_hidden)
+ })
+ {
need_workspaces_changed = true;
}
if need_workspaces_changed {
events.clear();
+ let mut last_output: Option<String> = None;
+ let mut visible_idx = 0usize;
let workspaces = layout
.workspaces()
- .map(|(mon, ws_idx, ws)| {
+ .filter_map(|(mon, ws_idx, ws)| {
+ if ws.hidden {
+ return None;
+ }
+
+ let output_name = mon.map(|mon| mon.output_name().clone());
+ if last_output != output_name {
+ visible_idx = 0;
+ last_output = output_name.clone();
+ }
+
let id = ws.id().get();
- Workspace {
+ let result = Workspace {
id,
- idx: u8::try_from(ws_idx + 1).unwrap_or(u8::MAX),
+ idx: u8::try_from(visible_idx + 1).unwrap_or(u8::MAX),
name: ws.name().cloned(),
- output: mon.map(|mon| mon.output_name().clone()),
+ output: output_name,
is_urgent: ws.is_urgent(),
is_active: mon.is_some_and(|mon| mon.active_workspace_idx() == ws_idx),
is_focused: Some(id) == focused_ws_id,
+ is_hidden: ws.hidden,
active_window_id: ws.active_window().map(|win| win.id().get()),
- }
+ };
+
+ visible_idx += 1;
+ Some(result)
})
.collect();
@@ -683,6 +729,26 @@ impl State {
state.apply(event.clone());
server.send_event(event);
}
+
+ for (mon, ws_idx, ws) in layout.workspaces() {
+ if !ws.hidden {
+ continue;
+ }
+ let id = ws.id().get();
+ let output_name = mon.map(|mon| mon.output_name().clone());
+ let hidden_ws = Workspace {
+ id,
+ idx: u8::try_from(ws_idx + 1).unwrap_or(u8::MAX),
+ name: ws.name().cloned(),
+ output: output_name,
+ is_urgent: ws.is_urgent(),
+ is_active: false,
+ is_focused: false,
+ is_hidden: true,
+ active_window_id: ws.active_window().map(|win| win.id().get()),
+ };
+ state.workspaces.insert(id, hidden_ws);
+ }
}
fn ipc_refresh_windows(&mut self) {
diff --git a/src/layout/mod.rs b/src/layout/mod.rs
index 5c4dd639..98ba676a 100644
--- a/src/layout/mod.rs
+++ b/src/layout/mod.rs
@@ -732,6 +732,31 @@ impl<W: LayoutElement> Layout<W> {
}
}
+ pub fn toggle_workspace_visibility(&mut self, workspace_name: String) {
+ let Some(monitor) = self.monitor_for_workspace_mut(&workspace_name) else {
+ return;
+ };
+ let Some(ws_idx) = monitor.find_named_workspace_index(&workspace_name) else {
+ return;
+ };
+
+ let is_hidden = monitor.workspaces[ws_idx].hidden;
+
+ if is_hidden {
+ let Some(ws) = monitor.find_named_workspace(&workspace_name) else {
+ return;
+ };
+ monitor.unhide_workspace_by_id(ws.id(), false);
+ // unhide_workspace_by_id clears the workspace switch when it moves
+ // the workspace, but it can also return early without doing so.
+ if monitor.workspace_switch.is_none() {
+ monitor.clean_up_workspaces();
+ }
+ } else {
+ monitor.hide_workspace_by_idx(ws_idx);
+ }
+ }
+
pub fn add_output(&mut self, output: Output, layout_config: Option<LayoutPart>) {
self.monitor_set = match mem::take(&mut self.monitor_set) {
MonitorSet::Normal {
@@ -788,9 +813,14 @@ impl<W: LayoutElement> Layout<W> {
// both will be empty and one of them needs to be removed. clean_up_workspaces
// takes care of this.
+ // A hidden block makes the two-workspace state reachable as
+ // [empty, hidden-named], which can coexist with a workspace
+ // switch in progress; clean_up_workspaces requires there to be
+ // none.
if stopped_primary_ws_switch
|| (primary.options.layout.empty_workspace_above_first
- && primary.workspaces.len() == 2)
+ && primary.workspaces.len() == 2
+ && primary.workspace_switch.is_none())
{
primary.clean_up_workspaces();
}
@@ -934,6 +964,7 @@ impl<W: LayoutElement> Layout<W> {
is_full_width: bool,
is_floating: bool,
activate: ActivateWindow,
+ force_unhide_workspace: bool,
) -> Option<&Output> {
let scrolling_height = height.map(SizeChange::from);
let id = window.id().clone();
@@ -1013,6 +1044,7 @@ impl<W: LayoutElement> Layout<W> {
scrolling_width,
is_full_width,
is_floating,
+ force_unhide_workspace,
);
if activate.map_smart(|| false) {
@@ -1170,10 +1202,12 @@ impl<W: LayoutElement> Layout<W> {
}
// Special case handling when empty_workspace_above_first is set and all
- // workspaces are empty.
+ // workspaces are empty. With a hidden workspace present
+ // ([empty, hidden-named]) there is nothing to collapse.
if mon.options.layout.empty_workspace_above_first
&& mon.workspaces.len() == 2
&& mon.workspace_switch.is_none()
+ && !mon.workspaces.iter().any(|ws| ws.hidden)
{
assert!(!mon.workspaces[0].has_windows_or_name());
assert!(!mon.workspaces[1].has_windows_or_name());
@@ -1348,6 +1382,11 @@ impl<W: LayoutElement> Layout<W> {
MonitorSet::NoOutputs { workspaces } => {
for (idx, ws) in workspaces.iter_mut().enumerate() {
if ws.id() == id {
+ // Unnaming removes the only way to unhide this workspace later
+ // (unhide/toggle-visibility both look workspaces up by name), so
+ // it must not be left hidden or pending a hide-on-switch-away.
+ ws.hidden = false;
+ ws.needs_hidden = false;
ws.unname();
// Clean up empty workspaces.
@@ -1538,7 +1577,7 @@ impl<W: LayoutElement> Layout<W> {
Some(WorkspaceSwitch::Gesture(gesture))
if gesture.current_idx.floor() == workspace_idx as f64
|| gesture.current_idx.ceil() == workspace_idx as f64 => {}
- _ => mon.switch_workspace(workspace_idx),
+ _ => mon.switch_workspace(workspace_idx, false),
}
return;
@@ -1574,7 +1613,7 @@ impl<W: LayoutElement> Layout<W> {
Some(WorkspaceSwitch::Gesture(gesture))
if gesture.current_idx.floor() == workspace_idx as f64
|| gesture.current_idx.ceil() == workspace_idx as f64 => {}
- _ => mon.switch_workspace(workspace_idx),
+ _ => mon.switch_workspace(workspace_idx, false),
}
return;
@@ -1680,7 +1719,8 @@ impl<W: LayoutElement> Layout<W> {
for mon in monitors {
for ws in &mon.workspaces {
for (tile, layout) in ws.tiles_with_ipc_layouts() {
- f(tile.window(), Some(&mon.output), Some(ws.id()), layout);
+ let output = if ws.hidden { None } else { Some(&mon.output) };
+ f(tile.window(), output, Some(ws.id()), layout);
}
}
}
@@ -1784,6 +1824,16 @@ impl<W: LayoutElement> Layout<W> {
})
}
+ pub fn monitor_for_workspace_mut(&mut self, workspace_name: &str) -> Option<&mut Monitor<W>> {
+ self.monitors_mut().find(|monitor| {
+ monitor.workspaces.iter().any(|ws| {
+ ws.name
+ .as_ref()
+ .is_some_and(|name| name.eq_ignore_ascii_case(workspace_name))
+ })
+ })
+ }
+
pub fn outputs(&self) -> impl Iterator<Item = &Output> + '_ {
self.monitors().map(|mon| &mon.output)
}
@@ -2183,11 +2233,11 @@ impl<W: LayoutElement> Layout<W> {
monitor.switch_workspace_down();
}
- pub fn switch_workspace(&mut self, idx: usize) {
+ pub fn switch_workspace(&mut self, idx: usize, force_unhide: bool) {
let Some(monitor) = self.active_monitor() else {
return;
};
- monitor.switch_workspace(idx);
+ monitor.switch_workspace(idx, force_unhide);
}
pub fn switch_workspace_auto_back_and_forth(&mut self, idx: usize) {
@@ -2935,7 +2985,11 @@ impl<W: LayoutElement> Layout<W> {
clock,
options,
);
- mon.insert_workspace(ws, 0, false);
+ if ws.hidden {
+ mon.insert_hidden_workspace(ws);
+ } else {
+ mon.insert_workspace(ws, 0, false);
+ }
}
MonitorSet::NoOutputs { workspaces } => {
let ws =
@@ -3370,6 +3424,7 @@ impl<W: LayoutElement> Layout<W> {
removed.width,
removed.is_full_width,
removed.is_floating,
+ false,
);
if activate.map_smart(|| false) {
*active_monitor_idx = new_idx;
@@ -4249,6 +4304,7 @@ impl<W: LayoutElement> Layout<W> {
move_.width,
move_.is_full_width,
false,
+ false,
);
}
InsertPosition::InColumn(column_idx, tile_idx) => {
@@ -4305,6 +4361,7 @@ impl<W: LayoutElement> Layout<W> {
move_.width,
move_.is_full_width,
true,
+ false,
);
}
}
@@ -4543,13 +4600,15 @@ impl<W: LayoutElement> Layout<W> {
// Conversely, if `ws` was the last workspace on a monitor, an
// empty workspace needs to be added after.
- if let MonitorSet::Normal {
- monitors,
- active_monitor_idx,
- ..
- } = &mut self.monitor_set
- {
- let monitor = &mut monitors[*active_monitor_idx];
+ if let MonitorSet::Normal { monitors, .. } = &mut self.monitor_set {
+ // Apply the compensation on the monitor that actually owns the
+ // workspace; it is not necessarily the active one.
+ let Some(monitor) = monitors
+ .iter_mut()
+ .find(|mon| mon.workspaces.iter().any(|ws| ws.id() == wsid))
+ else {
+ return;
+ };
if monitor.options.layout.empty_workspace_above_first
&& monitor
.workspaces
@@ -4558,11 +4617,15 @@ impl<W: LayoutElement> Layout<W> {
{
monitor.add_workspace_top();
}
- if monitor
+ // The named workspace may have been the last visible one (the trailing
+ // empty, doubling as the hidden-block guard), so restore an empty one
+ // after it.
+ let visible_end = monitor
.workspaces
- .last()
- .is_some_and(|last| last.id() == wsid)
- {
+ .iter()
+ .position(|ws| ws.hidden)
+ .unwrap_or(monitor.workspaces.len());
+ if visible_end > 0 && monitor.workspaces[visible_end - 1].id() == wsid {
monitor.add_workspace_bottom();
}
}
diff --git a/src/layout/monitor.rs b/src/layout/monitor.rs
index 53c06069..30bb8888 100644
--- a/src/layout/monitor.rs
+++ b/src/layout/monitor.rs
@@ -318,6 +318,21 @@ impl<W: LayoutElement> Monitor<W> {
}
}
+ // Hidden workspaces should always be at the end.
+ let mut hidden_workspaces = Vec::new();
+ let mut i = 0;
+ while i < workspaces.len() {
+ if workspaces[i].hidden {
+ let ws = workspaces.remove(i);
+ hidden_workspaces.push(ws);
+ if i < active_workspace_idx {
+ active_workspace_idx = active_workspace_idx.saturating_sub(1);
+ }
+ } else {
+ i += 1;
+ }
+ }
+
if options.layout.empty_workspace_above_first && !workspaces.is_empty() {
let ws = Workspace::new(output.clone(), clock.clone(), options.clone());
workspaces.insert(0, ws);
@@ -327,6 +342,9 @@ impl<W: LayoutElement> Monitor<W> {
let ws = Workspace::new(output.clone(), clock.clone(), options.clone());
workspaces.push(ws);
+ // Add hidden workspaces at the end
+ workspaces.extend(hidden_workspaces);
+
Self {
output_name: output.name(),
output,
@@ -427,7 +445,13 @@ impl<W: LayoutElement> Monitor<W> {
}
pub fn add_workspace_bottom(&mut self) {
- self.add_workspace_at(self.workspaces.len());
+ // The bottom of the visible region; hidden workspaces stay past it.
+ let visible_end = self
+ .workspaces
+ .iter()
+ .position(|ws| ws.hidden)
+ .unwrap_or(self.workspaces.len());
+ self.add_workspace_at(visible_end);
}
pub fn activate_workspace(&mut self, idx: usize) {
@@ -447,6 +471,7 @@ impl<W: LayoutElement> Monitor<W> {
}
let prev_active_idx = self.active_workspace_idx;
+
self.active_workspace_idx = idx;
let config = config.unwrap_or(self.options.animations.workspace_switch.0);
@@ -471,6 +496,19 @@ impl<W: LayoutElement> Monitor<W> {
return;
}
+ // Remove hidden if the previous active workspace was forced
+ // unhidden. This moves that workspace to the hidden block and
+ // can clean up empty workspaces, so the target index has to be
+ // resolved again afterwards.
+ let target_id = self.workspaces[idx].id();
+ self.hide_needs_hidden(prev_active_idx);
+ let idx = self
+ .workspaces
+ .iter()
+ .position(|ws| ws.id() == target_id)
+ .unwrap_or_else(|| self.active_workspace_idx.min(self.workspaces.len() - 1));
+ self.active_workspace_idx = idx;
+
self.workspace_switch = Some(WorkspaceSwitch::Animation(Animation::new(
self.clock.clone(),
current_idx,
@@ -518,6 +556,7 @@ impl<W: LayoutElement> Monitor<W> {
width: ColumnWidth,
is_full_width: bool,
is_floating: bool,
+ force_unhide_workspace: bool,
) {
// Currently, everything a workspace sets on a Tile is the same across all workspaces of a
// monitor. So we can use any workspace, not necessarily the exact target workspace.
@@ -531,10 +570,26 @@ impl<W: LayoutElement> Monitor<W> {
width,
is_full_width,
is_floating,
+ force_unhide_workspace,
);
}
pub fn add_column(&mut self, mut workspace_idx: usize, column: Column<W>, activate: bool) {
+ // A hidden workspace must never become the active one, since it isn't
+ // rendered. Unhide it first, marking it to hide again on switching away
+ // (the same force-unhide path add_tile uses).
+ if activate && self.workspaces[workspace_idx].hidden {
+ let ws_id = self.workspaces[workspace_idx].id();
+ if let Some(idx) = self.unhide_workspace_by_id(ws_id, true) {
+ workspace_idx = idx;
+ }
+ }
+
+ let first_hidden_idx = self.workspaces.iter().position(|ws| ws.hidden);
+ let is_last_visible = first_hidden_idx
+ .map(|hidden_idx| workspace_idx + 1 == hidden_idx)
+ .unwrap_or(workspace_idx == self.workspaces.len() - 1);
+
let workspace = &mut self.workspaces[workspace_idx];
workspace.add_column(column, activate);
@@ -544,9 +599,15 @@ impl<W: LayoutElement> Monitor<W> {
workspace.original_output = OutputId::new(&self.output);
}
- if workspace_idx == self.workspaces.len() - 1 {
- self.add_workspace_bottom();
+ // Insert a new empty workspace.
+ if is_last_visible {
+ if first_hidden_idx.is_some() {
+ self.ensure_empty_before_hidden();
+ } else {
+ self.add_workspace_bottom();
+ }
}
+
if self.options.layout.empty_workspace_above_first && workspace_idx == 0 {
self.add_workspace_top();
workspace_idx += 1;
@@ -568,9 +629,28 @@ impl<W: LayoutElement> Monitor<W> {
width: ColumnWidth,
is_full_width: bool,
is_floating: bool,
+ force_unhide_workspace: bool,
) {
let (mut workspace_idx, target) = self.resolve_add_window_target(target);
+ // Force-unhide the workspace if requested and it's hidden. Also unhide
+ // whenever this tile is going to activate its workspace: a hidden
+ // workspace must never become the active one, since it isn't rendered.
+ // This is the same condition used to activate below, evaluated before
+ // anything moves.
+ let will_activate = allow_to_activate_workspace && activate.map_smart(|| false);
+ if (force_unhide_workspace || will_activate) && self.workspaces[workspace_idx].hidden {
+ let ws_id = self.workspaces[workspace_idx].id();
+ if let Some(idx) = self.unhide_workspace_by_id(ws_id, true) {
+ workspace_idx = idx;
+ }
+ }
+
+ let first_hidden_idx = self.workspaces.iter().position(|ws| ws.hidden);
+ let is_last_visible = first_hidden_idx
+ .map(|hidden_idx| workspace_idx + 1 == hidden_idx)
+ .unwrap_or(workspace_idx == self.workspaces.len() - 1);
+
let workspace = &mut self.workspaces[workspace_idx];
workspace.add_tile(tile, target, activate, width, is_full_width, is_floating);
@@ -580,9 +660,12 @@ impl<W: LayoutElement> Monitor<W> {
workspace.original_output = OutputId::new(&self.output);
}
- if workspace_idx == self.workspaces.len() - 1 {
- // Insert a new empty workspace.
- self.add_workspace_bottom();
+ if is_last_visible {
+ if first_hidden_idx.is_some() {
+ self.ensure_empty_before_hidden();
+ } else {
+ self.add_workspace_bottom();
+ }
}
if self.options.layout.empty_workspace_above_first && workspace_idx == 0 {
@@ -595,9 +678,19 @@ impl<W: LayoutElement> Monitor<W> {
}
}
+ pub fn ensure_empty_before_hidden(&mut self) {
+ let first_hidden_idx = self.workspaces.iter().position(|ws| ws.hidden);
+
+ if let Some(hidden_idx) = first_hidden_idx {
+ if hidden_idx == 0 || self.workspaces[hidden_idx - 1].has_windows_or_name() {
+ self.add_workspace_at(hidden_idx);
+ }
+ }
+ }
+
pub fn add_tile_to_column(
&mut self,
- workspace_idx: usize,
+ mut workspace_idx: usize,
column_idx: usize,
tile_idx: Option<usize>,
tile: Tile<W>,
@@ -605,6 +698,15 @@ impl<W: LayoutElement> Monitor<W> {
// FIXME: Refactor ActivateWindow enum to make this better.
allow_to_activate_workspace: bool,
) {
+ // A hidden workspace must never become the active one; unhide it first
+ // if this tile is going to activate it.
+ if allow_to_activate_workspace && activate && self.workspaces[workspace_idx].hidden {
+ let ws_id = self.workspaces[workspace_idx].id();
+ if let Some(idx) = self.unhide_workspace_by_id(ws_id, true) {
+ workspace_idx = idx;
+ }
+ }
+
let workspace = &mut self.workspaces[workspace_idx];
workspace.add_tile_to_column(column_idx, tile_idx, tile, activate);
@@ -624,17 +726,27 @@ impl<W: LayoutElement> Monitor<W> {
pub fn clean_up_workspaces(&mut self) {
assert!(self.workspace_switch.is_none());
+ let last_hidden_idx = self.workspaces.iter().position(|ws| ws.hidden);
let range_start = if self.options.layout.empty_workspace_above_first {
1
} else {
0
};
- for idx in (range_start..self.workspaces.len() - 1).rev() {
+ let last_index_to_clean = if let Some(last_hidden_idx) = last_hidden_idx {
+ last_hidden_idx.saturating_sub(1)
+ } else {
+ self.workspaces.len() - 1
+ };
+ for idx in (range_start..last_index_to_clean).rev() {
if self.active_workspace_idx == idx {
continue;
}
+ if self.workspaces[idx].hidden {
+ continue;
+ }
+
if !self.workspaces[idx].has_windows_or_name() {
self.workspaces.remove(idx);
if self.active_workspace_idx > idx {
@@ -644,8 +756,12 @@ impl<W: LayoutElement> Monitor<W> {
}
// Special case handling when empty_workspace_above_first is set and all workspaces
- // are empty.
- if self.options.layout.empty_workspace_above_first && self.workspaces.len() == 2 {
+ // are empty. With a hidden workspace present ([empty, hidden-named]) there is
+ // nothing to collapse.
+ if self.options.layout.empty_workspace_above_first
+ && self.workspaces.len() == 2
+ && !self.workspaces.iter().any(|ws| ws.hidden)
+ {
assert!(!self.workspaces[0].has_windows_or_name());
assert!(!self.workspaces[1].has_windows_or_name());
self.workspaces.remove(1);
@@ -654,10 +770,14 @@ impl<W: LayoutElement> Monitor<W> {
}
pub fn unname_workspace(&mut self, id: WorkspaceId) -> bool {
+ self.unhide_workspace_by_id(id, false);
let Some(ws) = self.workspaces.iter_mut().find(|ws| ws.id() == id) else {
return false;
};
-
+ // Unnaming removes the only way to unhide this workspace later, so it
+ // must not be left pending a hide-on-switch-away (the unhide call above
+ // only clears this when the workspace was actually hidden).
+ ws.needs_hidden = false;
ws.unname();
if self.workspace_switch.is_none() {
@@ -667,8 +787,88 @@ impl<W: LayoutElement> Monitor<W> {
true
}
+ pub fn unhide_workspace_by_id(&mut self, id: WorkspaceId, needs_hidden: bool) -> Option<usize> {
+ let idx = self.workspaces.iter().position(|ws| ws.id() == id)?;
+
+ // Nothing to do if the workspace isn't actually hidden. Avoid the
+ // remove/reinsert work below, which resets workspace_switch and
+ // reorders the workspace vec even though nothing needs to move.
+ if !self.workspaces[idx].hidden {
+ return None;
+ }
+
+ let mut ws = self.remove_workspace_by_idx(idx);
+ ws.hidden = false;
+ ws.needs_hidden = needs_hidden;
+
+ // Unhidden workspaces go to the end of the visible region, right
+ // before the trailing empty workspace.
+ let visible_end = self
+ .workspaces
+ .iter()
+ .position(|ws| ws.hidden)
+ .unwrap_or(self.workspaces.len());
+ self.insert_workspace(ws, visible_end.saturating_sub(1), false);
+ self.workspaces.iter().position(|ws| ws.id() == id)
+ }
+
+ pub fn hide_workspace_by_name(&mut self, name: &str) {
+ let Some(idx) = self.find_named_workspace_index(name) else {
+ return;
+ };
+ self.hide_workspace_by_idx(idx);
+ }
+
+ // Currently only named workspaces can be hidden
+ pub fn hide_workspace_by_id(&mut self, id: WorkspaceId) -> bool {
+ let name = self
+ .workspaces
+ .iter()
+ .find(|ws| ws.id() == id)
+ .and_then(|ws| ws.name.clone());
+
+ let Some(name) = name else {
+ return false;
+ };
+
+ self.hide_workspace_by_name(&name);
+ true
+ }
+
+ pub fn hide_workspace_by_idx(&mut self, mut idx: usize) {
+ // Never hide the last visible workspace: the visible region must keep
+ // its trailing empty workspace, which also guards the hidden block.
+ let visible_end = self
+ .workspaces
+ .iter()
+ .position(|ws| ws.hidden)
+ .unwrap_or(self.workspaces.len());
+ if idx + 1 >= visible_end {
+ return;
+ }
+ if self.options.layout.empty_workspace_above_first && idx == 0 {
+ // The new empty workspace on top shifts the target down by one.
+ self.add_workspace_top();
+ idx += 1;
+ }
+
+ self.workspaces[idx].hidden = true;
+ self.workspaces[idx].needs_hidden = false;
+ let ws = self.remove_workspace_by_idx(idx);
+ self.workspaces.push(ws);
+ self.ensure_empty_before_hidden();
+ }
+
pub fn remove_workspace_by_idx(&mut self, mut idx: usize) -> Workspace<W> {
- if idx == self.workspaces.len() - 1 {
+ // When removing the last visible workspace, add a new empty one first to
+ // keep the visible region non-empty. Removing a hidden workspace doesn't
+ // need a replacement.
+ let visible_end = self
+ .workspaces
+ .iter()
+ .position(|ws| ws.hidden)
+ .unwrap_or(self.workspaces.len());
+ if !self.workspaces[idx].hidden && idx + 1 == visible_end {
self.add_workspace_bottom();
}
if self.options.layout.empty_workspace_above_first && idx == 0 {
@@ -677,7 +877,13 @@ impl<W: LayoutElement> Monitor<W> {
}
let mut ws = self.workspaces.remove(idx);
- ws.set_output(None);
+
+ // hidden workspaces are always named, when we remove one
+ // we're always going to be readding it to the same monitor
+ // so we preserve its output.
+ if !ws.hidden {
+ ws.set_output(None);
+ }
// For monitor current workspace removal, we focus previous rather than next (<= rather
// than <). This is different from columns and tiles, but it lets move-workspace-to-monitor
@@ -692,12 +898,47 @@ impl<W: LayoutElement> Monitor<W> {
ws
}
+ // Hidden workspaces always live at the end of the vec, even when newly
+ // added. On unhide they go to the end of the visible region.
+ pub fn insert_hidden_workspace(&mut self, mut ws: Workspace<W>) {
+ ws.set_output(Some(self.output.clone()));
+ ws.update_config(self.options.clone());
+
+ self.workspaces.push(ws);
+ self.workspace_switch = None;
+ self.clean_up_workspaces();
+ // The monitor may not have had a hidden block before this insert; make
+ // sure the block ends up guarded by an empty workspace.
+ self.ensure_empty_before_hidden();
+ }
+
pub fn insert_workspace(&mut self, mut ws: Workspace<W>, mut idx: usize, activate: bool) {
+ // A hidden workspace never belongs in the visible region (this happens
+ // when moving a hidden workspace to another output). Route it to the
+ // hidden block; it stays named, so it remains reachable.
+ if ws.hidden {
+ self.insert_hidden_workspace(ws);
+ return;
+ }
+
ws.set_output(Some(self.output.clone()));
ws.update_config(self.options.clone());
- // Don't insert past the last empty workspace.
- if idx == self.workspaces.len() {
+ // Hidden workspaces must stay contiguous at the end of the vec: never
+ // insert a visible workspace into or past that block. The visible
+ // region ends at the first hidden workspace, or at the vec end if
+ // there is none.
+ let visible_end = self
+ .workspaces
+ .iter()
+ .position(|ws| ws.hidden)
+ .unwrap_or(self.workspaces.len());
+ idx = idx.min(visible_end);
+
+ // Don't insert past the last empty workspace: the trailing empty when
+ // there is no hidden block, or the empty workspace guarding the hidden
+ // block.
+ if idx == visible_end && idx > 0 {
idx -= 1;
}
if idx == 0 && self.options.layout.empty_workspace_above_first {
@@ -731,13 +972,25 @@ impl<W: LayoutElement> Monitor<W> {
ws.update_config(self.options.clone());
}
- let empty_was_focused = self.active_workspace_idx == self.workspaces.len() - 1;
+ // Incoming hidden workspaces go to the hidden block at the end.
+ let (incoming_visible, incoming_hidden): (Vec<_>, Vec<_>) =
+ workspaces.into_iter().partition(|ws| !ws.hidden);
- // Push the workspaces from the removed monitor in the end, right before the
- // last, empty, workspace.
- let empty = self.workspaces.remove(self.workspaces.len() - 1);
- self.workspaces.extend(workspaces);
- self.workspaces.push(empty);
+ // The visible region ends with the empty trailing workspace (which also
+ // guards the hidden block when one exists). Splice the incoming visible
+ // workspaces right before it, and append incoming hidden ones at the end.
+ let visible_end = self
+ .workspaces
+ .iter()
+ .position(|ws| ws.hidden)
+ .unwrap_or(self.workspaces.len());
+ let empty_idx = visible_end - 1;
+ let empty_id = self.workspaces[empty_idx].id();
+ let empty_was_focused = self.active_workspace_idx == empty_idx;
+
+ self.workspaces
+ .splice(empty_idx..empty_idx, incoming_visible);
+ self.workspaces.extend(incoming_hidden);
// If empty_workspace_above_first is set and the first workspace is now no longer empty,
// add a new empty workspace on top.
@@ -749,7 +1002,11 @@ impl<W: LayoutElement> Monitor<W> {
// If the empty workspace was focused on the primary monitor, keep it focused.
if empty_was_focused {
- self.active_workspace_idx = self.workspaces.len() - 1;
+ self.active_workspace_idx = self
+ .workspaces
+ .iter()
+ .position(|ws| ws.id() == empty_id)
+ .unwrap();
}
// FIXME: if we're adding workspaces to currently invisible positions
@@ -813,13 +1070,21 @@ impl<W: LayoutElement> Monitor<W> {
removed.width,
removed.is_full_width,
removed.is_floating,
+ false,
);
}
pub fn move_to_workspace_down(&mut self, focus: bool) {
let source_workspace_idx = self.active_workspace_idx;
- let new_idx = min(source_workspace_idx + 1, self.workspaces.len() - 1);
+ // The workspace below is the next visible one; hidden workspaces sit
+ // past the end of the visible region.
+ let visible_end = self
+ .workspaces
+ .iter()
+ .position(|ws| ws.hidden)
+ .unwrap_or(self.workspaces.len());
+ let new_idx = min(source_workspace_idx + 1, visible_end - 1);
if new_idx == source_workspace_idx {
return;
}
@@ -847,6 +1112,7 @@ impl<W: LayoutElement> Monitor<W> {
removed.width,
removed.is_full_width,
removed.is_floating,
+ false,
);
}
@@ -900,6 +1166,7 @@ impl<W: LayoutElement> Monitor<W> {
removed.width,
removed.is_full_width,
removed.is_floating,
+ false,
);
if self.workspace_switch.is_none() {
@@ -931,7 +1198,14 @@ impl<W: LayoutElement> Monitor<W> {
pub fn move_column_to_workspace_down(&mut self, activate: bool) {
let source_workspace_idx = self.active_workspace_idx;
- let new_idx = min(source_workspace_idx + 1, self.workspaces.len() - 1);
+ // The workspace below is the next visible one; hidden workspaces sit
+ // past the end of the visible region.
+ let visible_end = self
+ .workspaces
+ .iter()
+ .position(|ws| ws.hidden)
+ .unwrap_or(self.workspaces.len());
+ let new_idx = min(source_workspace_idx + 1, visible_end - 1);
if new_idx == source_workspace_idx {
return;
}
@@ -983,12 +1257,33 @@ impl<W: LayoutElement> Monitor<W> {
let new = current.ceil() - 1.;
new.clamp(0., (self.workspaces.len() - 1) as f64) as usize
}
- _ => self.active_workspace_idx.saturating_sub(1),
+ // If the workspace is hidden, we shouldn't switch to it.
+ _ => {
+ let mut new_idx = self.active_workspace_idx.saturating_sub(1);
+ while new_idx > 0 && self.workspaces[new_idx].hidden {
+ new_idx = new_idx.saturating_sub(1);
+ }
+ // Don't move if there is only hidden above
+ if self.workspaces[new_idx].hidden {
+ self.active_workspace_idx
+ } else {
+ new_idx
+ }
+ }
};
self.activate_workspace(new_idx);
}
+ pub fn hide_needs_hidden(&mut self, idx: usize) -> bool {
+ let needs_hidden = self.workspaces[idx].needs_hidden;
+ if needs_hidden {
+ self.hide_workspace_by_idx(idx);
+ return true;
+ }
+ return false;
+ }
+
pub fn switch_workspace_down(&mut self) {
let new_idx = match &self.workspace_switch {
// During a DnD scroll, select the next apparent workspace.
@@ -997,7 +1292,20 @@ impl<W: LayoutElement> Monitor<W> {
let new = current.floor() + 1.;
new.clamp(0., (self.workspaces.len() - 1) as f64) as usize
}
- _ => min(self.active_workspace_idx + 1, self.workspaces.len() - 1),
+ // If the workspace is hidden, we shouldn't switch to it.
+ // Instead we need to bump the workspace down
+ _ => {
+ let max = self.workspaces.len() - 1;
+ let mut new_idx = min(self.active_workspace_idx + 1, max);
+ while new_idx < max && self.workspaces[new_idx].hidden {
+ new_idx += 1;
+ }
+ if new_idx > max || self.workspaces[new_idx].hidden {
+ return;
+ }
+
+ new_idx
+ }
};
self.activate_workspace(new_idx);
@@ -1008,8 +1316,26 @@ impl<W: LayoutElement> Monitor<W> {
self.workspaces.iter().position(|w| w.id() == id)
}
- pub fn switch_workspace(&mut self, idx: usize) {
- self.activate_workspace(min(idx, self.workspaces.len() - 1));
+ pub fn switch_workspace(&mut self, idx: usize, force_unhide: bool) {
+ let mut actual_idx = min(idx, self.workspaces.len() - 1);
+
+ if force_unhide {
+ let id = &self.workspaces[actual_idx].id().clone();
+ // If this workspace was forcefully unhidden by needing focus
+ // also make sure it needs to be hidden later.
+ if let Some(idx) = self.unhide_workspace_by_id(*id, force_unhide) {
+ actual_idx = idx;
+ }
+ }
+ if self.workspaces[actual_idx].hidden && !force_unhide {
+ if let Some(visible_idx) = (0..actual_idx).rev().find(|&i| !self.workspaces[i].hidden) {
+ actual_idx = visible_idx;
+ } else {
+ return;
+ }
+ }
+
+ self.activate_workspace(actual_idx);
}
pub fn switch_workspace_auto_back_and_forth(&mut self, idx: usize) {
@@ -1017,16 +1343,16 @@ impl<W: LayoutElement> Monitor<W> {
if idx == self.active_workspace_idx {
if let Some(prev_idx) = self.previous_workspace_idx() {
- self.switch_workspace(prev_idx);
+ self.switch_workspace(prev_idx, false);
}
} else {
- self.switch_workspace(idx);
+ self.switch_workspace(idx, false);
}
}
pub fn switch_workspace_previous(&mut self) {
if let Some(idx) = self.previous_workspace_idx() {
- self.switch_workspace(idx);
+ self.switch_workspace(idx, false);
}
}
@@ -1240,14 +1566,20 @@ impl<W: LayoutElement> Monitor<W> {
}
pub fn move_workspace_down(&mut self) {
- let mut new_idx = min(self.active_workspace_idx + 1, self.workspaces.len() - 1);
+ // Stay within the visible region: hidden workspaces sit past its end.
+ let visible_end = self
+ .workspaces
+ .iter()
+ .position(|ws| ws.hidden)
+ .unwrap_or(self.workspaces.len());
+ let mut new_idx = min(self.active_workspace_idx + 1, visible_end - 1);
if new_idx == self.active_workspace_idx {
return;
}
self.workspaces.swap(self.active_workspace_idx, new_idx);
- if new_idx == self.workspaces.len() - 1 {
+ if new_idx == visible_end - 1 {
// Insert a new empty workspace.
self.add_workspace_bottom();
}
@@ -1273,7 +1605,12 @@ impl<W: LayoutElement> Monitor<W> {
self.workspaces.swap(self.active_workspace_idx, new_idx);
- if self.active_workspace_idx == self.workspaces.len() - 1 {
+ let visible_end = self
+ .workspaces
+ .iter()
+ .position(|ws| ws.hidden)
+ .unwrap_or(self.workspaces.len());
+ if self.active_workspace_idx == visible_end - 1 {
// Insert a new empty workspace.
self.add_workspace_bottom();
}
@@ -1295,8 +1632,18 @@ impl<W: LayoutElement> Monitor<W> {
if self.workspaces.len() <= old_idx {
return;
}
+ // Hidden workspaces have no meaningful position; reordering must stay
+ // within the visible region.
+ if self.workspaces[old_idx].hidden {
+ return;
+ }
+ let visible_end = self
+ .workspaces
+ .iter()
+ .position(|ws| ws.hidden)
+ .unwrap_or(self.workspaces.len());
- let mut new_idx = new_idx.clamp(0, self.workspaces.len() - 1);
+ let mut new_idx = new_idx.clamp(0, visible_end - 1);
if old_idx == new_idx {
return;
}
@@ -1305,7 +1652,7 @@ impl<W: LayoutElement> Monitor<W> {
self.workspaces.insert(new_idx, ws);
if new_idx > old_idx {
- if new_idx == self.workspaces.len() - 1 {
+ if new_idx == visible_end - 1 {
// Insert a new empty workspace.
self.add_workspace_bottom();
}
@@ -1315,7 +1662,7 @@ impl<W: LayoutElement> Monitor<W> {
new_idx += 1;
}
} else {
- if old_idx == self.workspaces.len() - 1 {
+ if old_idx == visible_end - 1 {
// Insert a new empty workspace.
self.add_workspace_bottom();
}
@@ -1510,7 +1857,7 @@ impl<W: LayoutElement> Monitor<W> {
let geo = self.workspaces_render_geo();
zip(self.workspaces.iter(), geo)
// Cull out workspaces outside the output.
- .filter(move |(_ws, geo)| geo.intersection(output_geo).is_some())
+ .filter(move |(ws, geo)| !ws.hidden && geo.intersection(output_geo).is_some())
}
pub fn workspaces_with_render_geo_idx(
@@ -1521,7 +1868,7 @@ impl<W: LayoutElement> Monitor<W> {
let geo = self.workspaces_render_geo();
zip(self.workspaces.iter().enumerate(), geo)
// Cull out workspaces outside the output.
- .filter(move |(_ws, geo)| geo.intersection(output_geo).is_some())
+ .filter(move |(ws, geo)| !ws.1.hidden && geo.intersection(output_geo).is_some())
}
pub fn workspaces_with_render_geo_mut(
@@ -1533,7 +1880,9 @@ impl<W: LayoutElement> Monitor<W> {
let geo = self.workspaces_render_geo();
zip(self.workspaces.iter_mut(), geo)
// Cull out workspaces outside the output.
- .filter(move |(_ws, geo)| !cull || geo.intersection(output_geo).is_some())
+ .filter(move |(ws, geo)| {
+ !ws.hidden && (!cull || geo.intersection(output_geo).is_some())
+ })
}
pub fn workspace_under(
@@ -2076,9 +2425,31 @@ impl<W: LayoutElement> Monitor<W> {
assert!(after_idx < self.workspaces.len());
}
+ // Hidden workspaces are contiguous at the end of the vec and always named
+ // (unhide and toggle-visibility look workspaces up by name).
+ let visible_count = self
+ .workspaces
+ .iter()
+ .position(|ws| ws.hidden)
+ .unwrap_or(self.workspaces.len());
+ for ws in &self.workspaces[visible_count..] {
+ assert!(
+ ws.hidden,
+ "hidden workspaces must be contiguous at the end of the workspace vec"
+ );
+ assert!(ws.name.is_some(), "hidden workspaces must be named");
+ }
assert!(
- !self.workspaces.last().unwrap().has_windows(),
- "monitor must have an empty workspace in the end"
+ visible_count > 0,
+ "monitor must have at least one visible workspace"
+ );
+
+ // The visible region ends with an empty unnamed workspace. When a hidden
+ // block exists, that same workspace is the guard directly before the block.
+ let last_visible = &self.workspaces[visible_count - 1];
+ assert!(
+ !last_visible.has_windows(),
+ "monitor must have an empty workspace at the end of the visible region"
);
if self.options.layout.empty_workspace_above_first {
assert!(
@@ -2088,8 +2459,8 @@ impl<W: LayoutElement> Monitor<W> {
}
assert!(
- self.workspaces.last().unwrap().name.is_none(),
- "monitor must have an unnamed workspace in the end"
+ last_visible.name.is_none(),
+ "monitor must have an unnamed workspace at the end of the visible region"
);
if self.options.layout.empty_workspace_above_first {
assert!(
@@ -2098,35 +2469,28 @@ impl<W: LayoutElement> Monitor<W> {
)
}
- if self.options.layout.empty_workspace_above_first {
+ if self.options.layout.empty_workspace_above_first && visible_count == self.workspaces.len()
+ {
assert!(
self.workspaces.len() != 2,
"if empty_workspace_above_first is set there must be just 1 or 3+ workspaces"
)
}
- // If there's no workspace switch in progress, there can't be any non-last non-active
- // empty workspaces. If empty_workspace_above_first is set then the first workspace
- // will be empty too.
+ // If there's no workspace switch in progress, there can't be any non-last
+ // non-active empty workspaces in the visible region. If
+ // empty_workspace_above_first is set then the first workspace will be empty too.
let pre_skip = if self.options.layout.empty_workspace_above_first {
1
} else {
0
};
if self.workspace_switch.is_none() {
- for (idx, ws) in self
- .workspaces
- .iter()
- .enumerate()
- .skip(pre_skip)
- .rev()
- // skip last
- .skip(1)
- {
- if idx != self.active_workspace_idx {
+ for (idx, ws) in self.workspaces[..visible_count].iter().enumerate() {
+ if idx >= pre_skip && idx != visible_count - 1 && idx != self.active_workspace_idx {
assert!(
ws.has_windows_or_name(),
- "non-active workspace can't be empty and unnamed except the last one"
+ "non-active workspace can't be empty and unnamed except the last visible one"
);
}
}
diff --git a/src/layout/tests.rs b/src/layout/tests.rs
index 31265dd9..9450f1aa 100644
--- a/src/layout/tests.rs
+++ b/src/layout/tests.rs
@@ -557,6 +557,7 @@ enum Op {
#[proptest(strategy = "proptest::option::of(1..=5usize)")]
ws_name: Option<usize>,
},
+ ToggleWorkspaceVisibility(#[proptest(strategy = "1..=5usize")] usize),
MoveWindowToOutput {
#[proptest(strategy = "proptest::option::of(1..=5usize)")]
window_id: Option<usize>,
@@ -858,6 +859,7 @@ impl Op {
layout_config,
} => {
layout.ensure_named_workspace(&WorkspaceConfig {
+ hidden: None,
name: WorkspaceName(format!("ws{ws_name}")),
open_on_output: output_name.map(|name| format!("output{name}")),
layout: layout_config.map(|x| niri_config::WorkspaceLayoutPart(*x)),
@@ -893,6 +895,9 @@ impl Op {
ws_name.map(|ws_name| WorkspaceReference::Name(format!("ws{ws_name}")));
layout.unset_workspace_name(ws_ref);
}
+ Op::ToggleWorkspaceVisibility(ws_name) => {
+ layout.toggle_workspace_visibility(format!("ws{ws_name}"));
+ }
Op::AddWindow { mut params } => {
if layout.has_window(¶ms.id) {
return;
@@ -913,6 +918,7 @@ impl Op {
false,
is_floating,
ActivateWindow::default(),
+ false,
);
}
Op::AddWindowNextTo {
@@ -982,6 +988,7 @@ impl Op {
false,
is_floating,
ActivateWindow::default(),
+ false,
);
}
Op::AddWindowToNamedWorkspace {
@@ -1056,6 +1063,7 @@ impl Op {
false,
is_floating,
ActivateWindow::default(),
+ false,
);
}
Op::CloseWindow(id) => {
@@ -1181,7 +1189,7 @@ impl Op {
Op::CenterVisibleColumns => layout.center_visible_columns(),
Op::FocusWorkspaceDown => layout.switch_workspace_down(),
Op::FocusWorkspaceUp => layout.switch_workspace_up(),
- Op::FocusWorkspace(idx) => layout.switch_workspace(idx),
+ Op::FocusWorkspace(idx) => layout.switch_workspace(idx, false),
Op::FocusWorkspaceAutoBackAndForth(idx) => {
layout.switch_workspace_auto_back_and_forth(idx)
}
@@ -2141,6 +2149,699 @@ fn workspaces_update_original_output_on_moving_to_same_monitor() {
assert_eq!(mon.output_name(), "output2");
}
+#[test]
+fn verify_invariants_accepts_hidden_workspaces() {
+ let ops = [
+ Op::AddOutput(1),
+ Op::AddWindow {
+ params: TestWindowParams::new(1),
+ },
+ Op::FocusWorkspaceDown,
+ Op::AddWindow {
+ params: TestWindowParams::new(2),
+ },
+ Op::SetWorkspaceName {
+ new_ws_name: 2,
+ ws_name: None,
+ },
+ Op::FocusWorkspaceDown,
+ Op::AddWindow {
+ params: TestWindowParams::new(3),
+ },
+ Op::SetWorkspaceName {
+ new_ws_name: 3,
+ ws_name: None,
+ },
+ ];
+ let mut layout = check_ops(ops);
+
+ layout.toggle_workspace_visibility("ws3".to_string());
+ layout.verify_invariants();
+ layout.toggle_workspace_visibility("ws2".to_string());
+ layout.verify_invariants();
+ layout.toggle_workspace_visibility("ws3".to_string());
+ layout.verify_invariants();
+}
+
+#[test]
+fn unhide_goes_to_end_of_visible_region() {
+ let ops = [
+ Op::AddOutput(1),
+ Op::AddWindow {
+ params: TestWindowParams::new(1),
+ },
+ Op::SetWorkspaceName {
+ new_ws_name: 1,
+ ws_name: None,
+ },
+ Op::FocusWorkspaceDown,
+ Op::AddWindow {
+ params: TestWindowParams::new(2),
+ },
+ Op::FocusWorkspaceDown,
+ Op::AddWindow {
+ params: TestWindowParams::new(3),
+ },
+ ];
+ // ["ws1"(win1), win2, win3, empty]
+ let mut layout = check_ops(ops);
+
+ layout.toggle_workspace_visibility("ws1".to_string());
+ layout.verify_invariants();
+ layout.toggle_workspace_visibility("ws1".to_string());
+ layout.verify_invariants();
+
+ // The unhidden workspace lands at the end of the visible region, right
+ // before the trailing empty: [win2, win3, "ws1"(win1), empty].
+ let monitor = match &layout.monitor_set {
+ MonitorSet::Normal { monitors, .. } => &monitors[0],
+ MonitorSet::NoOutputs { .. } => unreachable!(),
+ };
+ let pos_ws1 = monitor
+ .workspaces
+ .iter()
+ .position(|ws| ws.name.as_deref() == Some("ws1"))
+ .unwrap();
+ assert_eq!(pos_ws1, monitor.workspaces.len() - 2);
+}
+
+#[test]
+fn unname_focused_visible_workspace_keeps_focus() {
+ let ops = [
+ Op::AddOutput(1),
+ Op::AddWindow {
+ params: TestWindowParams::new(1),
+ },
+ Op::SetWorkspaceName {
+ new_ws_name: 1,
+ ws_name: None,
+ },
+ Op::FocusWorkspaceDown,
+ Op::AddWindow {
+ params: TestWindowParams::new(2),
+ },
+ Op::FocusWorkspaceUp,
+ ];
+ // ["ws1"(win1), win2, empty], focus back on "ws1".
+ let mut layout = check_ops(ops);
+
+ layout.unname_workspace("ws1");
+ layout.verify_invariants();
+
+ // Unnaming a visible workspace must not reorder or refocus anything.
+ let monitor = match &layout.monitor_set {
+ MonitorSet::Normal { monitors, .. } => &monitors[0],
+ MonitorSet::NoOutputs { .. } => unreachable!(),
+ };
+ assert!(monitor.workspaces[0].has_window(&1));
+ assert!(monitor.workspaces[1].has_window(&2));
+ assert_eq!(
+ monitor.active_workspace_idx, 0,
+ "focus must stay on the unnamed workspace"
+ );
+}
+
+#[test]
+fn clean_up_workspaces_skips_two_workspace_collapse_with_hidden() {
+ let options = Options {
+ layout: niri_config::Layout {
+ empty_workspace_above_first: true,
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+ let ops = [
+ Op::AddOutput(1),
+ Op::AddWindow {
+ params: TestWindowParams::new(1),
+ },
+ Op::SetWorkspaceName {
+ new_ws_name: 1,
+ ws_name: None,
+ },
+ ];
+ // [emptyTop, "ws1"(win1), empty]
+ let mut layout = check_ops_with_options(options, ops);
+
+ // Hiding "ws1" leaves [emptyTop, "ws1"(hidden)].
+ layout.toggle_workspace_visibility("ws1".to_string());
+ layout.verify_invariants();
+
+ // A later cleanup (e.g. after a workspace-switch gesture ends) must not
+ // assert on the legal [empty, hidden-named] state.
+ let monitor = match &mut layout.monitor_set {
+ MonitorSet::Normal { monitors, .. } => &mut monitors[0],
+ MonitorSet::NoOutputs { .. } => unreachable!(),
+ };
+ monitor.clean_up_workspaces();
+ layout.verify_invariants();
+}
+
+#[test]
+fn close_window_in_hidden_workspace_with_empty_workspace_above_first() {
+ let options = Options {
+ layout: niri_config::Layout {
+ empty_workspace_above_first: true,
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+ let ops = [
+ Op::AddOutput(1),
+ Op::AddWindow {
+ params: TestWindowParams::new(1),
+ },
+ Op::SetWorkspaceName {
+ new_ws_name: 1,
+ ws_name: None,
+ },
+ ];
+ let mut layout = check_ops_with_options(options, ops);
+
+ layout.toggle_workspace_visibility("ws1".to_string());
+ layout.verify_invariants();
+
+ // Closing the hidden workspace's window reaches remove_window's own
+ // two-workspace collapse; it must not assert on [empty, hidden-named].
+ Op::CloseWindow(1).apply(&mut layout);
+ layout.verify_invariants();
+}
+
+#[test]
+fn hide_workspace_at_index_zero_hides_the_right_workspace() {
+ let options = Options {
+ layout: niri_config::Layout {
+ empty_workspace_above_first: true,
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+ let ops = [
+ Op::AddOutput(1),
+ Op::AddWindow {
+ params: TestWindowParams::new(1),
+ },
+ ];
+ let mut layout = check_ops_with_options(options, ops);
+
+ let monitor = match &mut layout.monitor_set {
+ MonitorSet::Normal { monitors, .. } => &mut monitors[0],
+ MonitorSet::NoOutputs { .. } => unreachable!(),
+ };
+ // Manufacture a named workspace at idx 0.
+ monitor.workspaces[0].name = Some("ws1".to_string());
+
+ monitor.hide_workspace_by_idx(0);
+
+ // The named workspace must be the hidden one — not the freshly added empty.
+ let hidden: Vec<_> = monitor.workspaces.iter().filter(|ws| ws.hidden).collect();
+ assert_eq!(hidden.len(), 1);
+ assert_eq!(hidden[0].name.as_deref(), Some("ws1"));
+}
+
+#[test]
+fn move_hidden_workspace_to_other_output_keeps_it_hidden() {
+ let ops = [
+ Op::AddOutput(1),
+ Op::AddOutput(2),
+ Op::AddWindow {
+ params: TestWindowParams::new(1),
+ },
+ Op::SetWorkspaceName {
+ new_ws_name: 1,
+ ws_name: None,
+ },
+ ];
+ let mut layout = check_ops(ops);
+
+ layout.toggle_workspace_visibility("ws1".to_string());
+ layout.verify_invariants();
+
+ // Move the hidden workspace to output 2.
+ let (old_idx, old_output, new_output) = match &layout.monitor_set {
+ MonitorSet::Normal { monitors, .. } => {
+ let old_idx = monitors[0]
+ .workspaces
+ .iter()
+ .position(|ws| ws.name.as_deref() == Some("ws1"))
+ .unwrap();
+ (
+ old_idx,
+ monitors[0].output.clone(),
+ monitors[1].output.clone(),
+ )
+ }
+ MonitorSet::NoOutputs { .. } => unreachable!(),
+ };
+ layout.move_workspace_to_output_by_id(old_idx, Some(old_output), &new_output);
+ layout.verify_invariants();
+
+ // The workspace lives on monitor 1 now, still hidden, still reachable by name.
+ let monitor = match &layout.monitor_set {
+ MonitorSet::Normal { monitors, .. } => &monitors[1],
+ MonitorSet::NoOutputs { .. } => unreachable!(),
+ };
+ let ws = monitor
+ .workspaces
+ .iter()
+ .find(|ws| ws.name.as_deref() == Some("ws1"))
+ .expect("moved workspace must be on the target monitor");
+ assert!(ws.hidden, "moved workspace must stay hidden");
+
+ layout.toggle_workspace_visibility("ws1".to_string());
+ layout.verify_invariants();
+}
+
+#[test]
+fn output_disconnect_preserves_hidden_blocks() {
+ let ops = [
+ Op::AddOutput(1),
+ Op::AddOutput(2),
+ // Window + named workspace on output 1 (primary).
+ Op::AddWindow {
+ params: TestWindowParams::new(1),
+ },
+ Op::SetWorkspaceName {
+ new_ws_name: 1,
+ ws_name: None,
+ },
+ // Window + named workspace on output 2.
+ Op::FocusOutput(2),
+ Op::AddWindow {
+ params: TestWindowParams::new(2),
+ },
+ Op::SetWorkspaceName {
+ new_ws_name: 2,
+ ws_name: None,
+ },
+ // A visible workspace on output 2 too, so the incoming set mixes
+ // visible and hidden workspaces.
+ Op::FocusWorkspaceDown,
+ Op::AddWindow {
+ params: TestWindowParams::new(3),
+ },
+ ];
+ let mut layout = check_ops(ops);
+ layout.toggle_workspace_visibility("ws1".to_string());
+ layout.toggle_workspace_visibility("ws2".to_string());
+ layout.verify_invariants();
+
+ // Disconnect output 2; its workspaces (incl. the hidden one) land on output 1.
+ Op::RemoveOutput(2).apply(&mut layout);
+ layout.verify_invariants();
+
+ // Both hidden workspaces must be reachable again.
+ layout.toggle_workspace_visibility("ws1".to_string());
+ layout.verify_invariants();
+ layout.toggle_workspace_visibility("ws2".to_string());
+ layout.verify_invariants();
+}
+
+#[test]
+fn move_window_to_output_targeting_hidden_workspace() {
+ // Found by proptest: an explicit target workspace index that lands in the
+ // hidden block must not break hidden contiguity.
+ check_ops([
+ Op::AddScaledOutput {
+ id: 2,
+ scale: 1.0,
+ layout_config: None,
+ },
+ Op::AddNamedWorkspace {
+ ws_name: 2,
+ output_name: None,
+ layout_config: None,
+ },
+ Op::AddWindow {
+ params: TestWindowParams::new(1),
+ },
+ Op::ToggleWorkspaceVisibility(2),
+ Op::MoveWindowToOutput {
+ window_id: None,
+ output_id: 2,
+ target_ws_idx: Some(2),
+ },
+ Op::MoveWorkspaceDown,
+ ]);
+}
+
+#[test]
+fn re_hiding_on_switch_away_keeps_the_switch_target_valid() {
+ // Found by proptest: switching away from a force-unhidden workspace
+ // re-hides it, which shifts the workspace vec; the switch animation must
+ // target where the destination ended up, not its pre-hide index.
+ check_ops([
+ Op::AddNamedWorkspace {
+ ws_name: 5,
+ output_name: None,
+ layout_config: None,
+ },
+ Op::AddOutput(1),
+ Op::ToggleWorkspaceVisibility(5),
+ Op::AddWindow {
+ params: TestWindowParams::new(1),
+ },
+ Op::MoveWindowToWorkspace {
+ window_id: None,
+ workspace_idx: 3,
+ },
+ Op::FocusWorkspaceAutoBackAndForth(3),
+ ]);
+}
+
+#[test]
+fn add_output_during_workspace_switch_gesture() {
+ // Found by proptest: add_output's two-workspace cleanup ran while a
+ // workspace switch gesture was in progress, tripping clean_up_workspaces'
+ // workspace_switch.is_none() assert.
+ let options = Options {
+ layout: niri_config::Layout {
+ empty_workspace_above_first: true,
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+ check_ops_with_options(
+ options,
+ [
+ Op::AddOutput(4),
+ Op::SetWorkspaceName {
+ new_ws_name: 2,
+ ws_name: None,
+ },
+ Op::ToggleWorkspaceVisibility(2),
+ Op::WorkspaceSwitchGestureBegin {
+ output_idx: 4,
+ is_touchpad: false,
+ },
+ Op::AddOutput(1),
+ ],
+ );
+}
+
+#[test]
+fn hiding_the_last_visible_workspace_is_refused() {
+ let ops = [
+ Op::AddOutput(1),
+ Op::AddWindow {
+ params: TestWindowParams::new(1),
+ },
+ Op::SetWorkspaceName {
+ new_ws_name: 1,
+ ws_name: None,
+ },
+ ];
+ let mut layout = check_ops(ops);
+ // ["ws1"(win1), empty]; hiding "ws1" leaves ["-", "ws1"(hidden)].
+ layout.toggle_workspace_visibility("ws1".to_string());
+ layout.verify_invariants();
+
+ let monitor = match &mut layout.monitor_set {
+ MonitorSet::Normal { monitors, .. } => &mut monitors[0],
+ MonitorSet::NoOutputs { .. } => unreachable!(),
+ };
+ let visible_end = monitor.workspaces.iter().position(|ws| ws.hidden).unwrap();
+ assert_eq!(visible_end, 1);
+ // Name the remaining visible workspace so it is hideable in principle,
+ // then try to hide it: the visible region must not be left empty.
+ monitor.workspaces[0].name = Some("ws2".to_string());
+ monitor.hide_workspace_by_idx(0);
+
+ assert!(
+ !monitor.workspaces[0].hidden,
+ "the last visible workspace must not be hidden"
+ );
+ assert_eq!(
+ monitor.workspaces.iter().filter(|ws| ws.hidden).count(),
+ 1,
+ "no new hidden workspace may appear"
+ );
+}
+
+#[test]
+fn move_column_to_hidden_workspace_then_move_workspace_down() {
+ // Found by proptest: moving a column into a hidden workspace and focusing
+ // it must unhide it first, otherwise the hidden workspace becomes active
+ // and the following workspace move swaps it out of the hidden block.
+ check_ops([
+ Op::AddOutput(1),
+ Op::AddWindow {
+ params: TestWindowParams::new(1),
+ },
+ Op::FocusWorkspace(1),
+ Op::SetWorkspaceName {
+ new_ws_name: 2,
+ ws_name: None,
+ },
+ Op::ToggleWorkspaceVisibility(2),
+ Op::MoveColumnToWorkspace(2, true),
+ Op::MoveWorkspaceDown,
+ ]);
+}
+
+#[test]
+fn move_window_to_hidden_workspace_without_focus_keeps_it_hidden() {
+ // Sending a window to a hidden workspace without focusing it must leave
+ // the workspace hidden (the scratchpad flow).
+ let ops = [
+ Op::AddOutput(1),
+ Op::AddWindow {
+ params: TestWindowParams::new(1),
+ },
+ Op::SetWorkspaceName {
+ new_ws_name: 1,
+ ws_name: None,
+ },
+ Op::FocusWorkspaceDown,
+ Op::AddWindow {
+ params: TestWindowParams::new(2),
+ },
+ ];
+ let mut layout = check_ops(ops);
+ layout.toggle_workspace_visibility("ws1".to_string());
+ layout.verify_invariants();
+
+ let hidden_idx = match &layout.monitor_set {
+ MonitorSet::Normal { monitors, .. } => monitors[0]
+ .workspaces
+ .iter()
+ .position(|ws| ws.hidden)
+ .unwrap(),
+ MonitorSet::NoOutputs { .. } => unreachable!(),
+ };
+ Op::MoveColumnToWorkspace(hidden_idx, false).apply(&mut layout);
+ layout.verify_invariants();
+
+ let monitor = match &layout.monitor_set {
+ MonitorSet::Normal { monitors, .. } => &monitors[0],
+ MonitorSet::NoOutputs { .. } => unreachable!(),
+ };
+ let ws = monitor
+ .workspaces
+ .iter()
+ .find(|ws| ws.name.as_deref() == Some("ws1"))
+ .unwrap();
+ assert!(ws.hidden, "workspace must stay hidden when not focusing it");
+ assert!(ws.has_window(&2), "the window must have moved there");
+}
+
+#[test]
+fn moving_last_visible_workspace_away_keeps_visible_region() {
+ // Found by proptest: moving the only visible workspace (the empty guard)
+ // to another output must leave a visible workspace behind, not a bare
+ // hidden block.
+ check_ops([
+ Op::AddOutput(1),
+ Op::AddNamedWorkspace {
+ ws_name: 1,
+ output_name: None,
+ layout_config: None,
+ },
+ Op::ToggleWorkspaceVisibility(1),
+ Op::AddOutput(2),
+ Op::MoveWorkspaceToOutput(2),
+ ]);
+}
+
+#[test]
+fn move_workspace_down_stops_at_hidden_block() {
+ // Moving the active workspace down must not swap it into the hidden block.
+ check_ops([
+ Op::AddOutput(1),
+ Op::AddNamedWorkspace {
+ ws_name: 1,
+ output_name: None,
+ layout_config: None,
+ },
+ Op::ToggleWorkspaceVisibility(1),
+ Op::MoveWorkspaceDown,
+ ]);
+}
+
+#[test]
+fn move_workspace_to_idx_stays_in_visible_region() {
+ let ops = [
+ Op::AddOutput(1),
+ Op::AddWindow {
+ params: TestWindowParams::new(1),
+ },
+ Op::SetWorkspaceName {
+ new_ws_name: 1,
+ ws_name: None,
+ },
+ Op::FocusWorkspaceDown,
+ Op::AddWindow {
+ params: TestWindowParams::new(2),
+ },
+ ];
+ let mut layout = check_ops(ops);
+ layout.toggle_workspace_visibility("ws1".to_string());
+ layout.verify_invariants();
+
+ let monitor = match &mut layout.monitor_set {
+ MonitorSet::Normal { monitors, .. } => &mut monitors[0],
+ MonitorSet::NoOutputs { .. } => unreachable!(),
+ };
+ let hidden_idx = monitor.workspaces.iter().position(|ws| ws.hidden).unwrap();
+
+ // Moving a hidden workspace is a no-op.
+ monitor.move_workspace_to_idx(hidden_idx, 0);
+ layout.verify_invariants();
+
+ // Moving a visible workspace to a huge index clamps to the visible region.
+ let monitor = match &mut layout.monitor_set {
+ MonitorSet::Normal { monitors, .. } => &mut monitors[0],
+ MonitorSet::NoOutputs { .. } => unreachable!(),
+ };
+ monitor.move_workspace_to_idx(0, 100);
+ layout.verify_invariants();
+}
+
+#[test]
+fn unname_hidden_workspace_without_outputs_leaves_it_reachable() {
+ let ops = [
+ Op::AddOutput(1),
+ Op::AddWindow {
+ params: TestWindowParams::new(1),
+ },
+ Op::SetWorkspaceName {
+ new_ws_name: 1,
+ ws_name: None,
+ },
+ ];
+ let mut layout = check_ops(ops);
+ layout.toggle_workspace_visibility("ws1".to_string());
+ Op::RemoveOutput(1).apply(&mut layout);
+ layout.verify_invariants();
+
+ // Unname while no outputs are connected.
+ layout.unname_workspace("ws1");
+ layout.verify_invariants();
+
+ // When the output returns, the workspace must be visible (an unnamed
+ // hidden workspace would be unreachable forever).
+ Op::AddOutput(1).apply(&mut layout);
+ layout.verify_invariants();
+ let monitor = match &layout.monitor_set {
+ MonitorSet::Normal { monitors, .. } => &monitors[0],
+ MonitorSet::NoOutputs { .. } => unreachable!(),
+ };
+ let ws = monitor
+ .workspaces
+ .iter()
+ .find(|ws| ws.has_window(&1))
+ .unwrap();
+ assert!(!ws.hidden);
+}
+
+#[test]
+fn naming_last_visible_workspace_restores_empty_guard() {
+ let ops = [
+ Op::AddOutput(1),
+ Op::AddWindow {
+ params: TestWindowParams::new(1),
+ },
+ Op::SetWorkspaceName {
+ new_ws_name: 1,
+ ws_name: None,
+ },
+ ];
+ let mut layout = check_ops(ops);
+ layout.toggle_workspace_visibility("ws1".to_string());
+ layout.verify_invariants();
+
+ // Name the empty guard workspace (the last visible one, sitting before the
+ // hidden block). A new empty workspace must be added after it.
+ let wsid = match &layout.monitor_set {
+ MonitorSet::Normal { monitors, .. } => {
+ let visible_end = monitors[0]
+ .workspaces
+ .iter()
+ .position(|ws| ws.hidden)
+ .unwrap();
+ monitors[0].workspaces[visible_end - 1].id()
+ }
+ MonitorSet::NoOutputs { .. } => unreachable!(),
+ };
+ layout.set_workspace_name("ws2".to_string(), Some(WorkspaceReference::Id(wsid.get())));
+ layout.verify_invariants();
+}
+
+#[test]
+fn naming_workspace_on_non_active_monitor_compensates_there() {
+ let options = Options {
+ layout: niri_config::Layout {
+ empty_workspace_above_first: true,
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+ let ops = [Op::AddOutput(1), Op::AddOutput(2)];
+ // Focus stays on output 1 (the active monitor).
+ let mut layout = check_ops_with_options(options, ops);
+
+ // Name the FIRST workspace of the non-active monitor by id. The compensating
+ // empty workspace must be added on that monitor, not the active one.
+ let wsid = match &layout.monitor_set {
+ MonitorSet::Normal { monitors, .. } => monitors[1].workspaces[0].id(),
+ MonitorSet::NoOutputs { .. } => unreachable!(),
+ };
+ layout.set_workspace_name("ws1".to_string(), Some(WorkspaceReference::Id(wsid.get())));
+ layout.verify_invariants();
+}
+
+#[test]
+fn hidden_workspaces_are_not_rendered() {
+ let ops = [
+ Op::AddOutput(1),
+ Op::AddWindow {
+ params: TestWindowParams::new(1),
+ },
+ Op::SetWorkspaceName {
+ new_ws_name: 1,
+ ws_name: None,
+ },
+ ];
+ let mut layout = check_ops(ops);
+ layout.toggle_workspace_visibility("ws1".to_string());
+
+ // In the overview the workspace strip is zoomed out, so the hidden
+ // workspace's geometry intersects the output; it still must not render.
+ Op::ToggleOverview.apply(&mut layout);
+ Op::AdvanceAnimations { msec_delta: 1000 }.apply(&mut layout);
+
+ let monitor = match &mut layout.monitor_set {
+ MonitorSet::Normal { monitors, .. } => &mut monitors[0],
+ MonitorSet::NoOutputs { .. } => unreachable!(),
+ };
+ assert!(monitor
+ .workspaces_with_render_geo_mut(false)
+ .all(|(ws, _)| !ws.hidden));
+ assert!(monitor
+ .workspaces_with_render_geo_mut(true)
+ .all(|(ws, _)| !ws.hidden));
+}
+
#[test]
fn large_negative_height_change() {
let ops = [
diff --git a/src/layout/workspace.rs b/src/layout/workspace.rs
index 49548a83..5e40f3d3 100644
--- a/src/layout/workspace.rs
+++ b/src/layout/workspace.rs
@@ -111,6 +111,12 @@ pub struct Workspace<W: LayoutElement> {
/// Unique ID of this workspace.
id: WorkspaceId,
+
+ /// whether we should hide this workspace for indexing
+ pub hidden: bool,
+
+ /// whether this workspace needs to be hidden
+ pub needs_hidden: bool,
}
#[derive(Debug, Clone)]
@@ -252,6 +258,9 @@ impl<W: LayoutElement> Workspace<W> {
let shadow_config =
compute_workspace_shadow_config(options.overview.workspace_shadow, view_size);
+ let is_hidden = config
+ .as_mut()
+ .is_some_and(|c| c.hidden.is_some_and(|hidden| hidden));
Self {
scrolling,
@@ -268,6 +277,8 @@ impl<W: LayoutElement> Workspace<W> {
clock,
base_options,
options,
+ hidden: is_hidden,
+ needs_hidden: false,
name: config.map(|c| c.name.0),
layout_config,
id: WorkspaceId::next(),
@@ -317,6 +328,10 @@ impl<W: LayoutElement> Workspace<W> {
let shadow_config =
compute_workspace_shadow_config(options.overview.workspace_shadow, view_size);
+ let is_hidden = config
+ .as_mut()
+ .is_some_and(|c| c.hidden.is_some_and(|hidden| hidden));
+
Self {
scrolling,
floating,
@@ -332,6 +347,8 @@ impl<W: LayoutElement> Workspace<W> {
clock,
base_options,
options,
+ hidden: is_hidden,
+ needs_hidden: false,
name: config.map(|c| c.name.0),
layout_config,
id: WorkspaceId::next(),
@@ -523,7 +540,9 @@ impl<W: LayoutElement> Workspace<W> {
}
pub fn update_output_size(&mut self) {
- let output = self.output.as_ref().unwrap();
+ let Some(output) = self.output.as_ref() else {
+ return;
+ };
let scale = output.current_scale();
let transform = output.current_transform();
let view_size = output_size(output);
diff --git a/src/protocols/ext_workspace.rs b/src/protocols/ext_workspace.rs
index 3d97cc4f..8b3b7d7e 100644
--- a/src/protocols/ext_workspace.rs
+++ b/src/protocols/ext_workspace.rs
@@ -92,7 +92,9 @@ pub fn refresh(state: &mut State) {
let mut seen_workspaces = HashMap::new();
for (mon, _, ws) in state.niri.layout.workspaces() {
let output = mon.map(|mon| mon.output());
- seen_workspaces.insert(ws.id(), output);
+ if !ws.hidden {
+ seen_workspaces.insert(ws.id(), output);
+ }
}
protocol_state.workspaces.retain(|id, workspace| {
@@ -133,6 +135,9 @@ pub fn refresh(state: &mut State) {
// Update existing workspaces and create new ones.
for (mon, ws_idx, ws) in state.niri.layout.workspaces() {
+ if ws.hidden {
+ continue;
+ }
changed |= refresh_workspace(protocol_state, mon, ws_idx, ws);
}
diff --git a/src/ui/mru.rs b/src/ui/mru.rs
index d8ec6de1..6b467e43 100644
--- a/src/ui/mru.rs
+++ b/src/ui/mru.rs
@@ -582,6 +582,10 @@ impl WindowMru {
let config = niri.config.borrow().recent_windows.previews;
let mut thumbnails = Vec::new();
for (mon, ws_idx, ws) in niri.layout.workspaces() {
+ if ws.hidden {
+ continue;
+ }
+
let mon = mon.expect("an active output exists so all workspaces have a monitor");
let on_current_output = mon.output() == output;
let on_current_workspace = on_current_output && mon.active_workspace_idx() == ws_idx;
8.7. Niri patch to get events for hidden workspaces
diff --git a/niri-ipc/src/state.rs b/niri-ipc/src/state.rs
index b603dfc6..230a24cc 100644
--- a/niri-ipc/src/state.rs
+++ b/niri-ipc/src/state.rs
@@ -118,7 +118,12 @@ impl EventStreamStatePart for EventStreamState {
impl EventStreamStatePart for WorkspacesState {
fn replicate(&self) -> Vec<Event> {
- let workspaces = self.workspaces.values().cloned().collect();
+ let workspaces = self
+ .workspaces
+ .values()
+ .filter(|ws| !ws.is_hidden)
+ .cloned()
+ .collect();
vec![Event::WorkspacesChanged { workspaces }]
}
8.8. Niri patch to keep gestures out of hidden workspaces
diff --git a/src/layout/monitor.rs b/src/layout/monitor.rs
index 30bb888..352f006 100644
--- a/src/layout/monitor.rs
+++ b/src/layout/monitor.rs
@@ -444,6 +444,13 @@ impl<W: LayoutElement> Monitor<W> {
self.add_workspace_at(0);
}
+ fn visible_workspace_count(&self) -> usize {
+ self.workspaces
+ .iter()
+ .position(|ws| ws.hidden)
+ .unwrap_or(self.workspaces.len())
+ }
+
pub fn add_workspace_bottom(&mut self) {
// The bottom of the visible region; hidden workspaces stay past it.
let visible_end = self
@@ -1255,7 +1262,7 @@ impl<W: LayoutElement> Monitor<W> {
Some(WorkspaceSwitch::Gesture(gesture)) if gesture.dnd_last_event_time.is_some() => {
let current = gesture.current_idx;
let new = current.ceil() - 1.;
- new.clamp(0., (self.workspaces.len() - 1) as f64) as usize
+ new.clamp(0., (self.visible_workspace_count() - 1) as f64) as usize
}
// If the workspace is hidden, we shouldn't switch to it.
_ => {
@@ -1290,7 +1297,7 @@ impl<W: LayoutElement> Monitor<W> {
Some(WorkspaceSwitch::Gesture(gesture)) if gesture.dnd_last_event_time.is_some() => {
let current = gesture.current_idx;
let new = current.floor() + 1.;
- new.clamp(0., (self.workspaces.len() - 1) as f64) as usize
+ new.clamp(0., (self.visible_workspace_count() - 1) as f64) as usize
}
// If the workspace is hidden, we shouldn't switch to it.
// Instead we need to bump the workspace down
@@ -2184,6 +2191,8 @@ impl<W: LayoutElement> Monitor<W> {
timestamp: Duration,
is_touchpad: bool,
) -> Option<bool> {
+ let visible_count = self.visible_workspace_count();
+
let Some(WorkspaceSwitch::Gesture(gesture)) = &self.workspace_switch else {
return None;
};
@@ -2218,7 +2227,7 @@ impl<W: LayoutElement> Monitor<W> {
let pos = gesture.tracker.pos() / total_height;
- let (min, max) = gesture.min_max(self.workspaces.len());
+ let (min, max) = gesture.min_max(visible_count);
let new_idx = gesture.start_idx + pos;
let new_idx = rubber_band.clamp(min, max, new_idx);
@@ -2232,6 +2241,7 @@ impl<W: LayoutElement> Monitor<W> {
pub fn dnd_scroll_gesture_scroll(&mut self, pos: Point<f64, Logical>, speed: f64) -> bool {
let zoom = self.overview_zoom();
+ let visible_count = self.visible_workspace_count();
let Some(WorkspaceSwitch::Gesture(gesture)) = &mut self.workspace_switch else {
return false;
@@ -2305,7 +2315,7 @@ impl<W: LayoutElement> Monitor<W> {
let pos = gesture.tracker.pos() / total_height;
let unclamped = gesture.start_idx + pos;
- let (min, max) = gesture.min_max(self.workspaces.len());
+ let (min, max) = gesture.min_max(visible_count);
let clamped = unclamped.clamp(min, max);
// Make sure that DnD scrolling too much outside the min/max does not "build up".
@@ -2316,6 +2326,8 @@ impl<W: LayoutElement> Monitor<W> {
}
pub fn workspace_switch_gesture_end(&mut self, is_touchpad: Option<bool>) -> bool {
+ let visible_count = self.visible_workspace_count();
+
let Some(WorkspaceSwitch::Gesture(gesture)) = &self.workspace_switch else {
return false;
};
@@ -2348,7 +2360,7 @@ impl<W: LayoutElement> Monitor<W> {
let current_pos = gesture.tracker.pos() / total_height;
let pos = gesture.tracker.projected_end_pos() / total_height;
- let (min, max) = gesture.min_max(self.workspaces.len());
+ let (min, max) = gesture.min_max(visible_count);
let new_idx = gesture.start_idx + pos;
let new_idx = new_idx.clamp(min, max);
diff --git a/src/layout/tests.rs b/src/layout/tests.rs
index 9450f1a..6bc7cd5 100644
--- a/src/layout/tests.rs
+++ b/src/layout/tests.rs
@@ -2842,6 +2842,51 @@ fn hidden_workspaces_are_not_rendered() {
.all(|(ws, _)| !ws.hidden));
}
+#[test]
+fn workspace_switch_gesture_stops_at_hidden_block() {
+ let ops = [
+ Op::AddOutput(1),
+ Op::AddWindow {
+ params: TestWindowParams::new(1),
+ },
+ Op::SetWorkspaceName {
+ new_ws_name: 1,
+ ws_name: None,
+ },
+ Op::FocusWorkspaceDown,
+ Op::AddWindow {
+ params: TestWindowParams::new(2),
+ },
+ Op::ToggleWorkspaceVisibility(1),
+ Op::FocusWorkspaceDown,
+ Op::WorkspaceSwitchGestureBegin {
+ output_idx: 1,
+ is_touchpad: true,
+ },
+ Op::WorkspaceSwitchGestureUpdate {
+ delta: 400.,
+ timestamp: Duration::from_millis(10),
+ is_touchpad: true,
+ },
+ Op::WorkspaceSwitchGestureUpdate {
+ delta: 400.,
+ timestamp: Duration::from_millis(20),
+ is_touchpad: true,
+ },
+ Op::WorkspaceSwitchGestureEnd {
+ is_touchpad: Some(true),
+ },
+ ];
+ let mut layout = check_ops(ops);
+
+ let monitor = match &mut layout.monitor_set {
+ MonitorSet::Normal { monitors, .. } => &mut monitors[0],
+ MonitorSet::NoOutputs { .. } => unreachable!(),
+ };
+ assert_eq!(monitor.active_workspace_idx, 1);
+ assert!(!monitor.workspaces[monitor.active_workspace_idx].hidden);
+}
+
#[test]
fn large_negative_height_change() {
let ops = [
8.9. Niri patch to allow actions to target workspaces under the cursor
diff --git a/niri-config/src/binds.rs b/niri-config/src/binds.rs
index c5b4e6f..fcfc8cc 100644
--- a/niri-config/src/binds.rs
+++ b/niri-config/src/binds.rs
@@ -187,10 +187,8 @@ pub enum Action {
CenterWindowById(u64),
CenterVisibleColumns,
FocusWorkspaceDown,
- #[knuffel(skip)]
FocusWorkspaceDownUnderMouse,
FocusWorkspaceUp,
- #[knuffel(skip)]
FocusWorkspaceUpUnderMouse,
FocusWorkspace(#[knuffel(argument)] WorkspaceReference),
FocusWorkspacePrevious,
8.10. Firezone-GUI patch to fix state loop
--- a/rust/gui-client/src-frontend/components/App.tsx
+++ b/rust/gui-client/src-frontend/components/App.tsx
@@ -92,7 +92,7 @@
advancedSettingsChangedUnlisten.then((unlistenFn) => unlistenFn());
logsRecountedUnlisten.then((unlistenFn) => unlistenFn());
};
- }, [location, handleClick]);
+ }, []);
const isDev = import.meta.env.DEV;
8.11. nginx-otel patch for c++20
From e3b6c98b1556e4c82cec39acc7be91a62449fa84 Mon Sep 17 00:00:00 2001
From: Aleksei Bavshin <a.bavshin@f5.com>
Date: Mon, 30 Mar 2026 14:59:33 -0700
Subject: [PATCH] Fix build with C++20.
OpenTelemetry SDK built with C++20 uses std::span in the API, and we
want to match the standard to avoid type changes at the API boundary.
However, std::span constructor is explicit for non-default Extent,
requiring us to use a more verbose specification instead of an
initializer list.
---
src/http_module.cpp | 6 ++++--
src/trace_context.hpp | 7 +++++--
2 files changed, 9 insertions(+), 4 deletions(-)
diff --git a/src/http_module.cpp b/src/http_module.cpp
index 78a5e896..1ccfece9 100644
--- a/src/http_module.cpp
+++ b/src/http_module.cpp
@@ -859,6 +859,8 @@ template <class Id>
ngx_int_t hexIdVar(ngx_http_request_t* r, ngx_http_variable_value_t* v,
uintptr_t data)
{
+ namespace nostd = opentelemetry::nostd;
+
auto ctx = ensureOtelCtx(r);
if (!ctx) {
return NGX_ERROR;
@@ -867,13 +869,13 @@ ngx_int_t hexIdVar(ngx_http_request_t* r, ngx_http_variable_value_t* v,
auto id = (Id*)((char*)ctx + data);
if (id->IsValid()) {
- auto size = id->Id().size() * 2;
+ constexpr auto size = 2 * Id::kSize;
auto buf = (char*)ngx_pnalloc(r->pool, size);
if (buf == NULL) {
return NGX_ERROR;
}
- id->ToLowerBase16({buf, size});
+ id->ToLowerBase16(nostd::span<char, size>{buf, size});
v->len = size;
v->valid = 1;
diff --git a/src/trace_context.hpp b/src/trace_context.hpp
index 2d9c266d..62ae0390 100644
--- a/src/trace_context.hpp
+++ b/src/trace_context.hpp
@@ -67,16 +67,19 @@ struct TraceContext {
static void serialize(const TraceContext& tc, char* out)
{
using namespace opentelemetry::trace::propagation;
+ namespace nostd = opentelemetry::nostd;
*out++ = '0';
*out++ = '0';
*out++ = '-';
- tc.traceId.ToLowerBase16({out, kTraceIdSize});
+ tc.traceId.ToLowerBase16(
+ nostd::span<char, kTraceIdSize>{out, kTraceIdSize});
out += kTraceIdSize;
*out++ = '-';
- tc.spanId.ToLowerBase16({out, kSpanIdSize});
+ tc.spanId.ToLowerBase16(
+ nostd::span<char, kSpanIdSize>{out, kSpanIdSize});
out += kSpanIdSize;
*out++ = '-';
8.12. Default Flake Template
{
description = "name";
inputs = {
flake-parts = {
inputs.nixpkgs-lib.follows = "nixpkgs";
url = "github:hercules-ci/flake-parts";
};
git-hooks-nix = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:cachix/git-hooks.nix";
};
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
pedantix = {
inputs = {
flake-parts.follows = "flake-parts";
git-hooks-nix.follows = "git-hooks-nix";
nixpkgs.follows = "nixpkgs";
treefmt-nix.follows = "treefmt-nix";
};
url = "github:Swarsel/pedantix";
};
treefmt-nix = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:numtide/treefmt-nix";
};
};
outputs =
inputs:
inputs.flake-parts.lib.mkFlake { inherit inputs; } {
imports = [
inputs.git-hooks-nix.flakeModule
inputs.pedantix.flakeModules.default
inputs.treefmt-nix.flakeModule
];
perSystem =
{ config, pkgs, ... }:
{
devShells.default = pkgs.mkShell {
inputsFrom = [ config.treefmt.build.devShell ];
packages = [ pkgs.nixd ];
shellHook = config.pre-commit.installationScript;
};
pre-commit.settings.hooks = {
deadnix.enable = true;
statix.enable = true;
treefmt.enable = true;
};
treefmt.programs.pedantix.enable = true;
};
systems = [
"x86_64-linux"
"aarch64-linux"
];
};
}
8.13. Go Flake Template
{
description = "name";
inputs = {
flake-parts = {
inputs.nixpkgs-lib.follows = "nixpkgs";
url = "github:hercules-ci/flake-parts";
};
git-hooks-nix = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:cachix/git-hooks.nix";
};
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
pedantix = {
inputs = {
flake-parts.follows = "flake-parts";
git-hooks-nix.follows = "git-hooks-nix";
nixpkgs.follows = "nixpkgs";
treefmt-nix.follows = "treefmt-nix";
};
url = "github:Swarsel/pedantix";
};
treefmt-nix = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:numtide/treefmt-nix";
};
};
outputs =
inputs:
inputs.flake-parts.lib.mkFlake { inherit inputs; } {
imports = [
inputs.git-hooks-nix.flakeModule
inputs.pedantix.flakeModules.default
inputs.treefmt-nix.flakeModule
];
perSystem =
{
config,
lib,
pkgs,
self',
...
}:
{
devShells.default = pkgs.mkShell {
inputsFrom = [
self'.packages.default
config.treefmt.build.devShell
];
packages = with pkgs; [
delve
gopls
];
shellHook = config.pre-commit.installationScript;
};
packages.default =
let
name = baseNameOf (lib.head (builtins.match "module ([^\n]+)\n.*" (builtins.readFile ./go.mod)));
in
pkgs.buildGoModule {
pname = name;
src = lib.fileset.toSource {
fileset = lib.fileset.unions [
./go.mod
(lib.fileset.fileFilter (file: file.hasExt "go") ./.)
];
root = ./.;
};
vendorHash = null;
version = "0.1.0";
meta.mainProgram = name;
};
pre-commit.settings.hooks = {
deadnix.enable = true;
statix.enable = true;
treefmt.enable = true;
};
treefmt.programs = {
gofmt.enable = true;
pedantix.enable = true;
};
};
systems = [
"x86_64-linux"
"aarch64-linux"
];
};
}
8.14. LaTeX Flake Template
{
description = "name";
inputs = {
flake-parts = {
inputs.nixpkgs-lib.follows = "nixpkgs";
url = "github:hercules-ci/flake-parts";
};
git-hooks-nix = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:cachix/git-hooks.nix";
};
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
pedantix = {
inputs = {
flake-parts.follows = "flake-parts";
git-hooks-nix.follows = "git-hooks-nix";
nixpkgs.follows = "nixpkgs";
treefmt-nix.follows = "treefmt-nix";
};
url = "github:Swarsel/pedantix";
};
treefmt-nix = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:numtide/treefmt-nix";
};
};
outputs =
inputs:
inputs.flake-parts.lib.mkFlake { inherit inputs; } {
imports = [
inputs.git-hooks-nix.flakeModule
inputs.pedantix.flakeModules.default
inputs.treefmt-nix.flakeModule
];
perSystem =
{
config,
pkgs,
self',
...
}:
{
devShells.default = pkgs.mkShell {
inputsFrom = [
self'.packages.default
config.treefmt.build.devShell
];
packages = [ pkgs.texlab ];
shellHook = config.pre-commit.installationScript;
};
packages.default = pkgs.stdenvNoCC.mkDerivation {
buildPhase = ''
runHook preBuild
export TEXMFHOME=$PWD/.cache TEXMFVAR=$PWD/.cache/var
latexmk -interaction=nonstopmode -pretex='\pdfvariable suppressoptionalinfo 512\relax' -usepretex
runHook postBuild
'';
env.SOURCE_DATE_EPOCH = toString inputs.self.lastModified;
installPhase = ''
install -Dm644 main.pdf $out
'';
name = "document.pdf";
nativeBuildInputs = [
pkgs.python3Packages.pygments
(pkgs.texliveMedium.withPackages (
ps: with ps; [
biber
biblatex
catchfile
cleveref
comment
csquotes
dejavu
environ
footmisc
framed
fvextra
latexmk
ltablex
makecell
minted
multirow
tabu
threeparttable
threeparttablex
titlesec
upquote
wrapfig
xltabular
xstring
]
))
];
src = ./.;
};
pre-commit.settings.hooks = {
deadnix.enable = true;
statix.enable = true;
treefmt.enable = true;
};
treefmt.programs.pedantix.enable = true;
};
systems = [
"x86_64-linux"
"aarch64-linux"
];
};
}
8.15. Python Flake Template
{
description = "name";
inputs = {
flake-parts = {
inputs.nixpkgs-lib.follows = "nixpkgs";
url = "github:hercules-ci/flake-parts";
};
git-hooks-nix = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:cachix/git-hooks.nix";
};
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
pedantix = {
inputs = {
flake-parts.follows = "flake-parts";
git-hooks-nix.follows = "git-hooks-nix";
nixpkgs.follows = "nixpkgs";
treefmt-nix.follows = "treefmt-nix";
};
url = "github:Swarsel/pedantix";
};
pyproject-build-systems = {
inputs = {
nixpkgs.follows = "nixpkgs";
pyproject-nix.follows = "pyproject-nix";
uv2nix.follows = "uv2nix";
};
url = "github:pyproject-nix/build-system-pkgs";
};
pyproject-nix = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:pyproject-nix/pyproject.nix";
};
treefmt-nix = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:numtide/treefmt-nix";
};
uv2nix = {
inputs = {
nixpkgs.follows = "nixpkgs";
pyproject-nix.follows = "pyproject-nix";
};
url = "github:pyproject-nix/uv2nix";
};
};
outputs =
inputs:
inputs.flake-parts.lib.mkFlake { inherit inputs; } {
imports = [
inputs.git-hooks-nix.flakeModule
inputs.pedantix.flakeModules.default
inputs.treefmt-nix.flakeModule
];
perSystem =
{
config,
lib,
pkgs,
...
}:
let
inherit ((lib.importTOML ./pyproject.toml).project) name;
workspace = inputs.uv2nix.lib.workspace.loadWorkspace { workspaceRoot = ./.; };
pythonSet =
(pkgs.callPackage inputs.pyproject-nix.build.packages { python = pkgs.python3; }).overrideScope
(
lib.composeManyExtensions [
inputs.pyproject-build-systems.overlays.default
(workspace.mkPyprojectOverlay { sourcePreference = "wheel"; })
]
);
editableSet = pythonSet.overrideScope (
workspace.mkEditablePyprojectOverlay { root = "$REPO_ROOT"; }
);
in
{
devShells.default = pkgs.mkShell {
env = {
UV_NO_SYNC = "1";
UV_PYTHON_DOWNLOADS = "never";
};
inputsFrom = [ config.treefmt.build.devShell ];
packages = [
(editableSet.mkVirtualEnv "${name}-dev-env" workspace.deps.all)
pkgs.basedpyright
pkgs.uv
];
shellHook = ''
unset PYTHONPATH
export REPO_ROOT=$(git rev-parse --show-toplevel)
${config.pre-commit.installationScript}
'';
};
packages.default = lib.addMetaAttrs { mainProgram = name; } (
pythonSet.mkVirtualEnv "${name}-env" workspace.deps.default
);
pre-commit.settings.hooks = {
deadnix.enable = true;
statix.enable = true;
treefmt.enable = true;
};
treefmt.programs = {
pedantix.enable = true;
ruff-check.enable = true;
ruff-format.enable = true;
};
};
systems = [
"x86_64-linux"
"aarch64-linux"
];
};
}
8.16. Rust Flake Template
{
description = "name";
inputs = {
flake-parts = {
inputs.nixpkgs-lib.follows = "nixpkgs";
url = "github:hercules-ci/flake-parts";
};
git-hooks-nix = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:cachix/git-hooks.nix";
};
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
pedantix = {
inputs = {
flake-parts.follows = "flake-parts";
git-hooks-nix.follows = "git-hooks-nix";
nixpkgs.follows = "nixpkgs";
treefmt-nix.follows = "treefmt-nix";
};
url = "github:Swarsel/pedantix";
};
treefmt-nix = {
inputs.nixpkgs.follows = "nixpkgs";
url = "github:numtide/treefmt-nix";
};
};
outputs =
inputs:
inputs.flake-parts.lib.mkFlake { inherit inputs; } {
imports = [
inputs.git-hooks-nix.flakeModule
inputs.pedantix.flakeModules.default
inputs.treefmt-nix.flakeModule
];
perSystem =
{
config,
lib,
pkgs,
self',
...
}:
{
devShells.default = pkgs.mkShell {
inputsFrom = [
self'.packages.default
config.treefmt.build.devShell
];
packages = with pkgs; [
clippy
gdb
rust-analyzer
];
shellHook = config.pre-commit.installationScript;
};
packages.default =
let
manifest = (lib.importTOML ./Cargo.toml).package;
in
pkgs.rustPlatform.buildRustPackage {
inherit (manifest) version;
cargoLock.lockFile = ./Cargo.lock;
pname = manifest.name;
src = lib.fileset.toSource {
fileset = lib.fileset.unions [
./Cargo.toml
./Cargo.lock
./src
];
root = ./.;
};
meta.mainProgram = manifest.name;
};
pre-commit.settings = {
hooks = {
clippy.enable = true;
deadnix.enable = true;
statix.enable = true;
treefmt.enable = true;
};
settings.rust = {
cargoManifestPath = "./Cargo.toml";
check.cargoDeps = pkgs.rustPlatform.importCargoLock { lockFile = ./Cargo.lock; };
};
};
treefmt.programs = {
pedantix.enable = true;
rustfmt.enable = true;
taplo.enable = true;
};
};
systems = [
"x86_64-linux"
"aarch64-linux"
];
};
}
8.17. GitHub README
Here lies defined the README for GitHub and Forgejo:
<h1 id="header" align="center">
<img width="150" height="140" alt="nixos logo using earthbound giant step icon" src="https://github.com/Swarsel/.dotfiles/blob/main/files/icons/logo.svg" />
<br>
  
~SwarselSystems~
<sup><sub><sup><sub><i>(née .dotfiles)</i></sub></sup></sub></sup>
</h1>
<p align="center">
<i>"With NixOS, your <a href="https://github.com/user-attachments/assets/58742580-fb02-4b51-978a-364f5df1ddbd">entire system</a> is just one file: <code>/etc/nixos/configuration.nix</code>!"</i><br>
... I took that <i><a href="https://swarsel.github.io/.dotfiles/">literally</a></i>.
</p>
<p align="center">
<img width="49%" alt="screenshot showing emacs and glide" src="https://github.com/user-attachments/assets/3e5874be-ab3a-4cc5-88aa-28a8032799a7" />
<img width="49%" alt="screenshot showing fastfetch and music player" src="https://github.com/user-attachments/assets/1a329b72-d404-49cb-8873-4de6a684d1cf" />
<img width="49%" alt="screenshot showing noctalia bar" src="https://github.com/user-attachments/assets/394ff2ca-859b-4886-9125-2cf64d68f2ea" />
<img width="49%" alt="screenshot showing wallpaper" src="https://github.com/user-attachments/assets/824a4fab-5d47-4468-859d-d59f9e0982c5" />
</p>
<h2 id="header" align="left">
Overview <img height="24" align="right" alt="ness" src="https://github.com/Swarsel/.dotfiles/blob/main/files/icons/ness.png" />
</h2>
- [Literate configuration](https://swarsel.github.io/.dotfiles/) defining my entire infrastructure, including Emacs
- Dendritic configuration based on flakes (using flake-file) for personal hosts as well as servers on:
- [NixOS](https://github.com/NixOS/nixpkgs)
- [home-manager](https://github.com/nix-community/home-manager) only (no full NixOS) with support from [nixGL](https://github.com/nix-community/nixGL)
- [nix-darwin](https://github.com/LnL7/nix-darwin)
- [nix-on-droid](https://github.com/nix-community/nix-on-droid)
- Streamlined configuration and deployment pipeline:
- Framework for [packages](https://github.com/Swarsel/.dotfiles/blob/main/modules/flake/packages.nix), [overlays](https://github.com/Swarsel/.dotfiles/blob/main/modules/flake/overlays.nix), [dendritic modules (features)](https://github.com/Swarsel/.dotfiles/tree/main/modules), and [library functions](https://github.com/Swarsel/.dotfiles/blob/main/modules/flake/lib.nix)
- Dynamically generated config:
- host configurations
- dns records
- network setup (+ WireGuard mesh on systemd-networkd)
- Remote Builders for `[x86_64,aarch64]-linux` running on Buildbot, feeding a private nix binary cache and updating the flake on a weekly basis
- Fully autonomous remote deployment using [nixos-anywhere](https://github.com/nix-community/nixos-anywhere) and [disko](https://github.com/nix-community/disko) (with secrets handling)
- Improved nix tooling
- Support for advanced features:
- Secrets handling using [sops-nix](https://github.com/Mic92/sops-nix) (pls no pwn ❤️)
- Management of personally identifiable information at evaluation time through [piix](https://github.com/Swarsel/piix)
- Full Yubikey support (with SSH support for SK keys, certs and PGP keys)
- LUKS-encryption with support for remote disk unlock over SSH
- Secure boot using [Lanzaboote](https://github.com/nix-community/lanzaboote)
- BTRFS-based [Impermanence](https://github.com/nix-community/impermanence)
- Configuration shared between configurations (configuration for one nixosConfiguration can be defined in another nixosConfiguration)
- Global attributes shared between all configurations to reduce attribute re-declaration
- [Config library](https://github.com/Swarsel/.dotfiles/blob/9acfc5f93457ec14773cc0616cab616917cc8af5/modules/shared/config-lib.nix#L4) for defining config-based functions for generating service information
- Reduced friction between full NixOS- and home-manager-only deployments
- efficient secrets handling depending on system context
- automatic config sharing between contexts
- dendritic structure for keeping features in a centralized manner
<h2 id="header" align="left">
Infrastructure <img height="24" align="right" alt="paula" src="https://github.com/Swarsel/.dotfiles/blob/main/files/icons/paula.png" />
</h2>
<details>
<summary>Click here for a summary of my infrastructure</summary>
<img alt="full topology diagram" src="https://github.com/Swarsel/.dotfiles/blob/main/files/topology/topology.png" />
### Programs
| Topic | Program |
|-----------------|-------------------------------------|
| ⛩️ **Bar** | [Noctalia Shell][] |
| ✒️ **Editor** | [Emacs][] |
| 🌐 **Browser** | [Glide][] |
| 🎨 **Theme** | [City-Lights (managed by stylix)][] |
| 🐚 **Shell** | [zsh][] |
| 🖥️ **Terminal** | [Kitty][] |
| 🚀 **Launcher** | [Noctalia Shell][] |
| 🚨 **Alerts** | [Noctalia Shell][] |
| 🚪 **DM** | [greetd][] |
| 🪟 **WM** | [Niri][] |
[Noctalia Shell]: https://github.com/Swarsel/.dotfiles/tree/main/modules/client/programs/noctalia.nix
[Emacs]: https://swarsel.github.io/.dotfiles/emacs/init.el.html
[Glide]: https://github.com/Swarsel/.dotfiles/tree/main/modules/client/programs/glide.nix
[City-Lights (managed by stylix)]: https://github.com/Swarsel/.dotfiles/tree/main/modules/client/programs/stylix.nix
[zsh]: https://github.com/Swarsel/.dotfiles/tree/main/modules/client/programs/zsh.nix
[Kitty]: https://github.com/Swarsel/.dotfiles/tree/main/modules/client/programs/kitty.nix
[greetd]: https://github.com/Swarsel/.dotfiles/tree/main/modules/client/system/login.nix
[Niri]: https://github.com/Swarsel/.dotfiles/tree/main/modules/client/programs/niri.nix
### Services
| Topic | Program |
|------------------------------|-----------------------------------------------------------------------------------------|
| ☁️ **S3** | [Garage][] |
| ⚓ **Anki Sync** | [Anki Sync Server][] |
| ⛏️ **Minecraft** | [Minecraft][] |
| ✂️ **Paste Tool** | [Microbin][] |
| ✉️ **Mail** | [simple-nixos-mailserver][] |
| 🃏 **Collections** | [Koillection][] |
| 🌳 **Git** | [Forgejo][] |
| 🍴 **RSS** | [FreshRss][] |
| 🍽️ **Recipes** | [Mealie][] |
| 🎞️ **Photos** | [Immich][] |
| 🎧 **Audiobooks** | [Audiobookshelf][] |
| 🎵 **Music** | [Navidrome][] + [Spotifyd][] + [MPD][] |
| 🎼 **Music Downloader** | [Yubal][] |
| 🐙 **Nix Build farm** | [Buildbot][] |
| 🐝 **Home Automation** | [Home Assistant][] + [Zigbee2MQTT][] + [Mosquitto][] |
| 🐽 **Threat Detection** | [CrowdSec][] |
| 👀 **DNS Records** | [Knot][] |
| 👁️ **Monitoring** | [Grafana][] + [Mimir][] + [Loki][] + [Tempo][] + [Alloy][] + [Pyroscope][] + [Gotify][] |
| 💸 **Finance** | [Firefly-III][] + [Spliit][] |
| 💾 **Backups** | [Restic][] |
| 📁 **Filesharing** | [Nextcloud][] + [CopyParty][] + [Croc][]. Also [slskd][], [transmission + friends][] |
| 📄 **Documents** | [Paperless][] |
| 📅 **CalDav/CardDav** | [Radicale][] |
| 📖 **Books** | [Kavita][] |
| 📚 **Bookmarks** | [Readeck][] |
| 📝 **Office Suite** | [Collabora Online][] + [Filestash][] |
| 📋 **Forms** | [OpnForm][] |
| 📸 **Image Sharing** | [Slink][] |
| 📹 **Video Downloader** | [MeTube][] |
| 📺 **Video Streaming** | [Invidious][] + [Invidious Companion][] |
| 📼 **Videos** | [Jellyfin][] |
| 🔄 **File Sync** | [Syncthing][] |
| 🚀 **Speedtest** | [LibreSpeed][] |
| 🔎 **Search Engine** | [SearXNG][] |
| 🔑 **Cert-based SSH** | [OPKSSH][] |
| 🔗 **Link Shortener** | [Shlink][] |
| 🔨 **Home Asset Management** | [Homebox][] |
| 🕸️ **Nix Binary Cache** | [Attic][] |
| 🗃️ **Shell History** | [Atuin][] |
| 🗨️ **Messaging** | [Matrix][] |
| 🗺️ **Location History** | [Dawarich][] |
| 🚇 **VPN Access** | [Firezone][] |
| 🛎️ **DHCP** | [Kea][] |
| 🛡️ **Local DNS Resolver** | [AdGuard Home][] |
| 🦊 **Firefox Sync** | [Firefox-Syncserver][] |
| **Second Hand Site Info** | [Shopservatory][] + [Socks Proxy][] |
| 🪪 **SSO** | [Kanidm][] + [oauth2-proxy][] |
[Garage]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/garage.nix
[Anki Sync Server]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/ankisync.nix
[Minecraft]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/minecraft.nix
[Microbin]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/microbin.nix
[simple-nixos-mailserver]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/mailserver.nix
[Koillection]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/koillection.nix
[Forgejo]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/forgejo.nix
[FreshRss]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/freshrss.nix
[Mealie]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/mealie.nix
[Immich]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/immich.nix
[Audiobookshelf]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/audiobookshelf.nix
[Navidrome]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/navidrome.nix
[Spotifyd]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/spotifyd.nix
[MPD]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/mpd.nix
[Yubal]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/yubal.nix
[Buildbot]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/buildbot.nix
[Home Assistant]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/home-assistant.nix
[Zigbee2MQTT]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/zigbee2mqtt.nix
[Mosquitto]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/mosquitto.nix
[CrowdSec]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/crowdsec.nix
[Knot]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/knot.nix
[Grafana]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/grafana.nix
[Mimir]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/mimir.nix
[Loki]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/loki.nix
[Tempo]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/tempo.nix
[Alloy]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/alloy.nix
[Pyroscope]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/pyroscope.nix
[Gotify]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/gotify.nix
[Firefly-III]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/firefly-iii.nix
[Spliit]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/spliit.nix
[Restic]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/restic.nix
[Nextcloud]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/nextcloud.nix
[CopyParty]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/copyparty.nix
[Croc]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/croc.nix
[slskd]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/slskd.nix
[transmission + friends]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/transmission.nix
[Paperless]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/paperless.nix
[Radicale]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/radicale.nix
[Kavita]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/kavita.nix
[Readeck]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/readeck.nix
[Collabora Online]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/collabora-online.nix
[Filestash]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/filestash.nix
[OpnForm]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/opnform.nix
[Slink]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/slink.nix
[MeTube]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/metube.nix
[Invidious]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/invidious.nix
[Invidious Companion]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/invidious-companion.nix
[Jellyfin]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/jellyfin.nix
[Syncthing]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/syncthing.nix
[LibreSpeed]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/librespeed.nix
[SearXNG]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/searx.nix
[OPKSSH]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/opkssh.nix
[Shlink]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/shlink.nix
[Homebox]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/homebox.nix
[Attic]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/attic.nix
[Atuin]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/atuin.nix
[Matrix]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/matrix.nix
[Dawarich]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/dawarich.nix
[Firezone]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/firezone.nix
[Kea]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/kea.nix
[AdGuard Home]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/adguardhome.nix
[Firefox-Syncserver]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/firefox-syncserver.nix
[Shopservatory]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/shopservatory.nix
[Socks Proxy]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/services/socks-proxy.nix
[Kanidm]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/kanidm.nix
[oauth2-proxy]: https://github.com/Swarsel/.dotfiles/tree/main/modules/server/infra/oauth2-proxy.nix
### Hosts
| Name | Hardware | Use |
|-----------------------|--------------------------------------------------|---------------------------------|
| 💻 **bakery** | Lenovo Ideapad 720S-13IKB | Personal laptop |
| 💻 **pyramid** | Framework 16, AMD 7940HS, RX 7700S, 64GB RAM | Work laptop |
| 💻 **machpizza** | MacBook Pro 2016 | Alternative work laptop, MacOS |
| 🏠 **treehouse** | NVIDIA DGX Spark | AI sandbox, HM-only |
| 🖥️ **hintbooth** | HUNSN RM02, 8GB RAM | Router, home proxy/DNS |
| 🖥️ **summers** | ASUS Z10PA-D8, 2 Intel Xeon E5-2650 v4, 128G RAM | Main Homeserver, NAS |
| 🖥️ **winters** | ASRock J4105-ITX, 32GB RAM | IoT Homeserver, Wi-Fi(6) AP |
| ☁️ **belchsfactory** | 4 vCPUs, 24GB RAM | Remote Builder, nix cache |
| ☁️ **eagleland** | 2 vCPUs, 8GB RAM | Mailserver |
| ☁️ **liliputsteps** | 1 vCPUs, 8GB RAM | SSH bastion |
| ☁️ **moonside** | 4 vCPUs, 24GB RAM | Non-critical services |
| ☁️ **stoicclub** | 1 vCPUs, 8GB RAM | Authoritative DNS server |
| ☁️ **twothreetunnel** | 2 vCPUs, 8GB RAM | Web proxy |
| 🪟 **chaostheater** | Asus Z97-A, i7-4790k, GTX970, 32GB RAM | Game streaming (on AtlasOS) |
| 📱 **magicant** | Samsung Galaxy Z Flip 6 | Phone (nix-on-droid) |
| 💿 **brickroad** | - | Kexec tarball for low-mem hosts |
| 💿 **drugstore** | - | Installer ISO for new hosts |
| 💿 **policestation** | - | Live ISO for generating keys |
| ❔ **vacanthouse** | - | Staging environment |
</details>
<h2 id="header" align="left">
Documentation <img height="24" align="right" alt="jeff" src="https://github.com/Swarsel/.dotfiles/blob/main/files/icons/jeff.png" />
</h2>
The full documentation can be found here:
[SwarselSystems literate configuration](https://swarsel.github.io/.dotfiles/)
I went to great lengths in order to document the full design process of my infrastructure properly; the above document strives to serve as an introductory lecture to nix / NixOS while at the same time explaining the config in general.
### Emacs
If you came here for my raw Emacs configuration, the relevant files live here in elisp form (these files are generated from the nix `emacs-init` module):
- [early-init.el](https://swarsel.github.io/.dotfiles/emacs/early-init.el.html)
- [init.el](https://swarsel.github.io/.dotfiles/emacs/init.el.html)
### Deployment
<details>
<summary>Click here for deployment instructions</summary>
0) Fork this repo, and write your own host config at `hosts/nixos/<YOUR_ARCHITECTURE>/<YOUR_CONFIG_NAME>/default.nix`. At the very least, you should replace the `secrets/` directory with your own secrets and replace the SSH public keys with your own ones (otherwise I will come visit you!🔓❤️). I personally recommend to use the literate configuration and `org-babel-tangle-file` in Emacs, but you can also simply edit the separate `.nix` files.
1) Boot into a NixOS installer
2) Make sure that your Yubikey is plugged in or that you have your SSH key available (and configured)
3) Run `swarsel-bootstrap <CONFIGURATION_NAME> <TARGET_IP>` and follow the prompts
</details>
<h2 id="header" align="left">
Attributions <img height="24" align="right" alt="poo" src="https://github.com/Swarsel/.dotfiles/blob/main/files/icons/poo.png" />
</h2>
I would like to express my gratitude (not solely) to:
<details>
<summary>The people who help maintain <a href="https://github.com/orgs/NixOS/people">NixOS</a>, <a href="https://github.com/orgs/nix-community/people">nix-community</a>, and other nix-related projects.</summary>
</details>
<details>
<summary>The people who have inspired me with their configurations</summary>
- [theSuess](https://github.com/theSuess) with their [home-manager](https://code.kulupu.party/thesuess/home-manager)
- [hlissner](https://github.com/hlissner) with their [dotfiles](https://github.com/hlissner/dotfiles)
- [AntonHakansson](https://github.com/AntonHakansson) with their [nixos-config](https://github.com/AntonHakansson/nixos-config?tab=readme-ov-file)
- [EmergentMind](https://github.com/EmergentMind) with their [nix-config](https://github.com/EmergentMind/nix-config)
- [oddlama](https://github.com/oddlama) with their [nix-config](https://github.com/oddlama/nix-config)
</details>
If you feel that I forgot to pay you tribute for code that I used in this repository, please shoot me a message and I will fix it :)
<h2 id="header" align="left">
FAQ <img height="24" align="right" alt="king" src="https://github.com/Swarsel/.dotfiles/blob/main/files/icons/king.png" />
</h2>
Q: <i>How do I get started with nix?</i><br>
<details><summary>A: Click here for a small list of tips that should be helpful if you are new to the nix ecosystem</summary>
- Temporarily install any package using `nix shell nixpkgs#<PACKAGE_NAME>` - this can be e.g. useful if you accidentally removed home-manager from your packages on a non-NixOS machine.
- if you need multiple packages, you can do `nix shell nixpkgs#{<pkg1>,<pkg2>,<pkg3>}`.
- you can set `nix.registry` to add more flakes to your registry. I use this to add a `n` shorthand to `nixpkgs`, which allows me to do `nix shell n#{<pkg1>,<pkg2>,<pkg3>}`.
- Alternatively, use [comma](https://github.com/nix-community/comma)
- More info on `nix [...]` commands: https://nixos.org/manual/nix/stable/command-ref/new-cli/nix
- some examples:
- `nix flake update <input-name>` lets you update a specific input only.
- `nix repl <your flake path>` gives quick insight into your written configuration.
- `nix eval <your flake path>#<config attribute>` quickly returns an attribute in your written configuration
- `nix fmt` formats your flake using the formatter specified under `formatter` in your `flake.nix`
- When you are trying to setup a new configuration part, [GitHub code search](https://github.com/search?q=language%3ANix&type=code) can really help you to find a working configuration. Just filter for `.nix` files and the options you are trying to set up.
- getting packages at a different version than your target (or not packaged at all) can be done in most cases easily with fetchFromGithub (https://ryantm.github.io/nixpkgs/builders/fetchers/)
- you can easily install old revisions of packages using https://lazamar.co.uk/nix-versions/. You can conveniently spawn a shell with a chosen package available using `vershell <NIXPKGS_REVISION> <PACKAGE>`. Just make sure to pick a revision that has flakes enabled, otherwise you will need the legacy way of spawning the shell (see the link for more info)
- when developing modules in a dev branch of another flake, you can use `--override-input` to temporarily use the local directory as the flake source.
- including `nixosConfig ? config` in your module arguments is a smart way of enabling a module to pull in config from NixOS or home-manager config, no matter if it is a NixOS system or not.
- you can have a quick CLI evaluation for nix commands with e.g. `nixpgks.lib` available using `nix-instantiate --strict --eval --expr "let lib = import <nixpkgs/lib>; in <expression>"`.
- if you are looking for a specific library, `nix-locate` makes it easy to look for them.
- to look at the dependencies pulled in by a tool, use `nix-tree`
- to find out which derivation uses another derivation, use `nix store --query --referrers <derivation>`
- to get a neat overview of your config changes in recent generations, use `nix profile diff-closures --profile /nix/var/nix/profiles/system`
- to get instead the changes since the last boot, use `nix profile diff-closures /run/*-system`
- if you just need the generation numbers, use `sudo nix-env --list-generations --profile /nix/var/nix/profiles/system`
- to then switch to another generation, you can use `sudo nix-env --switch-generation <generation number> -p /nix/var/nix/profiles/system` followed by `sudo /nix/var/nix/profiles/system/bin/switch-to-configuration switch`
- These links are your best friends:
- The nix documentation: https://nix.dev/
- The nixpkgs reference manual: https://nixos.org/manual/nixpkgs/unstable/#buildpythonapplication-function
- the [nixpkgs repository](https://github.com/NixOS/nixpkgs) - especially useful to look at the various READMEs that are in various places in the repository (find using GitHub code search) as well as the [issues](https://github.com/Swarsel/.dotfiles/issues) and [PRs](https://github.com/Swarsel/.dotfiles/pulls) pages
- and the [nixpkgs Pull Request Tracker](https://nixpk.gs/pr-tracker.html)
- The NixOS manual: https://nixos.org/manual/nixos/stable/
- The NixOS package search: https://search.nixos.org/packages
- and the nix package version search: https://lazamar.co.uk/nix-versions/
- The NixOS option search https://search.nixos.org/options
- [mipmip](https://github.com/mipmip)'s home-manager option search: https://mipmip.github.io/home-manager-option-search/
- [Alan Pearce](https://alanpearce.eu/)'s `nix-darwin` search: https://searchix.alanpearce.eu/options/darwin/search (which supports all of the other versions as well :o)
- For the above, you can use the CLI tool [manix](https://github.com/mlvzk/manix)
- Nix function search: https://noogle.dev/
- Search for nix-community options: https://search.nüschtos.de/
- But that is not all:
- Some nix resources
- A tour of Nix: https://nixcloud.io/tour/
- The Nix One Pager: https://github.com/tazjin/nix-1p
- another one page introduction: https://learnxinyminutes.com/nix/
- a very short introduction to Nix features: https://zaynetro.com/explainix
- introductory nix article: https://medium.com/@MrJamesFisher/nix-by-example-a0063a1a4c55
- and another one: https://web.archive.org/web/20210121042658/https://ebzzry.io/en/nix/#nix
- How to learn nix: https://ianthehenry.com/posts/how-to-learn-nix/
- the Nix Cookbook: https://github.com/functionalops/nix-cookbook?tab=readme-ov-file
- and the Nix Pills: https://nixos.org/guides/nix-pills/
- Some resources on flakes
- Why to use flakes and introduction to flakes: https://www.tweag.io/blog/2020-05-25-flakes/
- The [NixOS & Flakes Book](https://nixos-and-flakes.thiscute.world/)
- and [Wombat's book](https://mhwombat.codeberg.page/nix-book/)
- as well as [Ekala's book](https://ekala-project.github.io/nix-book/)
- or the [Zero to Nix series](https://zero-to-nix.com/)
- last but not least, [NixOS in Production](https://leanpub.com/nixos-in-production)
- Practical nix flakes article: https://serokell.io/blog/practical-nix-flakes
- A bit on Overlays:
- Overview on overlays: [Mastering Nixpkgs overlays article](https://nixcademy.com/posts/mastering-nixpkgs-overlays-techniques-and-best-practice/)
- Some examples on best practices: [Do's and Don'ts of overlays](https://flyingcircus.io/news/detailsansicht/nixos-the-dos-and-donts-of-nixpkgs-overlays)
- Blog article about overrides: https://bobvanderlinden.me/customizing-packages-in-nix/#using-modified-packages
- Also useful is the [official NixOS Wiki](https://wiki.nixos.org/wiki/NixOS_Wiki)
- there is also the [unofficial NixOS Wiki](https://nixos.wiki/) that tends to be a bit outdated, use with care
- Some resources for specific nix tools:
- Flake output reference: https://nixos-and-flakes.thiscute.world/other-usage-of-flakes/outputs
- You can find public repositories with modules at https://nur.nix-community.org/ (you should check what you are installing however):
- I like to use this for rycee's Firefox extensions: https://nur.nix-community.org/repos/rycee/
- List of nerd-fonts: https://github.com/NixOS/nixpkgs/blob/nixos-unstable/pkgs/data/fonts/nerd-fonts/manifests/fonts.json
- Stylix configuration options: https://danth.github.io/stylix/
- nix-on-droid options: https://nix-community.github.io/nix-on-droid/nix-on-droid-options.html#sec-options
- Very useful tools that are mostly not directly used in configuration but instead called on need:
- Convert non-NixOS machines to NixOS using [nixos-infect](https://github.com/elitak/nixos-infect)
- Create various installation media with [nixos-generators](https://github.com/nix-community/nixos-generators)
- Remotely deploy NixOS using [nixos-anywhere](https://github.com/nix-community/nixos-anywhere)
- And a few links that are not directly nix-related, but may still serve you well:
- List of pre-commit-hooks: https://devenv.sh/reference/options/#pre-commithooks
</details>
<br>
Q: <i>Why Is this just called `.dotfiles`?</i><br>
<details><summary>A: Would you rename your children once they turn 18?</summary></details>
8.18. GitHub Workflow: Build-and-deploy
This file defines the workflow that I use to build the HTML version of this document. It will first tangle this file, which will generate the style.css that is going to be used by the site before exporting the file to html, which will generate the index.html. Finally we build the site.
name: Build and Deploy
on:
push:
branches:
- main
workflow_dispatch:
permissions:
contents: read
pages: write
id-token: write
concurrency:
group: "pages"
cancel-in-progress: false
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with:
fetch-depth: 0
- name: Install Nix
uses: cachix/install-nix-action@8aa03977d8d733052d78f4e008a241fd1dbf36b3 # v31.10.6
- name: Build Emacs from the locked nixpkgs
run: |
rev=$(jq -r '.nodes[.nodes.root.inputs.nixpkgs].locked.rev' flake.lock)
emacs=$(nix build --no-link --print-out-paths --expr "(builtins.getFlake \"github:NixOS/nixpkgs/$rev\").legacyPackages.x86_64-linux.emacs.pkgs.withPackages (epkgs: with epkgs; [ htmlize nix-mode nix-ts-mode markdown-mode terraform-mode transient treesit-grammars.with-all-grammars ])")
echo "EMACS=$emacs/bin/emacs" >> "$GITHUB_ENV"
- name: Prepare site images
run: |
mkdir -p site/files/topology
cp files/topology/topology_small.png site/files/topology/topology_small.png
- name: Render the Emacs configuration
run: |
mkdir -p emacs site/emacs
cp modules/client/programs/emacs/*.nix emacs/
perl -0pi -e 's/(?<!\x27\x27)\$(\{(?:[^{}]++|(?1))*\})/\${"<REDACTED>"}/g' emacs/*.nix
for file in early-init init; do
nix eval --raw --impure --expr "(import ./.github/emacs-init.nix ./emacs).$file" > "site/emacs/$file.el"
done
- name: Tangle files & export to HTML
run: |
"$EMACS" --batch \
--eval "(require 'htmlize)" \
--eval "(setq python-indent-guess-indent-offset-verbose nil)" \
--eval "(advice-add 'display-graphic-p :override (lambda (&rest _) t))" \
--eval "(advice-add 'color-values :around (lambda (orig color &optional frame) (or (ignore-errors (funcall orig color frame)) (and (stringp color) (= (length color) 7) (= (aref color 0) ?#) (list (* 257 (string-to-number (substring color 1 3) 16)) (* 257 (string-to-number (substring color 3 5) 16)) (* 257 (string-to-number (substring color 5 7) 16)))) '(0 0 0))))" \
--eval "(setq css-fontify-colors nil)" \
--eval "(set-face-attribute 'default nil :foreground \"#a0b3c5\" :background \"#1d252c\")" \
--eval "(set-face-attribute 'font-lock-comment-face nil :foreground \"#41505e\" :slant 'italic)" \
--eval "(set-face-attribute 'font-lock-comment-delimiter-face nil :foreground \"#41505e\")" \
--eval "(set-face-attribute 'font-lock-doc-face nil :foreground \"#54677d\" :slant 'italic)" \
--eval "(set-face-attribute 'font-lock-string-face nil :foreground \"#539afc\")" \
--eval "(set-face-attribute 'font-lock-keyword-face nil :foreground \"#5ec4ff\" :weight 'bold)" \
--eval "(set-face-attribute 'font-lock-builtin-face nil :foreground \"#5ec4ff\")" \
--eval "(set-face-attribute 'font-lock-function-name-face nil :foreground \"#33ccff\")" \
--eval "(set-face-attribute 'font-lock-variable-name-face nil :foreground \"#718ca1\")" \
--eval "(set-face-attribute 'font-lock-type-face nil :foreground \"#ebbf83\")" \
--eval "(set-face-attribute 'font-lock-constant-face nil :foreground \"#ff5e9e\")" \
--eval "(set-face-attribute 'font-lock-warning-face nil :foreground \"#ff5e9e\")" \
--eval "(set-face-attribute 'font-lock-preprocessor-face nil :foreground \"#b62d65\")" \
--eval "(set-face-attribute 'font-lock-negation-char-face nil :foreground \"#5ec4ff\")" \
--eval "(set-face-attribute 'font-lock-regexp-grouping-construct nil :foreground \"#5ec4ff\" :weight 'bold)" \
--eval "(set-face-attribute 'font-lock-regexp-grouping-backslash nil :foreground \"#33ccff\")" \
--eval "(require 'org)" \
--eval "(defun org-babel-execute:bash (_body _params) \"\")" \
--eval "(defun org-babel-execute:sh (_body _params) \"\")" \
--eval "(defun org-babel-execute:shell (_body _params) \"\")" \
--eval "(defun org-babel-execute:markdown (_body _params) \"\")" \
--eval "(setq make-backup-files nil
org-confirm-babel-evaluate nil
org-html-validation-link nil
org-export-headline-levels 6
org-export-with-broken-links 'mark
org-html-htmlize-output-type 'inline-css)" \
--visit=SwarselSystems.org \
--funcall org-babel-tangle \
--funcall org-html-export-to-html \
--eval "(dolist (file '(\"site/emacs/early-init.el\" \"site/emacs/init.el\"))
(with-current-buffer (find-file-noselect file)
(let ((indent-tabs-mode nil) (lisp-indent-offset 2))
(indent-region (point-min) (point-max)))
(save-buffer))
(htmlize-file file))"
- name: Setup Pages
uses: actions/configure-pages@1f0c5cde4bc74cd7e1254d0cb4de8d49e9068c7d # v4
- name: Upload artifact
uses: actions/upload-pages-artifact@56afc609e74202658d3ffba0e8f6dda462b719fa # v3
with:
path: 'site'
deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
needs: build
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@d6db90164ac5ed86f2b6aed7e0febac5b3c0c03e # v4
8.19. GitHub Workflow: emacs-init.nix
modules:
let
flake = builtins.getFlake (toString ../.);
inherit (flake.inputs) home-manager nixpkgs nur-expressions;
pkgs = nixpkgs.legacyPackages.x86_64-linux;
home = home-manager.lib.homeManagerConfiguration {
inherit pkgs;
modules = [
"${nur-expressions}/hm-modules/emacs-init.nix"
{
programs.emacs = {
enable = true;
init.enable = true;
};
home = {
homeDirectory = "/home/user";
stateVersion = "25.05";
username = "user";
};
}
]
++ map (file: (import "${modules}/${file}").flake.modules.homeManager.emacs-init or { }) (
builtins.attrNames (builtins.readDir modules)
);
};
files = home.config.programs.emacs.extraPackages pkgs.emacsPackages;
in
{
early-init = (builtins.elemAt files 0).src.text;
init = (builtins.elemAt files 1).src.text;
}
8.20. Private topology flake
This flake is automatically loaded as an override when building the repo topology using the alias build-topology defined in zsh.
{
description = "Flake that sets topologyPrivate to true for building topology.";
outputs = _: { topologyPrivate = true; };
}
8.21. Public topology flake
This flake is loaded per default as an input to not obfuscate values that could be exposed to nix-topology.
{
description = "Flake that sets topologyPrivate to false for general purpose.";
outputs = _: { topologyPrivate = false; };
}
8.22. Grafana dashboard
{
"apiVersion": "dashboard.grafana.app/v2",
"kind": "Dashboard",
"metadata": {
"name": "adwjj9h"
},
"spec": {
"annotations": [
{
"kind": "AnnotationQuery",
"spec": {
"builtIn": true,
"enable": true,
"hide": true,
"iconColor": "rgba(0, 211, 255, 1)",
"name": "Annotations & Alerts",
"query": {
"datasource": {
"name": "-- Grafana --"
},
"group": "grafana",
"kind": "DataQuery",
"spec": {},
"version": "v0"
}
}
}
],
"cursorSync": "Off",
"editable": true,
"elements": {
"panel-1": {
"kind": "Panel",
"spec": {
"data": {
"kind": "QueryGroup",
"spec": {
"queries": [
{
"kind": "PanelQuery",
"spec": {
"hidden": false,
"query": {
"datasource": {
"name": "mimir"
},
"group": "prometheus",
"kind": "DataQuery",
"spec": {
"editorMode": "code",
"exemplar": false,
"expr": "max by (host) (up) or max by (host) (label_replace(probe_success{probe=\"ping\"}, \"host\", \"$1\", \"name\", \"(.+)\")) or max by (host) (host_expected * 0) or max by (host) (label_replace(probe_expected{probe=\"ping\"} * 0, \"host\", \"$1\", \"name\", \"(.+)\"))",
"instant": false,
"legendFormat": "{{probe_from}}",
"range": true
},
"version": "v0"
},
"refId": "A"
}
}
],
"queryOptions": {},
"transformations": []
}
},
"description": "",
"id": 1,
"links": [],
"title": "Probes summary",
"vizConfig": {
"group": "stat",
"kind": "VizConfig",
"spec": {
"fieldConfig": {
"defaults": {
"color": {
"mode": "thresholds"
},
"fieldMinMax": false,
"mappings": [
{
"options": {
"0": {
"color": "red",
"index": 1,
"text": "DOWN"
},
"1": {
"color": "green",
"index": 0,
"text": "UP"
}
},
"type": "value"
}
],
"thresholds": {
"mode": "percentage",
"steps": [
{
"color": "orange",
"value": 0
}
]
},
"unit": "short"
},
"overrides": []
},
"options": {
"colorMode": "value",
"graphMode": "none",
"justifyMode": "auto",
"orientation": "horizontal",
"percentChangeColorMode": "standard",
"reduceOptions": {
"calcs": [
"lastNotNull"
],
"fields": "",
"values": false
},
"showPercentChange": false,
"text": {
"titleSize": 20,
"valueSize": 20
},
"textMode": "value_and_name",
"wideLayout": true
}
},
"version": "13.0.1+security-01"
}
}
},
"panel-10": {
"kind": "Panel",
"spec": {
"data": {
"kind": "QueryGroup",
"spec": {
"queries": [
{
"kind": "PanelQuery",
"spec": {
"hidden": false,
"query": {
"datasource": {
"name": "mimir"
},
"group": "prometheus",
"kind": "DataQuery",
"spec": {
"editorMode": "code",
"expr": "zfs_pool_health",
"legendFormat": "{{host}}:{{pool}}",
"range": true
},
"version": "v0"
},
"refId": "A"
}
}
],
"queryOptions": {},
"transformations": []
}
},
"description": "",
"id": 10,
"links": [],
"title": "ZFS Pool Health",
"vizConfig": {
"group": "stat",
"kind": "VizConfig",
"spec": {
"fieldConfig": {
"defaults": {
"color": {
"mode": "thresholds"
},
"mappings": [
{
"options": {
"0": {
"index": 0,
"text": "ONLINE"
},
"1": {
"index": 1,
"text": "DEGRADED"
},
"2": {
"index": 2,
"text": "FAULTED"
},
"3": {
"index": 3,
"text": "OFFLINE"
},
"4": {
"index": 4,
"text": "UNAVAIL"
},
"5": {
"index": 5,
"text": "REMOVED"
},
"6": {
"index": 6,
"text": "ADJUSTED"
}
},
"type": "value"
}
],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": 0
},
{
"color": "red",
"value": 1
}
]
}
},
"overrides": []
},
"options": {
"colorMode": "value",
"graphMode": "area",
"justifyMode": "auto",
"orientation": "auto",
"percentChangeColorMode": "standard",
"reduceOptions": {
"calcs": [
"lastNotNull"
],
"fields": "",
"values": false
},
"showPercentChange": false,
"textMode": "auto",
"wideLayout": true
}
},
"version": "13.0.1+security-01"
}
}
},
"panel-2": {
"kind": "Panel",
"spec": {
"data": {
"kind": "QueryGroup",
"spec": {
"queries": [
{
"kind": "PanelQuery",
"spec": {
"hidden": false,
"query": {
"datasource": {
"name": "mimir"
},
"group": "prometheus",
"kind": "DataQuery",
"spec": {
"editorMode": "code",
"exemplar": false,
"expr": "min by (name) (probe_http_status_code{probe=\"http\"})\n",
"format": "table",
"instant": true,
"legendFormat": "__auto",
"range": false
},
"version": "v0"
},
"refId": "B"
}
},
{
"kind": "PanelQuery",
"spec": {
"hidden": false,
"query": {
"datasource": {
"name": "mimir"
},
"group": "prometheus",
"kind": "DataQuery",
"spec": {
"editorMode": "code",
"expr": "max by (name) (probe_failed_due_to_regex{probe=\"http\"})",
"format": "table",
"instant": true,
"legendFormat": "__auto"
},
"version": "v0"
},
"refId": "A"
}
},
{
"kind": "PanelQuery",
"spec": {
"hidden": false,
"query": {
"datasource": {
"name": "mimir"
},
"group": "prometheus",
"kind": "DataQuery",
"spec": {
"editorMode": "code",
"exemplar": false,
"expr": "min by (name) (probe_success{probe=~\"http|tcp|dns\"})\nor on(name) min by (name) (label_replace(node_systemd_unit_state{state=\"active\"} * on(host, name) group_left(check) unit_expected{oneshot=\"false\"} or (1 - node_systemd_unit_state{state=\"failed\"}) * on(host, name) group_left(check) unit_expected{oneshot=\"true\"}, \"name\", \"$1\", \"check\", \"(.*)\"))\nor on(name) (max by (name) (probe_expected{probe=~\"http|tcp|dns\"}) * 0)\nor on(name) (max by (name) (label_replace(unit_expected, \"name\", \"$1\", \"check\", \"(.*)\")) * 0)\n",
"format": "table",
"instant": true,
"legendFormat": "__auto",
"range": false
},
"version": "v0"
},
"refId": "C"
}
}
],
"queryOptions": {},
"transformations": [
{
"group": "joinByField",
"kind": "Transformation",
"spec": {
"options": {
"byField": "name",
"mode": "outer"
}
}
},
{
"group": "organize",
"kind": "Transformation",
"spec": {
"options": {
"excludeByName": {
"Time": true,
"Time 1": true,
"Time 2": true,
"Time 3": true,
"Value #C": false,
"host": true,
"instance": true,
"job": true,
"probe": true
},
"includeByName": {},
"indexByName": {},
"renameByName": {
"Time 1": "",
"Time 3": "",
"Value #A": "regexCheck",
"Value #B": "HTTP Status Code",
"Value #C": "Status",
"name": "Service"
}
}
}
}
]
}
},
"description": "",
"id": 2,
"links": [],
"title": "Service health",
"vizConfig": {
"group": "table",
"kind": "VizConfig",
"spec": {
"fieldConfig": {
"defaults": {
"color": {
"mode": "thresholds"
},
"custom": {
"align": "auto",
"cellOptions": {
"mode": "basic",
"type": "color-background"
},
"filterable": true,
"footer": {
"reducers": []
},
"inspect": false
},
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "red",
"value": 0
}
]
}
},
"overrides": [
{
"matcher": {
"id": "byName",
"options": "name",
"scope": "series"
},
"properties": [
{
"id": "color",
"value": {
"fixedColor": "transparent",
"mode": "fixed"
}
}
]
},
{
"matcher": {
"id": "byName",
"options": "Value #A",
"scope": "series"
},
"properties": [
{
"id": "mappings",
"value": [
{
"options": {
"0": {
"color": "green",
"index": 0,
"text": "OK"
},
"1": {
"color": "red",
"index": 1,
"text": "FAIL"
}
},
"type": "value"
}
]
},
{
"id": "thresholds",
"value": {
"mode": "absolute",
"steps": [
{
"color": "transparent",
"value": 0
},
{
"color": "green",
"value": 0
}
]
}
}
]
},
{
"matcher": {
"id": "byName",
"options": "Value #B",
"scope": "series"
},
"properties": [
{
"id": "color",
"value": {
"fixedColor": "transparent",
"mode": "fixed"
}
},
{
"id": "mappings",
"value": []
}
]
},
{
"matcher": {
"id": "byName",
"options": "Value #C",
"scope": "series"
},
"properties": [
{
"id": "mappings",
"value": [
{
"options": {
"0": {
"color": "red",
"index": 0,
"text": "DOWN"
},
"1": {
"color": "green",
"index": 1,
"text": "UP"
}
},
"type": "value"
}
]
}
]
},
{
"matcher": {
"id": "byName",
"options": "Service"
},
"properties": [
{
"id": "custom.width",
"value": 221
}
]
},
{
"matcher": {
"id": "byName",
"options": "HTTP Status Code"
},
"properties": [
{
"id": "custom.width",
"value": 50
}
]
},
{
"matcher": {
"id": "byName",
"options": "expectedBodyRegex"
},
"properties": [
{
"id": "custom.width",
"value": 154
}
]
},
{
"matcher": {
"id": "byName",
"options": "regexCheck"
},
"properties": [
{
"id": "custom.width",
"value": 50
}
]
},
{
"matcher": {
"id": "byName",
"options": "Status"
},
"properties": [
{
"id": "custom.width",
"value": 57
}
]
}
]
},
"options": {
"cellHeight": "sm",
"showHeader": true,
"sortBy": [
{
"desc": false,
"displayName": "name"
}
]
}
},
"version": "13.0.1+security-01"
}
}
},
"panel-3": {
"kind": "Panel",
"spec": {
"data": {
"kind": "QueryGroup",
"spec": {
"queries": [
{
"kind": "PanelQuery",
"spec": {
"hidden": false,
"query": {
"datasource": {
"name": "loki"
},
"group": "loki",
"kind": "DataQuery",
"spec": {
"direction": "backward",
"editorMode": "builder",
"expr": "{host=\"$Host\", unit=\"$Service\"}",
"queryType": "range"
},
"version": "v0"
},
"refId": "A"
}
}
],
"queryOptions": {},
"transformations": []
}
},
"description": "",
"id": 3,
"links": [],
"title": "Logs",
"vizConfig": {
"group": "logs",
"kind": "VizConfig",
"spec": {
"fieldConfig": {
"defaults": {},
"overrides": []
},
"options": {
"dedupStrategy": "none",
"enableInfiniteScrolling": false,
"enableLogDetails": true,
"prettifyLogMessage": true,
"showControls": false,
"showFieldSelector": false,
"showLevel": true,
"showTime": false,
"sortOrder": "Descending",
"timestampResolution": "ms",
"unwrappedColumns": false,
"wrapLogMessage": false
}
},
"version": "13.0.1+security-01"
}
}
},
"panel-4": {
"kind": "Panel",
"spec": {
"data": {
"kind": "QueryGroup",
"spec": {
"queries": [
{
"kind": "PanelQuery",
"spec": {
"hidden": false,
"query": {
"datasource": {
"name": "mimir"
},
"group": "prometheus",
"kind": "DataQuery",
"spec": {
"editorMode": "code",
"expr": "100 - (avg(irate(node_cpu_seconds_total{host=\"$Host\",mode=\"idle\"}[30m])) * 100)\n",
"legendFormat": "__auto",
"range": true
},
"version": "v0"
},
"refId": "A"
}
}
],
"queryOptions": {},
"transformations": []
}
},
"description": "",
"id": 4,
"links": [],
"title": "$Host CPU",
"vizConfig": {
"group": "gauge",
"kind": "VizConfig",
"spec": {
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": 0
},
{
"color": "red",
"value": 80
}
]
},
"unit": "percent"
},
"overrides": []
},
"options": {
"barShape": "flat",
"barWidthFactor": 0.47,
"effects": {
"barGlow": false,
"centerGlow": false,
"gradient": false
},
"endpointMarker": "point",
"minVizHeight": 75,
"minVizWidth": 75,
"orientation": "horizontal",
"reduceOptions": {
"calcs": [
"lastNotNull"
],
"fields": "",
"values": false
},
"segmentCount": 1,
"segmentSpacing": 0.3,
"shape": "gauge",
"showThresholdLabels": false,
"showThresholdMarkers": true,
"sizing": "auto",
"sparkline": true,
"textMode": "auto"
}
},
"version": "13.0.1+security-01"
}
}
},
"panel-5": {
"kind": "Panel",
"spec": {
"data": {
"kind": "QueryGroup",
"spec": {
"queries": [
{
"kind": "PanelQuery",
"spec": {
"hidden": false,
"query": {
"datasource": {
"name": "mimir"
},
"group": "prometheus",
"kind": "DataQuery",
"spec": {
"editorMode": "code",
"expr": "(node_memory_MemTotal_bytes{host=\"$Host\"} - node_memory_MemAvailable_bytes{host=\"$Host\"}) \n/ node_memory_MemTotal_bytes{host=\"$Host\"} * 100",
"legendFormat": "__auto",
"range": true
},
"version": "v0"
},
"refId": "A"
}
}
],
"queryOptions": {},
"transformations": []
}
},
"description": "",
"id": 5,
"links": [],
"title": "$Host RAM",
"vizConfig": {
"group": "gauge",
"kind": "VizConfig",
"spec": {
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": 0
},
{
"color": "red",
"value": 80
}
]
},
"unit": "percent"
},
"overrides": []
},
"options": {
"barShape": "flat",
"barWidthFactor": 0.47,
"effects": {
"barGlow": false,
"centerGlow": false,
"gradient": false
},
"endpointMarker": "point",
"minVizHeight": 75,
"minVizWidth": 75,
"orientation": "horizontal",
"reduceOptions": {
"calcs": [
"lastNotNull"
],
"fields": "",
"values": false
},
"segmentCount": 1,
"segmentSpacing": 0.3,
"shape": "gauge",
"showThresholdLabels": false,
"showThresholdMarkers": true,
"sizing": "auto",
"sparkline": true,
"textMode": "auto"
}
},
"version": "13.0.1+security-01"
}
}
},
"panel-6": {
"kind": "Panel",
"spec": {
"data": {
"kind": "QueryGroup",
"spec": {
"queries": [
{
"kind": "PanelQuery",
"spec": {
"hidden": false,
"query": {
"datasource": {
"name": "mimir"
},
"group": "prometheus",
"kind": "DataQuery",
"spec": {
"editorMode": "code",
"exemplar": false,
"expr": "max by (host, device, fstype) (\n 100 - 100 * node_filesystem_avail_bytes{fstype!~\"zfs|virtiofs|vfat|tmpfs|overlay|squashfs|fuse.*|ramfs|devtmpfs|autofs|nsfs|tracefs|debugfs|securityfs|cgroup.*|configfs|pstore|bpf|proc|sysfs|hugetlbfs|mqueue|binfmt_misc\"}\n / node_filesystem_size_bytes{fstype!~\"zfs|virtiofs|vfat|tmpfs|overlay|squashfs|fuse.*|ramfs|devtmpfs|autofs|nsfs|tracefs|debugfs|securityfs|cgroup.*|configfs|pstore|bpf|proc|sysfs|hugetlbfs|mqueue|binfmt_misc\"}\n )\nor\nmax by (host, device, fstype) (\n label_replace(label_replace(100 * zfs_pool_allocated_bytes / zfs_pool_size_bytes, \"device\", \"$1\", \"pool\", \"(.+)\"), \"fstype\", \"zfs\", \"\", \"\")\n )\n",
"format": "table",
"instant": true,
"legendFormat": "__auto",
"range": false
},
"version": "v0"
},
"refId": "A"
}
}
],
"queryOptions": {},
"transformations": [
{
"group": "organize",
"kind": "Transformation",
"spec": {
"options": {
"excludeByName": {
"Time": true,
"fstype": false,
"{device=\"Lazy\", fstype=\"zfs\", host=\"summers\"}": false
},
"includeByName": {},
"indexByName": {},
"renameByName": {
"Value #A": "",
"device 1": ""
}
}
}
}
]
}
},
"description": "",
"id": 6,
"links": [],
"title": "Disk Usage",
"vizConfig": {
"group": "table",
"kind": "VizConfig",
"spec": {
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"align": "auto",
"cellOptions": {
"type": "auto"
},
"footer": {
"reducers": []
},
"inspect": false
},
"fieldMinMax": false,
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": 0
}
]
},
"unit": "percent"
},
"overrides": [
{
"matcher": {
"id": "byName",
"options": "fstype"
},
"properties": [
{
"id": "custom.width",
"value": 74
}
]
},
{
"matcher": {
"id": "byName",
"options": "Value"
},
"properties": [
{
"id": "custom.width",
"value": 58
}
]
},
{
"matcher": {
"id": "byName",
"options": "device"
},
"properties": [
{
"id": "custom.width",
"value": 85
}
]
},
{
"matcher": {
"id": "byName",
"options": "host"
},
"properties": [
{
"id": "custom.width",
"value": 123
}
]
}
]
},
"options": {
"cellHeight": "sm",
"frameIndex": 0,
"showHeader": true,
"sortBy": [
{
"desc": false,
"displayName": "fstype"
}
]
}
},
"version": "13.0.1+security-01"
}
}
},
"panel-7": {
"kind": "Panel",
"spec": {
"data": {
"kind": "QueryGroup",
"spec": {
"queries": [
{
"kind": "PanelQuery",
"spec": {
"hidden": false,
"query": {
"datasource": {
"name": "mimir"
},
"group": "prometheus",
"kind": "DataQuery",
"spec": {
"editorMode": "code",
"exemplar": false,
"expr": "smartctl_device_smart_status",
"format": "time_series",
"instant": false,
"legendFormat": "{{host}} ({{device}})",
"range": true
},
"version": "v0"
},
"refId": "A"
}
}
],
"queryOptions": {},
"transformations": []
}
},
"description": "",
"id": 7,
"links": [],
"title": "SMART Status",
"vizConfig": {
"group": "stat",
"kind": "VizConfig",
"spec": {
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"mappings": [
{
"options": {
"0": {
"color": "red",
"index": 1,
"text": "FAIL"
},
"1": {
"color": "green",
"index": 0,
"text": "OK"
}
},
"type": "value"
}
],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": 0
}
]
}
},
"overrides": []
},
"options": {
"colorMode": "value",
"graphMode": "none",
"justifyMode": "auto",
"orientation": "auto",
"percentChangeColorMode": "standard",
"reduceOptions": {
"calcs": [
"lastNotNull"
],
"fields": "",
"values": false
},
"showPercentChange": false,
"textMode": "auto",
"wideLayout": true
}
},
"version": "13.0.1+security-01"
}
}
},
"panel-8": {
"kind": "Panel",
"spec": {
"data": {
"kind": "QueryGroup",
"spec": {
"queries": [
{
"kind": "PanelQuery",
"spec": {
"hidden": false,
"query": {
"datasource": {
"name": "mimir"
},
"group": "prometheus",
"kind": "DataQuery",
"spec": {
"editorMode": "code",
"exemplar": false,
"expr": "smartctl_device_temperature{temperature_type=\"current\"}",
"format": "time_series",
"instant": false,
"legendFormat": "{{host}} ({{device}})",
"range": true
},
"version": "v0"
},
"refId": "A"
}
}
],
"queryOptions": {},
"transformations": []
}
},
"description": "",
"id": 8,
"links": [],
"title": "Drive Temperature",
"vizConfig": {
"group": "bargauge",
"kind": "VizConfig",
"spec": {
"fieldConfig": {
"defaults": {
"color": {
"mode": "thresholds"
},
"max": 70,
"min": 20,
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": 0
},
{
"color": "#EAB839",
"value": 40
},
{
"color": "red",
"value": 55
}
]
}
},
"overrides": []
},
"options": {
"displayMode": "basic",
"legend": {
"calcs": [],
"displayMode": "list",
"placement": "bottom",
"showLegend": false
},
"maxVizHeight": 300,
"minVizHeight": 16,
"minVizWidth": 8,
"namePlacement": "auto",
"orientation": "horizontal",
"reduceOptions": {
"calcs": [
"lastNotNull"
],
"fields": "",
"values": false
},
"showUnfilled": true,
"sizing": "auto",
"valueMode": "color"
}
},
"version": "13.0.1+security-01"
}
}
},
"panel-9": {
"kind": "Panel",
"spec": {
"data": {
"kind": "QueryGroup",
"spec": {
"queries": [
{
"kind": "PanelQuery",
"spec": {
"hidden": false,
"query": {
"datasource": {
"name": "mimir"
},
"group": "prometheus",
"kind": "DataQuery",
"spec": {
"editorMode": "code",
"expr": "smartctl_device_attribute{attribute_name=~\"Reallocated_Sector_Ct|Current_Pending_Sector|Offline_Uncorrectable|Reported_Uncorrect\", attribute_value_type=\"raw\"}",
"legendFormat": "{{host}} {{device}} {{attribute_name}}",
"range": true
},
"version": "v0"
},
"refId": "A"
}
}
],
"queryOptions": {},
"transformations": []
}
},
"description": "",
"id": 9,
"links": [],
"title": "Bad Sectors",
"vizConfig": {
"group": "stat",
"kind": "VizConfig",
"spec": {
"fieldConfig": {
"defaults": {
"color": {
"mode": "thresholds"
},
"fieldMinMax": false,
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": 0
},
{
"color": "red",
"value": 1
}
]
}
},
"overrides": []
},
"options": {
"colorMode": "value",
"graphMode": "area",
"justifyMode": "auto",
"orientation": "horizontal",
"percentChangeColorMode": "standard",
"reduceOptions": {
"calcs": [
"lastNotNull"
],
"fields": "",
"values": false
},
"showPercentChange": false,
"text": {
"titleSize": 15,
"valueSize": 20
},
"textMode": "auto",
"wideLayout": true
}
},
"version": "13.0.1+security-01"
}
}
},
"panel-11": {
"kind": "Panel",
"spec": {
"data": {
"kind": "QueryGroup",
"spec": {
"queries": [
{
"kind": "PanelQuery",
"spec": {
"hidden": false,
"query": {
"datasource": {
"name": "mimir"
},
"group": "prometheus",
"kind": "DataQuery",
"spec": {
"editorMode": "code",
"exemplar": false,
"expr": "min by (name) ((probe_ssl_earliest_cert_expiry{probe=\"cert\"} - time()) / 86400) or (max by (name) (probe_expected{probe=\"cert\"}) * 0)",
"format": "time_series",
"instant": false,
"legendFormat": "{{name}}",
"range": true
},
"version": "v0"
},
"refId": "A"
}
}
],
"queryOptions": {},
"transformations": []
}
},
"description": "Days until the served TLS certificate expires",
"id": 11,
"links": [],
"title": "Certificate Validity",
"vizConfig": {
"group": "bargauge",
"kind": "VizConfig",
"spec": {
"fieldConfig": {
"defaults": {
"color": {
"mode": "thresholds"
},
"decimals": 0,
"max": 90,
"min": 0,
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "red",
"value": 0
},
{
"color": "#EAB839",
"value": 14
},
{
"color": "green",
"value": 30
}
]
},
"unit": "d"
},
"overrides": []
},
"options": {
"displayMode": "basic",
"legend": {
"calcs": [],
"displayMode": "list",
"placement": "bottom",
"showLegend": false
},
"maxVizHeight": 300,
"minVizHeight": 16,
"minVizWidth": 8,
"namePlacement": "auto",
"orientation": "horizontal",
"reduceOptions": {
"calcs": [
"lastNotNull"
],
"fields": "",
"values": false
},
"showUnfilled": true,
"sizing": "auto",
"valueMode": "color"
}
},
"version": "13.0.1+security-01"
}
}
}
},
"layout": {
"kind": "RowsLayout",
"spec": {
"rows": [
{
"kind": "RowsLayoutRow",
"spec": {
"collapse": false,
"layout": {
"kind": "GridLayout",
"spec": {
"items": [
{
"kind": "GridLayoutItem",
"spec": {
"element": {
"kind": "ElementReference",
"name": "panel-3"
},
"height": 17,
"width": 24,
"x": 0,
"y": 0
}
},
{
"kind": "GridLayoutItem",
"spec": {
"element": {
"kind": "ElementReference",
"name": "panel-1"
},
"height": 21,
"width": 7,
"x": 0,
"y": 17
}
},
{
"kind": "GridLayoutItem",
"spec": {
"element": {
"kind": "ElementReference",
"name": "panel-2"
},
"height": 32,
"width": 9,
"x": 7,
"y": 17
}
},
{
"kind": "GridLayoutItem",
"spec": {
"element": {
"kind": "ElementReference",
"name": "panel-6"
},
"height": 13,
"width": 8,
"x": 16,
"y": 17
}
},
{
"kind": "GridLayoutItem",
"spec": {
"element": {
"kind": "ElementReference",
"name": "panel-8"
},
"height": 8,
"width": 8,
"x": 16,
"y": 30
}
},
{
"kind": "GridLayoutItem",
"spec": {
"element": {
"kind": "ElementReference",
"name": "panel-9"
},
"height": 11,
"width": 7,
"x": 0,
"y": 38
}
},
{
"kind": "GridLayoutItem",
"spec": {
"element": {
"kind": "ElementReference",
"name": "panel-7"
},
"height": 8,
"width": 8,
"x": 16,
"y": 38
}
},
{
"kind": "GridLayoutItem",
"spec": {
"element": {
"kind": "ElementReference",
"name": "panel-10"
},
"height": 3,
"width": 8,
"x": 16,
"y": 46
}
},
{
"kind": "GridLayoutItem",
"spec": {
"element": {
"kind": "ElementReference",
"name": "panel-11"
},
"height": 6,
"width": 24,
"x": 0,
"y": 49
}
},
{
"kind": "GridLayoutItem",
"spec": {
"element": {
"kind": "ElementReference",
"name": "panel-5"
},
"height": 5,
"repeat": {
"direction": "h",
"mode": "variable",
"value": "Host"
},
"width": 24,
"x": 0,
"y": 55
}
},
{
"kind": "GridLayoutItem",
"spec": {
"element": {
"kind": "ElementReference",
"name": "panel-4"
},
"height": 5,
"repeat": {
"direction": "h",
"mode": "variable",
"value": "Host"
},
"width": 24,
"x": 0,
"y": 95
}
}
]
}
},
"title": "New row"
}
}
]
}
},
"links": [],
"liveNow": false,
"preload": false,
"tags": [
"service-status",
"blackbox"
],
"timeSettings": {
"autoRefresh": "",
"autoRefreshIntervals": [
"5s",
"10s",
"30s",
"1m",
"5m",
"15m",
"30m",
"1h",
"2h",
"1d"
],
"fiscalYearStartMonth": 0,
"from": "now-30m",
"hideTimepicker": false,
"timezone": "browser",
"to": "now"
},
"title": "Overview",
"variables": [
{
"kind": "QueryVariable",
"spec": {
"allowCustomValue": false,
"current": {
"text": "All",
"value": "$__all"
},
"definition": "",
"hide": "dontHide",
"includeAll": true,
"multi": false,
"name": "Host",
"options": [],
"query": {
"datasource": {
"name": "loki"
},
"group": "loki",
"kind": "DataQuery",
"spec": {
"label": "host",
"refId": "LokiVariableQueryEditor-VariableQuery",
"stream": "",
"type": 1
},
"version": "v0"
},
"refresh": "onDashboardLoad",
"regex": "",
"regexApplyTo": "value",
"skipUrlSync": false,
"sort": "disabled"
}
},
{
"kind": "QueryVariable",
"spec": {
"allowCustomValue": false,
"current": {
"text": "",
"value": ""
},
"definition": "",
"hide": "dontHide",
"includeAll": false,
"multi": false,
"name": "Service",
"options": [],
"query": {
"datasource": {
"name": "loki"
},
"group": "loki",
"kind": "DataQuery",
"spec": {
"label": "unit",
"refId": "LokiVariableQueryEditor-VariableQuery",
"stream": "{host=\"$Host\"}",
"type": 1
},
"version": "v0"
},
"refresh": "onTimeRangeChanged",
"regex": "",
"regexApplyTo": "value",
"skipUrlSync": false,
"sort": "disabled"
}
}
]
}
}
8.23. Repo-wide Pedantix config
{
args = {
first = [
"self"
"root"
"name"
"homeConfig"
"inputs"
"config"
"lib"
"pkgs"
"options"
];
last = [
"modulesPath"
"<defaulted>"
"..."
];
};
attrs = {
first = [
"flake-file"
"flake"
"imports"
"options"
"config"
"swarselsystems"
"topology"
"globals"
"sops"
"users"
"services"
"programs"
"enable"
"package"
];
flatten = true;
last = [
"systemd"
"nodes"
"meta"
];
merge = true;
name-style = "identifier";
};
inherits = {
first = [
"self"
"name"
"homeConfig"
"inputs"
"config"
"lib"
"pkgs"
"options"
"modulesPath"
];
name-style = "identifier";
sort = true;
};
overrides = [
{
attrs.first = [ ];
path = "inputs";
}
{
attrs.blank-lines = 1;
path = "flake-file.inputs";
}
{
attrs.blank-lines = 1;
path = "flake.overlays";
}
];
top-level-blank-lines = 1;
}
9. Appendix C: Explanations to nix functions and operators
This sections explains commonly used functions in nix (both builtins as well as in the nixpkgs library).
9.1. Concepts
9.1.1. The '//' operator
The // operator in nix is used to merge attribute sets; if an attribute exists in both sets, then the latter set takes precedence:
swarsel-instantiate '{ a = 1; b = 2; } // { b = 3; c = 4; }'
Also, this will not merge nested sets:
swarsel-instantiate '{ a = { a1 = 1; a2 = 2; }; b = { b1 = 1; b2 = 2; }; } // { b = { b1 = 3; b3 = 4;}; c = 4; }'
It only took the latter b set, even though the b2 value was not contested. This functionality is provided by nixpkgs.lib.recursiveUpdate.
9.2. Built-in functions
The following functions are only base functionality of nix, and not exported to nixpkgs. When using them we need to make sure that the nix version in use is matching the expected function.
9.2.1. builtins.readDir
builtins.readDir reads the name of items of a directory as attributes and their type as values.
swarsel-instantiate 'builtins.readDir ./hosts/nixos'
9.3. Built-in functions exported to nixpkgs
These functions exist in nix, but are exported to nixpkgs to make sure they use a nix version that works in the used nixpkgs. Most of the times I should prefer to use the nixpkgs version of these.
9.3.1. nixpkgs.lib.listToAttrs
builtins.listToAttrs converts a list of name-value pairs into an attribute set.
swarsel-instantiate 'builtins.listToAttrs [{ name = "foo"; value = 1; } { name = "bar"; value = 2; }]'
9.3.2. nixpkgs.lib.attrNames
nixpkgs.lib.attrNames returns the list of attribute names from an attribute set.
swarsel-instantiate 'lib.attrNames { a = 1; b = 2; c = 3; }'
9.3.3. nixpkgs.lib.map
nixpkgs.lib.map takes a function and applies the elements of a list upon them.
swarsel-instantiate 'lib.map (x: x + 1) [1 2 3]'
swarsel-instantiate 'lib.map (x: { result = x + 1; }) [1 2 3]'
9.3.4. nixpkgs.lib.filter
nixpkgs.lib.filter takes a list as input and only keeps elements that fulfill a given function:
swarsel-instantiate 'lib.filter (x: x != "a") (lib.attrNames { a = 1; b = 2; c = 3; })'
9.3.5. nixpkgs.lib.concatLists
nixpkgs.lib.concatLists, as the name suggests, concatenates lists, while keeping the original order of items:
swarsel-instantiate 'lib.concatLists [ [ 1 2 ] [ 3 4 ] [ 5 ] ]'
9.3.6. nixpkgs.lib.genList
nixpkgs.lib.genList generates a list from a function:
swarsel-instantiate 'lib.genList (i: if i < 16 then 1 else 0) 32'
9.3.7. nixpkgs.lib.concatStringsSep
nixpkgs.lib.concatStringsSep concatenates a list of strings with a defined separator:
swarsel-instantiate 'lib.concatStringsSep "." ["services" "nginx"]'
9.3.8. nixpkgs.lib.split
nixpkgs.lib.split creates a list containing both the list of regex matches as well as the non-matched strings of a regex pattern:
swarsel-instantiate 'lib.split "\\." "sub.about.com"'
Another example with regex matches:
swarsel-instantiate 'lib.split "(s)." "swarsel"'
The result list always begins with non-matching patterns, so if the first character is in a match, the first element will be "".
9.3.9. nixpkgs.lib.tail
nixpkgs.lib.tail returns a list without its first item:
swarsel-instantiate 'lib.tail [ "sub" "about" "com" ]'
9.3.10. nixpkgs.lib.head
nixpkgs.lib.tail returns the first item of a list:
swarsel-instantiate 'lib.head [ "sub" "about" "com" ]'
9.3.11. nixpkgs.lib.isString
nixpkgs.lib.isString returns a bool based on if the input evaluates to a string:
swarsel-instantiate 'lib.isString [ "1" ]'
swarsel-instantiate 'lib.isString "1"'
9.3.12. nixpkgs.lib.length
nixpkgs.lib.length returns the length of a list:
swarsel-instantiate 'lib.length [ "1" [] ]'
9.3.13. nixpkgs.lib.stringLength
nixpkgs.lib.stringLength returns the byte length of a string:
swarsel-instantiate 'lib.stringLength "<3"'
swarsel-instantiate 'lib.stringLength "❤"'
swarsel-instantiate 'lib.stringLength "❤️"'
9.3.14. nixpkgs.lib.subString
nixpkgs.lib.substring returns the substring within the specified range (excluding the end index):
swarsel-instantiate 'lib.substring 0 3 "about"'
9.4. Functions in nixpkgs
These functions only exist in nixpkgs and cannot be used in generic nix code.
9.4.1. nixpkgs.lib.recursiveUpdate
If you want to merge nested attribute sets, use nixpkgs.lib.recursiveUpdate instead of The '//' operator:
swarsel-instantiate 'lib.recursiveUpdate { a = { a1 = 1; a2 = 2; }; b = { b1 = 1; b2 = 2; }; } { b = { b1 = 3; b3 = 4;}; c = 4; }'
9.4.2. nixpkgs.lib.genAttrs
nixpkgs.lib.genAttrs is used to generate an attribute set (a dictionary-like structure) from a list of keys and a function that computes the values for those keys.
swarsel-instantiate 'lib.genAttrs ["a" "b" "c"] (x: "${x}-value")'
9.4.3. nixpkgs.lib.mkOverride
nixpkgs.lib.mkOverride sets the priority of an expression.
If two expression are defined twice across the configuration, the evaluator does not know which one should take precedence; this will lead to an error. By default, all option definitions are given priority 100. Lower values take precedence over lower values. For reference, here are some commonly used values:
- nixpkgs.lib.mkForce sets the priority to 50, which is a very low value, meaning it will be prioritized in nearly all cases
- nixpkgs.lib.mkDefault sets the priority to 1000, which is a quite high value that will almost never be used if the same attribute is defined elsewhere.
9.4.4. nixpkgs.lib.mkForce
An alias for (nixpkgs.lib.mkOverride 50).
9.4.5. nixpkgs.lib.mkDefault
An alias for (nixpkgs.lib.mkOverride 1000).
9.4.6. nixpkgs.lib.mapAttrsToList
nixpkgs.lib.mapAttrsToList converts an attribute set into a list by applying a given function to each name-value pair:
swarsel-instantiate 'lib.mapAttrsToList (name: value: "${name} = ${value}") { a = "1"; b = "2"; }'
9.4.7. nixpkgs.lib.flip
nixpkgs.lib.flipreverses the argument order passed to an expression (in semantics, that is lib.flip f a b == f b a). This is useful when an expression has one big argument and one small one; in that case it is convenient to have the shorter expression at the start of the function. Take this example of a function that simply prints its attributes as a list:
swarsel-instantiate 'lib.mapAttrsToList (name: value: "${name} = ${value}") {a = "1"; b = "2";}'
It prints the attributes unchanged, as is to be expected. If, however, we call the function using nixpkgs.lib.flip:
swarsel-instantiate 'lib.mapAttrsToList (lib.flip (name: value: "${name} = ${value}")) {a = "1"; b = "2";}'
9.4.8. nixpkgs.lib.mkMerge
nixpgks.lib.mkMergeis used to deeply merge values.
swarsel-instantiate '
lib.mkMerge [
{
a = [ 1 ];
}
{
a = [ 3 ];
}
]
'
9.4.9. nixpkgs.lib.foldl
nixpkgs.lib.foldl reduces an attribute set by repeatedly calling a function on an attribute set from the left.
swarsel-instantiate 'lib.foldl (acc: x: "(" + acc + " + " + x + ")") "0" ["1" "2" "3"]'
similarly, there exists an version that starts from the right.
swarsel-instantiate 'lib.foldr (acc: x: "(" + acc + " + " + x + ")") "0" ["1" "2" "3"]'
9.4.10. nixpkgs.lib.toInt
nixpkgs.lib.toInt casts a value to an int. Strips spaces:
swarsel-instantiate 'lib.toInt " 3"'
Note that the string cannot be preceded by 0 - lib.toInt "01" would yield => error: Ambiguity in interpretation of 00024 between octal and zero padded integer.
10. Appendix D: Notable Commits
In this section I try to add commits whenever they feel like they changed something about this repository (but often also other commits around the same time are important). I wanted to do this for a while already and always was too lazy. I will need to do another run through the history at another point, but for now here are some interesting states:
10.1. 978f4a7 - treewide: major cleanup (2026-11-11)
At this point I decided to drop all of the unused tooling I had amassed over the years. I kept this mostly around in order for it to be able to be found through the GitHub search, but it started getting on my nerves. But you, the avid reader, can find it because of this section :3
10.2. bb0d4ad - feat: adopt sops-rekey (2026-11-04)
So for years I had always been a little sad because agenix-rekey is a thing. Basically that is an extension to agenix that gives some cool features. The mean thing is something called "rekey" - basically reusing an existing secret and encrypting it for another receiver. That is nice and all, but the main feature I was jealous about was that it provided a slew of neat "generators" that could be used to define a secret of a certain structure right at the secret definition. Similar to flake-file, you then need to call a tool to generate the actual secret, but I still think this is very convenient.
Well, so finally I ported agenix-rekey as far as I could and the result is sops-rekey. And here i migrated to it :)
10.3. bfb70b7 - refactor[client]: move magicant to dendritic (2026-11-01)
This commit is simply a little cool because it marks the point where the last of my machines was migrated to the dendritic pattern. Also I made the whole android tooling a lot nicer, including some helpers that allow for remote building and fetching of nix-on-droid configurations.
Also, I noticed that for years I had pinned some 2024 revision for nixpkgs regarding nix-on-droid and thought it was the last release they ever had. Welp, that was not the case :p
10.4. 78edb33 - feat[client]: migrate to emacs-init (2026-06-10)
For years my Emacs configuration was a hand-written init.el and early-init.el that I tangled from this very document. Here, I converted the whole config to rycee's emacs-init home-manager module, which generates the init.el from native nix config. I also used the opportunity to restructure the Emacs section a little bit. I had wanted to do this for years already, but was always too afraid that I would at some point move away from nix. However, I recently realized that even rewriting the entire Emacs config from scratch would be a laughable effort compared to the rest of what I did in this project, so well, I just did it now :)
10.5. fffcee1 - refactor: move to dendritic pattern (2026-06-06)
Here, I moved the whole repository over to the dendritic pattern, where every .nix file under modules/ is a flake-parts module that gets auto-imported via import-tree, and features are composed through flake.modules.* (this allows to write configuration for multiple contexts in a single file). This made the project a lot more concise, saving around 2000 lines of code here.
10.6. 85e830d - feat: use flake-file (2026-06-04)
Here I started using flake-file to manage my flake inputs. Instead of maintaining the inputs block in flake.nix by hand, each feature can now declare the inputs it needs next to where it uses them, and the actual flake.nix inputs block is generated from those declarations.
This revision is particularly interesting, because at this point I was not yet using a dendritic pattern for the rest of the project. I figured out a neat way to still make full use of flake-file anyway, even if it was just for this single commit.
10.7. 8b2fe83 - feat[server]: modernize nginx/acme setup (2026-06-02)
In this commit I dropped the OCSP stapling and RSA, which also allowed me to drop the DH parameter generation block.
10.8. 9e2cb74 - fix[server]: move away from full module load system (2026-05-06)
For a while at this point, it had become a pain to rebuild summers, since evaluation was always taking around 10min or more. I then one day checked on my configuration builder and wondered why summers kept failing and failing. Previously I had assumed that just something was broken or the arch emulation failed, but then I tested an eval using NIX_SHOW_STATS=1 and noticed that evaluating summers took upwards of 80G of RAM - I just never noticed this because I rebuilt this node from my local machine only normally.
I found the issue quite quickly - it was me creating too many nftables rules. I removed those (and I actually removed too many at the time!), but that saved around 60G of eval memory, which was crazy to me.
However, I wanted more; I noticed that my (at the time) current system that was always importing all modules unconditionally and then using options to gate them was also costing quite some memory - around 4G. Hence, I reluctantly changed it. I still like the old system, even though I now have to say that this approach has some very nice benefits (like being able to import module inputs only when they are needed! even though I don't do that yet at that point haha)
10.9. 99d0d75 - feat: manage .sops.yaml using tofu (2026-05-02)
At this point, it had become painful to maintain .sops.yaml, as I kept having to introduce new classes of secret files that were most of the times scoped to only one or two hosts. I needed this to make sure no host could read secrets that they did not need. At the same time, I then had to curate a ton of rules myself. Hence I added a simple terraform file provisioner to generate the file on demand
10.10. 2cb6780 - feat[server]: use confLib to manage services (2025-11-25)
Here I introduced the confLib module argument. Basically a collection of functions that mostly act as code generators that I use in server nix files to save myself some hassle in computing some IPs, networks, and NGINX blocks.
10.11. 0caef3e - feat: use nixos-extra-modules (2025-11-08)
Another change that I did in the wake of wanting to use MicroVMs. I pulled in the nixos-extra-modules flake that had some helper functions for MicroVMs and networking that I did not feel like fully copying over and maintaining. Adopting this was quite the chore and I am nowadays actually not sure if I should keep this in, or re-implement the things that I actually need on my own.
10.12. 7d614f7 - feat!: switch to full flake-parts (2025-07-03)
Here I finally cleaned up the old flake.nix and instead started to use flake-parts. Along with that, I also overhauled the host definitions, library functions, devShells and more I believe
10.13. 2aa5e00 - feat: add globals system (2025-06-29)
At this point I was needing more and more the ability for nodes to share config with each other. At the same point, I was well aware that cross-node config checks are an expensive operation. Hence, I added a globals output that worked by evaluating the full configuration once and reading out values set across several places in the repo. This would then allow for pseudo-cross node config references without incurring that cost every time - a change in wake of me wanting to switch to MicroVMs :)
10.14. a11c785 - feat: new deploy system, allows for in-repo pii (2025-06-11)
This is the change I mentioned where I moved to a system of in-repo secrets that is described here: https://oddlama.org/blog/evaluation-time-secrets-in-nix/ and implemented the core needed for using it.
10.15. 267c03f - Merge pull request #1: Module refactor (2025-05-24)
At this point, I wanted a cleaner structuring of modules into some notion of categories (like common, shared, etc.)
10.16. 47b99bb - feat: add nix-topology (2024-12-28)
This was the point where I finally accepted that this project had actually become more than just dotfiles :p of course I did not rename it! Instead I started curating these nice topology diagrams that would show the network structure of the infrastructure (although still crude at that point)
10.17. 6788494 - feat: full bootstrapping (2024-12-17)
For some time at this point, I wanted to have a system that would allow me to bootstrap hosts faster, in a more automated fashion. My big gripe with this was back then the .sops.yaml file, which would not be updated yet if a new host was added.
With this and other commits around this timeline, I then automated most of the bootstrapping steps for a new host, also including disk encryption and secure boot. I also introduced the notion of a minimal config that could be used for the nixos-anywhere deployment and on top of which the actual configuration would be built.
10.18. 3a272b1 - feat!: dynamically create hosts (2024-12-10)
At this point I got kind of annoyed that I had so much boilerplate code concerning the definitions of my nixosConfigurations. I moved to a pattern where I derived the configurations from the folder structure of the repo: hosts/[system]/<host>. By doing this, I could use functions to generate the actual nixosConfigurations automatically.
10.19. 040fce3 - feat: add private secrets flake for flake purity (2024-12-10)
At this point I felt that I exposed some level of personal data in this repository, that, while I did not really care, I also felt people did not need to see it. My solution to this was to introduce another, private flake, that would hold arbitrary values that I could then insert into the respective attributes.
This approach had some flaws, mainly being that I had to keep in sync two separate repositories just to keep everything working. Later on at [[https://github.com/Swarsel/.dotfiles/tree/a11c785][a11c785 - feat: new deploy system, allows for in-repo pii (2025-06-11)]], I then moved to another system that allowed for in-repo secrets. However, that approach is more complex in general, which comes with some cost of maintenance at points; I still think the approach in this commit is valid.
10.20. 33046cb - refactor: use inputs.self instead of rel. paths (2024-12-05)
This replaced most of the ./path/to/[...].nix relative imports with
self + [...] (this or in string form). I am still not sure if it is best practice to do this, but for me this is a useful pattern.
10.21. 84b5cd8 - move flake to own repository (2023-12-11)
This is the state of the repository when I decided to migrate to flakes. At this point I kind of considered this a new project and decided to start with a fresh git history (a move that I today find debatable).
11. Appendix E: Current TODOs
Enhancements:
- generate the topology thumbnail automatically either upon html export or GitHub workflow
Fixes:
- split off invidious-companion into own VM(?)
Blocked:
- look into self-hosted Cospend (Spliit module?) to deprecate Nextcloud
- fix router bridge interfaces after kitchen construction concludes
