<# .SYNOPSIS 8D Interactive / Station Agent v0.2 / PC2 RTX 5070 / Windows / STAGING. .DESCRIPTION Solo permite Pair, Transfer, HeartbeatOnce, Config o Run. No inicia ni controla TouchDesigner/TouchPlayer, ni cambia firewall, red, servicios o tareas programadas. Transfer requiere el token DPAPI anterior en este mismo usuario Windows, un código temporal del Máster y que TouchDesigner y TouchPlayer estén cerrados. No compartir el código ni ningún token. No ejecutar sin validación local. .EXAMPLE .\8d-station-agent-v0.2.ps1 -Mode Transfer .EXAMPLE .\8d-station-agent-v0.2.ps1 -Mode Config #> [CmdletBinding()] param( [ValidateSet('Pair','Transfer','HeartbeatOnce','Config','Run')] [string]$Mode='HeartbeatOnce', [ValidateRange(20,300)] [int]$IntervalSeconds=30 ) Set-StrictMode -Version Latest $ErrorActionPreference='Stop' # Fixed exact endpoint. Never use dynamic URLs or remote commands. $ApiBase='https://8d-interactive-analytics-staging.8d-qr.workers.dev' $AgentVersion='s1-agent-v0.2' $Root=Join-Path $env:LOCALAPPDATA '8DInteractive\Station1' $SecretPath=Join-Path $Root 'device-token.dpapi' function SecureToPlain([securestring]$s){ $ptr=[Runtime.InteropServices.Marshal]::SecureStringToBSTR($s) try { return [Runtime.InteropServices.Marshal]::PtrToStringBSTR($ptr) } finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ptr) } } function Api([string]$path,[string]$verb,[object]$body,[string]$secret){ if($path -notmatch '^/api/stations/(pair|transfer|heartbeat|config)$'){throw 'unexpected_api_path'} $headers=@{Accept='application/json'} if(-not [string]::IsNullOrEmpty($secret)){$headers.Authorization='Station '+$secret} $opts=@{Uri=$ApiBase+$path;Method=$verb;Headers=$headers;TimeoutSec=15;MaximumRedirection=0;ErrorAction='Stop'} if($null -ne $body){$opts.Body=ConvertTo-Json -InputObject $body -Depth 4 -Compress;$opts.ContentType='application/json; charset=utf-8'} try{return Invoke-RestMethod @opts} catch{throw 'station_api_request_failed'} } function Read-DeviceToken { if(-not(Test-Path -LiteralPath $SecretPath -PathType Leaf)){throw 'not_paired_on_this_windows_profile'} $blob=[IO.File]::ReadAllText($SecretPath,[Text.Encoding]::UTF8) return SecureToPlain (ConvertTo-SecureString -String $blob -ErrorAction Stop) } function Save-NewToken([string]$token,[bool]$replace){ if($token -notmatch '^[A-Za-z0-9_-]{40,70}$'){throw 'invalid_server_token'} if(-not(Test-Path -LiteralPath $Root -PathType Container)){ New-Item -Path $Root -ItemType Directory -Force | Out-Null } $newEncrypted=ConvertFrom-SecureString -SecureString (ConvertTo-SecureString -String $token -AsPlainText -Force) $tmp=Join-Path $Root ('credential-'+[guid]::NewGuid().ToString('N')+'.tmp') $backup=Join-Path $Root 'device-token.previous-revoked.dpapi' try{ [IO.File]::WriteAllText($tmp,$newEncrypted,(New-Object System.Text.UTF8Encoding($false))) if($replace){ if(-not(Test-Path -LiteralPath $SecretPath -PathType Leaf)){throw 'original_token_missing'} # Same volume atomic Windows replace. The backup contains only the REVOKED, DPAPI-protected token. [IO.File]::Replace($tmp,$SecretPath,$backup,$true) }else{ if(Test-Path -LiteralPath $SecretPath){throw 'device_already_paired_local'} [IO.File]::Move($tmp,$SecretPath) } $check=Read-DeviceToken if($check -cne $token){throw 'dpapi_roundtrip_failed'} $check=$null if(Test-Path -LiteralPath $backup){Remove-Item -LiteralPath $backup -Force} }finally{ if(Test-Path -LiteralPath $tmp){Remove-Item -LiteralPath $tmp -Force} } } function Read-OneTimeCode { $s=Read-Host -Prompt 'Código temporal de 8D Máster (no se registra)' -AsSecureString $c=SecureToPlain $s if($c -notmatch '^[A-Za-z0-9_-]{22}$'){throw 'invalid_code_format'} return $c } function Pair-Once { if(Test-Path -LiteralPath $SecretPath){throw 'device_already_paired_local'} $code=Read-OneTimeCode $resp=Api '/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 'invalid_pairing_response'} Save-NewToken ([string]$resp.device_token) $false Write-Output ('PAIRING OK · Estación '+[string]$resp.station_code+' · Dispositivo '+[string]$resp.device_id) } function Transfer-Controlled { if(-not(Test-Path -LiteralPath $SecretPath)){throw 'previous_pairing_required'} # No remote start/stop. The human must first close TouchDesigner/TouchPlayer. $processes=@(Get-Process -Name 'TouchPlayer','TouchDesigner' -ErrorAction SilentlyContinue) if($processes.Count -gt 0){throw 'close_touchdesigner_and_touchplayer_before_transfer'} $old=Read-DeviceToken $code=Read-OneTimeCode Write-Output 'Solicitando el traslado a Cloudflare. No cierres esta ventana hasta ver el resultado.' $resp=Api '/api/stations/transfer' 'POST' @{code=$code;agent_version=$AgentVersion} $old $old=$null;$code=$null if(-not $resp.ok -or -not $resp.device_token -or -not $resp.device_id -or -not $resp.old_device_revoked){throw 'invalid_transfer_response'} try {Save-NewToken ([string]$resp.device_token) $true} catch {throw 'SERVER_TRANSFER_COMPLETED_BUT_LOCAL_CREDENTIAL_FAILED_CONTACT_MASTER'} $resp.device_token=$null $cfg=Api '/api/stations/config' 'GET' $null (Read-DeviceToken) if(-not $cfg.ok -or $cfg.client_id -ne $resp.client_id -or $cfg.station_code -ne $resp.station_code){ throw 'TRANSFER_COMPLETE_SERVER_IDENTITY_REQUIRES_MASTER_CHECK' } Write-Output ('TRANSFERENCIA OK · Cliente '+[string]$cfg.client_id+' · Estación '+[string]$cfg.station_code) Write-Output 'Credencial nueva cifrada con DPAPI. Credencial anterior revocada en servidor.' Write-Output 'No se modificaron TouchDesigner, TouchPlayer, archivos TOE ni hardware.' } function Heartbeat-Once { $token=Read-DeviceToken $player=@(Get-Process -Name 'TouchPlayer' -ErrorAction SilentlyContinue).Count -gt 0 $resp=Api '/api/stations/heartbeat' 'POST' @{ agent_version=$AgentVersion;player_running=[bool]$player;camera_status='unverified';reported_fps=$null } $token $token=$null if(-not $resp.ok){throw 'heartbeat_rejected'} Write-Output ('HEARTBEAT OK · '+[string]$resp.server_received_at+' · Player detectado '+[string]$player+' · FPS/cámara no verificados') } function Read-Config { $resp=Api '/api/stations/config' 'GET' $null (Read-DeviceToken) if(-not $resp.ok -or $resp.mode -ne 'inventory_only'){throw 'config_rejected'} Write-Output ('CONFIG OK · Cliente '+[string]$resp.client_id+' · Estación '+[string]$resp.station_code+ ' · Activación '+[string]$resp.activation_id+' · Experiencias '+($resp.experiences -join ', ')) } try{ switch($Mode){ 'Pair' {Pair-Once} 'Transfer' {Transfer-Controlled} 'HeartbeatOnce' {Heartbeat-Once} 'Config' {Read-Config} 'Run' { Write-Output 'Modo heartbeat manual. Ctrl+C para detener. No instala servicios ni tareas.' while($true){try{Heartbeat-Once}catch{Write-Warning 'Heartbeat falló; el CMS mostrará OFFLINE al vencer la última señal.'};Start-Sleep -Seconds $IntervalSeconds} } } }catch{ # Do not print stack trace, HTTP bodies, tokens or the one-time transfer code. $msg=[string]$_.Exception.Message.Split([Environment]::NewLine)[0] if($msg -notmatch '^[A-Za-z0-9_ .\-]{4,120}$'){$msg='operation_failed_contact_master'} Write-Error ('No completado: '+$msg) exit 1 }