| 1 | import assert from "node:assert/strict"; |
| 2 | import { once } from "node:events"; |
| 3 | import { mkdtemp, rm, writeFile } from "node:fs/promises"; |
| 4 | import http from "node:http"; |
| 5 | import net from "node:net"; |
| 6 | import { tmpdir } from "node:os"; |
| 7 | import { join } from "node:path"; |
| 8 | import { randomUUID } from "node:crypto"; |
| 9 | import { setTimeout as delay } from "node:timers/promises"; |
| 10 | import test from "node:test"; |
| 11 | import { PhoneBrowser } from "./browser-phone.mjs"; |
| 12 | import { webAddress } from "./browser-phone-network.mjs"; |
| 13 | import { pathToFileURL } from "node:url"; |
| 14 | import { playwrightPhonePipe } from "../../scripts/guest-os/windows-phone-browser.mjs"; |
| 15 | |
| 16 | test("phone navigation accepts public web URLs", () => { |
| 17 | for (const url of ["file:///tmp/file", "chrome://settings", "http://2130706433", "http://10.0.0.1", |
| 18 | "http://localhost./", "http://db.internal", "http://[::1]", "https://user:[email protected]"]) { |
| 19 | assert.throws(() => webAddress(url)); |
| 20 | } |
| 21 | assert.equal(webAddress("https://example.org/path"), "https://example.org/path"); |
| 22 | }); |
| 23 | |
| 24 | test("a failed Chromium launch reports an unavailable browser and releases the session", async t => { |
| 25 | const directory = await mkdtemp(join(tmpdir(), "cage-phone-launch-")); |
| 26 | t.after(() => rm(directory, { recursive: true, force: true })); |
| 27 | const phone = new PhoneBrowser({ binary: join(directory, "missing-browser"), directory }); |
| 28 | const id = randomUUID(); |
| 29 | await assert.rejects(phone.run("open", { id, profile: "a".repeat(64), width: 390, height: 640 }), { status: 503 }); |
| 30 | await assert.rejects(phone.run("frame", { id }), { status: 410 }); |
| 31 | await writeFile(join(directory, "b".repeat(64)), "not a profile directory"); |
| 32 | await assert.rejects(phone.run("open", { id, profile: "b".repeat(64), width: 390, height: 640 }), { status: 503 }); |
| 33 | }); |
| 34 | |
| 35 | |
| 36 | |
| 37 | |
| 38 | test("real phone Chromium routes, resizes, types, and keeps paired profiles separate", |
| 39 | { skip: !process.env.CAGE_TEST_CHROMIUM }, async t => { |
| 40 | const directory = await mkdtemp(join(tmpdir(), "cage-phone-browser-")); |
| 41 | t.after(() => rm(directory, { recursive: true, force: true })); |
| 42 | const seen = []; |
| 43 | let acceptLanguage; |
| 44 | const site = http.createServer((req, res) => { |
| 45 | seen.push(req.url); |
| 46 | if (req.url === "/remember" || req.url === "/restored") acceptLanguage = req.headers["accept-language"]; |
| 47 | if (req.url === "/private") { |
| 48 | res.writeHead(302, { Location: `http://127.0.0.1:${site.address().port}/forbidden` }); |
| 49 | return res.end(); |
| 50 | } |
| 51 | if (req.url === "/private-ws") { |
| 52 | res.setHeader("Content-Type", "text/html; charset=utf-8"); |
| 53 | return res.end(`<meta name="viewport" content="width=device-width,initial-scale=1"><script> |
| 54 | const socket=new WebSocket('ws://127.0.0.1:${site.address().port}/forbidden-ws'); |
| 55 | document.title=JSON.stringify([innerWidth,innerHeight,'ws-attempted']); |
| 56 | </script>`); |
| 57 | } |
| 58 | if (req.url === "/remember") res.setHeader("Set-Cookie", "state=known; Path=/; Max-Age=3600"); |
| 59 | res.setHeader("Content-Type", "text/html; charset=utf-8"); |
| 60 | if (req.url === "/wide") return res.end(`<style>body{margin:0}input{position:absolute;left:450px;top:40px;width:200px;height:48px}</style> |
| 61 | <input><script>onload = () => document.title = JSON.stringify([innerWidth,visualViewport.scale]);</script>`); |
| 62 | res.end(`<meta name="viewport" content="width=device-width,initial-scale=1"> |
| 63 | <style>body{margin:0;height:320vh}input{display:block;width:200px;height:50px}</style> |
| 64 | <input aria-label="draft"><input type=password aria-label="password"> |
| 65 | <script> |
| 66 | const show = () => document.title = JSON.stringify([innerWidth, innerHeight, |
| 67 | document.querySelector("input").value, document.cookie, scrollY, navigator.maxTouchPoints, navigator.language, Intl.DateTimeFormat().resolvedOptions().timeZone, devicePixelRatio, |
| 68 | navigator.webdriver, Object.getOwnPropertyDescriptor(Navigator.prototype, 'webdriver').get.toString()]); |
| 69 | oninput = onresize = onscroll = show; show(); |
| 70 | </script>`); |
| 71 | }); |
| 72 | site.listen(0, "127.0.0.1"); |
| 73 | site.on("upgrade", (request, socket) => { seen.push(request.url); socket.destroy(); }); |
| 74 | await once(site, "listening"); |
| 75 | t.after(() => site.close()); |
| 76 | const chromium = process.env.CAGE_TEST_PHONE_PLAYWRIGHT ? (await import(pathToFileURL(process.env.CAGE_TEST_PHONE_PLAYWRIGHT))).chromium : null; |
| 77 | const browser = new PhoneBrowser({ |
| 78 | directory, binary: process.env.CAGE_TEST_CHROMIUM, language: "ja-JP", |
| 79 | connect: async (name, port) => { |
| 80 | if (name !== "phone.example" || port !== site.address().port) throw new Error("fixture denies destination"); |
| 81 | const socket = net.connect({ host: "127.0.0.1", port }); |
| 82 | await once(socket, "connect"); |
| 83 | return socket; |
| 84 | }, |
| 85 | ...(chromium ? { pipeFactory: (binary, args) => playwrightPhonePipe(chromium, binary, args) } : {}), |
| 86 | }); |
| 87 | t.after(() => browser.dispose()); |
| 88 | let id = randomUUID(); |
| 89 | const url = `http://phone.example:${site.address().port}`; |
| 90 | const open = (profile, path = "/") => browser.run("open", { id, profile, url: url + path, width: 390, height: 750 }); |
| 91 | const action = (type, extra) => browser.run("action", { id, type, ...extra }); |
| 92 | async function read(check = () => true) { |
| 93 | let latest; |
| 94 | for (let i = 0; i < 25; i++) { |
| 95 | try { latest = await browser.run("frame", { id }); } |
| 96 | catch (error) { if (error.status !== 409) throw error; await delay(50); continue; } |
| 97 | if (latest.title.startsWith("[") && check(JSON.parse(latest.title), latest)) return latest; |
| 98 | await delay(50); |
| 99 | } |
| 100 | throw new Error("expected frame missing: " + latest?.title); |
| 101 | } |
| 102 | async function settled(frame) { |
| 103 | |
| 104 | for (let i = 0; i < 20; i++) { |
| 105 | const next = await browser.run("frame", { id, after: frame.frame_tag }); |
| 106 | if (next.unchanged) { |
| 107 | assert.deepEqual(next, { id, frame_tag: frame.frame_tag, unchanged: true }); |
| 108 | return frame; |
| 109 | } |
| 110 | frame = next; |
| 111 | await delay(50); |
| 112 | } |
| 113 | throw new Error("static page never produced an unchanged frame"); |
| 114 | } |
| 115 | assert.deepEqual(await open("a".repeat(64), "/remember"), { id }); |
| 116 | let page = await read(([w, h, , cookie, , touch]) => w === 390 && h === 750 && cookie === "state=known" && touch >= 1); |
| 117 | assert.equal(JSON.parse(page.title)[6], "ja-JP"); |
| 118 | assert.equal(JSON.parse(page.title)[8], 2); |
| 119 | assert.deepEqual(JSON.parse(page.title).slice(9), [false, "function get webdriver() { [native code] }"]); |
| 120 | assert.match(acceptLanguage, /^ja-JP/i); |
| 121 | if (process.env.TZ) assert.equal(JSON.parse(page.title)[7], Intl.DateTimeFormat().resolvedOptions().timeZone); |
| 122 | assert.ok(Buffer.from(page.image, "base64").subarray(0, 2).equals(Buffer.from([255, 216]))); |
| 123 | assert.match(page.frame_tag, /^[a-f0-9]{32}$/); |
| 124 | page = await settled(page); |
| 125 | const initialTag = page.frame_tag; |
| 126 | page = await action("tap", { x: 60, y: 25, document: page.document, return_frame: true }); |
| 127 | assert.ok(page.focus && page.image); |
| 128 | assert.notEqual(page.frame_tag, initialTag); |
| 129 | const old = { document: page.document, focus: page.focus }; |
| 130 | assert.deepEqual(await action("text", { ...old, text: "你好 Cage" }), { id }); |
| 131 | page = await read(([, , value]) => value === "你好 Cage"); |
| 132 | const capture = browser.frame; |
| 133 | browser.frame = async () => { throw new Error("frame changed after text input"); }; |
| 134 | try { |
| 135 | assert.deepEqual(await action("text", { ...old, text: "!", return_frame: true }), { id }); |
| 136 | } finally { browser.frame = capture; } |
| 137 | await read(([, , value]) => value === "你好 Cage!"); |
| 138 | await action("resize", { width: 390, height: 400 }); |
| 139 | page = await read(([, h]) => h === 400); |
| 140 | assert.equal(page.focus, old.focus); |
| 141 | assert.notEqual(page.document, old.document); |
| 142 | await action("text", { focus: old.focus, document: page.document, text: "✓" }); |
| 143 | page = await read(([, , value]) => value === "你好 Cage!✓"); |
| 144 | await action("tap", { x: 60, y: 75, document: page.document }); |
| 145 | await read((_, frame) => frame.password && frame.focus !== old.focus); |
| 146 | await assert.rejects(action("text", { document: page.document, focus: old.focus, text: "stale" }), /输入框已改变/); |
| 147 | await action("scroll", { x: 100, y: 280, dx: 0, dy: 200, document: page.document }); |
| 148 | await read(([, , , , y]) => y > 0); |
| 149 | await action("resize", { width: 750, height: 390 }); |
| 150 | await read(([w, h]) => w === 750 && h === 390); |
| 151 | await assert.rejects(action("tap", { x: 30, y: 30, document: old.document }), /页面已切换/); |
| 152 | await action("navigate", { url: url + "/next" }); |
| 153 | page = await read(); |
| 154 | await action("tap", { x: 60, y: 25, document: page.document }); |
| 155 | page = await read((_, frame) => Boolean(frame.focus)); |
| 156 | assert.notEqual(page.focus, old.focus); |
| 157 | await assert.rejects(action("text", { document: page.document, focus: old.focus, text: "stale" }), /输入框已改变/); |
| 158 | await action("resize", { width: 390, height: 750 }); |
| 159 | await action("navigate", { url: url + "/wide" }); |
| 160 | page = await read(([w, scale]) => w >= 980 && scale < 1); |
| 161 | const scale = JSON.parse(page.title)[1]; |
| 162 | await action("tap", { x: 550 * scale, y: 65 * scale, document: page.document }); |
| 163 | await read((_, frame) => Boolean(frame.focus)); |
| 164 | await action("navigate", { url: url + "/private" }).catch(() => {}); |
| 165 | await delay(250); |
| 166 | assert.equal(seen.includes("/forbidden"), false); |
| 167 | await action("navigate", { url: url + "/private-ws" }); |
| 168 | await read(([, , status]) => status === "ws-attempted"); |
| 169 | await delay(200); |
| 170 | assert.equal(seen.includes("/forbidden-ws"), false, "a WebSocket bypassed the public-only proxy"); |
| 171 | await browser.run("close", { id }); |
| 172 | browser.language = "fr-FR"; |
| 173 | id = randomUUID(); await open("a".repeat(64), "/restored"); |
| 174 | page = await read(([, , , cookie]) => cookie === "state=known"); |
| 175 | assert.equal(JSON.parse(page.title)[6], "fr-FR"); |
| 176 | assert.match(acceptLanguage, /^fr-FR/i); |
| 177 | await browser.run("close", { id }); |
| 178 | id = randomUUID(); await open("b".repeat(64)); |
| 179 | await read(([, , , cookie]) => cookie === ""); |
| 180 | |
| 181 | |
| 182 | const s = browser.session; |
| 183 | const originalOnEvent = s.pipe.onEvent; |
| 184 | const { product } = await s.pipe.send("Browser.getVersion"); |
| 185 | const major = product.split("/")[1].split(".")[0]; |
| 186 | s.pipe.onEvent = event => { |
| 187 | originalOnEvent(event); |
| 188 | if (event.method !== "Fetch.requestPaused") return; |
| 189 | const { request, requestId } = event.params; |
| 190 | const headers = Object.fromEntries(Object.entries(request.headers).map(([k, v]) => [k.toLowerCase(), v])); |
| 191 | const mobile = headers["sec-ch-ua-mobile"] === "?1" && headers["user-agent"].includes(" Mobile ") && |
| 192 | headers["sec-ch-ua"]?.includes(`"Chromium";v="${major}"`); |
| 193 | const html = `<meta name="viewport" content="width=device-width,initial-scale=1"> |
| 194 | <style>body{margin:0} form{width:${mobile ? "95%" : "768px"}}</style> |
| 195 | <form><input></form><script>document.title=JSON.stringify([innerWidth, document.forms[0].offsetWidth, |
| 196 | navigator.userAgentData.mobile,navigator.language]);</script>`; |
| 197 | void s.send("Fetch.fulfillRequest", { requestId, responseCode: 200, responseHeaders: [{ name: "Content-Type", value: "text/html" }], |
| 198 | body: Buffer.from(html).toString("base64") }); |
| 199 | }; |
| 200 | await s.send("Fetch.enable", { patterns: [{ urlPattern: "https://phone.example/*" }] }); |
| 201 | await action("navigate", { url: "https://phone.example/search" }); |
| 202 | page = await read(([w, form, mobile]) => w === 390 && form <= w && mobile === true); |
| 203 | assert.equal(JSON.parse(page.title)[3], "fr-FR"); |
| 204 | page = await settled(page); |
| 205 | |
| 206 | await s.send("Runtime.evaluate", { expression: 'document.title = "new title"' }); |
| 207 | const renamed = await browser.run("frame", { id, after: page.frame_tag }); |
| 208 | assert.equal(renamed.title, "new title"); |
| 209 | assert.equal(renamed.image, page.image); |
| 210 | assert.notEqual(renamed.frame_tag, page.frame_tag); |
| 211 | await browser.run("close", { id }); |
| 212 | }); |