<# .SYNOPSIS Lab capture: talk to the lab Sunshine's local API (docs/LAB_CAPTURE.md sections 2, 3, 5). Not elevated. .DESCRIPTION Every call goes to https://127.0.0.2:47990 with Basic auth built in memory, no Origin/Referer header (the documented non-browser path), TLS pinned to the lab certificate in keys\ byte for byte. Credentials come only from DPAPI files in secrets\; they are never printed, logged or put on a command line. -Action Rotate throwaway credentials (from lab-install.ps1) -> fresh lab credentials; deletes the throwaway -Action Status lists paired clients and apps (names only) -Action Pin submits the PIN Moonlight shows: -PinFile (the file is deleted after reading), optional -PairingId, -ClientName (default "DomiStream lab Moonlight") -Action Logs saves GET /api/logs to captures\sunshine.log (not printed: it may hold secrets) -Action Cleanup unpair all clients, drop the lab cert/key from the config (bind_address stays 127.0.0.2), restart Sunshine #> [CmdletBinding()] param( [Parameter(Mandatory = $true)] [ValidateSet('Rotate', 'Status', 'Pin', 'Logs', 'Cleanup')] [string] $Action, [string] $LabRoot = 'E:\build\play-remotely\lab', [string] $PinFile, [string] $PairingId, [string] $ClientName = 'DomiStream lab Moonlight' ) Set-StrictMode -Version 2.0 $ErrorActionPreference = 'Stop' $BaseUrl = 'https://127.0.0.2:47990' $keys = Join-Path $LabRoot 'keys' $secrets = Join-Path $LabRoot 'secrets' $captures = Join-Path $LabRoot 'captures' $throwawayFile = Join-Path $secrets 'sunshine-throwaway.cred' $labFile = Join-Path $secrets 'sunshine-lab.cred' $certFile = Join-Path $keys 'sunshine-lab-cert.pem' function Fail([string] $Why) { Write-Host "lab-api: STOPPED: $Why" exit 1 } # --- TLS pinning: accept exactly the lab certificate ------------------------------------------------------------- if (-not (Test-Path -LiteralPath $certFile)) { Fail "lab certificate not found: $certFile" } $pem = Get-Content -LiteralPath $certFile -Raw $m = [regex]::Match($pem, '-----BEGIN CERTIFICATE-----([A-Za-z0-9+/=\s]+)-----END CERTIFICATE-----') if (-not $m.Success) { Fail 'lab certificate is not PEM' } $pinnedDer = [Convert]::FromBase64String(($m.Groups[1].Value -replace '\s', '')) if (-not ('DomiLabPin' -as [type])) { Add-Type -TypeDefinition @' using System; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; public static class DomiLabPin { public static byte[] Pinned; public static bool Check(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors) { if (cert == null || Pinned == null) return false; byte[] raw = cert.GetRawCertData(); if (raw.Length != Pinned.Length) return false; int diff = 0; for (int i = 0; i < raw.Length; i++) diff |= raw[i] ^ Pinned[i]; return diff == 0; } public static void Install() { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(Check); } } '@ } [DomiLabPin]::Pinned = $pinnedDer [DomiLabPin]::Install() [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 # --- Credentials ------------------------------------------------------------------------------------------------- function Read-Cred([string] $File) { if (-not (Test-Path -LiteralPath $File)) { Fail "credentials file not found: $File" } $j = Get-Content -LiteralPath $File -Raw | ConvertFrom-Json $u = New-Object Management.Automation.PSCredential('x', ($j.user | ConvertTo-SecureString)) $p = New-Object Management.Automation.PSCredential('x', ($j.password | ConvertTo-SecureString)) return @{ User = $u.GetNetworkCredential().Password; Password = $p.GetNetworkCredential().Password } } function Save-Cred([string] $File, [string] $User, [string] $Password) { @{ user = (ConvertTo-SecureString -String $User -AsPlainText -Force | ConvertFrom-SecureString) password = (ConvertTo-SecureString -String $Password -AsPlainText -Force | ConvertFrom-SecureString) } | ConvertTo-Json | Set-Content -LiteralPath $File -Encoding ASCII } function New-Secret { $bytes = New-Object byte[] 32 $rng = [Security.Cryptography.RandomNumberGenerator]::Create() $rng.GetBytes($bytes) $rng.Dispose() return ([Convert]::ToBase64String($bytes)).TrimEnd('=').Replace('+', '-').Replace('/', '_') } # --- One API call ------------------------------------------------------------------------------------------------ function Invoke-Sunshine([hashtable] $Cred, [string] $Method, [string] $Path, $Body, [string] $OutFile) { $pair = [Text.Encoding]::UTF8.GetBytes($Cred.User + ':' + $Cred.Password) $headers = @{ Authorization = 'Basic ' + [Convert]::ToBase64String($pair) } $req = @{ Uri = $BaseUrl + $Path; Method = $Method; Headers = $headers; UseBasicParsing = $true; TimeoutSec = 30 } if ($null -ne $Body) { $req.Body = ($Body | ConvertTo-Json -Depth 5 -Compress) $req.ContentType = 'application/json' } try { if ($OutFile) { Invoke-WebRequest @req -OutFile $OutFile | Out-Null return $null } return Invoke-RestMethod @req } catch { # The message names the call only; the request, which holds the credentials, is never echoed. Fail "$Method $Path failed: $($_.Exception.GetType().Name)" } } # --- Actions ----------------------------------------------------------------------------------------------------- switch ($Action) { 'Rotate' { $old = Read-Cred $throwawayFile $newUser = 'lab' + (New-Secret).Substring(0, 12) $newPass = New-Secret $null = Invoke-Sunshine $old 'POST' '/api/password' @{ currentUsername = $old.User currentPassword = $old.Password newUsername = $newUser newPassword = $newPass confirmNewPassword = $newPass } Save-Cred $labFile $newUser $newPass # Prove the new pair works before forgetting the old one. $null = Invoke-Sunshine (Read-Cred $labFile) 'GET' '/api/clients/list' $null Remove-Item -LiteralPath $throwawayFile -Force Write-Host 'lab-api: credentials rotated; throwaway deleted' } 'Status' { $c = Read-Cred $labFile $clients = Invoke-Sunshine $c 'GET' '/api/clients/list' $null $apps = Invoke-Sunshine $c 'GET' '/api/apps' $null Write-Host ('lab-api: clients: ' + (($clients | ConvertTo-Json -Depth 4 -Compress))) Write-Host ('lab-api: apps: ' + ((@($apps.apps) | ForEach-Object { $_.name }) -join ', ')) } 'Pin' { if (-not $PinFile) { Fail '-PinFile is required' } $pin = (Get-Content -LiteralPath $PinFile -Raw).Trim() Remove-Item -LiteralPath $PinFile -Force if ($pin -notmatch '^[0-9]{4}$') { Fail 'the PIN file must hold exactly 4 digits' } $body = @{ pin = $pin; name = $ClientName } if ($PairingId) { $body.pairing_id = $PairingId } $r = Invoke-Sunshine (Read-Cred $labFile) 'POST' '/api/pin' $body Write-Host ('lab-api: PIN submitted, answer: ' + ($r | ConvertTo-Json -Compress)) } 'Logs' { $out = Join-Path $captures 'sunshine.log' $null = Invoke-Sunshine (Read-Cred $labFile) 'GET' '/api/logs' $null $out Write-Host "lab-api: Sunshine log saved to $out (not shown: it may hold secrets)" } 'Cleanup' { $c = Read-Cred $labFile $null = Invoke-Sunshine $c 'POST' '/api/clients/unpair-all' $null # Same loopback-only config as lab-install.ps1, without the lab cert/key, so Sunshine makes a fresh pair. $null = Invoke-Sunshine $c 'POST' '/api/config' @{ bind_address = '127.0.0.2' address_family = 'ipv4' origin_web_ui_allowed = 'pc' upnp = 'disabled' external_ip = '127.0.0.2' sunshine_name = 'DomiStream-lab' lan_encryption_mode = '1' wan_encryption_mode = '1' } $null = Invoke-Sunshine $c 'POST' '/api/restart' $null Write-Host 'lab-api: unpaired all clients, lab cert/key dropped from the config, Sunshine restarting' Write-Host 'lab-api: next: delete keys\sunshine-lab-*.pem and keys\moonlight-lab-*.pem once Sunshine is back' } } exit 0