| 1 | import assert from "node:assert/strict"; |
| 2 | import http from "node:http"; |
| 3 | import { createHash } from "node:crypto"; |
| 4 | import { mkdtemp, rm } from "node:fs/promises"; |
| 5 | import { tmpdir } from "node:os"; |
| 6 | import { join } from "node:path"; |
| 7 | import { fileURLToPath } from "node:url"; |
| 8 | import { createRequire } from "node:module"; |
| 9 | |
| 10 | const require = createRequire(import.meta.url); |
| 11 | const { chromium } = require(process.env.CAGE_PLAYWRIGHT_MODULE || "playwright"); |
| 12 | const extension = fileURLToPath(new URL("../internal/cage/split-extension", import.meta.url)); |
| 13 | const extensionId = createHash("sha256").update(extension).digest("hex").slice(0, 32) |
| 14 | .replace(/./g, digit => String.fromCharCode(97 + parseInt(digit, 16))); |
| 15 | const profile = await mkdtemp(join(tmpdir(), "cage-favicon-extension-")); |
| 16 | const requests = []; |
| 17 | const icons = http.createServer((req, res) => { |
| 18 | requests.push(req.url); |
| 19 | res.setHeader("Content-Type", "image/svg+xml"); |
| 20 | const color = req.url.includes("blue") ? "blue" : "red"; |
| 21 | res.end(`<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><path fill="${color}" d="M0 0h32v32H0z"/></svg>`); |
| 22 | }); |
| 23 | await new Promise(resolve => icons.listen(0, "127.0.0.1", resolve)); |
| 24 | const iconOrigin = `http://127.0.0.1:${icons.address().port}`; |
| 25 | const site = http.createServer((req, res) => { |
| 26 | res.setHeader("Content-Type", "text/html"); |
| 27 | res.setHeader("Content-Security-Policy", req.url.startsWith("/blocked") |
| 28 | ? "default-src 'none'; img-src 'none'; connect-src *" |
| 29 | : "default-src 'none'; img-src *; connect-src 'none'"); |
| 30 | res.end(`<!doctype html><link rel="icon" href="${iconOrigin}/red.svg"><title>Favicon fixture</title>`); |
| 31 | }); |
| 32 | await new Promise(resolve => site.listen(0, "127.0.0.1", resolve)); |
| 33 | const origin = `http://localhost:${site.address().port}`; |
| 34 | const launch = () => chromium.launchPersistentContext(profile, { |
| 35 | executablePath: process.env.CAGE_TEST_BROWSER_PATH, |
| 36 | channel: "chromium", |
| 37 | headless: true, |
| 38 | args: [`--disable-extensions-except=${extension}`, `--load-extension=${extension}`, "--restore-last-session"], |
| 39 | }); |
| 40 | let context; |
| 41 | async function waitFor(action, label) { |
| 42 | const deadline = Date.now() + 10000; |
| 43 | while (Date.now() < deadline) { |
| 44 | const value = await action(); |
| 45 | if (value) return value; |
| 46 | await new Promise(resolve => setTimeout(resolve, 50)); |
| 47 | } |
| 48 | throw new Error(`Timed out waiting for ${label}`); |
| 49 | } |
| 50 | async function targetFor(page) { |
| 51 | const session = await context.newCDPSession(page); |
| 52 | const { targetInfo } = await session.send("Target.getTargetInfo"); |
| 53 | await session.detach(); |
| 54 | return targetInfo.targetId; |
| 55 | } |
| 56 | async function setupController() { |
| 57 | const page = await context.newPage(); |
| 58 | await page.goto(`chrome-extension://${extensionId}/control.html`); |
| 59 | await page.evaluate(() => { |
| 60 | globalThis.faviconEvents = []; |
| 61 | globalThis.cageFaviconChanged = target => faviconEvents.push(target); |
| 62 | }); |
| 63 | return page; |
| 64 | } |
| 65 | async function read(page, target) { |
| 66 | return page.evaluate(id => readCageFavicon(id), target); |
| 67 | } |
| 68 | try { |
| 69 | context = await launch(); |
| 70 | let controller = await setupController(); |
| 71 | const blocked = await context.newPage(); |
| 72 | await blocked.goto(origin + "/blocked"); |
| 73 | const blockedTarget = await targetFor(blocked); |
| 74 | assert.equal((await read(controller, blockedTarget)).favicon, "", "img-src denial must keep the fallback"); |
| 75 | assert.deepEqual(requests, [], "controller must never load the blocked website icon"); |
| 76 | |
| 77 | const page = await context.newPage(); |
| 78 | await page.goto(origin + "/allowed"); |
| 79 | const target = await targetFor(page); |
| 80 | const red = await waitFor(async () => (await read(controller, target))?.favicon, "native favicon despite connect-src denial"); |
| 81 | assert.match(red, /^data:image\/png;base64,/); |
| 82 | assert.ok(red.length <= 8192); |
| 83 | const bytes = Buffer.from(red.split(",")[1], "base64"); |
| 84 | assert.equal(bytes.readUInt32BE(16), 32); |
| 85 | assert.equal(bytes.readUInt32BE(20), 32); |
| 86 | const nativeRequestCount = requests.length; |
| 87 | await read(controller, target); |
| 88 | await read(controller, target); |
| 89 | assert.equal(requests.length, nativeRequestCount, "cache reads must not request website resources"); |
| 90 | await page.evaluate(() => history.pushState({}, "", "/next")); |
| 91 | await waitFor(async () => (await read(controller, target))?.favicon === red, "favicon after SPA route change"); |
| 92 | await controller.evaluate(() => { faviconEvents.length = 0; }); |
| 93 | await page.evaluate(url => { document.querySelector('link[rel="icon"]').href = url; }, iconOrigin + "/blue.svg"); |
| 94 | const blue = await waitFor(async () => { |
| 95 | const result = await read(controller, target); |
| 96 | return result?.favicon && result.favicon !== red && result.favicon; |
| 97 | }, "dynamic favicon update"); |
| 98 | await waitFor(() => controller.evaluate(id => faviconEvents.includes(id), target), "favicon invalidation binding"); |
| 99 | assert.notEqual(blue, red); |
| 100 | |
| 101 | |
| 102 | await controller.evaluate(id => { |
| 103 | const decode = HTMLImageElement.prototype.decode; |
| 104 | globalThis.originalFaviconDecode = decode; |
| 105 | HTMLImageElement.prototype.decode = async function () { |
| 106 | await decode.call(this); |
| 107 | await new Promise(resolve => { globalThis.releaseFaviconDecode = resolve; }); |
| 108 | }; |
| 109 | globalThis.pendingFaviconRead = readCageFavicon(id); |
| 110 | }, target); |
| 111 | await controller.waitForFunction(() => typeof releaseFaviconDecode === "function"); |
| 112 | await page.goto(origin + "/blocked-race"); |
| 113 | await controller.evaluate(() => releaseFaviconDecode()); |
| 114 | assert.equal(await controller.evaluate(() => pendingFaviconRead), null, "navigation cannot publish the previous document's icon"); |
| 115 | await controller.evaluate(() => { HTMLImageElement.prototype.decode = originalFaviconDecode; }); |
| 116 | await page.goto(origin + "/allowed"); |
| 117 | await waitFor(async () => (await read(controller, target))?.favicon === red, "favicon after full navigation"); |
| 118 | await controller.evaluate(id => { |
| 119 | globalThis.releaseFaviconDecode = null; |
| 120 | HTMLImageElement.prototype.decode = async function () { |
| 121 | await originalFaviconDecode.call(this); |
| 122 | await new Promise(resolve => { globalThis.releaseFaviconDecode = resolve; }); |
| 123 | }; |
| 124 | globalThis.pendingFaviconRead = readCageFavicon(id); |
| 125 | }, target); |
| 126 | await controller.waitForFunction(() => typeof releaseFaviconDecode === "function"); |
| 127 | await page.close(); |
| 128 | await controller.evaluate(() => releaseFaviconDecode()); |
| 129 | assert.equal(await controller.evaluate(() => pendingFaviconRead), null, "a closed tab cannot publish a late icon"); |
| 130 | assert.equal(await read(controller, target), null); |
| 131 | const saved = await context.newPage(); |
| 132 | await saved.goto(origin + "/restored"); |
| 133 | await context.close(); |
| 134 | |
| 135 | context = await launch(); |
| 136 | controller = await setupController(); |
| 137 | const restored = await waitFor(async () => context.pages().find(tab => tab.url() === origin + "/restored"), "restored browser tab"); |
| 138 | const restoredTarget = await targetFor(restored); |
| 139 | await waitFor(async () => (await read(controller, restoredTarget))?.favicon === red, "restored tab favicon"); |
| 140 | console.log("PASS: native Chromium icon cache, reciprocal CSP policies, cross-origin icons, 32px bounded PNG, SPA, dynamic updates, navigation/close races and session restoration"); |
| 141 | } finally { |
| 142 | await context?.close(); |
| 143 | await Promise.all([new Promise(resolve => site.close(resolve)), new Promise(resolve => icons.close(resolve))]); |
| 144 | await rm(profile, { recursive: true, force: true }); |
| 145 | } |