Alpenwerk HR 0.1.0 Betrieb auf Windows Server - Die Anwendung läuft im IIS (HttpPlatformHandler) unter dem Konto des Anwendungspools, ohne Administratorrechte und ohne eigenen Windows-Dienst - Das Zertifikat kommt aus dem Zertifikatsspeicher; die Bindung folgt jeder Erneuerung automatisch - Neue Versionen mit aktualisieren.ps1 -Paket <zip>, mit Sicherung vorab; Rückstieg mit zuruecksetzen.ps1 - HR-Zugang für ganze Domains mit freischalten.ps1 -Domain; Einzelsperren haben Vorrang - Anmeldung ausschließlich über Microsoft Entra ID - Das Windows-Paket hängt an jedem Release Fachliche Erweiterungen - Änderungen per Austauschdatei importieren, mit Vorschau, Prüfung und Fehlerdatei - Einstellung: eigene Maske für externe Personen, Übernahme von Leiharbeitskräften, Planstellen zum Eintrittstag - Organisationsstruktur: Einheiten und Kostenstellen anlegen, umbenennen und abschließen; Suche nach Planstelle, Einheit und Kostenstelle - Historie: Austritt, Versetzung und Eintritt berichtigen oder zurücknehmen; Planstelle mit Bezeichnung - Abwesenheiten ohne Ende, geplante Abwesenheiten mit Art, Checklisten mit Anlass, auch zur Rückkehr - Berichte mit Mehrfachauswahl in allen Kriterien; Kostenstelle als Filter und Gruppierung - Stammdaten: mehrere Notfallkontakte, Lehrzeit, Ferialkraft, Altersteilzeit, erweiterte Beschäftigtengruppen und Geschlechtsangaben
313 lines
13 KiB
PowerShell
313 lines
13 KiB
PowerShell
# Gemeinsame Bausteine der Betriebsskripte. Wird von den anderen Skripten
|
|
# per Dot-Sourcing geladen, nicht direkt aufgerufen.
|
|
#
|
|
# Bewusst ohne Umlaute: Windows PowerShell 5.1 liest Skripte ohne BOM als
|
|
# ANSI, und aus "Pruefung" wuerde sonst Zeichensalat.
|
|
#
|
|
# Bewusst ohne PowerShell-7-Syntax (kein ??, kein ?:, kein &&): auf einem
|
|
# Windows Server ist 5.1 das, was da ist.
|
|
|
|
$ErrorActionPreference = 'Stop'
|
|
|
|
# Die Anwendung laeuft im IIS: Website und Anwendungspool tragen diese Namen.
|
|
$PoolName = 'AlpenwerkHR'
|
|
$SiteName = 'Alpenwerk HR'
|
|
|
|
# Wohlbekannte SIDs statt Namen: "Administratoren" heisst auf einem deutschen
|
|
# Server anders als auf einem englischen, die SID ueberall gleich.
|
|
$SidAdministratoren = '*S-1-5-32-544'
|
|
$SidSystem = '*S-1-5-18'
|
|
$SidLocalService = '*S-1-5-19'
|
|
$SidIisIusrs = '*S-1-5-32-568'
|
|
|
|
function Read-EnvDatei {
|
|
param([Parameter(Mandatory = $true)][string]$Pfad)
|
|
$werte = @{}
|
|
if (-not (Test-Path -LiteralPath $Pfad)) { return $werte }
|
|
foreach ($zeile in Get-Content -LiteralPath $Pfad -Encoding UTF8) {
|
|
$t = $zeile.Trim()
|
|
if ($t -eq '' -or $t.StartsWith('#')) { continue }
|
|
$i = $t.IndexOf('=')
|
|
if ($i -lt 1) { continue }
|
|
$schluessel = $t.Substring(0, $i).Trim()
|
|
$wert = $t.Substring($i + 1).Trim()
|
|
if ($wert.Length -ge 2 -and (($wert.StartsWith('"') -and $wert.EndsWith('"')) -or ($wert.StartsWith("'") -and $wert.EndsWith("'")))) {
|
|
$wert = $wert.Substring(1, $wert.Length - 2)
|
|
}
|
|
$werte[$schluessel] = $wert
|
|
}
|
|
return $werte
|
|
}
|
|
|
|
# Liefert die Namen der Pflichtwerte, die fehlen oder noch einen Platzhalter
|
|
# <...> / {{...}} tragen.
|
|
function Get-FehlendeWerte {
|
|
param([hashtable]$Werte, [string[]]$Pflicht)
|
|
$fehlend = @()
|
|
foreach ($name in $Pflicht) {
|
|
$w = $Werte[$name]
|
|
if (-not $w -or $w -match '<[^>]*>' -or $w -match '\{\{') { $fehlend += $name }
|
|
}
|
|
return $fehlend
|
|
}
|
|
|
|
$PflichtApp = @(
|
|
'PORT', 'DATABASE_URL', 'AUTH_SECRET', 'AUTH_URL',
|
|
'AUTH_MICROSOFT_ENTRA_ID_ID', 'AUTH_MICROSOFT_ENTRA_ID_SECRET', 'AUTH_MICROSOFT_ENTRA_ID_ISSUER',
|
|
'CRON_SECRET'
|
|
)
|
|
$PflichtVerwaltung = @('MIGRATE_DATABASE_URL')
|
|
|
|
function New-Geheimnis {
|
|
param([int]$Bytes = 32)
|
|
$puffer = New-Object byte[] $Bytes
|
|
$rng = [System.Security.Cryptography.RandomNumberGenerator]::Create()
|
|
$rng.GetBytes($puffer)
|
|
$rng.Dispose()
|
|
# Hex statt Base64: kommt ohne + / = aus und muss deshalb in einer
|
|
# Verbindungs-URL nicht maskiert werden.
|
|
return -join ($puffer | ForEach-Object { $_.ToString('x2') })
|
|
}
|
|
|
|
function Get-NodePfad {
|
|
$befehl = Get-Command node.exe -ErrorAction SilentlyContinue
|
|
if (-not $befehl) { throw 'node.exe nicht gefunden. Node.js installieren (https://nodejs.org) und eine neue Konsole oeffnen.' }
|
|
return $befehl.Source
|
|
}
|
|
|
|
function Assert-NodeVersion {
|
|
$node = Get-NodePfad
|
|
$version = (& $node --version).Trim().TrimStart('v')
|
|
$haupt = [int]($version.Split('.')[0])
|
|
if ($haupt -lt 22) { throw "Node.js $version ist zu alt; gebraucht wird mindestens 22." }
|
|
Write-Host "Node.js $version ($node)"
|
|
}
|
|
|
|
# Neueste Installation unter "C:\Program Files\PostgreSQL\<version>\bin",
|
|
# sofern nicht ausdruecklich angegeben.
|
|
function Get-PgBin {
|
|
param([string]$Vorgabe)
|
|
if ($Vorgabe) {
|
|
if (-not (Test-Path -LiteralPath (Join-Path $Vorgabe 'pg_dump.exe'))) { throw "In $Vorgabe liegt kein pg_dump.exe." }
|
|
return $Vorgabe
|
|
}
|
|
$basis = Join-Path $env:ProgramFiles 'PostgreSQL'
|
|
$kandidat = Get-ChildItem -LiteralPath $basis -Directory -ErrorAction SilentlyContinue |
|
|
Where-Object { Test-Path -LiteralPath (Join-Path $_.FullName 'bin\pg_dump.exe') } |
|
|
Sort-Object { [int]($_.Name -replace '\D', '') } -Descending |
|
|
Select-Object -First 1
|
|
if (-not $kandidat) { throw "PostgreSQL-Programme nicht gefunden unter $basis. Pfad mit -PgBin angeben." }
|
|
return (Join-Path $kandidat.FullName 'bin')
|
|
}
|
|
|
|
# Fuehrt ein Node-Skript im Anwendungsverzeichnis aus, mit beiden
|
|
# Konfigurationsdateien. Bricht ab, wenn es scheitert.
|
|
function Invoke-NodeSkript {
|
|
param(
|
|
[Parameter(Mandatory = $true)][string]$AppVerzeichnis,
|
|
[Parameter(Mandatory = $true)][string]$Ziel,
|
|
[Parameter(Mandatory = $true)][string]$Skript
|
|
)
|
|
$node = Get-NodePfad
|
|
Push-Location -LiteralPath $AppVerzeichnis
|
|
try {
|
|
& $node "--env-file=$Ziel\app.env" "--env-file=$Ziel\verwaltung.env" $Skript
|
|
if ($LASTEXITCODE -ne 0) { throw "$Skript ist fehlgeschlagen (Exit-Code $LASTEXITCODE)." }
|
|
} finally {
|
|
Pop-Location
|
|
}
|
|
}
|
|
|
|
function Invoke-Icacls {
|
|
param([string[]]$Argumente)
|
|
# 2>&1 auf ein natives Programm erzeugt in PowerShell 5.1 Fehlerobjekte, und
|
|
# mit 'Stop' bricht schon die erste Zeile auf stderr alles ab -- deshalb hier
|
|
# lokal 'Continue' und die Entscheidung allein am Exit-Code.
|
|
$ErrorActionPreference = 'Continue'
|
|
$ausgabe = & icacls.exe @Argumente 2>&1
|
|
if ($LASTEXITCODE -ne 0) { throw "icacls $($Argumente -join ' ') ist fehlgeschlagen: $ausgabe" }
|
|
}
|
|
|
|
# Wartet, bis die Anwendung auf /login mit 200 antwortet. Der Weg fuehrt ueber
|
|
# die lokale Bindung des IIS (127.0.0.1:PORT), nicht direkt zu Node.
|
|
function Wait-Gesund {
|
|
param([int]$Port, [int]$Sekunden = 90)
|
|
$bis = (Get-Date).AddSeconds($Sekunden)
|
|
while ((Get-Date) -lt $bis) {
|
|
try {
|
|
$antwort = Invoke-WebRequest -Uri "http://127.0.0.1:$Port/login" -UseBasicParsing -TimeoutSec 5 -MaximumRedirection 0
|
|
if ($antwort.StatusCode -eq 200) { return $true }
|
|
} catch {
|
|
# Fehler sind hier der Normalfall: der Dienst startet noch.
|
|
}
|
|
# Die Pause steht ausserhalb des catch. Stand sie nur darin, drehte eine
|
|
# Antwort, die zwar durchkommt aber nicht 200 ist, neunzig Sekunden lang
|
|
# eine Schleife ohne Pause -- gegen einen Dienst, der gerade hochfaehrt.
|
|
Start-Sleep -Seconds 3
|
|
}
|
|
return $false
|
|
}
|
|
|
|
function Copy-Verzeichnis {
|
|
param([string]$Quelle, [string]$Ziel, [switch]$Spiegeln)
|
|
# robocopy statt Copy-Item: kommt mit langen Pfaden in node_modules zurecht.
|
|
# /MIR loescht im Ziel, was in der Quelle fehlt; ohne nur hinzufuegen.
|
|
$modus = '/E'
|
|
if ($Spiegeln) { $modus = '/MIR' }
|
|
& robocopy.exe $Quelle $Ziel $modus /NFL /NDL /NJH /NJS /NP /R:2 /W:2 | Out-Null
|
|
# robocopy: 0-7 heisst Erfolg (mit oder ohne kopierte Dateien), ab 8 Fehler.
|
|
if ($LASTEXITCODE -ge 8) { throw "Kopieren von $Quelle nach $Ziel ist fehlgeschlagen (robocopy $LASTEXITCODE)." }
|
|
$global:LASTEXITCODE = 0
|
|
}
|
|
|
|
# -- IIS ----------------------------------------------------------------
|
|
|
|
# Das Konto, unter dem der Anwendungspool und damit Node laeuft: ohne eigene
|
|
# Vorgabe das virtuelle Konto "IIS AppPool\AlpenwerkHR", sonst das in
|
|
# installieren.ps1 mit -Konto angegebene.
|
|
function Get-PoolKonto {
|
|
Import-Module WebAdministration
|
|
$modell = Get-ItemProperty "IIS:\AppPools\$PoolName" -Name processModel
|
|
if ($modell.identityType -eq 'SpecificUser') { return $modell.userName }
|
|
return "IIS AppPool\$PoolName"
|
|
}
|
|
|
|
# Lesen fuer die Anwendung und app.env, Schreiben nur in logs\ und in den
|
|
# Cache von Next.js. Gilt fuer das Konto des Pools und fuer LocalService, unter
|
|
# dem der naechtliche Lauf app.env liest und ins Protokoll schreibt.
|
|
function Set-AppRechte {
|
|
param([Parameter(Mandatory = $true)][string]$Ziel)
|
|
$konto = Get-PoolKonto
|
|
foreach ($k in @($konto, $SidLocalService)) {
|
|
Invoke-Icacls @($Ziel, '/grant', "${k}:(OI)(CI)RX")
|
|
Invoke-Icacls @("$Ziel\logs", '/grant', "${k}:(OI)(CI)M")
|
|
}
|
|
$cache = "$Ziel\app\.next\cache"
|
|
New-Item -ItemType Directory -Force -Path $cache | Out-Null
|
|
Invoke-Icacls @($cache, '/grant', "${konto}:(OI)(CI)M")
|
|
}
|
|
|
|
# Schreibt C:\AlpenwerkHR\iis\web.config aus der Vorlage: Pfad zu node.exe,
|
|
# Installationsverzeichnis und die Proxy-Zeilen aus app.env.
|
|
#
|
|
# Die Proxy-Einstellung (NODE_USE_ENV_PROXY, HTTPS_PROXY, NO_PROXY) liest Node
|
|
# beim Start, bevor --env-file wirkt. Sie muss deshalb als Umgebung des
|
|
# Prozesses gesetzt sein; gepflegt wird sie trotzdem nur in app.env.
|
|
function Write-AlpenwerkWebConfig {
|
|
param(
|
|
[Parameter(Mandatory = $true)][string]$Ziel,
|
|
[Parameter(Mandatory = $true)][string]$Vorlage
|
|
)
|
|
$app = Read-EnvDatei "$Ziel\app.env"
|
|
$zeilen = @()
|
|
foreach ($name in @('NODE_USE_ENV_PROXY', 'HTTPS_PROXY', 'HTTP_PROXY', 'NO_PROXY')) {
|
|
if ($app[$name]) {
|
|
$wert = [System.Security.SecurityElement]::Escape($app[$name])
|
|
$zeilen += " <environmentVariable name=`"$name`" value=`"$wert`" />"
|
|
}
|
|
}
|
|
$text = Get-Content -LiteralPath $Vorlage -Raw -Encoding UTF8
|
|
$text = $text.Replace('__NODE__', [System.Security.SecurityElement]::Escape((Get-NodePfad)))
|
|
$text = $text.Replace('__ZIEL__', [System.Security.SecurityElement]::Escape($Ziel))
|
|
$text = $text.Replace('__UMGEBUNG__', ($zeilen -join "`r`n"))
|
|
New-Item -ItemType Directory -Force -Path "$Ziel\iis" | Out-Null
|
|
[System.IO.File]::WriteAllText("$Ziel\iis\web.config", $text, (New-Object System.Text.UTF8Encoding $false))
|
|
}
|
|
|
|
# Haelt den Pool an und wartet, bis auch Node beendet ist. Erst dann sind die
|
|
# Dateien in app\ frei und lassen sich tauschen.
|
|
function Stop-AlpenwerkPool {
|
|
param([Parameter(Mandatory = $true)][string]$Ziel)
|
|
Import-Module WebAdministration
|
|
if (-not (Test-Path "IIS:\AppPools\$PoolName")) { return }
|
|
if ((Get-WebAppPoolState -Name $PoolName).Value -ne 'Stopped') { Stop-WebAppPool -Name $PoolName }
|
|
$bis = (Get-Date).AddSeconds(60)
|
|
while ((Get-Date) -lt $bis) {
|
|
$laeuft = @(Get-CimInstance Win32_Process -Filter "Name='node.exe'" |
|
|
Where-Object { $_.CommandLine -like "*$Ziel\app\server.js*" })
|
|
if ((Get-WebAppPoolState -Name $PoolName).Value -eq 'Stopped' -and $laeuft.Count -eq 0) { return }
|
|
Start-Sleep -Seconds 2
|
|
}
|
|
throw "Der Anwendungspool $PoolName laesst sich nicht anhalten."
|
|
}
|
|
|
|
function Start-AlpenwerkPool {
|
|
Import-Module WebAdministration
|
|
if ((Get-WebAppPoolState -Name $PoolName).Value -ne 'Started') { Start-WebAppPool -Name $PoolName }
|
|
}
|
|
|
|
# Das gueltige Zertifikat fuer den Hostnamen aus Cert:\LocalMachine\My, mit
|
|
# privatem Schluessel, das am laengsten gilt. Ein Zertifikat aus der
|
|
# automatischen Registrierung (Auto-Enrollment) liegt genau dort; eine Datei
|
|
# wird nie eingespielt.
|
|
function Find-Zertifikat {
|
|
param([Parameter(Mandatory = $true)][string]$HostName, [string]$Fingerabdruck)
|
|
if ($Fingerabdruck) {
|
|
$Fingerabdruck = $Fingerabdruck -replace '\s', ''
|
|
$z = Get-Item -LiteralPath "Cert:\LocalMachine\My\$Fingerabdruck" -ErrorAction SilentlyContinue
|
|
if (-not $z) { throw "Zertifikat $Fingerabdruck nicht in Cert:\LocalMachine\My gefunden." }
|
|
return $z
|
|
}
|
|
$jetzt = Get-Date
|
|
$z = Get-ChildItem Cert:\LocalMachine\My |
|
|
Where-Object { $_.HasPrivateKey -and $_.NotBefore -le $jetzt -and $_.NotAfter -gt $jetzt -and
|
|
(@($_.DnsNameList | ForEach-Object { $_.Unicode }) -contains $HostName) } |
|
|
Sort-Object NotAfter -Descending | Select-Object -First 1
|
|
if (-not $z) {
|
|
throw "Kein gueltiges Zertifikat fuer $HostName in Cert:\LocalMachine\My. Der Name muss als alternativer Antragstellername (SAN) im Zertifikat stehen. Fingerabdruck sonst mit -Zertifikat angeben."
|
|
}
|
|
return $z
|
|
}
|
|
|
|
# -- Datenbank ----------------------------------------------------------
|
|
|
|
function Invoke-Psql {
|
|
param(
|
|
[Parameter(Mandatory = $true)][string]$PgBin,
|
|
[Parameter(Mandatory = $true)][string]$Url,
|
|
[Parameter(Mandatory = $true)][string]$Sql
|
|
)
|
|
$env:PGCLIENTENCODING = 'UTF8'
|
|
$ErrorActionPreference = 'Continue'
|
|
$ausgabe = & (Join-Path $PgBin 'psql.exe') "--dbname=$Url" -X -A -t -v ON_ERROR_STOP=1 -c $Sql 2>&1
|
|
$code = $LASTEXITCODE
|
|
$ErrorActionPreference = 'Stop'
|
|
if ($code -ne 0) { throw "psql ist fehlgeschlagen: $ausgabe" }
|
|
return @($ausgabe | ForEach-Object { "$_".Trim() } | Where-Object { $_ -ne '' })
|
|
}
|
|
|
|
# Die Versionen aller eingespielten Migrationen, aufsteigend.
|
|
function Get-Migrationen {
|
|
param([Parameter(Mandatory = $true)][string]$PgBin, [Parameter(Mandatory = $true)][string]$Url)
|
|
return Invoke-Psql -PgBin $PgBin -Url $Url -Sql 'select version from migrationen.schema_migrations order by version'
|
|
}
|
|
|
|
# Spielt eine Sicherung als ganze Datenbank zurueck: Die Datenbank wird
|
|
# geloescht und aus der Sicherung neu angelegt.
|
|
#
|
|
# Ein Einspielen in die bestehende Datenbank genuegt nicht. Tabellen und
|
|
# Funktionen, die erst nach der Sicherung entstanden sind, blieben sonst
|
|
# stehen, waehrend die Buchfuehrung der Migrationen auf den alten Stand
|
|
# zurueckgeht -- und das naechste Update scheiterte an genau diesen Resten.
|
|
function Restore-Sicherung {
|
|
param(
|
|
[Parameter(Mandatory = $true)][string]$PgBin,
|
|
[Parameter(Mandatory = $true)][string]$Url,
|
|
[Parameter(Mandatory = $true)][string]$Datei
|
|
)
|
|
if (-not (Test-Path -LiteralPath $Datei)) { throw "Sicherung nicht gefunden: $Datei" }
|
|
$uri = [Uri]$Url
|
|
$datenbank = [Uri]::UnescapeDataString($uri.AbsolutePath.TrimStart('/'))
|
|
if (-not $datenbank) { throw 'MIGRATE_DATABASE_URL nennt keine Datenbank.' }
|
|
# Verbindung zur Wartungsdatenbank: dieselbe Adresse, nur mit "postgres"
|
|
# statt des Datenbanknamens.
|
|
$wartung = $Url -replace '/[^/?]+(\?|$)', '/postgres$1'
|
|
$name = $datenbank.Replace("'", "''")
|
|
Invoke-Psql -PgBin $PgBin -Url $wartung -Sql "select pg_terminate_backend(pid) from pg_stat_activity where datname = '$name' and pid <> pg_backend_pid()" | Out-Null
|
|
$ErrorActionPreference = 'Continue'
|
|
$ausgabe = & (Join-Path $PgBin 'pg_restore.exe') --clean --if-exists --create --exit-on-error "--dbname=$wartung" $Datei 2>&1
|
|
$code = $LASTEXITCODE
|
|
$ErrorActionPreference = 'Stop'
|
|
if ($code -ne 0) { throw "pg_restore ist fehlgeschlagen: $ausgabe" }
|
|
}
|