<# .SYNOPSIS 8D Interactive / Station 1.0 / PC2 RTX 5070 / LAB / v0.1 .DESCRIPTION Narrow Windows agent. Pair once, send heartbeat, query read-only station config. Does NOT start/stop TouchPlayer, execute cloud commands, touch TOE, change firewall, schedule startup, write photos, change GPU settings or download content. NOT INSTALLED OR RUN; require distinct approval before execution on PC2. SERVER MUST BE DEPLOYED AND VERIFIED before attempting Pair or Heartbeat. .EXAMPLE .\8d-station-agent-v0.1.ps1 -Mode Pair .\8d-station-agent-v0.1.ps1 -Mode HeartbeatOnce .\8d-station-agent-v0.1.ps1 -Mode Config .\8d-station-agent-v0.1.ps1 -Mode Run #> [CmdletBinding()] param( [ValidateSet('Pair','HeartbeatOnce','Run','Config')] [string]$Mode = 'HeartbeatOnce', [ValidateRange(20,300)] [int]$IntervalSeconds = 30 ) Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' # Fixed, allowlisted staging URL. Do not accept endpoint from CLI or the cloud. $ApiBase = 'https://8d-interactive-analytics-staging.8d-qr.workers.dev' $AgentVersion = 's1-agent-v0.1' $Root = Join-Path $env:LOCALAPPDATA '8DInteractive\Station1' $SecretPath = Join-Path $Root 'device-token.dpapi' function Convert-SecureToPlain([securestring]$secure) { $ptr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure) try { return [Runtime.InteropServices.Marshal]::PtrToStringBSTR($ptr) } finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ptr) } } function Send-StationRequest([string]$path, [string]$verb, [object]$body, [string]$secret) { if(-not $path.StartsWith('/api/stations/')) { throw 'unexpected_api_path' } $headers = @{'Accept'='application/json'} if(-not [string]::IsNullOrEmpty($secret)) { $headers['Authorization']='Station '+$secret } $args = @{ Uri = $ApiBase + $path Method = $verb Headers = $headers TimeoutSec = 15 MaximumRedirection = 0 ErrorAction = 'Stop' } if($null -ne $body) { $args['Body'] = ConvertTo-Json -InputObject $body -Depth 5 -Compress $args['ContentType'] = 'application/json; charset=utf-8' } return Invoke-RestMethod @args } function Read-LocalDeviceToken { if(-not (Test-Path -LiteralPath $SecretPath -PathType Leaf)) { throw 'not_paired' } # DPAPI bound to this Windows user and machine; no token in command line or Drive. $blob = Get-Content -LiteralPath $SecretPath -Raw -ErrorAction Stop $secure = ConvertTo-SecureString -String $blob -ErrorAction Stop return Convert-SecureToPlain $secure } function Pair-Once { if(Test-Path -LiteralPath $SecretPath) { throw 'device_already_paired_local' } $inputCode = Read-Host -Prompt 'Código de vinculación mostrado por Master (no se registra)' -AsSecureString $code = Convert-SecureToPlain $inputCode if($code -notmatch '^[A-Za-z0-9_-]{22}$') { throw 'invalid_pairing_code_format' } $resp = Send-StationRequest '/api/stations/pair' 'Post' @{ code=$code; label='PC2 RTX 5070'; agent_version=$AgentVersion } $null $code = $null if(-not $resp.ok -or -not $resp.device_token -or -not $resp.device_id) { throw 'pairing_response_invalid' } $secure = ConvertTo-SecureString -String ([string]$resp.device_token) -AsPlainText -Force if(-not (Test-Path -LiteralPath $Root)) { New-Item -ItemType Directory -Path $Root -Force | Out-Null } $encrypted = ConvertFrom-SecureString -SecureString $secure # No cleartext token is ever written to disk. The operator must review folder # ACLs before first run; the actual DPAPI blob remains Windows-user-bound. [IO.File]::WriteAllText($SecretPath,$encrypted,[Text.Encoding]::UTF8) Write-Output ('PAIRING OK · Station: '+[string]$resp.station_code+' · Device: '+[string]$resp.device_id) Write-Output 'Credencial cifrada DPAPI en el perfil de usuario. No compartir este archivo.' } function Send-HeartbeatOnce { $token = Read-LocalDeviceToken # This is a PROCESS CHECK, not evidence of game health or measured render FPS. $player = @(Get-Process -Name 'TouchPlayer' -ErrorAction SilentlyContinue).Count -gt 0 $body = @{ agent_version=$AgentVersion player_running=[bool]$player camera_status='unverified' # Never claim camera healthy without an independent check. reported_fps=$null # Never fabricate a number. } $resp = Send-StationRequest '/api/stations/heartbeat' 'Post' $body $token $token = $null if(-not $resp.ok) { throw 'heartbeat_rejected' } Write-Output ('Heartbeat recibido por servidor: '+[string]$resp.server_received_at+ ' · TouchPlayer detectado: '+[string]$player+' · cámara/FPS: NO VERIFICADOS') } function Read-Config { $token = Read-LocalDeviceToken $resp = Send-StationRequest '/api/stations/config' 'Get' $null $token $token = $null if(-not $resp.ok -or $resp.mode -ne 'inventory_only') { throw 'config_invalid' } Write-Output ('Station: '+[string]$resp.station_code+' · Experiencias: '+($resp.experiences -join ', ')) Write-Output 'Sin comandos remotos; el TOE y sus assets no fueron modificados.' } try { switch($Mode) { 'Pair' { Pair-Once } 'HeartbeatOnce' { Send-HeartbeatOnce } 'Config' { Read-Config } 'Run' { Write-Output 'Modo manual de heartbeat. Ctrl+C para detener. No crea tareas programadas.' while($true) { try { Send-HeartbeatOnce } catch { Write-Warning 'Heartbeat falló; la web mostrará OFFLINE cuando venza la señal.' } Start-Sleep -Seconds $IntervalSeconds } } } } catch { # Do not print Exception.ToString(): could contain sensitive request internals. Write-Error ('No completado: '+[string]$_.Exception.Message.Split([Environment]::NewLine)[0]) exit 1 }