跳到主要内容

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

浏览文件

provision-claude-offline-windows.ps1

212 行 · 12.1 KB历史下载
1#requires -Version 5.1
2<#
3.SYNOPSIS
4Stage the official Claude x64 MSIX in a stopped Cage Windows evaluation VM.
5.DESCRIPTION
6Run from elevated 64-bit Windows PowerShell on the Hyper-V host. Provide the VM
7GUID and private directory from new-windows-test-vm.ps1. An evaluation setup
8receipt and a readable EnterpriseEval OS partition are required. The report
9and DISM scratch/log are saved beside the test disk. This does not boot the VM
10or register the application for a user.
11.LINK
12https://support.claude.com/en/articles/12622703-deploy-claude-desktop-for-windows
13.LINK
14https://learn.microsoft.com/en-us/powershell/module/dism/add-appxprovisionedpackage
15#>
16[CmdletBinding()]
17param(
18 [Parameter(Mandatory)][Guid]$VMId,
19 [Parameter(Mandatory)][string]$InstanceDirectory,
20 [Parameter(Mandatory)][string]$MsixPath
21)
22$ErrorActionPreference = 'Stop'
23. (Join-Path $PSScriptRoot 'claude-desktop-windows.ps1') -MsixPath $MsixPath
24
25function Assert-CageOfflineTarget($Machine, $Drive, $Snapshots, $Vhd, $Receipt, [string]$Root, [guid]$Id) {
26 $expected = Join-Path $Root 'system.vhdx'
27 $location = [IO.Path]::GetFullPath($Machine.ConfigurationLocation).TrimEnd('\')
28 if ($Id -eq [guid]::Empty -or $Machine.Id -ne $Id -or [guid]$Receipt.VMId -ne $Id -or
29 $Receipt.Edition -ne 'EnterpriseEval' -or $Receipt.InstanceDirectory -ne $Root -or $Receipt.Disk -ne $expected -or
30 ($location -ne $Root -and !$location.StartsWith($Root + '\', [StringComparison]::OrdinalIgnoreCase))) {
31 throw 'The VM, setup receipt and private instance directory do not match.'
32 }
33 if ($Machine.State -ne 'Off' -or $Machine.Generation -ne 2 -or @($Snapshots).Count -ne 0 -or
34 @($Drive).Count -ne 1 -or $Drive[0].Path -ne $expected -or $Vhd.Path -ne $expected -or
35 $Vhd.VhdFormat -ne 'VHDX' -or $Vhd.VhdType -ne 'Dynamic' -or $Vhd.ParentPath -or $Vhd.Attached -ne $false) {
36 throw 'Requires a stopped Gen 2 VM with one unattached, standalone dynamic VHDX and no snapshots.'
37 }
38}
39
40function Assert-MountedGuestDisk($Disk, $BackingVHD, [string]$ExpectedPath) {
41 if (@($Disk).Count -ne 1 -or $null -eq $Disk.Number -or $BackingVHD.DiskNumber -ne $Disk.Number -or
42 $BackingVHD.Path -ne $ExpectedPath -or $BackingVHD.Attached -ne $true -or
43 $Disk.IsBoot -ne $false -or $Disk.IsSystem -ne $false -or $Disk.IsOffline -ne $false -or
44 $Disk.IsReadOnly -ne $false -or $Disk.PartitionStyle -ne 'GPT') {
45 throw 'The attached disk is not the selected writable guest GPT disk, or is a host boot/system disk.'
46 }
47}
48
49function Select-GuestWindowsPartition($Partitions, [int]$DiskNumber) {
50 $basic = @($Partitions | Where-Object { ([string]$_.GptType).Trim('{}') -eq 'EBD0A0A2-B9E5-4433-87C0-68B6B72699C7' })
51 if ($basic.Count -ne 1 -or $basic[0].DiskNumber -ne $DiskNumber -or
52 $basic[0].IsBoot -ne $false -or $basic[0].IsSystem -ne $false) {
53 throw 'Expected exactly one Windows basic-data partition on the selected guest disk.'
54 }
55 return $basic[0]
56}
57
58function Get-OfflineClaude([hashtable]$Image, [string]$Package) {
59 $matchesName = @(Get-AppxProvisionedPackage @Image | Where-Object DisplayName -ceq 'Claude')
60 if ($matchesName.Count -gt 1 -or ($matchesName.Count -eq 1 -and $matchesName[0].PackageName -cne $Package)) {
61 throw 'The offline image already contains a different Claude package. It was preserved.'
62 }
63 if ($matchesName.Count -eq 1) { return $matchesName[0] }
64}
65
66function Install-OfflineClaude([hashtable]$Image, [string]$PackageFile, [string]$PackageName) {
67 $existing = Get-OfflineClaude $Image $PackageName
68 if (!$existing) {
69 $null = Add-AppxProvisionedPackage @Image -PackagePath $PackageFile -SkipLicense -Regions 'all'
70 }
71 $installed = Get-OfflineClaude $Image $PackageName
72 if (!$installed) { throw 'DISM did not list the expected Claude provisioning entry in the guest.' }
73 return [pscustomobject]@{ PackageName=$installed.PackageName; AlreadyProvisioned=[bool]$existing }
74}
75
76if ([Environment]::OSVersion.Platform -ne 'Win32NT' -or ![Environment]::Is64BitProcess) { throw 'Run on the 64-bit Windows Hyper-V host.' }
77$root = Get-Item -LiteralPath $InstanceDirectory
78if ($root -isnot [IO.DirectoryInfo] -or $root.FullName.StartsWith('\\') -or [IO.DriveInfo]::new($root.Root.FullName).DriveType -ne 'Fixed') {
79 throw 'The VM directory must be on a local fixed drive.'
80}
81for ($ancestor=$root; $ancestor; $ancestor=$ancestor.Parent) {
82 if ($ancestor.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'A redirected VM directory is not supported.' }
83}
84$qa = Get-Item -LiteralPath (Join-Path $root.FullName 'evaluation-setup')
85$receiptFile = Get-Item -LiteralPath (Join-Path $qa.FullName 'receipt.json')
86$diskFile = Get-Item -LiteralPath (Join-Path $root.FullName 'system.vhdx')
87foreach ($entry in @($qa,$receiptFile,$diskFile)) {
88 if ($entry.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Unexpected reparse point in the instance or receipt.' }
89}
90$receipt = Get-Content -LiteralPath $receiptFile.FullName -Raw | ConvertFrom-Json
91$packageFile = Get-Item -LiteralPath $MsixPath
92if ($packageFile -isnot [IO.FileInfo] -or $packageFile.Extension -ne '.msix' -or
93 ($packageFile.Attributes -band [IO.FileAttributes]::ReparsePoint) -or $packageFile.FullName.StartsWith('\\') -or
94 [IO.DriveInfo]::new($packageFile.Directory.Root.FullName).DriveType -eq 'Network') {
95 throw 'Supply a regular local x64 Claude MSIX.'
96}
97$lock = [IO.File]::Open((Join-Path $qa.FullName 'setup.lock'), 'OpenOrCreate', 'ReadWrite', 'None')
98$mounted = $false
99$addedAccess = $false
100$packageHandle = $null
101$run = $null
102$report = [ordered]@{ VMId=$VMId; Disk=$diskFile.FullName; Provisioned=$null; UserRegistration='NotTested'; Window='NotTested' }
103try {
104 $vm = Get-VM -Id $VMId
105 $drives = @(Get-VMHardDiskDrive -VM $vm)
106 $snapshots = @(Get-VMSnapshot -VM $vm)
107 $vhd = Get-VHD -Path $diskFile.FullName
108 Assert-CageOfflineTarget $vm $drives $snapshots $vhd $receipt $root.FullName $VMId
109 $owners = @(Get-VM | Get-VMHardDiskDrive | Where-Object Path -eq $diskFile.FullName)
110 if ($owners.Count -ne 1 -or $owners[0].VMId -ne $VMId) { throw 'The guest disk is not owned exclusively by this VM.' }
111 $hostVolume = Get-Volume -FilePath $diskFile.FullName
112 if ($hostVolume.FileSystemType -ne 'NTFS') { throw 'The private host directory must support NTFS volume mount points.' }
113 $run = New-Item -ItemType Directory -Path (Join-Path $qa.FullName ('offline-claude-' + [guid]::NewGuid().ToString('N')))
114 $mount = New-Item -ItemType Directory -Path (Join-Path $run.FullName 'os')
115 $scratch = New-Item -ItemType Directory -Path (Join-Path $run.FullName 'scratch')
116 $log = Join-Path $run.FullName 'dism.log'
117 $report['DismLog'] = $log
118 $report['HostBuild'] = (Get-CimInstance Win32_OperatingSystem).BuildNumber
119 $packageHandle = [IO.File]::Open($packageFile.FullName,'Open','Read','Read')
120 $version = Get-VerifiedClaudeMsixVersion $packageFile $packageHandle
121 $expectedPackage = 'Claude_{0}_x64__pzs8sxrjxfjjc' -f $version
122 $report['VerifiedInputPackage'] = $expectedPackage
123
124 $attached = Mount-VHD -Path $diskFile.FullName -NoDriveLetter -Passthru
125 $mounted = $true
126 $report['VhdDetached'] = $false
127 $disk = @($attached | Get-Disk)
128 if ($disk.Count -ne 1) { throw 'The VHDX attachment did not resolve to one disk.' }
129 $disk = $disk[0]
130 $backing = Get-VHD -DiskNumber $disk.Number
131 Assert-MountedGuestDisk $disk $backing $diskFile.FullName
132 $partition = Select-GuestWindowsPartition @(Get-Partition -DiskNumber $disk.Number) $disk.Number
133 $volumes = @(Get-Volume -Partition $partition)
134 if ($volumes.Count -ne 1 -or !$volumes[0].UniqueId -or $volumes[0].UniqueId -eq $hostVolume.UniqueId) {
135 throw 'Could not identify a separate guest OS volume.'
136 }
137 $volume = $volumes[0]
138 # Query only this VHD volume. An unencrypted VHD need not have a BitLocker provider entry.
139 $volPath = [string]$volume.Path
140 $report['BitLocker'] = 'No provider entry'
141 if ($volPath) {
142 $escaped = $volPath.Replace('\','\\').Replace("'","\'")
143 try {
144 $encrypted = @(Get-CimInstance -Namespace 'root/CIMV2/Security/MicrosoftVolumeEncryption' -ClassName Win32_EncryptableVolume -Filter "DeviceID='$escaped'")
145 } catch { $encrypted = @(); $report['BitLocker'] = 'Provider unavailable' }
146 if ($encrypted.Count -gt 1) { throw 'Ambiguous guest BitLocker volume.' }
147 if ($encrypted.Count -eq 1) {
148 $state = Invoke-CimMethod -InputObject $encrypted[0] -MethodName GetLockStatus
149 if ($state.ReturnValue -ne 0 -or $state.LockStatus -ne 0) { throw 'Guest BitLocker volume is locked or its status is unavailable.' }
150 $report['BitLocker'] = 'Unlocked'
151 }
152 }
153 if ($volume.FileSystemType -ne 'NTFS') { throw 'Guest partition is locked or is not a readable NTFS volume.' }
154 $accessPath = $mount.FullName + '\'
155 Add-PartitionAccessPath -DiskNumber $disk.Number -PartitionNumber $partition.PartitionNumber -AccessPath $accessPath
156 $addedAccess = $true
157 $report['AccessPathRemoved'] = $false
158 foreach ($relative in @('Windows','Windows\System32','Windows\System32\config','Windows\System32\config\SOFTWARE')) {
159 $item = Get-Item -LiteralPath (Join-Path $mount.FullName $relative)
160 if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Unexpected reparse point in guest OS identification path.' }
161 }
162 $osVolume = Get-Volume -FilePath $item.FullName
163 if ($osVolume.UniqueId -ne $volume.UniqueId) { throw 'The mounted Windows image resolves to another volume.' }
164 $dism = Join-Path ([Environment]::SystemDirectory) 'dism.exe'
165 $info = @(& $dism /English ("/Image:$($mount.FullName)") /Get-CurrentEdition ("/ScratchDir:$($scratch.FullName)") ("/LogPath:$log") 2>&1)
166 if ($LASTEXITCODE -ne 0) { throw "DISM could not service the guest edition (exit $LASTEXITCODE). See $log" }
167 $lines = $info -join "`n"
168 if ($lines -notmatch '(?im)^\s*Current Edition\s*:\s*EnterpriseEval\s*$') { throw 'Offline OS is not Windows Enterprise Evaluation.' }
169 $report['GuestEdition'] = 'EnterpriseEval'
170 $report['GuestImageVersion'] = [regex]::Match($lines,'(?im)^\s*Image Version\s*:\s*([\d.]+)').Groups[1].Value
171 $report['DismVersion'] = [regex]::Match($lines,'(?im)^\s*Version\s*:\s*([\d.]+)').Groups[1].Value
172 if (!$report.GuestImageVersion -or !$report.DismVersion) { throw 'Could not read offline image and DISM servicing versions.' }
173 $image = @{Path=$mount.FullName; ScratchDirectory=$scratch.FullName; LogPath=$log; ErrorAction='Stop'}
174 $installed = Install-OfflineClaude $image $packageFile.FullName $expectedPackage
175 $report['Provisioned'] = $true
176 $report['PackageName'] = $installed.PackageName
177 $report['AlreadyProvisioned'] = $installed.AlreadyProvisioned
178} catch {
179 $report['Error'] = $_.Exception.Message
180 throw
181} finally {
182 try {
183 if ($addedAccess) {
184 Remove-PartitionAccessPath -DiskNumber $disk.Number -PartitionNumber $partition.PartitionNumber -AccessPath $accessPath -Confirm:$false
185 $paths = (Get-Partition -DiskNumber $disk.Number -PartitionNumber $partition.PartitionNumber).AccessPaths
186 if (@($paths | Where-Object { $_ -and $_.TrimEnd('\') -eq $mount.FullName }).Count) { throw 'The guest access path did not detach.' }
187 $report['AccessPathRemoved'] = $true
188 }
189 } catch {
190 $report['AccessPathCleanupError'] = $_.Exception.Message
191 throw
192 } finally {
193 try {
194 if ($mounted) { Dismount-VHD -Path $diskFile.FullName -ErrorAction Stop }
195 if ($mounted) {
196 $report['VhdDetached'] = ((Get-VHD -Path $diskFile.FullName).Attached -eq $false)
197 if (!$report.VhdDetached) { throw 'The test VHDX did not detach.' }
198 }
199 } catch {
200 $report['VhdCleanupError'] = $_.Exception.Message
201 throw
202 } finally {
203 if ($packageHandle) { $packageHandle.Dispose() }
204 $lock.Dispose()
205 if ($run) {
206 $reportFile = Join-Path $run.FullName 'result.json'
207 [IO.File]::WriteAllText($reportFile, ($report | ConvertTo-Json))
208 }
209 }
210 }
211}
212[pscustomobject]$report