diff --git a/.ai/contexts/README.md b/.ai/contexts/README.md index d8966fbb4..eafe40f33 100644 --- a/.ai/contexts/README.md +++ b/.ai/contexts/README.md @@ -10,6 +10,7 @@ change without re-reading `main.js`, now ~4100 LOC. |---|---| | Module-move codemod, VM stub inference and layout checks | [module-moves](module-moves.md) | | CLI adapter contract, Claude delegation and pure launch argv | [cli-harnesses](cli-harnesses.md) | +| Managed browser lifecycle library, Linux identity/lock and test-pr cleanup | [managed-browser](managed-browser.md) | | The fast pre-commit check (staged lint, test selection) | [fast-check](fast-check.md) | | SQLite, indexing, search, heatmap aggregation, fs.watch | [session-cache](session-cache.md) | | Cron schedules, schedule `.md` files, `claude --resume -p` spawn | [schedule-runner](schedule-runner.md) | diff --git a/.ai/contexts/managed-browser.md b/.ai/contexts/managed-browser.md new file mode 100644 index 000000000..78f2ec442 --- /dev/null +++ b/.ai/contexts/managed-browser.md @@ -0,0 +1,138 @@ +# Managed browser lifecycle (#812, S2) + +`src/main/browser/managed-browser.js` exports `createManager` and +`cleanupDataDir`. It is CommonJS and Electron-free. Requiring it or constructing +a manager does no filesystem, socket, HTTP or process work. No renderer, IPC, +settings or session-launch path calls Open/ensureStarted in this slice. There +is no MCP dependency or configuration writer yet; that belongs to S3. + +The main process constructs the manager using the directory of DB_PATH. +`shutdownForExit` calls `stopForQuit` synchronously immediately after its +repeat guard and before starting the bounded drain. Only an owner of a verified +child-mode browser with its own matching spawner identity sends SIGTERM there. +Scope/detached browsers and followers receive no quit signal. Source-extraction +fixtures must supply the manager when evaluating this shutdown function. +The quit call is caught and logged so a manager exception cannot prevent the +remaining bounded shutdown or the repeat guard from taking effect. + +Operations are queued. Linux starts on explicit Open or ensureStarted only; +other platforms return an unsupported result without touching storage or +spawning. Results include status, role, port, binary, mode, survival, notice +and error. Errors stay recoverable values. Browser-open is best-effort HTTP +activation, with a PUT new-page fallback; compositor focus is unverified. + +Discovery accepts an absolute ELF executable or numeric-descending Chromium cache +revisions. Executable launcher scripts are refused with a request to configure +the real Chromium ELF binary, for example `/usr/lib/chromium/chromium`, rather +than `/usr/bin/chromium`. Only the four-byte ELF magic is checked, not the ELF +architecture or browser provenance. An explicit cache root is authoritative. +Symlink hops, directory links and final targets are checked for Snap; no installed-browser fallback, +download, headless-shell or personal profile is used. A private canonical data +directory holds profile, output, state and a per-start truncated log. Directory +modes are 0700, file modes 0600; foreign owners and symlinks are refused. +State writes use unique exclusive temporary files, fsync and rename. Output +pruning covers only ordinary old files directly under output, after ownership +has been acquired. No profile files are pruned. + +Failure memo keys include configured paths, cache-root/revision candidates and +binary metadata. Installing a browser or changing the selected binary retries +without waiting sixty seconds. A synchronous spawn refusal clears the pending +reservation; publication failure after spawn terminates only the verified +launch before returning an error. Ambiguous outcomes retain their state. + +The owner lock is a Unix listener at a hash-derived path in a private absolute +XDG_RUNTIME_DIR, or a short socket under the managed directory. Live socket +means follower. ECONNREFUSED permits one inode-checked stale unlink/retry. +Long/unsafe/unavailable paths refuse management. Operations retry acquisition +for followers; followers do not write state, prune, start or stop. There remains +a simultaneous stale-takeover check/unlink race: a competing new socket could +replace the checked inode before unlink. The browser profile singleton is the +last backstop, not the locking protocol. Socket close has a similar unavoidable +pathname race. Neither is a cross-user security boundary. + +State schema version 1 records a persistent port, canonical profile/binary, +PID/startTime/boot identity, spawner identity, mode, unit and start time. Pending +launches also record the launcher's PID/startTime/boot immediately after spawn, +before readiness polling. A port +reservation may have no PID. Start time and boot ID, rather than PID existence, +decide whether a recorded browser still exists. A reused PID or another boot +resets the state to a port-only reservation without signalling the replacement. +An owner reconciles a pending ambiguous launch before Start or Stop: in the same +boot, a still-live launcher or an unavailable launcher identity blocks recovery +with an error, retaining the pending state and profile. Once the recorded +launcher identity is gone (including PID reuse), scan for the exact +binary/profile/port and adopt a verified match; no match clears the pending +state to a port-only reservation. A different boot clears it without scanning. +Missing boot identity or an adoption verification failure retains data. +Followers cannot reconcile or write pending state. Stop and cleanup therefore +cannot authorize profile deletion while a slow launcher could still exec the +browser, and another Open cannot spawn a duplicate. Legacy pending states +without a recorded launcher remain uncertain within the same boot. +An unverified failed/timed-out launch receives a best-effort positive-PID TERM +only when the recorded launcher identity still matches, rechecked immediately +before signalling. Its pending state remains available for owner recovery, +including when the launcher ignores TERM; a reused launcher PID is not signalled. +Reserve before discovery; reuse across Stop/Open. Foreign occupation replaces the port and returns a +restart-sessions notice. Bind/spawn races are checked against the actual +listener, with at most three allocations in the start budget. + +Linux identity uses field 22 from proc stat (index 19 after the final `)`), boot +ID, executable, exact profile/port argv and the listening socket inode in that +PID's fds. TCP6 or wildcard listeners are refused. Joined and NUL argv forms +are supported, with bounded size and exactly one profile and debugging-port +argument. A version HTTP response alone cannot establish ownership. +Listener ownership by a browser child is deliberately unsupported pending real +headful evidence. Source orphan adoption requires a dead start-verified spawner +and records the new one before it can signal at quit. + +Packaged starts use systemd-run --user --scope, detached/unref and file-backed +stdio; every command argument doubles dollars. Only a definite missing-user-bus +failure before a browser exists permits one detached fallback. It is marked as +not surviving restart. FATAL/sandbox errors and ambiguous timeouts never cause +a detached or no-sandbox retry. Chromium's sandbox remains enabled. +Dollar handling is NOT verified against real systemd: `--scope` may not perform +the environment expansion that doubling dollars assumes. The escaping behavior +is preserved pending a real systemd check, including literal-dollar paths. + +Normal Stop re-verifies the endpoint, sends Browser.close, waits five seconds, +then re-verifies immediately before TERM (three seconds) and KILL (one second). +Descendant ancestry is captured before close, but ancestry alone does not +authorize a signal: a descendant must have the browser executable, an exact +profile argument, or a Chromium `--type=` argument on a crashpad handler +(`chrome_crashpad_handler` or `crashpad_handler`) alongside the browser binary. +An arbitrary executable's `--type=` is insufficient. Only verified descendants +become parents for further traversal: the walk stops at a native-messaging host +even if its children use the browser executable or Electron type markers. +Start time, boot ID and +these executable/argv markers are checked again immediately before each +positive-PID signal. Unrelated native-messaging hosts and download handlers, +including descendants that exec into them during close, are left alive. +When the browser identity still verifies but its listener has already closed, +Stop skips CDP and waits up to five seconds for exit before the usual verified +TERM/KILL escalation. A listener disappearing during endpoint verification uses +the same path. A foreign listener or identity change still refuses signalling. +Without pidfd, identity-check-to-signal races remain; no process group, name or +scope-wide kill is used. The twenty-second start readiness budget and bounded +HTTP responses do not prove Linux sandbox, cgroup or signed-in survival. + +HTTP requests have both a 500 ms total deadline and an inactivity timeout, plus +a 64 KiB response limit. WebSocket uses the existing runtime `ws` dependency so +it also works without a Node global WebSocket. Permission failure during owner +socket setup closes the listener before rejecting acquisition. + +`scripts/test-pr.js` captures SWITCHBOARD_DATA_DIR before fixture preparation, +awaits cleanup on launch success/rejection/fixture error, and removes launchCwd +only after confirmed browser exit. A cleanup error retains both paths with a +warning. `cleanWorktree` is now async and stops the browser before unlinking +the dependency junction or removing the worktree/data. It never creates a +manager when no managed-browser directory exists. Windows refuses cleanup of +an unexpected existing browser directory rather than guessing at Linux PIDs. + +Tests use real disposable files, fake process/clock/lock boundaries, injected +procfs/net fixtures and a Node HTTP/WebSocket fake browser. Windows tests prove +the unsupported policy; Linux mode/permissions/process behavior still requires +Linux execution. No real browser, Electron or Playwright is needed for S2. + +Loopback CDP has no user/session authentication. Other local processes can +control the signed-in browser; this library is not a filesystem or network +isolation boundary. Chromium's own sandbox stays enabled. diff --git a/main.js b/main.js index a23e1be18..ffc4245eb 100644 --- a/main.js +++ b/main.js @@ -261,6 +261,7 @@ async function sweepContinuationChoices() { // The trace file sits next to switchboard.db — DB_PATH is the one resolution // of SWITCHBOARD_DATA_DIR, never re-derived here. const TRACE_DIR = path.dirname(DB_PATH); +const managedBrowser = require('./src/main/browser/managed-browser').createManager({ dataDir: TRACE_DIR, isPackaged: app.isPackaged }); const PLAIN_TERMINAL_INIT_DIR = path.join(path.dirname(DB_PATH), 'shell-init'); activityTrace.init(TRACE_DIR); activityTrace.setEnabled( @@ -4215,6 +4216,7 @@ function drainForUpdate() { } function shutdownForExit() { if (shutdownPromise) return shutdownPromise; + try { managedBrowser.stopForQuit(); } catch (error) { log.error('[shutdown] managed browser quit failed', error); } shutdownPromise = boundedShutdown(() => writer.beginShutdown(async () => { appQuitting = true; if (TRACE.on) trace('app.quit', null, {}); diff --git a/scripts/test-pr.js b/scripts/test-pr.js index 1e2f55cba..71ce5978d 100644 --- a/scripts/test-pr.js +++ b/scripts/test-pr.js @@ -6,6 +6,7 @@ const path = require('node:path'); const { execFileSync, spawn } = require('node:child_process'); const { isDeepStrictEqual } = require('node:util'); const { scrubSessionEnv } = require('../src/main/shared/clean-env'); +const { cleanupDataDir } = require('../src/main/browser/managed-browser'); function validatePr(pr) { if (!/^\d+$/.test(String(pr ?? ''))) throw new Error('PR must be numeric: task test-pr PR='); @@ -160,12 +161,14 @@ function parseBundleScript(script) { return options; } -function cleanWorktree({ checkout, pr, home = process.env.HOME || os.homedir(), run = runCommand }) { +async function cleanWorktree({ checkout, pr, home = process.env.HOME || os.homedir(), run = runCommand, stopBrowser = cleanupDataDir }) { validatePr(pr); + const data = path.join(home, `.switchboard-dev-pr${pr}`); + if (!await stopBrowser(data)) throw new Error(`Browser exit uncertain; retaining ${data} and worktree`); const worktree = path.join(checkout, '.worktrees', `pr-${pr}-test`); unlinkNodeModules(worktree); run('git', ['worktree', 'remove', '--force', worktree], { cwd: checkout, stdio: 'inherit' }); - fs.rmSync(path.join(home, `.switchboard-dev-pr${pr}`), { recursive: true, force: true }); + fs.rmSync(data, { recursive: true, force: true }); } function runElectron(executable, args, options) { @@ -193,6 +196,7 @@ function runElectron(executable, args, options) { async function main({ checkout = path.resolve(__dirname, '..'), env = process.env, clean = false, run = runCommand, launch = runElectron, fixtures = prepareFixtures, + stopBrowser = cleanupDataDir, log = console.log, warn = console.error, removeDir = dir => fs.rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }) } = {}) { const pr = env.PR; @@ -201,7 +205,7 @@ async function main({ checkout = path.resolve(__dirname, '..'), env = process.en const allowClaude = validateAllowClaude(env.ALLOW_CLAUDE, isolated); const home = env.HOME || os.homedir(); if (clean) { - cleanWorktree({ checkout, pr, home, run }); + await cleanWorktree({ checkout, pr, home, run, stopBrowser }); log(`Cleaned up worktree and data dir for PR #${pr}`); return 0; } @@ -236,10 +240,11 @@ async function main({ checkout = path.resolve(__dirname, '..'), env = process.en } let tempHome; let launchCwd; + let config; try { launchCwd = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), `sb-pr-${pr}-`))); if (isolated) tempHome = launchCwd; - const config = buildLaunch({ pr, home, env, isolated, allowClaude, tempHome, port: env.DEBUG_PORT || 9223, + config = buildLaunch({ pr, home, env, isolated, allowClaude, tempHome, port: env.DEBUG_PORT || 9223, entry: path.resolve(worktree) }); if (isolated) { fixtures(tempHome, config.env, { allowClaude }); @@ -254,7 +259,13 @@ async function main({ checkout = path.resolve(__dirname, '..'), env = process.en const executable = require(path.join(worktree, 'node_modules', 'electron')); return await launch(executable, config.args, { cwd: launchCwd, env: config.env }); } finally { - if (launchCwd) { + let stopped = true; + if (config) { + try { stopped = await stopBrowser(config.env.SWITCHBOARD_DATA_DIR); } + catch (error) { stopped = false; warn(`Browser cleanup failed: ${error.message}`); } + if (!stopped) warn(`Browser exit uncertain; retaining ${launchCwd} and ${config.env.SWITCHBOARD_DATA_DIR}. Stop the verified browser before removing them.`); + } + if (launchCwd && stopped) { try { removeDir(launchCwd); } catch (error) { diff --git a/src/main/browser/discovery.js b/src/main/browser/discovery.js new file mode 100644 index 000000000..89f6b4bd6 --- /dev/null +++ b/src/main/browser/discovery.js @@ -0,0 +1,58 @@ +'use strict'; + +const path = require('node:path'); + +function snap(file) { + return /(^|\/)snap(\/|$)|(^|\/)(snap|snapd)$/.test(file.replace(/\\/g, '/')); +} + +function executable(file, fs) { + if (!path.isAbsolute(file)) throw new Error('Browser binary must be absolute'); + let current = file; + for (let hop = 0; hop < 40; hop++) { + if (snap(current)) throw new Error('Snap browsers are unsupported; configure a native executable'); + const parts = path.resolve(current).split(path.sep); + let prefix = parts.shift() + path.sep; + let redirected = false; + for (let i = 0; i < parts.length; i++) { + prefix = path.join(prefix, parts[i]); + const stat = fs.lstatSync(prefix); + if (stat.isSymbolicLink()) { + current = path.resolve(path.dirname(prefix), fs.readlinkSync(prefix), ...parts.slice(i + 1)); + redirected = true; + break; + } + } + if (redirected) continue; + const real = fs.realpathSync(current); + if (snap(real) || /headless[_-]shell/.test(real)) throw new Error('Snap and headless-shell browsers are unsupported'); + if (!fs.statSync(real).isFile()) throw new Error('Browser is not an executable file'); + fs.accessSync(real, fs.constants?.X_OK ?? 1); + const fd = fs.openSync(real, 'r'); + const magic = Buffer.alloc(4); + try { fs.readSync(fd, magic, 0, magic.length, 0); } finally { fs.closeSync(fd); } + if (!magic.equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46]))) throw new Error(`Browser ${real} is not ELF; configure the real Chromium binary (for example /usr/lib/chromium/chromium), not its launcher script`); + return real; + } + throw new Error('Browser symlink chain is too long'); +} + +function discoverBrowser({ binaryPath = '', env = process.env, home = require('node:os').homedir(), fs = require('node:fs') } = {}) { + if (binaryPath) { + try { return { binary: executable(binaryPath, fs), source: 'configured' }; } + catch (error) { throw new Error(`Configure an absolute executable Chromium binary: ${error.message}`); } + } + const root = env.PLAYWRIGHT_BROWSERS_PATH ?? path.join(home, '.cache', 'ms-playwright'); + if (!path.isAbsolute(root)) throw new Error('PLAYWRIGHT_BROWSERS_PATH must be absolute'); + let revisions; + try { revisions = fs.readdirSync(root).filter(name => /^chromium-\d+$/.test(name)); } catch { revisions = []; } + revisions.sort((a, b) => Number(b.slice(9)) - Number(a.slice(9))); + for (const revision of revisions) { + for (const layout of ['chrome-linux64', 'chrome-linux']) { + try { return { binary: executable(path.join(root, revision, layout, 'chrome'), fs), source: 'playwright-cache' }; } catch {} + } + } + throw new Error('Install Playwright Chromium manually or configure an absolute executable browser path'); +} + +module.exports = { discoverBrowser }; diff --git a/src/main/browser/linux-process.js b/src/main/browser/linux-process.js new file mode 100644 index 000000000..dd6f97eb8 --- /dev/null +++ b/src/main/browser/linux-process.js @@ -0,0 +1,108 @@ +'use strict'; + +const path = require('node:path').posix; + +function parseStat(text) { + const end = text.lastIndexOf(')'); + const fields = text.slice(end + 1).trim().split(/\s+/); + if (end < 0 || !/^\d+$/.test(fields[19])) return null; + return { startTime: fields[19], parentPid: Number(fields[1]) }; +} + +function matchesArgv(text, binary, profile, port) { + if (text.length > 65536 || (text.match(/--user-data-dir(?:=| )/g) || []).length !== 1 || + (text.match(/--remote-debugging-port(?:=| )/g) || []).length !== 1) return false; + const args = text.split('\0').filter(Boolean); + if (args.length > 256) return false; + if (args.length > 1) return args[0] === binary && args.includes(`--user-data-dir=${profile}`) && args.includes(`--remote-debugging-port=${port}`); + const joined = args[0] || ''; + const contains = value => joined.includes(` ${value} `) || joined.endsWith(` ${value}`); + return joined.startsWith(`${binary} `) && contains(`--user-data-dir=${profile}`) && contains(`--remote-debugging-port=${port}`); +} + +function createProc({ fs = require('node:fs'), pid = process.pid, kill = process.kill.bind(process) } = {}) { + const read = file => fs.readFileSync(file, 'utf8'); + function identity(n) { + if (!Number.isSafeInteger(n) || n <= 0) return null; + try { + const stat = parseStat(read(`/proc/${n}/stat`)); + return stat ? { pid: n, ...stat, boot: read('/proc/sys/kernel/random/boot_id').trim() } : null; + } catch { return null; } + } + function alive(state) { + const actual = identity(state?.pid); + return !!actual && actual.startTime === state.startTime && actual.boot === state.boot; + } + function verify(state) { + if (!alive(state)) return false; + try { + return fs.realpathSync(`/proc/${state.pid}/exe`) === state.binary && matchesArgv(read(`/proc/${state.pid}/cmdline`), state.binary, state.profile, state.port); + } catch { return false; } + } + function listeners(port) { + const found = []; + for (const table of ['tcp', 'tcp6']) { + for (const line of read(`/proc/net/${table}`).trim().split('\n')) { + const fields = line.trim().split(/\s+/); + if (fields[3] !== '0A') continue; + const [address, hex] = fields[1].split(':'); + if (Number.parseInt(hex, 16) === port) found.push({ address, inode: fields[9], table }); + } + } + return found; + } + function listener(state) { + try { + const rows = listeners(state.port); + if (!rows.length) return 'missing'; + if (!verify(state) || rows.some(row => row.table !== 'tcp' || row.address !== '0100007F')) return 'foreign'; + const inodes = new Set(fs.readdirSync(`/proc/${state.pid}/fd`).flatMap(fd => { + try { return [fs.readlinkSync(`/proc/${state.pid}/fd/${fd}`)]; } catch { return []; } + })); + return rows.every(row => inodes.has(`socket:[${row.inode}]`)) ? 'owned' : 'foreign'; + } catch { return 'foreign'; } + } + function findBrowser(state) { + try { + for (const name of fs.readdirSync('/proc')) { + if (!/^\d+$/.test(name)) continue; + const found = { ...state, ...identity(Number(name)) }; + if (verify(found)) return found.pid; + } + } catch {} + return null; + } + function verifyDescendant(child, state) { + if (!alive(child) || child.boot !== state.boot) return false; + try { + const exe = fs.realpathSync(`/proc/${child.pid}/exe`); + if (exe === state.binary) return true; + const typeAllowed = path.dirname(exe) === path.dirname(state.binary) && /^(?:chrome_)?crashpad_handler$/.test(path.basename(exe)); + const cmdline = read(`/proc/${child.pid}/cmdline`); + if (cmdline.length > 65536) return false; + const args = cmdline.split('\0').filter(Boolean); + if (args.length > 256) return false; + if (args.length > 1) return args.includes(`--user-data-dir=${state.profile}`) || (typeAllowed && args.some(arg => /^--type=\S+$/.test(arg))); + return (typeAllowed && /(?:^| )--type=\S+(?: |$)/.test(cmdline)) || + (` ${cmdline} `).includes(` --user-data-dir=${state.profile} `); + } catch { return false; } + } + function descendants(state) { + const found = [], parents = new Set([state.pid]); + let entries; + try { entries = fs.readdirSync('/proc').filter(name => /^\d+$/.test(name)).map(name => identity(Number(name))).filter(Boolean); } catch { return found; } + for (let pass = 0; pass < entries.length; pass++) { + let added = false; + for (const entry of entries) { + if (parents.has(entry.pid) || !parents.has(entry.parentPid) || entry.boot !== state.boot) continue; + if (!verifyDescendant(entry, state)) continue; + parents.add(entry.pid); found.push(entry); added = true; + } + if (!added) break; + } + return found; + } + return { self: () => identity(pid), identity, alive, verify, listener, findBrowser, listenerPid: findBrowser, descendants, verifyDescendant, signal: kill }; +} + +module.exports = { parseStat, matchesArgv, createProc }; diff --git a/src/main/browser/managed-browser.js b/src/main/browser/managed-browser.js new file mode 100644 index 000000000..249567873 --- /dev/null +++ b/src/main/browser/managed-browser.js @@ -0,0 +1,293 @@ +'use strict'; + +const path = require('node:path'); +const { createHash } = require('node:crypto'); +const { createStorage } = require('./storage'); +const { createProc } = require('./linux-process'); +const { createLock } = require('./owner-lock'); +const { discoverBrowser } = require('./discovery'); +const transport = require('./transport'); +const { cleanEnv } = require('../shared/clean-env'); + +function browserEnv(env) { + const cleaned = cleanEnv(env, { locale: false }); + return Object.fromEntries(Object.entries(cleaned).filter(([key]) => + !/^(ELECTRON_.*|APPIMAGE.*|APPDIR|ARGV0|INVOCATION_ID|JOURNAL_STREAM|SYSTEMD_.*|NOTIFY_SOCKET|WATCHDOG_PID|WATCHDOG_USEC|CHROME_CRASHPAD_PIPE_NAME|CHROME_RESTART|SWITCHBOARD_.*|NODE_PATH|LD_LIBRARY_PATH|LD_PRELOAD)$/i.test(key))); +} + +function validState(state, profile) { + if (state === null) return null; + const positive = value => Number.isSafeInteger(value) && value > 0; + const identity = value => value && positive(value.pid) && typeof value.startTime === 'string' && /^\d+$/.test(value.startTime) && typeof value.boot === 'string' && value.boot.length > 0; + if (state.version !== 1 || !positive(state.port) || state.port > 65535 || state.profile !== profile || + (state.launcher != null && !identity(state.launcher)) || + (state.pid !== null && (!identity(state) || !identity(state.spawnedBy) || !path.isAbsolute(state.binary) || + !['child', 'scope', 'detached'].includes(state.mode) || typeof state.startedAt !== 'number' || + (state.mode === 'scope' && !/^switchboard-browser-[a-f0-9]+-\d+-[a-f0-9]+$/.test(state.unit))))) throw new Error('Invalid managed-browser state; retaining data for inspection'); + return state; +} + +function createManager({ dataDir, platform = process.platform, isPackaged = false, + fs = require('node:fs'), env = process.env, home = require('node:os').homedir(), + proc = createProc({ fs }), lock = createLock({ fs, env }), storage = createStorage({ dataDir, fs }), + discover = discoverBrowser, spawn = require('node:child_process').spawn, + request = transport.request, allocatePort = transport.allocatePort, portFree = transport.portFree, + closeBrowser = transport.closeBrowser, now = Date.now, sleep = ms => new Promise(resolve => setTimeout(resolve, ms)), +} = {}) { + let queue = Promise.resolve(), owner, state, profile, base, memo, disposed = false, quitting = false; + let result = { supported: platform === 'linux', status: 'stopped', role: null, port: null, survivesRestart: false }; + const snapshot = (status, extra = {}) => (result = { ...result, status, role: owner?.role ?? null, + port: state?.port ?? null, pid: state?.pid ?? null, mode: state?.mode ?? null, + binary: state?.binary ?? null, survivesRestart: status === 'running' && state?.mode === 'scope', error: null, notice: null, ...extra }); + const enqueue = work => { + const next = queue.then(async () => { + if (platform !== 'linux') return { ...result, supported: false, error: 'Managed browser is supported on Linux only' }; + if (disposed || quitting) return snapshot('error', { error: 'Managed browser is disposing or quitting' }); + try { return await work(); } catch (error) { return snapshot('error', { error: error.message }); } + }); + queue = next.catch(() => {}); return next; + }; + const write = () => storage.write('state.json', state); + function discoveryInputs(binaryPath) { + let candidates = [binaryPath]; + if (!binaryPath) { + const root = env.PLAYWRIGHT_BROWSERS_PATH ?? path.join(home, '.cache', 'ms-playwright'); + if (!path.isAbsolute(root)) return [root]; + try { + candidates = fs.readdirSync(root).filter(name => /^chromium-\d+$/.test(name)).sort().flatMap(name => + ['chrome-linux64', 'chrome-linux'].map(layout => path.join(root, name, layout, 'chrome'))); + } catch { return [root, null]; } + } + return candidates.map(file => { + try { + const stat = fs.statSync(file); + return [file, stat.ino, stat.mtimeMs, stat.size, stat.mode]; + } catch { return [file, null]; } + }); + } + async function initialize() { + base = storage.init(); profile = path.join(base, 'profile'); + if (owner?.role !== 'owner') owner = await lock.acquire(path.dirname(base), base); + state = validState(storage.read('state.json'), profile); + if (owner.role === 'owner') storage.prune(); + } + async function ready(candidate) { + if (!proc.verify(candidate) || proc.listener(candidate) !== 'owned') return null; + let version; + try { version = await request(candidate.port, '/json/version'); } catch { return null; } + if (!version || typeof version.Browser !== 'string' || version.Browser.length > 512 || typeof version.webSocketDebuggerUrl !== 'string') return null; + if (!proc.verify(candidate) || proc.listener(candidate) !== 'owned') return null; + return version; + } + function signal(candidate, kind) { + if (!proc.verify(candidate)) return false; + try { proc.signal(candidate.pid, kind); return true; } catch { return false; } + } + async function waitGone(candidate, ms) { + const deadline = now() + ms; + while (proc.alive(candidate) && now() < deadline) await sleep(Math.min(50, deadline - now())); + return !proc.identity(candidate.pid); + } + function reservePort() { + state = { version: 1, port: state.port, pid: null, profile }; write(); + } + function recoverPending() { + if (!state?.launchPending) return; + if (owner.role !== 'owner') throw new Error('Browser launch recovery requires its owner'); + const boot = proc.self()?.boot, pendingBoot = state.launcher?.boot || state.boot || state.spawnedBy?.boot; + if (!boot || !pendingBoot) throw new Error('Browser launch boot identity uncertain; data retained'); + if (boot === pendingBoot) { + if (!state.launcher || proc.alive(state.launcher)) throw new Error('Browser launcher is alive or its identity is uncertain; data retained'); + const pid = proc.findBrowser(state); + if (pid) { + const candidate = { ...state, ...proc.identity(pid) }; + if (!proc.verify(candidate)) throw new Error('Pending browser identity changed during recovery; data retained'); + delete candidate.launchPending; + state = candidate; write(); return; + } + } + reservePort(); + } + async function stopOwned() { + recoverPending(); + if (!state?.pid) return snapshot('stopped'); + if (!proc.alive(state)) { reservePort(); return snapshot('stopped'); } + if (!proc.verify(state) || proc.listener(state) === 'foreign') return snapshot('foreign', { error: 'Browser identity or listener ownership changed; data retained' }); + const descendants = proc.descendants(state); + if (proc.listener(state) === 'owned') { + const version = await ready(state); + if (!proc.alive(state)) { reservePort(); return snapshot('stopped'); } + if (!proc.verify(state) || proc.listener(state) === 'foreign') return snapshot('foreign', { error: 'Browser ownership changed' }); + if (proc.listener(state) === 'owned') { + if (!version) return snapshot('foreign', { error: 'Browser endpoint could not be verified; data retained' }); + try { await closeBrowser(state, version); } catch {} + } + } + let gone = await waitGone(state, 5000); + for (const [kind, delay] of [['SIGTERM', 3000], ['SIGKILL', 1000]]) { + if (gone) break; + if (!signal(state, kind)) return snapshot('foreign', { error: 'Browser identity changed before signal; data retained' }); + gone = await waitGone(state, delay); + } + if (!gone) return snapshot('error', { error: 'Browser exit uncertain; data retained' }); + for (const child of descendants) { + if (!proc.verifyDescendant(child, state)) continue; + try { if (proc.verifyDescendant(child, state)) proc.signal(child.pid, 'SIGTERM'); } catch {} + if (!await waitGone(child, 3000)) { + if (!proc.verifyDescendant(child, state)) continue; + try { if (proc.verifyDescendant(child, state)) proc.signal(child.pid, 'SIGKILL'); } catch {} + if (!await waitGone(child, 1000)) return snapshot('error', { error: 'Browser descendant exit uncertain; data retained' }); + } + } + state = { version: 1, port: state.port, pid: null, profile }; write(); return snapshot('stopped'); + } + async function start(options = {}, explicit = false) { + await initialize(); + recoverPending(); + if (state?.pid && proc.alive(state)) { + const version = await ready(state); + if (!version) return snapshot('foreign', { error: 'Existing browser identity or listener conflict; no duplicate start' }); + if (owner.role === 'owner' && state.mode === 'child' && !sameIdentity(state.spawnedBy, proc.self())) { + if (proc.alive(state.spawnedBy)) return snapshot('foreign', { error: 'Source browser spawner is still alive' }); + state.spawnedBy = { ...proc.self() }; write(); + } + return snapshot('running', { version: version.Browser }); + } + if (owner.role !== 'owner') return snapshot('stopped', { notice: 'Browser owner is not running a verified browser' }); + let notice = null; + if (!state) state = { version: 1, port: await allocatePort(), pid: null, profile }; + else { + state = { version: 1, port: state.port, pid: null, profile }; + if (!await portFree(state.port)) { state.port = await allocatePort(); notice = 'Browser port changed; restart existing sessions'; } + } + write(); + const key = JSON.stringify([options.binaryPath || '', env.PLAYWRIGHT_BROWSERS_PATH, home, discoveryInputs(options.binaryPath)]); + if (!explicit && memo?.key === key && now() - memo.at < 60000) return snapshot('error', { error: memo.error, notice }); + snapshot('starting'); + let launch; + const deadline = now() + 20000; + try { + const found = discover({ binaryPath: options.binaryPath || '', env, home, fs }); + if (!found?.binary || !path.isAbsolute(found.binary)) throw new Error('Discovery did not return an absolute executable'); + const source = found.source; + for (let attempt = 0; attempt < 3; attempt++) { + const binary = found.binary; + const args = [`--user-data-dir=${profile}`, `--remote-debugging-port=${state.port}`, '--remote-debugging-address=127.0.0.1', '--no-first-run', '--no-default-browser-check', 'about:blank']; + const hash = createHash('sha256').update(base).digest('hex').slice(0, 16); + const unit = `switchboard-browser-${hash}-${now()}-${require('node:crypto').randomBytes(4).toString('hex')}`; + let mode = isPackaged ? 'scope' : 'child', fallback = false; + while (true) { + if (quitting) throw new Error('Browser start cancelled by quit'); + const fd = storage.log(); let child, exited, spawnError; + try { + state = { ...state, launchPending: true, launcher: null, binary, mode, unit: mode === 'scope' ? unit : null, + spawnedBy: { ...proc.self() }, startedAt: now() }; write(); + const argv = mode === 'scope' ? ['--user', '--scope', '--quiet', '--collect', `--unit=${unit}`, '--', ...[binary, ...args].map(arg => arg.replace(/\$/g, () => '$$'))] : args; + try { + child = spawn(mode === 'scope' ? 'systemd-run' : binary, argv, { shell: false, detached: mode !== 'child', env: browserEnv(env), stdio: ['ignore', fd, fd], windowsHide: true }); + } catch (error) { + state = { version: 1, port: state.port, pid: null, profile }; write(); throw error; + } + child.once('exit', (code, sig) => { exited = { code, sig }; }); + child.once('error', error => { spawnError = error; }); + const launcher = proc.identity(child.pid); + state.launcher = launcher ? { pid: launcher.pid, startTime: launcher.startTime, boot: launcher.boot } : null; + write(); + if (mode !== 'child') child.unref(); + } finally { storage.close(fd); } + const candidate = { version: 1, port: state.port, profile, binary, mode, unit: mode === 'scope' ? unit : null, + spawnedBy: { ...proc.self() }, startedAt: now(), pid: null }; + launch = null; + while (now() < deadline) { + const n = mode === 'scope' ? proc.listenerPid(candidate) : child.pid; + const identity = proc.identity(n); + if (identity) { + const possible = { ...candidate, ...identity }; + if (proc.verify(possible)) { launch = possible; state = possible; write(); } + } + if (launch) { + const version = await ready(launch); + if (version) { memo = null; return snapshot('running', { version: version.Browser, source, notice }); } + } + if (quitting) { if (launch) signal(launch, 'SIGTERM'); throw new Error('Browser start cancelled by quit'); } + if (spawnError || exited) break; + if (launch && proc.listener(launch) === 'foreign') break; + await sleep(50); + } + const tail = storage.tail(); + const missingBus = mode === 'scope' && !fallback && !launch && (spawnError?.code === 'ENOENT' || + (exited?.code !== undefined && exited.code !== 0 && /Failed to connect to (?:bus|user bus)|Failed to start transient scope.*(?:bus|connection)/i.test(tail) && !/FATAL|sandbox/i.test(tail))); + if (missingBus) { fallback = true; mode = 'detached'; continue; } + if (launch) { + const collision = proc.listener(launch) === 'foreign'; + if (!signal(launch, 'SIGTERM') || !await waitGone(launch, 3000)) throw new Error('Failed launch exit uncertain; data retained'); + if (collision && attempt < 2 && now() < deadline) { + state = { version: 1, port: await allocatePort(), pid: null, profile }; write(); + notice = 'Browser port changed; restart existing sessions'; break; + } + } + if (!launch && (spawnError || exited)) { + if (spawnError && !child.pid) reservePort(); + else recoverPending(); + } + throw new Error(`Browser did not become ready: ${spawnError?.message || (exited ? `exit ${exited.code}` : '20-second start deadline')}${tail ? `; ${tail}` : ''}`); + } + } + throw new Error('Browser port collision retry budget exhausted'); + } catch (error) { + if (!launch && state?.launchPending && state.launcher && proc.alive(state.launcher)) { + try { if (proc.alive(state.launcher)) proc.signal(state.launcher.pid, 'SIGTERM'); } catch {} + } + if (launch && proc.verify(launch)) { + if (signal(launch, 'SIGTERM') && await waitGone(launch, 3000)) { + state = { version: 1, port: state.port, pid: null, profile }; + try { write(); } catch {} + } + } + memo = { key, at: now(), error: error.message }; + return snapshot('error', { error: error.message, notice }); + } + } + function stopForQuit() { + quitting = true; + if (platform !== 'linux' || owner?.role !== 'owner' || state?.mode !== 'child' || !sameIdentity(state.spawnedBy, proc.self()) || proc.listener(state) !== 'owned') return false; + return signal(state, 'SIGTERM'); + } + async function dispose() { + disposed = true; + await queue; + if (owner?.role === 'owner') await owner.release(); + owner = null; + } + return { + ensureStarted: options => enqueue(() => start(options)), + open: options => enqueue(async () => { + const current = await start(options, true); + if (current.status !== 'running' || current.role !== 'owner') return current; + try { + if (!await ready(state)) return snapshot('foreign', { error: 'Browser ownership changed before Open' }); + const pages = await request(state.port, '/json/list'); + const page = Array.isArray(pages) && pages.find(page => typeof page.id === 'string'); + if (page) await request(state.port, `/json/activate/${encodeURIComponent(page.id)}`); + else await request(state.port, '/json/new?about:blank', 'PUT'); + } catch (error) { return snapshot('running', { notice: `Browser opened; activation failed: ${error.message}` }); } + return current; + }), + stop: () => enqueue(async () => { await initialize(); return owner.role === 'owner' ? stopOwned() : snapshot(result.status, { notice: 'Only the browser owner can stop it' }); }), + getState: () => ({ ...result }), stopForQuit, dispose, + }; +} + +function sameIdentity(a, b) { return !!a && !!b && a.pid === b.pid && a.startTime === b.startTime && a.boot === b.boot; } + +async function cleanupDataDir(dataDir, options = {}) { + const fs = options.fs || require('node:fs'); + if (!fs.existsSync(path.join(dataDir, 'managed-browser'))) return true; + const manager = createManager({ ...options, dataDir }); + try { + const stopped = await manager.stop(); + return stopped.supported && stopped.role === 'owner' && stopped.status === 'stopped'; + } finally { await manager.dispose(); } +} + +module.exports = { createManager, cleanupDataDir }; diff --git a/src/main/browser/owner-lock.js b/src/main/browser/owner-lock.js new file mode 100644 index 000000000..b62bdb338 --- /dev/null +++ b/src/main/browser/owner-lock.js @@ -0,0 +1,57 @@ +'use strict'; + +const path = require('node:path'); +const { createHash } = require('node:crypto'); + +function createLock({ fs = require('node:fs'), net = require('node:net'), uid = process.getuid?.(), env = process.env } = {}) { + function safeRuntime(dir) { + try { const stat = fs.lstatSync(dir); return path.isAbsolute(dir) && !stat.isSymbolicLink() && stat.isDirectory() && stat.uid === uid && (stat.mode & 0o077) === 0; } catch { return false; } + } + function connect(socket) { + return new Promise(resolve => { + const client = net.createConnection(socket); + const finish = code => { client.destroy(); resolve(code); }; + client.once('connect', () => finish('live')); + client.once('error', error => finish(error.code)); + client.setTimeout(300, () => finish('ETIMEDOUT')); + }); + } + async function acquire(dataDir, managed) { + const hash = createHash('sha256').update(dataDir).digest('hex').slice(0, 24); + const socket = env.XDG_RUNTIME_DIR && safeRuntime(env.XDG_RUNTIME_DIR) + ? path.join(env.XDG_RUNTIME_DIR, `sb-browser-${hash}.sock`) : path.join(managed, 'owner.sock'); + if (Buffer.byteLength(socket) > 100) throw new Error('Managed browser management unavailable: owner socket path too long'); + for (let attempt = 0; attempt < 2; attempt++) { + const server = net.createServer(client => client.end()); + const error = await new Promise(resolve => { + server.once('error', resolve); + server.listen(socket, () => resolve(null)); + }); + if (!error) { + let ours; + try { fs.chmodSync(socket, 0o600); ours = fs.lstatSync(socket); } + catch (setupError) { await new Promise(resolve => server.close(resolve)); throw setupError; } + server.unref(); + return { role: 'owner', release: () => new Promise((resolve, reject) => { + let current; + try { current = fs.lstatSync(socket); } catch (e) { if (e.code !== 'ENOENT') { reject(e); return; } } + if (current && (current.dev !== ours.dev || current.ino !== ours.ino)) { reject(new Error('Owner socket identity changed; retaining lock')); return; } + server.close(resolve); + }) }; + } + if (error.code !== 'EADDRINUSE') throw new Error(`Managed browser management unavailable: ${error.message}`); + const before = fs.lstatSync(socket); + if (!before.isSocket() || before.isSymbolicLink() || (uid !== undefined && before.uid !== uid)) throw new Error('Unsafe owner socket'); + const result = await connect(socket); + if (result === 'live') return { role: 'follower' }; + if (result !== 'ECONNREFUSED' || attempt !== 0) throw new Error('Managed browser lock ownership is uncertain'); + const current = fs.lstatSync(socket); + if (current.ino !== before.ino || current.dev !== before.dev || !current.isSocket()) throw new Error('Owner socket changed during stale recovery'); + fs.unlinkSync(socket); + } + throw new Error('Managed browser lock recovery exhausted'); + } + return { acquire }; +} + +module.exports = { createLock }; diff --git a/src/main/browser/storage.js b/src/main/browser/storage.js new file mode 100644 index 000000000..70dff6c3d --- /dev/null +++ b/src/main/browser/storage.js @@ -0,0 +1,77 @@ +'use strict'; + +const path = require('node:path'); +const { randomUUID } = require('node:crypto'); + +function createStorage({ dataDir, fs = require('node:fs'), uid = process.getuid?.(), now = Date.now }) { + let root; + function checked(file, kind) { + const stat = fs.lstatSync(file); + if (stat.isSymbolicLink() || (uid !== undefined && stat.uid !== uid) || !stat[kind]()) throw new Error(`Unsafe managed-browser path: ${file}`); + return stat; + } + function directory(dir) { + if (!fs.existsSync(dir)) fs.mkdirSync(dir, { mode: 0o700 }); + checked(dir, 'isDirectory'); + fs.chmodSync(dir, 0o700); + } + function init() { + if (!path.isAbsolute(dataDir)) throw new Error('Browser data directory must be absolute'); + root = fs.realpathSync(dataDir); + checked(root, 'isDirectory'); + const managed = path.join(root, 'managed-browser'); + directory(managed); + for (const name of ['profile', 'output']) directory(path.join(managed, name)); + return managed; + } + function base() { return path.join(root, 'managed-browser'); } + function read(name) { + const file = path.join(base(), name); + try { checked(file, 'isFile'); } catch (error) { if (error.code === 'ENOENT') return null; throw error; } + const fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0)); + try { + if (fs.fstatSync(fd).size > 65536) throw new Error('Managed-browser state is too large'); + return JSON.parse(fs.readFileSync(fd, 'utf8')); + } finally { fs.closeSync(fd); } + } + function write(name, value) { + const file = path.join(base(), name); + try { checked(file, 'isFile'); } catch (error) { if (error.code !== 'ENOENT') throw error; } + const temp = path.join(base(), `.${name}.${process.pid}.${randomUUID()}.tmp`); + let fd; + try { + fd = fs.openSync(temp, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | (fs.constants.O_NOFOLLOW || 0), 0o600); + fs.fchmodSync(fd, 0o600); + fs.writeFileSync(fd, JSON.stringify(value)); + fs.fsyncSync(fd); fs.closeSync(fd); fd = undefined; + fs.renameSync(temp, file); + } finally { if (fd !== undefined) fs.closeSync(fd); try { fs.unlinkSync(temp); } catch (error) { if (error.code !== 'ENOENT') throw error; } } + } + function log() { + const file = path.join(base(), 'browser.log'); + try { checked(file, 'isFile'); } catch (error) { if (error.code !== 'ENOENT') throw error; } + const fd = fs.openSync(file, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_TRUNC | (fs.constants.O_NOFOLLOW || 0), 0o600); + fs.fchmodSync(fd, 0o600); + return fd; + } + function tail() { + const file = path.join(base(), 'browser.log'); + let fd; + try { + checked(file, 'isFile'); fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0)); + const size = fs.fstatSync(fd).size, buffer = Buffer.alloc(Math.min(4096, size)); + fs.readSync(fd, buffer, 0, buffer.length, Math.max(0, size - buffer.length)); + return buffer.toString('utf8'); + } catch { return ''; } finally { if (fd !== undefined) fs.closeSync(fd); } + } + function prune() { + const output = path.join(base(), 'output'); checked(output, 'isDirectory'); + for (const name of fs.readdirSync(output)) { + const file = path.join(output, name), stat = fs.lstatSync(file); + if (stat.isFile() && !stat.isSymbolicLink() && (uid === undefined || stat.uid === uid) && stat.mtimeMs < now() - 7 * 86400000) fs.unlinkSync(file); + } + } + return { init, base, read, write, log, tail, prune, close: fd => fs.closeSync(fd) }; +} + +module.exports = { createStorage }; diff --git a/src/main/browser/transport.js b/src/main/browser/transport.js new file mode 100644 index 000000000..40c6b8611 --- /dev/null +++ b/src/main/browser/transport.js @@ -0,0 +1,65 @@ +'use strict'; + +const http = require('node:http'); +const net = require('node:net'); +const WebSocket = require('ws'); + +function request(port, route, method = 'GET') { + return new Promise((resolve, reject) => { + let timer; + const fail = error => { clearTimeout(timer); reject(error); }; + const req = http.request({ host: '127.0.0.1', port, path: route, method, timeout: 500 }, res => { + const chunks = []; let bytes = 0; + res.on('data', chunk => { + bytes += chunk.length; + if (bytes > 65536) req.destroy(new Error('Browser response exceeds limit')); + else chunks.push(chunk); + }); + res.on('error', fail); + res.on('end', () => { + clearTimeout(timer); + if (res.statusCode !== 200) { fail(new Error(`Browser HTTP ${res.statusCode}`)); return; } + const text = Buffer.concat(chunks).toString('utf8'); + try { resolve(JSON.parse(text)); } catch { + if (route.startsWith('/json/activate/')) resolve({}); else fail(new Error('Invalid browser JSON response')); + } + }); + }); + timer = setTimeout(() => req.destroy(new Error('Browser request timed out')), 500); + req.once('timeout', () => req.destroy(new Error('Browser request timed out'))); + req.once('error', fail); req.end(); + }); +} + +function free(port) { + return new Promise(resolve => { + const server = net.createServer(); + server.once('error', () => resolve(false)); + server.listen(port, '127.0.0.1', () => server.close(() => resolve(true))); + }); +} + +function allocatePort() { + return new Promise((resolve, reject) => { + const server = net.createServer(); server.once('error', reject); + server.listen(0, '127.0.0.1', () => { const port = server.address().port; server.close(() => resolve(port)); }); + }); +} + +function closeBrowser(state, version) { + return new Promise((resolve, reject) => { + let url; + try { url = new URL(version.webSocketDebuggerUrl); } catch { reject(new Error('Invalid browser WebSocket URL')); return; } + if (url.protocol !== 'ws:' || url.hostname !== '127.0.0.1' || Number(url.port) !== state.port || url.username || url.password) { + reject(new Error('Browser WebSocket must use the owned loopback port')); return; + } + const socket = new WebSocket(url); + const timer = setTimeout(() => { socket.close(); reject(new Error('Browser close timed out')); }, 500); + socket.addEventListener('open', () => socket.send(JSON.stringify({ id: 1, method: 'Browser.close' })), { once: true }); + socket.addEventListener('error', () => { clearTimeout(timer); reject(new Error('Browser close failed')); }, { once: true }); + socket.addEventListener('message', () => { clearTimeout(timer); socket.close(); resolve(); }, { once: true }); + socket.addEventListener('close', () => { clearTimeout(timer); resolve(); }, { once: true }); + }); +} + +module.exports = { request, portFree: free, allocatePort, closeBrowser }; diff --git a/test/fixtures/fake-chromium.js b/test/fixtures/fake-chromium.js new file mode 100644 index 000000000..5506d20fe --- /dev/null +++ b/test/fixtures/fake-chromium.js @@ -0,0 +1,34 @@ +'use strict'; + +const http = require('node:http'); +const { WebSocketServer } = require('ws'); + +function createBrowser({ port = 0, delay = 0, ignoreClose = false } = {}) { + const server = http.createServer((req, res) => { + res.setHeader('content-type', 'application/json'); + if (req.url === '/json/version') res.end(JSON.stringify({ Browser: 'FakeChromium/1', webSocketDebuggerUrl: `ws://127.0.0.1:${server.address().port}/devtools/browser/fake` })); + else if (req.url === '/json/list') res.end(JSON.stringify([{ id: 'page', type: 'page' }])); + else if (req.url === '/json/activate/page' || req.url === '/json/new?about:blank') res.end('{}'); + else { res.statusCode = 404; res.end('{}'); } + }); + const sockets = new WebSocketServer({ server }); + sockets.on('connection', socket => socket.on('message', data => { + const request = JSON.parse(data); + if (request.method === 'Browser.close' && !ignoreClose) { + socket.send(JSON.stringify({ id: request.id, result: {} })); + socket.close(); server.close(); + } + })); + return new Promise(resolve => setTimeout(() => server.listen(port, '127.0.0.1', () => resolve({ server, sockets, port: server.address().port, + close: () => new Promise(done => { for (const socket of sockets.clients) socket.terminate(); sockets.close(); server.close(done); }), + })), delay)); +} + +if (require.main === module) { + if (process.env.FAKE_BROWSER_FATAL) { console.error('FATAL fake browser sandbox failure'); process.exitCode = 1; } + else createBrowser({ port: Number(process.argv.find(a => a.startsWith('--remote-debugging-port='))?.split('=')[1]), + delay: Number(process.env.FAKE_BROWSER_DELAY || 0), ignoreClose: process.env.FAKE_BROWSER_IGNORE_CLOSE === '1', + }).then(browser => { console.log(JSON.stringify({ pid: process.pid, port: browser.port })); }); +} + +module.exports = { createBrowser }; diff --git a/test/fixtures/pty-job-native.cjs b/test/fixtures/pty-job-native.cjs index 739ccfbe3..a1bfa49d9 100644 --- a/test/fixtures/pty-job-native.cjs +++ b/test/fixtures/pty-job-native.cjs @@ -163,6 +163,7 @@ async function run(mode) { const events = [], filename = require.resolve('../../main'), source = fs.readFileSync(filename, 'utf8'); const record = name => async () => { events.push(name); }; const context = vm.createContext({ Promise, Map, setTimeout, clearTimeout, shutdownPromise: null, + managedBrowser: { stopForQuit() {} }, shutdownComplete: false, appQuitting: false, TRACE: {}, updateInstalling: false, log: { error: (...args) => events.push(args.join(' ')) }, stopNonDatabaseResources() {}, closedSessions: new Map(), activeSessions: new Map(cases.map((c, i) => [String(i), c.session])), killPty, diff --git a/test/fixtures/shutdown-exit.cjs b/test/fixtures/shutdown-exit.cjs index f7a93295e..d3916d664 100644 --- a/test/fixtures/shutdown-exit.cjs +++ b/test/fixtures/shutdown-exit.cjs @@ -64,6 +64,7 @@ async function run() { let readersStopped = 0; const reader = { shutdown: async () => { readersStopped++; } }; const context = vm.createContext({ + managedBrowser: { stopForQuit() {} }, require: name => name === './shutdown-exit' ? { exitWithWatchdog: () => setTimeout(() => process.kill(process.pid, 'SIGKILL'), 1100) } : require(name), console, process: { pid: process.pid, kill(pid, signal) { diff --git a/test/managed-browser-boundaries.test.js b/test/managed-browser-boundaries.test.js new file mode 100644 index 000000000..20d80e370 --- /dev/null +++ b/test/managed-browser-boundaries.test.js @@ -0,0 +1,107 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { EventEmitter } = require('node:events'); +const { createBrowser } = require('./fixtures/fake-chromium'); +const transport = require('../src/main/browser/transport'); +const { createLock } = require('../src/main/browser/owner-lock'); + +test('loopback HTTP has a total deadline even when the server keeps sending small chunks', async t => { + const http = require('node:http'); + let timer; + const server = http.createServer((_req, res) => { + const parts = ['{', '"Browser"', ':', '"Fake"', '}']; + res.write(parts.shift()); + timer = setInterval(() => { const part = parts.shift(); if (parts.length) res.write(part); else { clearInterval(timer); res.end(part); } }, 150); + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + t.after(() => { clearInterval(timer); return new Promise(resolve => server.close(resolve)); }); + await assert.rejects(transport.request(server.address().port, '/json/version'), /timed out/); +}); + +test('fake browser exercises bounded loopback version, activation and real Browser.close exchange', async t => { + const previous = global.WebSocket; global.WebSocket = undefined; + t.after(() => { global.WebSocket = previous; }); + const browser = await createBrowser(); t.after(() => browser.close()); + const version = await transport.request(browser.port, '/json/version'); + assert.equal(version.Browser, 'FakeChromium/1'); + assert.equal((await transport.request(browser.port, '/json/list'))[0].id, 'page'); + await transport.request(browser.port, '/json/activate/page'); + await assert.doesNotReject(() => transport.closeBrowser({ port: browser.port }, version)); + await assert.rejects(transport.request(browser.port, '/json/version')); +}); + +test('close transport rejects foreign/wildcard WebSocket endpoints before connecting', async () => { + for (const url of ['ws://0.0.0.0:41000/x', 'ws://127.0.0.1:41001/x', 'ws://example.invalid:41000/x']) { + await assert.rejects(transport.closeBrowser({ port: 41000 }, { webSocketDebuggerUrl: url }), /owned loopback/); + } +}); + +function fakeSocket({ stale = false, change = false } = {}) { + let inode = 1, listening = false, unlinked = 0, attempts = 0; + let exists = stale; + const stat = () => ({ isSocket: () => true, isSymbolicLink: () => false, uid: 1, ino: inode, dev: 1 }); + const fs = { lstatSync: stat, chmodSync() {}, unlinkSync() { exists = false; unlinked++; } }; + const net = { createServer: () => { + const server = new EventEmitter(); server.unref = () => {}; + server.listen = (_path, fn) => { + attempts++; + queueMicrotask(() => { if (exists) server.emit('error', { code: 'EADDRINUSE' }); else { exists = true; listening = true; fn(); } }); + }; + server.close = fn => { listening = false; exists = false; fn(); }; + return server; + }, createConnection: () => { + const client = new EventEmitter(); client.destroy = () => {}; client.setTimeout = () => {}; + queueMicrotask(() => { if (change) inode++; if (listening) client.emit('connect'); else client.emit('error', { code: 'ECONNREFUSED' }); }); + return client; + } }; + return { fs, net, env: {}, uid: 1, stats: () => ({ unlinked, attempts }) }; +} + +test('owner socket distinguishes follower, takeover, bounded stale recovery and identity change', async () => { + const f = fakeSocket(); const lock = createLock(f); + const owner = await lock.acquire('/data', '/data/managed-browser'); + assert.equal(owner.role, 'owner'); + assert.equal((await lock.acquire('/data', '/data/managed-browser')).role, 'follower'); + await owner.release(); + const next = await lock.acquire('/data', '/data/managed-browser'); assert.equal(next.role, 'owner'); await next.release(); + const stale = fakeSocket({ stale: true }); + const recovered = await createLock(stale).acquire('/data', '/data/managed-browser'); + assert.equal(recovered.role, 'owner'); assert.deepEqual(stale.stats(), { unlinked: 1, attempts: 2 }); await recovered.release(); + const changed = fakeSocket({ stale: true, change: true }); + await assert.rejects(createLock(changed).acquire('/data', '/data/managed-browser'), /changed/); + assert.equal(changed.stats().unlinked, 0); +}); + +test('an overlong socket path refuses management without trying a listener', async () => { + const f = fakeSocket(); + await assert.rejects(createLock(f).acquire('/data', '/data/' + 'x'.repeat(150)), /too long/); + assert.equal(f.stats().attempts, 0); +}); + +test('socket permission failure closes the newly acquired listener', async () => { + const f = fakeSocket(); let closed = 0; + const create = f.net.createServer; + f.net.createServer = () => { const server = create(); const close = server.close; + server.close = done => { closed++; close(done); }; return server; }; + f.fs.chmodSync = () => { throw new Error('chmod refused'); }; + await assert.rejects(createLock(f).acquire('/data', '/data/managed-browser'), /chmod refused/); + assert.equal(closed, 1); +}); + +test('Snap intermediary symlinks cannot be hidden by a non-Snap real target', () => { + const { discoverBrowser } = require('../src/main/browser/discovery'); + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'browser-discovery-')); + try { + const binary = path.join(root, 'chrome'); fs.writeFileSync(binary, '\x7fELF', { mode: 0o755 }); + const snapPath = path.join(root, 'snap', 'launcher'); + const fake = { ...fs, lstatSync: file => file === binary ? { isSymbolicLink: () => true } : fs.lstatSync(file), + readlinkSync: file => file === binary ? snapPath : fs.readlinkSync(file), realpathSync: () => binary, + }; + assert.throws(() => discoverBrowser({ binaryPath: binary, fs: fake }), /Snap/); + } finally { fs.rmSync(root, { recursive: true, force: true }); } +}); diff --git a/test/managed-browser-shutdown.test.js b/test/managed-browser-shutdown.test.js new file mode 100644 index 000000000..20971c897 --- /dev/null +++ b/test/managed-browser-shutdown.test.js @@ -0,0 +1,41 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const vm = require('node:vm'); +const { extractFunction } = require('./app-source'); + +test('source quit signals browser synchronously after the repeat guard and before bounded drain', () => { + const filename = require.resolve('../main'); + const events = [], pending = Promise.resolve(); + const context = vm.createContext({ shutdownPromise: null, queueMicrotask, + managedBrowser: { stopForQuit: () => { events.push('browser'); } }, + boundedShutdown: () => { events.push('drain'); return pending; }, + stopWorkersForExit: async () => {}, log: { error() {} }, shutdownComplete: false, + }); + vm.runInContext(extractFunction(fs.readFileSync(filename, 'utf8'), 'shutdownForExit'), context, { filename }); + const first = context.shutdownForExit(); + assert.deepEqual(events, ['browser', 'drain']); + assert.equal(context.shutdownForExit(), first); + assert.deepEqual(events, ['browser', 'drain']); +}); + +test('browser quit exception is logged and bounded shutdown still completes once', async () => { + const filename = require.resolve('../main'); const events = []; + const context = vm.createContext({ shutdownPromise: null, + managedBrowser: { stopForQuit: () => { events.push('browser'); throw new Error('browser quit failed'); } }, + boundedShutdown: () => { events.push('drain'); return Promise.resolve(); }, + stopWorkersForExit: async () => { events.push('workers'); return true; }, + log: { error: (...args) => events.push(args.map(String).join(' ')) }, shutdownComplete: false, + }); + vm.runInContext(extractFunction(fs.readFileSync(filename, 'utf8'), 'shutdownForExit'), context, { filename }); + let first; + assert.doesNotThrow(() => { first = context.shutdownForExit(); }); + assert.equal(context.shutdownForExit(), first); + await first; + assert.equal(context.shutdownComplete, true); + assert.equal(events.filter(event => event === 'browser').length, 1); + assert.ok(events.some(event => event.includes('browser quit failed'))); + assert.ok(events.includes('drain')); assert.ok(events.includes('workers')); +}); diff --git a/test/managed-browser.test.js b/test/managed-browser.test.js new file mode 100644 index 000000000..9f976b9a3 --- /dev/null +++ b/test/managed-browser.test.js @@ -0,0 +1,638 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { EventEmitter } = require('node:events'); + +function api() { + const file = path.join(__dirname, '../src/main/browser/managed-browser.js'); + assert.ok(fs.existsSync(file), 'Electron-free lifecycle manager must exist'); + return require('../src/main/browser/managed-browser'); +} + +function setup(t, extra = {}) { + const { createManager } = api(); + const dataDir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'browser-812-'))); + t.after(() => fs.rmSync(dataDir, { recursive: true, force: true })); + const calls = [], processes = new Map(); + const self = { pid: 80, startTime: '800', boot: 'boot' }; + let pid = 100, port = 41000, time = 1000, liveLock = false; + const proc = { + self: () => self, + identity: n => processes.get(n)?.identity || (n === 80 ? self : null), + alive: identity => !!identity && proc.identity(identity.pid)?.startTime === identity.startTime && proc.identity(identity.pid)?.boot === identity.boot, + verify: state => proc.alive(state) && processes.get(state.pid)?.profile === state.profile && processes.get(state.pid)?.binary === state.binary, + listener: state => proc.verify(state) && processes.get(state.pid)?.port === state.port ? 'owned' : processes.get(state.pid)?.conflict ? 'foreign' : 'missing', + listenerPid: state => [...processes].find(([, p]) => p.port === state.port && p.profile === state.profile)?.[0], + findBrowser: state => [...processes].find(([pid]) => proc.verify({ ...state, ...proc.identity(pid) }))?.[0], + descendants: () => [], + signal: (n, signal) => { calls.push(['signal', n, signal]); processes.delete(n); }, + }; + const options = { dataDir, platform: 'linux', isPackaged: false, proc, + discover: () => ({ binary: '/fake/chrome $literal', source: 'configured' }), + allocatePort: async () => ++port, portFree: async () => true, + lock: { acquire: async () => { if (liveLock) return { role: 'follower' }; liveLock = true; return { role: 'owner', release: async () => { liveLock = false; } }; } }, + request: async (_port, route) => { calls.push(['http', route]); return route === '/json/version' + ? { Browser: 'Fake/1', webSocketDebuggerUrl: `ws://127.0.0.1:${_port}/devtools/browser/fake` } + : route === '/json/list' ? [{ id: 'page' }] : {}; }, + closeBrowser: async state => { calls.push(['close', state.pid]); processes.delete(state.pid); }, + spawn: (file, args, opts) => { + calls.push(['spawn', file, args, opts]); + const child = new EventEmitter(); child.pid = ++pid; child.unref = () => calls.push(['unref']); + const profile = args.find(a => a.startsWith('--user-data-dir='))?.slice('--user-data-dir='.length); + const assignedPort = Number(args.find(a => a.startsWith('--remote-debugging-port='))?.split('=')[1]); + processes.set(pid, { identity: { pid, startTime: String(pid * 10), boot: 'boot' }, profile, port: assignedPort, binary: '/fake/chrome $literal' }); + queueMicrotask(() => child.emit('spawn')); + return child; + }, + now: () => time, sleep: async ms => { time += ms; }, env: { DISPLAY: ':1', DBUS_SESSION_BUS_ADDRESS: 'bus', APPIMAGE: 'bad', ELECTRON_BAD: 'bad', CLAUDECODE: 'bad' }, + ...extra, + }; + const manager = createManager(options); + t.after(() => manager.dispose()); + return { manager, options, dataDir, calls, processes, proc, self, advance: ms => { time += ms; } }; +} + +test('construction is inert and unsupported Windows operations refuse without spawn', async t => { + const f = setup(t, { platform: 'win32', spawn: () => assert.fail('Windows must not spawn') }); + assert.equal(fs.existsSync(path.join(f.dataDir, 'managed-browser')), false); + assert.equal((await f.manager.open()).supported, false); + assert.equal((await f.manager.stop()).supported, false); + assert.equal(fs.existsSync(path.join(f.dataDir, 'managed-browser')), false); +}); + +test('source child start is serialized, private and preserves a stable port across Stop/Open', async t => { + const f = setup(t); + const [a, b] = await Promise.all([f.manager.ensureStarted(), f.manager.ensureStarted()]); + assert.equal(a.status, 'running'); assert.equal(b.port, a.port); + assert.equal(f.calls.filter(c => c[0] === 'spawn').length, 1); + assert.equal(a.mode, 'child'); assert.equal(a.survivesRestart, false); + const launch = f.calls.find(c => c[0] === 'spawn'); + assert.ok(launch[2].includes('--remote-debugging-address=127.0.0.1')); + assert.ok(launch[2].includes(`--user-data-dir=${path.join(f.dataDir, 'managed-browser/profile')}`)); + assert.equal(launch[3].shell, false); + assert.equal(launch[3].env.DISPLAY, ':1'); assert.equal(launch[3].env.DBUS_SESSION_BUS_ADDRESS, 'bus'); + for (const key of ['APPIMAGE', 'ELECTRON_BAD', 'CLAUDECODE']) assert.equal(launch[3].env[key], undefined); + assert.ok(!launch[2].some(a => /no-sandbox|disable-web-security|remote-allow-origins|headless/.test(a))); + await f.manager.stop(); + assert.equal((await f.manager.open()).port, a.port); +}); + +test('Stop queued during a start finishes stopped and Open activates the existing page', async t => { + const f = setup(t); + const starting = f.manager.ensureStarted(), stopping = f.manager.stop(); + await starting; + assert.equal((await stopping).status, 'stopped'); + await f.manager.open(); + assert.ok(f.calls.some(c => c[1] === '/json/activate/page')); +}); + +test('packaged scope escapes dollars, detaches/unrefs and survives synchronous quit', async t => { + const f = setup(t, { isPackaged: true }); + const result = await f.manager.open(); + assert.equal(result.mode, 'scope'); assert.equal(result.survivesRestart, true); + const launch = f.calls.find(c => c[0] === 'spawn'); + assert.equal(launch[1], 'systemd-run'); assert.ok(launch[2].includes('--scope')); + assert.ok(launch[2].includes('/fake/chrome $$literal')); assert.equal(launch[3].detached, true); + assert.ok(f.calls.some(c => c[0] === 'unref')); + f.manager.stopForQuit(); + assert.equal(f.calls.filter(c => c[0] === 'signal').length, 0); +}); + +test('missing binary reserves a persistent endpoint before resolution and memo clears on path change or Open', async t => { + let attempts = 0; + const f = setup(t, { discover: () => { attempts++; throw new Error('Install Chromium or configure an absolute executable'); } }); + const first = await f.manager.ensureStarted({ binaryPath: '/one' }); + assert.equal(first.status, 'error'); assert.ok(first.port > 0); + assert.equal(JSON.parse(fs.readFileSync(path.join(f.dataDir, 'managed-browser/state.json'))).port, first.port); + await f.manager.ensureStarted({ binaryPath: '/one' }); assert.equal(attempts, 1); + await f.manager.ensureStarted({ binaryPath: '/two' }); assert.equal(attempts, 2); + await f.manager.open({ binaryPath: '/two' }); assert.equal(attempts, 3); +}); + +test('changed discovered cache inputs clear automatic failure memo', async t => { + let attempts = 0; + const f = setup(t, { discover: () => { attempts++; throw new Error('missing browser'); } }); + const root = path.join(f.dataDir, 'cache'); fs.mkdirSync(root); f.options.env.PLAYWRIGHT_BROWSERS_PATH = root; + await f.manager.ensureStarted(); await f.manager.ensureStarted(); assert.equal(attempts, 1); + fs.mkdirSync(path.join(root, 'chromium-1234')); + await f.manager.ensureStarted(); assert.equal(attempts, 2); +}); + +test('foreign persisted port is replaced with a restart notice and never closed or signalled', async t => { + const f = setup(t); + const first = await f.manager.open(); await f.manager.stop(); + f.options.portFree = async () => false; + const second = api().createManager(f.options); await f.manager.dispose(); + t.after(() => second.dispose()); + const result = await second.open(); + assert.notEqual(result.port, first.port); assert.match(result.notice, /restart/i); +}); + +test('bind/spawn collision cleans only its own launch and retries on a new port', async t => { + const f = setup(t); const realSpawn = f.options.spawn; + let count = 0; + const manager = api().createManager({ ...f.options, spawn: (...args) => { + const child = realSpawn(...args); + if (++count === 1) { const record = f.processes.get(child.pid); record.port = 1; record.conflict = true; } + return child; + } }); + t.after(() => manager.dispose()); + const running = await manager.open(); + assert.equal(running.status, 'running'); assert.equal(count, 2); + assert.match(running.notice, /restart/i); + assert.deepEqual(f.calls.filter(c => c[0] === 'signal'), [['signal', 101, 'SIGTERM']]); +}); + +test('foreign identity cannot be adopted from a successful version response', async t => { + const f = setup(t); const start = await f.manager.open(); + f.processes.get(start.pid).profile += '-old'; + const calls = f.calls.length; + assert.equal((await f.manager.ensureStarted()).status, 'foreign'); + assert.equal((await f.manager.stop()).status, 'foreign'); + assert.equal(f.calls.slice(calls).some(c => ['signal', 'close'].includes(c[0])), false); +}); + +test('source quit sends verified positive PID TERM synchronously only for its own spawner', async t => { + const f = setup(t); const state = await f.manager.open(); + const result = f.manager.stopForQuit(); + assert.equal(result, true); + assert.deepEqual(f.calls.at(-1), ['signal', state.pid, 'SIGTERM']); +}); + +test('quit refuses reused browser PID and a changed spawner identity', async t => { + for (const changed of ['browser', 'spawner']) { + const f = setup(t); const state = await f.manager.open(); + if (changed === 'browser') f.processes.get(state.pid).identity.startTime = 'reused'; + else f.self.startTime = 'changed'; + assert.equal(f.manager.stopForQuit(), false); + assert.equal(f.calls.some(c => c[0] === 'signal'), false); + } +}); + +test('Browser.close precedes TERM and KILL, each escalation rechecks PID identity', async t => { + const f = setup(t, { closeBrowser: async state => { f.calls.push(['close', state.pid]); } }); + await f.manager.open(); + f.proc.signal = (pid, signal) => { + f.calls.push(['signal', pid, signal]); + f.processes.get(pid).identity.startTime = 'reused'; + }; + const stopped = await f.manager.stop(); + assert.equal(stopped.status, 'foreign'); + assert.deepEqual(f.calls.filter(c => c[0] === 'signal').map(c => c[2]), ['SIGTERM']); + assert.ok(f.calls.findIndex(c => c[0] === 'close') < f.calls.findIndex(c => c[0] === 'signal')); +}); + +test('a second manager is follower, never spawns/stops/prunes, then takes over after owner disposal', async t => { + const f = setup(t); await f.manager.open(); + const follower = api().createManager(f.options); t.after(() => follower.dispose()); + assert.equal((await follower.open()).role, 'follower'); + const count = f.calls.length; + assert.equal((await follower.stop()).role, 'follower'); + assert.equal(f.calls.length, count); + await f.manager.dispose(); + const taken = await follower.ensureStarted(); + assert.equal(taken.role, 'owner', JSON.stringify(taken)); + assert.equal(f.calls.filter(c => c[0] === 'spawn').length, 1); +}); + +test('storage refuses hostile state symlinks and errors remain recoverable status', async t => { + const f = setup(t); await f.manager.open(); await f.manager.stop(); + const state = path.join(f.dataDir, 'managed-browser/state.json'); + fs.unlinkSync(state); + const outside = path.join(f.dataDir, 'outside'); fs.writeFileSync(outside, 'untouched'); + try { fs.symlinkSync(outside, state); } catch (e) { if (e.code === 'EPERM') { t.skip('Windows symlink privilege unavailable'); return; } throw e; } + assert.equal((await f.manager.open()).status, 'error'); + assert.equal(fs.readFileSync(outside, 'utf8'), 'untouched'); +}); + +test('Linux discovery sorts revisions numerically and honors explicit roots and invalid paths', t => { + const f = setup(t); + const { discoverBrowser } = require('../src/main/browser/discovery'); + const root = path.join(f.dataDir, 'cache'); + const modes = new Map(); + const posixFs = { ...fs, + writeFileSync: (file, data, options) => { modes.set(file, options?.mode ?? 0o666); fs.writeFileSync(file, data, options); }, + accessSync: (file, mode) => { + assert.equal(mode, fs.constants.X_OK); + if (!(modes.get(file) & 0o111)) throw Object.assign(new Error('POSIX X_OK: EACCES'), { code: 'EACCES' }); + }, + }; + for (const rev of [999, 1234]) { + const binary = path.join(root, `chromium-${rev}`, 'chrome-linux64', 'chrome'); + fs.mkdirSync(path.dirname(binary), { recursive: true }); posixFs.writeFileSync(binary, '\x7fELF', { mode: 0o755 }); + } + let result; + assert.doesNotThrow(() => { result = discoverBrowser({ fs: posixFs, home: f.dataDir, env: { PLAYWRIGHT_BROWSERS_PATH: root } }); }, 'fake executables must pass POSIX X_OK on Windows too'); + assert.ok(result.binary.includes('1234')); + assert.throws(() => discoverBrowser({ fs, binaryPath: 'relative', home: f.dataDir, env: {} }), /absolute/); + assert.throws(() => discoverBrowser({ fs, binaryPath: path.join(root, 'missing'), home: f.dataDir, env: { PLAYWRIGHT_BROWSERS_PATH: root } }), /executable/); + assert.throws(() => discoverBrowser({ fs, home: f.dataDir, env: { PLAYWRIGHT_BROWSERS_PATH: path.join(root, 'absent') } }), /Install/); +}); + +test('proc identity validates stat field 22, exact profile, executable, boot, listener inode and address', t => { + setup(t); + const { parseStat, matchesArgv, createProc } = require('../src/main/browser/linux-process'); + assert.equal(parseStat('100 (name with ) parens) S ' + Array.from({ length: 20 }, (_, i) => i + 4).join(' ')).startTime, '22'); + for (const sep of ['\0', ' ']) { + assert.equal(matchesArgv(['/chrome', '--user-data-dir=/data/profile', '--remote-debugging-port=41000'].join(sep), '/chrome', '/data/profile', 41000), true); + assert.equal(matchesArgv(['/chrome', '--user-data-dir=/data/profile-old', '--remote-debugging-port=41000'].join(sep), '/chrome', '/data/profile', 41000), false); + assert.equal(matchesArgv(['/chrome', '--user-data-dir=/data/profile', '--user-data-dir=/other', '--remote-debugging-port=41000'].join(sep), '/chrome', '/data/profile', 41000), false); + } + const state = { pid: 100, startTime: '22', boot: 'b', binary: '/chrome', profile: '/data/profile', port: 41000 }; + let address = '0100007F', inode = '99', start = '22', boot = 'b'; + const procFs = { readFileSync: file => { + if (file.endsWith('boot_id')) return boot; + if (file.endsWith('/stat')) return '100 (chrome) S ' + [...Array.from({ length: 18 }, (_, i) => i + 4), start].join(' '); + if (file.endsWith('/cmdline')) return '/chrome\0--user-data-dir=/data/profile\0--remote-debugging-port=41000\0'; + if (file.endsWith('/tcp')) return ` 0: ${address}:A028 00000000:0000 0A 0:0 0:0 0 0 0 99`; + if (file.endsWith('/tcp6')) return ''; + throw new Error(file); + }, readlinkSync: file => file.endsWith('/exe') ? '/chrome' : `socket:[${inode}]`, readdirSync: () => ['1'], realpathSync: file => file.endsWith('/exe') ? '/chrome' : file }; + const proc = createProc({ fs: procFs }); + assert.equal(proc.verify(state), true); assert.equal(proc.listener(state), 'owned'); + inode = '98'; assert.equal(proc.listener(state), 'foreign'); + inode = '99'; address = '00000000'; assert.equal(proc.listener(state), 'foreign'); + start = '23'; assert.equal(proc.verify(state), false); + start = '22'; boot = 'other'; assert.equal(proc.verify(state), false); +}); + +test('a verified missing user bus falls back once; Chromium FATAL never falls back', async t => { + for (const fatal of [false, true]) { + const f = setup(t, { isPackaged: true }); + const realSpawn = f.options.spawn; + const manager = api().createManager({ ...f.options, spawn: (file, args, options) => { + if (file !== 'systemd-run') return realSpawn(file, args, options); + f.calls.push(['spawn', file, args, options]); + fs.writeSync(options.stdio[1], fatal ? 'FATAL sandbox initialization failed' : 'Failed to connect to bus: No medium found'); + const child = new EventEmitter(); child.pid = 77; child.unref = () => {}; + queueMicrotask(() => child.emit('exit', 1)); return child; + } }); + t.after(() => manager.dispose()); + const result = await manager.open(); + if (!fatal) assert.equal(result.mode, 'detached'); + assert.equal(result.status, fatal ? 'error' : 'running'); + assert.equal(f.calls.filter(c => c[0] === 'spawn').length, fatal ? 1 : 2); + assert.equal(result.survivesRestart, false); + } +}); + +test('ambiguous scope timeout retains pending launch until an owner rescan proves it absent', async t => { + const f = setup(t, { isPackaged: true, spawn: () => { + f.processes.set(200, { identity: { pid: 200, startTime: '2000', boot: 'boot' } }); + const child = new EventEmitter(); child.pid = 200; child.unref = () => {}; return child; + } }); + f.proc.signal = (pid, kind) => f.calls.push(['signal', pid, kind]); + const result = await f.manager.open(); + assert.equal(result.status, 'error'); + const stored = JSON.parse(fs.readFileSync(path.join(f.dataDir, 'managed-browser/state.json'))); + assert.equal(stored.launchPending, true); + f.processes.delete(200); + assert.equal((await f.manager.stop()).status, 'stopped'); + assert.equal(JSON.parse(fs.readFileSync(path.join(f.dataDir, 'managed-browser/state.json'))).launchPending, undefined); + assert.equal((await f.manager.open()).status, 'error'); +}); + +test('an unavailable or overlong owner lock never becomes an unlocked writer', async t => { + const f = setup(t, { lock: { acquire: async () => { throw new Error('owner socket path too long'); } } }); + const status = await f.manager.open(); + assert.equal(status.status, 'error'); assert.match(status.error, /socket/); + assert.equal(f.calls.length, 0); + assert.equal(fs.existsSync(path.join(f.dataDir, 'managed-browser/state.json')), false); +}); + +test('existing directories are hardened and atomic state writes leave no temporary files', async t => { + const f = setup(t); + const { createStorage } = require('../src/main/browser/storage'); + const modes = []; + const storage = createStorage({ dataDir: f.dataDir, fs: { ...fs, chmodSync: (file, mode) => { modes.push([file, mode]); fs.chmodSync(file, mode); } } }); + const base = storage.init(); storage.write('state.json', { port: 1 }); + storage.write('state.json', { port: 2 }); + assert.ok(modes.filter(([, mode]) => mode === 0o700).length >= 3); + assert.deepEqual(storage.read('state.json'), { port: 2 }); + assert.equal(fs.readdirSync(base).some(file => file.endsWith('.tmp')), false); + if (process.platform === 'linux') assert.equal(fs.statSync(path.join(base, 'state.json')).mode & 0o777, 0o600); +}); + +test('interleaved state publishers use unique temporary names and preserve complete JSON', t => { + const f = setup(t); + const { createStorage } = require('../src/main/browser/storage'); + let interleave = false, storage; + const proxy = { ...fs, openSync: (file, ...args) => { + const fd = fs.openSync(file, ...args); + if (interleave && file.endsWith('.tmp')) { interleave = false; storage.write('state.json', { writer: 'inner' }); } + return fd; + } }; + storage = createStorage({ dataDir: f.dataDir, fs: proxy }); const base = storage.init(); + interleave = true; + assert.doesNotThrow(() => storage.write('state.json', { writer: 'outer' })); + assert.deepEqual(storage.read('state.json'), { writer: 'outer' }); + assert.equal(fs.readdirSync(base).some(name => name.endsWith('.tmp')), false); +}); + +test('quit cannot signal after loss of listener ownership, and followers never signal on quit', async t => { + const f = setup(t); const running = await f.manager.open(); + f.processes.get(running.pid).port = 42; + assert.equal(f.manager.stopForQuit(), false); + assert.equal(f.calls.some(c => c[0] === 'signal'), false); + const follower = api().createManager(f.options); t.after(() => follower.dispose()); + await follower.ensureStarted(); assert.equal(follower.stopForQuit(), false); +}); + +test('a follower of a running source browser cannot signal it on quit', async t => { + const f = setup(t); await f.manager.open(); + const follower = api().createManager(f.options); t.after(() => follower.dispose()); + assert.equal((await follower.ensureStarted()).status, 'running'); + assert.equal(follower.stopForQuit(), false); + assert.equal(f.calls.some(c => c[0] === 'signal'), false); +}); + +test('failed state publication returns an error and never spawns', async t => { + const f = setup(t); + const manager = api().createManager({ ...f.options, fs: { ...fs, renameSync: () => { throw new Error('write failed'); } } }); + t.after(() => manager.dispose()); + let status; + await assert.doesNotReject(async () => { status = await manager.open(); }); + assert.match(status.error, /write failed/); + assert.equal(f.calls.some(c => c[0] === 'spawn'), false); +}); + +test('publication failure after spawn cleans the verified launch before returning an error', async t => { + const f = setup(t); let publications = 0; + const manager = api().createManager({ ...f.options, fs: { ...fs, renameSync: (...args) => { + if (++publications === 3) throw new Error('publication failed after spawn'); + return fs.renameSync(...args); + } } }); + t.after(() => manager.dispose()); + let result; await assert.doesNotReject(async () => { result = await manager.open(); }); + assert.equal(result.status, 'error'); + assert.equal(f.processes.size, 0); + assert.deepEqual(f.calls.filter(c => c[0] === 'signal'), [['signal', 101, 'SIGTERM']]); +}); + +test('a synchronous spawn refusal clears pending launch so explicit Open can retry', async t => { + const f = setup(t); let failed = false; + const manager = api().createManager({ ...f.options, spawn: (...args) => { + if (!failed) { failed = true; throw new Error('spawn refused'); } + return f.options.spawn(...args); + } }); + t.after(() => manager.dispose()); + assert.match((await manager.open()).error, /spawn refused/); + assert.equal((await manager.open()).status, 'running'); +}); + +test('pruning removes only ordinary old output files and retains recent files and profile', async t => { + const f = setup(t); + const { createStorage } = require('../src/main/browser/storage'); + const storage = createStorage({ dataDir: f.dataDir }); const base = storage.init(); + for (const name of ['old', 'recent']) fs.writeFileSync(path.join(base, 'output', name), 'keep'); + const old = new Date(Date.now() - 8 * 86400000); fs.utimesSync(path.join(base, 'output', 'old'), old, old); + fs.writeFileSync(path.join(base, 'profile', 'login'), 'keep'); + storage.prune(); + assert.equal(fs.existsSync(path.join(base, 'output', 'old')), false); + assert.equal(fs.existsSync(path.join(base, 'output', 'recent')), true); + assert.equal(fs.readFileSync(path.join(base, 'profile', 'login'), 'utf8'), 'keep'); +}); + +test('source orphan adoption requires dead spawner and records new spawner before quit', async t => { + const f = setup(t); const running = await f.manager.open(); + await f.manager.dispose(); + const file = path.join(f.dataDir, 'managed-browser/state.json'); + const stored = JSON.parse(fs.readFileSync(file)); stored.spawnedBy = { pid: 300, startTime: '3000', boot: 'boot' }; + fs.writeFileSync(file, JSON.stringify(stored)); + f.processes.set(300, { identity: stored.spawnedBy }); + const manager = api().createManager(f.options); t.after(() => manager.dispose()); + assert.equal((await manager.ensureStarted()).status, 'foreign'); + f.processes.delete(300); + assert.equal((await manager.ensureStarted()).status, 'running'); + assert.deepEqual(JSON.parse(fs.readFileSync(file)).spawnedBy, f.self); + assert.equal(manager.stopForQuit(), true); + assert.deepEqual(f.calls.at(-1), ['signal', running.pid, 'SIGTERM']); +}); + +test('Linux procfs parser agrees with independent uptime oracle', { skip: process.platform !== 'linux' && 'real Linux procfs is unavailable on Windows' }, () => { + const { createProc } = require('../src/main/browser/linux-process'); + const identity = createProc().self(); + const { execFileSync } = require('node:child_process'); + const hz = Number(execFileSync('getconf', ['CLK_TCK'], { encoding: 'utf8' })); + const uptime = Number(fs.readFileSync('/proc/uptime', 'utf8').split(' ')[0]); + const age = uptime - Number(identity.startTime) / hz; + assert.ok(Math.abs(age - process.uptime()) < 5); +}); + +for (const changed of ['reused PID', 'different boot']) { + for (const operation of ['start', 'stop', 'cleanup']) { + test(`stale ${changed} resets the reservation during ${operation} without touching its replacement`, async t => { + const f = setup(t); const first = await f.manager.open(); + await f.manager.dispose(); + const replacement = f.processes.get(first.pid); + if (changed === 'reused PID') replacement.identity.startTime = '99999'; + else { f.self.boot = 'new-boot'; replacement.identity.boot = 'new-boot'; } + const manager = api().createManager(f.options); t.after(() => manager.dispose()); + const before = f.calls.length; + if (operation === 'cleanup') assert.equal(await api().cleanupDataDir(f.dataDir, f.options), true); + else assert.equal((await (operation === 'start' ? manager.open() : manager.stop())).status, operation === 'start' ? 'running' : 'stopped'); + const stored = JSON.parse(fs.readFileSync(path.join(f.dataDir, 'managed-browser/state.json'))); + assert.equal(stored.port, first.port); + assert.equal(operation === 'start' ? stored.pid !== first.pid : stored.pid === null, true); + assert.equal(f.processes.get(first.pid), replacement); + assert.equal(f.calls.slice(before).some(c => ['signal', 'close'].includes(c[0]) && c[1] === first.pid), false); + }); + } +} + +for (const recovery of ['adopt', 'same boot absent', 'different boot']) { + test(`pending launch recovery: ${recovery}`, async t => { + const f = setup(t); const spawn = f.options.spawn; let first = true; + const manager = api().createManager({ ...f.options, spawn: (...args) => { + const child = spawn(...args); + if (first) { first = false; f.processes.get(child.pid).binary = '/wrapper/sh'; } + return child; + } }); + t.after(() => manager.dispose()); + assert.equal((await manager.open()).status, 'error'); + const file = path.join(f.dataDir, 'managed-browser/state.json'); + const pending = JSON.parse(fs.readFileSync(file)); assert.equal(pending.launchPending, true); + f.processes.delete(101); + if (recovery === 'adopt') { + f.processes.set(220, { identity: { pid: 220, startTime: '2200', boot: 'boot' }, binary: pending.binary, profile: pending.profile, port: pending.port }); + } else if (recovery === 'different boot') { + f.self.boot = 'new-boot'; + f.proc.findBrowser = () => assert.fail('a pending launch from another boot must not be scanned or adopted'); + } + if (recovery === 'adopt') { + const running = await manager.ensureStarted(); + assert.equal(running.status, 'running'); assert.equal(running.pid, 220); + assert.equal(f.calls.filter(c => c[0] === 'spawn').length, 1); + } else { + assert.equal((await manager.stop()).status, 'stopped'); + assert.equal(JSON.parse(fs.readFileSync(file)).pid, null); + assert.equal((await manager.open()).status, 'running'); + } + assert.equal(JSON.parse(fs.readFileSync(file)).launchPending, undefined); + }); +} + +test('discovery refuses executable shell wrappers and names the real ELF binary to configure', t => { + const f = setup(t); const { discoverBrowser } = require('../src/main/browser/discovery'); + const binary = path.join(f.dataDir, 'chromium'); + fs.writeFileSync(binary, '#!/bin/sh\nexec /usr/lib/chromium/chromium "$@"\n', { mode: 0o755 }); + assert.throws(() => discoverBrowser({ binaryPath: binary }), /ELF.*real.*binary.*\/usr\/lib\/chromium\/chromium/); +}); + +test('an exited launcher cannot clear a pending browser that the owner scan can adopt', async t => { + const f = setup(t); const spawn = f.options.spawn; + const manager = api().createManager({ ...f.options, spawn: (...args) => { + const child = spawn(...args); const browser = { ...f.processes.get(child.pid) }; + f.processes.get(child.pid).binary = '/wrapper/sh'; + queueMicrotask(() => { + f.processes.delete(child.pid); + f.processes.set(220, { ...browser, identity: { pid: 220, startTime: '2200', boot: 'boot' } }); + child.emit('exit', 0); + }); return child; + } }); + t.after(() => manager.dispose()); + await manager.open(); + const stored = JSON.parse(fs.readFileSync(path.join(f.dataDir, 'managed-browser/state.json'))); + assert.equal(stored.pid, 220, 'exited launcher must not erase the live browser reservation'); + assert.equal(stored.launchPending, undefined); + assert.equal((await manager.ensureStarted()).status, 'running'); + assert.equal(f.calls.filter(c => c[0] === 'spawn').length, 1); +}); + +for (const outcome of ['exits', 'needs TERM', 'PID reused']) { + test(`stop with verified identity and missing listener ${outcome}`, async t => { + const f = setup(t); const running = await f.manager.open(); + let waited = 0; + f.processes.get(running.pid).port = null; + const manager = api().createManager({ ...f.options, sleep: async ms => { + waited += ms; + f.advance(ms); + if (outcome === 'exits') f.processes.delete(running.pid); + if (outcome === 'PID reused') f.processes.get(running.pid).identity.startTime = 'reused'; + } }); + await f.manager.dispose(); t.after(() => manager.dispose()); + const stopped = await manager.stop(); + assert.ok(waited > 0, 'missing listener must allow a bounded wait for the verified browser to exit'); + assert.equal(stopped.status, outcome === 'PID reused' ? 'foreign' : 'stopped'); + assert.equal(f.calls.some(c => c[0] === 'close'), false); + assert.deepEqual(f.calls.filter(c => c[0] === 'signal'), outcome === 'needs TERM' ? [['signal', running.pid, 'SIGTERM']] : []); + }); +} + +test('Stop leaves unrelated descendants alive and rechecks browser markers before signalling', async t => { + const f = setup(t); const running = await f.manager.open(); + const { createProc } = require('../src/main/browser/linux-process'); + const rows = new Map([ + [running.pid, { parentPid: 80, exe: running.binary, argv: [running.binary, `--user-data-dir=${path.join(f.dataDir, 'managed-browser/profile')}`, `--remote-debugging-port=${running.port}`] }], + [201, { parentPid: running.pid, exe: '/native/host', argv: ['/native/host'] }], + [202, { parentPid: running.pid, exe: running.binary, argv: [running.binary] }], + [203, { parentPid: 201, exe: '/helper', argv: ['/helper', '--type=renderer'] }], + [204, { parentPid: running.pid, exe: '/helper', argv: ['/helper', `--user-data-dir=${path.join(f.dataDir, 'managed-browser/profile')}`] }], + [205, { parentPid: running.pid, exe: '/download', argv: ['/download', `--user-data-dir=${path.join(f.dataDir, 'managed-browser/profile')}-other`, '--typewriter=yes'] }], + [206, { parentPid: running.pid, exe: running.binary, argv: [running.binary] }], + ]); + const procFs = { + readdirSync: () => [...rows.keys()].map(String), + realpathSync: file => rows.get(Number(file.split('/')[2])).exe, + readFileSync: file => { + if (file.endsWith('boot_id')) return 'boot'; + const pid = Number(file.split('/')[2]), row = rows.get(pid); + if (!row) throw new Error('ESRCH'); + if (file.endsWith('/stat')) return `${pid} (name) S ${row.parentPid} ${Array(17).fill('0').join(' ')} ${pid * 10}`; + if (file.endsWith('/cmdline')) return row.argv.join('\0') + '\0'; + throw new Error(file); + }, + }; + const proc = createProc({ fs: procFs, kill: (pid, kind) => { f.calls.push(['signal', pid, kind]); rows.delete(pid); } }); + f.proc.descendants = state => proc.descendants(state); + f.proc.alive = state => state.pid === running.pid ? f.processes.has(state.pid) : proc.alive(state); + f.proc.identity = pid => pid === running.pid ? f.processes.get(pid)?.identity : proc.identity(pid); + f.proc.verifyDescendant = (child, state) => proc.verifyDescendant(child, state); + f.proc.signal = proc.signal; + f.options.closeBrowser = async state => { + f.processes.delete(state.pid); rows.delete(state.pid); + rows.get(206).exe = '/download'; rows.get(206).argv = ['/download']; + }; + await f.manager.dispose(); + const manager = api().createManager(f.options); t.after(() => manager.dispose()); + assert.equal((await manager.stop()).status, 'stopped'); + assert.deepEqual(f.calls.filter(c => c[0] === 'signal').map(c => c[1]), [202, 204]); + assert.deepEqual([...rows.keys()], [201, 203, 205, 206]); +}); + +test('a live timed-out launcher blocks Stop, cleanup and duplicate Open without losing data', async t => { + const f = setup(t, { isPackaged: true, spawn: () => { + f.calls.push(['spawn']); + f.processes.set(200, { identity: { pid: 200, startTime: '2000', boot: 'boot' } }); + const child = new EventEmitter(); child.pid = 200; child.unref = () => {}; return child; + } }); + f.proc.signal = (pid, kind) => f.calls.push(['signal', pid, kind]); + assert.equal((await f.manager.open()).status, 'error'); + const file = path.join(f.dataDir, 'managed-browser/state.json'); + const before = fs.readFileSync(file, 'utf8'); + const profileFile = path.join(f.dataDir, 'managed-browser/profile/keep'); + fs.writeFileSync(profileFile, 'signed-in data'); + assert.equal((await f.manager.stop()).status, 'error', 'live launcher must block Stop'); + assert.equal(fs.readFileSync(file, 'utf8'), before); + await f.manager.dispose(); + assert.equal(await api().cleanupDataDir(f.dataDir, f.options), false, 'live launcher must block cleanup'); + assert.equal(fs.readFileSync(file, 'utf8'), before); + assert.equal(fs.readFileSync(profileFile, 'utf8'), 'signed-in data'); + const next = api().createManager(f.options); t.after(() => next.dispose()); + assert.equal((await next.open()).status, 'error'); + assert.equal(f.calls.filter(c => c[0] === 'spawn').length, 1); + const pending = JSON.parse(before); + assert.deepEqual(pending.launcher, { pid: 200, startTime: '2000', boot: 'boot' }); + assert.deepEqual(f.calls.filter(c => c[0] === 'signal'), [['signal', 200, 'SIGTERM']]); +}); + +test('an unverified timed-out launcher receives TERM only after its identity verifies', async t => { + const f = setup(t, { isPackaged: true, spawn: () => { + f.processes.set(200, { identity: { pid: 200, startTime: '2000', boot: 'boot' } }); + const child = new EventEmitter(); child.pid = 200; child.unref = () => {}; return child; + } }); + assert.equal((await f.manager.open()).status, 'error'); + assert.deepEqual(f.calls.filter(c => c[0] === 'signal'), [['signal', 200, 'SIGTERM']], 'unverified timeout must terminate its identity-verified launcher'); + assert.equal(f.processes.has(200), false); +}); + +test('a launcher whose PID was reused is never signalled after its start deadline', async t => { + const f = setup(t, { isPackaged: true, spawn: () => { + f.processes.set(200, { identity: { pid: 200, startTime: '2000', boot: 'boot' } }); + const child = new EventEmitter(); child.pid = 200; child.unref = () => {}; return child; + }, sleep: async ms => { f.advance(ms); f.processes.get(200).identity.startTime = '3000'; } }); + assert.equal((await f.manager.open()).status, 'error'); + assert.equal(f.calls.some(c => c[0] === 'signal'), false); + assert.equal((await f.manager.stop()).status, 'stopped'); + assert.equal(f.processes.get(200).identity.startTime, '3000'); +}); + +test('descendant traversal stops at foreign parents and type markers need a browser executable', () => { + const { createProc } = require('../src/main/browser/linux-process'); + const state = { pid: 100, startTime: '1000', boot: 'boot', binary: '/chrome/chrome', profile: '/profile' }; + const rows = new Map([ + [201, { parent: 100, exe: '/native/host', args: [] }], + [202, { parent: 201, exe: state.binary, args: [] }], + [203, { parent: 100, exe: '/electron/helper', args: ['--type=renderer'] }], + [204, { parent: 100, exe: '/chrome/chrome_crashpad_handler', args: ['--type=crashpad-handler'] }], + [205, { parent: 100, exe: '/other/chrome_crashpad_handler', args: ['--type=crashpad-handler'] }], + [206, { parent: 204, exe: state.binary, args: [] }], + ]); + for (const separator of ['\0', ' ']) { + const proc = createProc({ fs: { + readdirSync: () => [...rows.keys()].reverse().map(String), + realpathSync: file => rows.get(Number(file.split('/')[2])).exe, + readFileSync: file => { + if (file.endsWith('boot_id')) return 'boot'; + const pid = Number(file.split('/')[2]), row = rows.get(pid); + if (file.endsWith('/stat')) return `${pid} (name) S ${row.parent} ${Array(17).fill('0').join(' ')} ${pid * 10}`; + return [row.exe, ...row.args].join(separator); + }, + } }); + assert.deepEqual(proc.descendants(state).map(child => child.pid).sort(), [204, 206], 'foreign helper and descendants of native hosts must survive'); + } +}); diff --git a/test/open-terminal-attach.test.js b/test/open-terminal-attach.test.js index 280971bde..e4e6db06e 100644 --- a/test/open-terminal-attach.test.js +++ b/test/open-terminal-attach.test.js @@ -57,6 +57,7 @@ test('window close releases the Agents subscriber and app quit stops the job wat const end = MAIN.indexOf('\n });', idx) + '\n });'.length; let closed, _beforeQuit, unsubscribed = 0, stopped = 0; const context = { + managedBrowser: { stopForQuit() {} }, mainWindow: { on: (_name, callback) => { closed = callback; } }, activeSessions: new Map(), closedSessions: new Map(), changesWatchers: { closeAll() {} }, closeAllFileWatchers() {}, transcriptFollower: require('../src/main/viewer/transcript-follower').createTranscriptFollower(), diff --git a/test/pty-job-shutdown.test.js b/test/pty-job-shutdown.test.js index b658167fa..e83c0de2c 100644 --- a/test/pty-job-shutdown.test.js +++ b/test/pty-job-shutdown.test.js @@ -92,6 +92,7 @@ test('real shutdown function closes three PTYs synchronously and flushes within const filename = require.resolve('../main'); const source = fs.readFileSync(filename, 'utf8'); const context = vm.createContext({ Promise, Map, setTimeout, clearTimeout, + managedBrowser: { stopForQuit() {} }, shutdownPromise: null, appQuitting: false, shutdownComplete: false, TRACE: {}, updateInstalling: false, log: { error: (...args) => events.push(args.join(' ')) }, stopNonDatabaseResources() {}, closedSessions: new Map(), activeSessions: sessions, killPty: (session, id) => killPty(session, id, { platform: 'win32' }), diff --git a/test/remote-ssh-spawn-sites.test.js b/test/remote-ssh-spawn-sites.test.js index f7a0f0751..432d4dc62 100644 --- a/test/remote-ssh-spawn-sites.test.js +++ b/test/remote-ssh-spawn-sites.test.js @@ -34,6 +34,9 @@ const HOW_TO_FIX = 'Route the program through resolveSshPath()/resolveScpPath() // Sites whose program is not ssh or scp and cannot be proven so statically — file -> enclosing function. const UNRESOLVED_ALLOWED = { + 'src/main/browser/managed-browser.js': { + start: 'validated Chromium executable from browser discovery, or literal systemd-run; not a remote transport', + }, 'main.js': { spawnPty: 'node-pty wrapper: the shell of a local session, or the attach adapter\'s resolved ssh', runScheduleCommand: 'the shell of the schedule\'s shell profile', diff --git a/test/session-index-review-regressions.test.js b/test/session-index-review-regressions.test.js index 442404d3a..9fe3a0f6f 100644 --- a/test/session-index-review-regressions.test.js +++ b/test/session-index-review-regressions.test.js @@ -260,6 +260,7 @@ function lifecycleFixture(extra = {}) { const nativeUpdater = new EventEmitter(); const noop = () => {}; const context = vm.createContext({ + managedBrowser: { stopForQuit() {} }, ...clock, console, Promise, process: { pid: 6166, kill: (pid, signal) => calls.push(`kill:${pid}:${signal}`) }, appQuitting: false, activityFlushedForQuit: false, quitAttemptToken: null, exitInventory: null, inventory: () => ({}), flushForLogoff: null, updateInstalling: false, updateInstallPromise: null, updateWaitTimer: null, app: { removeListener: noop, on: (_name, fn) => { context.quit = fn; }, exit: () => calls.push('exit'), quit: () => calls.push('quit') }, diff --git a/test/test-pr.test.js b/test/test-pr.test.js index 3fe86be7a..14bce940f 100644 --- a/test/test-pr.test.js +++ b/test/test-pr.test.js @@ -220,7 +220,7 @@ test('dependency sharing preserves a private install without creating nested lin assert.deepEqual(fs.readdirSync(target), ['private']); }); -test('cleanup removes the dependency link before git removes the worktree, preserving its source', (t) => { +test('cleanup removes the dependency link before git removes the worktree, preserving its source', async (t) => { const root = temp(t); const source = path.join(root, 'source'); fs.mkdirSync(source); @@ -230,7 +230,7 @@ test('cleanup removes the dependency link before git removes the worktree, prese tooling().linkNodeModules(worktree, source); assert.ok(fs.lstatSync(path.join(worktree, 'node_modules')).isSymbolicLink()); const calls = []; - tooling().cleanWorktree({ checkout: root, pr: '122', home: root, run: (file, args) => { + await tooling().cleanWorktree({ checkout: root, pr: '122', home: root, run: (file, args) => { calls.push([file, args]); assert.equal(fs.existsSync(path.join(worktree, 'node_modules')), false); assert.equal(fs.readFileSync(path.join(source, 'sentinel'), 'utf8'), 'keep'); @@ -290,6 +290,61 @@ function workflow(t, script = bundleScript) { log: message => messages.push(message), warn: message => messages.push(message) }; } +for (const reject of [false, true]) { + test(`browser cleanup awaits captured data directory before removing HOME on launch rejection=${reject}`, async t => { + const setup = workflow(t), effects = []; + let cwd, data, release; + const gate = new Promise(resolve => { release = resolve; }); + const running = tooling().main({ ...setup, env: { ...setup.env, ISOLATED: '1' }, fixtures() {}, + launch: async (_file, _args, options) => { + cwd = options.cwd; data = options.env.SWITCHBOARD_DATA_DIR; + if (reject) throw new Error('launch rejected'); return 0; + }, + stopBrowser: async captured => { effects.push(['stop', captured]); await gate; return true; }, + removeDir: target => { effects.push(['delete', target]); fs.rmSync(target, { recursive: true, force: true }); }, + }); + running.catch(() => {}); + await new Promise(resolve => setImmediate(resolve)); + assert.deepEqual(effects, [['stop', data]]); + assert.equal(fs.existsSync(cwd), true); + release(); + if (reject) await assert.rejects(running, /launch rejected/); else assert.equal(await running, 0); + assert.deepEqual(effects, [['stop', data], ['delete', cwd]]); + }); +} + +test('uncertain browser cleanup retains HOME and reports recovery, including cleanup rejection', async t => { + for (const fail of ['false', 'throw']) { + const setup = workflow(t); let cwd; + await tooling().main({ ...setup, env: { ...setup.env, ISOLATED: '1' }, fixtures() {}, + launch: async (_file, _args, options) => { cwd = options.cwd; return 0; }, + stopBrowser: async () => { if (fail === 'throw') throw new Error('uncertain'); return false; }, + removeDir: target => fs.rmSync(target, { recursive: true, force: true }), + }); + assert.equal(fs.existsSync(cwd), true); + assert.ok(setup.messages.some(message => /browser.*retain|retain.*browser/i.test(message))); + fs.rmSync(cwd, { recursive: true, force: true }); + } +}); + +test('clean awaits browser exit before removing worktree/junction and persistent data', async t => { + const setup = workflow(t), effects = []; + await tooling().main({ ...setup, clean: true, + stopBrowser: async data => { effects.push(data); return false; }, + run: () => assert.fail('uncertain cleanup must not remove worktree'), + }).then(() => assert.fail('clean must refuse uncertain browser exit'), error => assert.match(error.message, /browser/i)); + assert.deepEqual(effects, [path.join(setup.home, '.switchboard-dev-pr122')]); +}); + +test('fixture failure after config capture still stops the captured browser data directory', async t => { + const setup = workflow(t); let data, stopped; + await assert.rejects(tooling().main({ ...setup, env: { ...setup.env, ISOLATED: '1' }, + fixtures: (_home, env) => { data = env.SWITCHBOARD_DATA_DIR; throw new Error('fixtures failed'); }, + stopBrowser: async dir => { stopped = dir; return true; }, + }), /fixtures failed/); + assert.equal(stopped, data); +}); + for (const isolated of ['0', '1']) { test(`mode ISOLATED=${isolated} confines relative native writes outside the checkout and cleans them on exit`, async (t) => { const setup = workflow(t);