<# .SYNOPSIS Deploy FitOS na alternatywne urzadzenie (alt-host 192.168.50.127) - porty 13xxx. .DESCRIPTION 1. Czyta konfiguracje z remote/.deploy.env (gitignore; wzorzec: .deploy.env.example). 2. Pakuje zrodla (api, app, admin, remote) tarem bez node_modules/dist/.env. 3. Wysyla na host przez SFTP, wypakowuje do ~/fitos-alt, generuje ~/fitos-alt/.env oraz config.js (adres API) z config.js.tpl. 4. docker compose -f remote/docker-compose.yml --env-file ../.env up -d --build 5. Weryfikuje /health API, config.js app/admin i kontenery przez API Portainera. Sekrety puste w .deploy.env (JWT, haslo admina) sa generowane losowo i zapisywane z powrotem do .deploy.env - po pierwszym runie sa trwale. .USAGE .\deploy.ps1 # pelny deploy (sync + build + up + weryfikacja) .\deploy.ps1 -SkipSync # bez wgrywania zrodel (restart / sama zmiana env i config.js) .\deploy.ps1 -NoBuild # up -d bez --build (obrazy juz zbudowane) .\deploy.ps1 -Logs # na koniec: docker compose logs (ostatnie linie) #> [CmdletBinding()] param( [switch]$SkipSync, [switch]$NoBuild, [switch]$Logs ) $ErrorActionPreference = 'Stop' function Write-Step([string]$msg) { Write-Host "==> $msg" -ForegroundColor Cyan } function Write-Ok([string]$msg) { Write-Host " OK: $msg" -ForegroundColor Green } function Get-RandomHex([int]$bytes) { $buf = New-Object byte[] $bytes [Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($buf) ($buf | ForEach-Object { $_.ToString('x2') }) -join '' } function Get-RandomPassword([int]$length = 20) { $chars = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789!@#$%' $buf = New-Object byte[] $length [Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($buf) -join ($buf | ForEach-Object { $chars[$_ % $chars.Length] }) } # --- 1. konfiguracja ------------------------------------------------------- $repoRoot = Split-Path -Parent $PSScriptRoot $deployEnvPath = Join-Path $PSScriptRoot '.deploy.env' if (-not (Test-Path -LiteralPath $deployEnvPath)) { Write-Host "Brak pliku $deployEnvPath" -ForegroundColor Red Write-Host 'Skopiuj remote\.deploy.env.example -> remote\.deploy.env i uzupelnij (plik jest w .gitignore).' exit 1 } $cfg = @{} Get-Content -LiteralPath $deployEnvPath | ForEach-Object { $line = $_.Trim() if ($line -and -not $line.StartsWith('#') -and $line.Contains('=')) { $k, $v = $line.Split('=', 2) $cfg[$k.Trim()] = $v.Trim() } } function Cfg([string]$key, [string]$default) { $v = $cfg[$key] if ($v) { $v } else { $default } } foreach ($key in 'SSH_HOST', 'SSH_USER', 'SSH_PASSWORD') { if (-not $cfg[$key]) { Write-Host "Brak $key w .deploy.env" -ForegroundColor Red; exit 1 } } $hostAlias = $cfg['SSH_HOST'] $user = $cfg['SSH_USER'] $remoteDir = Cfg 'REMOTE_DIR' 'fitos-alt' # porty alt-hosta odpowiadają głównemu mapowaniu 9xxx: admin 13000, app 13001, api 13002 $apiPort = Cfg 'API_HOST_PORT' '13002' $appPort = Cfg 'APP_HOST_PORT' '13001' $adminPort = Cfg 'ADMIN_HOST_PORT' '13000' $apiUrl = Cfg 'API_PUBLIC_URL' ("http://{0}:{1}" -f $hostAlias, $apiPort) # sekrety: uzupelnij losowymi wartosciami i zapisz z powrotem, zeby byly trwale $envDirty = $false foreach ($key in 'JWT_ACCESS_SECRET', 'JWT_REFRESH_SECRET') { if (-not $cfg[$key]) { $cfg[$key] = Get-RandomHex 32; $envDirty = $true } } if (-not $cfg['FITOS_FIRST_ADMIN_PASSWORD']) { $cfg['FITOS_FIRST_ADMIN_PASSWORD'] = Get-RandomPassword Write-Host (" Wygenerowano haslo pierwszego admina: {0}" -f $cfg['FITOS_FIRST_ADMIN_PASSWORD']) -ForegroundColor Yellow $envDirty = $true } if ($envDirty) { Write-Step 'Zapis wygenerowanych sekretow do remote\.deploy.env' $lines = Get-Content -LiteralPath $deployEnvPath | ForEach-Object { $line = $_ foreach ($key in 'JWT_ACCESS_SECRET', 'JWT_REFRESH_SECRET', 'FITOS_FIRST_ADMIN_PASSWORD') { if ($line -match ("^\s*" + $key + "\s*=")) { $line = ("{0}={1}" -f $key, $cfg[$key]); break } } $line } [IO.File]::WriteAllLines($deployEnvPath, $lines, (New-Object Text.UTF8Encoding($false))) Write-Ok 'sekrety zapisane' } if (-not (Get-Module -ListAvailable Posh-SSH)) { Write-Host 'Brak modulu Posh-SSH. Zainstaluj: Install-Module Posh-SSH -Scope CurrentUser' -ForegroundColor Red exit 1 } Import-Module Posh-SSH # --- 2. sesja SSH ----------------------------------------------------------- Write-Step ("SSH {0}@{1}" -f $user, $hostAlias) $securePass = ConvertTo-SecureString $cfg['SSH_PASSWORD'] -AsPlainText -Force $cred = New-Object Management.Automation.PSCredential($user, $securePass) $session = New-SSHSession -ComputerName $hostAlias -Credential $cred -AcceptKey -ConnectionTimeout 20 Write-Ok ("sesja SSH #{0}" -f $session.SessionId) function Invoke-Remote([string]$cmd, [int]$timeoutSec = 3600) { $r = Invoke-SSHCommand -SessionId $session.SessionId -Command $cmd -TimeOut $timeoutSec if ($r.ExitStatus -ne 0) { Write-Host ("Polecenie zdalne nieudane (exit {0}):`n{1}" -f $r.ExitStatus, $cmd) -ForegroundColor Red if ($r.Error) { Write-Host $r.Error } throw 'Deploy przerwany.' } return ($r.Output -join "`n") } try { # --- 3. sync zrodel ------------------------------------------------------ if (-not $SkipSync) { Write-Step 'Pakowanie zrodel (api, app, admin, remote) bez node_modules/dist/.env' $tgz = Join-Path $env:TEMP 'fitos-alt-src.tgz' if (Test-Path -LiteralPath $tgz) { Remove-Item -LiteralPath $tgz } $tarArgs = @( '-czf', $tgz, '--exclude=node_modules', '--exclude=dist', '--exclude=.env', '--exclude=.deploy.env', '--exclude=.git', '-C', $repoRoot, 'api', 'app', 'admin', 'remote' ) $tarOut = & tar.exe @tarArgs 2>&1 if ($LASTEXITCODE -ne 0) { throw "tar.exe nieudany: $tarOut" } Write-Ok ("paczka {0:N1} MB" -f ((Get-Item -LiteralPath $tgz).Length / 1MB)) Write-Step 'Upload na host (SFTP)' $sftp = New-SFTPSession -ComputerName $hostAlias -Credential $cred -AcceptKey Set-SFTPItem -SessionId $sftp.SessionId -Path $tgz -Destination '/tmp' -Force Remove-SFTPSession -SessionId $sftp.SessionId | Out-Null Remove-Item -LiteralPath $tgz Write-Ok 'wyslano /tmp/fitos-alt-src.tgz' Write-Step ("Rozpakowanie do ~/{0} (stare drzewo -> .old)" -f $remoteDir) Invoke-Remote @" set -e cd ~ rm -rf $remoteDir.new mkdir -p $remoteDir.new tar -xzf /tmp/fitos-alt-src.tgz -C $remoteDir.new rm -rf $remoteDir.old /tmp/fitos-alt-src.tgz if [ -d $remoteDir ]; then mv $remoteDir $remoteDir.old; fi mv $remoteDir.new $remoteDir rm -rf $remoteDir.old "@ | Out-Null Write-Ok ("drzewo zrodlowe w ~/{0}" -f $remoteDir) } else { Write-Step 'Pominieto sync zrodel (-SkipSync)' } # --- 4. srodowisko stosu + runtime config -------------------------------- Write-Step ("Generowanie ~/{0}/.env oraz config.js (apiUrl={1})" -f $remoteDir, $apiUrl) $stackLines = @( 'NODE_ENV=production', ("JWT_ACCESS_SECRET={0}" -f $cfg['JWT_ACCESS_SECRET']), ("JWT_REFRESH_SECRET={0}" -f $cfg['JWT_REFRESH_SECRET']), ("FITOS_FIRST_ADMIN_EMAIL={0}" -f (Cfg 'FITOS_FIRST_ADMIN_EMAIL' 'admin@fitos.local')), ("FITOS_FIRST_ADMIN_PASSWORD={0}" -f $cfg['FITOS_FIRST_ADMIN_PASSWORD']), ("LOG_LEVEL={0}" -f (Cfg 'LOG_LEVEL' 'info')), ("COOKIE_SECURE={0}" -f (Cfg 'COOKIE_SECURE' 'false')), ("CORS_EXTRA_ORIGINS={0}" -f (Cfg 'CORS_EXTRA_ORIGINS' '')), ("TZ={0}" -f (Cfg 'TZ' 'Europe/Warsaw')), ("API_HOST_PORT={0}" -f $apiPort), ("APP_HOST_PORT={0}" -f $appPort), ("ADMIN_HOST_PORT={0}" -f $adminPort), ("DB_HOST_PORT={0}" -f (Cfg 'DB_HOST_PORT' '13543')) ) -join "`n" $envB64 = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($stackLines + "`n")) Invoke-Remote @" set -e cd ~/$remoteDir printf '%s' '$envB64' | base64 -d > .env chmod 600 .env sed 's|__API_PUBLIC_URL__|$apiUrl|' remote/config/config.js.tpl > remote/config/app.config.js cp remote/config/app.config.js remote/config/admin.config.js "@ | Out-Null Write-Ok '.env (chmod 600) + config.js wygenerowane' # --- 5. build + up --------------------------------------------------------- $buildFlag = '' if (-not $NoBuild) { $buildFlag = ' --build' } Write-Step ("docker compose up -d{0} (projekt fitos-alt; pierwsze budowanie bywa dlugie)" -f $buildFlag) Invoke-Remote ("cd ~/{0}/remote && docker compose --env-file ../.env up -d{1} 2>&1" -f $remoteDir, $buildFlag) | Out-Null Write-Ok 'kontenery wystartowaly' # --- 6. weryfikacja -------------------------------------------------------- Write-Step ("Zdrowie: http://{0}:{1}/health (czekam max 180 s)" -f $hostAlias, $apiPort) $ok = $false for ($i = 0; $i -lt 60; $i++) { try { $h = Invoke-RestMethod -Uri ("http://{0}:{1}/health" -f $hostAlias, $apiPort) -TimeoutSec 5 if ($h.status -eq 'ok') { $ok = $true; break } } catch { Start-Sleep -Seconds 3 } } if ($ok) { Write-Ok 'API healthy' } else { Write-Host ' API nie odpowiada! Ostatnie logi api:' -ForegroundColor Red Invoke-Remote ("cd ~/{0}/remote && docker compose logs --tail 40 api" -f $remoteDir) 120 | Write-Host throw 'Weryfikacja /health nieudana.' } foreach ($p in $appPort, $adminPort) { $cfgJs = (Invoke-WebRequest -Uri ("http://{0}:{1}/config.js" -f $hostAlias, $p) -UseBasicParsing -TimeoutSec 10).Content if ($cfgJs -match [regex]::Escape("'" + $apiUrl + "'")) { Write-Ok ("port {0} serwuje config.js z apiUrl={1}" -f $p, $apiUrl) } else { Write-Host (" UWAGA: port {0} - config.js ma inne apiUrl!" -f $p) -ForegroundColor Yellow } } if ($cfg['PORTAINER_URL'] -and $cfg['PORTAINER_PASSWORD']) { Write-Step 'Weryfikacja przez API Portainera' try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 [Net.ServicePointManager]::ServerCertificateValidationCallback = { $true } # JSON przez ConvertTo-Json - reczne formatowanie z klamram JSONa # amie operator -f (klamerki to znaki specjalne formatu .NET) $authBody = (@{ Username = $cfg['PORTAINER_USER']; Password = $cfg['PORTAINER_PASSWORD'] } | ConvertTo-Json -Compress) $jwt = (Invoke-RestMethod -Uri ($cfg['PORTAINER_URL'] + '/api/auth') -Method Post -Body $authBody -ContentType 'application/json' -TimeoutSec 15).JWT $headers = @{ Authorization = "Bearer $jwt" } # lokalny endpoint (typ 1); Portainer 2.33 nie pozwala go utworzyc przez API - # jezeli lista jest pusta, uzytkownik musi raz dodac 'Environments > Add environment # > Docker (socket)' w UI, pozniej ta weryfikacja dziala automatycznie $endpoints = Invoke-RestMethod -Uri ($cfg['PORTAINER_URL'] + '/api/endpoints') -Headers $headers -TimeoutSec 15 $endpoint = $endpoints | Where-Object { $_.Type -eq 1 } | Select-Object -First 1 if (-not $endpoint) { Write-Host (" Portainer: brak skonfigurowanego srodowiska lokalnego - raz dodaj w UI: {0} (Environments > Add environment > Docker)" -f $cfg['PORTAINER_URL']) -ForegroundColor Yellow } else { $filter = [Uri]::EscapeDataString('{"label":["com.docker.compose.project=fitos-alt"]}') $containers = Invoke-RestMethod -Uri ($cfg['PORTAINER_URL'] + "/api/endpoints/$($endpoint.Id)/docker/containers/json?all=1&filters=$filter") -Headers $headers -TimeoutSec 15 foreach ($c in $containers) { $name = ($c.Names | Where-Object { $_ -like '/fitos*' }) -replace '/', '' Write-Ok ("{0,-16} {1,-10} {2}" -f $name, $c.State, $c.Status) } } } catch { Write-Host (" Portainer: nie sprawdzono ({0})" -f $_.Exception.Message) -ForegroundColor Yellow } } if ($Logs) { Write-Step 'Logi stosu (ostatnie 60 linii)' Invoke-Remote ("cd ~/{0}/remote && docker compose logs --tail 60" -f $remoteDir) | Write-Host } Write-Host '' Write-Host 'Deploy zakonczony - FitOS (alt-host):' -ForegroundColor Green Write-Host (" App: http://{0}:{1}" -f $hostAlias, $appPort) Write-Host (" Admin: http://{0}:{1}" -f $hostAlias, $adminPort) Write-Host (" API: http://{0}:{1}/api/v1 (docs: /api/docs)" -f $hostAlias, $apiPort) Write-Host ' Logowanie z przegladarek: originaly DDNS (dowolny port) lub IP z CORS_EXTRA_ORIGINS.' } finally { Remove-SSHSession -SessionId $session.SessionId | Out-Null }