跳到主要内容

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

浏览文件

browser-clipboard-smoke.mjs

319 行 · 11.0 KB历史下载
1// Uses Playwright's isolated Chromium headless shell and its process-local
2// clipboard. Do not substitute a headed browser or a running user profile.
3import assert from "node:assert/strict";
4import http from "node:http";
5import { createRequire } from "node:module";
6import { randomUUID } from "node:crypto";
7import { BrowserClipboard } from "../internal/cage/browser-clipboard.mjs";
8
9const { chromium } = createRequire(import.meta.url)(
10 process.env.CAGE_PLAYWRIGHT_MODULE || "playwright",
11);
12const site = http.createServer((request, response) => {
13 response.setHeader("Content-Type", "text/html; charset=utf-8");
14 response.end(`<!doctype html><button id="copy">Copy</button><script>
15 const originalWrite = navigator.clipboard.writeText.bind(navigator.clipboard);
16 window.action = () => navigator.clipboard.writeText("中文🙂\\nexact text");
17 document.querySelector("button").onclick = () => {
18 window.finished = false;
19 Promise.resolve().then(() => action()).then(() => { finished = true; }, () => { finished = true; });
20 };
21 </script>`);
22});
23await new Promise((resolve) => site.listen(0, "127.0.0.1", resolve));
24const origin = `http://127.0.0.1:${site.address().port}`;
25const browser = await chromium.launch({ headless: true });
26const context = await browser.newContext({
27 permissions: ["clipboard-read", "clipboard-write"],
28});
29const copies = [];
30const sessions = new Map();
31const pageIds = new WeakMap();
32const observer = new BrowserClipboard(
33 (method, params, id) => sessions.get(id).send(method, params),
34 (copy) => copies.push(copy),
35);
36async function attach(page, id) {
37 pageIds.set(page, id);
38 const session = await context.newCDPSession(page);
39 sessions.set(id, session);
40 for (const method of [
41 "Runtime.executionContextCreated",
42 "Runtime.executionContextDestroyed",
43 "Runtime.executionContextsCleared",
44 "Runtime.bindingCalled",
45 "Page.frameNavigated",
46 "Page.frameDetached",
47 ])
48 session.on(method, (params) =>
49 observer.event({ method, params, sessionId: id }),
50 );
51 await session.send("Page.enable");
52 return observer.attach(id, id);
53}
54async function click(page, expected) {
55 const count = copies.length;
56 await observer.setContext(pageIds.get(page), randomUUID());
57 await page.click("#copy");
58 await page.waitForFunction(() => window.finished);
59 await page.waitForTimeout(50);
60 assert.deepEqual(
61 copies.slice(count).map((copy) => copy.text),
62 expected,
63 );
64}
65try {
66 const page = await context.newPage();
67 await page.goto(origin);
68 assert.deepEqual(await attach(page, "existing"), { skipped: [] });
69 await observer.setContext("existing", randomUUID());
70 await sessions.get("existing").send("Runtime.evaluate", {
71 expression: 'navigator.clipboard.writeText("background write")',
72 awaitPromise: true,
73 userGesture: false,
74 });
75 await page.waitForTimeout(50);
76 assert.deepEqual(copies, []);
77 await click(page, ["中文🙂\nexact text"]);
78 await page.reload();
79 await click(page, ["中文🙂\nexact text"]);
80
81 await page.evaluate(() => {
82 window.action = () =>
83 navigator.clipboard.write([
84 new ClipboardItem({
85 "text/plain": new Blob(["ClipboardItem🙂"], { type: "text/plain" }),
86 }),
87 ]);
88 });
89 await click(page, ["ClipboardItem🙂"]);
90 await page.evaluate(() => {
91 document.addEventListener("copy", (event) => {
92 event.clipboardData.setData("text/plain", "first value");
93 event.clipboardData.clearData("text/plain");
94 event.clipboardData.setData("text", "execCommand 精确文本");
95 event.preventDefault();
96 });
97 window.action = () => document.execCommand("copy");
98 });
99 await click(page, ["execCommand 精确文本"]);
100
101 for (const mode of ["textarea", "input", "shadow", "password", "collapsed"]) {
102 await page.reload();
103 const previousClipboard = await page.evaluate(() =>
104 navigator.clipboard.readText(),
105 );
106 await page.evaluate((mode) => {
107 window.action = () => {
108 const field = document.createElement(
109 mode === "input" || mode === "password" ? "input" : "textarea",
110 );
111 if (mode === "password") field.type = "password";
112 field.value = "默认复制🙂\n保留\u00a0空格";
113 let parent = document.body;
114 if (mode === "shadow") {
115 const host = document.createElement("div");
116 document.body.append(host);
117 parent = host.attachShadow({ mode: "open" });
118 }
119 parent.append(field);
120 field.select();
121 if (mode === "collapsed") field.setSelectionRange(0, 0);
122 document.execCommand("copy");
123 field.remove();
124 };
125 }, mode);
126 const expected =
127 mode === "input"
128 ? "默认复制🙂保留\u00a0空格"
129 : "默认复制🙂\n保留\u00a0空格";
130 const exported = mode !== "password" && mode !== "collapsed";
131 await click(page, exported ? [expected] : []);
132 assert.equal(
133 await page.evaluate(() => navigator.clipboard.readText()),
134 exported ? expected : previousClipboard,
135 mode,
136 );
137 }
138
139 await page.reload();
140 await page.evaluate(() => {
141 window.action = () => {
142 const field = document.createElement("textarea");
143 field.value = "original selection";
144 const content = document.createElement("div");
145 content.innerHTML = 'a<img alt="image alternative">b';
146 document.body.append(field, content);
147 field.select();
148 document.addEventListener(
149 "copy",
150 () => getSelection().selectAllChildren(content),
151 { once: true },
152 );
153 document.execCommand("copy");
154 field.remove();
155 };
156 });
157 await click(page, []);
158 assert.equal(
159 await page.evaluate(() => navigator.clipboard.readText()),
160 "aimage alternativeb",
161 );
162
163 await page.reload();
164 await page.evaluate(() => {
165 window.action = () => {};
166 });
167 await click(page, []);
168 await page.evaluate(() => {
169 window.action = () =>
170 document.dispatchEvent(
171 new ClipboardEvent("copy", {
172 clipboardData: new DataTransfer(),
173 cancelable: true,
174 }),
175 );
176 });
177 await click(page, []);
178 await page.evaluate(() => {
179 window.action = () =>
180 navigator.clipboard.write([
181 new ClipboardItem({
182 "text/plain": new Blob(["must not escape"], { type: "text/plain" }),
183 "application/x-cage-invalid": new Blob(["unsupported"], {
184 type: "application/x-cage-invalid",
185 }),
186 }),
187 ]);
188 });
189 await click(page, []);
190
191 // The observer must keep captured primitives when a site later patches them.
192 await page.reload();
193 await page.evaluate(() => {
194 window.action = () =>
195 navigator.clipboard.writeText("captured native success");
196 Function.prototype.call = () => {
197 throw new Error("site patched call");
198 };
199 Document.prototype.hasFocus = () => false;
200 JSON.stringify = () => '{"text":"forged"}';
201 Object.prototype.toJSON = () => ({ text: "forged" });
202 });
203 await click(page, ["captured native success"]);
204
205 await page.reload();
206 const beforeBlur = copies.length;
207 await page.evaluate(() => {
208 window.action = () =>
209 navigator.clipboard.write([
210 new ClipboardItem({
211 "text/plain": new Promise((resolve) => {
212 window.finishBlob = resolve;
213 }),
214 }),
215 ]);
216 });
217 await observer.setContext("existing", randomUUID());
218 await page.click("#copy");
219 await page.waitForFunction(() => typeof window.finishBlob === "function");
220 // Dispatching blur cancels authorization just as the native focus event does.
221 // The workbench smoke separately exercises host focus and tab cancellation.
222 await page.evaluate(() => {
223 window.dispatchEvent(new Event("blur"));
224 finishBlob(new Blob(["late clipboard"], { type: "text/plain" }));
225 });
226 await page.waitForFunction(() => window.finished);
227 await page.waitForTimeout(50);
228 assert.equal(copies.length, beforeBlur);
229
230 await page.reload();
231 await page.evaluate(() => {
232 window.action = () =>
233 navigator.clipboard.write([
234 new ClipboardItem({
235 "text/plain": new Promise((resolve) => {
236 window.finishBlob = resolve;
237 }),
238 }),
239 ]);
240 });
241 const contextA = randomUUID(),
242 contextB = randomUUID();
243 await observer.setContext("existing", contextA);
244 const beforeContextChange = copies.length;
245 await page.click("#copy");
246 await page.waitForFunction(() => typeof window.finishBlob === "function");
247 await observer.setContext("existing", contextB);
248 await page.evaluate(() =>
249 finishBlob(new Blob(["copy began in A"], { type: "text/plain" })),
250 );
251 await page.waitForFunction(() => window.finished);
252 await page.waitForTimeout(50);
253 assert.deepEqual(copies.slice(beforeContextChange), [
254 { id: "existing", text: "copy began in A", context: contextA },
255 ]);
256
257 const modified = await context.newPage();
258 await modified.goto(origin);
259 await modified.evaluate(() => {
260 Clipboard.prototype.writeText = () => Promise.resolve();
261 });
262 const result = await attach(modified, "modified");
263 assert.match(result.skipped[0]?.reason, /writeText/);
264 await click(modified, []);
265 await modified.reload();
266 await click(modified, ["中文🙂\nexact text"]);
267
268 const poisoned = await context.newPage();
269 await poisoned.goto(origin);
270 await poisoned.evaluate(() => {
271 const originalDefine = Object.defineProperty;
272 const originalWrite = Clipboard.prototype.writeText;
273 Clipboard.prototype.writeText = () => Promise.resolve();
274 window.leakedReferenceTable = false;
275 Object.defineProperty = (object, key, descriptor) => {
276 if (object && Object.hasOwn(object, "apply")) {
277 window.leakedReferenceTable = true;
278 object.defineProperty = originalDefine;
279 object.writeText = originalWrite;
280 return object;
281 }
282 return originalDefine(object, key, descriptor);
283 };
284 });
285 const poisonedResult = await attach(poisoned, "poisoned");
286 assert.match(poisonedResult.skipped[0]?.reason, /defineProperty/);
287 assert.equal(
288 await poisoned.evaluate(() => window.leakedReferenceTable),
289 false,
290 );
291 await click(poisoned, []);
292 await poisoned.close();
293
294 await modified.evaluate(() => {
295 const frame = document.createElement("iframe");
296 frame.src = "/frame";
297 document.body.append(frame);
298 });
299 const frameCount = copies.length;
300 const frameContext = randomUUID();
301 await modified.frameLocator("iframe").locator("#copy").waitFor();
302 await observer.setContext("modified", frameContext);
303 await modified.frameLocator("iframe").locator("#copy").click();
304 await modified.waitForTimeout(100);
305 assert.deepEqual(copies.slice(frameCount), [
306 { id: "modified", text: "中文🙂\nexact text", context: frameContext },
307 ]);
308
309 await modified.evaluate(() => {
310 window.action = () => navigator.clipboard.writeText("x".repeat(65537));
311 });
312 await click(modified, []);
313 console.log(
314 "PASS: existing and new documents, exact writeText/write/execCommand content, rejected and late writes, synthetic events, captured native functions, modified existing APIs, same-process frames and size bound",
315 );
316} finally {
317 await browser.close();
318 await new Promise((resolve) => site.close(resolve));
319}