[CmdletBinding()] param() $ErrorActionPreference = 'Stop' $repositoryRoot = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..')) $protectedDataAssembly = Join-Path $repositoryRoot 'artifacts\pilot-terminal\System.Security.Cryptography.ProtectedData.dll' if (-not (Test-Path -LiteralPath $protectedDataAssembly -PathType Leaf)) { throw "DPAPI assembly is missing: $protectedDataAssembly" } Add-Type -Path $protectedDataAssembly $statePath = Join-Path $env:LOCALAPPDATA 'Krona\StaffTerminal\terminal-state.dat' $pilotDirectory = Join-Path $env:LOCALAPPDATA 'KronaStaff\pilot' $tokenPath = Join-Path $pilotDirectory 'terminal.token' $certificatePath = Join-Path $pilotDirectory 'certificate.sha256' foreach ($requiredPath in @($statePath, $tokenPath, $certificatePath)) { if (-not (Test-Path -LiteralPath $requiredPath -PathType Leaf)) { throw "Required pilot file is missing: $requiredPath" } } $entropy = [System.Text.Encoding]::UTF8.GetBytes('Krona.Staff.Terminal.v1') $encrypted = [System.IO.File]::ReadAllBytes($statePath) $clear = [System.Security.Cryptography.ProtectedData]::Unprotect( $encrypted, $entropy, [System.Security.Cryptography.DataProtectionScope]::CurrentUser) $json = [System.Text.Encoding]::UTF8.GetString($clear) $state = $json | ConvertFrom-Json if ($null -eq $state.Settings) { throw 'Terminal state does not contain Settings.' } $state.Settings | Add-Member -NotePropertyName StaffServerUrl -NotePropertyValue 'https://192.168.1.81:8453' -Force $state.Settings | Add-Member -NotePropertyName StaffServerToken -NotePropertyValue ((Get-Content -LiteralPath $tokenPath -Raw).Trim()) -Force $state.Settings | Add-Member -NotePropertyName StaffServerCertificateSha256 -NotePropertyValue ((Get-Content -LiteralPath $certificatePath -Raw).Trim()) -Force $updatedJson = $state | ConvertTo-Json -Depth 30 $updatedClear = [System.Text.Encoding]::UTF8.GetBytes($updatedJson) $updatedEncrypted = [System.Security.Cryptography.ProtectedData]::Protect( $updatedClear, $entropy, [System.Security.Cryptography.DataProtectionScope]::CurrentUser) $backupPath = "$statePath.pilot-backup" if (-not (Test-Path -LiteralPath $backupPath)) { Copy-Item -LiteralPath $statePath -Destination $backupPath } $temporaryPath = "$statePath.pilot-tmp" [System.IO.File]::WriteAllBytes($temporaryPath, $updatedEncrypted) Move-Item -LiteralPath $temporaryPath -Destination $statePath -Force Write-Output 'Pilot server settings were imported into the DPAPI-protected terminal state.'