diff --git a/.vscode/launch.json b/.vscode/launch.json index 5fc872aeb6a..4ab788532d8 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -55,11 +55,23 @@ "timeout": 60000, "presentation": { "hidden": true } }, + { + // Attaches to the Chrome instance launched by `npm run debug:browser`. The target tree + // covers every extension context: popup, tab pages, and the background service worker. + "type": "chrome", + "request": "attach", + "name": "Browser: Extension (attach)", + "port": 9200, + "webRoot": "${workspaceFolder}/apps/browser", + "sourceMaps": true, + "timeout": 60000, + "presentation": { "hidden": true } + }, { "type": "chrome", "request": "attach", "name": "Web: Renderer (attach)", - "port": 9223, + "port": 9200, "webRoot": "${workspaceFolder}/apps/web", "sourceMaps": true, "timeout": 60000 @@ -83,6 +95,16 @@ "Desktop: Main desktop-native rust debugger (attach)" ], "stopAll": true + }, + { + "name": "Browser: Attach Debugger (extension)", + "configurations": ["Browser: Extension (attach)"] + }, + { + "name": "Browser: Start and debug", + "preLaunchTask": "browser: debug start", + "configurations": ["Browser: Extension (attach)"], + "stopAll": true } ] } diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 23edc2ec8de..a592fbbee7a 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -28,6 +28,34 @@ "endsPattern": ".*Debugger listening on ws.*" } } + }, + { + // Backing task for the "Browser: Start and debug" compound: builds the extension and + // launches an isolated Chrome with it loaded, so the attach configuration has + // something to attach to. + "label": "browser: debug start", + "type": "npm", + "script": "debug:browser", + "path": "", + "isBackground": true, + "presentation": { + "reveal": "always", + "panel": "dedicated", + "clear": true + }, + "problemMatcher": { + "owner": "browser-debug", + // The pipeline's own output is already readable in the terminal; nothing here should + // land in the Problems panel, so the pattern is deliberately inert. + "pattern": [{ "regexp": "^$", "file": 1, "location": 2, "message": 3 }], + "background": { + "activeOnStart": true, + "beginsPattern": ".*Building extension.*", + // dev-chrome.mjs prints this once Chrome's remote debugging port is listening, + // which is exactly when the debugger can attach. + "endsPattern": ".*DevTools:\\s+http://localhost.*" + } + } } ] } diff --git a/apps/browser/scripts/dev-chrome.mjs b/apps/browser/scripts/dev-chrome.mjs new file mode 100644 index 00000000000..7d323607b4b --- /dev/null +++ b/apps/browser/scripts/dev-chrome.mjs @@ -0,0 +1,181 @@ +#!/usr/bin/env node + +//// +// Launch Chrome for Testing with the unpacked extension from build/. +// +// Chrome restricts --load-extension on the stable channel, so this +// deliberately uses a Chrome for Testing binary, where the flag still +// works. The binary is resolved from the puppeteer cache and downloaded +// on first run. +// +// node scripts/dev-chrome.mjs [--popup] +// +// --popup open the extension popup once loaded +//// + +import { spawnSync } from "node:child_process"; +import { readFile } from "node:fs/promises"; +import { createRequire } from "node:module"; +import { homedir } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url)); +const BROWSER_DIR = resolve(SCRIPT_DIR, ".."); +const BUILD_DIR = join(BROWSER_DIR, "build"); +const REPO_ROOT = resolve(BROWSER_DIR, "../.."); + +// Shared with `npm run debug:desktop`, which writes the desktop client's native messaging +// manifest into this profile so the two debug instances can reach each other. +const PROFILE_DIR = join(REPO_ROOT, ".debug", "chrome-profile"); + +// The desktop client's IPC socket directory. Chrome spawns the native messaging proxy, so the +// proxy inherits this from Chrome's environment and finds the debug client's socket instead of +// the installed client's default one. Must match debug-start.js. +const IPC_SOCKET_DIR = join(REPO_ROOT, ".debug"); + +// Matches the chrome-devtools-attach server in the repo root .mcp.json and the vs code launch config. +const DEBUG_PORT = 9200; + +// Chrome for Testing tracks the stable channel; dev builds need nothing newer. +const CHANNEL = "stable"; +const SERVICE_WORKER = "service_worker"; +const EXTENSION_SCHEME = "chrome-extension://"; + +const BUILD_SCRIPT = "build:chrome"; +const NPM = process.platform === "win32" ? "npm.cmd" : "npm"; + +const require = createRequire(import.meta.url); + +function parseArgs(argv) { + return { + popup: argv.includes("--popup"), + }; +} + +// puppeteer-core is intentionally not a dependency of this monorepo. Fail +// with the install line rather than a bare MODULE_NOT_FOUND. +function loadDeps() { + try { + return { + puppeteer: require("puppeteer-core"), + browsers: require("@puppeteer/browsers"), + }; + } catch { + throw new Error( + "Missing dev dependencies. Install them first:\n" + + " npm install --no-save puppeteer-core @puppeteer/browsers", + ); + } +} + +// Always rebuild so the launched browser loads the current working tree. +function build() { + console.log("Building extension..."); + + const result = spawnSync(NPM, ["run", BUILD_SCRIPT], { + cwd: BROWSER_DIR, + stdio: "inherit", + shell: process.platform === "win32", + }); + + if (result.error) { + throw result.error; + } + + if (result.status !== 0) { + throw new Error(`npm run ${BUILD_SCRIPT} failed.`); + } +} + +// Reuse the cached Chrome for Testing download when present; install it +// on first run so a fresh clone needs no manual browser setup. +async function resolveChrome(browsers) { + const cacheDir = join(homedir(), ".cache", "puppeteer"); + const platform = browsers.detectBrowserPlatform(); + + if (!platform) { + throw new Error("Unsupported platform for Chrome for Testing downloads."); + } + + const buildId = await browsers.resolveBuildId(browsers.Browser.CHROME, platform, CHANNEL); + + const installed = await browsers.install({ + browser: browsers.Browser.CHROME, + buildId, + cacheDir, + platform, + }); + + return installed.executablePath; +} + +async function launch(puppeteer, executablePath) { + return puppeteer.launch({ + executablePath, + headless: false, + userDataDir: PROFILE_DIR, + env: { ...process.env, BITWARDEN_IPC_SOCKET_DIR: IPC_SOCKET_DIR }, + defaultViewport: null, + args: [ + `--load-extension=${BUILD_DIR}`, + `--disable-extensions-except=${BUILD_DIR}`, + `--remote-debugging-port=${DEBUG_PORT}`, + "--no-first-run", + "--no-default-browser-check", + ], + }); +} + +// The extension id is only knowable once its service worker registers. +async function waitForExtensionId(browser) { + const target = await browser.waitForTarget( + (t) => t.type() === SERVICE_WORKER && t.url().startsWith(EXTENSION_SCHEME), + { timeout: 30_000 }, + ); + + const url = new URL(target.url()); + + return url.hostname; +} + +async function openPopup(browser, extensionId) { + const manifest = JSON.parse(await readFile(join(BUILD_DIR, "manifest.json"), "utf8")); + const popup = manifest.action?.default_popup; + + if (!popup) { + return; + } + + const page = await browser.newPage(); + await page.goto(`${EXTENSION_SCHEME}${extensionId}/${popup}`); +} + +async function main() { + const args = parseArgs(process.argv.slice(2)); + const { puppeteer, browsers } = loadDeps(); + + build(); + + const executablePath = await resolveChrome(browsers); + console.log(`Chrome: ${executablePath}`); + + const browser = await launch(puppeteer, executablePath); + const id = await waitForExtensionId(browser); + + console.log(`Extension: ${id}`); + console.log(`Profile: ${PROFILE_DIR}`); + console.log(`DevTools: http://localhost:${DEBUG_PORT}`); + + if (args.popup) { + await openPopup(browser, id); + } + + // Hold the process open until the browser window is closed. + await new Promise((res) => browser.on("disconnected", res)); +} + +main().catch((e) => { + console.error(e.message); + process.exit(1); +}); diff --git a/package.json b/package.json index 7b2c7d44aef..766db20909c 100644 --- a/package.json +++ b/package.json @@ -42,7 +42,8 @@ "icons:reverse-migrate": "ts-node scripts/material-icons/reverse-migrate-icon-names.ts", "dev:reverse-proxy": "node --experimental-strip-types scripts/reverse-proxy-emulator/index.ts", "debug:desktop": "npm run debug:electron --workspace @bitwarden/desktop", - "debug:desktop:automation": "cross-env USE_AUTOMATION_BIOMETRICS=true npm run debug:desktop" + "debug:desktop:automation": "cross-env USE_AUTOMATION_BIOMETRICS=true npm run debug:desktop", + "debug:browser": "node apps/browser/scripts/dev-chrome.mjs --popup" }, "workspaces": [ "apps/*",