{
  config,
  lib,
  ...
}:
let
  inherit (config.machine.vaultwarden)
    enable
    domain
    port
    ;
in
with lib;
mkIf enable {
  networking.firewall = {
    allowedTCPPorts = [ port ];
  };

  services.nginx.virtualHosts =
    with lib;
    mkIf (domain != null) {
      "${domain}" = {
        forceSSL = true;
        enableACME = true;
        locations."/" = {
          proxyPass = "http://127.0.0.1:${toString port}";
          proxyWebsockets = true;
          extraConfig = ''
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header X-Forwarded-Host $host;
          '';
        };

        extraConfig = ''
          add_header X-Frame-Options DENY;
          add_header X-Content-Type-Options nosniff;
          add_header Referrer-Policy same-origin;
          add_header X-XSS-Protection "1; mode=block";
        '';
      };
    };

  services.vaultwarden = {
    inherit enable;
    backupDir = "/var/local/vaultwarden/backup";
    environmentFile = "/var/lib/vaultwarden/vaultwarden.env";
    config = {
      DOMAIN = "https://${domain}";
      SIGNUPS_ALLOWED = true;

      ROCKET_ADDRESS = "127.0.0.1";
      ROCKET_PORT = port;
      ROCKET_LOG = "critical";
    };
  };
}
