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(daemon): the Bridge goes through launchd whenever its caller is quarantined, waits for a launchd job still running instead of booting it out, spawns one itself if that job never answers, retries a bootstrap launchd was not ready for, and is taken out of launchd on uninstall; a library the user allowed with Open Anyway is kept, and the sweep no longer holds up the daemon's start

Shahriar208b9671d41c
diff --git a/docs/internals/extension.md b/docs/internals/extension.md
index d1369db..5ecbea5 100644
--- a/docs/internals/extension.md
+++ b/docs/internals/extension.md
@@ -574,10 +574,11 @@ only; **Always on ‹site›** stays in the panel.
`nativeMessaging` is what lets a browser start a daemon that is down. When no port answers,
`giveUp` calls `wakeDaemon`, which asks the browser to run the `com.browsentic.daemon` host that
-`browsentic setup` registered. That host runs `ensureDaemon` and exits. On macOS it starts the daemon
-as a launchd job, not as its own child: a browser runs its native hosts quarantined, and a daemon
-the host spawned would pass that on to every file it and its agents write, so Gatekeeper would
-refuse any code they unpack (`src/daemon/quarantine.ts`). `browsentic stop` leaves
+`browsentic setup` registered. That host runs `ensureDaemon` and exits. On macOS a browser runs its
+native hosts quarantined, and a daemon the host spawned would pass that on to every file it and its
+agents write, so Gatekeeper would refuse any code they unpack. So whenever a probe file the caller
+writes comes out quarantined, `ensureDaemon` starts the daemon as a launchd job instead of as its own
+child, and waits for one that launchd is still running (`src/daemon/quarantine.ts`). `browsentic stop` leaves
`~/.browsentic/stopped` behind, and while it is there the host starts nothing; the next daemon to
start, by any other path, removes it.
diff --git a/src/daemon/cli.ts b/src/daemon/cli.ts
index cb1f28e..81fe02b 100644
--- a/src/daemon/cli.ts
+++ b/src/daemon/cli.ts
@@ -154,7 +154,7 @@ switch (command) {
break;
case 'native-host':
await serveNativeHost({
- ensure: (caller) => ensureDaemon({ outsideJob: caller?.family === 'firefox', outsideBrowser: true }),
+ ensure: (caller) => ensureDaemon({ outsideJob: caller?.family === 'firefox' }),
held: wakeHeld,
mode: () => pairingMode(),
version: pkg.version,
diff --git a/src/daemon/daemon-main.ts b/src/daemon/daemon-main.ts
index 73cbc9d..b6718a5 100644
--- a/src/daemon/daemon-main.ts
+++ b/src/daemon/daemon-main.ts
@@ -14,12 +14,14 @@ const daemon = await startDaemon({
process.exit(1);
});
-if (process.platform === 'darwin') {
- for (const file of dropQuarantinedBunLibraries()) log(`removed ${file}, a library an agent unpacked while the Bridge ran quarantined`);
-}
-
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
process.on(signal, () => {
void daemon.stop().then(() => process.exit(0));
});
}
+
+if (process.platform === 'darwin') {
+ void dropQuarantinedBunLibraries().then((dropped) => {
+ for (const file of dropped) log(`removed ${file}, a library an agent unpacked while the Bridge ran quarantined`);
+ });
+}
diff --git a/src/daemon/ensure-daemon.ts b/src/daemon/ensure-daemon.ts
index 60da4be..5420663 100644
--- a/src/daemon/ensure-daemon.ts
+++ b/src/daemon/ensure-daemon.ts
@@ -5,7 +5,7 @@ import { dirname, join } from 'node:path';
import { clearLockfile, holdWake, isRunning, readLockfile, stateDir, type Lockfile } from './lockfile';
import { log } from './log';
import { daemonPorts } from './ports';
-import { startBridgeJob } from './quarantine';
+import { runsQuarantined, startBridgeJob } from './quarantine';
import { runBridgeTask } from './windows-task';
const SPAWN_TIMEOUT_MS = 8_000;
@@ -18,8 +18,6 @@ export const daemonMainPath = () => join(dirname(fileURLToPath(import.meta.url))
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;
- /** Start it through launchd: the caller is a browser's native host, quarantined on macOS (see quarantine.ts). */
- outsideBrowser?: boolean;
}
/**
@@ -70,7 +68,7 @@ function readStartLock(): [number, number] {
}
/** One the task started is waited for, never doubled by one spawned in the job that is about to die. */
-async function spawnDaemon({ outsideJob = false, outsideBrowser = false }: EnsureOptions): Promise<Lockfile> {
+async function spawnDaemon({ outsideJob = false }: EnsureOptions): Promise<Lockfile> {
if (outsideJob && process.platform === 'win32' && runBridgeTask()) {
log('no daemon reachable; starting one through Task Scheduler');
return cameUp();
@@ -80,11 +78,14 @@ async function spawnDaemon({ outsideJob = false, outsideBrowser = false }: Ensur
delete env.CLAUDECODE;
delete env.CLAUDE_CODE_ENTRYPOINT;
delete env.NODE_NO_WARNINGS;
- if (outsideBrowser && process.platform === 'darwin' && startBridgeJob(process.execPath, daemonMainPath(), env)) {
+ if (process.platform === 'darwin' && runsQuarantined() && (await startBridgeJob(process.execPath, daemonMainPath(), env))) {
log('no daemon reachable; starting one through launchd');
- return cameUp();
+ const started = await waitForDaemon(SPAWN_TIMEOUT_MS);
+ if (started) return started;
+ log(`the Bridge launchd started did not answer within ${SPAWN_TIMEOUT_MS}ms; spawning one`);
+ } else {
+ log('no daemon reachable; spawning one');
}
- log('no daemon reachable; spawning one');
const child = spawn(process.execPath, [daemonMainPath()], {
detached: true,
stdio: 'ignore',
diff --git a/src/daemon/native-host.test.ts b/src/daemon/native-host.test.ts
index 57c3b24..621e8e1 100644
--- a/src/daemon/native-host.test.ts
+++ b/src/daemon/native-host.test.ts
@@ -23,6 +23,7 @@ import {
} from './native-host';
import { extensionDir } from './paths';
import { bits, modeOf } from './test/modes';
+import { BRIDGE_JOB, type Launchd } from './quarantine';
import type { TaskScheduler } from './windows-task';
const STORE_ORIGINS = ['chrome-extension://cbkjhkgjcpihokphhdkbahilpcjojpdc/', 'chrome-extension://npmocgldfflonjjmdadmdefpnfagnjmp/'];
@@ -274,14 +275,22 @@ 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`);
+ let bootedOut: string[] = [];
+ const jobs: Launchd = { state: () => 'idle', bootout: (label) => void bootedOut.push(label), bootstrap: () => {} };
const mac = (installed: string[], forks: { browser: string; app: string; dataDir: string }[] = []) =>
- ({ platform: 'darwin', home, forks: () => forks, exists: (path: string) => installed.includes(path) }) as const;
+ ({ platform: 'darwin', home, forks: () => forks, exists: (path: string) => installed.includes(path), jobs }) as const;
beforeEach(() => {
removeNativeHost(mac([]));
rmSync(support, { recursive: true, force: true });
});
+ it('takes away the launchd job that starts the Bridge on uninstall', () => {
+ bootedOut = [];
+ expect(removeNativeHost(mac([]))).toContain(`the ${BRIDGE_JOB} launchd job`);
+ expect(bootedOut).toEqual([BRIDGE_JOB]);
+ });
+
it('writes Chrome’s and Mozilla’s folders even when neither browser is installed', () => {
const installed = installNativeHost('/opt/browsentic/dist/cli.js', mac([]));
diff --git a/src/daemon/native-host.ts b/src/daemon/native-host.ts
index 90f5309..e6ba1a1 100644
--- a/src/daemon/native-host.ts
+++ b/src/daemon/native-host.ts
@@ -21,6 +21,7 @@ import { readAgentConfig } from './agent/config';
import { stateDir } from './lockfile';
import { log } from './log';
import { extensionDir } from './paths';
+import { BRIDGE_JOB, removeBridgeJob, type Launchd } from './quarantine';
import { BRIDGE_TASK, registerBridgeTask, removeBridgeTask, windowsTasks, type TaskScheduler } from './windows-task';
export { NATIVE_HOST_NAME };
@@ -390,6 +391,8 @@ export interface HostOptions {
state?: string;
/** Windows Task Scheduler, which starts the Bridge for Firefox. */
tasks?: TaskScheduler;
+ /** macOS launchd, which starts the Bridge for a quarantined caller. */
+ jobs?: Launchd;
}
/**
@@ -519,6 +522,7 @@ export function removeNativeHost(options: HostOptions = {}): string[] {
const { platform, targets, registry } = machine(options);
const removed: string[] = [];
if (platform === 'win32' && removeBridgeTask(options.tasks)) removed.push(`the ${BRIDGE_TASK} task`);
+ if (platform === 'darwin' && removeBridgeJob(options.jobs)) removed.push(`the ${BRIDGE_JOB} launchd job`);
if (platform === 'win32') {
const keys = new Set([...targets.map((target) => target.registryKey!), ...RETIRED_WINDOWS_VENDORS.map(windowsKey)]);
for (const key of keys) {
diff --git a/src/daemon/quarantine.test.ts b/src/daemon/quarantine.test.ts
index 3718563..ad0f866 100644
--- a/src/daemon/quarantine.test.ts
+++ b/src/daemon/quarantine.test.ts
@@ -3,39 +3,82 @@ import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSy
import { tmpdir } from 'node:os';
import { basename, join } from 'node:path';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { BRIDGE_JOB, bridgeJobPlist, dropQuarantinedBunLibraries, startBridgeJob, type Launchd } from './quarantine';
+import {
+ BRIDGE_JOB,
+ bridgeJobPlist,
+ dropQuarantinedBunLibraries,
+ removeBridgeJob,
+ runsQuarantined,
+ startBridgeJob,
+ type JobState,
+ type Launchd,
+} from './quarantine';
const onMac = process.platform === 'darwin';
+const logged = () => readFileSync(join(process.env.BROWSENTIC_HOME!, 'daemon.log'), 'utf8');
-describe('the launchd job that starts the Bridge outside the browser', () => {
- let loaded: { plist: string; label: string; existed: boolean }[];
+function fakeLaunchd(state: JobState, refusals = 0) {
+ const calls: string[] = [];
+ const plists: string[] = [];
const jobs: Launchd = {
- load: (file, label) => void loaded.push({ plist: readFileSync(file, 'utf8'), label, existed: existsSync(file) }),
+ state: () => state,
+ bootout: (label) => void calls.push(`bootout ${label}`),
+ bootstrap: (file) => {
+ calls.push(`bootstrap ${existsSync(file)}`);
+ plists.push(readFileSync(file, 'utf8'));
+ if (refusals-- > 0) throw new Error('Bootstrap failed: 5: Input/output error');
+ },
};
+ return { jobs, calls, plists };
+}
+
+describe('the launchd job that starts the Bridge outside a quarantined caller', () => {
+ it('runs the daemon once, now, with the environment it is handed', async () => {
+ const { jobs, calls, plists } = fakeLaunchd('absent');
+
+ expect(await startBridgeJob('/opt/node/bin/node', '/Users/me/cli/dist/daemon-main.js', { PATH: '/opt/homebrew/bin:/usr/bin', TOKEN: 'a&b<c>' }, jobs)).toBe(true);
+
+ expect(calls).toEqual(['bootstrap true']);
+ expect(BRIDGE_JOB).toMatch(/^com\.browsentic\.bridge\.[0-9a-f]{8}$/);
+ expect(plists[0]).toContain(`<key>Label</key><string>${BRIDGE_JOB}</string>`);
+ expect(plists[0]).toContain('<array><string>/opt/node/bin/node</string><string>/Users/me/cli/dist/daemon-main.js</string></array>');
+ expect(plists[0]).toContain('<key>PATH</key><string>/opt/homebrew/bin:/usr/bin</string>');
+ expect(plists[0]).toContain('<key>TOKEN</key><string>a&amp;b&lt;c&gt;</string>');
+ expect(plists[0]).toContain('<key>RunAtLoad</key><true/>');
+ expect(plists[0]).not.toContain('KeepAlive');
+ });
- beforeEach(() => {
- loaded = [];
+ it('replaces a job that has finished with a fresh one', async () => {
+ const { jobs, calls } = fakeLaunchd('idle');
+
+ expect(await startBridgeJob('/node', '/daemon-main.js', {}, jobs)).toBe(true);
+ expect(calls).toEqual([`bootout ${BRIDGE_JOB}`, 'bootstrap true']);
+ });
+
+ it('waits for a job that is still running instead of booting it out', async () => {
+ const { jobs, calls } = fakeLaunchd('running');
+
+ expect(await startBridgeJob('/node', '/daemon-main.js', {}, jobs)).toBe(true);
+ expect(calls).toEqual([]);
+ });
+
+ it('tries once more while launchd is still taking the old job down', async () => {
+ const { jobs, calls } = fakeLaunchd('idle', 1);
+
+ expect(await startBridgeJob('/node', '/daemon-main.js', {}, jobs)).toBe(true);
+ expect(calls).toEqual([`bootout ${BRIDGE_JOB}`, 'bootstrap true', 'bootstrap true']);
});
- it('runs the daemon once, now, with the environment it is handed', () => {
- expect(startBridgeJob('/opt/node/bin/node', '/Users/me/cli/dist/daemon-main.js', { PATH: '/opt/homebrew/bin:/usr/bin', TOKEN: 'a&b<c>' }, jobs)).toBe(true);
-
- expect(loaded).toHaveLength(1);
- const [{ plist, label, existed }] = loaded;
- expect(existed).toBe(true);
- expect(label).toBe(BRIDGE_JOB);
- expect(label).toMatch(/^com\.browsentic\.bridge\.[0-9a-f]{8}$/);
- expect(plist).toContain('<array><string>/opt/node/bin/node</string><string>/Users/me/cli/dist/daemon-main.js</string></array>');
- expect(plist).toContain('<key>PATH</key><string>/opt/homebrew/bin:/usr/bin</string>');
- expect(plist).toContain('<key>TOKEN</key><string>a&amp;b&lt;c&gt;</string>');
- expect(plist).toContain('<key>RunAtLoad</key><true/>');
- expect(plist).not.toContain('KeepAlive');
+ it('says so when launchd refuses it, so the caller spawns the Bridge itself', async () => {
+ const { jobs } = fakeLaunchd('absent', 2);
+
+ expect(await startBridgeJob('/node', '/daemon-main.js', {}, jobs)).toBe(false);
+ expect(logged()).toContain('could not start the Bridge through launchd');
});
- it('leaves no property list behind, holding the environment, once launchd has it', () => {
- startBridgeJob('/node', '/daemon-main.js', { SECRET: 'x' }, jobs);
+ it('leaves no property list behind, holding the environment, once launchd has it', async () => {
+ await startBridgeJob('/node', '/daemon-main.js', { SECRET: 'x' }, fakeLaunchd('absent').jobs);
- expect(loaded[0].existed).toBe(true);
expect(readdirSync(join(process.env.BROWSENTIC_HOME!, 'native-host'))).not.toContain('bridge-job.plist');
});
@@ -52,15 +95,14 @@ describe('the launchd job that starts the Bridge outside the browser', () => {
expect(plist).not.toContain('Chrome');
});
- it('says so when launchd refuses it, so the caller spawns the Bridge itself', () => {
- const refusing: Launchd = {
- load: () => {
- throw new Error('Bootstrap failed: 5: Input/output error');
- },
- };
+ it('is taken away on uninstall, when there is one', () => {
+ const loaded = fakeLaunchd('idle');
+ expect(removeBridgeJob(loaded.jobs)).toBe(true);
+ expect(loaded.calls).toEqual([`bootout ${BRIDGE_JOB}`]);
- expect(startBridgeJob('/node', '/daemon-main.js', {}, refusing)).toBe(false);
- expect(readFileSync(join(process.env.BROWSENTIC_HOME!, 'daemon.log'), 'utf8')).toContain('could not start the Bridge through launchd');
+ const none = fakeLaunchd('absent');
+ expect(removeBridgeJob(none.jobs)).toBe(false);
+ expect(none.calls).toEqual([]);
});
it.runIf(onMac)('is a property list launchd can read', () => {
@@ -74,6 +116,10 @@ describe('the launchd job that starts the Bridge outside the browser', () => {
rmSync(dir, { recursive: true, force: true });
}
});
+
+ it.runIf(onMac)('is needed only when what this process writes comes out quarantined', () => {
+ expect(runsQuarantined()).toBe(false);
+ });
});
describe('libraries a Bun-built agent unpacked while the Bridge ran quarantined', () => {
@@ -87,25 +133,31 @@ describe('libraries a Bun-built agent unpacked while the Bridge ran quarantined'
afterEach(() => rmSync(dir, { recursive: true, force: true }));
- it('removes this user’s quarantined ones and leaves everything else', () => {
+ it('removes this user’s quarantined ones and leaves everything else', async () => {
touch('.bun-501-1d98d107b4c544c0.dylib', '.bun-501-aaaaaaaaaaaaaaaa.node', '.bun-502-bbbbbbbbbbbbbbbb.dylib', 'libsomething.dylib');
const marked = new Set(['.bun-501-1d98d107b4c544c0.dylib', '.bun-502-bbbbbbbbbbbbbbbb.dylib', 'libsomething.dylib']);
+ const quarantineOf = async (file: string) => (marked.has(basename(file)) ? '0081;6ae24f49;Chrome;' : null);
- const dropped = dropQuarantinedBunLibraries({ dir, uid, quarantined: (file) => marked.has(basename(file)) });
-
- expect(dropped).toEqual([join(dir, '.bun-501-1d98d107b4c544c0.dylib')]);
+ expect(await dropQuarantinedBunLibraries({ dir, uid, quarantineOf })).toEqual([join(dir, '.bun-501-1d98d107b4c544c0.dylib')]);
expect(readdirSync(dir).sort()).toEqual(['.bun-501-aaaaaaaaaaaaaaaa.node', '.bun-502-bbbbbbbbbbbbbbbb.dylib', 'libsomething.dylib']);
});
- it('finds nothing to do in a folder that is not there', () => {
- expect(dropQuarantinedBunLibraries({ dir: join(dir, 'gone'), uid, quarantined: () => true })).toEqual([]);
+ it('keeps one the user let run with Open Anyway', async () => {
+ touch('.bun-501-1d98d107b4c544c0.dylib');
+
+ expect(await dropQuarantinedBunLibraries({ dir, uid, quarantineOf: async () => '00c1;6ae24f49;Chrome;' })).toEqual([]);
+ expect(readdirSync(dir)).toEqual(['.bun-501-1d98d107b4c544c0.dylib']);
+ });
+
+ it('finds nothing to do in a folder that is not there', async () => {
+ expect(await dropQuarantinedBunLibraries({ dir: join(dir, 'gone'), uid, quarantineOf: async () => '0081;0;x;' })).toEqual([]);
});
- it.runIf(onMac)('reads the quarantine flag macOS set', () => {
+ it.runIf(onMac)('reads the quarantine flag macOS set', async () => {
touch('.bun-501-cccccccccccccccc.dylib', '.bun-501-dddddddddddddddd.dylib');
spawnSync('/usr/bin/xattr', ['-w', 'com.apple.quarantine', '0081;6ae24f49;Chrome;', join(dir, '.bun-501-cccccccccccccccc.dylib')]);
- expect(dropQuarantinedBunLibraries({ dir, uid })).toEqual([join(dir, '.bun-501-cccccccccccccccc.dylib')]);
+ expect(await dropQuarantinedBunLibraries({ dir, uid })).toEqual([join(dir, '.bun-501-cccccccccccccccc.dylib')]);
expect(readdirSync(dir)).toEqual(['.bun-501-dddddddddddddddd.dylib']);
});
});
diff --git a/src/daemon/quarantine.ts b/src/daemon/quarantine.ts
index 3a65618..a614c26 100644
--- a/src/daemon/quarantine.ts
+++ b/src/daemon/quarantine.ts
@@ -1,12 +1,12 @@
/**
* A browser on macOS runs its native hosts quarantined, and every process a quarantined one starts is
- * quarantined too. A Bridge the host spawned would mark each file it and its agent CLIs write as
+ * quarantined too. A Bridge spawned there would mark each file it and its agent CLIs write as
* downloaded by the browser, and Gatekeeper refuses any of those that is code and not notarized, such
* as the library OpenCode unpacks into the temporary folder before loading it. A Bridge that launchd
* starts is no child of the browser and writes its files unmarked.
*/
-import { spawnSync } from 'node:child_process';
+import { execFile, spawnSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { mkdirSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
@@ -14,29 +14,41 @@ import { join } from 'node:path';
import { stateDir } from './lockfile';
import { log } from './log';
+const QUARANTINE = 'com.apple.quarantine';
+const USER_APPROVED = 0x40;
+const BOOTSTRAP_RETRY_MS = 300;
+
/** One per Bridge home, so that a scratch Bridge never boots out the real one. */
export const BRIDGE_JOB = `com.browsentic.bridge.${createHash('sha256').update(stateDir).digest('hex').slice(0, 8)}`;
+export type JobState = 'running' | 'idle' | 'absent';
+
export interface Launchd {
- /** Loads the job afresh, which starts it. Throws when launchd refuses it. */
- load(plistFile: string, label: string): void;
+ state(label: string): JobState;
+ bootout(label: string): void;
+ /** Loads the job, which starts it. Throws when launchd refuses it. */
+ bootstrap(plistFile: string): void;
}
-const launchctl = (args: string[]) => {
- const { status, stderr } = spawnSync('/bin/launchctl', args, { encoding: 'utf8' });
+const launchctl = (args: string[]): string => {
+ const { status, stdout, stderr, error } = spawnSync('/bin/launchctl', args, { encoding: 'utf8' });
+ if (error) throw error;
if (status !== 0) throw new Error(stderr.trim() || `launchctl ${args[0]} exited with ${status}`);
+ return stdout;
};
+const domain = () => `gui/${process.getuid?.()}`;
+
export const launchd: Launchd = {
- load: (plistFile, label) => {
- const domain = `gui/${process.getuid?.()}`;
+ state: (label) => {
try {
- launchctl(['bootout', `${domain}/${label}`]);
+ return /^\tstate = running$/m.test(launchctl(['print', `${domain()}/${label}`])) ? 'running' : 'idle';
} catch {
- // Not loaded: no Bridge was started this way since login.
+ return 'absent';
}
- launchctl(['bootstrap', domain, plistFile]);
},
+ bootout: (label) => void launchctl(['bootout', `${domain()}/${label}`]),
+ bootstrap: (plistFile) => void launchctl(['bootstrap', domain(), plistFile]),
};
const escapeXml = (value: string) => value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
@@ -74,13 +86,27 @@ export function bridgeJobPlist(nodePath: string, daemonMain: string, env: NodeJS
].join('\n');
}
-export function startBridgeJob(nodePath: string, daemonMain: string, env: NodeJS.ProcessEnv, jobs: Launchd = launchd): boolean {
+/**
+ * Starts the Bridge as a launchd job. A job launchd is still running is a Bridge on its way up, or
+ * one too busy to answer, so it is waited for and never booted out. False when launchd would not
+ * take the job, and the caller spawns the Bridge itself.
+ */
+export async function startBridgeJob(nodePath: string, daemonMain: string, env: NodeJS.ProcessEnv, jobs: Launchd = launchd): Promise<boolean> {
const dir = join(stateDir, 'native-host');
const file = join(dir, 'bridge-job.plist');
try {
+ const state = jobs.state(BRIDGE_JOB);
+ if (state === 'running') return true;
+ if (state === 'idle') jobs.bootout(BRIDGE_JOB);
mkdirSync(dir, { recursive: true, mode: 0o700 });
writeFileSync(file, bridgeJobPlist(nodePath, daemonMain, env), { mode: 0o600 });
- jobs.load(file, BRIDGE_JOB);
+ try {
+ jobs.bootstrap(file);
+ } catch {
+ // launchd can still be taking the old job down when the new one arrives.
+ await new Promise((resolve) => setTimeout(resolve, BOOTSTRAP_RETRY_MS));
+ jobs.bootstrap(file);
+ }
return true;
} catch (error) {
log(`native host: could not start the Bridge through launchd: ${String(error)}`);
@@ -90,13 +116,46 @@ export function startBridgeJob(nodePath: string, daemonMain: string, env: NodeJS
}
}
-const hasQuarantine = (file: string) =>
- spawnSync('/usr/bin/xattr', ['-p', 'com.apple.quarantine', file], { stdio: 'ignore' }).status === 0;
+/** On uninstall: launchd keeps a job, and the environment it carries, until logout. */
+export function removeBridgeJob(jobs: Launchd = launchd): boolean {
+ if (jobs.state(BRIDGE_JOB) === 'absent') return false;
+ try {
+ jobs.bootout(BRIDGE_JOB);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+const quarantineOf = (file: string): string | null => {
+ const { status, stdout } = spawnSync('/usr/bin/xattr', ['-p', QUARANTINE, file], { encoding: 'utf8' });
+ return status === 0 ? stdout.trim() : null;
+};
+
+/** Whether what this process writes comes out quarantined, passed on by whatever started it. */
+export function runsQuarantined(): boolean {
+ const probe = join(stateDir, `.quarantine-probe-${process.pid}`);
+ try {
+ mkdirSync(stateDir, { recursive: true, mode: 0o700 });
+ writeFileSync(probe, '');
+ return quarantineOf(probe) !== null;
+ } catch {
+ return false;
+ } finally {
+ rmSync(probe, { force: true });
+ }
+}
+
+const quarantineOfAsync = (file: string): Promise<string | null> =>
+ new Promise((resolve) => execFile('/usr/bin/xattr', ['-p', QUARANTINE, file], (error, stdout) => resolve(error ? null : stdout.trim())));
+
+/** The user let it run with Open Anyway, which Gatekeeper records in the flag instead of removing it. */
+const approved = (quarantine: string) => (Number.parseInt(quarantine.split(';')[0], 16) & USER_APPROVED) !== 0;
export interface BunLibraries {
dir?: string;
uid?: number;
- quarantined?: (file: string) => boolean;
+ quarantineOf?: (file: string) => Promise<string | null>;
}
/**
@@ -104,17 +163,17 @@ export interface BunLibraries {
* `.bun-<uid>-<hash>.<ext>` and reuse that copy on every later start. One unpacked under a quarantined
* Bridge stays quarantined, and Gatekeeper refuses it with a dialog at each start until it is gone.
*/
-export function dropQuarantinedBunLibraries({ dir = tmpdir(), uid = process.getuid?.() ?? 0, quarantined = hasQuarantine }: BunLibraries = {}): string[] {
+export async function dropQuarantinedBunLibraries({ dir = tmpdir(), uid = process.getuid?.() ?? 0, quarantineOf = quarantineOfAsync }: BunLibraries = {}): Promise<string[]> {
let names: string[];
try {
- names = readdirSync(dir);
+ names = readdirSync(dir).filter((name) => name.startsWith(`.bun-${uid}-`));
} catch {
return [];
}
const dropped: string[] = [];
- for (const name of names.filter((entry) => entry.startsWith(`.bun-${uid}-`))) {
- const file = join(dir, name);
- if (!quarantined(file)) continue;
+ for (const file of names.map((name) => join(dir, name))) {
+ const quarantine = await quarantineOf(file);
+ if (quarantine === null || approved(quarantine)) continue;
try {
rmSync(file, { force: true });
dropped.push(file);