跳到主要内容

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

浏览文件

ClipboardAgent.cs

402 行 · 22.6 KB历史下载
1using System.Collections.Specialized;
2using System.Diagnostics;
3using System.Drawing.Imaging;
4using System.Runtime.InteropServices;
5using System.Text.Json;
6using System.Text.Json.Nodes;
7using System.Threading.Channels;
8
9namespace Cage.GuestClipboard;
10
11internal sealed class ClipboardAgent : Control
12{
13 internal static ClipboardAgent? Current { get; private set; }
14 [DllImport("user32.dll")] static extern bool AddClipboardFormatListener(IntPtr window);
15 [DllImport("user32.dll")] static extern bool RemoveClipboardFormatListener(IntPtr window);
16 [DllImport("user32.dll")] static extern uint GetClipboardSequenceNumber();
17 [DllImport("wtsapi32.dll", SetLastError = true)] private static extern bool WTSRegisterSessionNotification(IntPtr window, uint flags);
18 [DllImport("wtsapi32.dll")] private static extern bool WTSUnRegisterSessionNotification(IntPtr window);
19 internal readonly string Session = Guid.NewGuid().ToString("N");
20 private long sessionEpoch = 1;
21 internal long SessionEpoch => Interlocked.Read(ref sessionEpoch);
22 internal bool SessionEventsRegistered { get; private set; }
23 readonly string helper;
24 readonly HashSet<string> approved = new(StringComparer.OrdinalIgnoreCase);
25 readonly Queue<string[]> selections = new();
26 sealed class CachedCopy(string id, string[] paths, bool pinned)
27 {
28 internal readonly string ID = id;
29 internal readonly string[] Paths = paths;
30 internal bool Pinned = pinned;
31 }
32 readonly Dictionary<string, CachedCopy> copies = new();
33 readonly Dictionary<Guid, string[]> fileReaders = new();
34 bool copiesLoaded, collectingCopies;
35 DateTime nextCacheCheck;
36 readonly System.Windows.Forms.Timer timer = new() { Interval = 250 };
37 Channel<JsonObject>? subscriber;
38 uint observed;
39 bool seeded, reading, lastAvailable;
40 CancellationTokenSource? selectionCopy;
41 internal ClipboardAgent(string filesHelper)
42 {
43 Current = this;
44 helper = filesHelper;
45 CreateControl(); _ = Handle;
46 if (!File.Exists(helper) || !AddClipboardFormatListener(Handle)) throw new InvalidOperationException("clipboard_agent_unavailable");
47 SessionEventsRegistered = WTSRegisterSessionNotification(Handle, 0);
48 lastAvailable = SessionGuard.Available(); observed = GetClipboardSequenceNumber();
49 timer.Tick += (_, _) => Tick(); timer.Start();
50 }
51 protected override void WndProc(ref Message m)
52 {
53 if (m.Msg == 0x031D) Tick(); // WM_CLIPBOARDUPDATE
54 if (m.Msg == 0x02B1) { Interlocked.Increment(ref sessionEpoch); Tick(); }
55 base.WndProc(ref m);
56 }
57 protected override void Dispose(bool disposing)
58 {
59 if (disposing) { timer.Stop(); timer.Dispose(); RemoveClipboardFormatListener(Handle); if (SessionEventsRegistered) WTSUnRegisterSessionNotification(Handle); subscriber?.Writer.TryComplete(); }
60 base.Dispose(disposing);
61 }
62 internal Task<T> GUI<T>(Func<T> action)
63 {
64 var result = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously);
65 BeginInvoke(() => { try { result.SetResult(action()); } catch (Exception ex) { result.SetException(ex); } });
66 return result.Task;
67 }
68 internal Task<uint> Revision() => GUI(() => { SessionGuard.Assert(); return GetClipboardSequenceNumber(); });
69 internal Task<bool> PasteImage(byte[] bytes, Action paste) => GUI(() =>
70 {
71 SessionGuard.Assert(); Protocol.Png(bytes);
72 using var input = new MemoryStream(bytes); using var image = Image.FromStream(input, false, true);
73 using var bitmap = new Bitmap(image);
74 var data = new DataObject(); data.SetData("PNG", false, new MemoryStream(bytes)); data.SetImage(bitmap);
75 Clipboard.SetDataObject(data, true); paste(); return true;
76 });
77 internal Task<bool> PasteFiles(string[] paths, Action paste) => GUI(() =>
78 {
79 SessionGuard.Assert(); Protocol.Paths(JsonSerializer.SerializeToNode(paths));
80 Approve(paths); var list=new StringCollection();list.AddRange(paths);
81 Clipboard.SetFileDropList(list);paste();return true;
82 });
83 // Private browser receipts confirm native Windows clipboard ownership.
84 // Content still travels through the single observer, preserving PNG and
85 // file selections instead of rewriting a browser's text-only result.
86 internal Task<JsonObject> Receipt(uint previous, bool requireChange) => GUI(() =>
87 {
88 SessionGuard.Assert(); var revision = GetClipboardSequenceNumber();
89 if (requireChange && revision == previous) throw new InvalidDataException("clipboard_copy_not_observed");
90 return new JsonObject { ["revision"] = revision, ["changed"] = revision != previous, ["available"] = true };
91 });
92 internal Task<JsonObject> PreparePaste() => GUI(() =>
93 {
94 SessionGuard.Assert(); var revision = GetClipboardSequenceNumber();
95 if (Clipboard.ContainsFileDropList()) { var paths = Protocol.Paths(JsonSerializer.SerializeToNode(Clipboard.GetFileDropList().Cast<string>().ToArray())); AssertApproved(paths); }
96 else if (Clipboard.TryGetData<MemoryStream>("PNG", out var png) && png != null) Protocol.Png(png.ToArray());
97 else if (Clipboard.ContainsImage())
98 {
99 using var image = Clipboard.GetImage() ?? throw new InvalidDataException("clipboard_image_unavailable");
100 if ((long)image.Width * image.Height > 40_000_000) throw new InvalidDataException("image_limit");
101 using var bytes = new MemoryStream(); image.Save(bytes, ImageFormat.Png); Protocol.Png(bytes.ToArray());
102 }
103 else if (Clipboard.ContainsText() && Protocol.Utf8.GetByteCount(Clipboard.GetText(TextDataFormat.UnicodeText)) > Protocol.TextLimit) throw new InvalidDataException("text_limit");
104 if (GetClipboardSequenceNumber() != revision) throw new InvalidDataException("clipboard_selection_changed");
105 return new JsonObject { ["revision"] = revision, ["available"] = true };
106 });
107 internal Task<JsonObject> WriteBrowserPng(uint expectedRevision, byte[] png) => GUI(() =>
108 {
109 SessionGuard.Assert(); Protocol.Png(png);
110 if (GetClipboardSequenceNumber() != expectedRevision) throw new InvalidDataException("clipboard_selection_changed");
111 using var input = new MemoryStream(png); using var image = Image.FromStream(input, false, true); using var bitmap = new Bitmap(image);
112 if (GetClipboardSequenceNumber() != expectedRevision) throw new InvalidDataException("clipboard_selection_changed");
113 var data = new DataObject(); data.SetData("PNG", false, new MemoryStream(png)); data.SetImage(bitmap); Clipboard.SetDataObject(data, true);
114 observed = GetClipboardSequenceNumber(); seeded = true;
115 Publish(new JsonObject { ["png"] = Convert.ToBase64String(png), ["source"] = "guest" });
116 return new JsonObject { ["revision"] = observed, ["available"] = true };
117 });
118 internal Task<JsonObject> WriteBrowserText(uint expectedRevision, string text) => GUI(() =>
119 {
120 SessionGuard.Assert();
121 if (Protocol.Utf8.GetByteCount(text) > Protocol.TextLimit) throw new InvalidDataException("text_limit");
122 if (GetClipboardSequenceNumber() != expectedRevision) throw new InvalidDataException("clipboard_selection_changed");
123 if (text.Length == 0) Clipboard.Clear(); else Clipboard.SetText(text, TextDataFormat.UnicodeText);
124 observed = GetClipboardSequenceNumber(); seeded = true;
125 Publish(new JsonObject { ["text"] = text, ["source"] = "guest" });
126 return new JsonObject { ["revision"] = observed, ["available"] = true };
127 });
128 internal JsonObject Hello() => new() { ["version"] = 1, ["os"] = "windows", ["session"] = Session, ["formats"] = new JsonArray("text", "png", "files"), ["available"] = SessionGuard.Available(), ["file_release"] = true };
129 internal Task<ChannelReader<JsonObject>> Subscribe() => GUI(() =>
130 {
131 if (subscriber != null) throw new InvalidOperationException("clipboard_busy");
132 subscriber = Channel.CreateBounded<JsonObject>(new BoundedChannelOptions(16) { SingleReader = true, FullMode = BoundedChannelFullMode.Wait });
133 seeded = false; observed = GetClipboardSequenceNumber();
134 return subscriber.Reader;
135 });
136 internal Task<bool> Unsubscribe() => GUI(() => {
137 subscriber?.Writer.TryComplete(); subscriber = null; seeded = false;
138 foreach (var copy in copies.Values) copy.Pinned = false;
139 CollectCopies(); return true;
140 });
141 void Publish(JsonObject message)
142 {
143 if (subscriber != null && subscriber.Writer.TryWrite(message)) return;
144 if (message["files"] is not null) RetireCopies(Protocol.Paths(message["files"]));
145 subscriber?.Writer.TryComplete(new IOException("clipboard_consumer_slow"));
146 }
147 internal void ReportError() => Publish(new() { ["error"] = SessionGuard.Available() ? "clipboard_selection_unavailable" : "requires_gui_login" });
148 void Tick()
149 {
150 if (DateTime.UtcNow >= nextCacheCheck) { nextCacheCheck = DateTime.UtcNow.AddSeconds(1); CollectCopies(); }
151 var available = SessionGuard.Available();
152 if (available != lastAvailable) { Interlocked.Increment(ref sessionEpoch); lastAvailable = available; Publish(Protocol.PublicHello(Hello())); }
153 if (!available) selectionCopy?.Cancel();
154 if (!available || !seeded || subscriber == null || reading) return;
155 var sequence = GetClipboardSequenceNumber();
156 if (sequence == observed) return;
157 ReadSelection(sequence);
158 }
159 async void ReadSelection(uint sequence)
160 {
161 reading = true;
162 var capturedSubscriber = subscriber;
163 var capturedSession = SessionEpoch;
164 try
165 {
166 SessionGuard.Assert();
167 JsonObject payload;
168 if (Clipboard.ContainsFileDropList())
169 {
170 var paths = Clipboard.GetFileDropList().Cast<string>().ToArray();
171 Protocol.Paths(JsonSerializer.SerializeToNode(paths));
172 Approve(paths); // The native GUI selection itself is an explicit source grant.
173 // This child inherits the actual GUI token, never Session0 or a
174 // management administrator's access to the selected files.
175 using var copying = new CancellationTokenSource(TimeSpan.FromMinutes(30)); selectionCopy = copying;
176 string[] copied;
177 try { copied = await FilePaths("copy", paths, copying.Token); }
178 finally { if (selectionCopy == copying) selectionCopy = null; }
179 if (!SessionGuard.Available() || GetClipboardSequenceNumber() != sequence || subscriber != capturedSubscriber || SessionEpoch != capturedSession || !seeded) { RetireCopies(copied); return; }
180 Approve(copied);
181 payload = new() { ["files"] = JsonSerializer.SerializeToNode(copied) };
182 }
183 else if (Clipboard.ContainsData("PNG") || Clipboard.ContainsImage())
184 {
185 byte[] bytes;
186 if (Clipboard.TryGetData<MemoryStream>("PNG", out var png) && png != null) bytes = png.ToArray();
187 else
188 {
189 using var image = Clipboard.GetImage() ?? throw new InvalidDataException("clipboard_image_unavailable");
190 if ((long)image.Width * image.Height > 40_000_000) throw new InvalidDataException("image_limit");
191 using var output = new MemoryStream(); image.Save(output, ImageFormat.Png); bytes = output.ToArray();
192 }
193 Protocol.Png(bytes); payload = new() { ["png"] = Convert.ToBase64String(bytes) };
194 }
195 else
196 {
197 var text = Clipboard.ContainsText() ? Clipboard.GetText(TextDataFormat.UnicodeText) : "";
198 if (Protocol.Utf8.GetByteCount(text) > Protocol.TextLimit) throw new InvalidDataException("text_limit");
199 payload = new() { ["text"] = text };
200 }
201 if (!SessionGuard.Available() || GetClipboardSequenceNumber() != sequence) return;
202 observed = sequence; payload["source"] = "guest"; Publish(payload);
203 }
204 catch { if (SessionGuard.Available()) { observed = sequence; Publish(new() { ["error"] = "clipboard_selection_unavailable" }); } }
205 finally { reading = false; }
206 }
207 internal Task<bool> Apply(JsonObject message) => GUI(() =>
208 {
209 if (message["release"] is not null) { RetireCopies(Protocol.Paths(message["release"])); return true; }
210 SessionGuard.Assert();
211 selectionCopy?.Cancel();
212 var serial = message["serial"]?.GetValue<long>() ?? 0;
213 if (serial < 1 || new[] { "text", "png", "files" }.Count(message.ContainsKey) != 1) throw new InvalidDataException("clipboard_message_invalid");
214 if (message["files"] != null)
215 {
216 var paths = Protocol.Paths(message["files"]); AssertApproved(paths);
217 var list = new StringCollection(); list.AddRange(paths); Clipboard.SetFileDropList(list);
218 }
219 else if (message["png"] != null)
220 {
221 var bytes = Convert.FromBase64String(message["png"]!.GetValue<string>()); Protocol.Png(bytes);
222 using var input = new MemoryStream(bytes); using var image = Image.FromStream(input, false, true);
223 using var bitmap = new Bitmap(image);
224 var data = new DataObject(); data.SetData("PNG", false, new MemoryStream(bytes)); data.SetImage(bitmap);
225 Clipboard.SetDataObject(data, true);
226 }
227 else
228 {
229 var text = message["text"]!.GetValue<string>();
230 if (Protocol.Utf8.GetByteCount(text) > Protocol.TextLimit) throw new InvalidDataException("text_limit");
231 if (text.Length == 0) Clipboard.Clear(); else Clipboard.SetText(text, TextDataFormat.UnicodeText);
232 }
233 // The revision is saved on the STA before queued clipboard notifications
234 // run. Only a completed host write receives an acknowledgement.
235 observed = GetClipboardSequenceNumber(); seeded = true; Publish(new() { ["ack"] = serial }); return true;
236 });
237 void RememberCopy(JsonObject result)
238 {
239 var id = result["cache_id"]?.GetValue<string>();
240 if (string.IsNullOrEmpty(id)) return;
241 var paths = Protocol.Paths(result["paths"]);
242 copies[id] = new CachedCopy(id, paths, true);
243 _ = PublishCopy(id);
244 }
245 async Task PublishCopy(string id)
246 {
247 try { await Cache("publish", id); } catch { }
248 }
249 void RetireCopies(string[] paths)
250 {
251 foreach (var copy in copies.Values)
252 if (copy.Paths.Any(path => paths.Contains(path, StringComparer.OrdinalIgnoreCase))) copy.Pinned = false;
253 CollectCopies();
254 }
255 static bool References(string[] paths, string[] owned)
256 {
257 var root = Path.GetDirectoryName(owned[0])!;
258 return paths.Any(path => Path.GetFullPath(path).Equals(root, StringComparison.OrdinalIgnoreCase)
259 || Path.GetFullPath(path).StartsWith(root + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)
260 || root.StartsWith(Path.GetFullPath(path).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase));
261 }
262 async Task<JsonObject> Cache(string action, string id = "")
263 {
264 var start = new ProcessStartInfo(helper) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true };
265 start.ArgumentList.Add("cache"); start.ArgumentList.Add(JsonSerializer.Serialize(new { action, cache_id = id }));
266 using var child = Process.Start(start) ?? throw new IOException("clipboard_cache_unavailable");
267 child.StandardInput.Close();
268 _ = child.StandardError.BaseStream.CopyToAsync(Stream.Null);
269 using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10));
270 using var cancellation = timeout.Token.Register(() => { try { child.Kill(true); } catch { } });
271 var result = await Protocol.Read(child.StandardOutput.BaseStream, Protocol.WireLimit, timeout.Token) ?? throw new IOException("clipboard_cache_failed");
272 await child.WaitForExitAsync(timeout.Token);
273 if (child.ExitCode != 0) throw new IOException("clipboard_cache_failed");
274 return result;
275 }
276 async void CollectCopies()
277 {
278 if (collectingCopies || IsDisposed) return;
279 collectingCopies = true;
280 try
281 {
282 if (!copiesLoaded)
283 {
284 var previous = await Cache("list");
285 foreach (var item in previous["selections"]!.AsArray())
286 {
287 var id = item!["cache_id"]!.GetValue<string>();
288 copies.TryAdd(id, new CachedCopy(id, Protocol.Paths(item["paths"]), false));
289 }
290 copiesLoaded = true;
291 }
292 foreach (var copy in copies.Values.ToArray())
293 {
294 var selected = Clipboard.ContainsFileDropList() ? Clipboard.GetFileDropList().Cast<string>().ToArray() : [];
295 if (copy.Pinned || References(selected, copy.Paths) || fileReaders.Values.Any(paths => References(paths, copy.Paths))) continue;
296 try
297 {
298 await Cache("release", copy.ID);
299 copies.Remove(copy.ID);
300 foreach (var path in copy.Paths) approved.Remove(path);
301 }
302 catch { /* Keep its creation receipt for an ownership-change retry. */ }
303 }
304 }
305 catch { /* An unreadable clipboard retains its currently referenced files. */ }
306 finally { collectingCopies = false; }
307 }
308 void Approve(string[] paths)
309 {
310 selections.Enqueue(paths);
311 foreach (var path in paths) approved.Add(Path.GetFullPath(path));
312 while (selections.Count > 100)
313 {
314 var old = selections.Dequeue();
315 foreach (var path in old) if (!selections.Any(s => s.Contains(path, StringComparer.OrdinalIgnoreCase))) approved.Remove(Path.GetFullPath(path));
316 }
317 }
318 void AssertApproved(string[] paths)
319 {
320 if (paths.Any(path => !approved.Contains(Path.GetFullPath(path)))) throw new InvalidDataException("selection_not_authorized");
321 }
322 Process StartHelper(string operation)
323 {
324 SessionGuard.Assert();
325 var start = new ProcessStartInfo(helper) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true };
326 start.ArgumentList.Add(operation); if (operation != "import") start.ArgumentList.Add("--paths-stdin");
327 var process = Process.Start(start) ?? throw new IOException("file_helper_unavailable");
328 _ = process.StandardError.BaseStream.CopyToAsync(Stream.Null); return process;
329 }
330 internal async Task<string[]> FilePaths(string operation, string[]? paths, CancellationToken token)
331 {
332 var reader = Guid.NewGuid();
333 if (paths != null) await GUI(() => { fileReaders[reader] = paths; return true; });
334 string[]? created = null;
335 Process? child = null;
336 try
337 {
338 child = StartHelper(operation);
339 using var cancellation = token.Register(() => { try { child.Kill(true); } catch { } });
340 if (paths != null) await JsonSerializer.SerializeAsync(child.StandardInput.BaseStream, paths, cancellationToken: token);
341 child.StandardInput.Close();
342 var result = await Protocol.Read(child.StandardOutput.BaseStream, Protocol.PathLimit, token) ?? throw new IOException("file_helper_failed");
343 created = Protocol.Paths(result["paths"]);
344 await GUI(() => { RememberCopy(result); return true; });
345 await child.WaitForExitAsync(token);
346 if (child.ExitCode != 0) throw new IOException("file_helper_failed");
347 return created;
348 }
349 catch
350 {
351 if (child != null && !child.HasExited) { child.Kill(true); await child.WaitForExitAsync(); }
352 await GUI(() => { if (created != null) RetireCopies(created); else copiesLoaded = false; return true; });
353 throw;
354 }
355 finally { child?.Dispose(); await GUI(() => { fileReaders.Remove(reader); CollectCopies(); return true; }); }
356 }
357 internal async Task Import(Stream stream, CancellationToken token)
358 {
359 var capturedSubscriber = await GUI(() => subscriber);
360 var capturedSession = SessionEpoch;
361 using var child = StartHelper("import");
362 using var cancellation = token.Register(() => { try { child.Kill(true); } catch { } });
363 string[]? paths = null;
364 try
365 {
366 await Protocol.ReceiveFrames(stream, child.StandardInput.BaseStream, token); child.StandardInput.Close();
367 var result = await Protocol.Read(child.StandardOutput.BaseStream, Protocol.PathLimit, token) ?? throw new IOException("file_helper_failed");
368 paths = Protocol.Paths(result["paths"]);
369 await GUI(() => { RememberCopy(result); return true; });
370 await child.WaitForExitAsync(token);
371 if (child.ExitCode != 0) throw new IOException("file_helper_failed");
372 await GUI(() => {
373 SessionGuard.Assert();
374 if (SessionEpoch != capturedSession || capturedSubscriber != null && subscriber != capturedSubscriber) throw new IOException("clipboard_session_changed");
375 Approve(paths); return true;
376 });
377 await Protocol.Write(stream, new() { ["paths"] = JsonSerializer.SerializeToNode(paths) }, token);
378 }
379 catch
380 {
381 if (!child.HasExited) { child.Kill(true); await child.WaitForExitAsync(); }
382 await GUI(() => { if (paths != null) RetireCopies(paths); else copiesLoaded = false; CollectCopies(); return true; });
383 throw;
384 }
385 }
386 internal async Task Export(Stream stream, JsonNode? selection, CancellationToken token)
387 {
388 var paths = Protocol.Paths(selection);
389 var reader = Guid.NewGuid();
390 await GUI(() => { SessionGuard.Assert(); AssertApproved(paths); fileReaders[reader] = paths; return true; });
391 try
392 {
393 using var child = StartHelper("export");
394 using var cancellation = token.Register(() => { try { child.Kill(true); } catch { } });
395 await JsonSerializer.SerializeAsync(child.StandardInput.BaseStream, paths, cancellationToken: token); child.StandardInput.Close();
396 await Protocol.SendFrames(child.StandardOutput.BaseStream, stream, token);
397 await child.WaitForExitAsync(token); SessionGuard.Assert();
398 await Protocol.Write(stream, new() { ["complete"] = child.ExitCode == 0 }, token);
399 }
400 finally { await GUI(() => { fileReaders.Remove(reader); CollectCopies(); return true; }); }
401 }
402}