repositories

NixDaemon

NixOS pentest workstation as one flake — IceBreaker's successor

clonegit clone https://git.daemon-sec.xyz/NixDaemon.git
session.nixNix322 lines13.6 KiBraw download
# modules/home/session.nix — what every Wayland session needs, whichever
# compositor is running: the polkit agent (privilege prompts), clipboard
# history, auto-mounting, and the screenshot / clipboard tools the Niri binds
# and the toolbox scripts expect on PATH. Grim + Satty capture and annotate
# screenshots; Loupe opens images and zathura opens PDFs by default. Not gated on a desktop switch, so a
# Niri-only system keeps working. Everything hangs off graphical-session.target,
# which uwsm (Hyprland) and niri-session both manage.
{ self, ... }:
let
  theme = import ../_palette.nix;
  sattySettings = {
    general = {
      fullscreen = false;
      initial-tool = "pointer";
      early-exit = [];
      auto-copy = false;
      save-after-copy = false;
      actions-on-enter = [ "save-to-file" "save-to-clipboard" ];
      actions-on-escape = [ "exit" ];
      copy-command = "wl-copy --type image/png";
      default-fill-shapes = true;
      corner-roundness = 0;
      notification-thumbnail = "app-icon";
    };
    font.family = "Noto Sans";
    color-palette.palette = [ "#000000" "#ffffff" ] ++
      (map (name: theme.palette.${name}) [ "rose" "love" "gold" "pine" "foam" "iris" ]);
  };
in
{
  perSystem = { pkgs, ... }: {
    packages.niri-screensaver = pkgs.stdenvNoCC.mkDerivation {
      pname = "niri-screensaver";
      version = "2026-10-12";
      src = pkgs.fetchzip {
        url = "https://github.com/jfreed-dev/niri-screensaver/archive/d8a204ddba4ad41af9fb4c8b02b75228f1ef628a.tar.gz";
        hash = "sha256-8zFTuZ+HphU/5L/5ic2Qc8tyxCmrcbmlFAv+F8US/UA=";
      };
      nativeBuildInputs = [ pkgs.makeWrapper ];
      dontBuild = true;
      installPhase = ''
        runHook preInstall
        mkdir -p "$out/bin" "$out/share/niri-screensaver"
        cp bin/niri-screensaver{,-launch,-ctl} "$out/bin/"
        chmod +x "$out/bin/"*
        cp -r share/* "$out/share/niri-screensaver/"
        substituteInPlace "$out/bin/niri-screensaver-launch" \
          --replace-fail '-- alacritty' '-- ${pkgs.alacritty}/bin/alacritty'
        substituteInPlace "$out/share/niri-screensaver/alacritty-screensaver.toml" \
          --replace-fail '#000000' '${theme.palette.base}' \
          --replace-fail '#ffffff' '${theme.palette.text}'
        ${pkgs.figlet}/bin/figlet -f small NixDaemon > "$out/share/niri-screensaver/logos/nixdaemon.txt"
        for program in "$out/bin/"*; do
          wrapProgram "$program" \
            --set NIRI_SCREENSAVER_DATA "$out/share/niri-screensaver" \
            --prefix PATH : ${pkgs.lib.makeBinPath [ pkgs.alacritty pkgs.niri pkgs.jq pkgs.python3Packages.terminaltexteffects pkgs.figlet pkgs.playerctl pkgs.libnotify pkgs.procps pkgs.coreutils pkgs.gnugrep pkgs.gawk pkgs.bash ]}
        done
        runHook postInstall
      '';
      meta.mainProgram = "niri-screensaver-launch";
    };

    packages.screen-record = pkgs.writeShellApplication {
      name = "screen-record";
      runtimeInputs = with pkgs; [ wf-recorder slurp pulseaudio libnotify coreutils jq util-linux gawk ];
      text = ''
        umask 077
        state="''${XDG_RUNTIME_DIR:?No Wayland session}/nixdaemon-recorder"
        mkdir -p "$state"
        is_recording() {
          [ -s "$state/pid" ] || return 1
          read -r pid born < "$state/pid"
          [[ "$pid" =~ ^[0-9]+$ && "$born" =~ ^[0-9]+$ ]] || return 1
          [ -r "/proc/$pid/stat" ] || return 1
          [ "$(awk '{print $22}' "/proc/$pid/stat")" = "$born" ] && kill -0 "$pid" 2>/dev/null
        }
        mode="''${1:-video}"
        case "$mode" in
          status) is_recording; exit $? ;;
          stop)
            if is_recording; then kill -INT "$pid"; fi
            exit 0 ;;
          video|audio) ;;
          *) echo 'Usage: screen-record [video|audio|stop|status]' >&2; exit 2 ;;
        esac
        exec 9> "$state/lock"
        flock -n 9 || exit 0
        plugin="''${XDG_CONFIG_HOME:-$HOME/.config}/noctalia/plugins/screen-shot-and-record/settings.json"
        directory="$HOME/Videos"
        notifications=true
        if [ -f "$plugin" ]; then
          selected=$(jq -r '.recordingSavePath // empty' "$plugin")
          [ -z "$selected" ] || directory="$selected"
          notifications=$(jq -r 'if .recordingNotifications == false then false else true end' "$plugin")
        fi
        case "$directory" in
          \~/*) directory="$HOME/''${directory:2}" ;;
        esac
        case "$directory" in
          /*) ;;
          *) notify-send -a Recorder "Invalid recording folder" "Choose an absolute folder path."; exit 1 ;;
        esac
        mkdir -p "$directory"
        sleep 0.25
        geometry=$(slurp -d -c '${theme.palette.rose}ff' -b '${theme.palette.base}99' -s '${theme.palette.rose}22') || exit 0
        audio=()
        if [ "$mode" = audio ]; then
          sink=$(pactl get-default-sink) || { notify-send -a Recorder "Recording failed" "Could not find the desktop audio output."; exit 1; }
          audio=("--audio=$sink.monitor")
        fi
        output="$directory/Recording-$(date +%Y-%m-%d_%H-%M-%S-%N).mp4"
        recorder=""
        cleanup() {
          if [ -n "$recorder" ]; then
            kill -INT "$recorder" 2>/dev/null || true
            wait "$recorder" 2>/dev/null || true
          fi
          rm -f "$state/pid"
        }
        trap cleanup EXIT
        trap 'exit 130' INT TERM
        # Pad odd-size regions for H.264; SIGINT finalizes the MP4 on Stop.
        wf-recorder --geometry "$geometry" --file "$output" --codec libx264 \
          --pixel-format yuv420p -F 'pad=ceil(iw/2)*2:ceil(ih/2)*2' "''${audio[@]}" &
        recorder=$!
        if [ ! -r "/proc/$recorder/stat" ]; then
          notify-send -a Recorder "Recording failed" "The recorder could not start."; exit 1
        fi
        born=$(awk '{print $22}' "/proc/$recorder/stat")
        printf '%s %s\n' "$recorder" "$born" > "$state/pid"
        sleep 0.5
        if ! is_recording; then
          notify-send -a Recorder "Recording failed" "The recorder exited before recording could start."; exit 1
        fi
        if [ "$notifications" = true ]; then notify-send -a Recorder "Recording started" "Use Stop in the screenshot plugin to finish."; fi
        result=0
        wait "$recorder" || result=$?
        recorder=""
        if [ "$result" -eq 0 ] && [ -s "$output" ]; then
          if [ "$notifications" = true ]; then notify-send -a Recorder "Recording saved" "$output"; fi
        else
          notify-send -a Recorder "Recording failed" "Check the recorder output before using this video."; exit 1
        fi
      '';
    };

    # Grim + slurp + Tesseract: select a region, read the text in it, copy it.
    # Languages are baked in (English and Spanish); `screen-ocr spa` picks one,
    # anything else tesseract accepts (eng+spa) works too.
    packages.screen-ocr =
      let tesseract = pkgs.tesseract.override { enableLanguages = [ "eng" "spa" "osd" ]; };
      in pkgs.writeShellApplication {
        name = "screen-ocr";
        runtimeInputs = [ tesseract ] ++ (with pkgs; [ grim slurp wl-clipboard libnotify coreutils ]);
        text = ''
          umask 077
          lang="''${1:-eng}"
          case "$lang" in
            -h|--help) echo 'Usage: screen-ocr [LANGUAGE]   # eng (default), spa, eng+spa' >&2; exit 0 ;;
          esac
          # Let a bar panel close before selecting the region.
          sleep 0.25
          geometry=$(slurp -d -c '${theme.palette.rose}ff' -b '${theme.palette.base}99' -s '${theme.palette.rose}22') || exit 0
          capture=$(mktemp "''${XDG_RUNTIME_DIR:-/tmp}/screen-ocr-XXXXXXXX.png")
          trap 'rm -f "$capture"' EXIT
          grim -g "$geometry" "$capture" || {
            notify-send -a OCR "OCR failed" "The region could not be captured."; exit 1
          }
          text=$(tesseract "$capture" - -l "$lang" 2>/dev/null) || {
            notify-send -a OCR "OCR failed" "Tesseract could not read that region."; exit 1
          }
          # Drop the blank lines and trailing form feed Tesseract leaves behind.
          text=$(printf '%s' "$text" | sed -e 's/[[:space:]]*$//' -e '/^$/d')
          if [ -z "$text" ]; then
            notify-send -a OCR "No text found" "Nothing readable in that region."
            exit 0
          fi
          printf '%s' "$text" | wl-copy --type text/plain
          notify-send -a OCR "Text copied" "$(printf '%s' "$text" | head -c 200)"
        '';
      };

    packages.screenshot =
      let defaults = (pkgs.formats.toml {}).generate "satty.toml" sattySettings;
      in pkgs.writeShellApplication {
        name = "screenshot";
        runtimeInputs = with pkgs; [ grim slurp satty wl-clipboard libnotify coreutils jq zenity xdg-user-dirs ];
        text = ''
          umask 077
          mode="''${1:-region}"
          state="''${XDG_STATE_HOME:-$HOME/.local/state}/nixdaemon-screenshot"
          mkdir -p "$state"
          config="''${XDG_CONFIG_HOME:-$HOME/.config}/satty/config.toml"
          [ -f "$config" ] || config=${defaults}
          pictures=$(xdg-user-dir PICTURES)
          [ "$pictures" != "$HOME" ] || pictures="$HOME/Pictures"
          directory="$pictures/Screenshots"
          [ ! -s "$state/directory" ] || IFS= read -r directory < "$state/directory"
          # The bar's writable plugin setting is also used by keyboard captures.
          plugin="''${XDG_CONFIG_HOME:-$HOME/.config}/noctalia/plugins/screen-shot-and-record/settings.json"
          if [ -f "$plugin" ]; then
            selected=$(jq -r '.savePath // empty' "$plugin")
            [ -z "$selected" ] || directory="$selected"
          fi
          if [ "''${2:-}" = "--directory" ]; then directory="$3"; fi
          case "$directory" in
            \~/*) directory="$HOME/''${directory:2}" ;;
          esac
          case "$directory" in
            /*) ;;
            *) notify-send -a Screenshot "Invalid screenshot folder" "Choose an absolute folder path."; exit 1 ;;
          esac
          mkdir -p "$directory"
          case "$mode" in
            folder)
              selected=$(zenity --file-selection --directory --title="Screenshot save folder" --filename="$directory/") || exit 0
              [ -n "$selected" ] || exit 0
              printf '%s\n' "$selected" > "$state/directory"
              if [ -f "$plugin" ]; then
                updated=$(jq --arg directory "$selected" '.savePath = $directory' "$plugin")
                printf '%s\n' "$updated" > "$plugin"
              fi
              notify-send -a Screenshot "Screenshot save folder" "$selected"
              exit 0 ;;
            region|screen|clipboard) ;;
            *) echo 'Usage: screenshot [region|screen|clipboard|folder] [--directory PATH]' >&2; exit 2 ;;
          esac
          # Let a bar panel close before selecting/capturing the desktop.
          sleep 0.25
          capture=$(mktemp "''${XDG_RUNTIME_DIR:-/tmp}/screenshot-XXXXXXXX.png")
          trap 'rm -f "$capture"' EXIT
          if [ "$mode" = screen ]; then
            grim "$capture"
          else
            geometry=$(slurp -d -c '${theme.palette.rose}ff' -b '${theme.palette.base}99' -s '${theme.palette.rose}22') || exit 0
            grim -g "$geometry" "$capture"
          fi
          if [ "$mode" = clipboard ]; then
            wl-copy --type image/png < "$capture"
            notify-send -a Screenshot "Screenshot copied" "Ready to paste."
          else
            # Escape percent signs because Satty expands strftime patterns.
            output="''${directory//%/%%}/Screenshot-$(date +%Y-%m-%d_%H-%M-%S-%N).png"
            satty --config "$config" --filename "$capture" --output-filename "$output"
          fi
        '';
      };
  };

  flake.homeModules.session =
  { lib, pkgs, ... }:
  {
    home.packages = with pkgs; [
      grim
      slurp
      wl-clipboard
      libnotify
      self.packages.${pkgs.stdenv.hostPlatform.system}.screenshot
      self.packages.${pkgs.stdenv.hostPlatform.system}.screen-record
      self.packages.${pkgs.stdenv.hostPlatform.system}.screen-ocr
      loupe
    ];

    programs.satty = { enable = true; settings = sattySettings; };
    xdg.desktopEntries.screenshot = {
      name = "Screenshot";
      comment = "Capture a region, blur, censor, annotate and save";
      exec = "screenshot region";
      icon = "satty";
      categories = [ "Graphics" "Utility" ];
      terminal = false;
      actions = {
        screen = { name = "Capture whole screen"; exec = "screenshot screen"; };
        folder = { name = "Choose screenshot save folder"; exec = "screenshot folder"; };
      };
    };

    xdg.mimeApps = {
      enable = true;
      defaultApplications =
        lib.genAttrs [
          "application/pdf"
          "application/postscript"
          "image/vnd.djvu"
          "application/vnd.comicbook+zip"
        ] (_: [ "org.pwmt.zathura.desktop" ])
        // lib.genAttrs [
          "image/png"
          "image/jpeg"
          "image/gif"
          "image/webp"
          "image/avif"
          "image/heif"
          "image/jxl"
          "image/bmp"
          "image/tiff"
          "image/svg+xml"
          "image/x-icon"
        ] (_: [ "org.gnome.Loupe.desktop" ]);
    };

    systemd.user.services.hyprpolkitagent = {
      Unit = {
        Description = "Hyprland polkit authentication agent";
        After = [ "graphical-session.target" ];
        PartOf = [ "graphical-session.target" ];
      };
      Service = {
        ExecStart = "${pkgs.hyprpolkitagent}/libexec/hyprpolkitagent";
        Restart = "on-failure";
        Slice = "session.slice";
      };
      Install.WantedBy = [ "graphical-session.target" ];
    };
    services.cliphist.enable = true; # history for `caelestia clipboard` and Noctalia's clipboard tab
    services.udiskie = {
      enable = true;
      tray = "auto";
    };
  }
  ;
}