跳到主要内容

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

提交记录
修改desktop/Updates.swift+15 −3看文件
@@ -7,7 +7,11 @@ let cageUpdateBundleID = "io.github.lee-xeo.claude-cage"
77
88enum CageProfile {
99 static var clientOnly: Bool { Bundle.main.object(forInfoDictionaryKey: "CageClientOnly") as? Bool == true }
10新增: static var macGuestTrial: Bool { Bundle.main.bundleIdentifier == cageUpdateBundleID + ".macos-trial" }
1011 static func configURL() -> URL {
12新增: if macGuestTrial {
13新增: return FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".claude-cage/macos-trial/config.json")
14新增: }
1115 if let path = ProcessInfo.processInfo.environment["CLAUDE_CAGE_CONFIG"], !path.isEmpty {
1216 return URL(fileURLWithPath: path).standardizedFileURL
1317 }
@@ -269,6 +273,12 @@ final class CageAppUpdater {
269273 }
270274 }
271275 func handle(_ operation: String) -> [String: Any] {
276新增: if Bundle(url: bundleURL)?.bundleIdentifier == cageUpdateBundleID + ".macos-trial" {
277新增: if state["phase"] as? String != "manual" {
278新增: change(["phase": "manual", "message": "macOS 客机试用版通过本机安装更新。"])
279新增: }
280新增: return state
281新增: }
272282 if Bundle(url: bundleURL)?.object(forInfoDictionaryKey: "CageClientOnly") as? Bool == true {
273283 if state["phase"] as? String != "manual" || operation != "status" {
274284 change(["phase": "manual", "message": "轻量客户端使用独立安装包更新;连接配置会保留,云端任务不受影响。"])
@@ -276,6 +286,8 @@ final class CageAppUpdater {
276286 return state
277287 }
278288 let busy = ["checking", "downloading", "downloaded", "verifying", "installing"].contains(state["phase"] as? String ?? "")
289新增: if ["check", "install"].contains(operation), let value = state["retryAt"] as? String,
290新增: let date = ISO8601DateFormatter().date(from: value), date > Date() { return state }
279291 switch operation {
280292 case "status": break
281293 case "check": if !busy && worker == nil && validationTask == nil && installer == nil && prepared == nil { startDownload(checkOnly: true) }
@@ -332,11 +344,11 @@ final class CageAppUpdater {
332344 for (key, value) in values { state[key] = value }
333345 onChange(state)
334346 }
335删除: private func failure(_ message: String) { change(["phase": "failed", "message": message, "retryable": true]) }
347新增: private func failure(_ message: String, retryAt: String = "") { change(["phase": "failed", "message": message, "retryable": true, "retryAt": retryAt]) }
336348 private var cage: URL { bundleURL.appendingPathComponent("Contents/Resources/cage") }
337349 private func startDownload(checkOnly: Bool) {
338350 generation += 1; let operation = generation
339删除: change(["phase": "checking", "message": "正在通过所选代理检查更新", "receivedBytes": 0, "totalBytes": 0, "retryable": false])
351新增: change(["phase": "checking", "message": "正在通过所选代理检查更新", "receivedBytes": 0, "totalBytes": 0, "retryable": false, "retryAt": ""])
340352 let process = Process(); process.executableURL = cage; process.arguments = ["app-update", checkOnly ? "check" : "download"]
341353 let pipe = Pipe(); process.standardOutput = pipe; process.standardError = FileHandle.nullDevice
342354 worker = process
@@ -362,7 +374,7 @@ final class CageAppUpdater {
362374 if self.worker === process { self.worker = nil }
363375 guard self.generation == operation else { return }
364376 if process.terminationStatus != 0 {
365删除: self.failure(result?["message"] as? String ?? "更新请求未完成,请重试")
377新增: self.failure(result?["message"] as? String ?? "更新请求未完成,请重试", retryAt: result?["retryAt"] as? String ?? "")
366378 } else if !checkOnly, let result, result["phase"] as? String == "downloaded" {
367379 self.verifyDownload(result, operation: operation)
368380 }
修改desktop/UpdatesTests.swift+22 −0看文件
@@ -168,6 +168,28 @@ enum UpdatesTests {
168168 try expect(!updater.awaitingInitialWorkbench, "initialized workbench keeps ordinary quit confirmation")
169169 try expect(FileManager.default.fileExists(atPath: root.appendingPathComponent("profile/updates/launch-\(confirmation).json").path), "explicit workbench readiness writes installer acknowledgement")
170170
171新增: let probeBundle = root.appendingPathComponent("retry-protocol.app")
172新增: let resources = probeBundle.appendingPathComponent("Contents/Resources")
173新增: try CageUpdateFiles.privateDirectory(resources)
174新增: let countFile = root.appendingPathComponent("retry-invocations")
175新增: let retryAt = ISO8601DateFormatter().string(from: Date().addingTimeInterval(3600))
176新增: let script = "#!/bin/sh\nprintf x >> '\(countFile.path)'\nprintf '%s\\n' '{\"phase\":\"failed\",\"message\":\"limited\",\"retryable\":true,\"retryAt\":\"\(retryAt)\"}'\nexit 1\n"
177新增: let probe = resources.appendingPathComponent("cage")
178新增: try Data(script.utf8).write(to: probe)
179新增: try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: probe.path)
180新增: var received: [String: Any] = [:]
181新增: let limited = CageAppUpdater(bundleURL: probeBundle, onChange: { received = $0 }, quit: {}, reconnect: {})
182新增: _ = limited.handle("check")
183新增: let deadline = Date().addingTimeInterval(5)
184新增: while received["phase"] as? String != "failed" && Date() < deadline { _ = RunLoop.current.run(mode: .default, before: Date().addingTimeInterval(0.01)) }
185新增: // Drain the process-exit callback as well as the streamed failed state.
186新增: _ = RunLoop.current.run(mode: .default, before: Date().addingTimeInterval(0.1))
187新增: try expect(limited.handle("status")["retryAt"] as? String == retryAt, "native process-exit handling retained server retry deadline")
188新增: _ = limited.handle("check"); _ = limited.handle("install")
189新增: let invocationData = try Data(contentsOf: countFile)
190新增: try expect(String(data: invocationData, encoding: .utf8) == "x", "native menu or install bypassed cooldown")
191新增: print("PASS: native update failure retained retry deadline and blocked early check/install")
192新增:
171193 if CommandLine.arguments.count == 2 {
172194 let signed = URL(fileURLWithPath: CommandLine.arguments[1])
173195 let team = try CageUpdateFiles.signingInfo(signed, bundle: true)
修改desktop/windows.tests/Cage.Windows.Tests.csproj+6 −0看文件
@@ -6,8 +6,14 @@
66 <ImplicitUsings>enable</ImplicitUsings>
77 </PropertyGroup>
88 <ItemGroup>
9新增: <EmbeddedResource Include="../../packaging/windows/installation-files.ps1" LogicalName="Cage.InstallationFiles.ps1" />
10新增: <EmbeddedResource Include="../../packaging/windows/verified-file-deletion.cs" LogicalName="Cage.VerifiedFileDeletion.cs" />
911 <Compile Include="../windows/UpdatePolicy.cs" Link="UpdatePolicy.cs" />
1012 <Compile Include="../windows/Backend.cs" Link="Backend.cs" />
1113 <Compile Include="../windows/UpdateRecovery.cs" Link="UpdateRecovery.cs" />
14新增: <Compile Include="../windows/AppUpdater.cs" Link="AppUpdater.cs" />
15新增: <Compile Include="../windows/UpdateInstaller.cs" Link="UpdateInstaller.cs" />
16新增: <Compile Include="../windows/Authenticode.cs" Link="Authenticode.cs" />
17新增: <Compile Include="../windows/WindowLayout.cs" Link="WindowLayout.cs" />
1218 </ItemGroup>
1319</Project>
修改desktop/windows.tests/Program.cs+103 −2看文件
@@ -1,5 +1,12 @@
11using Cage.Windows;
22
3新增:if (args is ["app-update", "check" or "download"])
4新增:{
5新增: File.AppendAllText(Path.Combine(Backend.Root, "retry-invocations"), "x");
6新增: Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(new { phase = "failed", message = "limited", retryable = true, retryAt = Environment.GetEnvironmentVariable("CAGE_UPDATE_RETRY_AT") }));
7新增: Environment.Exit(1);
8新增:}
9新增:
310// The recovery integration tests launch a copy of this executable through the
411// same subprocess/JSON boundary used by the shipped updater.
512if (args is ["prepare-update", "--json", "--stop"])
@@ -23,6 +30,26 @@ void Reject(Action action, string message)
2330 try { action(); } catch (InvalidDataException) { return; }
2431 throw new Exception(message);
2532}
33新增:foreach (var (work, dpi) in new[] {
34新增: (new System.Drawing.Rectangle(0, 0, 3840, 2080), 96),
35新增: (new System.Drawing.Rectangle(0, 0, 3840, 2080), 192),
36新增: (new System.Drawing.Rectangle(0, 0, 1920, 1040), 144),
37新增: (new System.Drawing.Rectangle(0, 0, 1366, 728), 96),
38新增: (new System.Drawing.Rectangle(-1920, 0, 1920, 1040), 96),
39新增: (new System.Drawing.Rectangle(0, 0, 1280, 680), 192),
40新增:})
41新增:{
42新增: var bounds = WindowLayout.Bounds(work, dpi, null);
43新增: Check(work.Contains(bounds), "initial window extends beyond the monitor work area");
44新增: Check(bounds.Width >= WindowLayout.Minimum(work, dpi).Width, "initial window is below its DPI-aware minimum");
45新增: var restored = WindowLayout.Bounds(work, dpi, new WindowPlacement(5000, 3000, 5000, 4000, 96, false));
46新增: Check(work.Contains(restored), "saved window is inaccessible after a monitor or DPI change");
47新增:}
48新增:Check(WindowLayout.Bounds(new(0, 0, 3840, 2080), 96, null).Width > 2500, "4K window stayed at a fixed 1280 pixels");
49新增:Check(WindowLayout.Bounds(new(0, 0, 3840, 2080), 192, new(100, 100, 1000, 700, 96, false)).Width == 2000,
50新增: "restoring a user size did not account for the new monitor DPI");
51新增:Console.WriteLine($"Windows window layout: {assertions} assertions passed.");
52新增:assertions = 0;
2653Check(UpdatePolicy.IsWorkbench("http://localhost:4321/", 4321), "expected local origin rejected");
2754foreach (var origin in new[] { "https://localhost:4321/", "http://localhost:4322/", "http://localhost.evil:4321/", "http://user@localhost:4321/", "http://127.0.0.1:4321/", "file:///C:/workbench.html" })
2855 Check(!UpdatePolicy.IsWorkbench(origin, 4321), "foreign native bridge origin accepted: " + origin);
@@ -43,7 +70,7 @@ foreach (var path in new[] { Path.Combine(root + "-other", "download-abc", "Cage
4370 Reject(() => UpdatePolicy.DownloadPath(path, root), "untrusted download path accepted: " + path);
4471Console.WriteLine($"Windows update/bridge policy: {assertions} assertions passed.");
4572
46删除:var integration = Path.Combine(Path.GetTempPath(), "cage-recovery-" + Guid.NewGuid());
73新增:var integration = Path.Combine(OperatingSystem.IsMacOS() ? "/private/tmp" : Path.GetTempPath(), "cage-recovery-" + Guid.NewGuid());
4774Directory.CreateDirectory(integration);
4875var savedProfile = Environment.GetEnvironmentVariable("CLAUDE_CAGE_CONFIG");
4976try
@@ -63,6 +90,49 @@ try
6390 if (broken) File.WriteAllText(Path.Combine(resources, "broken-backend"), "cannot start");
6491 }
6592 InstallFixture(backup, false); InstallFixture(candidate, true);
93新增: var snapshotSource = Path.Combine(integration, "snapshot source");
94新增: var snapshotTarget = Path.Combine(integration, "snapshot target");
95新增: Directory.CreateDirectory(Path.Combine(snapshotSource, "my-project"));
96新增: File.WriteAllText(Path.Combine(snapshotSource, "program.txt"), "program");
97新增: File.WriteAllText(Path.Combine(snapshotSource, "my-project", "work.txt"), "personal data");
98新增: File.WriteAllText(Path.Combine(snapshotSource, "Cage.install-files.json"), System.Text.Json.JsonSerializer.Serialize(new {
99新增: version = 1, files = new[] { new { path = "program.txt", sha256 = new string('a', 64) } },
100新增: }));
101新增: var copyTree = typeof(UpdateInstaller).GetMethod("CopyTree", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static)!;
102新增: copyTree.Invoke(null, [snapshotSource, snapshotTarget]);
103新增: Check(File.ReadAllText(Path.Combine(snapshotTarget, "program.txt")) == "program", "update snapshot missed a declared program file");
104新增: Check(!Directory.Exists(Path.Combine(snapshotTarget, "my-project")), "update snapshot copied live user data into the program rollback snapshot");
105新增: Check(File.ReadAllText(Path.Combine(snapshotSource, "my-project", "work.txt")) == "personal data", "snapshot changed personal data");
106新增: var nestedSnapshot = Path.Combine(snapshotSource, "updates", "backup");
107新增: var rejectedNestedSnapshot = false;
108新增: try { copyTree.Invoke(null, [snapshotSource, nestedSnapshot]); }
109新增: catch (System.Reflection.TargetInvocationException error) when (error.InnerException is InvalidDataException) { rejectedNestedSnapshot = true; }
110新增: Check(rejectedNestedSnapshot, "snapshot recursively copied its own output");
111新增: Check(!Directory.Exists(nestedSnapshot), "overlapping snapshot destination was created before validation");
112新增: var ensureComplete = typeof(UpdateInstaller).GetMethod("EnsureInstallationComplete", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static)!;
113新增: ensureComplete.Invoke(null, [snapshotSource]);
114新增: var recoveryReceipt = snapshotSource + ".cage-installation.json";
115新增: File.WriteAllText(recoveryReceipt, System.Text.Json.JsonSerializer.Serialize(new { stagePath = candidate, backupPath = backup }));
116新增: string? pendingRecovery = null;
117新增: try { ensureComplete.Invoke(null, [snapshotSource]); }
118新增: catch (System.Reflection.TargetInvocationException error) when (error.InnerException is IOException) { pendingRecovery = error.InnerException.Message; }
119新增: Check(pendingRecovery != null, "updater accepted a partially restored installation");
120新增: Check(pendingRecovery!.Contains(candidate) && pendingRecovery.Contains(backup), "recovery error omitted the preserved directories");
121新增: Check(File.Exists(recoveryReceipt), "recovery validation removed the persistent receipt");
122新增: File.Delete(recoveryReceipt);
123新增: var rejectedMissingInstallation = false;
124新增: try { ensureComplete.Invoke(null, [Path.Combine(integration, "missing installation")]); }
125新增: catch (System.Reflection.TargetInvocationException error) when (error.InnerException is IOException) { rejectedMissingInstallation = true; }
126新增: Check(rejectedMissingInstallation, "updater accepted a missing installation and could restore a program-only snapshot");
127新增: if (!OperatingSystem.IsWindows())
128新增: {
129新增: File.Delete(Path.Combine(snapshotSource, "Cage.install-files.json"));
130新增: Directory.CreateSymbolicLink(Path.Combine(snapshotSource, "external-link"), Path.Combine(snapshotSource, "my-project"));
131新增: var legacySnapshot = Path.Combine(integration, "legacy snapshot");
132新增: copyTree.Invoke(null, [snapshotSource, legacySnapshot]);
133新增: Check(File.ReadAllText(Path.Combine(legacySnapshot, "my-project", "work.txt")) == "personal data", "legacy snapshot missed a regular file");
134新增: Check(!Directory.Exists(Path.Combine(legacySnapshot, "external-link")), "legacy snapshot followed a user link");
135新增: }
66136 await UpdateRecovery.PrepareRollback(backup);
67137 Check(File.Exists(Path.Combine(backup, "resources", "controller-invoked")), "recovery did not execute the old backend");
68138 Check(!File.Exists(Path.Combine(candidate, "resources", "controller-invoked")), "recovery executed the broken candidate backend");
@@ -92,7 +162,38 @@ try
92162 locked?.Dispose();
93163 if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(garbage, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
94164 }
95删除: Console.WriteLine($"Windows recovery integration: {assertions - 22} assertions passed; actual child process and filesystem failures exercised.");
165新增: Console.WriteLine($"Windows snapshot/recovery integration: {assertions - 22} assertions passed; actual child process and filesystem failures exercised.");
166新增:
167新增: // Exercise the production updater's streamed state and process-exit path.
168新增: var nativeResources = Path.Combine(AppContext.BaseDirectory, "resources");
169新增: if (Directory.Exists(nativeResources)) throw new IOException("retry fixture requires an unused test resources directory");
170新增: Directory.CreateDirectory(nativeResources);
171新增: var savedRetry = Environment.GetEnvironmentVariable("CAGE_UPDATE_RETRY_AT");
172新增: try
173新增: {
174新增: foreach (var file in Directory.EnumerateFiles(AppContext.BaseDirectory)) File.Copy(file, Path.Combine(nativeResources, Path.GetFileName(file)));
175新增: var executable = Path.Combine(nativeResources, "cage.exe");
176新增: File.Copy(Environment.ProcessPath!, executable, true);
177新增: if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(executable, File.GetUnixFileMode(Environment.ProcessPath!));
178新增: var retryAt = DateTimeOffset.UtcNow.AddHours(1).ToString("yyyy-MM-dd'T'HH:mm:ss'Z'");
179新增: Directory.CreateDirectory(Backend.Root);
180新增: Environment.SetEnvironmentVariable("CAGE_UPDATE_RETRY_AT", retryAt);
181新增: var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
182新增: var failures = 0;
183新增: using var updater = new AppUpdater(state => { if (state.GetValueOrDefault("phase") as string == "failed" && Interlocked.Increment(ref failures) == 2) completion.TrySetResult(); }, () => throw new Exception("unexpected installation"), () => {});
184新增: updater.Handle("check");
185新增: await completion.Task.WaitAsync(TimeSpan.FromSeconds(5));
186新增: Check(updater.Handle("status").GetValueOrDefault("retryAt") as string == retryAt, "process-exit path lost retry deadline");
187新增: updater.Handle("check"); updater.Handle("install");
188新增: await Task.Delay(100);
189新增: Check(File.ReadAllText(Path.Combine(Backend.Root, "retry-invocations")) == "x", "native check/install bypassed server cooldown");
190新增: Console.WriteLine("Windows updater protocol: real subprocess preserved deadline; early check/install blocked.");
191新增: }
192新增: finally
193新增: {
194新增: Environment.SetEnvironmentVariable("CAGE_UPDATE_RETRY_AT", savedRetry);
195新增: Directory.Delete(nativeResources, true);
196新增: }
96197}
97198finally {
98199 Environment.SetEnvironmentVariable("CLAUDE_CAGE_CONFIG", savedProfile);
修改desktop/windows/AppUpdater.cs+9 −3看文件
@@ -1,4 +1,5 @@
11using System.Diagnostics;
2新增:using System.Globalization;
23using System.Reflection;
34using System.Security.Cryptography;
45using System.Text.Json;
@@ -40,6 +41,9 @@ internal sealed class AppUpdater : IDisposable
4041 Change("manual", "轻量客户端使用独立安装包更新;连接配置会保留,云端任务不受影响。");
4142 return new(state);
4243 }
44新增: if (operation is "check" or "install" &&
45新增: DateTimeOffset.TryParse(state.GetValueOrDefault("retryAt") as string, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var retryAt) && retryAt > DateTimeOffset.UtcNow)
46新增: return new(state);
4347 switch (operation)
4448 {
4549 case "status": break;
@@ -51,9 +55,9 @@ internal sealed class AppUpdater : IDisposable
5155 return new(state);
5256 }
5357
54删除: private void Change(string phase, string message, bool retryable = false)
58新增: private void Change(string phase, string message, bool retryable = false, string retryAt = "")
5559 {
56删除: state["phase"] = phase; state["message"] = message; state["retryable"] = retryable; changed(new(state));
60新增: state["phase"] = phase; state["message"] = message; state["retryable"] = retryable; state["retryAt"] = retryAt; changed(new(state));
5761 }
5862
5963 public void MarkReady()
@@ -71,6 +75,7 @@ internal sealed class AppUpdater : IDisposable
7175 var token = cancellation.Token;
7276 Change("checking", "正在通过所选代理检查更新");
7377 string? archive = null;
78新增: string retryAt = "";
7479 using var process = new Process { StartInfo = Backend.StartInfo(Backend.Executable, "app-update", checkOnly ? "check" : "download") };
7580 var started = false;
7681 try
@@ -84,6 +89,7 @@ internal sealed class AppUpdater : IDisposable
8489 {
8590 if (line.Length > 65536) throw new IOException("更新响应超过允许大小");
8691 last = JsonDocument.Parse(line).RootElement.Clone();
92新增: retryAt = last.Text("retryAt");
8793 foreach (var property in last.EnumerateObject())
8894 if (property.Name is not ("archivePath" or "sha256")) state[property.Name] = property.Value.ValueKind switch {
8995 JsonValueKind.String => property.Value.GetString(),
@@ -110,7 +116,7 @@ internal sealed class AppUpdater : IDisposable
110116 Change("ready", "更新已下载并验证,可安装重启", true);
111117 }
112118 catch (OperationCanceledException) { Change("failed", "更新已暂停,可稍后重试", true); }
113删除: catch (Exception error) { Change("failed", error.Message, true); }
119新增: catch (Exception error) { Change("failed", error.Message, true, retryAt); }
114120 finally
115121 {
116122 if (started && !process.HasExited) process.Kill();
修改desktop/windows/Cage.Windows.csproj+3 −0看文件
@@ -3,6 +3,7 @@
33 <OutputType>WinExe</OutputType>
44 <TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
55 <UseWindowsForms>true</UseWindowsForms>
6新增: <ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode>
67 <EnableWindowsTargeting>true</EnableWindowsTargeting>
78 <RuntimeIdentifier>win-x64</RuntimeIdentifier>
89 <SelfContained>true</SelfContained>
@@ -21,6 +22,8 @@
2122 </PropertyGroup>
2223 <ItemGroup>
2324 <PackageReference Include="Microsoft.Web.WebView2" Version="1.0.4314.35" />
25新增: <EmbeddedResource Include="../../packaging/windows/installation-files.ps1" LogicalName="Cage.InstallationFiles.ps1" />
26新增: <EmbeddedResource Include="../../packaging/windows/verified-file-deletion.cs" LogicalName="Cage.VerifiedFileDeletion.cs" />
2427 </ItemGroup>
2528 <Target Name="RemoveUnusedWebView2WpfReference" BeforeTargets="ResolveAssemblyReferences">
2629 <ItemGroup><Reference Remove="@(Reference)" Condition="'%(Reference.Filename)' == 'Microsoft.Web.WebView2.Wpf'" /></ItemGroup>
修改desktop/windows/UpdateInstaller.cs+126 −9看文件
@@ -6,6 +6,8 @@ namespace Cage.Windows;
66
77internal static class UpdateInstaller
88{
9新增: [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
10新增: private static extern int MessageBoxW(IntPtr owner, string text, string title, uint flags);
911 public static void VerifyArchive(string path, string hash, string version, string publisher)
1012 {
1113 UpdatePolicy.DownloadPath(path, AppUpdater.Root); UpdatePolicy.PlainPath(path);
@@ -60,6 +62,7 @@ internal static class UpdateInstaller
6062 if (Directory.Exists(backup)) throw new IOException("更新备份目录已存在");
6163 // Preparation is reversible and completes before the controller stops.
6264 CopyTree(plan.Target, backup);
65新增: Authenticode.SamePublisher(UpdateRecovery.BackendPath(backup), ownPublisher);
6366 Console.WriteLine("READY"); await Console.Out.FlushAsync();
6467 if (await Console.In.ReadLineAsync(inputTimeout.Token) != "COMMIT") return 1;
6568 committed = true;
@@ -78,6 +81,7 @@ internal static class UpdateInstaller
7881 catch (TimeoutException) { if (!installer.HasExited) installer.Kill(true); await installer.WaitForExitAsync(); throw; }
7982 if (installer.ExitCode != 0) throw new IOException("Windows 安装程序未完成安装");
8083 }
84新增: EnsureInstallationComplete(plan.Target);
8185 Authenticode.SamePublisher(original, ownPublisher);
8286 if (FileVersionInfo.GetVersionInfo(original).ProductVersion != plan.Version)
8387 throw new IOException("安装后版本不匹配");
@@ -114,10 +118,16 @@ internal static class UpdateInstaller
114118 {
115119 if (succeeded) return 0;
116120 var detail = error.Message;
121新增: var recoveryIncomplete = false;
117122 if (replaced && plan != null && backup != null)
118123 {
119124 try
120125 {
126新增: // NSIS and this helper both require a newly created named
127新增: // object and retain its handle for the entire transaction.
128新增: using var installationLock = new Mutex(false, "Global\\Cage.Installation", out var ownsInstallation);
129新增: if (!ownsInstallation) throw new IOException("另一个安装或卸载正在进行,已保留更新备份,请等待完成后恢复。");
130新增: EnsureInstallationComplete(plan.Target);
121131 // Stop the exact new controller through its lifecycle API before
122132 // restoring files. Never kill other Cage instances by name.
123133 Authenticode.SamePublisher(UpdateRecovery.BackendPath(backup), plan.Publisher);
@@ -126,18 +136,39 @@ internal static class UpdateInstaller
126136 var restored = plan.Target + ".restore-" + plan.Confirmation;
127137 var failed = plan.Target + ".failed-" + plan.Confirmation;
128138 CopyTree(backup, restored);
129删除: var hadCandidate = Directory.Exists(plan.Target);
130删除: if (hadCandidate) Directory.Move(plan.Target, failed);
131删除: try { Directory.Move(restored, plan.Target); }
132删除: catch { if (hadCandidate) Directory.Move(failed, plan.Target); throw; }
139新增: var receipt = plan.Target + ".cage-installation.json";
140新增: await PreserveFiles("prepare", plan.Target, restored, receipt, failed);
141新增: Directory.Move(plan.Target, failed);
142新增: try
143新增: {
144新增: await PreserveFiles("move", failed, restored, receipt);
145新增: Directory.Move(restored, plan.Target);
146新增: }
147新增: catch
148新增: {
149新增: await PreserveFiles("restore", restored, failed, receipt);
150新增: Directory.Move(failed, plan.Target);
151新增: await PreserveFiles("complete", "", plan.Target, receipt);
152新增: throw;
153新增: }
154新增: await PreserveFiles("cleanup", failed, plan.Target, receipt);
155新增: EnsureInstallationComplete(plan.Target);
133156 UpdateRecovery.CleanupDirectory(backup); backup = null;
134157 Result(false, "更新未完成,已恢复原应用:" + detail);
135158 Process.Start(new ProcessStartInfo(Path.Combine(plan.Target, "Cage.exe")) { UseShellExecute = false, WorkingDirectory = plan.Target });
136159 return 1;
137160 }
138删除: catch (Exception recovery) { detail += ";自动恢复未完成,原应用备份已保留:" + recovery.Message; }
161新增: catch (Exception recovery)
162新增: {
163新增: recoveryIncomplete = true;
164新增: detail += "。自动恢复未完成。" + recovery.Message;
165新增: if (File.Exists(plan.Target + ".cage-installation.json"))
166新增: detail += "。恢复目录记录在 " + plan.Target + ".cage-installation.json";
167新增: if (backup != null) detail += "。程序备份保留在 " + backup;
168新增: }
139169 }
140170 Result(false, "更新未完成:" + detail);
171新增: if (recoveryIncomplete && OperatingSystem.IsWindows()) MessageBoxW(IntPtr.Zero, detail, "Cage 更新需要恢复", 0x00010010);
141172 if (committed && !replaced && plan != null)
142173 {
143174 try
@@ -170,18 +201,104 @@ internal static class UpdateInstaller
170201 catch (UnauthorizedAccessException) { }
171202 }
172203
204新增: private static void EnsureInstallationComplete(string target)
205新增: {
206新增: var receipt = target + ".cage-installation.json";
207新增: if (!File.Exists(receipt) && Directory.Exists(target)) return;
208新增: var message = "安装目录或个人文件仍需恢复,已停止自动启动。请保留并检查 " + receipt;
209新增: if (File.Exists(receipt) && new FileInfo(receipt).Length <= 16 * 1024 * 1024)
210新增: {
211新增: try
212新增: {
213新增: using var document = JsonDocument.Parse(File.ReadAllText(receipt));
214新增: foreach (var name in new[] { "stagePath", "backupPath" })
215新增: if (document.RootElement.Text(name) is { Length: > 0 } path) message += "。保留目录 " + path;
216新增: }
217新增: catch (Exception error) when (error is IOException or JsonException or InvalidOperationException) { }
218新增: }
219新增: throw new IOException(message);
220新增: }
221新增:
222新增: private static async Task PreserveFiles(string operation, string source, string target, string receipt, string? backupPath = null)
223新增: {
224新增: var directory = receipt + ".helper-" + Guid.NewGuid().ToString("N");
225新增: Directory.CreateDirectory(directory);
226新增: var script = Path.Combine(directory, "installation-files.ps1");
227新增: try
228新增: {
229新增: await using (var resource = typeof(UpdateInstaller).Assembly.GetManifestResourceStream("Cage.InstallationFiles.ps1")
230新增: ?? throw new IOException("缺少安装文件保留组件"))
231新增: await using (var output = File.Create(script)) { await resource.CopyToAsync(output); }
232新增: await using (var resource = typeof(UpdateInstaller).Assembly.GetManifestResourceStream("Cage.VerifiedFileDeletion.cs")
233新增: ?? throw new IOException("缺少安装文件校验组件"))
234新增: await using (var output = File.Create(Path.Combine(directory, "verified-file-deletion.cs"))) { await resource.CopyToAsync(output); }
235新增: using var deadline = new CancellationTokenSource(TimeSpan.FromMinutes(10));
236新增: var executable = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "WindowsPowerShell", "v1.0", "powershell.exe");
237新增: var arguments = new List<string> { "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", script,
238新增: "-Operation", operation, "-Source", source, "-Target", target, "-Receipt", receipt, "-LegacyTarget" };
239新增: if (backupPath != null) { arguments.Add("-Backup"); arguments.Add(backupPath); }
240新增: using var process = new Process { StartInfo = Backend.StartInfo(executable, arguments.ToArray()) };
241新增: if (!process.Start()) throw new IOException("无法启动安装文件保留组件");
242新增: using var abort = deadline.Token.Register(() => { try { if (!process.HasExited) process.Kill(); } catch (InvalidOperationException) { } });
243新增: var outputText = Backend.ReadLimited(process.StandardOutput, 65536, deadline.Token);
244新增: var errorText = Backend.ReadLimited(process.StandardError, 65536, deadline.Token);
245新增: await process.WaitForExitAsync(deadline.Token);
246新增: await outputText;
247新增: var error = await errorText;
248新增: if (process.ExitCode != 0) throw new IOException("安装文件保留未完成:" + error.Trim());
249新增: }
250新增: finally
251新增: {
252新增: UpdateRecovery.CleanupDirectory(directory);
253新增: }
254新增: }
255新增:
173256 private static void CopyTree(string source, string target)
174257 {
175删除: UpdatePolicy.PlainPath(source); Directory.CreateDirectory(target);
258新增: source = Path.GetFullPath(source).TrimEnd(Path.DirectorySeparatorChar);
259新增: target = Path.GetFullPath(target).TrimEnd(Path.DirectorySeparatorChar);
260新增: var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
261新增: if (string.Equals(source, target, comparison) || target.StartsWith(source + Path.DirectorySeparatorChar, comparison))
262新增: throw new InvalidDataException("更新备份目录位于程序目录内,无法安全备份。请使用完整安装包手动更新。");
263新增: UpdatePolicy.PlainPath(source); UpdatePolicy.PlainPath(target); Directory.CreateDirectory(target);
264新增: HashSet<string>? owned = null;
265新增: var manifest = Path.Combine(source, "Cage.install-files.json");
266新增: if (File.Exists(manifest) && (File.GetAttributes(manifest) & FileAttributes.ReparsePoint) == 0)
267新增: {
268新增: try
269新增: {
270新增: using var document = JsonDocument.Parse(File.ReadAllText(manifest));
271新增: if (document.RootElement.GetProperty("version").GetInt32() == 1)
272新增: {
273新增: var paths = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
274新增: foreach (var entry in document.RootElement.GetProperty("files").EnumerateArray())
275新增: {
276新增: var path = entry.GetProperty("path").GetString();
277新增: var digest = entry.GetProperty("sha256").GetString();
278新增: if (string.IsNullOrEmpty(path) || path.StartsWith('/') || path.Contains('\\') || path.Contains(':') ||
279新增: path.Split('/').Any(part => part is "." or "..") || digest?.Length != 64 || !digest.All(char.IsAsciiHexDigit))
280新增: throw new JsonException("Invalid installation file record");
281新增: paths.Add(path);
282新增: }
283新增: if (paths.Count > 0) { paths.Add("Cage.install-files.json"); owned = paths; }
284新增: }
285新增: }
286新增: catch (Exception error) when (error is IOException or JsonException or InvalidOperationException or KeyNotFoundException or FormatException) { }
287新增: }
176288 long size = 0; var count = 0;
177289 var pending = new Queue<string>(); pending.Enqueue(source);
178290 while (pending.TryDequeue(out var directory))
179291 foreach (var entry in Directory.EnumerateFileSystemEntries(directory))
180292 {
181293 var attributes = File.GetAttributes(entry);
182删除: if (++count > 100000 || (attributes & FileAttributes.ReparsePoint) != 0)
183删除: throw new IOException("安装目录包含联接或过多文件,无法安全备份");
184删除: var destination = Path.Combine(target, Path.GetRelativePath(source, entry));
294新增: if (++count > 100000) throw new IOException("安装目录文件过多,无法安全备份");
295新增: // User links remain in the installed tree. NSIS and rollback move
296新增: // them with their user subtree, preserving link identity and targets.
297新增: if ((attributes & FileAttributes.ReparsePoint) != 0) continue;
298新增: var relative = Path.GetRelativePath(source, entry);
299新增: var key = relative.Replace(Path.DirectorySeparatorChar, '/');
300新增: if (owned != null && !owned.Contains(key) && !owned.Any(path => path.StartsWith(key + "/", StringComparison.OrdinalIgnoreCase))) continue;
301新增: var destination = Path.Combine(target, relative);
185302 if ((attributes & FileAttributes.Directory) != 0) { Directory.CreateDirectory(destination); pending.Enqueue(entry); }
186303 else
187304 {
新增internal/appupdate/retry.go+48 −0看文件
@@ -0,0 +1,48 @@
1新增:package appupdate
2新增:
3新增:import (
4新增: "errors"
5新增: "net/http"
6新增: "strconv"
7新增: "strings"
8新增: "time"
9新增:)
10新增:
11新增:type retryError struct{ at time.Time }
12新增:
13新增:func (e *retryError) Error() string { return "更新源请求受限,请稍后重试" }
14新增:func (e *retryError) RetryAt() time.Time { return e.at }
15新增:
16新增:func (s *State) fail(err error) {
17新增: s.Phase, s.Message, s.Retryable, s.RetryAt = "failed", err.Error(), true, ""
18新增: var delayed interface{ RetryAt() time.Time }
19新增: if errors.As(err, &delayed) {
20新增: s.RetryAt = delayed.RetryAt().UTC().Format(time.RFC3339)
21新增: }
22新增:}
23新增:
24新增:func updateSourceError(resp *http.Response, now time.Time) error {
25新增: after := strings.TrimSpace(resp.Header.Get("Retry-After"))
26新增: exhausted := strings.TrimSpace(resp.Header.Get("X-RateLimit-Remaining")) == "0"
27新增: if resp.StatusCode == http.StatusForbidden && after == "" && !exhausted {
28新增: return errors.New("更新源拒绝访问(HTTP 403),请检查所选代理或稍后重试")
29新增: }
30新增: var at time.Time
31新增: if seconds, err := strconv.ParseInt(after, 10, 64); err == nil && seconds >= 0 && seconds <= int64((1<<63-1)/time.Second) {
32新增: at = now.Add(time.Duration(seconds) * time.Second)
33新增: } else if date, err := http.ParseTime(after); err == nil {
34新增: at = date
35新增: }
36新增: if exhausted {
37新增: // Unix seconds through 9999-12-31 fit the RFC3339 native bridge field.
38新增: if seconds, err := strconv.ParseInt(resp.Header.Get("X-RateLimit-Reset"), 10, 64); err == nil && seconds > 0 && seconds <= 253402300799 {
39新增: if reset := time.Unix(seconds, 0); reset.After(at) {
40新增: at = reset
41新增: }
42新增: }
43新增: }
44新增: if !at.After(now) {
45新增: at = now.Add(5 * time.Minute)
46新增: }
47新增: return &retryError{at: at}
48新增:}
新增internal/appupdate/retry_test.go+69 −0看文件
@@ -0,0 +1,69 @@
1新增:package appupdate
2新增:
3新增:import (
4新增: "context"
5新增: "encoding/json"
6新增: "errors"
7新增: "fmt"
8新增: "io"
9新增: "net/http"
10新增: "strconv"
11新增: "strings"
12新增: "testing"
13新增: "time"
14新增:)
15新增:
16新增:func TestUpdateSourceRetryInstructions(t *testing.T) {
17新增: now := time.Now().UTC().Truncate(time.Second)
18新增: for _, tc := range []struct {
19新增: name string
20新增: status int
21新增: headers http.Header
22新增: wait time.Duration
23新增: }{
24新增: {"seconds", 429, http.Header{"Retry-After": {"3600"}}, time.Hour},
25新增: {"date", 429, http.Header{"Retry-After": {now.Add(2 * time.Hour).Format(http.TimeFormat)}}, 2 * time.Hour},
26新增: {"primary", 403, http.Header{"X-Ratelimit-Remaining": {"0"}, "X-Ratelimit-Reset": {strconv.FormatInt(now.Add(time.Hour).Unix(), 10)}}, time.Hour},
27新增: {"both", 429, http.Header{"Retry-After": {"60"}, "X-Ratelimit-Remaining": {"0"}, "X-Ratelimit-Reset": {strconv.FormatInt(now.Add(time.Hour).Unix(), 10)}}, time.Hour},
28新增: {"malformed", 429, http.Header{"Retry-After": {"9999999999999999999999"}}, 5 * time.Minute},
29新增: {"past", 429, http.Header{"Retry-After": {now.Add(-time.Hour).Format(http.TimeFormat)}}, 5 * time.Minute},
30新增: {"forbidden", 403, nil, 0},
31新增: {"remaining", 403, http.Header{"X-Ratelimit-Remaining": {"10"}, "X-Ratelimit-Reset": {strconv.FormatInt(now.Add(time.Hour).Unix(), 10)}}, 0},
32新增: } {
33新增: t.Run(tc.name, func(t *testing.T) {
34新增: client := &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
35新增: return &http.Response{StatusCode: tc.status, Header: tc.headers, Body: io.NopCloser(strings.NewReader("private response must stay out of errors")), Request: r}, nil
36新增: })}
37新增: _, err := findRelease(context.Background(), client, "0.1.0")
38新增: if err == nil || strings.Contains(err.Error(), "private response") {
39新增: t.Fatalf("unsafe error: %v", err)
40新增: }
41新增: var delayed interface{ RetryAt() time.Time }
42新增: if tc.wait == 0 {
43新增: if errors.As(err, &delayed) || !strings.Contains(err.Error(), "403") {
44新增: t.Fatalf("ordinary forbidden misclassified: %v", err)
45新增: }
46新增: return
47新增: }
48新增: if !errors.As(err, &delayed) {
49新增: t.Fatalf("retry deadline lost: %v", err)
50新增: }
51新增: if delta := delayed.RetryAt().Sub(now.Add(tc.wait)); delta < -time.Second || delta > 5*time.Second {
52新增: t.Fatalf("wrong retry deadline: %s", delayed.RetryAt())
53新增: }
54新增: state := State{}
55新增: state.fail(fmt.Errorf("wrapped: %w", err))
56新增: data, _ := json.Marshal(state)
57新增: var wire map[string]any
58新增: _ = json.Unmarshal(data, &wire)
59新增: if wire["retryAt"] != delayed.RetryAt().UTC().Format(time.RFC3339) {
60新增: t.Fatalf("native protocol lost deadline: %s", data)
61新增: }
62新增: state.fail(errors.New("unrelated failure"))
63新增: data, _ = json.Marshal(state)
64新增: if !strings.Contains(string(data), `"retryAt":""`) {
65新增: t.Fatalf("stale deadline retained by merging native bridge: %s", data)
66新增: }
67新增: })
68新增: }
69新增:}
修改internal/appupdate/update.go+21 −7看文件
@@ -21,8 +21,10 @@ import (
2121 "time"
2222
2323 "github.com/sylvinus/agent-vm/internal/cage"
24新增: "github.com/sylvinus/agent-vm/internal/diagnostics"
2425 "github.com/sylvinus/agent-vm/internal/host"
2526 "github.com/sylvinus/agent-vm/internal/managedproxy"
27新增: "github.com/sylvinus/agent-vm/internal/usererror"
2628 "github.com/sylvinus/agent-vm/internal/version"
2729 "golang.org/x/mod/semver"
2830)
@@ -61,10 +63,15 @@ type State struct {
6163 TotalBytes int64 `json:"totalBytes,omitempty"`
6264 Message string `json:"message,omitempty"`
6365 Retryable bool `json:"retryable,omitempty"`
66新增: RetryAt string `json:"retryAt"`
6467 ArchivePath string `json:"archivePath,omitempty"`
6568 SHA256 string `json:"sha256,omitempty"`
6669}
6770
71新增:type proxyUnavailableError struct{ message string }
72新增:
73新增:func (e *proxyUnavailableError) Error() string { return e.message }
74新增:
6875// Run only accepts fixed operations. URLs and destinations come from the
6976// verified repository response and the current private profile.
7077func Run(configPath string, args []string, output io.Writer) int {
@@ -72,7 +79,14 @@ func Run(configPath string, args []string, output io.Writer) int {
7279 state := State{CurrentVersion: version.Version}
7380 emit := func() { _ = enc.Encode(state) }
7481 fail := func(err error) int {
75删除: state.Phase, state.Message, state.Retryable = "failed", err.Error(), true
82新增: var unavailable *proxyUnavailableError
83新增: if len(args) == 1 && args[0] == "check" && errors.As(err, &unavailable) {
84新增: state.Phase, state.Message, state.Retryable = "waiting", err.Error(), true
85新增: emit()
86新增: return 0
87新增: }
88新增: _ = diagnostics.New(filepath.Dir(configPath)).Record("warn", "app-update", fmt.Sprintf("%v; cause=%v", err, errors.Unwrap(err)))
89新增: state.fail(err)
7690 emit()
7791 return 1
7892 }
@@ -156,10 +170,10 @@ func managedClient(ctx context.Context, configPath string) (*http.Client, error)
156170 profile := filepath.Dir(configPath)
157171 p, err := managedproxy.Applied(profile, cfg.ProxyURL, cfg.ProxyRevision)
158172 if err != nil {
159删除: return nil, errors.New("所选代理尚未应用,请在网络与代理中配置后重试")
173新增: return nil, &proxyUnavailableError{"所选代理尚未应用,更新检查将在代理就绪后重试"}
160174 }
161175 if !managedproxy.Running(ctx, profile, p) {
162删除: return nil, errors.New("所选代理未运行,请在网络与代理中启动后重试;更新不会改用主机直连")
176新增: return nil, &proxyUnavailableError{"所选代理未运行,更新检查将在代理就绪后重试;更新不会改用主机直连"}
163177 }
164178 egress, err := cage.NewEgress(cfg)
165179 if err != nil {
@@ -208,18 +222,18 @@ func request(ctx context.Context, client *http.Client, raw string) (*http.Respon
208222 }
209223 resp, err := client.Do(req)
210224 if err != nil {
211删除: if ctx.Err() != nil {
225新增: if errors.Is(ctx.Err(), context.Canceled) {
212226 return nil, errors.New("更新下载已取消")
213227 }
214删除: return nil, errors.New("无法通过所选代理连接更新源,请检查网络后重试")
228新增: return nil, usererror.Wrap("连接应用更新源", errors.Join(ctx.Err(), err), "请在网络与代理设置中确认所选节点可以连接 GitHub,再检查更新。")
215229 }
216230 if resp.StatusCode != http.StatusOK {
217231 resp.Body.Close()
218232 switch resp.StatusCode {
219233 case 404:
220删除: return nil, errors.New("更新源暂不可访问:仓库尚未公开或该发行包不可用")
234新增: return nil, errors.New("更新源找不到请求的版本或安装包(HTTP 404)。请稍后检查更新;需要手动安装时,请核对 Cage 发布页面中的对应平台文件。")
221235 case 403, 429:
222删除: return nil, errors.New("更新源请求受限,请稍后重试")
236新增: return nil, updateSourceError(resp, time.Now())
223237 default:
224238 return nil, fmt.Errorf("更新源返回 HTTP %d,请稍后重试", resp.StatusCode)
225239 }
修改internal/appupdate/update_test.go+1 −1看文件
@@ -121,7 +121,7 @@ func TestChecksumListMustAgreeAndBelongToSameRelease(t *testing.T) {
121121 }
122122}
123123func TestPrivateReleaseAndMissingProxyDoNotReportCurrent(t *testing.T) {
124删除: if _, err := findRelease(context.Background(), responseClient(`{"message":"Not Found"}`, 404), "0.1.0"); err == nil || !strings.Contains(err.Error(), "尚未公开") {
124新增: if _, err := findRelease(context.Background(), responseClient(`{"message":"Not Found"}`, 404), "0.1.0"); err == nil || !strings.Contains(err.Error(), "HTTP 404") {
125125 t.Fatal(err)
126126 }
127127 var output bytes.Buffer
新增internal/appupdate/waiting_test.go+42 −0看文件
@@ -0,0 +1,42 @@
1新增:package appupdate
2新增:
3新增:import (
4新增: "bytes"
5新增: "encoding/json"
6新增: "os"
7新增: "path/filepath"
8新增: "testing"
9新增:
10新增: "github.com/sylvinus/agent-vm/internal/cage"
11新增: "github.com/sylvinus/agent-vm/internal/diagnostics"
12新增:)
13新增:
14新增:func TestUpdateCheckWaitsForProxyButDownloadReportsFailure(t *testing.T) {
15新增: for _, operation := range []string{"check", "download"} {
16新增: t.Run(operation, func(t *testing.T) {
17新增: profile := t.TempDir()
18新增: config := filepath.Join(profile, "config.json")
19新增: data, _ := json.Marshal(cage.DefaultConfig())
20新增: if err := os.WriteFile(config, data, 0600); err != nil {
21新增: t.Fatal(err)
22新增: }
23新增: var output bytes.Buffer
24新增: code := Run(config, []string{operation}, &output)
25新增: var state State
26新增: if err := json.Unmarshal(output.Bytes(), &state); err != nil {
27新增: t.Fatal(err)
28新增: }
29新增: if operation == "check" {
30新增: if code != 0 || state.Phase != "waiting" || !state.Retryable {
31新增: t.Fatalf("expected deferred check: code=%d %+v", code, state)
32新增: }
33新增: info, err := diagnostics.New(profile).Info()
34新增: if err != nil || info.Bytes != 0 {
35新增: t.Fatalf("ordinary wait logged as failure: %+v %v", info, err)
36新增: }
37新增: } else if code == 0 || state.Phase != "failed" {
38新增: t.Fatalf("requested download must report unavailable proxy: code=%d %+v", code, state)
39新增: }
40新增: })
41新增: }
42新增:}
修改packaging/windows/Cage.nsi+261 −19看文件
@@ -1,17 +1,19 @@
11Unicode true
22RequestExecutionLevel user
3删除:SetCompressor /SOLID lzma
3新增:; Per-file decompression avoids a full payload copy in the system TEMP drive.
4新增:SetCompressor lzma
45SetCompressorDictSize 32
56ManifestDPIAware true
67ManifestSupportedOS all
7删除:Icon "Cage.ico"
8删除:UninstallIcon "Cage.ico"
98
109!include MUI2.nsh
10新增:!define MUI_ICON "Cage.ico"
11新增:!define MUI_UNICON "Cage.ico"
1112!include LogicLib.nsh
1213!include FileFunc.nsh
1314!include x64.nsh
1415!include WinVer.nsh
16新增:!include nsDialogs.nsh
1517
1618!ifndef APP_DIR
1719 !error "APP_DIR is required"
@@ -52,6 +54,7 @@ VIAddVersionKey /LANG=1033 "LegalCopyright" "Cage contributors"
5254!insertmacro MUI_PAGE_LICENSE "${APP_DIR}/LICENSE.txt"
5355!define MUI_DIRECTORYPAGE_TEXT_TOP "$(CageDirectoryHelp)"
5456!insertmacro MUI_PAGE_DIRECTORY
57新增:Page custom ShortcutOptionsPage ShortcutOptionsLeave
5558!insertmacro MUI_PAGE_INSTFILES
5659!insertmacro MUI_PAGE_FINISH
5760!insertmacro MUI_UNPAGE_CONFIRM
@@ -61,11 +64,143 @@ VIAddVersionKey /LANG=1033 "LegalCopyright" "Cage contributors"
6164
6265LangString CageDirectoryHelp ${LANG_ENGLISH} "Choose where to install the Cage application. On first launch, you can choose a separate drive for the Linux image, download cache, and virtual disks before starting the environment."
6366LangString CageDirectoryHelp ${LANG_SIMPCHINESE} "请选择 Cage 程序的安装目录。首次打开 Cage 后,可以在启动环境前单独选择存放 Linux 镜像、下载缓存和虚拟磁盘的磁盘。"
67新增:LangString CageShortcutsTitle ${LANG_ENGLISH} "Shortcuts"
68新增:LangString CageShortcutsTitle ${LANG_SIMPCHINESE} "快捷方式"
69新增:LangString CageShortcutsHelp ${LANG_ENGLISH} "Choose where to add Cage shortcuts for your Windows account."
70新增:LangString CageShortcutsHelp ${LANG_SIMPCHINESE} "选择为当前 Windows 用户添加的 Cage 快捷方式。"
71新增:LangString CageDesktopShortcut ${LANG_ENGLISH} "Add a desktop shortcut"
72新增:LangString CageDesktopShortcut ${LANG_SIMPCHINESE} "添加桌面快捷方式"
73新增:LangString CageStartMenuShortcuts ${LANG_ENGLISH} "Add to the Start menu"
74新增:LangString CageStartMenuShortcuts ${LANG_SIMPCHINESE} "添加到开始菜单"
6475
6576Var UpdateMode
6677Var StageDir
6778Var BackupDir
6879Var ExistingInstall
80新增:Var DesktopShortcut
81新增:Var StartMenuShortcuts
82新增:Var DesktopShortcutControl
83新增:Var StartMenuShortcutsControl
84新增:Var InstallationMutex
85新增:Var TransactionRecord
86新增:
87新增:!macro AcquireInstallationMutex
88新增: ; NSIS and UpdateInstaller both reject an existing named object and keep
89新增: ; their handle until the transaction ends. No caller waits for ownership.
90新增: System::Call 'kernel32::CreateMutexW(p 0, i 0, w "Global\Cage.Installation") p.r0 ?e'
91新增: Pop $1
92新增: ${If} $0 == 0
93新增: SetErrorLevel 2
94新增: Abort "无法锁定 Cage 安装操作,请核对系统权限后重试。"
95新增: ${EndIf}
96新增: StrCpy $InstallationMutex $0
97新增: ${If} $1 == 183
98新增: SetErrorLevel 2
99新增: Abort "另一个 Cage 安装或卸载仍在进行,请等待完成后重试。"
100新增: ${EndIf}
101新增:!macroend
102新增:
103新增:Function .onGUIEnd
104新增: ${If} $InstallationMutex != ""
105新增: System::Call 'kernel32::CloseHandle(p $InstallationMutex)'
106新增: ${EndIf}
107新增:FunctionEnd
108新增:
109新增:Function un.onGUIEnd
110新增: ${If} $InstallationMutex != ""
111新增: System::Call 'kernel32::CloseHandle(p $InstallationMutex)'
112新增: ${EndIf}
113新增:FunctionEnd
114新增:
115新增:Function LoadShortcutOptions
116新增: ; Fresh installs enable both entries. Older installs inherit actual shortcuts.
117新增: StrCpy $DesktopShortcut 1
118新增: StrCpy $StartMenuShortcuts 1
119新增: ReadRegStr $0 HKCU "${UNINSTALL_KEY}" "InstallLocation"
120新增: ${If} $0 != ""
121新增: StrCpy $DesktopShortcut 0
122新增: StrCpy $StartMenuShortcuts 0
123新增: ${If} ${FileExists} "$DESKTOP\Cage.lnk"
124新增: StrCpy $DesktopShortcut 1
125新增: ${EndIf}
126新增: ${If} ${FileExists} "$SMPROGRAMS\Cage\Cage.lnk"
127新增: StrCpy $StartMenuShortcuts 1
128新增: ${EndIf}
129新增: ${EndIf}
130新增: ClearErrors
131新增: ReadRegDWORD $0 HKCU "${UNINSTALL_KEY}" "DesktopShortcut"
132新增: ${IfNot} ${Errors}
133新增: StrCpy $DesktopShortcut $0
134新增: ${EndIf}
135新增: ClearErrors
136新增: ReadRegDWORD $0 HKCU "${UNINSTALL_KEY}" "StartMenuShortcuts"
137新增: ${IfNot} ${Errors}
138新增: StrCpy $StartMenuShortcuts $0
139新增: ${EndIf}
140新增: ${GetParameters} $0
141新增: ClearErrors
142新增: ${GetOptions} $0 "/DESKTOPSHORTCUT=" $1
143新增: ${IfNot} ${Errors}
144新增: ${If} $1 != "0"
145新增: ${AndIf} $1 != "1"
146新增: SetErrorLevel 2
147新增: Abort "DESKTOPSHORTCUT must be 0 or 1."
148新增: ${EndIf}
149新增: StrCpy $DesktopShortcut $1
150新增: ${EndIf}
151新增: ClearErrors
152新增: ${GetOptions} $0 "/STARTMENUSHORTCUT=" $1
153新增: ${IfNot} ${Errors}
154新增: ${If} $1 != "0"
155新增: ${AndIf} $1 != "1"
156新增: SetErrorLevel 2
157新增: Abort "STARTMENUSHORTCUT must be 0 or 1."
158新增: ${EndIf}
159新增: StrCpy $StartMenuShortcuts $1
160新增: ${EndIf}
161新增:FunctionEnd
162新增:
163新增:Function ShortcutOptionsPage
164新增: !insertmacro MUI_HEADER_TEXT "$(CageShortcutsTitle)" "$(CageShortcutsHelp)"
165新增: nsDialogs::Create 1018
166新增: Pop $0
167新增: ${If} $0 == error
168新增: Abort
169新增: ${EndIf}
170新增: ${NSD_CreateCheckbox} 0 8u 100% 16u "$(CageDesktopShortcut)"
171新增: Pop $DesktopShortcutControl
172新增: ${NSD_SetState} $DesktopShortcutControl $DesktopShortcut
173新增: ${NSD_CreateCheckbox} 0 36u 100% 16u "$(CageStartMenuShortcuts)"
174新增: Pop $StartMenuShortcutsControl
175新增: ${NSD_SetState} $StartMenuShortcutsControl $StartMenuShortcuts
176新增: ${NSD_OnBack} ShortcutOptionsLeave
177新增: nsDialogs::Show
178新增:FunctionEnd
179新增:
180新增:Function ShortcutOptionsLeave
181新增: ${NSD_GetState} $DesktopShortcutControl $DesktopShortcut
182新增: ${NSD_GetState} $StartMenuShortcutsControl $StartMenuShortcuts
183新增:FunctionEnd
184新增:
185新增:Function SetDefaultInstallDirectory
186新增: ; NSIS removes /D= from $CMDLINE, so inspect the original command line.
187新增: System::Call 'kernel32::GetCommandLineW() w .r0'
188新增: ClearErrors
189新增: ${GetOptions} $0 "/D=" $1
190新增: ${IfNot} ${Errors}
191新增: Return
192新增: ${EndIf}
193新增: ; Keep upgrades in the registered location, including installations on C:.
194新增: ReadRegStr $0 HKCU "${UNINSTALL_KEY}" "InstallLocation"
195新增: ${If} $0 != ""
196新增: StrCpy $INSTDIR $0
197新增: Return
198新增: ${EndIf}
199新增: System::Call 'kernel32::GetDriveTypeW(w "D:\") i .r0'
200新增: ${If} $0 == 3
201新增: StrCpy $INSTDIR "D:\Cage"
202新增: ${EndIf}
203新增:FunctionEnd
69204
70205!macro CheckStopped FILE
71206 ${If} ${FileExists} "$INSTDIR\${FILE}"
@@ -93,6 +228,8 @@ Function .onInit
93228 SetErrorLevel 1633
94229 Quit
95230 ${EndIf}
231新增: Call SetDefaultInstallDirectory
232新增: Call LoadShortcutOptions
96233 StrCpy $UpdateMode "0"
97234 ${GetParameters} $0
98235 ClearErrors
@@ -113,7 +250,9 @@ Function CheckDestination
113250 ${EndIf}
114251 StrCpy $ExistingInstall "0"
115252 IfFileExists "$INSTDIR\Cage.install-id" existing
116删除: IfFileExists "$INSTDIR\*.*" foreign done
253新增: ; IfFileExists with a wildcard also matches an empty directory.
254新增: ${DirState} "$INSTDIR" $0
255新增: StrCmp $0 1 foreign done
117256 existing:
118257 FileOpen $0 "$INSTDIR\Cage.install-id" r
119258 FileRead $0 $1
@@ -132,9 +271,40 @@ Function CheckDestination
132271 SetErrorLevel 2
133272 Abort "The destination contains files from another installation. Choose an empty folder."
134273 done:
274新增: ClearErrors
275新增:FunctionEnd
276新增:
277新增:Function RestorePreservedFiles
278新增: nsExec::ExecToStack '"$SYSDIR\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -File "$PLUGINSDIR\installation-files.ps1" -Operation restore -Target "$BackupDir" -Source "$StageDir" -Receipt "$TransactionRecord"'
279新增: Pop $0
280新增: Pop $1
281新增: ${If} $0 != 0
282新增: DetailPrint "$1"
283新增: SetErrorLevel 2
284新增: Abort "安装恢复尚未完成。文件分别保留在 $BackupDir 和 $StageDir,请保留这两个目录后重试。"
285新增: ${EndIf}
286新增: ClearErrors
287新增: Rename "$BackupDir" "$INSTDIR"
288新增: ${If} ${Errors}
289新增: SetErrorLevel 2
290新增: Abort "原安装目录未能恢复。文件保留在 $BackupDir,新程序保留在 $StageDir。"
291新增: ${EndIf}
292新增: nsExec::ExecToStack '"$SYSDIR\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -File "$PLUGINSDIR\installation-files.ps1" -Operation complete -Target "$INSTDIR" -Receipt "$TransactionRecord"'
293新增: Pop $0
294新增: Pop $1
295新增: ${If} $0 != 0
296新增: SetErrorLevel 2
297新增: Abort "仍有文件需要核对,安装回执保留在 $TransactionRecord。请保留相关目录后处理。"
298新增: ${EndIf}
135299FunctionEnd
136300
137301Section "Cage" Main
302新增: !insertmacro AcquireInstallationMutex
303新增: StrCpy $TransactionRecord "$INSTDIR.cage-installation.json"
304新增: ${If} ${FileExists} "$TransactionRecord"
305新增: SetErrorLevel 2
306新增: Abort "存在未处理的安装事务记录:$TransactionRecord。请先按记录恢复保留的目录,再重试。"
307新增: ${EndIf}
138308 Call CheckDestination
139309 ${GetParent} "$INSTDIR" $0
140310 CreateDirectory "$0"
@@ -182,13 +352,45 @@ Section "Cage" Main
182352 ${GetParent} "$INSTDIR" $0
183353 GetTempFileName $BackupDir "$0"
184354 Delete "$BackupDir"
355新增: ${EndIf}
356新增: InitPluginsDir
357新增: SetOutPath "$PLUGINSDIR"
358新增: File /oname=installation-files.ps1 "installation-files.ps1"
359新增: File /oname=verified-file-deletion.cs "verified-file-deletion.cs"
360新增: DetailPrint "正在检查并保留已有项目和修改文件…"
361新增: nsExec::ExecToStack '"$SYSDIR\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -File "$PLUGINSDIR\installation-files.ps1" -Operation prepare -Target "$StageDir" -Source "$INSTDIR" -Backup "$BackupDir" -Receipt "$TransactionRecord"'
362新增: Pop $0
363新增: Pop $1
364新增: DetailPrint "$1"
365新增: ${If} $0 != 0
366新增: SetOutPath "$TEMP"
367新增: RMDir /r "$StageDir"
368新增: SetErrorLevel 2
369新增: Abort "无法安全保留现有文件,安装已停止。原安装目录已保留,请检查磁盘空间、文件占用和安装日志。"
370新增: ${EndIf}
371新增: SetOutPath "$TEMP"
372新增: ${If} $ExistingInstall == "1"
185373 ClearErrors
186374 Rename "$INSTDIR" "$BackupDir"
187375 ${If} ${Errors}
376新增: nsExec::ExecToStack '"$SYSDIR\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -File "$PLUGINSDIR\installation-files.ps1" -Operation complete -Target "$INSTDIR" -Receipt "$TransactionRecord"'
377新增: Pop $0
378新增: Pop $1
188379 RMDir /r "$StageDir"
189380 SetErrorLevel 2
190381 Abort "Could not move the installed application. Quit Cage and retry."
191382 ${EndIf}
383新增: DetailPrint "正在迁入个人文件并保留原有链接…"
384新增: nsExec::ExecToStack '"$SYSDIR\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -File "$PLUGINSDIR\installation-files.ps1" -Operation move -Target "$StageDir" -Source "$BackupDir" -Receipt "$TransactionRecord"'
385新增: Pop $0
386新增: Pop $1
387新增: DetailPrint "$1"
388新增: ${If} $0 != 0
389新增: Call RestorePreservedFiles
390新增: RMDir /r "$StageDir"
391新增: SetErrorLevel 2
392新增: Abort "个人文件未能迁入新程序目录,原安装已恢复。请关闭占用文件的程序后重试。"
393新增: ${EndIf}
192394 ${Else}
193395 RMDir "$INSTDIR"
194396 ${EndIf}
@@ -196,21 +398,31 @@ Section "Cage" Main
196398 Rename "$StageDir" "$INSTDIR"
197399 ${If} ${Errors}
198400 ${If} $BackupDir != ""
199删除: ClearErrors
200删除: Rename "$BackupDir" "$INSTDIR"
201删除: ${If} ${Errors}
202删除: RMDir /r "$StageDir"
203删除: SetErrorLevel 2
204删除: Abort "Installation failed. The previous application is preserved at $BackupDir; restore that folder before retrying."
205删除: ${EndIf}
401新增: Call RestorePreservedFiles
206402 ${EndIf}
207403 RMDir /r "$StageDir"
208404 SetErrorLevel 2
209405 Abort "Could not install Cage. The previous installation has been restored."
210406 ${EndIf}
211407 ${If} $BackupDir != ""
212删除: ; BackupDir came from the verified Cage installation above. User data lives elsewhere.
213删除: RMDir /r "$BackupDir"
408新增: DetailPrint "正在清理已核对的旧程序文件…"
409新增: nsExec::ExecToStack '"$SYSDIR\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -File "$PLUGINSDIR\installation-files.ps1" -Operation cleanup -Target "$INSTDIR" -Source "$BackupDir" -Receipt "$TransactionRecord"'
410新增: Pop $0
411新增: Pop $1
412新增: DetailPrint "$1"
413新增: ${If} $0 != 0
414新增: DetailPrint "旧目录中仍有需要保留的文件:$BackupDir"
415新增: SetErrorLevel 2
416新增: Abort "安装仍有待恢复的文件。请保留 $TransactionRecord 及其中记录的目录,再处理恢复。"
417新增: ${EndIf}
418新增: ${Else}
419新增: nsExec::ExecToStack '"$SYSDIR\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -File "$PLUGINSDIR\installation-files.ps1" -Operation complete -Target "$INSTDIR" -Receipt "$TransactionRecord"'
420新增: Pop $0
421新增: Pop $1
422新增: ${If} $0 != 0
423新增: SetErrorLevel 2
424新增: Abort "安装回执未能完成,记录保留在 $TransactionRecord。"
425新增: ${EndIf}
214426 ${EndIf}
215427 WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayName" "Cage"
216428 WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayVersion" "${VERSION}"
@@ -221,9 +433,23 @@ Section "Cage" Main
221433 WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayIcon" "$INSTDIR\Cage.exe,0"
222434 WriteRegDWORD HKCU "${UNINSTALL_KEY}" "NoModify" 1
223435 WriteRegDWORD HKCU "${UNINSTALL_KEY}" "NoRepair" 1
224删除: CreateDirectory "$SMPROGRAMS\Cage"
225删除: CreateShortcut "$SMPROGRAMS\Cage\Cage.lnk" "$INSTDIR\Cage.exe"
226删除: CreateShortcut "$SMPROGRAMS\Cage\Uninstall Cage.lnk" "$INSTDIR\Uninstall.exe"
436新增: SetOutPath "$INSTDIR"
437新增: ${If} $DesktopShortcut == 1
438新增: CreateShortcut "$DESKTOP\Cage.lnk" "$INSTDIR\Cage.exe"
439新增: ${Else}
440新增: Delete "$DESKTOP\Cage.lnk"
441新增: ${EndIf}
442新增: ${If} $StartMenuShortcuts == 1
443新增: CreateDirectory "$SMPROGRAMS\Cage"
444新增: CreateShortcut "$SMPROGRAMS\Cage\Cage.lnk" "$INSTDIR\Cage.exe"
445新增: CreateShortcut "$SMPROGRAMS\Cage\Uninstall Cage.lnk" "$INSTDIR\Uninstall.exe"
446新增: ${Else}
447新增: Delete "$SMPROGRAMS\Cage\Cage.lnk"
448新增: Delete "$SMPROGRAMS\Cage\Uninstall Cage.lnk"
449新增: RMDir "$SMPROGRAMS\Cage"
450新增: ${EndIf}
451新增: WriteRegDWORD HKCU "${UNINSTALL_KEY}" "DesktopShortcut" $DesktopShortcut
452新增: WriteRegDWORD HKCU "${UNINSTALL_KEY}" "StartMenuShortcuts" $StartMenuShortcuts
227453 SetErrorLevel 0
228454SectionEnd
229455
@@ -244,12 +470,28 @@ Function un.onInit
244470FunctionEnd
245471
246472Section "Uninstall"
473新增: !insertmacro AcquireInstallationMutex
474新增: ${If} ${FileExists} "$INSTDIR.cage-installation.json"
475新增: SetErrorLevel 2
476新增: Abort "存在待恢复的安装事务,请先处理 $INSTDIR.cage-installation.json 中记录的目录。"
477新增: ${EndIf}
478新增: InitPluginsDir
479新增: SetOutPath "$PLUGINSDIR"
480新增: File /oname=installation-files.ps1 "installation-files.ps1"
481新增: File /oname=verified-file-deletion.cs "verified-file-deletion.cs"
482新增: File /oname=install-files.json "${FILE_MANIFEST}"
483新增: nsExec::ExecToStack '"$SYSDIR\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -File "$PLUGINSDIR\installation-files.ps1" -Operation uninstall -Target "$INSTDIR" -Manifest "$PLUGINSDIR\install-files.json"'
484新增: Pop $0
485新增: Pop $1
486新增: DetailPrint "$1"
487新增: ${If} $0 != 0
488新增: SetErrorLevel 2
489新增: Abort "部分程序文件正在使用或无法读取,卸载未完成。个人文件已保留,请关闭占用程序后重试。"
490新增: ${EndIf}
491新增: Delete "$DESKTOP\Cage.lnk"
247492 Delete "$SMPROGRAMS\Cage\Cage.lnk"
248493 Delete "$SMPROGRAMS\Cage\Uninstall Cage.lnk"
249494 RMDir "$SMPROGRAMS\Cage"
250495 DeleteRegKey HKCU "${UNINSTALL_KEY}"
251删除: ; Delete only files shipped in this build. Preserve user-created files and all external data.
252删除: !include "${UNINSTALL_MANIFEST}"
253删除: Delete "$INSTDIR\Uninstall.exe"
254496 RMDir "$INSTDIR"
255497SectionEnd
修改packaging/windows/README.txt+16 −1看文件
@@ -1,6 +1,11 @@
11Cage for Windows 10 and Windows 11 (x64)
22
3删除:Install Cage for the current Windows user, then open it from the Start menu.
3新增:Install Cage for the current Windows user. On the Shortcuts page, choose a
4新增:desktop shortcut and Start menu entries. Both are selected on a fresh install.
5新增:Upgrades remember the selection. Open Cage from either selected location.
6新增:For a first installation, the default is D:\Cage when D: is a local fixed
7新增:drive, or %LOCALAPPDATA%\Programs\Cage otherwise. Upgrades keep the existing
8新增:installation folder. You can choose another location in the installer.
49No Go, Node.js, .NET SDK, QEMU, OpenSSH or Clash installation is required.
510The installer includes the Microsoft WebView2 offline runtime installer.
611
@@ -17,6 +22,14 @@ Proxy service and Claude account are not included. Changes to shared projects
1722affect the original files.
1823
1924Updates preserve the Cage configuration, virtual disk and project files.
25新增:Projects and links inside the installation folder are retained. Modified files
26新增:that conflict with the new program, and unrecognized libraries in program load
27新增:directories, are kept in Cage-preserved-files inside that folder. Changes made
28新增:during installation can also be retained in its late-* subdirectories.
29新增:If recovery is interrupted, a .cage-installation.json record beside the
30新增:application folder identifies the retained installation, staged and backup
31新增:folders. Keep the record and those folders until recovery is complete.
32新增:Automatic updates stop application launch while recovery remains incomplete.
2033Stop the environment and quit Cage before running an installer manually.
2134In-app updates stop the environment after your confirmation, verify the new
2235installer and publisher, and restart the application after installation.
@@ -25,6 +38,8 @@ Unsigned development builds cannot install automatic updates.
2538Uninstall using Windows Settings > Apps > Installed apps (Windows 11) or
2639Apps & features (Windows 10). Uninstall removes application files and shortcuts.
2740It preserves user data in %USERPROFILE%\.claude-cage and all shared projects.
41新增:If personal files remain inside the installation folder, the folder remains
42新增:available for a later installation.
2843Microsoft WebView2 is a shared runtime and is not removed by Cage uninstall.
2944
3045Getting started: https://github.com/Lee-xeo/Claude-Cage/blob/main/docs/windows.md
新增packaging/windows/installation-files.ps1+315 −0看文件
@@ -0,0 +1,315 @@
1新增:#requires -Version 5.1
2新增:[CmdletBinding()]
3新增:param(
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新增: [switch]$LegacyTarget
11新增:)
12新增:$ErrorActionPreference = 'Stop'
13新增:$manifestName = 'Cage.install-files.json'
14新增:$identityName = 'Cage.install-id'
15新增:
16新增:function Read-FileManifest([string]$Path) {
17新增: $files = [Collections.Generic.Dictionary[string,string]]::new([StringComparer]::OrdinalIgnoreCase)
18新增: if (!(Test-Path -LiteralPath $Path -PathType Leaf)) { return ,$files }
19新增: if ((Get-Item -LiteralPath $Path -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) { return ,$files }
20新增: try {
21新增: $value = Get-Content -LiteralPath $Path -Raw -Encoding UTF8 | ConvertFrom-Json
22新增: if ($value.version -ne 1) { throw 'Unknown installation manifest version.' }
23新增: foreach ($entry in $value.files) {
24新增: if (!$entry.path -or $entry.path -match '(^/|[\\:]|(^|/)\.\.?(/|$))' -or $entry.sha256 -notmatch '^[a-fA-F0-9]{64}$' -or $files.ContainsKey($entry.path)) {
25新增: throw 'Invalid installation manifest entry.'
26新增: }
27新增: $files.Add($entry.path, $entry.sha256.ToLowerInvariant())
28新增: }
29新增: } catch {
30新增: # An unreadable legacy manifest grants no permission to delete files.
31新增: $files.Clear()
32新增: }
33新增: return ,$files
34新增:}
35新增:
36新增:function Directory-Paths([string[]]$Paths) {
37新增: $directories = [Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
38新增: $null = $directories.Add('')
39新增: foreach ($path in $Paths) {
40新增: $parent = Split-Path $path -Parent
41新增: while ($parent) { $null = $directories.Add($parent.Replace('\', '/')); $parent = Split-Path $parent -Parent }
42新增: }
43新增: return ,$directories
44新增:}
45新增:
46新增:function Read-Tree([string]$Root, [string[]]$KnownPaths) {
47新增: $entries = [Collections.Generic.List[object]]::new()
48新增: $directories = [Collections.Generic.Queue[string]]::new()
49新增: $neededDirectories = Directory-Paths $KnownPaths
50新增: foreach ($path in $KnownPaths) { $null = $neededDirectories.Add($path) }
51新增: $directories.Enqueue($Root)
52新增: while ($directories.Count) {
53新增: foreach ($entry in Get-ChildItem -LiteralPath $directories.Dequeue() -Force) {
54新增: $entries.Add($entry)
55新增: if ($entry.PSIsContainer -and !($entry.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
56新增: if ($null -eq $KnownPaths -or $neededDirectories.Contains((Relative-Path $Root $entry.FullName))) { $directories.Enqueue($entry.FullName) }
57新增: }
58新增: }
59新增: }
60新增: return $entries.ToArray()
61新增:}
62新增:
63新增:function Relative-Path([string]$Root, [string]$Path) {
64新增: return $Path.Substring($Root.TrimEnd([IO.Path]::DirectorySeparatorChar).Length + 1).Replace('\', '/')
65新增:}
66新增:
67新增:function Open-ReadLocked([string]$Path) {
68新增: return [IO.File]::Open($Path, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::Read -bor [IO.FileShare]::Delete)
69新增:}
70新增:
71新增:function Stream-Hash([IO.Stream]$Stream) {
72新增: $algorithm = [Security.Cryptography.SHA256]::Create()
73新增: try { return ([BitConverter]::ToString($algorithm.ComputeHash($Stream))).Replace('-', '').ToLowerInvariant() }
74新增: finally { $algorithm.Dispose(); $Stream.Position = 0 }
75新增:}
76新增:
77新增:function Initialize-VerifiedDeletion {
78新增: if (!('CageVerifiedFile' -as [type])) { Add-Type -Path (Join-Path $PSScriptRoot 'verified-file-deletion.cs') }
79新增:}
80新增:
81新增:function Remove-MatchingFile([string]$Root, [string]$Relative, [string]$Hash) {
82新增: $Path = Join-Path $Root $Relative
83新增: if (!(Test-Path -LiteralPath $Path -PathType Leaf)) { return }
84新增: if ((Get-Item -LiteralPath $Path -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) { return }
85新增: $windows = $env:OS -eq 'Windows_NT'
86新增: if ($windows) { Initialize-VerifiedDeletion; $stream = [CageVerifiedFile]::Open($Root, $Relative) }
87新增: else { $stream = Open-ReadLocked $Path }
88新增: try {
89新增: if ((Stream-Hash $stream) -eq $Hash) {
90新增: if ($windows) { [CageVerifiedFile]::Delete($stream) } else { [IO.File]::Delete($Path) }
91新增: }
92新增: }
93新增: finally { $stream.Dispose() }
94新增:}
95新增:
96新增:function Remove-EmptyDirectories([string]$Root, [string[]]$KnownDirectories) {
97新增: foreach ($directory in @(Read-Tree $Root $KnownDirectories | Where-Object { $_.PSIsContainer -and !($_.Attributes -band [IO.FileAttributes]::ReparsePoint) } | Sort-Object { $_.FullName.Length } -Descending)) {
98新增: if ((Relative-Path $Root $directory.FullName) -in $KnownDirectories -and @(Get-ChildItem -LiteralPath $directory.FullName -Force).Count -eq 0) {
99新增: [IO.Directory]::Delete($directory.FullName)
100新增: }
101新增: }
102新增:}
103新增:
104新增:function Preserved-Destination([string]$Relative, [bool]$Quarantine) {
105新增: $path = Join-Path $Target $Relative
106新增: $parent = Split-Path $path -Parent
107新增: $conflict = $Quarantine -or (Test-Path -LiteralPath $path)
108新增: while ($parent -ne $Target) {
109新增: if (Test-Path -LiteralPath $parent -PathType Leaf) { $conflict = $true; break }
110新增: $parent = Split-Path $parent -Parent
111新增: }
112新增: if ($conflict) { return $recovery + '/' + $Relative }
113新增: return $Relative
114新增:}
115新增:
116新增:function Save-Transfer($Transfer) {
117新增: $temporary = $Receipt + '.' + [guid]::NewGuid().ToString('N') + '.tmp'
118新增: try {
119新增: $Transfer | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath $temporary -Encoding UTF8
120新增: [IO.File]::Replace($temporary, $Receipt, [NullString]::Value)
121新增: } finally { if (Test-Path -LiteralPath $temporary) { [IO.File]::Delete($temporary) } }
122新增:}
123新增:
124新增:function Complete-Transfer {
125新增: $transfer = Get-Content -LiteralPath $Receipt -Raw -Encoding UTF8 | ConvertFrom-Json
126新增: if ($transfer.kind -ne 'cage-installation' -or !(Test-Path -LiteralPath (Join-Path $Target $identityName))) { throw '安装目录尚未恢复,事务回执已保留。' }
127新增: if ($transfer.backupPath -and (Test-Path -LiteralPath $transfer.backupPath)) { throw ('旧目录仍需恢复,事务回执已保留:' + $transfer.backupPath) }
128新增: foreach ($entry in $transfer.moves) {
129新增: if ($entry.state -eq 'absent') { continue }
130新增: $relative = if ($entry.state -eq 'moved') { $entry.destination } else { $entry.path }
131新增: if (!(Get-Item -LiteralPath (Join-Path $Target $relative) -Force -ErrorAction SilentlyContinue)) { throw ('个人文件尚未恢复,事务回执已保留:' + $relative) }
132新增: }
133新增: $hash = (Get-FileHash -LiteralPath $Receipt -Algorithm SHA256).Hash
134新增: Remove-MatchingFile (Split-Path $Receipt -Parent) (Split-Path $Receipt -Leaf) $hash
135新增: if (Test-Path -LiteralPath $Receipt) { throw '安装回执在完成期间发生变化,已保留待核对。' }
136新增:}
137新增:
138新增:$Target = [IO.Path]::GetFullPath($Target).TrimEnd([IO.Path]::DirectorySeparatorChar)
139新增:foreach ($rootPath in @($Target, $Source)) {
140新增: if (!$rootPath) { continue }
141新增: $rootEntry = Get-Item -LiteralPath $rootPath -Force -ErrorAction SilentlyContinue
142新增: if ($rootEntry -and $rootEntry.Attributes -band [IO.FileAttributes]::ReparsePoint) {
143新增: throw ('安装目录本身是文件系统链接,原文件已保留。请选择实际程序目录:' + $rootPath)
144新增: }
145新增:}
146新增:if ($Operation -eq 'prepare') {
147新增: if (Test-Path -LiteralPath $Receipt) { throw ('仍有未完成的安装事务,请保留并检查回执:' + $Receipt) }
148新增: $current = Read-FileManifest (Join-Path $Target $manifestName)
149新增: $legacySnapshot = !$current.Count -and $LegacyTarget
150新增: if ($legacySnapshot) {
151新增: $identity = Open-ReadLocked (Join-Path $Target $identityName)
152新增: try { $current[$identityName] = Stream-Hash $identity } finally { $identity.Dispose() }
153新增: }
154新增: if (!$current.Count) { throw '新程序缺少有效文件清单,安装已停止。' }
155新增: $uninstaller = Open-ReadLocked (Join-Path $Target 'Uninstall.exe')
156新增: try { $current['Uninstall.exe'] = Stream-Hash $uninstaller } finally { $uninstaller.Dispose() }
157新增: $transfers = [Collections.Generic.List[object]]::new()
158新增: $moves = [Collections.Generic.List[object]]::new()
159新增: $directories = @()
160新增: $recovery = 'Cage-preserved-files/' + [guid]::NewGuid().ToString('N')
161新增: $programDirectories = Directory-Paths @($current.Keys)
162新增: if ($Source -and (Test-Path -LiteralPath $Source -PathType Container)) {
163新增: $Source = [IO.Path]::GetFullPath($Source).TrimEnd([IO.Path]::DirectorySeparatorChar)
164新增: $previous = Read-FileManifest (Join-Path $Source $manifestName)
165新增: $previousDirectories = Directory-Paths @($previous.Keys)
166新增: $pending = [Collections.Generic.Queue[string]]::new()
167新增: $pending.Enqueue($Source)
168新增: while ($pending.Count) {
169新增: foreach ($entry in Get-ChildItem -LiteralPath $pending.Dequeue() -Force) {
170新增: $relative = Relative-Path $Source $entry.FullName
171新增: $isLink = [bool]($entry.Attributes -band [IO.FileAttributes]::ReparsePoint)
172新增: $programContent = $previous.ContainsKey($relative) -or (
173新增: $programDirectories.Contains((Split-Path $relative -Parent).Replace('\', '/')) -and
174新增: ($entry.Extension -in @('.dll','.exe','.ocx','.sys','.pyd','.so','.dylib') -or $entry.Name -eq 'node_modules'))
175新增: $hasOwnedChildren = $previousDirectories.Contains($relative)
176新增: # A legacy rollback snapshot also contains old personal files.
177新增: # The failed candidate's manifest identifies its program paths, so
178新增: # current personal content can return to its original location.
179新增: if ($legacySnapshot -and $previous.Count -and !$programContent -and !$hasOwnedChildren -and
180新增: $relative -notin @($manifestName, 'Cage-preserved-files')) {
181新增: $oldCopy = Get-Item -LiteralPath (Join-Path $Target $relative) -Force -ErrorAction SilentlyContinue
182新增: if ($oldCopy) {
183新增: $oldDestination = Join-Path $Target ($recovery + '/previous/' + $relative)
184新增: [IO.Directory]::CreateDirectory((Split-Path $oldDestination -Parent)) | Out-Null
185新增: if ($oldCopy.Attributes -band [IO.FileAttributes]::Directory) { [IO.Directory]::Move($oldCopy.FullName, $oldDestination) }
186新增: else { [IO.File]::Move($oldCopy.FullName, $oldDestination) }
187新增: }
188新增: }
189新增: if ($isLink -or ($entry.PSIsContainer -and !$hasOwnedChildren -and !(Test-Path -LiteralPath (Join-Path $Target $relative) -PathType Container))) {
190新增: $moves.Add(@{path = $relative; destination = (Preserved-Destination $relative $programContent); directory = ($entry.PSIsContainer -or [bool]($entry.Attributes -band [IO.FileAttributes]::Directory)); state = 'prepared'})
191新增: continue
192新增: }
193新增: if ($entry.PSIsContainer) {
194新增: $directories += $relative
195新增: $pending.Enqueue($entry.FullName)
196新增: continue
197新增: }
198新增: if (!$previous.ContainsKey($relative) -and !(Test-Path -LiteralPath (Join-Path $Target $relative)) -and $relative -ne $manifestName) {
199新增: $moves.Add(@{path = $relative; destination = (Preserved-Destination $relative $programContent); directory = $false; state = 'prepared'})
200新增: continue
201新增: }
202新增: $sourceStream = Open-ReadLocked $entry.FullName
203新增: try {
204新增: $hash = Stream-Hash $sourceStream
205新增: if (($previous.ContainsKey($relative) -and $previous[$relative] -eq $hash) -or ($relative -eq $manifestName -and $previous.Count)) {
206新增: $transfers.Add(@{ path = $relative; sha256 = $hash; destination = $null })
207新增: continue
208新增: }
209新增: $path = Join-Path $Target $relative
210新增: if (Test-Path -LiteralPath $path -PathType Leaf) {
211新增: $candidate = Open-ReadLocked $path
212新增: try { $same = (Stream-Hash $candidate) -eq $hash } finally { $candidate.Dispose() }
213新增: if ($same) {
214新增: $transfers.Add(@{ path = $relative; sha256 = $hash; destination = $relative })
215新增: continue
216新增: }
217新增: }
218新增: $moves.Add(@{path = $relative; destination = (Preserved-Destination $relative $programContent); directory = $false; state = 'prepared'})
219新增: } finally { $sourceStream.Dispose() }
220新增: }
221新增: }
222新增: }
223新增: $files = @($current.Keys | Sort-Object | ForEach-Object { @{ path = $_; sha256 = $current[$_] } })
224新增: @{ version = 1; files = $files } | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath (Join-Path $Target $manifestName) -Encoding UTF8
225新增: $record = @{kind = 'cage-installation'; version = 1; installPath = $Source; stagePath = $Target; backupPath = $Backup; files = @($transfers); directories = $directories; moves = @($moves)}
226新增: $encoding = [Text.UTF8Encoding]::new($true)
227新增: [byte[]]$bytes = $encoding.GetPreamble() + $encoding.GetBytes(($record | ConvertTo-Json -Depth 6))
228新增: $temporary = $Receipt + '.' + [guid]::NewGuid().ToString('N') + '.tmp'
229新增: try {
230新增: $output = [IO.File]::Open($temporary, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None)
231新增: try { $output.Write($bytes, 0, $bytes.Length); $output.Flush($true) } finally { $output.Dispose() }
232新增: [IO.File]::Move($temporary, $Receipt)
233新增: } finally { if (Test-Path -LiteralPath $temporary) { [IO.File]::Delete($temporary) } }
234新增:} elseif ($Operation -in @('move','restore')) {
235新增: $transfer = Get-Content -LiteralPath $Receipt -Raw -Encoding UTF8 | ConvertFrom-Json
236新增: $moves = @($transfer.moves)
237新增: if ($Operation -eq 'restore') { [Array]::Reverse($moves) }
238新增: foreach ($entry in $moves) {
239新增: if ($Operation -eq 'restore' -and $entry.state -notin @('moving','moved')) { continue }
240新增: $from = if ($Operation -eq 'move') { $entry.path } else { $entry.destination }
241新增: $to = if ($Operation -eq 'move') { $entry.destination } else { $entry.path }
242新增: $from = Join-Path $Source $from
243新增: $to = Join-Path $Target $to
244新增: if (!(Get-Item -LiteralPath $from -Force -ErrorAction SilentlyContinue)) {
245新增: if ($Operation -eq 'restore' -and !(Get-Item -LiteralPath $to -Force -ErrorAction SilentlyContinue)) { throw ('待恢复的个人文件无法定位,回执已保留:' + $entry.path) }
246新增: if ($Operation -eq 'move' -and $entry.state -eq 'prepared') { $entry.state = 'absent'; Save-Transfer $transfer }
247新增: continue
248新增: }
249新增: [IO.Directory]::CreateDirectory((Split-Path $to -Parent)) | Out-Null
250新增: if ($Operation -eq 'move') { $entry.state = 'moving'; Save-Transfer $transfer }
251新增: $moved = $false
252新增: try {
253新增: if ($entry.directory) { [IO.Directory]::Move($from, $to) } else { [IO.File]::Move($from, $to) }
254新增: $moved = $true
255新增: $entry.state = if ($Operation -eq 'move') { 'moved' } else { 'restored' }
256新增: Save-Transfer $transfer
257新增: } catch {
258新增: if ($Operation -eq 'move' -and !$moved) { $entry.state = 'failed'; Save-Transfer $transfer }
259新增: throw
260新增: }
261新增: }
262新增: if ($Operation -eq 'move' -and @($moves | Where-Object { $_.destination.StartsWith('Cage-preserved-files/') }).Count) {
263新增: Write-Output ('同名修改或旧程序文件已保留在 ' + (Join-Path $Target 'Cage-preserved-files'))
264新增: }
265新增:} elseif ($Operation -eq 'cleanup') {
266新增: $transfer = Get-Content -LiteralPath $Receipt -Raw -Encoding UTF8 | ConvertFrom-Json
267新增: $actual = @(Read-Tree $Source @($transfer.files.path) | Where-Object { !($_.Attributes -band [IO.FileAttributes]::ReparsePoint) } | ForEach-Object { Relative-Path $Source $_.FullName })
268新增: foreach ($entry in $transfer.files) {
269新增: if ($entry.path -notin $actual) { continue }
270新增: try {
271新增: if ($entry.destination) {
272新增: $copy = Open-ReadLocked (Join-Path $Target $entry.destination)
273新增: try { if ((Stream-Hash $copy) -ne $entry.sha256) { continue } } finally { $copy.Dispose() }
274新增: }
275新增: Remove-MatchingFile $Source $entry.path $entry.sha256
276新增: } catch { Write-Output '安装期间变化或被占用的文件已保留在旧目录。' }
277新增: }
278新增: Remove-EmptyDirectories $Source $transfer.directories
279新增: if (@(Get-ChildItem -LiteralPath $Source -Force).Count) {
280新增: $recovery = Join-Path $Target ('Cage-preserved-files/late-' + [guid]::NewGuid().ToString('N'))
281新增: [IO.Directory]::CreateDirectory((Split-Path $recovery -Parent)) | Out-Null
282新增: [IO.Directory]::Move($Source, $recovery)
283新增: Write-Output ('安装期间变化的文件已保留在 ' + $recovery)
284新增: } else { [IO.Directory]::Delete($Source) }
285新增: Complete-Transfer
286新增:} elseif ($Operation -eq 'complete') {
287新增: Complete-Transfer
288新增:} else {
289新增: # The payload list comes from this uninstaller's embedded build manifest.
290新增: $owned = Read-FileManifest $Manifest
291新增: if (!$owned.Count) { throw '卸载文件清单无效,原文件已保留。' }
292新增: $installed = Read-FileManifest (Join-Path $Target $manifestName)
293新增: if ($installed.ContainsKey('Uninstall.exe')) { $owned['Uninstall.exe'] = $installed['Uninstall.exe'] }
294新增: $actual = @(Read-Tree $Target @($owned.Keys) | Where-Object { !($_.Attributes -band [IO.FileAttributes]::ReparsePoint) } | ForEach-Object { Relative-Path $Target $_.FullName })
295新增: foreach ($relative in $owned.Keys) {
296新增: if ($relative -ne $identityName -and $relative -in $actual) { Remove-MatchingFile $Target $relative $owned[$relative] }
297新增: }
298新增: if ($installed.Count) {
299新增: $manifestStream = Open-ReadLocked (Join-Path $Target $manifestName)
300新增: try { $manifestHash = Stream-Hash $manifestStream } finally { $manifestStream.Dispose() }
301新增: Remove-MatchingFile $Target $manifestName $manifestHash
302新增: }
303新增: $directories = @()
304新增: foreach ($relative in $owned.Keys) {
305新增: $directory = Split-Path $relative -Parent
306新增: while ($directory) { $directories += $directory.Replace('\', '/'); $directory = Split-Path $directory -Parent }
307新增: }
308新增: Remove-EmptyDirectories $Target $directories
309新增: # A retained identity lets a later installation reuse this data-bearing folder.
310新增: $remaining = @(Get-ChildItem -LiteralPath $Target -Force | Where-Object Name -ne $identityName)
311新增: if (!$remaining.Count) {
312新增: if ($owned.ContainsKey($identityName)) { Remove-MatchingFile $Target $identityName $owned[$identityName] }
313新增: if (@(Get-ChildItem -LiteralPath $Target -Force).Count -eq 0) { [IO.Directory]::Delete($Target) }
314新增: } else { Write-Output ('用户新增或修改的文件已保留在 ' + $Target) }
315新增:}
新增packaging/windows/verified-file-deletion.cs+78 −0看文件
@@ -0,0 +1,78 @@
1新增:using System;
2新增:using System.ComponentModel;
3新增:using System.IO;
4新增:using System.Runtime.InteropServices;
5新增:using Microsoft.Win32.SafeHandles;
6新增:
7新增:public static class CageVerifiedFile
8新增:{
9新增: [StructLayout(LayoutKind.Sequential)] private struct UnicodeString { public ushort Length, MaximumLength; public IntPtr Buffer; }
10新增: [StructLayout(LayoutKind.Sequential)] private struct ObjectAttributes
11新增: {
12新增: public int Length;
13新增: public IntPtr RootDirectory, ObjectName;
14新增: public uint Attributes;
15新增: public IntPtr SecurityDescriptor, SecurityQualityOfService;
16新增: }
17新增: [StructLayout(LayoutKind.Sequential)] private struct IOStatus { public IntPtr Status, Information; }
18新增: [StructLayout(LayoutKind.Sequential)] private struct AttributeTag { public uint Attributes, Tag; }
19新增:
20新增: [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
21新增: private static extern SafeFileHandle CreateFile(string path, uint access, uint share, IntPtr security, uint disposition, uint flags, IntPtr template);
22新增: [DllImport("kernel32.dll", SetLastError = true)]
23新增: private static extern bool GetFileInformationByHandleEx(SafeFileHandle file, int kind, out AttributeTag info, uint size);
24新增: [DllImport("kernel32.dll", SetLastError = true)]
25新增: private static extern bool SetFileInformationByHandle(SafeFileHandle file, int kind, ref byte delete, uint size);
26新增: [DllImport("ntdll.dll")]
27新增: private static extern int NtCreateFile(out SafeFileHandle file, uint access, ref ObjectAttributes attributes,
28新增: out IOStatus status, IntPtr allocationSize, uint fileAttributes, uint share, uint disposition, uint options, IntPtr ea, uint eaLength);
29新增: [DllImport("ntdll.dll")] private static extern uint RtlNtStatusToDosError(int status);
30新增:
31新增: public static FileStream Open(string root, string relative)
32新增: {
33新增: if (String.IsNullOrEmpty(relative) || Path.IsPathRooted(relative) || relative.IndexOf(':') >= 0)
34新增: throw new IOException("Invalid relative installation path");
35新增: foreach (string part in relative.Replace('/', '\\').Split('\\'))
36新增: if (part == ".." || part == "." || part.Length == 0) throw new IOException("Invalid relative installation path");
37新增:
38新增: // The directory handle anchors the lookup. OBJ_DONT_REPARSE also
39新增: // refuses a junction swapped into any ancestor of the relative path.
40新增: using (SafeFileHandle directory = CreateFile(root, 0x80000000, 7, IntPtr.Zero, 3, 0x02200000, IntPtr.Zero))
41新增: {
42新增: if (directory.IsInvalid) throw new Win32Exception(Marshal.GetLastWin32Error());
43新增: AttributeTag tag;
44新增: if (!GetFileInformationByHandleEx(directory, 9, out tag, 8)) throw new Win32Exception(Marshal.GetLastWin32Error());
45新增: if ((tag.Attributes & 0x400) != 0) throw new IOException("Installation directory is a reparse point");
46新增: IntPtr text = Marshal.StringToHGlobalUni(relative.Replace('/', '\\'));
47新增: IntPtr name = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(UnicodeString)));
48新增: try
49新增: {
50新增: UnicodeString value = new UnicodeString { Length = checked((ushort)(relative.Length * 2)), MaximumLength = checked((ushort)(relative.Length * 2)), Buffer = text };
51新增: Marshal.StructureToPtr(value, name, false);
52新增: ObjectAttributes attributes = new ObjectAttributes {
53新增: Length = Marshal.SizeOf(typeof(ObjectAttributes)), RootDirectory = directory.DangerousGetHandle(), ObjectName = name, Attributes = 0x1040,
54新增: };
55新增: IOStatus status;
56新增: SafeFileHandle file;
57新增: // GENERIC_READ | DELETE | SYNCHRONIZE, sharing read/delete
58新增: // but never writes while the verified handle is held.
59新增: int result = NtCreateFile(out file, 0x80110000, ref attributes, out status, IntPtr.Zero, 0, 5, 1, 0x00200060, IntPtr.Zero, 0);
60新增: if (result < 0) { if (file != null) file.Dispose(); throw new Win32Exception((int)RtlNtStatusToDosError(result)); }
61新增: try
62新增: {
63新增: if (!GetFileInformationByHandleEx(file, 9, out tag, 8)) throw new Win32Exception(Marshal.GetLastWin32Error());
64新增: if ((tag.Attributes & 0x410) != 0) throw new IOException("Installation file is a directory or reparse point");
65新增: return new FileStream(file, FileAccess.Read);
66新增: }
67新增: catch { file.Dispose(); throw; }
68新增: }
69新增: finally { Marshal.FreeHGlobal(name); Marshal.FreeHGlobal(text); }
70新增: }
71新增: }
72新增:
73新增: public static void Delete(FileStream file)
74新增: {
75新增: byte delete = 1;
76新增: if (!SetFileInformationByHandle(file.SafeFileHandle, 4, ref delete, 1)) throw new Win32Exception(Marshal.GetLastWin32Error());
77新增: }
78新增:}
修改scripts/cleanup-apps.mjs+13 −2看文件
@@ -33,13 +33,19 @@ function inUse(bundle) {
3333 throw error;
3434 }
3535}
36新增:function intact(bundle) {
37新增: try {
38新增: execFileSync('/usr/bin/codesign', ['--verify', '--deep', '--strict', bundle], { stdio: 'ignore' });
39新增: return true;
40新增: } catch { return false; }
41新增:}
3642
37删除:export async function cleanupApps({ keep, roots, onInUse = () => {} }) {
43新增:export async function cleanupApps({ keep, roots, onInUse = () => {}, onModified = () => {} }) {
3844 if (!keep.length)
3945 throw new Error("At least one verified Cage.app must be kept.");
4046 const retained = new Set();
4147 for (const bundle of keep) {
42删除: if (!isCage(bundle)) throw new Error(`Invalid replacement App: ${bundle}`);
48新增: if (!isCage(bundle) || !intact(bundle)) throw new Error(`Invalid replacement App: ${bundle}`);
4349 retained.add(await realpath(bundle));
4450 }
4551 const removed = [];
@@ -56,6 +62,10 @@ export async function cleanupApps({ keep, roots, onInUse = () => {} }) {
5662 if (retained.has(canonical)) return;
5763 if (directory.endsWith(".app")) {
5864 if (isCage(directory)) {
65新增: if (!intact(directory)) {
66新增: onModified(directory);
67新增: return;
68新增: }
5969 if (inUse(directory)) {
6070 onInUse(directory);
6171 return;
@@ -91,6 +101,7 @@ if (
91101 for (const bundle of await cleanupApps({
92102 keep, roots,
93103 onInUse: (bundle) => console.error(`Old Cage App is still running; quit it and rerun cleanup: ${bundle}`),
104新增: onModified: (bundle) => console.error(`旧应用包含修改内容或无法验证完整性,文件已保留:${bundle}`),
94105 }))
95106 console.log(`Removed old App: ${bundle}`);
96107}
修改scripts/cleanup-apps.test.mjs+19 −5看文件
@@ -11,7 +11,7 @@ import {
1111import os from "node:os";
1212import path from "node:path";
1313import test from "node:test";
14删除:import { spawn } from "node:child_process";
14新增:import { execFileSync, spawn } from "node:child_process";
1515import { cleanupApps } from "./cleanup-apps.mjs";
1616
1717const cageID = "io.github.lee-xeo.claude-cage";
@@ -21,9 +21,7 @@ test("cleanup preserves a Cage executable still in use", { skip: process.platfor
2121 try {
2222 const latest = await app(path.join(directory, "new.app"));
2323 const running = await app(path.join(directory, "running.app"));
24删除: await mkdir(path.join(running, "Contents/MacOS"));
2524 const executable = path.join(running, "Contents/MacOS/Cage");
26删除: await copyFile("/bin/sleep", executable);
2725 child = spawn(executable, ["30"], { stdio: "ignore" });
2826 await new Promise((resolve, reject) => { child.once("spawn", resolve); child.once("error", reject); });
2927 const skipped = [];
@@ -39,14 +37,30 @@ test("cleanup preserves a Cage executable still in use", { skip: process.platfor
3937 }
4038});
4139async function app(directory, id = cageID) {
42删除: await mkdir(path.join(directory, "Contents"), { recursive: true });
40新增: await mkdir(path.join(directory, "Contents/MacOS"), { recursive: true });
4341 await writeFile(
4442 path.join(directory, "Contents/Info.plist"),
45删除: `<?xml version="1.0"?><plist version="1.0"><dict><key>CFBundleIdentifier</key><string>${id}</string></dict></plist>`,
43新增: `<?xml version="1.0"?><plist version="1.0"><dict><key>CFBundleIdentifier</key><string>${id}</string><key>CFBundleExecutable</key><string>Cage</string><key>CFBundlePackageType</key><string>APPL</string></dict></plist>`,
4644 );
45新增: await copyFile('/bin/sleep', path.join(directory, 'Contents/MacOS/Cage'));
46新增: execFileSync('/usr/bin/codesign', ['--force', '--sign', '-', directory], { stdio: 'ignore' });
4747 return directory;
4848}
4949
50新增:test('cleanup retains project files added to a previously signed app', { skip: process.platform !== 'darwin' }, async (t) => {
51新增: const directory = await mkdtemp(path.join(os.tmpdir(), 'cage-cleanup-modified-'));
52新增: t.after(() => rm(directory, { recursive: true, force: true }));
53新增: const latest = await app(path.join(directory, 'new.app'));
54新增: const modified = await app(path.join(directory, 'old.app'));
55新增: const project = path.join(modified, 'Contents/my-project');
56新增: await mkdir(project);
57新增: await writeFile(path.join(project, 'work.txt'), 'user work');
58新增: const retained = [];
59新增: assert.deepEqual(await cleanupApps({ keep: [latest], roots: [directory], onModified: value => retained.push(value) }), []);
60新增: assert.deepEqual(retained, [modified]);
61新增: await access(path.join(project, 'work.txt'));
62新增:});
63新增:
5064test(
5165 "cleanup removes old Cage copies while retaining replacement, foreign apps and linked directories",
5266 { skip: process.platform !== "darwin" },
修改scripts/test-windows-install.ps1+46 −1看文件
@@ -15,18 +15,49 @@ function Assert-PersonalData {
1515 Invoke-BuildTool 'node' @($fixture, 'verify', $env:USERPROFILE, $manifest)
1616}
1717function Run-Installer {
18删除: param([switch]$Update, [int]$ExpectedExitCode = 0)
18新增: param([switch]$Update, [int]$ExpectedExitCode = 0, [string[]]$ShortcutOptions = @())
1919 $arguments = @('/S')
2020 if ($Update) { $arguments += '/UPDATE' }
21新增: $arguments += $ShortcutOptions
2122 $arguments += "/D=$target"
2223 $process = Start-Process -FilePath $Installer -ArgumentList $arguments -PassThru
2324 if (-not $process.WaitForExit(300000)) { throw 'Installer exceeded five minutes.' }
2425 if ($process.ExitCode -ne $ExpectedExitCode) { throw "Installer returned $($process.ExitCode), expected $ExpectedExitCode" }
2526}
27新增:$desktopShortcut = Join-Path ([Environment]::GetFolderPath('DesktopDirectory')) 'Cage.lnk'
28新增:$startMenuDirectory = Join-Path ([Environment]::GetFolderPath('Programs')) 'Cage'
29新增:function Assert-Shortcuts {
30新增: param([bool]$Desktop, [bool]$StartMenu)
31新增: if ((Test-Path -LiteralPath $desktopShortcut) -ne $Desktop) { throw 'Desktop shortcut differs from the installer selection.' }
32新增: foreach ($name in @('Cage.lnk', 'Uninstall Cage.lnk')) {
33新增: if ((Test-Path -LiteralPath (Join-Path $startMenuDirectory $name)) -ne $StartMenu) { throw "Start menu shortcut differs from the installer selection: $name" }
34新增: }
35新增: if ($Desktop) {
36新增: $shell = New-Object -ComObject WScript.Shell
37新增: if ($shell.CreateShortcut($desktopShortcut).TargetPath -ne (Join-Path $target 'Cage.exe')) { throw 'Desktop shortcut targets a different installation.' }
38新增: }
39新增:}
40新增:# Cover the directory-picker path where the user creates an empty folder first.
41新增:New-Item -ItemType Directory -Path $target | Out-Null
2642Run-Installer
2743Assert-PersonalData
44新增:Assert-Shortcuts $true $true
2845if (-not (Test-Path -LiteralPath (Join-Path $target 'Cage.exe'))) { throw 'Installer did not create Cage.exe.' }
46新增:foreach ($file in @('new-windows-guest.ps1', 'windows-guest-media.ps1', 'install-guest-powershell.cmd', 'publish-windows-component-manifest.ps1')) {
47新增: if (!(Test-Path -LiteralPath (Join-Path $target "resources/guest-os/$file") -PathType Leaf)) {
48新增: throw "Installed app is missing a Windows guest setup file: $file"
49新增: }
50新增:}
51新增:$phoneImports = @'
52新增:import { pathToFileURL } from 'node:url';
53新增:import { join } from 'node:path';
54新增:for (const file of ['windows-phone-browser.mjs', 'modules/browser-phone.mjs'])
55新增: await import(pathToFileURL(join(process.argv[1], file)));
56新增:'@
57新增:Invoke-BuildTool 'node' @('--input-type=module', '--eval', $phoneImports, (Join-Path $target 'resources/guest-os/payload'))
2958Invoke-BuildTool (Join-Path $target 'resources/cage.exe') @('--help')
59新增:Invoke-BuildTool (Join-Path $target 'resources/cage.exe') @('verify-vm-assets')
60新增:Invoke-BuildTool (Join-Path $target 'resources/cage.exe') @('verify-web-assets')
3061Invoke-BuildTool (Join-Path $target 'resources/mihomo.exe') @('-v')
3162Invoke-BuildTool (Join-Path $target 'resources/runtime/qemu/qemu-system-x86_64.exe') @('--version')
3263Invoke-BuildTool (Join-Path $target 'resources/runtime/openssh/ssh.exe') @('-V')
@@ -50,6 +81,18 @@ if ((Get-FileHash -LiteralPath (Join-Path $target 'Cage.exe') -Algorithm SHA256)
5081# Reinstall through the real atomic replacement path. User data must survive.
5182Run-Installer -Update
5283Assert-PersonalData
84新增:Assert-Shortcuts $true $true
85新增:Run-Installer -Update -ShortcutOptions @('/DESKTOPSHORTCUT=0', '/STARTMENUSHORTCUT=0')
86新增:Assert-Shortcuts $false $false
87新增:Run-Installer -Update
88新增:Assert-Shortcuts $false $false
89新增:Run-Installer -Update -ShortcutOptions @('/DESKTOPSHORTCUT=1', '/STARTMENUSHORTCUT=0')
90新增:Assert-Shortcuts $true $false
91新增:Run-Installer -Update -ShortcutOptions @('/DESKTOPSHORTCUT=0', '/STARTMENUSHORTCUT=1')
92新增:Assert-Shortcuts $false $true
93新增:Run-Installer -Update -ShortcutOptions @('/DESKTOPSHORTCUT=1', '/STARTMENUSHORTCUT=1')
94新增:Assert-Shortcuts $true $true
95新增:Assert-PersonalData
5396$uninstall = Start-Process -FilePath (Join-Path $target 'Uninstall.exe') -ArgumentList @('/S') -PassThru
5497if (-not $uninstall.WaitForExit(120000) -or $uninstall.ExitCode -ne 0) { throw 'Uninstall failed.' }
5598# NSIS may relaunch its uninstaller from TEMP so that it can delete the original.
@@ -57,5 +100,7 @@ $deadline = [DateTime]::UtcNow.AddSeconds(120)
57100while ((Test-Path -LiteralPath (Join-Path $target 'Uninstall.exe')) -and [DateTime]::UtcNow -lt $deadline) { Start-Sleep -Milliseconds 200 }
58101if (Test-Path -LiteralPath (Join-Path $target 'Cage.exe')) { throw 'Uninstall left Cage.exe behind.' }
59102if (Test-Path -LiteralPath (Join-Path $target 'Uninstall.exe')) { throw 'Uninstall left its launcher behind.' }
103新增:if (Test-Path -LiteralPath $target) { throw 'Uninstall left packaged files or directories that would block installation into the same folder.' }
60104Assert-PersonalData
105新增:Assert-Shortcuts $false $false
61106Write-Host 'Install, WebView2 workbench, reinstall, uninstall and user-data preservation passed. VM startup was not tested.'
新增scripts/test-windows-installation-files.ps1+237 −0看文件
@@ -0,0 +1,237 @@
1新增:#requires -Version 5.1
2新增:param([string]$HelperShell = (Get-Process -Id $PID).Path)
3新增:$ErrorActionPreference = 'Stop'
4新增:$helper = Join-Path $PSScriptRoot '../packaging/windows/installation-files.ps1'
5新增:$root = Join-Path ([IO.Path]::GetTempPath()) ('cage-install-files-' + [guid]::NewGuid().ToString('N'))
6新增:$checks = 0
7新增:$windows = $env:OS -eq 'Windows_NT'
8新增:function Check([bool]$Value, [string]$Message) {
9新增: if (!$Value) { throw $Message }
10新增: $script:checks++
11新增:}
12新增:function Write-File([string]$Path, [string]$Value) {
13新增: [IO.Directory]::CreateDirectory((Split-Path $Path -Parent)) | Out-Null
14新增: [IO.File]::WriteAllText($Path, $Value)
15新增:}
16新增:function New-FileLink([string]$Path, [string]$Target) {
17新增: if ($windows) {
18新增: & cmd.exe /c mklink $Path.Replace('/', '\') $Target.Replace('/', '\') | Out-Null
19新增: if ($LASTEXITCODE -ne 0) { throw 'Could not create the isolated file link fixture.' }
20新增: } else { [IO.File]::CreateSymbolicLink($Path, $Target) | Out-Null }
21新增:}
22新增:function Read-Link([string]$Path) {
23新增: $entry = Get-Item -LiteralPath $Path -Force
24新增: if ($windows) { return ([string]@($entry.Target)[0]).Replace('\', '/') }
25新增: return $entry.LinkTarget
26新增:}
27新增:function Remove-TestTree([string]$Path) {
28新增: foreach ($entry in Get-ChildItem -LiteralPath $Path -Force) {
29新增: if (!$windows -and $entry.Attributes -band [IO.FileAttributes]::ReparsePoint) {
30新增: [IO.File]::Delete($entry.FullName)
31新增: } elseif ($entry.Attributes -band [IO.FileAttributes]::Directory) {
32新增: if (!($entry.Attributes -band [IO.FileAttributes]::ReparsePoint)) { Remove-TestTree $entry.FullName }
33新增: [IO.Directory]::Delete($entry.FullName)
34新增: } else { [IO.File]::Delete($entry.FullName) }
35新增: }
36新增:}
37新增:function App([string]$Path, [string]$Version) {
38新增: Write-File (Join-Path $Path 'Cage.install-id') 'io.github.lee-xeo.claude-cage'
39新增: Write-File (Join-Path $Path 'program.txt') $Version
40新增: Write-File (Join-Path $Path 'resources/customizable.txt') ('default-' + $Version)
41新增: Write-File (Join-Path $Path 'Uninstall.exe') ('uninstaller-' + $Version)
42新增: $files = @(Get-ChildItem -LiteralPath $Path -File -Recurse | ForEach-Object {
43新增: @{path = $_.FullName.Substring($Path.TrimEnd('\','/').Length + 1).Replace('\', '/'); sha256 = (Get-FileHash $_.FullName).Hash.ToLowerInvariant()}
44新增: })
45新增: @{version = 1; files = $files} | ConvertTo-Json -Depth 4 | Set-Content (Join-Path $Path 'Cage.install-files.json')
46新增:}
47新增:function Invoke-Helper([string[]]$Arguments, [int]$Expected = 0) {
48新增: try {
49新增: $ErrorActionPreference = 'Continue'
50新增: $output = & $HelperShell -NoProfile -File $helper @Arguments 2>&1 | Out-String
51新增: } finally { $ErrorActionPreference = 'Stop' }
52新增: if ($LASTEXITCODE -ne $Expected) { throw "Helper returned $LASTEXITCODE, expected $Expected. $output" }
53新增:}
54新增:function Prepare([string]$Old, [string]$Stage, [string]$Receipt) {
55新增: Invoke-Helper @('-Operation','prepare','-Source',$Old,'-Target',$Stage,'-Receipt',$Receipt,'-Backup',($Old+'-backup'))
56新增:}
57新增:function Commit([string]$Old, [string]$Stage, [string]$Receipt) {
58新增: $backup = $Old + '-backup'
59新增: [IO.Directory]::Move($Old, $backup)
60新增: Invoke-Helper @('-Operation','move','-Source',$backup,'-Target',$Stage,'-Receipt',$Receipt)
61新增: [IO.Directory]::Move($Stage, $Old)
62新增: Invoke-Helper @('-Operation','cleanup','-Source',$backup,'-Target',$Old,'-Receipt',$Receipt)
63新增: return $backup
64新增:}
65新增:try {
66新增: foreach ($manifestState in @('current','missing','invalid')) {
67新增: $scenario = Join-Path $root $manifestState
68新增: $old = Join-Path $scenario 'installed'; $stage = Join-Path $scenario 'staged'; $receipt = Join-Path $scenario 'receipt.json'
69新增: App $old 'old'; App $stage 'new'
70新增: $manifest = Join-Path $old 'Cage.install-files.json'
71新增: if ($manifestState -eq 'missing') { Remove-Item $manifest }
72新增: if ($manifestState -eq 'invalid') { Write-File $manifest '{broken' }
73新增: Write-File (Join-Path $old 'my-project/work.txt') 'project data'
74新增: Write-File (Join-Path $old 'resources/customizable.txt') 'user customization'
75新增: Write-File (Join-Path $scenario 'outside/config.txt') 'outside data'
76新增: [IO.Directory]::CreateDirectory((Join-Path $old 'empty-project')) | Out-Null
77新增: Prepare $old $stage $receipt
78新增: Check ((Get-Content (Join-Path $old 'program.txt') -Raw) -eq 'old') 'Preparation modified the original installation.'
79新增: $backup = Commit $old $stage $receipt
80新增: Check ((Get-Content (Join-Path $old 'program.txt') -Raw) -eq 'new') 'New program was overwritten by legacy files.'
81新增: Check ((Get-Content (Join-Path $old 'my-project/work.txt') -Raw) -eq 'project data') 'Project data was lost.'
82新增: Check ((Get-Content (Join-Path $scenario 'outside/config.txt') -Raw) -eq 'outside data') 'External profile was modified.'
83新增: Check (Test-Path (Join-Path $old 'empty-project') -PathType Container) 'Empty project directory was lost.'
84新增: $copies = @(Get-ChildItem (Join-Path $old 'Cage-preserved-files') -File -Recurse | Where-Object { (Get-Content $_.FullName -Raw) -eq 'user customization' })
85新增: Check ($copies.Count -eq 1) 'Modified same-name program content was not retained exactly once.'
86新增: Check (!(Test-Path $backup)) 'Completed transfer left a full old application copy.'
87新增: $embedded = Join-Path $scenario 'embedded.json'
88新增: Copy-Item (Join-Path $old 'Cage.install-files.json') $embedded
89新增: Write-File (Join-Path $old 'resources/customizable.txt') 'new customization'
90新增: Invoke-Helper @('-Operation','uninstall','-Target',$old,'-Manifest',$embedded)
91新增: Check (!(Test-Path (Join-Path $old 'program.txt'))) 'Uninstaller retained an unchanged program file.'
92新增: Check ((Get-Content (Join-Path $old 'my-project/work.txt') -Raw) -eq 'project data') 'Uninstall deleted a project.'
93新增: Check ((Get-Content (Join-Path $old 'resources/customizable.txt') -Raw) -eq 'new customization') 'Uninstall deleted a modified program file.'
94新增: Check (Test-Path (Join-Path $old 'empty-project') -PathType Container) 'Uninstall deleted an unknown empty project.'
95新增: Check (Test-Path (Join-Path $old 'Cage.install-id')) 'Retained data directory cannot be recognized on reinstall.'
96新增: App $stage 'reinstalled'
97新增: Prepare $old $stage $receipt
98新增: $null = Commit $old $stage $receipt
99新增: Check ((Get-Content (Join-Path $old 'my-project/work.txt') -Raw) -eq 'project data') 'Reinstall after uninstall lost the project.'
100新增: }
101新增: $scenario = Join-Path $root 'concurrent'
102新增: $old = Join-Path $scenario 'installed'; $stage = Join-Path $scenario 'staged'; $receipt = Join-Path $scenario 'receipt.json'
103新增: App $old 'old'; App $stage 'new'
104新增: Write-File (Join-Path $old 'project.txt') 'first'
105新增: Prepare $old $stage $receipt
106新增: Write-File (Join-Path $old 'project.txt') 'late edit'
107新增: Write-File (Join-Path $old 'new-project.txt') 'created during install'
108新增: [IO.Directory]::CreateDirectory((Join-Path $old 'late-empty-project')) | Out-Null
109新增: $null = Commit $old $stage $receipt
110新增: $late = @(Get-ChildItem (Join-Path $old 'Cage-preserved-files') -File -Recurse)
111新增: Check ((Get-Content (Join-Path $old 'project.txt') -Raw) -eq 'late edit') 'Concurrent edit was deleted.'
112新增: Check (@($late | Where-Object { (Get-Content $_.FullName -Raw) -eq 'created during install' }).Count -eq 1) 'Concurrent new file was deleted.'
113新增: Check (@(Get-ChildItem (Join-Path $old 'Cage-preserved-files') -Directory -Recurse | Where-Object Name -eq 'late-empty-project').Count -eq 1) 'Concurrent empty project was deleted.'
114新增: $scenario = Join-Path $root 'rollback'
115新增: $old = Join-Path $scenario 'installed'; $stage = Join-Path $scenario 'staged'; $receipt = Join-Path $scenario 'receipt.json'
116新增: App $old 'old'; App $stage 'new'
117新增: Write-File (Join-Path $old 'project.txt') 'rollback project'
118新增: Prepare $old $stage $receipt
119新增: $backup = $old + '-backup'
120新增: [IO.Directory]::Move($old, $backup)
121新增: Remove-Item -LiteralPath $stage -Recurse
122新增: try { [IO.Directory]::Move($stage, $old); throw 'Expected the missing stage to fail.' }
123新增: catch [IO.DirectoryNotFoundException] { [IO.Directory]::Move($backup, $old) }
124新增: Invoke-Helper @('-Operation','complete','-Target',$old,'-Receipt',$receipt)
125新增: Check ((Get-Content (Join-Path $old 'project.txt') -Raw) -eq 'rollback project') 'Failed replacement lost the original project.'
126新增: Check ((Get-Content (Join-Path $old 'program.txt') -Raw) -eq 'old') 'Failed replacement changed the original program.'
127新增: $stage = Join-Path $scenario 'staged-again'; App $stage 'new'
128新增: $locked = [IO.File]::Open((Join-Path $old 'program.txt'), 'Open', 'ReadWrite', 'None')
129新增: try { Invoke-Helper @('-Operation','prepare','-Source',$old,'-Target',$stage,'-Receipt',$receipt) 1 }
130新增: finally { $locked.Dispose() }
131新增: Check ((Get-Content (Join-Path $old 'project.txt') -Raw) -eq 'rollback project') 'Failed preparation changed a locked project.'
132新增: $fresh = Join-Path $root 'fresh'; App $fresh 'fresh'
133新增: $embedded = Join-Path $root 'fresh-embedded.json'; Copy-Item (Join-Path $fresh 'Cage.install-files.json') $embedded
134新增: Invoke-Helper @('-Operation','uninstall','-Target',$fresh,'-Manifest',$embedded)
135新增: Check (!(Test-Path $fresh)) 'An unmodified installation was not fully removed.'
136新增: $scenario = Join-Path $root 'links'
137新增: $old = Join-Path $scenario 'installed'; $stage = Join-Path $scenario 'staged'; $receipt = Join-Path $scenario 'receipt.json'
138新增: App $old 'old'; App $stage 'new'
139新增: Write-File (Join-Path $scenario 'outside/target.txt') 'external link target'
140新增: [IO.Directory]::CreateDirectory((Join-Path $old 'my-project')) | Out-Null
141新增: New-FileLink (Join-Path $old 'my-project/relative.txt') '../../outside/target.txt'
142新增: New-FileLink (Join-Path $old 'my-project/missing.txt') 'missing-target'
143新增: $junction = Join-Path $old 'my-project/junction'
144新增: if ($windows) {
145新增: & cmd.exe /c mklink /J $junction (Join-Path $scenario 'outside') | Out-Null
146新增: if ($LASTEXITCODE -ne 0) { throw 'Could not create the isolated junction fixture.' }
147新增: } else { [IO.Directory]::CreateSymbolicLink($junction, (Join-Path $scenario 'outside')) | Out-Null }
148新增: Prepare $old $stage $receipt
149新增: $null = Commit $old $stage $receipt
150新增: Check ((Read-Link (Join-Path $old 'my-project/relative.txt')) -eq '../../outside/target.txt') 'Relative symlink text changed during installation.'
151新增: Check ((Get-Content (Join-Path $old 'my-project/relative.txt') -Raw) -eq 'external link target') 'Relative symlink no longer reaches its target.'
152新增: Check ((Read-Link (Join-Path $old 'my-project/missing.txt')) -eq 'missing-target') 'Dangling symlink was lost.'
153新增: Check ((Get-Content (Join-Path $junction 'target.txt') -Raw) -eq 'external link target') 'Directory link was not retained.'
154新增: $embedded = Join-Path $scenario 'embedded.json'; Copy-Item (Join-Path $old 'Cage.install-files.json') $embedded
155新增: Invoke-Helper @('-Operation','uninstall','-Target',$old,'-Manifest',$embedded)
156新增: Check ((Get-Content (Join-Path $scenario 'outside/target.txt') -Raw) -eq 'external link target') 'Uninstall changed an external link target.'
157新增: Check ((Read-Link (Join-Path $old 'my-project/relative.txt')) -eq '../../outside/target.txt') 'Uninstall removed a project link.'
158新增: $scenario = Join-Path $root 'linked-program-directory'
159新增: $old = Join-Path $scenario 'installed'; App $old 'old'
160新增: $embedded = Join-Path $scenario 'embedded.json'; Copy-Item (Join-Path $old 'Cage.install-files.json') $embedded
161新增: Write-File (Join-Path $scenario 'outside/customizable.txt') 'default-old'
162新增: Remove-Item (Join-Path $old 'resources') -Recurse
163新增: if ($windows) {
164新增: & cmd.exe /c mklink /J (Join-Path $old 'resources') (Join-Path $scenario 'outside') | Out-Null
165新增: if ($LASTEXITCODE -ne 0) { throw 'Could not create the isolated junction fixture.' }
166新增: } else { [IO.Directory]::CreateSymbolicLink((Join-Path $old 'resources'), (Join-Path $scenario 'outside')) | Out-Null }
167新增: Invoke-Helper @('-Operation','uninstall','-Target',$old,'-Manifest',$embedded)
168新增: Check ((Get-Content (Join-Path $scenario 'outside/customizable.txt') -Raw) -eq 'default-old') 'Uninstall followed a replaced program directory link.'
169新增: Check ([bool]((Get-Item (Join-Path $old 'resources') -Force).Attributes -band [IO.FileAttributes]::ReparsePoint)) 'Uninstall removed a user directory link.'
170新增: $scenario = Join-Path $root 'linked-installation-root'
171新增: $actual = Join-Path $scenario 'actual'; $old = Join-Path $scenario 'installed'; $stage = Join-Path $scenario 'staged'; $receipt = Join-Path $scenario 'receipt.json'
172新增: App $actual 'old'; App $stage 'new'
173新增: Write-File (Join-Path $actual 'my-project/work.txt') 'external installation project'
174新增: if ($windows) {
175新增: & cmd.exe /c mklink /J $old $actual | Out-Null
176新增: if ($LASTEXITCODE -ne 0) { throw 'Could not create the isolated installation junction.' }
177新增: } else { [IO.Directory]::CreateSymbolicLink($old, $actual) | Out-Null }
178新增: Invoke-Helper @('-Operation','prepare','-Source',$old,'-Target',$stage,'-Receipt',$receipt) 1
179新增: Check ((Get-Content (Join-Path $actual 'my-project/work.txt') -Raw) -eq 'external installation project') 'Preparation followed the installation root link and changed its target.'
180新增: Check (!(Test-Path $receipt)) 'Preparation published a transaction for a redirected installation root.'
181新增: $scenario = Join-Path $root 'move-rollback'
182新增: $old = Join-Path $scenario 'installed'; $stage = Join-Path $scenario 'staged'; $receipt = Join-Path $scenario 'receipt.json'
183新增: App $old 'old'; App $stage 'new'
184新增: Write-File (Join-Path $old 'first-project/work.txt') 'first user project'
185新增: Write-File (Join-Path $old 'second-project/work.txt') 'second user project'
186新增: New-FileLink (Join-Path $old 'first-project/link.txt') 'work.txt'
187新增: Prepare $old $stage $receipt
188新增: $moves = @((Get-Content $receipt -Raw | ConvertFrom-Json).moves)
189新增: $backup = $old + '-backup'; [IO.Directory]::Move($old, $backup)
190新增: [IO.Directory]::CreateDirectory((Join-Path $stage $moves[-1].destination)) | Out-Null
191新增: Invoke-Helper @('-Operation','move','-Source',$backup,'-Target',$stage,'-Receipt',$receipt) 1
192新增: Invoke-Helper @('-Operation','restore','-Source',$stage,'-Target',$backup,'-Receipt',$receipt)
193新增: [IO.Directory]::Move($backup, $old)
194新增: Check ((Get-Content (Join-Path $old 'first-project/work.txt') -Raw) -eq 'first user project') 'Rollback missed an already moved project.'
195新增: Check ((Get-Content (Join-Path $old 'second-project/work.txt') -Raw) -eq 'second user project') 'Rollback changed the project whose move failed.'
196新增: Check ((Read-Link (Join-Path $old 'first-project/link.txt')) -eq 'work.txt') 'Rollback changed a relative project link.'
197新增: $scenario = Join-Path $root 'type-conflicts'
198新增: $old = Join-Path $scenario 'installed'; $stage = Join-Path $scenario 'staged'; $receipt = Join-Path $scenario 'receipt.json'
199新增: App $old 'old'; App $stage 'new'
200新增: Remove-Item (Join-Path $old 'Cage.install-files.json')
201新增: Write-File (Join-Path $old 'obsolete.dll') 'obsolete library'
202新增: Write-File (Join-Path $old 'resources/new-tool/data.txt') 'user directory'
203新增: Write-File (Join-Path $stage 'resources/new-tool') 'new program file'
204新增: Prepare $old $stage $receipt
205新增: $null = Commit $old $stage $receipt
206新增: Check (!(Test-Path (Join-Path $old 'obsolete.dll'))) 'Legacy unknown DLL remained in the new application loader path.'
207新增: Check ((Get-Content (Join-Path $old 'resources/new-tool') -Raw) -eq 'new program file') 'A user directory replaced a new program file.'
208新增: $retained = @(Get-ChildItem (Join-Path $old 'Cage-preserved-files') -File -Recurse)
209新增: Check (@($retained | Where-Object { (Get-Content $_.FullName -Raw) -eq 'obsolete library' }).Count -eq 1) 'Legacy DLL bytes were lost.'
210新增: Check (@($retained | Where-Object { (Get-Content $_.FullName -Raw) -eq 'user directory' }).Count -eq 1) 'Conflicting user directory was lost.'
211新增: $scenario = Join-Path $root 'legacy-automatic-rollback'
212新增: $old = Join-Path $scenario 'installed'; $stage = Join-Path $scenario 'restored'; $receipt = Join-Path $scenario 'receipt.json'
213新增: App $stage 'old-program'
214新增: Remove-Item (Join-Path $stage 'Cage.install-files.json')
215新增: Write-File (Join-Path $stage 'my-project/work.txt') 'before attempted update'
216新增: Write-File (Join-Path $stage 'personal.txt') 'old personal file'
217新增: App $old 'failed-new-program'
218新增: Write-File (Join-Path $old 'my-project/work.txt') 'saved while the new version was running'
219新增: Write-File (Join-Path $old 'personal.txt') 'latest personal file'
220新增: New-FileLink (Join-Path $old 'my-project/latest-link.txt') 'work.txt'
221新增: Invoke-Helper @('-Operation','prepare','-Source',$old,'-Target',$stage,'-Receipt',$receipt,'-Backup',($old+'-backup'),'-LegacyTarget')
222新增: $null = Commit $old $stage $receipt
223新增: Check ((Get-Content (Join-Path $old 'program.txt') -Raw) -eq 'old-program') 'Legacy recovery did not restore the previous program.'
224新增: Check ((Get-Content (Join-Path $old 'my-project/work.txt') -Raw) -eq 'saved while the new version was running') 'Legacy recovery put an old project at the active path.'
225新增: Check ((Get-Content (Join-Path $old 'personal.txt') -Raw) -eq 'latest personal file') 'Legacy recovery put an old personal file at the active path.'
226新增: Check ((Read-Link (Join-Path $old 'my-project/latest-link.txt')) -eq 'work.txt') 'Legacy recovery lost the current relative link.'
227新增: $previousCopies = @(Get-ChildItem (Join-Path $old 'Cage-preserved-files') -File -Recurse)
228新增: Check (@($previousCopies | Where-Object { (Get-Content $_.FullName -Raw) -eq 'before attempted update' }).Count -eq 1) 'Legacy recovery deleted the previous project version.'
229新增: Check (@($previousCopies | Where-Object { (Get-Content $_.FullName -Raw) -eq 'old personal file' }).Count -eq 1) 'Legacy recovery deleted the previous personal-file version.'
230新增: if ($windows) {
231新增: & $HelperShell -NoProfile -File (Join-Path $PSScriptRoot 'test-windows-verified-file-deletion.ps1')
232新增: if ($LASTEXITCODE -ne 0) { throw 'Verified-handle deletion regression failed.' }
233新增: }
234新增: Write-Output "Installation file ownership: $checks checks passed."
235新增:} finally {
236新增: if (Test-Path -LiteralPath $root) { Remove-TestTree $root; [IO.Directory]::Delete($root) }
237新增:}
新增scripts/test-windows-verified-file-deletion.ps1+59 −0看文件
@@ -0,0 +1,59 @@
1新增:#requires -Version 5.1
2新增:$ErrorActionPreference = 'Stop'
3新增:$source = Join-Path $PSScriptRoot '../packaging/windows'
4新增:$root = Join-Path ([IO.Path]::GetTempPath()) ('delete-race-' + [guid]::NewGuid().ToString('N'))
5新增:New-Item -ItemType Directory -Path $root | Out-Null
6新增:try {
7新增: Add-Type -Path (Join-Path $source 'verified-file-deletion.cs')
8新增: $tokens = $null
9新增: $errors = $null
10新增: $ast = [Management.Automation.Language.Parser]::ParseFile((Join-Path $source 'installation-files.ps1'), [ref]$tokens, [ref]$errors)
11新增: if ($errors.Count) { throw 'The production installation helper has syntax errors.' }
12新增: $definitions = $ast.FindAll({ param($node) $node -is [Management.Automation.Language.FunctionDefinitionAst] }, $true)
13新增: foreach ($definition in $definitions) {
14新增: if ($definition.Name -in @('Open-ReadLocked', 'Stream-Hash', 'Initialize-VerifiedDeletion', 'Remove-MatchingFile')) {
15新增: . ([scriptblock]::Create($definition.Extent.Text))
16新增: }
17新增: }
18新增:
19新增: $script:originalHash = (Get-Item function:Stream-Hash).ScriptBlock
20新增: $script:replacePath = Join-Path $root 'program.dll'
21新增: $script:renamedPath = Join-Path $root 'original-renamed.dll'
22新增: [IO.File]::WriteAllText($script:replacePath, 'verified old program')
23新增: $expected = (Get-FileHash $script:replacePath).Hash
24新增: function Stream-Hash([IO.Stream]$Stream) {
25新增: $hash = & $script:originalHash $Stream
26新增: [IO.File]::Move($script:replacePath, $script:renamedPath)
27新增: [IO.File]::WriteAllText($script:replacePath, 'new personal data')
28新增: return $hash
29新增: }
30新增: Remove-MatchingFile $root 'program.dll' $expected
31新增: $replacementRetained = [IO.File]::ReadAllText($script:replacePath) -eq 'new personal data'
32新增: $verifiedObjectDeleted = !(Test-Path $script:renamedPath)
33新增:
34新增: $outside = Join-Path $root 'outside'
35新增: New-Item -ItemType Directory -Path $outside | Out-Null
36新增: [IO.File]::WriteAllText((Join-Path $outside 'owned.dll'), 'external target')
37新增: $link = Join-Path $root 'linked'
38新增: & cmd.exe /c mklink /J $link $outside | Out-Null
39新增: if ($LASTEXITCODE -ne 0) { throw 'Could not create the isolated junction fixture.' }
40新增: $reparseDenied = $false
41新增: try {
42新增: $stream = [CageVerifiedFile]::Open($root, 'linked/owned.dll')
43新增: $stream.Dispose()
44新增: } catch { $reparseDenied = $true }
45新增: $externalRetained = [IO.File]::ReadAllText((Join-Path $outside 'owned.dll')) -eq 'external target'
46新增: [pscustomobject]@{
47新增: ReplacementRetained = $replacementRetained
48新增: VerifiedObjectDeleted = $verifiedObjectDeleted
49新增: ReparseTraversalDenied = $reparseDenied
50新增: ExternalTargetRetained = $externalRetained
51新增: PowerShell = $PSVersionTable.PSVersion.ToString()
52新增: } | ConvertTo-Json -Compress
53新增: if (!$replacementRetained -or !$verifiedObjectDeleted -or !$reparseDenied -or !$externalRetained) {
54新增: throw 'Verified-handle deletion postconditions failed.'
55新增: }
56新增:} finally {
57新增: if (Test-Path -LiteralPath (Join-Path $root 'linked')) { [IO.Directory]::Delete((Join-Path $root 'linked')) }
58新增: Remove-Item -LiteralPath $root -Recurse -Force
59新增:}
新增scripts/windows-native-bridge.test.mjs+65 −0看文件
@@ -0,0 +1,65 @@
1新增:import test from 'node:test';
2新增:import assert from 'node:assert/strict';
3新增:import { readFile } from 'node:fs/promises';
4新增:import { randomUUID } from 'node:crypto';
5新增:import vm from 'node:vm';
6新增:
7新增:const source = await readFile(new URL('../desktop/windows/MainWindow.cs', import.meta.url), 'utf8');
8新增:const script = source.match(/private const string BridgeScript = """\s*([\s\S]*?)\s*""";/)?.[1];
9新增:assert.ok(script);
10新增:
11新增:function bridge() {
12新增: let reply, sent;
13新增: const timers = new Map();
14新增: const window = {};
15新增: window.top = window;
16新增: vm.runInNewContext(script, {
17新增: window, location: { protocol: 'http:', hostname: 'localhost' }, crypto: { randomUUID },
18新增: chrome: { webview: {
19新增: addEventListener: (_, callback) => { reply = callback; },
20新增: postMessage: value => { sent = value; },
21新增: } },
22新增: setTimeout: (callback, delay) => { const id = randomUUID(); timers.set(id, { callback, delay }); return id; },
23新增: clearTimeout: id => timers.delete(id),
24新增: });
25新增: return {
26新增: call: request => window.webkit.messageHandlers.cage.postMessage(request),
27新增: reply: value => reply({ data: { id: sent.id, ...value } }),
28新增: timers,
29新增: };
30新增:}
31新增:
32新增:test('native file replies remain pending beyond four minutes and through the backend deadline', async () => {
33新增: for (const action of ['uploadHostFiles', 'chooseUploadFiles', 'clipboardSyncRead', 'clipboardSyncWrite',
34新增: 'saveBrowserDownload', 'browserDownloadAction', 'desktopFileAction', 'exportDiagnostics', 'importTheme', 'exportTheme',
35新增: 'shareLocalProject', 'chooseFolder', 'chooseGuestMedia']) {
36新增: const fixture = bridge();
37新增: const pending = fixture.call({ action });
38新增: const timer = [...fixture.timers.values()][0];
39新增: assert.ok(timer.delay > 30 * 60 * 1000, action);
40新增: fixture.reply({ result: { saved: true } });
41新增: assert.equal((await pending).saved, true, action);
42新增: assert.equal(fixture.timers.size, 0);
43新增: }
44新增:});
45新增:
46新增:test('file failure reaches the caller and the following request can succeed', async () => {
47新增: const fixture = bridge();
48新增: const first = fixture.call({ action: 'saveBrowserDownload' });
49新增: fixture.reply({ error: '磁盘空间不足' });
50新增: await assert.rejects(first, /磁盘空间不足/);
51新增: const second = fixture.call({ action: 'clipboardSyncRead' });
52新增: fixture.reply({ result: { text: 'next copy' } });
53新增: assert.equal((await second).text, 'next copy');
54新增: assert.equal(fixture.timers.size, 0);
55新增:});
56新增:
57新增:test('ordinary native commands retain their bounded timeout', async () => {
58新增: const fixture = bridge();
59新增: const pending = fixture.call({ action: 'accountDevice' });
60新增: const timer = [...fixture.timers.values()][0];
61新增: assert.equal(timer.delay, 240_000);
62新增: timer.callback();
63新增: await assert.rejects(pending, /原生操作超时/);
64新增: fixture.reply({ result: true });
65新增:});