Skip to content

An agentic browser harness: an AI side panel & orb in your own logged-in Chrome, Edge, Arc, Brave or even Firefox run by the agent/subscription you already use (Claude Code, Codex, Antigravity). Free, open source, no API key. Also an MCP server.

fix(bridge): every browser can start the Bridge: Chrome's and Mozilla's host locations are always written, so a Mac with Brave or Opera and no Chrome, and a Mac whose Firefox never made a Mozilla folder, are let in; forks are found by CrProductDirName; registration is atomic, hourly and repins a launcher whose Node or CLI has gone; one Bridge starts however many browsers ask at once; Firefox on Windows starts it through Task Scheduler, outside the job it kills; the host keeps stderr silent; a scratch BROWSENTIC_HOME never registers; the Windows uninstaller unregisters

Shahriar7d7a6622e169
diff --git a/src/daemon/cli.ts b/src/daemon/cli.ts
index e7a6468..4beb0cb 100644
--- a/src/daemon/cli.ts
+++ b/src/daemon/cli.ts
@@ -36,7 +36,8 @@ import { install, InstallError, readStamp } from './install';
import { logPath, readLockfile, wakeHeld } from './lockfile';
import { log } from './log';
import { installKind } from './npx';
-import { installNativeHost, registeredBrowsers, removeNativeHost, serveNativeHost } from './native-host';
+import { installNativeHost, registeredBrowsers, registrationCurrent, removeNativeHost } from './native-host';
+import { serveNativeHost } from './native-messaging';
import { extensionDir } from './paths';
import { RELEASES_PAGE, signedAddonAttached } from './firefox-addon';
import { RemoteBridge } from './remote-bridge';
@@ -137,7 +138,10 @@ switch (command) {
await uninstall(process.argv.slice(3));
break;
case 'native-host':
- await serveNativeHost(ensureDaemon, wakeHeld);
+ await serveNativeHost({ ensure: (caller) => ensureDaemon({ outsideJob: caller?.family === 'firefox' }), held: wakeHeld });
+ break;
+ case 'unregister-host':
+ unregisterHost();
break;
case 'pair':
await pair();
@@ -283,12 +287,13 @@ function printSkills(): void {
async function showStatus(): Promise<void> {
const lock = await probeExisting();
const waking = registeredBrowsers();
+ const outdated = waking.length && !registrationCurrent() ? ' (an older Bridge registered it: run "browsentic setup")' : '';
const wake = `wake-up: ${
!waking.length
? 'not registered — run "browsentic setup"'
: wakeHeld()
? `held since "browsentic stop" — "browsentic start" lets ${waking.join(', ')} start it again`
- : `${waking.join(', ')} can start the Bridge`
+ : `${waking.join(', ')} can start the Bridge${outdated}`
}`;
if (!lock) {
console.log('bridge: not running');
@@ -487,7 +492,7 @@ async function setup(argv: string[]): Promise<void> {
if (!json) {
console.log(`\n Browsentic ${pkg.version} — your browser's superpower\n`);
console.log(` ✓ Browsentic Bridge running on 127.0.0.1:${lock.port} (pid ${lock.pid})`);
- console.log(` ${wakeLine(wake.browsers)}`);
+ console.log(` ${wakeLine(wake)}`);
for (const line of agentLines(await bridge.agent())) console.log(` ${line}`);
console.log();
}
@@ -563,12 +568,19 @@ async function setup(argv: string[]): Promise<void> {
}
}
-function wakeLine(browsers: string[]): string {
+function wakeLine({ browsers, skipped }: { browsers: string[]; skipped?: string }): string {
+ if (skipped) return `· Wake-up not registered: ${skipped}`;
return browsers.length
? `✓ Wake-up ${browsers.join(', ')} can start the Bridge when it is down`
: '· Wake-up no supported browser found, so start the Bridge yourself after a reboot';
}
+/** For the Windows app's uninstaller, which leaves the Bridge's files but must not leave browsers able to start it. */
+function unregisterHost(): void {
+ const removed = removeNativeHost();
+ console.log(removed.length ? `Unregistered from ${removed.length} place${removed.length === 1 ? '' : 's'}.` : 'Nothing was registered.');
+}
+
function agentLines(state: AgentState): string[] {
const ready = state.runners.filter((runner) => runner.ready).map((runner) => runner.kind);
const active = AGENTS[state.active].label;
diff --git a/src/daemon/daemon.ts b/src/daemon/daemon.ts
index cb758c1..76bcacf 100644
--- a/src/daemon/daemon.ts
+++ b/src/daemon/daemon.ts
@@ -1,6 +1,7 @@
import { randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
import { createServer, type IncomingMessage, type Server } from 'node:http';
import type { AddressInfo } from 'node:net';
+import { dirname, join } from 'node:path';
import type { Duplex } from 'node:stream';
import { WebSocketServer, type WebSocket } from 'ws';
import {
@@ -76,6 +77,7 @@ import {
import { ExtensionLink } from './extension-link';
import { startScheduler } from './schedules/scheduler';
import { refreshNativeHost } from './native-host';
+import { daemonMainPath } from './ensure-daemon';
import {
ANYWHERE,
INJECT_ACTION,
@@ -108,6 +110,7 @@ function phoneReply(request: PhoneRequest, result: ActionResult<never>): SocketF
}
const IDLE_EXIT_MS = 30 * 60 * 1000;
+const REREGISTER_MS = 60 * 60 * 1000;
const BINDING_IDLE_MS = 2 * 60 * 1000;
const BROWSER_LABEL_MAX = 40;
const HANDSHAKE_TIMEOUT_MS = 10_000;
@@ -266,8 +269,12 @@ export async function startDaemon({ version, idleExit = true, android = androidO
lock.port = port;
writeLockfile(lock);
releaseWake();
- // A registration an older daemon wrote lets in only what it knew, which leaves the store copies out.
- refreshNativeHost();
+ // A registration an older daemon wrote lets in only what it knew, which leaves the store copies out,
+ // and a browser installed since needs its own; both are put right now and every hour.
+ const reregister = () => refreshNativeHost({ cliPath: join(dirname(daemonMainPath()), 'cli.js') });
+ reregister();
+ const reregistering = setInterval(reregister, REREGISTER_MS);
+ reregistering.unref();
log(`daemon ${version} listening on 127.0.0.1:${port} (pid ${process.pid})`);
scheduleIdleExit();
@@ -1047,6 +1054,7 @@ export async function startDaemon({ version, idleExit = true, android = androidO
async function stop(): Promise<void> {
if (idleTimer) clearTimeout(idleTimer);
+ clearInterval(reregistering);
scheduler.stop();
unwatchConfig();
for (const watcher of [...androidWatches.keys()]) unwatchAndroid(watcher);
diff --git a/src/daemon/ensure-daemon.test.ts b/src/daemon/ensure-daemon.test.ts
new file mode 100644
index 0000000..7d248f3
--- /dev/null
+++ b/src/daemon/ensure-daemon.test.ts
@@ -0,0 +1,44 @@
+import { existsSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { afterEach, describe, expect, it } from 'vitest';
+import { takeStartLock } from './ensure-daemon';
+import { stateDir } from './lockfile';
+
+const lock = join(stateDir, 'daemon.start.lock');
+
+describe('the start lock', () => {
+ let release: (() => void) | null = null;
+
+ afterEach(() => release?.());
+
+ it('lets one starter spawn and keeps every other one waiting for it', () => {
+ release = takeStartLock();
+
+ expect(release).toBeTypeOf('function');
+ expect(takeStartLock()).toBeNull();
+ });
+
+ it('is free again once released', () => {
+ takeStartLock()!();
+
+ release = takeStartLock();
+ expect(release).toBeTypeOf('function');
+ });
+
+ it('breaks a lock its holder died with', () => {
+ writeFileSync(lock, `999999999 ${Date.now()}\n`);
+
+ release = takeStartLock();
+ expect(release).toBeTypeOf('function');
+ });
+
+ it('breaks a lock held far longer than any start takes', () => {
+ writeFileSync(lock, `${process.pid} ${Date.now() - 60_000}\n`);
+
+ release = takeStartLock();
+ expect(release).toBeTypeOf('function');
+ release!();
+ release = null;
+ expect(existsSync(lock)).toBe(false);
+ });
+});
diff --git a/src/daemon/ensure-daemon.ts b/src/daemon/ensure-daemon.ts
index 506759c..95d6e99 100644
--- a/src/daemon/ensure-daemon.ts
+++ b/src/daemon/ensure-daemon.ts
@@ -1,39 +1,106 @@
import { spawn, spawnSync } from 'node:child_process';
+import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
-import { clearLockfile, holdWake, isRunning, readLockfile, type Lockfile } from './lockfile';
+import { clearLockfile, holdWake, isRunning, readLockfile, stateDir, type Lockfile } from './lockfile';
import { log } from './log';
import { daemonPorts } from './ports';
+import { runBridgeTask } from './windows-task';
const SPAWN_TIMEOUT_MS = 8_000;
const POLL_INTERVAL_MS = 150;
+const START_LOCK = join(stateDir, 'daemon.start.lock');
+const STALE_START_MS = SPAWN_TIMEOUT_MS * 2;
+const TASK_GRACE_MS = 4_000;
-export async function ensureDaemon(): Promise<Lockfile> {
- const existing = await probeExisting();
- if (existing) return existing;
+export const daemonMainPath = () => join(dirname(fileURLToPath(import.meta.url)), 'daemon-main.js');
- log('no daemon reachable; spawning one');
- const daemonMain = join(dirname(fileURLToPath(import.meta.url)), 'daemon-main.js');
+export interface EnsureOptions {
+ /** Start it through Task Scheduler: the caller runs in a job that dies with it (Firefox's native host on Windows). */
+ outsideJob?: boolean;
+}
+
+/**
+ * Several browsers wake the Bridge at once when the computer starts, and each would spawn its own on
+ * the next free port. Whoever holds the start lock spawns; everyone else waits for the one it starts.
+ */
+export async function ensureDaemon(options: EnsureOptions = {}): Promise<Lockfile> {
+ const deadline = Date.now() + SPAWN_TIMEOUT_MS * 2;
+ for (;;) {
+ const existing = await probeExisting();
+ if (existing) return existing;
+ const release = takeStartLock();
+ if (release) {
+ try {
+ return (await probeExisting()) ?? (await spawnDaemon(options));
+ } finally {
+ release();
+ }
+ }
+ if (Date.now() > deadline) throw new Error('Another Browsentic Bridge was starting and never came up — see "browsentic logs"');
+ await delay(POLL_INTERVAL_MS);
+ }
+}
+
+export function takeStartLock(retry = true): (() => void) | null {
+ mkdirSync(stateDir, { recursive: true, mode: 0o700 });
+ try {
+ writeFileSync(START_LOCK, `${process.pid} ${Date.now()}\n`, { flag: 'wx', mode: 0o600 });
+ return () => rmSync(START_LOCK, { force: true });
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') return () => undefined;
+ }
+ const [pid, at] = readStartLock();
+ if (retry && (!isRunning(pid) || Date.now() - at > STALE_START_MS)) {
+ rmSync(START_LOCK, { force: true });
+ return takeStartLock(false);
+ }
+ return null;
+}
+
+function readStartLock(): [number, number] {
+ try {
+ const [pid, at] = readFileSync(START_LOCK, 'utf8').trim().split(' ').map(Number);
+ return [pid || 0, at || 0];
+ } catch {
+ return [0, 0];
+ }
+}
+
+async function spawnDaemon({ outsideJob = false }: EnsureOptions): Promise<Lockfile> {
+ if (outsideJob && process.platform === 'win32' && runBridgeTask()) {
+ log('no daemon reachable; starting one through Task Scheduler');
+ const started = await waitForDaemon(TASK_GRACE_MS);
+ if (started) return started;
+ log('the Task Scheduler start never came up; spawning one directly');
+ } else {
+ log('no daemon reachable; spawning one');
+ }
const env: NodeJS.ProcessEnv = { ...process.env };
delete env.BROWSENTIC_AGENT_RUN;
delete env.CLAUDECODE;
delete env.CLAUDE_CODE_ENTRYPOINT;
-
- const child = spawn(process.execPath, [daemonMain], {
+ delete env.NODE_NO_WARNINGS;
+ const child = spawn(process.execPath, [daemonMainPath()], {
detached: true,
stdio: 'ignore',
env,
windowsHide: true,
});
child.unref();
+ const started = await waitForDaemon(SPAWN_TIMEOUT_MS);
+ if (started) return started;
+ throw new Error(`The Browsentic daemon did not come up within ${SPAWN_TIMEOUT_MS}ms — see the log with "browsentic logs"`);
+}
- const deadline = Date.now() + SPAWN_TIMEOUT_MS;
+async function waitForDaemon(timeoutMs: number): Promise<Lockfile | null> {
+ const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
await delay(POLL_INTERVAL_MS);
const started = await probeExisting();
if (started) return started;
}
- throw new Error(`The Browsentic daemon did not come up within ${SPAWN_TIMEOUT_MS}ms — see the log with "browsentic-mcp logs"`);
+ return null;
}
export async function probeExisting(): Promise<Lockfile | null> {
diff --git a/src/daemon/native-host.test.ts b/src/daemon/native-host.test.ts
index f2152b4..bfc69e5 100644
--- a/src/daemon/native-host.test.ts
+++ b/src/daemon/native-host.test.ts
@@ -1,26 +1,31 @@
-import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
+import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
-import { dirname, join } from 'node:path';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { dirname, join, posix } from 'node:path';
+import { beforeEach, describe, expect, it } from 'vitest';
import {
NATIVE_HOST_NAME,
- STOPPED_REPLY,
allowedOrigins,
- answerNativeMessage,
- decodeNativeMessage,
- encodeNativeMessage,
hostManifest,
hostTargets,
installNativeHost,
+ launcherPath,
+ launcherPins,
launcherScript,
nativeHostDir,
+ refreshNativeHost,
registeredBrowsers,
+ registersHosts,
+ registrationCurrent,
removeNativeHost,
unpackedExtensionOrigin,
+ writeIfChanged,
type Registry,
} from './native-host';
import { extensionDir } from './paths';
import { bits, modeOf } from './test/modes';
+import type { TaskScheduler } from './windows-task';
+
+const STORE_ORIGINS = ['chrome-extension://cbkjhkgjcpihokphhdkbahilpcjojpdc/', 'chrome-extension://npmocgldfflonjjmdadmdefpnfagnjmp/'];
describe('unpackedExtensionOrigin', () => {
it('names the folder the way Chrome does', () => {
@@ -46,38 +51,70 @@ describe('allowedOrigins', () => {
});
it('lets both store copies start the daemon before they have ever paired', () => {
- expect(allowedOrigins('darwin')).toEqual(
- expect.arrayContaining([
- 'chrome-extension://npmocgldfflonjjmdadmdefpnfagnjmp/',
- 'chrome-extension://cbkjhkgjcpihokphhdkbahilpcjojpdc/',
- ]),
- );
+ expect(allowedOrigins('darwin')).toEqual(expect.arrayContaining(STORE_ORIGINS));
});
});
describe('hostTargets', () => {
- it('points each browser at its own manifest folder, or its registry key on Windows', () => {
- const mac = hostTargets('darwin', '/Users/me').find((target) => target.browser === 'Edge');
- expect(mac?.manifestDir).toBe('/Users/me/Library/Application Support/Microsoft Edge/NativeMessagingHosts');
+ const mac = (browser: string) => hostTargets('darwin', '/Users/me').find((target) => target.browser === browser);
+ const support = '/Users/me/Library/Application Support';
+
+ it('points each browser at the folders it reads, or its registry key on Windows', () => {
+ expect(mac('Edge')?.manifestDirs).toEqual([`${support}/Microsoft Edge/NativeMessagingHosts`]);
const linux = hostTargets('linux', '/home/me').find((target) => target.browser === 'Firefox');
- expect(linux).toMatchObject({ family: 'firefox', manifestDir: '/home/me/.mozilla/native-messaging-hosts' });
+ expect(linux).toMatchObject({ family: 'firefox', manifestDirs: ['/home/me/.mozilla/native-messaging-hosts'] });
const windows = hostTargets('win32', 'C:\\Users\\me', {}).find((target) => target.browser === 'Chrome');
expect(windows).toMatchObject({
- home: 'C:\\Users\\me\\AppData\\Local\\Google\\Chrome\\User Data',
+ installs: ['C:\\Users\\me\\AppData\\Local\\Google\\Chrome\\User Data'],
registryKey: `HKCU\\Software\\Google\\Chrome\\NativeMessagingHosts\\${NATIVE_HOST_NAME}`,
});
});
- it('lets Brave and Vivaldi in through the key Chrome reads, which every Chromium build falls back to', () => {
+ it('sends Brave and Opera on macOS to Chrome’s folder, which is the one they read', () => {
+ expect(mac('Brave')?.manifestDirs).toContain(`${support}/Google/Chrome/NativeMessagingHosts`);
+ expect(mac('Opera')?.manifestDirs).toEqual([`${support}/Google/Chrome/NativeMessagingHosts`]);
+ });
+
+ it('finds Firefox on macOS by its own profile folder, and writes to Mozilla’s', () => {
+ expect(mac('Firefox')).toMatchObject({
+ family: 'firefox',
+ installs: expect.arrayContaining([`${support}/Firefox`, '/Applications/Firefox.app']),
+ manifestDirs: [`${support}/Mozilla/NativeMessagingHosts`],
+ baseline: true,
+ });
+ });
+
+ it('leaves Tor Browser out on purpose', () => {
+ for (const platform of ['darwin', 'win32', 'linux'] as const) {
+ expect(hostTargets(platform, '/Users/me', {}).map((target) => target.browser)).not.toContain('Tor Browser');
+ }
+ });
+
+ it('adds a macOS fork no table names, at the data folder its Info.plist gives', () => {
+ const forks = [
+ { browser: 'Helium', app: '/Applications/Helium.app', dataDir: 'net.imput.helium' },
+ { browser: 'Brave Browser', app: '/Applications/Brave Browser.app', dataDir: 'BraveSoftware/Brave-Browser' },
+ ];
+ const targets = hostTargets('darwin', '/Users/me', {}, forks);
+ expect(targets.find((target) => target.browser === 'Helium')).toMatchObject({
+ installs: ['/Applications/Helium.app'],
+ manifestDirs: [`${support}/net.imput.helium/NativeMessagingHosts`],
+ });
+ expect(targets.filter((target) => target.browser.startsWith('Brave Browser'))).toEqual([]);
+ });
+
+ it('lets Brave, Vivaldi and Opera in on Windows through the key Chrome reads, which every Chromium build falls back to', () => {
const keys = Object.fromEntries(hostTargets('win32', 'C:\\Users\\me', {}).map((target) => [target.browser, target.registryKey]));
expect(keys.Brave).toBe(keys.Chrome);
expect(keys.Vivaldi).toBe(keys.Chrome);
+ expect(keys.Opera).toBe(keys.Chrome);
expect(keys.Edge).toBe(`HKCU\\Software\\Microsoft\\Edge\\NativeMessagingHosts\\${NATIVE_HOST_NAME}`);
+ expect(keys.Zen).toBe(keys.Firefox);
});
it('looks for Windows profiles where AppData really is', () => {
const env = { LOCALAPPDATA: 'D:\\Local', APPDATA: 'D:\\Roaming' };
- const homes = Object.fromEntries(hostTargets('win32', 'C:\\Users\\me', env).map((target) => [target.browser, target.home]));
+ const homes = Object.fromEntries(hostTargets('win32', 'C:\\Users\\me', env).map((target) => [target.browser, target.installs[0]]));
expect(homes.Edge).toBe('D:\\Local\\Microsoft\\Edge\\User Data');
expect(homes.Firefox).toBe('D:\\Roaming\\Mozilla\\Firefox');
});
@@ -96,17 +133,14 @@ describe('hostManifest', () => {
});
describe('launcherScript', () => {
- it('pins node, the CLI and PATH, and falls back to npx once the CLI moves', () => {
- const script = launcherScript({
- platform: 'darwin',
- cliPath: "/Users/o'neil/cli.js",
- nodePath: '/opt/node/bin/node',
- pathEnv: '/opt/node/bin:/usr/bin',
- });
- expect(script.split('\n')).toEqual([
+ const pins = { cliPath: "/Users/o'neil/cli.js", nodePath: '/opt/node/bin/node', pathEnv: '/opt/node/bin:/usr/bin' };
+
+ it('pins node, the CLI and PATH, keeps Node quiet, and falls back to npx once the CLI moves', () => {
+ expect(launcherScript({ platform: 'darwin', ...pins }).split('\n')).toEqual([
'#!/bin/sh',
"PATH='/opt/node/bin:/usr/bin'",
- 'export PATH',
+ 'NODE_NO_WARNINGS=1',
+ 'export PATH NODE_NO_WARNINGS',
"NODE='/opt/node/bin/node'",
'[ -x "$NODE" ] || NODE=node',
"CLI='/Users/o'\\''neil/cli.js'",
@@ -119,6 +153,7 @@ describe('launcherScript', () => {
it('writes a batch file on Windows', () => {
const script = launcherScript({ platform: 'win32', cliPath: 'C:\\b\\cli.js', nodePath: 'C:\\node.exe', pathEnv: 'C:\\bin' });
expect(script).toContain('"C:\\node.exe" "C:\\b\\cli.js" native-host %*');
+ expect(script).toContain('set "NODE_NO_WARNINGS=1"');
expect(script).toContain('call npx --yes browsentic native-host %*');
});
@@ -126,39 +161,56 @@ describe('launcherScript', () => {
const lines = launcherScript({ platform: 'win32', cliPath: 'C:\\Users\\José\\cli.js', nodePath: 'C:\\node.exe', pathEnv: 'C:\\bin' }).split('\r\n');
expect(lines.slice(0, 2)).toEqual(['@echo off', 'chcp 65001 >nul']);
});
-});
-describe('the message frame', () => {
- it('round-trips a message and waits for a whole one', () => {
- const frame = encodeNativeMessage({ op: 'ensure' });
- expect(frame.readUInt32LE(0)).toBe(frame.length - 4);
- expect(decodeNativeMessage(frame)).toEqual({ op: 'ensure' });
- expect(decodeNativeMessage(frame.subarray(0, frame.length - 1))).toBeUndefined();
+ it('reads back what a launcher was pinned to, on both platforms', () => {
+ expect(launcherPins(launcherScript({ platform: 'darwin', ...pins }), 'darwin')).toEqual(pins);
+ const windows = { cliPath: 'C:\\Users\\José\\cli.js', nodePath: 'C:\\Program Files\\nodejs\\node.exe', pathEnv: 'C:\\bin;C:\\x' };
+ expect(launcherPins(launcherScript({ platform: 'win32', ...windows }), 'win32')).toEqual(windows);
+ });
+
+ it('reads a launcher an older Bridge wrote, before Node was kept quiet', () => {
+ const old = ['#!/bin/sh', "PATH='/usr/bin'", 'export PATH', "NODE='/old/node'", '[ -x "$NODE" ] || NODE=node', "CLI='/old/cli.js'", ''].join('\n');
+ expect(launcherPins(old, 'darwin')).toEqual({ pathEnv: '/usr/bin', nodePath: '/old/node', cliPath: '/old/cli.js' });
});
});
-describe('answering the browser', () => {
- const ensure = vi.fn(async () => ({ port: 8765 }));
+describe('writeIfChanged', () => {
+ const file = join(homedir(), 'write-if-changed.json');
- beforeEach(() => ensure.mockClear());
+ it('writes a new file, leaves an identical one alone, and replaces a different one whole', () => {
+ rmSync(file, { force: true });
+ expect(writeIfChanged(file, 'a')).toBe(true);
+ expect(writeIfChanged(file, 'a')).toBe(false);
+ expect(writeIfChanged(file, 'b')).toBe(true);
+ expect(readFileSync(file, 'utf8')).toBe('b');
+ expect(existsSync(`${file}.${process.pid}.tmp`)).toBe(false);
+ });
+});
+
+describe('registersHosts', () => {
+ it('registers from a Bridge whose state lives in the home folder', () => {
+ expect(registersHosts({ state: '/Users/me/.browsentic', home: '/Users/me', env: {}, platform: 'darwin' })).toBe(true);
+ expect(registersHosts({ state: 'C:\\Users\\Me\\.browsentic', home: 'c:\\users\\me', env: {}, platform: 'win32' })).toBe(true);
+ });
- it('starts the daemon when asked', async () => {
- expect(await answerNativeMessage({ op: 'ensure' }, ensure, () => false)).toEqual({ ok: true, port: 8765 });
- expect(ensure).toHaveBeenCalledOnce();
+ it('never points the user’s browsers at a scratch Bridge kept elsewhere', () => {
+ expect(registersHosts({ state: '/tmp/scratch/.browsentic', home: '/Users/me', env: {}, platform: 'darwin' })).toBe(false);
+ expect(registersHosts({ state: '/Users/me', home: '/Users/me', env: {}, platform: 'darwin' })).toBe(false);
+ expect(registersHosts({ state: '/Users/meet/.browsentic', home: '/Users/me', env: {}, platform: 'darwin' })).toBe(false);
});
- it('leaves a daemon stopped on purpose down', async () => {
- expect(await answerNativeMessage({ op: 'ensure' }, ensure, () => true)).toBe(STOPPED_REPLY);
- expect(ensure).not.toHaveBeenCalled();
+ it('lets someone who really keeps it elsewhere say so', () => {
+ expect(registersHosts({ state: '/Volumes/x/.browsentic', home: '/Users/me', env: { BROWSENTIC_REGISTER_HOST: '1' }, platform: 'darwin' })).toBe(true);
});
- it('refuses anything but ensure', async () => {
- expect(await answerNativeMessage({ op: 'spawn' }, ensure, () => false)).toMatchObject({ ok: false });
- expect(ensure).not.toHaveBeenCalled();
+ it('installs, refreshes and removes nothing from a scratch Bridge', () => {
+ const scratch = { platform: 'linux', state: '/tmp/elsewhere', env: {} } as const;
+ expect(installNativeHost('/opt/browsentic/dist/cli.js', scratch)).toMatchObject({ browsers: [], skipped: expect.any(String) });
+ expect(removeNativeHost(scratch)).toEqual([]);
});
});
-describe('registering the host', () => {
+describe('registering the host on Linux', () => {
const linux = { platform: 'linux' } as const;
const chromeHome = join(homedir(), '.config', 'google-chrome');
const manifest = join(chromeHome, 'NativeMessagingHosts', `${NATIVE_HOST_NAME}.json`);
@@ -176,13 +228,17 @@ describe('registering the host', () => {
expect(modeOf(installed.launcher)).toBe(bits(0o755));
expect(JSON.parse(readFileSync(manifest, 'utf8'))).toMatchObject({
path: installed.launcher,
- allowed_origins: [
- 'chrome-extension://cbkjhkgjcpihokphhdkbahilpcjojpdc/',
- unpackedExtensionOrigin(extensionDir(), 'linux'),
- 'chrome-extension://npmocgldfflonjjmdadmdefpnfagnjmp/',
- ].sort(),
+ allowed_origins: [...STORE_ORIGINS, unpackedExtensionOrigin(extensionDir(), 'linux')].sort(),
});
expect(registeredBrowsers(linux)).toEqual(['Chrome']);
+ expect(registrationCurrent(linux)).toBe(true);
+ });
+
+ it('says so when an older Bridge’s manifest leaves the store copies out', () => {
+ installNativeHost('/opt/browsentic/dist/cli.js', linux);
+ writeFileSync(manifest, JSON.stringify(hostManifest('chromium', '/x', ['chrome-extension://old/'])));
+
+ expect(registrationCurrent(linux)).toBe(false);
});
it('removes every trace on uninstall', () => {
@@ -207,11 +263,102 @@ describe('registering the host', () => {
});
});
+describe('registering the host on macOS', () => {
+ const home = homedir();
+ const support = posix.join(home, 'Library', 'Application Support');
+ const manifestIn = (dir: string) => posix.join(support, dir, 'NativeMessagingHosts', `${NATIVE_HOST_NAME}.json`);
+ const mac = (installed: string[], forks: { browser: string; app: string; dataDir: string }[] = []) =>
+ ({ platform: 'darwin', home, forks: () => forks, exists: (path: string) => installed.includes(path) }) as const;
+
+ beforeEach(() => {
+ removeNativeHost(mac([]));
+ rmSync(support, { recursive: true, force: true });
+ });
+
+ it('writes Chrome’s and Mozilla’s folders even when neither browser is installed', () => {
+ const installed = installNativeHost('/opt/browsentic/dist/cli.js', mac([]));
+
+ expect(installed.browsers).toEqual([]);
+ expect(JSON.parse(readFileSync(manifestIn('Google/Chrome'), 'utf8'))).toMatchObject({ allowed_origins: expect.arrayContaining(STORE_ORIGINS) });
+ expect(JSON.parse(readFileSync(manifestIn('Mozilla'), 'utf8'))).toMatchObject({ allowed_extensions: ['[email protected]'] });
+ });
+
+ it('lets a Mac with Brave and no Chrome start the Bridge, through Chrome’s folder', () => {
+ const machine = mac(['/Applications/Brave Browser.app']);
+
+ expect(installNativeHost('/opt/browsentic/dist/cli.js', machine).browsers).toEqual(['Brave']);
+ expect(existsSync(manifestIn('Google/Chrome'))).toBe(true);
+ expect(registeredBrowsers(machine)).toEqual(['Brave']);
+ });
+
+ it('registers Firefox on a Mac that never made a Mozilla folder', () => {
+ const machine = mac([posix.join(support, 'Firefox')]);
+
+ expect(installNativeHost('/opt/browsentic/dist/cli.js', machine).browsers).toEqual(['Firefox']);
+ expect(existsSync(manifestIn('Mozilla'))).toBe(true);
+ });
+
+ it('registers a fork in the data folder its Info.plist names', () => {
+ const machine = mac(['/Applications/Helium.app'], [{ browser: 'Helium', app: '/Applications/Helium.app', dataDir: 'net.imput.helium' }]);
+
+ expect(installNativeHost('/opt/browsentic/dist/cli.js', machine).browsers).toEqual(['Helium']);
+ expect(existsSync(manifestIn('net.imput.helium'))).toBe(true);
+ });
+
+ it('removes what it wrote, baselines included', () => {
+ installNativeHost('/opt/browsentic/dist/cli.js', mac(['/Applications/Brave Browser.app']));
+
+ removeNativeHost(mac([]));
+
+ expect(existsSync(manifestIn('Google/Chrome'))).toBe(false);
+ expect(existsSync(manifestIn('BraveSoftware/Brave-Browser'))).toBe(false);
+ expect(existsSync(manifestIn('Mozilla'))).toBe(false);
+ });
+});
+
+describe('refreshing the registration', () => {
+ const linux = { platform: 'linux' } as const;
+ const gone = '/gone/for/good';
+
+ beforeEach(() => removeNativeHost(linux));
+
+ it('does nothing before setup has written a launcher', () => {
+ refreshNativeHost(linux);
+ expect(existsSync(launcherPath('linux'))).toBe(false);
+ });
+
+ it('repins a launcher whose CLI and Node have gone to the ones this Bridge runs on', () => {
+ installNativeHost(join(gone, 'cli.js'), linux);
+ writeFileSync(launcherPath('linux'), launcherScript({ platform: 'linux', cliPath: join(gone, 'cli.js'), nodePath: join(gone, 'node'), pathEnv: '/usr/bin' }));
+ const here = join(homedir(), 'cli.js');
+ writeFileSync(here, '');
+
+ refreshNativeHost({ ...linux, cliPath: here, nodePath: process.execPath });
+
+ expect(launcherPins(readFileSync(launcherPath('linux'), 'utf8'), 'linux')).toEqual({ cliPath: here, nodePath: process.execPath, pathEnv: '/usr/bin' });
+ });
+
+ it('keeps a launcher whose pins still exist, but brings it up to date', () => {
+ const here = join(homedir(), 'cli.js');
+ writeFileSync(here, '');
+ installNativeHost(here, linux);
+ const old = ['#!/bin/sh', "PATH='/usr/bin'", 'export PATH', `NODE='${process.execPath}'`, `CLI='${here}'`, ''].join('\n');
+ writeFileSync(launcherPath('linux'), old);
+
+ refreshNativeHost({ ...linux, cliPath: join(gone, 'cli.js') });
+
+ const script = readFileSync(launcherPath('linux'), 'utf8');
+ expect(script).toContain('NODE_NO_WARNINGS=1');
+ expect(launcherPins(script, 'linux')).toEqual({ cliPath: here, nodePath: process.execPath, pathEnv: '/usr/bin' });
+ });
+});
+
describe('registering the host on Windows', () => {
const home = 'C:\\Users\\me';
const profile = (dir: string) => `C:\\Users\\me\\AppData\\Local\\${dir}\\User Data`;
const key = (vendor: string) => `HKCU\\Software\\${vendor}\\NativeMessagingHosts\\${NATIVE_HOST_NAME}`;
let keys: Map<string, string>;
+ let scheduled: string[];
const registry: Registry = {
set: (path, value) => void keys.set(path, value),
has: (path) => keys.has(path),
@@ -219,38 +366,51 @@ describe('registering the host on Windows', () => {
if (!keys.delete(path)) throw new Error(`no key ${path}`);
},
};
- const windows = (installed: string[]) => ({ platform: 'win32', home, env: {}, registry, exists: (path: string) => installed.includes(path) }) as const;
+ const tasks: TaskScheduler = {
+ register: (file) => void scheduled.push(`register ${readFileSync(file).subarray(2).toString('utf16le').includes('daemon-main.js')}`),
+ run: () => void scheduled.push('run'),
+ remove: () => void scheduled.push('remove'),
+ };
+ const windows = (installed: string[]) =>
+ ({ platform: 'win32', home, env: {}, registry, tasks, state: 'C:\\Users\\me\\.browsentic', exists: (path: string) => installed.includes(path) }) as const;
beforeEach(() => {
keys = new Map();
+ scheduled = [];
removeNativeHost(windows([]));
+ scheduled = [];
});
- it('registers only with the browsers that are installed, as macOS and Linux do', () => {
+ it('writes Chrome’s and Mozilla’s keys always, and each installed browser’s own', () => {
const machine = windows([profile('Microsoft\\Edge'), profile('BraveSoftware\\Brave-Browser')]);
const installed = installNativeHost('C:\\b\\dist\\cli.js', machine);
expect(installed.browsers).toEqual(['Edge', 'Brave']);
- expect([...keys.keys()].sort()).toEqual([key('Google\\Chrome'), key('Microsoft\\Edge')]);
+ expect([...keys.keys()].sort()).toEqual([key('Google\\Chrome'), key('Microsoft\\Edge'), key('Mozilla')]);
expect(JSON.parse(readFileSync(keys.get(key('Google\\Chrome'))!, 'utf8'))).toMatchObject({ path: installed.launcher });
expect(registeredBrowsers(machine)).toEqual(['Edge', 'Brave']);
});
- it('registers a Beta, Dev or Canary channel on its own, through the key its browser reads', () => {
+ it('registers a Beta, Dev or Canary channel through the key its browser reads', () => {
const machine = windows([profile('Google\\Chrome SxS'), profile('Microsoft\\Edge Beta')]);
- const installed = installNativeHost('C:\\b\\dist\\cli.js', machine);
-
- expect(installed.browsers).toEqual(['Chrome Canary', 'Edge Beta']);
- expect([...keys.keys()].sort()).toEqual([key('Google\\Chrome'), key('Microsoft\\Edge')]);
+ expect(installNativeHost('C:\\b\\dist\\cli.js', machine).browsers).toEqual(['Chrome Canary', 'Edge Beta']);
expect(registeredBrowsers(machine)).toEqual(['Chrome Canary', 'Edge Beta']);
});
- it('says a browser installed since setup cannot start the daemon yet', () => {
+ it('lets a browser installed since setup start the Bridge through the baseline key', () => {
installNativeHost('C:\\b\\dist\\cli.js', windows([profile('Microsoft\\Edge')]));
- expect(registeredBrowsers(windows([profile('Microsoft\\Edge'), profile('Google\\Chrome')]))).toEqual(['Edge']);
+ expect(registeredBrowsers(windows([profile('Microsoft\\Edge'), profile('Google\\Chrome')]))).toEqual(['Chrome', 'Edge']);
+ });
+
+ it('registers the task that starts the Bridge for Firefox, and takes it away on uninstall', () => {
+ installNativeHost('C:\\b\\dist\\cli.js', windows([]));
+ expect(scheduled).toEqual(['register true']);
+
+ removeNativeHost(windows([]));
+ expect(scheduled).toContain('remove');
});
it('removes every key on uninstall, the one written for Brave before it was known to read Chrome’s too', () => {
diff --git a/src/daemon/native-host.ts b/src/daemon/native-host.ts
index 34686c2..8955254 100644
--- a/src/daemon/native-host.ts
+++ b/src/daemon/native-host.ts
@@ -1,48 +1,108 @@
/**
- * Lets the browser start the daemon. Chrome, Edge, Brave and Firefox each launch a program
- * registered as a native messaging host when the extension asks for it; ours only makes sure
- * a daemon is running and exits. The registration lists the exact extension origins allowed
- * to launch it: both store listings always, plus the unpacked folder and whatever has paired,
- * recomputed on every setup and every pairing.
+ * Lets the browser reach Browsentic Bridge. Chrome, Edge, Brave, Firefox and their forks each launch a
+ * program registered as a native messaging host when the extension asks for it. The registration lists
+ * the exact extension origins allowed to launch it: both store listings always, plus the unpacked folder
+ * and whatever has paired, recomputed on every setup, every pairing and every Bridge start.
+ *
+ * A browser does not always read its own folder: Brave and Opera read Chrome's on macOS, and every
+ * Chromium fork on Windows falls back to Chrome's key. So Chrome's and Mozilla's locations are written
+ * whether or not those browsers are installed, and each installed browser's own location on top.
*/
import { execFileSync } from 'node:child_process';
-import { NATIVE_HOST_NAME } from '@/lib/actions/protocol';
-import { FIREFOX_ADDON_ID, STORE_EXTENSION_IDS } from '@/lib/stores';
import { createHash } from 'node:crypto';
-import { chmodSync, existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
+import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
-import { join, posix, win32 } from 'node:path';
+import { dirname, join, posix, win32 } from 'node:path';
+import { NATIVE_HOST_NAME } from '@/lib/actions/protocol';
+import { FIREFOX_ADDON_ID, STORE_EXTENSION_IDS } from '@/lib/stores';
import { listSessions } from './auth-store';
import { readAgentConfig } from './agent/config';
import { stateDir } from './lockfile';
import { log } from './log';
import { extensionDir } from './paths';
+import { registerBridgeTask, removeBridgeTask, windowsTasks, type TaskScheduler } from './windows-task';
export { NATIVE_HOST_NAME };
-type Family = 'chromium' | 'firefox';
+export type Family = 'chromium' | 'firefox';
export interface HostTarget {
browser: string;
family: Family;
- /** Where the browser keeps its profile; the host is only registered where the browser is installed. */
- home: string;
- /** macOS and Linux read the manifest from this directory. */
- manifestDir?: string;
- /** Windows reads the manifest path from this registry key. */
+ /** Any of these present means the browser is installed. */
+ installs: string[];
+ /** macOS and Linux: every folder this browser reads a manifest from, which is not always its own. */
+ manifestDirs?: string[];
+ /** Windows: the registry key this browser reads. */
registryKey?: string;
+ /** Written whether or not this browser is installed, because other browsers read it too. */
+ baseline?: boolean;
+}
+
+interface MacBrowser {
+ browser: string;
+ family?: Family;
+ /** Its folder under ~/Library/Application Support. */
+ profile: string;
+ apps: string[];
+ /** The folders under ~/Library/Application Support whose NativeMessagingHosts it reads. */
+ reads: string[];
+ baseline?: boolean;
}
-const MAC_BROWSERS: [string, Family, string][] = [
- ['Chrome', 'chromium', 'Google/Chrome'],
- ['Chrome for Testing', 'chromium', 'Google/Chrome for Testing'],
- ['Chromium', 'chromium', 'Chromium'],
- ['Edge', 'chromium', 'Microsoft Edge'],
- ['Brave', 'chromium', 'BraveSoftware/Brave-Browser'],
- ['Vivaldi', 'chromium', 'Vivaldi'],
- ['Arc', 'chromium', 'Arc/User Data'],
- ['Firefox', 'firefox', 'Mozilla'],
+const CHROME = 'Google/Chrome';
+const MOZILLA = 'Mozilla';
+
+const MAC_BROWSERS: MacBrowser[] = [
+ { browser: 'Chrome', profile: CHROME, apps: ['Google Chrome.app'], reads: [CHROME], baseline: true },
+ { browser: 'Chrome Beta', profile: 'Google/Chrome Beta', apps: ['Google Chrome Beta.app'], reads: ['Google/Chrome Beta'] },
+ { browser: 'Chrome Dev', profile: 'Google/Chrome Dev', apps: ['Google Chrome Dev.app'], reads: ['Google/Chrome Dev'] },
+ { browser: 'Chrome Canary', profile: 'Google/Chrome Canary', apps: ['Google Chrome Canary.app'], reads: ['Google/Chrome Canary'] },
+ {
+ browser: 'Chrome for Testing',
+ profile: 'Google/Chrome for Testing',
+ apps: ['Google Chrome for Testing.app'],
+ reads: ['Google/Chrome for Testing'],
+ },
+ { browser: 'Chromium', profile: 'Chromium', apps: ['Chromium.app'], reads: ['Chromium'] },
+ { browser: 'Edge', profile: 'Microsoft Edge', apps: ['Microsoft Edge.app'], reads: ['Microsoft Edge'] },
+ { browser: 'Edge Beta', profile: 'Microsoft Edge Beta', apps: ['Microsoft Edge Beta.app'], reads: ['Microsoft Edge Beta'] },
+ { browser: 'Edge Dev', profile: 'Microsoft Edge Dev', apps: ['Microsoft Edge Dev.app'], reads: ['Microsoft Edge Dev'] },
+ { browser: 'Edge Canary', profile: 'Microsoft Edge Canary', apps: ['Microsoft Edge Canary.app'], reads: ['Microsoft Edge Canary'] },
+ // brave-core points both host folders at Chrome's (brave_main_delegate.cc); its own is kept for when it stops.
+ { browser: 'Brave', profile: 'BraveSoftware/Brave-Browser', apps: ['Brave Browser.app'], reads: [CHROME, 'BraveSoftware/Brave-Browser'] },
+ {
+ browser: 'Brave Beta',
+ profile: 'BraveSoftware/Brave-Browser-Beta',
+ apps: ['Brave Browser Beta.app'],
+ reads: [CHROME, 'BraveSoftware/Brave-Browser-Beta'],
+ },
+ {
+ browser: 'Brave Nightly',
+ profile: 'BraveSoftware/Brave-Browser-Nightly',
+ apps: ['Brave Browser Nightly.app'],
+ reads: [CHROME, 'BraveSoftware/Brave-Browser-Nightly'],
+ },
+ { browser: 'Vivaldi', profile: 'Vivaldi', apps: ['Vivaldi.app'], reads: ['Vivaldi'] },
+ { browser: 'Arc', profile: 'Arc/User Data', apps: ['Arc.app'], reads: ['Arc/User Data', CHROME] },
+ { browser: 'Opera', profile: 'com.operasoftware.Opera', apps: ['Opera.app'], reads: [CHROME] },
+ { browser: 'Opera GX', profile: 'com.operasoftware.OperaGX', apps: ['Opera GX.app'], reads: [CHROME] },
+ { browser: 'Comet', profile: 'Comet', apps: ['Comet.app'], reads: [CHROME] },
+ { browser: 'Thorium', profile: 'Thorium', apps: ['Thorium.app'], reads: ['Thorium'] },
+ {
+ browser: 'Firefox',
+ family: 'firefox',
+ profile: 'Firefox',
+ apps: ['Firefox.app', 'Firefox Developer Edition.app', 'Firefox Nightly.app'],
+ reads: [MOZILLA],
+ baseline: true,
+ },
+ { browser: 'Zen', family: 'firefox', profile: 'zen', apps: ['Zen.app', 'Zen Browser.app'], reads: [MOZILLA] },
+ { browser: 'LibreWolf', family: 'firefox', profile: 'librewolf', apps: ['LibreWolf.app'], reads: [MOZILLA] },
+ { browser: 'Floorp', family: 'firefox', profile: 'Floorp', apps: ['Floorp.app'], reads: [MOZILLA] },
+ // Waterfox reads Mozilla's folder only from 6.7.6 on.
+ { browser: 'Waterfox', family: 'firefox', profile: 'Waterfox', apps: ['Waterfox.app'], reads: ['Waterfox', MOZILLA] },
];
const LINUX_BROWSERS: [string, Family, string, string][] = [
@@ -54,11 +114,13 @@ const LINUX_BROWSERS: [string, Family, string, string][] = [
['Firefox', 'firefox', '.mozilla', '.mozilla/native-messaging-hosts'],
];
+type WindowsRoot = 'LOCALAPPDATA' | 'APPDATA';
+
/**
* Every Chromium build falls back to Chrome's key, and only Chromium's own reads another first
- * (launch_context_win.cc), so Brave, Vivaldi and Chrome for Testing are let in through Chrome's.
+ * (launch_context_win.cc), so Brave, Vivaldi, Opera and Chrome for Testing are let in through Chrome's.
*/
-const WINDOWS_BROWSERS: [string, Family, string, 'LOCALAPPDATA' | 'APPDATA', string][] = [
+const WINDOWS_BROWSERS: [string, Family, string, WindowsRoot, string][] = [
['Chrome', 'chromium', 'Google\\Chrome', 'LOCALAPPDATA', 'Google\\Chrome\\User Data'],
['Chrome Beta', 'chromium', 'Google\\Chrome', 'LOCALAPPDATA', 'Google\\Chrome Beta\\User Data'],
['Chrome Dev', 'chromium', 'Google\\Chrome', 'LOCALAPPDATA', 'Google\\Chrome Dev\\User Data'],
@@ -73,23 +135,50 @@ const WINDOWS_BROWSERS: [string, Family, string, 'LOCALAPPDATA' | 'APPDATA', str
['Brave Beta', 'chromium', 'Google\\Chrome', 'LOCALAPPDATA', 'BraveSoftware\\Brave-Browser-Beta\\User Data'],
['Brave Nightly', 'chromium', 'Google\\Chrome', 'LOCALAPPDATA', 'BraveSoftware\\Brave-Browser-Nightly\\User Data'],
['Vivaldi', 'chromium', 'Google\\Chrome', 'LOCALAPPDATA', 'Vivaldi\\User Data'],
+ ['Opera', 'chromium', 'Google\\Chrome', 'APPDATA', 'Opera Software\\Opera Stable'],
+ ['Opera GX', 'chromium', 'Google\\Chrome', 'APPDATA', 'Opera Software\\Opera GX Stable'],
['Firefox', 'firefox', 'Mozilla', 'APPDATA', 'Mozilla\\Firefox'],
+ ['Zen', 'firefox', 'Mozilla', 'APPDATA', 'zen'],
+ ['LibreWolf', 'firefox', 'Mozilla', 'APPDATA', 'librewolf'],
+ ['Waterfox', 'firefox', 'Mozilla', 'APPDATA', 'Waterfox'],
+ ['Floorp', 'firefox', 'Mozilla', 'APPDATA', 'Floorp'],
];
+const WINDOWS_BASELINES = new Set(['Chrome', 'Firefox']);
+
/** Written for Brave up to 0.8.1, which never read it; an uninstall still takes it away. */
const RETIRED_WINDOWS_VENDORS = ['BraveSoftware\\Brave-Browser'];
const windowsKey = (vendor: string) => `HKCU\\Software\\${vendor}\\NativeMessagingHosts\\${NATIVE_HOST_NAME}`;
-export function hostTargets(platform: NodeJS.Platform = process.platform, home = homedir(), env = process.env): HostTarget[] {
+/** A macOS app that names its own Chromium user-data folder in Info.plist, as forks do. */
+export interface ChromiumFork {
+ browser: string;
+ app: string;
+ dataDir: string;
+}
+
+export function hostTargets(
+ platform: NodeJS.Platform = process.platform,
+ home = homedir(),
+ env = process.env,
+ forks: readonly ChromiumFork[] = [],
+): HostTarget[] {
if (platform === 'darwin') {
const support = posix.join(home, 'Library', 'Application Support');
- return MAC_BROWSERS.map(([browser, family, dir]) => ({
+ const hostsIn = (dir: string) => posix.join(support, dir, 'NativeMessagingHosts');
+ const known = MAC_BROWSERS.map(({ browser, family = 'chromium', profile, apps, reads, baseline }) => ({
browser,
family,
- home: posix.join(support, dir),
- manifestDir: posix.join(support, dir, 'NativeMessagingHosts'),
+ installs: [posix.join(support, profile), ...apps.flatMap((app) => macApps(home).map((root) => posix.join(root, app)))],
+ manifestDirs: reads.map(hostsIn),
+ baseline,
}));
+ const covered = new Set(MAC_BROWSERS.flatMap(({ apps }) => apps));
+ const discovered = forks
+ .filter((fork) => !covered.has(posix.basename(fork.app)))
+ .map((fork) => ({ browser: fork.browser, family: 'chromium' as const, installs: [fork.app], manifestDirs: [hostsIn(fork.dataDir)] }));
+ return [...known, ...discovered];
}
if (platform === 'win32') {
const roots = {
@@ -99,18 +188,64 @@ export function hostTargets(platform: NodeJS.Platform = process.platform, home =
return WINDOWS_BROWSERS.map(([browser, family, vendor, root, profile]) => ({
browser,
family,
- home: win32.join(roots[root], profile),
+ installs: [win32.join(roots[root], profile)],
registryKey: windowsKey(vendor),
+ baseline: WINDOWS_BASELINES.has(browser),
}));
}
return LINUX_BROWSERS.map(([browser, family, dir, manifests]) => ({
browser,
family,
- home: posix.join(home, dir),
- manifestDir: posix.join(home, manifests),
+ installs: [posix.join(home, dir)],
+ manifestDirs: [posix.join(home, manifests)],
}));
}
+const macApps = (home: string) => ['/Applications', posix.join(home, 'Applications')];
+
+const CR_PRODUCT_DIR = /<key>CrProductDirName<\/key>\s*<string>([^<]+)<\/string>/;
+
+/** Chromium derives a fork's host folder from CrProductDirName (chrome_paths_mac.mm), so a fork no table names still gets one. */
+export function chromiumForks(home = homedir()): ChromiumFork[] {
+ return macApps(home).flatMap((root) => {
+ let names: string[];
+ try {
+ names = readdirSync(root).filter((name) => name.endsWith('.app'));
+ } catch {
+ return [];
+ }
+ return names.flatMap((name) => {
+ const dataDir = productDir(posix.join(root, name, 'Contents', 'Info.plist'));
+ return dataDir ? [{ browser: name.slice(0, -'.app'.length), app: posix.join(root, name), dataDir }] : [];
+ });
+ });
+}
+
+function productDir(plist: string): string | undefined {
+ let raw: Buffer;
+ try {
+ raw = readFileSync(plist);
+ } catch {
+ return undefined;
+ }
+ if (!raw.includes('CrProductDirName')) return undefined;
+ const text = raw.toString('utf8');
+ const named = text.startsWith('bplist') ? binaryPlistValue(plist) : CR_PRODUCT_DIR.exec(text)?.[1];
+ const dir = named?.trim();
+ return dir && !dir.startsWith('/') && !dir.split('/').includes('..') ? dir : undefined;
+}
+
+function binaryPlistValue(plist: string): string | undefined {
+ try {
+ return execFileSync('plutil', ['-extract', 'CrProductDirName', 'raw', '-o', '-', plist], {
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'ignore'],
+ });
+ } catch {
+ return undefined;
+ }
+}
+
/**
* Chrome names an unpacked extension after its folder: the SHA-256 of the path, spelled in a–p.
* On Windows it hashes the path as UTF-16, with a lower-case drive letter raised first
@@ -138,7 +273,7 @@ export function allowedOrigins(platform: NodeJS.Platform = process.platform): st
export function hostManifest(family: Family, launcher: string, origins: readonly string[]): Record<string, unknown> {
return {
name: NATIVE_HOST_NAME,
- description: 'Starts the Browsentic daemon when the browser needs it',
+ description: 'Starts and connects to Browsentic Bridge when the browser needs it',
path: launcher,
type: 'stdio',
...(family === 'firefox' ? { allowed_extensions: [FIREFOX_ADDON_ID] } : { allowed_origins: origins }),
@@ -147,12 +282,17 @@ export function hostManifest(family: Family, launcher: string, origins: readonly
const shellQuote = (value: string) => `'${value.replace(/'/g, `'\\''`)}'`;
-export function launcherScript(options: {
- platform: NodeJS.Platform;
+export interface LauncherPins {
cliPath: string;
nodePath: string;
pathEnv: string;
-}): string {
+}
+
+/**
+ * A host must write nothing but its framed reply: Firefox up to 157 on macOS can wait forever on a host
+ * that writes to stderr (bug 1981177), and Node prints its own warnings there.
+ */
+export function launcherScript(options: LauncherPins & { platform: NodeJS.Platform }): string {
const { platform, cliPath, nodePath, pathEnv } = options;
if (platform === 'win32') {
// cmd.exe reads each line in the console's code page, which mangles a UTF-8 path like C:\Users\José.
@@ -160,6 +300,7 @@ export function launcherScript(options: {
'@echo off',
'chcp 65001 >nul',
`set "PATH=${pathEnv}"`,
+ 'set "NODE_NO_WARNINGS=1"',
`if exist "${cliPath}" (`,
` "${nodePath}" "${cliPath}" native-host %*`,
') else (',
@@ -171,7 +312,8 @@ export function launcherScript(options: {
return [
'#!/bin/sh',
`PATH=${shellQuote(pathEnv)}`,
- 'export PATH',
+ 'NODE_NO_WARNINGS=1',
+ 'export PATH NODE_NO_WARNINGS',
`NODE=${shellQuote(nodePath)}`,
'[ -x "$NODE" ] || NODE=node',
`CLI=${shellQuote(cliPath)}`,
@@ -181,6 +323,22 @@ export function launcherScript(options: {
].join('\n');
}
+const unquoteShell = (quoted: string) => quoted.replace(/'\\''/g, "'");
+
+/** What a launcher was pinned to, read back from the script itself. */
+export function launcherPins(script: string, platform: NodeJS.Platform): LauncherPins | null {
+ if (platform === 'win32') {
+ const run = /^\s*"([^"]+)" "([^"]+)" native-host %\*\s*$/m.exec(script);
+ const path = /^set "PATH=(.*)"\s*$/m.exec(script);
+ return run && path ? { nodePath: run[1], cliPath: run[2], pathEnv: path[1] } : null;
+ }
+ const quoted = (name: string) => new RegExp(`^${name}='((?:[^']|'\\\\'')*)'$`, 'm').exec(script)?.[1];
+ const [nodePath, cliPath, pathEnv] = ['NODE', 'CLI', 'PATH'].map(quoted);
+ return nodePath !== undefined && cliPath !== undefined && pathEnv !== undefined
+ ? { nodePath: unquoteShell(nodePath), cliPath: unquoteShell(cliPath), pathEnv: unquoteShell(pathEnv) }
+ : null;
+}
+
export const nativeHostDir = join(stateDir, 'native-host');
export const launcherPath = (platform: NodeJS.Platform = process.platform) =>
join(nativeHostDir, platform === 'win32' ? 'browsentic-native-host.cmd' : 'browsentic-native-host');
@@ -188,6 +346,8 @@ export const launcherPath = (platform: NodeJS.Platform = process.platform) =>
export interface HostInstall {
launcher: string;
browsers: string[];
+ /** Set when nothing was registered because this Bridge's state lives outside the home folder. */
+ skipped?: string;
}
/** The keys Windows browsers read. A test hands in its own. */
@@ -218,9 +378,28 @@ export interface HostOptions {
platform?: NodeJS.Platform;
home?: string;
env?: NodeJS.ProcessEnv;
- /** Whether a browser's profile is there. */
+ /** Whether a browser's profile or app is there. */
exists?: (path: string) => boolean;
registry?: Registry;
+ /** macOS apps that name their own Chromium data folder. */
+ forks?: () => readonly ChromiumFork[];
+ /** Where this Bridge keeps its state. */
+ state?: string;
+ /** Windows Task Scheduler, which starts the Bridge for Firefox. */
+ tasks?: TaskScheduler;
+}
+
+/**
+ * The user's browsers read one set of manifests and keys. A Bridge whose state lives outside the home
+ * folder, a scratch BROWSENTIC_HOME above all, must not point them at its own launcher, or the user's
+ * browsers would wake and pair with a throwaway Bridge.
+ */
+export function registersHosts({ state = stateDir, home = homedir(), env = process.env, platform = process.platform }: HostOptions = {}): boolean {
+ if (env.BROWSENTIC_REGISTER_HOST === '1') return true;
+ const path = platform === 'win32' ? win32 : posix;
+ const fold = (value: string) => (platform === 'win32' || platform === 'darwin' ? value.toLowerCase() : value);
+ const inside = path.relative(fold(home), fold(state));
+ return !!inside && !inside.startsWith('..') && !path.isAbsolute(inside);
}
const machine = ({
@@ -229,54 +408,114 @@ const machine = ({
env = process.env,
exists = existsSync,
registry = windowsRegistry,
-}: HostOptions) => ({ platform, targets: hostTargets(platform, home, env), exists, registry });
+ forks = () => (platform === 'darwin' ? chromiumForks(home) : []),
+}: HostOptions) => ({ platform, targets: hostTargets(platform, home, env, forks()), exists, registry });
+
+const installedTarget = (target: HostTarget, exists: (path: string) => boolean) => target.installs.some(exists);
+
+/** Leaves an unchanged file alone, and never leaves a half-written one where a browser reads it. */
+export function writeIfChanged(file: string, content: string): boolean {
+ if (existsSync(file) && readFileSync(file, 'utf8') === content) return false;
+ const temporary = `${file}.${process.pid}.tmp`;
+ writeFileSync(temporary, content);
+ renameSync(temporary, file);
+ return true;
+}
function register(launcher: string, options: HostOptions): string[] {
const { platform, targets, exists, registry } = machine(options);
const origins = allowedOrigins(platform);
- const registered: string[] = [];
- const written = new Set<string>();
- for (const target of targets.filter((candidate) => exists(candidate.home))) {
- const manifest = `${JSON.stringify(hostManifest(target.family, launcher, origins), null, 2)}\n`;
+ const chosen = targets.filter((target) => target.baseline || installedTarget(target, exists));
+ const done = new Map<string, boolean>();
+ const write = (location: string, family: Family, put: (manifest: string) => void) => {
+ if (done.has(location)) return done.get(location)!;
try {
- if (target.registryKey && !written.has(target.registryKey)) {
- const file = join(nativeHostDir, `${target.family}.json`);
- writeFileSync(file, manifest);
- registry.set(target.registryKey, file);
- written.add(target.registryKey);
- } else if (target.manifestDir) {
- mkdirSync(target.manifestDir, { recursive: true });
- writeFileSync(join(target.manifestDir, `${NATIVE_HOST_NAME}.json`), manifest);
- }
- registered.push(target.browser);
+ put(`${JSON.stringify(hostManifest(family, launcher, origins), null, 2)}\n`);
+ done.set(location, true);
} catch (error) {
- log(`native host: could not register for ${target.browser}: ${String(error)}`);
+ log(`native host: could not register at ${location}: ${String(error)}`);
+ done.set(location, false);
+ }
+ return done.get(location)!;
+ };
+ for (const target of chosen) {
+ if (target.registryKey) {
+ write(target.registryKey, target.family, (manifest) => {
+ const file = join(nativeHostDir, `${target.family}.json`);
+ writeIfChanged(file, manifest);
+ registry.set(target.registryKey!, file);
+ });
+ }
+ for (const dir of target.manifestDirs ?? []) {
+ write(dir, target.family, (manifest) => {
+ mkdirSync(dir, { recursive: true });
+ writeIfChanged(join(dir, `${NATIVE_HOST_NAME}.json`), manifest);
+ });
}
}
- return registered;
+ const reached = (target: HostTarget) => [target.registryKey, ...(target.manifestDirs ?? [])].some((location) => !!location && done.get(location));
+ return chosen.filter((target) => installedTarget(target, exists) && reached(target)).map((target) => target.browser);
}
+const SKIPPED = 'this Bridge keeps its state outside your home folder, so it leaves your browsers registered with the one that does not';
+
+const daemonMainBeside = (cliPath: string) => join(dirname(cliPath), 'daemon-main.js');
+
export function installNativeHost(cliPath: string, options: HostOptions = {}): HostInstall {
- const { platform = process.platform } = options;
+ const { platform = process.platform, tasks = windowsTasks } = options;
const launcher = launcherPath(platform);
+ if (!registersHosts(options)) return { launcher, browsers: [], skipped: SKIPPED };
mkdirSync(nativeHostDir, { recursive: true, mode: 0o700 });
- writeFileSync(launcher, launcherScript({ platform, cliPath, nodePath: process.execPath, pathEnv: process.env.PATH ?? '' }));
- if (platform !== 'win32') chmodSync(launcher, 0o755);
+ writeLauncher({ cliPath, nodePath: process.execPath, pathEnv: process.env.PATH ?? '' }, platform);
+ if (platform === 'win32') registerBridgeTask(process.execPath, daemonMainBeside(cliPath), tasks);
return { launcher, browsers: register(launcher, options) };
}
-/** A newly paired browser has to be let in; the launcher stays as setup wrote it. */
-export function refreshNativeHost(options: HostOptions = {}): void {
- const launcher = launcherPath(options.platform);
- if (!existsSync(launcher)) return;
+function writeLauncher(pins: LauncherPins, platform: NodeJS.Platform): void {
+ const launcher = launcherPath(platform);
+ if (writeIfChanged(launcher, launcherScript({ ...pins, platform })) && platform !== 'win32') chmodSync(launcher, 0o755);
+}
+
+export interface Refresh extends HostOptions {
+ /** The CLI this Bridge runs from, to repin a launcher whose own CLI or Node has gone. */
+ cliPath?: string;
+ nodePath?: string;
+}
+
+/**
+ * Re-registers with what is installed now, letting in whatever has paired since. A launcher whose
+ * Node or CLI has gone (a Node upgrade, a moved payload) is repinned to the ones this Bridge runs on.
+ */
+export function refreshNativeHost(options: Refresh = {}): void {
+ const { platform = process.platform, cliPath, nodePath = process.execPath, exists = existsSync, tasks = windowsTasks } = options;
+ const launcher = launcherPath(platform);
+ if (!existsSync(launcher) || !registersHosts(options)) return;
+ const pinned = launcherPins(readFileSync(launcher, 'utf8'), platform);
+ const healed = pinned && {
+ pathEnv: pinned.pathEnv,
+ cliPath: exists(pinned.cliPath) || !cliPath || !exists(cliPath) ? pinned.cliPath : cliPath,
+ nodePath: exists(pinned.nodePath) || !exists(nodePath) ? pinned.nodePath : nodePath,
+ };
+ try {
+ if (healed) writeLauncher(healed, platform);
+ } catch (error) {
+ log(`native host: could not rewrite the launcher: ${String(error)}`);
+ }
+ if (healed && (healed.cliPath !== pinned.cliPath || healed.nodePath !== pinned.nodePath)) {
+ log(`native host: repinned the launcher to ${healed.nodePath} ${healed.cliPath}`);
+ if (platform === 'win32') registerBridgeTask(healed.nodePath, daemonMainBeside(healed.cliPath), tasks);
+ }
register(launcher, options);
}
export function removeNativeHost(options: HostOptions = {}): string[] {
+ if (!registersHosts(options)) return [];
const { platform, targets, registry } = machine(options);
const removed: string[] = [];
+ if (platform === 'win32' && removeBridgeTask(options.tasks)) removed.push('the Browsentic\\Bridge task');
if (platform === 'win32') {
- for (const key of new Set([...targets.map((target) => target.registryKey!), ...RETIRED_WINDOWS_VENDORS.map(windowsKey)])) {
+ const keys = new Set([...targets.map((target) => target.registryKey!), ...RETIRED_WINDOWS_VENDORS.map(windowsKey)]);
+ for (const key of keys) {
try {
registry.remove(key);
removed.push(key);
@@ -285,8 +524,8 @@ export function removeNativeHost(options: HostOptions = {}): string[] {
}
}
}
- for (const target of targets.filter((candidate) => candidate.manifestDir)) {
- const manifest = join(target.manifestDir!, `${NATIVE_HOST_NAME}.json`);
+ for (const dir of new Set(targets.flatMap((target) => target.manifestDirs ?? []))) {
+ const manifest = join(dir, `${NATIVE_HOST_NAME}.json`);
if (!existsSync(manifest)) continue;
try {
rmSync(manifest, { force: true });
@@ -302,7 +541,7 @@ export function removeNativeHost(options: HostOptions = {}): string[] {
return removed;
}
-/** The installed browsers that can start the daemon, read back from where each one looks. */
+/** The installed browsers that can start the Bridge, read back from where each one looks. */
export function registeredBrowsers(options: HostOptions = {}): string[] {
const { platform, targets, exists, registry } = machine(options);
if (!existsSync(launcherPath(platform))) return [];
@@ -312,67 +551,28 @@ export function registeredBrowsers(options: HostOptions = {}): string[] {
return keys.get(key)!;
};
return targets
- .filter((target) => exists(target.home))
+ .filter((target) => installedTarget(target, exists))
.filter((target) =>
- target.registryKey ? hasKey(target.registryKey) : existsSync(join(target.manifestDir!, `${NATIVE_HOST_NAME}.json`)),
+ target.registryKey
+ ? hasKey(target.registryKey)
+ : (target.manifestDirs ?? []).some((dir) => existsSync(join(dir, `${NATIVE_HOST_NAME}.json`))),
)
.map((target) => target.browser);
}
-export function encodeNativeMessage(value: unknown): Buffer {
- const body = Buffer.from(JSON.stringify(value), 'utf8');
- const head = Buffer.alloc(4);
- head.writeUInt32LE(body.length, 0);
- return Buffer.concat([head, body]);
-}
-
-export function decodeNativeMessage(buffer: Buffer): unknown | undefined {
- if (buffer.length < 4) return undefined;
- const length = buffer.readUInt32LE(0);
- if (buffer.length < 4 + length) return undefined;
- try {
- return JSON.parse(buffer.subarray(4, 4 + length).toString('utf8'));
- } catch {
- return null;
- }
-}
-
-function readNativeMessage(input: NodeJS.ReadableStream): Promise<unknown> {
- return new Promise((resolve) => {
- let held = Buffer.alloc(0);
- const done = (value: unknown) => {
- input.removeAllListeners('data');
- resolve(value);
- };
- input.on('data', (chunk: Buffer) => {
- held = Buffer.concat([held, chunk]);
- const message = decodeNativeMessage(held);
- if (message !== undefined) done(message);
- });
- input.on('end', () => done(null));
+/** Whether every manifest this Bridge wrote still lets in both store copies; one an older Bridge wrote may not. */
+export function registrationCurrent(options: HostOptions = {}): boolean {
+ const { platform, targets } = machine(options);
+ const files =
+ platform === 'win32'
+ ? (['chromium'] as const).map((family) => join(nativeHostDir, `${family}.json`))
+ : targets.filter((target) => target.family === 'chromium').flatMap((target) => (target.manifestDirs ?? []).map((dir) => join(dir, `${NATIVE_HOST_NAME}.json`)));
+ return files.filter(existsSync).every((file) => {
+ try {
+ const origins = (JSON.parse(readFileSync(file, 'utf8')) as { allowed_origins?: string[] }).allowed_origins ?? [];
+ return STORE_EXTENSION_IDS.every((id) => origins.includes(`chrome-extension://${id}/`));
+ } catch {
+ return false;
+ }
});
}
-
-export const STOPPED_REPLY = { ok: false, error: 'Stopped with "browsentic stop"; "browsentic start" lets the browser start it again.' };
-
-export async function serveNativeHost(ensure: () => Promise<{ port: number }>, held: () => boolean): Promise<void> {
- const message = (await readNativeMessage(process.stdin)) as { op?: unknown } | null;
- const reply = await answerNativeMessage(message, ensure, held);
- if (reply !== STOPPED_REPLY) {
- log(`native host: ${reply.ok ? 'daemon ready' : `could not start the daemon — ${'error' in reply ? reply.error : ''}`}`);
- }
- await new Promise<void>((resolve) => process.stdout.write(encodeNativeMessage(reply), () => resolve()));
-}
-
-export async function answerNativeMessage(
- message: { op?: unknown } | null,
- ensure: () => Promise<{ port: number }>,
- held: () => boolean,
-): Promise<{ ok: boolean; port?: number; error?: string }> {
- if (message?.op !== 'ensure') return { ok: false, error: 'Expected {"op":"ensure"}.' };
- if (held()) return STOPPED_REPLY;
- return ensure()
- .then((lock) => ({ ok: true, port: lock.port }))
- .catch((error) => ({ ok: false, error: String(error) }));
-}
-
diff --git a/src/daemon/native-messaging.test.ts b/src/daemon/native-messaging.test.ts
new file mode 100644
index 0000000..a9e357c
--- /dev/null
+++ b/src/daemon/native-messaging.test.ts
@@ -0,0 +1,57 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { STOPPED_REPLY, answerNativeMessage, callerOf, decodeNativeMessage, encodeNativeMessage } from './native-messaging';
+
+describe('the message frame', () => {
+ it('round-trips a message and waits for a whole one', () => {
+ const frame = encodeNativeMessage({ op: 'ensure' });
+ expect(frame.readUInt32LE(0)).toBe(frame.length - 4);
+ expect(decodeNativeMessage(frame)).toEqual({ op: 'ensure' });
+ expect(decodeNativeMessage(frame.subarray(0, frame.length - 1))).toBeUndefined();
+ });
+});
+
+describe('callerOf', () => {
+ const origin = 'chrome-extension://npmocgldfflonjjmdadmdefpnfagnjmp/';
+
+ it('reads the origin Chromium passes, wherever it sits, past --parent-window on Windows', () => {
+ expect(callerOf([origin])).toEqual({ family: 'chromium', origin });
+ expect(callerOf(['--parent-window=0', origin])).toEqual({ family: 'chromium', origin });
+ expect(callerOf([origin.slice(0, -1)])).toEqual({ family: 'chromium', origin });
+ });
+
+ it('reads the add-on id Firefox passes after the manifest path', () => {
+ expect(callerOf(['/Users/me/Library/Application Support/Mozilla/NativeMessagingHosts/x.json', '[email protected]'])).toEqual({
+ family: 'firefox',
+ addonId: '[email protected]',
+ });
+ });
+
+ it('names nobody it cannot recognise', () => {
+ expect(callerOf([])).toBeNull();
+ expect(callerOf(['chrome-extension://not-an-id/'])).toBeNull();
+ expect(callerOf(['[email protected]'])).toBeNull();
+ });
+});
+
+describe('answering ensure', () => {
+ const ensure = vi.fn(async () => ({ port: 8765 }));
+ const context = (held = false) => ({ ensure, held: () => held });
+
+ beforeEach(() => ensure.mockClear());
+
+ it('starts the daemon when asked, saying who asked', async () => {
+ const caller = { family: 'firefox', addonId: '[email protected]' } as const;
+ expect(await answerNativeMessage({ op: 'ensure' }, context(), caller)).toEqual({ ok: true, port: 8765 });
+ expect(ensure).toHaveBeenCalledWith(caller);
+ });
+
+ it('leaves a daemon stopped on purpose down', async () => {
+ expect(await answerNativeMessage({ op: 'ensure' }, context(true))).toBe(STOPPED_REPLY);
+ expect(ensure).not.toHaveBeenCalled();
+ });
+
+ it('refuses anything it does not know, in the words shipped extensions read', async () => {
+ expect(await answerNativeMessage({ op: 'spawn' }, context())).toEqual({ ok: false, error: 'Expected {"op":"ensure"}.' });
+ expect(ensure).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/daemon/native-messaging.ts b/src/daemon/native-messaging.ts
new file mode 100644
index 0000000..f44a9ca
--- /dev/null
+++ b/src/daemon/native-messaging.ts
@@ -0,0 +1,92 @@
+/**
+ * The host process a browser launches: one framed message in, one framed reply out, then exit.
+ * Stdout carries only that reply and stderr carries nothing, because a browser reads a stray byte
+ * as a broken host, and Firefox up to 157 on macOS can hang on a host's stderr (bug 1981177).
+ */
+
+import { FIREFOX_ADDON_ID } from '@/lib/stores';
+import { log } from './log';
+
+export function encodeNativeMessage(value: unknown): Buffer {
+ const body = Buffer.from(JSON.stringify(value), 'utf8');
+ const head = Buffer.alloc(4);
+ head.writeUInt32LE(body.length, 0);
+ return Buffer.concat([head, body]);
+}
+
+export function decodeNativeMessage(buffer: Buffer): unknown | undefined {
+ if (buffer.length < 4) return undefined;
+ const length = buffer.readUInt32LE(0);
+ if (buffer.length < 4 + length) return undefined;
+ try {
+ return JSON.parse(buffer.subarray(4, 4 + length).toString('utf8'));
+ } catch {
+ return null;
+ }
+}
+
+function readNativeMessage(input: NodeJS.ReadableStream): Promise<unknown> {
+ return new Promise((resolve) => {
+ let held = Buffer.alloc(0);
+ const done = (value: unknown) => {
+ input.removeAllListeners('data');
+ resolve(value);
+ };
+ input.on('data', (chunk: Buffer) => {
+ held = Buffer.concat([held, chunk]);
+ const message = decodeNativeMessage(held);
+ if (message !== undefined) done(message);
+ });
+ input.on('end', () => done(null));
+ });
+}
+
+/** Who launched this host, from the arguments the browser passes: an origin from Chromium, the add-on id from Firefox. */
+export type Caller = { family: 'chromium'; origin: string } | { family: 'firefox'; addonId: string };
+
+const CHROMIUM_CALLER = /^chrome-extension:\/\/[a-p]{32}\/?$/;
+
+export function callerOf(argv: readonly string[]): Caller | null {
+ const origin = argv.find((arg) => CHROMIUM_CALLER.test(arg));
+ if (origin) return { family: 'chromium', origin: origin.endsWith('/') ? origin : `${origin}/` };
+ return argv.includes(FIREFOX_ADDON_ID) ? { family: 'firefox', addonId: FIREFOX_ADDON_ID } : null;
+}
+
+export const STOPPED_REPLY = { ok: false, error: 'Stopped with "browsentic stop"; "browsentic start" lets the browser start it again.' };
+
+export interface HostContext {
+ /** Starts the Bridge if it is down, and says where it listens. */
+ ensure: (caller: Caller | null) => Promise<{ port: number }>;
+ /** True while `browsentic stop` holds the Bridge down. */
+ held: () => boolean;
+}
+
+export async function serveNativeHost(context: HostContext, argv: readonly string[] = process.argv.slice(3)): Promise<void> {
+ silenceStderr();
+ const caller = callerOf(argv);
+ const message = (await readNativeMessage(process.stdin)) as { op?: unknown } | null;
+ const reply = await answerNativeMessage(message, context, caller);
+ if (reply !== STOPPED_REPLY) {
+ log(`native host: ${reply.ok ? 'daemon ready' : `could not start the daemon — ${'error' in reply ? reply.error : ''}`}`);
+ }
+ await new Promise<void>((resolve) => process.stdout.write(encodeNativeMessage(reply), () => resolve()));
+}
+
+function silenceStderr(): void {
+ process.stderr.write = ((chunk: string | Uint8Array) => {
+ log(`native host stderr: ${String(chunk).trim()}`);
+ return true;
+ }) as typeof process.stderr.write;
+}
+
+export async function answerNativeMessage(
+ message: { op?: unknown } | null,
+ { ensure, held }: HostContext,
+ caller: Caller | null = null,
+): Promise<{ ok: boolean; port?: number; error?: string }> {
+ if (message?.op !== 'ensure') return { ok: false, error: 'Expected {"op":"ensure"}.' };
+ if (held()) return STOPPED_REPLY;
+ return ensure(caller)
+ .then((lock) => ({ ok: true, port: lock.port }))
+ .catch((error) => ({ ok: false, error: String(error) }));
+}
diff --git a/src/daemon/windows-task.ts b/src/daemon/windows-task.ts
new file mode 100644
index 0000000..f8d6b7a
--- /dev/null
+++ b/src/daemon/windows-task.ts
@@ -0,0 +1,92 @@
+/**
+ * Firefox on Windows runs a native host inside a job object and terminates the whole job once the host
+ * exits (subprocess_win.worker.js), and libuv's detached spawn does not ask to break away from it. So a
+ * Bridge the host starts there would die a moment after it came up. A per-user scheduled task is started
+ * by Task Scheduler, outside any job, in the user's own session.
+ */
+
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { stateDir } from './lockfile';
+import { log } from './log';
+
+export const BRIDGE_TASK = 'Browsentic\\Bridge';
+
+export interface TaskScheduler {
+ register(xmlFile: string): void;
+ run(): void;
+ remove(): void;
+}
+
+const schtasks = (args: string[]) => execFileSync('schtasks', args, { stdio: 'ignore', windowsHide: true });
+
+export const windowsTasks: TaskScheduler = {
+ register: (xmlFile) => schtasks(['/Create', '/TN', BRIDGE_TASK, '/XML', xmlFile, '/F']),
+ run: () => schtasks(['/Run', '/TN', BRIDGE_TASK]),
+ remove: () => schtasks(['/Delete', '/TN', BRIDGE_TASK, '/F']),
+};
+
+const escapeXml = (value: string) =>
+ value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&apos;');
+
+/** No trigger: it runs only when asked. `conhost --headless` keeps Node's console window from showing. */
+export function bridgeTaskXml(nodePath: string, daemonMain: string): string {
+ return [
+ '<?xml version="1.0" encoding="UTF-16"?>',
+ '<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">',
+ ' <RegistrationInfo><Description>Starts Browsentic Bridge when Firefox asks for it.</Description></RegistrationInfo>',
+ ' <Principals><Principal id="Author"><LogonType>InteractiveToken</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals>',
+ ' <Settings>',
+ ' <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>',
+ ' <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>',
+ ' <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>',
+ ' <AllowStartOnDemand>true</AllowStartOnDemand>',
+ ' <Hidden>true</Hidden>',
+ ' <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>',
+ ' </Settings>',
+ ' <Actions Context="Author">',
+ ' <Exec>',
+ ' <Command>conhost.exe</Command>',
+ ` <Arguments>--headless "${escapeXml(nodePath)}" "${escapeXml(daemonMain)}"</Arguments>`,
+ ' </Exec>',
+ ' </Actions>',
+ '</Task>',
+ '',
+ ].join('\r\n');
+}
+
+export function registerBridgeTask(nodePath: string, daemonMain: string, tasks: TaskScheduler = windowsTasks): boolean {
+ const dir = join(stateDir, 'native-host');
+ const file = join(dir, 'bridge-task.xml');
+ try {
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
+ writeFileSync(file, Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(bridgeTaskXml(nodePath, daemonMain), 'utf16le')]));
+ tasks.register(file);
+ return true;
+ } catch (error) {
+ log(`native host: could not register the ${BRIDGE_TASK} task: ${String(error)}`);
+ return false;
+ } finally {
+ rmSync(file, { force: true });
+ }
+}
+
+export function runBridgeTask(tasks: TaskScheduler = windowsTasks): boolean {
+ try {
+ tasks.run();
+ return true;
+ } catch (error) {
+ log(`native host: could not run the ${BRIDGE_TASK} task: ${String(error)}`);
+ return false;
+ }
+}
+
+export function removeBridgeTask(tasks: TaskScheduler = windowsTasks): boolean {
+ try {
+ tasks.remove();
+ return true;
+ } catch {
+ return false;
+ }
+}
diff --git a/src/windows/src-tauri/installer-hooks.nsh b/src/windows/src-tauri/installer-hooks.nsh
index 5eb9d6a..8eb839f 100644
--- a/src/windows/src-tauri/installer-hooks.nsh
+++ b/src/windows/src-tauri/installer-hooks.nsh
@@ -1,6 +1,6 @@
-; An update runs the old uninstaller too, with /UPDATE; only a real uninstall stops the daemon and
-; takes browsentic off the PATH. What the daemon keeps in ~/.browsentic stays, as it does when the
-; macOS app goes to the Trash; the app's own Uninstall removes that.
+; An update runs the old uninstaller too, with /UPDATE; only a real uninstall unregisters the
+; browsers' native host, stops the daemon and takes browsentic off the PATH. What the daemon keeps in
+; ~/.browsentic stays, as it does when the macOS app goes to the Trash; the app's own Uninstall removes that.
!macro NSIS_HOOK_PREUNINSTALL
${If} $UpdateMode <> 1
ExecWait '"$INSTDIR\${MAINBINARYNAME}.exe" --uninstall'
diff --git a/src/windows/src-tauri/src/main.rs b/src/windows/src-tauri/src/main.rs
index 21ea607..2333e36 100644
--- a/src/windows/src-tauri/src/main.rs
+++ b/src/windows/src-tauri/src/main.rs
@@ -197,15 +197,18 @@ async fn install_update(app: AppHandle) -> Result<()> {
update::install(&app).await
}
-/// Run by the uninstaller before the app's files go: stop the daemon and take browsentic off the PATH.
+/// Run by the uninstaller before the app's files go: take the browsers' way of starting the daemon
+/// away first, so none starts it again, then stop it and take browsentic off the PATH.
fn prepare_uninstall() {
let paths = paths::Paths::from_env();
if paths.shim().is_file() {
- let mut stop = std::process::Command::new(paths.shim());
- stop.arg("stop").current_dir(&paths.home);
- #[cfg(windows)]
- std::os::windows::process::CommandExt::creation_flags(&mut stop, 0x0800_0000);
- let _ = stop.status();
+ for command in ["unregister-host", "stop"] {
+ let mut run = std::process::Command::new(paths.shim());
+ run.arg(command).current_dir(&paths.home);
+ #[cfg(windows)]
+ std::os::windows::process::CommandExt::creation_flags(&mut run, 0x0800_0000);
+ let _ = run.status();
+ }
}
let _ = path_env::unlink(&paths.bin());
}