跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

qa-local-browser.ps1

100 行 · 10.3 KB历史下载
1#requires -Version 5.1
2param(
3 [Parameter(Mandatory)][string]$ProfilePath,
4 [Parameter(Mandatory)][string]$CredentialFile,
5 [Parameter(Mandatory)][string]$AssetDirectory,
6 [Parameter(Mandatory)][string]$EvidenceDirectory,
7 [switch]$EditorOnly
8)
9$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue'
10$utf8=[Text.UTF8Encoding]::new($false);[Console]::OutputEncoding=$utf8
11$binding=Get-Content -LiteralPath $ProfilePath -Raw|ConvertFrom-Json;$vm=Get-VM -Id ([guid]$binding.vm_id)
12if($vm.State -ne 'Running' -or @(Get-VMNetworkAdapter -VM $vm).Count -ne 0){throw 'The bound local-only guest must have zero normal NICs.'}
13$credential=Import-Clixml -LiteralPath $CredentialFile
14if(($credential.UserName -split '\\')[-1] -cne 'CageLabSetup'){throw 'The retained QA administrator identity does not match.'}
15$credential=[pscredential]::new('CageLabSetup',$credential.Password)
16$session=New-PSSession -VMId $vm.Id -Credential $credential
17$owned=[Collections.Generic.List[Diagnostics.Process]]::new();$changed=$false;$restored=$false
18function Bridge([string]$Operation){$s=[Diagnostics.ProcessStartInfo]::new();$s.FileName=$binding.relay_executable;$s.Arguments='--relay-profile "'+$ProfilePath+'" '+$Operation;$s.UseShellExecute=$false;$s.CreateNoWindow=$true;$s.RedirectStandardInput=$true;$s.RedirectStandardOutput=$true;$s.RedirectStandardError=$true;$s.StandardOutputEncoding=$utf8;$p=[Diagnostics.Process]::Start($s);$owned.Add($p);$null=$p.StandardError.ReadToEndAsync();return $p}
19function Send($p,$v){$bytes=$utf8.GetBytes((ConvertTo-Json -InputObject $v -Depth 12 -Compress)+"`n");$p.StandardInput.BaseStream.Write($bytes,0,$bytes.Length);$p.StandardInput.BaseStream.Flush()}
20function Read($p){$pending=$p.StandardOutput.ReadLineAsync();if(!$pending.Wait(45000) -or !$pending.Result){throw 'The owned local browser QA channel did not complete.'};return $pending.Result|ConvertFrom-Json}
21function Call([string]$Path,$Payload=@{},[string]$Method='POST'){Send $browser @{method=$Method;path=$Path;input=$Payload};$r=Read $browser;if($r.error){throw $r.error};return $r}
22try {
23 $null=New-Item -ItemType Directory -Path $EvidenceDirectory
24 $setup=Invoke-Command -Session $session -ArgumentList $vm.Id,$binding.gui_user_sid -ScriptBlock {
25 param($expected,$sid)
26 if([guid](Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters').VirtualMachineId -ne $expected){throw 'guest_identity_mismatch'}
27 $guiProfile=(Get-ItemProperty ('HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\'+$sid)).ProfileImagePath
28 $directory=Join-Path $guiProfile ('AppData\Local\Temp\CageLocalBrowserQA-'+[guid]::NewGuid().ToString('N'));$null=New-Item -ItemType Directory -Path $directory
29 $program=Join-Path $env:ProgramFiles ('Cage Guest Bridge\'+$expected);$config=Join-Path $program 'guest-config.json';$backup=Join-Path $program ('guest-config.browser-qa-'+[guid]::NewGuid().ToString('N')+'.backup')
30 if((Get-Item $config).Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'config_link_rejected'}
31 Copy-Item -LiteralPath $config -Destination $backup
32 [pscustomobject]@{Directory=$directory;Program=$program;Config=$config;Backup=$backup;Hash=(Get-FileHash $config -Algorithm SHA256).Hash}
33 }
34 Copy-Item -LiteralPath (Join-Path $AssetDirectory 'windows-browser-deny-proxy.mjs') -Destination (Join-Path $setup.Directory 'deny.mjs') -ToSession $session
35 $terminal=Bridge 'terminal';Send $terminal @{action='open';workspace='home';shell='powershell';cols=160;rows=30};if(!(Read $terminal).ready){throw 'GUI ConPTY unavailable'}
36 $privateHost=@(Get-NetIPAddress -AddressFamily IPv4|Where-Object {$_.IPAddress -notlike '127.*' -and $_.IPAddress -notlike '169.254.*' -and $_.AddressState -eq 'Preferred'})[0].IPAddress
37 if(!$privateHost){throw 'An actual private host address is required for the denied request probe.'}
38 $launch='& '''+(Join-Path $setup.Program 'node.exe')+''' '''+(Join-Path $setup.Directory 'deny.mjs')+''' '''+$setup.Directory+''' '''+$privateHost+''''
39 Send $terminal @{action='input';data=[Convert]::ToBase64String($utf8.GetBytes('powershell.exe -NoProfile -EncodedCommand '+[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($launch))+"`r"))}
40 $output='';while(!$output.Contains('CAGE_QA_DENY_PROXY_READY')){$r=Read $terminal;if($null -ne $r.exit -or $r.error){throw 'The local deny proxy exited.'};if($r.data){$output+=$utf8.GetString([Convert]::FromBase64String($r.data))}}
41 $port=Invoke-Command -Session $session -ArgumentList $setup.Directory -ScriptBlock {param($dir);[int](Get-Content (Join-Path $dir 'deny-proxy-port') -Raw)}
42 $changed=$true;$windowStartUtc=[DateTime]::UtcNow.ToString('o')
43 Invoke-Command -Session $session -ArgumentList $setup.Config,$port -ScriptBlock {
44 param($file,$port);$config=Get-Content -LiteralPath $file -Raw|ConvertFrom-Json
45 $config|Add-Member -NotePropertyName network_mode -NotePropertyValue 'proxy' -Force
46 $config|Add-Member -NotePropertyName browser_proxy -NotePropertyValue ('http://127.0.0.1:'+$port) -Force
47 [IO.File]::WriteAllText($file,($config|ConvertTo-Json -Depth 12),[Text.UTF8Encoding]::new($false))
48 }
49 [Console]::WriteLine('LOCAL_ONLY_QA_CONFIG_STARTED '+$windowStartUtc)
50 $browser=Bridge 'browser';$health=Call '/health' @{} 'GET';$version=Call '/info'
51 $audited=Call '/audit' @{network=$true;timezone='UTC'}
52 if($audited.network.status -ne 503){throw 'The actual browser request did not reach the rejecting local proxy.'}
53 $known=@((Call '/tabs' @{} 'GET').tabs|ForEach-Object {$_.id})
54 $null=Call '/new' @{url='http://example.com/'};$null=Call '/new' @{url=('http://'+$privateHost+'/')}
55 $connectDenied=$false;try{$null=Call '/new' @{url='https://example.com/'}}catch{$connectDenied=$true}
56 $counts=Invoke-Command -Session $session -ArgumentList $setup.Directory -ScriptBlock {param($dir);Get-Content (Join-Path $dir 'deny-proxy-counts.json') -Raw|ConvertFrom-Json}
57 if($counts.public_probe -lt 1 -or $counts.private_probe -lt 1 -or $counts.connect_probe -lt 1 -or !$connectDenied){throw 'The actual Chrome public/private host HTTP and HTTPS CONNECT probes were not all denied.'}
58 foreach($tab in (Call '/tabs' @{} 'GET').tabs){if($tab.id -notin $known){$null=Call '/close' @{id=$tab.id}}}
59 $tests=[ordered]@{local_only=$true;normal_nics=0;browser_version=$version.product;browser_audit_status=$audited.network.status;actual_public_http_denied=$true;actual_private_host_http_denied=$true;actual_https_connect_denied=$true;packet_network_verified=$false}
60 [IO.File]::WriteAllText((Join-Path $EvidenceDirectory 'local-only-network.json'),($tests|ConvertTo-Json),$utf8)
61 if(!$EditorOnly){$perf=Join-Path $EvidenceDirectory 'performance'; & (Join-Path $AssetDirectory 'qa-browser.ps1') -ProfilePath $ProfilePath -CredentialFile $CredentialFile -FixturePath (Join-Path $AssetDirectory 'windows-native-browser-fixture.mjs') -EvidenceDirectory $perf -PerfOnly}
62 $env:CAGE_TEST_WINDOWS_WORKBENCH_PROFILE=Split-Path -Parent $ProfilePath;$env:CAGE_TEST_WINDOWS_BROWSER_ARTIFACTS=Join-Path $EvidenceDirectory 'editor';$env:CAGE_TEST_WINDOWS_BROWSER_NATIVE='1'
63 & (Join-Path $AssetDirectory 'browser-editor-tests.exe') '-test.run=^TestWindowsBrowserEditorNativeE2E$' '-test.v' '-test.count=1'
64 if($LASTEXITCODE -ne 0){throw 'The real local-only native editor test failed.'}
65 if(!$EditorOnly){& (Join-Path $AssetDirectory 'qa-browser.ps1') -ProfilePath $ProfilePath -CredentialFile $CredentialFile -FixturePath (Join-Path $AssetDirectory 'windows-native-browser-fixture.mjs') -EvidenceDirectory (Join-Path $EvidenceDirectory 'native-core')}
66} finally {
67 try {
68 if($setup){
69 $restored=Invoke-Command -Session $session -ArgumentList $setup.Config,$setup.Backup,$setup.Hash,[bool]$changed,$vm.Id,$binding.gui_user_sid -ScriptBlock {
70 param($file,$backup,$hash,$changed,$vm,$sid)
71 if($changed){[IO.File]::WriteAllBytes($file,[IO.File]::ReadAllBytes($backup))}
72 if((Get-FileHash $file -Algorithm SHA256).Hash -cne $hash){throw 'The original guest configuration was not restored.'}
73 Remove-Item -LiteralPath $backup
74 if($changed){
75 $name='Cage-GUI-Bridge-'+$vm+'-'+$sid;$task=Get-ScheduledTask -TaskName $name
76 if($task.Description -cne ('Cage protected GUI bridge '+$vm+' '+$sid)){throw 'Owned GUI task mismatch'}
77 Stop-ScheduledTask -InputObject $task
78 $until=[DateTime]::UtcNow.AddSeconds(10)
79 while((Get-ScheduledTask -TaskName $name).State -eq 'Running' -and [DateTime]::UtcNow -lt $until){Start-Sleep -Milliseconds 100}
80 if((Get-ScheduledTask -TaskName $name).State -eq 'Running'){throw 'The owned GUI task did not stop.'}
81 Start-ScheduledTask -InputObject $task
82 $until=[DateTime]::UtcNow.AddSeconds(10)
83 while((Get-ScheduledTask -TaskName $name).State -ne 'Running' -and [DateTime]::UtcNow -lt $until){Start-Sleep -Milliseconds 100}
84 if((Get-ScheduledTask -TaskName $name).State -ne 'Running'){throw 'The owned GUI task did not restart.'}
85 }
86 return $true
87 }
88 }
89 if($restored -and $changed){
90 $until=[DateTime]::UtcNow.AddSeconds(10);$confirmed=$false
91 do{try{$status=Bridge 'status';$pending=$status.StandardOutput.ReadLineAsync();if($pending.Wait(2000) -and $pending.Result){$reply=$pending.Result|ConvertFrom-Json;$confirmed=$reply.available -eq $true -and $reply.vm_id -eq $binding.vm_id -and $reply.gui_user_sid -ceq $binding.gui_user_sid}}catch{};if(!$confirmed){Start-Sleep -Milliseconds 200}}while(!$confirmed -and [DateTime]::UtcNow -lt $until)
92 if(!$confirmed){throw 'Configuration restored, but the actual paired GUI status ACK is unavailable.'}
93 [Console]::WriteLine('LOCAL_ONLY_QA_GUI_ACK_CONFIRMED')
94 }
95 if($restored){$endUtc=[DateTime]::UtcNow.ToString('o');[IO.File]::WriteAllText((Join-Path $EvidenceDirectory 'configuration-window.json'),(@{start_utc=$windowStartUtc;end_utc=$endUtc;original_config_restored=$true;gui_ack_confirmed=$confirmed;network_mode='local-only-proxy';normal_nics=0}|ConvertTo-Json),$utf8);[Console]::WriteLine('LOCAL_ONLY_QA_CONFIG_RESTORED '+$endUtc)}
96 } finally {
97 foreach($p in $owned){try{$p.StandardInput.Close();if(!$p.WaitForExit(1000)){$p.Kill()};$p.Dispose()}catch{}}
98 if($session){Remove-PSSession $session}
99 }
100}