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.
TypeScript agentic-browseragentic-browsingagy-cliaiai-agentai-browser-extensionai-toolsbrave-extensionbrowser-agentbrowser-automationbrowser-extensionbrowser-usebrowserskillchrome-extensionclaude-codecodexfirefox-addonmcp-servernanobrowserweb-automation
feat(bridge): a browser pairs with no code: the native host asks the Bridge for a one-time grant bound to that browser profile and the origin the browser vouched for, redeemed through the same handshake; pairing.mode (auto by default, ask, or code) decides whether someone allows each browser first, in the app or with browsentic approve; a revoke or a deny keeps a browser out until it is reconnected; a refused session says whether it was revoked or is unknown; the welcome is sent in the same step a link is listed
Shahriar80e231030f3a
diff --git a/src/daemon/agent/config.ts b/src/daemon/agent/config.tsindex 1151c28..ce3563a 100644--- a/src/daemon/agent/config.ts+++ b/src/daemon/agent/config.ts@@ -3,6 +3,7 @@ import { join } from 'node:path';import { AGENTS, AGENT_KINDS, DEFAULT_AGENT, isAgentKind, isModelId, type AgentKind } from '@/lib/agents/catalog';import { FENCE_SETTING, UNATTENDED_SETTING, type GuardrailValue, type RuleEffect } from '@/lib/settings/guardrails';import { isThemeId, type ThemeId } from '@/lib/settings/theme';+import { DEFAULT_PAIRING_MODE, isPairingMode, type PairingMode } from '@/lib/pairing';import type { GuardrailConfig } from '../guardrails';import { stateDir } from '../lockfile';import { log } from '../log';@@ -47,6 +48,24 @@ export interface AgentConfig {};/** Driving Chrome on an Android phone. Off stops every use of adb; `adb` names the binary to use. */android?: { enabled?: boolean; adb?: string };+ /** How a browser pairs through the native host: by itself, once someone allows it, or only with a code. */+ pairing?: { mode?: unknown };+}++/** A hand edit naming a mode Browsentic does not know pairs nothing by itself: whoever wrote it meant something stricter than the default, or made a typo worth noticing. */+export function pairingMode(config: AgentConfig = readAgentConfig()): PairingMode {+ const mode = config.pairing?.mode;+ if (mode === undefined) return DEFAULT_PAIRING_MODE;+ if (isPairingMode(mode)) return mode;+ log(`pairing mode ${JSON.stringify(mode)} is not auto, ask or code; pairing by code only`);+ return 'code';+}++/** Sets how browsers pair, leaving every other key in config.json untouched. */+export function writePairingMode(mode: PairingMode): void {+ const stored = readStored();+ const pairing = { ...((stored.pairing as Record<string, unknown> | undefined) ?? {}), mode };+ write({ ...stored, pairing });}export interface AndroidSettings {diff --git a/src/daemon/auth-store.test.ts b/src/daemon/auth-store.test.tsindex 17072cd..7221b47 100644--- a/src/daemon/auth-store.test.ts+++ b/src/daemon/auth-store.test.ts@@ -2,6 +2,14 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';import {+ approveInstall,+ blockInstall,+ blockOf,+ isApproved,+ labelSession,+ listBlocked,+ mintGrantCode,+ unblockInstall,claimSession,clearAuth,consumePairing,@@ -132,7 +140,7 @@ describe('the file', () => {test('a damaged file pairs nothing, and the next write replaces it', () => {writeFileSync(authPath, '{"sessions": [');const session = createSession(chrome);- expect(JSON.parse(readFileSync(authPath, 'utf8'))).toEqual({ pairings: [], sessions: [session] });+ expect(JSON.parse(readFileSync(authPath, 'utf8'))).toEqual({ pairings: [], sessions: [session], approved: [], blocked: [] });});test('clearing it forgets every browser', () => {@@ -141,3 +149,64 @@ describe('the file', () => {expect([existsSync(authPath), listSessions()]).toEqual([false, []]);});});++describe('automatic pairing', () => {+ test('a grant is a long code in the typed alphabet', () => {+ expect(mintGrantCode()).toMatch(/^[ABCDEFGHJKMNPQRSTWXYZ23456789]{26}$/);+ });++ test('a session says how it was paired, by code unless told otherwise', () => {+ expect(createSession(chrome).pairedBy).toBe('code');+ expect(createSession(brave, 'auto').pairedBy).toBe('auto');+ });++ test('revoking keeps a browser out and forgets that it was allowed', () => {+ approveInstall(chrome);+ createSession(chrome);+ revokeSessions((session) => session.installId === chrome.installId);++ expect(blockOf(chrome.installId)).toMatchObject({ reason: 'revoked', origin: extension, browser: 'Google Chrome' });+ expect(isApproved(chrome.installId)).toBe(false);+ });++ test('a session paired before install ids is revoked without leaving a block nobody can name', () => {+ pairedBeforeInstallIds(extension);+ revokeSessions(() => true);+ expect(listBlocked()).toEqual([]);+ });++ test('pairing again, or allowing it, lifts a block', () => {+ blockInstall(chrome, 'denied');+ createSession(chrome);+ expect(blockOf(chrome.installId)).toBeUndefined();++ blockInstall(brave, 'revoked');+ approveInstall(brave);+ expect([blockOf(brave.installId), isApproved(brave.installId)]).toEqual([undefined, true]);+ });++ test('unblocking says whether there was a block', () => {+ blockInstall(chrome, 'revoked');+ expect([unblockInstall(chrome.installId), unblockInstall(chrome.installId)]).toEqual([true, false]);+ });++ test('keeps the newest two hundred blocks', () => {+ for (let index = 0; index < 205; index++) blockInstall({ ...chrome, installId: `install-block-${String(index).padStart(5, '0')}` }, 'revoked');+ const blocked = listBlocked();+ expect([blocked.length, blocked[0].installId]).toEqual([200, 'install-block-00005']);+ });++ test('a name chosen when allowing a browser is the name its session takes', () => {+ approveInstall({ ...chrome, label: 'Work Chrome' });+ expect(createSession(chrome).label).toBe('Work Chrome');+ });++ test('a paired browser can be named and the name cleared', () => {+ createSession(chrome);+ expect(labelSession(chrome.installId, ' Home\u0007 laptop ')).toBe(true);+ expect(listSessions()[0].label).toBe('Home laptop');+ expect(labelSession(chrome.installId, '')).toBe(true);+ expect(listSessions()[0].label).toBeUndefined();+ expect(labelSession('nobody', 'x')).toBe(false);+ });+});diff --git a/src/daemon/auth-store.ts b/src/daemon/auth-store.tsindex b4177b8..eb3af09 100644--- a/src/daemon/auth-store.ts+++ b/src/daemon/auth-store.ts@@ -1,13 +1,18 @@import { randomBytes, randomInt } from 'node:crypto';import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { join } from 'node:path';+import type { BlockedBrowser, PairedBy } from '@/lib/pairing';import { stateDir } from './lockfile';const authPath = join(stateDir, 'auth.json');const CODE_ALPHABET = 'ABCDEFGHJKMNPQRSTWXYZ23456789';const CODE_LENGTH = 8;+/** A grant goes from the Bridge to the extension through native messaging and is never typed, so it carries ~126 bits. */+const GRANT_LENGTH = 26;const PAIRING_TTL_MS = 10 * 60 * 1000;+/** Kept so a revoked or denied browser stays out; the oldest are let go past this many. */+const BLOCKED_KEPT = 200;/** The app, a terminal and a second terminal can each be showing one; a new code must not void theirs. */const LIVE_PAIRINGS = 3;@@ -17,11 +22,24 @@ export interface Session {/** Absent on a session paired before the extension sent one; the first reconnect claims it. */installId?: string;browser?: string;+ /** What someone named this browser, in the approval sheet or the app's list. */+ label?: string;+ /** Absent on a session paired before automatic pairing, which was always by code. */+ pairedBy?: PairedBy;extensionVersion: string;pairedAt: string;lastSeenAt: string;}+/** A browser profile someone allowed in ask mode; it pairs by itself from then on, until it is revoked. */+export interface Approval {+ installId: string;+ origin: string;+ browser?: string;+ label?: string;+ at: string;+}+interface Pairing {code: string;expiresAt: number;@@ -30,14 +48,16 @@ interface Pairing {interface AuthFile {pairings: Pairing[];sessions: Session[];+ approved: Approval[];+ blocked: BlockedBrowser[];}function read(): AuthFile {try {const parsed = JSON.parse(readFileSync(authPath, 'utf8')) as Partial<AuthFile>;- return { pairings: parsed.pairings ?? [], sessions: parsed.sessions ?? [] };+ return { pairings: parsed.pairings ?? [], sessions: parsed.sessions ?? [], approved: parsed.approved ?? [], blocked: parsed.blocked ?? [] };} catch {- return { pairings: [], sessions: [] };+ return { pairings: [], sessions: [], approved: [], blocked: [] };}}@@ -47,12 +67,14 @@ function write(auth: AuthFile): void {chmodSync(authPath, 0o600);}+const codeOf = (length: number) => Array.from({ length }, () => CODE_ALPHABET[randomInt(CODE_ALPHABET.length)]).join('');++/** In the typed codes' alphabet, so the extension's handshake treats it as any code. */+export const mintGrantCode = (): string => codeOf(GRANT_LENGTH);+export function createPairing(): { code: string; expiresAt: number } {const auth = read();- const code = Array.from(- { length: CODE_LENGTH },- () => CODE_ALPHABET[randomInt(CODE_ALPHABET.length)],- ).join('');+ const code = codeOf(CODE_LENGTH);const now = Date.now();const expiresAt = now + PAIRING_TTL_MS;const live = auth.pairings.filter((pairing) => pairing.expiresAt > now).slice(1 - LIVE_PAIRINGS);@@ -85,20 +107,23 @@ export interface Install {export const sessionId = (session: Pick<Session, 'installId' | 'origin'>): string =>session.installId ?? session.origin;-export function createSession({ installId, origin, extensionVersion, browser }: Install): Session {+export function createSession({ installId, origin, extensionVersion, browser }: Install, pairedBy: PairedBy = 'code'): Session {const auth = read();const now = new Date().toISOString();+ const label = auth.approved.find((approval) => approval.installId === installId)?.label;const session: Session = {key: randomBytes(32).toString('base64url'),origin,installId,browser,+ ...(label ? { label } : {}),+ pairedBy,extensionVersion,pairedAt: now,lastSeenAt: now,};const sessions = auth.sessions.filter((existing) => existing.installId !== installId);- write({ ...auth, sessions: [...sessions, session] });+ write({ ...auth, sessions: [...sessions, session], blocked: auth.blocked.filter((block) => block.installId !== installId) });return session;}@@ -125,11 +150,67 @@ export function listSessions(): Session[] {return read().sessions;}+/**+ * Unpairs the matching browsers and keeps them from pairing again by themselves, so a revoke is not+ * undone by the extension's next automatic attempt a minute later.+ */export function revokeSessions(predicate: (session: Session) => boolean): number {const auth = read();+ const revoked = auth.sessions.filter(predicate);const keep = auth.sessions.filter((session) => !predicate(session));- write({ ...auth, sessions: keep });- return auth.sessions.length - keep.length;+ const at = new Date().toISOString();+ const blocks = revoked+ .filter((session): session is Session & { installId: string } => !!session.installId)+ .map(({ installId, origin, browser }): BlockedBrowser => ({ installId, origin, browser, at, reason: 'revoked' }));+ write({ ...withBlocks(auth, blocks), sessions: keep });+ return revoked.length;+}++function withBlocks(auth: AuthFile, blocks: BlockedBrowser[]): AuthFile {+ const ids = new Set(blocks.map((block) => block.installId));+ return {+ ...auth,+ approved: auth.approved.filter((approval) => !ids.has(approval.installId)),+ blocked: [...auth.blocked.filter((block) => !ids.has(block.installId)), ...blocks].slice(-BLOCKED_KEPT),+ };+}++export function blockInstall(install: Pick<Install, 'installId' | 'origin' | 'browser'>, reason: BlockedBrowser['reason']): void {+ const { installId, origin, browser } = install;+ write(withBlocks(read(), [{ installId, origin, browser, at: new Date().toISOString(), reason }]));+}++/** True when there was a block to lift. */+export function unblockInstall(installId: string): boolean {+ const auth = read();+ const blocked = auth.blocked.filter((block) => block.installId !== installId);+ if (blocked.length === auth.blocked.length) return false;+ write({ ...auth, blocked });+ return true;+}++export const blockOf = (installId: string): BlockedBrowser | undefined => read().blocked.find((block) => block.installId === installId);++export const listBlocked = (): BlockedBrowser[] => read().blocked;++export function approveInstall(approval: Omit<Approval, 'at'>): void {+ const auth = read();+ const approved = [...auth.approved.filter((kept) => kept.installId !== approval.installId), { ...approval, at: new Date().toISOString() }];+ write({ ...auth, approved, blocked: auth.blocked.filter((block) => block.installId !== approval.installId) });+}++export const isApproved = (installId: string): boolean => read().approved.some((approval) => approval.installId === installId);++/** True when that browser was paired; an empty name clears it. */+export function labelSession(id: string, label: string): boolean {+ const auth = read();+ const session = auth.sessions.find((candidate) => sessionId(candidate) === id);+ if (!session) return false;+ const named = label.replace(/[\u0000-\u001f]/g, '').trim().slice(0, 40);+ if (named) session.label = named;+ else delete session.label;+ write(auth);+ return true;}export function clearAuth(): void {diff --git a/src/daemon/cli.ts b/src/daemon/cli.tsindex 4beb0cb..f6a3a23 100644--- a/src/daemon/cli.ts+++ b/src/daemon/cli.ts@@ -6,6 +6,7 @@ import { ANDROID_PROTOCOL } from '@/lib/actions/protocol';import type { AndroidState } from '@/lib/phone/types';import { AGENTS, AGENT_KINDS, AGENT_LIST, isAgentKind, type AgentKind, type AgentState, type ModelList } from '@/lib/agents/catalog';import { SOURCE_LABEL } from '@/lib/stores';+import { PAIRING_MODES, isPairingMode, type PairRequestSummary, type PairedBy, type PairingMode } from '@/lib/pairing';import { RESERVED_ACTIONS } from '@/lib/actions/reserved';import { assertToolNamesRoundTrip, toolNameFor } from '@/lib/actions/tool-names';import { formatWhen } from '@/lib/format-when';@@ -29,7 +30,8 @@ import { forgetGrants, listGrants } from './agent/approvals';import { describeMoment, describeRule } from '@/lib/schedules/rule';import { findTask, readSchedules, setEnabled, setPaused, updateSchedules } from './schedules/store';import { clearDownloads, downloadDir, storedDownloads } from './downloads';-import { readAgentConfig, rememberExtensionDir, writeAgentModel } from './agent/config';+import { pairingMode, readAgentConfig, rememberExtensionDir, writeAgentModel } from './agent/config';+import { desktopApp } from './desktop-app';import { loadSkills, skillDirNames, uploadedSkillsDir } from './agent/skills';import { ensureDaemon, probeExisting, runningDaemons, stopDaemons } from './ensure-daemon';import { install, InstallError, readStamp } from './install';@@ -56,9 +58,14 @@ const USAGE = `browsentic ${pkg.version} — Browsentic Bridge, the half of Browbrowsentic uninstall stop the Bridge and remove everything Browsentic wrotebrowsentic browsers the browsers on this computer, where each gets the extension, and which are connectedbrowsentic pair issue a one-time code to type into the extension+ browsentic pairing [mode] how browsers pair by themselves: auto, ask (you allow each one) or code (only with a code)+ browsentic requests browsers waiting for you to allow them, in ask mode+ browsentic approve [id] allow a waiting or unpaired browser; --watch asks about each one as it comes+ browsentic deny <id> turn a waiting browser downbrowsentic status the Bridge, each paired browser, and the agent- browsentic sessions list paired browsers- browsentic revoke [id] unpair one browser by the id "sessions" prints, or all of them+ browsentic sessions list paired browsers, and the ones kept out+ browsentic rename <id> <name> name a paired browser, e.g. "Work Chrome"+ browsentic revoke [id] unpair one browser by the id "sessions" prints, or all of them; it stays out until you reconnect itbrowsentic agent show which agent runs the side panel, and which are installedbrowsentic agent <name> switch to claude, codex, antigravity, vibe, grok, cursor, qwen or opencode@@ -97,6 +104,13 @@ For MCP clients// Above the switch, like USAGE: it runs the command before execution reaches the bottom of this// file, and the bundle hoists a constant declared down there as an undefined var.const AGENTS_GUIDE = 'https://browsentic.com/docs/guide/agents/';+const PAIRING_LINE: Record<PairingMode, string> = {+ auto: 'automatic: a browser with Browsentic connects by itself',+ ask: 'ask: a browser connects once you allow it, in the app or with "browsentic approve"',+ code: 'code only: a browser connects once you type a code from "browsentic pair" into it',+};++const PAIRED_BY: Record<PairedBy, string> = { code: 'paired with a code', auto: 'paired by itself', approved: 'allowed and paired' };const WAIT_MS = 5 * 60_000;const SPINNER = '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏';/** Offered when no browser is found, since detection can miss one installed somewhere unusual. */@@ -138,7 +152,17 @@ switch (command) {await uninstall(process.argv.slice(3));break;case 'native-host':- await serveNativeHost({ ensure: (caller) => ensureDaemon({ outsideJob: caller?.family === 'firefox' }), held: wakeHeld });+ await serveNativeHost({+ ensure: (caller) => ensureDaemon({ outsideJob: caller?.family === 'firefox' }),+ held: wakeHeld,+ mode: () => pairingMode(),+ version: pkg.version,+ app: () => {+ const app = desktopApp();+ return app && { kind: app.kind, present: app.present };+ },+ connect: (lock) => RemoteBridge.connect(lock.port, lock.token),+ });break;case 'unregister-host':unregisterHost();@@ -155,6 +179,21 @@ switch (command) {case 'revoke':await revoke(process.argv[3]);break;+ case 'pairing':+ await setPairing(positional[0]);+ break;+ case 'requests':+ await showRequests();+ break;+ case 'approve':+ await approve(positional[0]);+ break;+ case 'deny':+ await deny(positional[0]);+ break;+ case 'rename':+ await rename(positional[0], positional.slice(1).join(' '));+ break;case 'agent':await chooseAgent(positional[0], positional[1], positional[2]);break;@@ -338,6 +377,7 @@ async function showStatus(): Promise<void> {console.log(`tools: ${status.manifestInSync ? 'in sync' : `the extension's own list (extension v${status.extensionVersion}, Bridge v${status.daemonVersion})`}`,);+ if (status.pairing) console.log(`pairing: ${PAIRING_LINE[status.pairing.mode]}`);if (status.pairingPending) console.log('pairing: a code is waiting to be entered');}@@ -488,6 +528,7 @@ async function setup(argv: string[]): Promise<void> {const located = locateBrowsers();const sessions = await bridge.sessions();const rows = browserRows(sessions, located, pkg.version);+ const mode = (await bridge.pairing())?.mode ?? 'code';if (!json) {console.log(`\n Browsentic ${pkg.version} — your browser's superpower\n`);@@ -522,6 +563,7 @@ async function setup(argv: string[]): Promise<void> {version: pkg.version,daemon: { port: lock.port, pid: lock.pid },nativeHost: wake,+ pairing: { mode },extensionDir: folder ? dir : null,unpacked: folder && { version: folder.version, changed: folder.changed, alreadyCurrent: folder.alreadyCurrent },alreadyPaired: sessions.length > 0,@@ -542,18 +584,18 @@ async function setup(argv: string[]): Promise<void> {console.log(` ✓ Unpacked copy ${dir}, ${state}\n`);}- if (!choice) return printPlan(rows, sessions, folder?.version, code);+ if (!choice) return printPlan(rows, sessions, mode, folder?.version, code);if (settled) {console.log(` ${row!.label} is already connected: Browsentic ${settled.extensionVersion} from the ${SOURCE_LABEL[settled.source ?? 'unpacked']}.`);console.log(choice.unpacked ? ` Press ↻ on its card at ${row!.extensionsPage} to load this build.\n` : ' Nothing to do.\n');return;}- if (choice.unpacked) printUnpackedSteps(dir, row, code);- else await printStoreSteps(row!, opened, code);+ if (choice.unpacked) printUnpackedSteps(dir, row, mode, code);+ else await printStoreSteps(row!, opened, mode, code);if (!code || flag('no-wait')) return;- const joined = await waitForBrowser(bridge, since, row?.label ?? 'your browser');+ const joined = await waitForBrowser(bridge, since, row?.label ?? 'your browser', mode);if (joined) {const panel = browserOf(joined.browser) === 'firefox' ? 'sidebar' : 'side panel';console.log(` ✓ ${joined.browser ?? 'Your browser'} is connected: Browsentic ${joined.extensionVersion} from the ${SOURCE_LABEL[joined.source ?? 'unpacked']}.`);@@ -642,13 +684,14 @@ function writeExtension(dir: string, force: boolean) {}}-function codeLines(code: { code: string } | undefined): string[] {- return code- ? [`enter this code: ${groupCode(code.code)}`, 'It works once and expires in 10 minutes. Need another? "browsentic pair"']- : ['enter a code from "browsentic pair".'];+/** How the browser connects once the extension is in it, in this Bridge's pairing mode. */+function codeLines(mode: PairingMode, code: { code: string } | undefined): string[] {+ const enter = code ? `enter this code: ${groupCode(code.code)}` : 'enter a code from "browsentic pair".';+ const lead = { auto: `It connects by itself; if it asks for a code, ${enter}`, ask: `Allow it here when it asks; or ${enter}`, code: enter }[mode];+ return code ? [lead, 'The code works once and expires in 10 minutes. Need another? "browsentic pair"'] : [lead];}-async function printStoreSteps(row: BrowserRow, opened: boolean, code?: { code: string }): Promise<void> {+async function printStoreSteps(row: BrowserRow, opened: boolean, mode: PairingMode, code?: { code: string }): Promise<void> {console.log(opened ? ` Opening the ${row.store} in ${row.label}:` : ` Open this page in ${row.label}:`);console.log(` ${row.storeUrl}\n`);if (row.id === 'firefox' && (await signedAddonAttached(pkg.version)) === false) {@@ -658,15 +701,15 @@ async function printStoreSteps(row: BrowserRow, opened: boolean, code?: { code:if (row.sessions.some((session) => session.connected && session.source === 'unpacked')) {console.log(` ${row.label} already runs an unpacked copy. Remove it at ${row.extensionsPage} first, or both will answer.\n`);}- const [enter, ...rest] = codeLines(code);- const steps = [...row.steps, `Click Browsentic in the toolbar (the puzzle piece lists it; pin it there) and ${enter}`];+ const [enter, ...rest] = codeLines(mode, code);+ const steps = [...row.steps, `Click Browsentic in the toolbar (the puzzle piece lists it; pin it there). ${enter}`];steps.forEach((step, index) => console.log(` ${index + 1}. ${step}`));for (const line of rest) console.log(` ${line}`);console.log();}-function printUnpackedSteps(dir: string, row: BrowserRow | undefined, code?: { code: string }): void {- const [enter, ...rest] = codeLines(code);+function printUnpackedSteps(dir: string, row: BrowserRow | undefined, mode: PairingMode, code?: { code: string }): void {+ const [enter, ...rest] = codeLines(mode, code);console.log(` Load it unpacked in ${row?.label ?? 'your browser'}:\n`);console.log(` 1. Open ${row?.extensionsPage ?? 'its extensions page (chrome://extensions)'} and turn on Developer mode.`);console.log(` 2. Press “Load unpacked” and choose:\n`);@@ -675,7 +718,7 @@ function printUnpackedSteps(dir: string, row: BrowserRow | undefined, code?: { c// them. The folder picker shortcut is the next best thing, and it is where people stall.const picker = FOLDER_PICKER[process.platform];if (picker) console.log(` ${picker}`);- console.log(` 3. Click Browsentic in the toolbar and ${enter}`);+ console.log(` 3. Click Browsentic in the toolbar. ${enter}`);for (const line of rest) console.log(` ${line}`);console.log();}@@ -684,7 +727,7 @@ function printUnpackedSteps(dir: string, row: BrowserRow | undefined, code?: { c* Nobody to ask. Someone already set up hears what an update leaves them to do; anyone else, where* each browser gets the extension, with the choosing left to them.*/-function printPlan(rows: BrowserRow[], sessions: SessionSummary[], folderVersion?: string, code?: { code: string }): void {+function printPlan(rows: BrowserRow[], sessions: SessionSummary[], mode: PairingMode, folderVersion?: string, code?: { code: string }): void {if (sessions.length) {const stale = sessions.filter((session) => session.source === 'unpacked' && folderVersion && session.extensionVersion !== folderVersion);const pages = new Set(stale.map((session) => BROWSERS[browserOf(session.browser) ?? 'chrome'].extensionsPage));@@ -700,17 +743,18 @@ function printPlan(rows: BrowserRow[], sessions: SessionSummary[], folderVersionconsole.log(` ${store('chrome').storeUrl}`);console.log(` Firefox`);console.log(` ${store('firefox').storeUrl}\n`);- const [enter, ...rest] = codeLines(code);- console.log(` Then click Browsentic in the toolbar and ${enter}`);+ const [enter, ...rest] = codeLines(mode, code);+ console.log(` Then click Browsentic in the toolbar. ${enter}`);for (const line of rest) console.log(` ${line}`);console.log(` On a terminal, "browsentic setup" asks which browser and walks you through it.\n`);}-async function waitForBrowser(bridge: RemoteBridge, since: string, label: string): Promise<SessionSummary | null> {+async function waitForBrowser(bridge: RemoteBridge, since: string, label: string, mode: PairingMode): Promise<SessionSummary | null> {const line = `Waiting for ${label} to connect… (Ctrl-C stops waiting; nothing is undone)`;const spin = !!process.stdout.isTTY;if (!spin) console.log(` ${line}`);const deadline = Date.now() + WAIT_MS;+ const asked = new Set<string>();for (let tick = 0; Date.now() < deadline; tick++) {if (tick % 8 === 0) {const joined = (await bridge.sessions()).find((session) => session.connected && session.pairedAt >= since);@@ -718,6 +762,17 @@ async function waitForBrowser(bridge: RemoteBridge, since: string, label: stringif (spin) process.stdout.write('\r\x1b[2K');return joined;}+ if (mode === 'ask' && process.stdin.isTTY) {+ for (const request of await bridge.pairRequests('terminal')) {+ if (asked.has(request.id)) continue;+ asked.add(request.id);+ if (spin) process.stdout.write('\r\x1b[2K');+ const rl = createInterface({ input: process.stdin, output: process.stdout });+ const answer = (await rl.question(` ${describeRequest(request)} wants to connect. Allow it? [Y/n] `)).trim();+ rl.close();+ await bridge.decide(request.id, !/^n(o)?$/i.test(answer));+ }+ }}if (spin) process.stdout.write(`\r ${SPINNER[tick % SPINNER.length]} ${line}`);await new Promise((resolve) => setTimeout(resolve, 150));@@ -838,14 +893,16 @@ async function showSessions(): Promise<void> {const sessions = await bridge.sessions();await bridge.close();if (!sessions.length) {- return console.log('No paired browsers. Run "browsentic setup" to add one.');+ console.log('No paired browsers. Run "browsentic setup" to add one.');+ return showBlocked();}for (const session of sessions) {- console.log(`${session.connected ? '●' : '○'} ${session.browser ?? session.origin} ${session.id}`);+ console.log(`${session.connected ? '●' : '○'} ${session.label ?? session.browser ?? session.origin} ${session.id}`);console.log(- ` ${SOURCE_LABEL[session.source ?? 'unpacked']} (${session.origin}), extension v${session.extensionVersion}, paired ${session.pairedAt}, last seen ${session.lastSeenAt}`,+ ` ${SOURCE_LABEL[session.source ?? 'unpacked']} (${session.origin}), extension v${session.extensionVersion}, ${PAIRED_BY[session.pairedBy ?? 'code']} ${session.pairedAt}, last seen ${session.lastSeenAt}`,);}+ await showBlocked();}async function chooseAgent(first?: string, second?: string, third?: string): Promise<void> {@@ -929,7 +986,151 @@ async function revoke(browser?: string): Promise<void> {const revoked = await bridge.revoke(browser);await bridge.close();if (!revoked) return console.log(browser ? `No session for ${browser}.` : 'Nothing to revoke.');- console.log(`Revoked ${revoked} session(s). Pair again with "browsentic pair".`);+ console.log(`Revoked ${revoked} session(s). They will not pair again by themselves.`);+ console.log('Reconnect one from its extension, with "browsentic approve <id>", or with a code from "browsentic pair".');+}++async function setPairing(mode?: string): Promise<void> {+ if (mode !== undefined && !isPairingMode(mode)) {+ console.error(`Pairing is ${PAIRING_MODES.join(', ')}, not "${mode}".`);+ process.exit(1);+ }+ const bridge = await connect();+ const answer = await bridge.pairing(mode);+ await bridge.close();+ if (!answer) {+ console.error('This Browsentic Bridge is too old to pair by itself. Run "browsentic restart" to start the one installed.');+ process.exit(1);+ }+ if (answer.error) {+ console.error(answer.error);+ process.exit(1);+ }+ console.log(`Pairing: ${PAIRING_LINE[answer.mode]}.`);+ if (answer.mode === 'ask') {+ console.log(answer.approver === 'app' ? 'The Browsentic app asks you about each new browser.' : 'Allow each new browser with "browsentic approve".');+ }+}++function describeRequest(request: PairRequestSummary): string {+ const source = isSource(request.source) ? SOURCE_LABEL[request.source] : request.source;+ return `${request.browser ?? 'A browser'} (${source}, extension v${request.extensionVersion})`;+}++function isSource(value: string): value is keyof typeof SOURCE_LABEL {+ return value in SOURCE_LABEL;+}++async function showRequests(): Promise<void> {+ const bridge = await connect();+ const requests = await bridge.pairRequests();+ await bridge.close();+ if (wantsJson) return console.log(JSON.stringify({ requests }, null, 2));+ if (!requests.length) return console.log('No browser is waiting to be allowed.');+ for (const request of requests) console.log(` ${request.id} ${describeRequest(request)}, asked ${formatWhen(request.firstAt)}`);+ console.log('\nAllow one with "browsentic approve <id>", or turn it down with "browsentic deny <id>".');+}++async function approve(id?: string): Promise<void> {+ const bridge = await connect();+ try {+ if (process.argv.includes('--watch')) return await watchRequests(bridge);+ const requests = await bridge.pairRequests();+ const chosen = id ?? (requests.length === 1 ? requests[0].id : undefined);+ if (!chosen) {+ console.error(requests.length ? 'Several browsers are waiting. Name one: "browsentic requests" lists them.' : 'No browser is waiting to be allowed.');+ process.exit(1);+ }+ const name = valueAfter('--name');+ const { ok, error } = await bridge.decide(chosen, true, name);+ if (!ok) {+ console.error(error ?? `Nothing is waiting under ${chosen}.`);+ process.exit(1);+ }+ console.log('Allowed. It connects within a few seconds; "browsentic status" shows it.');+ } finally {+ await bridge.close();+ }+}++async function deny(id?: string): Promise<void> {+ if (!id) {+ console.error('Name the browser to turn down: "browsentic requests" lists them.');+ process.exit(1);+ }+ const bridge = await connect();+ const { ok, error } = await bridge.decide(id, false);+ await bridge.close();+ if (!ok) {+ console.error(error ?? `Nothing is waiting under ${id}.`);+ process.exit(1);+ }+ console.log('Turned down. It stays out until someone presses Reconnect in that browser and you allow it.');+}++async function rename(id?: string, name?: string): Promise<void> {+ if (!id || name === undefined) {+ console.error('Usage: browsentic rename <id> <name>. "browsentic sessions" prints the ids.');+ process.exit(1);+ }+ const bridge = await connect();+ const ok = await bridge.label(id, name);+ await bridge.close();+ if (!ok) {+ console.error(`No paired browser has the id ${id}.`);+ process.exit(1);+ }+ console.log(name.trim() ? `Named it "${name.trim()}".` : 'Cleared its name.');+}++async function showBlocked(): Promise<void> {+ const lock = await probeExisting();+ if (!lock) return;+ const bridge = await RemoteBridge.connect(lock.port, lock.token);+ const blocked = await bridge.blocked();+ await bridge.close();+ if (!blocked.length) return;+ console.log('\nKept out until you reconnect them:');+ for (const browser of blocked) {+ console.log(` ${browser.browser ?? browser.origin} ${browser.installId} ${browser.reason} ${browser.at}`);+ }+ console.log('Let one back in with "browsentic approve <id>".');+}++function valueAfter(flag: string): string | undefined {+ const at = process.argv.indexOf(flag);+ return at === -1 ? undefined : process.argv[at + 1];+}++/** A terminal that answers for every browser asking to pair, for as long as it runs. */+async function watchRequests(bridge: RemoteBridge): Promise<void> {+ if (!process.stdin.isTTY) {+ console.error('--watch asks you about each browser, so it needs a terminal.');+ process.exit(1);+ }+ const rl = createInterface({ input: process.stdin, output: process.stdout });+ const asked = new Set<string>();+ let busy = false;+ const review = async () => {+ if (busy) return;+ busy = true;+ try {+ for (const request of await bridge.pairRequests('terminal')) {+ if (asked.has(request.id)) continue;+ asked.add(request.id);+ const answer = (await rl.question(`\n ${describeRequest(request)} wants to connect. Allow it? [Y/n] `)).trim();+ const allow = !/^n(o)?$/i.test(answer);+ const { ok } = await bridge.decide(request.id, allow);+ console.log(ok ? (allow ? ' Allowed.' : ' Turned down.') : ' It had already been decided or had expired.');+ }+ } finally {+ busy = false;+ }+ };+ bridge.onPairRequestsChanged(() => void review());+ console.log('Waiting for browsers that ask to pair. Ctrl-C stops.');+ await review();+ await new Promise(() => undefined);}async function android(args: string[]): Promise<void> {diff --git a/src/daemon/control.ts b/src/daemon/control.tsindex f4d4dde..63fb48a 100644--- a/src/daemon/control.ts+++ b/src/daemon/control.ts@@ -4,6 +4,7 @@ import type { AgentKind, AgentState } from '@/lib/agents/catalog';import type { AndroidState } from '@/lib/phone/types';import type { Preferences } from '@/lib/settings/preferences';import type { Source } from '@/lib/stores';+import type { Approver, BlockedBrowser, GrantOutcome, PairRequestSummary, PairedBy, PairingMode } from '@/lib/pairing';export interface BridgeStatus {connected: boolean;@@ -17,6 +18,8 @@ export interface BridgeStatus {connectedBrowsers: number;pairedBrowsers: number;pairingPending: boolean;+ /** How browsers pair through the native host. Absent from a Bridge that cannot grant, which a newer host reads as "too old". */+ pairing?: { mode: PairingMode; approver: Approver };}export interface SessionSummary {@@ -29,6 +32,10 @@ export interface SessionSummary {pairedAt: string;lastSeenAt: string;connected: boolean;+ /** What someone named it. */+ label?: string;+ /** Absent from a Bridge before automatic pairing, when every browser paired by code. */+ pairedBy?: PairedBy;}/**@@ -56,7 +63,16 @@ export type ControlRequest =* `android-changed` and `watch: false` lets go, so the Bridge stops looking once nobody shows phones.* `peek` answers only what is already known, NOT_CHECKED while nobody watches.*/- | { id: string; op: 'android'; launch?: string; url?: string; watch?: boolean; peek?: boolean };+ | { id: string; op: 'android'; launch?: string; url?: string; watch?: boolean; peek?: boolean }+ /** Only the native host asks: `caller` is what the browser vouched for. `waitMs` holds the answer while ask mode waits on a person. */+ | { id: string; op: 'grant'; installId: string; caller: string; browser?: string; extensionVersion: string; gesture?: boolean; waitMs?: number }+ /** `watch` makes this caller an approver, sent `pair-requests-changed` whenever the list does. */+ | { id: string; op: 'pairRequests'; watch?: boolean; as?: Approver }+ /** `request` is a request id or an install id; an install id also lifts a block when allowed. */+ | { id: string; op: 'decide'; request: string; allow: boolean; label?: string }+ | { id: string; op: 'pairing'; set?: PairingMode }+ | { id: string; op: 'blocked' }+ | { id: string; op: 'label'; session: string; label: string };export type ControlMessage =| { id: string; op: 'describe'; tools: ToolDescriptor[]; reserved?: string[]; withheld?: ToolDescriptor[] }@@ -69,7 +85,15 @@ export type ControlMessage =| { id: string; op: 'agent'; state: AgentState }| { id: string; op: 'preferences'; result: ActionResult<Preferences> }| { id: string; op: 'android'; result: ActionResult<AndroidState> }+ | { id: string; op: 'grant'; outcome: GrantOutcome }+ | { id: string; op: 'pairRequests'; requests: PairRequestSummary[] }+ | { id: string; op: 'decide'; ok: boolean; error?: string }+ | { id: string; op: 'pairing'; mode: PairingMode; approver: Approver; error?: string }+ | { id: string; op: 'blocked'; blocked: BlockedBrowser[] }+ | { id: string; op: 'label'; ok: boolean; error?: string }| { event: 'manifest-changed' }+ /** A browser asked to pair, or a request was decided or expired: read `pairRequests` again. */+ | { event: 'pair-requests-changed' }/** config.json changed, from any side: read the preferences and the agent state again. */| { event: 'settings-changed' }| { event: 'android-changed'; state: AndroidState };diff --git a/src/daemon/daemon.ts b/src/daemon/daemon.tsindex 76bcacf..1a8bace 100644--- a/src/daemon/daemon.ts+++ b/src/daemon/daemon.ts@@ -40,11 +40,15 @@ import {type Transcript,} from '@/lib/actions/handshake';import {+ approveInstall,+ blockOf,claimSession,consumePairing,createPairing,createSession,hasPendingPairing,+ labelSession,+ listBlocked,listSessions,pendingPairings,revokeSessions,@@ -53,13 +57,16 @@ import {type Install,type Session,} from './auth-store';+import { MAX_PAIR_WAIT_MS, isPairingMode, type Approver, type GrantOutcome, type PairedBy, type RefusalCode } from '@/lib/pairing';+import { pairingDesk } from './pairing-desk';+import { desktopApp, launchDesktopApp } from './desktop-app';import { AgentSession } from './agent/service';import { androidOff, type Android } from './android/service';import { solveCaptchaWithAnalyst } from './agent/captcha-solver';import { FileAnalyses } from './agent/file-analyst';import { analyzeRecording } from './agent/recording';import { nameSession } from './agent/title';-import { readAgentConfig, writeActiveAgent, writeAgentModel } from './agent/config';+import { pairingMode, readAgentConfig, writeActiveAgent, writeAgentModel, writePairingMode } from './agent/config';import { agentSkills } from './agent/agent-skills';import { agentState, grantRunner, refreshModelLists } from './agent/runners';import { deleteSiteMap, deleteSkill, saveSkill } from './agent/skill-store';@@ -242,6 +249,20 @@ export async function startDaemon({ version, idleExit = true, android = androidOdaemonVersion: version,};+ const approvers = new Map<WebSocket, Approver>();+ const approverNow = (): Approver =>+ [...approvers.values()].includes('app') || desktopApp()?.present ? 'app' : 'terminal';+ const desk = pairingDesk({+ port: () => lock.port,+ mode: () => pairingMode(),+ approver: approverNow,+ appWatching: () => [...approvers.values()].includes('app'),+ launchApp: () => launchDesktopApp(),+ changed: () => {+ for (const ws of approvers.keys()) send(ws, { event: 'pair-requests-changed' });+ },+ });+const http = createServer((req, res) => {if (!fromLoopback(req)) {res.writeHead(403).end();@@ -311,10 +332,10 @@ export async function startDaemon({ version, idleExit = true, android = androidO}async function greet(ws: WebSocket, req: IncomingMessage): Promise<void> {- const reject = (reason: string, retryable: boolean) => {- log(`rejected extension: ${reason}`);+ const reject = (reason: string, retryable: boolean, code: RefusalCode) => {+ log(`rejected extension: ${reason} [${code}]`);try {- ws.send(JSON.stringify({ t: 'unauthorized', reason, retryable }));+ ws.send(JSON.stringify({ t: 'unauthorized', reason, retryable, code }));} catch {}ws.close(4401, 'unauthorized');@@ -369,25 +390,32 @@ export async function startDaemon({ version, idleExit = true, android = androidOlet secret: string;let sealedSessionKey: string | undefined;if (hello.auth?.kind === 'pair') {- const matched = await matchPairing(proven.proof, transcript);+ const matched = await matchPairing(proven.proof, transcript, install);if (!matched) {- return reject('That pairing code is wrong or expired. Run "browsentic pair" for a new one.', true);+ return reject('That pairing code is wrong or expired. Run "browsentic pair" for a new one.', true, 'bad-code');+ }+ if (matched.pairedBy === 'code') {+ consumePairing(matched.code);+ // Typing a code is consent enough, so ask mode lets this browser back in by itself from now on.+ approveInstall({ installId: install.installId, origin: install.origin, browser: install.browser });+ } else {+ desk.consume(install.installId);}- consumePairing(matched.code);secret = matched.secret;- const session = createSession(install);+ const session = createSession(install, matched.pairedBy);sealedSessionKey = await sealSessionKey(secret, transcript, session.key);- log(`paired ${install.browser ?? install.origin} (extension ${hello.extensionVersion})`);+ log(`paired ${install.browser ?? install.origin} (extension ${hello.extensionVersion}) [${matched.pairedBy}]`);refreshNativeHost();} else if (hello.auth?.kind === 'session') {const session = await matchSession(proven.proof, transcript, install);if (!session) {- return reject('This browser is no longer paired. Run "browsentic pair" to pair again.', false);+ const code = blockOf(install.installId) ? 'revoked' : 'unknown';+ return reject('This browser is no longer paired. Run "browsentic pair" to pair again.', false, code);}claimSession(session.key, install);secret = session.key;} else {- return reject('That hello named no credential to prove.', false);+ return reject('That hello named no credential to prove.', false, 'bad-code');}await settle(ws, hello, install, transcript, secret, sealedSessionKey);@@ -400,13 +428,20 @@ export async function startDaemon({ version, idleExit = true, android = androidOreturn null;}+ /** The grant held for this very browser first, so a typed code costs at most one more PBKDF2 than before. */async function matchPairing(proof: unknown,transcript: Transcript,- ): Promise<{ code: string; secret: string } | null> {- for (const code of pendingPairings()) {- const secret = await pairingSecret(code, transcript);- if (sameProof(proof, await clientProof(secret, transcript))) return { code, secret };+ install: Install,+ ): Promise<{ code: string; secret: string; pairedBy: PairedBy } | null> {+ const granted = desk.grantFor(install.installId, install.origin);+ const candidates = [+ ...(granted ? [{ code: granted.code, pairedBy: granted.pairedBy }] : []),+ ...pendingPairings().map((code) => ({ code, pairedBy: 'code' as const })),+ ];+ for (const candidate of candidates) {+ const secret = await pairingSecret(candidate.code, transcript);+ if (sameProof(proof, await clientProof(secret, transcript))) return { ...candidate, secret };}return null;}@@ -423,6 +458,14 @@ export async function startDaemon({ version, idleExit = true, android = androidOlinks.get(install.installId)?.close('superseded by a newer connection');const known = bundledByHash.get(hello.manifestHash);const manifestInSync = known !== undefined;+ const welcome = {+ daemonVersion: version,+ manifestHash: known ? hello.manifestHash : bundledHash,+ manifestInSync,+ sealedSessionKey,+ };+ // Proven before the link is listed, so no broadcast can reach this browser ahead of its welcome.+ const proof = await serverProof(secret, transcript, welcome);const accepted = new ExtensionLink(ws,{ ...hello, ...install },@@ -536,18 +579,7 @@ export async function startDaemon({ version, idleExit = true, android = androidOaccepted.tools = known ?? bundled;settleOffer();log(`extension ${hello.extensionVersion} connected from ${accepted.label} (manifest ${manifestInSync ? 'in sync' : 'DRIFTED'})`);- const welcome = {- daemonVersion: version,- manifestHash: known ? hello.manifestHash : bundledHash,- manifestInSync,- sealedSessionKey,- };- accepted.send({- t: 'welcome',- ...welcome,- protocolVersion: SOCKET_PROTOCOL_VERSION,- proof: await serverProof(secret, transcript, welcome),- });+ accepted.send({ t: 'welcome', ...welcome, protocolVersion: SOCKET_PROTOCOL_VERSION, proof });scheduleIdleExit();void pushAgentState(accepted);watchModels();@@ -923,6 +955,48 @@ export async function startDaemon({ version, idleExit = true, android = androidOsend(ws, { id: request.id, op: 'preferences', result: applyPreference(request.change) });return configChanged();}+ if (request.op === 'grant') {+ if (speaksForRun) {+ log(`control ${client} asked for a pairing grant from inside an agent run; refused`);+ return send(ws, { id: request.id, op: 'grant', outcome: { refused: 'off', error: 'An agent run cannot pair a browser.' } });+ }+ return send(ws, { id: request.id, op: 'grant', outcome: await settleGrant(request) });+ }+ if (request.op === 'pairRequests') {+ if (request.watch) approvers.set(ws, request.as === 'terminal' ? 'terminal' : 'app');+ return send(ws, { id: request.id, op: 'pairRequests', requests: desk.pending() });+ }+ if (request.op === 'decide') {+ if (speaksForRun) {+ log(`control ${client} tried to decide a pairing request from inside an agent run; refused`);+ return send(ws, { id: request.id, op: 'decide', ok: false, error: 'An agent run cannot let a browser in.' });+ }+ const ok = typeof request.request === 'string' && desk.decide(request.request, request.allow === true, request.label);+ return send(ws, { id: request.id, op: 'decide', ok, ...(ok ? {} : { error: 'No request or blocked browser has that id.' }) });+ }+ if (request.op === 'pairing') {+ if (request.set !== undefined) {+ if (speaksForRun) {+ log(`control ${client} tried to change how browsers pair from inside an agent run; refused`);+ return send(ws, { id: request.id, op: 'pairing', mode: pairingMode(), approver: approverNow(), error: 'An agent run cannot change how browsers pair.' });+ }+ if (!isPairingMode(request.set)) {+ return send(ws, { id: request.id, op: 'pairing', mode: pairingMode(), approver: approverNow(), error: 'Pairing is auto, ask or code.' });+ }+ writePairingMode(request.set);+ log(`control ${client} set pairing to ${request.set}`);+ configChanged();+ }+ return send(ws, { id: request.id, op: 'pairing', mode: pairingMode(), approver: approverNow() });+ }+ if (request.op === 'blocked') {+ return send(ws, { id: request.id, op: 'blocked', blocked: listBlocked() });+ }+ if (request.op === 'label') {+ if (speaksForRun) return send(ws, { id: request.id, op: 'label', ok: false, error: 'An agent run cannot rename a browser.' });+ const ok = typeof request.session === 'string' && typeof request.label === 'string' && labelSession(request.session, request.label);+ return send(ws, { id: request.id, op: 'label', ok });+ }if (request.op === 'revoke') {const { session: id, origin } = request;const revoked = revokeSessions((session) => (id ? sessionId(session) === id : !origin || session.origin === origin));@@ -938,6 +1012,7 @@ export async function startDaemon({ version, idleExit = true, android = androidOfor (const call of inflight.values()) call.abort();controls.delete(ws);settingsWatchers.delete(ws);+ approvers.delete(ws);unwatchAndroid(ws);scheduleIdleExit();};@@ -953,6 +1028,25 @@ export async function startDaemon({ version, idleExit = true, android = androidOfor (const ws of controls) send(ws, message);}+ /** A host in ask mode may hold its request open, so an open page hears the decision at once. */+ async function settleGrant(request: Extract<ControlRequest, { op: 'grant' }>): Promise<GrantOutcome> {+ if (!isInstallId(request.installId) || typeof request.caller !== 'string') {+ return { refused: 'off', error: 'That grant request names no browser.' };+ }+ const asker = {+ installId: request.installId,+ caller: request.caller,+ browser: browserLabel(request.browser),+ extensionVersion: typeof request.extensionVersion === 'string' ? request.extensionVersion.slice(0, 32) : 'unknown',+ gesture: request.gesture === true,+ };+ const first = desk.ask(asker);+ const waitMs = Math.min(MAX_PAIR_WAIT_MS, Math.max(0, Number(request.waitMs) || 0));+ if (!('wait' in first) || !waitMs) return first;+ await desk.settled(asker.installId, waitMs);+ return desk.ask({ ...asker, gesture: false });+ }+function sessionSummaries(): SessionSummary[] {return listSessions().map(({ key: _key, installId: _installId, ...session }) => {const id = sessionId({ installId: _installId, origin: session.origin });@@ -972,6 +1066,7 @@ export async function startDaemon({ version, idleExit = true, android = androidOconnectedBrowsers: openLinks().length,pairedBrowsers: listSessions().length,pairingPending: hasPendingPairing(),+ pairing: { mode: pairingMode(), approver: approverNow() },};}diff --git a/src/daemon/desktop-app.ts b/src/daemon/desktop-app.tsnew file mode 100644index 0000000..f58748e--- /dev/null+++ b/src/daemon/desktop-app.ts@@ -0,0 +1,49 @@+/**+ * The Mac and Windows apps lay the CLI down in ~/.browsentic/cli with a marker naming the app itself,+ * which is how the Bridge knows there is an app to ask, and how to start it when a browser asks to+ * pair and nobody is watching.+ */++import { spawn } from 'node:child_process';+import { existsSync, readFileSync } from 'node:fs';+import { join } from 'node:path';+import { stateDir } from './lockfile';+import { log } from './log';+import { APP_MARKER } from './npx';++export interface DesktopApp {+ kind: 'mac' | 'windows';+ path: string;+ present: boolean;+}++export function desktopApp(platform: NodeJS.Platform = process.platform, state = stateDir): DesktopApp | null {+ if (platform !== 'darwin' && platform !== 'win32') return null;+ try {+ const marker = JSON.parse(readFileSync(join(state, 'cli', APP_MARKER), 'utf8')) as { app?: unknown };+ if (typeof marker.app !== 'string' || !marker.app) return null;+ return { kind: platform === 'darwin' ? 'mac' : 'windows', path: marker.app, present: existsSync(marker.app) };+ } catch {+ return null;+ }+}++/** In the background on macOS (`open -g`), so it never takes the keyboard from the browser that asked. */+export function launchArgs(app: DesktopApp): [string, string[]] {+ return app.kind === 'mac' ? ['open', ['-g', app.path, '--args', '--pairing']] : [app.path, ['--pairing']];+}++export function launchDesktopApp(app: DesktopApp | null = desktopApp()): boolean {+ if (!app?.present) return false;+ const [file, args] = launchArgs(app);+ try {+ const child = spawn(file, args, { detached: true, stdio: 'ignore' });+ child.on('error', (error) => log(`could not start the app at ${app.path}: ${String(error)}`));+ child.unref();+ log(`started the app at ${app.path} to ask about a browser`);+ return true;+ } catch (error) {+ log(`could not start the app at ${app.path}: ${String(error)}`);+ return false;+ }+}diff --git a/src/daemon/native-messaging.test.ts b/src/daemon/native-messaging.test.tsindex a9e357c..96148f2 100644--- a/src/daemon/native-messaging.test.ts+++ b/src/daemon/native-messaging.test.ts@@ -1,5 +1,22 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';-import { STOPPED_REPLY, answerNativeMessage, callerOf, decodeNativeMessage, encodeNativeMessage } from './native-messaging';+import { describe, expect, it, vi } from 'vitest';+import type { GrantOutcome, PairingMode } from '@/lib/pairing';+import type { BridgeStatus } from './control';+import {+ STOPPED_REPLY,+ answerNativeMessage,+ callerOf,+ decodeNativeMessage,+ encodeNativeMessage,+ parsePairRequest,+ type Caller,+ type HostBridge,+ type HostContext,+} from './native-messaging';++const STORE = 'chrome-extension://npmocgldfflonjjmdadmdefpnfagnjmp/';+const chrome: Caller = { family: 'chromium', origin: STORE };+const firefox: Caller = { family: 'firefox', addonId: '[email protected]' };+const request = { op: 'pair', installId: 'install-host-test-01', browser: 'Google Chrome', extensionVersion: '0.9.0', protocolVersion: 23, reason: 'install' };describe('the message frame', () => {it('round-trips a message and waits for a whole one', () => {@@ -11,19 +28,14 @@ describe('the message frame', () => {});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 });+ expect(callerOf([STORE])).toEqual(chrome);+ expect(callerOf(['--parent-window=0', STORE])).toEqual(chrome);+ expect(callerOf([STORE.slice(0, -1)])).toEqual(chrome);});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]',- });+ expect(callerOf(['/Users/me/Library/Application Support/Mozilla/NativeMessagingHosts/x.json', '[email protected]'])).toEqual(firefox);});it('names nobody it cannot recognise', () => {@@ -33,25 +45,168 @@ describe('callerOf', () => {});});-describe('answering ensure', () => {- const ensure = vi.fn(async () => ({ port: 8765 }));- const context = (held = false) => ({ ensure, held: () => held });+function bridgeWith(status: Partial<BridgeStatus> | null, outcome: GrantOutcome | null = null) {+ const calls: string[] = [];+ const grants: Parameters<HostBridge['grant']>[0][] = [];+ const bridge: HostBridge = {+ status: async () => {+ calls.push('status');+ if (!status) throw new Error('no answer');+ return status as BridgeStatus;+ },+ grant: async (asked) => {+ calls.push('grant');+ grants.push(asked);+ return outcome;+ },+ pair: async () => {+ calls.push('pair');+ return { code: 'LEGACY23', expiresAt: 1 };+ },+ close: async () => void calls.push('close'),+ };+ return { bridge, calls, grants };+}- beforeEach(() => ensure.mockClear());+function contextWith(options: { mode?: PairingMode; held?: boolean; bridge?: HostBridge; ensure?: HostContext['ensure'] } = {}) {+ const ensure = vi.fn(options.ensure ?? (async () => ({ port: 8766, token: 't' })));+ const context: HostContext = {+ ensure,+ held: () => options.held ?? false,+ mode: () => options.mode ?? 'auto',+ version: '0.9.0',+ app: () => ({ kind: 'mac', present: true }),+ connect: async () => options.bridge ?? bridgeWith({ pairing: { mode: 'auto', approver: 'app' } }).bridge,+ };+ return { context, ensure };+}+describe('answering ensure', () => {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);+ const { context, ensure } = contextWith();+ expect(await answerNativeMessage({ op: 'ensure' }, context, firefox)).toEqual({ ok: true, port: 8766 });+ expect(ensure).toHaveBeenCalledWith(firefox);});it('leaves a daemon stopped on purpose down', async () => {- expect(await answerNativeMessage({ op: 'ensure' }, context(true))).toBe(STOPPED_REPLY);+ const { context, ensure } = contextWith({ held: true });+ expect(await answerNativeMessage({ op: 'ensure' }, context)).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"}.' });+ const { context, ensure } = contextWith();+ expect(await answerNativeMessage({ op: 'spawn' }, context)).toEqual({ ok: false, error: 'Expected {"op":"ensure"}.' });+ expect(ensure).not.toHaveBeenCalled();+ });+});++describe('answering hello', () => {+ it('says what it can do without starting the Bridge', async () => {+ const { context, ensure } = contextWith({ mode: 'ask' });+ expect(await answerNativeMessage({ op: 'hello' }, context)).toEqual({+ ok: true,+ host: 2,+ bridge: '0.9.0',+ ops: ['ensure', 'hello', 'pair'],+ mode: 'ask',+ held: false,+ app: { kind: 'mac', present: true },+ });+ expect(ensure).not.toHaveBeenCalled();+ });+});++describe('answering pair', () => {+ it('hands over the grant the Bridge gives, bound to the origin the browser vouched for', async () => {+ const fake = bridgeWith({ pairing: { mode: 'auto', approver: 'app' } }, { grant: { code: 'G'.repeat(26), port: 8766, expiresAt: 9 }, approver: 'app' });+ const { context } = contextWith({ bridge: fake.bridge });++ expect(await answerNativeMessage(request, context, chrome)).toEqual({ ok: true, grant: { code: 'G'.repeat(26), port: 8766, expiresAt: 9 }, mode: 'auto', approver: 'app' });+ expect(fake.grants).toEqual([expect.objectContaining({ installId: request.installId, caller: STORE, gesture: false, waitMs: 0 })]);+ expect(fake.calls.at(-1)).toBe('close');+ });++ it('binds a Firefox grant to the scheme, since its origin is random per install', async () => {+ const fake = bridgeWith({ pairing: { mode: 'auto', approver: 'app' } }, { grant: { code: 'G', port: 1, expiresAt: 1 }, approver: 'app' });+ await answerNativeMessage(request, contextWith({ bridge: fake.bridge }).context, firefox);+ expect(fake.grants[0].caller).toBe('moz-extension://');+ });++ it('passes on a wait and a refusal as they are', async () => {+ const waiting = bridgeWith({ pairing: { mode: 'ask', approver: 'terminal' } }, { wait: { request: 'r1', approver: 'terminal', retryAfterMs: 3000 } });+ expect(await answerNativeMessage({ ...request, waitMs: 99_000 }, contextWith({ mode: 'ask', bridge: waiting.bridge }).context, chrome)).toEqual({+ ok: false,+ wait: { request: 'r1', approver: 'terminal', retryAfterMs: 3000 },+ mode: 'ask',+ });+ expect(waiting.grants[0].waitMs).toBe(25_000);++ const refused = bridgeWith({ pairing: { mode: 'auto', approver: 'app' } }, { refused: 'revoked', error: 'gone' });+ expect(await answerNativeMessage(request, contextWith({ bridge: refused.bridge }).context, chrome)).toEqual({ ok: false, refused: 'revoked', error: 'gone', mode: 'auto' });+ });++ it('pairs nobody whose caller it cannot name', async () => {+ const { context, ensure } = contextWith();+ expect(await answerNativeMessage(request, context, null)).toMatchObject({ ok: false, refused: 'origin' });+ expect(ensure).not.toHaveBeenCalled();+ });++ it('pairs nothing in code mode, and leaves the Bridge alone', async () => {+ const { context, ensure } = contextWith({ mode: 'code' });+ expect(await answerNativeMessage(request, context, chrome)).toMatchObject({ ok: false, refused: 'off', mode: 'code' });expect(ensure).not.toHaveBeenCalled();});++ it('leaves a Bridge stopped on purpose down', async () => {+ const { context, ensure } = contextWith({ held: true });+ expect(await answerNativeMessage(request, context, chrome)).toMatchObject({ ok: false, refused: 'stopped' });+ expect(ensure).not.toHaveBeenCalled();+ });++ it('falls back to a plain code from a running Bridge older than grants, in auto mode', async () => {+ const old = bridgeWith({});+ expect(await answerNativeMessage(request, contextWith({ bridge: old.bridge }).context, chrome)).toEqual({+ ok: true,+ grant: { code: 'LEGACY23', port: 8766, expiresAt: 1 },+ mode: 'auto',+ approver: 'terminal',+ });+ expect(old.calls).not.toContain('grant');+ });++ it('asks for a restart instead in ask mode, since an old Bridge cannot ask anyone', async () => {+ const old = bridgeWith({});+ expect(await answerNativeMessage(request, contextWith({ mode: 'ask', bridge: old.bridge }).context, chrome)).toMatchObject({ ok: false, refused: 'restart' });+ expect(old.calls).not.toContain('pair');+ });++ it('fails without pairing when the Bridge will not start, answer, or decide', async () => {+ const broken = contextWith({ ensure: async () => Promise.reject(new Error('ports busy')) }).context;+ expect(await answerNativeMessage(request, broken, chrome)).toMatchObject({ ok: false, error: expect.stringContaining('ports busy') });++ const silent = bridgeWith(null);+ expect(await answerNativeMessage(request, contextWith({ bridge: silent.bridge }).context, chrome)).toEqual({ ok: false, error: 'Browsentic Bridge did not answer.' });++ const undecided = bridgeWith({ pairing: { mode: 'auto', approver: 'app' } }, null);+ expect(await answerNativeMessage(request, contextWith({ bridge: undecided.bridge }).context, chrome)).toEqual({+ ok: false,+ error: 'Browsentic Bridge did not answer the pairing request.',+ });+ });+});++describe('parsePairRequest', () => {+ it('takes only a request that names the browser, why it asks and what it runs', () => {+ expect(parsePairRequest(request)).toMatchObject({ installId: request.installId, reason: 'install', gesture: false, waitMs: 0 });+ expect(parsePairRequest({ ...request, installId: 'short' })).toBeNull();+ expect(parsePairRequest({ ...request, reason: 'because' })).toBeNull();+ expect(parsePairRequest({ ...request, extensionVersion: 3 })).toBeNull();+ expect(parsePairRequest(null)).toBeNull();+ });++ it('counts only a real true as a click', () => {+ expect(parsePairRequest({ ...request, gesture: 'yes' })?.gesture).toBe(false);+ expect(parsePairRequest({ ...request, gesture: true })?.gesture).toBe(true);+ });});diff --git a/src/daemon/native-messaging.ts b/src/daemon/native-messaging.tsindex f44a9ca..87038d6 100644--- a/src/daemon/native-messaging.ts+++ b/src/daemon/native-messaging.ts@@ -2,9 +2,26 @@* 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).+ *+ * The browser launches it only for the extension IDs its registration lists, so a request that+ * arrives here comes from our own extension, in a browser running as this user. That is what lets+ * `pair` hand out a grant with no code typed.*/+import { isInstallId } from '@/lib/actions/protocol';+import {+ FIREFOX_CALLER,+ HOST_OPS,+ MAX_PAIR_WAIT_MS,+ isPairReason,+ type GrantOutcome,+ type HostHello,+ type HostPairReply,+ type HostPairRequest,+ type PairingMode,+} from '@/lib/pairing';import { FIREFOX_ADDON_ID } from '@/lib/stores';+import type { BridgeStatus } from './control';import { log } from './log';export function encodeNativeMessage(value: unknown): Buffer {@@ -52,26 +69,69 @@ export function callerOf(argv: readonly string[]): Caller | null {return argv.includes(FIREFOX_ADDON_ID) ? { family: 'firefox', addonId: FIREFOX_ADDON_ID } : null;}+/** What a grant is bound to: the exact origin for Chromium, the scheme for Firefox. */+export const callerKey = (caller: Caller): string => (caller.family === 'chromium' ? caller.origin : FIREFOX_CALLER);+export const STOPPED_REPLY = { ok: false, error: 'Stopped with "browsentic stop"; "browsentic start" lets the browser start it again.' };+const UNKNOWN_OP = { ok: false, error: 'Expected {"op":"ensure"}.' };++/** The slice of a control connection the host uses. */+export interface HostBridge {+ status(timeoutMs: number): Promise<BridgeStatus>;+ grant(request: { installId: string; caller: string; browser?: string; extensionVersion: string; gesture?: boolean; waitMs?: number }, timeoutMs: number): Promise<GrantOutcome | null>;+ pair(): Promise<{ code: string; expiresAt: number }>;+ close(): Promise<void>;+}+export interface HostContext {/** Starts the Bridge if it is down, and says where it listens. */- ensure: (caller: Caller | null) => Promise<{ port: number }>;+ ensure: (caller: Caller | null) => Promise<{ port: number; token: string }>;/** True while `browsentic stop` holds the Bridge down. */held: () => boolean;+ /** Read from config.json, so a host answers even while the Bridge is down. */+ mode: () => PairingMode;+ version: string;+ app: () => HostHello['app'];+ connect: (lock: { port: number; token: string }) => Promise<HostBridge>;}+const STATUS_TIMEOUT_MS = 3_000;+const GRANT_TIMEOUT_MS = 5_000;+/** The longest a host takes to answer, past any wait it was asked to hold; the extension waits a little longer. */+export const HOST_DEADLINE_MS = 12_000;++const OFF = 'Automatic pairing is off on this computer. Pair with a code from "browsentic pair" or the app.';+const RESTART =+ 'Browsentic Bridge was updated but the old one is still running. Restart it ("browsentic restart", or Restart in the app) to pair this browser.';+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 : ''}`}`);- }+ const message = (await readNativeMessage(process.stdin)) as { op?: unknown; waitMs?: unknown } | null;+ const waited = message?.op === 'pair' ? waitFor(message.waitMs) : 0;+ const reply = await Promise.race([+ answerNativeMessage(message, context, caller),+ new Promise<HostPairReply>((resolve) =>+ setTimeout(() => resolve({ ok: false, error: 'Browsentic Bridge took too long to answer.' }), HOST_DEADLINE_MS + waited).unref(),+ ),+ ]);+ logReply(message?.op, reply, caller);await new Promise<void>((resolve) => process.stdout.write(encodeNativeMessage(reply), () => resolve()));}+function logReply(op: unknown, reply: object, caller: Caller | null): void {+ if (reply === STOPPED_REPLY) return;+ const who = caller ? callerKey(caller) : 'an unknown caller';+ if (op === 'ensure') {+ const failed = 'error' in reply ? ` — ${String(reply.error)}` : '';+ return log(`native host: ${'ok' in reply && reply.ok ? 'daemon ready' : `could not start the daemon${failed}`}`);+ }+ if (op !== 'pair') return;+ const outcome = 'grant' in reply ? 'granted' : 'wait' in reply ? 'waiting for approval' : 'refused' in reply ? `refused (${String(reply.refused)})` : `failed: ${'error' in reply ? String(reply.error) : ''}`;+ log(`native host: pair for ${who} ${outcome}`);+}+function silenceStderr(): void {process.stderr.write = ((chunk: string | Uint8Array) => {log(`native host stderr: ${String(chunk).trim()}`);@@ -79,14 +139,90 @@ function silenceStderr(): void {}) as typeof process.stderr.write;}+const waitFor = (value: unknown) => Math.min(MAX_PAIR_WAIT_MS, Math.max(0, typeof value === 'number' ? value : 0));+export async function answerNativeMessage(- message: { op?: unknown } | null,- { ensure, held }: HostContext,+ message: Record<string, unknown> | null,+ context: 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)+): Promise<object> {+ if (message?.op === 'hello') return hello(context);+ if (message?.op === 'pair') return pair(message, context, caller);+ if (message?.op !== 'ensure') return UNKNOWN_OP;+ if (context.held()) return STOPPED_REPLY;+ return context+ .ensure(caller).then((lock) => ({ ok: true, port: lock.port })).catch((error) => ({ ok: false, error: String(error) }));}++function hello(context: HostContext): HostHello {+ return { ok: true, host: 2, bridge: context.version, ops: [...HOST_OPS], mode: context.mode(), held: context.held(), app: context.app() };+}++export function parsePairRequest(message: unknown): HostPairRequest | null {+ const asked = message as Partial<Record<keyof HostPairRequest, unknown>> | null;+ if (!asked || !isInstallId(asked.installId) || !isPairReason(asked.reason)) return null;+ if (typeof asked.extensionVersion !== 'string' || typeof asked.protocolVersion !== 'number') return null;+ return {+ op: 'pair',+ installId: asked.installId,+ browser: typeof asked.browser === 'string' ? asked.browser.slice(0, 64) : undefined,+ extensionVersion: asked.extensionVersion.slice(0, 32),+ protocolVersion: asked.protocolVersion,+ reason: asked.reason,+ gesture: asked.gesture === true,+ waitMs: waitFor(asked.waitMs),+ };+}++async function pair(message: unknown, context: HostContext, caller: Caller | null): Promise<HostPairReply> {+ if (!caller) return { ok: false, refused: 'origin', error: 'Browsentic Bridge pairs only with its own extension.' };+ const request = parsePairRequest(message);+ if (!request) return { ok: false, error: 'That pair request is missing what it needs.' };+ const mode = context.mode();+ if (mode === 'code') return { ok: false, refused: 'off', error: OFF, mode };+ if (context.held()) return { ok: false, refused: 'stopped', error: STOPPED_REPLY.error, mode };++ let lock: { port: number; token: string };+ try {+ lock = await context.ensure(caller);+ } catch (error) {+ return { ok: false, error: `Browsentic Bridge could not start: ${String(error)}` };+ }+ let bridge: HostBridge;+ try {+ bridge = await context.connect(lock);+ } catch (error) {+ return { ok: false, error: `Could not reach Browsentic Bridge: ${String(error)}` };+ }+ try {+ const status = await bridge.status(STATUS_TIMEOUT_MS).catch(() => null);+ if (!status) return { ok: false, error: 'Browsentic Bridge did not answer.' };+ if (!status.pairing) {+ if (mode === 'ask') return { ok: false, refused: 'restart', error: RESTART, mode };+ const legacy = await bridge.pair();+ return { ok: true, grant: { code: legacy.code, port: lock.port, expiresAt: legacy.expiresAt }, mode, approver: 'terminal' };+ }+ const outcome = await bridge.grant(+ {+ installId: request.installId,+ caller: callerKey(caller),+ browser: request.browser,+ extensionVersion: request.extensionVersion,+ gesture: request.gesture,+ waitMs: request.waitMs,+ },+ (request.waitMs ?? 0) + GRANT_TIMEOUT_MS,+ );+ const current = status.pairing.mode;+ if (!outcome) return { ok: false, error: 'Browsentic Bridge did not answer the pairing request.' };+ if ('grant' in outcome) return { ok: true, grant: outcome.grant, mode: current, approver: outcome.approver };+ if ('wait' in outcome) return { ok: false, wait: outcome.wait, mode: current };+ return { ok: false, refused: outcome.refused, error: outcome.error, mode: current };+ } catch (error) {+ return { ok: false, error: String(error) };+ } finally {+ await bridge.close().catch(() => undefined);+ }+}diff --git a/src/daemon/pairing-desk.test.ts b/src/daemon/pairing-desk.test.tsnew file mode 100644index 0000000..b0a0466--- /dev/null+++ b/src/daemon/pairing-desk.test.ts@@ -0,0 +1,122 @@+import { mkdirSync } from 'node:fs';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { PairingMode } from '@/lib/pairing';+import { blockInstall, clearAuth, listBlocked } from './auth-store';+import { stateDir } from './lockfile';+import { callerMatches, pairingDesk, type Asker } from './pairing-desk';++const chrome: Asker = {+ installId: 'install-desk-chrome01',+ caller: 'chrome-extension://npmocgldfflonjjmdadmdefpnfagnjmp/',+ browser: 'Google Chrome',+ extensionVersion: '0.9.0',+ gesture: false,+};++function desk(mode: PairingMode, appWatching = false) {+ let clock = Date.now();+ const launched = vi.fn(() => true);+ const changed = vi.fn();+ const built = pairingDesk({+ port: () => 8765,+ mode: () => mode,+ approver: () => 'app',+ appWatching: () => appWatching,+ launchApp: launched,+ changed,+ now: () => clock,+ });+ return { desk: built, launched, changed, advance: (ms: number) => (clock += ms) };+}++beforeEach(() => {+ mkdirSync(stateDir, { recursive: true });+ clearAuth();+});++describe('callerMatches', () => {+ it('binds Chromium to the exact origin and Firefox to the scheme', () => {+ expect(callerMatches(chrome.caller, 'chrome-extension://npmocgldfflonjjmdadmdefpnfagnjmp')).toBe(true);+ expect(callerMatches(chrome.caller, 'chrome-extension://cbkjhkgjcpihokphhdkbahilpcjojpdc')).toBe(false);+ expect(callerMatches('moz-extension://', 'moz-extension://5b1d7a4e-9f3c')).toBe(true);+ expect(callerMatches('moz-extension://', chrome.caller)).toBe(false);+ });+});++describe('grants', () => {+ it('lasts two minutes and is handed out again while more than half a minute is left', () => {+ const { desk: built, advance } = desk('auto');+ const first = built.ask(chrome);+ advance(60_000);+ const second = built.ask(chrome);+ advance(40_000);+ const third = built.ask(chrome);++ const code = (outcome: typeof first) => ('grant' in outcome ? outcome.grant.code : null);+ expect(code(first)).toBe(code(second));+ expect(code(third)).not.toBe(code(first));+ expect('grant' in first && first.grant.expiresAt - (Date.now() - 100_000)).toBeGreaterThan(119_000);+ });++ it('is gone once it expires or is used', () => {+ const { desk: built, advance } = desk('auto');+ built.ask(chrome);+ expect(built.grantFor(chrome.installId, 'chrome-extension://npmocgldfflonjjmdadmdefpnfagnjmp')).toBeDefined();+ built.consume(chrome.installId);+ expect(built.grantFor(chrome.installId, 'chrome-extension://npmocgldfflonjjmdadmdefpnfagnjmp')).toBeUndefined();++ built.ask(chrome);+ advance(120_001);+ expect(built.grantFor(chrome.installId, 'chrome-extension://npmocgldfflonjjmdadmdefpnfagnjmp')).toBeUndefined();+ });+});++describe('ask mode', () => {+ it('starts the app once per request when nobody is watching, and tells approvers once', () => {+ const { desk: built, launched, changed } = desk('ask');+ built.ask(chrome);+ built.ask(chrome);+ expect(launched).toHaveBeenCalledOnce();+ expect(changed).toHaveBeenCalledOnce();+ });++ it('leaves a watching app to ask by itself', () => {+ const { desk: built, launched } = desk('ask', true);+ built.ask(chrome);+ expect(launched).not.toHaveBeenCalled();+ });++ it('forgets a request nobody asked about for ten minutes, without counting it as a deny', () => {+ const { desk: built, advance } = desk('ask');+ built.ask(chrome);+ advance(10 * 60_000);+ expect(built.pending()).toEqual([]);+ expect(listBlocked()).toEqual([]);+ });++ it('lets a click ask again a minute after a deny, not sooner', () => {+ const { desk: built, advance } = desk('ask');+ built.ask(chrome);+ built.decide(chrome.installId, false);++ expect(built.ask({ ...chrome, gesture: true })).toMatchObject({ refused: 'denied' });+ advance(61_000);+ expect(built.ask({ ...chrome, gesture: true })).toMatchObject({ wait: expect.anything() });+ });++ it('hears a decision the moment it is made', async () => {+ const { desk: built } = desk('ask');+ built.ask(chrome);+ const settled = built.settled(chrome.installId, 60_000);+ built.decide(chrome.installId, true);+ await expect(settled).resolves.toBeUndefined();+ });++ it('decides a blocked browser by its install id even with no request', () => {+ const { desk: built } = desk('ask');+ blockInstall({ installId: chrome.installId, origin: chrome.caller }, 'revoked');+ expect(built.decide(chrome.installId, true)).toBe(true);+ expect(listBlocked()).toEqual([]);+ expect(built.decide('nobody-at-all-here', true)).toBe(false);+ });+});diff --git a/src/daemon/pairing-desk.ts b/src/daemon/pairing-desk.tsnew file mode 100644index 0000000..aca0755--- /dev/null+++ b/src/daemon/pairing-desk.ts@@ -0,0 +1,211 @@+/**+ * Where the Bridge decides a native host's request for a grant. Grants and pending requests live in+ * memory only: a restart costs the extension one more ask, and nothing secret is left on disk.+ * Approvals and blocks are the user's decisions, so they persist in auth.json.+ */++import { randomBytes } from 'node:crypto';+import { FIREFOX_CALLER, type Approver, type Grant, type GrantOutcome, type PairRequestSummary, type PairWait, type PairedBy, type PairingMode } from '@/lib/pairing';+import { sourceOf } from '@/lib/stores';+import { approveInstall, blockInstall, blockOf, isApproved, mintGrantCode, unblockInstall } from './auth-store';+import { log } from './log';++const GRANT_TTL_MS = 120_000;+/** A grant with less left than this is replaced rather than handed out again. */+const GRANT_REUSE_MS = 30_000;+const REQUEST_TTL_MS = 10 * 60_000;+const RETRY_AFTER_MS = 3_000;+/** How soon after a deny a click in the browser may ask again. */+const REASK_AFTER_DENY_MS = 60_000;++/** Who is asking, as the native host vouches for it. */+export interface Asker {+ installId: string;+ /** `chrome-extension://<id>/` for Chromium, FIREFOX_CALLER for Firefox. */+ caller: string;+ browser?: string;+ extensionVersion: string;+ gesture: boolean;+}++interface HeldGrant {+ code: string;+ caller: string;+ expiresAt: number;+ pairedBy: PairedBy;+}++interface PendingRequest extends PairRequestSummary {+ caller: string;+}++export interface DeskOptions {+ port: () => number;+ mode: () => PairingMode;+ approver: () => Approver;+ /** True while the desktop app is listening for requests. */+ appWatching: () => boolean;+ /** Starts the desktop app in the background, if there is one. */+ launchApp: () => boolean;+ /** The pending list changed. */+ changed: () => void;+ now?: () => number;+}++export interface PairingDesk {+ ask(asker: Asker): GrantOutcome;+ /** Resolves when that browser's request is decided, or after `ms`. */+ settled(installId: string, ms: number): Promise<void>;+ decide(reference: string, allow: boolean, label?: string): boolean;+ pending(): PairRequestSummary[];+ /** The live grant that browser may redeem from that socket origin. */+ grantFor(installId: string, origin: string): HeldGrant | undefined;+ consume(installId: string): void;+}++const asOrigin = (origin: string) => (origin.endsWith('/') ? origin : `${origin}/`);++export function callerMatches(caller: string, origin: string): boolean {+ return caller === FIREFOX_CALLER ? origin.startsWith(FIREFOX_CALLER) : asOrigin(origin) === caller;+}++const REFUSED_WORDS = {+ off: 'Automatic pairing is off on this computer. Pair with a code from "browsentic pair" or the app.',+ revoked: 'This computer unpaired this browser. Press Reconnect, or pair with a code.',+ denied: 'This computer turned this browser down. Press Reconnect to ask again, or pair with a code.',+} as const;++export function pairingDesk(options: DeskOptions): PairingDesk {+ const now = options.now ?? Date.now;+ const grants = new Map<string, HeldGrant>();+ const requests = new Map<string, PendingRequest>();+ const waiters = new Map<string, Set<() => void>>();++ const label = (asker: Pick<Asker, 'installId' | 'browser' | 'caller'>) => `${asker.browser ?? asker.caller} (${asker.installId.slice(0, 8)})`;++ function grantFor(asker: Asker, pairedBy: PairedBy): Grant {+ const held = grants.get(asker.installId);+ if (held && held.caller === asker.caller && held.pairedBy === pairedBy && held.expiresAt - now() > GRANT_REUSE_MS) {+ return { code: held.code, port: options.port(), expiresAt: held.expiresAt };+ }+ const fresh: HeldGrant = { code: mintGrantCode(), caller: asker.caller, expiresAt: now() + GRANT_TTL_MS, pairedBy };+ grants.set(asker.installId, fresh);+ log(`granted pairing to ${label(asker)} [${pairedBy}]`);+ return { code: fresh.code, port: options.port(), expiresAt: fresh.expiresAt };+ }++ function waitOn(request: PendingRequest): PairWait {+ return { request: request.id, approver: options.approver(), retryAfterMs: RETRY_AFTER_MS };+ }++ function request(asker: Asker): PairWait {+ const known = requests.get(asker.installId);+ if (known && now() - known.lastAskAt < REQUEST_TTL_MS) {+ known.lastAskAt = now();+ return waitOn(known);+ }+ const created: PendingRequest = {+ id: randomBytes(6).toString('base64url'),+ installId: asker.installId,+ browser: asker.browser,+ source: sourceOf(asker.caller),+ extensionVersion: asker.extensionVersion,+ firstAt: now(),+ lastAskAt: now(),+ nonce: randomBytes(16).toString('base64url'),+ caller: asker.caller,+ };+ requests.set(asker.installId, created);+ log(`pairing request from ${label(asker)}`);+ if (!options.appWatching()) options.launchApp();+ options.changed();+ return waitOn(created);+ }++ function ask(asker: Asker): GrantOutcome {+ const mode = options.mode();+ if (mode === 'code') return { refused: 'off', error: REFUSED_WORDS.off };+ const block = blockOf(asker.installId);+ if (block) {+ const reaskTooSoon = block.reason === 'denied' && now() - Date.parse(block.at) < REASK_AFTER_DENY_MS;+ if (!asker.gesture || (mode === 'ask' && reaskTooSoon)) {+ log(`refused pairing for ${label(asker)} (${block.reason})`);+ return { refused: block.reason, error: REFUSED_WORDS[block.reason] };+ }+ if (mode === 'auto') {+ unblockInstall(asker.installId);+ log(`${label(asker)} reconnected from the browser, lifting the ${block.reason} block`);+ }+ }+ if (mode === 'ask' && (block || !isApproved(asker.installId))) return { wait: request(asker) };+ return { grant: grantFor(asker, mode === 'ask' ? 'approved' : 'auto'), approver: options.approver() };+ }++ /** A grant is checked again when it is redeemed, so switching to code, revoking or denying takes back one already handed out. */+ function stillGranted(installId: string): boolean {+ const mode = options.mode();+ if (mode === 'code' || blockOf(installId)) return false;+ return mode === 'auto' || isApproved(installId);+ }++ function settled(installId: string, ms: number): Promise<void> {+ return new Promise((resolve) => {+ const waiting = waiters.get(installId) ?? new Set<() => void>();+ const done = () => {+ clearTimeout(timer);+ waiting.delete(done);+ resolve();+ };+ const timer = setTimeout(done, ms);+ waiting.add(done);+ waiters.set(installId, waiting);+ });+ }++ function wake(installId: string): void {+ for (const done of [...(waiters.get(installId) ?? [])]) done();+ waiters.delete(installId);+ }++ function decide(reference: string, allow: boolean, name?: string): boolean {+ const asked = [...requests.values()].find((candidate) => candidate.id === reference || candidate.installId === reference);+ const installId = asked?.installId ?? reference;+ const block = blockOf(installId);+ if (!asked && !block) return false;+ const subject = { installId, origin: asked?.caller ?? block!.origin, browser: asked?.browser ?? block?.browser };+ if (allow) approveInstall({ ...subject, ...(name?.trim() ? { label: name.trim().slice(0, 40) } : {}) });+ else blockInstall(subject, 'denied');+ log(`${allow ? 'approved' : 'denied'} ${label({ ...subject, caller: subject.origin })}`);+ requests.delete(installId);+ wake(installId);+ options.changed();+ return true;+ }++ function pending(): PairRequestSummary[] {+ for (const [installId, asked] of requests) {+ if (now() - asked.lastAskAt >= REQUEST_TTL_MS) requests.delete(installId);+ }+ return [...requests.values()].map(({ caller: _caller, ...summary }) => summary);+ }++ return {+ ask,+ settled,+ decide,+ pending,+ grantFor: (installId, origin) => {+ const held = grants.get(installId);+ if (!held || held.expiresAt <= now()) return undefined;+ if (!stillGranted(installId)) {+ grants.delete(installId);+ log(`dropped the grant for ${installId.slice(0, 8)}: the pairing mode, an approval or a block changed since`);+ return undefined;+ }+ if (callerMatches(held.caller, origin)) return held;+ log(`a grant for ${installId.slice(0, 8)} was offered from ${origin}, not the origin it was given to; refused`);+ return undefined;+ },+ consume: (installId) => void grants.delete(installId),+ };+}diff --git a/src/daemon/preferences.ts b/src/daemon/preferences.tsindex 450335c..e5f8726 100644--- a/src/daemon/preferences.ts+++ b/src/daemon/preferences.ts@@ -12,7 +12,7 @@ import { failure, success, type ActionResult } from '@/lib/actions/protocol';import { findSecrets } from '@/lib/secrets';import { isPreferenceChange, type Preferences } from '@/lib/settings/preferences';import { normalizeProfile, PROFILE_FIELDS, sameProfile, type UserProfile } from '@/lib/settings/profile';-import { configPath, readAgentConfig, writeGuardrailSetting, writeTheme } from './agent/config';+import { configPath, pairingMode, readAgentConfig, writeGuardrailSetting, writeTheme } from './agent/config';import { guardrailSettings, settingWritable } from './guardrails';import { log } from './log';import { stateDir } from './paths';@@ -27,6 +27,7 @@ export function preferencesNow(): Preferences {theme: config.theme ?? null,guardrails: guardrailSettings(config.guardrails ?? {}, config.requireApproval, configPath),profile: readProfile(),+ pairing: { mode: pairingMode(config) },};}diff --git a/src/daemon/remote-bridge.ts b/src/daemon/remote-bridge.tsindex 07305e5..5e0ea84 100644--- a/src/daemon/remote-bridge.ts+++ b/src/daemon/remote-bridge.ts@@ -8,6 +8,7 @@ import { ANDROID_PROTOCOL, failure, type ActionResult } from '@/lib/actions/protimport type { AgentKind, AgentState } from '@/lib/agents/catalog';import type { AndroidState } from '@/lib/phone/types';import { AWAIT_DEFAULT_TIMEOUT_MS } from '@/lib/monitor/events';+import type { Approver, BlockedBrowser, GrantOutcome, PairRequestSummary, PairingMode } from '@/lib/pairing';import type { Bridge, BridgeStatus, ControlMessage, ControlRequest, Described, SessionSummary } from './control';const REQUEST_TIMEOUT_MS = 60_000;@@ -16,6 +17,7 @@ export class RemoteBridge implements Bridge {private readonly pending = new Map<string, (message: ControlMessage) => void>();private readonly manifestListeners = new Set<() => void>();private readonly androidListeners = new Set<(state: AndroidState) => void>();+ private readonly pairRequestListeners = new Set<() => void>();private constructor(private readonly socket: WebSocket,@@ -50,12 +52,48 @@ export class RemoteBridge implements Bridge {return failure('DAEMON_UNREACHABLE', 'The Browsentic daemon did not respond');}- async status(): Promise<BridgeStatus> {- const reply = await this.request({ id: randomUUID(), op: 'status' });+ async status(timeoutMs = REQUEST_TIMEOUT_MS): Promise<BridgeStatus> {+ const reply = await this.request({ id: randomUUID(), op: 'status' }, timeoutMs);if (reply && 'status' in reply) return reply.status;throw new Error('The Browsentic daemon did not respond to a status request');}+ /** Null when nothing answered in time: a Bridge older than grants never answers the op at all. */+ async grant(request: Omit<Extract<ControlRequest, { op: 'grant' }>, 'id' | 'op'>, timeoutMs: number): Promise<GrantOutcome | null> {+ const reply = await this.request({ id: randomUUID(), op: 'grant', ...request }, timeoutMs);+ return reply && 'outcome' in reply ? reply.outcome : null;+ }++ /** `watch` makes this caller an approver, told whenever the list changes. */+ async pairRequests(watch?: Approver): Promise<PairRequestSummary[]> {+ const reply = await this.request({ id: randomUUID(), op: 'pairRequests', ...(watch ? { watch: true, as: watch } : {}) });+ return reply && 'requests' in reply ? reply.requests : [];+ }++ async decide(request: string, allow: boolean, label?: string): Promise<{ ok: boolean; error?: string }> {+ const reply = await this.request({ id: randomUUID(), op: 'decide', request, allow, ...(label ? { label } : {}) });+ return reply && 'op' in reply && reply.op === 'decide' ? { ok: reply.ok, error: reply.error } : { ok: false, error: 'The Bridge did not answer.' };+ }++ async pairing(set?: PairingMode): Promise<{ mode: PairingMode; approver: Approver; error?: string } | null> {+ const reply = await this.request({ id: randomUUID(), op: 'pairing', ...(set ? { set } : {}) }, 5_000);+ return reply && 'op' in reply && reply.op === 'pairing' ? { mode: reply.mode, approver: reply.approver, error: reply.error } : null;+ }++ async blocked(): Promise<BlockedBrowser[]> {+ const reply = await this.request({ id: randomUUID(), op: 'blocked' }, 5_000);+ return reply && 'blocked' in reply ? reply.blocked : [];+ }++ async label(session: string, label: string): Promise<boolean> {+ const reply = await this.request({ id: randomUUID(), op: 'label', session, label }, 5_000);+ return !!reply && 'op' in reply && reply.op === 'label' && reply.ok;+ }++ onPairRequestsChanged(listener: () => void): void {+ this.pairRequestListeners.add(listener);+ }+async pair(): Promise<{ code: string; expiresAt: number }> {const reply = await this.request({ id: randomUUID(), op: 'pair' });if (reply && 'code' in reply) return reply;@@ -141,6 +179,7 @@ export class RemoteBridge implements Bridge {if ('event' in message) {if (message.event === 'manifest-changed') for (const listener of this.manifestListeners) listener();if (message.event === 'android-changed') for (const listener of this.androidListeners) listener(message.state);+ if (message.event === 'pair-requests-changed') for (const listener of this.pairRequestListeners) listener();return;}this.pending.get(message.id)?.(message);diff --git a/src/daemon/scripts/cli-smoke.ts b/src/daemon/scripts/cli-smoke.tsindex e892bb6..c01b175 100644--- a/src/daemon/scripts/cli-smoke.ts+++ b/src/daemon/scripts/cli-smoke.ts@@ -24,7 +24,7 @@ if (windows && !process.env.CI) die('On Windows this rewrites the registry keysconst HOST = 'com.browsentic.daemon';const PORTS = [47811, 47812];const CHROME_WEB_STORE = 'chrome-extension://npmocgldfflonjjmdadmdefpnfagnjmp/';-const COMMANDS = 'setup update uninstall browsers pair status sessions revoke agent skills approvals tasks downloads tools logs start stop restart token mcp'.split(' ');+const COMMANDS = 'setup update uninstall browsers pair pairing requests approve deny status sessions rename revoke agent skills approvals tasks downloads tools logs start stop restart token mcp'.split(' ');const version = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version as string;const scratch = mkdtempSync(join(tmpdir(), 'browsentic-smoke-'));@@ -122,6 +122,12 @@ function hostManifest(): { path: string; allowed_origins: string[] } {* npm is offline, so the launcher's npx fallback cannot answer for a CLI path it failed to read.*/async function wake(): Promise<{ ok: boolean; port?: number; error?: string }> {+ return askHost({ op: 'ensure' });+}++const PAIR = { op: 'pair', installId: 'install-cli-smoke-0001', browser: 'Google Chrome', extensionVersion: version, protocolVersion: 23, reason: 'install' };++async function askHost<T = { ok: boolean; port?: number; error?: string }>(message: object): Promise<T> {const manifest = hostManifest();const offline = { ...env, npm_config_offline: 'true' };must(manifest.allowed_origins.includes(CHROME_WEB_STORE), 'the store copy is not allowed to start the host');@@ -133,7 +139,7 @@ async function wake(): Promise<{ ok: boolean; port?: number; error?: string }> {windowsVerbatimArguments: true,}): spawn(manifest.path, [CHROME_WEB_STORE], { env: offline, cwd: dirname(manifest.path) });- const body = Buffer.from(JSON.stringify({ op: 'ensure' }));+ const body = Buffer.from(JSON.stringify(message));const head = Buffer.alloc(4);head.writeUInt32LE(body.length);host.stdin.end(Buffer.concat([head, body]));@@ -263,6 +269,31 @@ try {const reply = await wake();must(reply.ok && reply.port && PORTS.includes(reply.port), JSON.stringify(reply));});+ await check('the host says what it can do', async () => {+ const hello = await askHost<{ ok: boolean; ops: string[]; mode: string }>({ op: 'hello' });+ must(hello.ok && hello.ops.includes('pair') && hello.mode === 'auto', JSON.stringify(hello));+ });+ await check('the host pairs the store copy with no code', async () => {+ const reply = await askHost<{ ok: boolean; grant?: { code: string; port: number } }>(PAIR);+ must(reply.ok && reply.grant?.code.length === 26 && PORTS.includes(reply.grant.port), JSON.stringify(reply));+ });+ await check('ask mode waits for approve, and code mode pairs nothing', async () => {+ says(browsentic('pairing', 'ask'), 'Pairing: ask');+ const asked = await askHost<{ ok: boolean; wait?: { request: string } }>(PAIR);+ must(!asked.ok && asked.wait?.request, JSON.stringify(asked));+ const listed = json<{ requests: { id: string }[] }>(browsentic('requests', '--json'));+ must(listed.requests.some((request) => request.id === asked.wait!.request), JSON.stringify(listed));+ says(browsentic('approve', asked.wait!.request), 'Allowed.');+ must((await askHost<{ ok: boolean }>(PAIR)).ok, 'still not granted after approve');+ says(browsentic('pairing', 'code'), 'Pairing: code only');+ must(JSON.stringify(await askHost(PAIR)).includes('"refused":"off"'), 'code mode still paired');+ says(browsentic('pairing', 'auto'), 'Pairing: automatic');+ });+ if (windows) {+ await check('setup registered the task that starts the Bridge for Firefox', () =>+ must(spawnSync('schtasks', ['/Query', '/TN', 'Browsentic\\Bridge'], { windowsHide: true }).status === 0, 'no Browsentic\\Bridge task'),+ );+ }await check('stop', async () => {says(browsentic('stop'), 'Stopped the Bridge (pid');must((await answering()).length === 0, 'still answering');@@ -288,6 +319,7 @@ try {must((await answering()).length === 0, 'the Bridge still answers');says(browsentic('status'), 'not registered');if (windows) must(spawnSync('reg', ['query', `HKCU\\Software\\Google\\Chrome\\NativeMessagingHosts\\${HOST}`]).status !== 0, 'the key is left');+ if (windows) must(spawnSync('schtasks', ['/Query', '/TN', 'Browsentic\\Bridge'], { windowsHide: true }).status !== 0, 'the task is left');});} finally {if (await answering().then((ports) => ports.length)) browsentic('stop');diff --git a/src/daemon/test/auto-pair.test.ts b/src/daemon/test/auto-pair.test.tsnew file mode 100644index 0000000..fee8115--- /dev/null+++ b/src/daemon/test/auto-pair.test.ts@@ -0,0 +1,276 @@+import { rmSync } from 'node:fs';+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'vitest';+import { CHROME_WEB_STORE, EDGE_ADD_ONS } from '@/lib/stores';+import { FIREFOX_CALLER, type GrantOutcome } from '@/lib/pairing';+import { clearAuth, listSessions, pendingPairings } from '../auth-store';+import { configPath } from '../agent/config';+import { startDaemon, type Daemon } from '../daemon';+import { readLockfile } from '../lockfile';+import { RemoteBridge } from '../remote-bridge';+import { FakeBrowser, type Profile } from './fake-browser';++const origin = `chrome-extension://${CHROME_WEB_STORE.id}`;+const chrome: Profile = { origin, installId: 'install-auto-chrome01', browser: 'Google Chrome' };+const brave: Profile = { origin, installId: 'install-auto-brave001', browser: 'Brave' };+const firefox: Profile = { origin: 'moz-extension://5b1d7a4e-9f3c-4c2e-8d1a-0e6f2b7c9a11', installId: 'install-auto-firefox1', browser: 'Firefox' };++let daemon: Daemon;+let opened: { close(): unknown }[] = [];++beforeAll(async () => {+ daemon = await startDaemon({ version: '0.0.0-test', idleExit: false });+});++afterAll(async () => {+ await daemon?.stop();+});++afterEach(async () => {+ for (const each of opened) each.close();+ opened = [];+ await new Promise((resolve) => setTimeout(resolve, 20));+ clearAuth();+ rmSync(configPath, { force: true });+});++async function control(runId?: string): Promise<RemoteBridge> {+ const bridge = await RemoteBridge.connect(daemon.port, readLockfile()!.token, runId);+ opened.push(bridge);+ return bridge;+}++const asker = (profile: Profile, extra: { gesture?: boolean; waitMs?: number; caller?: string } = {}) => ({+ installId: profile.installId,+ caller: extra.caller ?? `${profile.origin}/`,+ browser: profile.browser,+ extensionVersion: '0.9.0',+ gesture: extra.gesture,+ waitMs: extra.waitMs,+});++async function grant(profile: Profile, extra: Parameters<typeof asker>[1] = {}): Promise<GrantOutcome> {+ const outcome = await (await control()).grant(asker(profile, extra), 30_000);+ if (!outcome) throw new Error('no answer');+ return outcome;+}++async function redeem(profile: Profile, outcome: GrantOutcome): Promise<FakeBrowser> {+ if (!('grant' in outcome)) throw new Error(`expected a grant, got ${JSON.stringify(outcome)}`);+ const browser = await FakeBrowser.connect(outcome.grant.port, profile, { kind: 'pair', code: outcome.grant.code });+ opened.push(browser);+ return browser;+}++const refusalOf = (error: unknown) => (error as { refusal?: string }).refusal;++async function setMode(mode: 'auto' | 'ask' | 'code'): Promise<void> {+ expect((await (await control()).pairing(mode))?.mode).toBe(mode);+}++describe('automatic pairing', () => {+ test('a browser pairs with a grant and no code, and comes back on its key', async () => {+ const paired = await redeem(chrome, await grant(chrome));+ expect(listSessions()).toEqual([expect.objectContaining({ installId: chrome.installId, pairedBy: 'auto' })]);+ paired.close();++ const back = await FakeBrowser.connect(daemon.port, chrome, { kind: 'session', key: paired.sessionKey });+ opened.push(back);+ expect(back.isOpen).toBe(true);+ });++ test('says the Bridge pairs by itself, and how each browser paired', async () => {+ await redeem(chrome, await grant(chrome));+ const bridge = await control();+ expect((await bridge.status()).pairing).toEqual({ mode: 'auto', approver: expect.any(String) });+ expect(await bridge.sessions()).toEqual([expect.objectContaining({ pairedBy: 'auto' })]);+ });++ test('a grant works once', async () => {+ const outcome = await grant(chrome);+ (await redeem(chrome, outcome)).close();+ await expect(redeem(chrome, outcome)).rejects.toSatisfy((error) => refusalOf(error) === 'bad-code');+ });++ test('a grant is good only for the browser it was given to, from the origin the browser vouched for', async () => {+ const outcome = await grant(chrome);+ await expect(redeem(brave, outcome)).rejects.toSatisfy((error) => refusalOf(error) === 'bad-code');+ await expect(redeem({ ...chrome, origin: `chrome-extension://${EDGE_ADD_ONS.id}` }, outcome)).rejects.toSatisfy(+ (error) => refusalOf(error) === 'bad-code',+ );+ expect((await redeem(chrome, outcome)).isOpen).toBe(true);+ });++ test('asking twice hands back the same grant', async () => {+ const first = await grant(chrome);+ const second = await grant(chrome);+ expect('grant' in first && 'grant' in second && first.grant.code === second.grant.code).toBe(true);+ });++ test('a grant never pushes out a code someone is reading off the screen', async () => {+ const bridge = await control();+ const codes = [await bridge.pair(), await bridge.pair(), await bridge.pair()].map(({ code }) => code);+ await grant(chrome);+ expect(pendingPairings()).toEqual(codes);+ });++ test('Firefox redeems a grant from its own random origin, bound by the scheme', async () => {+ const paired = await redeem(firefox, await grant(firefox, { caller: FIREFOX_CALLER }));+ expect(paired.isOpen).toBe(true);+ });++ test('a typed code still pairs, and says so', async () => {+ const { code } = await (await control()).pair();+ opened.push(await FakeBrowser.connect(daemon.port, chrome, { kind: 'pair', code }));+ expect(listSessions()).toEqual([expect.objectContaining({ pairedBy: 'code' })]);+ });++ test('pairs nothing by itself in code mode', async () => {+ await setMode('code');+ expect(await grant(chrome)).toEqual({ refused: 'off', error: expect.stringContaining('off') });+ });+});++describe('revoking', () => {+ test('keeps a browser out of automatic pairing until someone reconnects it', async () => {+ const paired = await redeem(chrome, await grant(chrome));+ expect(await (await control()).revoke(chrome.installId)).toBe(1);++ await expect(FakeBrowser.connect(daemon.port, chrome, { kind: 'session', key: paired.sessionKey })).rejects.toSatisfy(+ (error) => refusalOf(error) === 'revoked',+ );+ expect(await grant(chrome)).toMatchObject({ refused: 'revoked' });+ expect(await (await control()).blocked()).toEqual([expect.objectContaining({ installId: chrome.installId, reason: 'revoked' })]);+ });++ test('a click in that browser lets it back in, in auto mode', async () => {+ await redeem(chrome, await grant(chrome));+ await (await control()).revoke(chrome.installId);++ expect((await redeem(chrome, await grant(chrome, { gesture: true }))).isOpen).toBe(true);+ expect(await (await control()).blocked()).toEqual([]);+ });++ test('a code lets it back in too', async () => {+ await redeem(chrome, await grant(chrome));+ await (await control()).revoke(chrome.installId);+ const { code } = await (await control()).pair();++ opened.push(await FakeBrowser.connect(daemon.port, chrome, { kind: 'pair', code }));+ expect('grant' in (await grant(chrome))).toBe(true);+ });++ test('a key the Bridge never issued, or forgot, is called unknown, so the extension may pair again', async () => {+ await expect(FakeBrowser.connect(daemon.port, chrome, { kind: 'session', key: 'k'.repeat(43) })).rejects.toSatisfy(+ (error) => refusalOf(error) === 'unknown',+ );+ });+});++describe('ask mode', () => {+ test('waits for someone to allow the browser, then grants it', async () => {+ await setMode('ask');+ const approver = await control();+ let told = 0;+ approver.onPairRequestsChanged(() => told++);+ await approver.pairRequests('app');++ const asked = await grant(chrome);+ expect(asked).toMatchObject({ wait: { request: expect.any(String), approver: 'app' } });+ const [request] = await approver.pairRequests();+ expect(request).toMatchObject({ installId: chrome.installId, browser: 'Google Chrome', source: 'chrome-web-store', nonce: expect.any(String) });+ expect(told).toBeGreaterThan(0);++ expect(await approver.decide(request.id, true, 'Work Chrome')).toEqual({ ok: true });+ await redeem(chrome, await grant(chrome));+ expect(listSessions()).toEqual([expect.objectContaining({ pairedBy: 'approved', label: 'Work Chrome' })]);+ });++ test('asks once per browser, however often it asks', async () => {+ await setMode('ask');+ await grant(chrome);+ await grant(chrome);+ expect(await (await control()).pairRequests()).toHaveLength(1);+ });++ test('answers a held request the moment it is allowed', async () => {+ await setMode('ask');+ await grant(chrome);+ const approver = await control();+ const [request] = await approver.pairRequests();++ const held = grant(chrome, { waitMs: 20_000 });+ const started = Date.now();+ setTimeout(() => void approver.decide(request.id, true), 200);+ expect('grant' in (await held)).toBe(true);+ expect(Date.now() - started).toBeLessThan(5_000);+ });++ test('a denied browser stays out, and asking again at once changes nothing', async () => {+ await setMode('ask');+ await grant(chrome);+ const approver = await control();+ const [request] = await approver.pairRequests();+ await approver.decide(request.id, false);++ expect(await grant(chrome)).toMatchObject({ refused: 'denied' });+ expect(await grant(chrome, { gesture: true })).toMatchObject({ refused: 'denied' });+ });++ test('an allowed browser pairs by itself from then on', async () => {+ await setMode('ask');+ await grant(chrome);+ const approver = await control();+ await approver.decide((await approver.pairRequests())[0].id, true);+ (await redeem(chrome, await grant(chrome))).close();++ expect('grant' in (await grant(chrome))).toBe(true);+ });++ test('a code is consent enough', async () => {+ await setMode('ask');+ const { code } = await (await control()).pair();+ opened.push(await FakeBrowser.connect(daemon.port, chrome, { kind: 'pair', code }));++ expect('grant' in (await grant(chrome))).toBe(true);+ });+});++describe('an agent run', () => {+ test('cannot pair a browser, let one in, rename one, or change how they pair', async () => {+ const run = await control('run-under-test');+ await run.describe();++ expect(await run.grant(asker(chrome), 5_000)).toMatchObject({ refused: 'off' });+ expect(await run.decide(chrome.installId, true)).toMatchObject({ ok: false });+ expect(await run.pairing('code')).toMatchObject({ mode: 'auto', error: expect.any(String) });+ expect(await run.label(chrome.installId, 'x')).toBe(false);+ });+});++describe('the pairing setting', () => {+ test('refuses a mode it does not know', async () => {+ expect(await (await control()).pairing('sometimes' as never)).toMatchObject({ mode: 'auto', error: expect.any(String) });+ });++ test('reaches the browsers, read-only, through their preferences', async () => {+ const paired = await redeem(chrome, await grant(chrome));+ expect(paired.preferences?.pairing).toEqual({ mode: 'auto' });+ await setMode('code');+ await setMode('ask');+ while (paired.preferences?.pairing?.mode !== 'ask') await paired.frames('preferencesInfo', paired.received.filter((frame) => frame.t === 'preferencesInfo').length + 1);+ expect(paired.preferences?.pairing).toEqual({ mode: 'ask' });+ });++ test('takes back a grant already handed out when pairing is switched off', async () => {+ const outcome = await grant(chrome);+ await setMode('code');+ await expect(redeem(chrome, outcome)).rejects.toSatisfy((error) => refusalOf(error) === 'bad-code');+ });++ test('takes back a grant already handed out when the browser is revoked', async () => {+ (await redeem(chrome, await grant(chrome))).close();+ const outcome = await grant(chrome);+ await (await control()).revoke(chrome.installId);+ await expect(redeem(chrome, outcome)).rejects.toSatisfy((error) => refusalOf(error) === 'bad-code');+ });+});diff --git a/src/daemon/test/fake-browser.ts b/src/daemon/test/fake-browser.tsindex 454412f..5f15ad4 100644--- a/src/daemon/test/fake-browser.ts+++ b/src/daemon/test/fake-browser.ts@@ -100,7 +100,7 @@ export class FakeBrowser {send(socket, { t: 'prove', proof: await clientProof(secret, transcript) });const verdict = await inbox.next();- if (verdict?.t === 'unauthorized') throw new Error(verdict.reason);+ if (verdict?.t === 'unauthorized') throw Object.assign(new Error(verdict.reason), { refusal: verdict.code });if (verdict?.t !== 'welcome') throw new Error(`expected a welcome, got ${verdict?.t}`);const minted = verdict.sealedSessionKey ? await openSessionKey(secret, transcript, verdict.sealedSessionKey) : null;// The daemon asks a drifted build for its manifest right behind the welcome, so whateverdiff --git a/src/lib/actions/protocol.ts b/src/lib/actions/protocol.tsindex c49a1c1..4afd941 100644--- a/src/lib/actions/protocol.ts+++ b/src/lib/actions/protocol.ts@@ -9,6 +9,7 @@ import type { PreferenceChange, Preferences } from '@/lib/settings/preferences';import type { SkillCategory, SkillDraft } from '@/lib/skills/format';import type { SiteMapDraft } from '@/lib/skills/site-map';import type { TaskContext, TaskList, TaskOrder, TaskResult } from '@/lib/schedules/task';+import type { RefusalCode } from '@/lib/pairing';export const ACTION_CHANNEL = 'browsentic/action';export const BRIDGE_CHANNEL = 'browsentic/bridge';@@ -231,7 +232,8 @@ export type SocketFrame =proof: string;sealedSessionKey?: string;}- | { t: 'unauthorized'; reason: string; retryable: boolean }+ /** `code` says what an extension that pairs by itself may do about it; `reason` keeps the words shipped extensions read. */+ | { t: 'unauthorized'; reason: string; retryable: boolean; code?: RefusalCode }| { t: 'describe'; id: string }| { t: 'manifest'; id: string; tools: ToolDescriptor[] }| { t: 'invoke'; id: string; action: string; input?: unknown; tabId?: number; runId?: string }diff --git a/src/lib/pairing.ts b/src/lib/pairing.tsnew file mode 100644index 0000000..13ca903--- /dev/null+++ b/src/lib/pairing.ts@@ -0,0 +1,101 @@+/**+ * Automatic pairing: the extension asks the native messaging host, which only our own extensions can+ * launch, for a one-time grant from Browsentic Bridge, and redeems it through the same handshake a+ * typed code uses. `mode` decides whether someone approves the browser first; `code` turns it off.+ */++export const PAIRING_MODES = ['auto', 'ask', 'code'] as const;+export type PairingMode = (typeof PAIRING_MODES)[number];+export const DEFAULT_PAIRING_MODE: PairingMode = 'auto';++export const isPairingMode = (value: unknown): value is PairingMode => PAIRING_MODES.includes(value as PairingMode);++export const PAIR_REASONS = ['install', 'update', 'startup', 'alarm', 'open', 'gesture', 'unknown-session'] as const;+export type PairReason = (typeof PAIR_REASONS)[number];++export const isPairReason = (value: unknown): value is PairReason => PAIR_REASONS.includes(value as PairReason);++/** A Firefox extension's socket origin is a random UUID per install, so its grant is bound to the scheme. */+export const FIREFOX_CALLER = 'moz-extension://';++/** The ops a host that pairs answers; one that answers only `ensure` predates automatic pairing. */+export const HOST_OPS = ['ensure', 'hello', 'pair'] as const;++/** Where someone allows a browser: the desktop app, or `browsentic approve` in a terminal. */+export type Approver = 'app' | 'terminal';++/** The longest a host holds a pair request open waiting for an approval, so an open page hears it at once. */+export const MAX_PAIR_WAIT_MS = 25_000;++export interface HostPairRequest {+ op: 'pair';+ installId: string;+ browser?: string;+ extensionVersion: string;+ protocolVersion: number;+ reason: PairReason;+ /** Set only when someone pressed Connect or Reconnect. */+ gesture?: boolean;+ waitMs?: number;+}++export interface Grant {+ code: string;+ port: number;+ expiresAt: number;+}++export type PairRefusal = 'off' | 'revoked' | 'denied' | 'stopped' | 'origin' | 'restart';++export interface PairWait {+ request: string;+ approver: Approver;+ retryAfterMs: number;+}++/** What the Bridge answers a host that asks for a grant. */+export type GrantOutcome =+ | { grant: Grant; approver: Approver }+ | { wait: PairWait }+ | { refused: Exclude<PairRefusal, 'stopped' | 'origin' | 'restart'>; error: string };++export type HostPairReply =+ | { ok: true; grant: Grant; mode: PairingMode; approver: Approver }+ | { ok: false; wait: PairWait; mode: PairingMode }+ | { ok: false; refused: PairRefusal; error: string; mode?: PairingMode }+ | { ok: false; error: string };++export interface HostHello {+ ok: true;+ host: 2;+ bridge: string;+ ops: string[];+ mode: PairingMode;+ held: boolean;+ app: { kind: 'mac' | 'windows'; present: boolean } | null;+}++/** Why a session or code was refused, for an extension that can act on it; the reason text stays as shipped. */+export type RefusalCode = 'bad-code' | 'unknown' | 'revoked';++export type PairedBy = 'code' | 'auto' | 'approved';++export interface PairRequestSummary {+ id: string;+ installId: string;+ browser?: string;+ source: string;+ extensionVersion: string;+ firstAt: number;+ lastAskAt: number;+ /** Proves a `browsentic://` link came from the notification the app itself posted. */+ nonce: string;+}++export interface BlockedBrowser {+ installId: string;+ browser?: string;+ origin: string;+ at: string;+ reason: 'revoked' | 'denied';+}diff --git a/src/lib/settings/preferences.ts b/src/lib/settings/preferences.tsindex c7abb63..ae2e818 100644--- a/src/lib/settings/preferences.ts+++ b/src/lib/settings/preferences.ts@@ -7,12 +7,15 @@import { isThemeId, type ThemeId } from './theme';import { isRuleEffect, type GuardrailSettings, type GuardrailValue } from './guardrails';import { isUserProfile, type UserProfile } from './profile';+import type { PairingMode } from '@/lib/pairing';export interface Preferences {/** Null until someone picks one; a browser that already has a choice then hands it over. */readonly theme: ThemeId | null;readonly guardrails: GuardrailSettings;readonly profile: UserProfile;+ /** Shown, never changed, by the extension: the browser is what this setting guards. Absent from a Bridge before it. */+ readonly pairing?: { readonly mode: PairingMode };}export type PreferenceChange =