| 1 | import assert from "node:assert/strict"; |
| 2 | import { test } from "node:test"; |
| 3 | import http from "node:http"; |
| 4 | import net from "node:net"; |
| 5 | import { once } from "node:events"; |
| 6 | import { createInterface } from "node:readline"; |
| 7 | import { createHash } from "node:crypto"; |
| 8 | import { mkdtemp, readFile, rm } from "node:fs/promises"; |
| 9 | import { tmpdir } from "node:os"; |
| 10 | import path from "node:path"; |
| 11 | import { pathToFileURL } from "node:url"; |
| 12 | import { applyWindowsEditorHTMLDefault, checkedBrowserURL, checkedLoopbackProxy, createWindowsBrowserService, validWindowsBrowserFileName } from "../windows-browser.mjs"; |
| 13 | import { fixtureZip } from "./windows-browser-fixtures.mjs"; |
| 14 | import { serveMacOSBrowser } from "../macos-browser-service.mjs"; |
| 15 | const moduleURL = file => process.env.CAGE_BROWSER_TEST_MODULE_DIRECTORY ? pathToFileURL(path.join(process.env.CAGE_BROWSER_TEST_MODULE_DIRECTORY, file)) : new URL("../../../internal/cage/" + file, import.meta.url); |
| 16 | const { BrowserClipboard } = await import(moduleURL("browser-clipboard.mjs")); |
| 17 | const { UploadManager } = await import(moduleURL("browser-uploads.mjs")); |
| 18 | const { DownloadManager } = await import(moduleURL("browser-downloads.mjs")); |
| 19 | const { browserCookies } = await import(moduleURL("browser-cookies.mjs")); |
| 20 | const { BrowserExtensions } = await import(moduleURL("browser-extensions.mjs")); |
| 21 | const { BrowserVault } = await import(moduleURL("browser-vault.mjs")); |
| 22 | |
| 23 | test("Windows controller accepts only loopback proxy and HTTP pages without credentials", () => { |
| 24 | assert.equal(checkedLoopbackProxy("http://127.0.0.1:18501"), "http://127.0.0.1:18501"); |
| 25 | for (const value of ["http://localhost:18501", "https://127.0.0.1:18501", "http://user:[email protected]:18501", "http://127.0.0.1:18501/control", "http://192.168.1.1:18501", "http://127.0.0.1/"]) |
| 26 | assert.throws(() => checkedLoopbackProxy(value), { code: "network_unavailable" }); |
| 27 | for (const value of ["file:///C:/private", "javascript:alert(1)", "http://user:[email protected]/", "chrome://settings/"]) |
| 28 | assert.throws(() => checkedBrowserURL(value), { code: "invalid_url" }); |
| 29 | for (const name of ["../secret", "a\\b", "C:secret", "CON.txt", "lpt1", "a.", "a ", "a\0b"]) |
| 30 | assert.equal(validWindowsBrowserFileName(name), false); |
| 31 | assert.equal(validWindowsBrowserFileName("参考🙂.txt"), true); |
| 32 | }); |
| 33 | test("Cage editor changes only its fixed low-priority trust default in the official metadata", () => { |
| 34 | const data = { configurationDefaults: { "editor.fontSize": 19 }, remoteAuthority: "fixture.localhost", other: "keep & < > ' \" 中文" }; |
| 35 | const encoded = JSON.stringify(data).replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">"); |
| 36 | const html = `<meta id="vscode-workbench-web-configuration" data-settings="${encoded}"><meta id="vscode-workbench-auth-session" data-settings="untouched">`; |
| 37 | const result = applyWindowsEditorHTMLDefault(html, false); |
| 38 | const metadata = result.match(/id="vscode-workbench-web-configuration" data-settings="([^"]*)"/)[1].replace(/"/g, '"').replace(/'/g, "'").replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&"); |
| 39 | assert.deepEqual(JSON.parse(metadata), { ...data, configurationDefaults: { ...data.configurationDefaults, "security.workspace.trust.enabled": false } }); |
| 40 | assert(result.endsWith('<meta id="vscode-workbench-auth-session" data-settings="untouched">')); |
| 41 | assert.equal(applyWindowsEditorHTMLDefault(html, undefined), html); |
| 42 | assert.throws(() => applyWindowsEditorHTMLDefault("missing official metadata", false), { code: "editor_unavailable" }); |
| 43 | }); |
| 44 | |
| 45 | const playwrightPath = process.env.CAGE_BROWSER_TEST_PLAYWRIGHT; |
| 46 | const executablePath = process.env.CAGE_BROWSER_TEST_CHROMIUM; |
| 47 | const integration = playwrightPath && executablePath ? test : test.skip; |
| 48 | async function fixture(t, configured = {}) { |
| 49 | const root = await mkdtemp(path.join(tmpdir(), "cage-windows-browser-")); |
| 50 | const payload = Buffer.alloc((128 << 10) + 37); |
| 51 | for (let i = 0; i < payload.length; i++) payload[i] = i % 251; |
| 52 | const diagnosticCookies = []; |
| 53 | const server = http.createServer((req, res) => { |
| 54 | if (req.url === "http://198.18.0.254/egress") { diagnosticCookies.push(req.headers.cookie || ""); res.writeHead(503, { "Content-Type": "application/json" }); res.end(JSON.stringify({ ip: "198.51.100.44" })); return; } |
| 55 | if (req.url === "/download") { res.setHeader("Content-Disposition", 'attachment; filename="reference.bin"'); res.end(payload); return; } |
| 56 | res.setHeader("Content-Type", "text/html; charset=utf-8"); |
| 57 | const editorMetadata = req.url.startsWith("/?editor=") ? `<meta id="vscode-workbench-web-configuration" data-settings="${JSON.stringify({ remoteAuthority: req.headers.host, configurationDefaults: { "editor.fontSize": 19 } }).replace(/"/g, """)}">` : ""; |
| 58 | if (req.url.startsWith("/editor-")) res.setHeader("Set-Cookie", "editor_fixture=" + req.url.slice(8) + "; Path=/; SameSite=Lax"); |
| 59 | res.end(`<!doctype html><title>${req.url}</title>${editorMetadata}<style>body{margin:20px}textarea,input,button{display:block;margin:10px;width:300px;height:45px}#drop{height:100px;width:400px;border:1px solid}</style> |
| 60 | <textarea id="first"></textarea><textarea id="second"></textarea><input id="file" type="file" multiple> |
| 61 | <button id="copy">Copy actual clipboard</button><a id="download" href="/download">Download</a><div id="drop" tabindex="0">Drop files</div> |
| 62 | <script>copy.onclick=()=>navigator.clipboard.writeText('实际复制🙂'); |
| 63 | window.selectionEvents=[]; document.addEventListener('selectionchange',()=>selectionEvents.push(String(getSelection()))); |
| 64 | window.dropped=[]; drop.ondragover=e=>e.preventDefault(); drop.ondrop=async e=>{e.preventDefault();window.dropped=await Promise.all([...e.dataTransfer.files].map(async f=>({name:f.name,bytes:[...new Uint8Array(await f.arrayBuffer())]})))};</script>`); |
| 65 | }); |
| 66 | await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); |
| 67 | const url = `http://127.0.0.1:${server.address().port}`; |
| 68 | const chromium = (await import(pathToFileURL(playwrightPath))).chromium; |
| 69 | let browserContext, launchOptions; |
| 70 | const options = { |
| 71 | platform: process.env.CAGE_BROWSER_TEST_PLATFORM, |
| 72 | testing: true, headless: process.env.CAGE_BROWSER_TEST_HEADED !== "1", directory: path.join(root, "controller"), downloadDirectory: path.join(root, "saved"), executablePath, |
| 73 | chromium: { launchPersistentContext: async (directory, options) => { launchOptions = options; return browserContext = await chromium.launchPersistentContext(directory, options); } }, |
| 74 | modules: { BrowserClipboard, UploadManager, DownloadManager, browserCookies, BrowserVault, ...(process.env.CAGE_BROWSER_TEST_EXTENSIONS === "1" ? { BrowserExtensions } : {}) }, displayScale: 2, |
| 75 | splitDirectory: process.env.CAGE_BROWSER_TEST_SPLIT_DIRECTORY, |
| 76 | editor: async workspace => ({ url: `http://${workspace.slice(0, 16)}.cage-editor.localhost:${server.address().port}/editor-` + workspace }), |
| 77 | }; |
| 78 | let service = createWindowsBrowserService(options); |
| 79 | const settings = { proxy: configured.diagnostic ? url : "http://127.0.0.1:18501", ...configured }; |
| 80 | await service.request({ operation: "configure", input: settings }); |
| 81 | t.after(async () => { await service.close(); await new Promise(resolve => server.close(resolve)); await rm(root, { recursive: true, force: true }); }); |
| 82 | const call = (route, input = {}, method = "POST") => service.request({ method, path: "/" + route, input }); |
| 83 | async function open(route = "/one", privateTab = false) { |
| 84 | const { id } = await call("new", { url: url + route, incognito: privateTab }); |
| 85 | const page = browserContext.browser().contexts().flatMap(context => context.pages()).find(p => p.url() === url + route); |
| 86 | if (page) await page.waitForLoadState("domcontentloaded"); |
| 87 | return { id, page }; |
| 88 | } |
| 89 | async function click(id, page, selector) { |
| 90 | const box = await page.locator(selector).boundingBox(); |
| 91 | const size = page.viewportSize(); |
| 92 | await call("click", { id, x: (box.x + box.width / 2) / size.width, y: (box.y + box.height / 2) / size.height }); |
| 93 | } |
| 94 | return { root, payload, url, call, open, click, diagnosticCookies, launchOptions: () => launchOptions, privateRequest: (request, options) => service.request(request, options), releaseInput: signal => service.releaseInput(signal), context: () => browserContext, stop: () => service.close(), restart: async () => { |
| 95 | await service.close(); service = createWindowsBrowserService(options); |
| 96 | await service.request({ operation: "configure", input: settings }); |
| 97 | return call("tabs", {}, "GET"); |
| 98 | } }; |
| 99 | } |
| 100 | |
| 101 | integration("interactive browser identity is native in normal and private documents", async t => { |
| 102 | const f = await fixture(t); |
| 103 | for (const incognito of [false, true]) { |
| 104 | const { page } = await f.open("/identity", incognito); |
| 105 | assert.deepEqual(await page.evaluate(() => ({ |
| 106 | automated: navigator.webdriver, |
| 107 | getter: Object.getOwnPropertyDescriptor(Navigator.prototype, "webdriver").get.toString(), |
| 108 | })), { automated: false, getter: "function get webdriver() { [native code] }" }); |
| 109 | } |
| 110 | assert.ok(f.launchOptions().ignoreDefaultArgs.includes("--enable-automation")); |
| 111 | assert.equal(f.launchOptions().chromiumSandbox, true); |
| 112 | }); |
| 113 | |
| 114 | integration("closed browser tabs release their controller sessions", async t => { |
| 115 | const f = await fixture(t); |
| 116 | const original = (await f.call("health", {}, "GET")).resources; |
| 117 | for (let index = 0; index < 12; index++) { |
| 118 | const { id, page } = await f.open("/lifecycle-" + index); |
| 119 | await f.call("close", { id }); |
| 120 | assert.equal(page.isClosed(), true); |
| 121 | assert.deepEqual((await f.call("health", {}, "GET")).resources, original, "closed tabs must release their sessions"); |
| 122 | } |
| 123 | }); |
| 124 | |
| 125 | integration("removed browser frames release clipboard and controller sessions", async t => { |
| 126 | const f = await fixture(t); |
| 127 | const { id, page } = await f.open("/frame-lifecycle"); |
| 128 | const original = (await f.call("health", {}, "GET")).resources; |
| 129 | for (let index = 0; index < 5; index++) { |
| 130 | await page.evaluate(async url => { |
| 131 | const frame = document.createElement("iframe"); |
| 132 | frame.src = url; |
| 133 | const loaded = new Promise(resolve => { frame.onload = resolve; }); |
| 134 | document.body.append(frame); |
| 135 | await loaded; |
| 136 | }, f.url.replace("127.0.0.1", "localhost") + "/child-" + index); |
| 137 | await page.waitForTimeout(100); |
| 138 | const attached = (await f.call("health", {}, "GET")).resources; |
| 139 | assert.ok(attached.sessions > original.sessions); |
| 140 | await page.evaluate(() => document.querySelector("iframe").remove()); |
| 141 | await page.waitForTimeout(100); |
| 142 | assert.deepEqual((await f.call("health", {}, "GET")).resources, original, "detached frames must release clipboard state"); |
| 143 | await f.call("copy-context", { id, context: "a".repeat(32) }); |
| 144 | } |
| 145 | }); |
| 146 | |
| 147 | integration("actual Chromium tabs restore and project switching retains unsaved editor buffers", async t => { |
| 148 | const f = await fixture(t); |
| 149 | const one = await f.open("/one"), two = await f.open("/two"); |
| 150 | await f.call("activate", { id: one.id }); |
| 151 | await f.click(one.id, one.page, "#first"); |
| 152 | await f.call("insert-text", { id: one.id, text: "网页未保存内容" }); |
| 153 | await f.call("activate", { id: two.id }); |
| 154 | await f.call("activate", { id: one.id }); |
| 155 | assert.equal(await one.page.locator("#first").inputValue(), "网页未保存内容"); |
| 156 | await one.page.evaluate(() => { document.cookie = "cage_fixture=opaque-value; SameSite=Lax"; }); |
| 157 | const cookies = await f.call("cookies", { id: one.id, mode: "list", scope: "site" }); |
| 158 | const cookie = cookies.cookies.find(c => c.name === "cage_fixture"); assert(cookie); assert.equal(cookie.value, undefined); |
| 159 | const detail = await f.call("cookies", { id: one.id, mode: "details", scope: "site", cookieKey: cookie.key }); assert.equal(detail.value, "opaque-value"); |
| 160 | const projectA = "a".repeat(24), projectB = "b".repeat(24); |
| 161 | const editorA = await f.call("editor", { workspace: projectA }); |
| 162 | const pageA = f.context().pages().find(p => p.url().endsWith(projectA)); await pageA.waitForLoadState(); |
| 163 | await f.click(editorA.id, pageA, "#first"); await f.call("insert-text", { id: editorA.id, text: "未保存编辑器缓冲区" }); |
| 164 | const editorB = await f.call("editor", { workspace: projectB }); |
| 165 | const returned = await f.call("editor", { workspace: projectA }); |
| 166 | assert.equal(returned.id, editorA.id); assert.notEqual(editorB.id, editorA.id); |
| 167 | assert.equal(await pageA.locator("#first").inputValue(), "未保存编辑器缓冲区"); |
| 168 | const cookieA = await f.context().cookies(pageA.url()); |
| 169 | assert.equal(cookieA.find(c => c.name === "editor_fixture").value, projectA); |
| 170 | const privateTab = await f.open("/private", true); |
| 171 | const restored = await f.restart(); |
| 172 | assert(restored.tabs.some(t => t.id === one.id && t.url.endsWith("/one"))); |
| 173 | assert(restored.tabs.some(t => t.id === two.id && t.url.endsWith("/two"))); |
| 174 | assert(!restored.tabs.some(t => t.id === privateTab.id || t.incognito || t.url.endsWith("/private"))); |
| 175 | // Full Chrome can restore editor pages from its own profile. The controller |
| 176 | // keeps those buffers visible with their project access blocked on restart. |
| 177 | for (const editor of restored.tabs.filter(t => t.kind === "editor")) { |
| 178 | assert.equal(editor.blocked, true); |
| 179 | await assert.rejects(f.call("insert-text", { id: editor.id, text: "迟到输入" }), { code: "project_grant_unavailable" }); |
| 180 | } |
| 181 | }); |
| 182 | (process.env.CAGE_BROWSER_TEST_PLATFORM === "darwin" ? test.skip : integration)("Windows private editor connection applies only the issued alias's HTML defaults through loopback", async t => { |
| 183 | const f = await fixture(t), project = "d".repeat(16), connection = "e".repeat(32); |
| 184 | const url = new URL(f.url); url.hostname = project + ".cage-editor.localhost"; url.search = "?editor=" + project; |
| 185 | const input = { workspace: project, connection, url: url.href, folder: f.root, trust_default: false }; |
| 186 | await f.call("new", { url: f.url + "/one" }); |
| 187 | const serviceConnection = { operation: "editor-connect", input }; |
| 188 | // The fixture exposes the same private service seam used only by C#. |
| 189 | await f.privateRequest(serviceConnection); |
| 190 | const opened = await f.call("editor", { workspace: project }); |
| 191 | const page = f.context().pages().find(page => page.url() === url.href); await page.waitForLoadState(); |
| 192 | const metadata = await page.locator('#vscode-workbench-web-configuration').getAttribute('data-settings'); |
| 193 | assert.deepEqual(JSON.parse(metadata), { remoteAuthority: url.host, configurationDefaults: { "editor.fontSize": 19, "security.workspace.trust.enabled": false } }); |
| 194 | await assert.rejects(f.privateRequest({ operation: "editor-connect", input: { ...input, trust_default: { arbitrary: false } } }), /默认策略/); |
| 195 | await f.privateRequest({ operation: "editor-revoke", input: { workspace: project, connection } }); |
| 196 | await assert.rejects(f.call("frame", {}, "GET"), /授权/); |
| 197 | assert(opened.id); |
| 198 | }); |
| 199 | |
| 200 | const actualFocus = playwrightPath && executablePath && process.env.CAGE_BROWSER_TEST_HEADED === "1" ? test : test.skip; |
| 201 | actualFocus("a native page activation updates the private document proof and the next frame", async t => { |
| 202 | const f = await fixture(t), one = await f.open("/one"), two = await f.open("/two"); |
| 203 | await f.call("activate", { id: one.id }); |
| 204 | const before = await f.call("frame", {}, "GET"); assert.equal(before.id, one.id); |
| 205 | // Direct browser activation bypasses Cage's action route, as native Ctrl+Tab |
| 206 | // does. The proof must select the actual known document, not the old UI id. |
| 207 | await two.page.bringToFront(); |
| 208 | const frame = await f.call("frame", {}, "GET"); |
| 209 | assert.equal(frame.id, two.id); assert.equal(frame.native.id, two.id); |
| 210 | assert.equal(frame.native.documentFocused, true); |
| 211 | assert.equal((await f.call("tabs", {}, "GET")).active, two.id); |
| 212 | assert.notEqual(frame.target, before.target); |
| 213 | }); |
| 214 | |
| 215 | integration("private window popups are tracked and closing one tab retains its sibling", async t => { |
| 216 | const f = await fixture(t), one = await f.open("/private-one", true); |
| 217 | const created = one.page.context().waitForEvent("page"); |
| 218 | await one.page.evaluate(url => window.open(url, "_blank"), f.url + "/private-two"); |
| 219 | const two = await created; await two.waitForLoadState(); |
| 220 | let snapshot; |
| 221 | for(let i=0;i<30;i++){snapshot=await f.call("tabs",{},"GET");if(snapshot.tabs.some(t=>t.url.endsWith("/private-two")))break;await new Promise(r=>setTimeout(r,20));} |
| 222 | const second=snapshot.tabs.find(t=>t.url.endsWith("/private-two"));assert(second?.incognito); |
| 223 | await f.call("close",{id:one.id}); |
| 224 | assert.equal(two.isClosed(),false);assert.equal((await f.call("tabs",{},"GET")).tabs.some(t=>t.id===second.id),true); |
| 225 | }); |
| 226 | |
| 227 | integration("native page copy completion carries current context and ignores a synthetic copy", async t => { |
| 228 | const f = await fixture(t), one = await f.open(); |
| 229 | await f.context().grantPermissions(["clipboard-read", "clipboard-write"], { origin: f.url }); |
| 230 | const context = "c".repeat(32); |
| 231 | await f.call("copy-context", { id: one.id, context }); |
| 232 | await f.click(one.id, one.page, "#copy"); |
| 233 | await one.page.waitForFunction(() => navigator.clipboard.readText().then(v => v === "实际复制🙂")); |
| 234 | let result; |
| 235 | for (let i = 0; i < 20; i++) { |
| 236 | result = await f.call("events", {}, "GET"); |
| 237 | if (result.events.some(e => e.type === "clipboard")) break; |
| 238 | await new Promise(resolve => setTimeout(resolve, 25)); |
| 239 | } |
| 240 | assert(result.events.some(e => e.type === "clipboard" && e.value.text === "实际复制🙂" && e.value.context === context)); |
| 241 | const after = result.sequence; |
| 242 | await one.page.evaluate(() => { const data = new DataTransfer(); data.setData("text/plain", "forged"); document.dispatchEvent(new ClipboardEvent("copy", { clipboardData: data })); }); |
| 243 | assert.equal((await f.call("events", { after }, "GET")).events.filter(e => e.type === "clipboard").length, 0); |
| 244 | }); |
| 245 | |
| 246 | integration("64 KiB file blocks reach native chooser/drop, reject switched targets, and download unchanged bytes", async t => { |
| 247 | const f = await fixture(t), one = await f.open(); |
| 248 | await f.click(one.id, one.page, "#file"); |
| 249 | let chooser; |
| 250 | for (let i = 0; i < 20; i++) { |
| 251 | chooser = (await f.call("tabs", {}, "GET")).uploads[0]; |
| 252 | if (chooser) break; |
| 253 | await new Promise(resolve => setTimeout(resolve, 25)); |
| 254 | } |
| 255 | assert.equal(chooser.kind, "chooser"); |
| 256 | async function transfer(id, bytes, name = "参考🙂.bin") { |
| 257 | const opened = await f.call("file-open", { direction: "upload", id, name, length: bytes.length }); |
| 258 | let sequence = 0; |
| 259 | for (let offset = 0; offset < bytes.length; offset += 64 << 10) { |
| 260 | const ack = await f.call("file-chunk", { transfer: opened.transfer, sequence, data: bytes.subarray(offset, offset + (64 << 10)).toString("base64") }); |
| 261 | assert.equal(ack.ack, ++sequence); |
| 262 | } |
| 263 | await f.call("file-finish", { transfer: opened.transfer, sequence }); |
| 264 | } |
| 265 | await transfer(chooser.id, f.payload); |
| 266 | await f.call("upload-finish", { id: chooser.id }); |
| 267 | const selected = await one.page.locator("#file").evaluate(async e => ({ name: e.files[0].name, bytes: [...new Uint8Array(await e.files[0].arrayBuffer())] })); |
| 268 | assert.equal(selected.name, "参考🙂.bin"); assert.deepEqual(Buffer.from(selected.bytes), f.payload); |
| 269 | const box = await one.page.locator("#drop").boundingBox(), size = one.page.viewportSize(); |
| 270 | const drop = await f.call("upload-start", { id: one.id, kind: "drop", x: (box.x + 20) / size.width, y: (box.y + 20) / size.height }); |
| 271 | await transfer(drop.id, Buffer.from("dropped"), "drop.txt"); await f.call("upload-finish", { id: drop.id }); |
| 272 | await one.page.waitForFunction(() => window.dropped.length === 1); |
| 273 | assert.equal(await one.page.evaluate(() => window.dropped[0].name), "drop.txt"); |
| 274 | const stale = await f.call("upload-start", { id: one.id, kind: "paste" }); |
| 275 | const opened = await f.call("file-open", { direction: "upload", id: stale.id, name: "late.txt", length: 4 }); |
| 276 | await f.open("/other"); |
| 277 | await assert.rejects(f.call("file-chunk", { transfer: opened.transfer, sequence: 0, data: Buffer.from("late").toString("base64") }), /切换/); |
| 278 | await f.call("activate", { id: one.id }); await f.click(one.id, one.page, "#download"); |
| 279 | let record; |
| 280 | for (let i = 0; i < 100; i++) { |
| 281 | record = (await f.call("tabs", {}, "GET")).downloads[0]; |
| 282 | if (record?.state === "saved") break; |
| 283 | await new Promise(resolve => setTimeout(resolve, 25)); |
| 284 | } |
| 285 | assert.equal(record.state, "saved"); |
| 286 | const read = await f.call("file-open", { direction: "download", id: record.id }); |
| 287 | assert.equal(read.size, f.payload.length); |
| 288 | const chunks = []; let sequence = 0; |
| 289 | while (true) { |
| 290 | const chunk = await f.call("file-read", { transfer: read.transfer, sequence }); |
| 291 | assert.equal(chunk.sequence, ++sequence); chunks.push(Buffer.from(chunk.data, "base64")); if (chunk.eof) break; |
| 292 | } |
| 293 | assert.deepEqual(Buffer.concat(chunks), f.payload); |
| 294 | assert.deepEqual(await readFile(path.join(f.root, "saved", "reference.bin")), f.payload); |
| 295 | }); |
| 296 | |
| 297 | integration("page pointer release preserves drag position and does not reach a navigated document", async t => { |
| 298 | const f = await fixture(t), one = await f.open(); |
| 299 | await f.call("resize", { width: 2384, height: 1676 }); |
| 300 | await one.page.evaluate(() => { |
| 301 | window.pointerEvents = []; |
| 302 | for (const name of ["pointerdown", "pointermove", "pointerup"]) |
| 303 | addEventListener(name, event => window.pointerEvents.push({ name, x: event.clientX, y: event.clientY, buttons: event.buttons })); |
| 304 | }); |
| 305 | let frame = await f.call("frame", {}, "GET"); |
| 306 | await f.call("input", { target: frame.target, kind: "pointer", x: 1400, y: 1000, mask: 1 }); |
| 307 | await f.call("input", { target: frame.target, kind: "pointer", x: 2300, y: 1580, mask: 1 }); |
| 308 | await f.privateRequest({ operation: "input-release-pointer" }); |
| 309 | const events = await one.page.evaluate(() => window.pointerEvents); |
| 310 | assert(events.some(event => event.name === "pointermove" && event.x === 1150 && event.y === 790 && event.buttons === 1)); |
| 311 | assert.deepEqual(events.at(-1), { name: "pointerup", x: 1150, y: 790, buttons: 0 }); |
| 312 | await f.privateRequest({ operation: "input-release-pointer" }); |
| 313 | assert.equal(await one.page.evaluate(() => window.pointerEvents.length), events.length); |
| 314 | |
| 315 | await f.call("input", { target: frame.target, kind: "pointer", x: 1400, y: 1000, mask: 1 }); |
| 316 | await f.call("navigate", { id: one.id, url: f.url + "/next" }); |
| 317 | await one.page.waitForLoadState("domcontentloaded"); |
| 318 | await one.page.evaluate(() => { window.releases = 0; addEventListener("pointerup", () => window.releases++); }); |
| 319 | await f.privateRequest({ operation: "input-release-pointer" }); |
| 320 | assert.equal(await one.page.evaluate(() => window.releases), 0); |
| 321 | frame = await f.call("frame", {}, "GET"); |
| 322 | await f.call("input", { target: frame.target, kind: "pointer", x: 1400, y: 1000, mask: 1 }); |
| 323 | await f.privateRequest({ operation: "input-release-pointer" }); |
| 324 | assert.equal(await one.page.evaluate(() => window.releases), 1); |
| 325 | }); |
| 326 | |
| 327 | integration("physical frame geometry, RFB key/pointer and composition reject late page/field input", async t => { |
| 328 | const f = await fixture(t), one = await f.open(); |
| 329 | await f.call("resize", { width: 1400, height: 1000 }); |
| 330 | const frame = await f.call("frame", {}, "GET"); |
| 331 | assert.equal(frame.width, 1400); assert.equal(frame.height, 1000); assert.equal(frame.cssWidth, 700); assert.equal(frame.scale, 2); |
| 332 | assert(Buffer.from(frame.jpeg, "base64").subarray(0, 2).equals(Buffer.from([255, 216]))); |
| 333 | const box = await one.page.locator("#first").boundingBox(); |
| 334 | const input = { target: frame.target, kind: "pointer", x: (box.x + 10) * 2, y: (box.y + 10) * 2 }; |
| 335 | await f.call("input", { ...input, mask: 1 }); await f.call("input", { ...input, mask: 0 }); |
| 336 | for (const keysym of [97, 98]) { await f.call("input", { target: frame.target, kind: "key", keysym, down: true }); await f.call("input", { target: frame.target, kind: "key", keysym, down: false }); } |
| 337 | assert.equal(await one.page.locator("#first").inputValue(), "ab"); |
| 338 | const status = await f.call("ime", { id: one.id, target: "browser", mode: "status" }); assert(status.available); assert(status.rect[3] > 0); |
| 339 | const session = "d".repeat(32), common = { id: one.id, target: "browser", session }; |
| 340 | await f.call("ime", { ...common, mode: "begin", sequence: 0, context: status.context }); |
| 341 | await f.call("ime", { ...common, mode: "update", sequence: 1, text: "nihao", selectionStart: 5, selectionEnd: 5 }); |
| 342 | await f.call("ime", { ...common, mode: "commit", sequence: 2, text: "你好🙂" }); |
| 343 | assert.equal(await one.page.locator("#first").inputValue(), "ab你好🙂"); |
| 344 | const next = await f.call("ime", { id: one.id, target: "browser", mode: "status" }); |
| 345 | await f.call("ime", { ...common, mode: "begin", sequence: 3, context: next.context }); |
| 346 | await f.click(one.id, one.page, "#second"); |
| 347 | await assert.rejects(f.call("ime", { ...common, mode: "commit", sequence: 4, text: "迟到" }), /target changed/); |
| 348 | assert.equal(await one.page.locator("#second").inputValue(), ""); |
| 349 | await f.call("resize", { width: 1200, height: 900 }); |
| 350 | await assert.rejects(f.call("input", { ...input, mask: 1 }), /target changed/); |
| 351 | const later = await f.open("/after-resize"); |
| 352 | const resized = await f.call("frame", {}, "GET"); |
| 353 | const pixels = await later.page.evaluate(async jpeg => { |
| 354 | const image = new Image(); image.src = "data:image/jpeg;base64," + jpeg; await image.decode(); |
| 355 | return [image.naturalWidth, image.naturalHeight, innerWidth, innerHeight]; |
| 356 | }, resized.jpeg); |
| 357 | assert.deepEqual(pixels, [resized.width, resized.height, 600, 450]); |
| 358 | assert.deepEqual([resized.width, resized.height], [1200, 900]); |
| 359 | }); |
| 360 | |
| 361 | integration("split panes resize actual pages and route physical input to the clicked pane", async t => { |
| 362 | const f = await fixture(t), left = await f.open("/left"), right = await f.open("/right"); |
| 363 | await f.call("resize", { width: 1400, height: 1000 }); |
| 364 | await f.call("split", { left: left.id, right: right.id, id: left.id, fraction: 0.5 }); |
| 365 | assert.equal(left.page.viewportSize().width, 350); assert.equal(right.page.viewportSize().width, 350); |
| 366 | const frame = await f.call("frame", {}, "GET"); |
| 367 | assert.equal(frame.width, 1400); assert.equal(frame.panes.length, 2); assert.equal(frame.panes[1].x, 700); |
| 368 | assert.equal(frame.panes[0].width, 700); assert.equal(frame.panes[1].width, 700); |
| 369 | const box = await right.page.locator("#first").boundingBox(); |
| 370 | const input = { target: frame.target, kind: "pointer", x: 700 + (box.x + 10) * 2, y: (box.y + 10) * 2 }; |
| 371 | await f.call("input", { ...input, mask: 1 }); await f.call("input", { ...input, mask: 0 }); |
| 372 | assert.equal((await f.call("tabs", {}, "GET")).active, right.id); |
| 373 | await f.call("input", { target: frame.target, kind: "key", keysym: 97, down: true }); await f.call("input", { target: frame.target, kind: "key", keysym: 97, down: false }); |
| 374 | assert.equal(await right.page.locator("#first").inputValue(), "a"); assert.equal(await left.page.locator("#first").inputValue(), ""); |
| 375 | await f.call("navigate", { id: left.id, url: f.url + "/replacement" }); |
| 376 | await assert.rejects(f.call("input", { ...input, mask: 1 }), /target changed/); |
| 377 | await f.call("split", { id: right.id }); assert.equal(right.page.viewportSize().width, 700); |
| 378 | }); |
| 379 | |
| 380 | integration("screencast retains HiDPI pixels, skips static frames and resumes after its viewer leaves", async t => { |
| 381 | const f = await fixture(t), one = await f.open("/still"); |
| 382 | await one.page.evaluate(() => { document.body.style.background = "rgb(245, 240, 230)"; }); |
| 383 | const screenshot = one.page.screenshot.bind(one.page); |
| 384 | one.page.screenshot = async options => { |
| 385 | // A slow Windows capture can take longer than the idle viewer timeout. |
| 386 | one.page.screenshot = screenshot; |
| 387 | await new Promise(resolve => setTimeout(resolve, 1700)); |
| 388 | return screenshot(options); |
| 389 | }; |
| 390 | let frame = await f.call("frame", {}, "GET"); |
| 391 | const dimensions = await one.page.evaluate(async jpeg => { |
| 392 | const image = new Image(); image.src = "data:image/jpeg;base64," + jpeg; await image.decode(); |
| 393 | return [image.naturalWidth, image.naturalHeight, innerWidth, devicePixelRatio]; |
| 394 | }, frame.jpeg); |
| 395 | assert.deepEqual(dimensions, [2280, 1400, 1140, 2]); |
| 396 | const before = (await f.call("health", {}, "GET")).capture; |
| 397 | let unchanged = 0; |
| 398 | for (let i = 0; i < 16; i++) { |
| 399 | const next = await f.call("frame", { after: frame.sequence, nativeProof: i >= 8 }, "GET"); |
| 400 | if (next.unchanged) { |
| 401 | unchanged++; |
| 402 | assert.equal(next.jpeg, undefined); |
| 403 | if (i >= 8) { |
| 404 | assert.equal(next.native.id, one.id); |
| 405 | assert.equal(next.native.target, frame.target); |
| 406 | } else assert.equal(next.native, undefined); |
| 407 | } |
| 408 | else frame = next; |
| 409 | await new Promise(resolve => setTimeout(resolve, 40)); |
| 410 | } |
| 411 | assert(unchanged >= 12, "static page was repeatedly captured"); |
| 412 | if (before) { |
| 413 | const after = (await f.call("health", {}, "GET")).capture; |
| 414 | assert(after.screenshots - before.screenshots <= 4, "static polling repeatedly invoked a HiDPI screenshot"); |
| 415 | } |
| 416 | await one.page.evaluate(() => { document.body.style.background = "rgb(30, 120, 220)"; }); |
| 417 | let updated; |
| 418 | for (let i = 0; i < 20; i++) { |
| 419 | const next = await f.call("frame", { after: frame.sequence }, "GET"); |
| 420 | if (!next.unchanged) { updated = next; break; } |
| 421 | await new Promise(resolve => setTimeout(resolve, 40)); |
| 422 | } |
| 423 | assert(updated?.jpeg && updated.sequence !== frame.sequence); |
| 424 | await new Promise(resolve => setTimeout(resolve, 1700)); |
| 425 | const resumed = await f.call("frame", { after: updated.sequence }, "GET"); |
| 426 | assert(resumed.jpeg && resumed.sequence !== updated.sequence); |
| 427 | }); |
| 428 | |
| 429 | integration("a scrolled browser viewport stays visible while a web font is loading", async t => { |
| 430 | const f = await fixture(t, { displayScale: 1.5 }); |
| 431 | const { page } = await f.open(); |
| 432 | const initial = await f.call("frame", {}, "GET"); |
| 433 | let releaseFont; |
| 434 | const pending = new Promise(resolve => { releaseFont = resolve; }); |
| 435 | await page.route("**/pending-font.woff2", async route => { await pending; await route.abort(); }); |
| 436 | const requested = page.waitForRequest("**/pending-font.woff2"); |
| 437 | await page.evaluate(() => { |
| 438 | document.body.innerHTML = '<main style="height:90vh;overflow:auto"><div style="height:200vh;background:red"></div><div style="height:120vh;background:lime">waiting</div></main>'; |
| 439 | const font = new FontFace("pending", "url(/pending-font.woff2)"); |
| 440 | document.fonts.add(font); |
| 441 | document.body.style.fontFamily = "pending, sans-serif"; |
| 442 | const pane = document.querySelector("main"); |
| 443 | pane.scrollTop = pane.scrollHeight; |
| 444 | }); |
| 445 | await requested; |
| 446 | const timer = setTimeout(releaseFont, 4000); |
| 447 | try { |
| 448 | let after = initial.sequence; |
| 449 | for (;;) { |
| 450 | const frame = await f.call("frame", { after }, "GET"); |
| 451 | assert.equal(await page.evaluate(() => document.fonts.status), "loading", "scrolled frame must arrive before font loading ends"); |
| 452 | if (!frame.unchanged) { |
| 453 | const pixel = await page.evaluate(async ({ jpeg, width, height }) => { |
| 454 | const image = new Image(); image.src = "data:image/jpeg;base64," + jpeg; await image.decode(); |
| 455 | const ctx = document.createElement("canvas").getContext("2d"); |
| 456 | ctx.drawImage(image, width / 2, height / 2, 1, 1, 0, 0, 1, 1); |
| 457 | return { rgb: [...ctx.getImageData(0, 0, 1, 1).data], size: [image.width, image.height] }; |
| 458 | }, frame); |
| 459 | assert.deepEqual(pixel.size, [frame.width, frame.height]); |
| 460 | assert.equal(frame.scale, 1.5); |
| 461 | if (pixel.rgb[1] > 245 && pixel.rgb[0] < 10 && pixel.rgb[2] < 10) break; |
| 462 | after = frame.sequence; |
| 463 | } |
| 464 | await new Promise(resolve => setTimeout(resolve, 30)); |
| 465 | } |
| 466 | } finally { clearTimeout(timer); releaseFont(); } |
| 467 | }); |
| 468 | |
| 469 | integration("pixel wheel preserves distance and still rejects stale targets and invalid bounds", async t => { |
| 470 | const f = await fixture(t), { page } = await f.open(); |
| 471 | await page.evaluate(() => { document.body.style.height = "6000px"; document.documentElement.style.scrollBehavior = "auto"; }); |
| 472 | const frame = await f.call("frame", {}, "GET"); |
| 473 | const wheel = { kind: "pointer", target: frame.target, x: 600, y: 600, mask: 16, deltaX: 0, deltaY: 720 }; |
| 474 | await f.call("input", wheel); |
| 475 | await page.waitForFunction(() => scrollY >= 700); |
| 476 | assert.equal(await page.evaluate(() => scrollY), 720); |
| 477 | await f.call("input", { ...wheel, mask: 8, deltaY: -360 }); |
| 478 | await page.waitForFunction(() => scrollY === 360); |
| 479 | await assert.rejects(f.call("input", { ...wheel, target: "stale" }), /target changed/); |
| 480 | await assert.rejects(f.call("input", { ...wheel, deltaY: 2049 }), /滚动距离/); |
| 481 | await assert.rejects(f.call("input", { ...wheel, mask: 17 }), /滚动距离/); |
| 482 | assert.equal(await page.evaluate(() => scrollY), 360); |
| 483 | }); |
| 484 | |
| 485 | integration("audit reads configured browser state separately from expected values and preserves actual HTTP failures", async t => { |
| 486 | const f = await fixture(t, { timezone: "Pacific/Honolulu", language: "ja-JP", diagnostic: true }), one = await f.open(); |
| 487 | await f.context().addCookies([{ name: "private_fixture", value: "test-only", domain: "198.18.0.254", path: "/" }]); |
| 488 | const before = await f.call("tabs", {}, "GET"); |
| 489 | const result = await f.call("audit", { timezone: "Asia/Tokyo", network: true }); |
| 490 | assert.equal(result.timezone, "Pacific/Honolulu"); assert.equal(result.expected_timezone, "Asia/Tokyo"); assert.equal(result.language, "ja-JP"); |
| 491 | assert.equal(result.network.status, 503); assert.equal(result.network.ip, "198.51.100.44"); assert.deepEqual(f.diagnosticCookies, [""]); |
| 492 | assert.equal((await f.call("tabs", {}, "GET")).active, one.id); assert.equal((await f.call("tabs", {}, "GET")).tabs.length, before.tabs.length); |
| 493 | }); |
| 494 | |
| 495 | integration("native image focus proof stays stable for a field and changes before a different field receives input", async t => { |
| 496 | const f=await fixture(t),one=await f.open(); |
| 497 | await f.click(one.id,one.page,"#first"); |
| 498 | const original=await f.call("focus-proof",{},"GET"); |
| 499 | assert.equal((await f.call("focus-proof",{},"GET")).focus,original.focus); |
| 500 | await f.click(one.id,one.page,"#second"); |
| 501 | assert.notEqual((await f.call("focus-proof",{},"GET")).focus,original.focus); |
| 502 | }); |
| 503 | |
| 504 | const macImages = playwrightPath && executablePath && process.env.CAGE_BROWSER_TEST_PLATFORM === "darwin" ? test : test.skip; |
| 505 | macImages("Mac browser service keeps actual Chrome input when a viewer disconnects", async t => { |
| 506 | const f = await fixture(t); |
| 507 | const directory = await mkdtemp(path.join(tmpdir(), "cage-bs-")); |
| 508 | const service = await serveMacOSBrowser({ directory, dispatch: f.privateRequest, disconnect: f.releaseInput, close: f.stop }); |
| 509 | const connections = []; |
| 510 | const connect = async () => { |
| 511 | const socket = net.createConnection(path.join(directory, "browser.sock")); |
| 512 | connections.push(socket); |
| 513 | await once(socket, "connect"); |
| 514 | const input = createInterface({ input: socket }); |
| 515 | return { socket, call: async request => { |
| 516 | const result = once(input, "line"); |
| 517 | socket.write(JSON.stringify(request) + "\n"); |
| 518 | return JSON.parse((await result)[0]); |
| 519 | } }; |
| 520 | }; |
| 521 | try { |
| 522 | const first = await connect(); |
| 523 | const opened = await first.call({ method: "POST", path: "/new", input: { url: f.url + "/retained" } }); |
| 524 | const page = f.context().pages().find(page => page.url().endsWith("/retained")); |
| 525 | await page.locator("#first").waitFor(); |
| 526 | await f.click(opened.id, page, "#first"); |
| 527 | await first.call({ method: "POST", path: "/insert-text", input: { id: opened.id, text: "unsaved work survives its viewer" } }); |
| 528 | await page.evaluate(() => { window.releasedControl = false; document.addEventListener("keyup", event => { if (event.key === "Control") window.releasedControl = true; }); }); |
| 529 | const frame = await first.call({ method: "GET", path: "/frame" }); |
| 530 | await first.call({ method: "POST", path: "/input", input: { kind: "key", target: frame.target, keysym: 0xffe3, down: true } }); |
| 531 | first.socket.destroy(); |
| 532 | const second = await connect(); |
| 533 | const state = await second.call({ method: "GET", path: "/tabs" }); |
| 534 | assert.equal(state.service.persistent, true); |
| 535 | assert.equal(state.active, opened.id); |
| 536 | assert.equal(await page.locator("#first").inputValue(), "unsaved work survives its viewer"); |
| 537 | await page.waitForFunction(() => window.releasedControl === true); |
| 538 | await service.close(); |
| 539 | assert.equal(page.isClosed(), true); |
| 540 | } finally { |
| 541 | for (const socket of connections) socket.destroy(); |
| 542 | await service.close(); |
| 543 | await rm(directory, { recursive: true, force: true }); |
| 544 | } |
| 545 | }); |
| 546 | |
| 547 | macImages("Mac image preparation rejects a changed field before accepting bytes", async t => { |
| 548 | const f = await fixture(t), one = await f.open(); |
| 549 | await f.click(one.id, one.page, "#first"); |
| 550 | assert.equal((await f.call("tabs", {}, "GET")).capabilities.systemClipboard, false); |
| 551 | const prepared = await f.call("image-start", { id: one.id }); |
| 552 | const png = await one.page.screenshot({ type: "png" }); |
| 553 | await f.click(one.id, one.page, "#second"); |
| 554 | await assert.rejects(f.call("image-chunk", { transfer: prepared.transfer, sequence: 0, length: png.length, data: png.toString("base64") }), /target changed/i); |
| 555 | await assert.rejects(f.call("image-finish", { transfer: prepared.transfer, sequence: 0 }), /已关闭|顺序/); |
| 556 | const cancelled = await f.call("image-start", { id: one.id }); |
| 557 | await f.call("image-cancel", { transfer: cancelled.transfer }); |
| 558 | await assert.rejects(f.call("image-finish", { transfer: cancelled.transfer, sequence: 0 }), /已关闭|顺序/); |
| 559 | }); |
| 560 | |
| 561 | macImages("Mac clipboard text uses one bounded transfer and one final insertion", async t => { |
| 562 | const f = await fixture(t), one = await f.open(); |
| 563 | await one.page.evaluate(() => { |
| 564 | document.querySelector("#first").addEventListener("paste", event => { |
| 565 | window.textPaste = { trusted: event.isTrusted, text: event.clipboardData.getData("text/plain") }; |
| 566 | }); |
| 567 | }); |
| 568 | await f.click(one.id, one.page, "#first"); |
| 569 | assert.equal(f.launchOptions().ignoreDefaultArgs.includes("--mute-audio"), true); |
| 570 | const text = "中".repeat(Math.floor((2 << 20) / 3)) + "ab", bytes = Buffer.from(text); |
| 571 | assert.equal(bytes.length, 2 << 20); |
| 572 | const prepared = await f.call("paste-start", { id: one.id }); |
| 573 | let sequence = 0; |
| 574 | for (let offset = 0; offset < bytes.length; offset += 65536) { |
| 575 | const reply = await f.call("paste-chunk", { transfer: prepared.transfer, sequence, length: bytes.length, mime: "text/plain", data: bytes.subarray(offset, offset + 65536).toString("base64") }); |
| 576 | assert.equal(reply.ack, ++sequence); |
| 577 | } |
| 578 | assert.equal(await one.page.locator("#first").inputValue(), ""); |
| 579 | assert.equal((await f.call("paste-finish", { transfer: prepared.transfer, sequence })).ok, true); |
| 580 | const actual = await one.page.locator("#first").inputValue(); |
| 581 | assert.equal(Buffer.byteLength(actual), bytes.length); |
| 582 | assert.equal(createHash("sha256").update(actual).digest("hex"), createHash("sha256").update(text).digest("hex")); |
| 583 | const pasted = await one.page.evaluate(() => window.textPaste); |
| 584 | assert.equal(pasted.trusted, true); |
| 585 | assert.equal(pasted.text, text); |
| 586 | const tooLarge = await f.call("paste-start", { id: one.id }); |
| 587 | await assert.rejects(f.call("paste-chunk", { transfer: tooLarge.transfer, sequence: 0, length: bytes.length + 1, mime: "text/plain", data: "YQ==" }), /大小/); |
| 588 | }); |
| 589 | |
| 590 | const macImagePaste = playwrightPath && executablePath && process.env.CAGE_BROWSER_TEST_PLATFORM === "darwin" && process.env.CAGE_BROWSER_TEST_PNG_PASTE === "1" ? test : test.skip; |
| 591 | integration("native paste preparation rejects a field switch inside a child frame", async t => { |
| 592 | const f = await fixture(t), one = await f.open(); |
| 593 | for (const origin of [f.url, f.url.replace("127.0.0.1", "localhost")]) { |
| 594 | await one.page.evaluate(url => { |
| 595 | document.querySelector("#child")?.remove(); |
| 596 | const frame = document.createElement("iframe"); frame.id = "child"; frame.src = url; |
| 597 | document.body.append(frame); |
| 598 | }, origin + "/child"); |
| 599 | const child = one.page.frameLocator("#child"); |
| 600 | await child.locator("#first").click(); |
| 601 | const before = await f.call("focus-proof", {}, "GET"); |
| 602 | const prepared = await f.call("paste-start", { id: one.id }); |
| 603 | await child.locator("#second").focus(); |
| 604 | const after = await f.call("focus-proof", {}, "GET"); |
| 605 | assert.notEqual(after.focus, before.focus); |
| 606 | await assert.rejects(f.call("paste-chunk", { transfer: prepared.transfer, sequence: 0, mime: "text/plain", length: 1, data: "YQ==" }), /target changed/i); |
| 607 | } |
| 608 | }); |
| 609 | |
| 610 | macImagePaste("Mac headless image transfer delivers an actual PNG paste event", async t => { |
| 611 | const f = await fixture(t), one = await f.open(); |
| 612 | await one.page.evaluate(() => { |
| 613 | document.querySelector("#first").addEventListener("paste", async event => { |
| 614 | event.preventDefault(); |
| 615 | const file = event.clipboardData.files[0]; |
| 616 | window.imagePaste = { trusted: event.isTrusted, type: file?.type, bytes: file ? [...new Uint8Array(await file.arrayBuffer())] : [] }; |
| 617 | }); |
| 618 | }); |
| 619 | await f.click(one.id, one.page, "#first"); |
| 620 | const prepared = await f.call("image-start", { id: one.id }); |
| 621 | const png = await one.page.screenshot({ type: "png", clip: { x: 0, y: 0, width: 16, height: 16 } }); |
| 622 | let sequence = 0; |
| 623 | for (let offset = 0; offset < png.length; offset += 65536) { |
| 624 | const reply = await f.call("image-chunk", { transfer: prepared.transfer, sequence, length: png.length, data: png.subarray(offset, offset + 65536).toString("base64") }); |
| 625 | assert.equal(reply.ack, ++sequence); |
| 626 | } |
| 627 | assert.equal((await f.call("image-finish", { transfer: prepared.transfer, sequence })).ok, true); |
| 628 | await one.page.waitForFunction(() => window.imagePaste?.bytes.length > 0); |
| 629 | const pasted = await one.page.evaluate(() => window.imagePaste); |
| 630 | assert.equal(pasted.trusted, true); |
| 631 | assert.equal(pasted.type, "image/png"); |
| 632 | assert.deepEqual(Buffer.from(pasted.bytes).subarray(0, 8), png.subarray(0, 8)); |
| 633 | await assert.rejects(f.call("image-finish", { transfer: prepared.transfer, sequence }), /已关闭|顺序/); |
| 634 | }); |
| 635 | |
| 636 | async function readClipboardReference(f, copied) { |
| 637 | assert.match(copied.clipboard.id, /^[a-f0-9-]{36}$/); |
| 638 | const opened = await f.call("file-open", { direction: "download", id: copied.clipboard.id, tab: copied.id, context: copied.context, document: copied.document }); |
| 639 | assert.equal(opened.mime, copied.clipboard.mime); |
| 640 | assert.equal(opened.size, copied.clipboard.size); |
| 641 | const chunks = []; |
| 642 | let sequence = 0, result; |
| 643 | do { |
| 644 | result = await f.call("file-read", { transfer: opened.transfer, sequence }); |
| 645 | assert.equal(result.sequence, ++sequence); |
| 646 | chunks.push(Buffer.from(result.data, "base64")); |
| 647 | } while (!result.eof); |
| 648 | const bytes = Buffer.concat(chunks); |
| 649 | assert.equal(bytes.length, opened.size); |
| 650 | return bytes; |
| 651 | } |
| 652 | |
| 653 | macImagePaste("Mac webpage PNG copy exports a bound reference with the original pixels", async t => { |
| 654 | const f = await fixture(t), one = await f.open(); |
| 655 | await one.page.evaluate(() => { |
| 656 | document.querySelector("#copy").onclick = async () => { |
| 657 | const canvas = document.createElement("canvas"); |
| 658 | canvas.width = 8; canvas.height = 4; |
| 659 | const context = canvas.getContext("2d"); |
| 660 | context.fillStyle = "#d82931"; context.fillRect(0, 0, 4, 4); |
| 661 | context.fillStyle = "#264dc6"; context.fillRect(4, 0, 4, 4); |
| 662 | const blob = await new Promise(resolve => canvas.toBlob(resolve, "image/png")); |
| 663 | await navigator.clipboard.write([new ClipboardItem({ "image/png": blob })]); |
| 664 | }; |
| 665 | }); |
| 666 | const context = "b".repeat(32); |
| 667 | await f.call("copy-context", { id: one.id, context }); |
| 668 | await f.click(one.id, one.page, "#copy"); |
| 669 | let copied; |
| 670 | for (let attempt = 0; attempt < 100 && !copied; attempt++) { |
| 671 | const state = await f.call("events", {}, "GET"); |
| 672 | copied = state.events.find(event => event.type === "clipboard" && event.value.context === context)?.value; |
| 673 | if (!copied) await new Promise(resolve => setTimeout(resolve, 20)); |
| 674 | } |
| 675 | assert.equal(copied?.clipboard?.mime, "image/png", JSON.stringify(copied)); |
| 676 | assert.equal(copied.png, undefined); |
| 677 | assert.equal(copied.text, undefined); |
| 678 | assert.equal((await f.call("tabs", {}, "GET")).tabs.some(tab => tab.url.includes("cage-clipboard.localhost")), false); |
| 679 | await assert.rejects(f.call("file-open", { direction: "download", id: copied.clipboard.id }), { code: "copy_changed" }); |
| 680 | const bytes = await readClipboardReference(f, copied); |
| 681 | const pixels = await one.page.evaluate(async encoded => { |
| 682 | const bytes = Uint8Array.from(atob(encoded), value => value.charCodeAt(0)); |
| 683 | const bitmap = await createImageBitmap(new Blob([bytes], { type: "image/png" })); |
| 684 | const canvas = document.createElement("canvas"); canvas.width = bitmap.width; canvas.height = bitmap.height; |
| 685 | const context = canvas.getContext("2d"); context.drawImage(bitmap, 0, 0); |
| 686 | const result = { width: bitmap.width, height: bitmap.height, left: [...context.getImageData(1, 1, 1, 1).data], right: [...context.getImageData(6, 1, 1, 1).data] }; |
| 687 | bitmap.close(); |
| 688 | return result; |
| 689 | }, bytes.toString("base64")); |
| 690 | assert.deepEqual(pixels, { width: 8, height: 4, left: [216, 41, 49, 255], right: [38, 77, 198, 255] }); |
| 691 | await f.call("copy-context", { id: one.id, context: "c".repeat(32) }); |
| 692 | await assert.rejects(readClipboardReference(f, copied), { code: "copy_changed" }); |
| 693 | }); |
| 694 | |
| 695 | macImagePaste("Mac native copy and cut preserve 2 MiB UTF-8 text and reject superseded reads", async t => { |
| 696 | const f = await fixture(t), one = await f.open(); |
| 697 | const text = "中".repeat(Math.floor((2 << 20) / 3)) + "ab"; |
| 698 | await one.page.locator("#first").fill(text); |
| 699 | await one.page.locator("#first").selectText(); |
| 700 | const copied = await f.call("copy", { id: one.id, context: "1".repeat(32) }); |
| 701 | assert.equal(copied.clipboard.mime, "text/plain"); |
| 702 | assert.equal(copied.clipboard.size, 2 << 20); |
| 703 | assert.equal((await readClipboardReference(f, copied)).toString("utf8"), text); |
| 704 | assert.equal(await one.page.locator("#first").inputValue(), text); |
| 705 | const opened = await f.call("file-open", { direction: "download", id: copied.clipboard.id, tab: copied.id, context: copied.context, document: copied.document }); |
| 706 | const first = await f.call("file-read", { transfer: opened.transfer, sequence: 0 }); |
| 707 | assert.equal(first.eof, false); |
| 708 | await f.call("copy-context", { id: one.id, context: "2".repeat(32) }); |
| 709 | await assert.rejects(f.call("file-read", { transfer: opened.transfer, sequence: 1 }), { code: "copy_changed" }); |
| 710 | const cut = await f.call("cut", { id: one.id, context: "3".repeat(32) }); |
| 711 | assert.equal((await readClipboardReference(f, cut)).toString("utf8"), text); |
| 712 | assert.equal(await one.page.locator("#first").inputValue(), ""); |
| 713 | const state = await f.call("events", {}, "GET"); |
| 714 | assert.equal(state.events.some(event => event.type === "clipboard" && [copied.context, cut.context].includes(event.value.context)), false, "explicit copy results must have one consumer"); |
| 715 | await assert.rejects(f.call("copy", { id: one.id, context: "4".repeat(32) }), { code: "copy_unavailable" }); |
| 716 | }); |
| 717 | |
| 718 | const nativeExtensions = playwrightPath && executablePath && process.env.CAGE_BROWSER_TEST_EXTENSIONS === "1" ? test : test.skip; |
| 719 | nativeExtensions("native extension preview, disabled import, activation and restart preserve the selected state", async t => { |
| 720 | const f = await fixture(t), one = await f.open(); |
| 721 | assert.equal((await f.call("tabs", {}, "GET")).capabilities.extensions, true); |
| 722 | const archive = fixtureZip([{ name: "manifest.json", data: JSON.stringify({ manifest_version: 3, name: "Cage isolated extension fixture", version: "1.0", content_scripts: [{ matches: [f.url + "/*"], js: ["content.js"], run_at: "document_start" }] }) }, |
| 723 | { name: "content.js", data: "document.addEventListener('DOMContentLoaded',()=>document.documentElement.dataset.fixtureExtension='ran',{once:true})" }]); |
| 724 | const upload = await f.call("file-open", { direction: "extension", length: archive.length }); |
| 725 | await f.call("file-chunk", { transfer: upload.transfer, sequence: 0, data: archive.toString("base64") }); |
| 726 | const preview = await f.call("file-finish", { transfer: upload.transfer, sequence: 1 }); |
| 727 | assert(preview.hostPermissions.includes(f.url + "/*")); |
| 728 | let installed = await f.call("extensions", { mode: "install", session: preview.session, enabled: false }); |
| 729 | const extension = installed.items.find(item => item.name === "Cage isolated extension fixture"); assert(extension); assert.equal(extension.enabled, false); |
| 730 | await f.call("reload", { id: one.id }); await one.page.waitForLoadState("domcontentloaded"); |
| 731 | assert.equal(await one.page.evaluate(() => document.documentElement.dataset.fixtureExtension), undefined); |
| 732 | await f.call("extensions", { mode: "enable", id: extension.id }); |
| 733 | await f.call("reload", { id: one.id }); await one.page.waitForLoadState("domcontentloaded"); |
| 734 | assert.equal(await one.page.evaluate(() => document.documentElement.dataset.fixtureExtension), "ran"); |
| 735 | await f.call("extensions", { mode: "disable", id: extension.id }); |
| 736 | await f.restart(); |
| 737 | installed = await f.call("extensions", { mode: "list" }); assert.equal(installed.items.find(item => item.id === extension.id).enabled, false); |
| 738 | }); |
| 739 | |
| 740 | const nativeUI = playwrightPath && executablePath && process.env.CAGE_BROWSER_TEST_HEADED === "1" && process.env.CAGE_BROWSER_TEST_NATIVE_UI === "1" ? test : test.skip; |
| 741 | nativeUI("headed Chrome exposes owned window proof and CDP shortcuts alone do not focus native find UI", async t => { |
| 742 | const f = await fixture(t), one = await f.open(); |
| 743 | await f.click(one.id, one.page, "#first"); |
| 744 | const before = await f.call("frame", {}, "GET"); assert.equal(before.native.documentFocused, true); |
| 745 | await f.call("key", { id: one.id, key: "f", meta: process.platform === "darwin", ctrl: process.platform !== "darwin" }); |
| 746 | const after = await f.call("frame", {}, "GET"); |
| 747 | // Windows BrowserRpc must send this through its owned Win32 window bridge. |
| 748 | // A Page keyboard call does not provide a Chrome-chrome interaction proof. |
| 749 | assert.equal(after.native.documentFocused, true); |
| 750 | assert.equal(after.native.window.windowId, before.native.window.windowId); |
| 751 | assert.equal(after.native.document, before.native.document); |
| 752 | assert.equal(after.native.id, one.id); |
| 753 | }); |