using System; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Security.Cryptography; using System.Web.Script.Serialization; using System.Windows.Forms; // A fixed, user-level bootstrap. The independent Node host retains task state; // this program only validates an immutable release and starts its desktop client. internal static class Launcher { static bool hidden; static string Full(string value) { return Path.GetFullPath(value).TrimEnd(Path.DirectorySeparatorChar); } static bool Same(string a, string b) { return String.Equals(Full(a), Full(b), StringComparison.OrdinalIgnoreCase); } static bool Inside(string root, string file) { return Full(file).StartsWith(Full(root) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase); } static void Local(string file) { string full = Full(file), current = Path.GetPathRoot(full); if (current.StartsWith("\\\\")) throw new Exception("程序需要本机目录。"); foreach (string part in full.Substring(current.Length).Split(Path.DirectorySeparatorChar)) { if (part.IndexOf(':') >= 0) throw new Exception("路径包含无效文件名。"); current = Path.Combine(current, part); if ((File.Exists(current) || Directory.Exists(current)) && (File.GetAttributes(current) & FileAttributes.ReparsePoint) != 0) throw new Exception("程序路径不能使用链接或重解析目录。"); } } static Dictionary Json(string file) { Local(file); if (new FileInfo(file).Length > 16 * 1024 * 1024) throw new Exception("安装清单过大。"); JavaScriptSerializer reader = new JavaScriptSerializer(); reader.MaxJsonLength = 16 * 1024 * 1024; return reader.Deserialize>(File.ReadAllText(file, Encoding.UTF8)); } static string Str(Dictionary value, string key) { object result; if (!value.TryGetValue(key, out result) || !(result is string)) throw new Exception("安装登记缺少 " + key); return (string)result; } static string Hash(string file) { Local(file); using (SHA256 hash = SHA256.Create()) using (FileStream input = File.OpenRead(file)) return BitConverter.ToString(hash.ComputeHash(input)).Replace("-", "").ToLowerInvariant(); } static string Quote(string value) { if (value.IndexOf('"') >= 0 || value.EndsWith("\\")) throw new Exception("启动参数无效。"); return "\"" + value + "\""; } static void Verify(string root, string expected, string version) { string file = Path.Combine(root, "MANIFEST.json"); Dictionary manifest = Json(file); if (Str(manifest, "app") != "agent-workbench" || Str(manifest, "kind") != "portable" || Str(manifest, "platform") != "win32-x64") throw new Exception("需要完整 Windows 桌面发行。"); if (version != null && Str(manifest, "version") != version) throw new Exception("安装版本登记不一致。"); if (expected != null && Hash(file) != expected) throw new Exception("原安装清单发生变化。"); HashSet declared = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (object item in (IEnumerable)manifest["files"]) { Dictionary row = (Dictionary)item; string relative = Str(row, "path"); if (relative.IndexOf('\\') >= 0 || relative.IndexOf(':') >= 0 || relative.StartsWith("/") || Array.IndexOf(relative.Split('/'), "..") >= 0 || !declared.Add(relative) || declared.Count > 60000) throw new Exception("清单包含重复或越界文件。"); string source = Path.Combine(root, relative.Replace('/', Path.DirectorySeparatorChar)); if (!Inside(root, source) || !File.Exists(source) || new FileInfo(source).Length != Convert.ToInt64(row["bytes"]) || Hash(source) != Str(row, "sha256")) throw new Exception("发行文件与原清单不同:" + relative); } foreach (string required in new string[] { "runtime/node.exe", "desktop/AgentWorkbench.exe", "dist-server/server.mjs", "dist-server/install-manager.mjs", "dist-desktop/main.cjs", "dist-desktop/preload.cjs" }) if (!declared.Contains(required)) throw new Exception("桌面发行缺少 " + required); string[] actual = Directory.GetFiles(root, "*", SearchOption.AllDirectories); if (actual.Length != declared.Count + 1) throw new Exception("发行目录包含未登记文件。"); foreach (string value in actual) { Local(value); string relative = Full(value).Substring(Full(root).Length + 1).Replace('\\', '/'); if (relative != "MANIFEST.json" && !declared.Contains(relative)) throw new Exception("发行目录包含未登记文件。"); } } [STAThread] static int Main(string[] args) { try { string root = Full(Path.GetDirectoryName(Application.ExecutablePath)), data = Full(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "AgentWorkbench")); int port = 4318; string selectedData = null; int? selectedPort = null; bool uninstall = false; for (int i = 0; i < args.Length; i++) { if (args[i] == "--hidden-window" && !hidden) { hidden = true; continue; } if (args[i] == "--uninstall-preflight" && !uninstall) { uninstall = true; continue; } if (args[i] == "--data-root" && selectedData == null && ++i < args.Length) { selectedData = Full(args[i]); continue; } if (args[i] == "--port" && !selectedPort.HasValue && ++i < args.Length) { selectedPort = Int32.Parse(args[i]); continue; } throw new Exception("不支持的桌面启动参数。"); } string recordFile = Path.Combine(root, "current.json"), expected = null, version = null, release = root; if (File.Exists(recordFile)) { Dictionary record = Json(recordFile), active = (Dictionary)record["active"]; if (Convert.ToInt32(record["schema"]) != 1 || Str(record, "app") != "agent-workbench-installation" || !Regex.IsMatch(Str(record, "installId"), "^[a-f0-9-]{36}$") || Convert.ToInt64(record["revision"]) < 1) throw new Exception("安装登记无效。"); string directory = Str(active, "directory"); if (!Regex.IsMatch(directory, "^[A-Za-z0-9][A-Za-z0-9._-]{0,159}$")) throw new Exception("活动版本目录无效。"); release = Full(Path.Combine(root, "versions", directory)); if (!Inside(Path.Combine(root, "versions"), release)) throw new Exception("活动版本越界。"); expected = Str(active, "manifestSha256"); version = Str(active, "version"); if (!Regex.IsMatch(expected, "^[a-f0-9]{64}$") || !Regex.IsMatch(Str(active, "runtimeIdentity"), "^[a-f0-9]{64}$") || !Regex.IsMatch(version, "^\\d+\\.\\d+\\.\\d+$")) throw new Exception("原版本身份无效。"); data = Full(Str(record, "dataRoot")); port = Convert.ToInt32(record["port"]); if ((selectedData != null && !Same(selectedData, data)) || (selectedPort.HasValue && selectedPort.Value != port)) throw new Exception("已安装应用使用登记的数据目录及端口。"); } else { if (uninstall) throw new Exception("没有可核对的安装登记。"); if (selectedData != null) data = selectedData; if (selectedPort.HasValue) port = selectedPort.Value; } if (port < 1 || port > 65535 || Same(root, data) || Inside(root, data) || Inside(data, root)) throw new Exception("程序与用户数据需要独立目录及有效端口。"); Local(root); Local(data); Local(release); Verify(release, expected, version); ProcessStartInfo launch = new ProcessStartInfo(uninstall ? Path.Combine(release, "runtime", "node.exe") : Path.Combine(release, "desktop", "AgentWorkbench.exe")); launch.Arguments = uninstall ? Quote(Path.Combine(release, "dist-server", "install-manager.mjs")) + " uninstall --install-root " + Quote(root) + " --data-root " + Quote(data) + " --port " + port : "--app-root " + Quote(release) + " --data-root " + Quote(data) + " --port " + port + (hidden ? " --hidden-window" : ""); launch.WorkingDirectory = release; launch.UseShellExecute = false; launch.CreateNoWindow = true; List keys = new List(); foreach (string key in launch.EnvironmentVariables.Keys) keys.Add(key); Regex allowed = new Regex("^(path|pathext|systemroot|systemdrive|windir|comspec|temp|tmp|userprofile|homedrive|homepath|appdata|localappdata|programfiles(?:\\(x86\\))?|commonprogramfiles(?:\\(x86\\))?|lang|lc_all|AGENT_WORKBENCH_(?:DEEPSEEK_ROOT|PURGE_ROOT|PYTHON_PATH|TEST_PYTHON))$", RegexOptions.IgnoreCase); foreach (string key in keys) if (!allowed.IsMatch(key)) launch.EnvironmentVariables.Remove(key); using (Process child = Process.Start(launch)) { if (uninstall) { child.WaitForExit(); return child.ExitCode; } } return 0; } catch (Exception error) { if (!hidden) MessageBox.Show(error.Message, "Agent Workbench 无法打开", MessageBoxButtons.OK, MessageBoxIcon.Error); return 1; } } }