test-firefox-sender-context.mjs

13.5 KB · raw

1#!/usr/bin/env node23import { execFile } from "node:child_process";4import { promisify } from "node:util";5import { cp, mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";6import { existsSync } from "node:fs";7import { createServer as createHttpServer } from "node:http";8import { tmpdir } from "node:os";9import { join, resolve } from "node:path";10import net from "node:net";11import { start } from "geckodriver";1213const execFileAsync = promisify(execFile);14const ROOT = resolve(new URL("..", import.meta.url).pathname);15const DIST = join(ROOT, "dist-firefox");16const PROBE = join(ROOT, "tests/fixtures/firefox-sender-probe.js");17const WEB_EXT = join(ROOT, "node_modules/.bin/web-ext");18const EXTENSION_ID = "[email protected]";1920function findFirefoxBinary() {21  const candidates = [22    process.env.PEACH_FIREFOX_BINARY,23    process.env.FIREFOX_BIN,24    "/usr/bin/firefox",25    "/usr/local/bin/firefox",26    "/Applications/Firefox.app/Contents/MacOS/firefox",27    "/Applications/Firefox Nightly.app/Contents/MacOS/firefox",28    join(process.env.HOME ?? "", "Library/Caches/ms-playwright/firefox-1538/firefox/Nightly.app/Contents/MacOS/firefox"),29    join(process.env.HOME ?? "", "Library/Caches/ms-playwright/firefox-1511/firefox/Nightly.app/Contents/MacOS/firefox"),30  ].filter(Boolean);31  return candidates.find((candidate) => existsSync(candidate));32}3334function findFreePort() {35  return new Promise((resolvePort, reject) => {36    const server = net.createServer();37    server.once("error", reject);38    server.listen(0, "127.0.0.1", () => {39      const address = server.address();40      if (!address || typeof address === "string") {41        server.close();42        reject(new Error("Could not allocate a WebDriver port"));43        return;44      }45      server.close(() => resolvePort(address.port));46    });47  });48}4950async function waitForDriver(port, driver) {51  const deadline = Date.now() + 30_000;52  while (Date.now() < deadline) {53    try {54      const response = await fetchWithTimeout(`http://127.0.0.1:${port}/status`, {}, 5000);55      if (response.ok && (await response.json()).value?.ready) return;56    } catch {57      if (driver.exitCode !== null || driver.signalCode !== null) {58        throw new Error(`geckodriver exited during startup (${driver.exitCode ?? driver.signalCode})`);59      }60    }61    await new Promise((resolveDelay) => setTimeout(resolveDelay, 250));62  }63  throw new Error("geckodriver did not become ready within 30 seconds");64}6566async function fetchWithTimeout(url, options, timeoutMs) {67  const controller = new AbortController();68  let timeoutId;69  const timeout = new Promise((_, reject) => {70    timeoutId = setTimeout(() => reject(new Error(`Request timed out after ${timeoutMs}ms`)), timeoutMs);71  });72  try {73    return await Promise.race([74      fetch(url, { ...options, signal: controller.signal }),75      timeout,76    ]);77  } catch (error) {78    controller.abort();79    throw error;80  } finally {81    clearTimeout(timeoutId);82  }83}8485async function webdriverRequest(port, path, options = {}) {86  const response = await fetchWithTimeout(`http://127.0.0.1:${port}${path}`, {87    ...options,88    headers: { "content-type": "application/json", ...(options.headers ?? {}) },89  }, 10_000);90  const body = await response.json();91  if (!response.ok || body.value?.error) {92    throw new Error(`WebDriver ${options.method ?? "GET"} ${path} failed: ${JSON.stringify(body)}`);93  }94  return body.value;95}9697async function stopDriver(driver) {98  if (!driver || driver.exitCode !== null || driver.signalCode !== null) return;99  const exited = new Promise((resolveExit) => driver.once("exit", resolveExit));100  driver.kill("SIGTERM");101  let timeoutId;102  const stopped = await Promise.race([103    exited.then(() => true),104    new Promise((resolveTimeout) => {105      timeoutId = setTimeout(() => resolveTimeout(false), 5000);106    }),107  ]);108  clearTimeout(timeoutId);109  if (!stopped && driver.exitCode === null && driver.signalCode === null) {110    driver.kill("SIGKILL");111    await exited;112  }113}114115async function buildTestExtension(tempRoot) {116  const sourceDir = join(tempRoot, "extension");117  const artifactsDir = join(tempRoot, "artifacts");118  await cp(DIST, sourceDir, { recursive: true });119  await mkdir(artifactsDir, { recursive: true });120  await cp(PROBE, join(sourceDir, "firefox-sender-probe.js"));121122  const manifestPath = join(sourceDir, "manifest.json");123  const manifest = JSON.parse(await readFile(manifestPath, "utf8"));124  manifest.content_scripts.push({125    matches: ["<all_urls>"],126    js: ["firefox-sender-probe.js"],127    run_at: "document_start",128    all_frames: false,129  });130  await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);131132  await execFileAsync(WEB_EXT, [133    "build",134    "--source-dir", sourceDir,135    "--artifacts-dir", artifactsDir,136    "--filename", "peach-firefox-sender-context.xpi",137    "--overwrite-dest",138    "--no-input",139  ], { cwd: ROOT });140  return join(artifactsDir, "peach-firefox-sender-context.xpi");141}142143async function run() {144  if (!existsSync(DIST)) throw new Error("dist-firefox is missing; run npm run build:firefox first");145  if (!existsSync(WEB_EXT)) throw new Error("web-ext is missing; run bun install first");146147  const tempRoot = await mkdtemp(join(tmpdir(), "peach-firefox-sender-"));148  let driver;149  let driverPort;150  let sessionId;151  let fixtureServer;152  try {153    const xpiPath = await buildTestExtension(tempRoot);154    const firefoxBinary = findFirefoxBinary();155    // Match the Playwright Firefox release environment: this host cannot map156    // the hardware compositor, and Marionette must inherit the same fallback.157    Object.assign(process.env, {158      MOZ_HEADLESS: "1",159      MOZ_DISABLE_CONTENT_SANDBOX: "1",160      MOZ_DISABLE_RDD_SANDBOX: "1",161      LIBGL_ALWAYS_SOFTWARE: "1",162    });163    const port = await findFreePort();164    driverPort = port;165    driver = await start({166      host: "127.0.0.1",167      port,168      geckoDriverVersion: "0.37.1",169      ...(firefoxBinary ? { binary: firefoxBinary } : {}),170      log: "error",171      spawnOpts: {172        env: {173          ...process.env,174          MOZ_HEADLESS: "1",175          MOZ_DISABLE_CONTENT_SANDBOX: "1",176          MOZ_DISABLE_RDD_SANDBOX: "1",177          LIBGL_ALWAYS_SOFTWARE: "1",178        },179      },180    });181    await waitForDriver(port, driver);182183    const capabilities = {184      browserName: "firefox",185      acceptInsecureCerts: true,186      "moz:firefoxOptions": {187        args: ["-headless", "-no-remote"],188        ...(firefoxBinary ? { binary: firefoxBinary } : {}),189        prefs: {190          "browser.shell.checkDefaultBrowser": false,191          "browser.startup.page": 0,192          "browser.startup.homepage": "about:blank",193          "security.sandbox.content.level": 0,194          "security.sandbox.gpu.level": 0,195          "security.sandbox.rdd.level": 0,196          "gfx.webrender.all": false,197          "gfx.webrender.software": false,198          "layers.acceleration.disabled": true,199          "media.hardware-video-decoding.force-enabled": false,200          "remote.system-access-check.enabled": false,201        },202      },203    };204    const session = await webdriverRequest(port, "/session", {205      method: "POST",206      body: JSON.stringify({ capabilities: { alwaysMatch: capabilities } }),207    });208    sessionId = session.sessionId;209210    fixtureServer = createHttpServer((_request, response) => {211      response.writeHead(200, { "content-type": "text/html; charset=utf-8" });212      response.end("<!doctype html><html><head><title>Peach sender test</title></head><body></body></html>");213    });214    await new Promise((resolveListen, rejectListen) => {215      fixtureServer.once("error", rejectListen);216      fixtureServer.listen(0, "127.0.0.1", resolveListen);217    });218    const fixtureAddress = fixtureServer.address();219    if (!fixtureAddress || typeof fixtureAddress === "string") {220      throw new Error("Could not allocate the Firefox fixture server port");221    }222    const fixtureOrigin = `http://127.0.0.1:${fixtureAddress.port}`;223224    const install = await webdriverRequest(port, `/session/${sessionId}/moz/addon/install`, {225      method: "POST",226      body: JSON.stringify({227        path: xpiPath,228        temporary: true,229      }),230    });231    if (install?.id && install.id !== EXTENSION_ID) {232      throw new Error(`Unexpected Firefox add-on id: ${install.id}`);233    }234235    await webdriverRequest(port, `/session/${sessionId}/moz/context`, {236      method: "POST",237      body: JSON.stringify({ context: "chrome" }),238    });239    const addonInfo = await webdriverRequest(port, `/session/${sessionId}/execute/async`, {240      method: "POST",241      body: JSON.stringify({242        script: `243          const done = arguments[arguments.length - 1];244          const { AddonManager } = ChromeUtils.importESModule("resource://gre/modules/AddonManager.sys.mjs");245          const { ExtensionPermissions } = ChromeUtils.importESModule("resource://gre/modules/ExtensionPermissions.sys.mjs");246          AddonManager.getAddonByID(arguments[0]).then(async (addon) => {247            if (!addon) return null;248            const policy = WebExtensionPolicy.getByID(addon.id);249            await ExtensionPermissions.add(250              addon.id,251              { permissions: [], origins: ["<all_urls>"] },252              policy.extension,253            );254            await addon.reload();255            const reloadedAddon = await AddonManager.getAddonByID(addon.id);256            return {257              active: reloadedAddon.isActive,258              permissions: await ExtensionPermissions.get(addon.id),259            };260          }).then(done, (error) => done({ error: String(error), stack: error?.stack }));261        `,262        args: [EXTENSION_ID],263      }),264    });265    await webdriverRequest(port, `/session/${sessionId}/moz/context`, {266      method: "POST",267      body: JSON.stringify({ context: "content" }),268    });269    if (!addonInfo?.active || !addonInfo.permissions?.origins?.includes("<all_urls>")) {270      throw new Error(`Firefox add-on host permission was not granted: ${JSON.stringify(addonInfo)}`);271    }272273    await webdriverRequest(port, `/session/${sessionId}/url`, {274      method: "POST",275      body: JSON.stringify({ url: `${fixtureOrigin}/` }),276    });277    // Firefox may finish navigation before document_start content scripts have278    // registered their relay listener; wait for the extension boundary to settle.279    await new Promise((resolveDelay) => setTimeout(resolveDelay, 2000));280    const result = await webdriverRequest(port, `/session/${sessionId}/execute/async`, {281      method: "POST",282      body: JSON.stringify({283        script: `284          const done = arguments[arguments.length - 1];285          const source = "peach-firefox-sender-probe";286          const send = (message) => new Promise((resolve) => {287            const id = crypto.randomUUID();288            const timer = setTimeout(() => {289              window.removeEventListener("message", onResponse);290              resolve({ ok: false, error: "probe_timeout" });291            }, 5000);292            function onResponse(event) {293              let response;294              try {295                response = JSON.parse(event.data);296              } catch {297                return;298              }299              if (response?.source !== source + ":response" || response.id !== id) return;300              clearTimeout(timer);301              window.removeEventListener("message", onResponse);302              resolve(response.response);303            }304            window.addEventListener("message", onResponse);305            window.postMessage(JSON.stringify({ source, id, message }), "*");306          });307          Promise.all([308            send({ type: "GET_SETTINGS" }),309            send({ type: "GET_ENTRIES" }),310            send({ type: "GET_RECOVERY_WORDS" }),311            send({ type: "STORAGE_SESSION" }),312          ]).then(([allowed, entries, recovery, storage]) => done({313            pageOrigin: location.origin,314            probeReady: document.documentElement.dataset.peachFirefoxSenderProbe ?? null,315            allowed,316            entries,317            recovery,318            storage,319          }));320        `,321        args: [],322      }),323    });324325    if (result.pageOrigin !== fixtureOrigin) {326      throw new Error(`Unexpected page origin: ${result.pageOrigin}`);327    }328    if (result.probeReady !== "ready") {329      throw new Error(`Firefox content-script probe did not execute: ${JSON.stringify(result)}`);330    }331    if (Object.hasOwn(result.storage ?? {}, "peach_session_dk")) {332      throw new Error(`Firefox content-script accessed the session escrow key: ${JSON.stringify(result.storage)}`);333    }334    if (result.allowed?.error === "invalid_sender") {335      throw new Error("Content-script-allowed GET_SETTINGS was rejected");336    }337    for (const [name, response] of [["GET_ENTRIES", result.entries], ["GET_RECOVERY_WORDS", result.recovery]]) {338      if (response?.error !== "invalid_sender") {339        throw new Error(`${name} was not rejected from the real Firefox content-script sender: ${JSON.stringify({ result, response })}`);340      }341    }342    console.log("Firefox sender-context test passed: real content-script GET_ENTRIES and GET_RECOVERY_WORDS were rejected, GET_SETTINGS remained allowed.");343  } finally {344    if (driver && sessionId) {345      try {346        await webdriverRequest(driverPort, `/session/${sessionId}`, { method: "DELETE" });347      } catch {348        // The browser may already have exited after a failed startup.349      }350    }351    if (fixtureServer) {352      await new Promise((resolveClose) => fixtureServer.close(resolveClose));353    }354    await stopDriver(driver);355    await rm(tempRoot, { recursive: true, force: true });356  }357}358359run().catch((error) => {360  console.error(error instanceof Error ? error.message : error);361  process.exitCode = 1;362});