跳到主要内容

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

浏览文件

installation-files.ps1

348 行 · 19.5 KB历史下载
1#requires -Version 5.1
2[CmdletBinding()]
3param(
4 [Parameter(Mandatory)][ValidateSet('prepare', 'move', 'restore', 'cleanup', 'complete', 'uninstall')][string]$Operation,
5 [Parameter(Mandatory)][string]$Target,
6 [string]$Source,
7 [string]$Receipt,
8 [string]$Manifest,
9 [string]$Backup,
10 [string]$Diagnostics,
11 [switch]$LegacyTarget
12)
13$ErrorActionPreference = 'Stop'
14$diagnosticStep = 'initializing'
15trap {
16 $failure = $_
17 if ($Diagnostics) {
18 try {
19 if (!(Test-Path -LiteralPath $Diagnostics)) {
20 $chain = @()
21 $exception = $failure.Exception
22 for ($index = 0; $exception -and $index -lt 4; $index++) {
23 $chain += @{type = $exception.GetType().FullName; hresult = $exception.HResult}
24 $exception = $exception.InnerException
25 }
26 $lines = @([regex]::Matches($failure.ScriptStackTrace, ': line (\d+)') | ForEach-Object { [int]$_.Groups[1].Value })
27 @{operation = $Operation; phase = $diagnosticStep; pointerSize = [IntPtr]::Size; errors = $chain; lines = $lines; category = [string]$failure.CategoryInfo.Category} | ConvertTo-Json -Depth 4 |
28 Set-Content -LiteralPath $Diagnostics -Encoding UTF8
29 }
30 } catch { }
31 }
32 throw $failure
33}
34$manifestName = 'Cage.install-files.json'
35$identityName = 'Cage.install-id'
36
37function Read-FileManifest([string]$Path) {
38 $files = [Collections.Generic.Dictionary[string,string]]::new([StringComparer]::OrdinalIgnoreCase)
39 if (!(Test-Path -LiteralPath $Path -PathType Leaf)) { return ,$files }
40 if ((Get-Item -LiteralPath $Path -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) { return ,$files }
41 try {
42 $value = Get-Content -LiteralPath $Path -Raw -Encoding UTF8 | ConvertFrom-Json
43 if ($value.version -ne 1) { throw 'Unknown installation manifest version.' }
44 foreach ($entry in $value.files) {
45 if (!$entry.path -or $entry.path -match '(^/|[\\:]|(^|/)\.\.?(/|$))' -or $entry.sha256 -notmatch '^[a-fA-F0-9]{64}$' -or $files.ContainsKey($entry.path)) {
46 throw 'Invalid installation manifest entry.'
47 }
48 $files.Add($entry.path, $entry.sha256.ToLowerInvariant())
49 }
50 } catch {
51 # An unreadable legacy manifest grants no permission to delete files.
52 $files.Clear()
53 }
54 return ,$files
55}
56
57function Directory-Paths([string[]]$Paths) {
58 $directories = [Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
59 $null = $directories.Add('')
60 foreach ($path in $Paths) {
61 $parent = Split-Path $path -Parent
62 while ($parent) { $null = $directories.Add($parent.Replace('\', '/')); $parent = Split-Path $parent -Parent }
63 }
64 return ,$directories
65}
66
67function Read-Tree([string]$Root, [string[]]$KnownPaths) {
68 $entries = [Collections.Generic.List[object]]::new()
69 $directories = [Collections.Generic.Queue[string]]::new()
70 $neededDirectories = Directory-Paths $KnownPaths
71 foreach ($path in $KnownPaths) { $null = $neededDirectories.Add($path) }
72 $directories.Enqueue($Root)
73 while ($directories.Count) {
74 foreach ($entry in Get-ChildItem -LiteralPath $directories.Dequeue() -Force) {
75 $entries.Add($entry)
76 if ($entry.PSIsContainer -and !($entry.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
77 if ($null -eq $KnownPaths -or $neededDirectories.Contains((Relative-Path $Root $entry.FullName))) { $directories.Enqueue($entry.FullName) }
78 }
79 }
80 }
81 return $entries.ToArray()
82}
83
84function Relative-Path([string]$Root, [string]$Path) {
85 return $Path.Substring($Root.TrimEnd([IO.Path]::DirectorySeparatorChar).Length + 1).Replace('\', '/')
86}
87
88function Open-ReadLocked([string]$Path) {
89 return [IO.File]::Open($Path, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::Read -bor [IO.FileShare]::Delete)
90}
91
92function Stream-Hash([IO.Stream]$Stream) {
93 $algorithm = [Security.Cryptography.SHA256]::Create()
94 try { return ([BitConverter]::ToString($algorithm.ComputeHash($Stream))).Replace('-', '').ToLowerInvariant() }
95 finally { $algorithm.Dispose(); $Stream.Position = 0 }
96}
97
98function Initialize-VerifiedDeletion {
99 if (!('CageVerifiedFile' -as [type])) { Add-Type -Path (Join-Path $PSScriptRoot 'verified-file-deletion.cs') }
100}
101
102function Remove-MatchingFile([string]$Root, [string]$Relative, [string]$Hash) {
103 $Path = Join-Path $Root $Relative
104 if (!(Test-Path -LiteralPath $Path -PathType Leaf)) { return }
105 if ((Get-Item -LiteralPath $Path -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) { return }
106 $windows = $env:OS -eq 'Windows_NT'
107 if ($windows) { Initialize-VerifiedDeletion; $stream = [CageVerifiedFile]::Open($Root, $Relative) }
108 else { $stream = Open-ReadLocked $Path }
109 try {
110 if ((Stream-Hash $stream) -eq $Hash) {
111 if ($windows) { [CageVerifiedFile]::Delete($stream) } else { [IO.File]::Delete($Path) }
112 }
113 }
114 finally { $stream.Dispose() }
115}
116
117function Remove-EmptyDirectories([string]$Root, [string[]]$KnownDirectories) {
118 foreach ($directory in @(Read-Tree $Root $KnownDirectories | Where-Object { $_.PSIsContainer -and !($_.Attributes -band [IO.FileAttributes]::ReparsePoint) } | Sort-Object { $_.FullName.Length } -Descending)) {
119 if ((Relative-Path $Root $directory.FullName) -in $KnownDirectories -and @(Get-ChildItem -LiteralPath $directory.FullName -Force).Count -eq 0) {
120 [IO.Directory]::Delete($directory.FullName)
121 }
122 }
123}
124
125function Preserved-Destination([string]$Relative, [bool]$Quarantine) {
126 $path = Join-Path $Target $Relative
127 $parent = Split-Path $path -Parent
128 $conflict = $Quarantine -or (Test-Path -LiteralPath $path)
129 while ($parent -ne $Target) {
130 if (Test-Path -LiteralPath $parent -PathType Leaf) { $conflict = $true; break }
131 $parent = Split-Path $parent -Parent
132 }
133 if ($conflict) { return $recovery + '/' + $Relative }
134 return $Relative
135}
136
137function Save-Transfer($Transfer) {
138 $temporary = $Receipt + '.' + [guid]::NewGuid().ToString('N') + '.tmp'
139 try {
140 $Transfer | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath $temporary -Encoding UTF8
141 [IO.File]::Replace($temporary, $Receipt, [NullString]::Value)
142 } finally { if (Test-Path -LiteralPath $temporary) { [IO.File]::Delete($temporary) } }
143}
144
145function Complete-Transfer {
146 $transfer = Get-Content -LiteralPath $Receipt -Raw -Encoding UTF8 | ConvertFrom-Json
147 if ($transfer.kind -ne 'cage-installation' -or !(Test-Path -LiteralPath (Join-Path $Target $identityName))) { throw '安装目录尚未恢复,事务回执已保留。' }
148 if ($transfer.backupPath -and (Test-Path -LiteralPath $transfer.backupPath)) { throw ('旧目录仍需恢复,事务回执已保留:' + $transfer.backupPath) }
149 foreach ($entry in $transfer.moves) {
150 if ($entry.state -eq 'absent') { continue }
151 $relative = if ($entry.state -eq 'moved') { $entry.destination } else { $entry.path }
152 if (!(Get-Item -LiteralPath (Join-Path $Target $relative) -Force -ErrorAction SilentlyContinue)) { throw ('个人文件尚未恢复,事务回执已保留:' + $relative) }
153 }
154 $receiptStream = Open-ReadLocked $Receipt
155 try { $hash = Stream-Hash $receiptStream } finally { $receiptStream.Dispose() }
156 Remove-MatchingFile (Split-Path $Receipt -Parent) (Split-Path $Receipt -Leaf) $hash
157 if (Test-Path -LiteralPath $Receipt) { throw '安装回执在完成期间发生变化,已保留待核对。' }
158}
159
160$Target = [IO.Path]::GetFullPath($Target).TrimEnd([IO.Path]::DirectorySeparatorChar)
161foreach ($rootPath in @($Target, $Source)) {
162 if (!$rootPath) { continue }
163 $rootEntry = Get-Item -LiteralPath $rootPath -Force -ErrorAction SilentlyContinue
164 if ($rootEntry -and $rootEntry.Attributes -band [IO.FileAttributes]::ReparsePoint) {
165 throw ('安装目录本身是文件系统链接,原文件已保留。请选择实际程序目录:' + $rootPath)
166 }
167}
168if ($Operation -eq 'prepare') {
169 $diagnosticStep = 'reading_new_manifest'
170 if (Test-Path -LiteralPath $Receipt) { throw ('仍有未完成的安装事务,请保留并检查回执:' + $Receipt) }
171 $current = Read-FileManifest (Join-Path $Target $manifestName)
172 $legacySnapshot = !$current.Count -and $LegacyTarget
173 if ($legacySnapshot) {
174 $identity = Open-ReadLocked (Join-Path $Target $identityName)
175 try { $current[$identityName] = Stream-Hash $identity } finally { $identity.Dispose() }
176 }
177 if (!$current.Count) { throw '新程序缺少有效文件清单,安装已停止。' }
178 $diagnosticStep = 'reading_new_uninstaller'
179 $uninstaller = Open-ReadLocked (Join-Path $Target 'Uninstall.exe')
180 try { $current['Uninstall.exe'] = Stream-Hash $uninstaller } finally { $uninstaller.Dispose() }
181 $transfers = [Collections.Generic.List[object]]::new()
182 $moves = [Collections.Generic.List[object]]::new()
183 $directories = @()
184 $recovery = 'Cage-preserved-files/' + [guid]::NewGuid().ToString('N')
185 $programDirectories = Directory-Paths @($current.Keys)
186 if ($Source -and (Test-Path -LiteralPath $Source -PathType Container)) {
187 $diagnosticStep = 'scanning_previous_installation'
188 $Source = [IO.Path]::GetFullPath($Source).TrimEnd([IO.Path]::DirectorySeparatorChar)
189 $previous = Read-FileManifest (Join-Path $Source $manifestName)
190 $previousDirectories = Directory-Paths @($previous.Keys)
191 $pending = [Collections.Generic.Queue[string]]::new()
192 $pending.Enqueue($Source)
193 while ($pending.Count) {
194 foreach ($entry in Get-ChildItem -LiteralPath $pending.Dequeue() -Force) {
195 $relative = Relative-Path $Source $entry.FullName
196 $isLink = [bool]($entry.Attributes -band [IO.FileAttributes]::ReparsePoint)
197 $programContent = $previous.ContainsKey($relative) -or (
198 $programDirectories.Contains((Split-Path $relative -Parent).Replace('\', '/')) -and
199 ($entry.Extension -in @('.dll','.exe','.ocx','.sys','.pyd','.so','.dylib') -or $entry.Name -eq 'node_modules'))
200 $hasOwnedChildren = $previousDirectories.Contains($relative)
201 # A legacy rollback snapshot also contains old personal files.
202 # The failed candidate's manifest identifies its program paths, so
203 # current personal content can return to its original location.
204 if ($legacySnapshot -and $previous.Count -and !$programContent -and !$hasOwnedChildren -and
205 $relative -notin @($manifestName, 'Cage-preserved-files')) {
206 $oldCopy = Get-Item -LiteralPath (Join-Path $Target $relative) -Force -ErrorAction SilentlyContinue
207 if ($oldCopy) {
208 $oldDestination = Join-Path $Target ($recovery + '/previous/' + $relative)
209 [IO.Directory]::CreateDirectory((Split-Path $oldDestination -Parent)) | Out-Null
210 if ($oldCopy.Attributes -band [IO.FileAttributes]::Directory) { [IO.Directory]::Move($oldCopy.FullName, $oldDestination) }
211 else { [IO.File]::Move($oldCopy.FullName, $oldDestination) }
212 }
213 }
214 if ($isLink -or ($entry.PSIsContainer -and !$hasOwnedChildren -and !(Test-Path -LiteralPath (Join-Path $Target $relative) -PathType Container))) {
215 $moves.Add(@{path = $relative; destination = (Preserved-Destination $relative $programContent); directory = ($entry.PSIsContainer -or [bool]($entry.Attributes -band [IO.FileAttributes]::Directory)); state = 'prepared'})
216 continue
217 }
218 if ($entry.PSIsContainer) {
219 $directories += $relative
220 $pending.Enqueue($entry.FullName)
221 continue
222 }
223 if (!$previous.ContainsKey($relative) -and !(Test-Path -LiteralPath (Join-Path $Target $relative)) -and $relative -ne $manifestName) {
224 $moves.Add(@{path = $relative; destination = (Preserved-Destination $relative $programContent); directory = $false; state = 'prepared'})
225 continue
226 }
227 $sourceStream = Open-ReadLocked $entry.FullName
228 try {
229 $hash = Stream-Hash $sourceStream
230 if (($previous.ContainsKey($relative) -and $previous[$relative] -eq $hash) -or ($relative -eq $manifestName -and $previous.Count)) {
231 $transfers.Add(@{ path = $relative; sha256 = $hash; destination = $null })
232 continue
233 }
234 $path = Join-Path $Target $relative
235 if (Test-Path -LiteralPath $path -PathType Leaf) {
236 $candidate = Open-ReadLocked $path
237 try { $same = (Stream-Hash $candidate) -eq $hash } finally { $candidate.Dispose() }
238 if ($same) {
239 $transfers.Add(@{ path = $relative; sha256 = $hash; destination = $relative })
240 continue
241 }
242 }
243 $moves.Add(@{path = $relative; destination = (Preserved-Destination $relative $programContent); directory = $false; state = 'prepared'})
244 } finally { $sourceStream.Dispose() }
245 }
246 }
247 }
248 $diagnosticStep = 'writing_new_manifest'
249 $files = @($current.Keys | Sort-Object | ForEach-Object { @{ path = $_; sha256 = $current[$_] } })
250 @{ version = 1; files = $files } | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath (Join-Path $Target $manifestName) -Encoding UTF8
251 $diagnosticStep = 'writing_transaction_receipt'
252 $record = @{kind = 'cage-installation'; version = 1; installPath = $Source; stagePath = $Target; backupPath = $Backup; files = @($transfers); directories = $directories; moves = @($moves)}
253 $encoding = [Text.UTF8Encoding]::new($true)
254 [byte[]]$bytes = $encoding.GetPreamble() + $encoding.GetBytes(($record | ConvertTo-Json -Depth 6))
255 $temporary = $Receipt + '.' + [guid]::NewGuid().ToString('N') + '.tmp'
256 try {
257 $output = [IO.File]::Open($temporary, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None)
258 try { $output.Write($bytes, 0, $bytes.Length); $output.Flush($true) } finally { $output.Dispose() }
259 [IO.File]::Move($temporary, $Receipt)
260 } finally { if (Test-Path -LiteralPath $temporary) { [IO.File]::Delete($temporary) } }
261} elseif ($Operation -in @('move','restore')) {
262 $diagnosticStep = 'moving_preserved_files'
263 $transfer = Get-Content -LiteralPath $Receipt -Raw -Encoding UTF8 | ConvertFrom-Json
264 $moves = @($transfer.moves)
265 if ($Operation -eq 'restore') { [Array]::Reverse($moves) }
266 foreach ($entry in $moves) {
267 if ($Operation -eq 'restore' -and $entry.state -notin @('moving','moved')) { continue }
268 $from = if ($Operation -eq 'move') { $entry.path } else { $entry.destination }
269 $to = if ($Operation -eq 'move') { $entry.destination } else { $entry.path }
270 $from = Join-Path $Source $from
271 $to = Join-Path $Target $to
272 if (!(Get-Item -LiteralPath $from -Force -ErrorAction SilentlyContinue)) {
273 if ($Operation -eq 'restore' -and !(Get-Item -LiteralPath $to -Force -ErrorAction SilentlyContinue)) { throw ('待恢复的个人文件无法定位,回执已保留:' + $entry.path) }
274 if ($Operation -eq 'move' -and $entry.state -eq 'prepared') { $entry.state = 'absent'; Save-Transfer $transfer }
275 continue
276 }
277 [IO.Directory]::CreateDirectory((Split-Path $to -Parent)) | Out-Null
278 if ($Operation -eq 'move') { $entry.state = 'moving'; Save-Transfer $transfer }
279 $moved = $false
280 try {
281 if ($entry.directory) { [IO.Directory]::Move($from, $to) } else { [IO.File]::Move($from, $to) }
282 $moved = $true
283 $entry.state = if ($Operation -eq 'move') { 'moved' } else { 'restored' }
284 Save-Transfer $transfer
285 } catch {
286 if ($Operation -eq 'move' -and !$moved) { $entry.state = 'failed'; Save-Transfer $transfer }
287 throw
288 }
289 }
290 if ($Operation -eq 'move' -and @($moves | Where-Object { $_.destination.StartsWith('Cage-preserved-files/') }).Count) {
291 Write-Output ('同名修改或旧程序文件已保留在 ' + (Join-Path $Target 'Cage-preserved-files'))
292 }
293} elseif ($Operation -eq 'cleanup') {
294 $diagnosticStep = 'verifying_previous_file_ownership'
295 $transfer = Get-Content -LiteralPath $Receipt -Raw -Encoding UTF8 | ConvertFrom-Json
296 $actual = @(Read-Tree $Source @($transfer.files.path) | Where-Object { !($_.Attributes -band [IO.FileAttributes]::ReparsePoint) } | ForEach-Object { Relative-Path $Source $_.FullName })
297 foreach ($entry in $transfer.files) {
298 if ($entry.path -notin $actual) { continue }
299 try {
300 if ($entry.destination) {
301 $copy = Open-ReadLocked (Join-Path $Target $entry.destination)
302 try { if ((Stream-Hash $copy) -ne $entry.sha256) { continue } } finally { $copy.Dispose() }
303 }
304 Remove-MatchingFile $Source $entry.path $entry.sha256
305 } catch { Write-Output '安装期间变化或被占用的文件已保留在旧目录。' }
306 }
307 Remove-EmptyDirectories $Source $transfer.directories
308 if (@(Get-ChildItem -LiteralPath $Source -Force).Count) {
309 $recovery = Join-Path $Target ('Cage-preserved-files/late-' + [guid]::NewGuid().ToString('N'))
310 [IO.Directory]::CreateDirectory((Split-Path $recovery -Parent)) | Out-Null
311 [IO.Directory]::Move($Source, $recovery)
312 Write-Output ('安装期间变化的文件已保留在 ' + $recovery)
313 } else { [IO.Directory]::Delete($Source) }
314 Complete-Transfer
315} elseif ($Operation -eq 'complete') {
316 $diagnosticStep = 'completing_transaction_receipt'
317 Complete-Transfer
318} else {
319 # The payload list comes from this uninstaller's embedded build manifest.
320 $diagnosticStep = 'reading_uninstall_manifest'
321 $owned = Read-FileManifest $Manifest
322 if (!$owned.Count) { throw '卸载文件清单无效,原文件已保留。' }
323 $installed = Read-FileManifest (Join-Path $Target $manifestName)
324 if ($installed.ContainsKey('Uninstall.exe')) { $owned['Uninstall.exe'] = $installed['Uninstall.exe'] }
325 $actual = @(Read-Tree $Target @($owned.Keys) | Where-Object { !($_.Attributes -band [IO.FileAttributes]::ReparsePoint) } | ForEach-Object { Relative-Path $Target $_.FullName })
326 $diagnosticStep = 'deleting_verified_program_files'
327 foreach ($relative in $owned.Keys) {
328 if ($relative -ne $identityName -and $relative -in $actual) { Remove-MatchingFile $Target $relative $owned[$relative] }
329 }
330 if ($installed.Count) {
331 $manifestStream = Open-ReadLocked (Join-Path $Target $manifestName)
332 try { $manifestHash = Stream-Hash $manifestStream } finally { $manifestStream.Dispose() }
333 Remove-MatchingFile $Target $manifestName $manifestHash
334 }
335 $directories = @()
336 foreach ($relative in $owned.Keys) {
337 $directory = Split-Path $relative -Parent
338 while ($directory) { $directories += $directory.Replace('\', '/'); $directory = Split-Path $directory -Parent }
339 }
340 $diagnosticStep = 'removing_program_directories'
341 Remove-EmptyDirectories $Target $directories
342 # A retained identity lets a later installation reuse this data-bearing folder.
343 $remaining = @(Get-ChildItem -LiteralPath $Target -Force | Where-Object Name -ne $identityName)
344 if (!$remaining.Count) {
345 if ($owned.ContainsKey($identityName)) { Remove-MatchingFile $Target $identityName $owned[$identityName] }
346 if (@(Get-ChildItem -LiteralPath $Target -Force).Count -eq 0) { [IO.Directory]::Delete($Target) }
347 } else { Write-Output ('用户新增或修改的文件已保留在 ' + $Target) }
348}