{ config, lib, pkgs, modulesPath, ... }: let inherit (lib) mkOption mkEnableOption mkPackageOption mkDefault mkIf mkMerge types getExe; cfg = config.services.pterodactyl-panel; # management script pterodactyl-artisan = pkgs.writeShellScriptBin "pterodactyl-artisan" '' cd ${cfg.package} sudo=exec if [[ "$USER" != ${cfg.user} ]]; then sudo='exec /run/wrappers/bin/sudo -u ${cfg.user}' fi $sudo ${getExe cfg.package.phpPackage} artisan "$@" ''; secretType = types.submodule { options = { _secret = mkOption { type = with types; nullOr (oneOf [ str path ]); description = '' The path to a file containing the value the option should be set to in the final configuration file. ''; }; }; }; tlsEnabled = cfg.nginx.addSSL || cfg.nginx.forceSSL || cfg.nginx.onlySSL || cfg.nginx.enableACME; in { options.services.pterodactyl-panel = { enable = mkEnableOption "Pterodactyl Panel"; package = mkPackageOption pkgs "pterodactyl-panel" { }; user = mkOption { type = types.str; default = "pterodactyl-panel"; description = "User pterodactyl panel runs as."; }; group = mkOption { type = types.str; default = "pterodactyl-panel"; description = "Group pterodactyl panel runs as."; }; hostName = mkOption { type = types.str; description = "FQDN for the pterodactyl panel."; }; appUrl = mkOption { type = types.str; example = "https://example.com"; description = '' The root URL that you want to host the panel on. ''; default = "http${lib.optionalString tlsEnabled "s"}://${cfg.hostName}"; defaultText = '' http''${lib.optionalString tlsEnabled "s"}://''${cfg.hostName} ''; }; dataDir = mkOption { type = types.path; default = "/var/lib/pterodactyl-panel"; description = "Pterodactyl panel data directory."; }; appKeyFile = mkOption { type = types.path; example = "/run/secrets/appkey"; description = '' A file containing the Laravel APP_KEY - a 32 character long, base64 encoded key used for encryption where needed. Can be generated with `head -c 32 /dev/urandom | base64`. ''; }; hashIdsSaltFile = mkOption { type = types.path; example = "/run/secrets/hashids-salt"; description = '' Can be generated with `tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 20`. ''; }; initialAdmin = mkOption { type = types.submodule { options = { username = mkOption { type = types.str; default = "admin"; description = "Username of the inital admin account."; }; email = mkOption { type = types.str; description = "Email address of the initial admin account."; }; firstName = mkOption { type = types.str; default = "admin"; description = "First name of the initial admin account."; }; lastName = mkOption { type = types.str; default = "admin"; description = "Last name of the initial admin account."; }; passwordFile = mkOption { type = types.path; example = "/run/secrets/initial-admin-password"; description = "A file containing the password of the initial admin account."; }; }; }; description = '' The initial admin user account. Once created, changing these options will have no effect. ''; }; database = { createLocally = mkOption { type = types.bool; default = true; description = "Create the database and database user locally."; }; host = mkOption { type = types.str; default = "localhost"; description = "Database host address."; }; port = mkOption { type = types.port; default = 3306; description = "Database host port."; }; name = mkOption { type = types.str; default = "pterodactyl"; description = "Database name."; }; user = mkOption { type = types.str; default = cfg.user; defaultText = lib.literalExpression "user"; description = "Database username."; }; passwordFile = mkOption { type = with types; nullOr path; default = null; example = "/run/secrets/database-password"; description = '' A file containing the password corresponding to {option}`database.user`. ''; }; }; redis = { createLocally = lib.mkOption { type = types.bool; default = true; description = "Create a redis instance locally."; }; host = mkOption { type = types.str; default = "localhost"; description = "Redis host address."; }; port = mkOption { type = types.port; default = 6379; description = "Redis host port."; }; passwordFile = mkOption { type = with types; nullOr path; default = null; example = "/run/secrets/redis-password"; description = "A file containing the password for the redis instance."; }; }; mail = { driver = mkOption { type = types.enum [ "smtp" "sendmail" ]; default = "sendmail"; description = "Mail driver to use."; }; host = mkOption { type = types.str; default = "localhost"; description = "Mail host address."; }; port = mkOption { type = types.port; default = 1025; description = "Mail host port."; }; encryption = mkOption { type = with types; nullOr (enum [ "tls" "ssl" ]); default = null; description = "SMTP encryption mechanism to use."; }; user = mkOption { type = with types; nullOr str; default = null; example = "pterodactyl"; description = "Mail username."; }; passwordFile = mkOption { type = with types; nullOr path; default = null; example = "/run/secrets/mail-password"; description = '' A file containing the password corresponding to {option}`mail.user`. ''; }; from = { name = mkOption { type = types.str; default = "Pterodactyl Panel"; description = "Mail \"from\" name."; }; address = mkOption { type = types.str; default = "mail@example.com"; description = "Mail \"from\" address."; }; }; replyTo = { name = mkOption { type = types.str; default = cfg.mail.from.name; description = "Mail \"reply-to\" name."; }; address = mkOption { type = types.str; default = cfg.mail.from.address; description = "Mail \"reply-to\" address."; }; }; }; poolConfig = mkOption { type = with types; attrsOf (oneOf [ str int bool ]); default = { # defaults taken from pterodactyl-panel docker file "pm" = "dynamic"; "pm.start_servers" = 4; "pm.min_spare_servers" = 4; "pm.max_spare_servers" = 16; "pm.max_children" = 64; "pm.max_requests" = 256; }; description = "Options for the pterodactyl panel PHP-FPM pool."; }; nginx = mkOption { type = types.submodule ( import "${modulesPath}/services/web-servers/nginx/vhost-options.nix" { inherit config lib; } ); default = { }; example = lib.literalExpression '' { # To enable encryption and let let's encrypt take care of certificate forceSSL = true; enableACME = true; } ''; description = '' With this option, you can customize the nginx virtualHost settings. ''; }; settings = mkOption { type = types.submodule { freeformType = with types; attrsOf (oneOf [ bool int str path secretType ]); options = { }; }; }; }; config = mkIf cfg.enable { assertions = [ { assertion = cfg.database.createLocally -> cfg.database.passwordFile == null; message = "services.pterodactyl-panel.database.passwordFile cannot be specified if services.pterodactyl-panel.database.createLocally is set to true."; } { assertion = cfg.database.createLocally -> cfg.database.user == cfg.user; message = "services.pterodactyl-panel.database.user must be set to services.pterodactyl-panel.user if services.pterodactyl-panel.database.createLocally is set to true."; } ]; environment.systemPackages = [ pterodactyl-artisan ]; users = { users = { "${cfg.user}" = { isSystemUser = true; group = cfg.group; extraGroups = lib.optional cfg.redis.createLocally "redis-pterodactyl-panel"; }; "${config.services.nginx.user}".extraGroups = [ cfg.group ]; }; groups.${cfg.group} = { }; }; services.mysql = mkIf cfg.database.createLocally { enable = true; package = mkDefault pkgs.mariadb; ensureUsers = [{ name = cfg.user; ensurePermissions = { "${cfg.database.name}.*" = "ALL PRIVILEGES"; }; }]; ensureDatabases = [ cfg.database.name ]; }; services.redis.servers.pterodactyl-panel = mkIf cfg.redis.createLocally { enable = true; # Socket connection port = 0; }; services.pterodactyl-panel.settings = mkMerge [ { APP_ENV = mkDefault "production"; APP_DEBUG = mkDefault false; APP_ENVIRONMENT_ONLY = mkDefault true; APP_KEY._secret = cfg.appKeyFile; APP_URL = cfg.appUrl; HASHIDS_SALT._secret = cfg.hashIdsSaltFile; HASHIDS_LENGTH = mkDefault 8; SECURE_COOKIES = tlsEnabled; PTERODACTYL_TELEMETRY_ENABLED = mkDefault false; MAIL_DRIVER = cfg.mail.driver; MAIL_FROM_NAME = cfg.mail.from.name; MAIL_FROM_ADDRESS = cfg.mail.from.address; MAIL_REPLYTO_NAME = cfg.mail.replyTo.name; MAIL_REPLYTO_ADDRESS = cfg.mail.replyTo.address; MAIL_HOST = cfg.mail.host; MAIL_PORT = cfg.mail.port; MAIL_USERNAME = cfg.mail.user; MAIL_ENCRYPTION = cfg.mail.encryption; MAIL_PASSWORD._secret = cfg.mail.passwordFile; } { DB_CONNECTION = mkDefault "mysql"; DB_DATABASE = cfg.database.name; DB_USERNAME = cfg.database.user; } (mkIf cfg.database.createLocally { DB_SOCKET = mkDefault "/run/mysqld/mysqld.sock"; # socket connection, set port to 0 DB_PORT = 0; }) (mkIf (!cfg.database.createLocally) { DB_HOST = cfg.database.host; DB_PORT = cfg.database.port; DB_PASSWORD._secret = cfg.database.passwordFile; }) { CACHE_DRIVER = mkDefault "redis"; QUEUE_DRIVER = mkDefault "redis"; SESSION_DRIVER = mkDefault "redis"; } (mkIf cfg.redis.createLocally { # Support phpredis and predis configuration-style. REDIS_SCHEME = "unix"; REDIS_HOST = config.services.redis.servers.pterodactyl-panel.unixSocket; REDIS_PATH = config.services.redis.servers.pterodactyl-panel.unixSocket; }) (mkIf (!cfg.redis.createLocally) { REDIS_HOST = cfg.redis.host; REDIS_PORT = cfg.redis.port; REDIS_PASSWORD._secret = cfg.redis.passwordFile; }) ]; services.phpfpm.pools.pterodactyl = { user = cfg.user; group = cfg.group; phpPackage = cfg.package.phpPackage; settings = { "listen.owner" = cfg.user; "listen.group" = cfg.group; "listen.mode" = "0660"; "catch_workers_output" = true; } // cfg.poolConfig; }; # services.nginx = { enable = mkDefault true; virtualHosts."${cfg.hostName}" = mkMerge [ cfg.nginx { root = lib.mkForce "${cfg.package}/public"; locations = { "/" = { tryFiles = "$uri $uri/ /index.php?$query_string"; }; "~ \\.php$" = { extraConfig = '' fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:${config.services.phpfpm.pools.pterodactyl.socket}; fastcgi_index index.php; fastcgi_param PHP_VALUE "upload_max_filesize = 100M \n post_max_size=100M"; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param HTTP_PROXY ""; fastcgi_intercept_errors off; fastcgi_buffer_size 16k; fastcgi_buffers 4 16k; fastcgi_connect_timeout 300; fastcgi_send_timeout 300; fastcgi_read_timeout 300; include ${config.services.nginx.package}/conf/fastcgi_params; ''; }; "~ /\\.ht" = { extraConfig = "deny all;"; }; "= /favicon.ico" = { extraConfig = '' access_log off; log_not_found off; ''; }; "= /robots.txt" = { extraConfig = '' access_log off; log_not_found off; ''; }; }; extraConfig = '' index index.html index.htm index.php; # Allow larger uploads and longer requests. client_max_body_size 100m; client_body_timeout 120s; charset utf-8; sendfile off; ''; } ]; }; # scheduler service systemd.timers.pterodactyl-scheduler = { wantedBy = [ "timers.target" ]; timerConfig = { OnBootSec = "1m"; OnUnitActiveSec = "1m"; Unit = "pterodactyl-scheduler.service"; }; }; systemd.services.pterodactyl-scheduler = { description = "Pterodactyl Scheduler"; after = [ "pterodactyl-panel-setup.service" ]; requires = [ "pterodactyl-panel-setup.service" ]; path = [ pterodactyl-artisan ]; serviceConfig = { Type = "oneshot"; User = cfg.user; Group = cfg.group; # Prevents the service from automatically starting on rebuild. # See https://discourse.nixos.org/t/how-to-prevent-custom-systemd-service-from-restarting-on-nixos-rebuild-switch/43431 RemainAfterExit = true; ExecStart = "${lib.getExe pterodactyl-artisan} schedule:run"; }; }; # queue worker service systemd.services.pteroq = { description = "Pterodactyl Queue Worker"; after = [ "pterodactyl-panel-setup.service" ]; requires = [ "pterodactyl-panel-setup.service" ]; wantedBy = [ "multi-user.target" ]; startLimitIntervalSec = 180; startLimitBurst = 30; path = [ pterodactyl-artisan ]; serviceConfig = { User = cfg.user; Group = cfg.group; ExecStart = "${lib.getExe pterodactyl-artisan} queue:work --queue=high,standard,low --sleep=3 --tries=3"; Restart = "always"; RestartSec = "5s"; }; }; # recreate directory structure that was deleted in the package's postInstall stage # bootstrap/cache is symlinked to ${cfg.dataDir}/cache systemd.tmpfiles.rules = [ "d ${cfg.dataDir}/cache 0750 ${cfg.user} ${cfg.group} - -" "d ${cfg.dataDir}/storage 0700 ${cfg.user} ${cfg.group} - -" "d ${cfg.dataDir}/storage/app 0700 ${cfg.user} ${cfg.group} - -" "d ${cfg.dataDir}/storage/app/private 0700 ${cfg.user} ${cfg.group} - -" "d ${cfg.dataDir}/storage/app/public 0700 ${cfg.user} ${cfg.group} - -" "d ${cfg.dataDir}/storage/clockwork 0700 ${cfg.user} ${cfg.group} - -" "d ${cfg.dataDir}/storage/framework 0700 ${cfg.user} ${cfg.group} - -" "d ${cfg.dataDir}/storage/framework/cache 0700 ${cfg.user} ${cfg.group} - -" "d ${cfg.dataDir}/storage/framework/cache/data 0700 ${cfg.user} ${cfg.group} - -" "d ${cfg.dataDir}/storage/framework/sessions 0700 ${cfg.user} ${cfg.group} - -" "d ${cfg.dataDir}/storage/framework/views 0700 ${cfg.user} ${cfg.group} - -" "d ${cfg.dataDir}/storage/logs 0700 ${cfg.user} ${cfg.group} - -" ]; # setup service to systemd.services.pterodactyl-panel-setup = { before = [ "phpfpm-pterodactyl.service" ]; after = (lib.optional cfg.database.createLocally "mysql.service") ++ (lib.optional cfg.redis.createLocally "redis-pterodactyl-panel.service"); requires = (lib.optional cfg.database.createLocally "mysql.service") ++ (lib.optional cfg.redis.createLocally "redis-pterodactyl-panel.service"); wantedBy = [ "multi-user.target" ]; serviceConfig = { Type = "oneshot"; User = cfg.user; Group = cfg.group; StateDirectory = "pterodactyl-panel"; UMask = "077"; }; path = [ pkgs.replace-secret # mysql command is used by artisan pkgs.mariadb.client pterodactyl-artisan ]; script = let # function to check if an attribute set has a _secret attribute set isSecret = v: builtins.isAttrs v && v ? _secret && (builtins.isString v._secret || builtins.isPath v._secret); # function to generate a .env style config, but with secret values replaced by their sha256 hash generateEnvVars = lib.generators.toKeyValue { mkKeyValue = lib.flip lib.generators.mkKeyValueDefault "=" { mkValueString = v: with builtins; if isInt v then toString v else if isString v then "\"${v}\"" else if true == v then "true" else if false == v then "false" else if isSecret v then if (isString v._secret) then hashString "sha256" v._secret else hashString "sha256" (builtins.readFile v._secret) else throw "unsupported type ${typeOf v}: ${(lib.generators.toPretty { }) v}"; }; }; # get a list of all paths pointing to a file containing a secret secretPaths = lib.mapAttrsToList (_: v: v._secret) (lib.filterAttrs (_: isSecret) cfg.settings); # function to generate a command that replaces a given secret in the .env file mkSecretReplacement = file: '' replace-secret ${ lib.escapeShellArgs [ ( if (builtins.isString file) then builtins.hashString "sha256" file else builtins.hashString "sha256" (builtins.readFile file) ) file "${cfg.dataDir}/.env" ] } ''; # all replace-secret commands secretReplacements = lib.concatMapStrings mkSecretReplacement secretPaths; # remove empty attributes from settings filteredConfig = lib.converge (lib.filterAttrsRecursive ( _: v: !builtins.elem v [ { } null ] )) cfg.settings; configFile = pkgs.writeText "pterodactyl-env" (generateEnvVars filteredConfig); in '' set -euo pipefail # create .env file install -T -m 0600 -o ${cfg.user} ${configFile} ${cfg.dataDir}/.env # replace references to secrets with the actual secrets ${secretReplacements} # prepend `base64:` if it does not exist in APP_KEY if ! grep 'APP_KEY=base64:' "${cfg.dataDir}/.env" > /dev/null; then sed -i 's/APP_KEY=/APP_KEY=base64:/' "${cfg.dataDir}/.env" fi # clear cache rm -rf ${cfg.dataDir}/cache/* ${lib.getExe pterodactyl-artisan} view:clear ${lib.getExe pterodactyl-artisan} config:clear # setup/migrate db ${lib.getExe pterodactyl-artisan} migrate --seed --force # create initial admin user if ! [ -f ${cfg.dataDir}/.initial-admin-created ]; then ${lib.getExe pterodactyl-artisan} p:user:make --admin=1 \ --username=${cfg.initialAdmin.username} \ --email=${cfg.initialAdmin.email} \ --name-first=${cfg.initialAdmin.firstName} \ --name-last=${cfg.initialAdmin.lastName} < ${cfg.initialAdmin.passwordFile} touch ${cfg.dataDir}/.initial-admin-created fi ''; }; }; }