跳到主要内容

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

浏览文件

BrowserRpc.cs

510 行 · 32.4 KB历史下载
1using System.Diagnostics;
2using System.Collections.Concurrent;
3using System.Runtime.CompilerServices;
4using System.Security.AccessControl;
5using System.Security.Principal;
6using System.Text.Json.Nodes;
7
8namespace Cage.GuestClipboard;
9
10// A viewer connection owns its requests. The GUI agent owns the persistent
11// browser process, so reconnecting or locking the desktop preserves its tabs.
12internal static class BrowserRpc
13{
14 private static readonly SemaphoreSlim Gate = new(1, 1);
15 private static Process? browser;
16 private static GuestProcessJob? browserJob;
17 private static Stream? replies;
18 private static Task? errors;
19 private static bool ready;
20 private static bool wirePending;
21 private static JsonObject? cachedPageFrame;
22 private static NativeInputCoordinator.Lease? pagePointerOwner;
23 private static bool pagePointerReleasePending;
24 private static JsonObject features = new();
25 private static Func<bool>? packetReadiness;
26 private static string active = "";
27 private static readonly ConcurrentDictionary<string, WindowsEditorServer.Connection> EditorTabs = new(StringComparer.Ordinal);
28 private static readonly ConcurrentDictionary<string, WindowsEditorServer.Connection> EditorConnections = new(StringComparer.Ordinal);
29 private static readonly ConcurrentDictionary<string, uint> CopyRevisions = new(StringComparer.Ordinal);
30 private static readonly HashSet<string> Routes = ["health", "tabs", "events", "frame", "new", "activate", "close", "navigate", "back", "forward", "reload", "homepage", "resize", "insert-text", "copy-context", "ime", "copy", "cut", "paste", "select-all", "key", "pointer", "click", "wheel", "input", "editor", "editor-restart", "upload-start", "upload-finish", "upload-cancel", "download-retry", "info", "cookies", "settings", "internal-page", "extensions", "split", "audit", "vault", "login-open", "login-finish", "file-open", "file-chunk", "file-finish", "file-read", "file-close", "image-start", "image-chunk", "image-finish", "image-cancel"];
31
32 [ModuleInitializer]
33 internal static void Register()
34 {
35 Routes.UnionWith(["paste-start", "paste-chunk", "paste-finish", "paste-cancel", "tailnet", "phone-browser/open", "phone-browser/frame", "phone-browser/action", "phone-browser/close"]);
36 GuestOperations.Register("browser", Run);
37 ProjectRpc.Revoked += (project, grant) =>
38 {
39 WindowsEditorServer.Revoke(project, grant);
40 _ = RevokeNode(project, grant);
41 };
42 AppDomain.CurrentDomain.ProcessExit += (_, _) => { WindowsPhoneBrowser.Close(); WindowsEditorServer.Close(); Close(); };
43 }
44 // The packet runtime supplies its System-owned receipt verifier. A config
45 // string alone can never enable direct TCP access in a fresh browser.
46 internal static void RegisterPacketReadiness(Func<bool> verifier)
47 {
48 if (Interlocked.CompareExchange(ref packetReadiness, verifier, null) is not null) throw new InvalidOperationException("packet_verifier_already_registered");
49 }
50 private static bool PacketReady()
51 {
52 if (packetReadiness is not null) return packetReadiness();
53 try
54 {
55 var vm = GuestContext.VM;
56 if (vm == Guid.Empty || GuestContext.SID.Length == 0) return false;
57 var root = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Cage Guest Network", vm.ToString("D"));
58 var file = new FileInfo(Path.Combine(root, "network-ready.json"));
59 if (!file.Exists || file.Length is < 1 or > 16384 || file.Attributes.HasFlag(FileAttributes.ReparsePoint) || new DirectoryInfo(root).Attributes.HasFlag(FileAttributes.ReparsePoint)) return false;
60 var acl = file.GetAccessControl();
61 var owner = acl.GetOwner(typeof(SecurityIdentifier))?.Value;
62 if (owner is not ("S-1-5-18" or "S-1-5-32-544")) return false;
63 const FileSystemRights writes = FileSystemRights.WriteData | FileSystemRights.AppendData | FileSystemRights.WriteAttributes | FileSystemRights.WriteExtendedAttributes | FileSystemRights.Delete | FileSystemRights.ChangePermissions | FileSystemRights.TakeOwnership;
64 foreach (FileSystemAccessRule rule in acl.GetAccessRules(true, true, typeof(SecurityIdentifier)))
65 if (rule.AccessControlType == AccessControlType.Allow && (rule.FileSystemRights & writes) != 0 && rule.IdentityReference.Value is not ("S-1-5-18" or "S-1-5-32-544")) return false;
66 // The SYSTEM writer atomically replaces this file every second.
67 // Keep one immutable snapshot while permitting that replacement;
68 // File.ReadAllText's default sharing can block the writer on NTFS.
69 using var snapshot = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete);
70 if (snapshot.Length is < 1 or > 16384) return false;
71 using var reader = new StreamReader(snapshot);
72 var receipt = JsonNode.Parse(reader.ReadToEnd()) as JsonObject;
73 var updated = receipt?["updated_at"]?.GetValue<long>() ?? 0;
74 var age = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - updated;
75 return receipt?["version"]?.GetValue<int>() == 1 && Guid.TryParse(receipt["vm_id"]?.GetValue<string>(), out var receivedVM) && receivedVM == vm &&
76 receipt["gui_user_sid"]?.GetValue<string>() == GuestContext.SID && receipt["network"]?.GetValue<string>() == "packet" &&
77 receipt["adapter"]?.GetValue<string>() == "Cage-" + vm.ToString("N")[..8] && receipt["interface_index"]?.GetValue<int>() > 0 &&
78 receipt["session"]?.GetValue<string>() is { Length: > 0 and <= 128 } && age is >= -1000 and <= 5000;
79 }
80 catch { return false; }
81 }
82
83 internal static async Task Run(Stream stream, CancellationToken token, Func<bool> sessionAvailable)
84 {
85 var lease=BrowserWindowCapture.OpenLease();Task<JsonObject>? transaction=null;
86 try
87 {
88 while (await Protocol.Read(stream, 128 << 10, token) is { } request)
89 {
90 if (!sessionAvailable()) throw new InvalidDataException("requires_gui_login");
91 Validate(request);
92 // A canceled viewer leaves the reply drain running. Otherwise its
93 // pending reply could become the next viewer's browser response.
94 transaction = Exchange(request, token, lease);
95 JsonObject result;
96 try { result = await transaction.WaitAsync(token); }
97 catch (OperationCanceledException)
98 {
99 throw;
100 }
101 catch (InvalidDataException error)
102 {
103 var known = new HashSet<string> { "project_grant_unavailable", "editor_components_missing", "editor_start_failed", "editor_start_busy", "clipboard_copy_not_observed", "selection_not_authorized", "browser_network_unavailable", "browser_components_missing", "requires_gui_login", "editor_package_invalid", "browser_unavailable", "browser_response_timeout", "browser_target_changed", "browser_window_unavailable", "browser_process_unavailable", "browser_capture_surface_unavailable", "browser_focus_required", "browser_frame_limit", "desktop_target_changed", "desktop_empty_frame", "desktop_capture_buffer_invalid", "desktop_graphics_device_unavailable", "desktop_capture_permission_required", "desktop_capture_geometry_invalid" };
104 var code = known.Contains(error.Message) ? error.Message : "browser_operation_failed";
105 GuestDiagnostics.Record("browser", code);
106 result = new JsonObject { ["error"] = code, ["code"] = code };
107 }
108 if (!sessionAvailable()) throw new InvalidDataException("requires_gui_login");
109 await Protocol.Write(stream, result, token);
110 }
111 }
112 finally
113 {
114 // No transaction may inject a late down after this lease is closed.
115 if(transaction is not null)await Observe(transaction);
116 await Gate.WaitAsync();
117 try
118 {
119 if (pagePointerOwner == lease)
120 {
121 pagePointerOwner = null;
122 pagePointerReleasePending = true;
123 if (sessionAvailable())
124 {
125 using var releaseTimeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
126 try { await ReleasePagePointer(releaseTimeout.Token); }
127 catch { Close(); }
128 }
129 }
130 BrowserWindowCapture.CloseLease(lease);
131 }
132 finally { Gate.Release(); }
133 await WindowsPhoneBrowser.Release(lease);
134 }
135 }
136
137 private static void Validate(JsonObject value)
138 {
139 var method = value["method"]?.GetValue<string>();
140 var path = value["path"]?.GetValue<string>() ?? "";
141 if (value.ContainsKey("operation") || method is not ("GET" or "POST") ||
142 path.Length < 2 || !path.StartsWith('/') || !Routes.Contains(path[1..]) ||
143 value["input"] is not (null or JsonObject) ||
144 method == "GET" && path is not ("/health" or "/tabs" or "/events" or "/frame"))
145 throw new InvalidDataException("browser_request_invalid");
146 }
147
148 private static void AssertEditorTab(string? id)
149 {
150 if(id is not null && EditorTabs.TryGetValue(id,out var bound) && ProjectRpc.Resolve(bound.Project,bound.Grant)!=bound.Folder)
151 throw new InvalidDataException("project_grant_unavailable");
152 }
153 private static void AssertFrameEditors(JsonObject frame)
154 {
155 AssertEditorTab(frame["id"]?.GetValue<string>());
156 AssertEditorTab((frame["native"] as JsonObject)?["id"]?.GetValue<string>());
157 if(frame["panes"] is JsonArray panes)foreach(var pane in panes.OfType<JsonObject>())AssertEditorTab(pane["id"]?.GetValue<string>());
158 }
159 private static void AssertRequestedTab(JsonObject input,JsonObject proof)
160 {AssertEditorTab(proof["id"]?.GetValue<string>());if(input["id"]?.GetValue<string>() is {Length:>0} id&&id!=proof["id"]?.GetValue<string>())throw new InvalidDataException("browser_target_changed");}
161
162 private static async Task ReleasePagePointer(CancellationToken token)
163 {
164 if (browser is not null && !browser.HasExited)
165 await Control(new JsonObject { ["operation"] = "input-release-pointer" }, token);
166 pagePointerOwner = null;
167 pagePointerReleasePending = false;
168 }
169
170 private static async Task<JsonObject> Exchange(JsonObject request, CancellationToken connection, NativeInputCoordinator.Lease lease)
171 {
172 if (request["path"]?.GetValue<string>()?.StartsWith("/phone-browser/", StringComparison.Ordinal) == true)
173 return await WindowsPhoneBrowser.Exchange(request, connection, lease);
174 await Gate.WaitAsync(connection);
175 try
176 {
177 // The connection token must not interrupt the child's reply drain.
178 using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(35));
179 var route = request["path"]?.GetValue<string>() ?? "";
180 var input = request["input"] as JsonObject ?? new JsonObject();
181 if(route is "/paste-cancel" or "/image-cancel")
182 {
183 BrowserPasteInput.Cancel(input["transfer"]?.GetValue<string>() ?? "");
184 return new JsonObject { ["ok"] = true };
185 }
186 if(route=="/input"&&BrowserWindowCapture.ReleaseInput(lease,input))return new JsonObject { ["ok"] = true };
187 await Start(timeout.Token);
188 if (pagePointerReleasePending) await ReleasePagePointer(timeout.Token);
189 if (pagePointerOwner is not null && route is "/resize" or "/navigate" or "/new" or "/close" or "/activate" or "/split" or "/back" or "/forward" or "/reload" or "/paste" or "/cut" or "/copy" or "/select-all" or "/insert-text")
190 await ReleasePagePointer(timeout.Token);
191 connection.ThrowIfCancellationRequested();
192 WindowsEditorServer.Connection? editor = null;
193 if (route is "/editor" or "/editor-restart")
194 {
195 var project = input["project_id"]?.GetValue<string>() ?? "";
196 var grant = input["grant"]?.GetValue<string>() ?? "";
197 editor = await WindowsEditorServer.Open(project, grant, route == "/editor-restart", timeout.Token);
198 connection.ThrowIfCancellationRequested();
199 EditorConnections[editor.ID] = editor;
200 await Control(new JsonObject { ["operation"] = "editor-connect", ["input"] = new JsonObject
201 {
202 ["workspace"] = project, ["folder"] = editor.Folder, ["url"] = editor.URL, ["connection"] = editor.ID,
203 ["trust_default"] = editor.TrustDefault.HasValue ? JsonValue.Create(editor.TrustDefault.Value) : null,
204 } }, timeout.Token);
205 // Authorization uses only Resolve; a wire Workspace never selects
206 // an executable, path or browser URL.
207 input = new JsonObject { ["workspace"] = project };
208 request = new JsonObject { ["method"] = "POST", ["path"] = route, ["input"] = input };
209 }
210 var selected = input["id"]?.GetValue<string>() ?? active;
211 if (route is not ("/tabs" or "/events" or "/audit" or "/close" or "/new" or "/settings" or "/extensions" or "/internal-page" or "/editor" or "/editor-restart"))AssertEditorTab(selected);
212 if(route=="/split" && input["left"] is not null){AssertEditorTab(input["left"]?.GetValue<string>());AssertEditorTab(input["right"]?.GetValue<string>());}
213 if (route.StartsWith("/image-", StringComparison.Ordinal) || route.StartsWith("/paste-", StringComparison.Ordinal))
214 {
215 if(route=="/image-start")input["mime"]="image/png";
216 route=route.Replace("/paste-","/image-",StringComparison.Ordinal);
217 if (route == "/image-cancel") { BrowserPasteInput.Cancel(input["transfer"]?.GetValue<string>() ?? ""); return new JsonObject { ["ok"] = true }; }
218 if (route == "/image-chunk") return BrowserPasteInput.Chunk(input);
219 var proof = await Control(new JsonObject { ["method"] = "GET", ["path"] = "/frame-proof" }, timeout.Token);
220 AssertEditorTab(proof["id"]?.GetValue<string>());
221 var focus = await Control(new JsonObject { ["method"] = "GET", ["path"] = "/focus-proof" }, timeout.Token);
222 if (route == "/image-start") return await BrowserPasteInput.Start(input, proof, focus);
223 if (route == "/image-finish") return await BrowserPasteInput.Finish(input, proof, focus, async () =>
224 {
225 var current = await Control(new JsonObject { ["method"] = "GET", ["path"] = "/frame-proof" }, timeout.Token);
226 AssertEditorTab(current["id"]?.GetValue<string>());
227 var field = await Control(new JsonObject { ["method"] = "GET", ["path"] = "/focus-proof" }, timeout.Token);
228 if (current["target"]?.GetValue<string>() != proof["target"]?.GetValue<string>() || current["id"]?.GetValue<string>() != proof["id"]?.GetValue<string>() || field["focus"]?.GetValue<string>() != focus["focus"]?.GetValue<string>()) throw new InvalidDataException("image_target_changed");
229 if (BrowserWindowCapture.Edit(browser!, proof, "paste")) return new JsonObject { ["ok"] = true };
230 return await Control(new JsonObject { ["method"] = "POST", ["path"] = "/paste", ["input"] = new JsonObject { ["id"] = proof["id"]!.DeepClone(), ["document"] = proof["document"]!.DeepClone() } }, timeout.Token);
231 });
232 throw new InvalidDataException("image_request_invalid");
233 }
234 var clipboard = ClipboardAgent.Current;
235 uint? previous = null;
236 if (clipboard is not null && route is "/copy" or "/cut" or "/copy-context") previous = await clipboard.Revision();
237 if (clipboard is not null && route == "/paste") await clipboard.PreparePaste();
238 if (route == "/copy-context" && previous.HasValue && input["context"]?.GetValue<string>() is { } copyContext)
239 {
240 if (CopyRevisions.Count > 200) CopyRevisions.Clear();
241 CopyRevisions[copyContext] = previous.Value;
242 }
243 connection.ThrowIfCancellationRequested();
244 if (route == "/input")
245 {
246 if (input["kind"]?.GetValue<string>() == "pointer" && pagePointerOwner is not null)
247 {
248 if (pagePointerOwner != lease) throw new InvalidDataException("browser_target_changed");
249 if (input["mask"]?.GetValue<int>() == 0)
250 {
251 await ReleasePagePointer(timeout.Token);
252 return new JsonObject{["ok"]=true};
253 }
254 }
255 var proof = await Control(new JsonObject { ["method"] = "GET", ["path"] = "/frame-proof" }, timeout.Token);
256 AssertEditorTab(proof["id"]?.GetValue<string>());
257 if(BrowserWindowCapture.FocusRenderer(browser!,proof))
258 {proof=await Control(new JsonObject{["method"]="GET",["path"]="/frame-proof"},timeout.Token);AssertEditorTab(proof["id"]?.GetValue<string>());}
259 if (pagePointerOwner != lease && BrowserWindowCapture.SelectPane(browser!, lease, input, proof))
260 {
261 await Control(new JsonObject { ["operation"] = "input-select-pane", ["input"] = new JsonObject { ["target"] = proof["target"]!.DeepClone(), ["x"] = input["x"]!.DeepClone() } }, timeout.Token);
262 proof = await Control(new JsonObject { ["method"] = "GET", ["path"] = "/frame-proof" }, timeout.Token);
263 AssertEditorTab(proof["id"]?.GetValue<string>());
264 BrowserWindowCapture.Transition(browser!, proof);
265 }
266 if (BrowserWindowCapture.HandleInput(browser!, lease, input, proof, pagePointerOwner == lease))
267 {
268 if (input["kind"]?.GetValue<string>() == "pointer")
269 await Control(new JsonObject { ["operation"] = "input-reset" }, timeout.Token);
270 BrowserWindowCapture.Transition(browser!, await Control(new JsonObject { ["method"] = "GET", ["path"] = "/frame-proof" }, timeout.Token));
271 active = proof["id"]?.GetValue<string>() ?? active;
272 return new JsonObject { ["ok"] = true, ["active"] = active };
273 }
274 if (input["kind"]?.GetValue<string>() == "pointer" && ((input["mask"]?.GetValue<int>() ?? 0) & 7) != 0)
275 pagePointerOwner = lease;
276 }
277 if (route is "/paste" or "/copy" or "/cut" or "/select-all" or "/insert-text")
278 {
279 var proof = await Control(new JsonObject { ["method"] = "GET", ["path"] = "/frame-proof" }, timeout.Token);
280 AssertRequestedTab(input,proof);
281 if (BrowserWindowCapture.Edit(browser!, proof, route[1..], input["text"]?.GetValue<string>() ?? ""))
282 {
283 await Control(new JsonObject { ["operation"] = "input-reset" }, timeout.Token);
284 var receipt = new JsonObject { ["ok"] = true };
285 if (previous.HasValue && route is "/copy" or "/cut") receipt["clipboard"] = await clipboard!.Receipt(previous.Value, true);
286 return receipt;
287 }
288 }
289 if (route == "/ime")
290 {
291 var proof = await Control(new JsonObject { ["method"] = "GET", ["path"] = "/frame-proof" }, timeout.Token);
292 AssertRequestedTab(input,proof);
293 if (input["id"]?.GetValue<string>() != proof["id"]?.GetValue<string>()) throw new InvalidDataException("browser_target_changed");
294 var native = await BrowserWindowCapture.Ime(browser!, proof, input, timeout.Token);
295 if (native is not null) return native;
296 }
297 var afterFrame = route == "/frame" ? input["after"]?.GetValue<string>() : null;
298 if (route == "/frame")
299 {
300 // Cached page pixels and the current native-window proof have
301 // separate lifetimes. Native menus are inspected on every call.
302 input["after"] = cachedPageFrame?["sequence"]?.DeepClone();
303 input["nativeProof"] = true;
304 if (request["input"] is null) request["input"] = input;
305 }
306 var result = await Control(request, timeout.Token);
307 if (route == "/frame" && result["error"] is null)
308 {
309 if (result["unchanged"]?.GetValue<bool>() == true)
310 {
311 if (cachedPageFrame is null || result["sequence"]?.GetValue<string>() != cachedPageFrame["sequence"]?.GetValue<string>())
312 throw new InvalidDataException("browser_target_changed");
313 var proof = result["native"]?.DeepClone() ?? await Control(new JsonObject { ["method"] = "GET", ["path"] = "/frame-proof" }, timeout.Token);
314 result = (JsonObject)cachedPageFrame.DeepClone();
315 result["native"] = proof;
316 }
317 else
318 {
319 AssertFrameEditors(result);
320 cachedPageFrame = (JsonObject)result.DeepClone();
321 }
322 AssertFrameEditors(result);
323 await BrowserWindowCapture.Decorate(browser!, result, async ()=>{var current=await Control(new JsonObject { ["method"] = "GET", ["path"] = "/frame-proof" }, timeout.Token);AssertEditorTab(current["id"]?.GetValue<string>());return current;});
324 AssertFrameEditors(result);
325 result = BrowserWindowCapture.FrameReply(result, afterFrame);
326 }
327 if (result["error"] is null)
328 {
329 ready = true;
330 if (result["capabilities"] is JsonObject capability) features = (JsonObject)capability.DeepClone();
331 else if (result["state"]?["capabilities"] is JsonObject stateCapability) features = (JsonObject)stateCapability.DeepClone();
332 if (result["active"]?.GetValue<string>() is { } current) active = current;
333 if (route is "/activate" or "/new" or "/editor" or "/editor-restart") active = result["id"]?.GetValue<string>() ?? input["id"]?.GetValue<string>() ?? active;
334 if (editor is not null && result["id"]?.GetValue<string>() is { } tabID)
335 {
336 if (ProjectRpc.Resolve(editor.Project, editor.Grant) != editor.Folder) throw new InvalidDataException("project_grant_unavailable");
337 EditorTabs[tabID] = editor;
338 }
339 if (route == "/close") EditorTabs.TryRemove(selected, out _);
340 if (clipboard is not null && previous.HasValue && route is "/copy" or "/cut")
341 result["clipboard"] = await clipboard.Receipt(previous.Value, true);
342 if (clipboard is not null && result["events"] is JsonArray events)
343 {
344 foreach (var value in events.OfType<JsonObject>()) if (value["type"]?.GetValue<string>() == "clipboard")
345 {
346 var payload = value["value"] as JsonObject;
347 var context = payload?["context"]?.GetValue<string>() ?? "";
348 payload?.Remove("text"); value["type"] = "native-clipboard";
349 try
350 {
351 if (!CopyRevisions.TryGetValue(context, out var revision)) throw new InvalidDataException("copy_context_expired");
352 payload!["receipt"] = await clipboard.Receipt(revision, true);
353 }
354 catch { value["type"] = "copy-expired"; }
355 }
356 }
357 }
358 return result;
359 }
360 catch (OperationCanceledException)
361 { if (wirePending) Close(); throw new InvalidDataException("browser_response_timeout"); }
362 catch (EndOfStreamException) { Close(); throw new InvalidDataException("browser_unavailable"); }
363 finally { Gate.Release(); }
364 }
365
366 internal static async Task<JsonObject> ReadConfiguration(CancellationToken token, bool packetOnly = false)
367 {
368 var root = AppContext.BaseDirectory;
369 var configPath = Path.Combine(root, "guest-config.json");
370 var info = new FileInfo(configPath);
371 if (!info.Exists || info.Length is <= 0 or > 16384 || info.Attributes.HasFlag(FileAttributes.ReparsePoint))
372 throw new InvalidDataException("browser_network_unavailable");
373 using var snapshot = OpenPublishedFile(configPath);
374 using var reader = new StreamReader(snapshot);
375 var config = JsonNode.Parse(await reader.ReadToEndAsync(token)) as JsonObject
376 ?? throw new InvalidDataException("browser_network_unavailable");
377 var packet = config["network_mode"]?.GetValue<string>() == "packet";
378 if (packetOnly && !packet) throw new InvalidDataException("browser_network_unavailable");
379 var proxy = config["browser_proxy"]?.GetValue<string>();
380 Uri? address = null;
381 if (packet ? !PacketReady() : !Uri.TryCreate(proxy, UriKind.Absolute, out address) || address.Scheme != "http" ||
382 address.Host != "127.0.0.1" || address.IsDefaultPort || address.UserInfo != "" ||
383 address.AbsolutePath != "/" || address.Query != "" || address.Fragment != "")
384 throw new InvalidDataException("browser_network_unavailable");
385 var settings = packet ? new JsonObject { ["networkMode"] = "packet" } : new JsonObject { ["proxy"] = address!.GetLeftPart(UriPartial.Authority) };
386 if (config["timezone"] is JsonValue zone) settings["timezone"] = zone.DeepClone();
387 if (config["language"] is JsonValue lang) settings["language"] = lang.DeepClone();
388 return settings;
389 }
390 private static async Task Start(CancellationToken token)
391 {
392 if (browser is { HasExited: false }) return;
393 Close();
394 var root = AppContext.BaseDirectory;
395 var executable = Path.Combine(root, "node.exe");
396 var script = Path.Combine(root, "windows-browser.mjs");
397 if (!File.Exists(executable) || !File.Exists(script)) throw new InvalidDataException("browser_components_missing");
398 var settings = await ReadConfiguration(token);
399 var start = new ProcessStartInfo(executable)
400 {
401 UseShellExecute = false, RedirectStandardInput = true, RedirectStandardOutput = true,
402 RedirectStandardError = true, CreateNoWindow = true, WorkingDirectory = root,
403 StandardInputEncoding = Protocol.Utf8, StandardOutputEncoding = Protocol.Utf8, StandardErrorEncoding = Protocol.Utf8,
404 };
405 start.ArgumentList.Add(script);
406 browser = Process.Start(start) ?? throw new InvalidDataException("browser_unavailable");
407 var process = browser;
408 try { browserJob = new GuestProcessJob(process); }
409 catch { Close(); throw new InvalidDataException("browser_process_unavailable"); }
410 replies = new ReadAheadStream(process.StandardOutput.BaseStream);
411 errors = Task.Run(async () =>
412 {
413 var discard = new char[4096];
414 try { while (await process.StandardError.ReadAsync(discard) != 0) { } }
415 catch (ObjectDisposedException) { }
416 });
417 var result = await Control(new JsonObject
418 {
419 ["operation"] = "configure", ["input"] = settings,
420 }, token);
421 if (result?["ok"]?.GetValue<bool>() != true) { Close(); throw new InvalidDataException("browser_network_unavailable"); }
422 }
423
424 private static async Task<JsonObject> Control(JsonObject value, CancellationToken token)
425 {
426 wirePending = true;
427 await Protocol.Write(browser!.StandardInput.BaseStream, value, token);
428 var result = await Protocol.Read(replies!, Protocol.WireLimit, token) ?? throw new EndOfStreamException();
429 wirePending = false;
430 return result;
431 }
432
433 private static async Task RevokeNode(string project, string grant)
434 {
435 await Gate.WaitAsync();
436 try
437 {
438 if (browser is not { HasExited: false }) return;
439 using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
440 foreach (var editor in EditorConnections.Values.Where(e => e.Project == project && e.Grant == grant))
441 {
442 await Control(new JsonObject { ["operation"] = "editor-revoke", ["input"] = new JsonObject { ["workspace"] = project, ["connection"] = editor.ID } }, timeout.Token);
443 EditorConnections.TryRemove(editor.ID, out _);
444 }
445 }
446 catch { /* Every editor request also checks the live project resolver. */ }
447 finally { Gate.Release(); }
448 }
449
450 internal static bool BrowserExecutableInstalled() =>
451 File.Exists(Path.Combine(AppContext.BaseDirectory, "chrome", "chrome.exe")) ||
452 new[] { Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) }
453 .Any(basePath => new[] { "Google/Chrome/Application/chrome.exe", "Microsoft/Edge/Application/msedge.exe" }.Any(relative => File.Exists(Path.Combine(basePath, relative))));
454
455 internal static JsonObject Status()
456 {
457 var root = AppContext.BaseDirectory;
458 var installed = new[] { "node.exe", "windows-browser.mjs", "windows-browser-extensions.mjs", "playwright/index.mjs", "modules/browser-clipboard.mjs", "modules/browser-uploads.mjs", "modules/browser-downloads.mjs", "modules/browser-cookies.mjs", "modules/browser-extensions.mjs", "modules/browser-vault.mjs", "split-extension/manifest.json", "split-extension/control.html", "split-extension/control.js" }.All(file => File.Exists(Path.Combine(root, file)));
459 installed &= BrowserExecutableInstalled();
460 var network = false;var phoneNetwork = false;
461 try
462 {
463 var file = new FileInfo(Path.Combine(root, "guest-config.json"));
464 JsonObject? config = null;
465 if (file.Exists && file.Length is > 0 and <= 16384)
466 {
467 using var snapshot = OpenPublishedFile(file.FullName);
468 using var reader = new StreamReader(snapshot);
469 config = JsonNode.Parse(reader.ReadToEnd()) as JsonObject;
470 }
471 phoneNetwork = config?["network_mode"]?.GetValue<string>() == "packet" && PacketReady();
472 network = config?["network_mode"]?.GetValue<string>() == "packet" ? phoneNetwork : Uri.TryCreate(config?["browser_proxy"]?.GetValue<string>(), UriKind.Absolute, out var proxy) && proxy.Scheme == "http" && proxy.Host == "127.0.0.1" && !proxy.IsDefaultPort && proxy.UserInfo == "" && proxy.AbsolutePath == "/" && proxy.Query == "" && proxy.Fragment == "";
473 }
474 catch { }
475 return new JsonObject { ["installed"] = installed, ["network_configured"] = network, ["ready"] = ready && browser is { HasExited: false } && SessionGuard.Available(), ["editor_installed"] = WindowsEditorServer.Installed(), ["phone_installed"] = WindowsPhoneBrowser.Installed(), ["phone_network_configured"] = phoneNetwork, ["capabilities"] = features.DeepClone() };
476 }
477
478 private static async Task Observe(Task task) { try { await task; } catch { /* reply drain owns cleanup */ } }
479
480 private static FileStream OpenPublishedFile(string path)
481 {
482 var snapshot = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete);
483 if (snapshot.Length is > 0 and <= 16384) return snapshot;
484 snapshot.Dispose();
485 throw new InvalidDataException("browser_network_unavailable");
486 }
487
488 internal static void Close()
489 {
490 ready = false;
491 wirePending = false;
492 cachedPageFrame = null;
493 pagePointerOwner = null;
494 pagePointerReleasePending = false;
495 BrowserWindowCapture.Close();
496 BrowserPasteInput.Close();
497 var process = Interlocked.Exchange(ref browser, null);
498 if (process is null) return;
499 try
500 {
501 process.StandardInput.Close();
502 if (!process.WaitForExit(2000)) process.Kill(true);
503 process.WaitForExit(2000);
504 }
505 catch (InvalidOperationException) { }
506 finally { browserJob?.Dispose(); browserJob = null; replies?.Dispose(); replies = null; process.Dispose(); }
507 if (errors is { IsCompleted: true }) { try { errors.GetAwaiter().GetResult(); } catch { } }
508 errors = null;
509 }
510}