From f3660d350530b3ac1ba59bdf7d2e6855152fea33 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 11 Oct 2026 12:39:07 +0000 Subject: [PATCH] WIP: home-manager modules and install tooling (in progress, unreviewed) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01J1cugeLkfFLZMpiztQ8TyN --- .gitignore | 11 + apps/default.nix | 16 + hosts/desktop/home.nix | 28 + modules/home/apps.nix | 30 + modules/home/default.nix | 17 + modules/home/git.nix | 58 ++ modules/home/hyprland/binds.lua | 129 ++++ modules/home/hyprland/default.nix | 67 ++ modules/home/hyprland/rules.lua | 89 +++ modules/home/hyprland/settings.lua | 117 ++++ modules/home/neovim/default.nix | 54 ++ modules/home/neovim/init.lua | 149 +++++ modules/home/noctalia.nix | 50 ++ modules/home/shell.nix | 84 +++ modules/home/ssh.nix | 76 +++ modules/home/theming.nix | 51 ++ modules/home/wezterm.nix | 56 ++ modules/home/xdg.nix | 67 ++ modules/installer/default.nix | 75 +++ pkgs/create-keys/create-keys.sh | 137 ++++ pkgs/create-keys/default.nix | 24 + pkgs/default.nix | 18 + pkgs/install-system/default.nix | 42 ++ pkgs/install-system/install-system.sh | 773 ++++++++++++++++++++++ pkgs/secret-from-file/default.nix | 27 + pkgs/secret-from-file/secret-from-file.sh | 166 +++++ pkgs/set-password/default.nix | 20 + pkgs/set-password/set-password.sh | 82 +++ pkgs/switch-system/default.nix | 21 + pkgs/switch-system/switch-system.sh | 85 +++ 30 files changed, 2619 insertions(+) create mode 100644 .gitignore create mode 100644 apps/default.nix create mode 100644 hosts/desktop/home.nix create mode 100644 modules/home/apps.nix create mode 100644 modules/home/default.nix create mode 100644 modules/home/git.nix create mode 100644 modules/home/hyprland/binds.lua create mode 100644 modules/home/hyprland/default.nix create mode 100644 modules/home/hyprland/rules.lua create mode 100644 modules/home/hyprland/settings.lua create mode 100644 modules/home/neovim/default.nix create mode 100644 modules/home/neovim/init.lua create mode 100644 modules/home/noctalia.nix create mode 100644 modules/home/shell.nix create mode 100644 modules/home/ssh.nix create mode 100644 modules/home/theming.nix create mode 100644 modules/home/wezterm.nix create mode 100644 modules/home/xdg.nix create mode 100644 modules/installer/default.nix create mode 100644 pkgs/create-keys/create-keys.sh create mode 100644 pkgs/create-keys/default.nix create mode 100644 pkgs/default.nix create mode 100644 pkgs/install-system/default.nix create mode 100644 pkgs/install-system/install-system.sh create mode 100644 pkgs/secret-from-file/default.nix create mode 100644 pkgs/secret-from-file/secret-from-file.sh create mode 100644 pkgs/set-password/default.nix create mode 100644 pkgs/set-password/set-password.sh create mode 100644 pkgs/switch-system/default.nix create mode 100644 pkgs/switch-system/switch-system.sh diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..581d843 --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +# Private keys (SSH host key, Secure Boot keys): live only on the install USB stick. +keys/ + +# Build outputs +result +result-* +.direnv/ + +# Images +*.qcow2 +*.iso diff --git a/apps/default.nix b/apps/default.nix new file mode 100644 index 0000000..eacee54 --- /dev/null +++ b/apps/default.nix @@ -0,0 +1,16 @@ +# `nix run .#`: install and key/secret helpers (see ../pkgs). +{ pkgs, ... }: +let + app = pkg: description: { + type = "app"; + program = pkgs.lib.getExe pkg; + meta.description = description; + }; +in +{ + install = app pkgs.install-system "Install this flake onto this machine from the NixOS installer (wipes the configured disks)"; + create-keys = app pkgs.create-keys "Create the SSH host key and Secure Boot keys in keys//"; + set-password = app pkgs.set-password "Encrypt the login password into secrets/-password.age"; + secret-from-file = app pkgs.secret-from-file "Encrypt an existing file (e.g. an SSH key) as secrets/.age"; + switch = app pkgs.switch-system "Rebuild and switch this machine from the flake"; +} diff --git a/hosts/desktop/home.nix b/hosts/desktop/home.nix new file mode 100644 index 0000000..a43d470 --- /dev/null +++ b/hosts/desktop/home.nix @@ -0,0 +1,28 @@ +# home-manager config for the desktop's user (wired up in ./default.nix). +# The modules live in modules/home; this file only turns them on. +{ osConfig, ... }: +let + name = osConfig.my.user.name; +in +{ + home = { + username = name; + homeDirectory = "/home/${name}"; + + # Set once at install time; do not change on upgrades. + stateVersion = "26.05"; + }; + + my.home = { + hyprland.enable = true; + noctalia.enable = true; + wezterm.enable = true; + neovim.enable = true; + shell.enable = true; + git.enable = true; + ssh.enable = true; + xdg.enable = true; + theming.enable = true; + apps.enable = true; + }; +} diff --git a/modules/home/apps.nix b/modules/home/apps.nix new file mode 100644 index 0000000..985d250 --- /dev/null +++ b/modules/home/apps.nix @@ -0,0 +1,30 @@ +# Everyday desktop applications. +{ + config, + lib, + pkgs, + ... +}: +let + cfg = config.my.home.apps; +in +{ + options.my.home.apps.enable = lib.mkEnableOption "desktop applications"; + + config = lib.mkIf cfg.enable { + programs = { + firefox.enable = true; + mpv.enable = true; + imv.enable = true; + zathura.enable = true; + }; + + home.packages = with pkgs; [ + vesktop # Discord client with working screen sharing on Wayland + telegram-desktop + file-roller + loupe # image viewer + nautilus + ]; + }; +} diff --git a/modules/home/default.nix b/modules/home/default.nix new file mode 100644 index 0000000..6caed11 --- /dev/null +++ b/modules/home/default.nix @@ -0,0 +1,17 @@ +# Home-manager modules, all behind `my.home..enable` (default false). +# Loaded for every user through home-manager.sharedModules (see lib/default.nix); +# hosts//home.nix turns the wanted ones on. +{ + imports = [ + ./hyprland + ./noctalia.nix + ./wezterm.nix + ./neovim + ./shell.nix + ./git.nix + ./ssh.nix + ./xdg.nix + ./theming.nix + ./apps.nix + ]; +} diff --git a/modules/home/git.nix b/modules/home/git.nix new file mode 100644 index 0000000..0e0f4dd --- /dev/null +++ b/modules/home/git.nix @@ -0,0 +1,58 @@ +# Git identity and defaults. The name and email come from my.user so the +# identity is defined once, in the host file. +{ + config, + lib, + pkgs, + osConfig, + ... +}: +let + cfg = config.my.home.git; +in +{ + options.my.home.git.enable = lib.mkEnableOption "Git and GitHub CLI configuration"; + + config = lib.mkIf cfg.enable { + programs = { + git = { + enable = true; + + settings = { + user = { + name = osConfig.my.user.fullName; + inherit (osConfig.my.user) email; + }; + init.defaultBranch = "main"; + pull.rebase = true; + push.autoSetupRemote = true; + rebase.autoStash = true; + merge.conflictStyle = "zdiff3"; + diff.colorMoved = "default"; + }; + + ignores = [ + ".direnv/" + "result" + "result-*" + ".DS_Store" + ]; + }; + + # Syntax-highlighted diffs as the git pager. + delta = { + enable = true; + enableGitIntegration = true; + options = { + navigate = true; + line-numbers = true; + }; + }; + + gh = { + enable = true; + settings.git_protocol = "ssh"; + }; + }; + }; +} diff --git a/modules/home/hyprland/binds.lua b/modules/home/hyprland/binds.lua new file mode 100644 index 0000000..9ebf9cb --- /dev/null +++ b/modules/home/hyprland/binds.lua @@ -0,0 +1,129 @@ +-- Keybindings. Shell features (launcher, panels, media keys) go through +-- Noctalia's IPC: https://docs.noctalia.dev/noctalia/ipc/ +local nix = require("nixvars") + +local mainMod = "SUPER" +local ipc = "noctalia msg " + +-- Binds act as if the first layout (us) were active, so they also work while +-- the Russian layout is selected. + +---------------------- +---- APPLICATIONS ---- +---------------------- + +hl.bind(mainMod .. " + Return", hl.dsp.exec_cmd(nix.terminal)) +hl.bind(mainMod .. " + E", hl.dsp.exec_cmd(nix.fileManager)) + +--------------- +---- WINDOWS ---- +--------------- + +hl.bind(mainMod .. " + Q", hl.dsp.window.close()) +hl.bind(mainMod .. " + F", hl.dsp.window.fullscreen()) +hl.bind(mainMod .. " + SHIFT + F", hl.dsp.window.fullscreen({ mode = "maximized" })) +hl.bind(mainMod .. " + SHIFT + Space", hl.dsp.window.float({ action = "toggle" })) +hl.bind(mainMod .. " + P", hl.dsp.window.pseudo()) +hl.bind(mainMod .. " + T", hl.dsp.layout("togglesplit")) -- dwindle only + +-- Emergency exit if the shell is not running. +hl.bind(mainMod .. " + SHIFT + Escape", hl.dsp.exit()) + +-- Move focus with mainMod + arrow keys or hjkl +hl.bind(mainMod .. " + left", hl.dsp.focus({ direction = "left" })) +hl.bind(mainMod .. " + right", hl.dsp.focus({ direction = "right" })) +hl.bind(mainMod .. " + up", hl.dsp.focus({ direction = "up" })) +hl.bind(mainMod .. " + down", hl.dsp.focus({ direction = "down" })) +hl.bind(mainMod .. " + H", hl.dsp.focus({ direction = "left" })) +hl.bind(mainMod .. " + L", hl.dsp.focus({ direction = "right" })) +hl.bind(mainMod .. " + K", hl.dsp.focus({ direction = "up" })) +hl.bind(mainMod .. " + J", hl.dsp.focus({ direction = "down" })) + +-- Move the window with mainMod + SHIFT + arrow keys or hjkl +hl.bind(mainMod .. " + SHIFT + left", hl.dsp.window.move({ direction = "left" })) +hl.bind(mainMod .. " + SHIFT + right", hl.dsp.window.move({ direction = "right" })) +hl.bind(mainMod .. " + SHIFT + up", hl.dsp.window.move({ direction = "up" })) +hl.bind(mainMod .. " + SHIFT + down", hl.dsp.window.move({ direction = "down" })) +hl.bind(mainMod .. " + SHIFT + H", hl.dsp.window.move({ direction = "left" })) +hl.bind(mainMod .. " + SHIFT + L", hl.dsp.window.move({ direction = "right" })) +hl.bind(mainMod .. " + SHIFT + K", hl.dsp.window.move({ direction = "up" })) +hl.bind(mainMod .. " + SHIFT + J", hl.dsp.window.move({ direction = "down" })) + +-- Resize with mainMod + CTRL + arrow keys or hjkl +local resizeStep = 40 +local resizeKeys = { + { "left", "H", -resizeStep, 0 }, + { "right", "L", resizeStep, 0 }, + { "up", "K", 0, -resizeStep }, + { "down", "J", 0, resizeStep }, +} +for _, r in ipairs(resizeKeys) do + local action = hl.dsp.window.resize({ x = r[3], y = r[4], relative = true }) + hl.bind(mainMod .. " + CTRL + " .. r[1], action, { repeating = true }) + hl.bind(mainMod .. " + CTRL + " .. r[2], action, { repeating = true }) +end + +-- Move/resize windows with mainMod + LMB/RMB and dragging +hl.bind(mainMod .. " + mouse:272", hl.dsp.window.drag(), { mouse = true }) +hl.bind(mainMod .. " + mouse:273", hl.dsp.window.resize(), { mouse = true }) + +-------------------- +---- WORKSPACES ---- +-------------------- + +-- Switch workspaces with mainMod + [0-9] +-- Move active window to a workspace with mainMod + SHIFT + [0-9] +for i = 1, 10 do + local key = i % 10 -- 10 maps to key 0 + hl.bind(mainMod .. " + " .. key, hl.dsp.focus({ workspace = i })) + hl.bind(mainMod .. " + SHIFT + " .. key, hl.dsp.window.move({ workspace = i })) +end + +-- Scratchpad (special workspace) +hl.bind(mainMod .. " + minus", hl.dsp.workspace.toggle_special("magic")) +hl.bind(mainMod .. " + SHIFT + minus", hl.dsp.window.move({ workspace = "special:magic" })) + +-- Scroll through existing workspaces with mainMod + scroll +hl.bind(mainMod .. " + mouse_down", hl.dsp.focus({ workspace = "e+1" })) +hl.bind(mainMod .. " + mouse_up", hl.dsp.focus({ workspace = "e-1" })) + +------------------ +---- NOCTALIA ---- +------------------ + +hl.bind(mainMod .. " + Space", hl.dsp.exec_cmd(ipc .. "panel-toggle launcher")) +hl.bind(mainMod .. " + S", hl.dsp.exec_cmd(ipc .. "panel-toggle control-center")) +hl.bind(mainMod .. " + comma", hl.dsp.exec_cmd(ipc .. "settings-toggle")) +hl.bind(mainMod .. " + V", hl.dsp.exec_cmd(ipc .. "panel-toggle clipboard")) +hl.bind(mainMod .. " + W", hl.dsp.exec_cmd(ipc .. "panel-toggle wallpaper")) +hl.bind(mainMod .. " + Escape", hl.dsp.exec_cmd(ipc .. "panel-toggle session")) +hl.bind(mainMod .. " + ALT + L", hl.dsp.exec_cmd(ipc .. "session lock")) +hl.bind("ALT + Tab", hl.dsp.exec_cmd(ipc .. "window-switcher hold")) + +-- Volume, microphone, brightness and media keys +local held = { locked = true, repeating = true } +hl.bind("XF86AudioRaiseVolume", hl.dsp.exec_cmd(ipc .. "volume-up"), held) +hl.bind("XF86AudioLowerVolume", hl.dsp.exec_cmd(ipc .. "volume-down"), held) +hl.bind("XF86AudioMute", hl.dsp.exec_cmd(ipc .. "volume-mute"), held) +hl.bind("XF86AudioMicMute", hl.dsp.exec_cmd(ipc .. "mic-mute"), held) +hl.bind("XF86MonBrightnessUp", hl.dsp.exec_cmd(ipc .. "brightness-up"), held) +hl.bind("XF86MonBrightnessDown", hl.dsp.exec_cmd(ipc .. "brightness-down"), held) + +hl.bind("XF86AudioNext", hl.dsp.exec_cmd(ipc .. "media next"), { locked = true }) +hl.bind("XF86AudioPause", hl.dsp.exec_cmd(ipc .. "media toggle"), { locked = true }) +hl.bind("XF86AudioPlay", hl.dsp.exec_cmd(ipc .. "media toggle"), { locked = true }) +hl.bind("XF86AudioPrev", hl.dsp.exec_cmd(ipc .. "media previous"), { locked = true }) + +--------------------- +---- SCREENSHOTS ---- +--------------------- + +-- grim + slurp, straight to the clipboard. Cancelling slurp aborts the capture. +hl.bind("Print", hl.dsp.exec_cmd('geometry=$(slurp) && grim -g "$geometry" - | wl-copy')) +hl.bind("SHIFT + Print", hl.dsp.exec_cmd("grim - | wl-copy")) +-- Region to ~/Pictures/Screenshots and the clipboard. +hl.bind("CTRL + Print", hl.dsp.exec_cmd( + 'dir="$HOME/Pictures/Screenshots"; mkdir -p "$dir" && geometry=$(slurp) && ' .. + 'file="$dir/$(date +%F_%H-%M-%S).png" && grim -g "$geometry" "$file" && wl-copy < "$file"')) +-- Noctalia's own region capture with the annotation editor. +hl.bind(mainMod .. " + Print", hl.dsp.exec_cmd(ipc .. "screenshot-region")) diff --git a/modules/home/hyprland/default.nix b/modules/home/hyprland/default.nix new file mode 100644 index 0000000..3b80110 --- /dev/null +++ b/modules/home/hyprland/default.nix @@ -0,0 +1,67 @@ +# Hyprland user configuration. Hyprland 0.56 reads Lua, so the real config lives +# in the plain .lua files next to this module; Nix only passes in the few +# values that come from the system config (keyboard layouts, cursor, apps). +{ + config, + lib, + pkgs, + osConfig, + ... +}: +let + cfg = config.my.home.hyprland; + cursor = config.home.pointerCursor; + + # Exposed to the Lua files as `require("nixvars")`. + nixVars = { + kbLayout = lib.concatStringsSep "," osConfig.my.locale.keyboardLayouts; + kbOptions = lib.concatStringsSep "," osConfig.my.locale.keyboardOptions; + terminal = "wezterm"; + fileManager = "nautilus"; + cursorSize = if cursor.enable then cursor.size else 24; + cursorTheme = if cursor.enable then cursor.name else ""; + }; +in +{ + options.my.home.hyprland.enable = lib.mkEnableOption "Hyprland user configuration (Lua)"; + + config = lib.mkIf cfg.enable { + wayland.windowManager.hyprland = { + enable = true; + configType = "lua"; + + # The NixOS module (programs.hyprland) installs the compositor and the + # portal, built from the flake overlay. Installing them again here would + # put a second copy in the user profile. + package = null; + portalPackage = null; + + # UWSM owns the session and graphical-session.target; HM's own + # hyprland-session.target and dbus import would only duplicate that. + systemd.enable = false; + xwayland.enable = true; + + # Loaded in name order; `nixvars` is a helper module, not loaded on its own. + extraLuaFiles = { + nixvars = { + content = "return ${lib.generators.toLua { } nixVars}\n"; + autoLoad = false; + }; + "10-settings" = ./settings.lua; + "20-binds" = ./binds.lua; + "30-rules" = ./rules.lua; + }; + }; + + # Tools the binds call (screenshots, file manager). + home.packages = with pkgs; [ + grim + slurp + wl-clipboard + nautilus + ]; + + # Electron and Chromium apps pick Wayland instead of XWayland. + home.sessionVariables.NIXOS_OZONE_WL = "1"; + }; +} diff --git a/modules/home/hyprland/rules.lua b/modules/home/hyprland/rules.lua new file mode 100644 index 0000000..d73ee81 --- /dev/null +++ b/modules/home/hyprland/rules.lua @@ -0,0 +1,89 @@ +-- Window, layer and workspace rules. + +-- Ignore maximize requests from all apps. +hl.window_rule({ + name = "suppress-maximize-events", + match = { class = ".*" }, + + suppress_event = "maximize", +}) + +-- Fix some dragging issues with XWayland. +hl.window_rule({ + name = "fix-xwayland-drags", + match = { + class = "^$", + title = "^$", + xwayland = true, + float = true, + fullscreen = false, + pin = false, + }, + + no_focus = true, +}) + +-- Hyprland-run windowrule. +hl.window_rule({ + name = "move-hyprland-run", + match = { class = "hyprland-run" }, + + move = "20 monitor_h-120", + float = true, +}) + +-- Anything fullscreen keeps the screen awake (video players, games, browsers). +hl.window_rule({ + name = "idle-inhibit-fullscreen", + match = { class = ".*" }, + + idle_inhibit = "fullscreen", +}) + +------------------ +---- NOCTALIA ---- +------------------ + +-- Settings window floats at a comfortable size. +hl.window_rule({ + name = "noctalia-settings", + match = { class = "dev.noctalia.Noctalia" }, + + float = true, + size = { 1080, 920 }, +}) + +-- Blur behind the bar, panels, dock and notifications; Hyprland's own layer +-- animations are off so they do not fight Noctalia's. +hl.layer_rule({ + name = "noctalia", + match = { + namespace = "^noctalia-(bar-.+|notification|dock|panel|attached-panel|osd|window-switcher)$", + }, + + no_anim = true, + ignore_alpha = 0.5, + blur = true, + blur_popups = true, +}) + +---------------- +---- GAMING ---- +---------------- + +-- Steam Big Picture games (steam_app_) may tear for lower input latency. +-- This only takes effect in fullscreen with general.allow_tearing enabled. +hl.window_rule({ + name = "steam-games-tearing", + match = { class = "^steam_app_\\d+$" }, + + immediate = true, +}) + +-- Steam's small utility windows. +hl.window_rule({ + name = "steam-utility-windows", + match = { class = "^steam$", title = "^(Friends List|Steam Settings)$" }, + + float = true, +}) diff --git a/modules/home/hyprland/settings.lua b/modules/home/hyprland/settings.lua new file mode 100644 index 0000000..ab0b50b --- /dev/null +++ b/modules/home/hyprland/settings.lua @@ -0,0 +1,117 @@ +-- Monitors, environment, look and feel, input. +-- API reference: the official example (hyprland.lua) shipped with Hyprland. +local nix = require("nixvars") + +------------------ +---- MONITORS ---- +------------------ + +-- Any output, native mode, placed automatically. Use mode = "highrr" to prefer +-- the highest refresh rate instead. +hl.monitor({ + output = "", + mode = "preferred", + position = "auto", + scale = "auto", +}) + +------------------------------- +---- ENVIRONMENT VARIABLES ---- +------------------------------- + +hl.env("XCURSOR_SIZE", tostring(nix.cursorSize)) +hl.env("HYPRCURSOR_SIZE", tostring(nix.cursorSize)) +if nix.cursorTheme ~= "" then + hl.env("XCURSOR_THEME", nix.cursorTheme) +end + +----------------------- +---- LOOK AND FEEL ---- +----------------------- + +-- Gaps, rounding, shadow and blur follow the Noctalia documentation so the +-- shell's bar and panels sit well on top of the windows. +hl.config({ + general = { + gaps_in = 5, + gaps_out = 10, + + border_size = 2, + + col = { + -- Catppuccin Mocha: mauve to blue, surface1 when unfocused. + active_border = { colors = { "rgba(cba6f7ee)", "rgba(89b4faee)" }, angle = 45 }, + inactive_border = "rgba(45475aaa)", + }, + + resize_on_border = true, + + -- Only windows with the `immediate` rule (see 30-rules.lua) tear. + allow_tearing = true, + + layout = "dwindle", + }, + + decoration = { + rounding = 20, + rounding_power = 2, + + shadow = { + enabled = true, + range = 4, + render_power = 3, + color = 0xee1a1a1a, + }, + + blur = { + enabled = true, + size = 3, + passes = 2, + vibrancy = 0.1696, + }, + }, + + animations = { + enabled = true, + }, + + dwindle = { + preserve_split = true, + }, + + master = { + new_status = "master", + }, + + misc = { + -- Noctalia draws the wallpaper. + force_default_wallpaper = 0, + disable_hyprland_logo = true, + }, + + ecosystem = { + no_update_news = true, + no_donation_nag = true, + }, +}) + +--------------- +---- INPUT ---- +--------------- + +hl.config({ + input = { + kb_layout = nix.kbLayout, + kb_options = nix.kbOptions, + + numlock_by_default = true, + + follow_mouse = 1, + sensitivity = 0, + }, +}) + +-- Persistent workspaces keep the empty ones visible in Noctalia's indicator. +for i = 1, 5 do + hl.workspace_rule({ workspace = tostring(i), persistent = true }) +end diff --git a/modules/home/neovim/default.nix b/modules/home/neovim/default.nix new file mode 100644 index 0000000..34ebaf7 --- /dev/null +++ b/modules/home/neovim/default.nix @@ -0,0 +1,54 @@ +# Neovim with LSP, completion, fuzzy finding and format-on-save. +# The editor config is in init.lua next to this file. +{ + config, + lib, + pkgs, + ... +}: +let + cfg = config.my.home.neovim; +in +{ + options.my.home.neovim.enable = lib.mkEnableOption "Neovim editor"; + + config = lib.mkIf cfg.enable { + programs.neovim = { + enable = true; + defaultEditor = true; + viAlias = true; + vimAlias = true; + + plugins = with pkgs.vimPlugins; [ + nvim-treesitter.withAllGrammars + nvim-lspconfig + blink-cmp + telescope-nvim + telescope-fzf-native-nvim + plenary-nvim + lualine-nvim + gitsigns-nvim + which-key-nvim + oil-nvim + conform-nvim + catppuccin-nvim + nvim-web-devicons + mini-nvim + ]; + + # Language servers, formatters and search tools, visible to nvim only. + extraPackages = with pkgs; [ + nixd + nixfmt + lua-language-server + stylua + bash-language-server + shfmt + ripgrep + fd + ]; + + initLua = builtins.readFile ./init.lua; + }; + }; +} diff --git a/modules/home/neovim/init.lua b/modules/home/neovim/init.lua new file mode 100644 index 0000000..1656c8f --- /dev/null +++ b/modules/home/neovim/init.lua @@ -0,0 +1,149 @@ +-- Plugins are installed by Nix (see default.nix); this file only configures them. + +vim.g.mapleader = " " +vim.g.maplocalleader = " " + +----------------- +---- OPTIONS ---- +----------------- + +local o = vim.opt +o.number = true +o.relativenumber = true +o.signcolumn = "yes" +o.cursorline = true +o.termguicolors = true +o.mouse = "a" +o.clipboard = "unnamedplus" +o.undofile = true +o.ignorecase = true +o.smartcase = true +o.splitright = true +o.splitbelow = true +o.scrolloff = 8 +o.updatetime = 250 +o.timeoutlen = 400 +o.expandtab = true +o.shiftwidth = 2 +o.tabstop = 2 +o.smartindent = true +o.wrap = false +o.list = true +o.listchars = { tab = "» ", trail = "·", nbsp = "␣" } +o.inccommand = "split" + +--------------------- +---- COLORSCHEME ---- +--------------------- + +require("catppuccin").setup({ flavour = "mocha" }) +vim.cmd.colorscheme("catppuccin") + +require("nvim-web-devicons").setup() +require("lualine").setup({ options = { theme = "catppuccin", globalstatus = true } }) +require("gitsigns").setup() +require("which-key").setup() +require("oil").setup() + +-- mini.nvim: only the small editing helpers. +require("mini.pairs").setup() +require("mini.surround").setup() + +-------------------- +---- TREESITTER ---- +-------------------- + +-- Parsers come from nvim-treesitter.withAllGrammars. Starting the built-in +-- highlighter works with both the old and the rewritten nvim-treesitter. +vim.api.nvim_create_autocmd("FileType", { + callback = function(args) + pcall(vim.treesitter.start, args.buf) + end, +}) + +-------------------- +---- TELESCOPE ---- +-------------------- + +local telescope = require("telescope") +telescope.setup({}) +pcall(telescope.load_extension, "fzf") + +local builtin = require("telescope.builtin") +vim.keymap.set("n", "ff", builtin.find_files, { desc = "Find files" }) +vim.keymap.set("n", "fg", builtin.live_grep, { desc = "Grep" }) +vim.keymap.set("n", "fb", builtin.buffers, { desc = "Buffers" }) +vim.keymap.set("n", "fh", builtin.help_tags, { desc = "Help" }) +vim.keymap.set("n", "fr", builtin.oldfiles, { desc = "Recent files" }) + +vim.keymap.set("n", "-", "Oil", { desc = "File explorer" }) + +------------- +---- LSP ---- +------------- + +-- Neovim 0.11+ API. nvim-lspconfig supplies the default cmd, filetypes and +-- root markers for each server; the language servers are on nvim's PATH +-- (extraPackages in default.nix). +require("blink.cmp").setup({ + keymap = { preset = "default" }, + sources = { default = { "lsp", "path", "snippets", "buffer" } }, +}) + +vim.lsp.config("*", { + capabilities = require("blink.cmp").get_lsp_capabilities(), +}) + +vim.lsp.config("nixd", { + settings = { + nixd = { + formatting = { command = { "nixfmt" } }, + }, + }, +}) + +vim.lsp.config("lua_ls", { + settings = { + Lua = { + runtime = { version = "LuaJIT" }, + diagnostics = { globals = { "vim", "hl" } }, + workspace = { checkThirdParty = false }, + telemetry = { enable = false }, + }, + }, +}) + +vim.lsp.enable({ "nixd", "lua_ls", "bashls" }) + +vim.api.nvim_create_autocmd("LspAttach", { + callback = function(args) + local function map(lhs, rhs, desc) + vim.keymap.set("n", lhs, rhs, { buffer = args.buf, desc = desc }) + end + map("gd", vim.lsp.buf.definition, "Go to definition") + map("gr", vim.lsp.buf.references, "References") + map("K", vim.lsp.buf.hover, "Hover") + map("rn", vim.lsp.buf.rename, "Rename") + map("ca", vim.lsp.buf.code_action, "Code action") + map("e", vim.diagnostic.open_float, "Line diagnostics") + end, +}) + +vim.diagnostic.config({ virtual_text = true, severity_sort = true }) + +----------------------- +---- FORMAT ON SAVE ---- +----------------------- + +require("conform").setup({ + formatters_by_ft = { + nix = { "nixfmt" }, + lua = { "stylua" }, + sh = { "shfmt" }, + bash = { "shfmt" }, + }, + format_on_save = { + timeout_ms = 1000, + lsp_format = "fallback", + }, +}) diff --git a/modules/home/noctalia.nix b/modules/home/noctalia.nix new file mode 100644 index 0000000..86cb972 --- /dev/null +++ b/modules/home/noctalia.nix @@ -0,0 +1,50 @@ +# Noctalia v5 shell (bar, launcher, notifications, lock screen, wallpaper). +# The module itself comes from the noctalia flake (home-manager sharedModules). +# Settings are validated at build time by `noctalia config validate`, so only +# keys from the upstream schema may appear here. Anything changed in the +# settings window at runtime is stored separately and overrides this file. +{ + config, + lib, + pkgs, + ... +}: +let + cfg = config.my.home.noctalia; +in +{ + options.my.home.noctalia.enable = lib.mkEnableOption "Noctalia shell"; + + config = lib.mkIf cfg.enable { + programs.noctalia = { + enable = true; + + # A user service instead of hl.exec_cmd, so it restarts on failure and + # follows graphical-session.target (managed by UWSM). + systemd.enable = true; + + settings = { + theme = { + mode = "dark"; + source = "builtin"; + builtin = "Catppuccin"; + }; + + shell = { + font_family = "Inter"; + telemetry_enabled = false; + + # No other polkit agent is started in the session. + polkit_agent = true; + + # Apps started from the launcher get their own systemd scope, so + # restarting the shell service does not kill them. + launch_apps_as_systemd_services = true; + }; + }; + }; + + # Shell font. + home.packages = [ pkgs.inter ]; + }; +} diff --git a/modules/home/shell.nix b/modules/home/shell.nix new file mode 100644 index 0000000..711273d --- /dev/null +++ b/modules/home/shell.nix @@ -0,0 +1,84 @@ +# Interactive shell: zsh with starship prompt, fzf, zoxide, eza, bat, direnv. +{ + config, + lib, + pkgs, + ... +}: +let + cfg = config.my.home.shell; +in +{ + options.my.home.shell.enable = lib.mkEnableOption "zsh shell environment and CLI tools"; + + config = lib.mkIf cfg.enable { + programs = { + zsh = { + enable = true; + enableCompletion = true; + autosuggestion.enable = true; + syntaxHighlighting.enable = true; + autocd = true; + + history = { + size = 50000; + save = 50000; + # Share between open terminals, skip duplicates and space-prefixed lines. + share = true; + ignoreDups = true; + ignoreSpace = true; + extended = true; + }; + + shellAliases = { + cat = "bat"; + ".." = "cd .."; + g = "git"; + # nh builds, diffs and activates the flake in one step. + rebuild = "nh os switch"; + rebuild-boot = "nh os boot"; + rebuild-test = "nh os test"; + }; + }; + + starship = { + enable = true; + settings = { + add_newline = false; + # Keeps the prompt on one line when the nix shell or direnv is active. + nix_shell.format = "[$symbol$state]($style) "; + }; + }; + + fzf = { + enable = true; + defaultCommand = "fd --type f --hidden --exclude .git"; + fileWidget.command = "fd --type f --hidden --exclude .git"; + changeDirWidget.command = "fd --type d --hidden --exclude .git"; + }; + + # `z dir` jumps to frecent directories, `zi` picks with fzf. + zoxide.enable = true; + + # ls, ll, la, lt and lla aliases come from the zsh integration. + eza = { + enable = true; + icons = "auto"; + git = true; + }; + + bat.enable = true; + + direnv = { + enable = true; + nix-direnv.enable = true; + }; + + btop.enable = true; + fastfetch.enable = true; + }; + + # fd backs the fzf commands above. + home.packages = [ pkgs.fd ]; + }; +} diff --git a/modules/home/ssh.nix b/modules/home/ssh.nix new file mode 100644 index 0000000..c69ac26 --- /dev/null +++ b/modules/home/ssh.nix @@ -0,0 +1,76 @@ +# SSH client, agent and the user's keys. +# Private keys are agenix secrets (decrypted at boot into /run/agenix); this +# module only links them into ~/.ssh so ssh finds them at the usual path. +{ + config, + lib, + osConfig, + ... +}: +let + cfg = config.my.home.ssh; + + secrets = osConfig.my.secrets; + + # Keys that actually have an encrypted secret in the repo. Without a secret + # nothing is linked, so a fresh install still boots and ssh falls back to + # whatever key the user generates by hand. + keys = lib.filter (k: osConfig.age.secrets ? "ssh-${k}") secrets.userSshKeys; + + pubFile = k: secrets.dir + "/ssh-${k}.pub"; + + # The decrypted file lives outside the store, so link it by absolute path. + keyFiles = lib.listToAttrs ( + map ( + k: + lib.nameValuePair ".ssh/${k}" { + source = config.lib.file.mkOutOfStoreSymlink osConfig.age.secrets."ssh-${k}".path; + } + ) keys + ); + + # Public keys are not secret, so they are plain files from the repo. + pubFiles = lib.listToAttrs ( + map (k: lib.nameValuePair ".ssh/${k}.pub" { source = pubFile k; }) ( + lib.filter (k: builtins.pathExists (pubFile k)) keys + ) + ); +in +{ + options.my.home.ssh.enable = lib.mkEnableOption "SSH client, agent and agenix-provided keys"; + + config = lib.mkIf cfg.enable { + programs.ssh = { + enable = true; + + # Spell the defaults out below instead of relying on the deprecated ones. + enableDefaultConfig = false; + + settings = { + "*" = { + # Load a key into the agent on first use, so the passphrase (if any) + # is typed once per login. + AddKeysToAgent = "yes"; + ServerAliveInterval = 60; + ServerAliveCountMax = 3; + HashKnownHosts = false; + UserKnownHostsFile = "~/.ssh/known_hosts"; + }; + + "github.com" = { + User = "git"; + IdentityFile = "~/.ssh/id_ed25519"; + # Offer only this key, not everything in the agent. + IdentitiesOnly = true; + }; + }; + }; + + # A plain user service rather than gnome-keyring's agent: no keyring to + # unlock, and it sets SSH_AUTH_SOCK for shells, systemd and D-Bus. The + # system must not start another agent (programs.ssh.startAgent). + services.ssh-agent.enable = true; + + home.file = keyFiles // pubFiles; + }; +} diff --git a/modules/home/theming.nix b/modules/home/theming.nix new file mode 100644 index 0000000..c97e0d0 --- /dev/null +++ b/modules/home/theming.nix @@ -0,0 +1,51 @@ +# Dark GTK and Qt look, icons and cursor. Noctalia themes the shell itself; +# this keeps the apps consistent with it. +{ + config, + lib, + pkgs, + ... +}: +let + cfg = config.my.home.theming; +in +{ + options.my.home.theming.enable = lib.mkEnableOption "GTK/Qt theme, icons and cursor"; + + config = lib.mkIf cfg.enable { + gtk = { + enable = true; + colorScheme = "dark"; + + theme = { + name = "adw-gtk3-dark"; + package = pkgs.adw-gtk3; + }; + + iconTheme = { + name = "Papirus-Dark"; + package = pkgs.papirus-icon-theme; + }; + }; + + # GTK picks the cursor up from here (gtk.enable below). + home.pointerCursor = { + enable = true; + package = pkgs.bibata-cursors; + name = "Bibata-Modern-Classic"; + size = 24; + gtk.enable = true; + }; + + # Qt apps follow the GTK settings, with the Adwaita dark widget style. + qt = { + enable = true; + platformTheme.name = "gtk3"; + style.name = "adwaita-dark"; + }; + + # libadwaita and GTK 4 apps read the preference from dconf. The system + # needs programs.dconf.enable for this to be applied. + dconf.settings."org/gnome/desktop/interface".color-scheme = "prefer-dark"; + }; +} diff --git a/modules/home/wezterm.nix b/modules/home/wezterm.nix new file mode 100644 index 0000000..671042b --- /dev/null +++ b/modules/home/wezterm.nix @@ -0,0 +1,56 @@ +# WezTerm terminal (SUPER+Return in Hyprland). +{ + config, + lib, + pkgs, + ... +}: +let + cfg = config.my.home.wezterm; +in +{ + options.my.home.wezterm.enable = lib.mkEnableOption "WezTerm terminal"; + + config = lib.mkIf cfg.enable { + programs.wezterm = { + enable = true; + + extraConfig = '' + local act = wezterm.action + local config = wezterm.config_builder() + + config.color_scheme = 'Catppuccin Mocha' + config.font = wezterm.font_with_fallback { 'JetBrainsMono Nerd Font', 'Noto Color Emoji' } + config.font_size = 12.0 + + -- Wayland-native, no client-side titlebar (Hyprland draws the borders). + config.enable_wayland = true + config.window_decorations = 'NONE' + config.window_padding = { left = 8, right = 8, top = 8, bottom = 8 } + + -- A tab bar only when there is more than one tab. + config.hide_tab_bar_if_only_one_tab = true + config.use_fancy_tab_bar = false + + config.scrollback_lines = 20000 + config.audible_bell = 'Disabled' + config.check_for_updates = false + + -- Hyprland owns SUPER and ALT+Tab, so splits live on CTRL+SHIFT. + -- phys: keys are layout independent and work with the ru layout. + config.keys = { + { key = 'phys:D', mods = 'CTRL|SHIFT', action = act.SplitHorizontal { domain = 'CurrentPaneDomain' } }, + { key = 'phys:E', mods = 'CTRL|SHIFT', action = act.SplitVertical { domain = 'CurrentPaneDomain' } }, + } + + return config + ''; + }; + + # The font the config asks for; the emoji font is a fallback. + home.packages = with pkgs; [ + nerd-fonts.jetbrains-mono + noto-fonts-color-emoji + ]; + }; +} diff --git a/modules/home/xdg.nix b/modules/home/xdg.nix new file mode 100644 index 0000000..edee061 --- /dev/null +++ b/modules/home/xdg.nix @@ -0,0 +1,67 @@ +# XDG base dirs, the user folders and default applications. +# Documents, Downloads, Music, Pictures and Videos are separate subvolumes on +# the data SSD mounted into $HOME (my.disks); Desktop, Templates and Public +# are plain directories on the system disk. Home-manager's default folder +# names already match, so only the unwanted ones are changed. +{ + config, + lib, + ... +}: +let + cfg = config.my.home.xdg; + + firefox = "firefox.desktop"; + fileManager = "org.gnome.Nautilus.desktop"; + imageViewer = "org.gnome.Loupe.desktop"; + mediaPlayer = "mpv.desktop"; + pdfViewer = "org.pwmt.zathura.desktop"; + archiveManager = "org.gnome.FileRoller.desktop"; +in +{ + options.my.home.xdg.enable = lib.mkEnableOption "XDG directories and default applications"; + + config = lib.mkIf cfg.enable { + xdg = { + enable = true; + + userDirs = { + enable = true; + createDirectories = true; + + # No ~/Projects: code lives wherever the user clones it. + projects = null; + }; + + mimeApps = { + enable = true; + + defaultApplications = { + "text/html" = firefox; + "x-scheme-handler/http" = firefox; + "x-scheme-handler/https" = firefox; + "x-scheme-handler/about" = firefox; + "x-scheme-handler/unknown" = firefox; + + "inode/directory" = fileManager; + + "image/*" = imageViewer; + "video/*" = mediaPlayer; + "audio/*" = mediaPlayer; + "application/pdf" = pdfViewer; + + "application/zip" = archiveManager; + "application/x-tar" = archiveManager; + "application/x-7z-compressed" = archiveManager; + "application/vnd.rar" = archiveManager; + }; + }; + + # "Open in terminal" actions (desktop entries with Terminal=true) use WezTerm. + terminal-exec = { + enable = true; + settings.default = [ "org.wezfurlong.wezterm.desktop" ]; + }; + }; + }; +} diff --git a/modules/installer/default.nix b/modules/installer/default.nix new file mode 100644 index 0000000..6ca9625 --- /dev/null +++ b/modules/installer/default.nix @@ -0,0 +1,75 @@ +# Installer ISO (`nix build .#iso`): the minimal NixOS installer plus this +# flake and the install tooling. Wired up in lib/default.nix (mkInstaller). +{ + lib, + pkgs, + inputs, + self, + ... +}: +let + inherit (pkgs.stdenv.hostPlatform) system; + + # Every flake input including nested ones, so the sources are on the ISO and + # a locked flake installs without re-downloading them. + allInputs = builtins.genericClosure { + startSet = map (i: { + key = toString i.outPath; + inherit i; + }) (lib.attrValues inputs); + operator = + x: + map (i: { + key = toString i.outPath; + inherit i; + }) (lib.attrValues (x.i.inputs or { })); + }; +in +{ + nix.settings = { + experimental-features = [ + "nix-command" + "flakes" + ]; + # The flake's nixConfig lists binary caches (Noctalia, nix-community). + accept-flake-config = true; + }; + + # nmtui / nmcli instead of wpa_supplicant. + networking.networkmanager.enable = true; + networking.wireless.enable = lib.mkForce false; + + environment.systemPackages = [ + pkgs.install-system + pkgs.create-keys + pkgs.set-password + pkgs.secret-from-file + pkgs.git + pkgs.jq + pkgs.age + pkgs.sbctl + pkgs.btrfs-progs + pkgs.neovim + inputs.disko.packages.${system}.disko + inputs.agenix.packages.${system}.default + ]; + + # The flake itself, read-only. install-system copies it before changing it. + environment.etc."nixos-config".source = self; + + system.extraDependencies = map (x: x.i.outPath) allInputs; + + users.motd = '' + + NixOS installer for the "desktop" flake + + 1. Network: nmtui (Ethernet works out of the box) + 2. Install: sudo install-system + (flake: /etc/nixos-config, or --flake DIR for a copy on a stick; + --keys-dir DIR for keys/ on a mounted stick) + 3. Keys: create-keys, set-password, secret-from-file (see the README) + + install-system asks which disks to use and erases them only after you type the host name. + + ''; +} diff --git a/pkgs/create-keys/create-keys.sh b/pkgs/create-keys/create-keys.sh new file mode 100644 index 0000000..84bdf4a --- /dev/null +++ b/pkgs/create-keys/create-keys.sh @@ -0,0 +1,137 @@ +#!/usr/bin/env bash +# create-keys: generate the machine secrets that live only on the install USB +# stick, in keys// (gitignored): the SSH host key (agenix identity) and +# the Secure Boot keys (sbctl). Existing keys are never overwritten. +set -euo pipefail + +HOST=desktop +FLAKE_ARG= + +if [ -t 1 ]; then + RED=$'\033[1;31m' + GRN=$'\033[1;32m' + YEL=$'\033[1;33m' + RST=$'\033[0m' +else + RED= + GRN= + YEL= + RST= +fi + +ok() { printf '%s ok%s %s\n' "$GRN" "$RST" "$*"; } +warn() { printf '%swarning:%s %s\n' "$YEL" "$RST" "$*" >&2; } +die() { + printf '%serror:%s %s\n' "$RED" "$RST" "$*" >&2 + exit 1 +} + +usage() { + cat <<'EOF' +Usage: create-keys [--host NAME] [--flake DIR] + +Creates keys//ssh_host_ed25519_key(.pub) and keys//sbctl/{keys,GUID} +inside the flake directory (default: the repository you are in) if they do not +exist yet, then prints the public key to put into secrets/secrets.nix. +Copy keys/ to the install USB stick together with the repository. +EOF +} + +while [ "$#" -gt 0 ]; do + case "$1" in + --host) + [ "$#" -ge 2 ] || die "--host needs a value" + HOST=$2 + shift 2 + ;; + --flake) + [ "$#" -ge 2 ] || die "--flake needs a value" + FLAKE_ARG=$2 + shift 2 + ;; + -h | --help) + usage + exit 0 + ;; + *) die "unknown argument: $1 (see --help)" ;; + esac +done + +case "$HOST" in + '' | *[!A-Za-z0-9_-]*) die "invalid host name: '$HOST'" ;; +esac + +find_flake() { + local d + if [ -n "$FLAKE_ARG" ]; then + d=$FLAKE_ARG + elif d=$(git rev-parse --show-toplevel 2>/dev/null) && [ -f "$d/flake.nix" ]; then + : + elif [ -f "$PWD/flake.nix" ]; then + d=$PWD + else + die "no flake found: run inside the repository or pass --flake DIR" + fi + [ -f "$d/flake.nix" ] || die "no flake.nix in $d" + readlink -f "$d" +} + +FLAKE=$(find_flake) +KEYS="$FLAKE/keys/$HOST" +HOSTKEY="$KEYS/ssh_host_ed25519_key" +SBCTL="$KEYS/sbctl" + +# Private keys must never reach git (and through it, the world-readable Nix store). +if git -C "$FLAKE" rev-parse --is-inside-work-tree >/dev/null 2>&1 && + ! git -C "$FLAKE" check-ignore -q "keys/$HOST/ssh_host_ed25519_key"; then + die "keys/ is not ignored by git: add 'keys/' to $FLAKE/.gitignore first" +fi + +umask 077 +mkdir -p "$KEYS" + +if [ -e "$HOSTKEY" ]; then + ok "host key exists, left untouched: $HOSTKEY" +else + ssh-keygen -q -t ed25519 -N '' -C "root@$HOST" -f "$HOSTKEY" + ok "created host key: $HOSTKEY" +fi +if [ ! -e "$HOSTKEY.pub" ]; then + ssh-keygen -y -f "$HOSTKEY" >"$HOSTKEY.pub" + chmod 0644 "$HOSTKEY.pub" +fi + +if [ -d "$SBCTL/keys" ] && [ -f "$SBCTL/GUID" ]; then + ok "Secure Boot keys exist, left untouched: $SBCTL" +elif [ -e "$SBCTL/keys" ] || [ -e "$SBCTL/GUID" ]; then + die "$SBCTL is incomplete (needs both keys/ and GUID): inspect it and remove the leftovers yourself" +else + # landlock only allows writes below /var/lib, but we write into the repository. + sbctl --disable-landlock create-keys --export "$SBCTL/keys" --database-path "$SBCTL/GUID" + ok "created Secure Boot keys: $SBCTL" +fi + +# Run through sudo: hand the files back to the person who called us. +if [ "$(id -u)" -eq 0 ] && [ -n "${SUDO_UID:-}" ] && [ -n "${SUDO_GID:-}" ]; then + chown -R "$SUDO_UID:$SUDO_GID" "$FLAKE/keys" +fi + +PUB=$(cat "$HOSTKEY.pub") +cat </: SSH host key (agenix identity) and Secure Boot keys. +{ + lib, + writeShellApplication, + coreutils, + git, + openssh, + sbctl, +}: +writeShellApplication { + name = "create-keys"; + runtimeInputs = [ + coreutils + git + openssh + sbctl + ]; + text = builtins.readFile ./create-keys.sh; + meta = { + description = "Create the SSH host key and Secure Boot keys for a host (keys//)"; + mainProgram = "create-keys"; + platforms = lib.platforms.linux; + }; +} diff --git a/pkgs/default.nix b/pkgs/default.nix new file mode 100644 index 0000000..ef13ece --- /dev/null +++ b/pkgs/default.nix @@ -0,0 +1,18 @@ +# Our own packages: install and key helpers. Imported by overlays/additions.nix, +# so they show up as pkgs. on every host and on the installer ISO. +{ pkgs, inputs }: +let + inherit (pkgs.stdenv.hostPlatform) system; + + secret-from-file = pkgs.callPackage ./secret-from-file { }; +in +{ + inherit secret-from-file; + + install-system = pkgs.callPackage ./install-system { + disko = inputs.disko.packages.${system}.disko; + }; + create-keys = pkgs.callPackage ./create-keys { }; + set-password = pkgs.callPackage ./set-password { inherit secret-from-file; }; + switch-system = pkgs.callPackage ./switch-system { }; +} diff --git a/pkgs/install-system/default.nix b/pkgs/install-system/default.nix new file mode 100644 index 0000000..0c24775 --- /dev/null +++ b/pkgs/install-system/default.nix @@ -0,0 +1,42 @@ +# Installer for this flake: disks (disko), keys, secrets check, nixos-install. +# nixos-install, nixos-generate-config and nixos-enter come from the NixOS +# installer environment, not from here. +{ + lib, + writeShellApplication, + coreutils, + findutils, + gawk, + gnugrep, + gnutar, + util-linux, + jq, + git, + age, + openssh, + sbctl, + disko, +}: +writeShellApplication { + name = "install-system"; + runtimeInputs = [ + coreutils + findutils + gawk + gnugrep + gnutar + util-linux + jq + git + age + openssh + sbctl + disko + ]; + text = builtins.readFile ./install-system.sh; + meta = { + description = "Partition, install and key this NixOS flake from the NixOS installer"; + mainProgram = "install-system"; + platforms = lib.platforms.linux; + }; +} diff --git a/pkgs/install-system/install-system.sh b/pkgs/install-system/install-system.sh new file mode 100644 index 0000000..526074b --- /dev/null +++ b/pkgs/install-system/install-system.sh @@ -0,0 +1,773 @@ +#!/usr/bin/env bash +# install-system: install this flake onto the machine, from the NixOS installer. +# +# Flow: locate flake -> pick disks -> confirm -> disko -> hardware config -> +# host SSH key (+ secrets check) -> Secure Boot keys -> nixos-install -> +# password -> copy the repo into the new home directory. +set -euo pipefail + +HOST=desktop +FLAKE_ARG= +KEYS_ARG= +DISKO_MODE='destroy,format,mount' +ASSUME_YES=0 +FORCE_SELECT=0 +MNT=/mnt +WORKCOPY=/root/nixos-config + +if [ -t 1 ]; then + RED=$'\033[1;31m' + GRN=$'\033[1;32m' + YEL=$'\033[1;33m' + BLU=$'\033[1;34m' + RST=$'\033[0m' +else + RED= + GRN= + YEL= + BLU= + RST= +fi + +info() { printf '%s==>%s %s\n' "$BLU" "$RST" "$*"; } +ok() { printf '%s ok%s %s\n' "$GRN" "$RST" "$*"; } +warn() { printf '%swarning:%s %s\n' "$YEL" "$RST" "$*" >&2; } +die() { + printf '%serror:%s %s\n' "$RED" "$RST" "$*" >&2 + exit 1 +} + +usage() { + cat <<'EOF' +Usage: install-system [options] + +Partitions the disks, installs NixOS from this flake and prepares secrets and +Secure Boot keys. Run it as root from the NixOS installer (UEFI mode). + +Options: + --host NAME flake host to install (default: desktop) + --flake DIR flake directory (default: current directory if it has a + flake.nix, else /etc/nixos-config on the installer ISO) + --keys-dir DIR directory with /ssh_host_ed25519_key and + /sbctl (default: /keys, then mounted sticks) + --disko-mode MODE destroy,format,mount (default, WIPES the disks), + format,mount, or mount (nothing is wiped: re-runs/repairs) + --select-disks choose the disks again even if disk-ids.json is valid + -y, --yes do not ask for the typed confirmation + -h, --help show this help +EOF +} + +need_value() { + [ "$2" -ge 2 ] || die "option $1 needs a value (see --help)" +} + +while [ "$#" -gt 0 ]; do + case "$1" in + --host) + need_value "$1" "$#" + HOST=$2 + shift 2 + ;; + --flake) + need_value "$1" "$#" + FLAKE_ARG=$2 + shift 2 + ;; + --keys-dir) + need_value "$1" "$#" + KEYS_ARG=$2 + shift 2 + ;; + --disko-mode) + need_value "$1" "$#" + DISKO_MODE=$2 + shift 2 + ;; + --select-disks) + FORCE_SELECT=1 + shift + ;; + -y | --yes) + ASSUME_YES=1 + shift + ;; + -h | --help) + usage + exit 0 + ;; + *) die "unknown argument: $1 (see --help)" ;; + esac +done + +case "$HOST" in + '' | *[!A-Za-z0-9_-]*) die "invalid host name: '$HOST'" ;; +esac +case "$DISKO_MODE" in + destroy,format,mount | format,mount | mount) ;; + *) die "--disko-mode must be destroy,format,mount, format,mount or mount" ;; +esac + +# Everything that nix runs needs flakes; the flake's own nixConfig (binary +# caches) is accepted because the flake is our own. +NIX=(nix --extra-experimental-features 'nix-command flakes') +export NIX_CONFIG="${NIX_CONFIG:+$NIX_CONFIG$'\n'}experimental-features = nix-command flakes"$'\n'"accept-flake-config = true" + +umask 022 +WORK=$(mktemp -d) +trap 'rm -rf "$WORK"' EXIT + +FLAKE= +FLAKE_SRC= +KEYS_DIR= +KEYS_WRITABLE=0 +IDS_FILE= +SYS_DISK= +DATA_DISK= +USER_NAME= +USER_UID= +SB_ENABLE=false +SECRETS_ENABLE=false +HOST_PUB= +NEW_HOST_KEY=0 +DESTRUCTIVE=0 +case "$DISKO_MODE" in + mount) ;; + *) DESTRUCTIVE=1 ;; +esac + +is_writable_dir() { + local t + t=$(mktemp -p "$1" .write-test.XXXXXX 2>/dev/null) || return 1 + rm -f "$t" +} + +git_() { git -C "$FLAKE" "$@"; } + +# Flakes only see files that git tracks, so new files must be added. +git_add() { + git_ add -- "$@" || warn "git add $* failed: the flake will not see these files" +} + +preflight() { + [ "$(id -u)" -eq 0 ] || die "run as root: sudo install-system" + [ -d /sys/firmware/efi ] || + die "not booted in UEFI mode (/sys/firmware/efi is missing). Boot the USB stick in UEFI mode: Secure Boot and systemd-boot need it." + local c + for c in nix nixos-install nixos-generate-config nixos-enter disko git jq age ssh-keygen lsblk findmnt; do + command -v "$c" >/dev/null || die "missing command '$c': run this from the NixOS installer" + done +} + +# FLAKE_SRC is where the flake came from, FLAKE the writable git checkout used +# for the install. They differ when the source is read-only (installer ISO), +# not a git repository, or owned by another user (git would refuse it). +locate_flake() { + local cand top + if [ -n "$FLAKE_ARG" ]; then + cand=$FLAKE_ARG + elif [ -f "$PWD/flake.nix" ]; then + cand=$PWD + elif [ -f /etc/nixos-config/flake.nix ]; then + cand=/etc/nixos-config + else + die "no flake found: run from the repository, or pass --flake DIR" + fi + [ -f "$cand/flake.nix" ] || die "no flake.nix in $cand" + FLAKE_SRC=$(readlink -f "$cand") + + local reason= + if ! is_writable_dir "$FLAKE_SRC"; then + reason="it is read-only" + elif ! top=$(git -C "$FLAKE_SRC" rev-parse --show-toplevel 2>/dev/null) || + [ "$(readlink -f "$top")" != "$FLAKE_SRC" ]; then + reason="it is not a usable git repository root" + fi + + if [ -z "$reason" ]; then + FLAKE=$FLAKE_SRC + if [ -n "$(git_ ls-files -- keys)" ]; then + die "keys/ is tracked by git: private keys would be copied to the Nix store. Run: git rm -r --cached keys" + fi + ok "flake: $FLAKE" + return + fi + + info "flake source $FLAKE_SRC cannot be used in place ($reason); copying to $WORKCOPY" + if [ -e "$WORKCOPY" ]; then + rm -rf "${WORKCOPY:?}.old" + mv "$WORKCOPY" "$WORKCOPY.old" + warn "previous working copy moved to $WORKCOPY.old" + fi + mkdir -p "$WORKCOPY" + # keys/ must never end up in a path: flake (it would be copied into the + # world-readable Nix store), so it is not copied; KEYS_DIR points at the source. + tar -C "$FLAKE_SRC" --exclude=./keys --exclude=./result --exclude='./result-*' -cf - . | + tar -C "$WORKCOPY" --no-same-owner -xf - + chown -R root:root "$WORKCOPY" + chmod -R u+rwX "$WORKCOPY" + FLAKE=$WORKCOPY + if ! git -C "$FLAKE" rev-parse --show-toplevel >/dev/null 2>&1; then + rm -rf "$FLAKE/.git" + git -C "$FLAKE" init -q -b main + git -C "$FLAKE" add -A + git -C "$FLAKE" -c user.name=install-system -c user.email=install-system@localhost \ + commit -q -m "Import flake for installation" + fi + ok "flake: $FLAKE (copy of $FLAKE_SRC)" +} + +# Best effort: keep generated files on the stick so a re-run starts from them. +sync_back() { + [ "$FLAKE" != "$FLAKE_SRC" ] || return 0 + is_writable_dir "$FLAKE_SRC" || return 0 + local rel + for rel in "$@"; do + if [ -f "$FLAKE/$rel" ]; then + install -D -m 0644 "$FLAKE/$rel" "$FLAKE_SRC/$rel" 2>/dev/null || + warn "could not save $rel back to $FLAKE_SRC" + fi + done +} + +ensure_lock() { + if [ -f "$FLAKE/flake.lock" ]; then + return + fi + info "no flake.lock yet: locking all flake inputs (needs network, takes a minute)" + "${NIX[@]}" flake lock "$FLAKE" || die "could not lock the flake inputs (network?)" + git_add flake.lock + sync_back flake.lock +} + +find_keys_dir() { + if [ -n "$KEYS_ARG" ]; then + KEYS_DIR=$(readlink -f "$KEYS_ARG") + else + KEYS_DIR="$FLAKE_SRC/keys" + if [ ! -d "$KEYS_DIR/$HOST" ]; then + local d + for d in /run/media/*/*/keys /run/media/*/keys /media/*/keys /media/*/*/keys; do + if [ -d "$d/$HOST" ]; then + KEYS_DIR=$d + break + fi + done + fi + fi + if mkdir -p "$KEYS_DIR" 2>/dev/null && is_writable_dir "$KEYS_DIR"; then + KEYS_WRITABLE=1 + fi + if [ -f "$KEYS_DIR/$HOST/ssh_host_ed25519_key" ]; then + ok "keys: $KEYS_DIR/$HOST" + elif [ "$KEYS_WRITABLE" -eq 1 ]; then + info "no keys for $HOST in $KEYS_DIR yet: they will be generated and saved there" + else + warn "no keys for $HOST found and $KEYS_DIR is not writable: new keys will exist only on the target" + fi +} + +# ---- disks ----------------------------------------------------------------- + +disk_ok() { + case "$1" in + '' | *CHANGE-ME*) return 1 ;; + esac + [ -e "$1" ] && [ -b "$(readlink -f "$1")" ] +} + +disk_desc() { + local real + real=$(readlink -f "$1") + printf '%s (%s)' "$real" "$(lsblk -dno SIZE,MODEL "$real" 2>/dev/null | tr -s ' ')" +} + +# Mount points on a disk and everything below it (partitions, mappers). +disk_mounts() { + lsblk -J -o NAME,MOUNTPOINTS "$1" 2>/dev/null | + jq -r '[.blockdevices[] | recurse(.children[]?) | .mountpoints[]? | select(. != null)] | unique | .[]' +} + +# Anything mounted outside /mnt means: live USB, or the running system. +disk_busy_mounts() { + local m + while IFS= read -r m; do + case "$m" in + '' | '[SWAP]' | "$MNT" | "$MNT"/*) ;; + *) printf '%s ' "$m" ;; + esac + done < <(disk_mounts "$1") +} + +# Best stable name for /dev/: shortest by-id link that is not wwn/eui/partition. +by_id_for() { + local name=$1 best='' p base + for p in /dev/disk/by-id/*; do + [ -e "$p" ] || continue + [ "$(readlink -f "$p")" = "/dev/$name" ] || continue + base=${p##*/} + case "$base" in + wwn-* | *eui.* | *-part*) continue ;; + esac + if [ -z "$best" ] || [ "${#base}" -lt "${#best}" ]; then + best=$base + fi + done + if [ -n "$best" ]; then + printf '/dev/disk/by-id/%s' "$best" + else + printf '/dev/%s' "$name" + fi +} + +CAND_DEV=() +CAND_SIZE=() +CAND_MODEL=() +CAND_TRAN=() +CAND_ID=() + +list_candidates() { + local name size model tran busy + CAND_DEV=() + CAND_SIZE=() + CAND_MODEL=() + CAND_TRAN=() + CAND_ID=() + while IFS=$'\t' read -r name size model tran; do + busy=$(disk_busy_mounts "/dev/$name") + if [ -n "$busy" ]; then + printf ' skipping %-10s %-8s in use (mounted at: %s)\n' "$name" "$size" "$busy" + continue + fi + CAND_DEV+=("$name") + CAND_SIZE+=("$size") + CAND_MODEL+=("$model") + CAND_TRAN+=("$tran") + CAND_ID+=("$(by_id_for "$name")") + done < <(lsblk -d -J -o NAME,SIZE,MODEL,TRAN,TYPE | + jq -r '.blockdevices[] + | select(.type == "disk") + | select(.name | test("^(zram|ram|loop|sr|fd)") | not) + | [.name, .size, ((.model // "-") | gsub("^\\s+|\\s+$"; "") | if . == "" then "-" else . end), (.tran // "-")] + | @tsv') +} + +pick_disk() { + local label=$1 exclude=$2 n + while true; do + read -r -p "$label [1-${#CAND_DEV[@]}]: " n || die "no input (is this a terminal?)" + case "$n" in + '' | *[!0-9]*) + echo "enter a number from the list" + continue + ;; + esac + if [ "$n" -lt 1 ] || [ "$n" -gt "${#CAND_DEV[@]}" ]; then + echo "enter a number from the list" + continue + fi + if [ "$((n - 1))" -eq "$exclude" ]; then + echo "that disk is already used for the other role" + continue + fi + PICKED=$((n - 1)) + return + done +} + +prompt_for_disks() { + info "available disks (the live USB stick and mounted media are skipped):" + list_candidates + [ "${#CAND_DEV[@]}" -ge 2 ] || die "need at least two unused disks (system NVMe + data SSD), found ${#CAND_DEV[@]}" + local i + printf '\n %-3s %-12s %-9s %-6s %-30s %s\n' '#' DEVICE SIZE TRAN MODEL 'STABLE NAME' + for i in "${!CAND_DEV[@]}"; do + printf ' %-3s %-12s %-9s %-6s %-30s %s\n' "$((i + 1))" "${CAND_DEV[$i]}" "${CAND_SIZE[$i]}" \ + "${CAND_TRAN[$i]}" "${CAND_MODEL[$i]}" "${CAND_ID[$i]}" + done + printf '\n' + PICKED=-1 + pick_disk "SYSTEM disk (NVMe: /, /boot, /nix, swap)" -1 + local sys=$PICKED + pick_disk "DATA disk (SATA SSD: Games, Downloads, ...)" "$sys" + SYS_DISK=${CAND_ID[$sys]} + DATA_DISK=${CAND_ID[$PICKED]} + for i in "$SYS_DISK" "$DATA_DISK"; do + case "$i" in + /dev/disk/by-id/*) ;; + *) warn "$i has no stable /dev/disk/by-id name: the device name may change between boots" ;; + esac + done +} + +select_disks() { + IDS_FILE="$FLAKE/hosts/$HOST/disk-ids.json" + [ -d "$FLAKE/hosts/$HOST" ] || die "unknown host '$HOST': $FLAKE/hosts/$HOST does not exist" + if [ -f "$IDS_FILE" ]; then + SYS_DISK=$(jq -r '.system // ""' "$IDS_FILE" 2>/dev/null) || SYS_DISK= + DATA_DISK=$(jq -r '.data // ""' "$IDS_FILE" 2>/dev/null) || DATA_DISK= + fi + if [ "$FORCE_SELECT" -eq 0 ] && disk_ok "$SYS_DISK" && disk_ok "$DATA_DISK" && + [ "$(readlink -f "$SYS_DISK")" != "$(readlink -f "$DATA_DISK")" ]; then + ok "disks from hosts/$HOST/disk-ids.json" + return + fi + if [ "$FORCE_SELECT" -eq 0 ]; then + info "hosts/$HOST/disk-ids.json holds placeholders or devices that do not exist here" + fi + prompt_for_disks + jq -n --arg system "$SYS_DISK" --arg data "$DATA_DISK" '{system: $system, data: $data}' >"$WORK/ids.json" + install -m 0644 "$WORK/ids.json" "$IDS_FILE" + git_add "hosts/$HOST/disk-ids.json" + sync_back "hosts/$HOST/disk-ids.json" + ok "wrote hosts/$HOST/disk-ids.json" +} + +# ---- configuration values ---------------------------------------------------- + +eval_config() { + info "evaluating the configuration of $HOST (the first run downloads inputs)" + local json + json=$("${NIX[@]}" eval --json "$FLAKE#nixosConfigurations.$HOST.config.my" --apply ' + my: { + user = my.user.name; + uid = my.user.uid; + secureBoot = my.boot.secureBoot.enable; + secrets = my.secrets.enable; + }') || die "could not evaluate nixosConfigurations.$HOST (run: nix eval --show-trace $FLAKE#nixosConfigurations.$HOST.config.my.user.name)" + USER_NAME=$(jq -r '.user' <<<"$json") + USER_UID=$(jq -r '.uid' <<<"$json") + SB_ENABLE=$(jq -r '.secureBoot' <<<"$json") + SECRETS_ENABLE=$(jq -r '.secrets' <<<"$json") + case "$USER_NAME" in + '' | null | *[!A-Za-z0-9_.-]*) die "unexpected user name from the configuration: '$USER_NAME'" ;; + esac + case "$USER_UID" in + '' | *[!0-9]*) die "unexpected uid from the configuration: '$USER_UID'" ;; + esac + ok "user $USER_NAME (uid $USER_UID), Secure Boot: $SB_ENABLE, secrets: $SECRETS_ENABLE" +} + +# ---- confirmation --------------------------------------------------------------- + +# Refuse to touch a disk that holds the live system, this flake or the keys. +check_disks_not_live() { + local d busy path mp + for d in "$SYS_DISK" "$DATA_DISK"; do + busy=$(disk_busy_mounts "$(readlink -f "$d")") + if [ -n "$busy" ]; then + die "$d has mounted filesystems outside $MNT: $busy +It looks like the live USB stick or the running system. Pick other disks (--select-disks)." + fi + done + for path in "$FLAKE_SRC" "$KEYS_DIR"; do + mp=$(findmnt -n -o TARGET -T "$path" 2>/dev/null || true) + for d in "$SYS_DISK" "$DATA_DISK"; do + if [ -n "$mp" ] && disk_mounts "$(readlink -f "$d")" | grep -qxF "$mp"; then + die "$path lives on $d, which would be wiped" + fi + done + done +} + +confirm() { + if [ "$DESTRUCTIVE" -eq 0 ]; then + info "mode 'mount': existing partitions are mounted at $MNT, nothing is wiped" + return + fi + check_disks_not_live + printf '\n%s' "$RED" + cat <"$WORK/hw.nix" + grep -q 'boot.initrd.availableKernelModules' "$WORK/hw.nix" || + die "nixos-generate-config produced no usable hardware configuration" + install -m 0644 "$WORK/hw.nix" "$FLAKE/$rel" + git_add "$rel" + sync_back "$rel" + ok "wrote $rel" +} + +install_host_key() { + info "host SSH key (agenix identity)" + local src="$KEYS_DIR/$HOST/ssh_host_ed25519_key" + local dst="$MNT/etc/ssh/ssh_host_ed25519_key" + install -d -m 0755 -o root -g root "$MNT/etc/ssh" + if [ -f "$src" ]; then + install -m 0600 -o root -g root "$src" "$dst" + if [ -f "$src.pub" ]; then + install -m 0644 -o root -g root "$src.pub" "$dst.pub" + else + ssh-keygen -y -f "$dst" >"$WORK/hostkey.pub" + install -m 0644 -o root -g root "$WORK/hostkey.pub" "$dst.pub" + fi + ok "installed host key from $src" + elif [ -f "$dst" ]; then + ok "reusing host key already on the target ($dst)" + [ -f "$dst.pub" ] || ssh-keygen -y -f "$dst" >"$dst.pub" + else + ssh-keygen -q -t ed25519 -N '' -C "root@$HOST" -f "$dst" + NEW_HOST_KEY=1 + warn "generated a NEW host key; secrets must be encrypted for it (see below if the check fails)" + fi + chown root:root "$dst" "$dst.pub" + chmod 0600 "$dst" + chmod 0644 "$dst.pub" + HOST_PUB=$(cat "$dst.pub") + + if [ ! -f "$src" ]; then + if [ "$KEYS_WRITABLE" -eq 1 ]; then + install -d -m 0700 "$KEYS_DIR/$HOST" + install -m 0600 "$dst" "$src" + install -m 0644 "$dst.pub" "$src.pub" + ok "saved a copy to $KEYS_DIR/$HOST (keep it: re-installs reuse it)" + else + warn "$KEYS_DIR is not writable: back up $dst yourself, or secrets will not decrypt after a re-install" + fi + fi + printf ' host public key: %s\n' "$HOST_PUB" +} + +verify_secrets() { + if [ "$SECRETS_ENABLE" != true ]; then + info "my.secrets.enable is off: skipping the secrets check" + return + fi + local sdir="$FLAKE/secrets" hostkey="$MNT/etc/ssh/ssh_host_ed25519_key" + local files=() f + if [ -d "$sdir" ]; then + mapfile -t files < <(find "$sdir" -maxdepth 1 -type f -name '*.age' | sort) + fi + if [ "${#files[@]}" -eq 0 ]; then + info "no secrets/*.age files: nothing to check" + return + fi + info "checking that the host key can decrypt secrets/*.age" + + local hostmat rules='{}' + hostmat=$(awk '{print $2}' "$hostkey.pub") + if [ -f "$sdir/secrets.nix" ]; then + rules=$("${NIX[@]}" eval --json --file "$sdir/secrets.nix" \ + --apply 'r: builtins.mapAttrs (_: v: v.publicKeys) r' 2>/dev/null) || rules='{}' + fi + + local base listed failed=() warned=() + for f in "${files[@]}"; do + base=${f##*/} + listed=$(jq -r --arg f "$base" --arg k "$hostmat" ' + (.[$f] // []) + | map(select(type == "string") | split(" ") as $p | if ($p | length) > 1 then $p[1] else $p[0] end) + | any(. == $k)' <<<"$rules") + if [ "$rules" = '{}' ] && [ -f "$sdir/secrets.nix" ] && grep -qF "$hostmat" "$sdir/secrets.nix"; then + listed=true + fi + if age -d -i "$hostkey" "$f" >/dev/null 2>"$WORK/age.err"; then + ok "$base" + elif [ "$listed" = true ] || [ "$base" = "$USER_NAME-password.age" ]; then + failed+=("$base") + else + warned+=("$base") + fi + done + + for f in "${warned[@]}"; do + warn "$f is not encrypted for this host key; the installed system will not get it" + done + [ "${#failed[@]}" -eq 0 ] && return + + cat >&2 </keys/%s/ or the re-run keeps using it from there.\n' \ + "$hostkey" "$HOST" >&2 + fi + exit 1 +} + +install_sbctl_keys() { + if [ "$SB_ENABLE" != true ]; then + info "Secure Boot is disabled in the configuration: no sbctl keys needed" + return + fi + info "Secure Boot keys (sbctl)" + command -v sbctl >/dev/null || die "sbctl is not available" + local dst="$MNT/var/lib/sbctl" src="$KEYS_DIR/$HOST/sbctl" k + install -d -m 0700 -o root -g root "$dst" + if [ -d "$dst/keys" ] && [ -f "$dst/GUID" ]; then + ok "keys already on the target" + elif [ -d "$src/keys" ] && [ -f "$src/GUID" ]; then + cp -r --no-preserve=mode,ownership "$src/keys" "$dst/keys" + cp --no-preserve=mode,ownership "$src/GUID" "$dst/GUID" + ok "copied keys from $src" + else + # landlock would only allow writes below /var/lib, not below /mnt. + sbctl --disable-landlock create-keys --export "$dst/keys" --database-path "$dst/GUID" + fi + for k in PK KEK db; do + [ -f "$dst/keys/$k/$k.key" ] && [ -f "$dst/keys/$k/$k.pem" ] || + die "sbctl keys incomplete: $k.key or $k.pem missing below $dst/keys/$k" + done + chown -R root:root "$dst" + chmod 0700 "$dst" + find "$dst/keys" -type d -exec chmod 0700 {} + + find "$dst/keys" -type f -name '*.key' -exec chmod 0400 {} + + find "$dst/keys" -type f -name '*.pem' -exec chmod 0644 {} + + chmod 0644 "$dst/GUID" + + if [ ! -d "$src/keys" ]; then + if [ "$KEYS_WRITABLE" -eq 1 ]; then + install -d -m 0700 "$src" + cp -r --no-preserve=mode,ownership "$dst/keys" "$src/keys" + cp --no-preserve=mode,ownership "$dst/GUID" "$src/GUID" + ok "saved a copy to $src (keep it: re-installs reuse the enrolled keys)" + else + warn "$KEYS_DIR is not writable: back up $dst yourself, or you must re-enroll Secure Boot keys after a re-install" + fi + fi +} + +run_nixos_install() { + info "nixos-install (long: downloads and builds the system)" + nixos-install --flake "$FLAKE#$HOST" --no-root-passwd --no-channel-copy +} + +set_user_password() { + if [ "$SECRETS_ENABLE" = true ] && [ -f "$FLAKE/secrets/$USER_NAME-password.age" ]; then + ok "login password comes from secrets/$USER_NAME-password.age" + return + fi + info "no password secret: set the login password for $USER_NAME" + local i + for i in 1 2 3; do + if nixos-enter --root "$MNT" -c "passwd $(printf '%q' "$USER_NAME")"; then + ok "password set" + return + fi + warn "passwd failed (attempt $i of 3)" + done + warn "no password set: the configuration falls back to its initial password; change it with 'passwd' after the first login" +} + +copy_repo_to_home() { + info "copying the flake to ~/nixos-config" + local home="$MNT/home/$USER_NAME" dest="$MNT/home/$USER_NAME/nixos-config" m + [ -d "$home" ] || install -d -m 0700 -o "$USER_UID" -g 100 "$home" + rm -rf "${dest:?}" + mkdir -p "$dest" + tar -C "$FLAKE" --exclude=./keys --exclude=./result --exclude='./result-*' -cf - . | + tar -C "$dest" --no-same-owner -xf - + chown -R "$USER_UID:100" "$dest" + chmod -R u+rwX "$dest" + # The home directory and the data-disk subvolumes mounted into it are created + # by root; the user needs to own them (gid 100 is 'users' on NixOS). + chown "$USER_UID:100" "$home" + while IFS= read -r m; do + chown "$USER_UID:100" "$m" + done < <(findmnt -rn -o TARGET | awk -v h="$home/" 'index($0, h) == 1 && substr($0, length(h) + 1) !~ /\//') + if [ -d "$home/Games" ]; then + install -d -m 0755 -o "$USER_UID" -g 100 "$home/Games/SteamLibrary" + fi + sync + ok "copied to /home/$USER_NAME/nixos-config" +} + +next_steps() { + cat < Settings > Storage. + 4. The flake is in ~/nixos-config. Commit the files created by this install: + hosts/$HOST/disk-ids.json, hosts/$HOST/hardware-configuration.nix, flake.lock + (keys/ stays out of git). Rebuild later with: switch-system +EOF +} + +main() { + preflight + locate_flake + find_keys_dir + ensure_lock + select_disks + eval_config + confirm + run_disko + gen_hardware_config + install_host_key + verify_secrets + install_sbctl_keys + run_nixos_install + set_user_password + copy_repo_to_home + next_steps +} + +main diff --git a/pkgs/secret-from-file/default.nix b/pkgs/secret-from-file/default.nix new file mode 100644 index 0000000..edab0a7 --- /dev/null +++ b/pkgs/secret-from-file/default.nix @@ -0,0 +1,27 @@ +# Encrypts a file as secrets/.age for the recipients in secrets/secrets.nix. +# `nix` (to read secrets.nix) is taken from the system PATH. +{ + lib, + writeShellApplication, + coreutils, + diffutils, + git, + jq, + age, +}: +writeShellApplication { + name = "secret-from-file"; + runtimeInputs = [ + coreutils + diffutils + git + jq + age + ]; + text = builtins.readFile ./secret-from-file.sh; + meta = { + description = "Encrypt an existing file as secrets/.age using the agenix recipient rules"; + mainProgram = "secret-from-file"; + platforms = lib.platforms.linux; + }; +} diff --git a/pkgs/secret-from-file/secret-from-file.sh b/pkgs/secret-from-file/secret-from-file.sh new file mode 100644 index 0000000..510ed67 --- /dev/null +++ b/pkgs/secret-from-file/secret-from-file.sh @@ -0,0 +1,166 @@ +#!/usr/bin/env bash +# secret-from-file: encrypt an existing file (or stdin) as secrets/.age +# for the recipients listed in secrets/secrets.nix. Refuses to overwrite +# without --force. +set -euo pipefail + +FLAKE_ARG= +FORCE=0 +IDENTITY= +NAME= +SOURCE= + +if [ -t 2 ]; then + RED=$'\033[1;31m' + GRN=$'\033[1;32m' + RST=$'\033[0m' +else + RED= + GRN= + RST= +fi + +ok() { printf '%s ok%s %s\n' "$GRN" "$RST" "$*" >&2; } +die() { + printf '%serror:%s %s\n' "$RED" "$RST" "$*" >&2 + exit 1 +} + +usage() { + cat <<'EOF' +Usage: secret-from-file NAME.age SOURCE|- [options] + +Encrypts SOURCE (a file, or - for stdin) to secrets/NAME.age for the public +keys that secrets/secrets.nix lists under "NAME.age".publicKeys. + + -i, --identity FILE after encrypting, check that FILE (a private key that + is a recipient) can decrypt the result + --flake DIR flake directory (default: the repository you are in) + -f, --force replace an existing secrets/NAME.age + -h, --help show this help + +Examples: + secret-from-file ssh-id_ed25519.age ~/.ssh/id_ed25519 -i ~/.ssh/id_ed25519 + cp ~/.ssh/id_ed25519.pub secrets/ssh-id_ed25519.pub +EOF +} + +while [ "$#" -gt 0 ]; do + case "$1" in + -i | --identity) + [ "$#" -ge 2 ] || die "$1 needs a value" + IDENTITY=$2 + shift 2 + ;; + --flake) + [ "$#" -ge 2 ] || die "--flake needs a value" + FLAKE_ARG=$2 + shift 2 + ;; + -f | --force) + FORCE=1 + shift + ;; + -h | --help) + usage + exit 0 + ;; + -) + if [ -z "$SOURCE" ]; then SOURCE=-; else die "unexpected argument: -"; fi + shift + ;; + -*) die "unknown option: $1 (see --help)" ;; + *) + if [ -z "$NAME" ]; then + NAME=$1 + elif [ -z "$SOURCE" ]; then + SOURCE=$1 + else + die "unexpected argument: $1" + fi + shift + ;; + esac +done + +[ -n "$NAME" ] && [ -n "$SOURCE" ] || { + usage >&2 + exit 2 +} +case "$NAME" in + *.age) ;; + *) NAME=$NAME.age ;; +esac +# The name ends up inside a Nix expression: keep it boring. +case "$NAME" in + *[!A-Za-z0-9._-]* | .*) die "secret name may only contain letters, digits, '.', '_' and '-': $NAME" ;; +esac +if [ "$SOURCE" != - ] && [ ! -f "$SOURCE" ]; then + die "no such file: $SOURCE" +fi +if [ -n "$IDENTITY" ] && [ ! -f "$IDENTITY" ]; then + die "identity file not found: $IDENTITY" +fi + +find_flake() { + local d + if [ -n "$FLAKE_ARG" ]; then + d=$FLAKE_ARG + elif d=$(git rev-parse --show-toplevel 2>/dev/null) && [ -f "$d/flake.nix" ]; then + : + elif [ -f "$PWD/flake.nix" ]; then + d=$PWD + else + die "no flake found: run inside the repository or pass --flake DIR" + fi + [ -f "$d/flake.nix" ] || die "no flake.nix in $d" + readlink -f "$d" +} + +FLAKE=$(find_flake) +SECRETS="$FLAKE/secrets" +RULES="$SECRETS/secrets.nix" +OUT="$SECRETS/$NAME" +[ -f "$RULES" ] || die "$RULES not found" +if [ -e "$OUT" ] && [ "$FORCE" -eq 0 ]; then + die "$OUT already exists (use --force to replace it)" +fi + +umask 077 +WORK=$(mktemp -d) +trap 'rm -rf "$WORK"' EXIT + +if ! KEYS_JSON=$(nix --extra-experimental-features 'nix-command flakes' eval --json \ + --file "$RULES" --apply "r: r.\"$NAME\".publicKeys" 2>"$WORK/eval.err"); then + cat "$WORK/eval.err" >&2 + die "no rule for \"$NAME\" in $RULES. Add: + \"$NAME\".publicKeys = recipients;" +fi +if jq -e 'any(.[]; test("PLACEHOLDER"))' <<<"$KEYS_JSON" >/dev/null; then + die "$RULES still contains PLACEHOLDER keys: replace them first (create-keys prints the host key)" +fi +jq -r '.[]' <<<"$KEYS_JSON" >"$WORK/recipients" +[ -s "$WORK/recipients" ] || die "\"$NAME\" has no recipients in $RULES" + +if [ "$SOURCE" = - ]; then + cat >"$WORK/plain" + SOURCE=$WORK/plain +fi + +age --encrypt --armor -R "$WORK/recipients" -o "$WORK/out.age" "$SOURCE" || + die "encryption failed: check that every key in $RULES is valid" + +if [ -n "$IDENTITY" ]; then + age --decrypt -i "$IDENTITY" "$WORK/out.age" | cmp -s - "$SOURCE" || + die "$IDENTITY cannot decrypt the result: it is not one of the recipients; nothing was written" + ok "verified with $IDENTITY" +fi + +install -m 0644 "$WORK/out.age" "$OUT" +ok "wrote $OUT" + +if git -C "$FLAKE" rev-parse --is-inside-work-tree >/dev/null 2>&1; then + if git -C "$FLAKE" add -- "secrets/$NAME"; then + ok "git add secrets/$NAME (flakes only see tracked files)" + fi +fi diff --git a/pkgs/set-password/default.nix b/pkgs/set-password/default.nix new file mode 100644 index 0000000..41a36bb --- /dev/null +++ b/pkgs/set-password/default.nix @@ -0,0 +1,20 @@ +# Hashes a login password (yescrypt) and stores it via secret-from-file. +{ + lib, + writeShellApplication, + mkpasswd, + secret-from-file, +}: +writeShellApplication { + name = "set-password"; + runtimeInputs = [ + mkpasswd + secret-from-file + ]; + text = builtins.readFile ./set-password.sh; + meta = { + description = "Set the login password of a user as an agenix secret (secrets/-password.age)"; + mainProgram = "set-password"; + platforms = lib.platforms.linux; + }; +} diff --git a/pkgs/set-password/set-password.sh b/pkgs/set-password/set-password.sh new file mode 100644 index 0000000..fa39b43 --- /dev/null +++ b/pkgs/set-password/set-password.sh @@ -0,0 +1,82 @@ +#!/usr/bin/env bash +# set-password: hash a login password (yescrypt) and store it, encrypted with +# agenix recipients, as secrets/-password.age. +set -euo pipefail + +USER_NAME=faumaray +FLAKE_ARG= +IDENTITY= +FORCE=0 + +die() { + printf 'error: %s\n' "$*" >&2 + exit 1 +} + +usage() { + cat <<'EOF' +Usage: set-password [--user NAME] [--flake DIR] [-i IDENTITY] [--force] + +Asks for a password, hashes it with 'mkpasswd -m yescrypt' and encrypts the hash +to secrets/NAME-password.age (recipients: secrets/secrets.nix). + + --user NAME login name (default: faumaray) + --flake DIR flake directory (default: the repository you are in) + -i, --identity FILE verify the result decrypts with this private key + -f, --force replace an existing secrets/NAME-password.age +EOF +} + +while [ "$#" -gt 0 ]; do + case "$1" in + --user) + [ "$#" -ge 2 ] || die "--user needs a value" + USER_NAME=$2 + shift 2 + ;; + --flake) + [ "$#" -ge 2 ] || die "--flake needs a value" + FLAKE_ARG=$2 + shift 2 + ;; + -i | --identity) + [ "$#" -ge 2 ] || die "$1 needs a value" + IDENTITY=$2 + shift 2 + ;; + -f | --force) + FORCE=1 + shift + ;; + -h | --help) + usage + exit 0 + ;; + *) die "unknown argument: $1 (see --help)" ;; + esac +done + +case "$USER_NAME" in + '' | *[!A-Za-z0-9_-]*) die "invalid user name: '$USER_NAME'" ;; +esac + +args=("$USER_NAME-password.age" -) +if [ -n "$FLAKE_ARG" ]; then args+=(--flake "$FLAKE_ARG"); fi +if [ -n "$IDENTITY" ]; then args+=(--identity "$IDENTITY"); fi +if [ "$FORCE" -eq 1 ]; then args+=(--force); fi + +[ -t 0 ] || die "run this in a terminal: the password is read interactively" +read -r -s -p "Password for $USER_NAME: " pw1 +echo +read -r -s -p "Repeat password: " pw2 +echo +[ -n "$pw1" ] || die "empty password" +[ "$pw1" = "$pw2" ] || die "passwords differ" + +# The password goes through stdin only, never through argv. +hash=$(printf '%s' "$pw1" | mkpasswd -m yescrypt -s) +unset pw1 pw2 +printf '%s\n' "$hash" | secret-from-file "${args[@]}" + +echo +echo "Rebuild (switch-system) or reinstall to use the new password." diff --git a/pkgs/switch-system/default.nix b/pkgs/switch-system/default.nix new file mode 100644 index 0000000..a0ff14d --- /dev/null +++ b/pkgs/switch-system/default.nix @@ -0,0 +1,21 @@ +# Rebuild this machine from the flake (nh when present, else nixos-rebuild). +# nh and nixos-rebuild are taken from the system PATH on purpose. +{ + lib, + writeShellApplication, + coreutils, + git, +}: +writeShellApplication { + name = "switch-system"; + runtimeInputs = [ + coreutils + git + ]; + text = builtins.readFile ./switch-system.sh; + meta = { + description = "Rebuild and switch this NixOS machine from its flake (nh os / nixos-rebuild)"; + mainProgram = "switch-system"; + platforms = lib.platforms.linux; + }; +} diff --git a/pkgs/switch-system/switch-system.sh b/pkgs/switch-system/switch-system.sh new file mode 100644 index 0000000..12a3694 --- /dev/null +++ b/pkgs/switch-system/switch-system.sh @@ -0,0 +1,85 @@ +#!/usr/bin/env bash +# switch-system: rebuild and activate this machine from the flake. +# Uses `nh os` when available, else `sudo nixos-rebuild`. +set -euo pipefail + +HOST= +FLAKE_ARG= +ACTION=switch + +die() { + printf 'error: %s\n' "$*" >&2 + exit 1 +} + +usage() { + cat <<'EOF' +Usage: switch-system [--host NAME] [--flake DIR] [boot|switch|test] + + --host NAME flake host (default: this machine's host name) + --flake DIR flake directory (default: the repository you are in, else + ~/nixos-config) + switch build, activate now and make it the boot default (default) + boot build and activate on next boot + test build and activate now without touching the boot entry +EOF +} + +while [ "$#" -gt 0 ]; do + case "$1" in + --host) + [ "$#" -ge 2 ] || die "--host needs a value" + HOST=$2 + shift 2 + ;; + --flake) + [ "$#" -ge 2 ] || die "--flake needs a value" + FLAKE_ARG=$2 + shift 2 + ;; + boot | switch | test) + ACTION=$1 + shift + ;; + -h | --help) + usage + exit 0 + ;; + *) die "unknown argument: $1 (see --help)" ;; + esac +done + +if [ -z "$HOST" ]; then + HOST=$(cat /proc/sys/kernel/hostname) +fi + +# After `sudo`, $HOME can be root's: prefer the home of the invoking user. +home=$HOME +if [ -n "${SUDO_USER:-}" ]; then + home=$(getent passwd "$SUDO_USER" | cut -d: -f6) +fi + +if [ -n "$FLAKE_ARG" ]; then + DIR=$FLAKE_ARG +elif top=$(git rev-parse --show-toplevel 2>/dev/null) && [ -f "$top/flake.nix" ]; then + DIR=$top +elif [ -f "$home/nixos-config/flake.nix" ]; then + DIR=$home/nixos-config +else + die "no flake found: run inside the repository or pass --flake DIR" +fi +[ -f "$DIR/flake.nix" ] || die "no flake.nix in $DIR" +DIR=$(readlink -f "$DIR") + +# Flakes only see files tracked by git: warn about new, untracked files. +if git -C "$DIR" rev-parse --is-inside-work-tree >/dev/null 2>&1; then + untracked=$(git -C "$DIR" ls-files --others --exclude-standard) + if [ -n "$untracked" ]; then + printf 'warning: untracked files are invisible to the flake (git add them):\n%s\n' "$untracked" >&2 + fi +fi + +if command -v nh >/dev/null 2>&1; then + exec nh os "$ACTION" --hostname "$HOST" "$DIR" +fi +exec sudo nixos-rebuild "$ACTION" --flake "$DIR#$HOST"