main
   1{
   2  config,
   3  globals,
   4  lib,
   5  libx,
   6  pkgs,
   7  ...
   8}:
   9let
  10  # Common security headers for Caddy
  11  securityHeaders = ''
  12    header {
  13      Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
  14      X-Content-Type-Options "nosniff"
  15      X-Frame-Options "SAMEORIGIN"
  16      Referrer-Policy "strict-origin-when-cross-origin"
  17      Permissions-Policy "geolocation=(), microphone=(), camera=(), payment=(), usb=(), magnetometer=(), gyroscope=(), accelerometer=()"
  18      Content-Security-Policy "default-src 'self' *.sbr.pm *.demeester.fr; style-src 'self' 'unsafe-inline'; script-src 'self'"
  19      X-XSS-Protection "1; mode=block"
  20      Cache-Control "public, max-age=604800, immutable"
  21      -Server
  22    }
  23  '';
  24
  25  # Security headers for media services (more permissive CSP for multimedia)
  26  mediaSecurityHeaders = ''
  27    header {
  28      Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
  29      X-Content-Type-Options "nosniff"
  30      X-Frame-Options "SAMEORIGIN"
  31      Referrer-Policy "strict-origin-when-cross-origin"
  32      Permissions-Policy "geolocation=(), microphone=(), camera=(), payment=(), usb=()"
  33      -Server
  34    }
  35  '';
  36
  37  # Security headers for git repository viewer (allow inline scripts/styles for gitmal)
  38  gitSecurityHeaders = ''
  39    header {
  40      Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
  41      X-Content-Type-Options "nosniff"
  42      X-Frame-Options "SAMEORIGIN"
  43      Referrer-Policy "strict-origin-when-cross-origin"
  44      Permissions-Policy "geolocation=(), microphone=(), camera=(), payment=(), usb=()"
  45      Content-Security-Policy "default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'"
  46      X-XSS-Protection "1; mode=block"
  47      -Server
  48    }
  49  '';
  50
  51  # Robots.txt snippet - polite request to AI scrapers
  52  robotsTxtSnippet = ''
  53        @robots path /robots.txt
  54        handle @robots {
  55          respond 200 {
  56            body `User-agent: CCBot
  57    Disallow: /
  58
  59    User-agent: ChatGPT-User
  60    Disallow: /
  61
  62    User-agent: GPTBot
  63    Disallow: /
  64
  65    User-agent: Google-Extended
  66    Disallow: /
  67
  68    User-agent: anthropic-ai
  69    Disallow: /
  70
  71    User-agent: Omgilibot
  72    Disallow: /
  73
  74    User-agent: Omgili
  75    Disallow: /
  76
  77    User-agent: FacebookBot
  78    Disallow: /`
  79            close
  80          }
  81        }
  82  '';
  83
  84  # HTTP echo template - echoes request headers as plain text
  85  echoTemplate = pkgs.writeTextDir "index.txt" ''
  86    HTTP Echo — echo.sbr.pm
  87    ========================
  88
  89    Request
  90    -------
  91    {{.Req.Method}} {{placeholder "http.request.orig_uri"}} {{.Req.Proto}}
  92
  93    Headers
  94    -------
  95    {{range $name, $values := .Req.Header}}{{range $values}}{{$name}}: {{.}}
  96    {{end}}{{end}}
  97    Connection
  98    ----------
  99    Host: {{.Req.Host}}
 100    Remote IP: {{.RemoteIP}}
 101  '';
 102
 103  # AI bot blocking snippet - enforcement via HTTP 403
 104  blockAIBotsSnippet = ''
 105    @aibots {
 106      header User-Agent *CCBot*
 107      header User-Agent *ChatGPT-User*
 108      header User-Agent *GPTBot*
 109      header User-Agent *Google-Extended*
 110      header User-Agent *anthropic-ai*
 111      header User-Agent *Omgilibot*
 112      header User-Agent *Omgili*
 113      header User-Agent *FacebookBot*
 114    }
 115    handle @aibots {
 116      respond "AI scraping not permitted" 403
 117    }
 118  '';
 119in
 120{
 121  imports = [
 122
 123    ../common/services/openssh.nix
 124  ];
 125
 126  # ── Praetorian SSH command gating ───────────────────────────────────
 127  # Gates command-restricted keys (see globals.ssh.vincent) to git over SSH.
 128  # authorized_keys entries use command="praetorian run <alias>"; these aliases
 129  # define what each is allowed to run. Repos live under /home/vincent/git.
 130  services.praetorian = {
 131    enable = true;
 132    aliases = {
 133      # aomi TPM key: full git push + pull on any repo under ~/git.
 134      aomi-git.allow = {
 135        "git-receive-pack" = {
 136          arg = {
 137            pos = 1;
 138            glob = "/home/vincent/git/**";
 139          };
 140          num_args = 1;
 141        };
 142        "git-upload-pack" = {
 143          arg = {
 144            pos = 1;
 145            glob = "/home/vincent/git/**";
 146          };
 147          num_args = 1;
 148        };
 149      };
 150      # Termux phones: pull-only on any repo under ~/git (src/home, passage, ...).
 151      git-pull.allow = {
 152        "git-upload-pack" = {
 153          arg = {
 154            pos = 1;
 155            glob = "/home/vincent/git/**";
 156          };
 157          num_args = 1;
 158        };
 159      };
 160      # kyushu TPM key: full git push + pull on any repo under ~/git.
 161      kyushu-git.allow = {
 162        "git-receive-pack" = {
 163          arg = {
 164            pos = 1;
 165            glob = "/home/vincent/git/**";
 166          };
 167          num_args = 1;
 168        };
 169        "git-upload-pack" = {
 170          arg = {
 171            pos = 1;
 172            glob = "/home/vincent/git/**";
 173          };
 174          num_args = 1;
 175        };
 176      };
 177      # Passage sync keys: pull-only on the passage store repo.
 178      passage-pull.allow = {
 179        "git-upload-pack" = {
 180          arg = {
 181            pos = 1;
 182            glob = "/home/vincent/git/passage.git";
 183          };
 184          num_args = 1;
 185        };
 186      };
 187    };
 188  };
 189
 190  # ── Fail2ban ────────────────────────────────────────────────────────
 191  services.fail2ban = {
 192    enable = true;
 193
 194    # Ban for 1 hour, increase on repeat offenders via recidive jail
 195    bantime = "1h";
 196    bantime-increment = {
 197      enable = true;
 198      maxtime = "168h"; # Max 1 week ban
 199      factor = "4"; # Aggressive escalation
 200    };
 201
 202    maxretry = 5;
 203
 204    # Ignore VPN, loopback, and dynamic home IP (managed by athena)
 205    ignoreIP = [
 206      "127.0.0.0/8"
 207      "::1"
 208      "10.100.0.0/24" # WireGuard VPN
 209    ];
 210
 211    jails = {
 212      # Caddy auth failures (401/403 responses)
 213      caddy-auth = ''
 214        enabled = true
 215        backend = auto
 216        filter = caddy-auth
 217        logpath = /var/log/caddy/access*.log
 218        maxretry = 10
 219        findtime = 600
 220        bantime = 3600
 221      '';
 222
 223      # Caddy aggressive scanning (404 floods)
 224      caddy-scan = ''
 225        enabled = true
 226        backend = auto
 227        filter = caddy-scan
 228        logpath = /var/log/caddy/access*.log
 229        maxretry = 30
 230        findtime = 60
 231        bantime = 3600
 232      '';
 233
 234      # Caddy rate abuse (too many requests)
 235      caddy-flood = ''
 236        enabled = true
 237        backend = auto
 238        filter = caddy-flood
 239        logpath = /var/log/caddy/access*.log
 240        maxretry = 200
 241        findtime = 60
 242        bantime = 7200
 243      '';
 244    };
 245  };
 246
 247  # Caddy fail2ban filters for JSON access logs
 248  environment.etc = {
 249    # Ban IPs that get too many 401/403 responses (brute force / unauthorized access)
 250    # Excludes services with their own auth that naturally return 401 for token refreshes
 251    "fail2ban/filter.d/caddy-auth.conf".text = ''
 252      [Definition]
 253      failregex = ^.*"remote_ip":"<HOST>".*"status":(401|403),.*$
 254      ignoreregex = ^.*"host":"immich\.sbr\.pm".*$
 255                    ^.*"host":"photos\.sbr\.pm".*$
 256                    ^.*"host":"navidrome\.sbr\.pm".*$
 257                    ^.*"host":"music\.sbr\.pm".*$
 258                    ^.*"host":"jellyfin\.sbr\.pm".*$
 259                    ^.*"host":"audiobookshelf\.sbr\.pm".*$
 260                    ^.*"host":"podcasts\.sbr\.pm".*$
 261                    ^.*"host":"ntfy\.sbr\.pm".*$
 262      datepattern = "ts":{EPOCH}
 263    '';
 264
 265    # Ban IPs that trigger excessive 404s (scanning for vulnerabilities)
 266    # Exclude git.sbr.pm: dumb-HTTP git clones probe many loose objects,
 267    # generating bursts of 404s that look like scanning but are legitimate.
 268    "fail2ban/filter.d/caddy-scan.conf".text = ''
 269      [Definition]
 270      failregex = ^.*"remote_ip":"<HOST>".*"status":404,.*$
 271      ignoreregex = ^.*"host":"git\.sbr\.pm".*$
 272      datepattern = "ts":{EPOCH}
 273    '';
 274
 275    # Ban IPs with excessive request volume (flood / DDoS)
 276    "fail2ban/filter.d/caddy-flood.conf".text = ''
 277      [Definition]
 278      failregex = ^.*"remote_ip":"<HOST>".*"status":\d+,.*$
 279      ignoreregex = ^.*"remote_ip":"10\.100\.0\..*$
 280                    ^.*"host":"ntfy\.sbr\.pm".*$
 281                    ^.*"host":"git\.sbr\.pm".*$
 282                    ^.*"host":"music\.sbr\.pm".*$
 283                    ^.*"host":"navidrome\.sbr\.pm".*$
 284                    ^.*"host":"immich\.sbr\.pm".*$
 285                    ^.*"host":"photos\.sbr\.pm".*$
 286                    ^.*"host":"audiobookshelf\.sbr\.pm".*$
 287                    ^.*"host":"podcasts\.sbr\.pm".*$
 288                    ^.*"host":"jellyfin\.sbr\.pm".*$
 289      datepattern = "ts":{EPOCH}
 290    '';
 291  };
 292
 293  # Dynamic home IP whitelist for fail2ban
 294  # athena pushes the home public IP to /var/lib/fail2ban/home-ip.txt via SSH
 295  # A path unit watches the file and reloads fail2ban ignoreip accordingly
 296  systemd.tmpfiles.settings.fail2ban = {
 297    "/var/lib/fail2ban".d = {
 298      mode = "0755";
 299      user = "root";
 300      group = "root";
 301    };
 302  };
 303
 304  systemd.services.fail2ban-home-ip = {
 305    description = "Update fail2ban with dynamic home IP";
 306    serviceConfig = {
 307      Type = "oneshot";
 308      ExecStart = pkgs.writeShellScript "fail2ban-home-ip" ''
 309        #!/usr/bin/env bash
 310        set -euo pipefail
 311        IP_FILE="/var/lib/fail2ban/home-ip.txt"
 312        if [ ! -f "$IP_FILE" ]; then
 313          echo "No home IP file found, skipping"
 314          exit 0
 315        fi
 316        NEW_IP=$(${pkgs.coreutils}/bin/cat "$IP_FILE" | ${pkgs.coreutils}/bin/tr -d '[:space:]')
 317        if [ -z "$NEW_IP" ]; then
 318          echo "Empty IP file, skipping"
 319          exit 0
 320        fi
 321        # Validate IP format
 322        if ! echo "$NEW_IP" | ${pkgs.gnugrep}/bin/grep -qP '^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$'; then
 323          echo "Invalid IP format: $NEW_IP"
 324          exit 1
 325        fi
 326        OLD_IP_FILE="/var/lib/fail2ban/home-ip-current.txt"
 327        OLD_IP=""
 328        if [ -f "$OLD_IP_FILE" ]; then
 329          OLD_IP=$(${pkgs.coreutils}/bin/cat "$OLD_IP_FILE" | ${pkgs.coreutils}/bin/tr -d '[:space:]')
 330        fi
 331        if [ "$NEW_IP" = "$OLD_IP" ]; then
 332          echo "Home IP unchanged: $NEW_IP"
 333          exit 0
 334        fi
 335        echo "Updating home IP: $OLD_IP -> $NEW_IP"
 336        # Remove old IP from all jails
 337        if [ -n "$OLD_IP" ]; then
 338          for jail in caddy-auth caddy-flood caddy-scan sshd; do
 339            ${pkgs.fail2ban}/bin/fail2ban-client set "$jail" delignoreip "$OLD_IP" 2>/dev/null || true
 340            # Also unban in case it was already banned
 341            ${pkgs.fail2ban}/bin/fail2ban-client set "$jail" unbanip "$OLD_IP" 2>/dev/null || true
 342          done
 343        fi
 344        # Add new IP to all jails
 345        for jail in caddy-auth caddy-flood caddy-scan sshd; do
 346          ${pkgs.fail2ban}/bin/fail2ban-client set "$jail" addignoreip "$NEW_IP" 2>/dev/null || true
 347          # Unban new IP too in case it was banned before being whitelisted
 348          ${pkgs.fail2ban}/bin/fail2ban-client set "$jail" unbanip "$NEW_IP" 2>/dev/null || true
 349        done
 350        echo "$NEW_IP" > "$OLD_IP_FILE"
 351        echo "Home IP updated successfully: $NEW_IP"
 352      '';
 353    };
 354    after = [ "fail2ban.service" ];
 355    requires = [ "fail2ban.service" ];
 356  };
 357
 358  systemd.paths.fail2ban-home-ip = {
 359    description = "Watch for home IP changes";
 360    wantedBy = [ "multi-user.target" ];
 361    pathConfig = {
 362      PathModified = "/var/lib/fail2ban/home-ip.txt";
 363    };
 364  };
 365
 366  # Allow athena to write the home IP file via SSH
 367  # athena will: curl -s ifconfig.me | ssh carthage.vpn 'cat > /var/lib/fail2ban/home-ip.txt'
 368
 369  # Age secrets
 370  age.secrets."ntfy-token" = {
 371    file = ../../secrets/sakhalin/ntfy-token.age;
 372    mode = "400";
 373    owner = "root";
 374    group = "root";
 375  };
 376
 377  age.secrets."flux-github-token" = {
 378    file = ../../secrets/carthage/flux-github-token.age;
 379    mode = "400";
 380    owner = "vincent";
 381    group = "users";
 382  };
 383
 384  # Flux — website generator (hourly)
 385  systemd.tmpfiles.rules = [
 386    "d /var/lib/flux 0755 vincent users -"
 387    # Separate public notes; initially empty and maintained by vincent.
 388    "d /var/www/notes 0755 vincent users -"
 389    # Git directory permissions (for Caddy access to public repos)
 390    "d /home/vincent 0711 vincent users -" # Allow traversal to git directory
 391    "d /home/vincent/git 0700 vincent users -" # Private git directory
 392    "d /home/vincent/git/public 0755 vincent users -" # Public repositories only
 393    "d /var/log/git-builds 0755 vincent users -" # Git build logs
 394  ];
 395
 396  systemd.services.flux-generate = {
 397    description = "Generate and deploy vincent.demeester.fr";
 398    serviceConfig = {
 399      Type = "oneshot";
 400      User = "vincent";
 401      Group = "users";
 402      WorkingDirectory = "/var/lib/flux";
 403      ExecStart = "/var/lib/flux/www/scripts/flux-generate.sh";
 404      Environment = "HOME=/home/vincent";
 405    };
 406    path = with pkgs; [
 407      nix
 408      bash
 409      git
 410      openssh
 411      rsync
 412      coreutils
 413      findutils
 414      gnused
 415      gnugrep
 416      gnutar
 417      gzip
 418    ];
 419  };
 420
 421  systemd.timers.flux-generate = {
 422    description = "Generate website hourly";
 423    wantedBy = [ "timers.target" ];
 424    timerConfig = {
 425      OnCalendar = "hourly";
 426      Persistent = true;
 427      RandomizedDelaySec = "5min";
 428    };
 429  };
 430
 431  # Public, read-only notes. No writable folders, authentication, or comments.
 432  systemd.services.aniflow = {
 433    description = "Read-only public notes";
 434    wantedBy = [ "multi-user.target" ];
 435    serviceConfig = {
 436      DynamicUser = true;
 437      ExecStart = "${pkgs.aniflow}/bin/aniflow /var/www/notes --host 127.0.0.1 --port 8099 --base /notes --allow-host vincent.demeester.fr --no-comments";
 438      Restart = "on-failure";
 439      ProtectSystem = "strict";
 440      ProtectHome = true;
 441      PrivateTmp = true;
 442      NoNewPrivileges = true;
 443    };
 444  };
 445
 446  # Allow Caddy to access git repositories in vincent's home
 447  users.users.caddy.extraGroups = [ "users" ];
 448
 449  # Allow vincent to run systemd-run without password (for git hooks)
 450  # Use /run/current-system/sw/bin path to avoid hardcoded Nix store paths
 451  security.sudo.extraRules = [
 452    {
 453      users = [ "vincent" ];
 454      commands = [
 455        {
 456          command = "/run/current-system/sw/bin/systemd-run";
 457          options = [ "NOPASSWD" ];
 458        }
 459        {
 460          command = "${pkgs.rsync}/bin/rsync -a --delete /var/lib/pds/ /tmp/pds-backup/";
 461          options = [ "NOPASSWD" ];
 462        }
 463      ];
 464    }
 465  ];
 466
 467  # Install gitmal for self-hosted git web view
 468  environment.systemPackages = with pkgs; [
 469    gitmal
 470  ];
 471
 472  # Git hook background task execution with notifications
 473  systemd.services."git-notify@" = {
 474    description = "Git build notification for %i";
 475    serviceConfig = {
 476      Type = "oneshot";
 477      ExecStart = "${pkgs.writeShellScript "git-notify" ''
 478        #!/usr/bin/env bash
 479        set -euo pipefail
 480
 481        UNIT_NAME="$1"
 482        RESULT=$(${pkgs.systemd}/bin/systemctl show -p Result --value "$UNIT_NAME")
 483        EXIT_CODE=$(${pkgs.systemd}/bin/systemctl show -p ExecMainStatus --value "$UNIT_NAME")
 484
 485        # Get execution timestamps (in microseconds since epoch)
 486        START_TIME=$(${pkgs.systemd}/bin/systemctl show -p ExecMainStartTimestamp --value "$UNIT_NAME")
 487        EXIT_TIME=$(${pkgs.systemd}/bin/systemctl show -p ExecMainExitTimestamp --value "$UNIT_NAME")
 488
 489        # Calculate duration in seconds
 490        START_EPOCH=$(${pkgs.coreutils}/bin/date -d "$START_TIME" +%s 2>/dev/null || echo "0")
 491        EXIT_EPOCH=$(${pkgs.coreutils}/bin/date -d "$EXIT_TIME" +%s 2>/dev/null || echo "0")
 492        DURATION=$((EXIT_EPOCH - START_EPOCH))
 493
 494        # Format duration as human-readable
 495        if [ "$DURATION" -ge 60 ]; then
 496          MINUTES=$((DURATION / 60))
 497          SECONDS=$((DURATION % 60))
 498          DURATION_STR="''${MINUTES}m ''${SECONDS}s"
 499        else
 500          DURATION_STR="''${DURATION}s"
 501        fi
 502
 503        # Parse unit name to extract job type and repo
 504        # Format: git-<job>-<repo>-<timestamp>
 505        JOB_TYPE=$(echo "$UNIT_NAME" | cut -d'-' -f2)
 506        REPO=$(echo "$UNIT_NAME" | cut -d'-' -f3)
 507
 508        # Only notify on failure
 509        if [ "$RESULT" != "success" ]; then
 510          ${pkgs.curl}/bin/curl -s \
 511            -H "Authorization: Bearer $(${pkgs.coreutils}/bin/tr -d '\n' < ${
 512              config.age.secrets."ntfy-token".path
 513            })" \
 514            -H "Title: ❌ Git $JOB_TYPE Failed: $REPO (after $DURATION_STR)" \
 515            -H "Priority: high" \
 516            -H "Tags: x,git,$JOB_TYPE,warning" \
 517            -d "Job $UNIT_NAME failed after $DURATION_STR (exit code: $EXIT_CODE). Check logs: journalctl -u $UNIT_NAME" \
 518            "https://ntfy.sbr.pm/git-builds" || true
 519        fi
 520      ''} %i";
 521    };
 522  };
 523
 524  # Helper script for gitmal generation (called from post-receive hooks)
 525  environment.etc."git-hooks/generate-gitmal.sh" = {
 526    text = ''
 527      #!${pkgs.bash}/bin/bash
 528      set -euo pipefail
 529
 530      # Set PATH to include git and coreutils (gitmal needs git, script needs basename)
 531      export PATH="${pkgs.git}/bin:${pkgs.coreutils}/bin:$PATH"
 532
 533      REPO_PATH="$1"
 534      THEME="''${2:-github-dark}"  # Default to 'github-dark' theme if not specified
 535      REPO_NAME=$(basename "$REPO_PATH" .git)
 536      OUTPUT_DIR="/home/vincent/git/public/$REPO_NAME"
 537
 538      echo "Generating gitmal for repository: $REPO_NAME"
 539      echo "Repository path: $REPO_PATH"
 540      echo "Output directory: $OUTPUT_DIR"
 541      echo "Theme: $THEME"
 542
 543      # Generate static site with gitmal
 544      cd "$REPO_PATH"
 545      ${pkgs.gitmal}/bin/gitmal --output "$OUTPUT_DIR" --theme "$THEME"
 546
 547      echo "Gitmal generation complete: $OUTPUT_DIR"
 548    '';
 549    mode = "0755";
 550  };
 551
 552  # Remote build forwarding script
 553  environment.etc."git-hooks/forward-build.sh" = {
 554    text = ''
 555      #!${pkgs.bash}/bin/bash
 556      set -euo pipefail
 557
 558      REPO_NAME="$1"
 559      BUILD_TYPE="''${2:-auto}"
 560      TIMESTAMP=$(${pkgs.coreutils}/bin/date +%Y%m%d-%H%M%S)
 561      UNIT_NAME="build-remote-''${REPO_NAME}-''${TIMESTAMP}"
 562
 563      echo "Forwarding build to aomi: $REPO_NAME ($BUILD_TYPE)..."
 564
 565      # SSH to aomi and trigger build with systemd-run
 566      ${pkgs.openssh}/bin/ssh -o BatchMode=yes builder@10.100.0.17 \
 567        "sudo /run/current-system/sw/bin/systemd-run \
 568          --unit=\"$UNIT_NAME\" \
 569          --description=\"Remote build: $REPO_NAME ($BUILD_TYPE)\" \
 570          --property=\"OnSuccess=job-notify@\''${UNIT_NAME}.service\" \
 571          --property=\"OnFailure=job-notify@\''${UNIT_NAME}.service\" \
 572          --property=\"User=builder\" \
 573          --property=\"Group=users\" \
 574          --property=\"WorkingDirectory=/var/lib/git-builds\" \
 575          /etc/git-builds/execute-build.sh \"$REPO_NAME\" \"$BUILD_TYPE\""
 576
 577      echo "✓ Build queued on aomi: $UNIT_NAME"
 578      echo "  View status: ssh aomi 'systemctl status $UNIT_NAME'"
 579      echo "  View logs:   ssh aomi 'journalctl -u $UNIT_NAME'"
 580    '';
 581    mode = "0755";
 582  };
 583
 584  # Example post-receive hook template
 585  environment.etc."git-hooks/post-receive.example" = {
 586    text = ''
 587      #!${pkgs.bash}/bin/bash
 588      # Example post-receive hook for git repositories
 589      # Copy this to your repository's hooks/post-receive and make it executable
 590      #
 591      # This hook uses systemd-run to execute gitmal generation in the background
 592      # with automatic notifications via ntfy when the job completes.
 593      #
 594      # Optionally, it can also trigger remote builds on aomi.
 595
 596      set -euo pipefail
 597
 598      # Configuration
 599      GITMAL_ENABLED="true"
 600      GITMAL_THEME="github-dark"  # Options: github-dark, github-light, dark, light, auto
 601      REMOTE_BUILD_ENABLED="false"  # Set to "true" to enable remote builds on aomi
 602      BUILD_TYPE="nixos"             # Options: nixos, make, docker, go, custom, auto
 603
 604      REPO_PATH="$(pwd)"
 605      REPO_NAME=$(basename "$REPO_PATH" .git)
 606      TIMESTAMP=$(date +%Y%m%d-%H%M%S)
 607
 608      # 1. Generate gitmal (local static site on carthage)
 609      if [ "$GITMAL_ENABLED" = "true" ]; then
 610        UNIT_NAME="git-gitmal-''${REPO_NAME}-''${TIMESTAMP}"
 611        echo "Queuing gitmal generation for $REPO_NAME with theme: $GITMAL_THEME..."
 612
 613        sudo /run/current-system/sw/bin/systemd-run \
 614          --unit="$UNIT_NAME" \
 615          --description="Gitmal generation for $REPO_NAME" \
 616          --property="OnSuccess=git-notify@''${UNIT_NAME}.service" \
 617          --property="OnFailure=git-notify@''${UNIT_NAME}.service" \
 618          --property="User=vincent" \
 619          --property="Group=users" \
 620          --working-directory="$REPO_PATH" \
 621          /etc/git-hooks/generate-gitmal.sh "$REPO_PATH" "$GITMAL_THEME"
 622
 623        echo "✓ Gitmal generation queued as: $UNIT_NAME"
 624        echo "  View status: systemctl status $UNIT_NAME"
 625        echo "  View logs:   journalctl -u $UNIT_NAME"
 626      fi
 627
 628      # 2. Trigger remote build (on aomi)
 629      if [ "$REMOTE_BUILD_ENABLED" = "true" ]; then
 630        /etc/git-hooks/forward-build.sh "$REPO_NAME" "$BUILD_TYPE"
 631      fi
 632    '';
 633    mode = "0755";
 634  };
 635
 636  # Git directory permissions are set in the systemd.tmpfiles.rules above (with flux)
 637
 638  # Disable TPM2 (VPS has no TPM hardware)
 639  security.tpm2.enable = lib.mkForce false;
 640
 641  # Override common SSH config to restrict to VPN network only
 642  # SSH only on VPN interface — no public access
 643  services.openssh = {
 644    listenAddresses = [
 645      {
 646        addr = builtins.head globals.machines.carthage.net.vpn.ips;
 647        port = 22;
 648      }
 649    ];
 650    openFirewall = lib.mkForce false;
 651  };
 652
 653  services.wireguard.server = {
 654    enable = true;
 655    ips = libx.wg-ips globals.machines.carthage.net.vpn.ips;
 656    peers = libx.generateWireguardPeers globals.machines;
 657  };
 658
 659  services.gosmee = {
 660    enable = true;
 661    public-url = "https://webhook.sbr.pm";
 662  };
 663
 664  services.ntfy-sh = {
 665    enable = true;
 666    settings = {
 667      base-url = "https://ntfy.sbr.pm";
 668      upstream-base-url = "https://ntfy.sh";
 669      listen-http = "localhost:8111";
 670      behind-proxy = true;
 671      enable-login = true;
 672      auth-default-access = "deny-all";
 673    };
 674  };
 675
 676  # Firewall configuration
 677  # TODO: Migrate to nftables once wireguard server module supports it
 678  networking.firewall = {
 679    allowPing = true;
 680    # Public ports
 681    allowedTCPPorts = [
 682      80 # HTTP
 683      443 # HTTPS
 684    ];
 685
 686    # Additional iptables rules
 687    extraCommands = ''
 688      # Allow node exporter (9000) only from VPN network
 689      iptables -A nixos-fw -p tcp -s 10.100.0.0/24 --dport 9000 -j nixos-fw-accept
 690
 691      # Allow microsocks SOCKS5 proxy (1080) only from VPN network
 692      iptables -A nixos-fw -p tcp -s 10.100.0.0/24 --dport 1080 -j nixos-fw-accept
 693
 694      # Block known SYN flood source (USBINF INFORMATICA LTDA, Brazil)
 695      iptables -I nixos-fw 1 -s 45.233.176.0/22 -j DROP
 696      ip6tables -I nixos-fw 1 -s ::ffff:45.233.176.0/118 -j DROP
 697
 698      # SYN flood protection: limit new connections per /24 subnet
 699      iptables -A nixos-fw -p tcp --syn -m connlimit --connlimit-above 30 --connlimit-mask 24 -j DROP
 700      ip6tables -A nixos-fw -p tcp --syn -m connlimit --connlimit-above 30 --connlimit-mask 24 -j DROP
 701    '';
 702  };
 703  # ATProto PDS (Personal Data Server)
 704  age.secrets."pds.env" = {
 705    file = ../../secrets/carthage/pds.env.age;
 706    mode = "400";
 707    owner = "pds";
 708    group = "pds";
 709  };
 710
 711  age.secrets."restic-aix-password" = {
 712    file = ../../secrets/carthage/restic-aix-password.age;
 713    mode = "400";
 714    owner = "vincent";
 715    group = "users";
 716  };
 717
 718  services.restic.backups.aix-pds = {
 719    user = "vincent";
 720    repository = "sftp:vincent@aix.sbr.pm:/data/backup/restic/carthage";
 721    passwordFile = config.age.secrets."restic-aix-password".path;
 722
 723    paths = [
 724      "/tmp/pds-backup" # Snapshot copy of PDS data
 725    ];
 726
 727    timerConfig = {
 728      OnCalendar = "daily";
 729      Persistent = true;
 730      RandomizedDelaySec = "1h";
 731    };
 732
 733    pruneOpts = [
 734      "--keep-daily 7"
 735      "--keep-weekly 4"
 736      "--keep-monthly 12"
 737    ];
 738
 739    extraBackupArgs = [
 740      "--exclude-caches"
 741      "--verbose"
 742    ];
 743
 744    checkOpts = [
 745      "--read-data-subset=5%"
 746    ];
 747
 748    backupPrepareCommand = ''
 749      ${pkgs.coreutils}/bin/rm -rf /tmp/pds-backup
 750      ${pkgs.sudo}/bin/sudo ${pkgs.rsync}/bin/rsync -a --delete /var/lib/pds/ /tmp/pds-backup/
 751      ${pkgs.curl}/bin/curl \
 752        -H "Authorization: Bearer $(${pkgs.coreutils}/bin/tr -d '\n' < ${
 753          config.age.secrets."ntfy-token".path
 754        })" \
 755        -H "Title: Restic Backup Starting (carthage)" \
 756        -d "Starting PDS backup to aix" \
 757        https://ntfy.sbr.pm/backups
 758    '';
 759
 760    backupCleanupCommand = ''
 761      ${pkgs.curl}/bin/curl \
 762        -H "Authorization: Bearer $(${pkgs.coreutils}/bin/tr -d '\n' < ${
 763          config.age.secrets."ntfy-token".path
 764        })" \
 765        -H "Title: Restic Backup Complete (carthage)" \
 766        -H "Tags: white_check_mark" \
 767        -d "PDS backup to aix completed successfully" \
 768        https://ntfy.sbr.pm/backups || \
 769      ${pkgs.curl}/bin/curl \
 770        -H "Authorization: Bearer $(${pkgs.coreutils}/bin/tr -d '\n' < ${
 771          config.age.secrets."ntfy-token".path
 772        })" \
 773        -H "Title: Restic Backup Failed (carthage)" \
 774        -H "Tags: x,warning" \
 775        -H "Priority: high" \
 776        -d "PDS backup to aix failed! Check logs: journalctl -u restic-backups-aix-pds.service" \
 777        https://ntfy.sbr.pm/backups
 778    '';
 779  };
 780
 781  services.bluesky-pds = {
 782    enable = true;
 783    pdsadmin.enable = true;
 784    goat.enable = true;
 785    settings = {
 786      PDS_HOSTNAME = "pds.demeester.fr";
 787      PDS_DATA_DIRECTORY = "/var/lib/pds";
 788      PDS_BLOBSTORE_DISK_LOCATION = "/var/lib/pds/blocks";
 789      PDS_INVITE_REQUIRED = "true";
 790    };
 791    environmentFiles = [
 792      config.age.secrets."pds.env".path
 793    ];
 794  };
 795
 796  # Allow Caddy to access public git repositories only (override ProtectHome)
 797  systemd.services.caddy.serviceConfig = {
 798    ProtectHome = lib.mkForce "tmpfs"; # Allow read access to /home with bind mounts
 799    BindReadOnlyPaths = [ "/home/vincent/git/public" ];
 800  };
 801
 802  # fcgiwrap instance hosting git-http-backend for smart-HTTP git clones.
 803  # Runs as vincent because /home/vincent/git is mode 0700 (only vincent can
 804  # traverse it). The socket is owned by caddy so Caddy can reach it.
 805  services.fcgiwrap.instances.git = {
 806    process.user = "vincent";
 807    process.group = "users";
 808    socket = {
 809      type = "unix";
 810      address = "/run/fcgiwrap-git.sock";
 811      user = "caddy";
 812      group = "caddy";
 813      mode = "0660";
 814    };
 815  };
 816
 817  services.caddy = {
 818    enable = true;
 819    email = "vincent@sbr.pm";
 820
 821    # Use Caddy with rate-limit plugin
 822    package = pkgs.caddy.withPlugins {
 823      plugins = [ "github.com/mholt/caddy-ratelimit@v0.1.1-0.20250915152450-04ea34edc0c4" ];
 824      hash = "sha256-0wADCRP/42c8pan6/OqU+rPdLhb4pth+elAXiyzU/0k=";
 825    };
 826
 827    # Enable Prometheus metrics on VPN interface only
 828    globalConfig = ''
 829      admin ${builtins.head globals.machines.carthage.net.vpn.ips}:2019
 830      metrics
 831      servers {
 832        log_credentials
 833      }
 834    '';
 835
 836    # Enable JSON access logging (NixOS option)
 837    logFormat = ''
 838      output file /var/log/caddy/access.log {
 839        roll_size 100MiB
 840        roll_keep 10
 841        roll_keep_for 720h
 842      }
 843      format json
 844    '';
 845
 846    virtualHosts = {
 847      # File server with directory browsing (replaces fancyindex)
 848      "dl.sbr.pm".extraConfig = ''
 849        ${blockAIBotsSnippet}
 850        ${robotsTxtSnippet}
 851
 852        root * /var/www/dl.sbr.pm
 853        file_server browse {
 854          hide .fancyindex README.md HEADER.md
 855        }
 856
 857        ${securityHeaders}
 858      '';
 859
 860      # Alias for dl.sbr.pm
 861      "files.sbr.pm".extraConfig = ''
 862        redir https://dl.sbr.pm{uri} permanent
 863      '';
 864
 865      # ntfy - reverse proxy with websockets
 866      "ntfy.sbr.pm".extraConfig = ''
 867        # Rate limiting for notification service
 868        rate_limit {
 869          zone ntfy_publish {
 870            key {remote_host}
 871            events 50
 872            window 1m
 873          }
 874        }
 875
 876        reverse_proxy localhost:8111
 877      '';
 878
 879      # Static sites
 880      "paste.sbr.pm".extraConfig = ''
 881        ${blockAIBotsSnippet}
 882        ${robotsTxtSnippet}
 883
 884        root * /var/www/paste.sbr.pm
 885        file_server
 886        ${securityHeaders}
 887      '';
 888
 889      "sbr.pm".extraConfig = ''
 890        ${blockAIBotsSnippet}
 891        ${robotsTxtSnippet}
 892
 893        root * /var/www/sbr.pm
 894        file_server
 895        ${securityHeaders}
 896      '';
 897
 898      # Go vanity URL service
 899      "go.sbr.pm".extraConfig = ''
 900        reverse_proxy localhost:8080
 901        ${securityHeaders}
 902      '';
 903
 904      # Whoami service (remote)
 905      "whoami.sbr.pm".extraConfig = ''
 906        reverse_proxy 10.100.0.8:80 {
 907          header_up Host {host}
 908        }
 909      '';
 910
 911      # Immich photo management (proxied to rhea)
 912      "immich.sbr.pm".extraConfig = ''
 913        ${blockAIBotsSnippet}
 914        ${robotsTxtSnippet}
 915
 916        # Allow large photo/video uploads (50GB limit)
 917        request_body {
 918          max_size 50GB
 919        }
 920
 921        # Strict rate limiting for authentication endpoints
 922        @auth {
 923          path /auth/* /api/auth/*
 924        }
 925        route @auth {
 926          rate_limit {
 927            zone immich_auth {
 928              key {remote_host}
 929              events 10
 930              window 1m
 931            }
 932          }
 933          reverse_proxy 10.100.0.50:2283 {
 934            header_up Host {host}
 935            header_up X-Real-IP {remote_host}
 936          }
 937        }
 938
 939        # Image downloads use the general limit to allow thumbnail-heavy browsing.
 940        @api {
 941          path /api/*
 942          not {
 943            method GET HEAD
 944            path /api/assets/*/thumbnail /api/assets/*/original
 945          }
 946        }
 947        route @api {
 948          rate_limit {
 949            zone immich_api {
 950              key {remote_host}
 951              events 100
 952              window 1m
 953            }
 954          }
 955          reverse_proxy 10.100.0.50:2283 {
 956            header_up Host {host}
 957            header_up X-Real-IP {remote_host}
 958          }
 959        }
 960
 961        # Permissive rate limiting for media/general requests
 962        rate_limit {
 963          zone immich_media {
 964            key {remote_host}
 965            events 1000
 966            window 1m
 967          }
 968        }
 969
 970        reverse_proxy 10.100.0.50:2283 {
 971          header_up Host {host}
 972          header_up X-Real-IP {remote_host}
 973        }
 974
 975        ${mediaSecurityHeaders}
 976      '';
 977
 978      # Navidrome music streaming (proxied to aion)
 979      "navidrome.sbr.pm".extraConfig = ''
 980        ${blockAIBotsSnippet}
 981        ${robotsTxtSnippet}
 982
 983        # Rate limiting for music streaming
 984        rate_limit {
 985          zone navidrome_general {
 986            key {remote_host}
 987            events 500
 988            window 1m
 989          }
 990        }
 991
 992        reverse_proxy 10.100.0.49:4533 {
 993          header_up Host {host}
 994          header_up X-Real-IP {remote_host}
 995        }
 996
 997        ${mediaSecurityHeaders}
 998      '';
 999
1000      # Jellyfin media server (proxied to rhea)
1001      "jellyfin.sbr.pm".extraConfig = ''
1002        ${blockAIBotsSnippet}
1003        ${robotsTxtSnippet}
1004
1005        # Rate limiting for media server
1006        rate_limit {
1007          zone jellyfin_general {
1008            key {remote_host}
1009            events 500
1010            window 1m
1011          }
1012        }
1013
1014        reverse_proxy 10.100.0.50:8096 {
1015          header_up Host {host}
1016          header_up X-Real-IP {remote_host}
1017        }
1018
1019        ${mediaSecurityHeaders}
1020      '';
1021
1022      # Audiobookshelf audiobook server (proxied to aion)
1023      "audiobookshelf.sbr.pm".extraConfig = ''
1024        ${blockAIBotsSnippet}
1025        ${robotsTxtSnippet}
1026
1027        # Rate limiting for audiobook streaming
1028        rate_limit {
1029          zone audiobookshelf_general {
1030            key {remote_host}
1031            events 500
1032            window 1m
1033          }
1034        }
1035
1036        reverse_proxy 10.100.0.49:13378 {
1037          header_up Host {host}
1038          header_up X-Real-IP {remote_host}
1039        }
1040
1041        ${mediaSecurityHeaders}
1042      '';
1043
1044      # Service aliases (user-friendly URLs - transparent proxy)
1045      "music.sbr.pm".extraConfig = ''
1046        ${blockAIBotsSnippet}
1047        ${robotsTxtSnippet}
1048
1049        # Rate limiting for music streaming
1050        rate_limit {
1051          zone music_general {
1052            key {remote_host}
1053            events 500
1054            window 1m
1055          }
1056        }
1057
1058        reverse_proxy 10.100.0.49:4533 {
1059          header_up Host {host}
1060          header_up X-Real-IP {remote_host}
1061        }
1062
1063        ${mediaSecurityHeaders}
1064      '';
1065
1066      "photos.sbr.pm".extraConfig = ''
1067        ${blockAIBotsSnippet}
1068        ${robotsTxtSnippet}
1069
1070        # Allow large photo/video uploads (50GB limit)
1071        request_body {
1072          max_size 50GB
1073        }
1074
1075        # Strict rate limiting for authentication endpoints
1076        @auth {
1077          path /auth/* /api/auth/*
1078        }
1079        route @auth {
1080          rate_limit {
1081            zone photos_auth {
1082              key {remote_host}
1083              events 10
1084              window 1m
1085            }
1086          }
1087          reverse_proxy 10.100.0.50:2283 {
1088            header_up Host {host}
1089            header_up X-Real-IP {remote_host}
1090          }
1091        }
1092
1093        # Image downloads use the general limit to allow thumbnail-heavy browsing.
1094        @api {
1095          path /api/*
1096          not {
1097            method GET HEAD
1098            path /api/assets/*/thumbnail /api/assets/*/original
1099          }
1100        }
1101        route @api {
1102          rate_limit {
1103            zone photos_api {
1104              key {remote_host}
1105              events 100
1106              window 1m
1107            }
1108          }
1109          reverse_proxy 10.100.0.50:2283 {
1110            header_up Host {host}
1111            header_up X-Real-IP {remote_host}
1112          }
1113        }
1114
1115        # Permissive rate limiting for media/general requests
1116        rate_limit {
1117          zone photos_media {
1118            key {remote_host}
1119            events 1000
1120            window 1m
1121          }
1122        }
1123
1124        reverse_proxy 10.100.0.50:2283 {
1125          header_up Host {host}
1126          header_up X-Real-IP {remote_host}
1127        }
1128
1129        ${mediaSecurityHeaders}
1130      '';
1131
1132      "podcasts.sbr.pm".extraConfig = ''
1133        ${blockAIBotsSnippet}
1134        ${robotsTxtSnippet}
1135
1136        # Rate limiting for audiobook streaming
1137        rate_limit {
1138          zone podcasts_general {
1139            key {remote_host}
1140            events 500
1141            window 1m
1142          }
1143        }
1144
1145        reverse_proxy 10.100.0.49:13378 {
1146          header_up Host {host}
1147          header_up X-Real-IP {remote_host}
1148        }
1149
1150        ${mediaSecurityHeaders}
1151      '';
1152
1153      "rss.sbr.pm".extraConfig = ''
1154        ${blockAIBotsSnippet}
1155        ${robotsTxtSnippet}
1156
1157        # Rate limiting for RSS reader
1158        rate_limit {
1159          zone rss_general {
1160            key {remote_host}
1161            events 100
1162            window 1m
1163          }
1164        }
1165
1166        reverse_proxy 10.100.0.49:8085 {
1167          header_up Host {host}
1168          header_up X-Real-IP {remote_host}
1169        }
1170
1171        ${mediaSecurityHeaders}
1172      '';
1173
1174      # HTTP echo — echoes request headers (debug tool)
1175      # Logs all headers (including Authorization) to a dedicated log file
1176      "echo.sbr.pm".extraConfig = ''
1177        log {
1178          output file /var/log/caddy/echo-requests.log {
1179            roll_size 10MiB
1180            roll_keep 5
1181            roll_keep_for 720h
1182          }
1183          format json
1184        }
1185
1186        root * ${echoTemplate}
1187        templates {
1188          mime text/plain
1189        }
1190        try_files /index.txt
1191        file_server
1192      '';
1193
1194      # Webhook/gosmee service with SSE support
1195      "webhook.sbr.pm".extraConfig = ''
1196        reverse_proxy localhost:3333 {
1197          flush_interval -1
1198        }
1199      '';
1200
1201      # ATProto PDS
1202      "pds.demeester.fr".extraConfig = ''
1203        reverse_proxy localhost:3000 {
1204          header_up Host {host}
1205        }
1206      '';
1207
1208      # Personal website with directory browsing
1209      "vincent.demeester.fr".extraConfig = ''
1210        ${blockAIBotsSnippet}
1211        ${robotsTxtSnippet}
1212
1213        # Keep bot and robots handlers ahead of both notes and the static site.
1214        handle {
1215          handle /notes {
1216            redir * /notes/ 308
1217          }
1218          handle /notes/* {
1219            reverse_proxy 127.0.0.1:8099
1220          }
1221          handle {
1222            root * /var/www/vincent.demeester.fr
1223
1224            # Try files with .html extension
1225            try_files {path} {path}.html {path}/ /index.html
1226
1227            file_server browse {
1228              hide .fancyindex README.md HEADER.md
1229            }
1230
1231            ${securityHeaders}
1232          }
1233        }
1234      '';
1235
1236      # Self-hosted git repositories (public only).
1237      # Smart-HTTP clones/fetches are served by git-http-backend via fcgiwrap;
1238      # everything else falls through to gitmal static HTML browsing.
1239      "git.sbr.pm".extraConfig = ''
1240        ${blockAIBotsSnippet}
1241        ${robotsTxtSnippet}
1242
1243        # Route git smart-HTTP operations to git-http-backend (read-only;
1244        # pushes still go over SSH). Matches any *.git request path.
1245        @git path_regexp git ^/.+\.git(/.*)?$
1246        handle @git {
1247          reverse_proxy unix//run/fcgiwrap-git.sock {
1248            transport fastcgi {
1249              env SCRIPT_FILENAME ${pkgs.git}/bin/git-http-backend
1250              env GIT_PROJECT_ROOT /home/vincent/git/public
1251              env GIT_HTTP_EXPORT_ALL "1"
1252              env PATH_INFO {http.request.uri.path}
1253            }
1254          }
1255        }
1256
1257        # Static gitmal HTML views and directory browsing
1258        handle {
1259          root * /home/vincent/git/public
1260          file_server browse {
1261            hide .fancyindex README.md HEADER.md
1262          }
1263        }
1264
1265        ${gitSecurityHeaders}
1266      '';
1267    };
1268  };
1269
1270  services.govanityurl = {
1271    enable = true;
1272    user = "caddy";
1273    host = "go.sbr.pm";
1274    config = ''
1275      paths:
1276        /x:
1277          repo: https://github.com/vdemeester/x
1278        /lord:
1279          repo: https://github.com/vdemeester/lord
1280        /ape:
1281          repo: https://git.sr.ht/~vdemeester/ape
1282        /nr:
1283          repo: https://git.sr.ht/~vdemeester/nr
1284        /ram:
1285          repo: https://git.sr.ht/~vdemeester/ram
1286        /sec:
1287          repo: https://git.sr.ht/~vdemeester/sec
1288    '';
1289  };
1290  security.acme = {
1291    acceptTerms = true;
1292    defaults.email = "vincent@sbr.pm";
1293  };
1294}