{ config, lib, pkgs, ... }: let cfg = config.services.hm-options-mcp; # Determine database URL based on configuration # For postgres with connectionStringFile, the URL is set at runtime via script useConnectionStringFile = cfg.database.type == "postgres" && cfg.database.connectionStringFile != null; databaseUrl = if cfg.database.type == "sqlite" then "sqlite://${cfg.dataDir}/${cfg.database.name}" else if useConnectionStringFile then "" # Will be set at runtime from file else cfg.database.connectionString; in { options.services.hm-options-mcp = { enable = lib.mkEnableOption "Home Manager Options MCP server"; package = lib.mkPackageOption pkgs "hm-options-mcp" { }; user = lib.mkOption { type = lib.types.str; default = "hm-options-mcp"; description = "User account under which the service runs."; }; group = lib.mkOption { type = lib.types.str; default = "hm-options-mcp"; description = "Group under which the service runs."; }; dataDir = lib.mkOption { type = lib.types.path; default = "/var/lib/hm-options-mcp"; description = "Directory to store data files."; }; database = { type = lib.mkOption { type = lib.types.enum [ "sqlite" "postgres" ]; default = "sqlite"; description = "Database backend to use."; }; name = lib.mkOption { type = lib.types.str; default = "hm-options.db"; description = "SQLite database filename (when using sqlite backend)."; }; connectionString = lib.mkOption { type = lib.types.str; default = ""; description = '' PostgreSQL connection string (when using postgres backend). Example: "postgres://user:password@localhost/hm_options?sslmode=disable" WARNING: This value will be stored in the Nix store, which is world-readable. For production use with sensitive credentials, use connectionStringFile instead. ''; }; connectionStringFile = lib.mkOption { type = lib.types.nullOr lib.types.path; default = null; description = '' Path to a file containing the PostgreSQL connection string. The file should contain just the connection string, e.g.: postgres://user:password@localhost/hm_options?sslmode=disable This is the recommended way to configure PostgreSQL credentials as the file is not stored in the world-readable Nix store. The file must be readable by the service user. ''; example = "/run/secrets/hm-options-mcp-db"; }; }; indexOnStart = lib.mkOption { type = lib.types.listOf lib.types.str; default = [ ]; example = [ "hm-unstable" "release-24.11" ]; description = '' List of home-manager revisions to index on service start. Can be channel names (hm-unstable) or git hashes. Indexing is skipped if the revision is already indexed. ''; }; http = { address = lib.mkOption { type = lib.types.str; default = "127.0.0.1:8081"; description = "HTTP listen address for the MCP server."; }; endpoint = lib.mkOption { type = lib.types.str; default = "/mcp"; description = "HTTP endpoint path for MCP requests."; }; allowedOrigins = lib.mkOption { type = lib.types.listOf lib.types.str; default = [ ]; example = [ "http://localhost:3000" "https://example.com" ]; description = '' Allowed Origin headers for CORS. Empty list means only localhost origins are allowed. ''; }; sessionTTL = lib.mkOption { type = lib.types.str; default = "30m"; description = "Session TTL for HTTP transport (Go duration format)."; }; tls = { enable = lib.mkEnableOption "TLS for HTTP transport"; certFile = lib.mkOption { type = lib.types.nullOr lib.types.path; default = null; description = "Path to TLS certificate file."; }; keyFile = lib.mkOption { type = lib.types.nullOr lib.types.path; default = null; description = "Path to TLS private key file."; }; }; }; openFirewall = lib.mkOption { type = lib.types.bool; default = false; description = "Whether to open the firewall for the MCP HTTP server."; }; }; config = lib.mkIf cfg.enable { assertions = [ { assertion = cfg.database.type == "sqlite" || cfg.database.connectionString != "" || cfg.database.connectionStringFile != null; message = "services.hm-options-mcp.database: when using postgres backend, either connectionString or connectionStringFile must be set"; } { assertion = cfg.database.connectionString == "" || cfg.database.connectionStringFile == null; message = "services.hm-options-mcp.database: connectionString and connectionStringFile are mutually exclusive"; } { assertion = !cfg.http.tls.enable || (cfg.http.tls.certFile != null && cfg.http.tls.keyFile != null); message = "services.hm-options-mcp.http.tls: both certFile and keyFile must be set when TLS is enabled"; } ]; users.users.${cfg.user} = lib.mkIf (cfg.user == "hm-options-mcp") { isSystemUser = true; group = cfg.group; home = cfg.dataDir; description = "Home Manager Options MCP server user"; }; users.groups.${cfg.group} = lib.mkIf (cfg.group == "hm-options-mcp") { }; systemd.tmpfiles.rules = [ "d ${cfg.dataDir} 0750 ${cfg.user} ${cfg.group} -" ]; systemd.services.hm-options-mcp = { description = "Home Manager Options MCP Server"; wantedBy = [ "multi-user.target" ]; after = [ "network.target" ] ++ lib.optional (cfg.database.type == "postgres") "postgresql.service"; environment = lib.mkIf (!useConnectionStringFile) { HM_OPTIONS_DATABASE = databaseUrl; }; path = [ cfg.package ]; script = let indexCommands = lib.optionalString (cfg.indexOnStart != []) '' ${lib.concatMapStringsSep "\n" (rev: '' echo "Indexing revision: ${rev}" hm-options index "${rev}" || true '') cfg.indexOnStart} ''; # Build HTTP transport flags httpFlags = lib.concatStringsSep " " ([ "--transport http" "--http-address '${cfg.http.address}'" "--http-endpoint '${cfg.http.endpoint}'" "--session-ttl '${cfg.http.sessionTTL}'" ] ++ lib.optionals (cfg.http.allowedOrigins != []) ( map (origin: "--allowed-origins '${origin}'") cfg.http.allowedOrigins ) ++ lib.optionals cfg.http.tls.enable [ "--tls-cert '${cfg.http.tls.certFile}'" "--tls-key '${cfg.http.tls.keyFile}'" ]); in if useConnectionStringFile then '' # Read database connection string from file if [ ! -f "${cfg.database.connectionStringFile}" ]; then echo "Error: connectionStringFile not found: ${cfg.database.connectionStringFile}" >&2 exit 1 fi export HM_OPTIONS_DATABASE="$(cat "${cfg.database.connectionStringFile}")" ${indexCommands} exec hm-options serve ${httpFlags} '' else '' ${indexCommands} exec hm-options serve ${httpFlags} ''; serviceConfig = { Type = "simple"; User = cfg.user; Group = cfg.group; Restart = "on-failure"; RestartSec = "5s"; # Hardening NoNewPrivileges = true; ProtectSystem = "strict"; ProtectHome = true; PrivateTmp = true; PrivateDevices = true; ProtectKernelTunables = true; ProtectKernelModules = true; ProtectControlGroups = true; RestrictNamespaces = true; RestrictRealtime = true; RestrictSUIDSGID = true; MemoryDenyWriteExecute = true; LockPersonality = true; ReadWritePaths = [ cfg.dataDir ]; WorkingDirectory = cfg.dataDir; StateDirectory = lib.mkIf (cfg.dataDir == "/var/lib/hm-options-mcp") "hm-options-mcp"; }; }; # Open firewall for HTTP port if configured networking.firewall = lib.mkIf cfg.openFirewall (let # Extract port from address (format: "host:port" or ":port") addressParts = lib.splitString ":" cfg.http.address; port = lib.toInt (lib.last addressParts); in { allowedTCPPorts = [ port ]; }); }; }