[CmdletBinding()] param() $ErrorActionPreference = 'Stop' $ProgressPreference = 'SilentlyContinue' [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $script:SourceBaseUrl = if ($env:HEIMDALL_SOURCE_BASE_URL) { $env:HEIMDALL_SOURCE_BASE_URL.TrimEnd('/') } else { 'https://sources.tordais.cc/arnaud.dartois/Heimdall/raw/branch/main' } function Read-Answer { param([string]$Prompt, [string]$Default) $answer = Read-Host "$Prompt [$Default]" if ([string]::IsNullOrWhiteSpace($answer)) { return $Default } return $answer.Trim() } function Read-YesNo { param([string]$Prompt, [string]$Default = 'n') return (Read-Answer -Prompt $Prompt -Default $Default) -match '^(?i:o|oui|y|yes)$' } function New-RandomHex { param([int]$ByteCount = 32) $bytes = [byte[]]::new($ByteCount) $rng = [System.Security.Cryptography.RandomNumberGenerator]::Create() try { $rng.GetBytes($bytes) } finally { $rng.Dispose() } return [BitConverter]::ToString($bytes).Replace('-', '').ToLowerInvariant() } function Set-PrivateAcl { param([string]$Path, [bool]$IsDirectory = $false) $identity = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name $acl = Get-Acl -LiteralPath $Path $acl.SetAccessRuleProtection($true, $false) foreach ($rule in @($acl.Access)) { [void]$acl.RemoveAccessRuleAll($rule) } $inheritance = if ($IsDirectory) { [System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit } else { [System.Security.AccessControl.InheritanceFlags]::None } $rule = [System.Security.AccessControl.FileSystemAccessRule]::new( $identity, [System.Security.AccessControl.FileSystemRights]::FullControl, $inheritance, [System.Security.AccessControl.PropagationFlags]::None, [System.Security.AccessControl.AccessControlType]::Allow) [void]$acl.AddAccessRule($rule) Set-Acl -LiteralPath $Path -AclObject $acl } function Get-SourceAsset { param([string]$RelativePath, [string]$DestinationPath) $assetUri = "$script:SourceBaseUrl/$RelativePath" Invoke-WebRequest -UseBasicParsing -Uri $assetUri -OutFile $DestinationPath -TimeoutSec 60 } function Invoke-DockerCompose { param([string[]]$ComposeArguments) & docker compose @ComposeArguments if ($LASTEXITCODE -ne 0) { throw "docker compose a échoué (code $LASTEXITCODE)." } } if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) { throw 'Cet installateur est prévu pour Windows PowerShell ou PowerShell sous Windows.' } if (-not (Get-Command docker -ErrorAction SilentlyContinue)) { throw 'Docker est requis.' } & docker compose version | Out-Null if ($LASTEXITCODE -ne 0) { throw 'Le plugin Docker Compose est requis.' } Write-Host 'Installation de Heimdall Central (serveur + PostgreSQL).' $defaultDestination = Join-Path $HOME 'heimdall' $destination = [IO.Path]::GetFullPath((Read-Answer "Dossier d’installation" $defaultDestination)) $webPortText = Read-Answer 'Port HTTP du serveur' '5000' $corsOrigin = Read-Answer 'Origine(s) autorisée(s) par CORS' '*' $webPort = 0 if (-not [int]::TryParse($webPortText, [ref]$webPort) -or $webPort -lt 1 -or $webPort -gt 65535) { throw 'Port invalide.' } if ($corsOrigin -notmatch '^[A-Za-z0-9*.,:/_-]+$') { throw 'Origine CORS invalide.' } if ((Test-Path -LiteralPath (Join-Path $destination 'docker-compose.yml')) -or (Test-Path -LiteralPath (Join-Path $destination '.env'))) { throw "Le dossier contient déjà une installation Heimdall; aucun fichier n’a été remplacé." } $null = New-Item -ItemType Directory -Path $destination -Force $secretsDirectory = Join-Path $destination 'secrets' $optionalDirectory = Join-Path $destination 'optional' $optionalSecretsDirectory = Join-Path $optionalDirectory 'secrets' $null = New-Item -ItemType Directory -Path $secretsDirectory -Force $null = New-Item -ItemType Directory -Path $optionalSecretsDirectory -Force Set-PrivateAcl -Path $destination -IsDirectory $true Set-PrivateAcl -Path $secretsDirectory -IsDirectory $true Set-PrivateAcl -Path $optionalDirectory -IsDirectory $true Set-PrivateAcl -Path $optionalSecretsDirectory -IsDirectory $true $dbPassword = New-RandomHex $jwtKey = New-RandomHex $jwtRefreshKey = New-RandomHex $dbPasswordPath = Join-Path $secretsDirectory 'db_password' [IO.File]::WriteAllText($dbPasswordPath, $dbPassword, [Text.Encoding]::ASCII) Set-PrivateAcl -Path $dbPasswordPath $envContent = @" POSTGRES_DB=heimdall POSTGRES_USER=heimdall DATABASE_URL=Host=postgresql;Port=5432;Database=heimdall;Username=heimdall;Password=$dbPassword JWT__KEY=$jwtKey JWT__REFRESHKEY=$jwtRefreshKey JWT__ISSUER=heimdall JWT__AUDIENCE=heimdall-api ASPNETCORE_ENVIRONMENT=Production WEB_PORT=$webPort Cors__AllowedOrigins=$corsOrigin TZ=Europe/Paris REDIS_PASSWORD=$(New-RandomHex) HEIMDALL_DATA_VOLUME=heimdall_heimdall_data "@ $envPath = Join-Path $destination '.env' [IO.File]::WriteAllText($envPath, $envContent.TrimStart("`r", "`n"), [Text.Encoding]::ASCII) Set-PrivateAcl -Path $envPath $composeContent = @' name: heimdall services: postgresql: image: postgres:17-alpine environment: POSTGRES_DB: ${POSTGRES_DB} POSTGRES_USER: ${POSTGRES_USER} POSTGRES_PASSWORD_FILE: /run/secrets/db_password secrets: [db_password] volumes: [pgdata:/var/lib/postgresql/data] healthcheck: test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"] interval: 10s timeout: 5s retries: 5 start_period: 30s restart: unless-stopped networks: [heimdall-net] heimdall: image: eltruncho/heimdall:latest environment: DATABASE_URL: ${DATABASE_URL:?missing DATABASE_URL} JWT__Issuer: ${JWT__ISSUER} JWT__Audience: ${JWT__AUDIENCE} JWT__KEY: ${JWT__KEY:?missing JWT__KEY} JWT__REFRESHKEY: ${JWT__REFRESHKEY:?missing JWT__REFRESHKEY} ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT} ASPNETCORE_URLS: http://+:8080 Cors__AllowedOrigins: ${Cors__AllowedOrigins} ports: ["${WEB_PORT}:8080"] volumes: - heimdall_data:/var/lib/heimdall - heimdall_data:/app/data depends_on: postgresql: condition: service_healthy healthcheck: test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/healthz"] interval: 30s timeout: 10s retries: 3 start_period: 60s restart: unless-stopped networks: [heimdall-net] volumes: pgdata: heimdall_data: secrets: db_password: file: ./secrets/db_password networks: heimdall-net: name: heimdall-net driver: bridge '@ $composePath = Join-Path $destination 'docker-compose.yml' [IO.File]::WriteAllText($composePath, $composeContent, [Text.Encoding]::ASCII) Set-PrivateAcl -Path $composePath $selected = [Collections.Generic.List[string]]::new() foreach ($service in @('ollama', 'ntfy', 'rustfs', 'coturn', 'redis', 'backup')) { $prompt = if ($service -eq 'backup') { 'Activer les sauvegardes planifiées (nécessite une configuration dédiée) ?' } else { "Installer le service optionnel $service ?" } if (Read-YesNo $prompt) { $selected.Add($service) $assetPath = Join-Path $optionalDirectory "docker-compose.$service.yml" Get-SourceAsset "docker/docker-compose.$service.yml" $assetPath Set-PrivateAcl -Path $assetPath } } Write-Host "Compose généré dans $composePath" Write-Host "Variables protégées dans $envPath et secret PostgreSQL dans secrets (ACL utilisateur uniquement)." Write-Host 'Validation du Compose avant démarrage…' Invoke-DockerCompose @('--env-file', $envPath, '-f', $composePath, 'config', '--quiet') $startCore = Read-YesNo 'Démarrer PostgreSQL et Heimdall maintenant ?' 'o' if ($startCore) { Invoke-DockerCompose @('--env-file', $envPath, '-f', $composePath, 'up', '-d') } foreach ($service in $selected) { switch ($service) { 'rustfs' { $accessKeyPath = Join-Path $optionalSecretsDirectory 'rustfs_access_key' $secretKeyPath = Join-Path $optionalSecretsDirectory 'rustfs_secret_key' [IO.File]::WriteAllText($accessKeyPath, "heimdall$(New-RandomHex 8)", [Text.Encoding]::ASCII) [IO.File]::WriteAllText($secretKeyPath, (New-RandomHex), [Text.Encoding]::ASCII) Set-PrivateAcl $accessKeyPath Set-PrivateAcl $secretKeyPath } 'coturn' { $coturnSecretPath = Join-Path $optionalSecretsDirectory 'coturn_secret' [IO.File]::WriteAllText($coturnSecretPath, (New-RandomHex), [Text.Encoding]::ASCII) Set-PrivateAcl $coturnSecretPath } 'backup' { $backupScriptsPath = Join-Path $optionalDirectory 'scripts' $null = New-Item -ItemType Directory -Path $backupScriptsPath -Force Set-PrivateAcl -Path $backupScriptsPath -IsDirectory $true foreach ($name in @('backup.sh', 'backup-protected-data.sh', 'backup-rustfs.sh', 'restore.sh', 'restore-protected-data.sh')) { $assetPath = Join-Path $backupScriptsPath $name Get-SourceAsset "docker/scripts/$name" $assetPath Set-PrivateAcl -Path $assetPath } $backupDbPassword = Join-Path $optionalSecretsDirectory 'db_password' Copy-Item -LiteralPath $dbPasswordPath -Destination $backupDbPassword Set-PrivateAcl -Path $backupDbPassword } } if ($startCore -and (Read-YesNo "Démarrer le service optionnel $service ?" 'o')) { Invoke-DockerCompose @('--project-name', "heimdall-$service", '--env-file', $envPath, '-f', (Join-Path $optionalDirectory "docker-compose.$service.yml"), 'up', '-d') } else { Write-Host "Service $service préparé dans $optionalDirectory." } } Write-Host "Configurez ensuite les intégrations activées depuis les paramètres de Central; leurs valeurs restent gérées par l’IHM."