# LicensePanel installer — Windows. Per contracts/installer.md. # # Mirrors install.sh feature-for-feature on Windows Server 2019+ / Windows 11: # • online first install — KEK + Postgres TLS + bootstrap cert generated with # pure .NET crypto (no openssl, no cert-store use), # panel-stack compose written, `docker compose up -d` # • idempotent re-run — detects state.db, pulls latest image, re-ups, # asserts state.db is byte-identical afterwards # # Platform notes: # • State dir C:\ProgramData\LicensePanel, NTFS ACL locked to SYSTEM + # Administrators (the 0600-root posture from install.sh). # • Docker is a precondition (Docker Desktop / EE) — never auto-installed. # • Compose bind-mount sources resolve through PANEL_DATA_ROOT, so the single # cross-platform docker-compose.yml lands on the Windows state directory. # • Output never includes secrets (FR-007). #requires -Version 7.4 [CmdletBinding()] param( [string]$PanelHost, [string]$AcmeEmail, [switch]$NoDocker, [string]$Version = 'latest', [switch]$NoStart, # 0 = auto: edge ports prefer 80/443 but auto-fall back to a free port # when those are taken (Dokploy/nginx/CDN-occupied hosts). Explicit non- # zero values are treated as pins — a conflict hard-fails preflight. [int]$HttpPort = 0, [int]$HttpsPort = 0, [int]$PanelPort = 0, # -Reset -Yes: stop the stack (incl. named volumes), wipe ${PanelDir}, # then continue with fresh install. Two switches required to prevent # accidental wipes; there is no interactive prompt (iwr|iex has no tty). [switch]$Reset, [switch]$Yes, # DNS-01 ACME — set to opt into DNS-based Let's Encrypt issuance (no inbound # port needed). When set, the bundled Traefik renders with DNS-01 instead # of HTTP-01, so the panel can run on hosts where port 80 is already taken # (Dokploy, existing reverse proxy, ISP block, CDN, firewalled). [string]$AcmeDnsProvider, # Provider API credentials passed as env vars into the Traefik container. # Repeatable: -AcmeDnsEnv CF_DNS_API_TOKEN=...,-AcmeDnsEnv CF_API_EMAIL=... # See https://go-acme.github.io/lego/dns/ for per-provider variables. [string[]]$AcmeDnsEnv, # Orchestration backend (plan T16/T17). Mirrors install.sh. Dokploy requires # a Linux Swarm host, so on Windows only 'compose' is supported — '-Backend # dokploy' hard-fails below. The registry flags apply to the private # panel-image pull in compose mode too (interim manual creds, amendment O). [ValidateSet('compose', 'dokploy', '')] [string]$Backend = '', [switch]$AirGapped, [switch]$ExposeDokployDashboard, [string]$DokployApiKey, [string]$RegistryUrl = $env:LICENSEPANEL_REGISTRY_URL, [string]$RegistryUser = $env:LICENSEPANEL_REGISTRY_USER, [string]$RegistryToken = $env:LICENSEPANEL_REGISTRY_TOKEN, [string]$RegistryImagePrefix = $env:LICENSEPANEL_REGISTRY_IMAGE_PREFIX, # DKB-REG T7 — the customer types only their license: -License + -ActivationCode # fetch the private-registry pull credential from the LicenseServer before the # panel pull. Manual -Registry* override this license path. [string]$License = $env:LICENSEPANEL_LICENSE, [string]$ActivationCode = $env:LICENSEPANEL_ACTIVATION_CODE, [string]$LicenseServerUrl = $(if ($env:LICENSEPANEL_LS_BASE_URL) { $env:LICENSEPANEL_LS_BASE_URL } else { 'https://license-api.mod-sol-sa.com' }), [switch]$Help ) # Backend selection. Windows hosts run the compose backend only — Dokploy needs # a Linux Swarm. Default = compose (the plan's dokploy-on-Linux default applies # to install.sh). if (-not $Backend) { $Backend = 'compose' } if ($AirGapped) { $Backend = 'compose' } if ($Backend -eq 'dokploy') { Write-Error '-Backend dokploy is not supported on Windows (Dokploy requires a Linux Swarm host). Use the Linux install.sh with --backend dokploy, or run -Backend compose here.' exit 1 } $ErrorActionPreference = 'Stop' $PanelDir = 'C:\ProgramData\LicensePanel' # state.db lives under data/ so the panel's nonroot UID can both open it # AND create the sibling licensepanel-dataprotection-keys/ dir there. $StateDb = Join-Path (Join-Path $PanelDir 'data') 'state.db' $ComposeDir = Join-Path $PanelDir 'panel-stack' $ComposeFile = Join-Path $ComposeDir 'docker-compose.yml' $EnvFile = Join-Path $ComposeDir '.env' $TraefikDir = Join-Path $PanelDir 'traefik' $PostgresTlsDir = Join-Path $PanelDir 'postgres-tls' $PostgresInitDir = Join-Path $PanelDir 'postgres-init' $KeysDir = Join-Path $PanelDir 'keys' $DataDir = Join-Path $PanelDir 'data' $ServiceName = 'LicensePanel' # Canonical install host (Dokploy service). Overridable per environment. $InstallerLibUrl = if ($env:LICENSEPANEL_INSTALL_BASE) { $env:LICENSEPANEL_INSTALL_BASE } else { 'https://license-install.mod-sol-sa.com' } # Exit codes mirror contracts/installer.md. $Exit = @{ Success = 0 Generic = 1 Preflight = 2 DockerInstall = 3 # 4 reserved (was AirgapInvalid; air-gap install isn't shipped in R1). Permissions = 5 Fingerprint = 6 Tls = 7 Compose = 8 } function Write-Help { @' LicensePanel installer (Windows) Usage: iwr -useb https://license-install.mod-sol-sa.com/install.ps1 | iex & ([scriptblock]::Create((iwr -useb https://license-install.mod-sol-sa.com/install.ps1).Content)) ` -PanelHost 'panel.acme.example' -AcmeEmail 'ops@acme.example' No parameter is required. Bare `iwr … | iex` lands in bootstrap mode (self-signed cert on the direct-access port); finish setup — domain, ACME email, challenge type, DNS provider, DNS credentials — in Initial Configuration in the browser. The parameters below are pre-seeds. Parameters (all optional): -PanelHost Pre-seed the panel host (engages ACME at first boot when -AcmeEmail is also given). -AcmeEmail Let's Encrypt account contact. Without it, ACME stays off and IC collects it later. -NoDocker Skip Docker probe; install AOT binary as a Service. -Version Pin the panel image (default: latest). -NoStart Write state but do not start the stack/service. -HttpPort Edge HTTP port (default 80). With HTTP-01 ACME this must be 80. With -AcmeDnsProvider (DNS-01) any free port works. -HttpsPort Edge HTTPS port (default 443). -PanelPort Direct panel-access port (default: 8443, or the next free port if 8443 is in use). -AcmeDnsProvider

Use ACME DNS-01 instead of HTTP-01 for Let's Encrypt. No inbound port required.

is a Lego provider name (cloudflare | route53 | digitalocean | hetzner | ...). Implies -AcmeEmail. See https://go-acme.github.io/lego/dns/ -AcmeDnsEnv KEY=VAL Provider API credentials, repeatable. Examples: -AcmeDnsEnv CF_DNS_API_TOKEN=... -AcmeDnsEnv 'AWS_ACCESS_KEY_ID=...','AWS_SECRET_ACCESS_KEY=...' Stored at .env.acme-dns (mode 0600); never echoed. -Reset WIPE all panel state (state.db, KEK, certs, project data, postgres data volume) before installing fresh. MUST be paired with -Yes — there is no interactive confirmation (iwr|iex has no tty). -Yes Required by -Reset to acknowledge the destruction. -Help Print this help and exit 0. '@ } if ($Help) { Write-Help; exit $Exit.Success } # No required parameters. ACME settings without a matching email don't fail # the install — the panel falls back to bootstrap mode (self-signed cert on # the direct-access port) and Initial Configuration collects whatever is # missing. Warnings here are signal, not a wall. if ($PanelHost -and -not $AcmeEmail) { Write-Warning '-PanelHost was set without -AcmeEmail — ACME will NOT engage yet. The install lands in bootstrap mode (self-signed cert); finish ACME setup in Initial Configuration.' } if ($AcmeDnsProvider -and -not $AcmeEmail) { Write-Warning '-AcmeDnsProvider was set without -AcmeEmail — DNS-01 configured but ACME will NOT engage until an email is set (in Initial Configuration or by re-running with -AcmeEmail).' } if ($AcmeDnsEnv) { foreach ($kv in $AcmeDnsEnv) { if ($kv -notmatch '=') { Write-Error "error: -AcmeDnsEnv expects KEY=VALUE (got: $kv)" exit $Exit.Generic } } } if ($AcmeDnsProvider -and (-not $AcmeDnsEnv -or $AcmeDnsEnv.Count -eq 0)) { Write-Warning "-AcmeDnsProvider was set but no -AcmeDnsEnv credentials were passed. Traefik cannot authenticate to the DNS provider until those are supplied — see https://go-acme.github.io/lego/dns/$AcmeDnsProvider/" } # ============================================================================ # Helpers # ============================================================================ # A free TCP port: the preferred one if free, else the next free above it, # else a free high port. Get-Random here is selection, not secret material. function Test-PortInUse { param([int]$Port) $null -ne (Get-NetTCPConnection -State Listen -LocalPort $Port -ErrorAction SilentlyContinue) } function Find-FreePort { param([int]$Preferred) if (-not (Test-PortInUse $Preferred)) { return $Preferred } for ($p = $Preferred + 1; $p -le $Preferred + 100; $p++) { if (-not (Test-PortInUse $p)) { return $p } } foreach ($attempt in 1..5) { $p = Get-Random -Minimum 20000 -Maximum 40000 if (-not (Test-PortInUse $p)) { return $p } } return $Preferred } function Get-PrimaryIPv4 { $ip = (Get-NetIPAddress -AddressFamily IPv4 -ErrorAction SilentlyContinue | Where-Object { $_.PrefixOrigin -in 'Manual', 'Dhcp' -and $_.IPAddress -ne '127.0.0.1' } | Select-Object -First 1).IPAddress if (-not $ip) { return '127.0.0.1' } return $ip } # Cryptographically-strong alphanumeric secret (CSPRNG-backed, never printed). function New-RandomSecret { param([int]$Length) $charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' $bytes = [byte[]]::new($Length) [System.Security.Cryptography.RandomNumberGenerator]::Fill($bytes) -join ($bytes | ForEach-Object { $charset[$_ % $charset.Length] }) } # Resolve a helper file: local checkout copy if present (dev), otherwise fetch # from the installer host and cache it under the state dir. `$Name` may carry a # `../` segment (e.g. ../panel-stack/docker-compose.yml); paths are normalised # and parent dirs created — neither Join-Path nor curl makes parents itself. function Resolve-Lib { param([string]$Name) if ($PSScriptRoot) { $local = [System.IO.Path]::GetFullPath((Join-Path (Join-Path $PSScriptRoot 'lib') $Name)) if (Test-Path -LiteralPath $local) { return $local } } # Strip `../` for the cache path so a cached file never resolves onto a real # state path (installer-cache/../panel-stack would BE $ComposeDir). The URL # keeps the original name — the host normalises /lib/../panel-stack/. $cacheName = $Name -replace '\.\./', '' $dest = [System.IO.Path]::GetFullPath((Join-Path (Join-Path $PanelDir 'installer-cache') $cacheName)) if (-not (Test-Path -LiteralPath $dest)) { $parent = Split-Path -Parent $dest if (-not (Test-Path -LiteralPath $parent)) { New-Item -ItemType Directory -Path $parent -Force | Out-Null } Invoke-WebRequest -UseBasicParsing -Uri "$InstallerLibUrl/lib/$Name" ` -OutFile $dest -MaximumRetryCount 3 -RetryIntervalSec 2 -ConnectionTimeoutSeconds 10 } return $dest } function Write-TextFileLf { param([string]$Path, [string]$Content) # LF-only, UTF-8 no BOM — Docker .env / PEM / YAML consumers are Linux. [System.IO.File]::WriteAllText($Path, ($Content -replace "`r`n", "`n")) } # ============================================================================ # Certificate generation (pure .NET — no openssl, no Windows cert store) # ============================================================================ # Create an RSA-4096 / SHA-256 certificate. CA certs are self-signed with # KeyCertSign; leaf certs are signed by `-Issuer` with serverAuth EKU + SANs. # Returns the cert and the RSA key object (the key is needed for PEM export). function New-RsaCertificate { param( [string]$Subject, [switch]$IsCa, [string[]]$DnsNames = @(), [string[]]$IpAddresses = @(), [System.Security.Cryptography.X509Certificates.X509Certificate2]$Issuer, [int]$Days = 1825 ) $rsa = [System.Security.Cryptography.RSA]::Create(4096) $req = [System.Security.Cryptography.X509Certificates.CertificateRequest]::new( $Subject, $rsa, [System.Security.Cryptography.HashAlgorithmName]::SHA256, [System.Security.Cryptography.RSASignaturePadding]::Pkcs1) if ($IsCa) { $req.CertificateExtensions.Add( [System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension]::new($true, $false, 0, $true)) $req.CertificateExtensions.Add( [System.Security.Cryptography.X509Certificates.X509KeyUsageExtension]::new( [System.Security.Cryptography.X509Certificates.X509KeyUsageFlags]'KeyCertSign, CrlSign, DigitalSignature', $true)) } else { $req.CertificateExtensions.Add( [System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension]::new($false, $false, 0, $false)) $req.CertificateExtensions.Add( [System.Security.Cryptography.X509Certificates.X509KeyUsageExtension]::new( [System.Security.Cryptography.X509Certificates.X509KeyUsageFlags]'DigitalSignature, KeyEncipherment', $true)) $eku = [System.Security.Cryptography.OidCollection]::new() [void]$eku.Add([System.Security.Cryptography.Oid]::new('1.3.6.1.5.5.7.3.1')) # serverAuth $req.CertificateExtensions.Add( [System.Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension]::new($eku, $false)) } if ($DnsNames.Count -or $IpAddresses.Count) { $san = [System.Security.Cryptography.X509Certificates.SubjectAlternativeNameBuilder]::new() foreach ($d in $DnsNames) { $san.AddDnsName($d) } foreach ($ip in $IpAddresses) { $san.AddIpAddress([System.Net.IPAddress]::Parse($ip)) } $req.CertificateExtensions.Add($san.Build()) } $notBefore = [DateTimeOffset]::UtcNow.AddDays(-1) $notAfter = [DateTimeOffset]::UtcNow.AddDays($Days) if ($Issuer) { $serial = [byte[]]::new(16) [System.Security.Cryptography.RandomNumberGenerator]::Fill($serial) $serial[0] = $serial[0] -band 0x7F # keep the serial positive $public = $req.Create($Issuer, $notBefore, $notAfter, $serial) $cert = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::CopyWithPrivateKey($public, $rsa) $public.Dispose() } else { $cert = $req.CreateSelfSigned($notBefore, $notAfter) } return [pscustomobject]@{ Cert = $cert; Rsa = $rsa } } function Write-PemPair { param( [pscustomobject]$Material, [string]$CertPath, [string]$KeyPath ) Write-TextFileLf $CertPath ($Material.Cert.ExportCertificatePem().TrimEnd() + "`n") Write-TextFileLf $KeyPath ($Material.Rsa.ExportPkcs8PrivateKeyPem().TrimEnd() + "`n") } # KEK material — RSA-4096 self-signed cert exported as a password-less PKCS#12 # (master.pfx). The panel reads it via X509KekProvider; the PKCS#12 password is # wrapped at first boot through the in-process key-custody seam. Mirrors # install.sh generate_kek_material. function New-KekMaterial { $pfx = Join-Path $KeysDir 'master.pfx' if (Test-Path $pfx) { return } $kek = New-RsaCertificate -Subject 'CN=licensepanel-kek' -Days 1825 $bytes = $kek.Cert.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12, '') [System.IO.File]::WriteAllBytes($pfx, $bytes) Write-Output 'kek: master.pfx generated.' } # Postgres TLS — self-signed CA + server cert (5-year), consumed by the Postgres # container via ssl_*_file and reached by the panel with SslMode=VerifyFull. # Mirrors lib/generate-postgres-tls.sh. function New-PostgresTls { if (Test-Path (Join-Path $PostgresTlsDir 'server.crt')) { return } $ca = New-RsaCertificate -Subject 'CN=licensepanel-postgres-ca' -IsCa -Days 1825 $srv = New-RsaCertificate -Subject 'CN=panel-postgres' -Issuer $ca.Cert -Days 1825 ` -DnsNames @('panel-postgres', 'localhost') -IpAddresses @('127.0.0.1') Write-PemPair -Material $ca -CertPath (Join-Path $PostgresTlsDir 'ca.crt') -KeyPath (Join-Path $PostgresTlsDir 'ca.key') Write-PemPair -Material $srv -CertPath (Join-Path $PostgresTlsDir 'server.crt') -KeyPath (Join-Path $PostgresTlsDir 'server.key') Write-Output 'postgres-tls: CA + server cert written (valid 1825 days).' } # Bootstrap cert — short-lived (90-day) self-signed cert whose CN is the host's # primary IP, served by Traefik's bootstrap entrypoint until ACME succeeds. # Mirrors lib/generate-bootstrap-cert.sh. function New-BootstrapCert { if (Test-Path (Join-Path $TraefikDir 'bootstrap-cert.pem')) { return } $ip = Get-PrimaryIPv4 $bc = New-RsaCertificate -Subject "CN=$ip" -Days 90 ` -DnsNames @('localhost') -IpAddresses @($ip, '127.0.0.1') Write-PemPair -Material $bc ` -CertPath (Join-Path $TraefikDir 'bootstrap-cert.pem') ` -KeyPath (Join-Path $TraefikDir 'bootstrap-cert.key') Write-Output "bootstrap-cert: self-signed cert for $ip written (valid 90 days)." } # ============================================================================ # Lifecycle # ============================================================================ function Assert-Administrator { $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole( [Security.Principal.WindowsBuiltInRole]::Administrator) if (-not $isAdmin) { Write-Error 'error: must run as Administrator.' exit $Exit.Generic } } function Test-StatePerms { if (Test-Path $PanelDir) { $acl = Get-Acl $PanelDir $extras = $acl.Access | Where-Object { $_.IdentityReference.Value -notmatch '^(NT AUTHORITY\\SYSTEM|BUILTIN\\Administrators)$' } if ($extras) { Write-Error "error: $PanelDir has unexpected ACEs (FR-062). Refusing." exit $Exit.Permissions } } } function Initialize-StateDirs { # Panel-managed Traefik bundle dir (sibling to data/; the panel's # EdgeProvisioner writes here at first boot — needs to be present). $edgeDir = Join-Path $PanelDir 'edge' foreach ($dir in @($PanelDir, $KeysDir, $PostgresTlsDir, $TraefikDir, $ComposeDir, $PostgresInitDir, $DataDir, $edgeDir)) { if (-not (Test-Path $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null } } # One-time migration from earlier installs that put state.db directly under # $PanelDir. Move into data/ so the new path matches the compose env. $oldStateDb = Join-Path $PanelDir 'state.db' if ((Test-Path $oldStateDb) -and (-not (Test-Path $StateDb))) { Move-Item $oldStateDb $StateDb Write-Output "migrated state.db: $oldStateDb -> $StateDb" } # Lock the ACL to SYSTEM + Administrators only (mirrors 0600 root on Linux). $acl = New-Object System.Security.AccessControl.DirectorySecurity $acl.SetAccessRuleProtection($true, $false) foreach ($id in @('NT AUTHORITY\SYSTEM', 'BUILTIN\Administrators')) { $acl.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule( $id, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow'))) } Set-Acl -Path $PanelDir -AclObject $acl } function Test-ExistingInstall { return Test-Path $StateDb } function Get-EnvValue { param([string]$Key, [string]$Default) if (Test-Path $EnvFile) { $line = Get-Content $EnvFile | Where-Object { $_ -match "^$Key=" } | Select-Object -First 1 if ($line) { return $line.Split('=', 2)[1] } } return $Default } function Invoke-IdempotentRerun { Write-Output 'LicensePanel is already installed.' $shaBefore = (Get-FileHash $StateDb -Algorithm SHA256).Hash if (-not $NoDocker) { Invoke-StackPull if (-not $NoStart) { Push-Location $ComposeDir try { docker compose up -d if ($LASTEXITCODE -ne 0) { Write-Error 'error: docker compose up reported non-zero.' exit $Exit.Compose } } finally { Pop-Location } } } $shaAfter = (Get-FileHash $StateDb -Algorithm SHA256).Hash if ($shaBefore -ne $shaAfter) { Write-Error 'error: state.db SHA-256 changed during idempotent re-run (idempotency violation).' exit $Exit.Generic } Write-Output "Pulled image: registry.innovation-lab.co/modern-solutions/licensepanel:$Version" $bp = Get-EnvValue -Key 'BOOTSTRAP_PORT' -Default '8443' Write-Output 'Open in your browser:' if ($PanelHost) { Write-Output (' https://{0}/' -f $PanelHost) } Write-Output (' https://{0}:{1}/ (direct access)' -f (Get-PrimaryIPv4), $bp) exit $Exit.Success } function Resolve-Ports { if ($NoDocker) { if ($script:PanelPort -le 0) { $script:PanelPort = 8443 } if ($script:HttpPort -le 0) { $script:HttpPort = 80 } if ($script:HttpsPort -le 0) { $script:HttpsPort = 443 } return } # Edge ports: 0 = auto-prefer 80/443 with fallback if taken; explicit # non-zero = pin (hard-fail on conflict). if ($script:HttpPort -le 0) { if (Test-PortInUse 80) { $script:HttpPort = Find-FreePort 8080 Write-Output "port 80 is in use; using $($script:HttpPort) for edge HTTP (auto-picked). HTTP-01 ACME won't work on this host — switch to DNS-01 in Initial Configuration." } else { $script:HttpPort = 80 } } elseif (Test-PortInUse $script:HttpPort) { Write-Error "error: HTTP port $($script:HttpPort) is in use — choose another -HttpPort or pass 0 to auto-pick." exit $Exit.Preflight } if ($script:HttpsPort -le 0) { if (Test-PortInUse 443) { $script:HttpsPort = Find-FreePort 8443 if ($script:HttpsPort -eq $script:HttpPort) { $script:HttpsPort = Find-FreePort ($script:HttpsPort + 1) } Write-Output "port 443 is in use; using $($script:HttpsPort) for edge HTTPS (auto-picked). Customers reaching the panel on standard 443 will need an upstream proxy (see docs §4a)." } else { $script:HttpsPort = 443 } } elseif (Test-PortInUse $script:HttpsPort) { Write-Error "error: HTTPS port $($script:HttpsPort) is in use — choose another -HttpsPort or pass 0 to auto-pick." exit $Exit.Preflight } if ($script:PanelPort -le 0) { $script:PanelPort = Find-FreePort 8443 # Auto-pick must avoid colliding with chosen edge ports (Test-PortInUse # checks live listeners only; at install time neither is bound yet). # Use $script: explicitly — Resolve-Ports may have just rewritten the # http/https ports in the same scope, and Powershell's scope-walk would # otherwise pick up the param default. while ($script:PanelPort -eq $script:HttpPort -or $script:PanelPort -eq $script:HttpsPort) { $script:PanelPort = Find-FreePort ($script:PanelPort + 1) } if ($script:PanelPort -ne 8443) { Write-Output "direct panel-access port: $($script:PanelPort) (8443 was unavailable or collided with edge ports)." } } elseif (Test-PortInUse $script:PanelPort) { Write-Error "error: panel access port $($script:PanelPort) is in use — choose another -PanelPort." exit $Exit.Preflight } elseif ($script:PanelPort -eq $HttpPort -or $script:PanelPort -eq $HttpsPort) { Write-Error "error: -PanelPort $($script:PanelPort) collides with -HttpPort/-HttpsPort; choose a distinct port." exit $Exit.Preflight } # The auto-pick branches above log their own context-specific guidance. # If the edge ended up off-default and DNS-01 wasn't already configured, # one more nudge — DNS-01 is the universal answer. if ($script:HttpPort -ne 80 -and -not $AcmeDnsProvider) { Write-Output 'tip: with the edge on a non-standard port, the bundled Traefik cannot do Let''s Encrypt HTTP-01. Set DNS-01 in Initial Configuration or pass -AcmeDnsProvider on re-run.' } } # Render the panel-stack: .env (secrets + ports + PANEL_DATA_ROOT), the compose # file, and the Traefik dynamic config. Mirrors install.sh write_panel_stack. function Write-PanelStack { if (-not (Test-Path $ComposeDir)) { New-Item -ItemType Directory -Path $ComposeDir -Force | Out-Null } # PANEL_DATA_ROOT roots the compose bind-mount sources at the Windows state # dir; forward slashes are what Docker Desktop expects in compose volumes. $dataRoot = $PanelDir -replace '\\', '/' # Preserve persistent secrets across re-runs. The Postgres data volume is # init'd with whatever POSTGRES_PASSWORD was set on first boot — that # password is baked into pg_authid. Regenerating .env on every re-run # would silently break auth (cluster has password X, .env now has Y). # KEYCLOAK_ADMIN_PASSWORD has the same issue with the Keycloak DB. $postgresPwd = Get-EnvValue -Key 'POSTGRES_PASSWORD' -Default '' $keycloakPwd = Get-EnvValue -Key 'KEYCLOAK_ADMIN_PASSWORD' -Default '' if (-not $postgresPwd) { $postgresPwd = New-RandomSecret 32 } if (-not $keycloakPwd) { $keycloakPwd = New-RandomSecret 24 } # Keycloak 26 (hostname:v2) production-mode startup requires KC_HOSTNAME # as a full URL with NO trailing slash. Per the 26.5.2 hostname.adoc # validation rules + every example in the docs and operator CR. A # trailing slash trips the URL validator and the container exits at # boot, surfacing as Traefik 502 on /realms/*. if ($PanelHost) { $kcHostname = "https://$PanelHost" } else { $detectedIp = (Get-NetIPAddress -AddressFamily IPv4 -ErrorAction SilentlyContinue | Where-Object { $_.PrefixOrigin -ne 'WellKnown' } | Select-Object -First 1 -ExpandProperty IPAddress) if (-not $detectedIp) { $detectedIp = '127.0.0.1' } $kcHostname = "https://${detectedIp}:$($script:PanelPort)" } $envLines = @( "PANEL_VERSION=$Version" "PANEL_HOST=$PanelHost" "ACME_EMAIL=$AcmeEmail" "ACME_DNS_PROVIDER=$AcmeDnsProvider" "PANEL_DATA_ROOT=$dataRoot" "HTTP_PORT=$HttpPort" "HTTPS_PORT=$HttpsPort" "BOOTSTRAP_PORT=$($script:PanelPort)" "POSTGRES_PASSWORD=$postgresPwd" "KEYCLOAK_ADMIN_PASSWORD=$keycloakPwd" "KC_HOSTNAME=$kcHostname" ) Write-TextFileLf $EnvFile (($envLines -join "`n") + "`n") # Compose surface — copied verbatim from the bundled template. Copy-Item -Path (Resolve-Lib '../panel-stack/docker-compose.yml') -Destination $ComposeFile -Force # Postgres init script (mounted to /docker-entrypoint-initdb.d). Inlined # for the same reason install.sh inlines it — Resolve-Lib operates on # single files only, and the SQL is small. Postgres runs everything in # that dir exactly once when the data dir is empty, so re-runs of this # installer write the file again but never re-execute against an # already-initialized database. $kcDbSql = @" -- Provision the ``keycloak`` database alongside ``panel`` (created by -- POSTGRES_DB). Both owned by ``panel`` so Keycloak's KC_DB_USERNAME + -- KC_DB_PASSWORD share credentials with the panel. Without this Keycloak -- crashes on first boot: ``FATAL: database "keycloak" does not exist``. CREATE DATABASE keycloak OWNER panel; "@ Write-TextFileLf (Join-Path $PostgresInitDir '01-create-keycloak-db.sql') $kcDbSql # DNS-01: write provider creds to .env.acme-dns (ACL-locked, same SYSTEM + # Administrators inherit from $PanelDir) and apply the compose overlay. if ($AcmeDnsProvider) { $dnsEnvFile = Join-Path $ComposeDir '.env.acme-dns' $lines = @() if ($AcmeDnsEnv) { foreach ($kv in $AcmeDnsEnv) { if ($kv) { $lines += $kv } } } Write-TextFileLf $dnsEnvFile (($lines -join "`n") + "`n") Copy-Item -Path (Resolve-Lib '../panel-stack/docker-compose.dns01.override.yml') ` -Destination (Join-Path $ComposeDir 'docker-compose.override.yml') -Force Write-Output "acme: DNS-01 enabled (provider: $AcmeDnsProvider) — port 80 is no longer required for cert issuance." } # Traefik dynamic config — bootstrap mode unless BOTH panel host AND # ACME email are present. Without an email Let's Encrypt rejects the # account registration, so we stay on the self-signed bootstrap cert # and let Initial Configuration complete ACME setup later. # # Emit dynamic.yml directly (the previous template-substitution path put # `certresolver: bootstrap` and `Host("_")` in the file, both of which # Traefik rejects: "nonexistent certificate resolver" + "invalid HostSNI # matcher \"_\""). In bootstrap mode we drop the panel router entirely # — only panel-bootstrap (PathPrefix /) remains, with tls:{} resolving # to the file-provider's defaultCertificate (the bootstrap-cert PEM). $dynDir = Join-Path $TraefikDir 'dynamic' if (-not (Test-Path $dynDir)) { New-Item -ItemType Directory -Path $dynDir -Force | Out-Null } # Keycloak routers MUST win the priority race against the catch-all # panel routers; otherwise the OIDC well-known / authorize / token # endpoints land on the panel container instead of panel-keycloak. # Explicit priorities (100 vs 1) keep the behaviour independent of # Traefik's auto-priority heuristic. # Traefik v3 matcher syntax: PathPrefix takes a single argument; multi-path # OR matching uses `||` between PathPrefix calls (verified against # doc.traefik.io 3.x rules-and-priority guide). $lines = @('http:', ' routers:') if ($PanelHost -and $AcmeEmail) { $lines += @( ' keycloak:' (' rule: "Host(`{0}`) && (PathPrefix(`/realms`) || PathPrefix(`/resources`) || PathPrefix(`/admin`))"' -f $PanelHost) ' entrypoints: [websecure]' ' priority: 100' ' service: keycloak-svc' ' tls:' ' certresolver: le' ' panel:' (' rule: "Host(`{0}`)"' -f $PanelHost) # -f is format, not regex — host substitution is literal ' entrypoints: [websecure]' ' priority: 1' ' service: panel-svc' ' tls:' ' certresolver: le' ) } $lines += @( ' keycloak-bootstrap:' ' rule: "PathPrefix(`/realms`) || PathPrefix(`/resources`) || PathPrefix(`/admin`)"' ' entrypoints: [bootstrap]' ' priority: 100' ' service: keycloak-svc' ' tls: {}' ' panel-bootstrap:' ' rule: "PathPrefix(`/`)"' ' entrypoints: [bootstrap]' ' priority: 1' ' service: panel-svc' ' tls: {}' ' services:' ' panel-svc:' ' loadBalancer:' ' servers:' ' - url: "https://panel:8443"' ' passHostHeader: true' ' serversTransport: panel-transport' ' keycloak-svc:' ' loadBalancer:' ' servers:' ' - url: "http://panel-keycloak:8080"' ' passHostHeader: true' ' serversTransports:' ' panel-transport:' ' insecureSkipVerify: true' ' forwardingTimeouts:' ' dialTimeout: "5s"' ' responseHeaderTimeout: "30s"' 'tls:' ' stores:' ' default:' ' defaultCertificate:' ' certFile: "/etc/traefik/bootstrap-cert.pem"' ' keyFile: "/etc/traefik/bootstrap-cert.key"' ) Write-TextFileLf (Join-Path $dynDir 'dynamic.yml') (($lines -join "`n") + "`n") } function Register-PanelService { if (-not $NoDocker) { return } $binary = Join-Path $PanelDir 'bin\licensepanel.exe' if (-not (Test-Path $binary)) { Write-Error "error: panel binary missing at $binary (copy it manually before running with -NoDocker)." exit $Exit.Generic } if (-not (Get-Service -Name $ServiceName -ErrorAction SilentlyContinue)) { New-Service -Name $ServiceName -BinaryPathName "`"$binary`"" ` -DisplayName 'LicensePanel' -StartupType Automatic | Out-Null } if (-not $NoStart) { Start-Service -Name $ServiceName } } function Show-StackLogs { Write-Warning 'recent logs from the stack:' Push-Location $ComposeDir try { docker compose ps 2>&1 | ForEach-Object { Write-Warning " $_" } docker compose logs --tail=40 panel-postgres panel panel-traefik 2>&1 | ForEach-Object { Write-Warning " $_" } } finally { Pop-Location } Write-Warning "full logs: docker compose -f $ComposeFile logs" } function Invoke-StackPull { # Always pull before `compose up` so a re-run (especially after -Reset) # picks up the newest published images. Without this `docker compose up` # reuses whatever each tag (e.g. panel:latest) resolved to on the host's # *previous* pull. Failures are warned about but don't abort — air-gapped # hosts still want the install to proceed against the local cache. if ($NoDocker) { return } # DKB-REG T7 — resolve the registry credential: manual -Registry* override; # otherwise fetch it from the LicenseServer registry-bootstrap endpoint using # -License + -ActivationCode (the customer types only their license). if (-not ($RegistryUrl -and $RegistryUser -and $RegistryToken) -and $License -and $ActivationCode) { $body = @{ serial = $License; activationCode = $ActivationCode } | ConvertTo-Json -Compress $url = ($LicenseServerUrl.TrimEnd('/')) + '/api/v1/licenses/registry-bootstrap' try { $resp = Invoke-RestMethod -Method Post -Uri $url -ContentType 'application/json' -Body $body $RegistryUrl = $resp.registryUrl $RegistryUser = $resp.username $RegistryToken = $resp.token $RegistryImagePrefix = $resp.imagePrefix Write-Output ("registry: fetched license-driven pull credential for {0}" -f $RegistryUrl) } catch { throw ("registry-bootstrap failed — check the license serial + activation code: {0}" -f $_.Exception.Message) } } # T17 — the panel image is PRIVATE: log the host in BEFORE the pull (no-op when # creds are absent). Token via --password-stdin (never argv). if ($RegistryUrl -and $RegistryUser -and $RegistryToken) { Write-Output ("registry: docker login {0} as {1}" -f $RegistryUrl, $RegistryUser) $RegistryToken | docker login $RegistryUrl --username $RegistryUser --password-stdin if ($LASTEXITCODE -ne 0) { Write-Warning ("docker login failed for {0} — the private panel pull may fail." -f $RegistryUrl) } } Write-Output 'pulling stack images (panel, traefik, postgres) ...' Push-Location $ComposeDir try { docker compose pull --quiet if ($LASTEXITCODE -ne 0) { Write-Warning 'docker compose pull reported non-zero — falling back to local image cache.' } } finally { Pop-Location } } function Start-PanelStack { if ($NoStart) { Write-Output 'stack not started (-NoStart).'; return } if ($NoDocker) { Write-Output 'stack not started (-NoDocker).'; return } Invoke-StackPull Push-Location $ComposeDir try { docker compose up -d if ($LASTEXITCODE -ne 0) { Show-StackLogs Write-Error 'error: docker compose up reported non-zero — see logs above.' exit $Exit.Compose } } finally { Pop-Location } # Wait for panel to report healthy — mirrors install.sh. Up to 3 min; # first boot can be slow (EF migrations + Wolverine codegen + Kestrel # TLS bind). Prevents the operator's first browser hit hitting a 502. # Pull both .State and .Health so a crash-looping container (exited / # restarting) is detected immediately instead of being mistaken for # "still starting" until timeout. Write-Output 'waiting for the panel to report healthy (up to 3 min) ...' Write-Output " parallel: docker compose -f $ComposeFile logs -f panel" $deadline = (Get-Date).AddSeconds(180) $start = Get-Date; $lastBeat = $start while ((Get-Date) -lt $deadline) { Push-Location $ComposeDir try { $line = docker compose ps --format '{{.Service}} {{.State}} {{.Health}}' 2>$null | Where-Object { $_ -match '^panel\s' } | Select-Object -First 1 } finally { Pop-Location } $parts = if ($line) { $line -split '\s+' } else { @() } $containerState = if ($parts.Count -ge 2) { $parts[1] } else { '' } $state = if ($parts.Count -ge 3) { $parts[2] } else { '' } $elapsed = [int]((Get-Date) - $start).TotalSeconds switch ($state) { 'healthy' { Write-Output "panel is healthy (${elapsed}s)."; return } 'unhealthy' { Show-StackLogs Write-Error 'panel container reports UNHEALTHY — see logs above.' exit $Exit.Compose } } if ($containerState -in 'exited', 'dead') { Show-StackLogs Write-Error "panel container is $containerState mid-boot — see logs above." exit $Exit.Compose } if (((Get-Date) - $lastBeat).TotalSeconds -ge 15 -and $elapsed -gt 0) { $cs = if ($containerState) { $containerState } else { '?' } $hs = if ($state) { $state } else { 'starting' } Write-Output " still booting (${elapsed}s elapsed, container=$cs, health=$hs)" $lastBeat = Get-Date } Start-Sleep -Seconds 5 } Write-Warning 'panel did not report healthy within 180s — first boot can be slow on small VMs, but logs may explain why.' Show-StackLogs Write-Error "healthcheck timeout — see logs above. The stack is still running; check again with: docker compose -f $ComposeFile ps" exit $Exit.Compose } # -Reset -Yes: tear down the stack (incl. named volumes) and wipe $PanelDir # before fresh-installing. Two switches required; no interactive prompt. function Invoke-Reset { if (-not $Yes) { Write-Error '-Reset will WIPE all panel state (state.db, KEK, certs, project data, postgres data volume). Pair it with -Yes to confirm: -Reset -Yes' exit $Exit.Generic } Write-Output "-Reset -Yes: tearing down stack + wiping $PanelDir ..." if ((Test-Path $ComposeFile) -and (Get-Command docker -ErrorAction SilentlyContinue)) { Push-Location $ComposeDir try { docker compose down --volumes --remove-orphans 2>&1 | Out-Null } finally { Pop-Location } } if (Test-Path $PanelDir) { Remove-Item -Recurse -Force $PanelDir } Write-Output 'reset complete — proceeding with fresh install.' } # Partial-install info: state dir exists but no state.db. Reusing what's there. function Show-PartialInstallNotice { if (-not (Test-Path $PanelDir)) { return } $existing = @() if (Test-Path (Join-Path $KeysDir 'master.pfx')) { $existing += 'KEK' } if (Test-Path (Join-Path $PostgresTlsDir 'server.crt')) { $existing += 'postgres-tls' } if (Test-Path (Join-Path $TraefikDir 'bootstrap-cert.pem')) { $existing += 'bootstrap-cert' } if (Test-Path $EnvFile) { $existing += '.env (secrets)' } if ($existing.Count -gt 0) { Write-Output "resuming partial install — reusing: $($existing -join ', ')" } } function Show-FirstInstallSummary { Write-Output '' Write-Output 'LicensePanel installed.' Write-Output 'Open in your browser:' if ($PanelHost) { $suffix = if ($HttpsPort -ne 443) { ":$HttpsPort" } else { '' } Write-Output (' https://{0}{1}/' -f $PanelHost, $suffix) } Write-Output (' https://{0}:{1}/ (direct access)' -f (Get-PrimaryIPv4), $script:PanelPort) Write-Output '' Write-Output 'Bootstrap mode is active for the next 60 minutes.' Write-Output "Stack status: docker compose -f $ComposeFile ps" Write-Output "Stack logs: docker compose -f $ComposeFile logs -f panel" } # ============================================================================ # Entrypoint # ============================================================================ function Invoke-Install { Assert-Administrator Test-StatePerms if ($Reset) { Invoke-Reset } if (Test-ExistingInstall) { Invoke-IdempotentRerun # exits } Show-PartialInstallNotice Initialize-StateDirs Resolve-Ports if (-not $NoDocker) { if (-not (Get-Command docker -ErrorAction SilentlyContinue)) { Write-Error 'error: docker not found in PATH. Install Docker Desktop / EE or pass -NoDocker.' exit $Exit.DockerInstall } } New-KekMaterial New-PostgresTls New-BootstrapCert Write-PanelStack Register-PanelService Start-PanelStack Show-FirstInstallSummary } Invoke-Install