提交记录修改desktop/Updates.swift+15 −3看文件
修改desktop/UpdatesTests.swift+22 −0看文件
修改desktop/windows.tests/Cage.Windows.Tests.csproj+6 −0看文件
修改desktop/windows.tests/Program.cs+103 −2看文件
修改desktop/windows/AppUpdater.cs+9 −3看文件
修改desktop/windows/Cage.Windows.csproj+3 −0看文件
修改desktop/windows/UpdateInstaller.cs+126 −9看文件
新增internal/appupdate/retry.go+48 −0看文件
新增internal/appupdate/retry_test.go+69 −0看文件
修改internal/appupdate/update.go+21 −7看文件
修改internal/appupdate/update_test.go+1 −1看文件
新增internal/appupdate/waiting_test.go+42 −0看文件
修改packaging/windows/Cage.nsi+261 −19看文件
修改packaging/windows/README.txt+16 −1看文件
新增packaging/windows/installation-files.ps1+315 −0看文件
新增packaging/windows/verified-file-deletion.cs+78 −0看文件
修改scripts/cleanup-apps.mjs+13 −2看文件
修改scripts/cleanup-apps.test.mjs+19 −5看文件
修改scripts/test-windows-install.ps1+46 −1看文件
新增scripts/test-windows-installation-files.ps1+237 −0看文件
新增scripts/test-windows-verified-file-deletion.ps1+59 −0看文件
新增scripts/windows-native-bridge.test.mjs+65 −0看文件
| @@ -7,7 +7,11 @@ let cageUpdateBundleID = "io.github.lee-xeo.claude-cage" | ||
| 7 | 7 | |
| 8 | 8 | enum CageProfile { |
| 9 | 9 | static var clientOnly: Bool { Bundle.main.object(forInfoDictionaryKey: "CageClientOnly") as? Bool == true } |
| 10 | 新增: static var macGuestTrial: Bool { Bundle.main.bundleIdentifier == cageUpdateBundleID + ".macos-trial" } | |
| 10 | 11 | static func configURL() -> URL { |
| 12 | 新增: if macGuestTrial { | |
| 13 | 新增: return FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".claude-cage/macos-trial/config.json") | |
| 14 | 新增: } | |
| 11 | 15 | if let path = ProcessInfo.processInfo.environment["CLAUDE_CAGE_CONFIG"], !path.isEmpty { |
| 12 | 16 | return URL(fileURLWithPath: path).standardizedFileURL |
| 13 | 17 | } |
| @@ -269,6 +273,12 @@ final class CageAppUpdater { | ||
| 269 | 273 | } |
| 270 | 274 | } |
| 271 | 275 | 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 | 新增: } | |
| 272 | 282 | if Bundle(url: bundleURL)?.object(forInfoDictionaryKey: "CageClientOnly") as? Bool == true { |
| 273 | 283 | if state["phase"] as? String != "manual" || operation != "status" { |
| 274 | 284 | change(["phase": "manual", "message": "轻量客户端使用独立安装包更新;连接配置会保留,云端任务不受影响。"]) |
| @@ -276,6 +286,8 @@ final class CageAppUpdater { | ||
| 276 | 286 | return state |
| 277 | 287 | } |
| 278 | 288 | 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 } | |
| 279 | 291 | switch operation { |
| 280 | 292 | case "status": break |
| 281 | 293 | case "check": if !busy && worker == nil && validationTask == nil && installer == nil && prepared == nil { startDownload(checkOnly: true) } |
| @@ -332,11 +344,11 @@ final class CageAppUpdater { | ||
| 332 | 344 | for (key, value) in values { state[key] = value } |
| 333 | 345 | onChange(state) |
| 334 | 346 | } |
| 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]) } | |
| 336 | 348 | private var cage: URL { bundleURL.appendingPathComponent("Contents/Resources/cage") } |
| 337 | 349 | private func startDownload(checkOnly: Bool) { |
| 338 | 350 | 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": ""]) | |
| 340 | 352 | let process = Process(); process.executableURL = cage; process.arguments = ["app-update", checkOnly ? "check" : "download"] |
| 341 | 353 | let pipe = Pipe(); process.standardOutput = pipe; process.standardError = FileHandle.nullDevice |
| 342 | 354 | worker = process |
| @@ -362,7 +374,7 @@ final class CageAppUpdater { | ||
| 362 | 374 | if self.worker === process { self.worker = nil } |
| 363 | 375 | guard self.generation == operation else { return } |
| 364 | 376 | if process.terminationStatus != 0 { |
| 365 | 删除: self.failure(result?["message"] as? String ?? "更新请求未完成,请重试") | |
| 377 | 新增: self.failure(result?["message"] as? String ?? "更新请求未完成,请重试", retryAt: result?["retryAt"] as? String ?? "") | |
| 366 | 378 | } else if !checkOnly, let result, result["phase"] as? String == "downloaded" { |
| 367 | 379 | self.verifyDownload(result, operation: operation) |
| 368 | 380 | } |
| @@ -168,6 +168,28 @@ enum UpdatesTests { | ||
| 168 | 168 | try expect(!updater.awaitingInitialWorkbench, "initialized workbench keeps ordinary quit confirmation") |
| 169 | 169 | try expect(FileManager.default.fileExists(atPath: root.appendingPathComponent("profile/updates/launch-\(confirmation).json").path), "explicit workbench readiness writes installer acknowledgement") |
| 170 | 170 | |
| 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 | 新增: | |
| 171 | 193 | if CommandLine.arguments.count == 2 { |
| 172 | 194 | let signed = URL(fileURLWithPath: CommandLine.arguments[1]) |
| 173 | 195 | let team = try CageUpdateFiles.signingInfo(signed, bundle: true) |
| @@ -6,8 +6,14 @@ | ||
| 6 | 6 | <ImplicitUsings>enable</ImplicitUsings> |
| 7 | 7 | </PropertyGroup> |
| 8 | 8 | <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" /> | |
| 9 | 11 | <Compile Include="../windows/UpdatePolicy.cs" Link="UpdatePolicy.cs" /> |
| 10 | 12 | <Compile Include="../windows/Backend.cs" Link="Backend.cs" /> |
| 11 | 13 | <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" /> | |
| 12 | 18 | </ItemGroup> |
| 13 | 19 | </Project> |
| @@ -1,5 +1,12 @@ | ||
| 1 | 1 | using Cage.Windows; |
| 2 | 2 | |
| 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 | 新增: | |
| 3 | 10 | // The recovery integration tests launch a copy of this executable through the |
| 4 | 11 | // same subprocess/JSON boundary used by the shipped updater. |
| 5 | 12 | if (args is ["prepare-update", "--json", "--stop"]) |
| @@ -23,6 +30,26 @@ void Reject(Action action, string message) | ||
| 23 | 30 | try { action(); } catch (InvalidDataException) { return; } |
| 24 | 31 | throw new Exception(message); |
| 25 | 32 | } |
| 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; | |
| 26 | 53 | Check(UpdatePolicy.IsWorkbench("http://localhost:4321/", 4321), "expected local origin rejected"); |
| 27 | 54 | foreach (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" }) |
| 28 | 55 | 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 | ||
| 43 | 70 | Reject(() => UpdatePolicy.DownloadPath(path, root), "untrusted download path accepted: " + path); |
| 44 | 71 | Console.WriteLine($"Windows update/bridge policy: {assertions} assertions passed."); |
| 45 | 72 | |
| 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()); | |
| 47 | 74 | Directory.CreateDirectory(integration); |
| 48 | 75 | var savedProfile = Environment.GetEnvironmentVariable("CLAUDE_CAGE_CONFIG"); |
| 49 | 76 | try |
| @@ -63,6 +90,49 @@ try | ||
| 63 | 90 | if (broken) File.WriteAllText(Path.Combine(resources, "broken-backend"), "cannot start"); |
| 64 | 91 | } |
| 65 | 92 | 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 | 新增: } | |
| 66 | 136 | await UpdateRecovery.PrepareRollback(backup); |
| 67 | 137 | Check(File.Exists(Path.Combine(backup, "resources", "controller-invoked")), "recovery did not execute the old backend"); |
| 68 | 138 | Check(!File.Exists(Path.Combine(candidate, "resources", "controller-invoked")), "recovery executed the broken candidate backend"); |
| @@ -92,7 +162,38 @@ try | ||
| 92 | 162 | locked?.Dispose(); |
| 93 | 163 | if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(garbage, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); |
| 94 | 164 | } |
| 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 | 新增: } | |
| 96 | 197 | } |
| 97 | 198 | finally { |
| 98 | 199 | Environment.SetEnvironmentVariable("CLAUDE_CAGE_CONFIG", savedProfile); |
| @@ -1,4 +1,5 @@ | ||
| 1 | 1 | using System.Diagnostics; |
| 2 | 新增:using System.Globalization; | |
| 2 | 3 | using System.Reflection; |
| 3 | 4 | using System.Security.Cryptography; |
| 4 | 5 | using System.Text.Json; |
| @@ -40,6 +41,9 @@ internal sealed class AppUpdater : IDisposable | ||
| 40 | 41 | Change("manual", "轻量客户端使用独立安装包更新;连接配置会保留,云端任务不受影响。"); |
| 41 | 42 | return new(state); |
| 42 | 43 | } |
| 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); | |
| 43 | 47 | switch (operation) |
| 44 | 48 | { |
| 45 | 49 | case "status": break; |
| @@ -51,9 +55,9 @@ internal sealed class AppUpdater : IDisposable | ||
| 51 | 55 | return new(state); |
| 52 | 56 | } |
| 53 | 57 | |
| 54 | 删除: private void Change(string phase, string message, bool retryable = false) | |
| 58 | 新增: private void Change(string phase, string message, bool retryable = false, string retryAt = "") | |
| 55 | 59 | { |
| 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)); | |
| 57 | 61 | } |
| 58 | 62 | |
| 59 | 63 | public void MarkReady() |
| @@ -71,6 +75,7 @@ internal sealed class AppUpdater : IDisposable | ||
| 71 | 75 | var token = cancellation.Token; |
| 72 | 76 | Change("checking", "正在通过所选代理检查更新"); |
| 73 | 77 | string? archive = null; |
| 78 | 新增: string retryAt = ""; | |
| 74 | 79 | using var process = new Process { StartInfo = Backend.StartInfo(Backend.Executable, "app-update", checkOnly ? "check" : "download") }; |
| 75 | 80 | var started = false; |
| 76 | 81 | try |
| @@ -84,6 +89,7 @@ internal sealed class AppUpdater : IDisposable | ||
| 84 | 89 | { |
| 85 | 90 | if (line.Length > 65536) throw new IOException("更新响应超过允许大小"); |
| 86 | 91 | last = JsonDocument.Parse(line).RootElement.Clone(); |
| 92 | 新增: retryAt = last.Text("retryAt"); | |
| 87 | 93 | foreach (var property in last.EnumerateObject()) |
| 88 | 94 | if (property.Name is not ("archivePath" or "sha256")) state[property.Name] = property.Value.ValueKind switch { |
| 89 | 95 | JsonValueKind.String => property.Value.GetString(), |
| @@ -110,7 +116,7 @@ internal sealed class AppUpdater : IDisposable | ||
| 110 | 116 | Change("ready", "更新已下载并验证,可安装重启", true); |
| 111 | 117 | } |
| 112 | 118 | catch (OperationCanceledException) { Change("failed", "更新已暂停,可稍后重试", true); } |
| 113 | 删除: catch (Exception error) { Change("failed", error.Message, true); } | |
| 119 | 新增: catch (Exception error) { Change("failed", error.Message, true, retryAt); } | |
| 114 | 120 | finally |
| 115 | 121 | { |
| 116 | 122 | if (started && !process.HasExited) process.Kill(); |
| @@ -3,6 +3,7 @@ | ||
| 3 | 3 | <OutputType>WinExe</OutputType> |
| 4 | 4 | <TargetFramework>net10.0-windows10.0.19041.0</TargetFramework> |
| 5 | 5 | <UseWindowsForms>true</UseWindowsForms> |
| 6 | 新增: <ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode> | |
| 6 | 7 | <EnableWindowsTargeting>true</EnableWindowsTargeting> |
| 7 | 8 | <RuntimeIdentifier>win-x64</RuntimeIdentifier> |
| 8 | 9 | <SelfContained>true</SelfContained> |
| @@ -21,6 +22,8 @@ | ||
| 21 | 22 | </PropertyGroup> |
| 22 | 23 | <ItemGroup> |
| 23 | 24 | <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" /> | |
| 24 | 27 | </ItemGroup> |
| 25 | 28 | <Target Name="RemoveUnusedWebView2WpfReference" BeforeTargets="ResolveAssemblyReferences"> |
| 26 | 29 | <ItemGroup><Reference Remove="@(Reference)" Condition="'%(Reference.Filename)' == 'Microsoft.Web.WebView2.Wpf'" /></ItemGroup> |
| @@ -6,6 +6,8 @@ namespace Cage.Windows; | ||
| 6 | 6 | |
| 7 | 7 | internal static class UpdateInstaller |
| 8 | 8 | { |
| 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); | |
| 9 | 11 | public static void VerifyArchive(string path, string hash, string version, string publisher) |
| 10 | 12 | { |
| 11 | 13 | UpdatePolicy.DownloadPath(path, AppUpdater.Root); UpdatePolicy.PlainPath(path); |
| @@ -60,6 +62,7 @@ internal static class UpdateInstaller | ||
| 60 | 62 | if (Directory.Exists(backup)) throw new IOException("更新备份目录已存在"); |
| 61 | 63 | // Preparation is reversible and completes before the controller stops. |
| 62 | 64 | CopyTree(plan.Target, backup); |
| 65 | 新增: Authenticode.SamePublisher(UpdateRecovery.BackendPath(backup), ownPublisher); | |
| 63 | 66 | Console.WriteLine("READY"); await Console.Out.FlushAsync(); |
| 64 | 67 | if (await Console.In.ReadLineAsync(inputTimeout.Token) != "COMMIT") return 1; |
| 65 | 68 | committed = true; |
| @@ -78,6 +81,7 @@ internal static class UpdateInstaller | ||
| 78 | 81 | catch (TimeoutException) { if (!installer.HasExited) installer.Kill(true); await installer.WaitForExitAsync(); throw; } |
| 79 | 82 | if (installer.ExitCode != 0) throw new IOException("Windows 安装程序未完成安装"); |
| 80 | 83 | } |
| 84 | 新增: EnsureInstallationComplete(plan.Target); | |
| 81 | 85 | Authenticode.SamePublisher(original, ownPublisher); |
| 82 | 86 | if (FileVersionInfo.GetVersionInfo(original).ProductVersion != plan.Version) |
| 83 | 87 | throw new IOException("安装后版本不匹配"); |
| @@ -114,10 +118,16 @@ internal static class UpdateInstaller | ||
| 114 | 118 | { |
| 115 | 119 | if (succeeded) return 0; |
| 116 | 120 | var detail = error.Message; |
| 121 | 新增: var recoveryIncomplete = false; | |
| 117 | 122 | if (replaced && plan != null && backup != null) |
| 118 | 123 | { |
| 119 | 124 | try |
| 120 | 125 | { |
| 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); | |
| 121 | 131 | // Stop the exact new controller through its lifecycle API before |
| 122 | 132 | // restoring files. Never kill other Cage instances by name. |
| 123 | 133 | Authenticode.SamePublisher(UpdateRecovery.BackendPath(backup), plan.Publisher); |
| @@ -126,18 +136,39 @@ internal static class UpdateInstaller | ||
| 126 | 136 | var restored = plan.Target + ".restore-" + plan.Confirmation; |
| 127 | 137 | var failed = plan.Target + ".failed-" + plan.Confirmation; |
| 128 | 138 | 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); | |
| 133 | 156 | UpdateRecovery.CleanupDirectory(backup); backup = null; |
| 134 | 157 | Result(false, "更新未完成,已恢复原应用:" + detail); |
| 135 | 158 | Process.Start(new ProcessStartInfo(Path.Combine(plan.Target, "Cage.exe")) { UseShellExecute = false, WorkingDirectory = plan.Target }); |
| 136 | 159 | return 1; |
| 137 | 160 | } |
| 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 | 新增: } | |
| 139 | 169 | } |
| 140 | 170 | Result(false, "更新未完成:" + detail); |
| 171 | 新增: if (recoveryIncomplete && OperatingSystem.IsWindows()) MessageBoxW(IntPtr.Zero, detail, "Cage 更新需要恢复", 0x00010010); | |
| 141 | 172 | if (committed && !replaced && plan != null) |
| 142 | 173 | { |
| 143 | 174 | try |
| @@ -170,18 +201,104 @@ internal static class UpdateInstaller | ||
| 170 | 201 | catch (UnauthorizedAccessException) { } |
| 171 | 202 | } |
| 172 | 203 | |
| 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 | 新增: | |
| 173 | 256 | private static void CopyTree(string source, string target) |
| 174 | 257 | { |
| 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 | 新增: } | |
| 176 | 288 | long size = 0; var count = 0; |
| 177 | 289 | var pending = new Queue<string>(); pending.Enqueue(source); |
| 178 | 290 | while (pending.TryDequeue(out var directory)) |
| 179 | 291 | foreach (var entry in Directory.EnumerateFileSystemEntries(directory)) |
| 180 | 292 | { |
| 181 | 293 | 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); | |
| 185 | 302 | if ((attributes & FileAttributes.Directory) != 0) { Directory.CreateDirectory(destination); pending.Enqueue(entry); } |
| 186 | 303 | else |
| 187 | 304 | { |
| @@ -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 | 新增:} | |
| @@ -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 | 新增:} | |
| @@ -21,8 +21,10 @@ import ( | ||
| 21 | 21 | "time" |
| 22 | 22 | |
| 23 | 23 | "github.com/sylvinus/agent-vm/internal/cage" |
| 24 | 新增: "github.com/sylvinus/agent-vm/internal/diagnostics" | |
| 24 | 25 | "github.com/sylvinus/agent-vm/internal/host" |
| 25 | 26 | "github.com/sylvinus/agent-vm/internal/managedproxy" |
| 27 | 新增: "github.com/sylvinus/agent-vm/internal/usererror" | |
| 26 | 28 | "github.com/sylvinus/agent-vm/internal/version" |
| 27 | 29 | "golang.org/x/mod/semver" |
| 28 | 30 | ) |
| @@ -61,10 +63,15 @@ type State struct { | ||
| 61 | 63 | TotalBytes int64 `json:"totalBytes,omitempty"` |
| 62 | 64 | Message string `json:"message,omitempty"` |
| 63 | 65 | Retryable bool `json:"retryable,omitempty"` |
| 66 | 新增: RetryAt string `json:"retryAt"` | |
| 64 | 67 | ArchivePath string `json:"archivePath,omitempty"` |
| 65 | 68 | SHA256 string `json:"sha256,omitempty"` |
| 66 | 69 | } |
| 67 | 70 | |
| 71 | 新增:type proxyUnavailableError struct{ message string } | |
| 72 | 新增: | |
| 73 | 新增:func (e *proxyUnavailableError) Error() string { return e.message } | |
| 74 | 新增: | |
| 68 | 75 | // Run only accepts fixed operations. URLs and destinations come from the |
| 69 | 76 | // verified repository response and the current private profile. |
| 70 | 77 | func Run(configPath string, args []string, output io.Writer) int { |
| @@ -72,7 +79,14 @@ func Run(configPath string, args []string, output io.Writer) int { | ||
| 72 | 79 | state := State{CurrentVersion: version.Version} |
| 73 | 80 | emit := func() { _ = enc.Encode(state) } |
| 74 | 81 | 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) | |
| 76 | 90 | emit() |
| 77 | 91 | return 1 |
| 78 | 92 | } |
| @@ -156,10 +170,10 @@ func managedClient(ctx context.Context, configPath string) (*http.Client, error) | ||
| 156 | 170 | profile := filepath.Dir(configPath) |
| 157 | 171 | p, err := managedproxy.Applied(profile, cfg.ProxyURL, cfg.ProxyRevision) |
| 158 | 172 | if err != nil { |
| 159 | 删除: return nil, errors.New("所选代理尚未应用,请在网络与代理中配置后重试") | |
| 173 | 新增: return nil, &proxyUnavailableError{"所选代理尚未应用,更新检查将在代理就绪后重试"} | |
| 160 | 174 | } |
| 161 | 175 | if !managedproxy.Running(ctx, profile, p) { |
| 162 | 删除: return nil, errors.New("所选代理未运行,请在网络与代理中启动后重试;更新不会改用主机直连") | |
| 176 | 新增: return nil, &proxyUnavailableError{"所选代理未运行,更新检查将在代理就绪后重试;更新不会改用主机直连"} | |
| 163 | 177 | } |
| 164 | 178 | egress, err := cage.NewEgress(cfg) |
| 165 | 179 | if err != nil { |
| @@ -208,18 +222,18 @@ func request(ctx context.Context, client *http.Client, raw string) (*http.Respon | ||
| 208 | 222 | } |
| 209 | 223 | resp, err := client.Do(req) |
| 210 | 224 | if err != nil { |
| 211 | 删除: if ctx.Err() != nil { | |
| 225 | 新增: if errors.Is(ctx.Err(), context.Canceled) { | |
| 212 | 226 | return nil, errors.New("更新下载已取消") |
| 213 | 227 | } |
| 214 | 删除: return nil, errors.New("无法通过所选代理连接更新源,请检查网络后重试") | |
| 228 | 新增: return nil, usererror.Wrap("连接应用更新源", errors.Join(ctx.Err(), err), "请在网络与代理设置中确认所选节点可以连接 GitHub,再检查更新。") | |
| 215 | 229 | } |
| 216 | 230 | if resp.StatusCode != http.StatusOK { |
| 217 | 231 | resp.Body.Close() |
| 218 | 232 | switch resp.StatusCode { |
| 219 | 233 | case 404: |
| 220 | 删除: return nil, errors.New("更新源暂不可访问:仓库尚未公开或该发行包不可用") | |
| 234 | 新增: return nil, errors.New("更新源找不到请求的版本或安装包(HTTP 404)。请稍后检查更新;需要手动安装时,请核对 Cage 发布页面中的对应平台文件。") | |
| 221 | 235 | case 403, 429: |
| 222 | 删除: return nil, errors.New("更新源请求受限,请稍后重试") | |
| 236 | 新增: return nil, updateSourceError(resp, time.Now()) | |
| 223 | 237 | default: |
| 224 | 238 | return nil, fmt.Errorf("更新源返回 HTTP %d,请稍后重试", resp.StatusCode) |
| 225 | 239 | } |
| @@ -121,7 +121,7 @@ func TestChecksumListMustAgreeAndBelongToSameRelease(t *testing.T) { | ||
| 121 | 121 | } |
| 122 | 122 | } |
| 123 | 123 | func 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") { | |
| 125 | 125 | t.Fatal(err) |
| 126 | 126 | } |
| 127 | 127 | var output bytes.Buffer |
| @@ -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 | 新增:} | |
| @@ -1,17 +1,19 @@ | ||
| 1 | 1 | Unicode true |
| 2 | 2 | RequestExecutionLevel user |
| 3 | 删除:SetCompressor /SOLID lzma | |
| 3 | 新增:; Per-file decompression avoids a full payload copy in the system TEMP drive. | |
| 4 | 新增:SetCompressor lzma | |
| 4 | 5 | SetCompressorDictSize 32 |
| 5 | 6 | ManifestDPIAware true |
| 6 | 7 | ManifestSupportedOS all |
| 7 | 删除:Icon "Cage.ico" | |
| 8 | 删除:UninstallIcon "Cage.ico" | |
| 9 | 8 | |
| 10 | 9 | !include MUI2.nsh |
| 10 | 新增:!define MUI_ICON "Cage.ico" | |
| 11 | 新增:!define MUI_UNICON "Cage.ico" | |
| 11 | 12 | !include LogicLib.nsh |
| 12 | 13 | !include FileFunc.nsh |
| 13 | 14 | !include x64.nsh |
| 14 | 15 | !include WinVer.nsh |
| 16 | 新增:!include nsDialogs.nsh | |
| 15 | 17 | |
| 16 | 18 | !ifndef APP_DIR |
| 17 | 19 | !error "APP_DIR is required" |
| @@ -52,6 +54,7 @@ VIAddVersionKey /LANG=1033 "LegalCopyright" "Cage contributors" | ||
| 52 | 54 | !insertmacro MUI_PAGE_LICENSE "${APP_DIR}/LICENSE.txt" |
| 53 | 55 | !define MUI_DIRECTORYPAGE_TEXT_TOP "$(CageDirectoryHelp)" |
| 54 | 56 | !insertmacro MUI_PAGE_DIRECTORY |
| 57 | 新增:Page custom ShortcutOptionsPage ShortcutOptionsLeave | |
| 55 | 58 | !insertmacro MUI_PAGE_INSTFILES |
| 56 | 59 | !insertmacro MUI_PAGE_FINISH |
| 57 | 60 | !insertmacro MUI_UNPAGE_CONFIRM |
| @@ -61,11 +64,143 @@ VIAddVersionKey /LANG=1033 "LegalCopyright" "Cage contributors" | ||
| 61 | 64 | |
| 62 | 65 | LangString 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." |
| 63 | 66 | LangString 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} "添加到开始菜单" | |
| 64 | 75 | |
| 65 | 76 | Var UpdateMode |
| 66 | 77 | Var StageDir |
| 67 | 78 | Var BackupDir |
| 68 | 79 | Var 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 | |
| 69 | 204 | |
| 70 | 205 | !macro CheckStopped FILE |
| 71 | 206 | ${If} ${FileExists} "$INSTDIR\${FILE}" |
| @@ -93,6 +228,8 @@ Function .onInit | ||
| 93 | 228 | SetErrorLevel 1633 |
| 94 | 229 | Quit |
| 95 | 230 | ${EndIf} |
| 231 | 新增: Call SetDefaultInstallDirectory | |
| 232 | 新增: Call LoadShortcutOptions | |
| 96 | 233 | StrCpy $UpdateMode "0" |
| 97 | 234 | ${GetParameters} $0 |
| 98 | 235 | ClearErrors |
| @@ -113,7 +250,9 @@ Function CheckDestination | ||
| 113 | 250 | ${EndIf} |
| 114 | 251 | StrCpy $ExistingInstall "0" |
| 115 | 252 | 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 | |
| 117 | 256 | existing: |
| 118 | 257 | FileOpen $0 "$INSTDIR\Cage.install-id" r |
| 119 | 258 | FileRead $0 $1 |
| @@ -132,9 +271,40 @@ Function CheckDestination | ||
| 132 | 271 | SetErrorLevel 2 |
| 133 | 272 | Abort "The destination contains files from another installation. Choose an empty folder." |
| 134 | 273 | 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} | |
| 135 | 299 | FunctionEnd |
| 136 | 300 | |
| 137 | 301 | Section "Cage" Main |
| 302 | 新增: !insertmacro AcquireInstallationMutex | |
| 303 | 新增: StrCpy $TransactionRecord "$INSTDIR.cage-installation.json" | |
| 304 | 新增: ${If} ${FileExists} "$TransactionRecord" | |
| 305 | 新增: SetErrorLevel 2 | |
| 306 | 新增: Abort "存在未处理的安装事务记录:$TransactionRecord。请先按记录恢复保留的目录,再重试。" | |
| 307 | 新增: ${EndIf} | |
| 138 | 308 | Call CheckDestination |
| 139 | 309 | ${GetParent} "$INSTDIR" $0 |
| 140 | 310 | CreateDirectory "$0" |
| @@ -182,13 +352,45 @@ Section "Cage" Main | ||
| 182 | 352 | ${GetParent} "$INSTDIR" $0 |
| 183 | 353 | GetTempFileName $BackupDir "$0" |
| 184 | 354 | 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" | |
| 185 | 373 | ClearErrors |
| 186 | 374 | Rename "$INSTDIR" "$BackupDir" |
| 187 | 375 | ${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 | |
| 188 | 379 | RMDir /r "$StageDir" |
| 189 | 380 | SetErrorLevel 2 |
| 190 | 381 | Abort "Could not move the installed application. Quit Cage and retry." |
| 191 | 382 | ${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} | |
| 192 | 394 | ${Else} |
| 193 | 395 | RMDir "$INSTDIR" |
| 194 | 396 | ${EndIf} |
| @@ -196,21 +398,31 @@ Section "Cage" Main | ||
| 196 | 398 | Rename "$StageDir" "$INSTDIR" |
| 197 | 399 | ${If} ${Errors} |
| 198 | 400 | ${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 | |
| 206 | 402 | ${EndIf} |
| 207 | 403 | RMDir /r "$StageDir" |
| 208 | 404 | SetErrorLevel 2 |
| 209 | 405 | Abort "Could not install Cage. The previous installation has been restored." |
| 210 | 406 | ${EndIf} |
| 211 | 407 | ${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} | |
| 214 | 426 | ${EndIf} |
| 215 | 427 | WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayName" "Cage" |
| 216 | 428 | WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayVersion" "${VERSION}" |
| @@ -221,9 +433,23 @@ Section "Cage" Main | ||
| 221 | 433 | WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayIcon" "$INSTDIR\Cage.exe,0" |
| 222 | 434 | WriteRegDWORD HKCU "${UNINSTALL_KEY}" "NoModify" 1 |
| 223 | 435 | 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 | |
| 227 | 453 | SetErrorLevel 0 |
| 228 | 454 | SectionEnd |
| 229 | 455 | |
| @@ -244,12 +470,28 @@ Function un.onInit | ||
| 244 | 470 | FunctionEnd |
| 245 | 471 | |
| 246 | 472 | Section "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" | |
| 247 | 492 | Delete "$SMPROGRAMS\Cage\Cage.lnk" |
| 248 | 493 | Delete "$SMPROGRAMS\Cage\Uninstall Cage.lnk" |
| 249 | 494 | RMDir "$SMPROGRAMS\Cage" |
| 250 | 495 | 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" | |
| 254 | 496 | RMDir "$INSTDIR" |
| 255 | 497 | SectionEnd |
| @@ -1,6 +1,11 @@ | ||
| 1 | 1 | Cage for Windows 10 and Windows 11 (x64) |
| 2 | 2 | |
| 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. | |
| 4 | 9 | No Go, Node.js, .NET SDK, QEMU, OpenSSH or Clash installation is required. |
| 5 | 10 | The installer includes the Microsoft WebView2 offline runtime installer. |
| 6 | 11 | |
| @@ -17,6 +22,14 @@ Proxy service and Claude account are not included. Changes to shared projects | ||
| 17 | 22 | affect the original files. |
| 18 | 23 | |
| 19 | 24 | Updates 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. | |
| 20 | 33 | Stop the environment and quit Cage before running an installer manually. |
| 21 | 34 | In-app updates stop the environment after your confirmation, verify the new |
| 22 | 35 | installer and publisher, and restart the application after installation. |
| @@ -25,6 +38,8 @@ Unsigned development builds cannot install automatic updates. | ||
| 25 | 38 | Uninstall using Windows Settings > Apps > Installed apps (Windows 11) or |
| 26 | 39 | Apps & features (Windows 10). Uninstall removes application files and shortcuts. |
| 27 | 40 | It 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. | |
| 28 | 43 | Microsoft WebView2 is a shared runtime and is not removed by Cage uninstall. |
| 29 | 44 | |
| 30 | 45 | Getting started: https://github.com/Lee-xeo/Claude-Cage/blob/main/docs/windows.md |
| @@ -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 | 新增:} | |
| @@ -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 | 新增:} | |
| @@ -33,13 +33,19 @@ function inUse(bundle) { | ||
| 33 | 33 | throw error; |
| 34 | 34 | } |
| 35 | 35 | } |
| 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 | 新增:} | |
| 36 | 42 | |
| 37 | 删除:export async function cleanupApps({ keep, roots, onInUse = () => {} }) { | |
| 43 | 新增:export async function cleanupApps({ keep, roots, onInUse = () => {}, onModified = () => {} }) { | |
| 38 | 44 | if (!keep.length) |
| 39 | 45 | throw new Error("At least one verified Cage.app must be kept."); |
| 40 | 46 | const retained = new Set(); |
| 41 | 47 | 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}`); | |
| 43 | 49 | retained.add(await realpath(bundle)); |
| 44 | 50 | } |
| 45 | 51 | const removed = []; |
| @@ -56,6 +62,10 @@ export async function cleanupApps({ keep, roots, onInUse = () => {} }) { | ||
| 56 | 62 | if (retained.has(canonical)) return; |
| 57 | 63 | if (directory.endsWith(".app")) { |
| 58 | 64 | if (isCage(directory)) { |
| 65 | 新增: if (!intact(directory)) { | |
| 66 | 新增: onModified(directory); | |
| 67 | 新增: return; | |
| 68 | 新增: } | |
| 59 | 69 | if (inUse(directory)) { |
| 60 | 70 | onInUse(directory); |
| 61 | 71 | return; |
| @@ -91,6 +101,7 @@ if ( | ||
| 91 | 101 | for (const bundle of await cleanupApps({ |
| 92 | 102 | keep, roots, |
| 93 | 103 | onInUse: (bundle) => console.error(`Old Cage App is still running; quit it and rerun cleanup: ${bundle}`), |
| 104 | 新增: onModified: (bundle) => console.error(`旧应用包含修改内容或无法验证完整性,文件已保留:${bundle}`), | |
| 94 | 105 | })) |
| 95 | 106 | console.log(`Removed old App: ${bundle}`); |
| 96 | 107 | } |
| @@ -11,7 +11,7 @@ import { | ||
| 11 | 11 | import os from "node:os"; |
| 12 | 12 | import path from "node:path"; |
| 13 | 13 | import test from "node:test"; |
| 14 | 删除:import { spawn } from "node:child_process"; | |
| 14 | 新增:import { execFileSync, spawn } from "node:child_process"; | |
| 15 | 15 | import { cleanupApps } from "./cleanup-apps.mjs"; |
| 16 | 16 | |
| 17 | 17 | const cageID = "io.github.lee-xeo.claude-cage"; |
| @@ -21,9 +21,7 @@ test("cleanup preserves a Cage executable still in use", { skip: process.platfor | ||
| 21 | 21 | try { |
| 22 | 22 | const latest = await app(path.join(directory, "new.app")); |
| 23 | 23 | const running = await app(path.join(directory, "running.app")); |
| 24 | 删除: await mkdir(path.join(running, "Contents/MacOS")); | |
| 25 | 24 | const executable = path.join(running, "Contents/MacOS/Cage"); |
| 26 | 删除: await copyFile("/bin/sleep", executable); | |
| 27 | 25 | child = spawn(executable, ["30"], { stdio: "ignore" }); |
| 28 | 26 | await new Promise((resolve, reject) => { child.once("spawn", resolve); child.once("error", reject); }); |
| 29 | 27 | const skipped = []; |
| @@ -39,14 +37,30 @@ test("cleanup preserves a Cage executable still in use", { skip: process.platfor | ||
| 39 | 37 | } |
| 40 | 38 | }); |
| 41 | 39 | async function app(directory, id = cageID) { |
| 42 | 删除: await mkdir(path.join(directory, "Contents"), { recursive: true }); | |
| 40 | 新增: await mkdir(path.join(directory, "Contents/MacOS"), { recursive: true }); | |
| 43 | 41 | await writeFile( |
| 44 | 42 | 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>`, | |
| 46 | 44 | ); |
| 45 | 新增: await copyFile('/bin/sleep', path.join(directory, 'Contents/MacOS/Cage')); | |
| 46 | 新增: execFileSync('/usr/bin/codesign', ['--force', '--sign', '-', directory], { stdio: 'ignore' }); | |
| 47 | 47 | return directory; |
| 48 | 48 | } |
| 49 | 49 | |
| 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 | 新增: | |
| 50 | 64 | test( |
| 51 | 65 | "cleanup removes old Cage copies while retaining replacement, foreign apps and linked directories", |
| 52 | 66 | { skip: process.platform !== "darwin" }, |
| @@ -15,18 +15,49 @@ function Assert-PersonalData { | ||
| 15 | 15 | Invoke-BuildTool 'node' @($fixture, 'verify', $env:USERPROFILE, $manifest) |
| 16 | 16 | } |
| 17 | 17 | function Run-Installer { |
| 18 | 删除: param([switch]$Update, [int]$ExpectedExitCode = 0) | |
| 18 | 新增: param([switch]$Update, [int]$ExpectedExitCode = 0, [string[]]$ShortcutOptions = @()) | |
| 19 | 19 | $arguments = @('/S') |
| 20 | 20 | if ($Update) { $arguments += '/UPDATE' } |
| 21 | 新增: $arguments += $ShortcutOptions | |
| 21 | 22 | $arguments += "/D=$target" |
| 22 | 23 | $process = Start-Process -FilePath $Installer -ArgumentList $arguments -PassThru |
| 23 | 24 | if (-not $process.WaitForExit(300000)) { throw 'Installer exceeded five minutes.' } |
| 24 | 25 | if ($process.ExitCode -ne $ExpectedExitCode) { throw "Installer returned $($process.ExitCode), expected $ExpectedExitCode" } |
| 25 | 26 | } |
| 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 | |
| 26 | 42 | Run-Installer |
| 27 | 43 | Assert-PersonalData |
| 44 | 新增:Assert-Shortcuts $true $true | |
| 28 | 45 | if (-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')) | |
| 29 | 58 | Invoke-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') | |
| 30 | 61 | Invoke-BuildTool (Join-Path $target 'resources/mihomo.exe') @('-v') |
| 31 | 62 | Invoke-BuildTool (Join-Path $target 'resources/runtime/qemu/qemu-system-x86_64.exe') @('--version') |
| 32 | 63 | Invoke-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) | ||
| 50 | 81 | # Reinstall through the real atomic replacement path. User data must survive. |
| 51 | 82 | Run-Installer -Update |
| 52 | 83 | Assert-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 | |
| 53 | 96 | $uninstall = Start-Process -FilePath (Join-Path $target 'Uninstall.exe') -ArgumentList @('/S') -PassThru |
| 54 | 97 | if (-not $uninstall.WaitForExit(120000) -or $uninstall.ExitCode -ne 0) { throw 'Uninstall failed.' } |
| 55 | 98 | # NSIS may relaunch its uninstaller from TEMP so that it can delete the original. |
| @@ -57,5 +100,7 @@ $deadline = [DateTime]::UtcNow.AddSeconds(120) | ||
| 57 | 100 | while ((Test-Path -LiteralPath (Join-Path $target 'Uninstall.exe')) -and [DateTime]::UtcNow -lt $deadline) { Start-Sleep -Milliseconds 200 } |
| 58 | 101 | if (Test-Path -LiteralPath (Join-Path $target 'Cage.exe')) { throw 'Uninstall left Cage.exe behind.' } |
| 59 | 102 | if (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.' } | |
| 60 | 104 | Assert-PersonalData |
| 105 | 新增:Assert-Shortcuts $false $false | |
| 61 | 106 | Write-Host 'Install, WebView2 workbench, reinstall, uninstall and user-data preservation passed. VM startup was not tested.' |
| @@ -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 | 新增:} | |
| @@ -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 | 新增:} | |
| @@ -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 | 新增:}); | |

