跳到主要内容

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

浏览文件

windows-iso-setup.tests.ps1

120 行 · 8.7 KB历史下载
1#requires -Version 5.1
2$ErrorActionPreference = 'Stop'
3. (Join-Path $PSScriptRoot 'windows-host-image.ps1')
4function Assert-Check([bool]$Condition, [string]$Message) { if (!$Condition) { throw $Message } }
5$credential = [pscredential]::new('CageAdmin', (ConvertTo-SecureString 'Test-only<&>"Account!123' -AsPlainText -Force))
6$answer = New-CageISOAnswer $credential
7$ns = [Xml.XmlNamespaceManager]::new($answer.NameTable)
8$ns.AddNamespace('u', 'urn:schemas-microsoft-com:unattend')
9$roundtrip = [xml]$answer.OuterXml
10Assert-Check ($roundtrip.SelectSingleNode('//u:LocalAccount/u:Name', $ns).InnerText -ceq 'CageAdmin') 'Initial account name changed.'
11Assert-Check ($roundtrip.SelectSingleNode('//u:LocalAccount/u:Password/u:Value', $ns).InnerText -ceq $credential.GetNetworkCredential().Password) 'Password XML escaping changed the credential.'
12Assert-Check ($answer.SelectSingleNode('//u:LocalAccount/u:Group', $ns).InnerText -ceq 'Administrators') 'PowerShell Direct needs the initial administrator.'
13foreach ($setting in @('HideOnlineAccountScreens', 'HideWirelessSetupInOOBE')) {
14 Assert-Check ($answer.SelectSingleNode('//u:OOBE/u:'+$setting, $ns).InnerText -ceq 'true') 'Offline OOBE settings are missing.'
15}
16Assert-Check ($answer.SelectNodes('//u:DiskConfiguration | //u:ImageInstall | //u:HideEULAPage | //u:AcceptEula | //u:ProductKey | //u:AutoLogon | //u:UILanguage | //u:SkipMachineOOBE', $ns).Count -eq 0) 'Manual ISO choices or administrator sign-in were overridden.'
17foreach ($name in @('Administrator', 'cagesetup', 'host\user', '[email protected]', 'abcdefghijklmnopqrstu')) {
18 try {
19 $null = New-CageISOAnswer ([pscredential]::new($name, $credential.Password))
20 throw 'Invalid account accepted'
21 } catch { if ($_.Exception.Message -eq 'Invalid account accepted') { throw } }
22}
23
24# Execute the production branch which chooses the answer before creating a disk.
25$errors = $null
26$ast = [Management.Automation.Language.Parser]::ParseFile((Join-Path $PSScriptRoot 'new-windows-test-vm.ps1'), [ref]$null, [ref]$errors)
27Assert-Check ($errors.Count -eq 0) 'VM creation script failed to parse.'
28$selection = @($ast.EndBlock.Statements | Where-Object { $_.Extent.Text.StartsWith('if ($fromHost) {') })[0]
29Assert-Check ($null -ne $selection) 'Missing production answer selection.'
30$createAnswer = [scriptblock]::Create($selection.Extent.Text)
31$script:prompts = 0
32function Get-Credential { param($UserName, $Message); $script:prompts++; return $credential }
33$fromHost = $false
34$GuestAdministrator = $null
35. $createAnswer
36Assert-Check ($script:prompts -eq 1 -and $answer.SelectNodes('//u:LocalAccount', $ns).Count -eq 1) 'The manual route did not collect an offline account.'
37. $createAnswer
38Assert-Check ($script:prompts -eq 1) 'An explicit credential prompted again.'
39$fromHost = $true
40$GuestAdministrator = [pscredential]::new('cagesetup', $credential.Password)
41$ImageLanguage = 'zh-CN'
42. $createAnswer
43Assert-Check ($answer.SelectSingleNode('//u:LocalAccount/u:Name', $ns).InnerText -ceq 'cagesetup') 'Clone setup account changed.'
44Assert-Check ($answer.SelectSingleNode('//u:UILanguage', $ns).InnerText -ceq 'zh-CN') 'Clone locale changed.'
45
46# The owner's progress reader accepts only known stages and reads the final
47# stage after process exit. Arbitrary child output never becomes UI content.
48$ast = [Management.Automation.Language.Parser]::ParseFile((Join-Path $PSScriptRoot 'setup-windows-guest.ps1'), [ref]$null, [ref]$errors)
49Assert-Check ($errors.Count -eq 0) 'Setup orchestration failed to parse.'
50$wait = $ast.Find({ param($node) $node -is [Management.Automation.Language.FunctionDefinitionAst] -and $node.Name -eq 'Wait-CageWindowsInstaller' }, $true)
51. ([scriptblock]::Create($wait.Extent.Text))
52$progressFile = [IO.Path]::GetTempFileName()
53$heldProgress = [IO.File]::Open($progressFile, 'Open', 'ReadWrite', 'ReadWrite')
54$writer = [IO.File]::Open($progressFile, 'Open', 'Write', 'ReadWrite')
55try {
56 $process = [pscustomobject]@{ Position = 0; Writer = $writer; Stages = @('CAGE_GUEST_STAGE windows-11 account', 'private diagnostic fixture', 'CAGE_GUEST_STAGE windows-11 media', 'CAGE_GUEST_STAGE windows-11 tools', 'CAGE_GUEST_STAGE windows-11 services', 'CAGE_GUEST_STAGE windows-11 oobe') }
57 $process | Add-Member -MemberType ScriptMethod -Name WaitForExit -Value {
58 param($Timeout)
59 $bytes = [Text.Encoding]::UTF8.GetBytes($this.Stages[$this.Position])
60 $this.Writer.Position = 0
61 $this.Writer.SetLength(0)
62 $this.Writer.Write($bytes, 0, $bytes.Length)
63 $this.Writer.Flush()
64 $this.Position++
65 return $this.Position -eq $this.Stages.Count
66 }
67 $stages = @(Wait-CageWindowsInstaller $process $progressFile)
68 Assert-Check ($stages.Count -eq 5 -and $stages[-1] -ceq 'CAGE_GUEST_STAGE windows-11 oobe') 'Final progress or stage filtering failed.'
69 $writer.Dispose()
70
71 # Execute the exact encoded wrapper in a real child PowerShell process.
72 # UAC itself is covered by native acceptance, while file sharing is exercised here.
73 $wrapper = $ast.Find({ param($node) $node -is [Management.Automation.Language.AssignmentStatementAst] -and $node.Left.Extent.Text -eq '$command' -and $node.Right.Extent.Text.StartsWith("@'") }, $true)
74 $literal = $wrapper.Right.Find({ param($node) $node -is [Management.Automation.Language.StringConstantExpressionAst] }, $true)
75 $command = $literal.Value
76 $fixtureScript = $progressFile+'.ps1'
77 $stdout = $progressFile+'.stdout'
78 $stderr = $progressFile+'.stderr'
79 try {
80 [IO.File]::WriteAllText($fixtureScript, "Write-Output 'CAGE_GUEST_STAGE windows-11 account'`nWrite-Output 'private diagnostic fixture'`nWrite-Output 'CAGE_GUEST_STAGE windows-11 oobe'")
81 $payload = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes((@{ProgressFile=$progressFile}|ConvertTo-Json -Compress)))
82 $scriptPath = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($fixtureScript))
83 $command = $command.Replace('__PARAMETERS__', $payload).Replace('__SCRIPT__', $scriptPath)
84 $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command))
85 $child = Start-Process -FilePath (Get-Process -Id $PID).Path -ArgumentList @('-NoLogo','-NoProfile','-NonInteractive','-EncodedCommand',$encoded) -RedirectStandardOutput $stdout -RedirectStandardError $stderr -PassThru
86 try {
87 $null = $child.Handle
88 $forwarded = @(Wait-CageWindowsInstaller $child $progressFile)
89 Assert-Check ($child.ExitCode -eq 0) ('Encoded installer wrapper failed. '+[IO.File]::ReadAllText($stderr))
90 Assert-Check ($forwarded[-1] -ceq 'CAGE_GUEST_STAGE windows-11 oobe') 'The actual child could not publish its final stage.'
91 } finally { $child.Dispose() }
92 } finally {
93 foreach ($path in @($fixtureScript,$stdout,$stderr)) { [IO.File]::Delete($path) }
94 }
95} finally { $writer.Dispose(); $heldProgress.Dispose(); [IO.File]::Delete($progressFile) }
96
97# An interrupted or unauthenticated guest retains its answer media. Successful
98# cleanup only removes the fixed tools ISO and preserves the original disk.
99$directory = Join-Path ([IO.Path]::GetTempPath()) ('cage-iso-answer-'+[guid]::NewGuid().ToString('N'))
100$null = [IO.Directory]::CreateDirectory($directory)
101try {
102 $iso = Join-Path $directory 'windows-guest-tools.iso'
103 $disk = Join-Path $directory 'system.vhdx'
104 [IO.File]::WriteAllText($iso, 'private answer fixture')
105 [IO.File]::WriteAllText($disk, 'existing personal disk fixture')
106 $vm = [pscustomobject]@{ Id = [guid]::NewGuid() }
107 $script:guestReady = $false
108 $script:removedDVDs = @()
109 function Invoke-Command { param($Session, $ArgumentList, $ScriptBlock); if (!$script:guestReady) { throw 'Guest setup incomplete' } }
110 function Hyper-V\Get-VMDvdDrive { process { @([pscustomobject]@{Path=$iso}, [pscustomobject]@{Path='original-windows.iso'}) } }
111 function Hyper-V\Remove-VMDvdDrive { process { $script:removedDVDs += $_.Path } }
112 try { Remove-CageISOAnswer $vm 'session' $directory; throw 'Incomplete setup was accepted' }
113 catch { if ($_.Exception.Message -cne 'Guest setup incomplete') { throw } }
114 Assert-Check ((Test-Path -LiteralPath $iso) -and $script:removedDVDs.Count -eq 0) 'Unfinished setup lost its answer media.'
115 $script:guestReady = $true
116 Remove-CageISOAnswer $vm 'session' $directory
117 Assert-Check (!(Test-Path -LiteralPath $iso) -and $script:removedDVDs.Count -eq 1 -and $script:removedDVDs[0] -eq $iso) 'Cleanup touched the wrong DVD.'
118 Assert-Check ([IO.File]::ReadAllText($disk) -ceq 'existing personal disk fixture') 'Cleanup changed the retained disk.'
119} finally { [IO.Directory]::Delete($directory, $true) }
120Write-Output 'Passed manual ISO account/OOBE XML, retained manual choices, clone parity and elevated installer progress forwarding.'