param( [Parameter(Mandatory = $true)] [string]$EnvironmentFile ) $ErrorActionPreference = 'Stop' $envPath = [System.IO.Path]::GetFullPath($EnvironmentFile) if (-not (Test-Path -LiteralPath $envPath -PathType Leaf)) { throw "Environment file not found" } $bytes = New-Object byte[] 48 $generator = [System.Security.Cryptography.RandomNumberGenerator]::Create() try { $generator.GetBytes($bytes) } finally { $generator.Dispose() } $newSecret = [Convert]::ToBase64String($bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_') $found = $false $updated = foreach ($line in [System.IO.File]::ReadAllLines($envPath)) { if ($line -match '^JWT_SECRET=') { $found = $true "JWT_SECRET=$newSecret" } else { $line } } if (-not $found) { $updated += "JWT_SECRET=$newSecret" } $temporaryPath = "$envPath.rotate.tmp" $utf8WithoutBom = New-Object System.Text.UTF8Encoding($false) [System.IO.File]::WriteAllLines($temporaryPath, $updated, $utf8WithoutBom) Move-Item -LiteralPath $temporaryPath -Destination $envPath -Force Write-Output 'JWT_SECRET rotated'